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