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