Home
The Glorious Glasgow Haskell Compilation System User`s Guide
Contents
1. Options exclude PACKAGE MODULE exclude MODULE and or PACKAGE include PACKAGE MODULE include MODULE and or PACKAGE bleu Fels oiicjowie 12901013 function FUNCTION combine tix files with join function default ADD FUNCTION ADD DIFF SUB union use the union of the module namespace default is intersection 5 6 3 5 hpc map hpc map inverts or zeros a tix file hpc map does not change the original tix file it generates a new tix file hpc help map Usage hpc map OPTION lt TIX_FILE gt Map a function over a single tix file Options exclude PACKAGE MODULE exclude MODULE and or PACKAGE include PACKAGE MODULE include MODULE and or PACKAGE OPUSE OwliEjowhe Le function FUNCTION apply function to tix files default ID FUNCTION ID INV ZERO IO use the union of the module namespac default is intersection 5 6 3 6 hpc overlay and hpc draft Overlays are an experimental feature of HPC a textual description of coverage hpc draft is used to generate a draft overlay from a tix file and hpc overlay generates a tix files from an overlay The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 118 240 o hpc help overlay Usage hpc overlay OPTION lt OVERLAY_FILE gt lt OVERLAY_FILE gt Options srcdir DIR path to source directory of hs
2. Flag Description Static Dynamic Reverse tapes set the directory for dianie g temporary files 4 18 7 Finding imports Section 4 6 3 Flag Description Static Dynamic Reverse md l add dir dir2 etc to idiriidir2 is static set import path i ampty the import directory satset g list 4 18 8 Interface file options Section 4 6 7 Flag Description Static Dynamic Reverse dep Dump the new interface to usais stdout er Show the differences vs the ddump hi diffs old interface dynamic ddump minimal im Dump a minimal set of E dynamic ports imports show iface fil See Section 4 4 4 18 9 Recompilation checking Section 4 6 8 Flag Description Static Dynamic Reverse Turn off recompilation fforce recomp checking implied by any dynamic fno force recomp ddump X option 4 18 10 Interactive mode options Section 2 9 Flag Description Static Dynamic Reverse f Disable reading of ghci ignore dot ghci static files ona Enable reading of ghci static l files fbreak on except Break on any exception fno break on exc dynamic ion thrown eption O Break on uncaught dynamic fno break on err exceptions and errors or fprint evld with Enable usage of Show fno print evld w gt y dynamic show instances 1n print ith show fprint bind resu Turn on printing of binding dynamite fno print bind r lt results in GHCi esult The Glorious Glasgow Haskell
3. SPECIALIZE genericLookup Table Int b gt Int gt b intLookup This feature is no longer in GHC but rewrite rules let you do the same thing The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 204 240 RULES genericLookup Int genericLookup intLookup This slightly odd looking rule instructs GHC to replace genericLookup by int Lookup whenever the types match What is more this rule does not need to be in the same file as genericLookup unlike the SPECIALIZE pragmas which currently do so that they have an original definition available to specialise It is Your Responsibility to make sure that int Lookup really behaves as a specialised version of genericLookup An example in which using RULES for specialisation will Win Big toDouble Real a gt a gt Double toDouble fromRational toRational RULES toDouble Int toDouble i2d i2d 1l i D int2Double i uses Glasgow prim op directly The i2d function is virtually one machine instruction the default conversion via an intermediate Rat ional is obscenely expensive by comparison 7 14 5 Controlling what s going on e Use ddump rules to see what transformation rules GHC is using e Use ddump simpl stats to see what rules are being fired If you add dppr debug you get a more detailed listing e The definition of say build in GHC Base 1hs looks like this
4. gt E E a ELO 7 6 1 2 The superclasses of a class declaration In Haskell 98 the context of a class declaration which introduces superclasses must be simple that is each predicate must consist of a class applied to type variables The flag XFlexibleContexts Section 7 8 2 lifts this restriction so that the only restriction on the context in a class declaration is that the class hierarchy must be acyclic So these class declarations are OK class Functor m k gt FiniteMap m k where class Monad m Monad t m gt Transform t m where lire 2 m a dem a As in Haskell 98 The class hierarchy must be acyclic However the definition of acyclic involves only the superclass relation ships For example this is OK The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 155 240 class C a where Oo 38 D lo gt a gt lo gt Io class C a gt D a where Here C is a superclass of D but it s OK for a class operation op of C to mention D It would not be OK for D to be a superclass of C 7 6 1 3 Class method types Haskell 98 prohibits class method types to mention constraints on the class type variable thus class Seq s a where fromList a s a elem 23 Ba a gt a gt S a gt Bool The type of elem is illegal in Haskell 98 because it contains the constraint Eq a constrains only the class type variable in this case a GHC lifts this r
5. Then in some importing module M the constraint E a Int should be improved by setting a T even though there is no explicit mention of T in M These considerations lead to the following definition of an orphan module e An orphan module contains at least one orphan instance or at least one orphan rule e An instance declaration in a module M is an orphan instance if The class of the instance declaration is not declared in M and Either the class has no functional dependencies and none of the type constructors in the instance head is declared in M or there is a functional dependency for which none of the type constructors mentioned in the non determined part of the instance head is defined in M Only the instance head counts In the example above it is not good enough for C s declaration to be in module A it must be the declaration of D or T e A rewrite rule in a module M is an orphan rule if none of the variables type constructors or classes that are free in the left hand side of the rule are declared in M If you use the flag fwarn orphans GHC will warn you if you are creating an orphan module Like any warning you can switch the warning off with fno warn orphans and Werror will make the compilation fail if the warning is issued You can identify an orphan module by looking in its interface file M hi using the show iface mode If there is a orphan module on the first line GHC considers it an orphan modu
6. template FILE The template file see below c PROG or cc PROG The C compiler to use default ghc 1 PROG or 1d PROG The linker to use default gec C FLAG or cflag FLAG An extra flag to pass to the C compiler I DIR Passed to the C compiler L FLAG or 1flag FLAG An extra flag to pass to the linker i FILE or include FILE As if the appropriate include directive was placed in the source D NAME VALUE or define NAME VALUE As if the appropriate define directive was placed in the source no compile Stop after writing out the intermediate C program to disk The file name for the intermediate C program is the input file name with hsc replaced with _hsc_make c or help Display a summary of the available flags and exit successfully V or version Output version information and exit successfully The input file should end with hsc it should be plain Haskell source only literate Haskell is not supported at the moment Output files by default get names with the hsc suffix replaced hs Haskell file _hsc h C header _hsc c C file The C program is compiled using the Haskell compiler This provides the include path to HSFFI h which is automatically included into the C program The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 221 240 10 3 2 Input syntax All special processing is triggered by the opera
7. 236 240 numeric version 42 print libdir 42 supported languages 42 user 64 version 42 64 interactive 31 make 42 shared 225 A allocation area size 80 ANN 197 198 ANN module 198 ANN type 198 apparently erroneous do binding warning 57 arguments command line 40 ASCII 45 Assertions 194 author package specification 66 auto package specification 66 B Bang patterns 192 binds unused 56 bugs reporting 2 C C calls function headers 214 C pre processor options 70 CAFs in GHCi 36 category package specification 66 cc options package specification 67 Char size of 231 code coverage 114 command line arguments 40 compacting garbage collection 80 compiled code in GHCi 16 compiler problems 217 compiling faster 121 Concurrent Haskell using 77 consistency checks 88 Constant Applicative Form see CAFs constructor fields strict 69 copyright package specification 66 CORE pragma 204 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 Core syntax how to read 88 core annotation 204 cost centres automatically inserting 108 cost centre profiling 104 cpp pre processing with 70 Creating a Win32 DLL 225 CTAGS for Haskell 219 D debugger in GHCi 23 debugging options for GHC 86 defaulting mechanism warning 56 dependencies in Makefiles 51 dependency generation mode 42 depends package spe
8. The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 1 5 3 14 integer gmp e Version number 0 2 0 1 was 0 2 0 0 1 5 3 15 integer simple e No change version 0 1 0 0 1 5 3 16 old locale e No change version 1 0 0 2 1 5 3 17 old time e Version number 1 0 0 4 was 1 0 0 3 1 5 3 18 pretty e No change version 1 0 1 1 1 5 3 19 process e No change version 1 0 1 2 1 5 3 20 random e No change version 1 0 0 2 1 5 3 21 syb e No change version 0 1 0 2 1 5 3 22 template haskell e Version number 2 4 0 1 was 2 4 0 0 1 5 3 23 time e No change version 1 1 4 1 5 3 24 unix e Version number 2 4 0 1 was 2 4 0 0 1 5 3 25 Win32 e Version number 2 2 0 2 was 2 2 0 1 5 240 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 6 240 1 6 Release notes for version 6 12 1 The significant changes to the various parts of the compiler are listed in the following sections There have also been numerous bug fixes and performance improvements over the 6 10 branch 1 6 1 Highlights Considerably improved support for parallel execution GHC 6 10 would execute parallel Haskell programs but performance was often not very good Simon Marlow has done lots of performance tuning in 6 12 removing many of the accidental and largely invisible gotchas that made parallel programs run slowly As part of this parallel performance tuning Satnam
9. build O A eto it mallil lo la gt Jo gt 19 gt o gt Io el INLINE build build g g Notice the INLINE That prevents from being inlined when compiling PrelBase so that an importing module will see the and can match it on the LHS of a rule INLINE prevents any inlining happening in the RHS of the INLINE thing I regret the delicacy of this e Inlibraries base GHC Base lhs look at the rules for map to see how to write rules that will do fusion and yet give an efficient program even if fusion doesn t happen More rules in GHC List 1lhs 7 14 6 CORE pragma The external core format supports Note annotations the CORE pragma gives a way to specify what these should be in your Haskell source code Syntactically core annotations are attached to expressions and take a Haskell string literal as an argument The following function definition shows an example f x CORE foo show CORE bar x Semantically this is equivalent to g x show x However when external core is generated via fext core there will be Notes attached to the expressions show and x The core function declaration for f is if GR Sie iceilil ey 4 CHCA NONON ACES NOWRA gt a gt GHCziBase ZMZN GHCziBase Char a zddShow GHCziShow ZCTShow a eta a gt Snote foo Scase zddShow of tpl GHCziShow ZCTShow a GHCziShow ZCDShow The Glorious Gla
10. hT Generates a basic heap profile in the file prog hp To produce the heap profile graph use hp2ps see Section 5 5 The basic heap profile is broken down by data constructor with other types of closures functions thunks etc grouped into broad categories e g FUN THUNK To get a more detailed profile use the full profiling support Chapter 5 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 84 240 4 15 6 Tracing When the program is linked with the event 1og option Section 4 10 6 runtime events can be logged in two ways e In binary format to a file for later analysis by a variety of tools One such tool is ThreadScope which interprets the event log to produce a visual parallel execution profile of the program e As text to standard output for debugging purposes 1 flags Log events in binary format to the file program event log where flags is a sequence of zero or more characters indicating which kinds of events to log Currently there is only one type supported 1s for scheduler events The format of the log file is described by the header EventLogFormat h that comes with GHC and it can be parsed in Haskell using the ghc events library To dump the contents ofa event log file as text use the tool show ghc event s that comes with the ghc events package v flags Log events as text to standard output instead of to the event log file The flags are the same as for 1
11. The search path for finding source files is specified with the i option on the GHCi command line like so or it can be set using the set command from within GHCi see Section 2 8 2 One consequence of the way that GHCi follows dependencies to find modules to load is that every module must have a source file The only exception to the rule is modules that come from a package including the Prelude and standard libraries such as IO and Complex If you attempt to load a module for which GHCi can t find a source file even if there are object and interface files for the module you ll get an error message 2 2 2 Making changes and recompilation If you make some changes to the source code and want GHCi to recompile the program give the reload command The program will be recompiled as necessary with GHCi doing its best to avoid actually recompiling modules if their external dependencies haven t changed This is the same mechanism we use to avoid re compiling modules in the batch compilation setting see Section 4 6 8 3Tf you started up GHCi from the command line then GHCi s current directory is the same as the current directory of the shell from which it was started If you started GHCi from the Start menu in Windows then the current directory is probably something like C Document sandSett ings username 4Note that in GHCi and make mode the i option is used to specify the search path for source files whereas in stand
12. XNoIncoherentIns instances Implies XOve dynamic nces tances rlappingInstances XUndecidablelnst Enable undecidable dynamic XNoUndecidableIn ances instances y stances Pr n set the limit for context dio x n reduction Default is 20 y Enable arrow notation 3 XArrows dynamic XNoArrows extension XDisambiguateRec Enable record field dynamic XNoDisambiguateR ordFields disambiguation y ecordFields Enable foreign function XForeignFunction g y a XNoForeignFuncti interface implied by dynamic Interface onInterface fglasgow exts XGenerics Enable generic classes dynamic XNoGenerics Enable Implicit Parameters XImplicitParams Implied by dynamic XNoImplicitParams fglasgow exts The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 94 240 Flag Description Static Dynamic Reverse firrefutable tup Make tuple pattern fno irrefutable et dynamic les matching irrefutable tuples XNoImplicitPrelu Don t implicitly i x Yogi oImplicitPrelu on timplicitly import dynamic XImplicitPrelude de Prelude XNoMonomorphismR Disable the monomorphism dynamic XMonomorphismRre estriction restriction y striction i rt for n k A XNOoNPlusKPatterns Disable supporti inr dynamic XNPlusKPatterns patterns Mak
13. fno cse Turns off the common sub expression elimination optimisation Can be useful if you have some unsafePerf ormloO expressions that you don t want commoned up fno strictness Turns off the strictness analyser sometimes it eats too many cycles The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 69 240 fno full laziness Turns off the full laziness optimisation also known as let floating Full laziness increases sharing which can lead to increased memory residency NOTE GHC doesn t implement complete full laziness When optimisation in on and fno full laziness is not given some transformations that increase sharing are performed such as extracting repeated computations from a loop These are the same transformations that a fully lazy implementation would do the difference is that GHC doesn t consis tently apply full laziness so don t rely on it fspec constr Turn on call pattern specialisation fliberate case Turn on the liberate case transformation fstatic argument transformation Turn on the static argument transformation fno state hack Turn off the state hack whereby any lambda with a State token as argument is considered to be single entry hence it is considered OK to inline things inside it This can improve performance of IO and ST monad code but it runs the risk of reducing sharing fomit interface pragmas Tells GHC to omit all inessential information from the in
14. gt tvsrignt Of the class every type variable in S t VSright Must appear in S t vsjefi Where S is the substitution mapping each type variable in the class declaration to the corresponding type in the instance declaration These restrictions ensure that context reduction terminates each reduction step makes the problem smaller by at least one constructor Both the Paterson Conditions and the Coverage Condition are lifted if you give the KUndecidableInstances flag Section 7 6 3 3 You can find lots of background material about the reason for these restrictions in the paper Understanding functional dependencies via Constraint Handling Rules For example these are OK The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 160 240 instance C Int a Multiple parameters instance Eq S a Structured type in head Repeated type variable in head instance C4 a a gt C4 a a instance Stateful ST s MutVar s Head can consist of type variables only instance Ca instance Eq a Show b gt C2 ab Non type variables in context instance Show s a gt Show Sized s a instance C2 Int a gt C3 Bool a instance 2 Int a gt 3 al b But these are not Context assertion no smaller than head instance C a gt C a where C b b has more more occurrences of b than the head instance C b b gt Foo b where The same restrictions apply to instances generat
15. dep suffix lt suf gt Make extra dependencies that declare that files with suffix lt suf gt _ lt osuf gt depend on interface files with suffix lt suf gt _hi or for SOURCE imports on hi boot Multiple dep suffix flags are permitted For example dep suffix a dep suffix b will make dependencies for hs on hi a_hs on a_hi and b_hs on b_hi Useful in conjunction with NoFib ways exclude module lt file gt Regard lt file gt as stable i e exclude it from having dependencies on it include pkg deps Regard modules imported from packages as unstable i e generate dependencies on any imported package modules including Prelude and all other standard Haskell libraries Dependencies are not traced recursively into packages dependencies are only generated for home package modules on external package modules directly imported by the home package module This option is normally only used by the various system libraries lThis is a change in behaviour relative to 6 2 and earlier The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 53 240 4 6 12 Orphan modules and instance declarations Haskell specifies that when compiling module M any instance declaration in any module below M is visible Module A is below M if A is imported directly by M or if A is below a module that M imports directly In principle GHC must therefore read the interface files of every module bel
16. id The package ID It is up to you to choose a suitable one version The package s version usually in the form A B any number of components are allowed license string The type of license under which this package is distributed This field is a value of the License type license file optional string The name of a file giving detailed license information for this package copyright optional freeform The copyright string maintainer optinoal freeform The email address of the package s maintainer stability optional freeform A string describing the stability of the package eg stable provisional or experimental homepage optional freeform URL of the package s home page package url optional freeform URL of a downloadable distribution for this package The distribution should be a Cabal package description optional freeform Description of the package category optinoal freeform Which category the package belongs to This field is for use in conjunction with a future centralised package distribution framework tentatively titled Hackage author optional freeform Author of the package exposed bool Whether the package is exposed or not exposed modules string list modules exposed by this package The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 67 240 hidden modules string list modules provided by this package but not exposed to the programmer These modules cannot
17. maybeToBool Maybe a gt Bool maybeToBool Just x True maybeToBool Nothing False expectJust Maybe a gt a expectJust Just x x expectJust Nothing error Unexpected Nothing What is clunky doing The guard ok1 amp amp ok2 checks that both lookups succeed using maybeToBool to convert the M aybe types to booleans The lazily evaluated expect Just calls extract the values from the results of the lookups and binds the returned values to val1 and val2 respectively If either lookup fails then clunky takes the otherwise case and returns the sum of its arguments This is certainly legal Haskell but it is a tremendously verbose and un obvious way to achieve the desired effect Arguably a more direct way to write clunky would be to use case expressions The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 130 240 clunky env varl var2 case lookup env varl of Nothing gt fail Just vall gt case lookup env var2 of Nothing gt fail Just vella gt yall gt valz where enl yenil ap Venez This is a bit shorter but hardly better Of course we can rewrite any set of pattern matching guarded equations as case expres sions that is precisely what the compiler does when compiling equations The reason that Haskell provides guarded equations is because they allow us to write down the cases we want to consider one at a time independently of each other This structure is hidden i
18. MKFoo a gt la gt Bool gt Foo Any data type that can be declared in standard Haskell 98 syntax can also be declared using GADT style syntax The choice is largely stylistic but GADT style declarations differ in one important respect they treat class constraints on the data constructors differently Specifically if the constructor is given a type class context that context is made available by pattern matching For example data Set a where MkSet Eq a gt a gt Set a makeSet Eq a gt a gt Set a makeSet xs MkSet nub xs insert 88 E gt Sel a gt Ser e insert a MkSet as a elem as MkSet as otherwis MkSet a as A use of MkSet as a constructor e g in the definition of makeSet gives rise toa Eq a constraint as you would expect The new feature is that pattern matching on MkSet as in the definition of insert makes available an Eq a context In implementation terms the MkSet constructor has a hidden field that stores the Eq a dictionary that is passed to MkSet so when pattern matching that dictionary becomes available for the right hand side of the match In the example the equality dictionary is used to satisfy the equality constraint generated by the call to elem so that the type of insert itself has no Eq constraint For example one possible application is to reify dictionaries data NumInst a where MkNumInst Num a gt NumInst a Dacia 28 Nin
19. and brackets curly braces alone would ambiguous when they appear on right hand sides an extension we anticipate wanting 7 16 3 Terminology and restrictions Terminology A generic default method in a class declaration is one that is defined using type patterns as above A polymorphic default method is a default method defined as in Haskell 98 A generic class declaration is a class declaration with at least one generic default method Restrictions e Alas we do not yet implement the stuff about constructor names and field labels e A generic class can have only one parameter you can t have a generic multi parameter class e A default method must be defined entirely using type patterns or entirely without So this is illegal class Foo a where Ga 38 a gt lap BOOL op Unit Unit Unit True op Xx x False However it is perfectly OK for some methods of a generic class to have generic default methods and others to have polymorphic default methods e The type variable s in the type pattern for a generic method declaration scope over the right hand side So this is legal note e the use of the type variable p in a type signature on the right hand side class Foo a where QS 8 a gt BOOI Go a ss a il e ses Y 09 E 28 19 e The type patterns in a generic default method must take one of the forms O Bt 88 Jo Unit where a and b are type variables Furthermore all the ty
20. s Guide Version 6 12 2 169 240 Type family instance declarations are only legitimate when an appropriate family declaration is in scope just like class instances require the class declaration to be visible Moreover each instance declaration has to conform to the kind determined by its family declaration and the number of type parameters in an instance declaration must match the number of type parameters in the family declaration Finally the right hand side of a type instance must be a monotype i e it may not include foralls and after the expansion of all saturated vanilla type synonyms no synonyms except family synonyms may remain Here are some examples of admissible and illegal type instances Eye rany 1 el Re 2 type instance F Int Int 06 type instance F String Char OI type instance F F a a WRONG type parameter mentions a type family type instance F forall a a b b WRONG a forall type appears in a type parameter type instance F Float forall a a WRONG right hand side may not be a forall type cias Esimbllly 2 D 23 gt 3 type instance G Int 7 WRONG must be two type parameters type instance G Int Char Float Double WRONG must be two type parameters 7 7 2 2 1 Associated type instance declarations When an associated family instance is declared within a type class instance we drop the instance keyword in the family instance So the e instance
21. than using make see Section 4 4 1 for details E Evaluate expr see node a Section 4 4 2 for details Generate dependency information suitable for use M mode ina Makefile see Section 4 6 11 for details 4 18 4 Redirecting output Section 4 6 4 Flag Description Static Dynamic Reverse Eora set the suffix to use for dynamic PA intermediate C files y A set directory for interface dae files set the suffix to use for hisuf suffix y dynamic interface files o filename set output filename dynamic odir dir set directory for object files dynamic SO set the filename in which to R ohi filename p dynamic put the interface osuf suffix set the output file suffix dynamic stubdir dir redirect FFi stub files dynamic outputdir dir set output directory dynamic 4 18 5 Keeping intermediate files Section 4 6 5 Flag Description Static Dynamic Reverse keep hc fileor retain intermediate hc 4 dynamic keep hc files files s fil di e y A O A retain intermediate s files dynamic z keep s files keep raw s file or retain intermediate dynamic keep raw s files raw_s files retain all intermediate keep tmp files dynamic temporary files 4 18 6 Temporary files Section 4 6 6 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 92 240
22. with a bang pattern GHC resolves this ambiguity in favour of the latter If you want to define with bang patterns enabled you have to do so using prefix notation The semantics of Haskell pattern matching is described in Section 3 17 2 of the Haskell Report To this description add one extra item 10 saying e Matching the pattern pat against a value v behaves as follows if v is bottom the match diverges otherwise pat is matched against v Similarly in Figure 4 of Section 3 17 3 add a new case t case v of pat gt e _ gt e v seq case v of pat gt e _ gt e That leaves let expressions whose translation is given in Section 3 12 of the Haskell Report In the translation box first apply the following transformation for each pattern pi that is of form qi ei transform it to xi qi ei and and replace e0 by xi seq e0 Then when none of the left hand side patterns have a bang at the top apply the rules in the existing box The effect of the let rule is to force complete matching of the pattern qi before evaluation of the body is begun The bang is retained in the translated form in case qi is a variable thus let ly f x in b The let binding can be recursive However it is much more common for the let binding to be non recursive in which case the following law holds let p rhs in body is equivalent to case rhs of p gt body A pattern with a bang at
23. y Ignore marks Print out usage information 5 5 1 Manipulating the hp file Notes kindly offered by Jan Willhem Maessen The FOO hp file produced when you ask for the heap profile of a program FOO is a text file with a particularly simple structure Here s a representative example with much of the actual data omitted JO MOJO a MCH DAME WA Dee AG iseily ZOOAYW SAMPLE UNIT seconds VALUE_UNIT bytes BEGIN_SAMPLE 0 00 END_SAMPLE 0 00 BEGIN_SAMPLE 15 07 AS ampules LAT END_SAMPLE 15 07 BEGIN_SAMPLE 30 23 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 113 240 sample data END_SAMPLE 30 23 GEC BEGIN_SAMPLE 11695 47 END_SAMPLE 11695 47 The first four lines JOB DATE SAMPLE_UNIT VALUE_UNIT form a header Each block of lines starting with BEGIN_S AMPLE and ending with END_SAMPLE forms a single sample you can think of this as a vertical slice of your heap profile The hp2ps utility should accept any input with a properly formatted header followed by a series of complete samples 5 5 2 Zooming in on regions of your profile You can look at particular regions of your profile simply by loading a copy of the hp file into a text editor and deleting the unwanted samples The resulting hp file can be run through hp2ps and viewed or printed 5 5 3 Viewing the heap
24. 20 00 000 0000 000000000000 91 4 18 6 Temporary files sss seors acera eS RE RRR ee a we eo 91 418 7 FINE POS teo it de A SUES AAA ee wad ware Sx 92 4 18 8 Interface Me Options ss srta a Pe ee Be wR oe ees 92 4 18 9 Recompilation checking 20 0 a 92 4 18 10 Interactive mode Options 92 ALIS IU Packages oseo a a a a a A ad amp a 93 4 18 12 Language aptos 93 4 18 13 Warnings o e oe A eke ee eo AAN 95 4 18 14 Optimisation levels 4 3 6 24 bee oe le ee be EM Gyo be ewes Eee PRPS wd G s 97 4 18 15 Individual optimisations ee 97 4 18 16 Profiling options 2220002 SR OD a e A ee 98 4 18 17 Program coverage options 2 a 99 4 18 18 Haskell pre processor options a 99 4 18 19 C pre processor options a 99 4 18 20 Code generation aptos 99 4 18 2 Linking OpuiOns sws wa RG po RR Be AI a OE a we ek Rear ce ak 100 4 18 22 Replacing phases 2 essresrvvsesn testre unto SNESE EKES E SS 100 4 18 23 Forcing options to particular phases ee 101 4 18 24 Platform specific Options 101 4 18 25 External core file Options n reen paea apese e a E e e E a 101 4 18 26 Compiler debugging options 2 e a 102 4 18 27 Misc compiler options osaa a 103 5 Profiling 104 5 1 Cost centres and cost centre Stacks 104 5 1 1 Inserting cost centres by hand e a 00000002 e a e a e ee 106 5 1 2 Rules for attributing costs oaaae ee 107 5 2 Compiler options for
25. If the last character of size is a K or k multiply by 1000 if an M or m by 1 000 000 if a G or G by 1 000 000 000 And any wraparound in the counters is your fault Giving a RTS f option will print out the RTS options actually available in your program which vary depending on how you compiled NOTE since GHC is itself compiled by GHC you can change RTS options in the compiler using the normal RTS RTS combination eg to increase the maximum heap size for a compilation to 128M you would add RTS M128m RTS to the command line 4 15 1 Setting global RTS options RTS options are also taken from the environment variable GHCRTS For example to set the maximum heap size to 128M for all GHC compiled programs using an sh like shell GHCRTS M128m export GHCRTS RTS options taken from the GHCRTS environment variable can be overridden by options given on the command line 4 15 2 Miscellaneous RTS options Vsecs Sets the interval that the RTS clock ticks at The runtime uses a single timer signal to count ticks this timer signal is used to control the context switch timer Section 4 12 and the heap profiling timer Section 5 4 1 Also the time profiler uses the RTS timer signal directly to record time profiling samples Normally setting the V option directly is not necessary the resolution of the RTS timer is adjusted automatically if a short interval is requested with the C or i options However setting V i
26. In particular this means that the full module name must be given after the module keyword at the beginning of the module for example the module A B C must begin module A B C It is a common strategy to use the as keyword to save some typing when using qualified names with hierarchical modules For example impor teua lkb kedicontrolNMonadro M otr eeso For details on how GHC searches for source and interface files in the presence of hierarchical modules see Section 4 6 3 GHC comes with a large collection of libraries arranged hierarchically see the accompanying library documentation More libraries to install are available from HackageDB 7 3 5 Pattern guards The discussion that follows is an abbreviated version of Simon Peyton Jones s original proposal Note that the proposal was written before pattern guards were implemented so refers to them as unimplemented Suppose we have an abstract data type of finite maps with a lookup operation lookup FiniteMap gt Int gt Maybe Int The lookup returns Not hing if the supplied key is not in the domain of the mapping and Just v otherwise where v is the value that the key maps to Now consider the following definition clunky env varl var2 okl amp amp ok2 vall val2 otherwise varl var2 where ml lookup env varl m2 lookup env var2 okl maybeToBool ml ok2 maybeToBool m2 vall expectJust ml val2 expectJust m2 The auxiliary functions are
27. It refers to the input to the arrow In the above example lt is not an identifier but an new reserved symbol used for building commands from an expression of arrow type and an expression to be fed as input to that arrow The weird look will make more sense later It may be read as analogue of application for arrows The above example is equivalent to the Haskell expression ane NAS gt gt E That would make no sense if the expression to the left of lt involves the bound variable x More generally the expression to the left of lt may not involve any local variable i e a variable bound in the current arrow abstraction For such a situation there is a variant lt lt as in PROS ES ll which is equivalent to arr x EE O SSS zis so in this case the arrow must belong to the ArrowAppl y class Such an arrow is equivalent to a monad so if you re using this form you may find a monadic formulation more convenient 7 10 1 do notation for commands Another form of command is a form of do notation For example you can write procki S Clo WSS i E ll g lt 2xy let z x y T lt In lt 3 returnA lt t z You can read this much like ordinary do notation but with commands in place of monadic expressions The first line sends the value of x 1 as an input to the arrow f and matches its output against y In the next line the output is discarded The arrow returnA is defined in the Control Arrow module as arr id The
28. S_GHC pragma in a source file or set using set in GHCi Static Flags A few flags are static which means they can only be used on the command line and remain in force over the entire GHC GHCi run The flag reference tables Section 4 18 lists the status of each flag There are a few flags that are static except that they can also be used with GHCi s set command these are listed as static set in the table 4 3 Meaningful file suffixes File names with meaningful suffixes e g 1hs or o cause the right thing to happen to those files hs A Haskell module 1hs A literate Haskell module hi A Haskell interface file probably compiler generated hc Intermediate C file produced by the Haskell compiler c AC file not produced by the Haskell compiler s An assembly language source file usually produced by the compiler o An object file produced by an assembler Files with other suffixes or without suffixes are passed straight to the linker 4 4 Modes of operation GHC s behaviour is firstly controlled by a mode flag Only one of these flags may be given but it does not necessarily need to be the first option on the command line The available modes are ghc interactive Interactive mode which is also available as ghci Interactive mode is described in more detail in Chapter 2 ghc make In this mode GHC will build a multi module Haskell program automatically figuring out
29. TUS NO OS ES mot AS OPS Here the pattern signatures for ys and zs are fine but the one for v is not because b is not in scope However in all patterns other than pattern bindings a pattern type signature may mention a type variable that is not in scope in this case the signature brings that type variable into scope This is particularly important for existential data constructors For example data T forall a MkT a k gt T k Mk Esa MRT tes where eses leal lt ere Here the pattern type signature t a mentions a lexical type variable that is not already in scope Indeed it cannot already be in scope because it is bound by the pattern match GHC s rule is that in this situation and only then a pattern type signature can mention a type variable that is not already in scope the effect is to bring it into scope standing for the existentially bound type variable When a pattern type signature binds a type variable in this way GHC insists that the type variable is bound to a rigid or fully known type variable This means that any user written type signature always stands for a completely known type If all this seems a little odd we think so too But we must have some way to bring such type variables into scope else we could not name existentially bound type variables in subsequent type signatures This is now the only situation in which a pattern type signature is allowed to mention a lexical variable that is
30. class CollE s where empty class CollE s gt Coll s a where IMs BY gt Cl gt si 7 6 2 2 Background on functional dependencies The following description of the motivation and use of functional dependencies is taken from the Hugs user manual reproduced here with minor changes by kind permission of Mark Jones Consider the following class intended as part of a library for collection types class Collects ce wher EMPTY ce insert gt C gt member gt gt Bool The type variable e used here represents the element type while ce is the type of the container itself Within this framework we might want to define instances of this class for lists or characteristic functions both of which can be used to represent collections of any equality type bit sets which can be used to represent collections of characters or hash tables which can be used to represent any collection whose elements have a hash function Omitting standard implementation details this would lead to the following declarations instance Eq gt Collects e wher instance Eq gt Collects gt Bool where instance Collects Char BitSet where instance Hashable e Collects a ce gt Collects e Array Int ce where All this looks quite promising we have a class and a range of interesting implementations Unfortunately there are some serious problems with the class declaration First the empty function has an ambiguous typ
31. mpl See also the funbox strict fields flag which essentially has the effect of adding UNPACK to every strict constructor field 7 13 12 SOURCE pragma The SOURC Section 4 6 9 CJ pragma is used only in import declarations to break a module loop It is described in detail in 7 14 Rewrite rules The programmer can specify rewrite rules as part of the source program in a pragma Here is an example RULES map map tonal amp G xa naD map o xs map TG xS y Use the debug flag ddump simpl stats to see what rules fired If you need more information then ddump rule f irings shows you each individual rule firing in detail 7 14 1 Syntax From a syntactic point of view e There may be zero or more rules in a RULES pragma separated by semicolons which may be generated by the layout rule e The layout rule applies in a pragma Currently no new indentation level is set so if you put several rules in single RULES pragma and wish to use layout to separate them you must lay out the starting in the same column as the enclosing definitions RULES map map BOB aos mao ae mea Gg xS mao 0 xS map append forall f xs ys map f xs ys map f xs map f ys The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 201 240 Furthermore the closing should start in a column to the right of the opening Eac
32. s gcc or mingw s gcc or on a real unix system that little program can also deal with escaping V in paths Apart from the banner and the startup time something like this would also do The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 225 240 amp echo Directory getCurrent Directory gt DULCE DIEM mE o CaLlL y shew allege 11 6 Building and using Win32 DLLs Making Haskell libraries into DLLs doesn t work on Windows at the moment we hope to re instate this facility in the future see Section 4 11 Note that building an entire Haskell application as a single DLL is still supported it s just multi DLL Haskell programs that don t work The Windows distribution of GHC contains static libraries only 11 6 1 Creating a DLL Sealing up your Haskell library inside a DLL is straightforward compile up the object files that make up the library and then build the DLL by issuing a command of the form ghe shared o foo dll bar o baz o wibble a lfooble By feeding the ghc compiler driver the option shared it will build a DLL rather than produce an executable The DLL will consist of all the object files and archives given on the command line A couple of things to notice e By default the entry points of all the object files will be exported from the DLL when using shared Should you want to constrain this you can specify the module definition file to use on the command line as follo
33. t need to be witnessed at this point it can be floated out Furthermore floating them out increases sharing Lastly excluding them is a conservative choice it leaves a patch of territory free in case we need it later 7 8 3 Implicit parameters Implicit parameters are implemented as described in Implicit parameters dynamic scoping with static types J Lewis MB Shields E Meijer J Launchbury 27th ACM Symposium on Principles of Programming Languages POPL 00 Boston Jan 2000 Most of the following still rather incomplete documentation is due to Jeff Lewis Implicit parameter support is enabled with the option XImplicitParams A variable is called dynamically bound when it is bound by the calling context of a function and statically bound when bound by the callee s context In Haskell all variables are statically bound Dynamic binding of variables is a notion that goes back to Lisp but was later discarded in more modern incarnations such as Scheme Dynamic binding can be very confusing in an untyped language and unfortunately typed languages in particular Hindley Milner typed languages like Haskell only support static scoping of variables However by a simple extension to the type class system of Haskell we can support dynamic binding Basically we express the use of a dynamically bound variable as a constraint on the type These constraints lead to types of the form x t gt t which says this function uses a d
34. the outside any attempt to apply _this _inc or _display as functions will raise a compile time error In other words GHC defines a record selector function only for fields whose type does not mention the existentially quantified variables This example used an underscore in the fields for which record selectors will not be defined but that is only programming style GHC ignores them To make use of these hidden fields we need to create some helper functions inc Counter a gt Counter a inc NewCounter x i d t NewCounter clus al ame a Cele cl ua ic y diis pilay 23 Colimerz E gt 10 display NewCounter _this x _display d d x Now we can define counters with different underlying implementations counterA Counter String counterA NewCounter T class 0 aie lsh chisjolleyy joiestioe ieee Wri 5 counterB Counter String counterB NewCounter Je SS 44 im 139 _chisiulety jowtcSicicin tag Wie main do display inc counterA tara Wi display inc inc counterB prints Record update syntax is supported for existentials and GADTs seutas 238 Colina a gt gt Coline a setTag obj t obj tag t The rule for record update is this the types of the updated fields may mention only the universally quantified type variables of the data constructor For GADTs the field may mention only types that appear as a simple type variable argument in t
35. with the additional option t which indicates that the each event printed should be preceded by a timestamp value in the binary event log file all events are automatically associated with a timestamp The debugging options Dx also generate events which are logged using the tracing framework By default those events are dumped as text to stdout Dx implies v but they may instead be stored in the binary eventlog file by using the 1 option 4 15 7 RTS options for hackers debuggers and over interested souls These RTS options might be used a to avoid a GHC bug b to see what s really happening or c because you feel like it Not recommended for everyday use B Sound the bell at the start of each major garbage collection Oddly enough people really do use this option Our pal in Durham England Paul Callaghan writes Some people here use it for a variety of purposes honestly e g confirmation that the code machine is doing something infinite loop detection gauging cost of recently added code Certain people can even tell what stage the program is in by the beep pattern But the major use is for annoying others in the same office Dx An RTS debugging flag only availble if the program was linked with the debug option Various values of x are provided to enable debug messages and additional runtime sanity checks in different subsystems in the RTS for example RTS Ds RTS enables debug messages from
36. 1 Associated type instance declarations o e a 169 7 7 2 2 2 Overlap of type synonym instances ee ee ee 169 7 72 2 3 Decidability of type synonym instances 2 2 eee ee ee 169 7 7 2 3 Equality constraints gt es ee 170 7 7 2 4 Type families and instance declarations 2 2 ee 170 7 8 Other type system extensions cs ee ee Ee EE EH EEE ee ee ee eee ees 171 7 8 1 Explicit universal quantification forall 2 ee 171 7 8 2 The context of a type Signature 171 7 8 3 Implicit parameters se s s eeoa ee A ee ee ee we 172 7 8 3 1 Implicit parameter type constraints 0 0 0 0 0 00000000000 173 7 8 3 2 Implicit parameter bindings ooo e 173 7 8 3 3 Implicit parameters and polymorphic recursion s osoo a 174 7 8 3 4 Implicit parameters and monomorphism s sooo e 174 7 8 4 Explicitly kinded quantification 000 2 ee ee 174 7 8 5 Arbitrary rank polymorphism saaa ee 175 18 3 L Examples 1 ga age a eee Ee ad a a E 176 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 xii T8D2 Type inference os sc ke ae Pee R ae Se Oa RE ee Ped YA Sees eS 177 7 8 5 3 Tmplhcitguantification s 4s 6 24344 es BS heed a Gs Serie ARS i 5 178 7 8 6 Impredicative polymorphism 1 2 0 0 02 pe ee 178 7 8 7 Lexically scoped type variables 2 2 ee 179 POTN MOVCNIEW 24 205 54 22 ae eethe AA SAS Oe 179 7 8 7 2
37. 14 Integer omp curra Sk Rs AS EO REGS Ra goe ees 12 1 6 10 15 nteger simpl e e s 5 ea eR we Ee bee ew ae 12 1 6 10 16 old locale 2 oeoc sac epa eR RE oea RRR EE e o a Ee 12 16 1017 old time 24 5344 eA ES ee ee ee eA OR Re Re eee 12 V6 10 18 packedsting s ee eG ER RG Re ROA a ee AR eee ak 12 16 1009 pretty nk ces RR A RS e o ee SY eee ee OS 13 6 10 20ProcCess 2 5 5 has do SS 4 eh be A 3S 13 1 6 10 21 TandoM ke ter a o Oe SS 13 1O10 22 SYD 3 ue il ie Bee o de A ea lee eats Be E eh es amp amp 13 1 6 10 23 template haskelll ws sas 84528 ae 6G eee E EY ee eS We See ds e 13 ECAODA UME gt 23 8 eee es BREE GES bobo ee eS ewe AS Behe ees 3 WO O25 UDI oir a A E weal gos SR a AA e 13 1 6 10 26 WIN iria bw A A 13 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 v 2 Using GHCi 14 2 1 Introduction to GHCI 2 2 4 ata BG MOR AA ARA BRS Cae e aoe Eee ok 14 2 2 Loading source fil s lt ocg eo a ee OE Ba eee ae de wa eR a eo 14 2 2 1 Modules vs filenames os s soco a ma aa ao e ee 15 2 2 2 Making changes and recompilation 2 00 00 eee ee 15 2 3 Loading compiled code s essa p Ri e a a Be eRe e 16 2 4 Interactive evaluation at the prompt 17 2 4 1 TO actions at the prompt 2 2 17 2 4 2 Using do notation atthe prompt 18 2 43 What s really in scope atthe prompt 2 2 2 02 0 0 002 eee ee 19 ZAS smodule dnd soa hence eas BAe toh ea E ae ee oe SS ee ee E 20 2 4 3
38. 56 fwarn overlapping patterns 56 fwarn simple patterns 56 fwarn tabs 56 fwarn type defaults 56 fwarn unrecognised pragmas 54 fwarn unused binds 56 fwarn unused do bind 57 fwarn unused imports 56 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 fwarn unused matches 57 fwarn warnings deprecations 54 fwarn wrong do bind 57 h lt break down gt 111 hC RTS option 109 hT RTS option 83 hb RTS option 109 he RTS option 109 hesuf 47 hd RTS option 109 hi diffs option 218 hide package 59 hidir 47 hisuf 47 hm RTS option 109 hr RTS option 109 hy RTS option 109 1 109 idirs 46 ignore dot ghci 37 ignore package 59 ignore scc 108 k RTS option 81 keep hc file 47 keep hc files 47 keep raw s file 47 keep raw s files 47 keep s file 47 keep s files 47 keep tmp files 47 1 72 RTS option 84 m RTS option 81 m options 78 main is 73 monly N regs option 1X86 only 78 n 44 no auto link packages 59 no hs main 73 213 no user package conf 60 0 46 odir 46 ohi 47 optF 70 optL 70 optP 70 opta 70 235 240 optc 70 optdll 70 optl 70 optm 70 optwindres 70 osuf 47 185 outputdir 47 p 108 RTS option 104 package 58 73 package conf 60 64 package id 59 package name 59 pgmF 70 101 pgmL 69 101 pgmP 69 101 pgma 70 101 pgmc 69 101 pg
39. Chapter 5 Profiling Glasgow Haskell comes with a time and space profiling system Its purpose is to help you improve your understanding of your program s execution behaviour so you can improve it Any comments suggestions and or improvements you have are welcome Recommended profiling tricks would be especially cool Profiling a program is a three step process 1 Re compile your program for profiling with the prof option and probably one of the auto or auto all options These options are described in more detail in Section 5 2 2 Run your program with one of the profiling options eg RTS p RTS This generates a file of profiling information Note that multi processor execution e g RTS N2 is not supported while profiling 3 Examine the generated profiling information using one of GHC s profiling tools The tool to use will depend on the kind of profiling information generated 5 1 Cost centres and cost centre stacks GHC s profiling system assigns costs to cost centres A cost is simply the time or space required to evaluate an expression Cost centres are program annotations around expressions all costs incurred by the annotated expression are assigned to the enclosing cost centre Furthermore GHC will remember the stack of enclosing cost centres for any given expression at run time and generate a call graph of cost attributions Let s take a look at an example metia joio Goerallo 25 welo m
40. Declaration type signatures 2 ee 180 7 8 7 3 Expression type signatures ee 180 78 4 Pattern type signatures socos soe 255 2 a GG Ba ee AG BO ee 180 7 8 7 5 Class and instance declarations 1 2 e 181 7 8 8 Generalised typing of mutually recursive bindings e e 181 7 8 9 Monomorphic local bindings 2 2 2 2 02 ee 182 79 Template Haskell ica rra ee gd de aa eee ee de Re oe ew ee SO 182 POM SAAR ge bee Be Aes ee Be eee Oe Ree ie GE ee E ee Oe Gee e Ae 182 79 2 Using Template Haskell 2 44 see be RRP PER ERE RE REE ee ee Le 183 7 9 3 A Template Haskell Worked Example 02 2 0 000000000 eee ee 184 7 9 4 Using Template Haskell with Profiling 2 2 0 0 2000000000000 0000 185 7 9 5 Template Haskell Quasi quotation 2 2 0 000 0002 ee ee 185 PAO Arow notation ria A Bw BAe a Is e ee GS Ale Ge ds EE ees ox 187 7 10 1 do notation for commands 2 2 ee 188 7 10 2 Conditionalcommands 2 2 ee ee 189 7 10 3 Defining your own control structures 2 ee 189 T104 Primitive constructs sci i005 a Re EA RR E ee eS ER e Y 190 7 10 5 Differences withthe paper ee 191 7 10 60 Portability e aaa A A Re ee ee A Ge ee Re eee a 192 7 11 Bang pattems exi 5a ts Pe ee RR ee SARE ER a eee ee A 192 7 11 1 Informal description of bang patterns ee 192 7 11 2 Syntax and semantics 2 2 ee 193 TAZ ASSCMUODS mr eae B
41. GHC is derived according to the following rules where osuf is the object file suffix this can be changed with the osuf option e If there is no odir option the default then the object filename is derived from the source filename ignoring the module name by replacing the suffix with osuf e If odir dir has been specified then the object filename is dir mod osuf where mod is the module name with dots replaced by slashes GHC will silently create the necessary directory structure underneath dir if it does not already exist The name of the interface file is derived using the same rules except that the suffix is hisuf hi by default instead of osuf and the relevant options are hidir and hisuf instead of odir and osuf respectively For example if GHC compiles the module A B C in the file src A B C hs with no odir or hidir flags the interface file will be put in src A B C hi and the object file in src A B C o For any module that is imported GHC requires that the name of the module in the import statement exactly matches the name of the module in the interface file or source file found using the strategy specified in Section 4 6 3 This means that for most modules the source file name should match the module name However note that it is reasonable to have a module Main in a file named foo hs but this only works because GHC never needs to search for the interface for module Main because it is never imported It is th
42. Haskell utility programs 10 1 Ctags and Etags for Haskell hasktags 2 2 ee 10 1 1 Using tags with youreditor 2 2 ee 10 2 Yacc for Haskell happy 10 3 Writing Haskell interfaces to C code hse2hs 2 1 e 10 3 1 command line syntax 2 ee 10 3 2 Jnput syotax ice ee ea ee a eR ee a E a 103 3 CUSTOM COMSHUC S s e dn be eee aoe ho ee FOR Ae ER ee oe BO be ad we bo US BO ee Be aa Running GHC on Win32 systems 11 1 Starting GHC on Windows platforms 2 0 0 0 00 2 2 ee 11 2 Running GHCion Windows 11 3 Interacting with the terminal vince ei HR RR AER OER HER RE ROE AE ER ee e 11 4 Differences in library behaviour oaoa 11 5 Using GHC and other GHC compiled executables withcygwin o e 11 5 1 Backpround sea ee oe ee a heed be ee eR ae Se eee ee nae he ee a ee a oe 11 5 2 Lhe problem eii ee ka Bae eh SE eR Be lee Pe ea e Ae wale e L523 TOMES 1000 22 24 scee bt hee eS PHS ba A eee eS se 11 6 Building and using Win32 DLLs 2 0 ee 11 6 1 Creating A DEL ass cms a a ee eR EE ee eR as Ee wR Oe ee ee 11 6 2 Making DLLs to be called from other languages o o e e xiv 214 214 214 215 213 215 215 213 217 217 217 219 219 219 219 220 220 221 222 223 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 12 Known bugs and infelicities 12 1 Haskell 98 vs Glasgow Haskell language non
43. Hello lS Penner AS module Printf where Skeletal printf from the paper It needs to be in a separate module to the one wher gt NO eS CO se ia o Import some Template Haskell syntax import Language Haskell TH Describe a format string data Format D S L String Parse a format string This is left largely to you as we are here interested in building our first ever Template Haskell program and not in building printf Pots iS ln y O anal parse s bs Generate Haskell source code from a parsed representation of the format string This code will be spliced into the module which calls pr at compile time cea BS roma 0 12999 gen D An gt show n gen S gt s 11 gen L s stringE s Here we generate the Haskell code for the splice JEON cua E Ocio SNG hz 3 Sitreadias gt 0 150 pr s gen parse s Now run the compiler here we are a Cygwin prompt on Windows The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 185 240 ghe mak XTemplateHaskell main hs o main exe Run main exe and here is your output main Hello 7 9 4 Using Template Haskell with Profiling Template Haskell relies on GHC s built in bytecode compiler and interpreter to run the splice expressions The bytecode inter preter runs the compiled expression on top of the same runtime on which GHC itself is running this
44. M C M a a a This is useful if the field selector a for constructor M C is only in scope in qualified form The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 139 240 7 3 16 Record wildcards Record wildcards are enabled by the flag KRecordWildCards This flag implies XDisambiguateRecordFields For records with many fields it can be tiresome to write out each field individually in a record pattern as in esta C fe s2 fac lo 2 for 2s lbag el S3 nc 2 C la ip 19 p Gp el d D r amp ap Gl Record wildcard syntax permits a in a record pattern where each elided field f is replaced by the pattern f f For example the above pattern can be written as E 6 fa il oof lo sa E 32 el More details e Wildcards can be mixed with other patterns including puns Section 7 3 15 for example ina pattern C a 1 b Additionally record wildcards can be used wherever record patterns occur including in let bindings and at the top level For example the top level binding C a 1 e defines b c and d e Record wildcards can also be used in expressions writing for example let a o ce Sp ol A A ah in place of let a O ce Sp l 4 in C a a b b c c d d The expansion is purely syntactic so the record wildcard expression refers to the nearest enclosing variables that are spelled the same as the omitted field names e
45. Mai n hs where it is used but must be imported Main hs module Main where import Expr mesita 2 8 IO main do print eval Sexpr 1 2 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 Case t i ESOS module Expr where import qualified import Language H data Expr Int Ant Bin Ant deriving Show data BinOp Ad Su Mu Wat deriving Show Sveul gp lmao gt I eval IntExpr n eval BinopExpr o where opToFun AddOp opToFun SubOp opToFun MulOp opToFun DivOp expr QuasiQuote Meets Ela oey either a Q Exp for how to use parser of type separate pars parseExprExp S parseExprExp paris eExprratio parseExprPat Now run the compiler PEO Sep ta l gt in askell TH Quote Expr Integer AS e gt return Language Haskell TH as TH opExpr BinOp Expr Expr iExpr String Typeable Data dop bOp 10p vOp Typeable Data Heeger n px y opToFun op eval x eval y Ga div r parseExprExp parse ExprPat returning its representation as Gr a O an S th referenced paper SYB to do this by writing a single String gt Expr instead of two rs ROO Telno gt O Pere ghc make XQuasiQuotes Main hs o main Run main and here is your outpu
46. Maybe a gt a Data Maybe isJust Maybe a gt Bool Data Maybe isNothing Maybe a gt Bool Data Maybe listToMaybe a gt Maybe a Data Maybe mapMaybe a gt Maybe b gt a gt b Data Maybe maybeToList Maybe a gt a imported via Prelude Just a gt Maybe a data Maybe a Nothing Just a Nothing Maybe a mesos 8 lo gt a gt lo gt Maybe a gt b This output shows that in the context of the current session in the scope of Prelude the first group of items from Data Maybe have not been imported but are available in fully qualified form in the GHCi session see Section 2 4 3 whereas the second group of items have been imported via Prelude and are therefore available either unqualified or with a Prelude qualifier cd dir Changes the current working directory to dir A symbol at the beginning of dir will be replaced by the contents of the environment variable HOME NOTE changing directories causes all currently loaded modules to be unloaded This is because the search path is usually expressed using relative directories and changing the search path in the middle of a session is not supported cmd expr Executes expr as a computation of type IO String and then executes the resulting string as a list of GHCi commands Multiple commands are separated by newlines The cmd command is useful with def and set stop continue Continue the current evaluation when stopped
47. No NOINLINE 2 f No Maybe NOINLINE 2 f Maybe No INLINE f Yes Yes NOINLINE No No By Maybe we mean that the usual heuristic inlining rules apply if the function body is small or it is applied to interesting looking arguments etc Another way to understand the semantics is this e For both INLINE and NOINLINE the phase number says when inlining is allowed at all The INLINE pragma has the additional effect of making the function body look small so that when inlining is allowed it is very likely to happen The same phase numbering control is available for RULES Section 7 14 7 13 6 ANN pragmas GHC offers the ability to annotate various code constructs with additional data by using three pragmas This data can then be inspected at a later date by using GHC as a library 7 13 6 1 Annotating values Any expression that has both Typeable and Data instances may be attached to a top level value binding using an ANN pragma In particular this means you can use ANN to annotate data constructors e g Just as well as normal values e g take By way of example to annotate the function foo with the annotation Just Hello you would do this ANN foo Just Hello OO not A number of restrictions apply to use of annotations e The binder being annotated must be at the top level i e no nested binders e The binder being annotated must be declared in the curr
48. Singh and Simon Marlow have developed ThreadScope a GUI that lets you see what is going on inside your parallel program It s a huge step forward from It takes 4 seconds with 1 processor and 3 seconds with 8 processors now what ThreadScope will be released separately from GHC but at more or less the same time as GHC 6 12 Dynamic linking is now supported on Linux and support for other platforms will follow Thanks for this most recently go to the Industrial Haskell Group who pushed it into a fully working state dynamic linking is the culmination of the work of several people over recent years One effect of dynamic linking is that binaries shrink dramatically because the run time system and libraries are shared Perhaps more importantly it is possible to make dynamic plugins from Haskell code that can be used from other applications The I O libraries are now Unicode aware so your Haskell programs should now handle text files containing non ascii charac ters without special effort The package system has been made more robust by associating each installed package with a unique identifier based on its exposed ABI Now cases where the user re installs a package without recompiling packages that depend on it will be detected and the packages with broken dependencies will be disabled Previously this would lead to obscure compilation errors or worse segfaulting programs This change involved a lot of internal restructuring but it pa
49. The expands to the missing in scope record fields where in scope includes both unqualified and qualified only Any fields that are not in scope are not filled in For example module M where deta R R a b c s Int module X where import qualified M R a b ic ek doy et A a The expands to M a a M b b omitting c since it is not in scope at all 7 3 17 Local Fixity Declarations A careful reading of the Haskell 98 Report reveals that fixity declarations infix infixl and infixr are permitted to appear inside local bindings such those introduced by let and where However the Haskell Report does not specify the semantics of such bindings very precisely In GHC a fixity declaration may accompany a local binding let E ccs alimutabyee S MES alin The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 140 240 and the fixity declaration applies wherever the binding is in scope For example in a let it applies in the right hand sides of other 1et bindings and the body of the 1etC Or in recursive do expressions Section 7 3 8 the local fixity declarations of a let statement scope over other statements in the group just as the bound name does Moreover a local fixity declaration must accompany a local binding of that name it is not possible to revise the fixity of name bound elsewhere as in Lee imkis 9 da Because local fixity declarations are technically Haskell 98 n
50. The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 172 240 When a value with this type was used the constraint Eq tv would be introduced where tv is a fresh type variable and in the dictionary translation implementation the value would be applied to a dictionary for Eq tv The difficulty is that we can never know which instance of Eq to use because we never get any more information about tv Note that the reachability condition is weaker than saying that a is functionally dependent on a type variable free in type see Section 7 6 2 The reason for this is there might be a hidden dependency in a superclass perhaps So reachable is a conservative approximation to functionally dependent For example consider class Cab a gt b where class C a b gt D ab where E 89 corali alo D a lo gt a gt A This is fine because in fact a does functionally determine b but that is not immediately apparent from s type 2 Every constraint ci must mention at least one of the universally quantified type variables t vi For example this type is OK because C a b mentions the universally quantified type variable b forall a C a b gt burble The next type is illegal because the constraint Eq b does not mention a forall a Eq b gt burble The reason for this restriction is milder than the other one The excluded types are never useful or necessary because the offending context doesn
51. The special family distinguishes family from standard data declarations The result kind annotation is optional and as usual defaults to x if omitted An example is data family Array e Named arguments can also be given explicit kind signatures if needed Just as with http www haskell org ghc docs latest html users_ gu GADT declarations named arguments are entirely optional so that we can declare Array alternatively with data familly Array gt x 7 7 1 1 1 Associated data family declarations When a data family is declared as part of a type class we drop the family special The GMap declaration takes the following form class GMapKey k where claizamG Malo wae stan E In contrast to toplevel declarations named arguments must be used for all type parameters that are to be used as type indexes Moreover the argument names must be class parameters Each class parameter may only be used at most once per associated type but some may be omitted and they may be in an order other than in the class head Hence the following contrived example is admissible class C a b c where clama T E 23 8 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 165 240 7 7 1 2 Data instance declarations Instance declarations of data and newtype families are very similar to standard data and newtype declarations The only two differences are that the keyword data or newt ype is followed by instance and that some or al
52. a a fwarn unused matches no longer warns about bindings introduced by C x The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 7 240 The RecordWildCards language extension implies DisambiguateRecordFields Declarations such as data T a where Mier gg orali a we a T x vw sk la Ya are now only accepted if the extension TypeOperators is on It is now possible to define GADT records with class constraints The syntax is data T a where Mier 22 oral a we a gt x vw sk la T a You can now list multiple GADT constructors with the same type e g data T where Es Cee i oe It is now possible to use GADT syntax for data families data instance T a where ti 33 gt FT E and make data instances be GADTs data instance T a where ial 88 mye gt We foe TA 8 gt OA Record updates can now be used with datatypes containing existential type variables provided the fields being altered do not mention the existential types The ImpredicativeTypes extension now imples the RankNTypes extension The ImpredicativeTypes extension is no longer enabled by fglasgow exts and has been deprecated You can now give multi line DEPRECATED and WARNING pragmas DEPRECATED defaultUserHooks Use simpleUserHooks or autoconfUserHooks unless you need Cabal 1 2 compatibility in which case you must stick with defaultUserHo
53. above example is treated as an abbreviation for AN S Ge gt gt AS arr Aa e k SSS a7 Sse eure Ye 8 We lr W See lose ame Y gt 2y gt gt gt q gt gt gt arr snd gt gt gt arr AN G y lar a xy E Zip 2 See Firet ari Ga S see SSS In aS arie Gt 2 ete gt returnA Note that variables not used later in the composition are projected out After simplification using rewrite rules see Section 7 14 defined in the Control Arrow module this reduces to auas os E gt gt piest E gt gt gt eure ia Es MDI See ESTE G SSS arr A Cr r y gt let z xy in ee D Ss ELESE la FoF A a gt teh The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 189 240 which is what you might have written by hand With arrow notation GHC keeps track of all those tuples of variables for you Note that although the above translation suggests that 1et bound variables like z must be monomorphic the actual translation produces Core so polymorphic variables are allowed It s also possible to have mutually recursive bindings using the new rec keyword as in the following example counter ArrowCircuit a gt a Bool Int counter proc reset gt do rec output lt returnA lt if reset then 0 else next next lt delay 0 lt output 1 PECUERA OU pat The translation of such forms uses the Loop combinator so the arrow concerned must
54. alae m lt 2 then L else miio mil sr mrio a2 Compile and run this program as follows S oae proi auto pall 0 Maine Menta las Main RTS p 121593 When a GHC compiled program is run with the p RTS option it generates a file called lt prog gt prof In this case the file will contain something like this Fri May 12 14 06 2000 Time and Allocation Profiling Report Final IMIG EMS SS The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 105 240 ATAR A 2 ms excludes profiling overheads 0 14 secs 8 741 204 bytes total time total alloc OS E CENTRE MODULE Stime Salloc nfib Main LOOO 100 10 individual inherited COST GENTRE ODULE entries Stime Salloc Stime Salloc MAIN IAIN 0 030 omo TOO ROMO ORO main ain 0 0 0 0 10 0 0 0 0 CAF PrelHandle 3 040 ORO 0 0 0 0 CAF PrelAddr als 0 0 0 0 0 0 0 0 CAF ain 6 CORO OO 100 0 100 0 main ain dE 0 0 0 0 OO ROMO ORO BO ain PARTOS LOOO OOO LOCO TOTO The first part of the file gives the program name and options and the total time and total memory allocation measured during the run of the program note that the total memory allocation figure isn t the same as the amount of live memory needed by the program at any one time the latter can be determined using heap profiling which we will describe shortly The second part of the file is a break down by cost centre of the most costly functions in
55. although not all extensions are supported by all compilers of course The LANGUAGE pragma should be used instead of OPTIONS_GHC if possible For example to enable the FFI and preprocessing with CPP LANGUAGE ForeignFunctionInterface CPP The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 195 240 LANGUAGE is a file header pragma see Section 7 13 Every language extension can also be turned into a command line flag by prefixing it with X for example XForeignFu nctionInterface Similarly all X flags can be written as LANGUAGE pragmas A list of all supported language extensions can be obtained by invoking ghc supported languages see Section 4 4 Any extension from the Extension type defined in Language Haskell Extension may be used GHC will report an error if any of the requested extensions are not supported 7 13 2 OPTIONS_GHC pragma The OPTIONS_GHC pragma is used to specify additional options that are given to the compiler when compiling this source file See Section 4 1 2 for details Previous versions of GHC accepted OPTIONS rather than OPTIONS_GHC but that is now deprecated OPTIONS_GHC is a file header pragma see Section 7 13 7 13 3 INCLUDE pragma The INCLUDE used to be necessary for specifying header files to be included when using the FFI and compiling via C It is no longer required for GHC but is accepted and ignored for compat
56. amount of live data This is because by default see the RTS F option we allow the old generation to grow to twice its size 2L before collecting it and we require additionally L bytes to copy the live data into When using compacting collection see the RTS c option this is reduced to 2L and can further be reduced by tweaking the F option Also add the size of the allocation area currently a fixed 512Kb The stack isn t counted in the heap profile by default See the RTS xt option The program text itself the C stack any non heap data eg data allocated by foreign libraries and data allocated by the RTS and mmap d memory are not counted in the heap profile 5 5 hp2ps heap profile to PostScript Usage hp2ps flags lt file gt hp The program hp2ps converts a heap profile as produced by the h lt break down gt runtime option into a PostScript graph of the heap profile By convention the file to be processed by hp2ps has a hp extension The PostScript output is written to lt file gt ps If lt file gt is omitted entirely then the program behaves as a filter hp2ps is distributed in ghc utils hp2ps in a GHC source distribution It was originally developed by Dave Wakeling as part of the HBC LML heap profiler The flags are The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 112 240 d In order to make graphs more readable hp2ps sorts the shaded bands for each
57. and perform a reload Normally pre compiled code for the module will be loaded if available or otherwise the module will be compiled to byte code Using the x prefix forces the module to be loaded as byte code back Travel back one step in the history See Section 2 5 5 See also t race history forward break identifier module line column Seta breakpoint on the specified function or line and column See Section 2 5 1 1 browse module Displays the identifiers defined by the module module which must be either loaded into GHCi or be a member of a package If module is omitted the most recently loaded module is used If the x symbol is placed before the module name then all the identifiers in scope in module are shown otherwise the list is limited to the exports of module The form is only available for modules which are interpreted for compiled modules including modules from packages only the non form of browse is available If the symbol is appended to the command data constructors and class methods will be listed individually otherwise they will only be listed in the context of their data type or class declaration The form also annotates the listing with comments giving possible imports for each group of entries Prelude gt browse Data Maybe not currently imported Data Maybe catMaybes Maybe a gt a Data Maybe fromJust Maybe a gt a Data Maybe fromMaybe a gt
58. at a breakpoint ctags filename etags filename Generates a tags file for Vi style editors ctags or Emacs style editors etags If no filename is specified the default tags or TAGS is used respectively Tags for all the functions constructors and types in the currently loaded modules are created All modules must be interpreted for these commands to work See also Section 10 1 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 33 240 def name expr def is used to define new commands or macros in GHCi The command def name expr defines a new GHCi command name implemented by the Haskell expression expr which must have type String gt IO String When name argsis typed at the prompt GHCi will run the expression name args take the resulting String and feed it back into GHCi as a new sequence of commands Separate commands in the result must be separated by An That s all a little confusing so here s a few examples To start with here s a new GHCi command which doesn t take any arguments or produce any results it just outputs the current date amp time Prelude gt let date _ Time getClockTime gt gt print gt gt return Prelude gt def date date Prelude gt date Hiei Malian SUS iG 410 EME 200M Here s an example of a command that takes an argument It s a re implementation of cd Prelude gt let mycd d Directory setCurrentDirector
59. becomes a legal instance declaration instance C Maybe Int where See also the rules on overlap e With the XTypeSynonymInstances flag instance heads may use type synonyms As always using a type synonym is just shorthand for writing the RHS of the type synonym definition For example type Point Int Int ins tence lewealiaic where instance C Point where is legal However if you added instance C Int Int where as well then the compiler will complain about the overlapping actually identical instance declarations As always type synonyms must be fully applied You cannot for example write eye 2 e Mall instance Monad P where 7 6 3 2 Relaxed rules for instance contexts In Haskell 98 the assertions in the context of the instance declaration must be of the form C a where a is a type variable that occurs in the head The XFlexibleContexts flag relaxes this rule as well as the corresponding rule for type signatures see Section 7 8 2 With this flag the context of the instance declaration can each consist of arbitrary well kinded assertions C tl tn subject only to the following rules 1 The Paterson Conditions for each assertion in the context a No type variable has more occurrences in the assertion than in the head b The assertion has fewer constructors and variables taken together and counting repetitions than the head 2 The Coverage Condition For each functional dependency tvSleft
60. beware some of the counters can have large values The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 121 240 Chapter 6 Advice on sooner faster smaller thriftier Please advise us of other helpful hints that should go here 6 1 Sooner producing a program more quickly Don t use O or especially O2 By using them you are telling GHC that you are willing to suffer longer compilation times for better quality code GHC is surprisingly zippy for normal compilations without O Use more memory Within reason more memory for heap space means less garbage collection for GHC which means less compilation time If you use the Rghc timing option you ll get a garbage collector report Again you can use the cheap and nasty RTS S RTS option to send the GC stats straight to standard error If it says you re using more than 20 of total time in garbage collecting then more memory might help use the H lt size gt option Increasing the default allocation area size used by the compiler s RTS might also help use the RTS A lt size gt RTS option If GHC persists in being a bad memory citizen please report it as a bug Don t use too much memory As soon as GHC plus its fellow citizens other processes on your machine start using more than the real memory on your machine and the machine starts thrashing the party is over Compile times will be worse th
61. by binding cmp mir oe al ae a min let cmp lt in least A group of implicit parameter bindings may occur anywhere a normal group of Haskell bindings can occur except at top level That is they can occur in a let including in a list comprehension or do notation or pattern guards or a where clause Note the following points e An implicit parameter binding group must be a collection of simple bindings to implicit style variables no function style bindings and no type signatures these bindings are neither polymorphic or recursive e You may not mix implicit parameter bindings with ordinary bindings in a single let expression use two nested lets instead In the case of where you are stuck since you can t nest where clauses e You may put multiple implicit parameter bindings in a single binding group but they are not treated as a mutually recursive group as ordinary let bindings are Instead they are treated as a non recursive group simultaneously binding all the implicit parameter The bindings are not nested and may be re ordered without changing the meaning of the program For example consider The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 174 240 ioe dee De ip Cy Pear lesan y ua Ze ap Psy The use of x in the binding for y does not see the binding for x so the type of f is ie 88 SS Avie 7 8 3 3 Implicit parameters and polymorphic recursion Consid
62. checking within GHC at Core level It checks GHC s sanity not yours dstg lint Ditto for STG level NOTE currently doesn t work demm lint Ditto for C level 4 17 3 How to read Core syntax from some ddump flags Let s do this by commenting an example It s from doing ddump ds on this code SHOA ti m8 Slealjoy ier 2 Before we jump in a word about names of things Within GHC variables type constructors etc are identified by their Uniques These are of the form letter plus number both loosely interpreted The letter gives some idea of where the Unique came from e g _ means built in type variable t means from the typechecker s means from the simplifier and so on The number is printed fairly compactly in a base 62 format which everyone hates except me WDP Remember everything has a Unique and it is usually printed out when debugging in some form or another So here we go Desugared Main sk1p2 r116 _forall_ aS_4 gt Num a _4 gt a _4 gt a _4 Sp MES es tas Ulnmlee Tor Mabon Blip _4 is the Unique for the type variable template a Num a _4 is a dictionary argument NE _NI_ means no pragmatic information yet it will later evolve into the GHC_PRAGMA info that goes into interface files Main skip2 r1L6 IN _4 gt d Num t4Gt gt let CORSO
63. command then the commands are run when the specified breakpoint only is hit This can be quite useful for example set stop 1 continue effectively disables breakpoint 1 by running continue whenever it is hit although GHCi will still emit a message to say the breakpoint was hit What s more with cunning use of def and cmd you can use set stop to implement conditional breakpoints 7 Mad n gt der cola Nexis gt asias Wee dee 0 qe Ox taut iene nme tsi NIN les lt ema Noe aa Main gt set stop 0 cond x lt 3 Ignoring breakpoints for a specified number of iterations is also possible using similar techniques show bindings Show the bindings made at the prompt and their types show breaks List the active breakpoints show context List the active evaluations that are stopped at breakpoints show modules Show the list of modules currently loaded show packages Show the currently active package flags as well as the list of packages currently loaded show languages Show the currently active language flags show args prog prompt editor stop Displays the specified setting see set sprint Prints a value without forcing its evaluation sprint is similar to print with the difference that unevaluated subterms are not bound to new variables they are simply denoted by _ step expr Single step from the last breakpoint With an expression argument begins evaluation of the expression with a single step
64. compiler You shouldn t ever need to do this unless you re very cautious about code size NOTINLINE is a synonym for NOINLINE NOINLINE is specified by Haskell 98 as the standard way to disable inlining so it should be used if you want your code to be portable 7 13 5 3 Phase control Sometimes you want to control exactly when in GHC s pipeline the INLINE pragma is switched on Inlining happens only during runs of the simplifier Each run of the simplifier has a different phase number the phase number decreases towards zero If you use dverbose core2core you ll see the sequence of phase numbers for successive runs of the simplifier In an INLINE pragma you can optionally specify a phase number thus e INLINE k f means do not inline f until phase k but from phase k onwards be very keen to inline it e INLINE k f means be very keen to inline f until phase k but from phase k onwards do not inline it The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 197 240 e NOINLINE k f means do not inline f until phase k but from phase k onwards be willing to inline it as if there was no pragma e NOINLINE k f means be willing to inline f until phase k but from phase k onwards do not inline it The same information is summarised here Before phase 2 Phase 2 and later INLINE 2 f No Yes INLINE 22 Yes
65. dependencies for itself If you have a straightforward Haskell program this is likely to be much easier and faster than using make Make mode is described in Section 4 4 1 ghc e expr Expression evaluation mode This is very similar to interactive mode except that there is a single expression to evaluate expr which is given on the command line See Section 4 4 2 for more details The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 42 240 ghc Eghe cghce Sghe c This is the traditional batch compiler mode in which GHC can compile source files one at a time or link objects together into an executable This mode also applies if there is no other mode flag specified on the command line in which case it means that the specified files should be compiled and then linked to form a program See Section 4 4 3 ghc M Dependency generation mode In this mode GHC can be used to generate dependency information suitable for use ina Makefile See Section 4 6 11 ghc mk dll DLL creation mode Windows only See Section 11 6 1 ghc help ghc Cause GHC to spew a long usage message to standard output and then exit ghc show iface file Read the interface in file and dump it as text to stdout For example ghc show if ace M hi ghc supported languages Print the supported language extensions ghc info Print information about the compiler ghc versionghc V Print a one line string including GHC s
66. dph packages are version 0 4 0 1 6 10 8 extensible exceptions e Version number 0 1 1 1 was 0 1 1 0 1 6 10 9 filepath e Version number 1 1 0 3 was 1 1 0 2 The list of characters that are invalid in filenames on Windows now includes backslash 1 6 10 10 ghc binary e This is an internal package and should not be used 1 6 10 11 ghc prim e Version number 0 2 0 0 was 0 1 0 0 1 6 10 12 haskell98 e Version number 1 0 1 1 was 1 0 1 0 1 6 10 13 hpc e Version number 0 5 0 4 was 0 5 0 3 1 6 10 14 integer gmp e Version number 0 2 0 0 was called integer version 0 1 0 1 1 6 10 15 integer simple e This is a new boot package version 0 1 0 0 1 6 10 16 old locale e Version number 1 0 0 2 was 1 0 0 1 e Date and time in ISO8601 format are now separated by T rather than a space 1 6 10 17 old time e Version number 1 0 0 3 was 1 0 0 2 1 6 10 18 packedstring e This is no longer a boot package mba e l ma _ i a The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 6 10 19 pretty Version number 1 0 1 1 was 1 0 1 0 6 10 20 process Version number 1 0 1 2 was 1 0 1 1 6 10 21 random Version number 1 0 0 2 was 1 0 0 1 6 10 22 syb Version number 0 1 0 2 was 0 1 0 1 6 10 23 template haskell Version number 2 4 0 0 was 2 3 0 1 Support for inline and specialise pragmas has been added Support for bang patter
67. files multi use of srcdir possible hpcdir DIR sub directory that contains mix files default hpc rarely used blico IA Owe 19 ILI hpc help draft Usage hpc draft OPTION lt TIX_FILE gt Options exclude PACKAGE MODULE exclude MODULE and or PACKAGE include PACKAGE MODULE include MODULE and or PACKAGE srcdir DIR path to source directory of hs files multi use of srcdir possible hpcdir DIR sub directory that contains mix files default hpc rarely used Output FILE OUL PUL F LE E 5 6 4 Caveats and Shortcomings of Haskell Program Coverage HPC does not attempt to lock the tix file so multiple concurrently running binaries in the same directory will exhibit a race condition There is no way to change the name of the tix file generated apart from renaming the binary HPC does not work with GHCi 5 7 Using ticky ticky profiling for implementors ToDo document properly It is possible to compile Haskell programs so that they will count lots and lots of interesting things e g number of updates number of data constructors entered etc etc We call this ticky ticky profiling because that s the sound a CPU makes when it is running up all those counters slowly Ticky ticky profiling is mainly intended for implementors it is quite separate from the main cost centre profiling system intended for all users everywher
68. for details If the option XUndecidableInstances is passed to the compiler the above restrictions are not enforced and it is on the programmer to ensure termination of the normalisation of type families during type inference 7 7 2 3 Equality constraints Type context can include equality constraints of the form t1 t2 which denote that the types t 1 and t 2 need to be the same In the presence of type families whether two types are equal cannot generally be decided locally Hence the contexts of function signatures may include equality constraints as in the following example sumCollects Collects el Collects es Elem al Elem 2 gt cil C2 gt EZ where we require that the element type of c1 and c2 are the same In general the types t1 and t2 of an equality constraint may be arbitrary monotypes i e they may not contain any quantifiers independent of whether higher rank types are otherwise enabled Equality constraints can also appear in class and instance contexts The former enable a simple translation of programs using functional dependencies into programs using family synonyms instead The general idea is to rewrite a class declaration of the form class ab a gt b to class F a b gt C a b where type Ea That is we represent every functional dependency FD al an gt b by an FD type family F al an and a superclass context equality F al an b essentially giving a name to the
69. functional dependency In class instances we define the type instances of FD families in accordance with the class head Method signatures are not affected by that process NB Equalities in superclass contexts are not fully implemented in GHC 6 10 7 7 2 4 Type families and instance declarations Type families require us to extend the rules for the form of instance heads which are given in Section 7 6 3 1 Specifically e Data type families may appear in an instance head e Type synonym families may not appear at all in an instance head The reason for the latter restriction is that there is no way to check for Consider The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 171 240 type family F a type instance F Bool Int class Ca instance C Int instance C F a Now a constraint C F Bool would match both instances The situation is especially bad because the type instance for F Bool might be in another module or even in a module that is not yet written 7 8 Other type system extensions 7 8 1 Explicit universal quantification forall Haskell type signatures are implicitly quantified When the language option XExplicitForAll is used the keyword for all allows us to say exactly what this means For example a 8 lo gt Ip means this G 28 Eorzall lo lo gt 19 The two are treated identically Of course forall becomes a keyword you can t use forall as a ty
70. functions behave the same at all type instances whereas class methods can change their behaviour in dependence on the class type parameters Similarly vanilla type constructors imply the same data representation for all type instances but family constructors can have varying representation types for varying type indices Indexed type families come in two flavours data families and type synonym families They are the indexed family variants of algebraic data types and type synonyms respectively The instances of data families can be data types and newtypes Type families are enabled by the flag XTypeFamilies Additional information on the use of type families in GHC is available on the Haskell wiki page on type families 7 7 1 Data families Data families appear in two flavours 1 they can be defined on the toplevel or 2 they can appear inside type classes in which case they are known as associated types The former is the more general variant as it lacks the requirement for the type indexes to coincide with the class parameters However the latter can lead to more clearly structured code and compiler warnings if some type instances were possibly accidentally omitted In the following we always discuss the general toplevel form first and then cover the additional constraints placed on associated types 7 7 1 1 Data family declarations Indexed data families are introduced by a signature such as data family GMap k gt x
71. gt a gt IntMap a gt IntMap b gt IntMap a intersectionWithKey Key gt a gt b gt a gt IntMap a gt IntMap b gt IntMap a to intersectionWith a gt b gt Cc gt IntMap a gt IntMap b gt IntMap c ALIMIE OU SAC CALOMMAEIUKEW 23 NSW gt a gt 19 gt 0 gt mee E gt meli la gt Jairo E e The types of Data IntMap findMin and Data IntMap findMax have been changed from findMin IntMap a gt a findMax IntMap a gt a to icatinelMaliq EM p ek gt Mbaiey el findMax IntMap a gt Int a e Data Map now exports mapAccumRWithKey foldrWithKey fold1WithKey and toDescList e Data Sequence now exports replicate replicateA replicateM iteraten unfoldr unfoldl scanl scanll scanr scanrl tails inits takeWhileL takeWhileR dropwhileL dropWhileR spanl sp anr breakl breakr partition filter sort sortBy unstableSort unstableSortBy elemIndexL elemIndicesL elemIndexR elemIndicesR findIndexL findIndicesL findIndexR findIndicesR foldlWithIndex foldrWithIndex mapWithIndex zip zipWith zip3 zipWith3 zip4 and zipwith4 1 6 10 6 directory e Version number 1 0 1 0 was 1 0 0 3 e A new function copyPermissions has been added to System Directory The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 12 240 1 6 10 7 dph dph base dph par dph prim interface dph prim par dph prim seq dph seq e All the
72. immediately when evaluating _result Alternatively you can use force which ignores breakpoints 2 5 5 Tracing and history A question that we often want to ask when debugging a program is how did I get here Traditional imperative debuggers usually provide some kind of stack tracing feature that lets you see the stack of active function calls sometimes called the lexical call stack describing a path through the code to the current location Unfortunately this is hard to provide in Haskell because execution proceeds on a demand driven basis rather than a depth first basis as in strict languages The stack in GHC s execution engine bears little resemblance to the lexical call stack Ideally GHCi would maintain a separate lexical call stack in addition to the dynamic call stack and in fact this is exactly what our profiling system does Chapter 5 and what some other Haskell debuggers do For the time being however GHCi doesn t maintain a lexical call stack there are some technical The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 28 240 challenges to be overcome Instead we provide a way to backtrack from a breakpoint to previous evaluation steps essentially this is like single stepping backwards and should in many cases provide enough information to answer the how did I get here question To use tracing evaluate an expression with the trace command For example if we s
73. in a little script bin sh heads stgrep ne EH NDESAMPILE SOO hoa an cut Cia hl OO AN hp2ps gt FOO ps gv watch seascape FOO ps amp while LL sede sleep 10 We generate a new profile every 10 seconds heady Stgqreps net NDESAMPINTE HOO hp rie calles CUE SAS ON Mhp2Zps BOO 9S done Occasionally gv will choke as it tries to read an incomplete copy of FOO ps because hp2ps is still running as an update occurs A slightly more complicated script works around this problem by using the fact that sending a SIGHUP to gv will cause it to re read its input file The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 114 240 bin sh es di igre n DND _ CAMP Ewer OA teil L evt a s 6 I O ON hp2ps gt FOO ps gv FOO ps amp gvpsnum while 1 gt do sleep 10 neadi Egiesjo inl END SAM HHO la emi i ewe sel 9 E 1 WOO Ins dodajos gt OO es kill HUP Sgvpsnum done 5 6 Observing Code Coverage Code coverage tools allow a programmer to determine what parts of their code have been actually executed and which parts have never actually been invoked GHC has an option for generating instrumented code that records code coverage as part of the Haskell Program Coverage HPC toolkit which is included with GHC HPC tools can be used to render the generated code coverage information into human understandable format Correctly instr
74. in the context of the top level of the Main module Everything that is in scope at the top level in the module Main we just loaded is also in scope at the prompt probably including Prelude as long as Main doesn t explicitly hide it The syntax module indicates that it is the full top level scope of module that is contributing to the scope for expressions typed at the prompt Without the x just the exports of the module are visible We re not limited to a single module GHCi can combine scopes from multiple modules in any mixture of and non forms GHCi combines the scopes from all of these modules to form the scope that is in effect at the prompt NOTE for technical reasons GHCi can only support the form for modules that are interpreted Compiled modules and package modules can only contribute their exports to the current scope To ensure that GHCi loads the interpreted version of a module add the when loading the module e g load M The scope is manipulated using the module command For example if the current scope is Prelude then we can bring into scope the exports from the module TO like so Prelude gt module 10 Prelude 10 gt hPutStrLn stdout hello n hello Prelude IO gt Note you can use import Mas an alternative to module M and module can also be shortened to m The full syntax of the module command is smodule xmodl x modn Using the form of the module commands adds modules
75. initialise the plugin before any Haskell functions are called To build Haskell modules that export a C API into a shared library use the dynamic fPIC and shared flags cae makem chy mamltem clicks cue 21 1190 9 NOS ES As before the dynamic flag specifies that this library links against the shared library versions of the rts and base package The fPIC flag is required for all code that will end up in a shared library The shared flag specifies to make a shared library rather than a program To make this clearer we can break this down into separate compliation and link steps cla eyes 2118 8 Holas ghe dynamic shared Foo o o libfoo so In principle you can use shared without dynamic in the link step That means to statically link the rts all the base libraries into your new shared library This would make a very big but standalone shared library Indeed this is exactly what we must currently do on Windows where dynamic is not yet supported see Section 11 6 On most platforms however that would require all the static libraries to have been built with fP IC so that the code is suitable to include into a shared library and we do not do that at the moment Warning if your shared library exports a Haskell API then you cannot directly link it into another Haskell program and use that Haskell API You will get linker errors You must instead make it into a package as described in the section above 4 11 4 Finding shared libraries a
76. is limited to 20 bands with additional identifiers being grouped into an OTHER band The 1 flag removes this 20 band and limit producing as many bands as necessary No key is produced as it won t fit It is useful for creation time profiles with many bands m lt int gt Normally a profile is limited to 20 bands with additional identifiers being grouped into an OTHER band The m flag specifies an alternative band limit the maximum is 20 m0 requests the band limit to be removed As many bands as necessary are produced However no key is produced as it won t fit It is useful for displaying creation time profiles with many bands p Use previous parameters By default the PostScript graph is automatically scaled both horizontally and vertically so that 1t fills the page However when preparing a series of graphs for use in a presentation it is often useful to draw a new graph using the same scale shading and ordering as a previous one The p flag causes the graph to be drawn using the parameters determined by a previous run of hp2ps on file These are extracted from file aux s Use a small box for the title t lt float gt Normally trace elements which sum to a total of less than 1 of the profile are removed from the profile The t option allows this percentage to be modified maximum 5 t0 requests no trace elements to be removed from the profile ensuring that all the data will be displayed c Generate colour output
77. is not worker wrappered by strictness analysis It s going to be inlined wholesale instead All of these effects are aimed at ensuring that what gets inlined is exactly what you asked for no more and no less GHC ensures that inlining cannot go on forever every mutually recursive group is cut by one or more loop breakers that is never inlined see Secrets of the GHC inliner JFP 12 4 July 2002 GHC tries not to select a function with an INLINE pragma as a loop breaker but when there is no choice even an INLINE function can be selected in which case the INLINE pragma is ignored For example for a self recursive function the loop breaker can only be the function itself so an INLINE pragma is always ignored Syntactically an INLINE pragma for a function can be put anywhere its type signature could be put INLINE pragmas are a particularly good idea for the then return or bind unit functions in a monad For example in GHC s own UniqueSupply monad code we have INLINE thenUs INLINE returnUs See also the NOINLINE pragma Section 7 13 5 2 Note the HBC compiler doesn t like INLINE pragmas so if you want your code to be HBC compatible you ll have to surround the pragma with C pre processor directives ifdef __GLASGOW_HASKELL__ endif 7 13 5 2 NOINLINE pragma The NOINLINE pragma does exactly what you d expect it stops the named function from being inlined by the
78. is rejected by Haskell 98 but under Jones s scheme the definition for g is typechecked first separately from that for f because the reference to f in g s right hand side is ignored by the dependency analysis Then g s type is generalised to get e 232 Orc a gt a gt BOGI Now the definition for f is typechecked with this type for g in the type environment The same refined dependency analysis also allows the type signatures of mutually recursive functions to have different contexts something that is illegal in Haskell 98 Section 4 5 2 last sentence With XRelaxedPolyRec GHC only insists that the type signatures of a refined group have identical type signatures in practice this means that only variables bound by the same pattern binding must have the same context For example this is fine E 82 a a gt a gt Boal f x x x g True g Ord a gt a gt Bool gy y lt y Tous 7 8 9 Monomorphic local bindings We are actively thinking of simplifying GHC s type system by not generalising local bindings The rationale is described in the paper Let should not be generalised The experimental new behaviour is enabled by the flag KMonoLocalBinds The effect is that local that is non top level bindings without a type signature are not generalised at all You can think of it as an extreme but much more predictable version of the Monomorphism Restriction If you supply a type signature then the flag
79. is the most common form of data type declaration because it s easy to get right You can also write out the constructors but if you do so you must write it out precisely as in its real definition If you do not write out the constructors you may need to give a kind annotation Section 7 8 4 to tell GHC the kind of the type variable if it is not In source files this is worked out from the way the type variable is used in the constructors For example darak E E 28 gt a y You cannot use deriving on a data type declaration write an instance declaration instead e Class declarations is exactly as in Haskell except that you may not put default method declarations You can also omit all the superclasses and class methods entirely but you must either omit them all or put them all in e You can include instance declarations just as in Haskell but omit the where part 4 6 10 Using make It is reasonably straightforward to set up a Makefile to use with GHC assuming you name your source files the same as your modules Thus HC ghc HC_OPTS cpp S EXTRA_HC_OPTS SRCS Main lhs Foo lhs Bar lhs OBJS Main o Foo o Bar o SUIS E so ne ginal Mas one os The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 51 240 cool _ pom S OBJS rm f S HC o HC_OPTS OBJS Standard suffix rules Ore loal 2 Los or SC e p lt Sme OPTS hs o HC e S lt Scie
80. linker to split the single object file that would normally be generated into multiple object files one per top level Haskell function or type in the module This only makes sense for libraries where it means that executables linked against the library are smaller as they only link against the object files that they need However assembling all the sections separately is expensive so this is slower than compiling normally We use this feature for building GHC s libraries warning don t use it unless you know what you re doing static Tell the linker to avoid shared Haskell libraries if possible This is the default dynamic This flag tells GHC to link against shared Haskell libraries This flag only affects the selection of dependent libraries not the form of the current target see shared See Section 4 11 on how to create them Note that this option also has an effect on code generation see above shared Instead of creating an executable GHC produces a shared object with this linker flag Depending on the operating system target this might be an ELF DSO a Windows DLL or a Mac OS dylib GHC hides the operating system details beneath this uniform flag The flags dynamic static control whether the resulting shared object links statically or dynamically to Haskell package libraries given as package option Non Haskell libraries are linked as gcc would regularly link it on your system e g on most ELF system the linker uses t
81. means that the compiled code referred to by the interpreted expression must be compatible with this runtime and in particular this means that object code that is compiled for profiling cannot be loaded and used by a splice expression because profiled object code is only compatible with the profiling version of the runtime This causes difficulties if you have a multi module program containing Template Haskell code and you need to compile it for profiling because GHC cannot load the profiled object code and use it when executing the splices Fortunately GHC provides a workaround The basic idea is to compile the program twice 1 Compile the program or library first the normal way without prof 2 Then compile it again with prof and additionally use osuf p_o to name the object files differently you can choose any suffix that isn t the normal object suffix here GHC will automatically load the object files built in the first step when executing splice expressions If you omit the osuf flag when building with prof and Template Haskell is used GHC will emit an error message 7 9 5 Template Haskell Quasi quotation Quasi quotation allows patterns and expressions to be written using programmer defined concrete syntax the motivation behind the extension and several examples are documented in Why It s Nice to be Quoted Quasiquoting for Haskell Proc Haskell Workshop 2007 The example below shows how to write a quasiquoter for a simpl
82. must be a module name or filename but may not be the name of a module in a package All previously loaded modules except package modules are forgotten The new set of modules is known as the target set Note that load can be used without any arguments to unload all the currently loaded modules and bindings Normally pre compiled code for a module will be loaded if available or otherwise the module will be compiled to byte code Using the x prefix forces a module to be loaded as byte code After a load command the current context is set to module if it was loaded successfully or e the most recently successfully loaded module if any other modules were loaded as a result of the current load or e Prelude otherwise main arg argn When a program is compiled and executed it can use the getArgs function to access the command line arguments However we cannot simply pass the arguments to the main function while we are testing in ghci as the main function doesn t take its arguments directly Instead we can use the main command This runs whatever main is in scope with any arguments being treated the same as command line arguments e g Prelude gt let main System Environment getArgs gt gt print Prelude gt main foo bar to0 par We can also quote arguments which contains characters like spaces and they are treated like Haskell strings or we can just use Haskell list syntax Prelude gt m
83. must first import GHC Prim to bring them into scope Many of them have names ending in and to mention such names you need the KMagicHash extension Section 7 3 2 The primops make extensive use of unboxed types and unboxed tuples which we briefly summarise here 7 2 1 Unboxed types Most types in GHC are boxed which means that values of that type are represented by a pointer to a heap object The represen tation of a Haskell Int for example is a two word heap object An unboxed type however is represented by the value itself no pointers or heap allocation are involved Unboxed types correspond to the raw machine types you would use in C Int long int Double double Addr void etc The primitive operations PrimOps on these types are what you might expect e g is addition on Int s and is the machine addition that we all know and love usually one instruction Primitive unboxed types cannot be defined in Haskell and are therefore built into the language and compiler Primitive types are always unlifted that is a value of a primitive type cannot be bottom We use the convention but it is only a convention that primitive types values and operations have a suffix see Section 7 3 2 For some primitive types we have special syntax for literals also described in the same section Primitive values are often represented by a simple bit pattern such as Int Float D
84. nee lecleke 8 8 SS SA A IE t4Hg r3JH _4 d Num t4Gt AROMA 39 Midel Za j gt l INE TEOMINES tes Gromin S 4 A NU OE The class method Unique r3JH selects the addition code The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 from a Num dictionary now an explicit lambda d argument function that we will use subsequently We play the exact same game with the non standard class method fromInt Unsurprisingly the type Int is wired into the compiler Mate AHORA aN 1it t4Hb let dls Cu 36 Ibe 321 NI ds d4Qz I 2 Eam Som nit tas Ce soe CIF 24 is just the literal Int 2 it reflects the fact that GHC defines data Int I Int where Int is the primitive Because Core is 2nd order lambda calculus type applications eme eamas JA ars Splici So Sar ale irst agoalalcel to el type _4 then to a dictionary yielding the actual addition unboxed type s relevant info about unboxed types elsewher The after I indicates that this is a saturated application of the If data constructor i e not partially applied Skip2 se swe FS 4 ZNTS skip2 t3Ja m rlH4 gt ler ias cCOo car dal NIL ds d400 let SALON BB eA INE ds d4QY t4Hg m r1H4 1it t4Hb ane Sk tp ts dadas d4oy b bm AU AS
85. no way to control this we just like to see how much memory is being lost this way The total memory in use tells you the peak memory the RTS has allocated from the OS Next there is information about the garbage collections done For each generation it says how many garbage collections were done how many of those collections were done in parallel the total CPU time used for garbage collecting that generation and the total wall clock time elapsed while garbage collecting that generation The SPARKS statistic refers to the use of Control Parallel par and related functionality in the program Each spark represents a call to par a spark is converted when it is executed in parallel and a spark is pruned when it is found to be already evaluated and is discarded from the pool by the garbage collector Any remaining sparks are discarded at the end of execution so converted plus pruned does not necessarily add up to the total Next there is the CPU time and wall clock time elapsed broken down by what the runtime system was doing at the time INIT is the runtime system initialisation MUT is the mutator time i e the time spent actually running your code GC is the time spent doing garbage collection RP is the time spent doing retainer profiling PROF is the time spent doing other profiling EXIT is the runtime system shutdown time And finally Total is of course the total GC time tells you what percentage GC is of Total Alloc rate tel
86. of live data to heap size is high say gt 30 NOTE compaction doesn t currently work when a single generation is requested using the G1 option cn Default 30 Automatically enable compacting collection when the live data exceeds n of the maximum heap size see the M option Note that the maximum heap size is unlimited by default so this option has no effect unless the maximum heap size is set with Msi ze Ffactor Default 2 This option controls the amount of memory reserved for the older generations and in the case of a two space collector the size of the allocation area as a factor of the amount of live data For example if there was 2M of live data in the oldest generation when we last collected it then by default we ll wait until it grows to 4M before collecting it again The default seems to work well here If you have plenty of memory it is usually better to use Hsize than to increase E factor The F setting will be automatically reduced by the garbage collector when the maximum heap size the Ms i ze setting is approaching Ggenerations Default 2 Set the number of generations used by the garbage collector The default of 2 seems to be good but the garbage collector can support any number of generations Anything larger than about 4 is probably not a good idea unless your program runs for a long time because the oldest generation will hardly ever get collected Specifying 1 generation with RTS G1 gi
87. over the type signature for ys In Haskell 98 it is not possible to declare a type for ys a major benefit of scoped type variables is that it becomes possible to do so Lexically scoped type variables are enabled by XScopedTypeVariables This flag implies XRelaxedPolyRec Note GHC 6 6 contains substantial changes to the way that scoped type variables work compared to earlier releases Read this section carefully 7 8 7 1 Overview The design follows the following principles e A scoped type variable stands for a type variable and not for a type This is a change from GHC s earlier design Furthermore distinct lexical type variables stand for distinct type variables This means that every programmer written type signature including one that contains free scoped type variables denotes a rigid type that is the type is fully known to the type checker and no inference is involved Lexical type variables may be alpha renamed freely without changing the program A lexically scoped type variable can be bound by e A declaration type signature Section 7 8 7 2 e An expression type signature Section 7 8 7 3 e A pattern type signature Section 7 8 7 4 e Class and instance declarations Section 7 8 7 5 In Haskell a programmer written type signature is implicitly quantified over its free type variables Section 4 1 2 of the Haskell Report Lexically scoped type variables affect this implicit quantification rules as follows an
88. partial function Similarly from the two dependencies that are included in the definition of E we can see that E represents a partial one one mapping between types More generally dependencies take the form x1 xn gt yl ym where xl xn and yl yn are type vari ables with n gt 0 and m gt 0 meaning that the y parameters are uniquely determined by the x parameters Spaces can be used as separators if more than one variable appears on any single side of a dependency asint gt a b Note that a class may be an notated with multiple dependencies using commas as separators as in the definition of E above Some dependencies that we can write in this notation are redundant and will be rejected because they don t serve any useful purpose and may instead indicate an error in the program Examples of dependencies like this include a gt a a gt a a a gt etc There can also be some redundancy if multiple dependencies are given as in a gt b b gt c a gt c and in which some subset implies the remaining dependencies Examples like this are not treated as errors Note that dependencies appear only in class declarations and not in any other part of the language In particular the syntax for instance declarations class constraints and types is completely unchanged The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 158 240 By including dependencies in a class declaration we prov
89. retains a large structure There might be a large number of Bs but only a single A so A is really the one we re interested in eliminating However retainer profiling will in this case report B as the retainer of the large structure To move further up the chain of retainers we can ask for another retainer profile but this time restrict the profile to B objects so we get a profile of the retainers of B PROGRESA mr E This trick isn t foolproof because there might be other B closures in the heap which aren t the retainers we are interested in but we ve found this to be a useful technique in most cases 5 4 3 Biographical Profiling A typical heap object may be in one of the following four states at each point in its lifetime e The lag stage which is the time between creation and the first use of the object The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 111 240 e the use stage which lasts from the first use until the last use of the object and e The drag stage which lasts from the final use until the last reference to the object is dropped e An object which is never used is said to be in the void state for its whole lifetime A biographical heap profile displays the portion of the live heap in each of the four states listed above Usually the most interesting states are the void and drag states live heap in these states is more likely to be wasted space than heap in the lag or use states It
90. see Section 7 8 4 Such data types have only one value namely bottom Nevertheless they can be useful when defining phantom types 7 4 2 Infix type constructors classes and type variables GHC allows type constructors classes and type variables to be operators and to be written infix very much like expressions More specifically e A type constructor or class can be an operator beginning with a colon e g The lexical syntax is the same as that for data constructors e Data type and type synonym declarations can be written infix parenthesised if you want further arguments E g data oO OO type a HD Hather a b class a b where data a b x Baz ab x type a b y Either a b y e Types and class constraints can be written infix For example E ECO tos la t by a Y e A type variable can be an unqualified operator e g The lexical syntax is the same as that for variable operators excluding 05 D and In a binding position the operator must be parenthesised For example Emos I Gr Aisne ap oe LES Either f Left 3 liftA2 Arrow gt gt Ma D gt E gt le gt al gt e gt b gt e gt LECAS soo e Back quotes work as for expressions both for type constructors and type variables e g Int Either Bool or Int a Bool Similarly parentheses work the same e g Int Bool e Fixities may be declared
91. somewhat like pattern guards that can be nested inside of other patterns They are a convenient way of pattern matching against values of abstract types For example in a programming language implementation we might represent the syntax of the types of the language as follows type Typ data TypView Unit Arrow Typ Typ view Type gt TypeView additional operations for constructing Typ s The representation of Typ is held abstract permitting implementations to use a fancy representation e g hash consing to manage sharing Without view patterns using this signature a little inconvenient The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 131 240 size Typ gt Integer size t case view t of Uiaskie gt UL Arrow jedl t2 gt lze tel lt p Bas TZ It is necessary to iterate the case rather than using an equational function definition And the situation is even worse when the matching against t is buried deep inside another pattern View patterns permit calling the view function inside the pattern and matching against the result size view gt Unit 1 size view gt Arrow tl t2 size tl size t2 That is we add a new form of pattern written expression gt pattern that means apply the expression to whatever we re trying to match against and then match the result of that application against the pattern The expression can be any Haskell expression of functi
92. sparked computation should be required at a later time but not too soon Also the sparked computation should not be too small otherwise the cost of forking it in parallel will be too large relative to the amount of parallelism gained Getting these factors right is tricky in practice It is possible to glean a little information about how well par is working from the runtime statistics see Section 4 15 3 More sophisticated combinators for expressing parallelism are available from the Control Parallel Strategies mod ule in the parallel package This module builds functionality around par expressing more elaborate patterns of parallel compu tation such as parallel map 7 18 5 Data Parallel Haskell GHC includes experimental support for Data Parallel Haskell DPH This code is highly unstable and is only provided as a technology preview More information can be found on the corresponding DPH wiki page The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 211 240 Chapter 8 Foreign function interface FFI GHC mostly conforms to the Haskell 98 Foreign Function Interface Addendum 1 0 whose definition is available from http www haske To enable FFI support in GHC give the XForeignFunctionInterface flag GHC implements a number of GHC specific extensions to the FFI Addendum These extensions are described in Section 8 1 but please note that programs using these features are not portable Hence these fe
93. style the default the compiler s internal ideas about types are presented in Haskell source level syntax insofar as possible In the debug style which is the default for debugging output the types are printed in with explicit foralls and variables have their unique id attached so you can check for things that look the same but aren t This flag makes debugging output appear in the more verbose debug style The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 88 240 dsuppress uniques Suppress the printing of uniques in debugging output This may make the printout ambiguous e g unclear where an occurrence of x is bound but it makes the output of two compiler runs have many fewer gratuitous differences so you can realistically apply diff Once diff has shown you where to look you can try again without dsu ppress uniques dppr user length In error messages expressions are printed to a certain depth with subexpressions beyond the depth replaced by ellipses This flag sets the depth Its default value is 5 dno debug output Suppress any unsolicited debugging output When GHC has been built with the DEBUG option it occasionally emits debug output of interest to developers The extra output can confuse the testing framework and cause bogus test failures so this flag is provided to turn it off 4 17 2 Checking for consistency dcore lint Turn on heavyweight intra pass sanity
94. that this affected performance considerably hence the current restriction to just the free variables The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 25 240 Now since force has inspected the runtime value of left it has reconstructed its type We can see the results of this type reconstruction qsort hs 2 15 46 Main gt show bindings _result Integer EL 8 line Serene left Integer right Integer _tl Integer Not only do we now know the type of left but all the other partial types have also been resolved So we can ask for the value of a for example qsort hs 2 15 46 Main gt a 8 You might find it useful to use Haskell s seq function to evaluate individual thunks rather than evaluating the whole expression with force For example csozt ASEZ LOA MELO SOLNE EENE right _t1 Integer qsort hs 2 15 46 Main gt seg _t1 O Essorsa see 2 LoS Melia O ieslopouc aeie lt 23 2 eze ares We evaluated only the _t 1 thunk revealing the head of the list and the tail is another thunk now bound to _t2 The seq function is a little inconvenient to use here so you might want to use def to make a nicer interface left as an exercise for the reader Finally we can continue the current execution qsort hs 2 15 46 Main gt continue Stopped at qsort hs 2 15 46 eresule s ite ey Ge ol lema 26 el waeine 88 Tal qsort hs 2 15 46 xMain
95. the available swap space which at the least will result in the program being summarily killed by the operating system The maximum heap size also affects other garbage collection parameters when the amount of live data in the heap exceeds a certain fraction of the maximum heap size compacting collection will be automatically enabled for the oldest generation and the F parameter will be reduced in order to avoid exceeding the maximum heap size t file s file S file machine readable These options produce runtime system statistics such as the amount of time spent executing the program and in the garbage collector the amount of memory allocated the maximum size of the heap and so on The three variants give different levels of detail t produces a single line of output in the same format as GHC s Rghc timing option s produces a more detailed summary at the end of the program and S additionally produces information about each and every garbage collection The output is placed in file If file is omitted then the output is sent to stderr If you use the t flag then when your program finishes you will see something like this lt lt ghc 36169392 bytes 69 GCs 603392 1065272 avg max bytes residency 2 samples 3M lt lt in use 0 00 INIT 0 00 elapsed 0 02 MUT 0 02 elapsed 0 07 GC 0 07 elapsed ghce gt gt This tells you The Glorious Glasgow Haskell Compilation System User s Guide Version 6
96. the outermost level is not allowed at the top level of a module The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 194 240 7 12 Assertions If you want to make use of assertions in your standard Haskell code you could define a function like the following esse 83 lol gt 1 gt a assert False x error assertion failed assert _ xX X which works but gives you back a less than useful error message an assertion failed but which and where One way out is to define an extended assert function which also takes a descriptive string to include in the error message and perhaps combine this with the use of a pre processor which inserts the source location where assert was used Ghc offers a helping hand here doing all of this for you For every use of assert in the user s source kelvinToC Double gt Double kelvinToC k assert k gt 0 0 k 273 15 Ghc will rewrite this to also include the source location where the assertion was made assert pred val gt assertError Main hs 15 pred val The rewrite is only performed by the compiler when it spots applications of Control Exception assert so you can still define and use your own versions of assert should you so wish If not import Control Exception to make use assert in your code GHC ignores assertions when optimisation is turned on with the O flag That is expressions of the form assert pred e will be rewri
97. the program In this case there was only one significant function in the program namely nfib and it was responsible for 100 of both the time and allocation costs of the program The third and final section of the file gives a profile break down by cost centre stack This is roughly a call graph profile of the program In the example above it is clear that the costly call to nfib came from main The time and allocation incurred by a given part of the program is displayed in two ways individual which are the costs incurred by the code covered by this cost centre stack alone and inherited which includes the costs incurred by all the children of this node The usefulness of cost centre stacks is better demonstrated by modifying the example slightly menin prime GE 25 r AS IE igh EO al Gp id imlacabloy ar Meis 2 Rio m tre w lt A chaen l else mito Chai BOO Compile and run this program as before and take a look at the new profiling results COST CENTRE ODULE sce time Salloc Stime Salloc MAIN IAIN 0 050 omo 100 0 100 0 main ain 0 ORO 050 0 0 0 0 CAF PrelHandle 3 0 0 0 0 0 0 0 0 CAF PrelAddr dl DO ORO O 0 ORO CAF ain 9 ORO 0 0 TOO FORO ORO main ain i 050 omo LOOTO TO O g ain dE ORO 0 0 0 0 OF 2 nfib ain 465 0 0 OSZ 0 0 OFZ iE ain aL ORO 050 100 O 99 E atao ain ZAZE MOO IS E LOOT GNE Now although we had two calls to nfib in the program it is time The actual meaning of
98. this rule are covered below in Section 4 8 1 Building your own packages is also quite straightforward we provide the Cabal infrastructure which automates the process of configuring building installing and distributing a package All you need to do is write a simple configuration file put a few files in the right places and you have a package See the Cabal documentation for details and also the Cabal libraries Distribution Simple for example 4 8 1 Using Packages GHC only knows about packages that are installed To see which packages are installed use the ghc pkg list command ghc pkg list US que crol package condal Cabal 1 7 4 array Ore 00 A Dase orome O base 4 2 0 0 bin package db 0 0 0 0 leslie w 0 5 0 ih The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 bytestring 0 9 1 4 containers 0 2 0 1 chas y Lo 060 7 dph base 0 4 0 dph par 0 4 0 dph prim par 0 4 0 dph prim seg 0 4 0 dph seq 0 4 0 58 240 dph prim interface 0 4 0 xtensibl xceptions 0 1 1 0 i l G tilo do 0 HERE guie prim ON MORO haskeline 0 6 2 haskel198 1 0 1 0 pe DSZ integer gmp 0 1 0 0 eZ old locale 1 0 Olid carmel Or 10 pretty One a process nO i candonm e Monori cesa NO Syb ON MORT 0 de il template haskell 2 4 terminfo 0 3 1 time 1 1 4 ina 10 EES SE ra o 4 050 An installed package is either exposed or hidden by default Packages hidden
99. trace expr Evaluates the given expression or from the last breakpoint if no expression is given and additionally logs the evaluation steps for later inspection using history See Section 2 5 5 type expression Infers and prints the type of expression including explicit forall quantifiers for polymorphic types The monomorphism restriction is not applied to the expression during type inference undef name Undefines the user defined command name see def above unset option Unsets certain options See Section 2 8 for a list of available options command Executes the shell command command The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 36 240 2 8 The set command The set command sets two types of options GHCi options which begin with and command line options which begin with NOTE at the moment the set command doesn t support any kind of quoting in its arguments quotes will not be removed and cannot be used to group words together For example set DFOO BAR BAZ will not do what you expect 2 8 1 GHCi options GHCi options may be set using set and unset using unset The available GHCi options are r Normally any evaluation of top level expressions otherwise known as CAFs or Constant Applicative Forms in loaded modules is retained between evaluations Turning on r causes all evaluation of top level expressions to be discarded af
100. usual way NB does not affect D macros passed to the C compiler when compiling via C For those use the optc Dfoo hack see Section 4 10 2 Usymbol1 Undefine macro symbol in the usual way Idir Specify a directory in which to look for include files in the usual C way The GHC driver pre defines several macros when processing Haskell source code hs or 1hs files The symbols defined by GHC are listed below To check which symbols are defined by your local GHC installation the following trick is useful S Cine a Cj clll Go E00 iis cat foo hspp The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 71 240 you need a file foo hs but it isn t actually used __HASKELL98__ If defined this means that GHC supports the language defined by the Haskell 98 report __ HASKELL 98 In GHC 4 04 and later the _ HASKELL__ macro is defined as having the value 98 __HASKELL1____If defined to n that means GHC supports the Haskell language defined in the Haskell report version n Currently 5 This macro is deprecated and will probably disappear in future versions __GLASGOW_HASKELL___ For version x y z of GHC the value of __GLASGOW_HASKELL__ is the integer xyy if y is a single digit then a leading zero is added so for example in version 6 2 of GHC __GLASGOW_HASKELL__ 602 More information in Section 1 4 With any luck processing GLASGOW_HASKELL___ will be un
101. warning is only given if the binding is not exported A definition is regarded as used if a it is exported or b it is mentioned in the right hand side of another definition that is used or c the function it defines begins with an underscore The last case provides a way to suppress unused binding warnings selectively Notice that a variable is reported as unused even if it appears in the right hand side of another unused binding fwarn unused imports Report any modules that are explicitly imported but never used However the form import M is never reported as an unused import because it is a useful idiom for importing instance declarations which are anonymous in Haskell The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 57 240 fwarn unused matches Report all unused variables which arise from pattern matches including patterns consisting of a single variable For instance f x y would report x and y as unused The warning is suppressed if the variable name begins with an underscore thus f _x True fwarn unused do bind Report expressions occuring in do and mdo blocks that appear to silently throw information away For instance do mapM popInt xs return 10 would report the first statement in the do block as suspicious as it has the type StackM Int andnot StackM but that Int value is not bound to anything The warning is suppressed by explicitly mentioning in the source c
102. will act just as it does when a breakpoint is hit with the deviation that it will not show you any source code location Due to this these commands are only really useful in conjunction with trace in order to log the steps leading up to the exception For example Main gt set fbreak on exception Main gt trace qsort abc undefined Stopped at lt exception thrown gt _exception e lt exception thrown gt Main gt hist ES AS SI SS SES OS SIS 5S 3 SOS OSO A 2 ESOS ASA RL AA EsSOfRETANSS2RLO 4NS 5 8 SAS 1 0 S 55 lt end of history gt lt exception thrown gt Main gt back Logged breakpoint at qgsort hs 3 24 38 result lt al as ge al a ts sore ns 2 24 28l Main i force Els xxx Exception Prelude undefined ETS ona se ok 2A c s eaMann gt ss prine daS as Yio s Ye g eilg Clase The exception itself is bound to a new variable _exception Breaking on exceptions is particularly useful for finding out what your program was doing when it was in an infinite loop Just hit Control C and examine the history to find out what was going on 2 5 7 Example inspecting functions It is possible to use the debugger to examine function values When we are at a breakpoint and a function is in scope the debugger cannot show you the source code for it however it is possible to get some information by applying it to some arguments and observing the result The p
103. x Int gt Int so the occurrence of y in the body of the let will see the inner binding of x so 9 will return 14 7 8 4 Explicitly kinded quantification Haskell infers the kind of each type variable Sometimes it is nice to be able to give the kind explicitly as machine checked documentation just as it is nice to give a type signature for a function On some occasions it is essential to do so For example in his paper Restricted Data Types in Haskell Haskell Workshop 1999 John Hughes had to define the data type The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 175 240 data Set cxt a Set a gt Unised festa gt ON The only use for the Unused constructor was to force the correct kind for the type variable cxt GHC now instead allows you to specify the kind of a type variable directly wherever a type variable is explicitly bound with the flag XKindSignatures This flag enables kind signatures in the following places e data declarations Gata Se ex os oS SS Sete had e type declarations CMS I GE ke 55 gt 5 Sat Ime e class declarations class Wiecie AC hes a E a SES e forall s in type signatures jig Oe So e q dent ett ER A os UN 9h 0s The parentheses are required Some of the spaces are required too to separate the lexemes If you write gt x you will get a parse error because x gt x is a single lexeme in Haskell As part o
104. 1 3 2 Examples Assuming our running GMapKey class example let us look at some export lists and their meaning e module GMap GMapKey where Exports just the class name e module GMap GMapKey where Exports the class the associated type GMap and the member functions empty Lookup and insert None of the data constructors is exported e module GMap GMapKey GMap where As before but also exports all the data constructors GMapInt GMapChar GMapUnit GMapPair and GMapUnit e module GMap GMapKey empty lookup insert GMap where As before e module GMap GMapKey empty lookup insert GMap where As before Finally you can write GMapKey type GMap to denote both the class GMapKey as well as its associated type GMap How ever you cannot write GMapKey type GMap i e sub component specifications cannot be nested To specify GMap s data constructors you have to list it separately 7 7 1 3 3 Instances Family instances are implicitly exported just like class instances However this applies only to the heads of instances not to the data constructors an instance defines 7 7 2 Synonym families Type families appear in two flavours 1 they can be defined on the toplevel or 2 they can appear inside type classes in which case they are known as associated type synonyms The former is the more general variant as it lacks the requirement for the type inde
105. 12 2 162 240 2 33 Pol gt a f x Suppose that from the RHS of f we get the constraint C Int b But GHC does not commit to instance C because in a particular call of f b might be instantiate to Int in which case instance D would be more specific still So GHC rejects the program If you add the flag XIncoherentInstances GHC will instead pick C without complaining about the problem of subsequent instantiations Notice that we gave a type signature to f so GHC had to check that f has the specified type Suppose instead we do not give a type signature asking GHC to infer it instead In this case GHC will refrain from simplifying the constraint C Int b for the same reason as before but rather than rejecting the program it will infer the type E 33 tme o gt Mal gt ol That postpones the question of which instance to pick to the call site for by which time more is known about the type b You can write this type signature yourself 1f you use the XFlexibleContexts flag Exactly the same situation can arise in instance declarations themselves Suppose we have class Foo a where i 88 a gt A instance Foo b where f x and as before the constraint C Int b arises from s right hand side GHC will reject the instance complaining as before that it does not know how to resolve the constraint C Int b because it matches more than one instance declaration The solution is to postpone the choice by add
106. 12 2 82 240 The total number of bytes allocated by the program over the whole run e The total number of garbage collections performed e The average and maximum residency which is the amount of live data in bytes The runtime can only determine the amount of live data during a major GC which is why the number of samples corresponds to the number of major GCs and is usually relatively small To get a better picture of the heap profile of your program use the hT RTS option Section 4 15 5 e The peak memory the RTS has allocated from the OS e The amount of CPU time and elapsed wall clock time while initialising the runtime system INIT running the program itself MUT the mutator and garbage collecting GC You can also get this in a more future proof machine readable format with t machine readable Mot es allocare UY sGileose2 Vaya Cas Wes average_bytes_used 603392 max_bytes_used 1065272 num_byte_usage_samples 2 peak_megabytes_allocated 3 ae jouw secos WO O10 Vine well secos 0 00 muta tor ricpukEseconas OO ZN mutator_wall_seconds 0 02 cCMEPUESEconas O OA GC_wall_seconds 0 07 tf l tf If you use the s flag then when your program finishes you will see something like this the exact details will vary depending on what sort of RTS you have e g you will only see profiling data if your RTS is compi
107. 2 Qualified names o escea e444 a Re RA a eS 20 2 4 3 3 The main and run commands 00 0000 0002022 21 2 4 4 The tt variables s 06 subs Ae a oe gee gal el e a Shoe ee e a dl amp we 21 2 4 5 Type defaultinginGHCi 2 2 00 0 000000002 hese heee ee 22 2 3 The GHCi Debugger vs oppaana pe eRe E Ew REY ORE EEG HET EE we Ee a E 23 2 5 1 Breakpoints and inspecting variables 2 ee 23 25 1 1 Setting breakpoints s s se racore Pa Bae ee Ee A a we oS 23 2 5 1 2 Listing and deleting breakpoints 0 0 0 0 0 000000 26 2 9 2 Single steppmmg co RE HR A 26 2 5 3 Nested breakpoints se c ssc pee RR ER ee ea ee ee 2 2394 The FESUTE variables 22 4 5 he aa aa at o e a da 21 Zo racing and history s 5 06 rider RR ee eR a A eR eS os 27 2 5 6 Debugging exceptions s o ss cege seccare seti krep ee 29 2 5 7 Example inspecting functions oaoa ee 29 2 3 8 Limitations s ssis a Be aaa A e aa E aS Ge g e 30 2 0 Invoking GHC Lotto 22a eee eke RS E r ea eee ee OPS A ts a 31 26 1 Packages si a dee oe CN eee ee Ye E BR Pees dE Be ee Se eS 31 2 0 2 EXITA MDrAMes sp a He Git ae A Be eis A Ge amp amp 31 2 7 GHCi commands 22040 06 2660 aa 2b hae A A ee Ee ee AE eae 32 2 8 The set command gt pc seos esco RRR Ee RS LR ee 36 28 1 GHCLOPUONS s edi Ke ee Ele dees amp Mahe dS ea Sa eee BE Shed G 36 2 8 2 Setting GHC command line optionsinGHCi 0 00 00 0000000 36 29 The
108. 3 4 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 203 240 e map e take filter e iterate repeat zip zipWith The following are good consumers e List comprehensions e array on its second argument e on its first argument foldr e map e take filter concat e unzip unzip2 unzip3 unzip4 e zip zipWith but on one argument only if both are good producers zip will fuse with one but not the other e partition e head and or any all e sequence_ e msum e sortBy So for example the following should generate no intermediate lists ewe Ul i10 A CU a2 lt ima erik O S This list could readily be extended if there are Prelude functions that you use a lot which are not included please tell us If you want to write your own good consumers or producers look at the Prelude definitions of the above functions to see how to do so 7 14 4 Specialisation Rewrite rules can be used to get the same effect as a feature present in earlier versions of GHC For example suppose that genericLookup Ord a gt Table a b gt a 19 intLookup E Talgo Tar 1 gt Ime gt 19 where int Lookup is an implementation of genericLookup that works very fast for keys of type Int You might wish to tell GHC to use int Lookup instead of genericLookup whenever the latter was called with type Table Int b gt Int gt b It used to be possible to write
109. 8 4 9 1 Ox convenient packages of optimisation flags o a 68 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 vii 4 9 2 x platform independent flags 2 0 2 0 2002000000000 0 00000 68 4 10 Options related to a particular phase ee 69 4 10 1 Replacing the program for one Or more phases e 69 4 10 2 Forcing options to a particular phase e 70 4 10 3 Options affecting the C pre processor a 70 4 1031 CPP and string gaps suo SEA Be Se EE A e gii 4 10 4 Options affecting a Haskell pre processor ee 71 4 10 5 Options affecting code generation 72 4 10 6 Options affecting linking 2 2 2 2 2 ee 12 4 11 Using shared libraries 2 costos a a re a D eh ee A e ES T3 4 11 1 Building programs that use shared libraries ee iS 4 11 2 Shared libraries for Haskell packages e 73 4 11 3 Shared libraries that export a CAPI o 76 4 11 4 Finding shared libraries at runtime 76 4 12 Using Concurrent Haskell seneuna 71 4 13 Using SMP parallelism ee ee 77 4 13 1 Compile time options for SMP parallelism 2 a TI 4 13 2 RTS options for SMP parallelism a TI 4 13 3 Hints for using SMP parallelism a 78 4 14 Platform specific Flags s oo eri pe cyp reutae Eae a e E E e E E a 78 4 15 Running a compiled progra ooa e
110. 8 45 utilities Haskell 219 Vv verbosity options 44 version package specification 66 version of ghc 2 W WARNING 195 warnings 54 windres 74 Y Yacc for Haskell 219 240 240
111. A a ae Rae a eae Pa a ee a Re ew GU ee ea Se 194 TAS Pramas aeara ote oe De Sree EMS eS eRe Ree HS ewe See ta AA sx 194 7 13 1 LANGUAGE prami s ooe gp 5 aoe POR OR OR OR ROR Re RO a ee Ad ee 194 7 13 2 OPTIONS_GHC pragma 2 2 2 ee 195 7 13 3 INCLUDE pragma s s esenci d i a Se ee we ee Sw ee we 195 7 13 4 WARNING and DEPRECATED pragmas 2 2 2 ee 195 7 13 5 INLINE and NOINLINE pragmas 2 0 0000002 ee 195 1331 INLINE pragma s s o kee aig ak Ge A BRON RUB Bog aoe amp gl al Gok amp a 196 7 13 5 2 NOINLINE pragma 2 2 02 02 ee ee 196 TARSI Phasecontol 2255424444405 b 6834 555 6440S HER ene SHEE 196 71370 ANN pragmas s c sconces pea oo BWR A re eee HEE AE eee ee eS 197 7 13 6 1 Annotating values 2 ee 197 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 7 14 7 15 7 16 7 17 7 18 7 13 6 2 Annotating types 7 13 6 3 Annotating modules LINE pragma 7 13 8 RULES pragma 7 13 9 SPECIALIZE pragma 7 13 10 SPECIALIZE instance pragma 7 13 11 UNPACK pragma 7 13 12 SOURCE pragma 7 13 7 Rewrite rules 7 14 1 Syntax 7 14 2 7 14 3 7 14 4 7 14 5 7 14 6 Semantics List fusion Specialisation Controlling what s going on CORE pragma Special built in functions Generic classes 7 16 1 Using generics 7 16 2 Changes wrt the paper 7 16 3 Terminology and restrictions 7 16 4 Another example Control over monomorphism 7 17 1 Switching off the dreade
112. ADO end CoRec Sap S18 Skule It s just a simple functional language is an unregisterised trademark of Peyton Jones Enterprises plc 4 17 4 Unregisterised compilation 89 240 The term unregisterised really means compile via vanilla C disabling some of the platform specific tricks that GHC normally uses to make programs go faster When compiling unregisterised GHC simply generates a C file which is compiled via gcc Unregisterised compilation can be useful when porting GHC to a new machine since it reduces the prerequisite tools to gcc as and Id and nothing more and furthermore the amount of platform specific code that needs to be written in order to get unregisterised compilation going is usually fairly small Unregisterised compilation cannot be selected at compile time you have to build GHC with the appropriate options set Consult the GHC Building Guide for details The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 90 240 4 18 Flag reference This section is a quick reference for GHC s command line flags For each flag we also list its static dynamic status see Sec tion 4 2 and the flag s opposite if available 4 18 1 Help and verbosity options Section 4 5 Flag Description Static Dynamic Reverse help mode help help mode n do a dry run dynamic verbose mode
113. Compilation System User s Guide Version 6 12 2 93 240 Flag Description Static Dynamic Reverse fno print bind c Turn off printing of binding dynamic ontents contents in GHCi AE Turn off implicit qualified fno implicit imp eee A os pla import of everything in dynamic ES GHCi 4 18 11 Packages Section 4 8 Flag Description Static Dynamic Reverse E 7 Compile to be part of package name P package dynamic package P Expose package P static set hide all packages Hide all packages by default static hide package name Hide package P static set ignore package name Ignore package P static set Load more packages from package conf file static file no user package Don t load the user s static conf package config file no auto link pac Don t automatically link in i dynamic kages the haskell98 package 4 18 12 Language options 7 Language options can be enabled either by a command line option Xblah or by a LANGUAGE blah pragma in the file itself See Section 7 1 Flag Description Static Dynamic Reverse Enable most language fglasgow exts guag dynamic fno glasgow exts extensions XOverlappingInst Enable overlapping dynamic XNoOverlappingIn ances instances y stances Enable incoherent XIncoherentInsta
114. Compilation System User s Guide Version 6 12 2 xi 7 63 Instanc d clarations eacee ss EA YR a Se ees oS 159 7 6 3 1 Relaxed rules for the instance head o ee 159 7 6 3 2 Relaxed rules for instance contexts ee 159 7 6 3 3 Undecidable instances 2 ee 160 7 6 3 4 Overlapping instances ee 161 7 6 4 Overloaded string literals ee 163 1 7 Type tamiliess ss ra fed ee eh bade A A a bo e ee he ee ee ae E A 163 71 1 Data families sisas ob aa Ba Re a SE EO A Bak a aoe ad ee 164 7 7 1 1 Data family declarations 2 2 ee 164 7 7 1 1 1 Associated data family declarations o a 164 7 7 1 2 Data instance declarations ee 165 7 7 1 2 1 Associated data instances a 166 7 7 1 2 2 Scoping of class parameters a 166 7 7 1 2 3 Type class instances of family instances o a 166 7 71 24 Overlap Of data instances 20 0 2 0 0 0000002020002 166 7 1 1 3 Importandexport s sec eseo eR e a 167 TIal Associated families lt o sos pe s 6 ee eee ee Me AE AR AOE SR ES e 167 DIAZ Examples gte gat et BA eee gr a A ol 167 Flik ANStaMceS s seg ei ee ae ERR E be BR eae a 8 167 TZ Synonym families s lt e esoe eg res ria eta ee ea ee den a eG ede 167 7 7 2 1 Type family declarations 2 0 0200000000200 0 2222 168 7 7 2 1 1 Associated type family declarations o o a 168 7 1 2 2 Type instance declarations ee 168 7 722
115. D5 This class declaration explains how toBin and fromBin work for arbitrary data types They do so by giving cases for unit product and sum which are defined thus in the library module Generics data Unit Unit cewe E ze Ja maL a I Tar Jo daroa a O Now you can make a data type into an instance of Bin like this instance Bin a Bin b gt Bin a b instance Bin a gt Bin a That is just leave off the where clause Of course you can put in the where clause and over ride whichever methods you please The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 206 240 7 16 1 Using generics To use generics you need to e Use the flags fglasgow exts to enable the extra syntax XGenerics to generate extra per data type code and package lang to make the Generics library available e Import the module Generics from the lang package This import brings into scope the data types Unit and You don t need this import if you don t mention these types explicitly for example if you are simply giving instance declarations 7 16 2 Changes wrt the paper Note that the type constructors and can be written infix indeed you can now use any operator starting in a colon as an infix type constructor Also note that the type constructors are not exactly as in the paper Unit instead of 1 etc Finally note that the syntax of the type patterns in the class declaration uses
116. Foo declared static but never defined Un sightly but shouldn t be a problem Sensitivity to hi interface files GHC is very sensitive about interface files For example if it picks up a non standard Prelude hi file pretty terrible things will happen If you turn on XKNoImplicitPrelude the compiler will almost surely die unless you know what you are doing Furthermore as sketched below you may have big problems running programs compiled using unstable interfaces I think GHC is producing incorrect code Unlikely A useful be more paranoid option to give to GHC is dcore li nt this causes a lint pass to check for errors notably type errors after each Core to Core transformation pass We run with dcore lint on all the time it costs about 5 in compile time Why did I get a link error If the linker complains about not finding _ lt something gt _fast then something is inconsis tent you probably didn t compile modules in the proper dependency order Is this line number right On this score GHC usually does pretty well especially if you allow it to be off by one or two In the case of an instance or class declaration the line number may only point you to the declaration not to a specific method Please report line number errors that you find particularly unhelpful 9 2 When your program does the wrong thing For advice about overly slow or memory hungry Haskell programs
117. Gab data instance G a b where GL s gt tse iae as Ge 2 6 Lal wool e You can use a deriving clause ona data instance or newtype instance declaration Even if type families are defined as toplevel declarations functions that perform different computations for different family instances may still need to be defined as methods of type classes In particular the following is not possible data family T a data instance T Int A data instance T Char B LOG 28 Pa gt low LoS As all WRONG These two equations together COO 1B 2 will produce a type error Instead you would have to write foo as a class operation thus class C a where LOO FR IW ey gt de instance Foo Int where foo A 1 instance Foo Char where foo B 2 Given the functionality provided by GADTs Generalised Algebraic Data Types it might seem as if a definition such as the above should be feasible However type families are in contrast to GADTs are open i e new instances can always be added possibly in other modules Supporting pattern matching across different data instances would require a form of extensible case construct The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 166 240 7 7 1 2 1 Associated data instances When an associated data family instance is declared within a type class instance we drop the instance keyword in the family instance So the Either instance for GMap be
118. HASKELL___ see Section 4 10 3 for a major release x y z is the integer xyy if y is a single digit then a leading zero is added so for example in version 6 8 2 of GHC we would have __GLASGOW_HASKELL___ 608 Stable snapshots We may make snapshot releases of the current stable branch available for download and the latest sources are available from the darcs repositories Stable snapshot releases are named x y z YYYYMMDD where YYYYMMDD is the date of the sources from which the snap shot was built and x y z 1 is the next release to be made on that branch For example 6 8 1 20040225 would be a snapshot of the 6 8 branch during the development of 6 8 2 The value of__ GLASGOW_HASKELL_ fora snapshot release is the integer xyy You should never write any conditional code which tests for this value however since interfaces change on a day to day basis and we don t have finer granularity in the values of _ GLASGOW_HASKELL_ you should only conditionally compile using predicates which test whether __GLASGOW_HASKELL___is equal to later than or earlier than a given major release The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 3 240 Unstable snapshots We may make snapshot releases of the HEAD available for download and the latest sources are available from the darcs repositories Unstable snapshot releases are named x y YYYYMMDD where YYYYMMDD is the date of the sources from w
119. Haskell Compilation System User s Guide Version 6 12 2 123 240 f Wibble x y ugly and proud of it case unpack oom ell oly ei gt case paco Oly MO az b2 CA gt GHC loves single constructor data types It s all the better if a function is strict in a single constructor type a type with only one data constructor for example tuples are single constructor types Newtypes are better than datatypes If your datatype has a single constructor with a single field use a newt ype declaration instead of a data declaration The newt ype will be optimised away in most cases How do I find out a function s strictness Don t guess look it up Look for your function in the interface file then for the third field in the pragma it should say __S lt string gt The lt string gt gives the strictness of the function s arguments L is lazy bad S and E are strict good P is primitive good U is strict and unpackable very good and A is absent very good For an unpackable U argument the info inside tells the strictness of its components So if the argument is a pair and it says U AU LSS that means the first component of the pair isn t used the second component is itself unpackable with three components lazy in the first strict in the second amp third If the function isn t exported just compile with the extra flag ddump simp1 next to th
120. KKK KK KKK KKK KKK KKK KKK KKK KKK KKKKKKKKK KK KKK KKKK 3647137 ALLOC_HEAP_ctr 11882004 ALLOC_HEAP_tot 69647 ALLOC_FUN_ctr 69647 ALLOC_FUN_adm 69644 ALLOC_FUN_gds 34819 ALLOC_FUN_slp 34831 ALLOC_FUN_hst_0 34816 ALLOC_FUN_hst_1 O ALLOC_FUN_hst_2 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 120 240 O ALLOC_FUN_hst_3 O ALLOC_FUN_hst_4 Deo Ni IAS UIP Wisse oleae Or ALLOG SETHE ctr 308906 ENT_IND_ctr O E NT_PERM_IND_ctr requires RTS Z load MOTE morce naio ones ooo O GC_SEL_ABANDONED_ctr 0 GC SEL MINOR ctr O GC_SEL_MAJOR_ctr O GC_FAILED_PROMOTION_ctr 47524 GC_WORDS_COPIED_ctr The formatting of the information above the row of asterisks is subject to change but hopefully provides a useful human readable summary Below the asterisks all counters maintained by the ticky ticky system are dumped in a format intended to be machine readable zero or more spaces an integer a space the counter name and a newline In fact not all counters are necessarily dumped compile or run time flags can render certain counters invalid In this case either the counter will simply not appear or it will appear with a modified counter name possibly along with an explanation for the omission notice ENT_PERM_IND_ctr appears with an inserted above Software analysing this output should always check that it has the counters it expects Also
121. MS x tol fb mri Unambiguous ok2 n MkT x n 1 Unambiguous bacil k k af oe 3 Amorus bad2 k x k Ambiguous Even though there are two x s in scope it is clear that the x in the pattern in the definition of ok 1 can only mean the field x from type S Similarly for the function ok2 However in the record update in bad1 and the record selection in bad2 it is not clear which of the two types is intended Haskell 98 regards all four as ambiguous but with the XDisambiguateRecordFields flag GHC will accept the former two The rules are precisely the same as those for instance declarations in Haskell 98 where the method names on the left hand side of the method bindings in an instance declaration refer unambiguously to the method of that class provided they are in scope at all even if there are other variables in scope with the same name This reduces the clutter of qualified names when you import two records from different modules that use the same field name Some details e Field disambiguation can be combined with punning see Section 7 3 15 For exampe module Foo where import M x True okS MES 1 x 1 xi Uses both disambiguation and punning e With XDisambiguateRecordFields you can use unqualifed field names even if the correponding selector is only in scope qualified For example assuming the same module M as in our earlier example this is legal The Glorious Glasgow Haskell Compilation Syste
122. OTE hc files aren t generated when using the native code generator you may need to use fvia C to force them to be produced keep s file keep s files Keep intermediate s files keep raw s file keep raw s files Keep intermediate raw s files These are the direct output from the C compiler before GHC does assembly mangling to produce the s file Again these are not produced when using the native code generator keep tmp files Instructs the GHC driver not to delete any of its temporary files which it normally keeps in tmp or possibly elsewhere see Section 4 6 6 Running GHC with v will show you what temporary files were generated along the way The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 48 240 4 6 6 Redirecting temporary files tmpdir If you have trouble because of running out of space in tmp or wherever your installation thinks temporary files should go you may use the tmpdir lt dir gt option to specify an alternate directory For example tmpdir says to put temporary files in the current working directory Alternatively use your TMPDIR environment variable Set it to the name of the directory where temporary files should be put GCC and other programs will honour the TMPDIR variable as well Even better idea Set the DEFAULT_TMPDIR make variable when building GHC and never worry about TMPDIR again see the build documentation 4 6 7 Other options
123. OVS OOO si KOONCE E PLEAS DOCE Oslo Oot ALC Cmts SNE EMO EAS NS DORADO Ole SC e p lt SC OPTS Inter module dependencies Foo o Foo hc Foo s Bazo Na Foo imports Baz Maan o Main he Mannie Hoon Baz MI Main imports Foo and Baz Sophisticated make variants may achieve some of the above more elegantly Notably gmake s pattern rules let you write the more comprehensible oe c0 8 Bolling SEH e eE CORTS What we ve shown should work with any make Note the cheesy o hi rule It records the dependency of the interface hi file on the source The rule says a hi file can be made from a o file by doing nothing Which is true Note that the suffix rules are all repeated twice once for normal Haskell source files and once for hs boot files see Sec tion 4 6 9 Note also the inter module dependencies at the end of the Makefile which take the form HOOMOm O MERO OS 8 Beamon Foo imports Baz They tell make that if any of Foo o Foo hc or Foo s have an earlier modification date than Baz hi then the out of date file must be brought up to date To bring it up to date make looks for a rule to do so one of the preceding suffix rules does the job nicely These dependencies can be generated automatically by ghe see Section 4 6 11 4 6 11 Dependency generation Putting inter dependencies of the form Foo o Bar hi into yourMakefile by hand is rather error prone Don t worry GHC has
124. PECIALISE INLINE Arr Int gt Int gt Int SPECIALISE INLINE Arr a b gt Int gt a b ArrInt _ ba I i If indexIntArray ba i AerPair al az Ta 2 tal 12 2 ez 12 1 Here is a recursive function that indexes arrays of type Arr e Consider a call to at type Int Int The second specialisation will fire and the specialised function will be inlined It has two calls to both at type Int Both these calls fire the first specialisation whose body is also inlined The result is a type based unrolling of the indexing function a ECIALISE Warning you can make GHC diverge by using SP INLIN E on an ordinarily recursive function Note In earlier versions of GHC it was possible to provide your own specialised function for a given type SP valu ECIALIZE hammeredLookup ae This feature has been removed as it is now subsumed by the RULI 7 13 10 SPECIALIZE instance pragma Same idea except for instance declarations For example where Foo ime instance Eq a gt SPECIALIZE usual stuff Eq Foo a instance Eq Bar The pragma must occur inside the where part of the instance decl Compatible with HBC by the way except perhaps in the placemen 7 13 11 UNPACK pragma gt Int gt value intLookup ES pragma see Section 7 14 4 i aration t of the prag
125. RTS tstd err see Section 4 15 3 4 6 Filenames and separate compilation This section describes what files GHC expects to find what files it creates where these files are stored and what options affect this behaviour Note that this section is written with hierarchical modules in mind see Section 7 3 4 hierarchical modules are an extension to Haskell 98 which extends the lexical syntax of module names to include a dot Non hierarchical modules are thus a special case in which none of the module names contain dots The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 45 240 Pathname conventions vary from system to system In particular the directory separator is on Unix systems and on Windows systems In the sections that follow we shall consistently use as the directory separator substitute this for the appropriate character for your system 4 6 1 Haskell source files Each Haskell source module should be placed in a file on its own Usually the file should be named after the module name replacing dots in the module name by directory separators For example on a Unix system the module A B C should be placed in the file A B C hs relative to some base directory If the module is not going to be imported by another module Main for example then you are free to use any filename for it GHC assumes that source files are ASCII or UTF 8 only other encodings are not rec
126. S CAS gt ere member gt gt Bool The dependency ce gt e here specifies that the type e of elements is uniquely determined by the type of the collection ce Note that both parameters of Collects are of kind there are no constructor classes here Note too that all of the instances of Collects that we gave earlier can be used together with this new definition What about the ambiguity problems that we encountered with the original definition The empty function still has type Collects e ce gt ce but it is no longer necessary to regard that as an ambiguous type Although the variable e does not appear on the right of the gt symbol the dependency for class Collects tells us that it is uniquely determined by ce which does appear on the right of the gt symbol Hence the context in which empty is used can still give enough information to determine types for both ce and e without ambiguity More generally we need only regard a type as ambiguous if it contains a variable on the left of the gt that is not uniquely determined either directly or indirectly by the variables on the right Dependencies also help to produce more accurate types for user defined functions and hence to provide earlier detection of errors and less cluttered types for programmers to work with Recall the previous definition for a function f x y insert x y insert x insert y for which we originally obtained a type tot Codbects ac
127. Show a gt Ta are accepted again Importing qualified names is now an error ghc pkg now ensures that the conf files it writes are UTF8 The parsing of tracing flags has changed see Section 4 15 6 for details 1 5 2 Template Haskell e A bug in the kind parser has been fixed 1 5 3 Libraries 1 5 3 1 array e No change version 0 3 0 0 1 5 3 2 base e Version number 4 2 0 1 was 4 2 0 0 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 4 240 1 5 3 3 bytestring e Version number 0 9 1 6 was 0 9 1 5 1 5 3 4 Cabal e Version number 1 8 0 4 was 1 8 0 2 e Distribution ModuleName simple has been deprecated use Distribution ModuleName fromString in stead 1 5 3 5 containers e No change version 0 3 0 0 1 5 3 6 directory e Version number 1 0 1 1 was 1 0 1 0 e System Directory doesFileExist on Unix like OSes now correctly identifies various types of special file as files 1 5 3 7 dph dph base dph par dph prim interface dph prim par dph prim seq dph seq e All the dph packages are version 0 4 0 1 5 3 8 extensible exceptions e No change version 0 1 1 1 1 5 3 9 filepath e Version number 1 1 0 4 was 1 1 0 3 1 5 3 10 ghc binary e This is an internal package and should not be used 1 5 3 11 ghc prim e No change version 0 2 0 0 1 5 3 12 haskell98 e No change version 1 0 1 1 1 5 3 13 hpc e Version number 0 5 0 5 was 0 5 0 4
128. The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 COLLABORATORS TITLE The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 ACTION NAME DATE SIGNATURE WRITTEN BY The GHC Team April 21 2010 REVISION HISTORY NUMBER DATE DESCRIPTION NAME The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 Contents 1 Introduction to GHC 1 1 Obtaining GHC i ok oe rar RRR RG ERE ae eA AO Bk doe BR ala a 1 2 Meta information Web sites mailing lists etc 2 ee 13 Reporting bugs Ti GHC se s 62 60 e eh e SA eee ee ew Se eh ESS eae eee Ss Y 1 4 GHC version numbering policy 1 5 Release notes Tor version 6 12 2 ops evap Gy ts Bc Sed bE ES RE EY A eda amp amp 1 5 1 Compiler and Runtime system 2 2 0 00000022 2 ee 15 2 Template Haskell o nce ke OS Ea be a ede A 1 5 3 Libraries is 5 244 2b a ES eS Be ee e a eo ae te T531 armay eeaeee oR AN L332 Dase ee a Gee Eig ie ia A A Eee Snes Aes Ghee Oech e 2 1 5 3 3 DIESE pins pe eee ae ene P ERE Gee wee ee eee ee bee ee 15 34 Cabal cnc 6644 56644 4 4 bth ee Ghee beh ate eg whe Rae bee eo 1 5 3 5 CONLAINELS o ice BS eS RR o OS we o
129. VOTOU 36 ENE works in GHC A possible reason for this is that readLitChar accepts hex and octal escapes so it seems inconsistent not to do so for integers too isAlpha The Haskell 98 definition of isAlpha is isAlpha c isUpper c isLower c GHC s implementation diverges from the Haskell 98 definition in the sense that Unicode alphabetic characters which are neither upper nor lower case will still be identified as alphabetic by isAlpha hGetContents Lazy I O throws an exception if an error is encountered in contrast to the Haskell 98 spec which requires that errors are discarded see Section 21 2 2 of the Haskell 98 report The exception thrown is the usual IO exception that would be thrown if the failing IO operation was performed in the IO monad and can be caught by System IO Erro r catchorControl Exception catch The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 231 240 12 1 2 GHC s interpretation of undefined behaviour in Haskell 98 This section documents GHC s take on various issues that are left undefined or implementation specific in Haskell 98 The Char type Following the ISO 10646 standard maxBound Char in GHC is 0x10FFFF Sized integral types In GHC the Int type follows the size of an address on the host architecture in other words it holds 32 bits on a 32 bit machine and 64 bits on a 64 bit machine Arithmetic on Int is unchecked for overflow so all operations on Int happ
130. a gt a gt b gt ial JAMES italia xsi i s map ES xS MonadT m gt m a gt m a vetorn m x xs bind m x S yy oS foyligel m Cini im E S Wa return m y ys h hm hm In the function h we use the record selectors ret urn and bind to extract the polymorphic bind and return functions from the MonadT data structure rather than using pattern matching 7 8 5 2 Type inference In general type inference for arbitrary rank types is undecidable GHC uses an algorithm proposed by Odersky and Laufer Putting type annotations to work POPL 96 to get a decidable algorithm by requiring some help from the programmer We do not yet have a formal specification of some help but the rule is this For a lambda bound or case bound variable x either the programmer provides an explicit polymorphic type for x or GHC s type inference will assume that x s type has no foralls in it What does it mean to provide an explicit type for x You can do that by giving a type signature for x directly using a pattern type signature Section 7 8 7 thus i gg rorall a ema AS Alternatively you can give a type signature to the enclosing context which GHC can push down to find the type for the variable C af gt Ge Gene E Vel se Groirellil A aca gt Bos Cra Here the type signature on the expression can be pushed inwards to give a type signature for f Similarly and more commonly one can give a type
131. ad e The set of modules that are currently in scope at the prompt This set is modified by module and it is also set automatically after load add and reload You cannot add a module to the scope if it is not loaded This is why trying to use module to load a new module results in the message module M is not loaded 2 4 3 2 Qualified names To make life slightly easier the GHCi prompt also behaves as if there is an implicit import qualified declaration for every module in every package and every module currently loaded into GHCi This behaviour can be disabled with the flag fno implicit import qualified The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 21 240 2 4 3 3 The main and run commands When a program is compiled and executed it can use the get Args function to access the command line arguments However we cannot simply pass the arguments to the main function while we are testing in ghci as the main function doesn t take its directly Instead we can use the main command This runs whatever main is in scope with any arguments being treated the same as command line arguments e g Prelude gt let main System Environment getArgs gt gt print Prelude gt main foo bar ye aera wee hal Ore en We can also quote arguments which contains characters like spaces and they are treated like Haskell strings or we can just use Haskell list syntax Prelude gt main fo
132. aded exactly as in interactive mode The expression is evaluated in the context of the loaded modules For example to load and run a Haskell program containing a module Main we might say ghc e Main main Main hs or we can just use this mode to evaluate expressions in the context of the Prelude ghc e interact unlines map reverse lines hello olleh 4 4 3 Batch compiler mode In batch mode GHC will compile one or more source files given on the command line The first phase to run is determined by each input file suffix and the last phase is determined by a flag If no relevant flag is present then go all the way through to linking This table summarises ane e compllation Suffix saying start here Flag saying stop after suffix of output file literate pre processor 1hs hs C pre processor opt hs with cpp E hspp Haskell compiler hs C S he s C compiler opt heor c 8 S assembler S C linker other a out Thus a common invocation would be Gre e TOG NS to compile the Haskell source file Foo hs to an object file Foo o Note What the Haskell compiler proper produces depends on whether a native code generator is used producing assembly language or not producing C See Section 4 10 5 for more details Note C pre processing is optional the cpp flag turns it on See Section 4 10 3 for more details Note The option E ru
133. ager allocations 3647137 11882004 words 551104 words lost to speculative heap checks STACK USAGE En ENTERS 9400092 of which 2005772 21 3 direct to the entry code the rest indirected via Node s info ptr thunks data values function values of which 1999880 63 5 bypassed arg satisfaction chk LOOSE C ALS ES SAS Salsa K JAT SHA SA S355 348140 3 7 partial applications 308906 Sree normal indirect tons O 0 0 permanent indirections RETURNS 5870443 2137257 36 4 from entering a new constructor the rest from entering an existing constructor 2349219 40 0 vectored the rest unvectored RET_NEW DESIL S255 MAS Lilo Des MOS O 0 00 00 0 RET_OLD SAS 2e oa Olo Je 29 35 O07 0 07 00 0 0 0 05 0 05 RET_UNBOXED_TUP ZS 0 0 0 0 100 0 0 0 0 0 0 0 0 0 0 0 0 0 RET_VEC_RETURN 2349219 0 03 0 0 100 0 0 0 0 0 0 0 0 0 0 0 0 0 UPDATE FRAMES 2241725 0 omitted from thunks SEQ FRAMES il CATCH FRAMES iL UPDATES 2241725 0 0 0 data values 34827 1 6 partial applications 2 in place 34825 allocated new space 2206898 98 4 updates to existing heap objects 46 by squeezing UPD_CON_IN_NEW Ok 0 0 0 0 0 0 0 0 0 UPD_PAP_IN_NEW 34825 0 0 O 34825 0 0 0 0 0 NEW GEN UPDATES 2274700 99 9 OLD GEN UPDATES 1852 0 1 Total bytes copied during GC 190096 KEK KKK
134. ages were build with shared libraries On supported platforms GHC comes with shared libraries for all the core packages but if you install extra packages e g with Cabal then they would also have to be built with shared libraries nable shared for Cabal 4 11 2 Shared libraries for Haskell packages You can build Haskell code into a shared library and make a package to be used by other Haskell programs The easiest way is using Cabal simply configure the Cabal package with the nable shared flag If you want to do the steps manually or are writing your own build system then there are certain conventions that must be followed Building a shared library that exports Haskell code to be used by other Haskell code is a bit more complicated than it is for one that exports a C API and will be used by C code If you get it wrong you will usually end up with linker errors In particular Haskell shared libraries must be made into packages You cannot freely assign which modules go in which shared libraries The Haskell shared libraries must match the package boundaries Most of the conventions GHC expects when using packages are described in Section 4 8 7 GHC handles references to symbols within the same shared library or main executable binary differently from references to symbols between different shared libraries GHC needs to know for each imported module if that module lives locally in the same shared lib or in a separate shared lib The way
135. ain foo bar baz Petco bar ban Prelude gt main foo bar baz foo bar baz Finally other functions can be called either with the main is flag or the run command Prelude gt let foo putStrLn foo gt gt System Environment getArgs gt gt print Prelude gt let bar putStrLn bar gt gt System Environment getArgs gt gt print Prelude gt set main is foo Prelude gt main foo bar baz foo Pirow Das baz Preluce gt cu baer foo bas baz bar tas Moa baz module x mod x mod import mod Sets or modifies the current context for statements typed at the prompt The form import mod is equivalent to module mod See Section 2 4 3 for more details print names Prints a value without forcing its evaluation print may be used on values whose types are unknown or partially known which might be the case for local variables with polymorphic types at a breakpoint While inspecting the runtime value print attempts to reconstruct the type of the value and will elaborate the type in GHCi s environment if possible If any unevaluated components thunks are encountered then print binds a fresh variable with a name beginning with _t to each thunk See Section 2 5 1 for more information See also the sprint command which works like print but does not bind new variables quit Quits GHCi You can also quit by typing control D at the prompt r
136. allocation is on a given compiler platform so this section aims to shed some light on how the different kinds of allocation perform with GHC alloca and friends Useful for short term allocation when the allocation is intended to scope over a given IO computation This kind of allocation is commonly used when marshalling data to and from FFI functions In GHC alloca is implemented using MutableByteArray so allocation and deallocation are fast much faster than C s malloc free but not quite as fast as stack allocation in C Use alloca whenever you can mallocForeignPtr Useful for longer term allocation which requires garbage collection If you intend to store the pointer to the memory in a foreign data structure then mallocForeignPtr is not a good choice however In GHC mallocForeignPtr is also implemented using MutableByteArray Although the memory is pointed to by a ForeignPtr there are no actual finalizers involved unless you add one with addForeignPtrFinalizer and the deallocation is done using GC so mallocForeignPtr is normally very cheap The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 215 240 malloc free If all else fails then you need to resort to Foreign malloc and Foreign free These are just wrappers around the C functions of the same name and their efficiency will depend ultimately on the implementations of these functions in your platform s C library We usually find malloc and fre
137. am that would make the typechecker loop class Da clas sra ao instance F a la instance D c Fac gt D a c is not mentioned in the head Similarly it can be tempting to lift the coverage condition class Mul abc ab gt c where 245 25 2 b gt instance Mul Int Int Int where x instance Mul Int Float Float where x y fromIntegral x x y instance Mul a bc gt Mul a b c where x v map x v The third instance declaration does not obey the coverage condition and indeed the somewhat strange definition ee ly ey gt 12 lo them x oe Iyl else y makes instance inference go into a loop because it requires the constraint Mul a b b Nevertheless GHC allows you to experiment with more liberal rules If you use the experimental flag KUndecidableIn stances both the Paterson Conditions and the Coverage Condition described in Section 7 6 3 2 are lifted Termination is ensured by having a fixed depth recursion stack If you exceed the stack depth you get a sort of backtrace and the opportunity to increase the stack depth with fcontext stack N 7 6 3 4 Overlapping instances In general GHC requires that that it be unambiguous which instance declaration should be used to resolve a type class constraint This behaviour can be modified by two flags XOverlappingInstances and XIncoherentInstances as this section discusses Both these flags are dynamic flags and c
138. amically is controlled by the flag pair st at ic dynamic In make mode and interactive mode see Section 4 4 the compiler normally determines which packages are required by the current Haskell modules and links only those In batch mode however the dependency information isn t The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 59 240 available and explicit package options must be given when linking The one other time you might need to use pac kage to force linking a package is when the package does not contain any Haskell modules it might contain a C library only for example In that case GHC will never discover a dependency on it so it has to be mentioned explicitly For example to link a program consisting of objects Foo o and Main o where we made use of the net work package we need to give GHC the package flag thus ghc o myprog Foo o Main o package network The same flag is necessary even if we compiled the modules from source because GHC still reckons it s in batch mode ghc o myprog Foo hs Main hs package network package id P Exposes a package like package but the package is named by its ID rather than by name This is a more robust way to name packages and can be used to select packages that would otherwise be shadowed Cabal passes package 1d flags to GHC hide all packages Ignore the exposed flag on installed packages and hide them all by default If yo
139. ample the following program is not allowed let x gt y 1 y gt x e2 in x We may lift this restriction in the future the only cost is that type checking patterns would get a little more complicated e Typing If exp has type T1 gt T2 and pat matches a T2 then the whole view pattern matches a T1 e Matching To the equations in Section 3 17 3 of the Haskell 98 Report add the following case v of gt 9 gt al gt e2 case G Y ol 39 el y gt e2 That is to match a variable v against a pattern exp gt pat evaluate exp v and match the result against pat The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 132 240 e Efficiency When the same view function is applied in multiple branches of a function definition or a case expression e g in size above GHC makes an attempt to collect these applications into a single nested case expression so that the view function is only applied once Pattern compilation in GHC follows the matrix algorithm described in Chapter 4 of The Implementation of Functional Programming Languages When the top rows of the first column of a matrix are all view patterns with the same expression these patterns are transformed into a single nested case This includes for example adjacent view patterns that line up in a tuple as in f view gt A pl p2 el f view gt B p3 p4 e2 The current notion o
140. an be set on a per module basis using an OP TIONS_GHC pragma if desired Section 4 1 2 When GHC tries to resolve say the constraint C Int Bool it tries to match every instance declaration against the constraint by instantiating the head of the instance declaration For example consider these declarations instance contextl gt C Int a where A instance context2 gt Ca Bool where B instance context3 gt C Int a where 2 0 instance context4 gt C Int Int where D The instances A and B match the constraint C Int Bool but C and D do not When matching GHC takes no account of the context of the instance declaration context 1 etc GHC s default behaviour is that exactly one instance must match the constraint it is trying to resolve It is fine for there to be a potential of overlap by including both declarations A and B say an error is only reported if a particular constraint matches more than one The XOverlappingInstances flag instructs GHC to allow more than one instance to match provided there is a most specific one For example the constraint C Int Int matches instances A C and D but the last is more specific and hence is chosen If there is no most specific match the program is rejected However GHC is conservative about committing to an overlapping instance For example The Glorious Glasgow Haskell Compilation System User s Guide Version 6
141. an terrible Use something like the csh builtin time command to get a report on how many page faults you re getting If you don t know what virtual memory thrashing and page faults are or you don t know the memory configuration of your machine don t try to be clever about memory use you ll just make your life a misery and for other people too probably Try to use local disks when linking Because Haskell objects and libraries tend to be large it can take many real seconds to slurp the bits to from a remote filesystem It would be quite sensible to compile on a fast machine using remotely mounted disks then link on a slow machine that had your disks directly mounted Don t derive use Read unnecessarily It s ugly and slow GHC compiles some program constructs slowly We d rather you reported such behaviour as a bug so that we can try to correct it To figure out which part of the compiler is badly behaved the v2 option is your friend The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 122 240 6 2 Faster producing a program that runs quicker The key tool to use in making your Haskell program run faster are GHC s profiling facilities described separately in Chapter 5 There is no substitute for finding where your program s time space is really going as opposed to where you imagine it is going Another point to bear in mind By far the best way to improve a program s performanc
142. and it might help to reduce space leaks It can also help in a third way when used with funbox strict fields see Section 4 9 2 a strict field can be unpacked or unboxed in the constructor and one or more levels of indirection may be removed Unpacking only happens for single constructor datatypes Int is a good candidate for example Using funbox strict fields is only really a good idea in conjunction with O because otherwise the extra packing and unpacking won t be optimised away In fact it is possible that funbox strict fields may worsen performance even with O but this is unlikely let us know if it happens to you Use unboxed types a GHC extension When you are really desperate for speed and you want to get right down to the raw bits Please see Section 7 2 1 for some information about using unboxed types Before resorting to explicit unboxed types try using strict constructor fields and funbox strict fields first see above That way your code stays portable Use foreign import a GHC extension to plug into fast libraries This may take real work but There exist piles of massively tuned library code and the best thing is not to compete with it but link with it Chapter 8 describes the foreign function interface The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 124 240 Don t use Floats If you re using Complex definitely use Complex Double rather tha
143. ap ese sa e ew Be eR ee a ee Ee AU a oa E ai 5 6 3 6 hpc overlay and hpc draft e 5 6 4 Caveats and Shortcomings of Haskell Program Coverage 2 2 2 2 2 2 0000000004 5 7 Using ticky ticky profiling for Implementos Advice on sooner faster smaller thriftier 6 1 Sooner producing a program more quickly 0000 2 e eee ee 6 2 Faster producing a program that runs quicker ee ee 6 3 Smaller producing a program that is smaller ee 6 4 Thriftier producing a program that gobbles less heap Space o o e e o GHC Language Features TA Language options ss ss coea ecte ers e ee eR ee 7 2 Unboxed types and primitive operations ooo e TZ Unboxed types 2 tos ic ee eee PO Oe eR OR ee Soe Pee eS we SR ee e 7 2 2 Unboxed Tuples s secte seepe ee ee RR Re ee eb ae ee Wd Syntactic extensions s se 4 2 8 Sythe we ye ES eH Ree ee WAS AS oe wee wees ox 1 3 1 Unicode syntax ocio 24446 e e lon ee eb ee Ae a bade Soh Gam ba eo 7132 Themagichash 2 0 64864 be ee bh eee BRR RR AE e a a bh ae eo 7 3 3 New qualified operator syntax 7 3 4 Hierarchical Modules ee 73 Pattern guard 0 4 5 obo Se a BS o E A e as a eh ae we a T36 View pattems E sr aw detest Aye AE Sed Ye wee eae oe TIT DAK pattems oc 45 5 bb 4 eee ed eA ee a bade oad es SG ea ed 7 3 8 The recursive do notation ss 6 hese ee BE eR eo Eee eR oy YE ee ee od 7 3 8 1 Details of recu
144. appening Also it will mean that a GC is less likely to happen when the application is busy and so responsiveness may be improved However if the amount of live data in the heap is particularly large then the idle GC can cause a significant delay and too small an interval could adversely affect interactive responsiveness This is an experimental feature please let us know if it causes problems and or could benefit from further tuning ksize Default 1k Set the initial stack size for new threads Thread stacks including the main thread s stack live on the heap and grow as required The default value is good for concurrent applications with lots of small threads if your program doesn t fit this model then increasing this option may help performance The main thread is normally started with a slightly larger heap to cut down on unnecessary stack growth while the program is starting up Ksize Default 8M Set the maximum stack size for an individual thread to size bytes This option is there purely to stop the program eating up all the available memory in the machine if it gets into an infinite loop mn Minimum n of heap which must be available for allocation The default is 3 Msize Default unlimited Set the maximum heap size to size bytes The heap normally grows and shrinks according to the memory requirements of the program The only reason for having this option is to stop the heap growing without bound and filling up all
145. aration is invalid instance C c d where daras E Lal o MR ie a WRONG Tol ts not ala SCOS Here the right hand side of the data instance mentions the type variable d that does not occur in its left hand side We cannot admit such data instances as they would compromise type safety 7 7 1 2 3 Type class instances of family instances Type class instances of instances of data families can be defined as usual and in particular data instance declarations can have deriving clauses For example we can write data GMap v GMapUnit Maybe v deriving Show which implicitly defines an instance of the form instance Show v gt Show GMap v where Note that class instances are always for particular instances of a data family and never for an entire family as a whole This is for essentially the same reasons that we cannot define a toplevel function that performs pattern matching on the data constructors of different instances of a single type family It would require a form of extensible case construct 7 7 1 2 4 Overlap of data instances The instance declarations of a data family used in a single program may not overlap at all independent of whether they are associated or not In contrast to type class instances this is not only a matter of consistency but one of type safety The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 167 240 7 7 1 3 Import and export The association of data con
146. ard batch compilation mode the i option is used to specify the search path for interface files see Section 4 6 3 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 16 240 2 3 Loading compiled code When you load a Haskell source module into GHCi it is normally converted to byte code and run using the interpreter However interpreted code can also run alongside compiled code in GHCi indeed normally when GHCi starts it loads up a compiled copy of the base package which contains the Prelude Why should we want to run compiled code Well compiled code is roughly 10x faster than interpreted code but takes about 2x longer to produce perhaps longer if optimisation is on So it pays to compile the parts of a program that aren t changing very often and use the interpreter for the code being actively developed When loading up source modules with load GHCi normally looks for any corresponding compiled object files and will use one in preference to interpreting the source if possible For example suppose we have a 4 module program consisting of modules A B C and D Modules B and C both import D only and A imports both B amp C A EN Ba Nod D We can compile D then load the whole program like this Pruslmde gt 1 Glas eIDAS Prelude gt load A Compiling B B hs interpreted Compiling C C hs interpreted Compiling A A hs interpreted Ok modules loaded A B C D Ma
147. are attributed to the stack of lexically enclosing SCC annotations on top of the special CAF cost centre Otherwise costs are attributed to the stack of lexically enclosing SCC annotations appended to the cost centre stack in effect at the call site of the current top level definition Notice that this is a recursive definition Time spent in foreign code see Chapter 8 is always attributed to the cost centre in force at the Haskell call site of the foreign function What do we mean by one off costs Well Haskell is a lazy language and certain expressions are only ever evaluated once For example if we write xe rado 2 The call site is just the place in the source code which mentions the particular function or variable The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 108 240 then x will only be evaluated once if at all and subsequent demands for x will immediately get to see the cached result The definition x is called a CAF Constant Applicative Form because it has no arguments For the purposes of profiling we say that the expression nfib 25 belongs to the one off costs of evaluating x Since one off costs aren t strictly speaking part of the call graph of the program they are attributed to a special top level cost centre CAF There may be one CAF cost centre for each module the default or one for each top level definition with any one off costs this behaviour can be selecte
148. are used e g compiler writers sometimes a list of options can be put in a file and then slurped in with Ofile In that file comments are of the to end of line variety blank lines and most whitespace is ignored Please ask if you are baffled and would like an example of Ofile We don t use a Ox flag for day to day work We use O to get respectable speed e g when we want to measure something When we want to go for broke we tend to use 02 fvia C and we go for lots of coffee breaks The easiest way to see what O etc really mean is to run with v then stand back in amazement 4 9 2 x platform independent flags These flags turn on and off individual optimisations They are normally set via the O options described above and as such you shouldn t need to set any of them explicitly indeed doing so could lead to unexpected results However there are one or two that may be of interest fexcess precision When this option is given intermediate floating point values can have a greater precision range than the final type Generally this is a good thing but some programs may rely on the exact precision range of Float Double values and should not use this option for their compilation fignore asserts Causes GHC to ignore uses of the function Exception assert in source code in other words rewriting Exception assert p e toe see Section 7 12 This flag is turned on by O
149. aren t much use So the simple restriction no existential stuff on newt ype stands unless there are convincing reasons to change it e You can t use deriving to define instances of a data type with existentially quantified data constructors Reason in most cases it would not make sense For example The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 146 240 data T forall a MkT a deriving Eq To derive Eq in the standard way we would need to have equality between the single component of two MkT constructors instance Eq T where MkT a MkT b But a and b have distinct types and so can t be compared It s just about possible to imagine examples in which the derived instance would make sense but it seems altogether simpler simply to prohibit such declarations Define your own instances 7 4 5 Declaring data types with explicit constructor signatures GHC allows you to declare an algebraic data type by giving the type signatures of constructors explicitly For example data Maybe a where Nothing Maybe a Just a gt Maybe a The form is called a GADT style declaration because Generalised Algebraic Data Types described in Section 7 4 6 can only be declared using this form Notice that GADT style syntax generalises existential types Section 7 4 4 For example these two declarations are equivalent data Foo forall a MkFoo a a gt Bool data Foo where
150. as Time intInst MkNumInst PUSE Nuni nst a A plus MkNumInst pq p tq The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 147 240 Here a value of type NumInst a is equivalent to an explicit Num a dictionary All this applies to constructors declared using the syntax of Section 7 4 4 2 For example the NumInst data type above could equivalently be declared like this data NumInst a Num a gt MkNumInst NumInst a Notice that unlike the situation when declaring an existential there is no forall because the Num constrains the data type s universally quantified type variable a A constructor may have both universal and existential type variables for example the following two declarations are equivalent data Tl a forall b Num a Eq b gt MkT1 ab data T2 a where MIA se Num ey Be D SS a gt b gt T2 a All this behaviour contrasts with Haskell 98 s peculiar treatment of contexts on a data type declaration Section 4 2 1 of the Haskell 98 Report In Haskell 98 the definition data Eq a gt Set a MkSet a gives MkSet the same type as MkSet above But instead of making available an Eq a constraint pattern matching on MkSet requires an Eq a constraint GHC faithfully implements this behaviour odd though it is But for GAD Estyle declarations GHC s behaviour is much more useful as well as much more intuitive The rest of this sectio
151. at gcc is gt 3 0 In order to generate the parsers happy gt 1 16 is now required The parsers are pre generated in the source tarball so most users will not need Happy It is now possible to build GHC with a simple BSD licensed Haskell implementation of Integer instead of the implementation on top of GMP To do so set INTEGER_LIBRARY to integer simple in mk build mk The build system has been rewritten for the 6 12 series See the building guide for more information The build system now uses variables like bindir compatibly with the GNU standard 1 6 6 Compiler The Interface file version field of the ghc info output has been removed as it is no longer used by GHC There is a new LibDir field in the ghc info output A field f in the ghc info can now be printed with ghc print f with letters lower cased and spaces replaced by dashes GHC now works as a 32bit application on OS X Snow Leopard The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 9 240 e The native code generator now works on Sparc Solaris e Haddock interface files are now portable between different architectures e The new linker flag eventlog enables the RTS 1 event logging features The debug flag also enables them e There is a new flag feager blackholing which typically gives better performing code when running with multiple threads See Section 4 13 1 for more information e There is a
152. at section in GADT style syntax data Counter a where NewCounter _this self ENE self gt self EAS pay se selz gt 10 p tad shite val Counter a As before only one selector function is generated here that for tag Nevertheless you can still use all the field names in pattern matching and record construction 7 4 6 Generalised Algebraic Data Types GADTs Generalised Algebraic Data Types generalise ordinary algebraic data types by allowing constructors to have richer return types Here is an example data Term a where Lit G6 Wine gt ME inte SUCE ch Term int Term Int IsZero Term Int gt Term Bool LE Term Bool gt Term a gt Term a gt Term a Pair 22 Mea a gt Isa Jo gt sim Elo Notice that the return type of the constructors is not always Term a as is the case with ordinary data types This generality allows us to write a well typed eval function for these Terms eval Terma gt a eval Lit i i eval Succ t 1 eval t eval IsZero t eval t eval If b el e2 if eval b then eval el els val e2 eval Pair el e2 eval el eval e2 The key point about GADTs is that pattern matching causes type refinement For example in the right hand side of the equation vell 38 Terma gt El eval Lit i the type a is refined to Int That s the whole point A precise specification of the type rules is beyond what this user manual aspires to b
153. atures should be avoided where possible The FFI libraries are documented in the accompanying library documentation see for example the Foreign module 8 1 GHC extensions to the FFI Addendum The FFI features that are described in this section are specific to GHC Your code will not be portable to other compilers if you use them 8 1 1 Unboxed types The following unboxed types may be used as basic foreign types see FFI Addendum Section 3 2 Int Word Char Float Double Addr StablePtr a MutableByteArray ForeignObj and ByteArray 8 1 2 Newtype wrapping of the lO monad The FFI spec requires the IO monad to appear in various places but it can sometimes be convenient to wrap the IO monad in a newt ype thus newtype MyIO a MIO IO a A reason for doing so might be to prevent the programmer from calling arbitrary IO procedures in some part of the program The Haskell FFI already specifies that arguments and results of foreign imports and exports will be automatically unwrapped if they are newtypes Section 3 2 of the FFI addendum GHC extends the FFI by automatically unwrapping any newtypes that wrap the IO monad itself More precisely wherever the FFI specification requires an IO type GHC will accept any newtype wrapping of an IO type For example these declarations are OK forekga alimerowete r00 28 Ime gt Mano Tae OBS y baz s5 Imt gt Mylo Tat AO The Glorious Glasgow Haskell Compilati
154. aus fno warn incompl patterns could fail y ete patterns fwarn incomplete warn when a record update dynamic fno warn incompl record updates could fail y te record updates fwarn missing fi warn when fields of a fno warn missing Da a dynamic En elds record are uninitialised fields fwarn missing me warn when class methods Pee fno warn missing thods are undefined y methods fwarn missing si warn about top level aria fno warn missing gnatures functions without signatures y signatures fwarn name shado warn when names are fno warn name sh dynamic wing shadowed adowing warn when the module fwarn orphans contains orphan instance dynamic fno warn orphans declarations or rewrite rules fwarn overlappin warn about overlapping ds fno warn overlap g patterns patterns y ping patterns fwarn simple pat warn about lambda patterns fno warn simpl dynamic terns that can fail patterns warn if there are tabs in the fwarn tabs dynamic fno warn tabs source file fwarn t defau warn when defaultin 3 fno warn t d Yp 8 dynamic YP lts happens faults l warn when the fwarn monomorphi 3 EY fno warn monomor os Monomorphism Restriction dynamic PEA sm restriction y phism restriction is applied fwarn unused bin warn about bindings that fno warn unused dynamic ds are unused binds fwarn unused imp warn about unnecessary fno warn unused dynamic orts imports imports fwarn unused mat warn about variables in ia f
155. be and list to the ones that are allowed In an instance declaration for a generic class the idea is that the compiler will fill in the methods for you based on the generic templates However it can only do so if The instance type is simple a type constructor applied to type variables as in Haskell 98 No constructor of the instance type has unboxed fields Of course these things can only arise if you are already using GHC extensions However you can still give an instance declarations for types which break these rules provided you give explicit code to override any generic default methods The option ddump deriv dumps incomprehensible stuff giving details of what the compiler does with generic declarations 7 16 4 Another example Just to finish with here s another example I rather like class Tag a where ALGAS wt OP inCroymisy l vaie I _ l IAS H 37s b I 1 HOON SS sill ta o MOMS OO to r mCone oO tao The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 208 240 tag a gt fut tag Il Uate 7 1 ves e gee la 1 wet a se o Mal ree tas e Bare la ae y aeons ooies gel ESE Y 7 17 Control over monomorphism GHC supports two flags that control the way in which generalisation is carried out at let and where bindings 7 17 1 Switching off the dreaded Monomorphism Restriction Haskell s monomorphism restriction see Se
156. be imported but they are still subject to the overlapping constraint no other package in the same program may provide a module of the same name import dirs string list A list of directories containing interface files hi files for this package If the package contains profiling libraries then the interface files for those library modules should have the suffix p_hi So the package can contain both normal and profiling versions of the same library without conflict see also 1library_ dirs below library dirs string list A list of directories containing libraries for this package hs libraries string list A list of libraries containing Haskell code for this package with the a or d11 suffix omitted When packages are built as libraries the 1ib prefix is also omitted For use with GHCi each library should have an object file too The name of the object file does not have a 1ib prefix and has the normal object suffix for your platform For example if we specify a Haskell library as HSfoo in the package spec then the various flavours of library that GHC actually uses will be called libHSfoo a The name of the library on Unix and Windows mingw systems Note that we don t support building dynamic libraries of Haskell code on Unix systems HSfoo dl1 The name of the dynamic library on Windows systems optional HSfoo o HSfoo obj The object version of the library used by GHCi extra libraries string list A list of extra librari
157. begins from the current breakpoint just like step The history is only available when using trace the reason for this is we found that logging each breakpoint in the history cuts performance by a factor of 2 or more GHCi remembers the last 50 steps in the history perhaps in the future we 1l make this configurable The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 29 240 2 5 6 Debugging exceptions Another common question that comes up when debugging is where did this exception come from Exceptions such as those raised by error or head have no context information attached to them Finding which particular call to head in your program resulted in the error can be a painstaking process usually involving Debug Trace trace or compiling with profiling and using RTS xc see Section 5 3 The GHCi debugger offers a way to hopefully shed some light on these errors quickly and without modifying or recompiling the source code One way would be to set a breakpoint on the location in the source code that throws the exception and then use trace and history to establish the context However head is in a library and we can t set a breakpoint on it directly For this reason GHCi provides the flags fbreak on exception which causes the evaluator to stop when an exception is thrown and fbreak on error which works similarly but stops only on uncaught exceptions When stopping at an exception GHCi
158. belong to the ArrowLoop class 7 10 2 Conditional commands In the previous example we used a conditional expression to construct the input for an arrow Sometimes we want to conditionally execute different commands as in proc x y gt alse ik Se Sy Tiem ep Sail else h lt y 2 which is translated to euere NN EZ gt ME E Se y as Lere lt elge Riot y gt gt lari Qee gt y gt 5 Pl fare yy gt yra gt gt gt G Since the translation uses the arrow concerned must belong to the ArrowChoice class There are also case commands like Case input of LI 2 E 0 x gt g lt x 1 IES gt Clo w lt ln lt Gl 2 Ws lt Ik lt dx returnA lt y ys The syntax is the same as for case expressions except that the bodies of the alternatives are commands rather than expressions The translation is similar to that of i f commands 7 10 3 Defining your own control structures As we re seen arrow notation provides constructs modelled on those for expressions for sequencing value recursion and conditionals But suitable combinators which you can define in ordinary Haskell may also be used to build new commands out of existing ones The basic idea is that a command defines an arrow from environments to values These environments assign values to the free local variables of the command Thus combinators that produce arrows from arrows may also be used to build commands from commands F
159. by GHC Most people only have a general goal something like Compile quickly or Make my program run like greased lightning The following packages of optimisations or lack thereof should suffice Note that higher optimisation levels cause more cross module optimisation to be performed which can have an impact on how much of your program needs to be recompiled when you change something This is one reason to stick to no optimisation when developing code No Ox type option specified This is taken to mean Please compile quickly I m not over bothered about compiled code quality So for example ghc c Foo hs 00 Means turn off all optimisation reverting to the same settings as if no O options had been specified Saying 00 can be useful if eg make has inserted a 0 on the command line already Oor O1 Means Generate good quality code without taking too long about it Thus for example ghc c O Main Ihs 02 Means Apply every non dangerous optimisation even if it means significantly longer compile times The avoided dangerous optimisations are those that can make runtime or space worse if you re unlucky They are normally turned on or off individually At the moment 02 is unlikely to produce better code than O Ofile lt file gt NOTE not supported since GHC 4 x Please ask if you re interested in this For those who need absolute control over exactly what options
160. by default are listed in parentheses eg lang 1 0 or possibly in blue if your terminal supports colour in the output of ghc pkg list Command line flags described below allow you to expose a hidden package or hide an exposed one Only modules from exposed packages may be imported by your Haskell code if you try to import a module from a hidden package GHC will emit an error message Note if you re using Cabal then the exposed or hidden status of a package is irrelevant the available packages are instead determined by the dependencies listed in your cabal specification The exposed hidden status of packages is only relevant when using ghc or ghci directly To see which modules are provided by a package use the ghc pkg command see Section 4 8 6 ghc pkg field network xposed modules Network Network Network Network Network xposed modules BSD CGI Socket URI The GHC command line options that control packages are package P This option causes the installed package P to be exposed The package P can be specified in full with its version number e g network 1 0 or the version number can be omitted if there is only one version of the package installed If there are multiple versions of P installed then all other versions will become hidden The package P option also causes package P to be linked into the resulting executable or shared object Whether a packages library is linked statically or dyn
161. by default contains a single directory i e the current directory The following options can be used to add to or change the contents of the search path idirs This flag appends a colon separated list of dirs to the search path i resets the search path back to nothing This isn t the whole story GHC also looks for modules in pre compiled libraries known as packages See the section on packages Section 4 8 for details 4 6 4 Redirecting the compilation output s o file GHC s compiled output normally goes into a hc o etc file depending on the last run compilation phase The option o file re directs the output of that last run phase to file Note this feature can be counterintuitive ghc C o foo o foo hs will put the intermediate C code in the file foo o name notwithstanding This option is most often used when creating an executable file to set the filename of the executable For example ghe o prog make Main will compile the program starting with module Main and put the executable in the file prog Note on Windows if the result is an executable file the extension exe is added if the specified filename does not already have an extension Thus ains 3 00 Marinas will compile and link the module Main hs and put the resulting executable in foo exe not foo If you use ghe make and you don t use the o the name GHC will choose for the executable will be based on the name of t
162. c Collects Dc gt a ee e Given the dependency information that we have for Collects however we can deduce that a and b must be equal because they both appear as the second parameter in a Collects constraint with the same first parameter c Hence we can infer a shorter and more accurate type for f i 2S Collects e S gt a gt a gt c gt c In a similar way the earlier definition of g will now be flagged as a type error Although we have given only a few examples here it should be clear that the addition of dependency information can help to make multiple parameter classes more useful in practice avoiding ambiguity problems and allowing more general sets of instance declarations The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 159 240 7 6 3 Instance declarations An instance declaration has the form instance assertionl assertionn gt class typel typem where The part before the gt is the context while the part after the gt is the head of the instance declaration 7 6 3 1 Relaxed rules for the instance head In Haskell 98 the head of an instance declaration must be of the form C T al an where C is the class T is a data type constructor and the al an are distinct type variables GHC relaxes these rules in two ways e The XFlexiblelnstances flag allows the head of the instance declaration to mention arbitrary nested types For exam ple this
163. cannot be eta converted away It is a good thing that this deriv ing clause is rejected because NonMonad mis not in fact a monad for the same reason Try defining gt gt with the correct type you won t be able to Notice also that the order of class parameters becomes important since we can only derive instances for the last one If the StateMonad class above were instead defined as class StateMonad m s m gt s where then we would not have been able to derive an instance for the Parser type above We hypothesise that multi parameter classes usually have one main parameter for which deriving new instances is most interesting Lastly all of this applies only for classes other than Read Show Typeable and Data for which the built in derivation applies section 4 3 3 of the Haskell Report For the standard classes Eq Ord Ix and Bounded it is immaterial whether the standard method is used or the one described here 7 6 Class and instances declarations 7 6 1 Class declarations This section and the next one documents GHC s type class extensions There s lots of background in the paper Type classes exploring the design space Simon Peyton Jones Mark Jones Erik Meijer All the extensions are enabled by the fglasgow exts flag 7 6 1 1 Multi parameter type classes Multi parameter type classes are permitted with flag XMultiParamTypeClasses For example class Collection c a where tinto 88 E a gt
164. ce directory of hs files multi use of srcdir possible hpcdir DIR sub directory that contains mix files default hpc rarely used fun entry count show top level function entry counts highlight covered highlight covered code rather that code gaps destdir DIR path to write output to The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 5 6 3 3 hpc sum 117 240 hpc sum adds together any number of tix files into a single tix file hpc sum does not change the original tix file it generates a new tix file hpc help sum Usage hpc sum OPTION Sum multiple Options exclude PACKAGE MODU include PACKAGE MODUL MIC He LILI T UNON intersection 5 6 3 4 hpc combine lt TIX_FILE gt Ses alin A Single lt TIX_FILE gt tix file lt TIX_FILE gt T exclude MODULE and or PACKAG eal eal za include MODULE and or PACKAG nal OUEPUt FIGE modul E use the union of th namespac default is hpc combine is the swiss army knife of hpc It can be used to take the difference between tix files to subtract one tix file from another or to add two tix files hpc combine does not change the original tix file 1t generates a new tix file hpc help combine Usage hpc combine OPTION Combine two AS Ss ti n giles MTS IN ICIS SA E TS picas geal dks
165. ci 41 GHCRTS 79 Glasgow Haskell mailing lists 1 Glasgow Parallel Haskell 209 group 134 H haddock html package specification 67 haddock interfaces package specification 67 Happy 219 happy parser generator 219 Haskell 98 language vs GHC 229 Haskell Program Coverage 114 hasktags 219 heap profiles 111 heap size factor 80 heap size maximum 81 heap size suggested 81 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 heap space using less 124 heap minimum free 81 help options 44 hidden modules package specification 67 homepage package specification 66 hooks RTS 85 hp2ps 111 hp2ps program 111 hpc 114 hs boot files 49 hs libraries package specification 67 hs_add_root 213 hsc2hs 220 Hugs 14 hugs options package specification 67 I id package specification 66 idle GC 81 implicit parameters 140 implicit prelude warning 55 import dirs package specification 67 importing hi boot files 49 imports unused 56 improvement code 68 include dirs package specification 67 includes package specification 67 incomplete patterns warning 55 incomplete record updates warning 55 INLINE 196 INLINE pragma 196 inlining controlling 69 installer detection 74 Int size of 231 interactive see GHCi interactive mode 41 interface files 45 interface files finding them 46 interface files options 48 intermediate code generation 86 inte
166. cification 67 DEPRECATED 195 deprecated flags 54 deprecations 54 description package specification 66 DLL creation mode 42 do binding apparently erroneous 57 do binding unused 57 do notation in GHCi 18 dumping GHC intermediates 86 duplicate exports warning 55 dynamic options 36 41 Dynamic libraries using 75 E encoding 45 Environment variable GHC_PACKAGE_PATH 60 environment variable for setting RTS options 79 eval mode 41 eventlog files 84 events 84 export lists duplicates 55 exposed package specification 66 exposed modules package specification 66 extended list comprehensions 134 extensions options controlling 125 extensions GHC 125 extra libraries package specification 67 237 240 faster compiling 121 faster programs how to produce 122 FFI GHCi support 14 fields missing 55 file suffixes for GHC 41 filenames 45 of modules 15 finding interface files 46 floating point exceptions 231 forall 140 forcing GHC phase options 70 foreign 140 foreign export with GHC 212 Foreign Function Interface GHCi support 14 framework dirs package specification 67 frameworks package specification 67 fromInteger 231 fromIntegral 231 G garbage collection compacting 80 garbage collector options 80 generations number of 80 getArgs 35 getProgName 35 GHC vs the Haskell 98 language 229 GHC using 40 GHC_PACKAGE_PATH 60 ghc_rts_opts 85 GHCi 14 gh
167. cit import is disabled either by XNoImplicitPrelude ora LANGUAGE NoImplicitPrelude pragma Note that no warning is given for syntax that implicitly refers to the Prelude even if KNoImplicitPrelude would change whether it refers to the Prelude For example no warning is given when 368 means Prelude fromInteger 368 Prelude Integer where Prelude refers to the actual Prelude module regardless of the imports of the module being compiled This warning is off by default fwarn incomplete patterns Similarly for incomplete patterns the function g below will fail when applied to non empty lists so the compiler will emit a warning about this when fwarn incomplete patterns is enabled This option isn t enabled by default because it can be a bit noisy and it doesn t always indicate a bug in the program However it s generally considered good practice to cover all the cases in your functions fwarn incomplete record updates The function f below will fail when applied to Bar so the compiler will emit a warning about this when fwarn incomplete record updates is enabled dara OC Mo 2 82 dae Baz if 22 WCC gt KOG f foe foo 1 x 6 4 This option isn t enabled by default because it can be very noisy and it often doesn t indicate a bug in the program fwarn missing fields This option is on by default and warns you whenever the construction of a labelled field constructor isn t complete missing
168. comes instance GMapKey a GMapKey b gt GMapKey Either a b where data GMap Either a b v GMapEither GMap a v GMap b v The most important point about associated family instances is that the type indexes corresponding to class parameters must be identical to the type given in the instance head here this is the first argument of GMap namely Either a b which coincides with the only class parameter Any parameters to the family constructor that do not correspond to class parameters need to be variables in every instance here this is the variable v Instances for an associated family can only appear as part of instances declarations of the class in which the family was declared just as with the equations of the methods of a class Also in correspondence to how methods are handled declarations of associated types can be omitted in class instances If an associated family instance is omitted the corresponding instance type is not inhabited i e only diverging expressions such as undef ined can assume the type 7 7 1 2 2 Scoping of class parameters In the case of multi parameter type classes the visibility of class parameters in the right hand side of associated family instances depends solely on the parameters of the data family As an example consider the simple class declaration class C a b where data Ta Only one of the two class parameters is a parameter to the data family Hence the following instance decl
169. command Prelude gt load Main Compiling Main Main hs interpreted Ok modules loaded Main Main gt GHCi has loaded the Main module and the prompt has changed to Main gt to indicate that the current context for expressions typed at the prompt is the Main module we just loaded we ll explain what the means later in Section 2 4 3 So we can now type expressions involving the functions from Main hs Main gt fac 17 355687428096000 Loading a multi module program is just as straightforward just give the name of the topmost module to the load command hint load can be abbreviated to 1 The topmost module will normally be Main but it doesn t have to be GHCi will discover which modules are required directly or indirectly by the topmost module and load them all in dependency order 2 2 1 Modules vs filenames Question How does GHC find the filename which contains module M Answer it looks for the file M hs or M 1hs This means that for most modules the module name must match the filename If it doesn t GHCi won t be able to find it There is one exception to this general rule when you load a program with load or specify it when you invoke ghci you can give a filename rather than a module name This filename is loaded if it exists and it may contain any module you like This is particularly convenient if you have several Main modules in the same directory and you can t call them all Main hs
170. compliance 2 2 2 0000000004 12 1 1 Divergence from Haskell98 12 1 1 1 Lexical syntax 12 1 1 2 Context free syntax 12 1 1 3 Expressions and patterns 12 1 1 4 Declarations and bindings 12 1 1 5 Module system and interface files o e o 12 1 1 6 Numbers basic types and built in classes o ee 12 1 1 7 In Prelude support 12 1 2 GHC s interpretation of undefined behaviour in Haskell 98 2 2 ee 12 1 3 Divergence from the FFI specification ee 12 2 Known bugs or infelicities 12 2 1 BugsinGHC 12 2 2 Bugs in GHCi the interactive GHC 13 Index XV 229 229 229 229 229 230 230 230 230 230 291 231 231 231 232 233 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 xvi The Glasgow Haskell Compiler License Copyright 2002 2007 The University Court of the University of Glasgow All rights reserved Redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met e Redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer e Redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribut
171. core of the notation everything else can be built using them though the results would be somewhat clumsy For example we could simulate do notation by defining bind Arrow a gt a b gt a e BIO gt aA E UC SU A E bind S Arrow a gt a bea gt a G UI CA AO CN eaaa irc ea E We could simulate if by defining cond ArrowChoice a gt a lo gt al DIS SAB CO NO cond g arr e b gt if b then Left lse ice Gy Ses E II 7 10 5 Differences with the paper e Instead of a single form of arrow application arrow tail with two translations the implementation provides two forms lt first order and lt lt higher order e User defined operators are flagged with banana brackets instead of a new form keyword The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 192 240 7 10 6 Portability Although only GHC implements arrow notation directly there is also a preprocessor available from the arrows web page that translates arrow notation into Haskell 98 for use with other Haskell systems You would still want to check arrow programs with GHC tracing type errors in the preprocessor output is not easy Modules intended for both GHC and the preprocessor must observe some additional restrictions e The module must import Control Arrow e The preprocessor cannot cope with other Haskell extensions These would have to go in separate modules e Beca
172. ction 4 5 5 of the Haskell Report can be completely switched off by KNoMonom orphismRestriction 7 17 2 Monomorphic pattern bindings As an experimental change we are exploring the possibility of making pattern bindings monomorphic that is not generalised at all A pattern binding is a binding whose LHS has no function arguments and is not a simple variable For example f x x Not a pattern binding f Ne gt E Not a pattern binding E 28 Imt gt Imt Y e ac Not a pattern binding Gra e A pattern binding ES A pattern binding x e A pattern binding Experimentally GHC now makes pattern bindings monomorphic by default Use XNoMonoPatBinds to recover the standard behaviour 7 18 Concurrent and Parallel Haskell GHC implements some major extensions to Haskell to support concurrent and parallel programming Let us first establish terminology Parallelism means running a Haskell program on multiple processors with the goal of improving performance Ideally this should be done invisibly and with no semantic changes Concurrency means implementing a program by using multiple I O performing threads While a concurrent Haskell program can run on a parallel machine the primary goal of using concurrency is not to gain performance but rather because that is the simplest and most direct way to write the program Since the threads perform I O the semantics of the program is necessarily non deterministic GHC s
173. ctory You can use the flag srcdir to use hpc for any other directory and use srcdir multiple times to analyse programs compiled from difference locations as is typical for packages We now explain in more details the major modes of hpc 5 6 3 1 hpc report hpc report gives a textual report of coverage By default all modules and packages are considered in generating report unless include or exclude are used The report is a summary unless the per module flag is used The xml output option allows for tools to use hpc to glean coverage hpc help report Usage hpc report OPTION lt TIX_FILE gt lt MODULE gt lt MODULE gt 1 Options per module show module level detail deci sa show unused decls exclude PACKAGE MODULE exclude MODULE and or PACKAGE include PACKAGE MODULE include MODULE and or PACKAGE srcdir DIR path to source directory of hs files multi use of srcdir possible hpcdir DIR sub directory that contains mix files default hpc rarely used Loc She show output in XML 5 6 3 2 hpc markup hpc markup marks up source files into colored html hpc help markup Usage hpc markup OPTION lt TIX_FILE gt lt MODULE gt lt MODULE gt 11 Options exclude PACKAGE MODULE exclude MODULE and or PACKAGE include PACKAGE MODULE include MODULE and or PACKAGE srcdir DIR path to sour
174. d proc x gt DESEE ON AE if b then returnA lt else do DOC S untilA body cond lt x and use it in the same way Of course this infix syntax only makes sense for binary operators there is also a more general syntax involving special brackets EOS XX gt Co y g so E Al Cara Caemicaseme inten lt a o aclara 0 0 lt 29 1 7 10 4 Primitive constructs Some operators will need to pass additional inputs to their subcommands For example in an arrow type supporting exceptions the operator that attaches an exception handler will wish to pass the exception that occurred to the handler Such an operator might have a type handleA gt a C gt a 6 EX gt a ec where Ex is the type of exceptions handled You could then use this with arrow notation by writing a command The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 191 240 body handleA ex gt handler so that if an exception is raised in the command body the variable ex is bound to the value of the exception and the command handler which typically refers to ex is entered Though the syntax here looks like a functional lambda we are talking about commands and something different is going on The input to the arrow represented by a command consists of values for the free local variables in the command plus a stack of anonymous values In all the prior examples this stack was empty In the second ar
175. d lazy respectively e Like let and where bindings name shadowing is not allowed within a rec that is all the names bound in a single rec must be distinct Section 3 3 of the paper e It supports rebindable syntax see Section 7 3 11 7 3 8 2 Mdo notation deprecated GHC used to support the flag KRecursiveDo which enabled the keyword mdo precisely as described in A recursive do for Haskell but this is now deprecated Instead of mdo Q e writedo rec Q e Historical note The old implementation of the mdo notation and most of the existing documents used the name MonadRec for the class and the corresponding library This name is not supported by GHC 7 3 9 Parallel List Comprehensions Parallel list comprehensions are a natural extension to list comprehensions List comprehensions can be thought of as a nice syntax for writing maps and filters Parallel comprehensions extend this to include the zipWith family A parallel list comprehension has multiple independent branches of qualifier lists each separated by a I symbol For example the following zips together two lists The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 134 240 Gi 7 lt gt es yy lt 6 The behavior of parallel list comprehensions follows that of zip in that the resulting list will have the same length as the shortest branch We can define parallel list comprehensions by translation to regular comprehen
176. d Monomorphism Restriction 7 17 2 Monomorphic pattern bindings Concurrent and Parallel Haskell 7 18 1 7 18 2 7 18 3 7 18 4 7 18 5 Concurrent Haskell Software Transactional Memory Parallel Haskell Annotating pure code for parallelism Data Parallel Haskell 8 Foreign function interface FFI 8 1 8 2 GHC extensions to the FFI Addendum 8 1 1 Unboxed types o o 8 1 2 Newtype wrapping of the IO monad 8 1 3 Primitive imports o e Using the FFI with GHC o o 8 2 1 Using foreign export and foreign import ccall 8 2 1 1 Using your own main xiii The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 9 10 11 8 2 1 2 Making a Haskell library that can be called from foreign code 8 2 2 Using header files oops A A Re a a SG Rs ee A Bae a 8 2 3 Memory Allocation cepo 4 lt 5 06 de a SEhS4 bb ee ee ete een bb bev ecu 8 2 4 Multi threading andthe FFI 0000000000000 0000000004 8 2 4 1 Foreign imports and multi threading e 8 2 4 2 The relationship between Haskell threads and OS threads 2 2 2 ee 8 2 4 3 Foreign exports and multi threading 2 2 0 0 000000000 8 2 4 4 Ontheuseofhs_exit oaaae a a a What to do when something goes wrong 9 1 When the compiler does the wrong thing oaoa ee 9 2 When your program does the wrong thing Other
177. d by giving GHC the caf a11 flag If you think you have a weird profile or the call graph doesn t look like you expect it to feel free to send it and your program to us at glasgow haskell bugs haskell org 5 2 Compiler options for profiling prof To make use of the profiling system all modules must be compiled and linked with the prof option Any SCC annotations you ve put in your source will spring to life Without a prof option your SCCs are ignored so you can compile SCC laden code without changing it There are a few other profiling related compilation options Use them in addition to prof These do not have to be used consistently for all modules in a program auto GHC will automatically add _scc_ constructs for all top level exported functions auto all All top level functions exported or not will be automatically _scc_ d caf all The costs of all CAFs in a module are usually attributed to one big CAF cost centre With this option all CAFs get their own cost centre An if all else fails option ignore scc Ignore any _scc_ constructs so a module which already has _scc_s can be compiled for profiling with the annotations ignored 5 3 Time and allocation profiling To generate a time and allocation profile give one of the following RTS options to the compiled program when you run it RTS options should be enclosed between RTS RTS as usual por P The p option produces a standard
178. dd_root as normal to initialise the Haskell runtime and the corresponding deinitialisation function mylib_end calls hs_exit to shut down the runtime 8 2 2 Using header files C functions are normally declared using prototypes in a C header file Earlier versions of GHC 6 8 3 and earlier included the header file in the C source file generated from the Haskell code and the C compiler could therefore check that the C function being called via the FFI was being called at the right type GHC no longer includes external header files when compiling via C so this checking is not performed The change was made for compatibility with the native code backend fasm and to comply strictly with the FFI specification which requires that FFI calls are not subject to macro expansion and other CPP conversions that may be applied when using C header files This approach also simplifies the inlining of foreign calls across module and package boundaries there s no need for the header file to be available when compiling an inlined version of a foreign call so the compiler is free to inline foreign calls in any context The include option is now deprecated and the include files field in a Cabal package specification is ignored 8 2 3 Memory Allocation The FFI libraries provide several ways to allocate memory for use with the FFI and it isn t always clear which way is the best This decision may be affected by how efficient a particular kind of
179. dden register was spilled This may be due to a compiler bug or to impossible asm statements or clauses Just give some registers back with monly N regs Try 3 first then 2 If 2 doesn t work please report the bug to us 3 Whether hyperthreading cores should be counted or not is an open question please feel free to experiment and let us know what results you find The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 79 240 4 15 Running a compiled program To make an executable program the GHC system compiles your code and then links it with a non trivial runtime system RTS which handles storage management profiling etc You have some control over the behaviour of the RTS by giving special command line arguments to your program When your Haskell program starts up its RTS extracts command line arguments bracketed between RTS and RTS as its own For example T o a out E FRIS jo RIS lt n Too logue The RTS will snaffle p S for itself and the remaining arguments f h foo bar will be handed to your program if when it calls System getArgs No RTS option is required if the runtime system options extend to the end of the command line as in this example hls ltr usr etc RIS A5m If you absolutely positively want all the rest of the options in a command line to go to the program and not the RTS use a RTS As always for RTS options that take sizes
180. de generation dynamic fbyte code Generate byte code dynamic fobject cod Generate object code dynamic The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 4 18 21 Linking options Section 4 10 6 100 240 only Flag Description Static Dynamic Reverse Generate a shared library shared as opposed to an dynamic executable Generate fPIC position independent code static where available Ayna Use dynamic Haskell to libraries if available Selects one of a number of dynload modes for finding shared static libraries at runtime On Darwin MacOS X only link in the framework name framework name This option corresponds to dynamic the framework option for Apple s Linker On Darwin MacOS X only add dir to the list of framework path directories searched for dynamic name frameworks This option corresponds to the F option for Apple s Linker 11ib Link in library 1ib dynamic Add dir to the list of Ldir directories searched for dynamic libraries edo Set main module and main is y dynamic function DLL creation mode mk d11 Windows only dynamic en esa a Don t assume this program dianie g contains main no link Omit linking dynamic split objs Split objects for libraries dynamic static Use static Haskell libraries static threaded Use the threa
181. ded runtime static debug Use the debugging runtime static Enable runtime event eventlog Static tracing fie Genamadieest Do not generate a manifest ae file Windows only Do not embed the manifest fno embed manif i ES in the executable Windows dynamic only Don t generate an import fno shared implib library for a DLL Windows dynamic 4 18 22 Replacing phases Section 4 10 1 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 101 240 Flag Description Static Dynamic Reverse Use cmd as the literate y pgmL cmd dynamic pre processor Use cmd as the C pgmP cmd pre processor with cpp dynamic only pgmc cmd Use cmd as the C compiler dynamic pgmm cmd Use cmd as the mangler dynamic pgms cmd Use cmd as the splitter dynamic pgma cmd Use cmd as the assembler dynamic pgml cmd Use cmd as the linker dynamic pgndii cma Use cmd as the DLL duce generator Use cma as the pgmF cmd pre processor with F dynamic only Use cmd as the program for pgmwindres cmd embedding manifests on dynamic Windows 4 18 23 Forcing options to particular phases Section 4 10 2 Flag Description Static Dynamic Reverse f pass option to the literate optL option dynamic pre processor Zot D OBEI pass option to cpp with dynamic ptP option cpp only
182. defined but for a GADT the arguments to the type constructor can be arbitrary monotypes For example in the Term data type above the type of each constructor must end with Term ty but the ty need not be a type variable e g the Lit constructor It is permitted to declare an ordinary algebraic data type using GADT style syntax What makes a GADT into a GADT is not the syntax but rather the presence of data constructors whose result type is not just T a b You cannot use a deriving clause for a GADT only for an ordinary data type As mentioned in Section 7 4 5 record syntax is supported For example data Term a where ao val int So Mera Jae STOC num Term Int Term Int Pred num Sim ime y c Tern Tar IsZero arg Term Int Term Bool Pair argl Term a r ERES Term b Term a b TE end Term Bool o EEU Term a y Els Term a Term a However for GADTs there is the following additional constraint every constructor that has a field must have the same result type modulo alpha conversion Hence in the above example we cannot merge the num and arg fields above into a single name Although their field types are both Term Int their selector functions actually have different types Term Int gt Term Int Term Bool gt Term Int iaa gE Bua 88 When pattern matching against data constructors drawn from a GADT for example in a case expression the following rules apply The type of the scrutinee must be rig
183. defined in all other implementations that support C style pre For reference the comparable symbols for other systems are __HUGS__ for Hugs __ NHC___for nhc98 and__ HBC__ for hbc NB This macro is set when pre processing both Haskell source and C source including the C source generated from a Haskell module i e hs 1hs c and hc files __CONCURRENT_HASKELL___ This symbol is defined when pre processing Haskell input and pre processing C GHC out put Since GHC from version 4 00 now supports concurrent haskell by default this symbol is always defined __ PARALLEL HASKELL Only defined when parallel is in use This symbol is defined when pre processing Haskell input and pre processing C GHC output os_HOST_OS 1 This define allows conditional compilation based on the Operating System whereos is the name of the current Operating System eg linux mingw32 for Windows solaris etc arch_HOST_ARCH 1 This define allows conditional compilation based on the host architecture wherearch is the name of the current architecture eg i386 x86_64 powerpc sparc etc 4 10 3 1 CPP and string gaps A small word of warning cpp is not friendly to string gaps In other words strings such as the following sismos UN p N don t work with cpp usr bin cpp elides the backslash newline pairs However it appears that if you add a space at the end of the line then cpp at least GNU cpp and possibly ot
184. does not need to be in the same module as any of the variables it mentions though of course they need to be in scope All rules are implicitly exported from the module and are therefore in force in any module that imports the module that defined the rule directly or indirectly That is if A imports B which imports C then C s rules are in force when compiling A The situation is very similar to that for instance declarations Inside a RULE forall is treated as a keyword regardless of any other flag settings Furthermore inside a RULE the language extension XScopedTypeVariables is automatically enabled see Section 7 8 7 Like other pragmas RULE pragmas are always checked for scope errors and are typechecked Typechecking means that the LHS and RHS of a rule are typechecked and must have the same type However rules are only enabled if the fenable rewrite rules flag is on see Section 7 14 2 7 14 2 Semantics From a semantic point of view Rules are enabled that is used during optimisation by the fenable rewrite rules flag This flag is implied by O and may be switched off as usual by fno enable rewrite rules NB enabling fenable rewrite rules without O may not do what you expect though because without O GHC ignores all optimisation information in interface files see fignore interface pragmas Section 4 9 2 Note that fenable rewrite rules is an optimisation flag and has no effect on parsing or typ
185. don t want to pay the disk space cost of creating this import library which can be substantial it might require as much space as the code itself as Haskell DLLs tend to export lots of symbols As long as you are happy to only be able to link to the DLL using Get ProcAddress and friends you can supply the fno shared implib flag to disable the creation of the import library entirely The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 75 240 4 11 Using shared libraries On some platforms GHC supports building Haskell code into shared libraries Shared libraries are also sometimes known as dynamic libraries in particular on Windows they are referred to as dynamic link libraries DLLs Shared libraries allow a single instance of some pre compiled code to be shared between several programs In contrast with static linking the code is copied into each program Using shared libraries can thus save disk space They also allow a single copy of code to be shared in memory between several programs that use it Shared libraires are often used as a way of structuring large projects especially where different parts are written in different programming languages Shared libraries are also commonly used as a plugin mechanism by various applications This is particularly common on Windows using COM In GHC version 6 12 building shared libraries is supported for Linux on x86 and x86 64 architectures and there is partial supp
186. e You don t need to build GHC the libraries or the RTS a special way in order to use ticky ticky profiling You can decide on a module by module basis which parts of a program have the counters compiled in using the compile time ticky option Those modules that were not compiled with t icky won t contribute to the ticky ticky profiling results and that will normally include all the pre compiled packages that your program links with To get your compiled program to spit out the ticky ticky numbers e Link the program with debug t icky is a synonym for debug at link time This links in the debug version of the RTS which includes the code for aggregating and reporting the results of ticky ticky profilng e Run the program with the r RTS option See Section 4 15 Here is a sample ticky ticky statistics file generated by the invocation foo RTS rfoo ticky COO RID Omi IO CLENY ALLOCATIONS 3964631 11330900 words total 3999476 admin 6098829 goods 1232595 slop total words 2 3 4 5 6 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 119 240 69647 18s function values SOMONE ONO O0 0 0 orso 2382937 60 1 thunks O20 88 9 als 0 0 OO 1477218 37 3 data values ALO O 0 0 ORO 0 0 0 0 0 big tuples ZE DIO laca holes 0 0 100 0 0 0 ORO OO 0 0 0 prim things 34825 0 9 partial applications 0 0 Q0 OO TOO 050 2 0 0 thread state objects oo One O0 IO O Total storage man
187. e empty Collects ce gt c By ambiguous we mean that there is a type variable e that appears on the left of the gt symbol but not on the right The problem with this is that according to the theoretical foundations of Haskell overloading we cannot guarantee a well defined semantics for any term with an ambiguous type We can sidestep this specific problem by removing the empty member from the class declaration However although the remain ing members insert and member do not have ambiguous types we still run into problems when we try to use them For example consider the following two functions f x y insert x insert y g f True a for which GHC infers the following types st Collects a T Collects o E Poe ee ee G a 28 Collects Bool e Collects Crear C 0 gt C Notice that the type for f allows the two parameters x and y to be assigned different types even though it attempts to insert each of the two values one after the other into the same collection If we re trying to model collections that contain only one type of value then this is clearly an inaccurate type Worse still the definition for g is accepted without causing a type error As a result the error in this code will not be flagged at the point where it appears Instead it will show up only when we try to use g which might even be in a different module The Glorious Glasgow Haskell Compilation System User s Guide Ver
188. e The most common values are rts vanilla rt s_thr threaded runtime i e linked using the threaded option and rt s_p profiling runtime i e linked using the prof option Other variants include debug linked using debug t ticky ticky profiling and dyn the RTS is linked in dynamically i e a shared library rather than statically linked into the executable itself These can be combined e g you might have rts_thr_ debug_p Target platform Target architecture Target OS Target vendor These are the platform the program is compiled to run on Build platform Build architecture Build OS Build vendor These are the platform where the program was built on That is the target platform of GHC itself Ordinarily this is identical to the target platform It could potentially be different if cross compiling Host platform Host architecture Host OS Host vendor These are the platform where GHC itself was com piled Again this would normally be identical to the build and target platforms Word size Either 32 or 64 reflecting the word size of the target platform Compiler unregistered Was this program compiled with an unregistered version of GHC Le a version of GHC that has no platform specific optimisations compiled in usually because this is a currently unsupported platform This value will usually be no unless you re using an experimental build of GHC Tables next to code Putting info tables directly next to ent
189. e 19 4 15 1 Setting global RTS options a a ae E S E E E E EA R e e 79 4 15 2 Miscellaneous RTS Options a 79 4 15 3 RTS options to control the garbage collector oo e e 80 4 15 4 RTS options for concurrency and parallelism o e e e 83 4 15 5 RTS options for profiling saci 22 2 ee eee ee ee ee ee E 83 4 13 6 Trace ph ek ae ee ek Da ee het a eee eee we be So eb ee ee a eb 84 4 15 7 RTS options for hackers debuggers and over interested souls oo o 84 4 15 8 Hooks to change RTS behaviour ee 85 4 15 9 Getting information about the RTS 2 2 ee 85 4 16 Generating and compiling External Core Files 2 2 ee 86 4 17 Debugging the compiler ss ses ee 86 4 17 1 Dumping out compiler intermediate structures 2 2 ee 86 4 17 2 Checking for consistency ee sre ezo a BH SERS DYE EYED ES DAE BOSS EDS EES 88 4 17 3 How to read Core syntax from some ddump flags 2 2 2 2 0 2 000 000 0000 88 4 17 4 Unregisterised compilation 89 4 18 Flag referente nnsa 242 2 is a e A a A a di ES 90 4 18 1 Help and verbosity options 2 2 a 90 4 18 2 Whichphasestorun sess 2 ee 90 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 viii 4 18 3 Alternative modes of operation 2 ee 90 4184 Redirecting output 2 ao Syd ite AA ew GS opt oe wae wae ox 91 4 18 5 Keeping intermediate files
190. e case you may need to restrict your GUI operations to a single Haskell thread and possibly also use a bound thread see Section 8 2 4 2 Note that foreign calls made by different Haskell threads may execute in parallel even when the RTS N flag is not being used Section 4 13 2 The RTS N flag controls parallel execution of Haskell threads but there may be an arbitrary number of foreign calls in progress at any one time regardless of the RTS N value 8 2 4 2 The relationship between Haskell threads and OS threads Normally there is no fixed relationship between Haskell threads and OS threads This means that when you make a foreign call that call may take place in an unspecified OS thread Furthermore there is no guarantee that multiple calls made by one Haskell thread will be made by the same OS thread This usually isn t a problem and it allows the GHC runtime system to make efficient use of OS thread resources However there are cases where it is useful to have more control over which OS thread is used for example when calling foreign code that makes use of thread local state For cases like this we provide bound threads which are Haskell threads tied to a particular OS thread For information on bound threads see the documentation for the Control Concurrent module 8 2 4 3 Foreign exports and multi threading When the program is linked with threaded then you may invoke foreign exported functions from multiple OS threads conc
191. e default runtime system which is purely single threaded Note that you do not need threaded in order to use concurrency the single threaded runtime supports concurrency between Haskell threads just fine The threaded runtime system provides the following benefits e Parallelism on a multiprocessor or multicore machine See Section 4 13 The ability to make a foreign call that does not block all other Haskell threads and to invoke foreign exported Haskell functions from multiple OS threads See Section 8 2 4 eventlog Link the program with the eventlog version of the runtime system A program linked in this way can generate a runtime trace of events such as thread start stop to a binary file program event1log which can then be interpreted later by various tools See Section 4 15 6 for more information event log can be used with threaded It is implied by debug fno gen manifest On Windows GHC normally generates a manifestfile when linking a binary The manifest is placed in the file prog exe manifest where prog exe is the name of the executable The manifest file currently serves just one purpose it disables the installer detection in Windows Vista that attempts to elevate privileges for executables with certain names e g names containing install setup or patch Without the manifest file to turn off installer detection attempting to run an executable that Windows deems to be an installer will return a permission err
192. e dramatically is to use better algorithms Once profiling has thrown the spotlight on the guilty time consumer s it may be better to re think your program than to try all the tweaks listed below Another extremely efficient way to make your program snappy is to use library code that has been Seriously Tuned By Someone Else You might be able to write a better quicksort than the one in Data List but it will take you much longer than typing import Data List Please report any overly slow GHC compiled programs Since GHC doesn t have any credible competition in the performance department these days it s hard to say what overly slow means so just use your judgement Of course if a GHC compiled program runs slower than the same program compiled with NHC or Hugs then it s definitely a bug Optimise using O or 02 This is the most basic way to make your program go faster Compilation time will be slower especially with 02 At present O2 is nearly indistinguishable from 0O Compile via C and crank up GCC The native code generator is designed to be quick not mind bogglingly clever Better to let GCC have a go as it tries much harder on register allocation etc So when we want very fast code we use O fvia C Overloaded functions are not your friend Haskell s overloading using type classes is elegant neat etc etc but it is death to performance if left to linger in an inner loop How can you squash it Give e
193. e expression language In the example the quasiquoter expr is bound to a value of type Language Haskell1 TH Quote QuasiQuoter which contains two functions for quoting expressions and patterns respectively The first argument to each quoter is the arbitrary string enclosed in the Oxford brackets The context of the quasi quotation statement determines which of the two parsers is called if the quasi quotation occurs in an expression context the expression parser is called and if it occurs in a pattern context the pattern parser is called Note that in the example we make use of an antiquoted variable n indicated by the syntax int n this syntax for anti quotation was defined by the parser s author not by GHC This binds n to the integer value argument of the constructor IntExpr when pattern matching Please see the referenced paper for further details regarding anti quotation as well as the description of a technique that uses SYB to leverage a single parser of type String gt a to generate both an expression parser that returns a value of type O Exp and a pattern parser that returns a value of type Q Pat In general a quasi quote has the form quoter string The quoter must be the name of an imported quoter it cannot be an arbitrary expression The quoted st ring can be arbitrary and may contain newlines Quasiquoters must obey the same stage restrictions as Template Haskell e g in the example expr cannot be defined in
194. e file It must live in the same directory as its parent source file A hs Currently if you use a literate source file A 1hs you must also use a literate boot file A 1hs boot and vice versa A hs boot file is compiled by GHC just like a hs file Sia e A hs boo When a hs boot file A hs boot is compiled it is checked for scope and type errors When its parent module A hs is compiled the two are compared and an error is reported if the two are inconsistent Just as compiling A hs produces an interface file A hi and an object file A o so compiling A hs boot produces an interface file A hi boot and an pseudo object file A o boot The pseudo object file A o boot is empty don t link it but it is very useful when using a Makefile to record when the A hi boot was last brought up to date see Section 4 6 10 The hi boot generated by compiling a hs boot file is in the same machine generated binary format as any other GHC generated interface file e g B hi You can display its contents with ghe show iface If you specify a directory for interface files the ohidir flag then that affects hi boot files too The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 50 240 e If hs boot files are considered distinct from their parent source files and if a SOURCE import is considered to refer to the hs boot file then the module import graph must have no cycles The comma
195. e for embedding manifests on Windows Normally this is the program windres which is supplied with a GHC installation See fno embed mani fest in Section 4 10 6 4 10 2 Forcing options to a particular phase Options can be forced through to a particular compilation phase using the following flags optL option Pass option to the literate pre processor optP option Pass option to CPP makes sense only if cpp is also on optF option Pass option to the custom pre processor see Section 4 10 4 optc option Pass option to the C compiler optm option Pass option to the mangler opta option Pass option to the assembler optl option Pass option to the linker optdl1l option Pass option to the DLL generator optwindres option Pass option to windres when embedding manifests on Windows See fno embed manif st in Section 4 10 6 So for example to force an Ewurb1e option to the assembler you would tell the driver opta Ewurbl1e the dash before the E is required GHC is itself a Haskell program so if you need to pass options directly to GHC s runtime system you can enclose them in RTS RTS see Section 4 15 4 10 3 Options affecting the C pre processor cpp The C pre processor cpp is run over your Haskell code only if the cpp option is given Unless you are building a large system with significant doses of conditional compilation you really shouldn t need it Dsymbol value Define macro symbo1 in the
196. e package configuration file filein addition to the system default file and the user s local file Packages in additional files read this way will override those in the global and user databases no user package conf Prevent loading of the user s local package database 4 8 4 1 The GHC_PACKAGE PATH environment variable The GHC_PACKAGE_PATH environment variable may be set to a separated separated on Windows list of files containing package databases This list of package databases is used by GHC and ghc pkg with earlier databases in the list overriding later ones This order was chosen to match the behaviour of the PATH environment variable think of it as a list of package databases that are searched left to right for packages If GHC_PACKAGE_PATH ends in a separator then the default user and system package databases are appended in that order e g to augment the usual set of packages with a database of your own you could say on Unix export GHC_PACKAGE_PATH HOME my ghc packages conf use instead of on Windows To check whether your GHC_PACKAGE_PATH setting is doing the right thing ghc pkg list will list all the databases in use in the reverse order they are searched 2it used to in GHC 6 4 but not since 6 6 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 61 240 4 8 5 Package IDs dependencies and broken packages Each installed package has a un
197. e pattern bindings f XNoMonoPatBinds i dynamic XMonoPatBinds polymorphic Relaxed checking for XRelaxedPolyRec mutually recursive dynamic XNoRelaxedPolyRec polymorphic functions HCi s extend XExtendedDefault Dee Cas enas XNoExtendedDefau default rules in a normal dynamic Rules ltRules module XOverloadedStrin Enable overloaded string XNoOverloadedStr E dynamic gs literals ings Enable generalised XGADTs dynamic XNOGADT s algebraic data types XTypeFamilies Enable type families dynamic XNoTypeFamilies XScopedT Varia Enable eee XNoScopedTypeVar L i E a p YP type variables Implied by dynamic f p YP bles iables fglasgow exts Enable do not generalise i XMonoLocalBinds a Ge S dynamic XNoMonoLocalBinds local bindings Enable Template Haskell XNoTemplateHask XTemplateHaskell No longer implied by dynamic 11 fglasgow exts XQuasiQuotes Enable quasiquotation dynamic XNoQuasiQuotes XBangPatterns Enable bang patterns dynamic XNoBangPatterns XCPP Enable the C preprocessor dynamic XNoCPP XPatternGuards Enable pattern guards dynamic XNoPatternGuards XViewPatterns Enable view patterns dynamic XNoViewPatterns XUnicodeSyntax Enable unicode syntax dynamic XNoUnicodeSyntax XMagicHash di ic dynamic XNoMagicHash L a modifier on identifiers y a XNewQualifiedOpe Enable new qualified ae XNoNewQualifiedo rators operator syntax y perators Enable explicit universal quantification Imp
198. e signature for any binder it will print the self same pragmatic information as would be put in an interface file Besides Core syntax is fun to look at Force key functions to be INLINEd esp monads Placing INLINE pragmas on certain functions that are used a lot can have a dramatic effect See Section 7 13 5 1 Explicit export list If you do not have an explicit export list in a module GHC must assume that everything in that module will be exported This has various pessimising effects For example if a bit of code is actually unused perhaps because of unfolding effects GHC will not be able to throw it away because it is exported and some other module may be relying on its existence GHC can be quite a bit more aggressive with pieces of code if it knows they are not exported Look at the Core syntax The form in which GHC manipulates your code Just run your compilation with ddump simp1 don t forget the 0 If profiling has pointed the finger at particular functions look at their Core code let s are bad cases are good dictionar ies d lt Class gt lt Unique gt or anything overloading ish are bad nested lambdas are bad explicit data constructors are good primitive operations e g eqInt are good Use strictness annotations Putting a strictness annotation on a constructor field helps in two ways it adds strictness to the program which gives the strictness analyser more to work with
199. e the standard classes Eq Ord Enum Ix Bounded Read and Show GHC extends this list with several more classes that may be automatically derived e With XDeriveDataTypeable you can derive instances of the classes Typeable and Data defined in the library modules Data Typeable and Data Generics respectively An instance of Typeable can only be derived if the data type has seven or fewer type parameters all of kind The reason for this is that the Typeable class is derived using the scheme described in Scrap More Boilerplate Reflection Zips and Generalised Casts Section 7 4 of the paper describes the multiple Typeable classes that are used and only Typeablel up to Typeable7 are provided in the library In other cases there is nothing to stop the programmer writing a TypableX class whose kind suits that of the data type constructor and then writing the data type instance by hand e With XDeriveFunctor you can derive instances of the class Functor defined in GHC Base e With XDeriveFoldable you can derive instances of the class Foldable defined in Data Foldable e With XDeriveTraversable you can derive instances of the class Traversable defined in Data Traversable In each case the appropriate class must be in scope before it can be mentioned in the deriving clause 7 5 4 Generalised derived instances for newtypes When you define an abstract type using newt ype you may want the new type to inheri
200. e to be significantly slower than the other forms of allocation above Foreign Marshal Pool Pools are currently implemented using malloc free so while they might be a more convenient way to structure your memory allocation than using one of the other forms of allocation they won t be any more efficient We do plan to provide an improved performance implementation of Pools in the future however 8 2 4 Multi threading and the FFI In order to use the FFI in a multi threaded setting you must use the threaded option see Section 4 10 6 8 2 4 1 Foreign imports and multi threading When you calla foreign imported function that is annotated as safe the default and the program was linked using th readed then the call will run concurrently with other running Haskell threads If the program was linked without t hreaded then the other Haskell threads will be blocked until the call returns This means that if you need to make a foreign call to a function that takes a long time or blocks indefinitely then you should mark it safe and use threaded Some library functions make such calls internally their documentation should indicate when this is the case If you are making foreign calls from multiple Haskell threads and using t hreaded make sure that the foreign code you are calling is thread safe In particularly some GUI libraries are not thread safe and require that the caller only invokes GUI methods from a single thread If this is th
201. e two example to illustrate the condition under which overlap is permitted pens ano T ep Tome lal type instance F Int b b overlap permitted type instenes lap Ime fel type instance G Char a a ILLEGAL overlap as Char Int 7 7 2 2 3 Decidability of type synonym instances In order to guarantee that type inference in the presence of type families decidable we need to place a number of additional restrictions on the formation of type instance declarations c f Definition 5 Relaxed Conditions of Type Checking with Open Type Functions Instance declarations have the general form The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 170 240 bype anstance Eel en a where we require that for every type family application G s1 sm int l s1 smdo not contain any type family constructors 2 the total number of symbols data type constructors and type variables in s1 sm is strictly smaller than in t 1 tn and 3 for every type variable a a occurs in s1 smatmostasoftenasintl tn These restrictions are easily verified and ensure termination of type inference However they are not sufficient to guarantee com pleteness of type inference in the presence of so called loopy equalities such asa F a where a recursive occurrence of a type variable is underneath a family application and data constructor application see the above mentioned paper
202. e types match too See Section 7 14 4 below GHC keeps trying to apply the rules as it optimises the program For example consider let s map f map Y in S ic xS The expression s t xs does not match the rule map map but GHC will substitute for s and t giving an expression which does match If s or t was a used more than once and b large or a redex then it would not be substituted and the rule would not fire Ordinary inlining happens at the same time as rule rewriting which may lead to unexpected results Consider this artificial example x RULES f f True False Gyan y h z g True Since f s right hand side is small it is inlined into g to give g Y Y Now g is inlined into h but s RULE has no chance to fire If instead GHC had first inlined g into h then there would have been a better chance that s RULE might fire The way to get predictable behaviour is to use a NOINLINE pragma on f to ensure that it is not inlined until its RULEs have had a chance to fire 7 14 3 List fusion The RULES mechanism is used to implement fusion deforestation of common list functions If a good consumer consumes an intermediate list constructed by a good producer the intermediate list should be eliminated entirely The following are good producers List comprehensions Enumerations of Int and Char e g a z Explicit lists e g True False The cons constructor e g
203. ecause of the implementation costs of Haskell s high level features you can always code under them In an extreme case you can write all your time critical code in C and then just glue it together with Haskell Before you get too carried away working at the lowest level e g sloshing Mut ableByteArray s around your program you may wish to check if there are libraries that provide a Haskellised veneer over the features you want The separate libraries documentation describes all the libraries that come with GHC 7 1 Language options The language option flags control what variation of the language are permitted Leaving out all of them gives you standard Haskell 98 Language options can be controlled in two ways e Every language option can switched on by a command line flag X by the flag XNo e g XNoTemplateHaskel1l e g XTemplateHaskel1 and switched off e Language options recognised by Cabal can also be enabled using the LANGUAGE pragma thus LANGUAGE Templa teHaskell see Section 7 13 1 The flag fglasgow exts is equivalent to enabling the following extensions XPrintExplicitForalls XForei gnFunctionInterface XUnliftedFFITypes XGADTs XImplicitParams XScopedTypeVariables XUnboxedTuples XTypeSynonymInstances XStandaloneDeriving XDeriveDataTypeable XF lexibleContexts XFlexiblelnstances XConstrainedClassMethods XMultiParamTypeClasse
204. ecause this is usually too large to fit on the profile graph each retainer set is numbered and shown abbreviated on the graph along with its number and the full list of retainer sets is dumped into the file prog prof Retainer profiling requires multiple passes over the live heap in order to discover the full retainer set for each object which can be quite slow So we set a limit on the maximum size of a retainer set where all retainer sets larger than the maximum retainer set size are replaced by the special set MANY The maximum set size defaults to 8 and can be altered with the R RTS option Rsize Restrict the number of elements in a retainer set to size default 8 5 4 2 1 Hints for using retainer profiling The definition of retainers is designed to reflect a common cause of space leaks a large structure is retained by an unevaluated computation and will be released once the computation is forced A good example is looking up a value in a finite map where unless the lookup is forced in a timely manner the unevaluated lookup will cause the whole mapping to be retained These kind of space leaks can often be eliminated by forcing the relevant computations to be performed eagerly using seq or strictness annotations on data constructor fields Often a particular data structure is being retained by a chain of unevaluated closures only the nearest of which will be reported by retainer profiling for example A retains B B retains C and C
205. echecking Rules are regarded as left to right rewrite rules When GHC finds an expression that is a substitution instance of the LHS of a tule it replaces the expression by the appropriately substituted RHS By a substitution instance we mean that the LHS can be made equal to the expression by substituting for the pattern variables GHC makes absolutely no attempt to verify that the LHS and RHS of a rule have the same meaning That is undecidable in general and infeasible in most interesting cases The responsibility is entirely the programmer s The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 202 240 GHC makes no attempt to make sure that the rules are confluent or terminating For example WAS Tora A RS OE WY This rule will cause the compiler to go into an infinite loop If more than one rule matches a call GHC will choose one arbitrarily to apply GHC currently uses a very simple syntactic matching algorithm for matching a rule LHS with an expression It seeks a substitution which makes the LHS and expression syntactically equal modulo alpha conversion The pattern rule but not the expression is eta expanded if necessary Eta expanding the expression can lead to laziness bugs But not beta conversion that s called higher order matching Matching is carried out on GHC s intermediate language which includes type abstractions and applications So a rule only matches if th
206. ect the actual runtime value of a variable and attempt to reconstruct its type If we try iton left qsort hs 2 15 46 Main gt set fprint evld with show as orcas ao 4 Gila Manse printe ert lere A fell This isn t particularly enlightening What happened is that left is bound to an unevaluated computation a suspension or thunk and print does not force any evaluation The idea is that print can be used to inspect values at a breakpoint without any unfortunate side effects It won t force any evaluation which could cause the program to give a different answer than it would normally and hence it won t cause any exceptions to be raised infinite loops or further breakpoints to be triggered see Section 2 5 3 Rather than forcing thunks print binds each thunk to a fresh variable beginning with an underscore in this case _t 1 The flag fprint evld with show instructs print to reuse available Show instances when possible This happens only when the contents of the variable being inspected are completely evaluated If we aren t concerned about preserving the evaluatedness of a variable we can use force instead of print The force command behaves exactly like print except that it forces the evaluation of any thunks it encounters qsort hs 2 15 46 Main gt force left lote 40 3 11 6We originally provided bindings for all variables in scope rather than just the free variables of the expression but found
207. ed by deriving clauses Thus the following is accepted data MinHeap h a H a h a deriving Show because the derived instance instance Show a Show h a gt Show MinHeap h a conforms to the above rules A useful idiom permitted by the above rules is as follows If one allows overlapping instance declarations then it s quite conve nient to have a default instance declaration that applies if something more specific does not instance C a where OO 6o5 Detemilie 7 6 3 3 Undecidable instances Sometimes even the rules of Section 7 6 3 2 are too onerous For example sometimes you might want to use the following to get the effect of a class synonym class Cl a C2 a C3 a gt C a where instance Cl a C2 a C3 a gt C a where This allows you to write shorter signatures 88 Ca gt instead of tse Cl ap oa Es ae The restrictions on functional dependencies Section 7 6 2 are particularly troublesome It is tempting to introduce type variables in the context that do not appear in the head something that is excluded by the normal rules For example The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 161 240 class HasConverter a b a gt b where Convert k AS O data Foo a MkFoo a instance HasConverter a b Show b gt Show Foo a where show MkFoo value show convert value This is dangerous territory however Here for example is a progr
208. ed by this bug you get an error message of the form Loading package javavm linking WARNING Overflown relocation field relocs found amp 30785 The last time we looked this bug still wasn t fixed in the BFD codebase and there wasn t any noticeable interest in fixing it when we reported the bug back in 2001 or so The workaround is to split up the o files that make up your package into two or more o s along the lines of how the base package does it The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 Chapter 13 Index RTS 79 r 36 s 36 t 19 36 RTS 79 install signal handlers RTS option 79 machine readable RTS option 81 show iface 48 verbose ghc pkg option 64 64 A RTS option 80 A lt size gt RTS option 121 124 B RTS option 84 C 42 43 Cs RTS option 77 D 70 RTS option 84 E 42 43 E option 43 E 71 RTS option 80 G RTS option 80 G RTS option 124 H 44 121 RTS option 81 L 70 RTS option 81 K RTS option 81 L 73 RTS option 110 M RTS option 81 M lt size gt RTS option 124 Nx 233 240 RTS option 78 O 37 194 O option 68 O not specified 68 00 68 O1 option 68 02 option 68 Ofile lt file gt option 68 P 106 108 RTS 79 Rghc timing 44 S 42 43 RTS option 81 S RTS option 124 U 70 V 42 64 RTS option 79 W option 54 Wall 54 Werr
209. eful for reversing the effect of fobject code fPIC Generate position independent code code that can be put into shared libraries This currently works on Linux x86 and x86 64 when using the native code generator fasm On Windows position independent code is never used so the flag is a no op on that platform dynamic When generating code assume that entities imported from a different package will reside in a different shared library or binary Note that using this option when linking causes GHC to link against shared libraries 4 10 6 Options affecting linking GHC has to link your code with various libraries possibly including user supplied GHC supplied and system supplied 1m math library for example 11ib Link in the 1ib library On Unix systems this will be in a file called 1iblib a or 1iblib so which resides somewhere on the library directories path Because of the sad state of most UNIX linkers the order of such options does matter If library foo requires library bar then in general 1 foo should come before 1 bar on the command line There s one other gotcha to bear in mind when using external libraries if the library contains a main function then this will be linked in preference to GHC s own main function eg Libf2c and 11b1 have their own main s This is because GHC s main comes from the HSrts library which is normally included after all the other libraries on the linker s com
210. ellohelloh 7 3 11 Rebindable syntax and the implicit Prelude import GHC normally imports Prelude hi files for you If you d rather it didn t then give ita XNoImplicitPrelude option The idea is that you can then import a Prelude of your own But don t call it Prelude the Haskell module namespace is flat and you must not conflict with any Prelude module Suppose you are importing a Prelude of your own in order to define your own numeric class hierarchy It completely defeats that purpose if the literal 1 means Prelude fromInteger 1 which is what the Haskell Report specifies So the XN oImplicitPrelude flag also causes the following pieces of built in syntax to refer to whatever is in scope not the Prelude versions The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 136 240 An integer literal 368 means fromInteger 368 Integer rather than Prelude fromInteger 368 Integer Fractional literals are handed in just the same way except that the translation is fromRational 3 68 Rational The equality test in an overloaded numeric pattern uses whatever is in scope The subtraction operation and the greater than or equal test in n k patterns use whatever and gt are in scope Negation e g x means negate f x both in numeric patterns and expressions Do notation is translated using whatever functions gt gt gt gt and fail are
211. eload Attempts to reload the current target set see 1oad if any of the modules in the set or any dependent module has changed Note that this may entail loading new modules or dropping modules which are no longer indirectly required by the target The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 35 240 run See main set option Sets various options See Section 2 8 for a list of available options and Section 4 18 10 for a list of GHCi specific flags The set command by itself shows which options are currently set It also lists the current dynamic flag settings with GHCi specific flags listed separately set args arg Sets the list of arguments which are returned when the program calls System getArgs set editor cmd Sets the command used by edit to cmd set prog prog Sets the string to be returned when the program calls System get ProgName set prompt prompt Sets the string to be used as the prompt in GHCi Inside prompt the sequence s is replaced by the names of the modules currently in scope and is replaced by If prompt starts with then it is parsed as a Haskell String otherwise it is treated as a literal string set stop num cmd Set a command to be executed when a breakpoint is hit or a new item in the history is selected The most common use of set stop is to display the source code at the current location e g set stop list If a number is given before the
212. em User s Guide Version 6 12 2 148 240 Note that f is not overloaded the Eq constraint arising from the use of is discharged by the pattern match on T1 and similarly the Show constraint arising from the use of show Unlike a Haskell 98 style data type declaration the type variable s in the data Set a where header have no scope Indeed one can write a kind signature instead data Set x gt where or even a mixture of the two data Bar a gt gt wher The type variables if given may be explicitly kinded so we could also write the header for Foo like this data Bar a b x gt where You can use strictness annotations in the obvious places in the constructor type data Term a where ILE Be Mie gt term Iie 1155 BR Ten osL gt Mesa a gt Term a gt Term a Pair Term a gt Term b gt Term a b You can use a deriving clause on a GADT style data type declaration For example these two declarations are equivalent data Maybel a where Nothingl Maybel a Justl 28 a gt Memssel a Ip elsrbyabmac ie Orcs data Maybe2 a Nothing2 Just2 a deriving ES Ord The type signature may have quantified type variables that do not appear in the result type data Foo where MkFoo 31 a gt le Bool gt Foo Nil 1k ROG Here the type variable a does not appear in the result type of either constructor Although it is universally quantified in
213. en modulo 2 where n is the size in bits of the Int type The fromIntegerfunction and hence also fromIntegral is a special case when converting to Int The value of fromIntegral x Int is given by taking the lower n bits of abs x multiplied by the sign of x in 2 s complement n bit arithmetic This behaviour was chosen so that for example writing Oxffffffff Int preserves the bit pattern in the resulting Int Negative literals such as 3 are specified by a careful reading of the Haskell Report as meaning Prelude negate Prelude fromInteger 3 So 2147483648 means negate fromInteger 2147483648 Since f romInteger takes the lower 32 bits of the representation fromInteger 2147483648 Integer computed at type Int is 2147483648 Int The negate operation then overflows but it is unchecked so negate 2 147483648 Int is just 2147483648 In short one can write minBound Int as a literal with the expected meaning but that is not in general guaranteed The fromIntegral function also preserves bit patterns when converting between the sized integral types Int 8 I nt16 Int32 Int 64 and the unsigned Word variants see the modules Data Int and Data Word in the library documentation Unchecked float arithmetic Operations on Float and Double numbers are unchecked for overflow underflow and other sad occurrences note however that some architectures trap floating point overflow and loss of precision and report a f
214. ending on the type of I O and the platform be implemented using blocking foreign calls The GHC runtime treats program exit as a special case to avoid the need to wait for blocked threads when a standalone executable exits Since the program and all its threads are about to terminate at the same time that the code is removed from memory it isn t necessary to ensure that the threads have exited first Unofficially if you want to use this fast and loose version of hs_exit then call shut downHaskellAndExit instead The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 217 240 Chapter 9 What to do when something goes wrong If you still have a problem after consulting this section then you may have found a bug please report it See Section 1 3 for details on how to report a bug and a list of things we d like to know about your bug If in doubt send a report we love mail from irate users Section 12 1 which describes Glasgow Haskell s shortcomings vs the Haskell language definition may also be of interest 9 1 When the compiler does the wrong thing Help The compiler crashed or panic d These events are always bugs in the GHC system please report them This is a terrible error message If you think that GHC could have produced a better error message please report it as a bug What about this warning from the C compiler For example warning
215. ent module e The expression you are annotating with must have a type with Typeable and Data instances e The Template Haskell staging restrictions apply to the expression being annotated with so for example you cannot run a function from the module being compiled To be precise the annotation ANN x e is well staged if and only if e would be disregarding the usual type restrictions of the splice syntax and the usual restriction on splicing inside a splice 1 is fine as an annotation albeit redundant If you feel strongly that any of these restrictions are too onerous please give the GHC team a shout However apart from these restrictions many things are allowed including expressions which are not fully evaluated Annotation expressions will be evaluated by the compiler just like Template Haskell splices are So this annotation is fine ANN f SillyAnnotation foo id 10 20 II bar E ee The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 198 240 7 13 6 2 Annotating types You can annotate types with the ANN pragma by using the t ype keyword For example ANN type Foo Just A Maybe String annotation ceta FOO soc 7 13 6 3 Annotating modules You can annotate modules with the ANN pragma by using the module keyword For example ANN module Just A Maybe String annotation 7 13 7 LINE pragma This pragma is s
216. equivalent to v dynamic v3 vn set verbosity level dynamic V display GHC version mode supported langu display the supported od g ages language extensions ninfo display information about To _ the compiler version display GHC version mode display GHC version numeric version a mode numeric only print libdir display ene ny mode directory output full span in error ferror spans static messages Set the minimum heap size Hsize static to size Summarise timing stats for Rghc timing GHC same as RTS static tstderr 4 18 2 Which phases to run Section 4 4 3 Flag Description Static Dynamic Reverse qe Stop after preprocessing hspp file aud i B Stop after generating C he file made p Stop after generating gt assembly s file meee j C Do not link dynamic Override default behaviour x suffix static for source files 4 18 3 Alternative modes of operation Section 4 4 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 91 240 Flag Description Static Dynamic Reverse Interactive mode normally interactive used by just running ghci mode see Chapter 2 for details Build a multi module Haskell program automatically figuring out make dependencies Likely to be mode much easier and faster
217. er enough to figure out that they both need recompiling You can force recompilation by removing the object file or by using the f force recomp flag no hs main In the event you want to include ghc compiled code as part of another non Haskell program the RTS will not be supplying its definition of main at link time you will have to To signal that to the compiler when linking use no hs main See also Section 8 2 1 1 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 74 240 Notice that since the command line passed to the linker is rather involved you probably want to use ghc to do the final link of your mixed language application This is not a requirement though just try linking once with v on to see what options the driver passes through to the linker The no hs main flag can also be used to persuade the compiler to do the link step in make mode when there is no Haskell Main module present normally the compiler will not attempt linking when there is no Main debug Link the program with a debugging version of the runtime system The debugging runtime turns on numerous assertions and sanity checks and provides extra options for producing debugging output at runtime run the program with RTS to see a list threaded Link the program with the threaded version of the runtime system The threaded runtime system is so called because it manages multiple OS threads as opposed to th
218. er these two definitions kemi sg ial gt IUNE lenl xs let Pacc 0 in len_accl xs len_accl acc Len caceis ere Let Taco Facer Mist an Lenta dal ES lanz sg lal gt Tnt len2 xs let Pacc 0 in len_acc2 xs Lemacta Ss ace et imi aes fal gt me len_acc2 acc kaa acc dxixs Let ace aee lesint im len see xs The only difference between the two groups is that in the second group len_acc is given a type signature In the former case len_accl is monomorphic in its own right hand side so the implicit parameter acc is not passed to the recursive call In the latter case because 1en_acc2 has a type signature the recursive call is made to the polymorphic version which takes acc as an implicit parameter So we get the following results in GHCi Prog gt lenl hello 0 Prog gt len2 hello 5 Adding a type signature dramatically changes the result This is a rather counter intuitive phenomenon worth watching out for 7 8 3 4 Implicit parameters and monomorphism GHC applies the dreaded Monomorphism Restriction section 4 5 5 of the Haskell Report to implicit parameters For example consider i 38 Aine e ENE f v let x 0 in let y x v in let x 5 in y Since the binding for y falls under the Monomorphism Restriction it is not generalised so the type of y is simply Int not x Int gt Int Hence f 9 returns result 9 If you add a type signature for y then y will get type
219. erefore possible to have several Main modules in separate source files in the same directory and GHC will not get confused In batch compilation mode the name of the object file can also be overridden using the o option and the name of the interface file can be specified directly using the ohi option The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 46 240 4 6 3 The search path In your program you import a module Foo by saying import Foo In make mode or GHCi GHC will look for a source file for Foo and arrange to compile it first Without make GHC will look for the interface file for Foo which should have been created by an earlier compilation of Foo GHC uses the same strategy in each of these cases for finding the appropriate file This strategy is as follows GHC keeps a list of directories called the search path For each of these directories it tries appending basename extension to the directory and checks whether the file exists The value of basename is the module name with dots replaced by the directory separator or depending on the system and extension is a source extension hs 1hs if we are in make mode or GHCi or hisuf otherwise For example suppose the search path contains directories d1 d2 and d3 and we are in make mode looking for the source file for a module A B C GHC will look in d1 A B C hs d1 A B C 1hs d2 A B C hs and so on The search path
220. ermines how many threads to use based on the number of CPUs in your machine The parallel GC now uses the same threads as the mutator with the consequence that you can no longer select a different number of threads to use for GC The gn RTS option has been removed except that g1 is still accepted for backwards compatibility The new flag RTS qggen sets the minimum generation for which parallel garbage collection is used Defaults to 1 The flag qg on its own disables parallel GC The new flag RTS qbgen controls load balancing in the parallel GC The new flag RTS qa uses the OS to set thread affinity experimental If you link with the eventlog flag then the new flag RTS 1 generates prog event log files which tools such as ThreadScope can use to show the behaviour of your program see Section 4 15 6 The RTS D gt x output is also sent to the eventlog file if this option is enabled The RTS v flag sends eventlog data to stderr instead There is a new statistic in the RTS s output SPARKS 1430 2 converted 1427 pruned This tells you how many sparks requests for parallel execution caused by calls to par were created how many were actually evaluated in parallel converted and how many were found to be already evaluated and were thus discarded pruned Any unaccounted for sparks are simply discarded at the end of evaluation 1 6 5 Build system We now require GHC gt 6 8 to build We now require th
221. es for this package The difference between hs libraries and extra libraries is that hs libraries normally have several versions to support profiling parallel and other build options The various versions are given different suffixes to distinguish them for example the profiling version of the standard prelude library is named 1ibHSbase_p a with the _p indicating that this is a profiling version The suffix is added automatically by GHC for hs libraries only no suffix is added for libraries in ext ra libraries The libraries listed in ext ra libraries may be any libraries supported by your system s linker including dynamic libraries so on Unix DLL on Windows Also extra libraries are placed on the linker command line after the hs libraries for the same package If your package has dependencies in the other direction i e ext ra libraries depends on hs libraries and the libraries are static you might need to make two separate packages include dirs string list A list of directories containing C includes for this package includes string list A list of files to include for via C compilations using this package Typically the include file s will contain function prototypes for any C functions used in the package in case they end up being called as a result of Haskell functions from the package being inlined depends package id list Packages on which this package depends hugs options string list Options to pass to Hug
222. es must therefore belong to a package By default ghc M generates all the dependencies and then concatenates them onto the end of makefile or Makefile if makefile doesn ca bracketed by the lines DO NOT DELE n E Beginning of Haskell dependencies and DO NOT DELETE End of Haskell dependencies If these lines already exist in the makefile then the old dependencies are deleted first Don t forget to use the same package options on the ghc M command line as you would when compiling this enables the dependency generator to locate any imported modules that come from packages The package modules won t be included in the dependencies generated though but see the include pkg deps option below The dependency generation phase of GHC can take some additional options which you may find useful The options which affect dependency generation are ddump mod cycles Display a list of the cycles in the module graph This is useful when trying to eliminate such cycles v2 Print a full list of the module dependencies to stdout This is the standard verbosity flag so the list will also be displayed with v3 and v4 Section 4 5 dep makefile file Use file as the makefile rather than makefile or Makefile If file doesn t exist mkde pendHS creates it We often use dep makefile depend to put the dependencies in depend and then include the file depend into Makefile
223. estriction flag XConstrainedClassMethods 7 6 2 Functional dependencies Functional dependencies are implemented as described by Mark Jones in Type Classes with Functional Dependencies Mark P Jones In Proceedings of the 9th European Symposium on Programming ESOP 2000 Berlin Germany March 2000 Springer Verlag LNCS 1782 Functional dependencies are introduced by a vertical bar in the syntax of a class declaration e g class Monad m gt MonadState s m m gt s where class Foo a bc ab gt c where There should be more documentation but there isn t yet Yell if you need it 7 6 2 1 Rules for functional dependencies In a class declaration all of the class type variables must be reachable in the sense mentioned in Section 7 8 2 from the free variables of each method type For example class Coll s a where empty 11 8 insert gt a gt S is not OK because the type of empty doesn t mention a Functional dependencies can make the type variable reachable class Coll sa s gt a where empty lt lt S sec Bes eg gt a Alternatively Co11 might be rewritten class Coll s a where empty 2 S a INS SAS ES which makes the connection between the type of a collection of a s namely s a and the element type a Occasionally this really doesn t work in which case you can split the class like this The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 156 240
224. et a breakpoint on the base case of qsort Main gt list qsort L soe 11 T ZAS CA ASES OS IS AS O miene 3 where left right filter lt a as filter gt a as 4 x Main gt b 1 Breakpoint 1 activated at qsort hs 1 11 12 Main gt and then run a small qgsort with tracing Main gt trace qsort 3 2 1 SPOPDe Cm ale ees oras AZ result ss al some lis sil gall 121 lt a gt We can now inspect the history of evaluation steps ISORA SEA Menas SE 8 CBOE NSi SRA a Sis 2 8 S ice jase se2s 55 2 CSO nas ON SSS E GS OE SIZE O IA 8 ES OS ZO SO 0 E CESEN Se ASS 2 ASOMAN ES OS ON SADO 9 GSOLE ASIA LO 24 10 32 ceso melo 409 Sabi ES OM SES Zi Sis I 8 SQL oO 13 2 COC Joss 10 10 3 09 14 2 CSO E SELLO 24 ails 2 ESO ase 2815445 16 8 Ciscoe lass lL O 3 55 lt end of history gt To examine one of the steps in the history use back Losec lass i gili l2 Neima glock Logged breakpoint at qsort hs 3 24 38 result al as la a gu el al csiorstehisi3 22 SO AMS Note that the local variables at each step in the history have been preserved and can be examined as usual Also note that the prompt has changed to indicate that we re currently examining the first step in the history 1 The command forward can be used to traverse forward in the history The trace command can be used with or without an expression When used without an expression tracing
225. f has the legal in GHC type fe Oe P gt Co a el oa aie o BOS e You can apply a type synonym to a partially applied type synonym type Generic i o forall x i x gt 0 x type Id x x foo Generic Id After expanding the synonym foo has the legal in GHC type LOO 8 OPI ox se gt px GHC currently does kind checking before expanding synonyms though even that could be changed After expanding type synonyms GHC does validity checking on types looking for the following mal formedness which isn t detected simply by kind checking e Type constructor applied to a type involving for alls e Unboxed tuple on left of an arrow e Partially applied type synonym So for example this will be rejected type Pr Int Int A O DER because GHC does not allow unboxed tuples on the left of a function arrow The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 143 240 7 4 4 Existentially quantified data constructors The idea of using existential quantification in data type declarations was suggested by Perry and implemented in Hope Nigel Perry The Implementation of Practical Functional Programming Languages PhD Thesis University of London 1991 It was later formalised by Laufer and Odersky Polymorphic type inference and abstract data types TOPLAS 16 5 pp1411 1430 1994 It s been in Lennart Augustsson s hbe Haskell compiler for several years and proved very
226. f j ddump foreign ie eed a dynamic stubs D fter i 1 A Ae ump after instrumentation name for program coverage ddump inlinings Dump inlining info dynamic ddump occur anal e dynamic output D th lts of C ddump opt cmm a eur cnet oe dynamic C optimising passes ddump parsed Dump parse tree dynamic ddump prep Dump prepared core dynamic ddump rn Dump renamer output dynamic ddump rules Dump rules dynamic D fi impli a ddump simpl Dip a dynamic output ddump simpl phas Dump output from each danie _ es simplifier phase dd impl i D tput fr h dump s imp iter Jump output from eac dynam g ations simplifier iteration ddump spec Dump specialiser output dynamic Dump TH spliced ddump splices expressions and what they dynamic evaluate to ddump stg Dump final STG dynamic ddump stranai Dump strictness analyser dyire g output ddump tc Dump typechecker output dynamic ddump types Dump type signatures dynamic ddump worker wra Dump worker wrapper dynamie p pper output ddump if trac Trace interface files dynamic ddump tc trac Trace typechecker dynamic ddump rn trac Trace renamer dynamic ddump rn stats Renamer stats dynamic ddump simpl stats Dump simplifier stats dynamic The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 103 240 Flag Descri
227. f the recursive knot and as the paper describes also has a semantic effect unless the monad satisfies the right shrinking law e Then each resulting rec is desugared using a call to Control Monad Fix mfix For example the rec group in the preceding example is desugared like this mae 19 lt E amp gt Ge lt miis NN che I lt ir gi i lt la c lt fba 2 eerriism ore r In general the statment rec ssis desugared to the statement vs lt mfix vs gt do ss return vs where vs is a tuple of the variables bound by ss The original rec typechecks exactly when the above desugared version would do so For example this means that the variables vs are all monomorphic in the statements following the rec because they are bound by a lambda The mf ix function is defined in the MonadFix class in Control Monad Fix thus class Monad m gt MonadFix m where m ix 1 dea gt ma gt Ma Here are some other important points in using the recursive do notation e It is enabled with the flag XDoRec which is in turn implied by Eglasgow exts e If recursive bindings are required for a monad then that monad must be declared an instance of the MonadFix class e The following instances of MonadF ix are automatically provided List Maybe IO Furthermore the Control Monad ST and Control Monad ST Lazy modules provide the instances of the MonadFix class for Haskell s internal state monad strict an
228. f the same extension you can put kind annotations in types as well Thus Le ons eee AO Gp 28 at reewlil gi ec S a gs The syntax is cieve NC O Yas IKin 4 The parentheses are required 7 8 5 Arbitrary rank polymorphism GHC s type system supports arbitrary rank explicit universal quantification in types For example all the following types are legal El 28 aeiee a ld a gt 19 gt 8l UA OE AA a lgs Owe E O EE gt lo gt 2 ra es Orali as ase gt ate gt late TL EE Om AE q lal a BO O SI gt Time Pas oral ar aaa gt Ini gt BOL gt Boel iol ge inte gt orali gi A a The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 176 240 Here 1 and gl are rank 1 types and can be written in standard Haskell e g f1 a gt b gt a The forall makes explicit the universal quantification that is implicitly added by Haskell The functions 2 and g2 have rank 2 types the foral1 is on the left of a function arrow As g2 shows the polymorphic type on the left of the function arrow can be overloaded The function 3 has a rank 3 type it has rank 2 types on the left of a function arrow GHC has three flags to control higher rank types e XPolymorphicComponents data constructors only can have polymorphic argument types e XRank2Types any function including data constructors can have a rank 2 type e XRankNTypes any functi
229. f the specified cost centres at the top hCname Restrict the profile to closures produced by cost centre stacks with one of the specified cost centres anywhere in the stack hmmodule Restrict the profile to closures produced by the specified modules hddesc Restrict the profile to closures with the specified description strings hytype Restrict the profile to closures with the specified types hrcc Restrict the profile to closures with retainer sets containing cost centre stacks with one of the specified cost centres at the top hbbio Restrict the profile to closures with one of the specified biographies where bio is one of lag drag void or use For example the following options will generate a retainer profile restricted to Branch and Leaf constructors prog RIS hr hdBranch Leaf There can only be one break down option eg hr in the example above but there is no limit on the number of further restrictions that may be applied All the options may be combined with one exception GHC doesn t currently support mixing the hr and hb options There are three more options which relate to heap profiling isecs Set the profiling sampling interval to secs seconds the default is 0 1 second Fractions are allowed for example 10 2 will get 5 samples per second This only affects heap profiling time profiles are always sampled on a 1 50 second frequency The Glorious Glasgow Haskel
230. f when two view pattern expressions are the same is very restricted it is not even full syntactic equality However it does include variables literals applications and tuples e g two instances of view hi there will be collected However the current implementation does not compare up to alpha equivalence so two instances of x view x gt y will not be coalesced 7 3 7 n k patterns n k pattern support is enabled by default To disable it you can use the XNONP lusKPatterns flag 7 3 8 The recursive do notation The do notation of Haskell 98 does not allow recursive bindings that is the variables bound in a do expression are visible only in the textually following code block Compare this to a let expression where bound variables are visible in the entire binding group It turns out that several applications can benefit from recursive bindings in the do notation The XDoRec flag provides the necessary syntactic support Here is a simple albeit contrived example LANGUAGE DoRec Jus tONE SESION MS CSS US E Ss return map negate xs As you can guess justOnes will evaluate to Just 1 1 1 The background and motivation for recusrive do notation is described in A recursive do for Haskell by Levent Erkok John Launchbury Haskell Workshop 2002 pages 29 37 Pittsburgh Pennsylvania The theory behind monadic value recursion is explained further in Erkok s thesis Value Recursion in Monadic Compu
231. fix it with ghc arg or runghce will think that it is the program to run e g runghc package conf ghc arg foo conf Main hs The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 40 240 Chapter 4 Using GHC 4 1 Options overview GHC s behaviour is controlled by options which for historical reasons are also sometimes referred to as command line flags or arguments Options can be specified in three ways 4 1 1 Command line arguments An invocation of GHC takes the following form ghe argument Command line arguments are either options or file names Command line options begin with They may not be grouped vO is different from v O Options need not precede filenames e g ghc x o o foo All options are processed and then applied to all files you cannot for example invoke ghc c 01 Foo hs 02 Bar hs to apply different optimisation levels to the files Foo hs and Bar hs 4 1 2 Command line options in source files Sometimes it is useful to make the connection between a source file and the command line options it requires quite tight For instance if a Haskell source file deliberately uses name shadowing it should be compiled with the fno warn name shad owing option Rather than maintaining the list of per file options in a Makefile it is possible to do this directly in the source file using the OPTIONS_GHC pragma OPTIONS_GHC fno warn name shadowing
232. following meanings v0 Disable all non essential messages this is the default v1 Minimal verbosity print one line per compilation this is the default when make or interactive is on v2 Print the name of each compilation phase as it is executed equivalent to dAshow passes v3 The same as v2 except that in addition the full command line if appropriate for each compilation phase is also printed v4 The same as v3 except that the intermediate program representation after each compilation phase is also printed excluding preprocessed and C assembly files ferror spans Causes GHC to emit the full source span of the syntactic entity relating to an error message Normally GHC emits the source location of the start of the syntactic entity only For example test hs 3 6 parse error on input where becomes test296 hs 3 6 10 parse error on input where And multi line spans are possible too POSTS 5 4 Er 7 8 Conflicting definitions for a Bound at test hs 5 4 Ost sio an tas buchne grova ows a lo El Note that line numbers start counting at one but column numbers start at zero This choice was made to follow existing convention i e this is how Emacs does it Hsize Set the minimum size of the heap to size This option is equivalent to RTS Hsize see Section 4 15 3 Rghc timing Prints a one line summary of timing statistics for the GHC run This option is equivalent to
233. for Elem becomes instance Eq Elem e gt Collects e wher type Elem e The most important point about associated family instances is that the type indexes corresponding to class parameters must be identical to the type given in the instance head here this is e which coincides with the only class parameter Instances for an associated family can only appear as part of instances declarations of the class in which the family was declared just as with the equations of the methods of a class Also in correspondence to how methods are handled declarations of associated types can be omitted in class instances If an associated family instance is omitted the corresponding instance type is not inhabited i e only diverging expressions such as undef ined can assume the type 7 7 2 2 2 Overlap of type synonym instances The instance declarations of a type family used in a single program may only overlap if the right hand sides of the overlapping instances coincide for the overlapping types More formally two instance declarations overlap if there is a substitution that makes the left hand sides of the instances syntactically the same Whenever that is the case the right hand sides of the instances must also be syntactically equal under the same substitution This condition is independent of whether the type family is associated or not and it is not only a matter of consistency but one of type safety Here ar
234. for type constructors or classes just as for data constructors However one cannot distinguish between the two in a fixity declaration a fixity declaration sets the fixity for a data constructor and the corresponding type constructor For example til Po sat sets the fixity for both type constructor T and data constructor T and similarly for x Int a Bool e Function arrow is infixr with fixity 0 This might change I m not sure what it should be The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 142 240 7 4 3 Liberalised type synonyms Type synonyms are like macros at the type level but Haskell 98 imposes many rules on individual synonym declarations With the XLiberalTypeSynonyms extension GHC does validity checking on types only after expanding type synonyms That means that GHC can be very much more liberal about type synonyms than Haskell 98 e You can write a forall including overloading in a type synonym thus us Dakss Catala sO dll ree s Ow da gt El gt lo gt Ely Sian 2 23 Discersual al AA es Saui y G 8 Disens ime gt iin Sic wane A rank 2 type Gp at Se Sf Ine e If you also use XUnboxedTuples you can write an unboxed tuple in a type synonym type Pr Int Int I 28 bar gt PE w eG oe ke GF e You can apply a type synonym to a forall type type Foo a a gt a gt Bool fA noo thor Bla doa p sis After expanding the synonym
235. from the two Baz 1 construc tors e You can t pattern match on an existentially quantified constructor in a let or where group of bindings So this is illegal f3 x a b where Bazl ab x Instead use a case expression f3 x case x of Bazl ab gt a b In general you can only pattern match on an existentially quantified constructor in a case expression or in the patterns of a function definition The reason for this restriction is really an implementation one Type checking binding groups is already a nightmare without existentials complicating the picture Also an existential pattern binding at the top level of a module doesn t make sense because it s not clear how to prevent the existentially quantified type escaping So for now there s a simple to state restriction We ll see how annoying it is e You can t use existential quantification for newt ype declarations So this is illegal newtype T forall a Ord a gt MkT a Reason a value of type T must be represented as a pair of a dictionary for Ord t and a value of type t That contradicts the idea that newt ype should have no concrete representation You can get just the same efficiency and effect by using data instead of newt ype If there is no overloading involved then there is more of a case for allowing an existentially quantified newt ype because the data version does carry an implementation cost but single field existentially quantified constructors
236. g at garbage collection time There s no particularly good reason to turn it off except to ensure the accuracy of certain data collected regarding thunk entry counts The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 85 240 4 15 8 Hooks to change RTS behaviour GHC lets you exercise rudimentary control over the RTS settings for any given program by compiling in a hook that is called by the run time system The RTS contains stub definitions for all these hooks but by writing your own version and linking it on the GHC command line you can override the defaults Owing to the vagaries of DLL linking these hooks don t work under Windows when the program is built dynamically The hook ghc_rts_optslets you set RTS options permanently for a given program A common use for this is to give your program a default heap and or stack size that is greater than the default For example to set H128m K1m place the following definition in a C source file Chata lt qhcm ris HO pS a rib Sme helena Compile the C file and include the object file on the command line when you link your Haskell program These flags are interpreted first before any RTS flags from the GHCRTS environment variable and any flags on the command line You can also change the messages printed when the runtime system blows up e g on stack overflow The hooks for these are as follows void OutOfHeapHook unsigned lo
237. g package conf options on the ghc pkg command line When asked to modify a database ghc pkg modifies the global database by default Specifying user causes it to act on the user database or package conf can be used to act on another database entirely When multiple of these options are given the rightmost one is used as the database to act upon Commands that query the package database list latest describe field dot operate on the list of databases specified by the flags user global and package conf If none of these flags are given the default is global user If the environment variable GHC_PACKAGE_PATH is set and its value does not end in a separator on Unix on Windows then the last database is considered to be the global database and will be modified by default by ghc pkg The intention here is that GHC_PACKAGE_ PATH can be used to create a virtual package environment into which Cabal packages can be installed without setting anything other than GHC_PACKAGE_PATH The ghc pkg program may be run in the ways listed below Where a package name is required the package can be named in full including the version number e g net work 1 0 or without the version number Naming a package without the version number matches all versions of the package the specified action will be applied to all the matching packages A package specifier that matches all version of the package can also be written
238. g larger than this will be spewed into an interface file Increasing this figure is more likely to result in longer compile times than faster code The next option is more useful funfolding use threshold n Default 8 This is the magic cut off figure for unfolding below this size a function definition will be unfolded at the call site any bigger and it won t The size computed for a function depends on two things the actual size of the expression minus any discounts that apply see funfolding con discount 4 10 Options related to a particular phase 4 10 1 Replacing the program for one or more phases You may specify that a different program be used for one of the phases of the compilation system in place of whatever the ghe has wired into it For example you might want to try a different assembler The following options allow you to change the external program used for a given compilation phase pgmL cmd Use cmd as the literate pre processor pgmP cmd Use cmd as the C pre processor with cpp only pgme cmd Use cmd as the C compiler pgmm cmd Use cmd as the mangler The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 70 240 pgms cmd Use cmd as the splitter pgma cmd Use cmd as the assembler pgml cmd Use cmd as the linker pgmdl1l cmd Use cmd as the DLL generator pgmF cmd Use cmd as the pre processor with F only pgmwindres cmd Use cmd as the program to us
239. ge changes oes 2 sds a ka Re ES OR ERS Pa hae Ba a eS 6 1 63 Warnings 4 gece eine ee ida Sea eed dee ee eee tbe a eee a oe 7 1 6 4 RuntimesysteM soco ocea RE ew Dee ee a e e 8 1 65 Buildsystem e rebre ris ecg e848 4 4 eke ee EA be Pe ee ee 8 1 36 60 Compiler 46 ee oe Sed bre OR eee Ee RE Sey ed BEER Sas he Ov ee Ca 6 SY 8 LET GHC sect a oe Fale eee E Oe A ace ee Ee ea So PR Re ew SE 9 1 6 8 Template Haskel r ira 22 SE Pee Ghee Fb eee Gites A A A ES 9 1 6 9 Package Handling 54565 e554 6e be Sok a E See Ew bes 9 SEI lt AA th ie ee Se ae ee a PG ee oe ees RES ES amp amp 10 1 6104 arrays 4 bob eee we 6 aR ee AN 10 16 102 Dase ota cee eae beaw E E E noe be bade ee Pk ee ae ea ee 10 16103 bytestoos sige e PAS EOE REG Ear eRe Rago Bao 11 16104 Cabal s 0 2s 64 2 bbw Re ee ow ee ee bow ad oe wa ee 11 1 6 10 5 contamers lt seia mya eS we A e oea e DEORE RED eh a EA R Ge a a 11 1 6 10 6 ditectOfy s ise ea A eS ee ee be be Ook be epee ea eee 11 1 6 10 7 dph dph base dph par dph prim interface dph prim par dph prim seq dph seq 12 1 6 10 8 extensible exceptions re 12 16 109 hilepath gt 23 5 4 24 6 amp ok BEE ee EPS ee ed ee AS 12 1 6 10 10 she binary sfc 4 4s eee oan eB ER be Des ok Sa ee See Ra ES SS 12 1610 11 ebe piim a Bee o Me a ee eae ele A e 12 16 1012 askell98 ico rr ee ee ee a RE A ee Bee Se es e 12 L610 1S Bp ob ea de eae bea eee bea ROA E ba ee Pe eee a ee 12 1 6 10
240. ge to GHC before building and installing the files global Operate on the global package database this is the default This flag affects the register update unreg ister expose and hide commands help Outputs the command line syntax user Operate on the current user s local package database This flag affects the register update unregister expose and hide commands v n verbose n Control verbosity Verbosity levels range from 0 2 where the default is 1 and v alone selects level 2 V version Output the ghc pkg version number 4 8 7 Building a package from Haskell source We don t recommend building packages the hard way Instead use the Cabal infrastructure if possible If your package is particularly complicated or requires a lot of configuration then you might have to fall back to the low level mechanisms so a few hints for those brave souls follow You need to build an installed package info file for passing to ghc pkg when installing your package The contents of this file are described in Section 4 8 8 The Haskell code in a package may be built into one or more archive libraries e g 1ibHSfoo a or a single shared object e g 1ibHSfoo d11 so dylib The restriction to a single shared object is because the package system is used to tell the compiler when it should make an inter shared object call rather than an intra shared object call call inter shared object calls require an extra indirecti
241. get all of these at once lots of output by using v5 or most of them with v4 Some of the most useful ones are ddump parsed parser output ddump rn renamer output ddump tc typechecker output The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 87 240 ddump splices Dump Template Haskell expressions that we splice in and what Haskell code the expression evaluates to ddump types Dump a type signature for each value defined at the top level of the module The list is sorted alphabetically Using dppr debug dumps a type signature for all the imported and system defined things as well useful for debugging the compiler ddump deriv derived instances ddump ds desugarer output ddump spec output of specialisation pass ddump rules dumps all rewrite rules including those generated by the specialisation pass ddump simpl simplifier output Core to Core passes ddump inlinings inlining info from the simplifier ddump cpranal CPR analyser output ddump stranal strictness analyser output ddump cse CSE pass output ddump workwrap worker wrapper split output ddump occur anal occurrence analysis output ddump prep output of core preparation pass ddump stg output of STG to STG passes ddump flatc flattened Abstract C ddump cmm Print the C code out ddump opt cmm Dump the results of C to C optimising passes ddump a
242. gh le 2 434 bead SH he BEDE SHES eR LSS RES eRe SHES GS 36 2 10 Compiling to object code inside GHCi 2 2 ee 37 2 11 FAQ and Things To Watch Out For s se cosce secere eepe cnu timamu er neto rpe 37 3 Using runghe 39 SL TAS oie oe Bh EO A a be A a ee ee ee OE a 39 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 vi 4 Using GHC 40 41 lt Opuons Overview 2 s vs 4 2 4 a8 OE EE eS Aa ORE aoe Be Re ein Bee ed gd G4 40 4 1 1 Command line arguments 0 a 40 4 1 2 Command line options in source files 2 2 0 0 00 00000000000 000000000 40 4 1 3 Setting options in GHCi 0 0 0 0 000000 00000000022 ee 41 4 2 Static Dynamic and Mode options 41 4 33 Meaningful file suffixes a s esea dae e e E E a e e e e a i E R 41 4 4 Modes of operation s c wor 4 saos Sek Ga Ba eR ae GR E ORGS a dae a E bok ee 41 441 Using ghe mak es 64 sb eee a dens baby cae ee eee ee ee ee ba bas 42 4 4 2 Expression evaluation mode 43 443 Batch compiler mode 43 4 4 3 1 Overriding the default behaviour fora file o o 43 4 5 Help and verbosity options lt snes pps 66 5 Slee a Boe ewe BESS ESAS E 44 4 6 Filenames and separate compilation 44 4 6 1 Haskell source files ee ee ceros A 45 4 6 2 Output files ocios eae a RES RAD Se De eS e is ae eS 45 46 3 Thesearchpath arar SYR ee Rd ee ee ee eR we EG Oe See ee e 46 4 6 4 Redirecting the compilation Ou
243. gt The execution continued at the point it previously stopped and has now stopped at the breakpoint for a second time 2 5 1 1 Setting breakpoints Breakpoints can be set in various ways Perhaps the easiest way to set a breakpoint is to name a top level function break identifier Where identifier names any top level function in an interpreted module currently loaded into GHCi qualified names may be used The breakpoint will be set on the body of the function when it is fully applied but before any pattern matching has taken place Breakpoints can also be set by line and optionally column number break line break line column break module line break module line column The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 26 240 When a breakpoint is set on a particular line GHCi sets the breakpoint on the leftmost subexpression that begins and ends on that line If two complete subexpressions start at the same column the longest one is picked If there is no complete subexpression on the line then the leftmost expression starting on the line is picked and failing that the rightmost expression that partially or completely covers the line When a breakpoint is set on a particular line and column GHCi picks the smallest subexpression that encloses that location on which to set the breakpoint Note GHC considers the TAB character to have a width of 1 wherever it occurs in other words it co
244. gument to hand1eA this stack consists of one value the value of the exception The command form of lambda merely gives this value a name More concretely the values on the stack are paired to the right of the environment So operators like handleA that pass extra inputs to their subcommands can be designed for use with the notation by pairing the values with the environment in this way More precisely the type of each argument of the operator and its result should have the form Si a e A el tt ee where e is a polymorphic variable representing the environment and ti are the types of the values on the stack with t 1 being the top The polymorphic variable e must not occur in a ti or t However the arrows involved need not be the same Here are some more examples of suitable operators bracketA gt a boa te e gt amero Sa d runReader gt a a gt al e Orare runState il ss gt a c gt a e State c State We can supply the extra input required by commands built with the last two by applying them to ordinary expressions as in PROC MO SS runReader do l s which adds s to the stack of inputs to the command built using runReader The command versions of lambda abstraction and application are analogous to the expression versions In particular the beta and eta rules describe equivalences of commands These three features operators lambda abstraction and application are the
245. h GHC for displaying heap profiles 5 4 1 RTS options for heap profiling There are several different kinds of heap profile that can be generated All the different profile types yield a graph of live heap against time but they differ in how the live heap is broken down into bands The following RTS options select which break down to use hc Breaks down the graph by the cost centre stack which produced the data hm Break down the live heap by the module containing the code which produced the data hd Breaks down the graph by closure description For actual data the description is just the constructor name for other closures it is a compiler generated string identifying the closure hy Breaks down the graph by type For closures which have function type or unknown polymorphic type the string will represent an approximation to the actual type hr Break down the graph by retainer set Retainer profiling is described in more detail below Section 5 4 2 hb Break down the graph by biography Biographical profiling is described in more detail below Section 5 4 3 In addition the profile can be restricted to heap data which satisfies certain criteria for example you might want to display a profile by type but only for data produced by a certain module or a profile by retainer for a certain type of data Restrictions are specified as follows hcname Restrict the profile to closures produced by cost centre stacks with one o
246. h a eh a a a 15 3 6 UTE 4 see a Sh wR ee ee hw SSE a be aa ee ba ee 1 5 3 7 dph dph base dph par dph prim interface dph prim par dph prim seq dph seq 1 5 3 8 extensible exceptions spss 55 be Bb be RR edigu ead tora RE EE 1 5 3 9 filepath s 25 56 6445 6444 6444 bb a eed ee Pe Oba e 15 3 10 she bimary a nk ew oe ee SRS eR o eS e a RO a 1 5311 LCP 22 ssn edd a ee et be wa ee ee bbw a a E 15312 haskell S ic oe amp big aes A A ee ee eB ete amp IA HPC 2 25 Gans so Se ea ee Ee Ee er ee ek ee ee ee ee ee 5 344 anteseremp 4 24554 bbe eee beet bi bebe a AHS GS 1 5 3 15 imteger simple coo eR RE a ee ee 1 5 3 16 old locale 2 2224 wa hw a a ak ee Ee el ee ae a W3 3 07 A ae A ae a ROR RG Ba ee A a eae BOS ae 153 18 pretty 2 gas Aah ed ee ee eee ee AR BM Be LSO PIOCESS a a i bse eee ee DESL S SERS eek ee ThE SHEE 1 53 20 TADO 6s sce we ye RS OER ARES ree eR Ae oa oS Se ree ee oS 1 53 21 Sybe os de ew a eRe EE ewe ee ee Ee a a ee a Be The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 iv 1 3 3 22 tembplate haskell so perea e rr RA ae eS Re ee eo eS 3 T3323 Me e 24 66 00 SS e A e be eee Pe ea 4 N 5 N5324 UNK 2 ges Se es Be Ok ee eee A ee be pak Ge eee be OS a 5 L325 WM piee p A GE eons arue de A gat ee es eee Gnas Bien gu edn G A 5 1 6 Release notes for version6 12 1 ee 6 1 6 1 Highlights 0 44 608440344008 pae Ea Ra eed Aa ed e Ae ae a 6 1 6 2 Langua
247. h rule has a name enclosed in double quotes The name itself has no significance at all It is only used when reporting how many times the rule fired A rule may optionally have a phase control number see Section 7 13 5 3 immediately after the name of the rule Thus RULES map map 2 forall f g xs map f map g xs map f g xs i The 2 means that the rule is active in Phase 2 and subsequent phases The inverse notation 2 is also accepted meaning that the rule is active up to but not including Phase 2 Each variable mentioned in a rule must either be in scope e g map or bound by the forall e g f g xs The variables bound by the forall are called the pattern variables They are separated by spaces just like in a type forall A pattern variable may optionally have a type signature If the type of the pattern variable is polymorphic it must have a type signature For example here is the foldr build rule WecoulicVowwlalileh zorzal k 2 ces toral do a b gt b gt ib cold kez build gk oz Since g has a polymorphic type it must have a type signature The left hand side of a rule must consist of a top level variable applied to arbitrary expressions For example this is not OK wrongl forall el e2 case True of True gt el False gt e2 el wrong2 Rore E f True True In wrong1 the LHS is not an application in wrong2 the LHS has a pattern variable in the head A rule
248. has no effect 7 9 Template Haskell Template Haskell allows you to do compile time meta programming in Haskell The background to the main technical innova tions is discussed in Template Meta programming for Haskell Proc Haskell Workshop 2002 There is a Wiki page about Template Haskell at http www haskell org haskellwiki Template_Haskell and that is the best place to look for further details You may also consult the online Haskell library reference material look for module Language Haskell1 TH Many changes to the original design are described in Notes on Template Haskell version 2 Not all of these changes are in GHC however The first example from that paper is set out below Section 7 9 3 as a worked example to help get you started The documentation here describes the realisation of Template Haskell in GHC It is not detailed enough to understand Template Haskell see the Wiki page 7 9 1 Syntax Template Haskell has the following new syntactic constructions You need to use the flag XTemplateHaskel1 to switch these syntactic extensions on XTemplateHaskell is no longer implied by fglasgow exts e A splice is written x where x is an identifier or where the is an arbitrary expression There must be no space between the and the identifier or parenthesis This use of overrides its meaning as an infix operator just as M x overrides the meaning of as an infix operator If you want the
249. he constructor s result type For example asta To a Pere se bo O ld e c is existential UPA Se sede i OKS wac Se E alo gt el gt E an lo Wise We ox Do oS BAD 3 s type mentions c which is The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 145 240 existentially quantified cara alo wers CL elessa GAC 2 0 6 e el UPASEA ej EE Us gt 083 UPS CA gt Clo upd4 g x g g2 x BAD f2 s type mentions Cc which is not a simple type variable argument in Gl s result type 7 4 4 4 Restrictions There are several restrictions on the ways in which existentially quantified constructors can be use e When pattern matching each pattern match introduces a new distinct type for each existential type variable These types cannot be unified with any other type nor can they escape from the scope of the pattern match For example these fragments are incorrect A METEO OLA ei Here the type bound by MkFoo escapes because a is the result of 1 One way to see why this is wrong is to ask what type 1 has ill SY POO gt E Weird What is this a in the result type Clearly we don t mean this ind gg oral ay Os gt a Mone The original program is just plain wrong Here s another sort of error f2 Bazl a b Bazl p q a q It s ok to say a b or p q but a q is wrong because it equates the two distinct types arising
250. he dynamic libraries when found Object files linked into shared objects must be compiled with fP IC see Section 4 10 5 When creating shared objects for Haskell packages the shared object must be named properly so that GHC recognizes the shared object when linked against this package See shared object name mangling dynload This flag selects one of a number of modes for finding shared libraries at runtime See Section 4 11 4 for a description of each mode main is thing The normal rule in Haskell is that your program must supply a main function in module Main When testing it is often convenient to change which function is the main one and the main is flag allows you to do so The thing can be one of e A lower case identifier foo GHC assumes that the main function is Main foo An module name A GHC assumes that the main function is A main e An qualified name A foo GHC assumes that the main function is A foo Strictly speaking main is is not a link phase flag at all it has no effect on the link step The flag must be specified when compiling the module containing the specified main function e g module A in the latter two items above It has no effect for other modules and hence can safely be given to ghc make However if all the modules are otherwise up to date you may need to force recompilation both of the module where the new main is and of the module where the main function used to be ghc is not clev
251. he file containing the module Main Note that with GHC the Main module doesn t have to be put in file Main hs Thus both ghe make Prog and ghe make Prog hs will produce Prog or Prog exe if you are on Windows odir dir Redirects object files to directory dir For example S ghc c parse Foo hs parse Bar hs gurgle Bumble hs odir uname m The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 47 240 The object files Foo o Bar o and Bumble o would be put into a subdirectory named after the architecture of the executing machine x86 mips etc Note that the odir option does not affect where the interface files are put use the hidir option for that In the above example they would still be put in parse Foo hi parse Bar hi and gurgle Bumble hi ohi file The interface output may be directed to another file bar2 Wurble iface with the option ohi bar2 Wu rble iface not recommended WARNING if you redirect the interface file somewhere that GHC can t find it then the recompilation checker may get confused at the least you won t get any recompilation avoidance We recommend using a combination of hidir and hisuf options instead if possible To avoid generating an interface at all you could use this option to redirect the interface into the bit bucket ohi de v null for example hidir dir Redirects all generated interface files into dir instead of the default st
252. her cpps leaves the backslash space pairs alone and the string gap works as expected 4 10 4 Options affecting a Haskell pre processor F A custom pre processor is run over your Haskell source file only if the F option is given Running a custom pre processor at compile time is in some settings appropriate and useful The F option lets you run a pre processor as part of the overall GHC compilation pipeline which has the advantage over running a Haskell pre processor separately in that it works in interpreted mode and you can continue to take reap the benefits of GHC s recompilation checker The pre processor is run just before the Haskell compiler proper processes the Haskell input but after the literate markup has been stripped away and possibly the C pre processor has washed the Haskell input Use pgmF cmd to select the program to use as the preprocessor When invoked the cmd pre processor is given at least three arguments on its command line the first argument is the name of the original source file the second is the name of the file holding the input and the third is the name of the file where cmd should write its output to The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 72 240 Additional arguments to the pre processor can be passed in using the opt F option These are fed to cmd on the command line after the three standard input and output arguments An example of a pre processor is t
253. hich the snap shot was built For example 6 7 20040225 would be a snapshot of the HEAD before the creation of the 6 8 branch The value of__ GLASGOW_HASKELL_ fora snapshot release is the integer xyy You should never write any conditional code which tests for this value however since interfaces change on a day to day basis and we don t have finer granularity in the values of __GLASGOW_HASKELL__ you should only conditionally compile using predicates which test whether ___GLASGOW_HASKELL___is equal to later than or earlier than a given major release The version number of your copy of GHC can be found by invoking ghc with the version flag see Section 4 5 1 5 Release notes for version 6 12 2 The significant changes to the various parts of the compiler are listed in the following sections There have also been numerous bug fixes and performance improvements over the 6 10 branch 1 5 1 Compiler and Runtime system A new flag no rtsopts flag allows you to disable parsing of RTS options by the run time system In some use cases when a program can be run as another user this can cause security problems For example myprog tsomefile will overwrite somefi le if the other user has permissions to do so The mingw installation bundled with GHC on Windows now includes a C compiler again Support for the FreeBSD Dragonfly and Haiku OSes has been improved Datatypes with a context but no constructors e g data
254. iated Type Synonyms M Chakravarty G Keller and S Peyton Jones In Proceedings of The Tenth ACM SIGPLAN International Conference on Functional Programming ACM Press pages 241 253 2005 Type families themselves are described in the paper Type Checking with Open Type Functions T Schrijvers S Peyton Jones M Chakravarty and M Sulzmann in Proceedings of ICFP 2008 The 13th ACM SIGPLAN International Conference on Functional Programming ACM Press pages 51 62 2008 Type families essentially provide type indexed data The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 164 240 types and named functions on types which are useful for generic programming and highly parameterised library interfaces as well as interfaces with enhanced static information much like dependent types They might also be regarded as an alternative to functional dependencies but provide a more functional style of type level programming than the relational style of functional dependencies Indexed type families or type families for short are type constructors that represent sets of types Set members are denoted by supplying the type family constructor with type parameters which are called type indices The difference between vanilla parametrised type constructors and family constructors is much like between parametrically polymorphic functions and ad hoc polymorphic methods of type classes Parametric polymorphic
255. ibility with other compilers 7 13 4 WARNING and DEPRECATED pragmas The WARNING pragma allows you to attach an arbitrary warning to a particular function class or type A DEPRECATED pragma lets you specify that a particular function class or type is deprecated There are two ways of using these pragmas e You can work on an entire module thus module Wibble DEPRECATED Use Wobble instead wher Or module Wibble WARNING This is an unstable interface wher When you compile any module that import Wibble GHC will print the specified message e You can attach a warning to a function class type or data constructor with the following top level declarations DEPRECATED f C T Don t use these WARNING unsafePerformIO This is unsafe I hope you know what you re doing When you compile any module that imports and uses any of the specified entities GHC will print the specified message You can only attach to entities declared at top level in the module being compiled and you can only use unqualified names in the list of entities A capitalised name such as T refers to either the type constructor T or the data constructor T or both if both are in scope If both are in scope there is currently no way to specify one without the other c f fixities Section 7 4 2 Warnings and deprecations are not reported for a uses within the defining module and b uses in a
256. id The type of the entire case expression must be rigid The type of any free variable mentioned in any of the case alternatives must be rigid A type is rigid if it is completely known to the compiler at its binding site The easiest way to ensure that a variable a rigid type is to give it a type signature For more precise details see Simple unification based type inference for GADTs The criteria implemented by GHC are given in the Appendix 7 5 Extensions to the deriving mechanism 7 5 1 Inferred context for deriving clauses The Haskell Report is vague about exactly when a deriving clause is legal For example data TO f a MkTO a deriving Eq daro Wil ae MIOS Ge deriving Eq dara M2 g a MeL te r en AS Bin gi ng The natural generated Eq code would result in these instance declarations instance Eq a gt Eq TO f a where instance Eq f a gt Eq T1 f a where instance Eq f f a gt Eq T2 f a where The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 151 240 The first of these is obviously fine The second is still fine although less obviously The third is not Haskell 98 and risks losing termination of instances GHC takes a conservative position it accepts the first two but not the third The rule is this each constraint in the inferred instance context must consist only of type variables with no repetitions This
257. ide a mechanism for the programmer to specify each multiple parameter class more precisely The compiler on the other hand is responsible for ensuring that the set of instances that are in scope at any given point in the program is consistent with any declared dependencies For example the following pair of instance declarations cannot appear together in the same scope because they violate the dependency for D even though either one on its own would be acceptable instance D Bool Int where instance D Bool Char where Note also that the following declaration is not allowed even by itself instance D a b where The problem here is that this instance would allow one particular choice of a to be associated with more than one choice for b which contradicts the dependency specified in the definition of D More generally this means that in any instance of the form instance D t s where for some particular types t and s the only variables that can appear in s are the ones that appear in t and hence if the type t is known then s will be uniquely determined The benefit of including dependency information is that it allows us to define more general multiple parameter classes without ambiguity problems and with the benefit of more accurate types To illustrate this we return to the collection class example and annotate the original definition of Collects with a simple dependency class Collects ce ce gt wher Smary ss CS A
258. identifier The default sort ordering is for the bands with the largest area to be stacked on top of the smaller ones The d option causes rougher bands those representing series of values with the largest standard deviations to be stacked on top of smoother ones b Normally hp2ps puts the title of the graph in a small box at the top of the page However if the JOB string is too long to fit in a small box more than 35 characters then hp2ps will choose to use a big box instead The b option forces hp2ps to use a big box e lt float gt in mm pt Generate encapsulated PostScript suitable for inclusion in LaTeX documents Usually the PostScript graph is drawn in landscape mode in an area 9 inches wide by 6 inches high and hp2ps arranges for this area to be ap proximately centred on a sheet of a4 paper This format is convenient of studying the graph in detail but it is unsuitable for inclusion in LaTeX documents The e option causes the graph to be drawn in portrait mode with float specifying the width in inches millimetres or points the default The resulting PostScript file conforms to the Encapsulated PostScript EPS convention and it can be included in a LaTeX document using Rokicki s dvi to PostScript converter dvips g Create output suitable for the gs PostScript previewer or similar In this case the graph is printed in portrait mode without scaling The output is unsuitable for a laser printer 1 Normally a profile
259. ies documentation Every new binding shadows any existing bindings of the same name including entities that are in scope in the current module context WARNING temporary bindings introduced at the prompt only last until the next load or reload command at which time they will be simply lost However they do survive a change of context with module the temporary bindings just move to the new location HINT To get a list of the bindings currently in scope use the show bindings command Prelude gt show bindings xe BG iste Prelude gt HINT if you turn on the t option GHCi will show the type of each variable bound by a statement For example Prelude gt set t Prelude gt let x xs 1 x 11 Integer xS Integer 2 4 3 What s really in scope at the prompt When you type an expression at the prompt what identifiers and types are in scope GHCi provides a flexible way to control exactly how the context for an expression is constructed Let s start with the simple cases when you start GHCi the prompt looks like this Prelude gt Which indicates that everything from the module Prelude is currently in scope If we now load a file into GHCi the prompt will change Prelude gt load Main hs Compiling Main Main hs interpreted Main gt The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 20 240 The new prompt is Main which indicates that we are typing expressions
260. imilar to C s 1ine pragma and is mainly for use in automatically generated Haskell code It lets you specify the line number and filename of the original code for example LINE 42 Foo vhs if you d generated the current file from something called Foo vhs and this line corresponds to line 42 in the original GHC will adjust its error messages to refer to the line file named in the LINE pragma 7 13 8 RULES pragma The RULES pragma lets you specify rewrite rules It is described in Section 7 14 7 13 9 SPECIALIZE pragma UK spelling also accepted For key overloaded functions you can create extra versions NB more code space specialised to particular types Thus if you have an overloaded function hammeredLookup Ord key gt key value gt key gt valu If it is heavily used on lists with Widget keys you could specialise it as follows SPECIALIZE hammeredLookup Widget value gt Widget gt value A SPECIALIZE pragma for a function can be put anywhere its type signature could be put A SPECIALIZE has the effect of generating a a specialised version of the function and b a rewrite rule see Section 7 14 that rewrites a call to the un specialised function into a call to the specialised one The type in a SPECIALIZE pragma can be any type that is less polymorphic than the type of the original function In concrete terms if the original function is f
261. in gt In the messages from the compiler we see that there is no line for D This is because it isn t necessary to compile D because the source and everything it depends on is unchanged since the last compilation At any time you can use the command show modules to get a list of the modules currently loaded into GHCi Main gt show modules D Deher a E C hs interpreted B B hs interpreted A A hs interpreted Main gt If we now modify the source of D or pretend to using the Unix command touch on the source file is handy for this the compiler will no longer be able to use the object file because it might be out of date Main gt touch D hs Main gt reload Compiling D D hs interpreted Ok modules loaded A B C D Main gt Note that module D was compiled but in this instance because its source hadn t really changed its interface remained the same and the recompilation checker determined that A B and C didn t need to be recompiled So let s try compiling one of the other modules AMA sl Glace e Clas Main gt load A Compiling D Compiling B D hs interpreted B hs interpreted Compiling C C hs interpreted Compiling A A hs interpreted OK module slo de oa BE DS The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 17 240 We didn t get the compiled version of C What happened Well in GHCi a compiled module may only de
262. in gt let b f 10 Main gt t b ls 22 ID Main gt b lt interactive gt 1 0 Ambiguous type variable b in the constraint Show b arising from a use of print culiao 219 19 _t2 a ain gt seq b b Main gt t b b a Main gt p b b Just 10 Main gt t b b Maybe Integer Main gt t E Integer gt Maybe Integer Main gt 20 Just 20 Manim mape RS Just l aust 2p Just 3 Just 4 Just Al at lt interactive gt 1 0 In the first application of we had to do some more type reconstruction in order to recover the result type of But after that we are free to use f normally 2 5 8 Limitations e When stopped at a breakpoint if you try to evaluate a variable that is already under evaluation the second evaluation will hang The reason is that GHC knows the variable is under evaluation so the new evaluation just waits for the result before continuing The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 31 240 but of course this isn t going to happen because the first evaluation is stopped at a breakpoint Control C can interrupt the hung evaluation and return to the prompt The most common way this can happen is when you re evaluating a CAF e g main stop at a breakpoint and ask for the value of the CAF at the prompt again e Implicit parameters see Section 7 8 3 are only available at the scope of a breakpoint if the
263. in scope not the Prelude versions List comprehensions mdo Section 7 3 8 and parallel array comprehensions are unaffected Arrow notation see Section 7 10 uses whatever arr gt gt gt first app and loop functions are in scope But unlike the other constructs the types of these functions must match the Prelude types very closely Details are in flux if you want to use this ask In all cases apart from arrow notation the static semantics should be that of the desugared form even if that is a little unexpected For example the static semantics of the literal 368 is exactly that of fromInteger 368 Integer it s fine for from Integer to have any of the types fromInteger Integer gt Integer fromInteger forall a Foo a gt Integer gt a fromInteger Num a gt a gt Integer fromInteger Integer gt Bool gt Bool Be warned this is an experimental facility with fewer checks than usual Use dcore lint to typecheck the desugared program If Core Lint is happy you should be all right 7 3 12 Postfix operators The XPostfixOperators flag enables a small extension to the syntax of left operator sections which allows you to define postfix operators The extension is this the left section is equivalent from the point of view of both type checking and execution to the expression CEDES for any expression e and operator The strict Haskell 98 interpretation is that the section is equ
264. in the DLL would have a main function like MyApp cpp tinclude stdafx h tinclude Lewis h int main int argc char xargv if lewis_Begin can now safely call other functions exported by Lewis DLL lewis_End return 0 Lewis h would have to have some appropriate ifndef to ensure that the Haskell FFI types were defined for external users of the DLL who wouldn t necessarily have GHC installed and therefore wouldn t have the include files like HsFF I h etc The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 229 240 Chapter 12 Known bugs and infelicities 12 1 Haskell 98 vs Glasgow Haskell language non compliance This section lists Glasgow Haskell infelicities in its implementation of Haskell 98 See also the when things go wrong section Chapter 9 for information about crashes space leaks and other undesirable phenomena The limitations here are listed in Haskell Report order roughly 12 1 1 Divergence from Haskell 98 12 1 1 1 Lexical syntax e Certain lexical rules regarding qualified identifiers are slightly different in GHC compared to the Haskell report When you have module reservedop such as M GHC will interpret it as a single qualified operator rather than the two lexemes M and 12 1 1 2 Context free syntax e GHC is a little less strict about the layout rule when used in do expressions Specifically the restriction
265. indows To this end they introduce a unix style directory hierarchy under some root directory typically is C cygwin Moreover everything built against the cygwin API including the cygwin tools and programs compiled with cygwin s ghc will see as the root of their file system happily pretending to work in a typical unix environment and finding things like bin and usr include without ever explicitly bothering with their actual location on the windows system probably C cygwin bin and C cygwin usr include 11 5 2 The problem GHC by default no longer depends on cygwin but is a native windows program It is built using mingw and it uses mingw s ghc while compiling your Haskell sources even if you call it from cygwin s bash but what matters here is that just like any other normal windows program neither GHC nor the executables it produces are aware of cygwin s pretended unix hierarchy GHC will happily accept either or V as path separators but it won t know where to find home joe Main hs or bin bash or the like This causes all kinds of fun when GHC is used from within cygwin s bash or in make sessions running under cygwin 11 5 3 Things to do Don t use absolute paths in make configure amp co if there is any chance that those might be passed to GHC or to GHC compiled programs Relative paths are fine because cygwin tools are happy with them and GHC accepts as path separator And relative
266. infix operator put spaces around it A splice can occur in place of The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 183 240 an expression the spliced expression must have type O Exp an type the spliced expression must have type O Typ alist of top level declarations the spliced expression must have type Q Dec Inside a splice you can can only call functions defined in imported modules not functions defined elsewhere in the same module A expression quotation is written in Oxford brackets thus where the is an expression the quotation has type O Exp dl where the is a list of top level declarations the quotation has type Q Dec tl where the is a type the quotation has type Q Typ e A quasi quotation can appear in either a pattern context or an expression context and is also written in Oxford brackets Svarid where the is an arbitrary string a full description of the quasi quotation facility is given in Section 7 9 5 e A name can be quoted with either one or two prefix single quotes f has type Name and names the function f Similarly C has type Name and names the data constructor C In general thing interprets thing in an expression context T has type Name and names the type constructor T That is thing interprets thing in a type context These Names can be used
267. ing functional dependencies To get a more useful version of the Collects class Hugs provides a mechanism that allows programmers to specify dependencies between the parameters of a multiple parameter class For readers with an interest in theoretical foundations and previous work The use of dependency information can be seen both as a generalization of the proposal for parametric type classes that was put forward by Chen Hudak and Odersky or as a special case of Mark Jones s later framework for improvement of qualified types The underlying ideas are also discussed in a more theoretical and abstract setting in a manuscript implparam where they are identified as one point in a general design space for systems of implicit parameterization To start with an abstract example consider a declaration such as class C a b where which tells us simply that C can be thought of as a binary relation on types or type constructors depending on the kinds of a and b Extra clauses can be included in the definition of classes to add information about dependencies between parameters as in the following examples class Dab a gt b where class Boab a gt 6 lo gt a where The notation a gt b used here between the and where symbols not to be confused with a function type indicates that the a parameter uniquely determines the b parameter and might be read as a determines b Thus D is not just a relation but actually a
268. ing the constraint to the context of the instance declaration thus instance C Int b gt Foo b where f x You need XFlexibleInstances to do this The willingness to be overlapped or incoherent is a property of the instance declaration itself controlled by the presence or otherwise of the XOverlappingInstances and XIncoherentInstances flags when that module is being defined Neither flag is required in a module that imports and uses the instance declaration Specifically during the lookup process e An instance declaration is ignored during the lookup process if a a more specific match is found and b the instance declaration was compiled with XOverlappingInstances The flag setting for the more specific instance does not matter e Suppose an instance declaration does not match the constraint being looked up but does unify with it so that it might match when the constraint is further instantiated Usually GHC will regard this as a reason for not committing to some other constraint But if the instance declaration was compiled with XIncoherent Instances GHC will skip the does it unify check for that declaration These rules make it possible for a library author to design a library that relies on overlapping instances without the library client having to know If an instance declaration is compiled without XOverlappingInstances then that instance can never be overlapped This could perhaps be inconvenient Perhaps the ru
269. initializers for one or more fields While not an error the missing fields are initialised with bottoms it is often an indication of a programmer error fwarn missing methods This option is on by default and warns you whenever an instance declaration is missing one or more methods and the corresponding class declaration has no default declaration for them The warning is suppressed if the method name begins with an underscore Here s an example where this is useful class C a where SiMe sk EL SERLE Comoe k Gl el S SicieilimG complexFn x y _simpleFn The idea is that a users of the class will only call complexFn never _simpleFn and b instance declarations can define either complexFn or_simpleFn fwarn missing signatures If you would like GHC to check that every top level function value has a type signature use the fwarn missing signatures option As part of the warning GHC also reports the inferred type The option is off by default fwarn name shadowing This option causes a warning to be emitted whenever an inner scope value has the same name as an outer scope value i e the inner value shadows the outer one This can catch typographical errors that turn into hard to find bugs e g in the inadvertent capture of what would be a recursive call in f let f id in E The warning is suppressed for names beginning with an underscore For example The Glorious Glasgow Haskell Compilation System U
270. instead the call graph is flattened into a tree 5 1 1 Inserting cost centres by hand Cost centres are just program annotations When you say auto all to the compiler it automatically inserts a cost centre annotation around every top level function in your program but you are entirely free to add the cost centre annotations yourself The syntax of a cost centre annotation is SCC name lt expression gt where name is an arbitrary string that will become the name of your cost centre as it appears in the profiling output and lt expression gt is any Haskell expression An SCC annotation extends as far to the right as possible when parsing SCC stands for Set Cost Centre Here is an example of a program with a couple of SCCs menn se O main do let xs SCC X 1 1000000 let ys SCC Y 1 2000000 PAS SS prime last dale os print last ys Plis SS The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 107 240 q ATS h 28 764 440 bytes x seconc E ql 5M 45M 40M_ 35M _ 3M 25M 20M 15M TOM 5M WURA a which gives this heap profile when run 00 0 2 0 4 0 6 5 1 2 Rules for attributing costs The cost of evaluating any expression in your program is attributed to a cost centre stack using the following rules If the expression is part of the one off costs of evaluating the enclosing top level definition then costs
271. int contexts can be built up in this way For example sort ao A Ma Bee ceoce EAS stoppedtatrias orcas 0 55 result al eor risi GO Solo ile Maisie While stopped at the breakpoint on line 2 that we set earlier we started a new evaluation with step qsort 1 3 This new evaluation stopped after one step at the definition of gsort The prompt has changed now prefixed with to indicate that there are saved breakpoints beyond the current one To see the stack of contexts use show context qsort hs 1 0 3 55 Main gt show context gt main Stopped at gqsort hs 2 15 46 Goer AS Stopped Matmqsone ans in He Oi Soo gs oras GIRO Solo es Mai n gt To abandon the current evaluation use abandon sort isis GOS os Main abandona qsort hs 2 15 46 Main gt abandon Main gt 2 5 4 The _result variable When stopped at a breakpoint or single step GHCi binds the variable _result to the value of the currently active expression The value of _result is presumably not available yet because we stopped its evaluation but it can be forced if the type is known and showable then just entering _result at the prompt will show it However there s one caveat to doing this evaluating _result will be likely to trigger further breakpoints starting with the breakpoint we are currently stopped at if we stopped at a real breakpoint rather than due to step So it will probably be necessary to issue a cont inue
272. ion e Neither name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW AND THE CON TRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED IN NO EVENT SHALL THE UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT INDIRECT INCIDENTAL SPECIAL EXEMPLARY OR CONSEQUENTIAL DAMAGES INCLUDING BUT NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE DATA OR PROFITS OR BUSINESS INTERRUPTION HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY WHETHER IN CONTRACT STRICT LIABILITY OR TORT INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 1 240 Chapter 1 Introduction to GHC This is a guide to using the Glasgow Haskell Compiler GHC an interactive and batch compilation system for the Haskell 98 language GHC has two main components an interactive Haskell interpreter also known as GHCi described in Chapter 2 and a batch compiler described throughout Chapter 4 In fact GHC consists of a single program
273. ional libraries 1 1 6 10 1 array Version number 0 3 0 0 was 0 2 0 0 The Data Array Diff module has been moved to its own package 6 10 2 base Version number 4 2 0 0 was 4 1 0 0 We also ship a base version 3 0 3 2 was 3 0 3 1 so legacy code should continue to work This package is now deprecated and will be removed in a future version of GHC Handle IO now supports automatic character set encoding and newline translation For more information see the Unicode encoding decoding and Newline conversion sections in the System IO haddock docs Lazy I O now throws an exception if an error is encountered in a divergence from the Haskell 98 spec which requires that errors are discarded see Section 21 2 2 of the Haskell 98 report The exception thrown is the usual IO exception that would be thrown if the failing IO operation was performed in the IO monad and can be caught by System 10 Error catch or Control Exception catch It is now possible to create your own handles For more information see the GHC 10 Handle haddock docs System IO now exports two new functions openTempFileWithDefaultPermissions and openBinaryTemp FileWithDefaultPermissions Data Fixed now provides Data and Typeable instances for Fixed and exports a number of new types E0 Uni El Deci E2 Centi E3 Mi11i E9 and Nano In Control Exception BlockedOnDeadMVar has been renamed to BlockedIndefinitelyOnMVa
274. ions Auto add _scc_s to all auto all dynamic no auto all top level functions caf all a scc_s to all dynamic no caf all The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 99 240 Flag Description Static Dynamic Reverse prof Turn on profiling static ai cies Turn on ticky ticky Static i profiling 4 18 17 Program coverage options Section 5 6 Flag Description Static Dynamic Reverse thee Turn on Haskell program taic 7 coverage instrumentation Directory to deposit mix hpedir dir files during compilation dynamic 7 default is hpc 4 18 18 Haskell pre processor options Section 4 10 4 Flag Description Static Dynamic Reverse Enable the use of a F pre processor set with dynamic pgmF 4 18 19 C pre processor options Section 4 10 3 Flag Description Static Dynamic Reverse E Run the C pre processor on donant i PE Haskell source files y Define a symbol in the C Dsymbol value dynamic Usymbol pre processor Undefine a symbol in the C Usymbol dynamic pre processor Add dir to the directory Idir search list for include dynamic files 4 18 20 Code generation options Section 4 10 5 Flag Description Static Dynamic Reverse aaa Use the native code dnimi fvia C generator fvia C Compile via C dynamic fasm fno code Omit co
275. ious Glasgow Haskell Compilation System User s Guide Version 6 12 2 66 240 hidden modules nimxcrse chiess msie wo cine 6 12 12 30 140 Liorary chirss sie alo ciuo G q 12 7 1 vmi 2s 5 6 IL 0 hs rariles HS Un 2 om lO extra libraries rt util dl extra ghci libraries taclude 0i239 usr Lib che 6 121 12 3 i 0 aciluedls includes HsUnix h execvpe h depends base 4 2 0 0 247bb20cde37c3ef4093ee124e04bc1c hugs Ope roms cec OPERONS Lalo framework dirs frameworks haddock interfaces usr share doc ghc html libraries unix unix haddock haddock html usr share doc ghc html libraries unix Here is a brief description of the syntax of this file A package description consists of a number of field value pairs A field starts with the field name in the left hand column followed by a and the value continues until the next line that begins in the left hand column or the end of file The syntax of the value depends on the field The various field types are freeform Any arbitrary string no interpretation or parsing is done string A sequence of non space characters or a sequence of arbitrary characters surrounded by quotes string list A sequence of strings separated by commas The sequence may be empty In addition there are some fields with special syntax e g package names version dependencies The allowed fields with their types are name The package s name without the version
276. ique identifier the installed package ID or just package ID for short which distinguishes it from all other installed packages on the system To see the package IDs associated with each installed package use ghc pkg list v G gaem oke list y using cache usr lib ghc 6 12 1 package conf d package cache usr lib ghc 6 12 1 package conf d Cabal 1 7 4 Cabal 1 7 4 48f5247e06853af93593883240e11238 vea 02 Oal eray 0 2 e RANES NES SS Mel y 00 DASS US base 3 0 3 0 6cbb157b9ae852096266e113b8fac4a2 base 4 2 0 base 4 2 0 0 247bb20cde37c3ef4093ee124e04bc1c 0 0 The string in parentheses after the package name is the package ID it normally begins with the package name and version and ends in a hash string derived from the compiled package Dependencies between packages are expressed in terms of package IDs rather than just packages and versions For example take a look at the dependencies of the haske1198 package ghc pkg field haskell98 depends depends array 0 2 0 1 9cbf76a576b6ee9c1f880cf171a0928d base 4 2 0 0 247bb20cde37c3ef4093ee124e04bc1ca directory 1 0 0 2 51711bc872c35ce4a453aal9c799008 old locale 1 0 0 1 d17c9777c8ee53a0d459734e27 2b8e9 old time 1 0 0 1 1c0d8ea38056e5087efle75cb0d139d1 process 1 0 1 1 d8fc d3baf44678a29b9d59ca0ad5780 random 1 0 0 1 423d08c90 004795fd10e60384ce6561 The purpose of the package ID is to detect problems caused by re installing a package without also recompiling the
277. is also possible to break down the heap in one or more of these states by a different criteria by restricting a profile by biography For example to show the portion of the heap in the drag or void state by producer DOC ARIS MS Moires VOLE Once you know the producer or the type of the heap in the drag or void states the next step is usually to find the retainer s OE nR ES N EECa os NOTE this two stage process is required because GHC cannot currently profile using both biographical and retainer information simultaneously 5 4 4 Actual memory residency How does the heap residency reported by the heap profiler relate to the actual memory residency of your program when you run it You might see a large discrepancy between the residency reported by the heap profiler and the residency reported by tools on your system eg ps or top on Unix or the Task Manager on Windows There are several reasons for this There is an overhead of profiling itself which is subtracted from the residency figures by the profiler This overhead goes away when compiling without profiling support of course The space overhead is currently 2 extra words per heap object which probably results in about a 30 overhead Garbage collection requires more memory than the actual residency The factor depends on the kind of garbage collection algorithm in use a major GC in the standard generation copying collector will usually require 3L bytes of memory where L is the
278. it does this is by using packages When using dynamic a module from a separate package is assumed to come from a separate shared lib while modules from the same package or the default main package are assumed to be within the same shared lib or main executable binary Most of the conventions GHC expects when using packages are described in Section 4 8 7 In addition note that GHC expects the hi files to use the extension dyn_hi The other requirements are the same as for C libraries and are described below in particular the use of the flags dynamic fPIC and shared The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 76 240 4 11 3 Shared libraries that export a C API Building Haskell code into a shared library is a good way to include Haskell code in a larger mixed language project While with static linking it is recommended to use GHC to perform the final link step with shared libaries a Haskell library can be treated just like any other shared libary The linking can be done using the normal system C compiler or linker It is possible to load shared libraries generated by GHC in other programs not written in Haskell so they are suitable for using as plugins Of course to construct a plugin you will have to use the FFI to export C functions and follow the rules about initialising the RTS See Section 8 2 1 2 In particular you will probably want to export a C function from your shared library to
279. itch will occur at the next heap block allocation after the timer expires a heap block allocation occurs every 4k of allocation With C0 or C context switches will occur as often as possible at every heap block allocation By default context switches occur every 20ms 4 13 Using SMP parallelism GHC supports running Haskell programs in parallel on an SMP symmetric multiprocessor There s a fine distinction between concurrency and parallelism parallelism is all about making your program run faster by making use of multiple processors simultaneously Concurrency on the other hand is a means of abstraction it is a convenient way to structure a program that must respond to multiple asynchronous events However the two terms are certainly related By making use of multiple CPUs it is possible to run concurrent threads in parallel and this is exactly what GHC s SMP parallelism support does But it is also possible to obtain performance improvements with parallelism on programs that do not use concurrency This section describes how to use GHC to compile and run parallel programs in Section 7 18 we describe the language features that affect parallelism 4 13 1 Compile time options for SMP parallelism In order to make use of multiple CPUs your program must be linked with the threaded option see Section 4 10 6 Addi tionally the following compiler options affect parallelism feager blackholing Blackholing is the act of marki
280. ivalent to y gt 1 e y That is the operator must be a function of two arguments GHC allows it to take only one argument and that in turn allows you to write the function postfix The extension does not extend to the left hand side of function definitions you must define such a function in prefix form 7 3 13 Tuple sections The XTupleSections flag enables Python style partially applied tuple constructors For example the following program True 1s considered to be an alternative notation for the more unwieldy alternative x gt x True The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 137 240 You can omit any combination of arguments to the tuple as in the following o WIM p p Mowe y L337 which translates to sado e cl gt ep EY lo Ey Vows el 1337 If you have unboxed tuples enabled tuple sections will also be available for them like so True Because there is no unboxed unit tuple the following expression continues to stand for the unboxed singleton tuple data constructor 7 3 14 Record field disambiguation In record construction and record pattern matching it is entirely unambiguous which field is referred to even if there are two different data types in scope with a common field name For example module M where cara MES 1 x 86 Dame Y ES Bool module Foo where import M Glace IF Mica f oe 96 lame OI
281. king debugging 84 RULES pragma 200 runghc 39 running compiled program 79 runtime control of Haskell programs 79 S sanity checking options 54 search path 46 segmentation fault 218 separate compilation 42 44 shadowing interface files 55 shadowing warning 55 Shared libraries using 75 shell commands in GHCi 35 Show class 22 smaller programs how to produce 124 SMP 74 77 209 SOURCE 200 source file options 40 space leaks avoiding 124 SPECIALIZE pragma 122 198 199 specifying your own main function 73 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 sql 134 stability package specification 66 stack maximum size 81 stack minimum size 81 StackOverflowHook 85 startup files GHCi 36 statements in GHCi 18 static options 36 41 strict constructor fields 69 string gaps vs cpp 71 structure command line 40 suffixes file 41 T tabs warning 56 Template Haskell 140 temporary files keeping 47 redirecting 48 ThreadScope 84 ticky ticky profiling 84 ticky ticky profiling 118 time profile 108 TMPDIR environment variable 48 tracing 84 Type default 22 type signatures missing 55 U Unboxed types Glasgow extension 126 unfolding controlling 69 unicode 45 UNPACK 199 unregisterised compilation 89 unused binds warning 56 unused do binding warning 57 unused imports warning 56 unused matches warning 57 using GHC 40 UTF
282. l Compilation System User s Guide Version 6 12 2 110 240 xt Include the memory occupied by threads in a heap profile Each thread takes up a small area for its thread state in addition to the space allocated for its stack stacks normally start small and then grow as necessary This includes the main thread so using xt is a good way to see how much stack space the program is using Memory occupied by threads and their stacks is labelled as TSO when displaying the profile by closure description or type description Lnum Sets the maximum length of a cost centre stack name in a heap profile Defaults to 25 5 4 2 Retainer Profiling Retainer profiling is designed to help answer questions like why is this data being retained We start by defining what we mean by a retainer A retainer is either the system stack or an unevaluated closure thunk In particular constructors are not retainers An object B retains object A if i Bis a retainer object and 11 object A can be reached by recursively following pointers starting from object B but not meeting any other retainer objects on the way Each live object is retained by one or more retainer objects collectively called its retainer set or its retainer set or its retainers When retainer profiling is requested by giving the program the hr option a graph is generated which is broken down by retainer set A retainer set is displayed as a set of cost centre stacks b
283. l introduced by the existing keyword then then f This statement requires that f have the type forall a a gt a You can see an example of its use in the motivating example as this form is used to apply take 5 then f by e The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 135 240 This form is similar to the previous one but allows you to create a function which will be passed as the first argument to f As a consequence f must have the type forall a a gt t gt a gt a As you can see from the type this function lets f project out some information from the elements of the list it is transforming An example is shown in the opening example where sortWith is supplied with a function that lets it find out the sum salary for any item in the list comprehension it transforms then group by e using f This is the most general of the grouping type statements In this form f is required to have type forall a a gt t gt a gt a As with the then f by e case above the first argument is a function supplied to f by the compiler which lets it compute e on every element of the list being transformed However unlike the non grouping case f additionally partitions the list into a number of sublists this means that at every point after this statement binders occurring before it in the comprehension refer to lists of possible values not single values To help understand this le
284. l of the type arguments can be non variable types but may not contain forall types or type synonym families However data families are generally allowed in type parameters and type synonyms are allowed as long as they are fully applied and expand to a type that is itself admissible exactly as this is required for occurrences of type synonyms in class instance parameters For example the Either instance for GMap is data instance GMap Either a b v GMapEither GMap av GMap b v In this example the declaration has only one variant In general it can be any number Data and newtype instance declarations are only permitted when an appropriate family declaration is in scope just as a class instance declaratoin requires the class declaration to be visible Moreover each instance declaration has to conform to the kind determined by its family declaration This implies that the number of parameters of an instance declaration matches the arity determined by the kind of the family A data family instance declaration can use the full exprssiveness of ordinary data or newt ype declarations e Although a data family is introduced with the keyword dat a a data family instance can use either data or newt ype For example data family T a data sLinSiceligeG Ay rae S EZ O O newtype instance T Char INE BOGI e Adata instance can use GADT syntax for the data constructors and indeed can define a GADT For example data family
285. laration GHC does not restrict the form of the data type Instead GHC simply generates the appropriate boilerplate code for the specified class and typechecks it If there is a type error it is your problem GHC will show you the offending code if it has a type error The merit of this is that you can derive instances for GADTs and other exotic data types providing only that the boilerplate code does indeed typecheck For example data T a where TEE S Tata Ya OB Bool deriving instance Show T a In this example you cannot say deriving Show on the data type declaration for T because T is a GADT but you can generate the instance declaration using stand alone deriving e The stand alone syntax is generalised for newtypes in exactly the same way that ordinary deriving clauses are generalised Section 7 5 4 For example newtype Foo a MkFoo State Int a deriving instance MonadState Int Foo GHC always treats the last parameter of the instance Foo in this example as the type whose instance is being derived The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 152 240 7 5 3 Deriving clause for extra classes Typeable Data etc Haskell 98 allows the programmer to add deriving Eq Ord toa data type declaration to generate a standard instance declaration for classes specified in the deriving clause In Haskell 98 the only classes that may appear in the deriving clause ar
286. le The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 54 240 4 7 Warnings and sanity checking GHC has a number of options that select which types of non fatal error messages otherwise known as warnings can be generated during compilation By default you get a standard set of warnings which are generally likely to indicate bugs in your program These are fwarn overlapping patterns fwarn warnings deprecations fwarn deprecated fl ags fwarn duplicate exports fwarn missing fields fwarn missing methods fwarn lazy unlifted bindings fwarn wrong do bind and fwarn dodgy foreign imports The following flags are simple ways to select standard packages of warnings W Provides the standard warnings plus Ewarn incomplete patterns fwarn dodgy exports fwarn do dgy imports fwarn unused matches fwarn unused imports and fwarn unused binds Wal1 Turns on all warning options that indicate potentially suspicious code The warnings that are not enabled by Wa11 are fwarn simple patterns fwarn tabs fwarn incomplete record updates fwarn mon omorphism restriction fwarn unused do bind and fwarn implicit prelude w Turns off all warnings including the standard ones and those that Wa11 doesn t enable Werror Makes any warning into a fatal error Useful so that you don t miss warnings when doing batch compilation Wwarn Warnings a
287. le in interpreted modules compiled code is invisible to the debugger The debugger provides the following e The ability to set a breakpoint on a function definition or expression in the program When the function is called or the expression evaluated GHCi suspends execution and returns to the prompt where you can inspect the values of local variables before continuing with the execution e Execution can be single stepped the evaluator will suspend execution approximately after every reduction allowing local variables to be inspected This is equivalent to setting a breakpoint at every point in the program e Execution can take place in tracing mode in which the evaluator remembers each evaluation step as it happens but doesn t suspend execution until an actual breakpoint is reached When this happens the history of evaluation steps can be inspected e Exceptions e g pattern matching failure and error can be treated as breakpoints to help locate the source of an exception in the program There is currently no support for obtaining a stack trace but the tracing and history features provide a useful second best which will often be enough to establish the context of an error For instance it is possible to break automatically when an exception is thrown even if it is thrown from within compiled code see Section 2 5 6 2 5 1 Breakpoints and inspecting variables Let s use quicksort as a running example Here s the c
288. le should instead say that the overlapping instance declaration should be compiled in this way rather than the overlapped one Perhaps overlap at a usage site should be permitted regardless of how the instance declarations are compiled if the KOverlappingInstances flag is used at the usage site Mind you the exact usage site can occasionally be hard to pin down We are interested to receive feedback on these points The XIncoherent Instances flag implies the XOverlappingInstances flag but not vice versa The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 163 240 7 6 4 Overloaded string literals GHC supports overloaded string literals Normally a string literal has type St ring but with overloaded string literals enabled with XOverloadedStrings a string literal has type IsString a gt a This means that the usual string syntax can be used e g for packed strings and other variations of string like types String literals behave very much like integer literals i e they can be used in both expressions and patterns If used in a pattern the literal with be replaced by an equality test in the same way as an integer literal is The class IsSt ring is defined as class IsString a where ROMS Pl RR Siewaliangy gt 2 The only predefined instance is the obvious one to make strings work as usual instance IsString Char where fromString cs cs The class IsSt ring is not in scope by default If yo
289. led for profiling 36 169 392 bytes allocated in the heap 4 057 632 bytes copied during GC 1 065 272 bytes maximum residency 2 sample s 54 312 bytes maximum slop 3 MB total memory in use 0 MB lost due to fragmentation Generation 0 67 collections 0 parallel 0 04 0 03s elapsed Generation 1 2 collect tons 0 parallel O20ss 0 04s elapsed SPARKS 359207 557 converted 149591 pruned INIT time 0 00s 0 00s elapsed U time 0 01ls 0 02s elapsed GC time OTS 0 07s elapsed EXI time 0 00s 0 00s elapsed Total time 0 08s 0 09s elapsed SGC time Solos 75 3 elapsed Alloc rate 4 520 608 923 bytes per MUT second Productivity 10 5 of total user 9 1 of total elapsed e The bytes allocated in the heap is the total bytes allocated by the program over the whole run e GHC uses a copying garbage collector by default bytes copied during GC tells you how many bytes it had to copy during garbage collection e The maximum space actually used by your program is the bytes maximum residency figure This is only checked during major garbage collections so it is only an approximation the number of samples tells you how many times it is checked The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 83 240 The bytes maximum slop tells you the most space that is ever wasted due to the way GHC allocates memory in blocks Slop is memory at the end of a block that was wasted There s
290. les files are read ignore dot ghci Don t read either ghci or the other startup files when starting up read dot ghci Read ghci and the other startup files see above This is normally the default but the read d ot ghci option may be used to override a previous ignore dot ghci option 2 10 Compiling to object code inside GHCi By default GHCi compiles Haskell source code into byte code that is interpreted by the runtime system GHCi can also compile Haskell code to object code to turn on this feature use the fobject code flag either on the command line or with set the option fbyte code restores byte code compilation again Compiling to object code takes longer but typically the code will execute 10 20 times faster than byte code Compiling to object code inside GHCi is particularly useful if you are developing a compiled application because the reload command typically runs much faster than restarting GHC with make from the command line because all the interface files are already cached in memory There are disadvantages to compiling to object code you can t set breakpoints in object code modules for example Only the exports of an object code module will be visible in GHCi rather than all top level bindings as in interpreted modules 2 11 FAQ and Things To Watch Out For The interpreter can t load modules with foreign export declarations Unfortunately not We haven t implemented it yet Please c
291. lied by XScopedTypeVaria bles XLi 1T Bas XExplicitForALl XLlberalTypesyno dynamic XNoExplicitForAl nyms XRank2Types XRankNTypes XPol ymorphicComponents XExistentialQuan tification Enable polymorphic XPolymorphicComp iia XNoPolymorphicCo components for data dynamic onents mponents constructors XRank2Types Enable rank 2 types dynamic XNoRank2Types XRankNTypes Enable rank N types dynamic XNoRankNTypes X j iveTy AE XNoI edicative Merge oan Enable impredicative types dynamic i a a pes Types The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 95 240 Flag Description Static Dynamic Reverse XExistentialQuan Enable existential mama XNoExistentialQu tification quantification y antification XKindSignatures Enable kind signatures dynamic XNoKindSignatures XEmptyDataDecls Founi ADO ate dynamic XNoEmptyDataDecls nmpty declarations y ide Enable parallel list XNoParallelListC XParallelListComp dynamic comprehensions omp XTransformListCo Enable generalised list dnami XNoTransformList mp comprehensions y Comp i A XNoUnliftedFFITy XUnliftedFFITypes Enable unlifted FFI types dynamic pes E y XLiberalTypeSyno Enable liberalised type Iname XNoLiberalTypeS
292. ll With explicit parameters the default is that parameters must always be explicit propagated With implicit parameters the default is to always propagate them An implicit parameter type constraint differs from other type class constraints in the following way All uses of a particular implicit parameter must have the same type This means that the type of x x is x a gt a a andnot x za x b gt a b as would be the case for type class constraints You can t have an implicit parameter in the context of a class or instance declaration For example both these declarations are illegal class x Int gt C a where instance x a gt Foo a where Reason exactly which implicit parameter you pick up depends on exactly where you invoke a function But the invocation of instance declarations is done behind the scenes by the compiler so it s hard to figure out exactly where it is done Easiest thing is to outlaw the offending types Implicit parameter constraints do not cause ambiguity For example consider fos Ea Sean See ee ete ee rte Ena Gp Sica os JA REMOS LO WR ES in O PO g s show read s Here g has an ambiguous type and is rejected but f is fine The binding for x at s call site is quite unambiguous and fixes the type a 7 8 3 2 Implicit parameter bindings An implicit parameter is bound using the standard let or where binding forms For example we define the min function
293. loating point exception probably terminating the program 12 1 3 Divergence from the FFI specification hs_init not allowed after hs_exit The FFI spec requires the implementation to support re initialising itself after being shut down with hs_exit but GHC does not currently support that 12 2 Known bugs or infelicities The bug tracker lists bugs that have been reported in GHC but not yet fixed see the SourceForge GHC page In addition to those GHC also has the following known bugs or infelicities These bugs are more permanent it is unlikely that any of them will be fixed in the short term 12 2 1 Bugs in GHC e GHC can warn about non exhaustive or overlapping patterns see Section 4 7 and usually does so correctly But not always It gets confused by string patterns and by guards and can then emit bogus warnings The entire overlap check code needs an overhaul really e GHC does not allow you to have a data type with a context that mentions type variables that are not data type parameters For example data C a b gt T a MkT a so that MkT s type is Mie gs sore a jo C 2 lp gt a gt W a The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 232 240 In principle with a suitable class declaration with a functional dependency it s possible that this type is not ambiguous but GHC nevertheless rejects it The type variables mentioned in the context of the data type declaratio
294. low the download link to download GHC for your platform Alternatively if you want to build GHC yourself head on over to the GHC Building Guide to find out how to get the sources and build it on your system Note that GHC itself is written in Haskell so you will still need to install GHC in order to build it 1 2 Meta information Web sites mailing lists etc On the World Wide Web there are several URLs of likely interest e GHC home page e GHC Developers Home developer documentation wiki and bug tracker We run the following mailing lists about GHC We encourage you to join as you feel is appropriate The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 2 240 glasgow haskell users This list is for GHC users to chat among themselves If you have a specific question about GHC please check the FAQ first list email address glasgow haskell users haskell org subscribe at http www haskell org mailman listinfo glasgow haskell users admin email address glasgow haskell users admin haskell org list archives http www haskell org pipermail glasgow haskell users glasgow haskell bugs This list is for reporting and discussing GHC bugs However please see Section 1 3 before posting here list email address glasgow haskell bugs haskell org subscribe at http www haskell org mailman listinfo glasgow haskell bugs admin email address glasgow haskell bugs admin haskell org list archives htt
295. lows one to easily navigate around a multi file program finding definitions of functions types and constructors Invocation Syntax hasktags files This will read all the files listed in files and produce a ctags tags file and an etags TAGS file in the current directory Example usage find name hs xargs hasktags This will find all haskell source files in the current directory and below and create tags files indexing them in the current directory hasktags is a simple program that uses simple parsing rules to find definitions of functions constructors and types It isn t guaranteed to find everything and will sometimes create false index entries but it usually gets the job done fairly well In particular at present functions are only indexed if a type signature is given for them Before hasktags there used to be fptags and hstags which did essentially the same job however neither of these seem to be maintained any more 10 1 1 Using tags with your editor With NEdit load the tags file using File Load Tags File Use Ctrl D to search for a tag With XEmacs load the TAGS file using visit tags table Use M to search for a tag 10 2 Yacc for Haskell happy Andy Gill and Simon Marlow have written a parser generator for Haskell called happy Happy is to Haskell what Yacc is to C You can get happy from the Happy Homepage Happy is at its shining best when compiled by GHC The Glorious Glasg
296. ls you the bytes allocated in the heap divided by the MUT CPU time Productivity tells you what percentage of the Total CPU and wall clock elapsed times are spent in the mutator MUT The S flag as well as giving the same output as the s flag prints information about each GC as it happens Alloc Copied Live GC GE TOT TOT Page Flts bytes bytes bytes user elap user elap 528496 47728 aisla OOL 0 02 O02 0 02 0 0 Gen 1 oscil 524944 175944 1726384 0 00 0 00 0 08 0 dal 0 0 Gen 0 For each garbage collection we print How many bytes we allocated this garbage collection How many bytes we copied this garbage collection How many bytes are currently live How long this garbage collection took CPU time and elapsed wall clock time How long the program has been running CPU time and elapsed wall clock time How many page faults occured this garbage collection How many page faults occured since the end of the last garbage collection Which generation is being garbage collected 4 15 4 RTS options for concurrency and parallelism The RTS options related to concurrency are described in Section 4 12 and those for parallelism in Section 4 13 2 4 15 5 RTS options for profiling Most profiling runtime options are only available when you compile your program for profiling see Section 5 2 and Section 5 4 1 for the runtime options However there is one profiling option that is available for ordinary non profiled executables
297. ly defined by a triple package module and name 4 8 4 Package Databases A package database is where the details about installed packages are stored It is a directory usually called package conf d that contains a file for each package together with a binary cache of the package data in the file package cache Normally you won t need to look at or modify the contents of a package database directly all management of package databases can be done through the ghc pkg tool see Section 4 8 6 GHC knows about two package databases in particular e The global package database which comes with your GHC installation e g usr lib ghc 6 12 1 package conf d e A package database private to each user On Unix systems this will be SHOME ghc arch os version package conf d and on Windows it will be something like C Documents And Settings user ghc package conf d The ghc pkg tool knows where this file should be located and will create it if it doesn t exist see Section 4 8 6 When GHC starts up it reads the contents of these two package databases and builds up a list of the packages it knows about You can see GHC s package table by running GHC with the v flag Package databases may overlap for example packages in the user database will override shadow those of the same name and version in the global database You can control the loading of package databases using the following GHC options package conf file Read in th
298. m User s Guide Version 6 12 2 138 240 module Foo where import qualified M Note qualified ok4 M MkS x n n 1 Unambiguous Since the constructore MkS is only in scope qualified you must name it M MkS but the field x does not need to be qualified even though M x is in scope but x is not In effect it is qualified by the constructor 7 3 15 Record puns Record puns are enabled by the flag KNamedFieldPuns When using records it is common to write a pattern that binds a variable with the same name as a record field such as data Eo Cda ve Ine f C a a a Record punning permits the variable name to be elided so one can simply write f C a a to mean the same pattern as above That is in a record pattern the pattern a expands into the pattern a a for the same name a Note that e Record punning can also be used in an expression writing for example let a L in ta instead of let a 1 inC a a The expansion is purely syntactic so the expanded right hand side expression refers to the nearest enclosing variable that is spelled the same as the field name e Puns and other patterns can be mixed in the same record data C aa gl Seen O io Man DES 4 a e Puns can be used wherever record patterns occur e g in Let bindings or at the top level e A pun on a qualified field name is expanded by stripping off the module qualifier For example f C M a a means f
299. ma The UNPACK indicates to the compiler that it should unpack the contents of a constructor field into the constructor itself removing a level of indirection For example Float Float data T TI UNPACK UNPACK The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 200 240 will create a constructor T containing two unboxed floats This may not always be an optimisation if the T constructor is scrutinised and the floats passed to a non strict function for example they will have to be reboxed this is done automatically by the compiler Unpacking constructor fields should only be used in conjunction with O in order to expose unfoldings to the compiler so the reboxing can be removed as often as possible For example 2 2328 T gt Float ic E aal GE iL Pe The compiler will avoid reboxing 1 and f2 by inlining on floats but only when O is on Any single constructor data is eligible for unpacking for example data T T UNPACK Int Int will store the two Ints directly in the T constructor by flattening the pair Multi level unpacking is also supported data T T UNPACK S data S S UNPACK Int UNPACK Int will store two unboxed Int s directly in the T constructor The unpacker can see through newtypes too If a field cannot be unpacked you will not get a warning so it might be an idea to check the generated code with ddump si
300. making a dynamic library This reduces the disk space used when you do not need it e Packages can now be identified by a package ID which is based on a hash of the ABIs The new flag package id allows packages to be selected by this identifier see Section 4 8 5 Package IDs enable GHC to detect potential incompatibilities between packages and broken dependencies much more accurately than before e The new flag abi hash used thus Ghee ellas Malev The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 10 240 prints the combined hash of all the modules listed It is used to make package IDs You can now give ghc pkg a v0 flag to make it be silent v1 for normal verbosity the default or v2 or v for verbose output Rather than being a single package conf file package databases now consist of a directory containing one file per package and a binary cache of the information GHC should be much faster to start up when the package database grows large There is a new command ghc pkg init to create a package database There is a new command ghc pkg dot to generate a GraphViz graph of the dependencies between installed packages There is a new command ghc pkg recache to update the package database cache should it become out of date or for registering packages manually 1 6 10 Libraries GHC no longer comes with any extralibs instead the Haskell Platform will provide a consistent set of addit
301. mand line To force GHC s main to be used in preference to any other main s from external libraries just add the option 1HSrts before any other libraries on the command line c Onmits the link step This option can be used with make to avoid the automatic linking that takes place if the program contains a Main module The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 73 240 package name If you are using a Haskell package see Section 4 8 don t forget to add the relevant package option when linking the program too it will cause the appropriate libraries to be linked in with the program Forgetting the package option will likely result in several pages of link errors framework name On Darwin MacOS X only link in the framework name This option corresponds to the framework option for Apple s Linker Please note that frameworks and packages are two different things frameworks don t contain any haskell code Rather they are Apple s way of packaging shared libraries To link to Apple s Carbon API for example you d use framework Carbon Ldir Where to find user supplied libraries Prepend the directory dir to the library directories path framework pathdir On Darwin MacOS X only prepend the directory dir to the framework directories path This option corresponds to the F option for Apple s Linker F already means something else for GHC split objs Tell the
302. mdll 70 101 pgml 70 101 pgmm 69 pgms 70 pgmwindres 70 prof 104 108 185 qbRTS option 81 qgRTS option 80 T RTS option 84 r RTS option 118 read dot ghci 37 S RTS option 81 shared 73 split objs 73 static 73 stubdir 47 t RTS option 81 threaded 74 tmpdir 48 tmpdir lt dir gt option 48 v 44 121 ghc pkg option 64 RTS option 84 w 54 x 43 XC RTS option 84 108 xm RTS option 80 xt RTS option 110 ghci file 36 hc files saving 47 hi files 45 o files 45 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 S files saving 47 133 ToS A abandon 32 add 32 back 32 browse 32 cd 32 cmd 32 continue 32 def 33 delete 33 edit 33 etags 32 force 33 forward 33 help 33 history 33 info 33 kind 34 load 15 34 main 34 module 34 print 34 quit 34 reload 15 34 run 35 set 35 36 set args 35 set prog 35 show 35 show bindings 35 show breaks 35 show context 35 show languages 35 show modules 35 show packages 35 isprint 35 step 35 trace 35 type 35 undef 35 unset 35 _ CONCURRENT_HASKELL _ 71 _ GLASGOW_HASKELL__ 2 3 71 _ HASKELL1_ 71 __HASKELL98__ 71 __ HASKELL_ 98 71 _ PARALLEL HASKELL _ 71 show iface 42 auto ghci libs 64 force 64 global 64 help 42 64 info 42 make 41
303. module X where OPTIONS_GHC is a file header pragma see Section 7 13 Only dynamic flags can be used in an OPTIONS_GHC pragma see Section 4 2 Note that your command shell does not get to the source file options they are just included literally in the array of command line arguments the compiler maintains internally so yov ll be desperately disappointed if you try to glob etc inside OPTIONS_GHC NOTE the contents of OPTIONS_GHC are appended to the command line options so options given in the source file override those given on the command line It is not recommended to move all the contents of your Makefiles into your source files but in some circumstances the OPTION S_GHC pragma is the Right Thing If you use keep hc file and have OPTION flags in your module the OPTIONS_GHC will get put into the generated hc file The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 41 240 4 1 3 Setting options in GHCi Options may also be modified from within GHCi using the set command See Section 2 8 for more details 4 2 Static Dynamic and Mode options Each of GHC s command line options is classified as static dynamic or mode Mode flags For example make or E There may only be a single mode flag on the command line The available modes are listed in Section 4 4 Dynamic Flags Most non mode flags fall into this category A dynamic flag may be used on the command line in a OPTION
304. mr Gorte ciowe 3 where left right filter lt a as filter gt a as The list command lists the source code around the current breakpoint If your output device supports it then GHCi will highlight the active subexpression in bold GHCi has provided bindings for the free variables of the expression on which the breakpoint was placed a left right and additionally a binding for the result of the expression _result These variables are just like other variables that you might define in GHCi you can use them in expressions that you type at the prompt you can ask for their types with type and so on There is one important difference though these variables may only have partial types For example if we try to display the value of left qsort hs 2 15 46 Main gt left lt interactive gt 1 0 Ambiguous type variable a in the constraint Show a arising from a use of print at lt interactive gt 1 0 3 Cannot resolve unknown runtime types a Use print or force to determine these types This is because qsort is a polymorphic function and because GHCi does not carry type information at runtime it cannot determine the runtime types of free variables that involve type variables Hence when you ask to display left at the prompt GHCi can t figure out which instance of Show to use so it emits the type error above Fortunately the debugger includes a generic printing command print which can insp
305. n Complex Float the former is specialised heavily but the latter isn t Floats probably 32 bits are almost always a bad idea anyway unless you Really Know What You Are Doing Use Doubles There s rarely a speed disadvantage modern machines will use the same floating point unit for both With Doubles you are much less likely to hang yourself with numerical errors One time when Float might be a good idea is if you have a lot of them say a giant array of Floats They take up half the space in the heap compared to Doubles However this isn t true on a 64 bit machine Use unboxed arrays UArray GHC supports arrays of unboxed elements for several basic arithmetic element types including Int and Char see the Data Array Unboxed library for details These arrays are likely to be much faster than using standard Haskell 98 arrays from the Data Array library Use a bigger heap If your program s GC stats S RTS option indicate that it s doing lots of garbage collection say more than 20 of execution time more memory might help with the M lt size gt or A lt size gt RTS options see Section 4 15 3 6 3 Smaller producing a program that is smaller Decrease the go for it threshold for unfolding smallish expressions Give a funfolding use threshold0 option for the extreme case Only unfoldings with zero cost should proceed Warning except in certain specialised cases like Happy parsers this is likel
306. n export list The latter reduces spurious complaints within a library in which one module gathers together and re exports the exports of several others You can suppress the warnings with the flag fno warn warnings deprecations 7 13 5 INLINE and NOINLINE pragmas These pragmas control the inlining of function definitions The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 196 240 7 13 5 1 INLINE pragma GHC with O as always tries to inline or unfold functions values that are small enough thus avoiding the call overhead and possibly exposing other more wonderful optimisations Normally if GHC decides a function is too expensive to inline it will not do so nor will it export that unfolding for other modules to use The sledgehammer you can bring to bear is the INLINE pragma used thusly koya tunet onik tE e SENO gt BOO Double INLINE key_function The major effect of an INLINE pragma is to declare a function s cost to be very low The normal unfolding machinery will then be very keen to inline it However an INLINE pragma for a function f has a number of other effects e No functions are inlined into f Otherwise GHC might inline a big function into s right hand side making f big and then inline f blindly e The float in float out and common sub expression transformations are not applied to the body of f e An INLINE function
307. n gives further details about GADT style data type declarations e The result type of each data constructor must begin with the type constructor being defined If the result type of all constructors has the form T al an whereal an are distinct type variables then the data type is ordinary otherwise is a generalised data type Section 7 4 6 e As with other type signatures you can give a single signature for several data constructors In this example we give a single signature for T1 and T2 data T a where AE ES AA A ApS oe cil est e The type signature of each constructor is independent and is implicitly universally quantified as usual In particular the type variable s in the data T a where header have no scope and different constructors may have different universally quantified type variables data T a where The a has no scope TA tos o e a g Means torall bb 2 T b mS 8 W Means forall a Ta e A constructor signature may mention type class constraints which can differ for different constructors For example this is fine data T a where L ge we b gt b gt b gt T i Ta sa elvow 1 21 a gt el gt re When patten matching these constraints are made available to discharge constraints in the body of the match For example zee Ta gt Sicraimg ie EL x yy sey yes otherwise no E A a lo show a The Glorious Glasgow Haskell Compilation Syst
308. n instance 53 orphan instances warning 56 orphan module 53 orphan rule 53 orphan rules warning 56 OutOfHeapHook 85 output directing options 46 overflow Int 231 overlapping patterns warning 56 overloading death to 122 198 199 P package url package specification 66 packages 57 building 64 management 62 using 57 with GHCi 31 parallel list comprehensions 133 parallelism 74 77 208 parser generator for Haskell 219 Pattern guards Glasgow extension 129 patterns incomplete 55 patterns overlapping 56 phases changing 69 platform specific options 78 postscript from heap profiles 111 pragma 194 LANGUAGE 194 LINE 198 OPTIONS_GHC 195 pragma CORE 204 pragma RULES 200 pragma SPECIALIZE 198 pragmas 54 pre processing cpp 70 pre processing custom 71 239 240 Pre processor options 71 problems 217 problems running your program 217 problems with the compiler 217 proc 140 profiling 104 options 108 ticky ticky 84 with Template Haskell 185 profiling ticky ticky 118 prompt GHCi 14 Q quasi quotation 140 R reading Core syntax 88 recompilation checker 44 48 record updates incomplete 55 recursion between modules 49 redirecting compilation output 46 reporting bugs 2 rewrite rules 200 RTS 85 RTS behaviour changing 85 RTS hooks 85 RTS options 79 from the environment 79 garbage collection 80 RTS options concurrent 77 RTS options hac
309. n must be among the type parameters of the data type e GHC s inliner can be persuaded into non termination using the standard way to encode recursion via a data type data U MEU U gt Bool Eussel U gt Bool russel u MkU p not pu x 88 SOL x russel MkU russel We have never found another class of programs other than this contrived one that makes GHC diverge and fixing the problem would impose an extra overhead on every compilation So the bug remains un fixed There is more background in Secrets of the GHC inliner e GHC does not keep careful track of what instance declarations are in scope if they come from other packages Instead all instance declarations that GHC has seen in other packages are all in scope everywhere whether or not the module from that package is used by the command line expression This bug affects only the make mode and GHCi 12 2 2 Bugs in GHCi the interactive GHC e GHCi does not respect the default declaration in the module whose scope you are in Instead for expressions typed at the command line you always get the default default type behaviour that is default Int Double It would be better for GHCi to record what the default settings in each module are and use those of the current module whatever that is e On Windows there s a GNU ld BFD bug whereby it emits bogus PE object files that have more than Oxffff relocations When GHCi tries to load a package affect
310. n particular it is the record InstalledPackageInfo in the module Distribution InstalledPackag which is part of the Cabal package distributed with GHC An InstalledPackagelnfo has a human readable writable syntax The functions parseInstalledPackageInfo and showInstalledPackageInfo read and write this syntax respectively Here s an example of the InstalledPacka gelnfo for the unix package S ghc pkg describe unix name unix Weesakos 255 150 id unix 2 3 1 0 de7803f 1a8cd88d2161b29b083c94240 license BSD3 copyright maintainer libraries haskell org stability homepage package url description This package gives you access to the set of operating system services standardised by POSIX 1003 1b or the IEEE Portable Operating System Interface for Computing Environments WMA SEC LOOS The package is not supported under Windows except under Cygwin category System author exposed True xposed modules System Posix System Posix DynamicLinker Module System Posix DynamicLinker Prim System Posix Directory System Posix DynamicLinker System Posix Env System Posix Error System Posix Files System Posix IO System Posix Process System Posix Process Internals System Posix Resource System Posix Temp System Posix Terminal System Posix Time System Posix Unistd System Posix User System Posix Signals System Posix Signals Exts System Posix Semaphore System Posix SharedMem The Glor
311. n t 5 6 2 Options for instrumenting code for coverage Turning on code coverage is easy use the fhpc flag Instrumented and non instrumented can be freely mixed When compiling the Main module GHC automatically detects when there is an hpc compiled file and adds the correct initialization code 5 6 3 The hpc toolkit The hpc toolkit uses a cvs svn darcs like interface where a single binary contains many function units hpc Usage hpc COMMAND Commands help Display help for hpc or a single command Reporting Coverage FSDOTE Output textual report about program coverage markup Markup Haskell source with program coverage Processing Coverage files sum Sum multiple tix files in a single tix file The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 116 240 combine Combine two tix files in a single tix file map Map a function over a single tix file Coverage Overlays overlay Generate a tix file from an overlay file draft Generate draft overlay that provides 100 coverage Others show Show tix file in readable verbose format version Display version for hpc In general these options act on tix file after an instrumented binary has generated it which hpc acting as a conduit between the raw tix file and the more detailed reports produced The hpc tool assumes you are in the top level directory of the location where you built your application and the tix file is in the same top level dire
312. n the case version Two of the right hand sides are really the same fail and the whole expression tends to become more and more indented Here is how I would write clunky clunky env varl var2 Just vall lt lookup env veri Pp Util Veli locus Slow Wee za vall val2 Other equations for clunky The semantics should be clear enough The qualifiers are matched in order For a lt qualifier which I call a pattern guard the right hand side is evaluated and matched against the pattern on the left If the match fails then the whole guard fails and the next equation is tried If it succeeds then the appropriate binding takes place and the next qualifier is matched in the augmented environment Unlike list comprehensions however the type of the expression to the right of the lt is the same as the type of the pattern to its left The bindings introduced by pattern guards scope over all the remaining guard qualifiers and over the right hand side of the equation Just as with list comprehensions boolean expressions can be freely mixed with among the pattern guards For example i se wil lt Y gt S SI lt la y Haskell s current guards therefore emerge as a special case in which the qualifier list has just one element a boolean expression 7 3 6 View patterns View patterns are enabled by the flag KViewPatterns More information and examples of view patterns can be found on the Wiki page View patterns are
313. nables Unicode characters to be used to stand for certain ASCH character se quences The following alternatives are provided ASCII Unicode alternative gt gt forall y gt Ss 7 3 2 The magic hash The language extension XMagicHash allows as a postfix modifier to identifiers Thus x is a valid variable and T is a valid type constructor or data constructor The hash sign does not change sematics at all We tend to use variable names ending in for unboxed values or types e g Int but there is no requirement to do so they are just plain ordinary variables Nor does the KMagicHash extension bring anything into scope For example to bring Int into scope you must import GHC Prim see Section 7 2 the KMagicHash extension then allows you to refer to the Int that is now in scope The XMagicHash also enables some new forms of literals see Section 7 2 1 e x has type Char e foo has type Addr e 3 has type Int In general any Haskell 98 integer lexeme followed by a is an Int literal e g Ox3A as well as 324 e 3 has type Word In general any non negative Haskell 98 integer lexeme followed by is a Word e 3 2 has type Float e 3 2 has type Double 7 3 3 New qualified operator syntax A new syntax for referencing qualified operators is planned to be introduced by Haskell a
314. nd ghc M will report an error if a cycle is found e A module M that is SOURCE imported in a program will usually also be ordinarily imported elsewhere If not ghc make automatically adds M to the set of modules it tries to compile and link to ensure that M s implementation is included in the final program A hs boot file need only contain the bare minimum of information needed to get the bootstrapping process started For example it doesn t need to contain declarations for everything that module A exports only the things required by the module s that import A recursively A hs boot file is written in a subset of Haskell e The module header including the export list and import statements are exactly as in Haskell and so are the scoping rules Hence to mention a non Prelude type or class you must import it e There must be no value declarations but there can be type signatures for values For example clatlolle 2 Tate gt Itc e Fixity declarations are exactly as in Haskell e Type synonym declarations are exactly as in Haskell e A data type declaration can either be given in full exactly as in Haskell or it can be given abstractly by omitting the sign and everything that follows For example data Tab In a source program this would declare TA to have no constructors a GHC extension see Section 7 4 1 but in an hi boot file it means I don t know or care what the constructors are This
315. nd is enabled in GHC with the XNe wQualifiedOperators option In the new syntax the prefix form of a qualified operator is written module symbol in Haskell 98 this would be module symbo1 and the infix form is written module symbol in Haskell 98 this would be module symbol For example add x y Prelude x y subtract y Prelude y The new form of qualified operators is intended to regularise the syntax by eliminating odd cases like Prelude For example when NewQualifiedOperators is on it is possible to write the enumerated sequence Monday without spaces whereas in Haskell 98 this would be a reference to the operator from module Monday When XNewQualifiedOperators is on the old Haskell 98 syntax for qualified operators is not accepted so this option may cause existing Haskell 98 code to break The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 129 240 7 3 4 Hierarchical Modules GHC supports a small extension to the syntax of module names a module name is allowed to contain a dot This is also known as the hierarchical module namespace extension because it extends the normally flat Haskell module namespace into a more flexible hierarchy of modules This extension has very little impact on the language itself modules names are always fully qualified so you can just think of the fully qualified module name as the module name
316. ndow use the flag opt 1 mwindows in the link step Warning Windows GUI only programs have no stdin stdout or stderr so using the ordinary Haskell input output functions will cause your program to fail with an IO exception such as Fail lt stdout gt hPutChar failed Bad file descriptor The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 224 240 However using Debug Trace trace is alright because it uses Windows debugging output support rather than stderr For some reason Mingw ships with the readline library but not with the readline headers As a result GHC like Hugs does not use readline for interactive input on Windows You can get a close simulation by using an emacs shell buffer 11 4 Differences in library behaviour Some of the standard Haskell libraries behave slightly differently on Windows On Windows the Z character is interpreted as an end of file character so if you read a file containing this character the file will appear to end just before it To avoid this use IOExts openFileEx to open a file in binary untranslated mode or change an already opened file handle into binary mode using IOExts hSetBinaryMode The IOExts module is part of the Lang package 11 5 Using GHC and other GHC compiled executables with cygwin 11 5 1 Background The cygwin tools aim to provide a unix style API on top of the windows libraries to facilitate ports of unix software to w
317. new flag fbuilding cabal package which signals to GHC that it is being run by a build system rather than invoked directly This currently means that GHC gives different error messages in certain situations The following flags were static but are now dynamic fext core fauto sccs on all toplevs auto all no auto all fauto sccs on exported toplevs auto no auto fauto scecs on individu al cafs caf all and no caf all 1 6 7 GHCi e If the argument to set prompt starts with a double quote then it is read with Haskell String syntax e g Prelude gt set prompt Loaded s n gt Loaded Prelude gt e The arguments to set set and set show can now be tab completed e We inherit some benefits from an upgraded version of haskeline A multitude of new emacs and vi commands New preference historyDuplicates to prevent storage of duplicate lines Support PageUp and PageDown keys 1 6 8 Template Haskell e You can now omit the splice notation for top level declaration splices e g chica i ail 12 deriveMyStuff T e Splices are now nestable e g you can say f x g S h x e It is now possible to splice in types 1 6 9 Package Handling e Shared libraries are now supported on x86 and x86_64 Linux To use shared libraries use the dynamic flag See Section 4 11 for more information e The new fno shared implib flag can be used to stop GHC generating the 1 ib import library when
318. ng unsigned long The heap overflow message void StackOverflowHook long int The stack overflow message void MallocFailHook long int The message printed if malloc fails For examples of the use of these hooks see GHC s own versions in the file ghc compiler parser hschooks cina GHC source tree 4 15 9 Getting information about the RTS It is possible to ask the RTS to give some information about itself To do this use the info flag e g a out RTS info MUEIO RSU WNATgu UH Vers LON Ur ARMS Aya sh jo 4 Host platform x86_64 unknown linux Host architecture x86 64 Gost Sur lan Host vendor unknown Asta Lel olent roai SOUTO bes a Bula aren tecture 86264 BUIN SA ns Build vendor unknown Target platform x86_64 unknown linux Target architecture x86_64 beware US iia Target vendor unknown More siz Ss RS A Compiler unregisterised NO Tables next to code YES The information is formatted such that it can be read as a of type String String Currently the following fields are present GHC RTS Is this program linked against the GHC RTS always YES The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 86 240 GHC version The version of GHC used to compile this program RTS way The variant way of the runtim
319. ng a thunk lazy computuation as being under evaluation It is useful for three reasons firstly it lets us detect certain kinds of infinite loop the NonTermination exception secondly it avoids certain kinds of space leak and thirdly it avoids repeating a computation in a parallel program because we can tell when a computation is already in progress The option feager blackholing causes each thunk to be blackholed as soon as evaluation begins The default is lazy blackholing whereby thunks are only marked as being under evaluation when a thread is paused for some reason Lazy blackholing is typically more efficient by 1 2 or so because most thunks don t need to be blackholed However eager blackholing can avoid more repeated computation in a parallel program and this often turns out to be important for parallelism We recommend compiling any code that is intended to be run in parallel with the feager blackholing flag 4 13 2 RTS options for SMP parallelism To run a program on multiple CPUs use the RTS N option The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 78 240 N x Use x simultaneous threads when running the program Normally x should be chosen to match the number of CPU cores on the machine For example on a dual core machine we would probably use RTS N2 RTS Omitting x i e RTS N RTS lets the runtime choose the value of x itself based on how many processors are in you
320. ng this eager migration is that it tends to move threads that are communicating with each other onto the same CPU however there are pathalogical situations where it turns out to be a poor strategy Depending on the communication pattern in your program it may or may not be a good idea 4 13 3 Hints for using SMP parallelism Add the s RTS option when running the program to see timing stats which will help to tell you whether your program got faster by using more CPUs or not If the user time is greater than the elapsed time then the program used more than one CPU You should also run the program without N for comparison The output of RTS s tells you how many sparks were created and executed during the run of the program see Sec tion 4 15 3 which will give you an idea how well your par annotations are working GHC s parallelism support has improved in 6 12 1 as a result of much experimentation and tuning in the runtime system We d still be interested to hear how well it works for you and we re also interested in collecting parallel programs to add to our benchmarking suite 4 14 Platform specific Flags Some flags only make sense for particular target platforms monly 32 regs iX86 machines GHC tries to steal four registers from GCC for performance reasons it almost always works However when GCC is compiling some modules with four stolen registers it will crash probably saying Foo hc 533 fixed or forbi
321. no warn unused ches patterns that aren t used y matches warn about do bindings that fwarn unused do fno warn unused appear to throw away values dynamic bind do bind of types other than warn about do bindings that fwarn wrong do b appear to throw awa fno warn wrong d E PP y dynamic 3 ind monadic values that you should have bound instead o bind The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 4 18 14 Optimisation levels 97 240 Section 4 9 Flag Description Static Dynamic Reverse Enable default optimisation O dynamic 00 level 1 On Set optimisation level n dynamic 00 4 18 15 Individual optimisations Section 4 9 2 Flag Description Static Dynamic Reverse fcase merge Baeble e eSEE rE ME dynamic fno case mer g Implied by 0 y g fdicts strict Make dictionaries strict static fno dicts strict Share specialisations of l A snan fmethod sharing overloaded functions dynamic E default g Enable eta reduction i fno do eta reduc fdo eta reduction dynamic Implied by o tion fdo lambda eta e Enable lambda fno do lambda et dynamic xpansion eta reduction a expansion p Enable excess intermediate fno excess preci fexcess precision e dynamic precision sion E Ignore assertions in the fno ignore asser fignore asserts dynamic so
322. not already in scope For example both and g would be illegal if a was not already in scope 7 8 7 5 Class and instance declarations The type variables in the head of a class or instance declaration scope over the methods defined in the where part For example class C a where ga 88 leal gt a op xs let ys la ys reverse xs Tn head ys 7 8 8 Generalised typing of mutually recursive bindings The Haskell Report specifies that a group of bindings at top level or in a let or where should be sorted into strongly connected components and then type checked in dependency order Haskell Report Section 4 5 1 As each group is type checked any binders of the group that have an explicit type signature are put in the type environment with the specified poly morphic type and all others are monomorphic until the group is generalised Haskell Report Section 4 5 2 Following a suggestion of Mark Jones in his paper Typing Haskell in Haskell GHC implements a more general scheme If XR elaxedPolyRec is specified the dependency analysis ignores references to variables that have an explicit type signature As a result of this refined dependency analysis the dependency groups are smaller and more bindings will typecheck For example consider The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 182 240 E a a AB O O f x x x g True g Yes g y y lt y True This
323. not define a newtype whose representation type the argument type of the data constructor is an unboxed type Thus this is illegal newtype A MkA Int e You cannot bind a variable with an unboxed type in a top level binding e You cannot bind a variable with an unboxed type in a recursive binding e You may bind unboxed variables in a non recursive non top level pattern binding but you must make any such pattern match strict For example rather than data Foo Foo Int Int i og ler ROO 2 Jo W o omas gt s iim yola you must write The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 127 240 data Foo Foo Int Int i x ler LEO OO i scilisac O O CUYA since b has type Int 7 2 2 Unboxed Tuples Unboxed tuples aren t really exported by GHC Ext s they re available by default with Eglasgow exts An unboxed tuple looks like this Gin Ty nt Ean R where e_1 e_n are expressions of any type primitive or non primitive The type of an unboxed tuple looks the same Unboxed tuples are used for functions that need to return multiple values but they avoid the heap allocation normally associated with using fully fledged tuples When an unboxed tuple is returned the components are put directly into registers or on the stack the unboxed tuple itself does not have a composite representation Many of the primitive operations listed in primops txt pp return unboxed tuples In pa
324. ns 2 it must be different from the static name otherwise we would not be able to control the linker as precisely as necessary to make the st at ic dynamic flags work see Section 4 10 6 ghc shared libHSfoo 1 0 ghcGHCVersion so A o B o C o Using GHC s version number in the shared object name allows different library versions compiled by different GHC versions to be installed in standard system locations e g under nix usr lib To obtain the version number of GHC invoke ghc n umeric version and use its output in place of GHCVersion See also Section 4 10 5 on how object files must be prepared for shared object linking To compile a module which is to be part of a new package use the package name option Section 4 8 1 Failure to use the package name option when compiling a package will probably result in disaster but you will only discover later when you attempt to import modules from the package At this point GHC will complain that the package name it was expecting the module to come from is not the same as the package name stored in the hi file It is worth noting with shared objects when each package is built as a single shared object file since a reference to a shared object costs an extra indirection intra package references are cheaper than inter package references Of course this applies to the main package as well 4 8 8 InstalledPackagelInfo a package specification A package specification is a Haskell record i
325. ns has been added Support for kind annotations has been added Support for equality constraints has been added Support for type family declarations has been added 6 10 24 time This is a new boot package version 1 1 4 6 10 25 unix Version number 2 4 0 0 was 2 3 2 0 System Posix IO now exports fdReadBuf and fdWriteBuf System Posix Process executeFile now returns IO a instead of IO 6 10 26 Win32 Version number 2 2 0 1 was 2 2 0 0 13 240 System Win32 File now exports WIN32_FIND_DATA FindData getFindDataFileName findFirstFile findNextFile and findClose System Win32 Info now exports getCurrentDirectory getTemporaryDirectory getFullPathName and searchPath System Win32 Types now exports HRESULT There is a new module System Win32 Shell The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 14 240 Chapter 2 Using GHCi GHCi is GHC s interactive environment in which Haskell expressions can be interactively evaluated and programs can be inter preted If you re familiar with Hugs then you ll be right at home with GHCi However GHCi also has support for interactively loading compiled code as well as supporting all the language extensions that GHC provides GHCi also includes an interactive debugger see Section 2 5 2 1 Introduction to GHCi Let s start with an example GHCi session You can fire up GHCi with the command ghci S ghei GHCi versi
326. ns just the pre processing passes of the compiler dumping the result in a file 4 4 3 1 Overriding the default behaviour for a file As described above the way in which a file is processed by GHC depends on its suffix This behaviour can be overridden using the x option x suffix Causes all files following this option on the command line to be processed as if they had the suffix suffix For example to compile a Haskell module in the file M my hs use ghc c x hs M my hs The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 44 240 4 5 Help and verbosity options See also the he 1p version numeric version and print libdir modes in Section 4 4 n Does a dry run i e GHC goes through all the motions of compiling as normal but does not actually run any external commands v The v option makes GHC verbose it reports its version number and shows on stderr exactly how it invokes each phase of the compilation system Moreover it passes the v flag to most phases each reports its version number and possibly some other information Please oh please use the v option when reporting bugs Knowing that you ran the right bits in the right order is always the first thing we want to verify vn To provide more control over the compiler s verbosity the v flag takes an optional numeric argument Specifying v on its own is equivalent to v3 and the other levels have the
327. ntifier are shown If the option simple output is given then the packages are listed on a single line separated by spaces and the database names are not included This is intended to make it easier to parse the output of ghc pkg list using a script ghc pkg find module M simple output This option lists registered packages exposing module m Examples ghc pkg find module Var c fptools validate ghc driver package conf inplace ghc 6 9 20080428 ghc pkg find module Data Sequence c fptools validate ghc driver package conf inplace containers 0 1 Otherwise it behaves like ghc pkg list including options ghc pkg latest P Prints the latest available version of package P ghc pkg describe P Emit the full description of the specified package The description is in the form of an Installe dPackagelnfo the same as the input file format for ghc pkg register See Section 4 8 8 for details If the pattern matches multiple packages the description for each package is emitted separated by the string on a line by itself ghc pkg field P field field x Show just a single field of the installed package description for P Multiple fields can be selected by separating them with commas ghc pkg dot Generate a graph of the package dependencies in a form suitable for input for the graphviz tools For example to generate a PDF of the dependency graph ghc pkg dot tred dot Tpdf gt pkgs pdf ghc pkg dump Emit the full descri
328. o bar baz Perec bar oraz Prelude gt main foo bar baz PE SOO Yoc oas Finally other functions can be called either with the main is flag or the run command Prelude gt let foo putStrLn foo gt gt System Environment getArgs gt gt print Prelude gt let bar putStrLn bar gt gt System Environment getArgs gt gt print Prelude gt set main is foo Prelude gt main foo bar baz foo teat par baza Prelude gt run bar foo bar baz bar MECON ebara an 2 4 4 The it variable Whenever an expression or a non binding statement to be precise is typed at the prompt GHCi implicitly binds its value to the variable it For example Prelude gt 1 2 3 Prelude gt it x 2 6 What actually happens is that GHCi typechecks the expression and if it doesn t have an IO type then it transforms it as follows an expression e turns into let it e piete Lie which is then run as an IO action Hence the original expression must have a type which is an instance of the Show class or GHCi will complain Prelude gt id lt interactive gt 1 0 No instance for Show a gt a arising from use of print at lt interactive gt 1 0 1 Possible fix add an instance declaration for Show a gt a In the expression print it In a do expression print it The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 22 240 The erro
329. o convert your source files to the input encoding that GHC expects i e create a script convert sh containing the lines bin sh Geng Vise IN 1b SN IS E e thee S2 i gt 8S and pass F pgmF convert sh to GHC The f 11 option tells iconv to convert your Latin 1 file supplied in argument 2 while the t utf 8 options tell iconv to return a UTF 8 encoded file The result is redirected into argument 3 The echo LINE 1 2 just makes sure that your error positions are reported as in the original source file 4 10 5 Options affecting code generation fasm Use GHC s native code generator rather than compiling via C This will compile faster up to twice as fast but may produce code that is slightly slower than compiling via C fasm is the default fvia C Compile via C instead of using the native code generator This is the default on architectures for which GHC doesn t have a native code generator fno code Omit code generation and all later phases altogether Might be of some use if you just want to see dumps of the intermediate compilation phases fobject code Generate object code This is the default outside of GHCi and can be used with GHCi to cause object code to be generated in preference to bytecode fbyte code Generate byte code instead of object code This is the default in GHCi Byte code can currently only be used in the interactive interpreter not saved to disk This option is only us
330. o flag is necessary to enable them 7 3 18 Package qualified imports With the XPackageImports flag GHC allows import declarations to be qualified by the package name that the module is intended to be imported from For example import network Network Socket would import the module Network Socket from the package network any version This may be used to disambiguate an import when the same module is available from multiple packages or is present in both the current package being built and an external package Note you probably don t need to use this feature it was added mainly so that we can build backwards compatible versions of packages when APIs change It can lead to fragile dependencies in the common case modules occasionally move from one package to another rendering any package qualified imports broken 7 3 19 Summary of stolen syntax Turning on an option that enables special syntax might cause working Haskell 98 code to fail to compile perhaps because it uses a variable name which has become a reserved word This section lists the syntax that is stolen by language extensions We use notation and nonterminal names from the Haskell 98 lexical syntax see the Haskell 98 Report We only list syntax changes here that might affect existing working programs i e stolen syntax Many of these extensions will also enable new context free syntax but in all cases programs written to use the new syntax would not be compilable witho
331. o the dependencies never get out of sync with the source Any of the command line options described in the rest of this chapter can be used with make but note that any options you give on the command line will apply to all the source files compiled so if you want any options to apply to a single source file only you ll need to use an OPTIONS_GHC pragma see Section 4 1 2 If the program needs to be linked with additional objects say some auxiliary C code then the object files can be given on the command line and GHC will include them when linking the executable Note that GHC can only follow dependencies if it has the source file available so if your program includes a module for which there is no source file even if you have an object and an interface file for the module then GHC will complain The exception to this rule is for package modules which may or may not have source files The source files for the program don t all need to be in the same directory the i option can be used to add directories to the search path see Section 4 6 3 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 43 240 4 4 2 Expression evaluation mode This mode is very similar to interactive mode except that there is a single expression to evaluate which is specified on the command line as an argument to the e option ghc e expr Haskell source files may be named on the command line and they will be lo
332. o use the OS s built in support for allocating memory in the low 2Gb if available e g mmap with MAP_32BIT on Linux or otherwise xm40000000 4 15 3 RTS options to control the garbage collector There are several options to give you precise control over garbage collection Hopefully you won t need any of these in normal operation but there are several things that can be tweaked for maximum performance Asize Default 512k Set the allocation area size used by the garbage collector The allocation area actually generation 0 c step 0 is fixed and is never resized unless you use H below Increasing the allocation area size may or may not give better performance a bigger allocation area means worse cache behaviour but fewer garbage collections and less promotion With only 1 generation G1 the A option specifies the minimum allocation area since the actual size of the allocation area will be resized according to the amount of data in the heap see F below Use a compacting algorithm for collecting the oldest generation By default the oldest generation is collected using a copying algorithm this option causes it to be compacted in place instead The compaction algorithm is slower than the copying algorithm but the savings in memory use can be considerable For a given heap size using the H option compaction can in fact reduce the GC cost by allowing fewer GCs to be performed This is more likely when the ratio
333. ode asoma qsort a as qsort left a qsort right where left right filter lt a as filter gt a as MA ES EE 3p 4 WO Sp ty 28 iil i3 First load the module into GHCi Prelude gt 1 qsort hs 1 of 1 Compiling Main qsort hs interpreted Ok modules loaded Main Main gt Now let s set a breakpoint on the right hand side of the second equation of qsort Main gt break 2 Breakpoint 0 activated at qsort hs 2 15 46 Main gt The command break 2 sets a breakpoint on line 2 of the most recently loaded module in this case sort hs Specifically 1t picks the leftmost complete subexpression on that line on which to set the breakpoint which in this case is the expression qsort left a qsort right Now we run the program 5Note that packages only contain compiled code so debugging a package requires finding its source and loading that directly The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 24 240 Main gt main Stopped at qsort hs 2 15 46 result lt al a 33 A Lee se Tal waeine E qsort hs 2 15 46 Main gt Execution has stopped at the breakpoint The prompt has changed to indicate that we are currently stopped at a breakpoint and the location qsort hs 2 15 46 To further clarify the location we can use the list command qsort hs 2 15 46 Main gt list L epee M 2 aora lasas ceso lere lal
334. ode that your program is throwing something away Go lt mejatl SOI gt Suv LO y Of course in this particular situation you can do even better do mapM_ popInt xs return 10 fwarn wrong do bind Report expressions occuring in do and mdo blocks that appear to lack a binding For instance do return popInt 10 return 10 would report the first statement in the do block as suspicious as it has the type StackM StackM Int which consists of two nested applications of the same monad constructor but which is not then unpacked by binding the result The warning is suppressed by explicitly mentioning in the source code that your program is throwing something away alo lt recica aosime 110 8 eiccin 110 y For almost all sensible programs this will indicate a bug and you probably intended to write alo 9D LO premisa MO y If you re feeling really paranoid the dcore lint option is a good choice It turns on heavyweight intra pass sanity checking within GHC It checks GHC s sanity not yours 4 8 Packages A package is a library of Haskell modules known to the compiler GHC comes with several packages see the accompanying library documentation More packages to install can be obtained from HackageDB Using a package couldn t be simpler if you re using make or GHCi then most of the installed packages will be automatically available to your program without any further options The exceptions to
335. odule where the splice is to be run For example when compiling module A you can only run Template Haskell functions imported from B if B does not import A directly or indirectly The reason should be clear to run B we must compile and run A but we are currently type checking A The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 184 240 e The flag ddump splices shows the expansion of all top level splices as they happen e If you are building GHC from source you need at least a stage 2 bootstrap compiler to run Template Haskell A stage 1 compiler will reject the TH constructs Reason TH compiles and runs a program and then looks at the result So it s important that the program it compiles produces results whose representations are identical to those of the compiler itself Template Haskell works in any mode make interactive or file at a time There used to be a restriction to the former two but that restriction has been lifted 7 9 3 A Template Haskell Worked Example To help you get over the confidence barrier try out this skeletal worked example First cut and paste the two modules below into Main hs and Printf hs t Main ns module Main where Import our template pr import Printf pr The splice operator takes the Haskell source code generated at compile time by pr and splices it into gt the argument of VpubSt rin main putStrLn pr
336. oesn t exist here are problems in package process 1 0 1 1 dependency filepath 1 1 0 1 87511764eb0af2bce4db05e702750e63 doesn t exist here are problems in package directory 1 0 0 2 dependency filepath 1 1 0 1 87511764eb0af2bce4db05e702750e63 doesn t exist he following packages are broken either because they have a problem listed above or because they depend on a broken package The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 62 240 gine Ore Wager haskeline 0 6 2 Cabal 1 7 4 process 1 0 1 1 cure cto MORMOR bin package db 0 0 0 0 laysxe 0 5 S510 52 haskel1198 1 0 1 0 To fix the problem you need to recompile the broken packages against the new dependencies The easiest way to do this is to use cabal install or download the packages from HackageDB and build and install them as normal Be careful not to recompile any packages that GHC itself depends on as this may render the ghc package itself broken and ghc cannot be simply recompiled The only way to recover from this would be to re install GHC 4 8 6 Package management the ghc pkg command The ghc pkg tool is for querying and modifying package databases To see what package databases are in use use ghc p kg list The stack of databases that ghc pkg knows about can be modified using the GHC_PACKAGE_ PATH environment variable see Section 4 8 4 1 and usin
337. of stepping Use step to enable all the breakpoints in the program and execute until the next breakpoint is reached Use steplocal to limit the set of enabled breakpoints to those in the current top level function Similarly use stepmodule to single step only on breakpoints contained in the current module For example Main gt step main Stopped at gsort hs 5 7 47 REST sg iO The command step expr begins the evaluation of expr in single stepping mode If expr is omitted then it single steps from the current breakpoint st epover works similarly The list command is particularly useful when single stepping to see where you currently are qsort hs 5 7 47 Main gt list 4 MEAN OS O litt 4 OW Sr Lt 28 til Ta 6 asort hs 5 7 47 Main gt In fact GHCi provides a way to run a command when a breakpoint is hit so we can make it automatically do list The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 27 240 sort hias 53 72471 Meina sssr Strog list qsort hs 5 7 47 Main gt step Stopped at qgqsort hs 5 14 46 result Integer 4 S amp meia ANS O ith 0p Sr I 28 til Tal 6 asort hs 5 14 46 Main gt 2 5 3 Nested breakpoints When GHCi is stopped at a breakpoint and an expression entered at the prompt triggers a second breakpoint the new breakpoint becomes the current one and the old one is saved on a stack An arbitrary number of breakpo
338. ognised However invalid UTF 8 sequences will be ignored in comments so it is possible to use other encodings such as Latin 1 as long as the non comment source code is ASCII only 4 6 2 Output files When asked to compile a source file GHC normally generates two files an object file and an interface file The object file which normally ends in a o suffix contains the compiled code for the module The interface file which normally ends in a hi suffix contains the information that GHC needs in order to compile further modules that depend on this module It contains things like the types of exported functions definitions of data types and so on It is stored in a binary format so don t try to read one use the show iface option instead see Section 4 6 7 You should think of the object file and the interface file as a pair since the interface file is in a sense a compiler readable description of the contents of the object file If the interface file and object file get out of sync for any reason then the compiler may end up making assumptions about the object file that aren t true trouble will almost certainly follow For this reason we recommend keeping object files and interface files in the same place GHC does this by default but it is possible to override the defaults as we ll explain shortly Every module has a module name defined in its source code nodule A B C where The name of the object file generated by
339. oks ie The include flag and INCLUDE pragma are now deprecated and ignored Since version 6 10 1 GHC has generated its own C prototypes for foreign calls rather than relying on prototypes from C header files The threadsafe foreign import safety level is now deprecated use safe instead There is a new FFI calling convention called prim which allows calling C functions see Section 8 1 3 Most users are not expected to need this 6 3 Warnings A warning is now emitted if an unlifted type is bound in a lazy pattern in let or where clause or in an irrefutable pattern unless it is inside a bang pattern This warning is controlled by the fwarn lazy unlifted bindings flag In a future version of GHC this will be an error There are two new warnings if a monadic result of type other thanm is used in a do block but its result is not bound The flags Ewarn unused do bind and fwarn wrong do bind control these warnings see Section 4 7 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 8 240 The new flag fwarn dodgy exports controls whether an error is given for exporting a type synonym as T Name shadowing warnings are no longer given for variable names beginning with an underscore When Werror is given we now pass Werror to cpp 1 6 4 Runtime system The following options are all described in Section 4 15 3 The flag RTS N now automatically det
340. ompile any offending modules by hand before loading them into GHCi O doesn t work with GHCi For technical reasons the bytecode compiler doesn t interact well with one of the optimisation passes so we have disabled optimisation when using the interpreter This isn t a great loss you ll get a much bigger win by compiling the bits of your code that need to go fast rather than interpreting them with optimisation turned on Unboxed tuples don t work with GHCi That s right You can always compile a module that uses unboxed tuples and load it into GHCi however Incidentally the previous point namely that O is incompatible with GHCi is because the bytecode compiler can t deal with unboxed tuples Concurrent threads don t carry on running when GHCi is waiting for input This should work as long as your GHCi was built with the threaded switch which is the default Consult whoever supplied your GHCi installation The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 38 240 After using getContents I can t use stdin again until Ido load or reload This is the defined behaviour of ge tContents it puts the stdin Handle in a state known as semi closed wherein any further I O operations on it are forbidden Because I O state is retained between computations the semi closed state persists until the next load or reload command You can make stdin reset itself after every evaluation by gi
341. on e Building a static library is done by using the ar tool like so Bie cas luoiisStoo 1L 0 2 Ase BrO CaO cas where A o B o and so on are the compiled Haskell modules and 1ibHS foo a is the library you wish to create The syntax may differ slightly on your system so check the documentation if you run into difficulties Versions of the Haskell libraries for use with GHCi may also abe included GHCi cannot load a files directly instead it will look for an object file called HS foo o and load that On some systems the yhc pkg tool can automatically build the GHCi version of each library see Section 4 8 6 To build these libraries by hand from the a archive it is possible to use GNU Id as follows Iel z whole archiv ORNS roO Lino replace whole archive with all_load on MacOS X The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 65 240 e When building the package as shared library GHC can be used to perform the link step This hides some of the details out the underlying linker and provides a common interface to all shared object variants that are supported by GHC DLLs ELF DSOs and Mac OS dylibs The shared object must be named in specific way for two reasons 1 the name must contain the GHC compiler version so that two library variants don t collide that are compiled by different versions of GHC and that therefore are most likely incompatible with respect to calling conventio
342. on including data constructors can have an arbitrary rank type That is you can nest foralls arbitrarily deep in function arrows In particular a forall type also called a type scheme including an operational type class context is legal On the left or right see 4 for example of a function arrow As the argument of a constructor or type of a field in a data type declaration For example any of the 1 2 3 g1 g2 above would be valid field type signatures As the type of an implicit parameter In a pattern type signature see Section 7 8 7 7 8 5 1 Examples In a data or newt ype declaration one can quantify the types of the constructor arguments Here are several examples data t a Il forall o o gt b gt bj a data MonadT m MkMonad return forall a a gt ma bing Ss forall a b ma gt la mb gt m newtype Swizzle MkSwizzle Ord a gt a gt a The constructors have rank 2 types WL ss focald a forsi bos gt lg gt 15 gt a gt T a4 MOR S49 se neclil im Geenecilil As el im gt roca Jo w a gt la gt m l gt mo gt MonadT m Salar les 28 Oe e al gt ed gt Suite Notice that you don t need to use a foral1 if there s an explicit context For example in the first argument of the constructor kSwizzle an implicit forall a is prefixed to the argument type The implicit forall quantifies all type variables that are not already in
343. on 6 8 1 http www haskell org ghc for help Loading package base linking done Prelude gt There may be a short pause while GHCi loads the prelude and standard libraries after which the prompt is shown As the banner says you can type to see the list of commands available and a half line description of each of them We ll explain most of these commands as we go along For Hugs users many things work the same as in Hugs so you should be able to get going straight away Haskell expressions can be typed at the prompt Prelude gt 1 2 3 Prelude gt let x 42 in x 9 4 666666666666667 Prelude gt GHCi interprets the whole line as an expression to evaluate The expression may not span several lines as soon as you press enter GHCi will attempt to evaluate it 2 2 Loading source files Suppose we have the following Haskell source code which we place in a file Main hs main print fac 20 rae O Al fac n n fac n 1 The i stands for Interactive except foreign export at the moment The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 15 240 You can save Main hs anywhere you like but if you save it somewhere other than the current directory then we will need to change to the right directory in GHCi Prelude gt cd dir where dir is the directory or folder in which you saved Main hs To load a Haskell source file into GHCi use the Load
344. on System User s Guide Version 6 12 2 212 240 8 1 3 Primitive imports GHC extends the FFI with an additional calling convention prim e g foreign import prim foo foo ByteArray gt Int Int This is used to import functions written in Cmm code that follow an internal GHC calling convention This feature is not intended for use outside of the core libraries that come with GHC For more details see the GHC developer wiki 8 2 Using the FFI with GHC The following sections also give some hints and tips on the use of the foreign function interface in GHC 8 2 1 Using foreign export and foreign import ccall wrapper with GHC When GHC compiles a module say M hs which uses foreign export or foreign import wrapper it generates two additional files M_stub c and M_stub h GHC will automatically compile M_stub c to generate M_stub o at the same time For a plain foreign export the file M_stub h contains a C prototype for the foreign exported function and M_stub c contains its definition For example if we compile the following module module Foo where TOSCA Ero ecu LoS 28 Jime gt IO IMac oo 38 Mie gt 10 Tie foo n return length f n Int gt Int I n n n 1 Fh Fh Fh Then Foo_stub h will contain something like this include HsFFI h extern HsInt foo HsInt a0 and Foo_stub c contains the compiler generated definition of foo To invoke foo from C just include Foo_ s
345. on one processor if you want it to run in parallel you must link your program with the threaded and run it with the RTS N option see Section 4 13 The runtime will schedule the running Haskell threads among the available OS threads running as many in parallel as you specified with the N RTS option GHC only supports parallelism on a shared memory multiprocessor Glasgow Parallel Haskell GPH supports running Parallel Haskell programs on both clusters of machines and single multiprocessors GPH is developed and distributed separately from GHC see The GPH Page However the current version of GPH is based on a much older version of GHC 4 06 7 18 4 Annotating pure code for parallelism Ordinary single threaded Haskell programs will not benefit from enabling SMP parallelism alone you must expose parallelism to the compiler One way to do so is forking threads using Concurrent Haskell Section 7 18 1 but the simplest mechanism for extracting parallelism from pure code is to use the par combinator which is closely related to and often used with seq Both of these are available from the parallel library aanib O Spez aurie L Moses parie gt ly gt la peec ec O gt 9 The expression x par y sparks the evaluation of x to weak head normal form and returns y Sparks are queued for execution in FIFO order but are not executed immediately If the runtime detects that there is an idle CPU then it may convert a spark into a
346. on type and view patterns can be used wherever patterns are used The semantics of a pattern exp gt pat are as follows e Scoping The variables bound by the view pattern are the variables bound by pat Any variables in exp are bound occurrences but variables bound to the left in a pattern are in scope This feature permits for example one argument to a function to be used in the view of another argument For example the function clunky from Section 7 3 5 can be written using view patterns as follows clunky env lookup env gt Just vall lookup env gt Just val2 vall val2 cocote Sueltos Kor CU oas More precisely the scoping rules are Ina single pattern variables bound by patterns to the left of a view pattern expression are in scope For example example Maybe String gt Integer Integer String gt Bool example Just f _ f gt 4 True Additionally in function definitions variables bound by matching earlier curried arguments may be used in view pattern expressions in later arguments example String gt Integer gt String gt Bool xample f f gt 4 TEU That is the scoping is the same as it would be if the curried arguments were collected into a tuple In mutually recursive bindings such as let where or the top level view patterns in one declaration may not mention variables bound by other declarations That is each declaration must be self contained For ex
347. ons of class Storable for a given C struct see the Foreign Storable module in the library documentation poke struct_type field Similarly for poke It will have the type Storable b gt Ptr a gt b gt IO ptr struct_type field Makes a pointer to a field struct It will have the type Ptr a gt Ptr b offset struct_type field Computes the offset in bytes of field in struct_type It will have type Int size struct_type Computes the size in bytes of struct_type It will have type Int enum type constructor value value A shortcut for multiple definitions which use const Each value is a name of a C integer constant e g enumeration value The name will be translated to Haskell by making each letter following an underscore uppercase making all the rest lowercase and removing underscores You can supply a different translation by writing hs_name c_value instead of a value in which case c_value may be an arbitrary expression The hs_name will be defined as having the specified t ype Its definition is the specified constructor which in fact may be an expression or be empty applied to the appropriate integer value You can have multiple enum definitions with the same t ype this construct does not emit the type definition itself The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 222 240 10 3 3 Custom constructs const type peek poke and ptr are no
348. or 54 Wwarn 54 XForeignFunctionInterface 211 XIncoherentInstances 161 XMonoPatBinds 208 XNewQualifiedOperators 128 XNolImplicitPrelude option 135 217 XNoMonoPatBinds 208 XNoMonomorphismRestriction 208 XNoNPlusKPatterns 132 XOverlappingInstances 161 XTemplateHaskell 182 XUndecidablelnstances 161 XUnicodeS yntax 128 Z RTS option 84 auto 104 108 auto all 104 108 c 42 43 72 RTS option 80 caf all 108 cpp 43 70 cpp option 70 cpp vs string gaps 71 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 dcmm lint 88 dcore lint 57 88 dcore lint option 217 ddump options 86 ddump asm 87 ddump bcos 87 ddump cmm 87 ddump cpranal 87 ddump cse 87 ddump deriv 87 ddump ds 87 ddump flatC 87 ddump foreign 87 ddump hi 48 ddump hi diffs 48 ddump if trace 87 ddump inlinings 87 ddump minimal imports 48 ddump occur anal 87 ddump opt cmm 87 ddump parsed 86 ddump prep 87 ddump rn 86 ddump rn trace 87 ddump rules 87 ddump simpl 87 ddump simpl iterations 87 ddump simpl phases 87 ddump simpl stats option 87 ddump spec 87 ddump splices 87 ddump stg 87 ddump stranal 87 ddump tc 86 ddump tc trace 87 ddump types 87 ddump workwrap 87 debug 74 dfaststring stats 87 dno debug output 88 dppr debug 87 dppr user length 88 dshow passes 87 dshow rn stats 87 dstg lint 88 dsupp
349. or code to the invoker Depending on the invoker the result might be a dialog box asking the user for elevated permissions or it might simply be a permission denied error Installer detection can be also turned off globally for the system using the security control panel but GHC by default generates binaries that don t depend on the user having disabled installer detection The fno gen manifest disables generation of the manifest file One reason to do this would be if you had a manifest file of your own for example In the future GHC might use the manifest file for more things such as supplying the location of dependent DLLs fno gen manifest also implies Eno embed mani fest see below fno embed manifest The manifest file that GHC generates when linking a binary on Windows is also embedded in the executable itself by default This means that the binary can be distributed without having to supply the manifest file too The embedding is done by running windres to see exactly what GHC does to embed the manifest use the v flag A GHC installation comes with its own copy of windres for this reason See also pgmwindres Section 4 10 1 and optwindres Section 4 10 2 fno shared implib DLLs on Windows are typically linked to by linking to a corresponding 1ib or d1ll a the so called import library GHC will typically generate such a file for every DLL you create by compiling in shared mode However sometimes you
350. or example the Ar rowChoice class includes a combinator ArrowChoice a gt lt gt a Soa C o a G so we can use it to build commands The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 190 240 expr proc x gt do returnA lt x Sr elo Svoo ilie lt 6 VS anw lt XG Ke ae Ay OO symbol Minus lt y s cenn Oxo L x y The do on the first line is needed to prevent the first lt gt from being interpreted as part of the expression on the previous line This is equivalent to expr proc x gt returnA lt x lt r rO 3 gt Cle symbol Plus lt VES AE SA 6 EX A lt r gt ola x gt clo symbol Minus lt Y lt rann lt 11 expr lt x y It is essential that this operator be polymorphic in e representing the environment input to the command and thence to its subcommands and satisfy the corresponding naturality property gue Ie Ses Gr lt r Gi elise le Se ic lt p eee Kk E at least for strict k This should be automatic if you re not using seq This ensures that environments seen by the subcommands are environments of the whole command and also allows the translation to safely trim these environments The operator must also not use any variable defined within the current arrow abstraction We could define our own operator untilA ArrowChoice a gt a Za Bool gt 8 untilA body con
351. ormed types in Coar Miagi OK RLC e S 3 z Gaar ate Bool OKI Kime HET ORB oor WRONG kind mismatch in the first argument F Bool WRONG unsaturated application 7 7 2 1 1 Associated type family declarations When a type family is declared as part of a type class we drop the family special The Elem declaration takes the following form class Collects ce where type Elem ce x The argument names of the type family must be class parameters Each class parameter may only be used at most once per associated type but some may be omitted and they may be in an order other than in the class head Hence the following contrived example is admissible class C a b c where ES NO ieee ets ae These rules are exactly as for associated data families 7 7 2 2 Type instance declarations Instance declarations of type families are very similar to standard type synonym declarations The only two differences are that the keyword t ype is followed by instance and that some or all of the type arguments can be non variable types but may not contain forall types or type synonym families However data families are generally allowed and type synonyms are allowed as long as they are fully applied and expand to a type that is admissible these are the exact same requirements as for data instances For example the e instance for Elem is type instance Elem e The Glorious Glasgow Haskell Compilation System User
352. ort on Windows see Section 11 6 The crucial difference in support on Windows is that it is not currently possible to build each Haskell package as a separate DLL it is only possible to link an entire Haskell program as one massive DLL Building and using shared libraries is slightly more complicated than building and using static libraries When using Cabal much of the detail is hidden just use nable shared when configuring a package to build it into a shared library or to link it against other packages built as shared libraries The additional complexity when building code is to distinguish whether the code will be used in a shared library or will use shared library versions of other packages it depends on There is additional complexity when installing and distributing shared libraries or programs that use shared libraries to ensure that all shared libraries that are required at runtime are present in suitable locations 4 11 1 Building programs that use shared libraries To build a simple program and have it use shared libraries for the runtime system and the base libraries use the dynamic flag ghc make dynamic Main hs This has two effects The first is to compile the code in such a way that 1t can be linked against shared library versions of Haskell packages such as base The second is when linking to link against the shared versions of the packages libraries rather than the static versions Obviously this requires that the pack
353. ouble But this is not necessarily the case a primitive value might be represented by a pointer to a heap allocated object Examples include Array the type of primitive arrays A primitive array is heap allocated because it is too big a value to fit in a register and would be too expensive to copy around in a sense it is accidental that it is represented by a pointer If a pointer represents a primitive value then it really does point to that value no unevaluated thunks no indirections nothing can be at the other end of the pointer than the primitive value A numerically intensive program using unboxed types can go a lot faster than its standard counterpart we saw a threefold speedup on one example There are some restrictions on the use of primitive types e The main restriction is that you can t pass a primitive value to a polymorphic function or store one in a polymorphic data type This rules out things like Int i e lists of primitive integers The reason for this restriction is that polymorphic arguments and constructor fields are assumed to be pointers if an unboxed integer is stored in one of these the garbage collector would attempt to follow it leading to unpredictable space leaks Or a seq operation on the polymorphic component may attempt to dereference the pointer with disastrous results Even worse the unboxed value might be larger than a pointer Double for instance e You can
354. ove is relaxed thus All of the classes Ci are single parameter type classes e Rule 3 above is relaxed this At least one of the classes Ci is numeric or is Show Eq or Ord e The unit type is added to the start of the standard list of types which are tried when doing type defaulting The last point means that for example this program meli 2 8 IO 4 main print def instance Num def Num a Enum a gt a def toEnum 0 prints rather than 0 as the type is defaulted to rather than Integer The motivation for the change is that it means IO a actions default to IO which in turn means that ghci won t try to print a result when running them This is particularly important for printf which has an instance that returns IO a However it is only able to return undefined the reason for the instance having this type is so that printf doesn t require extensions to the class system so if the type defaults to Integer then ghci gives an error when running a printf The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 23 240 2 5 The GHCi Debugger GHCi contains a simple imperative style debugger in which you can stop a running computation in order to examine the values of variables The debugger is integrated into GHCi and is turned on by default no flags are required to enable the debugging facilities There is one major restriction breakpoints and single stepping are only availab
355. ow Haskell Compilation System User s Guide Version 6 12 2 220 240 10 3 Writing Haskell interfaces to C code hsc2hs The hsc2hs command can be used to automate some parts of the process of writing Haskell bindings to C code It reads an almost Haskell source with embedded special constructs and outputs a real Haskell file with these constructs processed based on information taken from some C headers The extra constructs deal with accessing C data from Haskell It may also output a C file which contains additional C functions to be linked into the program together with a C header that gets included into the C code to which the Haskell module will be compiled when compiled via C and into the C file These two files are created when the def construct is used see below Actually hsc2hs does not output the Haskell file directly It creates a C program that includes the headers gets automatically compiled and run That program outputs the Haskell code In the following Haskell file is the main output usually a hs file compiled Haskell file is the Haskell file after ghc has compiled it to C i e a hc file C program is the program that outputs the Haskell file C file is the optionally generated C file and C header is its header file 10 3 1 command line syntax hsc2hs takes input files as arguments and flags that modify its behavior o FILE or output FILE Name of the Haskell file t FILE or
356. ow M just in case they contain an instance declaration that matters to M This would be a disaster in practice so GHC tries to be clever In particular if an instance declaration is in the same module as the definition of any type or class mentioned in the head of the instance declaration the part after the gt see Section 7 6 3 2 then GHC has to visit that interface file anyway Example module A where instance C a gt D T a where data Ta The instance declaration is only relevant if the type T is in use and if so GHC will have visited A s interface file to find T s definition The only problem comes when a module contains an instance declaration and GHC has no other reason for visiting the module Example module Orphan where instance C a gt D T a where class C a where Here neither D nor T is declared in module Orphan We call such modules orphan modules GHC identifies orphan modules and visits the interface file of every orphan module below the module being compiled This is usually wasted work but there is no avoiding it You should therefore do your best to have as few orphan modules as possible Functional dependencies complicate matters Suppose we have module B where instance E T Int where data T Is this an orphan module Apparently not because T is declared in the same module But suppose class E had a functional dependency module Lib where class E x y y gt x where
357. owever f1 is a function binding and f2 binds a bare variable in both cases the type signature brings a into scope 7 8 7 3 Expression type signatures An expression type signature that has explicit quantification using forall brings into scope the explicitly quantified type variables in the annotated expression For example sabi eyo StS Vike oo SR CA S mme gt G x O ES PSN SE O OA Here the type signature forall a ST s Bool brings the type variable s into scope in the annotated expression op gt gt x STRef s Int gt g x 7 8 7 4 Pattern type signatures A type signature may occur in any pattern this is a pattern type signature For example f and g assume that a is already in scope E ES 3 Mate Wesel gt ox 28 sei x h x y 2 Ent Boo y x In the case where all the type variables in the pattern type signature are already in scope i e bound by the enclosing context matters are simple the signature simply constrains the type of the pattern in the obvious way Unlike expression and declaration type signatures pattern type signatures are not implicitly generalised The pattern in a pattern binding may only mention type variables that are already in scope For example The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 181 240 Ls forall a lal gt et el fxs di ZS where ys a n reverse xs length xs OK ASS SS OF
358. owing files in this order if they exist 1 ghci 2 appdata ghc ghci conf where appdata depends on your system but is usually something like C Document s and Settings user Application Data 3 On Unix SHOME ghc ghci conf 4 SHOME ghci The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 37 240 The ghci conf file is most useful for turning on favourite options eg set s and defining useful macros Placing a ghci file in a directory with a Haskell project is a useful way to set certain project wide options so you don t have to type them everytime you start GHCi eg if your project uses GHC extensions and CPP and has source files in three subdirectories A B and C you might put the following lines in ghci iset fglasgow exts cpp JSG AVAS IERIE Note that strictly speaking the i flag is a static one but in fact it works to set it using set like this The changes won t take effect until the next Load though Once you have a library of GHCi macros you may want to source them from separate files or you may want to source your ghci file into your running GHCi session while debugging it Jder Soules escu sie With this macro defined in your ghci file you can use source file to read GHCi commands from file You can find and contribute other suggestions for ghci files on this Haskell wiki page GHC GHCi Two command line options control whether the startup fi
359. p www haskell org pipermail glasgow haskell bugs evs ghe The hardcore GHC developers hang out here This list also gets commit message from the GHC darcs repository There are other lists for other darcs repositories most notably cvs libraries list email address cvs ghcOhaskell org subscribe at http www haskell org mailman listinfo cvs ghc admin email address cvs ghc admin haskell org list archives http www haskell org pipermail cvs ghc There are several other haskell and GHC related mailing lists served by www haskell org Go to http www haskell org mailman listinfo for the full list Some Haskell related discussion also takes place in the Usenet newsgroup comp lang functional 1 3 Reporting bugs in GHC Glasgow Haskell is a changing system so there are sure to be bugs in it If you find one please see this wiki page for information on how to report it 1 4 GHC version numbering policy As of GHC version 6 8 we have adopted the following policy for numbering GHC versions Stable Releases Stable branches are numbered x y where y is even Releases on the stable branch x y are numbered x y z where z gt 1 is the patchlevel number Patchlevels are bug fix releases only and never change the programmer interface to any system supplied code However if you install a new patchlevel over an old one you will need to recompile any code that was compiled against the old libraries The value of __GLASGOW_
360. packages that depend on it Recompiling dependencies is necessary because the newly compiled package may have a differnt ABI Application Binary Interface than the previous version even if both packages were built from the same source code using the same compiler With package IDs a recompiled package will have a different package ID from the previous version so packages that depended on the previous version are now orphaned one of their dependencies is not satisfied Packages that are broken in this way are shown in the ghc pkg list output either in red if possible or otherwise surrounded by braces In the following example we have recompiled and reinstalled the filepath package and this has caused various dependencies including Cabal to break ghc pkg list WARNING there are broken packages Run ghc pkg check for more details usr lib ghc 6 12 1 package conf d Cabal la V 0 exar 0 54 510 sib pase oronro STG Additionally ghc pkg list reminds you that there are broken packages and suggests ghc pkg check which displays more information about the nature of the failure ghc pkg check There are problems in package ghc 6 12 1 dependency filepath 1 1 0 1 87511764eb0af2bce4db05e702750e63 doesn t exist here are problems in package haskeline 0 6 2 dependency filepath 1 1 0 1 87511764eb0af2bce4db05e702750e63 doesn t exist here are problems in package Cabal 1 7 4 dependency filepath 1 1 0 1 87511764eb0af2bce4db05e702750e63 d
361. paths don t depend on where cygwin s root directory is located or on which partition or network drive your source tree happens to reside as long as you cd there first If you have to use absolute paths beware of the innocent looking ROOT pwd in makefile hierarchies or configure scripts cygwin provides a tool called cygpath that can convert cygwin s unix style paths to their actual windows style counterparts Many cygwin tools actually accept absolute windows style paths remember though that you either need to escape V or convert to so you should be fine just using those everywhere If you need to use tools that do some kind of path mangling that depends on unix style paths one fun example is trying to interpret as a separator in path lists you can still try to convert paths using cygpath just before they are passed to GHC and friends If you don t have cygpath you probably don t have cygwin and hence no problems with it unless you want to write one build process for several platforms Again relative paths are your friend but if you have to use absolute paths and don t want to use different tools on different platforms you can simply write a short Haskell program to print the current directory thanks to George Russell for this idea compiled with GHC this will give you the view of the file system that GHC depends on which will differ depending on whether GHC is compiled with cygwin
362. pe patterns for a single type constructor say must be identical they must use the same type variables So this is illegal The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 207 240 class Foo a where dj 28 a gt BOOL op a srs b inl x True as fi jes Sars oy 1 ams YA Talse The type patterns must be identical even in equations for different methods of the class So this too is illegal class Foo a where gak 23 BO OIL as a Bes Id e Bee Y Meus QA 88 vel gt BOO az ies Bees Ci jp ee 8x8 y False The reason for this restriction is that we gather all the equations for a particular type constructor into a single generic instance declaration e A generic method declaration must give a case for each of the three type constructors e The type for a generic method can be built only from Function arrows Type variables Tuples Arbitrary types not involving type variables Here are some example type signatures for generic methods GDL 23 ao gt JO GDA BR BOOL gt lka BOO QoS 3 Pinel gt 2 gt a opa e gt Bool Here op1 op2 op3 are OK but op4 is rejected because it has a type variable inside a list This restriction is an implementation restriction we just haven t got around to implementing the necessary bidirectional maps over arbitrary type constructors It would be relatively easy to add specific type constructors such as May
363. pe variable any more 7 8 2 The context of a type signature The XFlexibleContexts flag lifts the Haskell 98 restriction that the type class constraints in a type signature must have the form class type variable or class type variable type variable With XFlexibleContexts these type signatures are perfectly OK G es ime el gt soc a 88 Ormel a gt us The flag XFlexibleContexts also lifts the corresponding restriction on class declarations Section 7 6 1 2 and instance declarations Section 7 6 3 2 GHC imposes the following restrictions on the constraints in a type signature Consider the type corall elo cua Cil csore gt mye Here we write the foralls explicitly although the Haskell source language omits them in Haskell 98 all the free type variables of an explicit source language type signature are universally quantified except for the class type variables in a class declaration However in GHC you can give the foralls if you want See Section 7 8 1 1 Each universally quantified type variable t vi must be reachable from t ype A type variable a is reachable if it appears in the same constraint as either a type variable free in t ype or another reachable type variable A value with a type that does not obey this reachability restriction cannot be used without introducing ambiguity that is why the type is rejected Here for example is an illegal type toallas ma gt ine
364. pecConstr fspec constr transformation Implied by dynamic fno spec constr 02 Set the size threshold for fspec constr thr the SpecConstr fno spec constr eshold n transformation to n default ane threshold 200 Set to n default 3 the maximum number of fspec constr cou specialisations that will be sali fno spec constr nt n created for any one function count by the SpecConstr transformation Turn on the liberate case fliberate cas transformation Implied by dynamic fno liberate case 02 Turn on the static argument fstatic argument f F fno static argument transformation Implied by dynamic transformation 02 transformation Set the size threshold for fliberate case t the liberate case fno liberate cas hreshold n transformation to n default siau e threshold 200 funbox strict fi Flatten strict constructor d fno unbox strict elds fields er fields funfolding creat fno unfolding cr ion threshold IN Rap Saue eation threshold Fi ee Tweak unfolding settings static z o ee iscount n discount eee Tweak unfolding settings static ee AA ss factor eness factor funtolding use t Tweak unfolding settings static fnp untording us hreshold e threshold fno pre inlining Turn off pre inlining static A FORNELLI Turn on eager blackholing dynamic 4 18 16 Profiling options Chapter 5 Flag Description Static Dynamic Reverse Auto add _scc_s to all auto gt dynamic no auto exported funct
365. pend on other compiled modules and in this case C depends on D which doesn t have an object file so GHCi also rejected C s object file Ok so let s also compile D M Estia gt 31 Clas e olas Main gt reload Ok modules loaded A B C D Nothing happened Here s another lesson newly compiled modules aren t picked up by reload only load Main gt load A Compiling B B hs interpreted Compiling A A hs interpreted Ok modules loaded A B D The automatic loading of object files can sometimes lead to confusion because non exported top level definitions of a module are only available for use in expressions at the prompt when the module is interpreted see Section 2 4 3 For this reason you might sometimes want to force GHCi to load a module using the interpreter This can be done by prefixing a to the module name or filename when using load for example Prelude gt load A Compiling A A hs interpreted A gt When the is used GHCi ignores any pre compiled object code and interprets the module If you have already loaded a number of modules as object code and decide that you wanted to interpret one of them instead of re loading the whole set you can use add M to specify that you want M to be interpreted note that this might cause other modules to be interpreted too because compiled modules cannot depend on interpreted ones To always compile everything to object code and never use
366. pends on a couple of the DLLs that come with GHC make sure that they are in scope visible Building statically linked DLLs is the same as in the previous section it suffices to add static to the commands used to compile up the Haskell source and build the DLL The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 227 240 11 6 3 Beware of DlIMain The body of a D11Main function is an extremely dangerous place This is because the order in which DLLs are unloaded when a process is terminating is unspecified This means that the D11Main for your DLL may be called when other DLLs containing functions that you call when de initializing your DLL have already been unloaded In other words you can t put shutdown code inside D11Main unless your shutdown code only requires use of certain functions which are guaranteed to be available see the Platform SDK docs for more info In particular if you are writing a DLL that s statically linked with Haskell it is not safe to call hs_exit from D11Ma in since hs_exit may make use of other DLLs see also Section 8 2 4 4 What s more if you wait until program shutdown to execute your deinitialisation code Windows will have terminated all the threads in your program except the one calling D11Main which can cause even more problems A solution is to always export Begin and End functions from your DLL and call these from the application that use
367. pkg to make it clearer that multiple packages are being matched ghc pkg init path Creates a new empty package database at path which must not already exist ghc pkg register file Reads a package specification from file which may be to indicate standard input and adds it to the database of installed packages The syntax of file is given in Section 4 8 8 The package specification must be a package that isn t already installed ghc pkg update file Thesame as register except that if a package of the same name is already installed it is replaced by the new one ghc pkg unregister P Remove the specified package from the database ghc pkg expose P Sets the exposed flag for package P to True ghc pkg check Check consistency of dependencies in the package database and report packages that have missing depen dencies ghc pkg hide P Sets the exposed flag for package P to False ghc pkg list P simple output This option displays the currently installed packages for each of the databases known to ghc pkg That includes the global database the user s local database and any further files specified using the f option on the command line Hidden packages those for which the exposed flag is False are shown in parentheses in the list of packages The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 63 240 If an optional package identifier P is given then only packages matching that ide
368. please see Chapter 6 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 218 240 Help My program crashed e g a segmentation fault or core dumped If your program has no foreign calls in it and no calls to known unsafe functions such as unsafePerforml0 then a crash is always a BUG in the GHC system except in one case If your program is made of several modules each module must have been compiled after any modules on which it depends unless you use hi boot files in which case these must be correct with respect to the module source For example if an interface is lying about the type of an imported value then GHC may well generate duff code for the importing module This applies to pragmas inside interfaces too If the pragma is lying e g about the arity of a value then duff code may result Furthermore arities may change even if types do not In short if you compile a module and its interface changes then all the modules that import that interface must be re compiled A useful option to alert you when interfaces change is hi diffs It will run diff on the changed interface file before and after when applicable If you are using make GHC can automatically generate the dependencies required in order to make sure that every module is up to date with respect to its imported interfaces Please see Section 4 6 11 If you are down to your last compile before a b
369. profile of a running program The hp file is generated incrementally as your program runs In principle running hp2ps on the incomplete file should produce a snapshot of your program s heap usage However the last sample in the file may be incomplete causing hp2ps to fail If you are using a machine with UNIX utilities installed it s not too hard to work around this problem though the resulting command line looks rather Byzantine Head SNE due pi SE NDS AMENER O OA weer il ise el 9 ae IY O OLLAS hp2ps gt FOO ps The command fgrep n END_SAMPLE FOO hp finds the end of every complete sample in FOO hp and labels each sample with its ending line number We then select the line number of the last complete sample using tail and cut This is used as a parameter to head the result is as if we deleted the final incomplete sample from FOO hp This results in a properly formatted hp file which we feed directly to hp2ps 5 5 4 Viewing a heap profile in real time The gv and ghostview programs have a watch file option can be used to view an up to date heap profile of your program as it runs Simply generate an incremental heap profile as described in the previous section Run gv on your profile gv watch seascape FOO ps If you forget the wat ch flag you can still select Watch file from the State menu Now each time you generate a new profile FOO ps the view will update automatically This can all be encapsulated
370. profiling saoo 0 000 000 0022 ee 108 5 3 Time and allocation profiling osaa 000000022 2 ee ee 108 5 4 Profiling memory Us ge s soos seci o OE eS ae ae AA AR Se A we a 108 5 4 1 RTS options for heap profiling 0 0 0 0000000000000 000 109 5 4 2 RetamerPromling s mese pe a be ee ee ES are eH oe eR od Yee eee oS 110 5 4 2 1 Hints for using retainer profiling e 110 24 3 Biographical Profiling ces esegesi OR eR ORR ES eS Paw Se wR ER e 110 5 4 4 Actual memory residency oaoa ee 111 5 5 hp2ps heap profile to PostScript a 111 6 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 23 1 Mampulating the bp file i 46 bee ee Rd eee Ss od 5 5 2 Zooming in on regions of your profile e 5 5 3 Viewing the heap profile of a running program 1 2 2 2 2 00000 00 eee eee 5 5 4 Viewing a heap profile in real time 000 000 0002 eee ee 3 6 Observing Code Coverage s soso se sn a A A e 5 6 1 A small example Reciprocation 0 000 2p ee 5 6 2 Options for instrumenting code for coverage e 3 6 3 The hpetoolkit ic tek a a a ROR a A a be A ew ee 63 0 hperepot i 246 54 24 bow ethe edb Sb25 4640 bbe OR 2 ot bb SASS SH 5 6 3 2 hpemarkup lt se ss pact bee ee ee a eee EE A Oa E 56 33 PESIMA AOR ER EEG AR Sa ee RA Boece Ge a 5 634 hpecombiie 22654 2 45 e8e00b e254 26555 600h5 8 HSS beehive ds 5 6033 hp M
371. ption Static Dynamic Reverse licited dno debug output suppres PPSS static 7 debugging output Turn on debug printing tat appr debug more verbose ad Suppress the printing of dsuppress uniques uniques in debug output static easier to use diff Don t output pragma info in dppr noprags dumps static t the depth f inti dppr user length SELIP eP Dec ae static z expressions in error Msgs dsource stats Dump haskell source stats dynamic dcmm lint C pass sanity checking dynamic dstg lint STG pass sanity checking dynamic dstg stats Dump STG stats dynamic dverbose core2co Show output from each dynamic re core to core pass Show output from each e 2 d 3 dverbose stg2stg STG to STG pass ynamic Print out each EE EER Print out each pass name as dama 1t happens Show statistics for fast dfaststring stats 3 dynamic string usage when finished 4 18 27 Misc compiler options Flag Description Static Dynamic Reverse fno hi version c Don t complain about hi static heck file mismatches dno black holing Torn oi Black holing static probably doesn t work t simplification hist fhistory size gt S static size isterised ilati y funregisterised Diep stene compi anon static use unreg instead T ff bl li fno asm mangling EIN AE dynamic E use unreg instead The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 104 240
372. ption of every package in the form of an InstalledPackagelInfo Multiple package descriptions are separated by the string on a line by itself This is almost the same as ghc pkg describe x except that ghc pkg dump is intended for use by tools that parse the results so for example where ghc pkg describe x will emit an error if it can t find any packages that match the pattern ghc pkg dump will simply emit nothing ghc pkg recache Re creates the binary cache file package cache for the selected database This may be necessary if the cache has somehow become out of sync with the contents of the database ghc pkg will warn you if this might be the case The other time when ghc pkg recache is useful is for registering packages manually it is possible to register a package by simply putting the appropriate file in the package database directory and invoking ghc pkg recache to update the cache This method of registering packages may be more convenient for automated packaging systems Substring matching is supported for M in find module and for P in list describe and field where a x indicates open substring ends prefixx suffix infixx Examples output omitted list all regex related packages ghc pkg list x regexx ignore case list all string related packages ghc pkg list string ignore case list OpenGL related packages ghc pkg list x gl ignore case list packages e
373. r machine Be careful when using all the processors in your machine if some of your processors are in use by other programs this can actually harm performance rather than improve it Setting N also has the effect of enabling the parallel garbage collector see Section 4 15 3 There is no means currently by which this value may vary after the program has started The current value of the N option is available to the Haskell program via GHC Conc numCapabilities The following options affect the way the runtime schedules threads on CPUs qa Use the OS s affinity facilities to try to pin OS threads to CPU cores This is an experimental feature and may or may not be useful Please let us know whether it helps for you qm Disable automatic migration for load balancing Normally the runtime will automatically try to schedule threads across the available CPUs to make use of idle CPUs this option disables that behaviour Note that migration only applies to threads sparks created by par are load balanced separately by work stealing This option is probably only of use for concurrent programs that explicitly schedule threads onto CPUs with GHC Con c forkOnIo qw Migrate a thread to the current CPU when it is woken up Normally when a thread is woken up after being blocked it will be scheduled on the CPU it was running on last this option allows the thread to immediately migrate to the CPU that unblocked it The rationale for allowi
374. r and Blo ckedIndefinitely has been renamed to BlockedIndefinitelyOnSTM The Control O1dExcept ion module has been deprecated System Posix Internals setNonBlockingFD now takes an additional Bool argument so you can turn blocking back on again A new function eof has been added to Text ParserCombinators ReadP The Foreign C Types CLDouble type has been removed It was never correct but just a duplicate of Foreign C Types CDouble The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 11 240 In Data Data the StringRep and StringConstr constructors have been removed The CharRep and CharConstr constructors should be used instead In Data Data mkIntConstr has been deprecated in favour of the new mk IntegralConstr e InData Data mkFloatConstr has been deprecated in favour of the new mkRealConstr e InData Data mkNorepType has been deprecated in favour of the new mkNoRepType l 6 10 3 bytestring Version number 0 9 1 5 was 0 9 1 4 l 6 10 4 Cabal Version number 1 8 0 2 was 1 6 0 3 Many API changes See the Cabal docs for more information mba 6 10 5 containers e Version number 0 3 0 0 was 0 2 0 1 mapAccumRWithKey has been added to Data IntMap e A Traversable instance has been added to Data IntMap IntMap The types of Data IntMap intersectionWith and Data IntMap intersect ionWithKey have been changed from intersectionWith a gt b
375. r message contains some clues as to the transformation happening internally If the expression was instead of type IO a for some a then it will be bound to the result of the IO computation which is of type a eg Prelude gt Time getClockTime Wed Mar 14 12 23 13 GMT 2001 Prelude gt print it Wed Mar 14 12 23 13 GMT 2001 The corresponding translation for an IO typed e is it lt e Note that it is shadowed by the new value each time you evaluate a new expression and the old value of it is lost 2 4 5 Type defaulting in GHCi Consider this GHCi session ghci gt reverse What should GHCi do Strictly speaking the program is ambiguous show reverse which is what GHCi computes here has type Show a gt a and how that displays depends on the type a For example ghci gt reverse String we ghci gt reverse Int 1 However it is tiresome for the user to have to specify the type so GHCi extends Haskell s type defaulting rules Section 4 3 4 of the Haskell 98 Report Revised as follows The standard rules take each group of constraints Cl a C2 a Cn a for each type variable a and defaults the type variable if 1 The type variable a appears in no other constraints 2 All the classes Ci are standard 3 At least one of the classes Ci is numeric At the GHCi prompt or with GHC if the XExtendedDefaultRules flag is given the following additional differences apply e Rule 2 ab
376. re is an explicit type signature 2 6 Invoking GHCi GHCi is invoked with the command ghci or ghc interactive One or more modules or filenames can also be specified on the command line this instructs GHCi to load the specified modules or filenames and all the modules they depend on just as if you had said load modules at the GHCi prompt see Section 2 7 For example to start GHCi and load the program whose topmost module is in the file Main hs we could say ghci Main hs Most of the command line options accepted by GHC see Chapter 4 also make sense in interactive mode The ones that don t make sense are mostly obvious 2 6 1 Packages Most packages see Section 4 8 1 are available without needing to specify any extra flags at all they will be automatically loaded the first time they are needed For hidden packages however you need to request the package be loaded by using the package flag ghci package readline GHCi version 6 8 1 http www haskell org ghc for help Loading package base linking done Loading package readline 1 0 linking done Prelude gt The following command works to load new packages into a running GHCi Prelude gt set package nam But note that doing this will cause all currently loaded modules to be unloaded and you ll be dumped back into the Prelude 2 6 2 Extra libraries Extra libraries may be specified on the command line using the normal 11ib op
377. re treated only as warnings not as errors This is the default but can be useful to negate a Werror flag The full set of warning options is described below To turn off any warning simply give the corresponding fno warn option on the command line fwarn unrecognised pragmas Causes a warning to be emitted when a pragma that GHC doesn t recognise is used As well as pragmas that GHC itself uses GHC also recognises pragmas known to be used by other tools e g OPTIONS _ HUGS and DERIVE This option is on by default fwarn warnings deprecations Causes a warning to be emitted when a module function or type with a WARNING or DEPRECATED pragma is used See Section 7 13 4 for more details on the pragmas This option is on by default fwarn deprecated flags Causes a warning to be emitted when a deprecated commandline flag is used This option is on by default fwarn dodgy foreign imports Causes a warning to be emitted for foreign imports of the following form tor Sion importe Yew dE 8 IP IMIPICe Te on the grounds that it probably should be cereale moore ELY a 38 KUNCE i The first form declares that f is a pure C function that takes no arguments and returns a pointer to a C function with type t whereas the second form declares that f itself is a C function with type t The first declaration is usually a mistake and one that is hard to debug because it results in a crash hence thi
378. real thread and run the new thread on the idle CPU In this way the available parallelism is spread amongst the real CPUs For example consider the following parallel version of our old nemesis nfib The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 210 240 import Control Parallel miog SR ae gt Dmg n io a mn lt 1 1 otherwise par nl pseg n2 nl n2 1 where nl nfib n 1 m iaaralloy Gol For values of n greater than 1 we use par to spark a thread to evaluate nfib n 1 and then we use pseq to force the parent thread to evaluate nfib n 2 before going on to add together these two subexpressions In this divide and conquer approach we only spark a new thread for one branch of the computation leaving the parent to evaluate the other branch Also we must use pseq to ensure that the parent will evaluate n2 before n1 in the expression n1 n2 1 Itis not sufficient to reorder the expression as n2 n1 1 because the compiler may not generate code to evaluate the addends from left to right Note that we use pseq rather than seq The two are almost equivalent but differ in their runtime behaviour in a subtle way seq can evaluate its arguments in either order but pseq is required to evaluate its first argument before its second which makes it more suitable for controlling the evaluation order in conjunction with par When using par the general rule of thumb is that the
379. related to interface files ddump hi Dumps the new interface to standard output ddump hi diffs The compiler does not overwrite an existing hi interface file if the new one is the same as the old one this is friendly to make When an interface does change it is often enlightening to be informed The ddump hi diffs option will make GHC report the differences between the old and new hi files ddump minimal imports Dump to the file M imports where M is the module being compiled a minimal set of import declarations You can safely replace all the import declarations in M hs with those found in M imports Why would you want to do that Because the minimal imports a import everything explicitly by name and b import nothing that is not required It can be quite painful to maintain this property by hand so this flag is intended to reduce the labour show iface file where file is the name of an interface file dumps the contents of that interface in a human readable ish format See Section 4 4 4 6 8 The recompilation checker fforce recomp Turn off recompilation checking which is on by default Recompilation checking normally stops com pilation early leaving an existing o file in place if it can be determined that the module does not need to be recompiled In the olden days GHC compared the newly generated hi file with the previous version if they were identical it left the old one alone and didn t change it
380. rence when it precedes a variable or wild card a bang at the top level of a let or where binding makes the binding strict regardless of the pattern For example Las Uli e a lo is a strict binding operationally it evaluates e matches it against the pattern x y and then evaluates b We say apparent exception because the Right Way to think of it is that the bang at the top of a binding is not part of the pattern rather it is part of the syntax of the binding Nested bangs in a pattern binding behave uniformly with all other forms of pattern matching For example The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 193 240 Las ola e da Io is equivalent to this let t cas ue aly gt amp sea vw x fot t y ewel al a Jo The binding is lazy but when either x or y is evaluated by b the entire pattern is matched including forcing the evaluation of x Bang patterns work in case expressions too of course g5 x let y x in body g6 x cage i Oi y gt boch Gi x case E x ar y gt loochy The functions g5 and g6 mean exactly the same thing But g7 evaluates f x binds y to the result and then evaluates body 7 11 2 Syntax and semantics We add a single new production to the syntax of patterns pat pat There is one problem with syntactic ambiguity Consider i Use 3 Is this a definition of the infix function or of the
381. ress uniques 88 dverbose core2core 87 dverbose stg2stg 87 dynamic 73 dynload 73 eventlog 74 f 64 RTS option 79 f options GHC 68 fPIC 72 fasm 72 fbyte code 72 234 240 ferror spans 44 fexcess precision 68 fext core 86 fforce recomp 48 fglasgow exts 125 fignore asserts 68 194 fignore interface pragmas 69 fliberate case 69 fno options GHC 68 fno code 72 fno cse 68 fno embed manifest 74 fno force recomp 48 fno full laziness 69 fno gen manifest 74 fno implicit import qualified 20 fno print bind result 18 fno shared implib 74 fno state hack 69 fno strictness 68 fobject code 72 fomit interface pragmas 69 fprint bind result 18 framework 73 framework path 73 fspec constr 69 fstatic argument transformation 69 funbox strict fields 69 funfolding creation threshold 69 funfolding use threshold 69 funfolding use thresholdO option 124 fvia C 72 fwarn deprecated flags 54 fwarn dodgy exports 54 fwarn dodgy foreign imports 54 fwarn dodgy imports 54 fwarn duplicate exports 55 fwarn hi shadowing 55 fwarn implicit prelude 55 fwarn incomplete patterns 55 fwarn incomplete record updates 55 fwarn lazy unlifted bindings 54 fwarn missing fields 55 fwarn missing methods 55 fwarn missing signatures 55 fwarn missing signatures option 122 fwarn monomorphism restriction 56 fwarn name shadowing 55 fwarn orphans
382. ring literals concatenate Or use print s format directives Values of arguments must be given as strings unless the macro stringifies them itself using the C preprocessor s parameter syntax def C_definition The definition of a function variable struct or typedef is written to the C file and its prototype or extern declaration to the C header Inline functions are handled correctly struct definitions and typedefs are written to the C program too The inline struct or typedef keyword must come just after def if condition ifdef name ifndef name elif condition else endif terror message warning Conditional compilation directives are passed unmodified to the C program C file and C header Putting them in the C program means that appropriate parts of the Haskell file will be skipped const C_expression The expression must be convertible to Long or unsigned long Its value literal or negated literal will be output const_str C_expression The expression must be convertible to const char pointer Its value string literal will be output type C_type A Haskell equivalent of the C numeric type will be output It will be one of Int Word 8 16 32 64 Float Double LDouble peek struct_type field A function that peeks a field of a C struct will be output It will have the type Storable b gt Ptr a gt IO b The intention is that peek and poke can be used for implementing the operati
383. rmediate files saving 47 intermediate passes output 86 interpreter see GHCi invoking GHCi 31 it 21 238 240 L LANGUAGE pragma 194 language option 125 language GHC 125 Latin 1 45 ld options 72 1d options package specification 67 lhs suffix 41 libdir 42 libraries with GHCi 31 library dirs package specification 67 license file package specification 66 LINE pragma 198 linker options 72 linking Haskell libraries with foreign code 73 lint 88 list comprehensions generalised 134 parallel 133 M machine specific options 78 mailing lists Glasgow Haskell 1 maintainer package specification 66 make 50 make and recompilation 44 make mode 41 Makefile dependencies 51 Makefiles avoiding 42 MallocFailHook 85 manifest 74 matches unused 57 mdo 140 memory using less heap 124 methods missing 55 missing fields warning 55 missing methods warning 55 mode options 41 module system recursion 49 modules and filenames 15 monomorphism restriction warning 56 multicore 74 multiprocessor 74 N name The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 package specification 66 native code generator 43 NOINLINE 196 NOTINLINE 196 O object files 45 optimisation 68 optimise aggressively 68 normally 68 optimising customised 68 options for profiling 108 GHCi 36 language 125 OPTIONS_GHC 195 OPTIONS_GHC pragma 40 orpha
384. rocess is slightly complicated when the binding is polymorphic We show the process by means of an example To keep things simple we will use the well known map function import Prelude hiding map map a gt b gt a gt b MAA A 1 mag E 782S A SS We set a breakpoint on map and call it The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 Main gt break 5 Breakpoint 0 activated at map hs 5 15 28 Maim nap JuSt Si Stopped at map hs 4 0 5 12 result lt bj Sey Rete i 2S E gt Ip xs ge lal 30 240 GHCi tells us that among other bindings f is in scope However its type is not fully known yet and thus it is not possible to apply it to any arguments Nevertheless observe that the type of its first argument is the same as the type of x and its result type is shared with _result As we demonstrated earlier Section 2 5 1 the debugger has some intelligence built in to update the type of f whenever the types of x or __result are discovered So what we do in this scenario is force x a bit in order to recover both its type and the argument part of f Main gt seq x Main gt print x x l We can check now that as expected the type of x has been reconstructed and with it the type of f has been too calas Bie x i Integer Main gt t E 383 Integer gt lo From here we can apply f to any argument of type Integer and observe the results Ma
385. rsive do notation ee 7 3 8 2 Mdo notation deprecated ee 112 113 113 113 114 114 115 115 116 116 117 117 117 117 118 118 121 121 122 124 124 125 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 Xx 7 3 9 Parallel List Comprehensions 2 20 0 00 0 pe ee 133 7 3 10 Generalised SQL Like List Comprehensions 0 00 eee eee ee ee 134 7 3 11 Rebindable syntax and the implicit Prelude import e 135 13 12 POST Operators coca o a e ea Aa ee A ee 136 7313 Tuple sections si a egra i e a A A de a 136 7 3 14 Record field disambiguation aoaaa ee 137 143 15 Record puns sda ie wa a hee e E Ae al ba e el he ee a a 138 7 39 36 Record wildcards 242 3 sg8 Sek gaa ee a GER MEM ORGS aaa owe 139 7 3 17 Local Fixity Declarations ee 139 7 3 18 Package qualified Imports 140 7 3 19 Summary of stolen syntax 2 2 ee 140 7 4 Extensions to data types and type synonyms 2 0 00 ee ee ee 141 7 4 1 Datatypes with no constructors ee 141 7 4 2 Infix type constructors classes and type variables 2 2 2 0 eee eee eee ee eee 141 7 4 3 Liberalised type synonyms 2 2 ee 142 7 4 4 Existentially quantified data constructors 2 2 ee 143 TAAL Why existential seis hae Ree ee ee Rw EG Oe Se ee eS 143 74 4 2 Existentials and type classes 2 2 ee 143 74 4 3 Record Constructors g
386. rticular the 1O and ST monads use unboxed tuples to avoid unnecessary allocation during sequences of operations There are some pretty stringent restrictions on the use of unboxed tuples e Values of unboxed tuple types are subject to the same restrictions as other unboxed types i e they may not be stored in polymorphic data structures or passed to polymorphic functions e No variable can have an unboxed tuple type nor may a constructor or function argument have an unboxed tuple type The following are all illegal data oo ROO AE e i 3938 5 lote alo ai gt Gir lame Jae 47 fx x G 828 Gp Wore Wine 37 gt lone g a b a hy xe let yo RA ON ee The typical use of unboxed tuples is simply to return multiple values binding those multiple results with a case expression thus y x 1 y 1 x x Case i ox oie UG ap lo Gy gt gt a lo B g You can have an unboxed tuple in a pattern binding thus oe lee Gi ye a da ox aa less If the types of p and q are not unboxed the resulting binding is lazy like any other Haskell pattern binding The above example desugars like this f x let t case h xo fl p q gt p q i TSC ic G simo Te DADOA V Indeed the bindings can even be recursive The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 128 240 7 3 Syntactic extensions 7 3 1 Unicode syntax The language extension XUnicodeSyntax e
387. rts i dynamic XNoPackagelmports imports 4 18 13 Warnings Section 4 7 Flag Description Static Dynamic Reverse W enable normal warnings dynamic w Ww disable all warnings dynamic Wall enable almost all warnings ais x details in Section 4 7 y Werror make warnings fatal dynamic Wwarn Wwarn make warnings non fatal dynamic Werror The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 96 240 Flag Description Static Dynamic Reverse fwarn unrecognis warn about uses of pragmas ala fno warn unrecog ed pragmas that GHC doesn t recognise y nised pragmas warn about uses of fwarn warnings d functions amp types that have dynamie fno warn warning eprecations warnings or deprecated y s deprecations pragmas warn about uses of fwarn deprecated fno warn depreca commandline flags that are dynamic flags ted flags deprecated fwarn duplicate warn when an entity is dinamic fno warn duplica exports exported multiple times y te exports i warn when a hi file in the fwarn hi shadowi E fno warn hi shad current directory shadows a dynamic ng i owing library fwarn implicit p warn when the Prelude is Aviami fno warn implici relude implicitly imported y t prelude fwarn incomplete warn when a pattern match
388. rule is applied regardless of flags If you want a more exotic context you can write it yourself using the standalone deriving mechanism 7 5 2 Stand alone deriving declarations GHC now allows stand alone deriving declarations enabled by XStandaloneDeriving data Foo a Bar a Baz String deriving instance Eq a gt Eq Foo a The syntax is identical to that of an ordinary instance declaration apart from a the keyword deriving and b the absence of the where part Note the following points e You must supply an explicit context in the example the context is Eq a exactly as you would in an ordinary instance declaration In contrast ina deriving clause attached to a data type declaration the context is inferred e Aderiving instance declaration must obey the same rules concerning form and termination as ordinary instance dec larations controlled by the same flags see Section 7 6 3 e Unlike a deriving declaration attached to a dat a declaration the instance can be more specific than the data type assuming you also use XFlexiblelnstances Section 7 6 3 2 Consider for example data Foo a Bar a Baz String deriving instance Eq a gt Eq Foo a deriving instance Eq a gt Eq Foo Maybe a This will generate a derived instance for Foo a and Foo Maybe a but other types such as Foo Int Bo o1 will not be an instance of Eq e Unlike a deriving declaration attached to a data dec
389. ry code is a useful performance optimisation that is not available on all platforms This field tells you whether the program has been compiled with this optimisation Usually yes except on unusual platforms 4 16 Generating and compiling External Core Files GHC can dump its optimized intermediate code said to be in Core format to a file as a side effect of compilation Non GHC back end tools can read and process Core files these files have the suffix hcr The Core format is described in An External Representation for the GHC Core Language and sample tools for manipulating Core files in Haskell are in the GHC source distribution directory under utils ext core Note that the format of hcr files is different from the Core output format that GHC generates for debugging purposes Section 4 17 though the two formats appear somewhat similar The Core format natively supports notes which you can add to your source code using the CORE pragma see Section 7 13 fext core Generate hcr files Currently as of version 6 8 2 GHC does not have the ability to read in External Core files as source If you would like GHC to have this ability please make your wishes known to the GHC Team 4 17 Debugging the compiler HACKER TERRITORY HACKER TERRITORY You were warned 4 17 1 Dumping out compiler intermediate structures ddump pass Make a debugging dump after pass lt pass gt may be common enough to need a short form You can
390. s XFunctionalDependencies XMagicHash XPolymorphicComponents XExistentialQuantificat ion XUnicodeSyntax XPostfixOperators XPatternGuards XLiberalTypeSynonyms XExplic itForAll XRankNTypes XImpredicativeTypes XTypeOperators XDoRec XParallelListCom p XEmpt yDataDecls XKindSignatures XGeneralizedNewtypeDeriving XTypeFamilies Enabling these options is the only effect of Eglasgow exts We are trying to move away from this portmanteau flag and towards enabling features individually 7 2 Unboxed types and primitive operations GHC is built on a raft of primitive data types and operations primitive in the sense that they cannot be defined in Haskell itself While you really can use this stuff to write fast code we generally find it a lot less painful and more satisfying in the long run The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 126 240 to use higher level language features and libraries With any luck the code you write will be optimised to the efficient unboxed version in any case And if it isn t we d like to know about it All these primitive data types and operations are exported by the library GHC Prim for which there is detailed online documen tation This documentation is generated from the file compiler prelude primops txt pp If you want to mention any of the primitive data types or operations in your program you
391. s Haskell implementations that support the FFI standard The call to hs_init initializes GHC s runtime system Do NOT try to invoke any Haskell functions before calling hs_in it bad things will undoubtedly happen We pass references to argc and argv tohs_init so that it can separate out any arguments for the RTS i e those arguments between RTS RTS Next we call hs_add_root a GHC specific interface which is required to initialise the Haskell modules in the program The argument to hs_add_root should be the name of the initialization function for the root module in your program in other words the module which directly or indirectly imports all the other Haskell modules in the program In a standalone Haskell program the root module is normally Main but when you are using Haskell code from a library it may not be If your program has multiple root modules then you can call hs_add_root multiple times one for each root The name of the initialization function for module Mis___stginit_M and it may be declared as an external function symbol as in the code above Note that the symbol name should be transformed according to the Z encoding Character Replacement zd zu zq ZZ ZZ e NIN After we ve finished invoking our Haskell functions we can call hs_exit which terminates the RTS There can be multiple calls to hs_init but each one should be matched by one and only one call
392. s also pessimal for the short young generation collections in a parallel program because it can harm locality by moving data from the cache of the CPU where is it being used to the cache of another CPU Hence the default is to do load balancing only in the old generation In fact for a parallel program it is sometimes beneficial to disable load balancing entirely with qb Hsize Default 0 This option provides a suggested heap size for the garbage collector The garbage collector will use about this much memory until the program residency grows and the heap size needs to be expanded to retain reasonable performance By default the heap will start small and grow and shrink as necessary This can be bad for performance so if you have plenty of memory it s worthwhile supplying a big Hsize For improving GC performance using Hsize is usually a better bet than Asize Iseconds default 0 3 In the threaded and SMP versions of the RTS see threaded Section 4 10 6 a major GC is automatically performed if the runtime has been idle no Haskell computation has been running for a period of time The amount of idle time which must pass before a GC is performed is set by the I seconds option Specifying I0 disables the idle GC For an interactive application it is probably a good idea to use the idle GC because this will allow finalizers to run and deadlocked threads to be detected in the idle time when no Haskell computation is h
393. s for this package cc options string list Extra arguments to be added to the gcc command line when this package is being used only for via C compilations 1ld options string list Extra arguments to be added to the gec command line for linking when this package is being used framework dirs string list On Darwin MacOS X a list of directories containing frameworks for this package This corresponds to the framework path option It is ignored on all other platforms frameworks string list On Darwin MacOS X a list of frameworks to link to This corresponds to the framework option Take a look at Apple s developer documentation to find out what frameworks actually are This entry is ignored on all other platforms haddock interfaces string list A list of filenames containing Haddock interface files haddock files for this pack age haddock html optional string The directory containing the Haddock generated HTML for this package The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 68 240 4 9 Optimisation code improvement The Ox options specify convenient packages of optimisation flags the f options described later on specify individual optimisations to be turned on off the m options specify machine specific optimisations to be turned on off 4 9 1 Ox convenient packages of optimisation flags There are many options that affect the quality of code produced
394. s means you can bind values and functions to names and use them in future expressions or statements The syntax of a statement accepted at the GHCi prompt is exactly the same as the syntax of a statement in a Haskell do expression However there s no monad overloading here statements typed at the prompt must be in the IO monad Prelude gt x lt return 42 Prelude gt print x 42 Prelude gt The statement x lt return 42 means execute return 42 in the IO monad and bind the result to x We can then use x in future statements for example to print it as we did above If fprint bind result is set then GHCi will print the result of a statement if and only if e The statement is not a binding or it is a monadic binding p lt e that binds exactly one variable e The variable s type is not polymorphic is not and is an instance of Show Of course you can also bind normal non IO expressions using the 1et statement Prelude gt let x 42 Prelude gt x 42 Prelude gt Another important difference between the two types of binding is that the monadic bind p lt e is strict it evaluates e whereas with the 1et form the expression isn t evaluated immediately Prelude gt let x error help Prelude gt print x xxx Exception help Prelude gt Note that 1et bindings do not automatically print the value bound unlike monadic bindings Hint you can also use 1et statements to define func
395. s modification date In consequence importers of a module with an unchanged output hi file were not recompiled This doesn t work any more Suppose module C imports module B and B imports module A So changes to module A might require module C to be recompiled and hence when A hi changes we should check whether C should be recompiled However the dependencies of C will only list B hi not A hi and some changes to A changing the definition of a function that appears in an inlining of a function exported by B say may conceivably not change B hi one jot So now GHC calculates a fingerprint in fact an MD5 hash of each interface file and of each declaration within the interface file It also keeps in every interface file a list of the fingerprints of everything it used when it last compiled the file If the source file s modification date is earlier than the o file s date i e the source hasn t changed since the file was last compiled and the recompilation checking is on GHC will be clever It compares the fingerprints on the things it needs this time with the fingerprints on the things it needed last time gleaned from the interface file of the module being compiled if they are all the same it stops compiling early in the process saying Compilation IS NOT required What a beautiful sight You can read about how all this works in the GHC commentary The Glorious Glasgow Haskell Compilation System User s Guide Ver
396. s required in order to increase the resolution of the time profiler Using a value of zero disables the RTS clock completely and has the effect of disabling timers that depend on it the context switch timer and the heap profiling timer Context switches will still happen but deterministically and at a rate much faster than normal Disabling the interval timer is useful for debugging because it eliminates a source of non determinism at runtime install signal handlers yes no If yes the default the RTS installs signal handlers to catch things like ctrl C This option is primarily useful for when you are using the Haskell code as a DLL and want to set your own signal handlers The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 80 240 xmaddress WARNING this option is for working around memory allocation problems only Do not use unless GHCi fails with a message like failed to mmap memory below 2Gb If you need to use this option to get GHCi working on your machine please file a bug On 64 bit machines the RTS needs to allocate memory in the low 2Gb of the address space Support for this across different operating systems is patchy and sometimes fails This option is there to give the RTS a hint about where it should be able to allocate memory in the low 2Gb of the address space For example RTS xm20000000 RTS would hint that the RTS should allocate starting at the 0 5Gb mark The default is t
397. s the DLL so that you can be sure that all DLLs needed by any shutdown code in your End function are available when it is called The following example is untested but illustrates the idea please let us know if you find problems with this example or have a better one Suppose we have a DLL called Lewis which makes use of 2 Haskell modules Bar and Zap where Bar imports Zap and is therefore the root module in the sense of Section 8 2 1 1 Then the main C unit for the DLL would look something like Lewis cpp compiled using GCC include lt Windows h gt include HsFFI h define __LEWIS_DLL_EXPORT include Lewis h include Bar_stub h generated by GHC include Zap_stub h BOOL APIENTRY D11Main HANDLE hModule DWORD ul_reason_for_call LPVOID lpReserved it return TRUE extern C LEWIS_API HsBool lewis_Begin int argc char argv Initialize Haskell runtime hs_init amp argc amp argv Tell Haskell about all root modules hsBaddseroor sit Gamat ar do any other initialization here and return false if there was a problem return HS _ BOOL TRUE LEWIS_API void lewis_End hs_exit LEWIS_API HsInt lewis_Test HsInt x use Haskell functions exported by modules Bar and or Zap The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 228 240 return VE San Cw and some application which used the functions
398. s warning fwarn dodgy exports Causes a warning to be emitted when a datatype T is exported with all constructors i e T but is it just a type synonym Also causes a warning to be emitted when a module is re exported but that module exports nothing fwarn dodgy imports Causes a warning to be emitted when a datatype T is imported with all constructors i e T but has been exported abstractly i e T fwarn lazy unlifted bindings Causes a warning to be emitted when an unlifted type is bound in a way that looks lazy e g where I x Use where I x instead This will be an error rather than a warning in GHC 6 14 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 55 240 fwarn duplicate exports Have the compiler warn about duplicate entries in export lists This is useful information if you maintain large export lists and want to avoid the continued export of a definition after you ve deleted one mention of it in the export list This option is on by default fwarn hi shadowing Causes the compiler to emit a warning when a module or interface file in the current directory is shadowing one with the same module name in a library or other directory fwarn implicit prelude Have the compiler warn if the Prelude is implicitly imported This happens unless either the Prelude module is explicitly imported with an import Prelude line or this impli
399. scope and are mentioned in the type quantified over As for type signatures implicit quantification happens for non overloaded types too So if you write this data Ta MkT Either ab b gt b it s just as if you had written this data T a MkT forall 6 Bither a 6 forall b amp b o gt hb That is since the type variable b isn t in scope it s implicitly universally quantified Arguably it would be better to require explicit quantification on constructor arguments where that is what is wanted Feedback welcomed You construct values of types T1 MonadT Swizzle by applying the constructor to suitable values just as usual For example The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 177 240 al 38 T IDE al TL NES AZn as 82 amp wolzzila a2 MkSwizzle sort a3 MkSwizzle reverse a4 MonadT Maybe a4 let r x Just x bm k case m of muse yf S Ie ay Nothing gt Nothing in MkMonad r b mkT moral Ij Io gt lo gt lo gt a gt 11 al MES y Wil se ye EL se y n The type of the argument can as usual be more general than the type required as MkSwizzle reverse shows reve r se does not need the Ord constraint When you use pattern matching the bound variables may now have polymorphic types For example Fs T a gt a gt a Char ic IL Be gt i ke se we Yer Mel a Es Orol ei Oel lo gt Sa gt
400. se of hs boot files to cut the recursive loops among mutually recursive modules as described in Sec tion 4 6 9 This more of an infelicity than a bug the Haskell Report says Section 5 7 Depending on the Haskell implementation used separate compilation of mutually recursive modules may require that imported modules contain additional information so that they may be referenced before they are compiled Explicit type signatures for all exported values may be necessary to deal with mutual recursion The precise details of separate compilation are not defined by this Report 12 1 1 6 Numbers basic types and built in classes Multiply defined array elements not checked This code fragment should elicit a fatal error but it does not wain print erie il 1 l 2 ES DAD GHC s implementation of array takes the value of an array slot from the last index value pair in the list and does no checking for duplicates The reason for this is efficiency pure and simple 12 1 1 7 In Prelude support Arbitrary sized tuples Tuples are currently limited to size 100 HOWEVER standard instances for tuples Eq Ord Bound ed Ix Read and Show are available only up to 16 tuples This limitation is easily subvertible so please ask if you get stuck on it Reading integers GHC s implementation of the Read class for integral types accepts hexadecimal and octal literals the code in the Haskell 98 report doesn t So for example reacli
401. ser s Guide Version 6 12 2 56 240 f x do _ignore lt this _ignore lt that return the other fwarn orphans This option causes a warning to be emitted whenever the module contains an orphan instance declaration or rewrite rule An instance declaration is an orphan if it appears in a module in which neither the class nor the type being instanced are declared in the same module A rule is an orphan if it is a rule for a function declared in another module A module containing any orphans is called an orphan module The trouble with orphans is that GHC must pro actively read the interface files for all orphan modules just in case their instances or rules play a role whether or not the module s interface would otherwise be of any use See Section 4 6 12 for details fwarn overlapping patterns By default the compiler will warn you if a set of patterns are overlapping e g iE Strings Toyo i 1 Q ERS E 2 2 where the last pattern match in won t ever be reached as the second pattern overlaps it More often than not redundant patterns is a programmer mistake error so this option is enabled by default fwarn simple patterns Causes the compiler to warn about lambda bound patterns that can fail eg x xs gt Normally these aren t treated as incomplete patterns by fwarn incomplete patterns Lambda bound patterns includes all places where there is a single pattern including list comprehen
402. sgow Haskell Compilation System User s Guide Version 6 12 2 205 240 tp11 GHCziBase Int gt a gt GHCziBase ZMZN GHCziBase Char gt GHCziBase ZMZN GHCziBase Cha r tp12 a gt GHCziBase ZMZN GHCziBase Char tp13 GHCziBase ZMZN a gt GHCziBase ZMZN GHCziBase Char gt GHCziBase ZMZN GHCziBase Cha 2 gt tp12 Snote bar eta Here we can see that the function show which has been expanded out to a case expression over the Show dictionary has a note attached to it as does the expression eta which used to be called x 7 15 Special built in functions GHC has a few built in functions with special behaviour These are now described in the module GHC Prim in the library documentation 7 16 Generic classes The ideas behind this extension are described in detail in Derivable type classes Ralf Hinze and Simon Peyton Jones Haskell Workshop Montreal Sept 2000 pp94 105 An example will give the idea import Generics class Bin a where TOBA ma gt int EromBany lt 2 ist gt a Tint voBin ll Unit Unit Losin Ulla grs ae le a se 0 tobin x POB 2 grs Jo ine y EOS POBLA MAR to ke Sees VA ENB SX AO Bn roms A ware bs Unit bs Evombam la 24 ib 4oebs Indl x bs where x bs fromBin bs Crome 7 ita be iiss bae y 19 where y bs fromBin bs cromen CAN DS 6 8558 Y ls Wines Eplos J serclomleialici 9S OS sereomlBalig
403. signature for the function itself The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 178 240 hie soe toral ay a re P Bool Ona le GE Sie Meu E OY You don t need to give a type signature if the lambda bound variable is a constructor argument Here is an example we saw earlier 0 Sa M a gt a ap ea E a a c LS Cots EEA O Here we do not need to give a type signature to w because it is an argument of constructor T1 and that tells GHC all it needs to know 7 8 5 3 Implicit quantification GHC performs implicit quantification as follows At the top level only of user written types if and only if there is no explicit forall GHC finds all the type variables mentioned in the type that are not already in scope and universally quantifies them For example the following pairs are equivalent i 38 ey SS al O ge a gt a g x a let la e ey gt lo gt 19 la 3 y alias BS aes a ese lee E O O A OO lol Se AY Y ao aes a Notice that GHC does not find the innermost possible quantification point For example Paved a gt a gt imr MEANS Sk nora ay a gt a gt IMac NOD O O 2 E G 8 Oil a gt a gt gt E MEANS the illegal type JO AI Orc a gt a gt a O Sa NGL G 88 orali gy Qol A gt a gt a Mote The latter produces an illegal type which you might think is silly but at least the rule is simple If you want the latter t
404. sion 6 1 2 2 49 240 4 6 9 How to compile mutually recursive modules GHC supports the compilation of mutually recursive modules This section explains how Every cycle in the module import graph must be broken by a hs boot file Suppose that modules A hs and B hs are Haskell source files thus module A where import B newtype TA a Sa N f Mk IB gt TA B x module B where Mk MkTA loc IA boe import SOURCE A TA dara Ss Mis Paya g TA gt TB g MkTA x MkTB x Here A imports B but B imports A with a the module import graph must be broken by a SOURCE SOURCE acyclic if For every module A hs that is contains an abbreviated version of A hs thus module A where SOURCE pragma which breaks the circular dependency Every loop in E import or equivalently the module import graph must be imports are ignored SOURCE imported in this way there must exist a source file A hs boot This file newtype TA MkTA Int To compile these three files issue the following commands Gime C A lns loooir Produces A hi boot A o boot ghe e BINS Consumes A hi boot produces B hi B o aber T Consumes B hi produces A hi A o cias a Too Al OME Ome mel ein Kalen Chama Nep Crzeim There are several points to note here The file A hs boot is a programmer written sourc
405. sion 6 12 2 157 240 7 6 2 2 1 An attempt to use constructor classes Faced with the problems described above some Haskell programmers might be tempted to use something like the following version of the class declaration class Collects c wher Soy 34 0 G TNS OE gt a gt member gt E gt Bool The key difference here is that we abstract over the type constructor c that is used to form the collection type c e and not over that collection type itself represented by ce in the original class declaration This avoids the immediate problems that we mentioned above empty has type Collects c gt c e which is not ambiguous The function f from the previous section has a more accurate type E CO MESES E gt gt gt a gt e The function g from the previous section is now rejected with a type error as we would hope because the type of f does not allow the two arguments to have different types This then is an example of a multiple parameter class that does actually work quite well in practice without ambiguity problems There is however a catch This version of the Collects class is nowhere near as general as the original class seemed to be only one of the four instances for Collects given above can be used with this version of Collects because only one of them the instance for lists has a collection type that can be written in the form c e for some type constructor c and element type e 7 6 2 2 2 Add
406. sion for the package For example package mypkg 1 2 4 8 2 The main package Every complete Haskell program must define main in module Main in package main Omitting the package name flag compiles code for package main Failure to do so leads to a somewhat obscure link time error of the form usr bin ld Undefined symbols _ZCMain_main_closure stginit_ZCMain 4 8 3 Consequences of packages for the Haskell language It is possible that by using packages you might end up with a program that contains two modules with the same name perhaps you used a package P that has a hidden module M and there is also a module M in your program Or perhaps the dependencies of packages that you used contain some overlapping modules Perhaps the program even contains multiple versions of a certain package due to dependencies from other packages The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 60 240 None of these scenarios gives rise to an error on its own but they may have some interesting consequences For instance if you have a type M T from version 1 of package P then this is not the same as the type M T from version 2 of package P and GHC will report an error if you try to use one where the other is expected Formally speaking in Haskell 98 an entity function type or class in a program is uniquely identified by the pair of the module name in which it is defined and its name In GHC an entity is unique
407. sions Here s the basic idea Given a parallel comprehension of the form Le il lt gt oii 19 lt S12 ei lt e210 C2 lt 622 This will be translated to te Pipa el az o coc lt Zap al az jl lt elil p2 lt elZ sool ml ce cil lt eel CA lt G22 sool where zipN is the appropriate zip for the given number of branches 7 3 10 Generalised SQL Like List Comprehensions Generalised list comprehensions are a further enhancement to the list comprehension syntactic sugar to allow operations such as sorting and grouping which are familiar from SQL They are fully described in the paper Comprehensive comprehensions comprehensions with order by and group by except that the syntax we use differs slightly from the paper The extension is enabled with the flag XTransformListComp Here is an example employees Simon MS 80 Merwin MS 100 Mende met 40 Cordo nd eo 4 and Wiehe EONI r output the dept sum salary name dept salary lt employees then group by dept then sortWith by sum salary then take 5 In this example the list output would take on the value EC NewLe OO Mac 89 Muse 1130 There are three new keywords group by and using The function sort With is not a keyword it is an ordinary function that is exported by GHC Ext s There are five new forms of comprehension qualifier al
408. sions and do notation In these cases a pattern match failure is quite legitimate and triggers filtering list comprehensions or the monad fail operation monads For example f Maybe a gt a z se yy Just y lt xa Switching on fwarn simple patterns will elicit warnings about these probably innocent cases which is why the flag is off by default fwarn tabs Have the compiler warn if there are tabs in your source file This warning is off by default fwarn type defaults Have the compiler warn inform you where in your source the Haskell defaulting mechanism for numeric types kicks in This is useful information when converting code from a context that assumed one default into one with another e g the default default for Haskell 1 4 caused the otherwise unconstrained value 1 to be given the type Int whereas Haskell 98 defaults it to Integer This may lead to differences in performance and behaviour hence the usefulness of being non silent about this This warning is off by default fwarn monomorphism restriction Have the compiler warn inform you where in your source the Haskell Monomor phism Restriction is applied If applied silently the MR can give rise to unexpected behaviour so it can be helpful to have an explicit warning that it is being applied This warning is off by default fwarn unused binds Report any function definitions and local bindings which are unused For top level functions the
409. sm assembly language from the native code generator ddump bcos byte code compiler output ddump foreign dump foreign export stubs ddump simpl phases Show the output of each run of the simplifier Used when even dverbose simp1 doesn t cut it ddump simpl iterations Show the output of each iteration of the simplifier each run of the simplifier has a maxi mum number of iterations normally 4 This outputs even more information than ddump simpl phases ddump simpl stats Dump statistics about how many of each kind of transformation too place If you add dppr d ebug you get more detailed information ddump if trace Make the interface loader be real chatty about what it is upto ddump tc trace Make the type checker be real chatty about what it is upto ddump rn trace Make the renamer be real chatty about what it is upto ddump rn stats Print out summary of what kind of information the renamer had to bring in dverbose core2core dverbose stg2stg Show the output of the intermediate Core to Core and STG to STG passes respectively Lots of output So when we re really desperate o ghc noC O ddump simpl dverbose simpl dcore lint Foo hs dshow passes Print out each pass name as it happens dfaststring stats Show statistics for the usage of fast strings by the compiler dppr debug Debugging output is in one of several styles Take the printing of types for example In the user
410. stem User s Guide Version 6 12 2 153 240 In Haskell 98 we can define a parsing monad by type Parser tok m a State tok Failure m a which is automatically a monad thanks to the instance declarations above With the extension we can make the parser type abstract without needing to write an instance of class Monad via newtype Parser tok m a Parser State tok Failure m a deriving Monad In this case the derived instance declaration is of the form instance Monad State tok Failure m gt Monad Parser tok m Notice that since Monad is a constructor class the instance is a partial application of the new type not the entire left hand side We can imagine that the type declaration is eta converted to generate the context of the instance declaration We can even derive instances of multi parameter classes provided the newtype is the last class parameter In this case a partial application of the class appears in the deriving clause For example given the class class StateMonad s m m gt s where instance Monad m gt StateMonad s State s m where then we can derive an instance of StateMonad for Parsers by newtype Parser tok m a Parser State tok Failure m a deriving Monad StateMonad tok The derived instance is obtained by completing the application of the class to the new type instance StateMonad tok State tok Failure m gt StateMonad tok Parser tok m As a result of
411. structors with type families is more dynamic than that is the case with standard data and newtype declarations In the standard case the notation T in an import or export list denotes the type constructor and all the data constructors introduced in its declaration However a family declaration never introduces any data constructors instead data constructors are introduced by family instances As a result which data constructors are associated with a type family depends on the currently visible instance declarations for that family Consequently an import or export item of the form T denotes the family constructor and all currently visible data constructors in the case of an export item these may be either imported or defined in the current module The treatment of import and export items that explicitly list data constructors such as GMap GMapEither is analogous 7 7 1 3 1 Associated families As expected an import or export item of the form C denotes all of the class methods and associated types However when associated types are explicitly listed as subitems of a class we need some new syntax as uppercase identifiers as subitems are usually data constructors not type constructors To clarify that we denote types here each associated type name needs to be prefixed by the keyword type So for example when explicitly listing the components of the GMapKey class we write GMapKey type GMap empty lookup insert 7 7
412. support for automatically generating the required dependencies Add the following to your Makefile depend ghc M HC_OPTS SRCS Now before you start compiling and any time you change the imports in your program do make depend before you do make cool_pgm The command ghc M will append the needed dependencies to your Makefile In general ghc M Foo does the following For each module M in the set Foo plus all its imports transitively it adds to the Makefile The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 52 240 e A line recording the dependence of the object file on the source file MoR AMNS or M 1hs if that is the filename you used e For each import declaration import X in M a line recording the dependence of M on X Moo 3 iO e For each import declaration import SOURCI za Xin M a line recording the dependence of M on X MoO E om See Section 4 6 9 for details of hi boot style interface files If M imports multiple modules then there will be multiple lines with M o as the target There is no need to list all of the source files as arguments to the ghc M command ghc traces the dependencies just like ghc make a new feature in GHC 6 4 Note that ghc M needs to find a source file for each module in the dependency graph so that it can parse the import declarations and follow dependencies Any pre compiled modules without source fil
413. t main 3 I 186 240 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 187 240 7 10 Arrow notation Arrows are a generalization of monads introduced by John Hughes For more details see e Generalising Monads to Arrows John Hughes in Science of Computer Programming 37 pp67 111 May 2000 The paper that introduced arrows a friendly introduction motivated with programming examples e A New Notation for Arrows Ross Paterson in ICFP Sep 2001 Introduced the notation described here e Arrows and Computation Ross Paterson in The Fun of Programming Palgrave 2003 e Programming with Arrows John Hughes in 5th International Summer School on Advanced Functional Programming Lec ture Notes in Computer Science vol 3622 Springer 2004 This paper includes another introduction to the notation with practical examples e Type and Translation Rules for Arrow Notation in GHC Ross Paterson and Simon Peyton Jones September 16 2004 A terse enumeration of the formal rules used extracted from comments in the source code e The arrows web page at http www haskell org arrows With the XArrows flag GHC supports the arrow notation described in the second of these papers translating it using combi nators from the Control Arrow module What follows is a brief introduction to the notation it won t make much sense unless you ve read Hughes s paper The ex
414. t mel gt Srca ate chivaicla a e es e elen es 1 Position es r 0 show q 0 O show q digits recur where Ki a EAN QUO ERE ni drgits i recur dainnide nue Ces OSMELOM sg Mime gt ime gt Lime position n x xs n x 1 otherwise 1 position n xs SMOWRE CIEN O showRecip n U show n if r 0 then d else take p d drop p d The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 115 240 where Pe lengths el 18 el 15 reciprocal m main do number lt readLn putStrLn showRecip number main The HPC instrumentation is enabled using the fhpc flag ghc fhpc Recip hs make HPC index mix files are placed placed in hpc subdirectory These can be considered like the hi files for HPC Recip 1 3 0 ES We can generate a textual summary of coverage hpc report Recip 80 expressions used 81 101 12 boolean coverage 1 8 14 guards 1 7 3 always True 1 always False 2 unevaluated 0 if conditions 0 1 1 always False 100 qualifiers 0 0 55 alternatives used 5 9 100 local declarations used 9 9 100 top level declarations used 5 5 We can also generate a marked up version of the source hpc markup Recip writing Recip hs html This generates one file per Haskell module and 4 index files hpc_index html hpc_index_alt html hpc_index_exp html hpc_index_fu
415. t s look at an example Moss works similarly to iGgroupwilthy im Ele les but doesn t sort ibs input First cios 48 Ie la gt a gt 1 gt fal le groupRuns f groupBy x y gt f x f y QUEUE CelMNs se Ww s lt Mo Sl sae ian 2 o y lt 14556 then group by x using groupRuns This results in the variable output taking on the value below 1 4 5 6 2 4 5 61 3 4 5 6 1 4 5 2 4 5 6 Note that we have used the the function to change the type of x from a list to its original numeric type The variable y in contrast is left unchanged from the list form introduced by the grouping then group by e This form of grouping is essentially the same as the one described above However since no function to use for the grouping has been supplied it will fall back on the groupWith function defined in GHC Exts This is the form of the group statement that we made use of in the opening example then group using f With this form of the group statement f is required to simply have the type forall a la gt a which will be used to group up the comprehension so far directly An example of this form is as follows output x y s AS r 26 S ellos then group using inits This will yield a list containing every prefix of the word hello written out 5 times a a A LEA AA ilo hellon h lola ey Iloh IAR Lilon e LIOA ION g h
416. t s s ars a a Re RR Ba ee Re ec ee 144 TAAA Restrictions 2 06444 be Aw Se be ee ae ee sn ea ORAS Cae eo 145 7 4 5 Declaring data types with explicit constructor signatures 2 2 ee ee 146 7 4 6 Generalised Algebraic Data Types GADTs 0 0 0 0 0 00000004 149 7 5 Extensions to the deriving mechanism aoao 150 7 5 1 Inferred context for deriving clauses 2 ee 150 7 5 2 Stand alone deriving declarations 2 2 20 2 0 ee 151 7 5 3 Deriving clause for extra classes Typeable Data etc o e 152 7 5 4 Generalised derived instances fornewtypes ee 152 7 5 4 1 Generalising the deriving clause ee 152 7 5 4 2 Amore precise specification eee cestero ttre tE ered eres 153 7 6 Class and instances declarations ee 154 TO Class decl r tio s o cose so e E E A edd ee eae ba e 154 7 6 1 1 Multi parameter type classes 2 2 a 154 7 6 1 2 The superclasses of a class declaration o oo a 154 T 6 1 3 Class method types kor e 4 4 ma rr A a ts Ee 155 7 6 2 Functional dependencies s esec seee ee A 155 7 6 2 1 Rules for functional dependencies 2 0 000000000000 155 7 6 2 2 Background on functional dependencies 20 00 0000 000 156 7 6 2 2 1 An attempt to use constructor classes a 157 7 6 2 2 2 Adding functional dependencies a 157 The Glorious Glasgow Haskell
417. t cmd to get a Windows console and invoke ghci from there as long as it s in your PATH If you run GHCi in a Cygwin or MSYS shell then the Control C behaviour is adversely affected In one of these environments you should use the ghcii sh script to start GHCi otherwise when you hit Control C you ll be returned to the shell prompt but the GHCi process will still be running However even using the ghcii sh script if you hit Control C then the GHCi process will be killed immediately rather than letting you interrupt a running program inside GHCi as it should This problem is caused by the fact that the Cygwin and MSYS shell environments don t pass Control C events to non Cygwin child processes because in order to do that there needs to be a Windows console There s an exception you can use a Cygwin shell if the CYGWIN environment variable does not contain tt y In this mode the Cygwin shell behaves like a Windows console shell and console events are propagated to child processes Note that the CYGWIN environment variable must be set before starting the Cygwin shell changing it afterwards has no effect on the shell This problem doesn t just affect GHCi it affects any GHC compiled program that wants to catch console events See the GHC ConsoleHandler module 11 3 Interacting with the terminal By default GHC builds applications that open a console window when they start If you want to build a GUI only application with no console wi
418. t hardwired into the hsc2hs but are defined in a C template that is included in the C program template hsc h Custom constructs and templates can be used too Any construct with unknown key is expected to be handled by a C template A C template should define a macro or function with name prefixed by hsc_ that handles the construct by emitting the expansion to stdout See template hsc h for examples Such macros can also be defined directly in the source They are useful for making a 1et like macro whose expansion uses other 1et macros Plain 1et prepends hsc_ to the macro name and wraps the definition in a printf call The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 223 240 Chapter 11 Running GHC on Win32 systems 11 1 Starting GHC on Windows platforms The installer that installs GHC on Win32 also sets up the file suffix associations for hs and Ihs files so that double clicking them starts ghci Be aware of that ghe and ghci do require filenames containing spaces to be escaped using quotes e ghc bin ghci c Program Files Haskell Project hs If the quotes are left off in the above command ghci will interpret the filename as two c Program and Files Haskell Project hs 11 2 Running GHCi on Windows We recommend running GHCi in a standard Windows console select the GHCi option from the start menu item added by the GHC installer or use Start gt Run g
419. t runtime The primary difficulty with managing shared libraries is arranging things such that programs can find the libraries they need at runtime The details of how this works varies between platforms in particular the three major systems Unix ELF platforms Windows and Mac OS X On Unix there are two mechanisms Shared libraries can be installed into standard locations that the dynamic linker knows about For example usr lib or usr local 1ib on most systems The other mechanism is to use a runtime path or rpath embedded into programs and libraries themselves These paths can either be absolute paths or on at least Linux and Solaris they can be paths relative to the program or libary itself In principle this makes it possible to construct fully relocatable sets of programs and libraries GHC has a dynload linking flag to select the method that is used to find shared libraries at runtime There are currently three modes sysdep A system dependent mode This is also the default mode On Unix ELF systems this embeds rpaths into the shared library or executable In particular it uses absolute paths to where the shared libraries for the rts and each package can be found This means the program can immediately be run and it will be able to find the libraries it needs However it may not be suitable for deployment if the libraries are installed in a different location on another machine deploy This does not embed any runtime paths It relies on
420. t some instances from its representation In Haskell 98 you can inherit instances of Eq Ord Enum and Bounded by deriving them but for any other classes you have to write an explicit instance declaration For example if you define newtype Dollars Dollars Int and you want to use arithmetic on Dollars you have to explicitly define an instance of Num instance Num Dollars where Dollars a Dollars b Dollars atb All the instance does is apply and remove the newt ype constructor It is particularly galling that since the constructor doesn t appear at run time this instance declaration defines a dictionary which is wholly equivalent to the Int dictionary only slower 7 5 4 1 Generalising the deriving clause GHC now permits such instances to be derived instead using the flag XGeneralizedNewt ypeDeriving so one can write newtype Dollars Dollars Int deriving Eq Show Num and the implementation uses the same Num dictionary for Dollars as for Int Notionally the compiler derives an instance declaration of the form instance Num Int gt Num Dollars which just adds or removes the newt ype constructor according to the type We can also derive instances of constructor classes in a similar way For example suppose we have implemented state and failure monad transformers such that instance Monad m gt Monad State s m instance Monad m gt Monad Failure m The Glorious Glasgow Haskell Compilation Sy
421. tations However note that GHC uses a different syntax than the one described in these documents 7 3 8 1 Details of recursive do notation The recursive do notation is enabled with the flag XDoRec or equivalently the LANGUAGE pragma DoRec It introduces the single new keyword rec which wraps a mutually recursive group of monadic statements producing a single statement Similar to a let statement the variables bound in the rec are visible throughout the rec group and below it For example compare do a lt getChar do a lt getChar a diene al ae E m2 ec 1 El lt a 2 p ra o iil p 2 lt q wl a return ri eZ a erca rd eee In both cases r1 and r2 are available both throughout the 1et or rec block and in the statements that follow it The difference is that let is non monadic while rec is monadic In Haskell let is really let rec of course The static and dynamic semantics of rec can be described as follows e First similar to let bindings the rec is broken into minimal recursive groups a process known as segmentation For example The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 133 240 rec a lt getChar gt a lt getChar Si lt E 2 e rec b lt ac cs FRA N cay p joiners E T Pulte Chicane The details of segmentation are described in Section 3 2 of A recursive do for Haskell Segmentation improves polymorphism reduces the size o
422. tension adds a new kind of expression for defining arrows exp10 james apem gt cue where proc is a new keyword The variables of the pattern are bound in the body of the proc expression which is a new sort of thing called a command The syntax of commands is as follows cmd expl0 lt exp expl0 lt lt exp cmdO with cmd up to cmd defined using infix operators as for expressions and cweit 282 SSE cco Apate gt Ciel let decls in cmd if exp then cmd else cmd case exp of calts do SEE f car CSEmr eme fcmd fomd fcmd aexp i enc W acaso Cae ooa Cel cstmt let decls pat lt emel rec estat oco estubo lol gt cmd where calts are like alts except that the bodies are commands instead of expressions Commands produce values but like monadic computations may yield more than one value or none and may do other things as well For the most part familiarity with monadic notation is a good guide to using commands However the values of expressions even monadic ones are determined by the values of the variables they contain this is not necessarily the case for commands A simple example of the new notation is the expression The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 188 240 pios z gt E lt xrl We call this a procedure or arrow abstraction As with a lambda expression the variable x is a new variable bound within the proc expression
423. ter each evaluation they are still retained during a single evaluation This option may help if the evaluated top level expressions are consuming large amounts of space or if you need repeatable performance measurements s Display some stats after evaluating each expression including the elapsed time and number of bytes allocated NOTE the allocation figure is only accurate to the size of the storage manager s allocation area because it is calculated at every GC Hence you might see values of zero if no GC has occurred t Display the type of each variable bound after a statement is entered at the prompt If the statement is a single expression then the only variable binding will be for the variable it 2 8 2 Setting GHC command line options in GHCi Normal GHC command line options may also be set using set For example to turn on Eglasgow exts you would say Prelude gt set fglasgow exts Any GHC command line option that is designated as dynamic see the table in Section 4 18 may be set using set To unset an option you can set the reverse option Prelude gt set fno glasgow exts Section 4 18 lists the reverse for each option where applicable Certain static options package I i and 1 in particular will also work but some may not take effect until the next reload 2 9 The ghci file When it starts unless the ignore dot ghci flag is given GHCi reads and executes commands from the foll
424. terface file generated for the module being compiled say M This means that a module importing M will see only the types of the functions that M exports but not their unfoldings strictness info etc Hence for example no function exported by M will be inlined into an importing module The benefit is that modules that import M will need to be recompiled less often only when M s exports change their type not when they change their implementation fignore interface pragmas Tells GHC to ignore all inessential information when reading interface files That is even if M hi contains unfolding or strictness information for a function GHC will ignore that information funbox strict fields This option causes all constructor fields which are marked strict i e to be unboxed or unpacked if possible It is equivalent to adding an UNPACK pragma to every strict constructor field see Section 7 13 11 This option is a bit of a sledgehammer it might sometimes make things worse Selectively unboxing fields by using UNPACK pragmas might be better funfolding creation threshold n Default 45 Governs the maximum size that GHC will allow a function unfolding to be An unfolding has a size that reflects the cost in terms of code bloat of expanding that unfolding at at a call site A bigger function would be assigned a bigger cost Consequences a nothing larger than this will be inlined unless it has an INLINE pragma b nothin
425. that a nested context must be indented further to the right than the enclosing context is relaxed to allow the nested context to be at the same level as the enclosing context if the enclosing context is a do expression For example the following code is accepted by GHC main do args lt getArgs if null args then return else do ps lt mapM process args mapM print ps GHC doesn t do fixity resolution in expressions during parsing For example according to the Haskell report the following expression is legal Haskell let x 42 in x 42 True and parses as let x 42 in x 42 Tru because according to the report the let expression extends as far to the right as possible Since it can t extend past the second equals sign without causing a parse error is non fix the let expression must terminate there GHC simply gobbles up the whole expression parsing like this The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 230 240 let x 42 in x 42 True The Haskell report is arguably wrong here but nevertheless it s a difference between GHC amp Haskell 98 12 1 1 3 Expressions and patterns None known 12 1 1 4 Declarations and bindings GHC s typechecker makes all pattern bindings monomorphic by default this behaviour can be disabled with KNoMonoPat Binds See Section 7 1 12 1 1 5 Module system and interface files GHC requires the u
426. the interpreter use the fobject code option see Section 2 10 HINT since GHCi will only use a compiled object file if it can be sure that the compiled version is up to date a good technique when working on a large program is to occasionally run ghc make to compile the whole project say before you go for lunch then continue working in the interpreter As you modify code the changed modules will be interpreted but the rest of the project will remain compiled 2 4 Interactive evaluation at the prompt When you type an expression at the prompt GHCi immediately evaluates and prints the result Prelude gt reverse hello olleh Prelude gt 5 5 10 2 4 1 I O actions at the prompt GHCi does more than simple expression evaluation at the prompt If you type something of type IO a for some a then GHCi executes it as an IO computation Prelude gt hello hello Prelude gt putStrLn hello hello Furthermore GHCi will print the result of the I O action if and only if e The result type is an instance of Show The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 18 240 e The result type is not For example remembering that putStrLn String gt IO Prelude gt putStrLn hello hello Prelude gt do putStrLn hello return yes hello ves 2 4 2 Using do notation at the prompt GHCi actually accepts statements rather than just expressions at the prompt Thi
427. the scheduler Use RTS to find out which debug flags are supported Debug messages will be sent to the binary event log file instead of stdout if the 1 option is added This might be useful for reducing the overhead of debug tracing rfile Produce ticky ticky statistics at the end of the program run only available if the program was linked with debug The file business works just like on the S RTS option above For more information on ticky ticky profiling see Section 5 7 xc Only available when the program is compiled for profiling When an exception is raised in the program this option causes the current cost centre stack to be dumped to stderr This can be particularly useful for debugging if your program is complaining abouta head error and you haven t got a clue which bit of code is causing it compiling with prof auto all and running with RTS xc RTS will tell you exactly the call stack at the point the error was raised The output contains one line for each exception raised in the program the program might raise and catch several exceptions during its execution where each line is of the form EC ata CCH each cc is a cost centre in the program see Section 5 1 and the sequence represents the call stack at the point the exception was raised The leftmost item is the innermost function in the call stack and the rightmost item is the outermost function Z Turn off update frame squeezin
428. the shared libraries being available in a standard location or in a directory given by the LD_LIBRARY_PATH environment variable wrapped This mode generates a wrapper program which in turn calls the real program in the same directory but with a dyn extension in such a way that it can find the shared libraries that it needs At the current time this mode is somewhat experimental To use relative paths for dependent libraries on Linux and Solaris you can use the deploy mode and pass suitable a rpath flag to the linker The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 77 240 ghe dynamic Main hs o main lfoo L opt1 Wl rpath SORIGIN This assumes that the library 1ibfoo so is in the current directory and will be able to be found in the same directory as the executable main once the program is deployed Similarly it would be possible to use a subdirectory relative to the executable e g opt1 W1 rpath SORIGIN 1lib 4 12 Using Concurrent Haskell GHC supports Concurrent Haskell by default without requiring a special option or libraries compiled in a certain way To get access to the support libraries for Concurrent Haskell just import Control Concurrent More information on Concurrent Haskell is provided in the documentation for that module The following RTS option s affect the behaviour of Concurrent Haskell programs Cs Sets the context switch interval to s seconds A context sw
429. the type of the constructor such a type variable is often called existential Indeed the above declaration declares precisely the same type as the data Foo in Section 7 4 4 The type may contain a class context too of course data Showable where MkShowable Show a gt a gt Showable You can use record syntax on a GADT style data type declaration data Person where Adult name String children Person gt Person Cite 8 Show a gt 1 meme s3 iStcrlas EUA e aA gt Person As usual for every constructor that has a field f the type of field f must be the same modulo alpha conversion The Child constructor above shows that the signature may have a context existentially quantified variables and strictness annotations just as in the non record case NB the type that follows the double colon is not really a type because of the record syntax and strictness annotations A type of this form can appear only in a constructor signature Record updates are allowed with GADT style declarations only fields that have the following property the type of the field mentions no existential type variables The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 149 240 e As in the case of existentials declared using the Haskell 98 like record syntax Section 7 4 4 3 record selector functions are generated only for those fields that have well typed selectors Here is the example of th
430. the various columns in the output is entries The number of times this particular point in the call graph was entered immediately clear that it was the call from which took all the The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 106 240 individual time The percentage of the total run time of the program spent at this point in the call graph individual alloc The percentage of the total memory allocations excluding profiling overheads of the program made by this call inherited time The percentage of the total run time of the program spent below this point in the call graph inherited alloc The percentage of the total memory allocations excluding profiling overheads of the program made by this call and all of its sub calls In addition you can use the P RTS option to get the following additional information ticks The raw number of time ticks which were attributed to this cost centre from this we get the t ime figure mentioned above bytes Number of bytes allocated in the heap while in this cost centre again this is the raw number from which we get the alloc figure mentioned above What about recursive functions and mutually recursive groups of functions Where are the costs attributed Well although GHC does keep information about which groups of functions called each other recursively this information isn t displayed in the basic time and allocation profile
431. then the pragma SPECIALIZE f lt type gt is valid if and only if the definition f_spec lt type gt f_spec f is valid Here are some examples where we only give the type signature for the original function not its code The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 E 63 Re a gt a S lo gt Ip SPECIALISE f Int gt b gt b a 32 Be Ix lo gt a gt lo gt 19 SPECIALISE g Eq a gt a gt Int gt Int In ss he gt an gt a AS BE CUATES ERE a gt ai lal S il 199 240 I i The last of these examples will generate a RULE with a somewhat complex left hand side try it yourself so it might not fire very well If you use this kind of specialisation let us know how well it works A SPECIALIZE pragma can optionally be followed with a INLI described in Section 7 13 5 The INLINI function is recursive The motivating example is this gt A QADI tor arrays wichaa ENS data Arr e where indexed representa NI E or NOINLINE pragma optionally followed by a phase as E pragma affects the specialised version of the function only and applies even if the cion ArrInt Ving gt By teAcraya gt Ae int ArrPair Int gt Arr el gt Arr e2 gt Arr el e2 GS Arr e gt Int gt e S
432. think of the ordinary universally quantified type given above thereby avoiding adding a new existential quantification construct 7 4 4 2 Existentials and type classes An easy extension is to allow arbitrary contexts before the constructor For example data Baz forall a Eq a gt Bazlaa Sore dor Snow gt Baza o gt o The two constructors have the types you d expect Banail 8 toral as B a gt a gt a gt Baz Baz2 28 ROTAL Joy Show ig gt ly gt No gt lo gt BAZ But when pattern matching on Baz1 the matched values can be compared for equality and when pattern matching on Baz2 the first matched value can be converted to a string as well as applying the function to it So this program is legal The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 jaune if 32 Ban gt OTME Sal p q p q Yes otherwise No E BAZA W 0 show fn v Operationally in a dictionary passing implementation the constructors Baz1 and Baz2 must store the dictionaries for Eq and Show respectively and extract it on pattern matching 7 4 4 3 Record Constructors GHC allows existentials to be used with records syntax as well For example data Counter a forall self NewCounter AS 28 Sel Aia 3h Salnt E AECE Says gt 1O n TaN SR G Here tag is a public field with a well typed selector function tag Counter a gt a The self type is hidden from
433. this extension all derived instances in newtype declarations are treated uniformly and implemented just by reusing the dictionary for the representation type except Show and Read which really behave differently for the newtype and its representation 7 5 4 2 A more precise specification Derived instance declarations are constructed as follows Consider the declaration after expansion of any type synonyms MEWE UW Los a 1 e Vianos a ceriya il 4 se a where e The ci are partial applications of classes of the form C t1 t3 where the arity of C is exactly 3 1 That is C lacks exactly one type argument e The k is chosen so that ci T vl vk is well kinded e The type t is an arbitrary type e The type variables vk 1 vn do not occur in t nor in the ci and e None of the ci is Read Show Typeable or Data These classes should not look through the type or its constructor You can still derive these classes for a newtype but it happens in the usual way not via this new mechanism Then for each ci the derived instance declaration is Instance CL beet CT Vilos ko The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 154 240 As an example which does not work consider newtype NonMonad m s NonMonad State s m s deriving Monad Here we cannot derive the instance instance Monad State s m gt Monad NonMonad m because the type variable s occurs in State s m and so
434. time profile report It is written into the file program prof The P option produces a more detailed report containing the actual time and allocation data as well Not used much xc This option makes use of the extra information maintained by the cost centre stack profiler to provide useful information about the location of runtime errors See Section 4 15 7 5 4 Profiling memory usage In addition to profiling the time and allocation behaviour of your program you can also generate a graph of its memory usage over time This is useful for detecting the causes of space leaks when your program holds on to more memory at run time that it needs to Space leaks lead to longer run times due to heavy garbage collector activity and may even cause the program to run out of memory altogether To generate a heap profile from your program 1 Compile the program for profiling Section 5 2 2 Run it with one of the heap profiling options described below eg hc for a basic producer profile This generates the file prog hp The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 109 240 3 Run hp2ps to produce a Postscript file prog ps The hp2ps utility is described in detail in Section 5 5 4 Display the heap profile using a postscript viewer such as Ghostview or print it out on a Postscript capable printer You might also want to take a look at hp2any a more advanced suite of tools not distributed wit
435. tion The term library here refers to libraries of foreign object code for using libraries of Haskell source code see Section 2 2 1 For example to load the m library S owen im On systems with so style shared libraries the actual library loaded will the 1iblib so GHCi searches the following places for libraries in this order e Paths specified using the Lpath command line option e the standard library search path for your system which on some systems may be overridden by setting the LD_LIBRARY_P ATH environment variable On systems with d11 style shared libraries the actual library loaded will be 1ib d11 Again GHCi will signal an error if it can t find the library GHCi can also load plain object files o or obj depending on your platform from the command line Just add the name the object file to the command line Ordering of 1 options matters a library should be mentioned before the libraries it depends on see Section 4 10 6 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 32 240 2 7 GHCi commands GHCi commands all begin with and consist of a single command name followed by zero or more parameters The command name may be abbreviated with ambiguities being resolved in favour of the more commonly used commands abandon Abandons the current evaluation only available when stopped at a breakpoint add module Add module s to the current target set
436. tions at the prompt Prelude gt let add ab a b Prelude gt add 1 2 3 Prelude gt However this quickly gets tedious when defining functions with multiple clauses or groups of mutually recursive functions because the complete definition has to be given on a single line using explicit braces and semicolons instead of layout The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 19 240 Prelude ike 1 of i A im F 2 wo m ase In ej 16 oj m ic Prelude gt f O 1 3 6 Prelude gt To alleviate this issue GHCi commands can be split over multiple lines by wrapping them in and each on a single line of its own Prelude gt Prelude let g op n Prelude poa oa ia age la oj e ej iol te Prelude Prelude EXE i i S 6 Reel Such multiline commands can be used with any GHCi command and the lines between and are simply merged into a single line for interpretation That implies that each such group must form a single valid command when merged and that no layout rule is used The main purpose of multiline commands is not to replace module loading but to make definitions in ghci files see Section 2 9 more readable and maintainable Any exceptions raised during the evaluation or execution of the statement are caught and printed by the GHCi command line interface for more information on exceptions see the module Control Except ion in the librar
437. to construct Template Haskell expressions patterns declarations etc They may also be given as an argument to the rei fy function e You may omit the in atop level declaration splice Simply writing an expression rather than a declaration implies a splice For example you can write module Foo where import Bar ES deriveStuff f Uses un Sos DOTACION Sy Ard deriveStuff g OMS Che Elasa ln 2 Al This abbreviation makes top level declaration slices quieter and less intimidating Compared to the original paper there are many differences of detail The syntax for a declaration splice uses not splice The type of the enclosed expression must be Q Dec not Q Dec Pattern splices and quotations are not implemented 7 9 2 Using Template Haskell e The data types and monadic constructor functions for Template Haskell are in the library Language Haskell THSyntax e You can only run a function at compile time if it is imported from another module That is you can t define a function in a module and call it from within a splice in the same module It would make sense to do so but it s hard to implement e You can only run a function at compile time if it is imported from another module that is not part of a mutually recursive group of modules that includes the module currently being compiled Furthermore all of the modules of the mutually recursive group must be reachable by non SOURCE imports from the m
438. to hs_exit A NOTE when linking the final program it is normally easiest to do the link using GHC although this isn t essential If you do use GHC then don t forget the flag no hs main otherwise GHC will try to link to the Main Haskell module The outermost hs_exit will actually de initialise the system NOTE that currently GHC s runtime cannot reliably re initialise after this has happened see Section 12 1 3 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 214 240 8 2 1 2 Making a Haskell library that can be called from foreign code The scenario here is much like in Section 8 2 1 1 except that the aim is not to link a complete program but to make a library from Haskell code that can be deployed in the same way that you would deploy a library of C code The main requirement here is that the runtime needs to be initialized before any Haskell code can be called so your library should provide initialisation and deinitialisation entry points implemented in C or C For example HsBool mylib_init void iac GWEC ngo elague see soc Initialize Haskell runtime hs_init sarge amp argv Tell Haskell about all root modules hismacclin oil Est Gamal oo do any other initialization here and return false if there was a problem return HS BOOL TRUE void mylib_end void hs_exit The initialisation routine mylib_init calls hs_init and hs_a
439. to the current scope and removes them Without either or the current scope is replaced by the set of modules specified Note that if you use this form and leave out Prelude GHCi will assume that you really wanted the Prelude and add it in for you if you don t want the Prelude then ask to remove it with m Prelude The scope is automatically set after a load command to the most recently loaded target module in a form if possible For example if you say load foo hs bar hs and bar hs contains module Bar then the scope will be set to Bar if Bar is interpreted or if Bar is compiled it will be set to Prelude Bar GHCi automatically adds Prelude if it isn t present and there aren t any form modules With multiple modules in scope especially multiple form modules it is likely that name clashes will occur Haskell specifies that name clashes are only reported when an ambiguous identifier is used and GHCi behaves in the same way for expressions typed at the prompt Hint GHCi will tab complete names that are in scope for example if you run GHCi and type J lt t ab gt then GHCi will expand itto Just 2 4 3 1 module and load It might seem that module and load do similar things you can use both to bring a module into scope However there is a clear difference GHCi is concerned with two sets of modules e The set of modules that are currently loaded This set is modified by load add and relo
440. tor To output a literal write it twice Inside string literals and comments characters are not processed A is followed by optional spaces and tabs an alphanumeric keyword that describes the kind of processing and its arguments Arguments look like C expressions separated by commas they are not written inside parens They extend up to the nearest unmatched or orto the end of line if it occurs outside any 77 xx andis not preceded by a backslash Backslash newline pairs are stripped In addition stuff is equivalent to stuff except that it s self delimited and thus needs not to be placed at the end of line or in some brackets Meanings of specific keywords include lt file h gt include file h The specified file gets included into the C program the compiled Haskell file and the C header lt HsFF I h gt is included automatically define name define name value undef name Similar to include Note that includes and defin es may be put in the same file twice so they should not assume otherwise let name parameters definition Defines a macro to be applied to the Haskell source Parameter names are comma separated not inside parens Such macro is invoked as other constructs starting with name The definition will be put in the C program inside parens as arguments of printf To refer to a parameter close the quote put a parameter name and open the quote again to let C st
441. tput 46 4 6 5 Keeping Intermediate Files o es eric oce RR Re ee Ee ee ee 47 4 6 6 Redirecting temporary files 2 0 22 0 0 0 020 000 0000 000020000 48 4 6 7 Other options related to interface files 2 2 ee 48 4 6 8 The recompilation Checker 0 0 000000 0200 eee ee 48 4 6 9 How to compile mutually recursive modules 0200000000000 0000 49 4 010 Using make os eee eA a Be OR eg A E a a eR ee ee a 50 4 6 11 Dependency generation e sere ee ee ee E 4 6 12 Orphan modules and instance declarations e 53 4 7 Warnings and sanity checking ee 54 4 8 Packages ip a a Ree Pa ie Pa a eee e A ae ea ER 57 AS Usmo Packages eva tc eee Set Bee eo aa a ewes aetna ee ee Se wa he a 57 4 32 Themam packape 2 4664 654854405 RRP ERA RO oP ewe ed ee wR Pe ee oe 59 4 8 3 Consequences of packages for the Haskell language e e 59 4 8 4 Package Databases 2 4 55 ae RRR e a e A we eo 60 4 8 4 1 The GHC_PACKAGE_PATH environment variable 60 4 8 5 Package IDs dependencies and broken packages 2 2 2 20 0000000000 0000 61 4 8 6 Package management the g c pkg command 000 eee eee eee ee 62 4 8 7 Building a package from Haskell source 2 2 a 64 4 8 8 InstalledPackageInfo a package specification o e 65 4 9 Optimisation code improvement 2 2 ee 6
442. tten to e You can also disable assertions using the fignore asserts option Assertion failures can be caught see the documentation for the Cont rol Exception library for the details 7 13 Pragmas GHC supports several pragmas or instructions to the compiler placed in the source code Pragmas don t normally affect the meaning of the program but they might affect the efficiency of the generated code Pragmas all take the form word where word indicates the type of pragma and is followed optionally by information specific to that type of pragma Case is ignored in word The various values for word that GHC understands are described in the following sections any pragma encountered with an unrecognised word is ignored The layout rule applies in pragmas so the closing should start in a column to the right of the opening Certain pragmas are file header pragmas e A file header pragma must precede the module keyword in the file e There can be as many file header pragmas as you please and they can be preceded or followed by comments e File header pragmas are read once only before pre processing the file e g with cpp e The file header pragmas are LANGUAGE OPTIONS_GHC and INCLUDE 7 13 1 LANGUAGE pragma The LANGUAGE pragma allows language extensions to be enabled in a portable way It is the intention that all Haskell compilers support the LANGUAGE pragma with the same syntax
443. tub h and call foo The foo_stub c and foo_stub h files can be redirected using the st ubdir option see Section 4 6 4 When linking the program remember to include M_stub o in the final link command line or you ll get link errors for the missing function s this isn t necessary when building your program with ghc make as GHC will automatically link in the correct bits 8 2 1 1 Using your own main Normally GHC s runtime system provides a main which arranges to invoke Main main in the Haskell program However you might want to link some Haskell code into a program which has a main function written in another language say C In order to do this you have to initialize the Haskell runtime system explicitly Let s take the example from above and invoke it from a standalone C program Here s the C code The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 213 240 include lt stdio h gt includes Hs EEN ifdef _ GLASGOW_HASKELL include foo _ stub h endif ifdef _ GLASGOW_HASKELL racema ViOul ces tb gnc Jo N vorc Ja endif int main int argc char xargv Lie alg hs_init 8argc amp argv ifdef _ GLASGOW_HASKELL hs_add_root __stginit_Foo endif cow sl Of 1 lt Se ales Y heat UE AS AO hs_exit sicuicia Ole We ve surrounded the GHC specific bits with ifdef __GLASGOW_HASKELL__ the rest of the code should be portable acros
444. u use this flag then any packages you require including base need to be explicitly exposed using package options This is a good way to insulate your program from differences in the globally exposed packages and being explicit about package dependencies is a Good Thing Cabal always passes the hide all packages flag to GHC for exactly this reason hide package P This option does the opposite of package it causes the specified package to be hidden which means that none of its modules will be available for import by Haskell import directives Note that the package might still end up being linked into the final program if it is a dependency direct or indirect of another exposed package ignore package P Causes the compiler to behave as if package P and any packages that depend on P are not installed at all Saying ignore package P is the same as giving hide package flags for P and all the packages that depend on P Sometimes we don t know ahead of time which packages will be installed that depend on P which is when the ignore package flag can be useful no auto link packages By default GHC will automatically link in the haske1198 package This flag disables that behaviour package name foo Tells GHC the the module being compiled forms part of package foo If this flag is omitted a very common case then the default package main is assumed Note the argument to package name should be the full package name ver
445. u want to mention it explicitly for example to give an instance declaration for it you can import it from module GHC Exts Haskell s defaulting mechanism is extended to cover string literals when KOverloadedSt rings is specified Specifically e Each type in a default declaration must be an instance of Num or of IsSt ring e The standard defaulting rule Haskell Report Section 4 3 4 is extended thus defaulting applies when all the unresolved constraints involve standard classes or IsSt ring and at least one is a numeric class or IsSt ring A small example module Main where Imp Ome GHEE xt sis Sitiedin 0 newtype MyString MyString String deriving Eq Show instance IsString MyString where fromString MyString greet MyString gt MyString greet hello world greet other other main do print greet hello print greet fool Note that deriving Eq is necessary for the pattern matching to work since it gets translated into an equality comparison 7 7 Type families Indexed type families are a new GHC extension to facilitate type level programming Type families are a generalisation of associated data types Associated Types with Class M Chakravarty G Keller S Peyton Jones and S Marlow In Proceedings of The 32nd Annual ACM SIGPLAN SIGACT Symposium on Principles of Programming Languages POPL 05 pages 1 13 ACM Press 2005 and associated type synonyms Type Assoc
446. ubdir dir Redirects all generated FFI stub files into dir Stub files are generated when the Haskell source contains a foreign export or foreign import amp wrapper declaration see Section 8 2 1 The stubdir option behaves in exactly the same way as odir and hidir with respect to hierarchical modules outputdir dir The outputdir option is shorthand for the combination of odir hidir and stubdir osuf suffix hisuf suffix hcsuf suffix The osuf suffix will change the o file suffix for object files to whatever you specify We use this when compiling libraries so that objects for the profiling versions of the libraries don t clobber the normal ones Similarly the hi suf suffix will change the hi file suffix for non system interface files see Section 4 6 7 Finally the option hcsuf suffix will change the hc file suffix for compiler generated intermediate C files The hisuf osuf game is particularly useful if you want to compile a program both with and without profiling in the same directory You can say SNS oso to get the ordinary version and Cine ooo OSULE foro yO Site joo plas PEOR auton aMi to get the profiled version 4 6 5 Keeping Intermediate Files The following options are useful for keeping certain intermediate files around when normally GHC would throw these away after compilation keep hc file keep hc files Keep intermediate hc files when doing hs to o compilations via C N
447. ug report we would recommend that you add a dcore lint option for extra checking to your compilation options So before you report a bug because of a core dump you should probably rm 0 scrub your object files make my_prog re make your program use hi diffs to highlight changes as mentioned above us dcore lint to be more paranoid Sa MYM LOC ooo F Get Inv Of course if you have foreign calls in your program then all bets are off because you can trash the heap the stack or whatever My program entered an absent argument This is definitely caused by a bug in GHC Please report it see Section 1 3 What s with this arithmetic or floating exception Int Float and Double arithmetic is unchecked Overflows underflows and loss of precision are either silent or reported as an exception by the operating system depending on the platform Divide by zero may cause an untrapped exception please report it if it does The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 219 240 Chapter 10 Other Haskell utility programs This section describes other program s which we distribute that help with the Great Haskell Programming Task 10 1 Ctags and Etags for Haskell hasktags hasktags is a very simple Haskell program that produces ctags tags and etags TAGS files for Haskell programs When loaded into an editor such an NEdit Vim or Emacs this al
448. umented code provides coverage information of two kinds source coverage and boolean control coverage Source coverage is the extent to which every part of the program was used measured at three different levels declarations both top level and local alternatives among several equations or case branches and expressions at every level Boolean coverage is the extent to which each of the values True and False is obtained in every syntactic boolean context ie guard condition qualifier HPC displays both kinds of information in two primary ways textual reports with summary statistics hpc report and sources with color mark up hpc markup For boolean coverage there are four possible outcomes for each guard condition or qualifier both True and False values occur only True only False never evaluated In hpc markup output highlighting with a yellow background indicates a part of the program that was never evaluated a green background indicates an always True expression and a red background indicates an always False one 5 6 1 A small example Reciprocation For an example we have a program called Recip hs which computes exact decimal representations of reciprocals with recurring parts indicated in brackets reciproca liik E Sn gi reciprocal im m gt l 0 g 7 2 oiei EEn ESCUE otherwise error attempting to compute reciprocal of number lt 1 where digits recur divide n 1 ebialela sE ime gt ae g
449. unctions you want to call from the outside For example The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 226 240 module Adder where adde rana Wet gt ioe S WO Wnt O BA US SS MO AO adder x y return x y HOIMSiLeie Cexgoouee Siecleeulil ewcleleie gg Lime O alioic Compile it up ghc c adder hs fglasgow exts This will produce two files adder o and adder_stub o compile up a D11Main that starts up the Haskell RTS a possible implementation is tinclude lt windows h gt include lt Rts h gt extern void __stginit_Adder void Sucuio clacnes aros af Veja INAOAtAG des x N B argv arrays must end with NULL x BOOL STDCALL DllMain HANDLE hModule DWORD reason void reserved if reason DLL_PROCESS_ATTACH x By now the RTS DLL should have been hoisted in but we need to start it up startupHaskell 1 args __stginit_Adder return TRUE return TRUE Here Adder is the name of the root module in the module tree as mentioned above there must be a single root module and hence a single module tree in the DLL Compile this up gie 8 SILINE E Construct the DLL ghc shared o adder dll adder o adder_stub o dllMain o Start using adder from VBA here s how I would Declare it Private Declare Function adder Lib adder dll Alias adder 8 ByVal x As Long ByVal y As Long As Long Since this Haskell DLL de
450. unts characters rather than columns This matches what some editors do and doesn t match others The best advice is to avoid tab characters in your source code altogether see fwarn tabs in Section 4 7 If the module is omitted then the most recently loaded module is used Not all subexpressions are potential breakpoint locations Single variables are typically not considered to be breakpoint locations unless the variable is the right hand side of a function definition lambda or case alternative The rule of thumb is that all redexes are breakpoint locations together with the bodies of functions lambdas case alternatives and binding statements There is normally no breakpoint on a let expression but there will always be a breakpoint on its body because we are usually interested in inspecting the values of the variables bound by the let 2 5 1 2 Listing and deleting breakpoints The list of breakpoints currently enabled can be displayed using show breaks Main gt show breaks O Marne sortean sra AMAN so ens 2 5 6 To delete a breakpoint use the delete command with the number given in the output from show breaks Main gt delete 0 Main gt show breaks GO Nean sortean si2 e 15 46 To delete all breakpoints at once use delete x 2 5 2 Single stepping Single stepping is a great way to visualise the execution of your program and it is also a useful tool for identifying the source of a bug GHCi offers two variants
451. upports both concurrency and parallelism 7 18 1 Concurrent Haskell Concurrent Haskell is the name given to GHC s concurrency extension It is enabled by default so no special flags are required The Concurrent Haskell paper is still an excellent resource as is Tackling the awkward squad To the programmer Concurrent Haskell introduces no new language constructs rather it appears simply as a library Con trol Concurrent The functions exported by this library include The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 209 240 e Forking and killing threads e Sleeping e Synchronised mutable variables called MVars e Support for bound threads see the paper Extending the FFI with concurrency 7 18 2 Software Transactional Memory GHC now supports a new way to coordinate the activities of Concurrent Haskell threads called Software Transactional Memory STM The STM papers are an excellent introduction to what STM is and how to use it The main library you need to use is the stm library The main features supported are these e Atomic blocks e Transactional variables e Operations for composing transactions ret ry and orElse e Data invariants All these features are described in the papers mentioned earlier 7 18 3 Parallel Haskell GHC includes support for running Haskell programs in parallel on symmetric shared memory multi processor SMP By default GHC runs your program
452. urce ts fignore interfac Ignore pragmas in interface de fno ignore inter e pragmas files y face pragmas fomit interfac Don t generate interface fno omit interfa dynamic pragmas pragmas ce pragmas If a worker has that many arguments none will be fmax worker args static E unpacked anymore default 10 oaa Set the number of phases f lif phas Batre ee for the simplifier default dynamic 2 Ignored with 00 fmax simplifier Set the max iterations for A i ee dynamic iterations the simplifier Turn off the state hack whereby any lambda with a real world state token as fno state hack a static argument is considered to be single entry Hence OK to inline things inside it Turn on common fcse sub expression elimination dynamic fno cse Implied by o Turn on full laziness ffull laziness floating bindings dynamic fno full laziness outwards Implied by o The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 98 240 Flag Description Static Dynamic Reverse Switch on all rewrite rules including rules generated frewrite rules by automatic specialisation dynamic fno rewrite rules of overloaded functions Implied by o Turn on strictness analysis 7 fstrictness E dynamic fno strictness Implied by O Turn on the S
453. urrently The runtime system must be initialised as usual by calling hs_init and hs_add_root and these calls must complete before invoking any foreign exported functions 8 2 4 4 On the use of hs_exit hs_exit normally causes the termination of any running Haskell threads in the system and when hs_exit returns there will be no more Haskell threads running The runtime will then shut down the system in an orderly way generating profiling output and statistics if necessary and freeing all the memory it owns It isn t always possible to terminate a Haskell thread forcibly for example the thread might be currently executing a foreign call and we have no way to force the foreign call to complete What s more the runtime must assume that in the worst case the The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 216 240 Haskell code and runtime are about to be removed from memory e g if this is a Windows DLL hs_exit is normally called before unloading the DLL So hs_exit must wait until all outstanding foreign calls return before it can return itself The upshot of this is that if you have Haskell threads that are blocked in foreign calls then hs_exit may hang or possibly busy wait until the calls return Therefore it s a good idea to make sure you don t have any such threads in the system when calling hs_exit This includes any threads doing I O because I O may or may not dep
454. urther breakpoints which are ignored but displayed forward Move forward in the history See Section 2 5 5 See also trace history back help Displays a list of the available commands Repeat the previous command history num Display the history of evaluation steps With a number displays that many steps default 20 For use with trace see Section 2 5 5 info name Displays information about the given name s For example if name is a class then the class methods and their types will be printed if name is a type constructor then its definition will be printed if name is a function then its type will be printed If name has been loaded from a source file then GHCi will also display the location of its definition in the source For types and classes GHCi also summarises instances that mention them To avoid showing irrelevant information an instance is shown only if a its head mentions name and b all the other things mentioned in the instance are in scope either qualified or otherwise as a result of a load or module commands The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 34 240 kind type Infers and prints the kind of type The latter can be an arbitrary type expression including a partial application of a type constructor such as Either Int load module Recursively loads the specified modules and all the modules they depend on Here each module
455. use the preprocessor targets Haskell rather than Core 1et bound variables are monomorphic 7 11 Bang patterns GHC supports an extension of pattern matching called bang patterns written pat Bang patterns are under consideration for Haskell Prime The Haskell prime feature description contains more discussion and examples than the material below The key change is the addition of a new rule to the semantics of pattern matching in the Haskell 98 report Add new bullet 10 saying Matching the pattern pat against a value v behaves as follows e if v is bottom the match diverges e otherwise pat is matched against v Bang patterns are enabled by the flag XBangPatterns 7 11 1 Informal description of bang patterns The main idea is to add a single new production to the syntax of patterns Pate llpat Matching an expression e against a pattern p is done by first evaluating e to WHNF and then matching the result against p Example f1 x True This definition makes f1 is strict in x whereas without the bang it would be lazy Bang patterns can be nested of course BA Ie WA ls Here f2 is strict in x but not in y A bang only really has an effect if it precedes a variable or wild card pattern Es Liew oy 4 x y x y Here 3 and f4 are identical putting a bang before a pattern that forces evaluation anyway does nothing There is one apparent exception to this general rule that a bang only makes a diffe
456. useful Here s the idea Consider the declaration data Foo forall a MkFoo a a gt Bool Nil The data type Foo has two constructors with types MEPOG lt forall lt a a gt lea gt Bool gt BOS Nil 28 FOO Notice that the type variable a in the type of MkFoo does not appear in the data type itself which is plain Foo For example the following expression is fine MkFoo 3 even MkFoo c isUpper Foo Here MkFoo 3 even packages an integer with a function even that maps an integer to Bool andMkFoo c isUp per packages a character with a compatible function These two things are each of type Foo and can be put in a list What can we do with a value of type Foo In particular what happens when we pattern match on MkFoo E MkFoo val tn 272 Since all we know about val and fn is that they are compatible the only useful thing we can do with them is to apply fn to val to get a boolean For example NEO OE OO f MkFoo val fn fn val What this allows us to do is to package heterogeneous values together with a bunch of functions that manipulate them and then treat that collection of packages in a uniform manner You can express quite a bit of object oriented like programming this way 7 4 4 1 Why existential What has this to do with existential quantification Simply that MkFoo has the nearly isomorphic type MKF oO 202 existe a a a gt BOOL gt Poo But Haskell programmers can safely
457. ut the design closely follows that described in the paper Simple unification based type inference for GADTs ICFP 2006 The general principle is this type refinement is only carried out based on user supplied type annotations So if no type signature is supplied for eval no type refinement happens and lots of obscure error messages will occur However the refinement is quite general For example if we had vell 38 Terma gt gt al vall bite 1 3 alae the pattern match causes the type a to be refined to Int because of the type of the constructor Lit and that refinement also applies to the type of j and the result type of the case expression Hence the addition i J is legal These and many other examples are given in papers by Hongwei Xi and Tim Sheard There is a longer introduction on the wiki and Ralf Hinze s Fun with phantom types also has a number of examples Note that papers may use different notation to that implemented in GHC The rest of this section outlines the extensions to GHC that support GADTs The extension is enabled with XGADTs The XGADTs flag also sets XRelaxedPolyRec The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 150 240 A GADT can only be declared using GADT style syntax Section 7 4 5 the old Haskell 98 syntax for data declarations always declares an ordinary data type The result type of each constructor must begin with the type constructor being
458. ut the option enabled There are two classes of special syntax e New reserved words and symbols character sequences which are no longer available for use as identifiers in the program e Other special syntax sequences of characters that have a different meaning when this particular option is turned on The following syntax is stolen forall Stolen in types by XExplicitForAll and hence by XScopedTypeVariables XLiberalTypeS ynonyms XRank2Types XRankNTypes XPolymorphicComponents XExistentialQuantifica tion mdo Stolen by XRecursiveDo foreign Stolen by XForeignFunctionInterface rec proc lt gt lt lt gt gt and brackets Stolen by XArrows varid tvarid Stolen by XImplicitParams l fel pl dl tl varid Stolen by XTemplateHaskell varid Stolen by XQuasiQuotes varid char string integer float float Stolen by XMagicHash The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 141 240 7 4 Extensions to data types and type synonyms 7 4 1 Data types with no constructors With the fglasgow exts flag GHC lets you declare a data type with no constructors For example data S S 88 amp data T a T Ske gt h Syntactically the declaration lacks the constrs part The type can be parameterised over types of any kind but if the kind is not x then an explicit kind annotation must be used
459. version number ghc numeric version Print GHC s numeric version number only ghc print libdir Print the path to GHC s library directory This is the top of the directory tree containing GHC s libraries interfaces and include files usually something like usr local lib ghc 5 04 on Unix This is the value of 1ibdir in the package configuration file see Section 4 8 4 4 1 Using ghc make When given the make option GHC will build a multi module Haskell program by following dependencies from one or more root modules usually just Main For example if your Main module is in a file called Main hs you could compile and link the program like this ghc make Main hs The command line may contain any number of source file names or module names GHC will figure out all the modules in the program by following the imports from these initial modules It will then attempt to compile each module which is out of date and finally if there is a Main module the program will also be linked into an executable The main advantages to using ghc make over traditional Makefi les are e GHC doesn t have to be restarted for each compilation which means it can cache information between compilations Com piling a multi module program with ghc make can be up to twice as fast as running ghc individually on each source file e You don t have to write a Makefile e GHC re calculates the dependencies each time it is invoked s
460. ves the way for future improvements to the way packages are handled For instance in the future we expect to track profiled packages independently of non profiled ones and we hope to make it possible to upgrade a package in an ABI compatible way without recompiling the packages that depend on it This latter facility will be especially important as we move towards using more shared libraries 1 6 2 Language changes The new TupleSections language extension enables tuple sections such as True See Section 7 3 13 for more information The new MonoLocalBinds language extension disables type variable generalisation for bindings in let and where clauses It is now possible to derive instances for GADT datatypes provided the standard instance code is valid for the datatype The new DeriveFunctor DeriveFoldable and DeriveTraversable language extensions enable deriving for the respective type classes See Section 7 5 3 for more information The new NoNPlusKPatterns language extension disables n k patterns See Section 7 3 7 for more information The new ExplicitForAll language extension enables explicit forall s in types See Section 7 8 1 for more information The new DoRec language extension provides new syntax for recursive do notation and the old RecursiveDo language extension has been deprecated See Section 7 3 8 for more information Some improvements have been made to record puns C A a now works expandingtoC A
461. ves you a simple 2 space collector as you would expect In a 2 space collector the A option see above specifies the minimum allocation area size since the allocation area will grow with the amount of live data in the heap In a multi generational collector the allocation area is a fixed size unless you use the H option see below qg gen New in GHC 6 12 1 Default 0 Use parallel GC in generation gen and higher Omitting gen turns off the parallel GC completely reverting to sequential GC The default parallel GC settings are usually suitable for parallel programs i e those using par Strategies or with multiple threads However it is sometimes beneficial to enable the parallel GC for a single threaded sequential program too especially if the program has a large amount of heap data and GC is a significant fraction of runtime To use the parallel GC in a sequential program enable the parallel runtime with a suitable N option and additionally it might be beneficial to restrict parallel GC to the old generation with qg1 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 81 240 qb gen New in GHC 6 12 1 Default 1 Use load balancing in the parallel GC in generation gen and higher Omitting gen disables load balancing entirely Load balancing shares out the work of GC between the available cores This is a good idea when the heap is large and we need to parallelise the GC work however it i
462. ving GHCi the command set r This works because stdin is just a top level expression that can be reverted to its unevaluated state in the same way as any other top level expression CAF I can t use Control C to interrupt computations in GHCi on Windows See Section 11 2 The default buffering mode is different in GHCi to GHC In GHC the stdout handle is line buffered by default However in GHCi we turn off the buffering on stdout because this is normally what you want in an interpreter output appears as it is generated The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 39 240 Chapter 3 Using runghc runghc allows you to run Haskell programs without first having to compile them 3 1 Flags The runghc commandline looks like runghc runghc flags GHC flags module program args The runghc flags are f path to ghc which tells runghc which GHC to use to run the program and help which prints usage information If it is not given then runghc will search for GHC in the directories in the system search path runghc will try to work out where the boundaries between runghc flags and GHC flags and program args and module are but you can use a flag if it doesn t get it right For example runghc fglasgow exts Foo means runghc won t try to use glasgow exts as the path to GHC but instead will pass the flag to GHC If a GHC flag doesn t start with a dash then you need to pre
463. which is just run with different options to provide either the interactive or the batch system The batch compiler can be used alongside GHCi compiled modules can be loaded into an interactive session and used in the same way as interpreted code and in fact when using GHCi most of the library code will be pre compiled This means you get the best of both worlds fast pre compiled library code and fast compile turnaround for the parts of your program being actively developed GHC supports numerous language extensions including concurrency a foreign function interface exceptions type system ex tensions such as multi parameter type classes local universal and existential quantification functional dependencies scoped type variables and explicit unboxed types These are all described in Chapter 7 GHC has a comprehensive optimiser so when you want to Really Go For It and you ve got time to spare GHC can produce pretty fast code Alternatively the default option is to compile as fast as possible while not making too much effort to optimise the generated code although GHC probably isn t what you d describe as a fast compiler GHC s profiling system supports cost centre stacks a way of seeing the profile of a Haskell program in a call graph like structure See Chapter 5 for more details GHC comes with a number of libraries These are described in separate documentation 1 1 Obtaining GHC Go to the GHC home page and fol
464. ws ghc shared o MyDef def See Microsoft documentation for details but a module definition file simply lists what entry points you want to export Here s one that s suitable when building a Haskell COM server DLL EXPORTS D11CanUnloadNow D11CanUnloadNow 0 D11lGetClassObject D1llGetClassObject 12 D1llRegisterServer DllRegisterServer 0 D1lUnregisterServer D1llUnregisterServer 0 e In addition to creating a DLL the shared option also creates an import library The import library name is derived from the name of the DLL as follows Diners Coole CL gt mpare alos His COOH ms cul a The naming scheme may look a bit weird but it has the purpose of allowing the co existence of import libraries with ordinary static libraries e g LibHSfoo a and 1ibHSfoo dll a Additionally when the compiler driver is linking in non static mode it will rewrite occurrence of 1HS foo on the command line to 1HSfoo d11 By doing this for you switching from non static to static linking is simply a question of adding static to your command line 11 6 2 Making DLLs to be called from other languages If you want to package up Haskell code to be called from other languages such as Visual Basic or C there are some extra things it is useful to know This is a special case of Section 8 2 1 2 we ll deal with the DLL specific issues that arise below Here s an example e Use foreign export declarations to export the Haskell f
465. xes to coincide with the class parameters However the latter can lead to more clearly structured code and compiler warnings if some type instances were possibly accidentally omitted In the following we always discuss the general toplevel form first and then cover the additional constraints placed on associated types The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 168 240 7 7 2 1 Type family declarations Indexed type families are introduced by a signature such as type family Elem C x The special family distinguishes family from standard type declarations The result kind annotation is optional and as usual defaults to if omitted An example is type family Elem c Parameters can also be given explicit kind signatures if needed We call the number of parameters in a type family declaration the family s arity and all applications of a type family must be fully saturated w r t to that arity This requirement is unlike ordinary type synonyms and it implies that the kind of a type family is not sufficient to determine a family s arity and hence in general also insufficient to determine whether a type family application is well formed As an example consider the following declaration Eye ieamallly 18 a lo 88 e gt Ws axrity is 2 gt illicinowiejo les Overall cal ais 23 gt 2 gt gt Given this declaration the following are examples of well formed and malf
466. xplicit type signatures Signatures are the basic trick putting them on exported top level functions is good software engineering practice anyway Tip using fwarn missing signatures can help enforce good signature practice The automatic specialisation of overloaded functions with O should take care of overloaded local and or unex ported functions Use SPECIALIZE pragmas Specialize the overloading on key functions in your program See Section 7 13 9 and Sec tion 7 13 10 But how do I know where overloading is creeping in A low tech way grep search your interface files for over loaded type signatures You can view interface files using the show iface option see Section 4 6 7 ghc show iface Foo hi egrep a z gt Strict functions are your dear friends and among other things lazy pattern matching is your enemy If you don t know what a strict function is please consult a functional programming textbook A sentence or two of explanation here probably would not do much good Consider these two code fragments E WMidole lt lt MW goo a Select f arg let Wibble x y arg in lazy The former will result in far better code A less contrived example shows the use of cases instead of let s to get stricter code a good thing f Wibble x y beautiful but slow let al bl cl unpackFoo x a2 b2 c2 unpackFoo y aval ay Qo The Glorious Glasgow
467. xporting modules in the Data hierarchy ghe ekg find module Data list packages exporting Monad modules ghc pkg find module Monadx list names and maintainers for all packages ghc pkg field name maintainer list location of haddock htmls for all packages The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 64 240 ghc pkg field x haddock html dump the whole database ghc pkg describe x Additionally the following flags are accepted by ghc pkg auto ghci libs Automatically generate the GHCi o version of each a Haskell library using GNU ld if that is available Without this option yhc pkg will warn if GHCi versions of any Haskell libraries in the package don t exist GHCi o libraries don t necessarily have to live in the same directory as the corresponding a library However this option will cause the GHCi library to be created in the same directory as the a library f file package conf file Adds file to the stack of package databases Additionally i1e will also be the database modified by a register unregister expose or hide command unless it is overridden by a later package conf user or global option force Causes ghc pkg to ignore missing dependencies directories and libraries when registering a package and just go ahead and add it anyway This might be useful if your package installation system needs to add the packa
468. y nyms synonyms y nonyms XTypeOperators Enable type operators dynamic XNoType0perators i Enabl ive d d i XRecursiveDo ses i ondo dynamic XNoRecursiveDo notation XPArr Enable parallel arrays dynamic XNoPArr XNoRecordWildCar XRecordWildCards Enable record wildcards dynamic ds gt XNamedFieldPuns Enable record puns dynamic XNoNamedFieldPuns XDisambiguateRec Enable record field dynamic XNoDisambiguateR ordFields disambiguation y ecordFields XUnboxedTuples Enable unboxed tuples dynamic XNoUnboxedTuples XStandaloneDeriv dd XNoStandaloneDer Enable standalone deriving dynamic a ing iving XDeriveDataTypea Enable deriving for the i XNoDeriveDataTyp dynamic ble Data and Typeable classes eable XGeneralizedNewt s XNoGeneralizedN ner Enable newtype deriving dynamic fea ypeDeriving wtypeDeriving XTypeSynonyminst Enable type synonyms in XNoTypeSynonymIn dynamic ances instance heads stances r XNoFlexibleCont XFlexibleContexts Enable flexible contexts dynamic es XF ibleI i XNoF 1 ibleInsta exipreTnstane Enable flexible instances dynamic des es nces XConstrainedClas Enable constrained class E XNoConstrainedCl1 dynamic sMethods methods assMethods XMultiParamTypec Enable multi parameter a XNoMultiParamIyp lasses type classes y eClasses XFunctionalDepen Enable functional ds XNoFunctionalDep dencies dependencies y endencies Enable package qualified XPackageImpo
469. y zoptF option pass option to the custom dynamig i pre processor Seer pass option to the C i optc option compiler dynamic optm option pass option to the mangler dynamic ee pass option to the i opta option assembler dynamic optl option pass option to the linker dynamic seueatiepelen pass option to the DLL dani generator optwindres option pass optionto windres dynamic 4 18 24 Platform specific options Section 4 14 Flag Description Static Dynamic Reverse x86 only give some monly 432 regs registers back to the C dynamic compiler 4 18 25 External core file options Section 4 16 The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 102 240 Flag Description Static Dynamic Reverse eae a Generate hcr external dynamic Core files y 4 18 26 Compiler debugging options Section 4 17 Flag Description Static Dynamic Reverse dcore lint Turn on internal sanity ADE _ checking ddump asm Dump assembly dynamic ddump bcos Dump interpreter byte code dynamic ddump cmm Dump C output dynamic D ddump cpranal mp oe AQ RE dynamic analysis ddump cse Dump CSE output dynamic ddump deriv Dump deriving output dynamic ddump ds Dump desugarer output dynamic ddump flatC Dump flat C dynamic D
470. y d gt gt return Prelude gt def mycd mycd Prelude gt mycd Or I could define a simple way to invoke ghc make Main in the current directory Prelude gt def make _ gt return ghc make Main We can define a command that reads GHCi input from a file This might be useful for creating a set of bindings that we want to repeatedly load into the GHCi session Prelude gt def readFile Prelude gt cmds ghci Notice that we named the command by analogy with the Unix shell command that does the same thing Typing def on its own lists the currently defined macros Attempting to redefine an existing command name results in an error unless the def form is used in which case the old command with that name is silently overwritten delete num Delete one or more breakpoints by number use show breaks to see the number of each breakpoint The x form deletes all the breakpoints edit file Opens an editor to edit the file file or the most recently loaded module if file is omitted The editor to invoke is taken from the EDITOR environment variable or a default editor on your system if EDITOR is not set You can change the editor using set editor etags See ctags force identifier Prints the value of identifier in the same way as print Unlike print force evaluates each thunk that it encounters while traversing the value This may cause exceptions or infinite loops or f
471. y to actually increase the size of your program because unfolding generally enables extra simplifying optimisations to be performed Avoid Read Use strip on your executables 6 4 Thriftier producing a program that gobbles less heap space I think I have a space leak Re run your program with RTS S and remove all doubt You ll see the heap usage get bigger and bigger Hmmm this might be even easier with the G1 RTS option so a out RTS S G1 Once again the profiling facilities Chapter 5 are the basic tool for demystifying the space behaviour of your program Strict functions are good for space usage as they are for time as discussed in the previous section Strict functions get right down to business rather than filling up the heap with closures the system s notes to itself about how to evaluate something should it eventually be required The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 125 240 Chapter 7 GHC Language Features As with all known Haskell systems GHC implements some extensions to the language They are all enabled by options by default GHC understands only plain Haskell 98 Some of the Glasgow extensions serve to give you access to the underlying facilities with which we implement Haskell Thus you can get at the Raw Iron if you are willing to write some non portable code at a more primitive level You need not be stuck on performance b
472. y type variable that is in scope is not universally quantified For example if type variable a is in scope then e a gt a means e lt 3 a gt a ee lo gt la means fe forall e gt le sa gt 10 means le lt 2 orall hb a gt b The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 180 240 7 8 7 2 Declaration type signatures A declaration type signature that has explicit quantification using forall brings into scope the explicitly quantified type variables in the definition of the named function For example E 23 oredl ss lal gt ial se eai ox cob Tox SS non The forall a brings a into scope in the definition of f This only happens if e The quantification in f s type signature is explicit For example g es lal gt Tal G sza Ses ar Loc BS e 1 This program will be rejected because a does not scope over the definition of f so x a means x forall a a by Haskell s usual implicit quantification rules e The signature gives a type for a function binding or a bare variable binding not a pattern binding For example ii 93 roren es iall ia ied ERS IS r XI OK in 43 corall es fell gt a La N aS gt S Ss SR a OK TS 23 corall er leal gt a duer ES Juste MESS 38 e os 88 a 1 Not OK The binding for 3 is a pattern binding and so its type signature does not bring a into scope H
473. ynamically bound variable x of type t For example the following expresses the type of a sort function implicitly parameterized by a comparison function named cmp aort 82 zewg 838 a a gt Bool al Tal The dynamic binding constraints are just a new form of predicate in the type class system An implicit parameter occurs in an expression using the special form x where x is any valid identifier e g ord xisa valid expression Use of this construct also introduces a new dynamic binding constraint in the type of the expression For example the following definition shows how we can define an implicitly parameterized sort function in terms of an explicitly parameterized sort By function SOREEY s A gt a gt Bool gt al gt lal SO 38 Penis 238 a gt a gt Bool gt fal gt al sore SOS YC The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 173 240 7 8 3 1 Implicit parameter type constraints Dynamic binding constraints behave just like other type class constraints in that they are automatically propagated Thus when a function is used its implicit parameters are inherited by the function that called it For example our sort function might be used to pick out the least value in a list least 28 Sens 88 gt a gt Bool gt el gt a least xs head sort xs Without lifting a finger the cmp parameter is propagated to become a parameter of least as we
474. ype you can write your for alls explicitly Indeed doing so is strongly advised for rank 2 types 7 8 6 Impredicative polymorphism NOTE the impredicative polymorphism feature is deprecated in GHC 6 12 and will be removed or replaced in GHC 6 14 GHC supports impredicative polymorphism enabled with XImpredicativeTypes This means that you can call a poly morphic function at a polymorphic type and parameterise data structures over polymorphic types For example EEES Maybe tor alias Maybe tinto Chas ASA dust SAA CoN f Nothing Nothing The Glorious Glasgow Haskell Compilation System User s Guide Version 6 12 2 179 240 Notice here that the Maybe type is parameterised by the polymorphic type forall a a gt a The technical details of this extension are described in the paper Boxy types type inference for higher rank types and impred icativity which appeared at ICFP 2006 7 8 7 Lexically scoped type variables GHC supports lexically scoped type variables without which some type signatures are simply impossible to write For example ss forall e lal gt Tal AS SS where ye 3 le ys reverse xs The type signature for f brings the type variable a into scope because of the explicit forall Section 7 8 7 2 The type variables bound by a forall scope over the entire definition of the accompanying value declaration In this example the type variable a scopes over the whole definition of including
Download Pdf Manuals
Related Search
Related Contents
KX-TD816 Model KX-TD1232 Programming Guide La lutte contre le gaspillage un enjeu économique majeur pour les Samsung SGH-B520 Lietotāja rokasgrāmata Control Remoto Mediante Comunicaciones TCP/IP de Radioayudas SCXI-1520 User Manual ELR96 Earth Leakage Relay User'S Guide Kensington K38037US Samsung SWT50B3 دليل المستخدم Copyright © All rights reserved.
Failed to retrieve file