TH: Use atomicModifyIORef' for fresh names
[ghc.git] / libraries / template-haskell / Language / Haskell / TH / Syntax.hs
1 {-# LANGUAGE CPP, DeriveDataTypeable,
2 DeriveGeneric, FlexibleInstances, DefaultSignatures,
3 RankNTypes, RoleAnnotations, ScopedTypeVariables #-}
4
5 {-# OPTIONS_GHC -fno-warn-inline-rule-shadowing #-}
6
7 #if MIN_VERSION_base(4,9,0)
8 # define HAS_MONADFAIL 1
9 #endif
10
11 -----------------------------------------------------------------------------
12 -- |
13 -- Module : Language.Haskell.Syntax
14 -- Copyright : (c) The University of Glasgow 2003
15 -- License : BSD-style (see the file libraries/base/LICENSE)
16 --
17 -- Maintainer : libraries@haskell.org
18 -- Stability : experimental
19 -- Portability : portable
20 --
21 -- Abstract syntax definitions for Template Haskell.
22 --
23 -----------------------------------------------------------------------------
24
25 module Language.Haskell.TH.Syntax
26 ( module Language.Haskell.TH.Syntax
27 -- * Language extensions
28 , module Language.Haskell.TH.LanguageExtensions
29 ) where
30
31 import Data.Data hiding (Fixity(..))
32 import Data.IORef
33 import System.IO.Unsafe ( unsafePerformIO )
34 import Control.Monad (liftM)
35 import System.IO ( hPutStrLn, stderr )
36 import Data.Char ( isAlpha, isAlphaNum, isUpper )
37 import Data.Int
38 import Data.Word
39 import Data.Ratio
40 import GHC.Generics ( Generic )
41 import GHC.Lexeme ( startsVarSym, startsVarId )
42 import Language.Haskell.TH.LanguageExtensions
43 import Numeric.Natural
44
45 #if HAS_MONADFAIL
46 import qualified Control.Monad.Fail as Fail
47 #endif
48
49 -----------------------------------------------------
50 --
51 -- The Quasi class
52 --
53 -----------------------------------------------------
54
55 #if HAS_MONADFAIL
56 class Fail.MonadFail m => Quasi m where
57 #else
58 class Monad m => Quasi m where
59 #endif
60 qNewName :: String -> m Name
61 -- ^ Fresh names
62
63 -- Error reporting and recovery
64 qReport :: Bool -> String -> m () -- ^ Report an error (True) or warning (False)
65 -- ...but carry on; use 'fail' to stop
66 qRecover :: m a -- ^ the error handler
67 -> m a -- ^ action which may fail
68 -> m a -- ^ Recover from the monadic 'fail'
69
70 -- Inspect the type-checker's environment
71 qLookupName :: Bool -> String -> m (Maybe Name)
72 -- True <=> type namespace, False <=> value namespace
73 qReify :: Name -> m Info
74 qReifyFixity :: Name -> m (Maybe Fixity)
75 qReifyInstances :: Name -> [Type] -> m [Dec]
76 -- Is (n tys) an instance?
77 -- Returns list of matching instance Decs
78 -- (with empty sub-Decs)
79 -- Works for classes and type functions
80 qReifyRoles :: Name -> m [Role]
81 qReifyAnnotations :: Data a => AnnLookup -> m [a]
82 qReifyModule :: Module -> m ModuleInfo
83 qReifyConStrictness :: Name -> m [DecidedStrictness]
84
85 qLocation :: m Loc
86
87 qRunIO :: IO a -> m a
88 -- ^ Input/output (dangerous)
89
90 qAddDependentFile :: FilePath -> m ()
91
92 qAddTopDecls :: [Dec] -> m ()
93
94 qAddModFinalizer :: Q () -> m ()
95
96 qGetQ :: Typeable a => m (Maybe a)
97
98 qPutQ :: Typeable a => a -> m ()
99
100 qIsExtEnabled :: Extension -> m Bool
101 qExtsEnabled :: m [Extension]
102
103 -----------------------------------------------------
104 -- The IO instance of Quasi
105 --
106 -- This instance is used only when running a Q
107 -- computation in the IO monad, usually just to
108 -- print the result. There is no interesting
109 -- type environment, so reification isn't going to
110 -- work.
111 --
112 -----------------------------------------------------
113
114 instance Quasi IO where
115 qNewName s = do { n <- atomicModifyIORef' counter (\x -> (x + 1, x))
116 ; pure (mkNameU s n) }
117
118 qReport True msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
119 qReport False msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
120
121 qLookupName _ _ = badIO "lookupName"
122 qReify _ = badIO "reify"
123 qReifyFixity _ = badIO "reifyFixity"
124 qReifyInstances _ _ = badIO "reifyInstances"
125 qReifyRoles _ = badIO "reifyRoles"
126 qReifyAnnotations _ = badIO "reifyAnnotations"
127 qReifyModule _ = badIO "reifyModule"
128 qReifyConStrictness _ = badIO "reifyConStrictness"
129 qLocation = badIO "currentLocation"
130 qRecover _ _ = badIO "recover" -- Maybe we could fix this?
131 qAddDependentFile _ = badIO "addDependentFile"
132 qAddTopDecls _ = badIO "addTopDecls"
133 qAddModFinalizer _ = badIO "addModFinalizer"
134 qGetQ = badIO "getQ"
135 qPutQ _ = badIO "putQ"
136 qIsExtEnabled _ = badIO "isExtEnabled"
137 qExtsEnabled = badIO "extsEnabled"
138
139 qRunIO m = m
140
141 badIO :: String -> IO a
142 badIO op = do { qReport True ("Can't do `" ++ op ++ "' in the IO monad")
143 ; fail "Template Haskell failure" }
144
145 -- Global variable to generate unique symbols
146 counter :: IORef Int
147 {-# NOINLINE counter #-}
148 counter = unsafePerformIO (newIORef 0)
149
150
151 -----------------------------------------------------
152 --
153 -- The Q monad
154 --
155 -----------------------------------------------------
156
157 newtype Q a = Q { unQ :: forall m. Quasi m => m a }
158
159 -- \"Runs\" the 'Q' monad. Normal users of Template Haskell
160 -- should not need this function, as the splice brackets @$( ... )@
161 -- are the usual way of running a 'Q' computation.
162 --
163 -- This function is primarily used in GHC internals, and for debugging
164 -- splices by running them in 'IO'.
165 --
166 -- Note that many functions in 'Q', such as 'reify' and other compiler
167 -- queries, are not supported when running 'Q' in 'IO'; these operations
168 -- simply fail at runtime. Indeed, the only operations guaranteed to succeed
169 -- are 'newName', 'runIO', 'reportError' and 'reportWarning'.
170 runQ :: Quasi m => Q a -> m a
171 runQ (Q m) = m
172
173 instance Monad Q where
174 Q m >>= k = Q (m >>= \x -> unQ (k x))
175 (>>) = (*>)
176 #if !HAS_MONADFAIL
177 fail s = report True s >> Q (fail "Q monad failure")
178 #else
179 fail = Fail.fail
180
181 instance Fail.MonadFail Q where
182 fail s = report True s >> Q (Fail.fail "Q monad failure")
183 #endif
184
185 instance Functor Q where
186 fmap f (Q x) = Q (fmap f x)
187
188 instance Applicative Q where
189 pure x = Q (pure x)
190 Q f <*> Q x = Q (f <*> x)
191 Q m *> Q n = Q (m *> n)
192
193 -----------------------------------------------------
194 --
195 -- The TExp type
196 --
197 -----------------------------------------------------
198
199 type role TExp nominal -- See Note [Role of TExp]
200 newtype TExp a = TExp { unType :: Exp }
201
202 unTypeQ :: Q (TExp a) -> Q Exp
203 unTypeQ m = do { TExp e <- m
204 ; return e }
205
206 unsafeTExpCoerce :: Q Exp -> Q (TExp a)
207 unsafeTExpCoerce m = do { e <- m
208 ; return (TExp e) }
209
210 {- Note [Role of TExp]
211 ~~~~~~~~~~~~~~~~~~~~~~
212 TExp's argument must have a nominal role, not phantom as would
213 be inferred (Trac #8459). Consider
214
215 e :: TExp Age
216 e = MkAge 3
217
218 foo = $(coerce e) + 4::Int
219
220 The splice will evaluate to (MkAge 3) and you can't add that to
221 4::Int. So you can't coerce a (TExp Age) to a (TExp Int). -}
222
223 ----------------------------------------------------
224 -- Packaged versions for the programmer, hiding the Quasi-ness
225
226 {- |
227 Generate a fresh name, which cannot be captured.
228
229 For example, this:
230
231 @f = $(do
232 nm1 <- newName \"x\"
233 let nm2 = 'mkName' \"x\"
234 return ('LamE' ['VarP' nm1] (LamE [VarP nm2] ('VarE' nm1)))
235 )@
236
237 will produce the splice
238
239 >f = \x0 -> \x -> x0
240
241 In particular, the occurrence @VarE nm1@ refers to the binding @VarP nm1@,
242 and is not captured by the binding @VarP nm2@.
243
244 Although names generated by @newName@ cannot /be captured/, they can
245 /capture/ other names. For example, this:
246
247 >g = $(do
248 > nm1 <- newName "x"
249 > let nm2 = mkName "x"
250 > return (LamE [VarP nm2] (LamE [VarP nm1] (VarE nm2)))
251 > )
252
253 will produce the splice
254
255 >g = \x -> \x0 -> x0
256
257 since the occurrence @VarE nm2@ is captured by the innermost binding
258 of @x@, namely @VarP nm1@.
259 -}
260 newName :: String -> Q Name
261 newName s = Q (qNewName s)
262
263 -- | Report an error (True) or warning (False),
264 -- but carry on; use 'fail' to stop.
265 report :: Bool -> String -> Q ()
266 report b s = Q (qReport b s)
267 {-# DEPRECATED report "Use reportError or reportWarning instead" #-} -- deprecated in 7.6
268
269 -- | Report an error to the user, but allow the current splice's computation to carry on. To abort the computation, use 'fail'.
270 reportError :: String -> Q ()
271 reportError = report True
272
273 -- | Report a warning to the user, and carry on.
274 reportWarning :: String -> Q ()
275 reportWarning = report False
276
277 -- | Recover from errors raised by 'reportError' or 'fail'.
278 recover :: Q a -- ^ handler to invoke on failure
279 -> Q a -- ^ computation to run
280 -> Q a
281 recover (Q r) (Q m) = Q (qRecover r m)
282
283 -- We don't export lookupName; the Bool isn't a great API
284 -- Instead we export lookupTypeName, lookupValueName
285 lookupName :: Bool -> String -> Q (Maybe Name)
286 lookupName ns s = Q (qLookupName ns s)
287
288 -- | Look up the given name in the (type namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
289 lookupTypeName :: String -> Q (Maybe Name)
290 lookupTypeName s = Q (qLookupName True s)
291
292 -- | Look up the given name in the (value namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
293 lookupValueName :: String -> Q (Maybe Name)
294 lookupValueName s = Q (qLookupName False s)
295
296 {-
297 Note [Name lookup]
298 ~~~~~~~~~~~~~~~~~~
299 -}
300 {- $namelookup #namelookup#
301 The functions 'lookupTypeName' and 'lookupValueName' provide
302 a way to query the current splice's context for what names
303 are in scope. The function 'lookupTypeName' queries the type
304 namespace, whereas 'lookupValueName' queries the value namespace,
305 but the functions are otherwise identical.
306
307 A call @lookupValueName s@ will check if there is a value
308 with name @s@ in scope at the current splice's location. If
309 there is, the @Name@ of this value is returned;
310 if not, then @Nothing@ is returned.
311
312 The returned name cannot be \"captured\".
313 For example:
314
315 > f = "global"
316 > g = $( do
317 > Just nm <- lookupValueName "f"
318 > [| let f = "local" in $( varE nm ) |]
319
320 In this case, @g = \"global\"@; the call to @lookupValueName@
321 returned the global @f@, and this name was /not/ captured by
322 the local definition of @f@.
323
324 The lookup is performed in the context of the /top-level/ splice
325 being run. For example:
326
327 > f = "global"
328 > g = $( [| let f = "local" in
329 > $(do
330 > Just nm <- lookupValueName "f"
331 > varE nm
332 > ) |] )
333
334 Again in this example, @g = \"global\"@, because the call to
335 @lookupValueName@ queries the context of the outer-most @$(...)@.
336
337 Operators should be queried without any surrounding parentheses, like so:
338
339 > lookupValueName "+"
340
341 Qualified names are also supported, like so:
342
343 > lookupValueName "Prelude.+"
344 > lookupValueName "Prelude.map"
345
346 -}
347
348
349 {- | 'reify' looks up information about the 'Name'.
350
351 It is sometimes useful to construct the argument name using 'lookupTypeName' or 'lookupValueName'
352 to ensure that we are reifying from the right namespace. For instance, in this context:
353
354 > data D = D
355
356 which @D@ does @reify (mkName \"D\")@ return information about? (Answer: @D@-the-type, but don't rely on it.)
357 To ensure we get information about @D@-the-value, use 'lookupValueName':
358
359 > do
360 > Just nm <- lookupValueName "D"
361 > reify nm
362
363 and to get information about @D@-the-type, use 'lookupTypeName'.
364 -}
365 reify :: Name -> Q Info
366 reify v = Q (qReify v)
367
368 {- | @reifyFixity nm@ attempts to find a fixity declaration for @nm@. For
369 example, if the function @foo@ has the fixity declaration @infixr 7 foo@, then
370 @reifyFixity 'foo@ would return @'Just' ('Fixity' 7 'InfixR')@. If the function
371 @bar@ does not have a fixity declaration, then @reifyFixity 'bar@ returns
372 'Nothing', so you may assume @bar@ has 'defaultFixity'.
373 -}
374 reifyFixity :: Name -> Q (Maybe Fixity)
375 reifyFixity nm = Q (qReifyFixity nm)
376
377 {- | @reifyInstances nm tys@ returns a list of visible instances of @nm tys@. That is,
378 if @nm@ is the name of a type class, then all instances of this class at the types @tys@
379 are returned. Alternatively, if @nm@ is the name of a data family or type family,
380 all instances of this family at the types @tys@ are returned.
381 -}
382 reifyInstances :: Name -> [Type] -> Q [InstanceDec]
383 reifyInstances cls tys = Q (qReifyInstances cls tys)
384
385 {- | @reifyRoles nm@ returns the list of roles associated with the parameters of
386 the tycon @nm@. Fails if @nm@ cannot be found or is not a tycon.
387 The returned list should never contain 'InferR'.
388 -}
389 reifyRoles :: Name -> Q [Role]
390 reifyRoles nm = Q (qReifyRoles nm)
391
392 -- | @reifyAnnotations target@ returns the list of annotations
393 -- associated with @target@. Only the annotations that are
394 -- appropriately typed is returned. So if you have @Int@ and @String@
395 -- annotations for the same target, you have to call this function twice.
396 reifyAnnotations :: Data a => AnnLookup -> Q [a]
397 reifyAnnotations an = Q (qReifyAnnotations an)
398
399 -- | @reifyModule mod@ looks up information about module @mod@. To
400 -- look up the current module, call this function with the return
401 -- value of @thisModule@.
402 reifyModule :: Module -> Q ModuleInfo
403 reifyModule m = Q (qReifyModule m)
404
405 -- | @reifyConStrictness nm@ looks up the strictness information for the fields
406 -- of the constructor with the name @nm@. Note that the strictness information
407 -- that 'reifyConStrictness' returns may not correspond to what is written in
408 -- the source code. For example, in the following data declaration:
409 --
410 -- @
411 -- data Pair a = Pair a a
412 -- @
413 --
414 -- 'reifyConStrictness' would return @['DecidedLazy', DecidedLazy]@ under most
415 -- circumstances, but it would return @['DecidedStrict', DecidedStrict]@ if the
416 -- @-XStrictData@ language extension was enabled.
417 reifyConStrictness :: Name -> Q [DecidedStrictness]
418 reifyConStrictness n = Q (qReifyConStrictness n)
419
420 -- | Is the list of instances returned by 'reifyInstances' nonempty?
421 isInstance :: Name -> [Type] -> Q Bool
422 isInstance nm tys = do { decs <- reifyInstances nm tys
423 ; return (not (null decs)) }
424
425 -- | The location at which this computation is spliced.
426 location :: Q Loc
427 location = Q qLocation
428
429 -- |The 'runIO' function lets you run an I\/O computation in the 'Q' monad.
430 -- Take care: you are guaranteed the ordering of calls to 'runIO' within
431 -- a single 'Q' computation, but not about the order in which splices are run.
432 --
433 -- Note: for various murky reasons, stdout and stderr handles are not
434 -- necessarily flushed when the compiler finishes running, so you should
435 -- flush them yourself.
436 runIO :: IO a -> Q a
437 runIO m = Q (qRunIO m)
438
439 -- | Record external files that runIO is using (dependent upon).
440 -- The compiler can then recognize that it should re-compile the Haskell file
441 -- when an external file changes.
442 --
443 -- Expects an absolute file path.
444 --
445 -- Notes:
446 --
447 -- * ghc -M does not know about these dependencies - it does not execute TH.
448 --
449 -- * The dependency is based on file content, not a modification time
450 addDependentFile :: FilePath -> Q ()
451 addDependentFile fp = Q (qAddDependentFile fp)
452
453 -- | Add additional top-level declarations. The added declarations will be type
454 -- checked along with the current declaration group.
455 addTopDecls :: [Dec] -> Q ()
456 addTopDecls ds = Q (qAddTopDecls ds)
457
458 -- | Add a finalizer that will run in the Q monad after the current module has
459 -- been type checked. This only makes sense when run within a top-level splice.
460 --
461 -- The finalizer is given the local type environment at the splice point. Thus
462 -- 'reify' is able to find the local definitions when executed inside the
463 -- finalizer.
464 addModFinalizer :: Q () -> Q ()
465 addModFinalizer act = Q (qAddModFinalizer (unQ act))
466
467 -- | Get state from the 'Q' monad. Note that the state is local to the
468 -- Haskell module in which the Template Haskell expression is executed.
469 getQ :: Typeable a => Q (Maybe a)
470 getQ = Q qGetQ
471
472 -- | Replace the state in the 'Q' monad. Note that the state is local to the
473 -- Haskell module in which the Template Haskell expression is executed.
474 putQ :: Typeable a => a -> Q ()
475 putQ x = Q (qPutQ x)
476
477 -- | Determine whether the given language extension is enabled in the 'Q' monad.
478 isExtEnabled :: Extension -> Q Bool
479 isExtEnabled ext = Q (qIsExtEnabled ext)
480
481 -- | List all enabled language extensions.
482 extsEnabled :: Q [Extension]
483 extsEnabled = Q qExtsEnabled
484
485 instance Quasi Q where
486 qNewName = newName
487 qReport = report
488 qRecover = recover
489 qReify = reify
490 qReifyFixity = reifyFixity
491 qReifyInstances = reifyInstances
492 qReifyRoles = reifyRoles
493 qReifyAnnotations = reifyAnnotations
494 qReifyModule = reifyModule
495 qReifyConStrictness = reifyConStrictness
496 qLookupName = lookupName
497 qLocation = location
498 qRunIO = runIO
499 qAddDependentFile = addDependentFile
500 qAddTopDecls = addTopDecls
501 qAddModFinalizer = addModFinalizer
502 qGetQ = getQ
503 qPutQ = putQ
504 qIsExtEnabled = isExtEnabled
505 qExtsEnabled = extsEnabled
506
507
508 ----------------------------------------------------
509 -- The following operations are used solely in DsMeta when desugaring brackets
510 -- They are not necessary for the user, who can use ordinary return and (>>=) etc
511
512 returnQ :: a -> Q a
513 returnQ = return
514
515 bindQ :: Q a -> (a -> Q b) -> Q b
516 bindQ = (>>=)
517
518 sequenceQ :: [Q a] -> Q [a]
519 sequenceQ = sequence
520
521
522 -----------------------------------------------------
523 --
524 -- The Lift class
525 --
526 -----------------------------------------------------
527
528 -- | A 'Lift' instance can have any of its values turned into a Template
529 -- Haskell expression. This is needed when a value used within a Template
530 -- Haskell quotation is bound outside the Oxford brackets (@[| ... |]@) but not
531 -- at the top level. As an example:
532 --
533 -- > add1 :: Int -> Q Exp
534 -- > add1 x = [| x + 1 |]
535 --
536 -- Template Haskell has no way of knowing what value @x@ will take on at
537 -- splice-time, so it requires the type of @x@ to be an instance of 'Lift'.
538 --
539 -- 'Lift' instances can be derived automatically by use of the @-XDeriveLift@
540 -- GHC language extension:
541 --
542 -- > {-# LANGUAGE DeriveLift #-}
543 -- > module Foo where
544 -- >
545 -- > import Language.Haskell.TH.Syntax
546 -- >
547 -- > data Bar a = Bar1 a (Bar a) | Bar2 String
548 -- > deriving Lift
549 class Lift t where
550 -- | Turn a value into a Template Haskell expression, suitable for use in
551 -- a splice.
552 lift :: t -> Q Exp
553 default lift :: Data t => t -> Q Exp
554 lift = liftData
555
556 -- If you add any instances here, consider updating test th/TH_Lift
557 instance Lift Integer where
558 lift x = return (LitE (IntegerL x))
559
560 instance Lift Int where
561 lift x = return (LitE (IntegerL (fromIntegral x)))
562
563 instance Lift Int8 where
564 lift x = return (LitE (IntegerL (fromIntegral x)))
565
566 instance Lift Int16 where
567 lift x = return (LitE (IntegerL (fromIntegral x)))
568
569 instance Lift Int32 where
570 lift x = return (LitE (IntegerL (fromIntegral x)))
571
572 instance Lift Int64 where
573 lift x = return (LitE (IntegerL (fromIntegral x)))
574
575 instance Lift Word where
576 lift x = return (LitE (IntegerL (fromIntegral x)))
577
578 instance Lift Word8 where
579 lift x = return (LitE (IntegerL (fromIntegral x)))
580
581 instance Lift Word16 where
582 lift x = return (LitE (IntegerL (fromIntegral x)))
583
584 instance Lift Word32 where
585 lift x = return (LitE (IntegerL (fromIntegral x)))
586
587 instance Lift Word64 where
588 lift x = return (LitE (IntegerL (fromIntegral x)))
589
590 instance Lift Natural where
591 lift x = return (LitE (IntegerL (fromIntegral x)))
592
593 instance Integral a => Lift (Ratio a) where
594 lift x = return (LitE (RationalL (toRational x)))
595
596 instance Lift Float where
597 lift x = return (LitE (RationalL (toRational x)))
598
599 instance Lift Double where
600 lift x = return (LitE (RationalL (toRational x)))
601
602 instance Lift Char where
603 lift x = return (LitE (CharL x))
604
605 instance Lift Bool where
606 lift True = return (ConE trueName)
607 lift False = return (ConE falseName)
608
609 instance Lift a => Lift (Maybe a) where
610 lift Nothing = return (ConE nothingName)
611 lift (Just x) = liftM (ConE justName `AppE`) (lift x)
612
613 instance (Lift a, Lift b) => Lift (Either a b) where
614 lift (Left x) = liftM (ConE leftName `AppE`) (lift x)
615 lift (Right y) = liftM (ConE rightName `AppE`) (lift y)
616
617 instance Lift a => Lift [a] where
618 lift xs = do { xs' <- mapM lift xs; return (ListE xs') }
619
620 liftString :: String -> Q Exp
621 -- Used in TcExpr to short-circuit the lifting for strings
622 liftString s = return (LitE (StringL s))
623
624 instance Lift () where
625 lift () = return (ConE (tupleDataName 0))
626
627 instance (Lift a, Lift b) => Lift (a, b) where
628 lift (a, b)
629 = liftM TupE $ sequence [lift a, lift b]
630
631 instance (Lift a, Lift b, Lift c) => Lift (a, b, c) where
632 lift (a, b, c)
633 = liftM TupE $ sequence [lift a, lift b, lift c]
634
635 instance (Lift a, Lift b, Lift c, Lift d) => Lift (a, b, c, d) where
636 lift (a, b, c, d)
637 = liftM TupE $ sequence [lift a, lift b, lift c, lift d]
638
639 instance (Lift a, Lift b, Lift c, Lift d, Lift e)
640 => Lift (a, b, c, d, e) where
641 lift (a, b, c, d, e)
642 = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e]
643
644 instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f)
645 => Lift (a, b, c, d, e, f) where
646 lift (a, b, c, d, e, f)
647 = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f]
648
649 instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f, Lift g)
650 => Lift (a, b, c, d, e, f, g) where
651 lift (a, b, c, d, e, f, g)
652 = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f, lift g]
653
654 -- TH has a special form for literal strings,
655 -- which we should take advantage of.
656 -- NB: the lhs of the rule has no args, so that
657 -- the rule will apply to a 'lift' all on its own
658 -- which happens to be the way the type checker
659 -- creates it.
660 {-# RULES "TH:liftString" lift = \s -> return (LitE (StringL s)) #-}
661
662
663 trueName, falseName :: Name
664 trueName = mkNameG DataName "ghc-prim" "GHC.Types" "True"
665 falseName = mkNameG DataName "ghc-prim" "GHC.Types" "False"
666
667 nothingName, justName :: Name
668 nothingName = mkNameG DataName "base" "GHC.Base" "Nothing"
669 justName = mkNameG DataName "base" "GHC.Base" "Just"
670
671 leftName, rightName :: Name
672 leftName = mkNameG DataName "base" "Data.Either" "Left"
673 rightName = mkNameG DataName "base" "Data.Either" "Right"
674
675 -----------------------------------------------------
676 --
677 -- Generic Lift implementations
678 --
679 -----------------------------------------------------
680
681 -- | 'dataToQa' is an internal utility function for constructing generic
682 -- conversion functions from types with 'Data' instances to various
683 -- quasi-quoting representations. See the source of 'dataToExpQ' and
684 -- 'dataToPatQ' for two example usages: @mkCon@, @mkLit@
685 -- and @appQ@ are overloadable to account for different syntax for
686 -- expressions and patterns; @antiQ@ allows you to override type-specific
687 -- cases, a common usage is just @const Nothing@, which results in
688 -- no overloading.
689 dataToQa :: forall a k q. Data a
690 => (Name -> k)
691 -> (Lit -> Q q)
692 -> (k -> [Q q] -> Q q)
693 -> (forall b . Data b => b -> Maybe (Q q))
694 -> a
695 -> Q q
696 dataToQa mkCon mkLit appCon antiQ t =
697 case antiQ t of
698 Nothing ->
699 case constrRep constr of
700 AlgConstr _ ->
701 appCon (mkCon funOrConName) conArgs
702 where
703 funOrConName :: Name
704 funOrConName =
705 case showConstr constr of
706 "(:)" -> Name (mkOccName ":")
707 (NameG DataName
708 (mkPkgName "ghc-prim")
709 (mkModName "GHC.Types"))
710 con@"[]" -> Name (mkOccName con)
711 (NameG DataName
712 (mkPkgName "ghc-prim")
713 (mkModName "GHC.Types"))
714 con@('(':_) -> Name (mkOccName con)
715 (NameG DataName
716 (mkPkgName "ghc-prim")
717 (mkModName "GHC.Tuple"))
718
719 -- Tricky case: see Note [Data for non-algebraic types]
720 fun@(x:_) | startsVarSym x || startsVarId x
721 -> mkNameG_v tyconPkg tyconMod fun
722 con -> mkNameG_d tyconPkg tyconMod con
723
724 where
725 tycon :: TyCon
726 tycon = (typeRepTyCon . typeOf) t
727
728 tyconPkg, tyconMod :: String
729 tyconPkg = tyConPackage tycon
730 tyconMod = tyConModule tycon
731
732 conArgs :: [Q q]
733 conArgs = gmapQ (dataToQa mkCon mkLit appCon antiQ) t
734 IntConstr n ->
735 mkLit $ IntegerL n
736 FloatConstr n ->
737 mkLit $ RationalL n
738 CharConstr c ->
739 mkLit $ CharL c
740 where
741 constr :: Constr
742 constr = toConstr t
743
744 Just y -> y
745
746
747 {- Note [Data for non-algebraic types]
748 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
749 Class Data was originally intended for algebraic data types. But
750 it is possible to use it for abstract types too. For example, in
751 package `text` we find
752
753 instance Data Text where
754 ...
755 toConstr _ = packConstr
756
757 packConstr :: Constr
758 packConstr = mkConstr textDataType "pack" [] Prefix
759
760 Here `packConstr` isn't a real data constructor, it's an ordiary
761 function. Two complications
762
763 * In such a case, we must take care to build the Name using
764 mkNameG_v (for values), not mkNameG_d (for data constructors).
765 See Trac #10796.
766
767 * The pseudo-constructor is named only by its string, here "pack".
768 But 'dataToQa' needs the TyCon of its defining module, and has
769 to assume it's defined in the same module as the TyCon itself.
770 But nothing enforces that; Trac #12596 shows what goes wrong if
771 "pack" is defined in a different module than the data type "Text".
772 -}
773
774 -- | 'dataToExpQ' converts a value to a 'Q Exp' representation of the
775 -- same value, in the SYB style. It is generalized to take a function
776 -- override type-specific cases; see 'liftData' for a more commonly
777 -- used variant.
778 dataToExpQ :: Data a
779 => (forall b . Data b => b -> Maybe (Q Exp))
780 -> a
781 -> Q Exp
782 dataToExpQ = dataToQa varOrConE litE (foldl appE)
783 where
784 -- Make sure that VarE is used if the Constr value relies on a
785 -- function underneath the surface (instead of a constructor).
786 -- See Trac #10796.
787 varOrConE s =
788 case nameSpace s of
789 Just VarName -> return (VarE s)
790 Just DataName -> return (ConE s)
791 _ -> fail $ "Can't construct an expression from name "
792 ++ showName s
793 appE x y = do { a <- x; b <- y; return (AppE a b)}
794 litE c = return (LitE c)
795
796 -- | 'liftData' is a variant of 'lift' in the 'Lift' type class which
797 -- works for any type with a 'Data' instance.
798 liftData :: Data a => a -> Q Exp
799 liftData = dataToExpQ (const Nothing)
800
801 -- | 'dataToPatQ' converts a value to a 'Q Pat' representation of the same
802 -- value, in the SYB style. It takes a function to handle type-specific cases,
803 -- alternatively, pass @const Nothing@ to get default behavior.
804 dataToPatQ :: Data a
805 => (forall b . Data b => b -> Maybe (Q Pat))
806 -> a
807 -> Q Pat
808 dataToPatQ = dataToQa id litP conP
809 where litP l = return (LitP l)
810 conP n ps =
811 case nameSpace n of
812 Just DataName -> do
813 ps' <- sequence ps
814 return (ConP n ps')
815 _ -> fail $ "Can't construct a pattern from name "
816 ++ showName n
817
818 -----------------------------------------------------
819 -- Names and uniques
820 -----------------------------------------------------
821
822 newtype ModName = ModName String -- Module name
823 deriving (Show,Eq,Ord,Data,Generic)
824
825 newtype PkgName = PkgName String -- package name
826 deriving (Show,Eq,Ord,Data,Generic)
827
828 -- | Obtained from 'reifyModule' and 'thisModule'.
829 data Module = Module PkgName ModName -- package qualified module name
830 deriving (Show,Eq,Ord,Data,Generic)
831
832 newtype OccName = OccName String
833 deriving (Show,Eq,Ord,Data,Generic)
834
835 mkModName :: String -> ModName
836 mkModName s = ModName s
837
838 modString :: ModName -> String
839 modString (ModName m) = m
840
841
842 mkPkgName :: String -> PkgName
843 mkPkgName s = PkgName s
844
845 pkgString :: PkgName -> String
846 pkgString (PkgName m) = m
847
848
849 -----------------------------------------------------
850 -- OccName
851 -----------------------------------------------------
852
853 mkOccName :: String -> OccName
854 mkOccName s = OccName s
855
856 occString :: OccName -> String
857 occString (OccName occ) = occ
858
859
860 -----------------------------------------------------
861 -- Names
862 -----------------------------------------------------
863 --
864 -- For "global" names ('NameG') we need a totally unique name,
865 -- so we must include the name-space of the thing
866 --
867 -- For unique-numbered things ('NameU'), we've got a unique reference
868 -- anyway, so no need for name space
869 --
870 -- For dynamically bound thing ('NameS') we probably want them to
871 -- in a context-dependent way, so again we don't want the name
872 -- space. For example:
873 --
874 -- > let v = mkName "T" in [| data $v = $v |]
875 --
876 -- Here we use the same Name for both type constructor and data constructor
877 --
878 --
879 -- NameL and NameG are bound *outside* the TH syntax tree
880 -- either globally (NameG) or locally (NameL). Ex:
881 --
882 -- > f x = $(h [| (map, x) |])
883 --
884 -- The 'map' will be a NameG, and 'x' wil be a NameL
885 --
886 -- These Names should never appear in a binding position in a TH syntax tree
887
888 {- $namecapture #namecapture#
889 Much of 'Name' API is concerned with the problem of /name capture/, which
890 can be seen in the following example.
891
892 > f expr = [| let x = 0 in $expr |]
893 > ...
894 > g x = $( f [| x |] )
895 > h y = $( f [| y |] )
896
897 A naive desugaring of this would yield:
898
899 > g x = let x = 0 in x
900 > h y = let x = 0 in y
901
902 All of a sudden, @g@ and @h@ have different meanings! In this case,
903 we say that the @x@ in the RHS of @g@ has been /captured/
904 by the binding of @x@ in @f@.
905
906 What we actually want is for the @x@ in @f@ to be distinct from the
907 @x@ in @g@, so we get the following desugaring:
908
909 > g x = let x' = 0 in x
910 > h y = let x' = 0 in y
911
912 which avoids name capture as desired.
913
914 In the general case, we say that a @Name@ can be captured if
915 the thing it refers to can be changed by adding new declarations.
916 -}
917
918 {- |
919 An abstract type representing names in the syntax tree.
920
921 'Name's can be constructed in several ways, which come with different
922 name-capture guarantees (see "Language.Haskell.TH.Syntax#namecapture" for
923 an explanation of name capture):
924
925 * the built-in syntax @'f@ and @''T@ can be used to construct names,
926 The expression @'f@ gives a @Name@ which refers to the value @f@
927 currently in scope, and @''T@ gives a @Name@ which refers to the
928 type @T@ currently in scope. These names can never be captured.
929
930 * 'lookupValueName' and 'lookupTypeName' are similar to @'f@ and
931 @''T@ respectively, but the @Name@s are looked up at the point
932 where the current splice is being run. These names can never be
933 captured.
934
935 * 'newName' monadically generates a new name, which can never
936 be captured.
937
938 * 'mkName' generates a capturable name.
939
940 Names constructed using @newName@ and @mkName@ may be used in bindings
941 (such as @let x = ...@ or @\x -> ...@), but names constructed using
942 @lookupValueName@, @lookupTypeName@, @'f@, @''T@ may not.
943 -}
944 data Name = Name OccName NameFlavour deriving (Data, Eq, Generic)
945
946 instance Ord Name where
947 -- check if unique is different before looking at strings
948 (Name o1 f1) `compare` (Name o2 f2) = (f1 `compare` f2) `thenCmp`
949 (o1 `compare` o2)
950
951 data NameFlavour
952 = NameS -- ^ An unqualified name; dynamically bound
953 | NameQ ModName -- ^ A qualified name; dynamically bound
954 | NameU !Int -- ^ A unique local name
955 | NameL !Int -- ^ Local name bound outside of the TH AST
956 | NameG NameSpace PkgName ModName -- ^ Global name bound outside of the TH AST:
957 -- An original name (occurrences only, not binders)
958 -- Need the namespace too to be sure which
959 -- thing we are naming
960 deriving ( Data, Eq, Ord, Show, Generic )
961
962 data NameSpace = VarName -- ^ Variables
963 | DataName -- ^ Data constructors
964 | TcClsName -- ^ Type constructors and classes; Haskell has them
965 -- in the same name space for now.
966 deriving( Eq, Ord, Show, Data, Generic )
967
968 type Uniq = Int
969
970 -- | The name without its module prefix.
971 --
972 -- ==== __Examples__
973 --
974 -- >>> nameBase ''Data.Either.Either
975 -- "Either"
976 -- >>> nameBase (mkName "foo")
977 -- "foo"
978 -- >>> nameBase (mkName "Module.foo")
979 -- "foo"
980 nameBase :: Name -> String
981 nameBase (Name occ _) = occString occ
982
983 -- | Module prefix of a name, if it exists.
984 --
985 -- ==== __Examples__
986 --
987 -- >>> nameModule ''Data.Either.Either
988 -- Just "Data.Either"
989 -- >>> nameModule (mkName "foo")
990 -- Nothing
991 -- >>> nameModule (mkName "Module.foo")
992 -- Just "Module"
993 nameModule :: Name -> Maybe String
994 nameModule (Name _ (NameQ m)) = Just (modString m)
995 nameModule (Name _ (NameG _ _ m)) = Just (modString m)
996 nameModule _ = Nothing
997
998 -- | A name's package, if it exists.
999 --
1000 -- ==== __Examples__
1001 --
1002 -- >>> namePackage ''Data.Either.Either
1003 -- Just "base"
1004 -- >>> namePackage (mkName "foo")
1005 -- Nothing
1006 -- >>> namePackage (mkName "Module.foo")
1007 -- Nothing
1008 namePackage :: Name -> Maybe String
1009 namePackage (Name _ (NameG _ p _)) = Just (pkgString p)
1010 namePackage _ = Nothing
1011
1012 -- | Returns whether a name represents an occurrence of a top-level variable
1013 -- ('VarName'), data constructor ('DataName'), type constructor, or type class
1014 -- ('TcClsName'). If we can't be sure, it returns 'Nothing'.
1015 --
1016 -- ==== __Examples__
1017 --
1018 -- >>> nameSpace 'Prelude.id
1019 -- Just VarName
1020 -- >>> nameSpace (mkName "id")
1021 -- Nothing -- only works for top-level variable names
1022 -- >>> nameSpace 'Data.Maybe.Just
1023 -- Just DataName
1024 -- >>> nameSpace ''Data.Maybe.Maybe
1025 -- Just TcClsName
1026 -- >>> nameSpace ''Data.Ord.Ord
1027 -- Just TcClsName
1028 nameSpace :: Name -> Maybe NameSpace
1029 nameSpace (Name _ (NameG ns _ _)) = Just ns
1030 nameSpace _ = Nothing
1031
1032 {- |
1033 Generate a capturable name. Occurrences of such names will be
1034 resolved according to the Haskell scoping rules at the occurrence
1035 site.
1036
1037 For example:
1038
1039 > f = [| pi + $(varE (mkName "pi")) |]
1040 > ...
1041 > g = let pi = 3 in $f
1042
1043 In this case, @g@ is desugared to
1044
1045 > g = Prelude.pi + 3
1046
1047 Note that @mkName@ may be used with qualified names:
1048
1049 > mkName "Prelude.pi"
1050
1051 See also 'Language.Haskell.TH.Lib.dyn' for a useful combinator. The above example could
1052 be rewritten using 'dyn' as
1053
1054 > f = [| pi + $(dyn "pi") |]
1055 -}
1056 mkName :: String -> Name
1057 -- The string can have a '.', thus "Foo.baz",
1058 -- giving a dynamically-bound qualified name,
1059 -- in which case we want to generate a NameQ
1060 --
1061 -- Parse the string to see if it has a "." in it
1062 -- so we know whether to generate a qualified or unqualified name
1063 -- It's a bit tricky because we need to parse
1064 --
1065 -- > Foo.Baz.x as Qual Foo.Baz x
1066 --
1067 -- So we parse it from back to front
1068 mkName str
1069 = split [] (reverse str)
1070 where
1071 split occ [] = Name (mkOccName occ) NameS
1072 split occ ('.':rev) | not (null occ)
1073 , is_rev_mod_name rev
1074 = Name (mkOccName occ) (NameQ (mkModName (reverse rev)))
1075 -- The 'not (null occ)' guard ensures that
1076 -- mkName "&." = Name "&." NameS
1077 -- The 'is_rev_mod' guards ensure that
1078 -- mkName ".&" = Name ".&" NameS
1079 -- mkName "^.." = Name "^.." NameS -- Trac #8633
1080 -- mkName "Data.Bits..&" = Name ".&" (NameQ "Data.Bits")
1081 -- This rather bizarre case actually happened; (.&.) is in Data.Bits
1082 split occ (c:rev) = split (c:occ) rev
1083
1084 -- Recognises a reversed module name xA.yB.C,
1085 -- with at least one component,
1086 -- and each component looks like a module name
1087 -- (i.e. non-empty, starts with capital, all alpha)
1088 is_rev_mod_name rev_mod_str
1089 | (compt, rest) <- break (== '.') rev_mod_str
1090 , not (null compt), isUpper (last compt), all is_mod_char compt
1091 = case rest of
1092 [] -> True
1093 (_dot : rest') -> is_rev_mod_name rest'
1094 | otherwise
1095 = False
1096
1097 is_mod_char c = isAlphaNum c || c == '_' || c == '\''
1098
1099 -- | Only used internally
1100 mkNameU :: String -> Uniq -> Name
1101 mkNameU s u = Name (mkOccName s) (NameU u)
1102
1103 -- | Only used internally
1104 mkNameL :: String -> Uniq -> Name
1105 mkNameL s u = Name (mkOccName s) (NameL u)
1106
1107 -- | Used for 'x etc, but not available to the programmer
1108 mkNameG :: NameSpace -> String -> String -> String -> Name
1109 mkNameG ns pkg modu occ
1110 = Name (mkOccName occ) (NameG ns (mkPkgName pkg) (mkModName modu))
1111
1112 mkNameS :: String -> Name
1113 mkNameS n = Name (mkOccName n) NameS
1114
1115 mkNameG_v, mkNameG_tc, mkNameG_d :: String -> String -> String -> Name
1116 mkNameG_v = mkNameG VarName
1117 mkNameG_tc = mkNameG TcClsName
1118 mkNameG_d = mkNameG DataName
1119
1120 data NameIs = Alone | Applied | Infix
1121
1122 showName :: Name -> String
1123 showName = showName' Alone
1124
1125 showName' :: NameIs -> Name -> String
1126 showName' ni nm
1127 = case ni of
1128 Alone -> nms
1129 Applied
1130 | pnam -> nms
1131 | otherwise -> "(" ++ nms ++ ")"
1132 Infix
1133 | pnam -> "`" ++ nms ++ "`"
1134 | otherwise -> nms
1135 where
1136 -- For now, we make the NameQ and NameG print the same, even though
1137 -- NameQ is a qualified name (so what it means depends on what the
1138 -- current scope is), and NameG is an original name (so its meaning
1139 -- should be independent of what's in scope.
1140 -- We may well want to distinguish them in the end.
1141 -- Ditto NameU and NameL
1142 nms = case nm of
1143 Name occ NameS -> occString occ
1144 Name occ (NameQ m) -> modString m ++ "." ++ occString occ
1145 Name occ (NameG _ _ m) -> modString m ++ "." ++ occString occ
1146 Name occ (NameU u) -> occString occ ++ "_" ++ show u
1147 Name occ (NameL u) -> occString occ ++ "_" ++ show u
1148
1149 pnam = classify nms
1150
1151 -- True if we are function style, e.g. f, [], (,)
1152 -- False if we are operator style, e.g. +, :+
1153 classify "" = False -- shouldn't happen; . operator is handled below
1154 classify (x:xs) | isAlpha x || (x `elem` "_[]()") =
1155 case dropWhile (/='.') xs of
1156 (_:xs') -> classify xs'
1157 [] -> True
1158 | otherwise = False
1159
1160 instance Show Name where
1161 show = showName
1162
1163 -- Tuple data and type constructors
1164 -- | Tuple data constructor
1165 tupleDataName :: Int -> Name
1166 -- | Tuple type constructor
1167 tupleTypeName :: Int -> Name
1168
1169 tupleDataName 0 = mk_tup_name 0 DataName
1170 tupleDataName 1 = error "tupleDataName 1"
1171 tupleDataName n = mk_tup_name (n-1) DataName
1172
1173 tupleTypeName 0 = mk_tup_name 0 TcClsName
1174 tupleTypeName 1 = error "tupleTypeName 1"
1175 tupleTypeName n = mk_tup_name (n-1) TcClsName
1176
1177 mk_tup_name :: Int -> NameSpace -> Name
1178 mk_tup_name n_commas space
1179 = Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
1180 where
1181 occ = mkOccName ('(' : replicate n_commas ',' ++ ")")
1182 tup_mod = mkModName "GHC.Tuple"
1183
1184 -- Unboxed tuple data and type constructors
1185 -- | Unboxed tuple data constructor
1186 unboxedTupleDataName :: Int -> Name
1187 -- | Unboxed tuple type constructor
1188 unboxedTupleTypeName :: Int -> Name
1189
1190 unboxedTupleDataName 0 = error "unboxedTupleDataName 0"
1191 unboxedTupleDataName 1 = error "unboxedTupleDataName 1"
1192 unboxedTupleDataName n = mk_unboxed_tup_name (n-1) DataName
1193
1194 unboxedTupleTypeName 0 = error "unboxedTupleTypeName 0"
1195 unboxedTupleTypeName 1 = error "unboxedTupleTypeName 1"
1196 unboxedTupleTypeName n = mk_unboxed_tup_name (n-1) TcClsName
1197
1198 mk_unboxed_tup_name :: Int -> NameSpace -> Name
1199 mk_unboxed_tup_name n_commas space
1200 = Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
1201 where
1202 occ = mkOccName ("(#" ++ replicate n_commas ',' ++ "#)")
1203 tup_mod = mkModName "GHC.Tuple"
1204
1205 -----------------------------------------------------
1206 -- Locations
1207 -----------------------------------------------------
1208
1209 data Loc
1210 = Loc { loc_filename :: String
1211 , loc_package :: String
1212 , loc_module :: String
1213 , loc_start :: CharPos
1214 , loc_end :: CharPos }
1215 deriving( Show, Eq, Ord, Data, Generic )
1216
1217 type CharPos = (Int, Int) -- ^ Line and character position
1218
1219
1220 -----------------------------------------------------
1221 --
1222 -- The Info returned by reification
1223 --
1224 -----------------------------------------------------
1225
1226 -- | Obtained from 'reify' in the 'Q' Monad.
1227 data Info
1228 =
1229 -- | A class, with a list of its visible instances
1230 ClassI
1231 Dec
1232 [InstanceDec]
1233
1234 -- | A class method
1235 | ClassOpI
1236 Name
1237 Type
1238 ParentName
1239
1240 -- | A \"plain\" type constructor. \"Fancier\" type constructors are returned using 'PrimTyConI' or 'FamilyI' as appropriate
1241 | TyConI
1242 Dec
1243
1244 -- | A type or data family, with a list of its visible instances. A closed
1245 -- type family is returned with 0 instances.
1246 | FamilyI
1247 Dec
1248 [InstanceDec]
1249
1250 -- | A \"primitive\" type constructor, which can't be expressed with a 'Dec'. Examples: @(->)@, @Int#@.
1251 | PrimTyConI
1252 Name
1253 Arity
1254 Unlifted
1255
1256 -- | A data constructor
1257 | DataConI
1258 Name
1259 Type
1260 ParentName
1261
1262 -- | A pattern synonym.
1263 | PatSynI
1264 Name
1265 PatSynType
1266
1267 {- |
1268 A \"value\" variable (as opposed to a type variable, see 'TyVarI').
1269
1270 The @Maybe Dec@ field contains @Just@ the declaration which
1271 defined the variable -- including the RHS of the declaration --
1272 or else @Nothing@, in the case where the RHS is unavailable to
1273 the compiler. At present, this value is _always_ @Nothing@:
1274 returning the RHS has not yet been implemented because of
1275 lack of interest.
1276 -}
1277 | VarI
1278 Name
1279 Type
1280 (Maybe Dec)
1281
1282 {- |
1283 A type variable.
1284
1285 The @Type@ field contains the type which underlies the variable.
1286 At present, this is always @'VarT' theName@, but future changes
1287 may permit refinement of this.
1288 -}
1289 | TyVarI -- Scoped type variable
1290 Name
1291 Type -- What it is bound to
1292 deriving( Show, Eq, Ord, Data, Generic )
1293
1294 -- | Obtained from 'reifyModule' in the 'Q' Monad.
1295 data ModuleInfo =
1296 -- | Contains the import list of the module.
1297 ModuleInfo [Module]
1298 deriving( Show, Eq, Ord, Data, Generic )
1299
1300 {- |
1301 In 'ClassOpI' and 'DataConI', name of the parent class or type
1302 -}
1303 type ParentName = Name
1304
1305 -- | In 'UnboxedSumE' and 'UnboxedSumP', the number associated with a
1306 -- particular data constructor. 'SumAlt's are one-indexed and should never
1307 -- exceed the value of its corresponding 'SumArity'. For example:
1308 --
1309 -- * @(\#_|\#)@ has 'SumAlt' 1 (out of a total 'SumArity' of 2)
1310 --
1311 -- * @(\#|_\#)@ has 'SumAlt' 2 (out of a total 'SumArity' of 2)
1312 type SumAlt = Int
1313
1314 -- | In 'UnboxedSumE', 'UnboxedSumT', and 'UnboxedSumP', the total number of
1315 -- 'SumAlt's. For example, @(\#|\#)@ has a 'SumArity' of 2.
1316 type SumArity = Int
1317
1318 -- | In 'PrimTyConI', arity of the type constructor
1319 type Arity = Int
1320
1321 -- | In 'PrimTyConI', is the type constructor unlifted?
1322 type Unlifted = Bool
1323
1324 -- | 'InstanceDec' desribes a single instance of a class or type function.
1325 -- It is just a 'Dec', but guaranteed to be one of the following:
1326 --
1327 -- * 'InstanceD' (with empty @['Dec']@)
1328 --
1329 -- * 'DataInstD' or 'NewtypeInstD' (with empty derived @['Name']@)
1330 --
1331 -- * 'TySynInstD'
1332 type InstanceDec = Dec
1333
1334 data Fixity = Fixity Int FixityDirection
1335 deriving( Eq, Ord, Show, Data, Generic )
1336 data FixityDirection = InfixL | InfixR | InfixN
1337 deriving( Eq, Ord, Show, Data, Generic )
1338
1339 -- | Highest allowed operator precedence for 'Fixity' constructor (answer: 9)
1340 maxPrecedence :: Int
1341 maxPrecedence = (9::Int)
1342
1343 -- | Default fixity: @infixl 9@
1344 defaultFixity :: Fixity
1345 defaultFixity = Fixity maxPrecedence InfixL
1346
1347
1348 {-
1349 Note [Unresolved infix]
1350 ~~~~~~~~~~~~~~~~~~~~~~~
1351 -}
1352 {- $infix #infix#
1353 When implementing antiquotation for quasiquoters, one often wants
1354 to parse strings into expressions:
1355
1356 > parse :: String -> Maybe Exp
1357
1358 But how should we parse @a + b * c@? If we don't know the fixities of
1359 @+@ and @*@, we don't know whether to parse it as @a + (b * c)@ or @(a
1360 + b) * c@.
1361
1362 In cases like this, use 'UInfixE', 'UInfixP', or 'UInfixT', which stand for
1363 \"unresolved infix expression/pattern/type\", respectively. When the compiler
1364 is given a splice containing a tree of @UInfixE@ applications such as
1365
1366 > UInfixE
1367 > (UInfixE e1 op1 e2)
1368 > op2
1369 > (UInfixE e3 op3 e4)
1370
1371 it will look up and the fixities of the relevant operators and
1372 reassociate the tree as necessary.
1373
1374 * trees will not be reassociated across 'ParensE', 'ParensP', or 'ParensT',
1375 which are of use for parsing expressions like
1376
1377 > (a + b * c) + d * e
1378
1379 * 'InfixE', 'InfixP', and 'InfixT' expressions are never reassociated.
1380
1381 * The 'UInfixE' constructor doesn't support sections. Sections
1382 such as @(a *)@ have no ambiguity, so 'InfixE' suffices. For longer
1383 sections such as @(a + b * c -)@, use an 'InfixE' constructor for the
1384 outer-most section, and use 'UInfixE' constructors for all
1385 other operators:
1386
1387 > InfixE
1388 > Just (UInfixE ...a + b * c...)
1389 > op
1390 > Nothing
1391
1392 Sections such as @(a + b +)@ and @((a + b) +)@ should be rendered
1393 into 'Exp's differently:
1394
1395 > (+ a + b) ---> InfixE Nothing + (Just $ UInfixE a + b)
1396 > -- will result in a fixity error if (+) is left-infix
1397 > (+ (a + b)) ---> InfixE Nothing + (Just $ ParensE $ UInfixE a + b)
1398 > -- no fixity errors
1399
1400 * Quoted expressions such as
1401
1402 > [| a * b + c |] :: Q Exp
1403 > [p| a : b : c |] :: Q Pat
1404 > [t| T + T |] :: Q Type
1405
1406 will never contain 'UInfixE', 'UInfixP', 'UInfixT', 'InfixT', 'ParensE',
1407 'ParensP', or 'ParensT' constructors.
1408
1409 -}
1410
1411 -----------------------------------------------------
1412 --
1413 -- The main syntax data types
1414 --
1415 -----------------------------------------------------
1416
1417 data Lit = CharL Char
1418 | StringL String
1419 | IntegerL Integer -- ^ Used for overloaded and non-overloaded
1420 -- literals. We don't have a good way to
1421 -- represent non-overloaded literals at
1422 -- the moment. Maybe that doesn't matter?
1423 | RationalL Rational -- Ditto
1424 | IntPrimL Integer
1425 | WordPrimL Integer
1426 | FloatPrimL Rational
1427 | DoublePrimL Rational
1428 | StringPrimL [Word8] -- ^ A primitive C-style string, type Addr#
1429 | CharPrimL Char
1430 deriving( Show, Eq, Ord, Data, Generic )
1431
1432 -- We could add Int, Float, Double etc, as we do in HsLit,
1433 -- but that could complicate the
1434 -- supposedly-simple TH.Syntax literal type
1435
1436 -- | Pattern in Haskell given in @{}@
1437 data Pat
1438 = LitP Lit -- ^ @{ 5 or \'c\' }@
1439 | VarP Name -- ^ @{ x }@
1440 | TupP [Pat] -- ^ @{ (p1,p2) }@
1441 | UnboxedTupP [Pat] -- ^ @{ (\# p1,p2 \#) }@
1442 | UnboxedSumP Pat SumAlt SumArity -- ^ @{ (\#|p|\#) }@
1443 | ConP Name [Pat] -- ^ @data T1 = C1 t1 t2; {C1 p1 p1} = e@
1444 | InfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
1445 | UInfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
1446 --
1447 -- See "Language.Haskell.TH.Syntax#infix"
1448 | ParensP Pat -- ^ @{(p)}@
1449 --
1450 -- See "Language.Haskell.TH.Syntax#infix"
1451 | TildeP Pat -- ^ @{ ~p }@
1452 | BangP Pat -- ^ @{ !p }@
1453 | AsP Name Pat -- ^ @{ x \@ p }@
1454 | WildP -- ^ @{ _ }@
1455 | RecP Name [FieldPat] -- ^ @f (Pt { pointx = x }) = g x@
1456 | ListP [ Pat ] -- ^ @{ [1,2,3] }@
1457 | SigP Pat Type -- ^ @{ p :: t }@
1458 | ViewP Exp Pat -- ^ @{ e -> p }@
1459 deriving( Show, Eq, Ord, Data, Generic )
1460
1461 type FieldPat = (Name,Pat)
1462
1463 data Match = Match Pat Body [Dec] -- ^ @case e of { pat -> body where decs }@
1464 deriving( Show, Eq, Ord, Data, Generic )
1465 data Clause = Clause [Pat] Body [Dec]
1466 -- ^ @f { p1 p2 = body where decs }@
1467 deriving( Show, Eq, Ord, Data, Generic )
1468
1469 data Exp
1470 = VarE Name -- ^ @{ x }@
1471 | ConE Name -- ^ @data T1 = C1 t1 t2; p = {C1} e1 e2 @
1472 | LitE Lit -- ^ @{ 5 or \'c\'}@
1473 | AppE Exp Exp -- ^ @{ f x }@
1474 | AppTypeE Exp Type -- ^ @{ f \@Int }
1475
1476 | InfixE (Maybe Exp) Exp (Maybe Exp) -- ^ @{x + y} or {(x+)} or {(+ x)} or {(+)}@
1477
1478 -- It's a bit gruesome to use an Exp as the
1479 -- operator, but how else can we distinguish
1480 -- constructors from non-constructors?
1481 -- Maybe there should be a var-or-con type?
1482 -- Or maybe we should leave it to the String itself?
1483
1484 | UInfixE Exp Exp Exp -- ^ @{x + y}@
1485 --
1486 -- See "Language.Haskell.TH.Syntax#infix"
1487 | ParensE Exp -- ^ @{ (e) }@
1488 --
1489 -- See "Language.Haskell.TH.Syntax#infix"
1490 | LamE [Pat] Exp -- ^ @{ \\ p1 p2 -> e }@
1491 | LamCaseE [Match] -- ^ @{ \\case m1; m2 }@
1492 | TupE [Exp] -- ^ @{ (e1,e2) } @
1493 | UnboxedTupE [Exp] -- ^ @{ (\# e1,e2 \#) } @
1494 | UnboxedSumE Exp SumAlt SumArity -- ^ @{ (\#|e|\#) }@
1495 | CondE Exp Exp Exp -- ^ @{ if e1 then e2 else e3 }@
1496 | MultiIfE [(Guard, Exp)] -- ^ @{ if | g1 -> e1 | g2 -> e2 }@
1497 | LetE [Dec] Exp -- ^ @{ let x=e1; y=e2 in e3 }@
1498 | CaseE Exp [Match] -- ^ @{ case e of m1; m2 }@
1499 | DoE [Stmt] -- ^ @{ do { p <- e1; e2 } }@
1500 | CompE [Stmt] -- ^ @{ [ (x,y) | x <- xs, y <- ys ] }@
1501 --
1502 -- The result expression of the comprehension is
1503 -- the /last/ of the @'Stmt'@s, and should be a 'NoBindS'.
1504 --
1505 -- E.g. translation:
1506 --
1507 -- > [ f x | x <- xs ]
1508 --
1509 -- > CompE [BindS (VarP x) (VarE xs), NoBindS (AppE (VarE f) (VarE x))]
1510
1511 | ArithSeqE Range -- ^ @{ [ 1 ,2 .. 10 ] }@
1512 | ListE [ Exp ] -- ^ @{ [1,2,3] }@
1513 | SigE Exp Type -- ^ @{ e :: t }@
1514 | RecConE Name [FieldExp] -- ^ @{ T { x = y, z = w } }@
1515 | RecUpdE Exp [FieldExp] -- ^ @{ (f x) { z = w } }@
1516 | StaticE Exp -- ^ @{ static e }@
1517 | UnboundVarE Name -- ^ @{ _x }@ (hole)
1518 deriving( Show, Eq, Ord, Data, Generic )
1519
1520 type FieldExp = (Name,Exp)
1521
1522 -- Omitted: implicit parameters
1523
1524 data Body
1525 = GuardedB [(Guard,Exp)] -- ^ @f p { | e1 = e2
1526 -- | e3 = e4 }
1527 -- where ds@
1528 | NormalB Exp -- ^ @f p { = e } where ds@
1529 deriving( Show, Eq, Ord, Data, Generic )
1530
1531 data Guard
1532 = NormalG Exp -- ^ @f x { | odd x } = x@
1533 | PatG [Stmt] -- ^ @f x { | Just y <- x, Just z <- y } = z@
1534 deriving( Show, Eq, Ord, Data, Generic )
1535
1536 data Stmt
1537 = BindS Pat Exp
1538 | LetS [ Dec ]
1539 | NoBindS Exp
1540 | ParS [[Stmt]]
1541 deriving( Show, Eq, Ord, Data, Generic )
1542
1543 data Range = FromR Exp | FromThenR Exp Exp
1544 | FromToR Exp Exp | FromThenToR Exp Exp Exp
1545 deriving( Show, Eq, Ord, Data, Generic )
1546
1547 data Dec
1548 = FunD Name [Clause] -- ^ @{ f p1 p2 = b where decs }@
1549 | ValD Pat Body [Dec] -- ^ @{ p = b where decs }@
1550 | DataD Cxt Name [TyVarBndr]
1551 (Maybe Kind) -- Kind signature (allowed only for GADTs)
1552 [Con] Cxt
1553 -- ^ @{ data Cxt x => T x = A x | B (T x)
1554 -- deriving (Z,W)}@
1555 | NewtypeD Cxt Name [TyVarBndr]
1556 (Maybe Kind) -- Kind signature
1557 Con Cxt -- ^ @{ newtype Cxt x => T x = A (B x)
1558 -- deriving (Z,W Q)}@
1559 | TySynD Name [TyVarBndr] Type -- ^ @{ type T x = (x,x) }@
1560 | ClassD Cxt Name [TyVarBndr]
1561 [FunDep] [Dec] -- ^ @{ class Eq a => Ord a where ds }@
1562 | InstanceD (Maybe Overlap) Cxt Type [Dec]
1563 -- ^ @{ instance {\-\# OVERLAPS \#-\}
1564 -- Show w => Show [w] where ds }@
1565 | SigD Name Type -- ^ @{ length :: [a] -> Int }@
1566 | ForeignD Foreign -- ^ @{ foreign import ... }
1567 --{ foreign export ... }@
1568
1569 | InfixD Fixity Name -- ^ @{ infix 3 foo }@
1570
1571 -- | pragmas
1572 | PragmaD Pragma -- ^ @{ {\-\# INLINE [1] foo \#-\} }@
1573
1574 -- | data families (may also appear in [Dec] of 'ClassD' and 'InstanceD')
1575 | DataFamilyD Name [TyVarBndr]
1576 (Maybe Kind)
1577 -- ^ @{ data family T a b c :: * }@
1578
1579 | DataInstD Cxt Name [Type]
1580 (Maybe Kind) -- Kind signature
1581 [Con] Cxt -- ^ @{ data instance Cxt x => T [x]
1582 -- = A x | B (T x) deriving (Z,W)}@
1583
1584 | NewtypeInstD Cxt Name [Type]
1585 (Maybe Kind) -- Kind signature
1586 Con Cxt -- ^ @{ newtype instance Cxt x => T [x]
1587 -- = A (B x) deriving (Z,W)}@
1588 | TySynInstD Name TySynEqn -- ^ @{ type instance ... }@
1589
1590 -- | open type families (may also appear in [Dec] of 'ClassD' and 'InstanceD')
1591 | OpenTypeFamilyD TypeFamilyHead
1592 -- ^ @{ type family T a b c = (r :: *) | r -> a b }@
1593
1594 | ClosedTypeFamilyD TypeFamilyHead [TySynEqn]
1595 -- ^ @{ type family F a b = (r :: *) | r -> a where ... }@
1596
1597 | RoleAnnotD Name [Role] -- ^ @{ type role T nominal representational }@
1598 | StandaloneDerivD Cxt Type -- ^ @{ deriving instance Ord a => Ord (Foo a) }@
1599 | DefaultSigD Name Type -- ^ @{ default size :: Data a => a -> Int }@
1600
1601 -- | Pattern Synonyms
1602 | PatSynD Name PatSynArgs PatSynDir Pat
1603 -- ^ @{ pattern P v1 v2 .. vn <- p }@ unidirectional or
1604 -- @{ pattern P v1 v2 .. vn = p }@ implicit bidirectional or
1605 -- @{ pattern P v1 v2 .. vn <- p
1606 -- where P v1 v2 .. vn = e }@ explicit bidirectional
1607 --
1608 -- also, besides prefix pattern synonyms, both infix and record
1609 -- pattern synonyms are supported. See 'PatSynArgs' for details
1610
1611 | PatSynSigD Name PatSynType -- ^ A pattern synonym's type signature.
1612 deriving( Show, Eq, Ord, Data, Generic )
1613
1614 -- | Varieties of allowed instance overlap.
1615 data Overlap = Overlappable -- ^ May be overlapped by more specific instances
1616 | Overlapping -- ^ May overlap a more general instance
1617 | Overlaps -- ^ Both 'Overlapping' and 'Overlappable'
1618 | Incoherent -- ^ Both 'Overlappable' and 'Overlappable', and
1619 -- pick an arbitrary one if multiple choices are
1620 -- available.
1621 deriving( Show, Eq, Ord, Data, Generic )
1622
1623 -- | A Pattern synonym's type. Note that a pattern synonym's *fully*
1624 -- specified type has a peculiar shape coming with two forall
1625 -- quantifiers and two constraint contexts. For example, consider the
1626 -- pattern synonym
1627 --
1628 -- pattern P x1 x2 ... xn = <some-pattern>
1629 --
1630 -- P's complete type is of the following form
1631 --
1632 -- forall universals. required constraints
1633 -- => forall existentials. provided constraints
1634 -- => t1 -> t2 -> ... -> tn -> t
1635 --
1636 -- consisting of four parts:
1637 --
1638 -- 1) the (possibly empty lists of) universally quantified type
1639 -- variables and required constraints on them.
1640 -- 2) the (possibly empty lists of) existentially quantified
1641 -- type variables and the provided constraints on them.
1642 -- 3) the types t1, t2, .., tn of x1, x2, .., xn, respectively
1643 -- 4) the type t of <some-pattern>, mentioning only universals.
1644 --
1645 -- Pattern synonym types interact with TH when (a) reifying a pattern
1646 -- synonym, (b) pretty printing, or (c) specifying a pattern synonym's
1647 -- type signature explicitly:
1648 --
1649 -- (a) Reification always returns a pattern synonym's *fully* specified
1650 -- type in abstract syntax.
1651 --
1652 -- (b) Pretty printing via 'pprPatSynType' abbreviates a pattern
1653 -- synonym's type unambiguously in concrete syntax: The rule of
1654 -- thumb is to print initial empty universals and the required
1655 -- context as `() =>`, if existentials and a provided context
1656 -- follow. If only universals and their required context, but no
1657 -- existentials are specified, only the universals and their
1658 -- required context are printed. If both or none are specified, so
1659 -- both (or none) are printed.
1660 --
1661 -- (c) When specifying a pattern synonym's type explicitly with
1662 -- 'PatSynSigD' either one of the universals, the existentials, or
1663 -- their contexts may be left empty.
1664 --
1665 -- See the GHC users guide for more information on pattern synonyms
1666 -- and their types: https://downloads.haskell.org/~ghc/latest/docs/html/
1667 -- users_guide/syntax-extns.html#pattern-synonyms.
1668 type PatSynType = Type
1669
1670 -- | Common elements of 'OpenTypeFamilyD' and 'ClosedTypeFamilyD'. By
1671 -- analogy with "head" for type classes and type class instances as
1672 -- defined in /Type classes: an exploration of the design space/, the
1673 -- @TypeFamilyHead@ is defined to be the elements of the declaration
1674 -- between @type family@ and @where@.
1675 data TypeFamilyHead =
1676 TypeFamilyHead Name [TyVarBndr] FamilyResultSig (Maybe InjectivityAnn)
1677 deriving( Show, Eq, Ord, Data, Generic )
1678
1679 -- | One equation of a type family instance or closed type family. The
1680 -- arguments are the left-hand-side type patterns and the right-hand-side
1681 -- result.
1682 data TySynEqn = TySynEqn [Type] Type
1683 deriving( Show, Eq, Ord, Data, Generic )
1684
1685 data FunDep = FunDep [Name] [Name]
1686 deriving( Show, Eq, Ord, Data, Generic )
1687
1688 data FamFlavour = TypeFam | DataFam
1689 deriving( Show, Eq, Ord, Data, Generic )
1690
1691 data Foreign = ImportF Callconv Safety String Name Type
1692 | ExportF Callconv String Name Type
1693 deriving( Show, Eq, Ord, Data, Generic )
1694
1695 -- keep Callconv in sync with module ForeignCall in ghc/compiler/prelude/ForeignCall.hs
1696 data Callconv = CCall | StdCall | CApi | Prim | JavaScript
1697 deriving( Show, Eq, Ord, Data, Generic )
1698
1699 data Safety = Unsafe | Safe | Interruptible
1700 deriving( Show, Eq, Ord, Data, Generic )
1701
1702 data Pragma = InlineP Name Inline RuleMatch Phases
1703 | SpecialiseP Name Type (Maybe Inline) Phases
1704 | SpecialiseInstP Type
1705 | RuleP String [RuleBndr] Exp Exp Phases
1706 | AnnP AnnTarget Exp
1707 | LineP Int String
1708 deriving( Show, Eq, Ord, Data, Generic )
1709
1710 data Inline = NoInline
1711 | Inline
1712 | Inlinable
1713 deriving (Show, Eq, Ord, Data, Generic)
1714
1715 data RuleMatch = ConLike
1716 | FunLike
1717 deriving (Show, Eq, Ord, Data, Generic)
1718
1719 data Phases = AllPhases
1720 | FromPhase Int
1721 | BeforePhase Int
1722 deriving (Show, Eq, Ord, Data, Generic)
1723
1724 data RuleBndr = RuleVar Name
1725 | TypedRuleVar Name Type
1726 deriving (Show, Eq, Ord, Data, Generic)
1727
1728 data AnnTarget = ModuleAnnotation
1729 | TypeAnnotation Name
1730 | ValueAnnotation Name
1731 deriving (Show, Eq, Ord, Data, Generic)
1732
1733 type Cxt = [Pred] -- ^ @(Eq a, Ord b)@
1734
1735 -- | Since the advent of @ConstraintKinds@, constraints are really just types.
1736 -- Equality constraints use the 'EqualityT' constructor. Constraints may also
1737 -- be tuples of other constraints.
1738 type Pred = Type
1739
1740 data SourceUnpackedness
1741 = NoSourceUnpackedness -- ^ @C a@
1742 | SourceNoUnpack -- ^ @C { {\-\# NOUNPACK \#-\} } a@
1743 | SourceUnpack -- ^ @C { {\-\# UNPACK \#-\} } a@
1744 deriving (Show, Eq, Ord, Data, Generic)
1745
1746 data SourceStrictness = NoSourceStrictness -- ^ @C a@
1747 | SourceLazy -- ^ @C {~}a@
1748 | SourceStrict -- ^ @C {!}a@
1749 deriving (Show, Eq, Ord, Data, Generic)
1750
1751 -- | Unlike 'SourceStrictness' and 'SourceUnpackedness', 'DecidedStrictness'
1752 -- refers to the strictness that the compiler chooses for a data constructor
1753 -- field, which may be different from what is written in source code. See
1754 -- 'reifyConStrictness' for more information.
1755 data DecidedStrictness = DecidedLazy
1756 | DecidedStrict
1757 | DecidedUnpack
1758 deriving (Show, Eq, Ord, Data, Generic)
1759
1760 data Con = NormalC Name [BangType] -- ^ @C Int a@
1761 | RecC Name [VarBangType] -- ^ @C { v :: Int, w :: a }@
1762 | InfixC BangType Name BangType -- ^ @Int :+ a@
1763 | ForallC [TyVarBndr] Cxt Con -- ^ @forall a. Eq a => C [a]@
1764 | GadtC [Name] [BangType]
1765 Type -- See Note [GADT return type]
1766 -- ^ @C :: a -> b -> T b Int@
1767 | RecGadtC [Name] [VarBangType]
1768 Type -- See Note [GADT return type]
1769 -- ^ @C :: { v :: Int } -> T b Int@
1770 deriving (Show, Eq, Ord, Data, Generic)
1771
1772 -- Note [GADT return type]
1773 -- ~~~~~~~~~~~~~~~~~~~~~~~
1774 --
1775 -- The return type of a GADT constructor does not necessarily match the name of
1776 -- the data type:
1777 --
1778 -- type S = T
1779 --
1780 -- data T a where
1781 -- MkT :: S Int
1782 --
1783 --
1784 -- type S a = T
1785 --
1786 -- data T a where
1787 -- MkT :: S Char Int
1788 --
1789 --
1790 -- type Id a = a
1791 -- type S a = T
1792 --
1793 -- data T a where
1794 -- MkT :: Id (S Char Int)
1795 --
1796 --
1797 -- That is why we allow the return type stored by a constructor to be an
1798 -- arbitrary type. See also #11341
1799
1800 data Bang = Bang SourceUnpackedness SourceStrictness
1801 -- ^ @C { {\-\# UNPACK \#-\} !}a@
1802 deriving (Show, Eq, Ord, Data, Generic)
1803
1804 type BangType = (Bang, Type)
1805 type VarBangType = (Name, Bang, Type)
1806
1807 -- | As of @template-haskell-2.11.0.0@, 'Strict' has been replaced by 'Bang'.
1808 type Strict = Bang
1809
1810 -- | As of @template-haskell-2.11.0.0@, 'StrictType' has been replaced by
1811 -- 'BangType'.
1812 type StrictType = BangType
1813
1814 -- | As of @template-haskell-2.11.0.0@, 'VarStrictType' has been replaced by
1815 -- 'VarBangType'.
1816 type VarStrictType = VarBangType
1817
1818 -- | A pattern synonym's directionality.
1819 data PatSynDir
1820 = Unidir -- ^ @pattern P x {<-} p@
1821 | ImplBidir -- ^ @pattern P x {=} p@
1822 | ExplBidir [Clause] -- ^ @pattern P x {<-} p where P x = e@
1823 deriving( Show, Eq, Ord, Data, Generic )
1824
1825 -- | A pattern synonym's argument type.
1826 data PatSynArgs
1827 = PrefixPatSyn [Name] -- ^ @pattern P {x y z} = p@
1828 | InfixPatSyn Name Name -- ^ @pattern {x P y} = p@
1829 | RecordPatSyn [Name] -- ^ @pattern P { {x,y,z} } = p@
1830 deriving( Show, Eq, Ord, Data, Generic )
1831
1832 data Type = ForallT [TyVarBndr] Cxt Type -- ^ @forall \<vars\>. \<ctxt\> -> \<type\>@
1833 | AppT Type Type -- ^ @T a b@
1834 | SigT Type Kind -- ^ @t :: k@
1835 | VarT Name -- ^ @a@
1836 | ConT Name -- ^ @T@
1837 | PromotedT Name -- ^ @'T@
1838 | InfixT Type Name Type -- ^ @T + T@
1839 | UInfixT Type Name Type -- ^ @T + T@
1840 --
1841 -- See "Language.Haskell.TH.Syntax#infix"
1842 | ParensT Type -- ^ @(T)@
1843
1844 -- See Note [Representing concrete syntax in types]
1845 | TupleT Int -- ^ @(,), (,,), etc.@
1846 | UnboxedTupleT Int -- ^ @(\#,\#), (\#,,\#), etc.@
1847 | UnboxedSumT SumArity -- ^ @(\#|\#), (\#||\#), etc.@
1848 | ArrowT -- ^ @->@
1849 | EqualityT -- ^ @~@
1850 | ListT -- ^ @[]@
1851 | PromotedTupleT Int -- ^ @'(), '(,), '(,,), etc.@
1852 | PromotedNilT -- ^ @'[]@
1853 | PromotedConsT -- ^ @(':)@
1854 | StarT -- ^ @*@
1855 | ConstraintT -- ^ @Constraint@
1856 | LitT TyLit -- ^ @0,1,2, etc.@
1857 | WildCardT -- ^ @_,
1858 deriving( Show, Eq, Ord, Data, Generic )
1859
1860 data TyVarBndr = PlainTV Name -- ^ @a@
1861 | KindedTV Name Kind -- ^ @(a :: k)@
1862 deriving( Show, Eq, Ord, Data, Generic )
1863
1864 -- | Type family result signature
1865 data FamilyResultSig = NoSig -- ^ no signature
1866 | KindSig Kind -- ^ @k@
1867 | TyVarSig TyVarBndr -- ^ @= r, = (r :: k)@
1868 deriving( Show, Eq, Ord, Data, Generic )
1869
1870 -- | Injectivity annotation
1871 data InjectivityAnn = InjectivityAnn Name [Name]
1872 deriving ( Show, Eq, Ord, Data, Generic )
1873
1874 data TyLit = NumTyLit Integer -- ^ @2@
1875 | StrTyLit String -- ^ @"Hello"@
1876 deriving ( Show, Eq, Ord, Data, Generic )
1877
1878 -- | Role annotations
1879 data Role = NominalR -- ^ @nominal@
1880 | RepresentationalR -- ^ @representational@
1881 | PhantomR -- ^ @phantom@
1882 | InferR -- ^ @_@
1883 deriving( Show, Eq, Ord, Data, Generic )
1884
1885 -- | Annotation target for reifyAnnotations
1886 data AnnLookup = AnnLookupModule Module
1887 | AnnLookupName Name
1888 deriving( Show, Eq, Ord, Data, Generic )
1889
1890 -- | To avoid duplication between kinds and types, they
1891 -- are defined to be the same. Naturally, you would never
1892 -- have a type be 'StarT' and you would never have a kind
1893 -- be 'SigT', but many of the other constructors are shared.
1894 -- Note that the kind @Bool@ is denoted with 'ConT', not
1895 -- 'PromotedT'. Similarly, tuple kinds are made with 'TupleT',
1896 -- not 'PromotedTupleT'.
1897
1898 type Kind = Type
1899
1900 {- Note [Representing concrete syntax in types]
1901 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1902 Haskell has a rich concrete syntax for types, including
1903 t1 -> t2, (t1,t2), [t], and so on
1904 In TH we represent all of this using AppT, with a distinguished
1905 type constructor at the head. So,
1906 Type TH representation
1907 -----------------------------------------------
1908 t1 -> t2 ArrowT `AppT` t2 `AppT` t2
1909 [t] ListT `AppT` t
1910 (t1,t2) TupleT 2 `AppT` t1 `AppT` t2
1911 '(t1,t2) PromotedTupleT 2 `AppT` t1 `AppT` t2
1912
1913 But if the original HsSyn used prefix application, we won't use
1914 these special TH constructors. For example
1915 [] t ConT "[]" `AppT` t
1916 (->) t ConT "->" `AppT` t
1917 In this way we can faithfully represent in TH whether the original
1918 HsType used concrete syntax or not.
1919
1920 The one case that doesn't fit this pattern is that of promoted lists
1921 '[ Maybe, IO ] PromotedListT 2 `AppT` t1 `AppT` t2
1922 but it's very smelly because there really is no type constructor
1923 corresponding to PromotedListT. So we encode HsExplicitListTy with
1924 PromotedConsT and PromotedNilT (which *do* have underlying type
1925 constructors):
1926 '[ Maybe, IO ] PromotedConsT `AppT` Maybe `AppT`
1927 (PromotedConsT `AppT` IO `AppT` PromotedNilT)
1928 -}
1929
1930 -----------------------------------------------------
1931 -- Internal helper functions
1932 -----------------------------------------------------
1933
1934 cmpEq :: Ordering -> Bool
1935 cmpEq EQ = True
1936 cmpEq _ = False
1937
1938 thenCmp :: Ordering -> Ordering -> Ordering
1939 thenCmp EQ o2 = o2
1940 thenCmp o1 _ = o1