Make unboxedTuple{Type,Data}Name support 0- and 1-tuples
[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 n = mk_unboxed_tup_name n DataName
1191 unboxedTupleTypeName n = mk_unboxed_tup_name n TcClsName
1192
1193 mk_unboxed_tup_name :: Int -> NameSpace -> Name
1194 mk_unboxed_tup_name n space
1195 = Name (mkOccName tup_occ) (NameG space (mkPkgName "ghc-prim") tup_mod)
1196 where
1197 tup_occ | n == 1 = "Unit#" -- See Note [One-tuples] in TysWiredIn
1198 | otherwise = "(#" ++ replicate n_commas ',' ++ "#)"
1199 n_commas = n - 1
1200 tup_mod = mkModName "GHC.Tuple"
1201
1202 -----------------------------------------------------
1203 -- Locations
1204 -----------------------------------------------------
1205
1206 data Loc
1207 = Loc { loc_filename :: String
1208 , loc_package :: String
1209 , loc_module :: String
1210 , loc_start :: CharPos
1211 , loc_end :: CharPos }
1212 deriving( Show, Eq, Ord, Data, Generic )
1213
1214 type CharPos = (Int, Int) -- ^ Line and character position
1215
1216
1217 -----------------------------------------------------
1218 --
1219 -- The Info returned by reification
1220 --
1221 -----------------------------------------------------
1222
1223 -- | Obtained from 'reify' in the 'Q' Monad.
1224 data Info
1225 =
1226 -- | A class, with a list of its visible instances
1227 ClassI
1228 Dec
1229 [InstanceDec]
1230
1231 -- | A class method
1232 | ClassOpI
1233 Name
1234 Type
1235 ParentName
1236
1237 -- | A \"plain\" type constructor. \"Fancier\" type constructors are returned using 'PrimTyConI' or 'FamilyI' as appropriate
1238 | TyConI
1239 Dec
1240
1241 -- | A type or data family, with a list of its visible instances. A closed
1242 -- type family is returned with 0 instances.
1243 | FamilyI
1244 Dec
1245 [InstanceDec]
1246
1247 -- | A \"primitive\" type constructor, which can't be expressed with a 'Dec'. Examples: @(->)@, @Int#@.
1248 | PrimTyConI
1249 Name
1250 Arity
1251 Unlifted
1252
1253 -- | A data constructor
1254 | DataConI
1255 Name
1256 Type
1257 ParentName
1258
1259 -- | A pattern synonym.
1260 | PatSynI
1261 Name
1262 PatSynType
1263
1264 {- |
1265 A \"value\" variable (as opposed to a type variable, see 'TyVarI').
1266
1267 The @Maybe Dec@ field contains @Just@ the declaration which
1268 defined the variable -- including the RHS of the declaration --
1269 or else @Nothing@, in the case where the RHS is unavailable to
1270 the compiler. At present, this value is _always_ @Nothing@:
1271 returning the RHS has not yet been implemented because of
1272 lack of interest.
1273 -}
1274 | VarI
1275 Name
1276 Type
1277 (Maybe Dec)
1278
1279 {- |
1280 A type variable.
1281
1282 The @Type@ field contains the type which underlies the variable.
1283 At present, this is always @'VarT' theName@, but future changes
1284 may permit refinement of this.
1285 -}
1286 | TyVarI -- Scoped type variable
1287 Name
1288 Type -- What it is bound to
1289 deriving( Show, Eq, Ord, Data, Generic )
1290
1291 -- | Obtained from 'reifyModule' in the 'Q' Monad.
1292 data ModuleInfo =
1293 -- | Contains the import list of the module.
1294 ModuleInfo [Module]
1295 deriving( Show, Eq, Ord, Data, Generic )
1296
1297 {- |
1298 In 'ClassOpI' and 'DataConI', name of the parent class or type
1299 -}
1300 type ParentName = Name
1301
1302 -- | In 'UnboxedSumE' and 'UnboxedSumP', the number associated with a
1303 -- particular data constructor. 'SumAlt's are one-indexed and should never
1304 -- exceed the value of its corresponding 'SumArity'. For example:
1305 --
1306 -- * @(\#_|\#)@ has 'SumAlt' 1 (out of a total 'SumArity' of 2)
1307 --
1308 -- * @(\#|_\#)@ has 'SumAlt' 2 (out of a total 'SumArity' of 2)
1309 type SumAlt = Int
1310
1311 -- | In 'UnboxedSumE', 'UnboxedSumT', and 'UnboxedSumP', the total number of
1312 -- 'SumAlt's. For example, @(\#|\#)@ has a 'SumArity' of 2.
1313 type SumArity = Int
1314
1315 -- | In 'PrimTyConI', arity of the type constructor
1316 type Arity = Int
1317
1318 -- | In 'PrimTyConI', is the type constructor unlifted?
1319 type Unlifted = Bool
1320
1321 -- | 'InstanceDec' desribes a single instance of a class or type function.
1322 -- It is just a 'Dec', but guaranteed to be one of the following:
1323 --
1324 -- * 'InstanceD' (with empty @['Dec']@)
1325 --
1326 -- * 'DataInstD' or 'NewtypeInstD' (with empty derived @['Name']@)
1327 --
1328 -- * 'TySynInstD'
1329 type InstanceDec = Dec
1330
1331 data Fixity = Fixity Int FixityDirection
1332 deriving( Eq, Ord, Show, Data, Generic )
1333 data FixityDirection = InfixL | InfixR | InfixN
1334 deriving( Eq, Ord, Show, Data, Generic )
1335
1336 -- | Highest allowed operator precedence for 'Fixity' constructor (answer: 9)
1337 maxPrecedence :: Int
1338 maxPrecedence = (9::Int)
1339
1340 -- | Default fixity: @infixl 9@
1341 defaultFixity :: Fixity
1342 defaultFixity = Fixity maxPrecedence InfixL
1343
1344
1345 {-
1346 Note [Unresolved infix]
1347 ~~~~~~~~~~~~~~~~~~~~~~~
1348 -}
1349 {- $infix #infix#
1350 When implementing antiquotation for quasiquoters, one often wants
1351 to parse strings into expressions:
1352
1353 > parse :: String -> Maybe Exp
1354
1355 But how should we parse @a + b * c@? If we don't know the fixities of
1356 @+@ and @*@, we don't know whether to parse it as @a + (b * c)@ or @(a
1357 + b) * c@.
1358
1359 In cases like this, use 'UInfixE', 'UInfixP', or 'UInfixT', which stand for
1360 \"unresolved infix expression/pattern/type\", respectively. When the compiler
1361 is given a splice containing a tree of @UInfixE@ applications such as
1362
1363 > UInfixE
1364 > (UInfixE e1 op1 e2)
1365 > op2
1366 > (UInfixE e3 op3 e4)
1367
1368 it will look up and the fixities of the relevant operators and
1369 reassociate the tree as necessary.
1370
1371 * trees will not be reassociated across 'ParensE', 'ParensP', or 'ParensT',
1372 which are of use for parsing expressions like
1373
1374 > (a + b * c) + d * e
1375
1376 * 'InfixE', 'InfixP', and 'InfixT' expressions are never reassociated.
1377
1378 * The 'UInfixE' constructor doesn't support sections. Sections
1379 such as @(a *)@ have no ambiguity, so 'InfixE' suffices. For longer
1380 sections such as @(a + b * c -)@, use an 'InfixE' constructor for the
1381 outer-most section, and use 'UInfixE' constructors for all
1382 other operators:
1383
1384 > InfixE
1385 > Just (UInfixE ...a + b * c...)
1386 > op
1387 > Nothing
1388
1389 Sections such as @(a + b +)@ and @((a + b) +)@ should be rendered
1390 into 'Exp's differently:
1391
1392 > (+ a + b) ---> InfixE Nothing + (Just $ UInfixE a + b)
1393 > -- will result in a fixity error if (+) is left-infix
1394 > (+ (a + b)) ---> InfixE Nothing + (Just $ ParensE $ UInfixE a + b)
1395 > -- no fixity errors
1396
1397 * Quoted expressions such as
1398
1399 > [| a * b + c |] :: Q Exp
1400 > [p| a : b : c |] :: Q Pat
1401 > [t| T + T |] :: Q Type
1402
1403 will never contain 'UInfixE', 'UInfixP', 'UInfixT', 'InfixT', 'ParensE',
1404 'ParensP', or 'ParensT' constructors.
1405
1406 -}
1407
1408 -----------------------------------------------------
1409 --
1410 -- The main syntax data types
1411 --
1412 -----------------------------------------------------
1413
1414 data Lit = CharL Char
1415 | StringL String
1416 | IntegerL Integer -- ^ Used for overloaded and non-overloaded
1417 -- literals. We don't have a good way to
1418 -- represent non-overloaded literals at
1419 -- the moment. Maybe that doesn't matter?
1420 | RationalL Rational -- Ditto
1421 | IntPrimL Integer
1422 | WordPrimL Integer
1423 | FloatPrimL Rational
1424 | DoublePrimL Rational
1425 | StringPrimL [Word8] -- ^ A primitive C-style string, type Addr#
1426 | CharPrimL Char
1427 deriving( Show, Eq, Ord, Data, Generic )
1428
1429 -- We could add Int, Float, Double etc, as we do in HsLit,
1430 -- but that could complicate the
1431 -- supposedly-simple TH.Syntax literal type
1432
1433 -- | Pattern in Haskell given in @{}@
1434 data Pat
1435 = LitP Lit -- ^ @{ 5 or \'c\' }@
1436 | VarP Name -- ^ @{ x }@
1437 | TupP [Pat] -- ^ @{ (p1,p2) }@
1438 | UnboxedTupP [Pat] -- ^ @{ (\# p1,p2 \#) }@
1439 | UnboxedSumP Pat SumAlt SumArity -- ^ @{ (\#|p|\#) }@
1440 | ConP Name [Pat] -- ^ @data T1 = C1 t1 t2; {C1 p1 p1} = e@
1441 | InfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
1442 | UInfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
1443 --
1444 -- See "Language.Haskell.TH.Syntax#infix"
1445 | ParensP Pat -- ^ @{(p)}@
1446 --
1447 -- See "Language.Haskell.TH.Syntax#infix"
1448 | TildeP Pat -- ^ @{ ~p }@
1449 | BangP Pat -- ^ @{ !p }@
1450 | AsP Name Pat -- ^ @{ x \@ p }@
1451 | WildP -- ^ @{ _ }@
1452 | RecP Name [FieldPat] -- ^ @f (Pt { pointx = x }) = g x@
1453 | ListP [ Pat ] -- ^ @{ [1,2,3] }@
1454 | SigP Pat Type -- ^ @{ p :: t }@
1455 | ViewP Exp Pat -- ^ @{ e -> p }@
1456 deriving( Show, Eq, Ord, Data, Generic )
1457
1458 type FieldPat = (Name,Pat)
1459
1460 data Match = Match Pat Body [Dec] -- ^ @case e of { pat -> body where decs }@
1461 deriving( Show, Eq, Ord, Data, Generic )
1462 data Clause = Clause [Pat] Body [Dec]
1463 -- ^ @f { p1 p2 = body where decs }@
1464 deriving( Show, Eq, Ord, Data, Generic )
1465
1466 data Exp
1467 = VarE Name -- ^ @{ x }@
1468 | ConE Name -- ^ @data T1 = C1 t1 t2; p = {C1} e1 e2 @
1469 | LitE Lit -- ^ @{ 5 or \'c\'}@
1470 | AppE Exp Exp -- ^ @{ f x }@
1471 | AppTypeE Exp Type -- ^ @{ f \@Int }
1472
1473 | InfixE (Maybe Exp) Exp (Maybe Exp) -- ^ @{x + y} or {(x+)} or {(+ x)} or {(+)}@
1474
1475 -- It's a bit gruesome to use an Exp as the
1476 -- operator, but how else can we distinguish
1477 -- constructors from non-constructors?
1478 -- Maybe there should be a var-or-con type?
1479 -- Or maybe we should leave it to the String itself?
1480
1481 | UInfixE Exp Exp Exp -- ^ @{x + y}@
1482 --
1483 -- See "Language.Haskell.TH.Syntax#infix"
1484 | ParensE Exp -- ^ @{ (e) }@
1485 --
1486 -- See "Language.Haskell.TH.Syntax#infix"
1487 | LamE [Pat] Exp -- ^ @{ \\ p1 p2 -> e }@
1488 | LamCaseE [Match] -- ^ @{ \\case m1; m2 }@
1489 | TupE [Exp] -- ^ @{ (e1,e2) } @
1490 | UnboxedTupE [Exp] -- ^ @{ (\# e1,e2 \#) } @
1491 | UnboxedSumE Exp SumAlt SumArity -- ^ @{ (\#|e|\#) }@
1492 | CondE Exp Exp Exp -- ^ @{ if e1 then e2 else e3 }@
1493 | MultiIfE [(Guard, Exp)] -- ^ @{ if | g1 -> e1 | g2 -> e2 }@
1494 | LetE [Dec] Exp -- ^ @{ let x=e1; y=e2 in e3 }@
1495 | CaseE Exp [Match] -- ^ @{ case e of m1; m2 }@
1496 | DoE [Stmt] -- ^ @{ do { p <- e1; e2 } }@
1497 | CompE [Stmt] -- ^ @{ [ (x,y) | x <- xs, y <- ys ] }@
1498 --
1499 -- The result expression of the comprehension is
1500 -- the /last/ of the @'Stmt'@s, and should be a 'NoBindS'.
1501 --
1502 -- E.g. translation:
1503 --
1504 -- > [ f x | x <- xs ]
1505 --
1506 -- > CompE [BindS (VarP x) (VarE xs), NoBindS (AppE (VarE f) (VarE x))]
1507
1508 | ArithSeqE Range -- ^ @{ [ 1 ,2 .. 10 ] }@
1509 | ListE [ Exp ] -- ^ @{ [1,2,3] }@
1510 | SigE Exp Type -- ^ @{ e :: t }@
1511 | RecConE Name [FieldExp] -- ^ @{ T { x = y, z = w } }@
1512 | RecUpdE Exp [FieldExp] -- ^ @{ (f x) { z = w } }@
1513 | StaticE Exp -- ^ @{ static e }@
1514 | UnboundVarE Name -- ^ @{ _x }@ (hole)
1515 deriving( Show, Eq, Ord, Data, Generic )
1516
1517 type FieldExp = (Name,Exp)
1518
1519 -- Omitted: implicit parameters
1520
1521 data Body
1522 = GuardedB [(Guard,Exp)] -- ^ @f p { | e1 = e2
1523 -- | e3 = e4 }
1524 -- where ds@
1525 | NormalB Exp -- ^ @f p { = e } where ds@
1526 deriving( Show, Eq, Ord, Data, Generic )
1527
1528 data Guard
1529 = NormalG Exp -- ^ @f x { | odd x } = x@
1530 | PatG [Stmt] -- ^ @f x { | Just y <- x, Just z <- y } = z@
1531 deriving( Show, Eq, Ord, Data, Generic )
1532
1533 data Stmt
1534 = BindS Pat Exp
1535 | LetS [ Dec ]
1536 | NoBindS Exp
1537 | ParS [[Stmt]]
1538 deriving( Show, Eq, Ord, Data, Generic )
1539
1540 data Range = FromR Exp | FromThenR Exp Exp
1541 | FromToR Exp Exp | FromThenToR Exp Exp Exp
1542 deriving( Show, Eq, Ord, Data, Generic )
1543
1544 data Dec
1545 = FunD Name [Clause] -- ^ @{ f p1 p2 = b where decs }@
1546 | ValD Pat Body [Dec] -- ^ @{ p = b where decs }@
1547 | DataD Cxt Name [TyVarBndr]
1548 (Maybe Kind) -- Kind signature (allowed only for GADTs)
1549 [Con] [DerivClause]
1550 -- ^ @{ data Cxt x => T x = A x | B (T x)
1551 -- deriving (Z,W)
1552 -- deriving stock Eq }@
1553 | NewtypeD Cxt Name [TyVarBndr]
1554 (Maybe Kind) -- Kind signature
1555 Con [DerivClause] -- ^ @{ newtype Cxt x => T x = A (B x)
1556 -- deriving (Z,W Q)
1557 -- deriving stock Eq }@
1558 | TySynD Name [TyVarBndr] Type -- ^ @{ type T x = (x,x) }@
1559 | ClassD Cxt Name [TyVarBndr]
1560 [FunDep] [Dec] -- ^ @{ class Eq a => Ord a where ds }@
1561 | InstanceD (Maybe Overlap) Cxt Type [Dec]
1562 -- ^ @{ instance {\-\# OVERLAPS \#-\}
1563 -- Show w => Show [w] where ds }@
1564 | SigD Name Type -- ^ @{ length :: [a] -> Int }@
1565 | ForeignD Foreign -- ^ @{ foreign import ... }
1566 --{ foreign export ... }@
1567
1568 | InfixD Fixity Name -- ^ @{ infix 3 foo }@
1569
1570 -- | pragmas
1571 | PragmaD Pragma -- ^ @{ {\-\# INLINE [1] foo \#-\} }@
1572
1573 -- | data families (may also appear in [Dec] of 'ClassD' and 'InstanceD')
1574 | DataFamilyD Name [TyVarBndr]
1575 (Maybe Kind)
1576 -- ^ @{ data family T a b c :: * }@
1577
1578 | DataInstD Cxt Name [Type]
1579 (Maybe Kind) -- Kind signature
1580 [Con] [DerivClause] -- ^ @{ data instance Cxt x => T [x]
1581 -- = A x | B (T x)
1582 -- deriving (Z,W)
1583 -- deriving stock Eq }@
1584
1585 | NewtypeInstD Cxt Name [Type]
1586 (Maybe Kind) -- Kind signature
1587 Con [DerivClause] -- ^ @{ newtype instance Cxt x => T [x]
1588 -- = A (B x)
1589 -- deriving (Z,W)
1590 -- deriving stock Eq }@
1591 | TySynInstD Name TySynEqn -- ^ @{ type instance ... }@
1592
1593 -- | open type families (may also appear in [Dec] of 'ClassD' and 'InstanceD')
1594 | OpenTypeFamilyD TypeFamilyHead
1595 -- ^ @{ type family T a b c = (r :: *) | r -> a b }@
1596
1597 | ClosedTypeFamilyD TypeFamilyHead [TySynEqn]
1598 -- ^ @{ type family F a b = (r :: *) | r -> a where ... }@
1599
1600 | RoleAnnotD Name [Role] -- ^ @{ type role T nominal representational }@
1601 | StandaloneDerivD (Maybe DerivStrategy) Cxt Type
1602 -- ^ @{ deriving stock instance Ord a => Ord (Foo a) }@
1603 | DefaultSigD Name Type -- ^ @{ default size :: Data a => a -> Int }@
1604
1605 -- | Pattern Synonyms
1606 | PatSynD Name PatSynArgs PatSynDir Pat
1607 -- ^ @{ pattern P v1 v2 .. vn <- p }@ unidirectional or
1608 -- @{ pattern P v1 v2 .. vn = p }@ implicit bidirectional or
1609 -- @{ pattern P v1 v2 .. vn <- p
1610 -- where P v1 v2 .. vn = e }@ explicit bidirectional
1611 --
1612 -- also, besides prefix pattern synonyms, both infix and record
1613 -- pattern synonyms are supported. See 'PatSynArgs' for details
1614
1615 | PatSynSigD Name PatSynType -- ^ A pattern synonym's type signature.
1616 deriving( Show, Eq, Ord, Data, Generic )
1617
1618 -- | Varieties of allowed instance overlap.
1619 data Overlap = Overlappable -- ^ May be overlapped by more specific instances
1620 | Overlapping -- ^ May overlap a more general instance
1621 | Overlaps -- ^ Both 'Overlapping' and 'Overlappable'
1622 | Incoherent -- ^ Both 'Overlappable' and 'Overlappable', and
1623 -- pick an arbitrary one if multiple choices are
1624 -- available.
1625 deriving( Show, Eq, Ord, Data, Generic )
1626
1627 -- | A single @deriving@ clause at the end of a datatype.
1628 data DerivClause = DerivClause (Maybe DerivStrategy) Cxt
1629 -- ^ @{ deriving stock (Eq, Ord) }@
1630 deriving( Show, Eq, Ord, Data, Generic )
1631
1632 -- | What the user explicitly requests when deriving an instance.
1633 data DerivStrategy = StockStrategy -- ^ A \"standard\" derived instance
1634 | AnyclassStrategy -- ^ @-XDeriveAnyClass@
1635 | NewtypeStrategy -- ^ @-XGeneralizedNewtypeDeriving@
1636 deriving( Show, Eq, Ord, Data, Generic )
1637
1638 -- | A Pattern synonym's type. Note that a pattern synonym's *fully*
1639 -- specified type has a peculiar shape coming with two forall
1640 -- quantifiers and two constraint contexts. For example, consider the
1641 -- pattern synonym
1642 --
1643 -- pattern P x1 x2 ... xn = <some-pattern>
1644 --
1645 -- P's complete type is of the following form
1646 --
1647 -- forall universals. required constraints
1648 -- => forall existentials. provided constraints
1649 -- => t1 -> t2 -> ... -> tn -> t
1650 --
1651 -- consisting of four parts:
1652 --
1653 -- 1) the (possibly empty lists of) universally quantified type
1654 -- variables and required constraints on them.
1655 -- 2) the (possibly empty lists of) existentially quantified
1656 -- type variables and the provided constraints on them.
1657 -- 3) the types t1, t2, .., tn of x1, x2, .., xn, respectively
1658 -- 4) the type t of <some-pattern>, mentioning only universals.
1659 --
1660 -- Pattern synonym types interact with TH when (a) reifying a pattern
1661 -- synonym, (b) pretty printing, or (c) specifying a pattern synonym's
1662 -- type signature explicitly:
1663 --
1664 -- (a) Reification always returns a pattern synonym's *fully* specified
1665 -- type in abstract syntax.
1666 --
1667 -- (b) Pretty printing via 'pprPatSynType' abbreviates a pattern
1668 -- synonym's type unambiguously in concrete syntax: The rule of
1669 -- thumb is to print initial empty universals and the required
1670 -- context as `() =>`, if existentials and a provided context
1671 -- follow. If only universals and their required context, but no
1672 -- existentials are specified, only the universals and their
1673 -- required context are printed. If both or none are specified, so
1674 -- both (or none) are printed.
1675 --
1676 -- (c) When specifying a pattern synonym's type explicitly with
1677 -- 'PatSynSigD' either one of the universals, the existentials, or
1678 -- their contexts may be left empty.
1679 --
1680 -- See the GHC users guide for more information on pattern synonyms
1681 -- and their types: https://downloads.haskell.org/~ghc/latest/docs/html/
1682 -- users_guide/syntax-extns.html#pattern-synonyms.
1683 type PatSynType = Type
1684
1685 -- | Common elements of 'OpenTypeFamilyD' and 'ClosedTypeFamilyD'. By
1686 -- analogy with "head" for type classes and type class instances as
1687 -- defined in /Type classes: an exploration of the design space/, the
1688 -- @TypeFamilyHead@ is defined to be the elements of the declaration
1689 -- between @type family@ and @where@.
1690 data TypeFamilyHead =
1691 TypeFamilyHead Name [TyVarBndr] FamilyResultSig (Maybe InjectivityAnn)
1692 deriving( Show, Eq, Ord, Data, Generic )
1693
1694 -- | One equation of a type family instance or closed type family. The
1695 -- arguments are the left-hand-side type patterns and the right-hand-side
1696 -- result.
1697 data TySynEqn = TySynEqn [Type] Type
1698 deriving( Show, Eq, Ord, Data, Generic )
1699
1700 data FunDep = FunDep [Name] [Name]
1701 deriving( Show, Eq, Ord, Data, Generic )
1702
1703 data FamFlavour = TypeFam | DataFam
1704 deriving( Show, Eq, Ord, Data, Generic )
1705
1706 data Foreign = ImportF Callconv Safety String Name Type
1707 | ExportF Callconv String Name Type
1708 deriving( Show, Eq, Ord, Data, Generic )
1709
1710 -- keep Callconv in sync with module ForeignCall in ghc/compiler/prelude/ForeignCall.hs
1711 data Callconv = CCall | StdCall | CApi | Prim | JavaScript
1712 deriving( Show, Eq, Ord, Data, Generic )
1713
1714 data Safety = Unsafe | Safe | Interruptible
1715 deriving( Show, Eq, Ord, Data, Generic )
1716
1717 data Pragma = InlineP Name Inline RuleMatch Phases
1718 | SpecialiseP Name Type (Maybe Inline) Phases
1719 | SpecialiseInstP Type
1720 | RuleP String [RuleBndr] Exp Exp Phases
1721 | AnnP AnnTarget Exp
1722 | LineP Int String
1723 deriving( Show, Eq, Ord, Data, Generic )
1724
1725 data Inline = NoInline
1726 | Inline
1727 | Inlinable
1728 deriving (Show, Eq, Ord, Data, Generic)
1729
1730 data RuleMatch = ConLike
1731 | FunLike
1732 deriving (Show, Eq, Ord, Data, Generic)
1733
1734 data Phases = AllPhases
1735 | FromPhase Int
1736 | BeforePhase Int
1737 deriving (Show, Eq, Ord, Data, Generic)
1738
1739 data RuleBndr = RuleVar Name
1740 | TypedRuleVar Name Type
1741 deriving (Show, Eq, Ord, Data, Generic)
1742
1743 data AnnTarget = ModuleAnnotation
1744 | TypeAnnotation Name
1745 | ValueAnnotation Name
1746 deriving (Show, Eq, Ord, Data, Generic)
1747
1748 type Cxt = [Pred] -- ^ @(Eq a, Ord b)@
1749
1750 -- | Since the advent of @ConstraintKinds@, constraints are really just types.
1751 -- Equality constraints use the 'EqualityT' constructor. Constraints may also
1752 -- be tuples of other constraints.
1753 type Pred = Type
1754
1755 data SourceUnpackedness
1756 = NoSourceUnpackedness -- ^ @C a@
1757 | SourceNoUnpack -- ^ @C { {\-\# NOUNPACK \#-\} } a@
1758 | SourceUnpack -- ^ @C { {\-\# UNPACK \#-\} } a@
1759 deriving (Show, Eq, Ord, Data, Generic)
1760
1761 data SourceStrictness = NoSourceStrictness -- ^ @C a@
1762 | SourceLazy -- ^ @C {~}a@
1763 | SourceStrict -- ^ @C {!}a@
1764 deriving (Show, Eq, Ord, Data, Generic)
1765
1766 -- | Unlike 'SourceStrictness' and 'SourceUnpackedness', 'DecidedStrictness'
1767 -- refers to the strictness that the compiler chooses for a data constructor
1768 -- field, which may be different from what is written in source code. See
1769 -- 'reifyConStrictness' for more information.
1770 data DecidedStrictness = DecidedLazy
1771 | DecidedStrict
1772 | DecidedUnpack
1773 deriving (Show, Eq, Ord, Data, Generic)
1774
1775 data Con = NormalC Name [BangType] -- ^ @C Int a@
1776 | RecC Name [VarBangType] -- ^ @C { v :: Int, w :: a }@
1777 | InfixC BangType Name BangType -- ^ @Int :+ a@
1778 | ForallC [TyVarBndr] Cxt Con -- ^ @forall a. Eq a => C [a]@
1779 | GadtC [Name] [BangType]
1780 Type -- See Note [GADT return type]
1781 -- ^ @C :: a -> b -> T b Int@
1782 | RecGadtC [Name] [VarBangType]
1783 Type -- See Note [GADT return type]
1784 -- ^ @C :: { v :: Int } -> T b Int@
1785 deriving (Show, Eq, Ord, Data, Generic)
1786
1787 -- Note [GADT return type]
1788 -- ~~~~~~~~~~~~~~~~~~~~~~~
1789 --
1790 -- The return type of a GADT constructor does not necessarily match the name of
1791 -- the data type:
1792 --
1793 -- type S = T
1794 --
1795 -- data T a where
1796 -- MkT :: S Int
1797 --
1798 --
1799 -- type S a = T
1800 --
1801 -- data T a where
1802 -- MkT :: S Char Int
1803 --
1804 --
1805 -- type Id a = a
1806 -- type S a = T
1807 --
1808 -- data T a where
1809 -- MkT :: Id (S Char Int)
1810 --
1811 --
1812 -- That is why we allow the return type stored by a constructor to be an
1813 -- arbitrary type. See also #11341
1814
1815 data Bang = Bang SourceUnpackedness SourceStrictness
1816 -- ^ @C { {\-\# UNPACK \#-\} !}a@
1817 deriving (Show, Eq, Ord, Data, Generic)
1818
1819 type BangType = (Bang, Type)
1820 type VarBangType = (Name, Bang, Type)
1821
1822 -- | As of @template-haskell-2.11.0.0@, 'Strict' has been replaced by 'Bang'.
1823 type Strict = Bang
1824
1825 -- | As of @template-haskell-2.11.0.0@, 'StrictType' has been replaced by
1826 -- 'BangType'.
1827 type StrictType = BangType
1828
1829 -- | As of @template-haskell-2.11.0.0@, 'VarStrictType' has been replaced by
1830 -- 'VarBangType'.
1831 type VarStrictType = VarBangType
1832
1833 -- | A pattern synonym's directionality.
1834 data PatSynDir
1835 = Unidir -- ^ @pattern P x {<-} p@
1836 | ImplBidir -- ^ @pattern P x {=} p@
1837 | ExplBidir [Clause] -- ^ @pattern P x {<-} p where P x = e@
1838 deriving( Show, Eq, Ord, Data, Generic )
1839
1840 -- | A pattern synonym's argument type.
1841 data PatSynArgs
1842 = PrefixPatSyn [Name] -- ^ @pattern P {x y z} = p@
1843 | InfixPatSyn Name Name -- ^ @pattern {x P y} = p@
1844 | RecordPatSyn [Name] -- ^ @pattern P { {x,y,z} } = p@
1845 deriving( Show, Eq, Ord, Data, Generic )
1846
1847 data Type = ForallT [TyVarBndr] Cxt Type -- ^ @forall \<vars\>. \<ctxt\> -> \<type\>@
1848 | AppT Type Type -- ^ @T a b@
1849 | SigT Type Kind -- ^ @t :: k@
1850 | VarT Name -- ^ @a@
1851 | ConT Name -- ^ @T@
1852 | PromotedT Name -- ^ @'T@
1853 | InfixT Type Name Type -- ^ @T + T@
1854 | UInfixT Type Name Type -- ^ @T + T@
1855 --
1856 -- See "Language.Haskell.TH.Syntax#infix"
1857 | ParensT Type -- ^ @(T)@
1858
1859 -- See Note [Representing concrete syntax in types]
1860 | TupleT Int -- ^ @(,), (,,), etc.@
1861 | UnboxedTupleT Int -- ^ @(\#,\#), (\#,,\#), etc.@
1862 | UnboxedSumT SumArity -- ^ @(\#|\#), (\#||\#), etc.@
1863 | ArrowT -- ^ @->@
1864 | EqualityT -- ^ @~@
1865 | ListT -- ^ @[]@
1866 | PromotedTupleT Int -- ^ @'(), '(,), '(,,), etc.@
1867 | PromotedNilT -- ^ @'[]@
1868 | PromotedConsT -- ^ @(':)@
1869 | StarT -- ^ @*@
1870 | ConstraintT -- ^ @Constraint@
1871 | LitT TyLit -- ^ @0,1,2, etc.@
1872 | WildCardT -- ^ @_,
1873 deriving( Show, Eq, Ord, Data, Generic )
1874
1875 data TyVarBndr = PlainTV Name -- ^ @a@
1876 | KindedTV Name Kind -- ^ @(a :: k)@
1877 deriving( Show, Eq, Ord, Data, Generic )
1878
1879 -- | Type family result signature
1880 data FamilyResultSig = NoSig -- ^ no signature
1881 | KindSig Kind -- ^ @k@
1882 | TyVarSig TyVarBndr -- ^ @= r, = (r :: k)@
1883 deriving( Show, Eq, Ord, Data, Generic )
1884
1885 -- | Injectivity annotation
1886 data InjectivityAnn = InjectivityAnn Name [Name]
1887 deriving ( Show, Eq, Ord, Data, Generic )
1888
1889 data TyLit = NumTyLit Integer -- ^ @2@
1890 | StrTyLit String -- ^ @"Hello"@
1891 deriving ( Show, Eq, Ord, Data, Generic )
1892
1893 -- | Role annotations
1894 data Role = NominalR -- ^ @nominal@
1895 | RepresentationalR -- ^ @representational@
1896 | PhantomR -- ^ @phantom@
1897 | InferR -- ^ @_@
1898 deriving( Show, Eq, Ord, Data, Generic )
1899
1900 -- | Annotation target for reifyAnnotations
1901 data AnnLookup = AnnLookupModule Module
1902 | AnnLookupName Name
1903 deriving( Show, Eq, Ord, Data, Generic )
1904
1905 -- | To avoid duplication between kinds and types, they
1906 -- are defined to be the same. Naturally, you would never
1907 -- have a type be 'StarT' and you would never have a kind
1908 -- be 'SigT', but many of the other constructors are shared.
1909 -- Note that the kind @Bool@ is denoted with 'ConT', not
1910 -- 'PromotedT'. Similarly, tuple kinds are made with 'TupleT',
1911 -- not 'PromotedTupleT'.
1912
1913 type Kind = Type
1914
1915 {- Note [Representing concrete syntax in types]
1916 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1917 Haskell has a rich concrete syntax for types, including
1918 t1 -> t2, (t1,t2), [t], and so on
1919 In TH we represent all of this using AppT, with a distinguished
1920 type constructor at the head. So,
1921 Type TH representation
1922 -----------------------------------------------
1923 t1 -> t2 ArrowT `AppT` t2 `AppT` t2
1924 [t] ListT `AppT` t
1925 (t1,t2) TupleT 2 `AppT` t1 `AppT` t2
1926 '(t1,t2) PromotedTupleT 2 `AppT` t1 `AppT` t2
1927
1928 But if the original HsSyn used prefix application, we won't use
1929 these special TH constructors. For example
1930 [] t ConT "[]" `AppT` t
1931 (->) t ConT "->" `AppT` t
1932 In this way we can faithfully represent in TH whether the original
1933 HsType used concrete syntax or not.
1934
1935 The one case that doesn't fit this pattern is that of promoted lists
1936 '[ Maybe, IO ] PromotedListT 2 `AppT` t1 `AppT` t2
1937 but it's very smelly because there really is no type constructor
1938 corresponding to PromotedListT. So we encode HsExplicitListTy with
1939 PromotedConsT and PromotedNilT (which *do* have underlying type
1940 constructors):
1941 '[ Maybe, IO ] PromotedConsT `AppT` Maybe `AppT`
1942 (PromotedConsT `AppT` IO `AppT` PromotedNilT)
1943 -}
1944
1945 -----------------------------------------------------
1946 -- Internal helper functions
1947 -----------------------------------------------------
1948
1949 cmpEq :: Ordering -> Bool
1950 cmpEq EQ = True
1951 cmpEq _ = False
1952
1953 thenCmp :: Ordering -> Ordering -> Ordering
1954 thenCmp EQ o2 = o2
1955 thenCmp o1 _ = o1