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