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