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