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