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