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