Follow changes in comparison primops (see #6135)
[ghc.git] / libraries / template-haskell / Language / Haskell / TH / Syntax.hs
1 {-# LANGUAGE UnboxedTuples #-}
2
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module : Language.Haskell.Syntax
6 -- Copyright : (c) The University of Glasgow 2003
7 -- License : BSD-style (see the file libraries/base/LICENSE)
8 --
9 -- Maintainer : libraries@haskell.org
10 -- Stability : experimental
11 -- Portability : portable
12 --
13 -- Abstract syntax definitions for Template Haskell.
14 --
15 -----------------------------------------------------------------------------
16
17 module Language.Haskell.TH.Syntax where
18
19 import GHC.Exts
20 import Data.Data (Data(..), Typeable, mkConstr, mkDataType, constrIndex)
21 import qualified Data.Data as Data
22 import Control.Applicative( Applicative(..) )
23 import Data.IORef
24 import System.IO.Unsafe ( unsafePerformIO )
25 import Control.Monad (liftM)
26 import System.IO ( hPutStrLn, stderr )
27 import Data.Char ( isAlpha )
28 import Data.Word ( Word8 )
29
30 -----------------------------------------------------
31 --
32 -- The Quasi class
33 --
34 -----------------------------------------------------
35
36 class (Monad m, Applicative m) => Quasi m where
37 qNewName :: String -> m Name
38 -- ^ Fresh names
39
40 -- Error reporting and recovery
41 qReport :: Bool -> String -> m () -- ^ Report an error (True) or warning (False)
42 -- ...but carry on; use 'fail' to stop
43 qRecover :: m a -- ^ the error handler
44 -> m a -- ^ action which may fail
45 -> m a -- ^ Recover from the monadic 'fail'
46
47 -- Inspect the type-checker's environment
48 qLookupName :: Bool -> String -> m (Maybe Name)
49 -- True <=> type namespace, False <=> value namespace
50 qReify :: Name -> m Info
51 qReifyInstances :: Name -> [Type] -> m [Dec]
52 -- Is (n tys) an instance?
53 -- Returns list of matching instance Decs
54 -- (with empty sub-Decs)
55 -- Works for classes and type functions
56 qReifyRoles :: Name -> m [Role]
57
58 qLocation :: m Loc
59
60 qRunIO :: IO a -> m a
61 -- ^ Input/output (dangerous)
62
63 qAddDependentFile :: FilePath -> m ()
64
65 -----------------------------------------------------
66 -- The IO instance of Quasi
67 --
68 -- This instance is used only when running a Q
69 -- computation in the IO monad, usually just to
70 -- print the result. There is no interesting
71 -- type environment, so reification isn't going to
72 -- work.
73 --
74 -----------------------------------------------------
75
76 instance Quasi IO where
77 qNewName s = do { n <- readIORef counter
78 ; writeIORef counter (n+1)
79 ; return (mkNameU s n) }
80
81 qReport True msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
82 qReport False msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
83
84 qLookupName _ _ = badIO "lookupName"
85 qReify _ = badIO "reify"
86 qReifyInstances _ _ = badIO "classInstances"
87 qReifyRoles _ = badIO "reifyRoles"
88 qLocation = badIO "currentLocation"
89 qRecover _ _ = badIO "recover" -- Maybe we could fix this?
90 qAddDependentFile _ = badIO "addDependentFile"
91
92 qRunIO m = m
93
94 badIO :: String -> IO a
95 badIO op = do { qReport True ("Can't do `" ++ op ++ "' in the IO monad")
96 ; fail "Template Haskell failure" }
97
98 -- Global variable to generate unique symbols
99 counter :: IORef Int
100 {-# NOINLINE counter #-}
101 counter = unsafePerformIO (newIORef 0)
102
103
104 -----------------------------------------------------
105 --
106 -- The Q monad
107 --
108 -----------------------------------------------------
109
110 newtype Q a = Q { unQ :: forall m. Quasi m => m a }
111
112 -- \"Runs\" the 'Q' monad. Normal users of Template Haskell
113 -- should not need this function, as the splice brackets @$( ... )@
114 -- are the usual way of running a 'Q' computation.
115 --
116 -- This function is primarily used in GHC internals, and for debugging
117 -- splices by running them in 'IO'.
118 --
119 -- Note that many functions in 'Q', such as 'reify' and other compiler
120 -- queries, are not supported when running 'Q' in 'IO'; these operations
121 -- simply fail at runtime. Indeed, the only operations guaranteed to succeed
122 -- are 'newName', 'runIO', 'reportError' and 'reportWarning'.
123 runQ :: Quasi m => Q a -> m a
124 runQ (Q m) = m
125
126 instance Monad Q where
127 return x = Q (return x)
128 Q m >>= k = Q (m >>= \x -> unQ (k x))
129 Q m >> Q n = Q (m >> n)
130 fail s = report True s >> Q (fail "Q monad failure")
131
132 instance Functor Q where
133 fmap f (Q x) = Q (fmap f x)
134
135 instance Applicative Q where
136 pure x = Q (pure x)
137 Q f <*> Q x = Q (f <*> x)
138
139 ----------------------------------------------------
140 -- Packaged versions for the programmer, hiding the Quasi-ness
141
142 {- |
143 Generate a fresh name, which cannot be captured.
144
145 For example, this:
146
147 @f = $(do
148 nm1 <- newName \"x\"
149 let nm2 = 'mkName' \"x\"
150 return ('LamE' ['VarP' nm1] (LamE [VarP nm2] ('VarE' nm1)))
151 )@
152
153 will produce the splice
154
155 >f = \x0 -> \x -> x0
156
157 In particular, the occurrence @VarE nm1@ refers to the binding @VarP nm1@,
158 and is not captured by the binding @VarP nm2@.
159
160 Although names generated by @newName@ cannot /be captured/, they can
161 /capture/ other names. For example, this:
162
163 >g = $(do
164 > nm1 <- newName "x"
165 > let nm2 = mkName "x"
166 > return (LamE [VarP nm2] (LamE [VarP nm1] (VarE nm2)))
167 > )
168
169 will produce the splice
170
171 >g = \x -> \x0 -> x0
172
173 since the occurrence @VarE nm2@ is captured by the innermost binding
174 of @x@, namely @VarP nm1@.
175 -}
176 newName :: String -> Q Name
177 newName s = Q (qNewName s)
178
179 -- | Report an error (True) or warning (False),
180 -- but carry on; use 'fail' to stop.
181 report :: Bool -> String -> Q ()
182 report b s = Q (qReport b s)
183 {-# DEPRECATED report "Use reportError or reportWarning instead" #-} -- deprecated in 7.6
184
185 -- | Report an error to the user, but allow the current splice's computation to carry on. To abort the computation, use 'fail'.
186 reportError :: String -> Q ()
187 reportError = report True
188
189 -- | Report a warning to the user, and carry on.
190 reportWarning :: String -> Q ()
191 reportWarning = report False
192
193 -- | Recover from errors raised by 'reportError' or 'fail'.
194 recover :: Q a -- ^ handler to invoke on failure
195 -> Q a -- ^ computation to run
196 -> Q a
197 recover (Q r) (Q m) = Q (qRecover r m)
198
199 -- We don't export lookupName; the Bool isn't a great API
200 -- Instead we export lookupTypeName, lookupValueName
201 lookupName :: Bool -> String -> Q (Maybe Name)
202 lookupName ns s = Q (qLookupName ns s)
203
204 -- | Look up the given name in the (type namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
205 lookupTypeName :: String -> Q (Maybe Name)
206 lookupTypeName s = Q (qLookupName True s)
207
208 -- | Look up the given name in the (value namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
209 lookupValueName :: String -> Q (Maybe Name)
210 lookupValueName s = Q (qLookupName False s)
211
212 {-
213 Note [Name lookup]
214 ~~~~~~~~~~~~~~~~~~
215 -}
216 {- $namelookup #namelookup#
217 The functions 'lookupTypeName' and 'lookupValueName' provide
218 a way to query the current splice's context for what names
219 are in scope. The function 'lookupTypeName' queries the type
220 namespace, whereas 'lookupValueName' queries the value namespace,
221 but the functions are otherwise identical.
222
223 A call @lookupValueName s@ will check if there is a value
224 with name @s@ in scope at the current splice's location. If
225 there is, the @Name@ of this value is returned;
226 if not, then @Nothing@ is returned.
227
228 The returned name cannot be \"captured\".
229 For example:
230
231 > f = "global"
232 > g = $( do
233 > Just nm <- lookupValueName "f"
234 > [| let f = "local" in $( varE nm ) |]
235
236 In this case, @g = \"global\"@; the call to @lookupValueName@
237 returned the global @f@, and this name was /not/ captured by
238 the local definition of @f@.
239
240 The lookup is performed in the context of the /top-level/ splice
241 being run. For example:
242
243 > f = "global"
244 > g = $( [| let f = "local" in
245 > $(do
246 > Just nm <- lookupValueName "f"
247 > varE nm
248 > ) |] )
249
250 Again in this example, @g = \"global\"@, because the call to
251 @lookupValueName@ queries the context of the outer-most @$(...)@.
252
253 Operators should be queried without any surrounding parentheses, like so:
254
255 > lookupValueName "+"
256
257 Qualified names are also supported, like so:
258
259 > lookupValueName "Prelude.+"
260 > lookupValueName "Prelude.map"
261
262 -}
263
264
265 {- | 'reify' looks up information about the 'Name'.
266
267 It is sometimes useful to construct the argument name using 'lookupTypeName' or 'lookupValueName'
268 to ensure that we are reifying from the right namespace. For instance, in this context:
269
270 > data D = D
271
272 which @D@ does @reify (mkName \"D\")@ return information about? (Answer: @D@-the-type, but don't rely on it.)
273 To ensure we get information about @D@-the-value, use 'lookupValueName':
274
275 > do
276 > Just nm <- lookupValueName "D"
277 > reify nm
278
279 and to get information about @D@-the-type, use 'lookupTypeName'.
280 -}
281 reify :: Name -> Q Info
282 reify v = Q (qReify v)
283
284 {- | @reifyInstances nm tys@ returns a list of visible instances of @nm tys@. That is,
285 if @nm@ is the name of a type class, then all instances of this class at the types @tys@
286 are returned. Alternatively, if @nm@ is the name of a data family or type family,
287 all instances of this family at the types @tys@ are returned.
288 -}
289 reifyInstances :: Name -> [Type] -> Q [InstanceDec]
290 reifyInstances cls tys = Q (qReifyInstances cls tys)
291
292 {- | @reifyRoles nm@ returns the list of roles associated with the parameters of
293 the tycon @nm@. Fails if @nm@ cannot be found or is not a tycon.
294 The returned list should never contain 'InferR'.
295 -}
296 reifyRoles :: Name -> Q [Role]
297 reifyRoles nm = Q (qReifyRoles nm)
298
299 -- | Is the list of instances returned by 'reifyInstances' nonempty?
300 isInstance :: Name -> [Type] -> Q Bool
301 isInstance nm tys = do { decs <- reifyInstances nm tys
302 ; return (not (null decs)) }
303
304 -- | The location at which this computation is spliced.
305 location :: Q Loc
306 location = Q qLocation
307
308 -- |The 'runIO' function lets you run an I\/O computation in the 'Q' monad.
309 -- Take care: you are guaranteed the ordering of calls to 'runIO' within
310 -- a single 'Q' computation, but not about the order in which splices are run.
311 --
312 -- Note: for various murky reasons, stdout and stderr handles are not
313 -- necesarily flushed when the compiler finishes running, so you should
314 -- flush them yourself.
315 runIO :: IO a -> Q a
316 runIO m = Q (qRunIO m)
317
318 -- | Record external files that runIO is using (dependent upon).
319 -- The compiler can then recognize that it should re-compile the file using this TH when the external file changes.
320 -- Note that ghc -M will still not know about these dependencies - it does not execute TH.
321 -- Expects an absolute file path.
322 addDependentFile :: FilePath -> Q ()
323 addDependentFile fp = Q (qAddDependentFile fp)
324
325 instance Quasi Q where
326 qNewName = newName
327 qReport = report
328 qRecover = recover
329 qReify = reify
330 qReifyInstances = reifyInstances
331 qReifyRoles = reifyRoles
332 qLookupName = lookupName
333 qLocation = location
334 qRunIO = runIO
335 qAddDependentFile = addDependentFile
336
337
338 ----------------------------------------------------
339 -- The following operations are used solely in DsMeta when desugaring brackets
340 -- They are not necessary for the user, who can use ordinary return and (>>=) etc
341
342 returnQ :: a -> Q a
343 returnQ = return
344
345 bindQ :: Q a -> (a -> Q b) -> Q b
346 bindQ = (>>=)
347
348 sequenceQ :: [Q a] -> Q [a]
349 sequenceQ = sequence
350
351
352 -----------------------------------------------------
353 --
354 -- The Lift class
355 --
356 -----------------------------------------------------
357
358 class Lift t where
359 lift :: t -> Q Exp
360
361 instance Lift Integer where
362 lift x = return (LitE (IntegerL x))
363
364 instance Lift Int where
365 lift x= return (LitE (IntegerL (fromIntegral x)))
366
367 instance Lift Char where
368 lift x = return (LitE (CharL x))
369
370 instance Lift Bool where
371 lift True = return (ConE trueName)
372 lift False = return (ConE falseName)
373
374 instance Lift a => Lift (Maybe a) where
375 lift Nothing = return (ConE nothingName)
376 lift (Just x) = liftM (ConE justName `AppE`) (lift x)
377
378 instance (Lift a, Lift b) => Lift (Either a b) where
379 lift (Left x) = liftM (ConE leftName `AppE`) (lift x)
380 lift (Right y) = liftM (ConE rightName `AppE`) (lift y)
381
382 instance Lift a => Lift [a] where
383 lift xs = do { xs' <- mapM lift xs; return (ListE xs') }
384
385 liftString :: String -> Q Exp
386 -- Used in TcExpr to short-circuit the lifting for strings
387 liftString s = return (LitE (StringL s))
388
389 instance (Lift a, Lift b) => Lift (a, b) where
390 lift (a, b)
391 = liftM TupE $ sequence [lift a, lift b]
392
393 instance (Lift a, Lift b, Lift c) => Lift (a, b, c) where
394 lift (a, b, c)
395 = liftM TupE $ sequence [lift a, lift b, lift c]
396
397 instance (Lift a, Lift b, Lift c, Lift d) => Lift (a, b, c, d) where
398 lift (a, b, c, d)
399 = liftM TupE $ sequence [lift a, lift b, lift c, lift d]
400
401 instance (Lift a, Lift b, Lift c, Lift d, Lift e)
402 => Lift (a, b, c, d, e) where
403 lift (a, b, c, d, e)
404 = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e]
405
406 instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f)
407 => Lift (a, b, c, d, e, f) where
408 lift (a, b, c, d, e, f)
409 = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f]
410
411 instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f, Lift g)
412 => Lift (a, b, c, d, e, f, g) where
413 lift (a, b, c, d, e, f, g)
414 = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f, lift g]
415
416 -- TH has a special form for literal strings,
417 -- which we should take advantage of.
418 -- NB: the lhs of the rule has no args, so that
419 -- the rule will apply to a 'lift' all on its own
420 -- which happens to be the way the type checker
421 -- creates it.
422 {-# RULES "TH:liftString" lift = \s -> return (LitE (StringL s)) #-}
423
424
425 trueName, falseName :: Name
426 trueName = mkNameG DataName "ghc-prim" "GHC.Types" "True"
427 falseName = mkNameG DataName "ghc-prim" "GHC.Types" "False"
428
429 nothingName, justName :: Name
430 nothingName = mkNameG DataName "base" "Data.Maybe" "Nothing"
431 justName = mkNameG DataName "base" "Data.Maybe" "Just"
432
433 leftName, rightName :: Name
434 leftName = mkNameG DataName "base" "Data.Either" "Left"
435 rightName = mkNameG DataName "base" "Data.Either" "Right"
436
437
438 -----------------------------------------------------
439 -- Names and uniques
440 -----------------------------------------------------
441
442 newtype ModName = ModName String -- Module name
443 deriving (Eq,Ord,Typeable,Data)
444
445 newtype PkgName = PkgName String -- package name
446 deriving (Eq,Ord,Typeable,Data)
447
448 newtype OccName = OccName String
449 deriving (Eq,Ord,Typeable,Data)
450
451 mkModName :: String -> ModName
452 mkModName s = ModName s
453
454 modString :: ModName -> String
455 modString (ModName m) = m
456
457
458 mkPkgName :: String -> PkgName
459 mkPkgName s = PkgName s
460
461 pkgString :: PkgName -> String
462 pkgString (PkgName m) = m
463
464
465 -----------------------------------------------------
466 -- OccName
467 -----------------------------------------------------
468
469 mkOccName :: String -> OccName
470 mkOccName s = OccName s
471
472 occString :: OccName -> String
473 occString (OccName occ) = occ
474
475
476 -----------------------------------------------------
477 -- Names
478 -----------------------------------------------------
479 --
480 -- For "global" names ('NameG') we need a totally unique name,
481 -- so we must include the name-space of the thing
482 --
483 -- For unique-numbered things ('NameU'), we've got a unique reference
484 -- anyway, so no need for name space
485 --
486 -- For dynamically bound thing ('NameS') we probably want them to
487 -- in a context-dependent way, so again we don't want the name
488 -- space. For example:
489 --
490 -- > let v = mkName "T" in [| data $v = $v |]
491 --
492 -- Here we use the same Name for both type constructor and data constructor
493 --
494 --
495 -- NameL and NameG are bound *outside* the TH syntax tree
496 -- either globally (NameG) or locally (NameL). Ex:
497 --
498 -- > f x = $(h [| (map, x) |])
499 --
500 -- The 'map' will be a NameG, and 'x' wil be a NameL
501 --
502 -- These Names should never appear in a binding position in a TH syntax tree
503
504 {- $namecapture #namecapture#
505 Much of 'Name' API is concerned with the problem of /name capture/, which
506 can be seen in the following example.
507
508 > f expr = [| let x = 0 in $expr |]
509 > ...
510 > g x = $( f [| x |] )
511 > h y = $( f [| y |] )
512
513 A naive desugaring of this would yield:
514
515 > g x = let x = 0 in x
516 > h y = let x = 0 in y
517
518 All of a sudden, @g@ and @h@ have different meanings! In this case,
519 we say that the @x@ in the RHS of @g@ has been /captured/
520 by the binding of @x@ in @f@.
521
522 What we actually want is for the @x@ in @f@ to be distinct from the
523 @x@ in @g@, so we get the following desugaring:
524
525 > g x = let x' = 0 in x
526 > h y = let x' = 0 in y
527
528 which avoids name capture as desired.
529
530 In the general case, we say that a @Name@ can be captured if
531 the thing it refers to can be changed by adding new declarations.
532 -}
533
534 {- |
535 An abstract type representing names in the syntax tree.
536
537 'Name's can be constructed in several ways, which come with different
538 name-capture guarantees (see "Language.Haskell.TH.Syntax#namecapture" for
539 an explanation of name capture):
540
541 * the built-in syntax @'f@ and @''T@ can be used to construct names,
542 The expression @'f@ gives a @Name@ which refers to the value @f@
543 currently in scope, and @''T@ gives a @Name@ which refers to the
544 type @T@ currently in scope. These names can never be captured.
545
546 * 'lookupValueName' and 'lookupTypeName' are similar to @'f@ and
547 @''T@ respectively, but the @Name@s are looked up at the point
548 where the current splice is being run. These names can never be
549 captured.
550
551 * 'newName' monadically generates a new name, which can never
552 be captured.
553
554 * 'mkName' generates a capturable name.
555
556 Names constructed using @newName@ and @mkName@ may be used in bindings
557 (such as @let x = ...@ or @\x -> ...@), but names constructed using
558 @lookupValueName@, @lookupTypeName@, @'f@, @''T@ may not.
559 -}
560 data Name = Name OccName NameFlavour deriving (Typeable, Data)
561
562 data NameFlavour
563 = NameS -- ^ An unqualified name; dynamically bound
564 | NameQ ModName -- ^ A qualified name; dynamically bound
565 | NameU Int# -- ^ A unique local name
566 | NameL Int# -- ^ Local name bound outside of the TH AST
567 | NameG NameSpace PkgName ModName -- ^ Global name bound outside of the TH AST:
568 -- An original name (occurrences only, not binders)
569 -- Need the namespace too to be sure which
570 -- thing we are naming
571 deriving ( Typeable )
572
573 -- |
574 -- Although the NameFlavour type is abstract, the Data instance is not. The reason for this
575 -- is that currently we use Data to serialize values in annotations, and in order for that to
576 -- work for Template Haskell names introduced via the 'x syntax we need gunfold on NameFlavour
577 -- to work. Bleh!
578 --
579 -- The long term solution to this is to use the binary package for annotation serialization and
580 -- then remove this instance. However, to do _that_ we need to wait on binary to become stable, since
581 -- boot libraries cannot be upgraded separately from GHC itself.
582 --
583 -- This instance cannot be derived automatically due to bug #2701
584 instance Data NameFlavour where
585 gfoldl _ z NameS = z NameS
586 gfoldl k z (NameQ mn) = z NameQ `k` mn
587 gfoldl k z (NameU i) = z (\(I# i') -> NameU i') `k` (I# i)
588 gfoldl k z (NameL i) = z (\(I# i') -> NameL i') `k` (I# i)
589 gfoldl k z (NameG ns p m) = z NameG `k` ns `k` p `k` m
590 gunfold k z c = case constrIndex c of
591 1 -> z NameS
592 2 -> k $ z NameQ
593 3 -> k $ z (\(I# i) -> NameU i)
594 4 -> k $ z (\(I# i) -> NameL i)
595 5 -> k $ k $ k $ z NameG
596 _ -> error "gunfold: NameFlavour"
597 toConstr NameS = con_NameS
598 toConstr (NameQ _) = con_NameQ
599 toConstr (NameU _) = con_NameU
600 toConstr (NameL _) = con_NameL
601 toConstr (NameG _ _ _) = con_NameG
602 dataTypeOf _ = ty_NameFlavour
603
604 con_NameS, con_NameQ, con_NameU, con_NameL, con_NameG :: Data.Constr
605 con_NameS = mkConstr ty_NameFlavour "NameS" [] Data.Prefix
606 con_NameQ = mkConstr ty_NameFlavour "NameQ" [] Data.Prefix
607 con_NameU = mkConstr ty_NameFlavour "NameU" [] Data.Prefix
608 con_NameL = mkConstr ty_NameFlavour "NameL" [] Data.Prefix
609 con_NameG = mkConstr ty_NameFlavour "NameG" [] Data.Prefix
610
611 ty_NameFlavour :: Data.DataType
612 ty_NameFlavour = mkDataType "Language.Haskell.TH.Syntax.NameFlavour"
613 [con_NameS, con_NameQ, con_NameU,
614 con_NameL, con_NameG]
615
616 data NameSpace = VarName -- ^ Variables
617 | DataName -- ^ Data constructors
618 | TcClsName -- ^ Type constructors and classes; Haskell has them
619 -- in the same name space for now.
620 deriving( Eq, Ord, Data, Typeable )
621
622 type Uniq = Int
623
624 -- | The name without its module prefix
625 nameBase :: Name -> String
626 nameBase (Name occ _) = occString occ
627
628 -- | Module prefix of a name, if it exists
629 nameModule :: Name -> Maybe String
630 nameModule (Name _ (NameQ m)) = Just (modString m)
631 nameModule (Name _ (NameG _ _ m)) = Just (modString m)
632 nameModule _ = Nothing
633
634 {- |
635 Generate a capturable name. Occurrences of such names will be
636 resolved according to the Haskell scoping rules at the occurrence
637 site.
638
639 For example:
640
641 > f = [| pi + $(varE (mkName "pi")) |]
642 > ...
643 > g = let pi = 3 in $f
644
645 In this case, @g@ is desugared to
646
647 > g = Prelude.pi + 3
648
649 Note that @mkName@ may be used with qualified names:
650
651 > mkName "Prelude.pi"
652
653 See also 'Language.Haskell.TH.Lib.dyn' for a useful combinator. The above example could
654 be rewritten using 'dyn' as
655
656 > f = [| pi + $(dyn "pi") |]
657 -}
658 mkName :: String -> Name
659 -- The string can have a '.', thus "Foo.baz",
660 -- giving a dynamically-bound qualified name,
661 -- in which case we want to generate a NameQ
662 --
663 -- Parse the string to see if it has a "." in it
664 -- so we know whether to generate a qualified or unqualified name
665 -- It's a bit tricky because we need to parse
666 --
667 -- > Foo.Baz.x as Qual Foo.Baz x
668 --
669 -- So we parse it from back to front
670 mkName str
671 = split [] (reverse str)
672 where
673 split occ [] = Name (mkOccName occ) NameS
674 split occ ('.':rev) | not (null occ),
675 not (null rev), head rev /= '.'
676 = Name (mkOccName occ) (NameQ (mkModName (reverse rev)))
677 -- The 'not (null occ)' guard ensures that
678 -- mkName "&." = Name "&." NameS
679 -- The 'rev' guards ensure that
680 -- mkName ".&" = Name ".&" NameS
681 -- mkName "Data.Bits..&" = Name ".&" (NameQ "Data.Bits")
682 -- This rather bizarre case actually happened; (.&.) is in Data.Bits
683 split occ (c:rev) = split (c:occ) rev
684
685 -- | Only used internally
686 mkNameU :: String -> Uniq -> Name
687 mkNameU s (I# u) = Name (mkOccName s) (NameU u)
688
689 -- | Only used internally
690 mkNameL :: String -> Uniq -> Name
691 mkNameL s (I# u) = Name (mkOccName s) (NameL u)
692
693 -- | Used for 'x etc, but not available to the programmer
694 mkNameG :: NameSpace -> String -> String -> String -> Name
695 mkNameG ns pkg modu occ
696 = Name (mkOccName occ) (NameG ns (mkPkgName pkg) (mkModName modu))
697
698 mkNameG_v, mkNameG_tc, mkNameG_d :: String -> String -> String -> Name
699 mkNameG_v = mkNameG VarName
700 mkNameG_tc = mkNameG TcClsName
701 mkNameG_d = mkNameG DataName
702
703 instance Eq Name where
704 v1 == v2 = cmpEq (v1 `compare` v2)
705
706 instance Ord Name where
707 (Name o1 f1) `compare` (Name o2 f2) = (f1 `compare` f2) `thenCmp`
708 (o1 `compare` o2)
709
710 instance Eq NameFlavour where
711 f1 == f2 = cmpEq (f1 `compare` f2)
712
713 instance Ord NameFlavour where
714 -- NameS < NameQ < NameU < NameL < NameG
715 NameS `compare` NameS = EQ
716 NameS `compare` _ = LT
717
718 (NameQ _) `compare` NameS = GT
719 (NameQ m1) `compare` (NameQ m2) = m1 `compare` m2
720 (NameQ _) `compare` _ = LT
721
722 (NameU _) `compare` NameS = GT
723 (NameU _) `compare` (NameQ _) = GT
724 (NameU u1) `compare` (NameU u2) | isTrue# (u1 <# u2) = LT
725 | isTrue# (u1 ==# u2) = EQ
726 | otherwise = GT
727 (NameU _) `compare` _ = LT
728
729 (NameL _) `compare` NameS = GT
730 (NameL _) `compare` (NameQ _) = GT
731 (NameL _) `compare` (NameU _) = GT
732 (NameL u1) `compare` (NameL u2) | isTrue# (u1 <# u2) = LT
733 | isTrue# (u1 ==# u2) = EQ
734 | otherwise = GT
735 (NameL _) `compare` _ = LT
736
737 (NameG ns1 p1 m1) `compare` (NameG ns2 p2 m2) = (ns1 `compare` ns2) `thenCmp`
738 (p1 `compare` p2) `thenCmp`
739 (m1 `compare` m2)
740 (NameG _ _ _) `compare` _ = GT
741
742 data NameIs = Alone | Applied | Infix
743
744 showName :: Name -> String
745 showName = showName' Alone
746
747 showName' :: NameIs -> Name -> String
748 showName' ni nm
749 = case ni of
750 Alone -> nms
751 Applied
752 | pnam -> nms
753 | otherwise -> "(" ++ nms ++ ")"
754 Infix
755 | pnam -> "`" ++ nms ++ "`"
756 | otherwise -> nms
757 where
758 -- For now, we make the NameQ and NameG print the same, even though
759 -- NameQ is a qualified name (so what it means depends on what the
760 -- current scope is), and NameG is an original name (so its meaning
761 -- should be independent of what's in scope.
762 -- We may well want to distinguish them in the end.
763 -- Ditto NameU and NameL
764 nms = case nm of
765 Name occ NameS -> occString occ
766 Name occ (NameQ m) -> modString m ++ "." ++ occString occ
767 Name occ (NameG _ _ m) -> modString m ++ "." ++ occString occ
768 Name occ (NameU u) -> occString occ ++ "_" ++ show (I# u)
769 Name occ (NameL u) -> occString occ ++ "_" ++ show (I# u)
770
771 pnam = classify nms
772
773 -- True if we are function style, e.g. f, [], (,)
774 -- False if we are operator style, e.g. +, :+
775 classify "" = False -- shouldn't happen; . operator is handled below
776 classify (x:xs) | isAlpha x || (x `elem` "_[]()") =
777 case dropWhile (/='.') xs of
778 (_:xs') -> classify xs'
779 [] -> True
780 | otherwise = False
781
782 instance Show Name where
783 show = showName
784
785 -- Tuple data and type constructors
786 -- | Tuple data constructor
787 tupleDataName :: Int -> Name
788 -- | Tuple type constructor
789 tupleTypeName :: Int -> Name
790
791 tupleDataName 0 = mk_tup_name 0 DataName
792 tupleDataName 1 = error "tupleDataName 1"
793 tupleDataName n = mk_tup_name (n-1) DataName
794
795 tupleTypeName 0 = mk_tup_name 0 TcClsName
796 tupleTypeName 1 = error "tupleTypeName 1"
797 tupleTypeName n = mk_tup_name (n-1) TcClsName
798
799 mk_tup_name :: Int -> NameSpace -> Name
800 mk_tup_name n_commas space
801 = Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
802 where
803 occ = mkOccName ('(' : replicate n_commas ',' ++ ")")
804 tup_mod = mkModName "GHC.Tuple"
805
806 -- Unboxed tuple data and type constructors
807 -- | Unboxed tuple data constructor
808 unboxedTupleDataName :: Int -> Name
809 -- | Unboxed tuple type constructor
810 unboxedTupleTypeName :: Int -> Name
811
812 unboxedTupleDataName 0 = error "unboxedTupleDataName 0"
813 unboxedTupleDataName 1 = error "unboxedTupleDataName 1"
814 unboxedTupleDataName n = mk_unboxed_tup_name (n-1) DataName
815
816 unboxedTupleTypeName 0 = error "unboxedTupleTypeName 0"
817 unboxedTupleTypeName 1 = error "unboxedTupleTypeName 1"
818 unboxedTupleTypeName n = mk_unboxed_tup_name (n-1) TcClsName
819
820 mk_unboxed_tup_name :: Int -> NameSpace -> Name
821 mk_unboxed_tup_name n_commas space
822 = Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
823 where
824 occ = mkOccName ("(#" ++ replicate n_commas ',' ++ "#)")
825 tup_mod = mkModName "GHC.Tuple"
826
827
828
829 -----------------------------------------------------
830 -- Locations
831 -----------------------------------------------------
832
833 data Loc
834 = Loc { loc_filename :: String
835 , loc_package :: String
836 , loc_module :: String
837 , loc_start :: CharPos
838 , loc_end :: CharPos }
839
840 type CharPos = (Int, Int) -- ^ Line and character position
841
842
843 -----------------------------------------------------
844 --
845 -- The Info returned by reification
846 --
847 -----------------------------------------------------
848
849 -- | Obtained from 'reify' in the 'Q' Monad.
850 data Info
851 =
852 -- | A class, with a list of its visible instances
853 ClassI
854 Dec
855 [InstanceDec]
856
857 -- | A class method
858 | ClassOpI
859 Name
860 Type
861 ParentName
862 Fixity
863
864 -- | A \"plain\" type constructor. \"Fancier\" type constructors are returned using 'PrimTyConI' or 'FamilyI' as appropriate
865 | TyConI
866 Dec
867
868 -- | A type or data family, with a list of its visible instances. A closed
869 -- type family is returned with 0 instances.
870 | FamilyI
871 Dec
872 [InstanceDec]
873
874 -- | A \"primitive\" type constructor, which can't be expressed with a 'Dec'. Examples: @(->)@, @Int#@.
875 | PrimTyConI
876 Name
877 Arity
878 Unlifted
879
880 -- | A data constructor
881 | DataConI
882 Name
883 Type
884 ParentName
885 Fixity
886
887 {- |
888 A \"value\" variable (as opposed to a type variable, see 'TyVarI').
889
890 The @Maybe Dec@ field contains @Just@ the declaration which
891 defined the variable -- including the RHS of the declaration --
892 or else @Nothing@, in the case where the RHS is unavailable to
893 the compiler. At present, this value is _always_ @Nothing@:
894 returning the RHS has not yet been implemented because of
895 lack of interest.
896 -}
897 | VarI
898 Name
899 Type
900 (Maybe Dec)
901 Fixity
902
903 {- |
904 A type variable.
905
906 The @Type@ field contains the type which underlies the variable.
907 At present, this is always @'VarT' theName@, but future changes
908 may permit refinement of this.
909 -}
910 | TyVarI -- Scoped type variable
911 Name
912 Type -- What it is bound to
913 deriving( Show, Data, Typeable )
914
915 {- |
916 In 'ClassOpI' and 'DataConI', name of the parent class or type
917 -}
918 type ParentName = Name
919
920 -- | In 'PrimTyConI', arity of the type constructor
921 type Arity = Int
922
923 -- | In 'PrimTyConI', is the type constructor unlifted?
924 type Unlifted = Bool
925
926 -- | 'InstanceDec' desribes a single instance of a class or type function.
927 -- It is just a 'Dec', but guaranteed to be one of the following:
928 --
929 -- * 'InstanceD' (with empty @['Dec']@)
930 --
931 -- * 'DataInstD' or 'NewtypeInstD' (with empty derived @['Name']@)
932 --
933 -- * 'TySynInstD'
934 type InstanceDec = Dec
935
936 data Fixity = Fixity Int FixityDirection
937 deriving( Eq, Show, Data, Typeable )
938 data FixityDirection = InfixL | InfixR | InfixN
939 deriving( Eq, Show, Data, Typeable )
940
941 -- | Highest allowed operator precedence for 'Fixity' constructor (answer: 9)
942 maxPrecedence :: Int
943 maxPrecedence = (9::Int)
944
945 -- | Default fixity: @infixl 9@
946 defaultFixity :: Fixity
947 defaultFixity = Fixity maxPrecedence InfixL
948
949
950 {-
951 Note [Unresolved infix]
952 ~~~~~~~~~~~~~~~~~~~~~~~
953 -}
954 {- $infix #infix#
955 When implementing antiquotation for quasiquoters, one often wants
956 to parse strings into expressions:
957
958 > parse :: String -> Maybe Exp
959
960 But how should we parse @a + b * c@? If we don't know the fixities of
961 @+@ and @*@, we don't know whether to parse it as @a + (b * c)@ or @(a
962 + b) * c@.
963
964 In cases like this, use 'UInfixE' or 'UInfixP', which stand for
965 \"unresolved infix expression\" and \"unresolved infix pattern\". When
966 the compiler is given a splice containing a tree of @UInfixE@
967 applications such as
968
969 > UInfixE
970 > (UInfixE e1 op1 e2)
971 > op2
972 > (UInfixE e3 op3 e4)
973
974 it will look up and the fixities of the relevant operators and
975 reassociate the tree as necessary.
976
977 * trees will not be reassociated across 'ParensE' or 'ParensP',
978 which are of use for parsing expressions like
979
980 > (a + b * c) + d * e
981
982 * 'InfixE' and 'InfixP' expressions are never reassociated.
983
984 * The 'UInfixE' constructor doesn't support sections. Sections
985 such as @(a *)@ have no ambiguity, so 'InfixE' suffices. For longer
986 sections such as @(a + b * c -)@, use an 'InfixE' constructor for the
987 outer-most section, and use 'UInfixE' constructors for all
988 other operators:
989
990 > InfixE
991 > Just (UInfixE ...a + b * c...)
992 > op
993 > Nothing
994
995 Sections such as @(a + b +)@ and @((a + b) +)@ should be rendered
996 into 'Exp's differently:
997
998 > (+ a + b) ---> InfixE Nothing + (Just $ UInfixE a + b)
999 > -- will result in a fixity error if (+) is left-infix
1000 > (+ (a + b)) ---> InfixE Nothing + (Just $ ParensE $ UInfixE a + b)
1001 > -- no fixity errors
1002
1003 * Quoted expressions such as
1004
1005 > [| a * b + c |] :: Q Exp
1006 > [p| a : b : c |] :: Q Pat
1007
1008 will never contain 'UInfixE', 'UInfixP', 'ParensE', or 'ParensP'
1009 constructors.
1010
1011 -}
1012
1013 -----------------------------------------------------
1014 --
1015 -- The main syntax data types
1016 --
1017 -----------------------------------------------------
1018
1019 data Lit = CharL Char
1020 | StringL String
1021 | IntegerL Integer -- ^ Used for overloaded and non-overloaded
1022 -- literals. We don't have a good way to
1023 -- represent non-overloaded literals at
1024 -- the moment. Maybe that doesn't matter?
1025 | RationalL Rational -- Ditto
1026 | IntPrimL Integer
1027 | WordPrimL Integer
1028 | FloatPrimL Rational
1029 | DoublePrimL Rational
1030 | StringPrimL [Word8] -- ^ A primitive C-style string, type Addr#
1031 deriving( Show, Eq, Data, Typeable )
1032
1033 -- We could add Int, Float, Double etc, as we do in HsLit,
1034 -- but that could complicate the
1035 -- suppposedly-simple TH.Syntax literal type
1036
1037 -- | Pattern in Haskell given in @{}@
1038 data Pat
1039 = LitP Lit -- ^ @{ 5 or 'c' }@
1040 | VarP Name -- ^ @{ x }@
1041 | TupP [Pat] -- ^ @{ (p1,p2) }@
1042 | UnboxedTupP [Pat] -- ^ @{ (# p1,p2 #) }@
1043 | ConP Name [Pat] -- ^ @data T1 = C1 t1 t2; {C1 p1 p1} = e@
1044 | InfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
1045 | UInfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
1046 --
1047 -- See "Language.Haskell.TH.Syntax#infix"
1048 | ParensP Pat -- ^ @{(p)}@
1049 --
1050 -- See "Language.Haskell.TH.Syntax#infix"
1051 | TildeP Pat -- ^ @{ ~p }@
1052 | BangP Pat -- ^ @{ !p }@
1053 | AsP Name Pat -- ^ @{ x \@ p }@
1054 | WildP -- ^ @{ _ }@
1055 | RecP Name [FieldPat] -- ^ @f (Pt { pointx = x }) = g x@
1056 | ListP [ Pat ] -- ^ @{ [1,2,3] }@
1057 | SigP Pat Type -- ^ @{ p :: t }@
1058 | ViewP Exp Pat -- ^ @{ e -> p }@
1059 deriving( Show, Eq, Data, Typeable )
1060
1061 type FieldPat = (Name,Pat)
1062
1063 data Match = Match Pat Body [Dec] -- ^ @case e of { pat -> body where decs }@
1064 deriving( Show, Eq, Data, Typeable )
1065 data Clause = Clause [Pat] Body [Dec]
1066 -- ^ @f { p1 p2 = body where decs }@
1067 deriving( Show, Eq, Data, Typeable )
1068
1069 data Exp
1070 = VarE Name -- ^ @{ x }@
1071 | ConE Name -- ^ @data T1 = C1 t1 t2; p = {C1} e1 e2 @
1072 | LitE Lit -- ^ @{ 5 or 'c'}@
1073 | AppE Exp Exp -- ^ @{ f x }@
1074
1075 | InfixE (Maybe Exp) Exp (Maybe Exp) -- ^ @{x + y} or {(x+)} or {(+ x)} or {(+)}@
1076
1077 -- It's a bit gruesome to use an Exp as the
1078 -- operator, but how else can we distinguish
1079 -- constructors from non-constructors?
1080 -- Maybe there should be a var-or-con type?
1081 -- Or maybe we should leave it to the String itself?
1082
1083 | UInfixE Exp Exp Exp -- ^ @{x + y}@
1084 --
1085 -- See "Language.Haskell.TH.Syntax#infix"
1086 | ParensE Exp -- ^ @{ (e) }@
1087 --
1088 -- See "Language.Haskell.TH.Syntax#infix"
1089 | LamE [Pat] Exp -- ^ @{ \ p1 p2 -> e }@
1090 | LamCaseE [Match] -- ^ @{ \case m1; m2 }@
1091 | TupE [Exp] -- ^ @{ (e1,e2) } @
1092 | UnboxedTupE [Exp] -- ^ @{ (# e1,e2 #) } @
1093 | CondE Exp Exp Exp -- ^ @{ if e1 then e2 else e3 }@
1094 | MultiIfE [(Guard, Exp)] -- ^ @{ if | g1 -> e1 | g2 -> e2 }@
1095 | LetE [Dec] Exp -- ^ @{ let x=e1; y=e2 in e3 }@
1096 | CaseE Exp [Match] -- ^ @{ case e of m1; m2 }@
1097 | DoE [Stmt] -- ^ @{ do { p <- e1; e2 } }@
1098 | CompE [Stmt] -- ^ @{ [ (x,y) | x <- xs, y <- ys ] }@
1099 --
1100 -- The result expression of the comprehension is
1101 -- the /last/ of the @'Stmt'@s, and should be a 'NoBindS'.
1102 --
1103 -- E.g. translation:
1104 --
1105 -- > [ f x | x <- xs ]
1106 --
1107 -- > CompE [BindS (VarP x) (VarE xs), NoBindS (AppE (VarE f) (VarE x))]
1108
1109 | ArithSeqE Range -- ^ @{ [ 1 ,2 .. 10 ] }@
1110 | ListE [ Exp ] -- ^ @{ [1,2,3] }@
1111 | SigE Exp Type -- ^ @{ e :: t }@
1112 | RecConE Name [FieldExp] -- ^ @{ T { x = y, z = w } }@
1113 | RecUpdE Exp [FieldExp] -- ^ @{ (f x) { z = w } }@
1114 deriving( Show, Eq, Data, Typeable )
1115
1116 type FieldExp = (Name,Exp)
1117
1118 -- Omitted: implicit parameters
1119
1120 data Body
1121 = GuardedB [(Guard,Exp)] -- ^ @f p { | e1 = e2
1122 -- | e3 = e4 }
1123 -- where ds@
1124 | NormalB Exp -- ^ @f p { = e } where ds@
1125 deriving( Show, Eq, Data, Typeable )
1126
1127 data Guard
1128 = NormalG Exp -- ^ @f x { | odd x } = x@
1129 | PatG [Stmt] -- ^ @f x { | Just y <- x, Just z <- y } = z@
1130 deriving( Show, Eq, Data, Typeable )
1131
1132 data Stmt
1133 = BindS Pat Exp
1134 | LetS [ Dec ]
1135 | NoBindS Exp
1136 | ParS [[Stmt]]
1137 deriving( Show, Eq, Data, Typeable )
1138
1139 data Range = FromR Exp | FromThenR Exp Exp
1140 | FromToR Exp Exp | FromThenToR Exp Exp Exp
1141 deriving( Show, Eq, Data, Typeable )
1142
1143 data Dec
1144 = FunD Name [Clause] -- ^ @{ f p1 p2 = b where decs }@
1145 | ValD Pat Body [Dec] -- ^ @{ p = b where decs }@
1146 | DataD Cxt Name [TyVarBndr]
1147 [Con] [Name] -- ^ @{ data Cxt x => T x = A x | B (T x)
1148 -- deriving (Z,W)}@
1149 | NewtypeD Cxt Name [TyVarBndr]
1150 Con [Name] -- ^ @{ newtype Cxt x => T x = A (B x)
1151 -- deriving (Z,W)}@
1152 | TySynD Name [TyVarBndr] Type -- ^ @{ type T x = (x,x) }@
1153 | ClassD Cxt Name [TyVarBndr]
1154 [FunDep] [Dec] -- ^ @{ class Eq a => Ord a where ds }@
1155 | InstanceD Cxt Type [Dec] -- ^ @{ instance Show w => Show [w]
1156 -- where ds }@
1157 | SigD Name Type -- ^ @{ length :: [a] -> Int }@
1158 | ForeignD Foreign -- ^ @{ foreign import ... }
1159 --{ foreign export ... }@
1160
1161 | InfixD Fixity Name -- ^ @{ infix 3 foo }@
1162
1163 -- | pragmas
1164 | PragmaD Pragma -- ^ @{ {\-# INLINE [1] foo #-\} }@
1165
1166 -- | type families (may also appear in [Dec] of 'ClassD' and 'InstanceD')
1167 | FamilyD FamFlavour Name
1168 [TyVarBndr] (Maybe Kind) -- ^ @{ type family T a b c :: * }@
1169
1170 | DataInstD Cxt Name [Type]
1171 [Con] [Name] -- ^ @{ data instance Cxt x => T [x] = A x
1172 -- | B (T x)
1173 -- deriving (Z,W)}@
1174 | NewtypeInstD Cxt Name [Type]
1175 Con [Name] -- ^ @{ newtype instance Cxt x => T [x] = A (B x)
1176 -- deriving (Z,W)}@
1177 | TySynInstD Name TySynEqn -- ^ @{ type instance ... }@
1178
1179 | ClosedTypeFamilyD Name
1180 [TyVarBndr] (Maybe Kind)
1181 [TySynEqn] -- ^ @{ type family F a b :: * where ... }@
1182
1183 | RoleAnnotD Name [Role] -- ^ @{ type role T nominal representational }@
1184 deriving( Show, Eq, Data, Typeable )
1185
1186 -- | One equation of a type family instance or closed type family. The
1187 -- arguments are the left-hand-side type patterns and the right-hand-side
1188 -- result.
1189 data TySynEqn = TySynEqn [Type] Type
1190 deriving( Show, Eq, Data, Typeable )
1191
1192 data FunDep = FunDep [Name] [Name]
1193 deriving( Show, Eq, Data, Typeable )
1194
1195 data FamFlavour = TypeFam | DataFam
1196 deriving( Show, Eq, Data, Typeable )
1197
1198 data Foreign = ImportF Callconv Safety String Name Type
1199 | ExportF Callconv String Name Type
1200 deriving( Show, Eq, Data, Typeable )
1201
1202 data Callconv = CCall | StdCall
1203 deriving( Show, Eq, Data, Typeable )
1204
1205 data Safety = Unsafe | Safe | Interruptible
1206 deriving( Show, Eq, Data, Typeable )
1207
1208 data Pragma = InlineP Name Inline RuleMatch Phases
1209 | SpecialiseP Name Type (Maybe Inline) Phases
1210 | SpecialiseInstP Type
1211 | RuleP String [RuleBndr] Exp Exp Phases
1212 deriving( Show, Eq, Data, Typeable )
1213
1214 data Inline = NoInline
1215 | Inline
1216 | Inlinable
1217 deriving (Show, Eq, Data, Typeable)
1218
1219 data RuleMatch = ConLike
1220 | FunLike
1221 deriving (Show, Eq, Data, Typeable)
1222
1223 data Phases = AllPhases
1224 | FromPhase Int
1225 | BeforePhase Int
1226 deriving (Show, Eq, Data, Typeable)
1227
1228 data RuleBndr = RuleVar Name
1229 | TypedRuleVar Name Type
1230 deriving (Show, Eq, Data, Typeable)
1231
1232 type Cxt = [Pred] -- ^ @(Eq a, Ord b)@
1233
1234 data Pred = ClassP Name [Type] -- ^ @Eq (Int, a)@
1235 | EqualP Type Type -- ^ @F a ~ Bool@
1236 deriving( Show, Eq, Data, Typeable )
1237
1238 data Strict = IsStrict | NotStrict | Unpacked
1239 deriving( Show, Eq, Data, Typeable )
1240
1241 data Con = NormalC Name [StrictType] -- ^ @C Int a@
1242 | RecC Name [VarStrictType] -- ^ @C { v :: Int, w :: a }@
1243 | InfixC StrictType Name StrictType -- ^ @Int :+ a@
1244 | ForallC [TyVarBndr] Cxt Con -- ^ @forall a. Eq a => C [a]@
1245 deriving( Show, Eq, Data, Typeable )
1246
1247 type StrictType = (Strict, Type)
1248 type VarStrictType = (Name, Strict, Type)
1249
1250 data Type = ForallT [TyVarBndr] Cxt Type -- ^ @forall \<vars\>. \<ctxt\> -> \<type\>@
1251 | AppT Type Type -- ^ @T a b@
1252 | SigT Type Kind -- ^ @t :: k@
1253 | VarT Name -- ^ @a@
1254 | ConT Name -- ^ @T@
1255 | PromotedT Name -- ^ @'T@
1256
1257 -- See Note [Representing concrete syntax in types]
1258 | TupleT Int -- ^ @(,), (,,), etc.@
1259 | UnboxedTupleT Int -- ^ @(#,#), (#,,#), etc.@
1260 | ArrowT -- ^ @->@
1261 | ListT -- ^ @[]@
1262 | PromotedTupleT Int -- ^ @'(), '(,), '(,,), etc.@
1263 | PromotedNilT -- ^ @'[]@
1264 | PromotedConsT -- ^ @(':)@
1265 | StarT -- ^ @*@
1266 | ConstraintT -- ^ @Constraint@
1267 | LitT TyLit -- ^ @0,1,2, etc.@
1268 deriving( Show, Eq, Data, Typeable )
1269
1270 data TyVarBndr = PlainTV Name -- ^ @a@
1271 | KindedTV Name Kind -- ^ @(a :: k)@
1272 deriving( Show, Eq, Data, Typeable )
1273
1274 data TyLit = NumTyLit Integer -- ^ @2@
1275 | StrTyLit String -- ^ @"Hello"@
1276 deriving ( Show, Eq, Data, Typeable )
1277
1278 -- | Role annotations
1279 data Role = NominalR -- ^ @nominal@
1280 | RepresentationalR -- ^ @representational@
1281 | PhantomR -- ^ @phantom@
1282 | InferR -- ^ @_@
1283 deriving( Show, Eq, Data, Typeable )
1284
1285 -- | To avoid duplication between kinds and types, they
1286 -- are defined to be the same. Naturally, you would never
1287 -- have a type be 'StarT' and you would never have a kind
1288 -- be 'SigT', but many of the other constructors are shared.
1289 -- Note that the kind @Bool@ is denoted with 'ConT', not
1290 -- 'PromotedT'. Similarly, tuple kinds are made with 'TupleT',
1291 -- not 'PromotedTupleT'.
1292
1293 type Kind = Type
1294
1295 {- Note [Representing concrete syntax in types]
1296 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1297 Haskell has a rich concrete syntax for types, including
1298 t1 -> t2, (t1,t2), [t], and so on
1299 In TH we represent all of this using AppT, with a distinguished
1300 type constructor at the head. So,
1301 Type TH representation
1302 -----------------------------------------------
1303 t1 -> t2 ArrowT `AppT` t2 `AppT` t2
1304 [t] ListT `AppT` t
1305 (t1,t2) TupleT 2 `AppT` t1 `AppT` t2
1306 '(t1,t2) PromotedTupleT 2 `AppT` t1 `AppT` t2
1307
1308 But if the original HsSyn used prefix application, we won't use
1309 these special TH constructors. For example
1310 [] t ConT "[]" `AppT` t
1311 (->) t ConT "->" `AppT` t
1312 In this way we can faithfully represent in TH whether the original
1313 HsType used concrete syntax or not.
1314
1315 The one case that doesn't fit this pattern is that of promoted lists
1316 '[ Maybe, IO ] PromotedListT 2 `AppT` t1 `AppT` t2
1317 but it's very smelly because there really is no type constructor
1318 corresponding to PromotedListT. So we encode HsExplicitListTy with
1319 PromotedConsT and PromotedNilT (which *do* have underlying type
1320 constructors):
1321 '[ Maybe, IO ] PromotedConsT `AppT` Maybe `AppT`
1322 (PromotedConsT `AppT` IO `AppT` PromotedNilT)
1323 -}
1324
1325 -----------------------------------------------------
1326 -- Internal helper functions
1327 -----------------------------------------------------
1328
1329 cmpEq :: Ordering -> Bool
1330 cmpEq EQ = True
1331 cmpEq _ = False
1332
1333 thenCmp :: Ordering -> Ordering -> Ordering
1334 thenCmp EQ o2 = o2
1335 thenCmp o1 _ = o1
1336