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