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