11a35c1a919f48ba4ae91f08f150b97ae3eb32db
[packages/template-haskell.git] / Language / Haskell / TH / Syntax.hs
1 {-# LANGUAGE UnboxedTuples #-}
2
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module : Language.Haskell.Syntax
6 -- Copyright : (c) The University of Glasgow 2003
7 -- License : BSD-style (see the file libraries/base/LICENSE)
8 --
9 -- Maintainer : libraries@haskell.org
10 -- Stability : experimental
11 -- Portability : portable
12 --
13 -- Abstract syntax definitions for Template Haskell.
14 --
15 -----------------------------------------------------------------------------
16
17 module Language.Haskell.TH.Syntax where
18
19 import GHC.Exts
20 import Data.Data (Data(..), Typeable, mkConstr, mkDataType, constrIndex)
21 import qualified Data.Data as Data
22 import Control.Applicative( Applicative(..) )
23 import Data.IORef
24 import System.IO.Unsafe ( unsafePerformIO )
25 import Control.Monad (liftM)
26 import System.IO ( hPutStrLn, stderr )
27 import Data.Char ( isAlpha )
28 import Data.Word ( Word8 )
29
30 -----------------------------------------------------
31 --
32 -- The Quasi class
33 --
34 -----------------------------------------------------
35
36 class (Monad m, Applicative m) => Quasi m where
37 qNewName :: String -> m Name
38 -- ^ Fresh names
39
40 -- Error reporting and recovery
41 qReport :: Bool -> String -> m () -- ^ Report an error (True) or warning (False)
42 -- ...but carry on; use 'fail' to stop
43 qRecover :: m a -- ^ the error handler
44 -> m a -- ^ action which may fail
45 -> m a -- ^ Recover from the monadic 'fail'
46
47 -- Inspect the type-checker's environment
48 qLookupName :: Bool -> String -> m (Maybe Name)
49 -- True <=> type namespace, False <=> value namespace
50 qReify :: Name -> m Info
51 qReifyInstances :: Name -> [Type] -> m [Dec]
52 -- Is (n tys) an instance?
53 -- Returns list of matching instance Decs
54 -- (with empty sub-Decs)
55 -- Works for classes and type functions
56 qReifyRoles :: Name -> m [Role]
57
58 qLocation :: m Loc
59
60 qRunIO :: IO a -> m a
61 -- ^ Input/output (dangerous)
62
63 qAddDependentFile :: FilePath -> m ()
64
65 qAddTopDecls :: [Dec] -> m ()
66
67 qAddModFinalizer :: Q () -> m ()
68
69 qGetQ :: Typeable a => m (Maybe a)
70
71 qPutQ :: Typeable a => a -> m ()
72
73 -----------------------------------------------------
74 -- The IO instance of Quasi
75 --
76 -- This instance is used only when running a Q
77 -- computation in the IO monad, usually just to
78 -- print the result. There is no interesting
79 -- type environment, so reification isn't going to
80 -- work.
81 --
82 -----------------------------------------------------
83
84 instance Quasi IO where
85 qNewName s = do { n <- readIORef counter
86 ; writeIORef counter (n+1)
87 ; return (mkNameU s n) }
88
89 qReport True msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
90 qReport False msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
91
92 qLookupName _ _ = badIO "lookupName"
93 qReify _ = badIO "reify"
94 qReifyInstances _ _ = badIO "classInstances"
95 qReifyRoles _ = badIO "reifyRoles"
96 qLocation = badIO "currentLocation"
97 qRecover _ _ = badIO "recover" -- Maybe we could fix this?
98 qAddDependentFile _ = badIO "addDependentFile"
99 qAddTopDecls _ = badIO "addTopDecls"
100 qAddModFinalizer _ = badIO "addModFinalizer"
101 qGetQ = badIO "getQ"
102 qPutQ _ = badIO "putQ"
103
104 qRunIO m = m
105
106 badIO :: String -> IO a
107 badIO op = do { qReport True ("Can't do `" ++ op ++ "' in the IO monad")
108 ; fail "Template Haskell failure" }
109
110 -- Global variable to generate unique symbols
111 counter :: IORef Int
112 {-# NOINLINE counter #-}
113 counter = unsafePerformIO (newIORef 0)
114
115
116 -----------------------------------------------------
117 --
118 -- The Q monad
119 --
120 -----------------------------------------------------
121
122 newtype Q a = Q { unQ :: forall m. Quasi m => m a }
123
124 -- \"Runs\" the 'Q' monad. Normal users of Template Haskell
125 -- should not need this function, as the splice brackets @$( ... )@
126 -- are the usual way of running a 'Q' computation.
127 --
128 -- This function is primarily used in GHC internals, and for debugging
129 -- splices by running them in 'IO'.
130 --
131 -- Note that many functions in 'Q', such as 'reify' and other compiler
132 -- queries, are not supported when running 'Q' in 'IO'; these operations
133 -- simply fail at runtime. Indeed, the only operations guaranteed to succeed
134 -- are 'newName', 'runIO', 'reportError' and 'reportWarning'.
135 runQ :: Quasi m => Q a -> m a
136 runQ (Q m) = m
137
138 instance Monad Q where
139 return x = Q (return x)
140 Q m >>= k = Q (m >>= \x -> unQ (k x))
141 Q m >> Q n = Q (m >> n)
142 fail s = report True s >> Q (fail "Q monad failure")
143
144 instance Functor Q where
145 fmap f (Q x) = Q (fmap f x)
146
147 instance Applicative Q where
148 pure x = Q (pure x)
149 Q f <*> Q x = Q (f <*> x)
150
151 -----------------------------------------------------
152 --
153 -- The TExp type
154 --
155 -----------------------------------------------------
156
157 newtype TExp a = TExp { unType :: Exp }
158
159 unTypeQ :: Q (TExp a) -> Q Exp
160 unTypeQ m = do { TExp e <- m
161 ; return e }
162
163 unsafeTExpCoerce :: Q Exp -> Q (TExp a)
164 unsafeTExpCoerce m = do { e <- m
165 ; return (TExp e) }
166
167 ----------------------------------------------------
168 -- Packaged versions for the programmer, hiding the Quasi-ness
169
170 {- |
171 Generate a fresh name, which cannot be captured.
172
173 For example, this:
174
175 @f = $(do
176 nm1 <- newName \"x\"
177 let nm2 = 'mkName' \"x\"
178 return ('LamE' ['VarP' nm1] (LamE [VarP nm2] ('VarE' nm1)))
179 )@
180
181 will produce the splice
182
183 >f = \x0 -> \x -> x0
184
185 In particular, the occurrence @VarE nm1@ refers to the binding @VarP nm1@,
186 and is not captured by the binding @VarP nm2@.
187
188 Although names generated by @newName@ cannot /be captured/, they can
189 /capture/ other names. For example, this:
190
191 >g = $(do
192 > nm1 <- newName "x"
193 > let nm2 = mkName "x"
194 > return (LamE [VarP nm2] (LamE [VarP nm1] (VarE nm2)))
195 > )
196
197 will produce the splice
198
199 >g = \x -> \x0 -> x0
200
201 since the occurrence @VarE nm2@ is captured by the innermost binding
202 of @x@, namely @VarP nm1@.
203 -}
204 newName :: String -> Q Name
205 newName s = Q (qNewName s)
206
207 -- | Report an error (True) or warning (False),
208 -- but carry on; use 'fail' to stop.
209 report :: Bool -> String -> Q ()
210 report b s = Q (qReport b s)
211 {-# DEPRECATED report "Use reportError or reportWarning instead" #-} -- deprecated in 7.6
212
213 -- | Report an error to the user, but allow the current splice's computation to carry on. To abort the computation, use 'fail'.
214 reportError :: String -> Q ()
215 reportError = report True
216
217 -- | Report a warning to the user, and carry on.
218 reportWarning :: String -> Q ()
219 reportWarning = report False
220
221 -- | Recover from errors raised by 'reportError' or 'fail'.
222 recover :: Q a -- ^ handler to invoke on failure
223 -> Q a -- ^ computation to run
224 -> Q a
225 recover (Q r) (Q m) = Q (qRecover r m)
226
227 -- We don't export lookupName; the Bool isn't a great API
228 -- Instead we export lookupTypeName, lookupValueName
229 lookupName :: Bool -> String -> Q (Maybe Name)
230 lookupName ns s = Q (qLookupName ns s)
231
232 -- | Look up the given name in the (type namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
233 lookupTypeName :: String -> Q (Maybe Name)
234 lookupTypeName s = Q (qLookupName True s)
235
236 -- | Look up the given name in the (value namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
237 lookupValueName :: String -> Q (Maybe Name)
238 lookupValueName s = Q (qLookupName False s)
239
240 {-
241 Note [Name lookup]
242 ~~~~~~~~~~~~~~~~~~
243 -}
244 {- $namelookup #namelookup#
245 The functions 'lookupTypeName' and 'lookupValueName' provide
246 a way to query the current splice's context for what names
247 are in scope. The function 'lookupTypeName' queries the type
248 namespace, whereas 'lookupValueName' queries the value namespace,
249 but the functions are otherwise identical.
250
251 A call @lookupValueName s@ will check if there is a value
252 with name @s@ in scope at the current splice's location. If
253 there is, the @Name@ of this value is returned;
254 if not, then @Nothing@ is returned.
255
256 The returned name cannot be \"captured\".
257 For example:
258
259 > f = "global"
260 > g = $( do
261 > Just nm <- lookupValueName "f"
262 > [| let f = "local" in $( varE nm ) |]
263
264 In this case, @g = \"global\"@; the call to @lookupValueName@
265 returned the global @f@, and this name was /not/ captured by
266 the local definition of @f@.
267
268 The lookup is performed in the context of the /top-level/ splice
269 being run. For example:
270
271 > f = "global"
272 > g = $( [| let f = "local" in
273 > $(do
274 > Just nm <- lookupValueName "f"
275 > varE nm
276 > ) |] )
277
278 Again in this example, @g = \"global\"@, because the call to
279 @lookupValueName@ queries the context of the outer-most @$(...)@.
280
281 Operators should be queried without any surrounding parentheses, like so:
282
283 > lookupValueName "+"
284
285 Qualified names are also supported, like so:
286
287 > lookupValueName "Prelude.+"
288 > lookupValueName "Prelude.map"
289
290 -}
291
292
293 {- | 'reify' looks up information about the 'Name'.
294
295 It is sometimes useful to construct the argument name using 'lookupTypeName' or 'lookupValueName'
296 to ensure that we are reifying from the right namespace. For instance, in this context:
297
298 > data D = D
299
300 which @D@ does @reify (mkName \"D\")@ return information about? (Answer: @D@-the-type, but don't rely on it.)
301 To ensure we get information about @D@-the-value, use 'lookupValueName':
302
303 > do
304 > Just nm <- lookupValueName "D"
305 > reify nm
306
307 and to get information about @D@-the-type, use 'lookupTypeName'.
308 -}
309 reify :: Name -> Q Info
310 reify v = Q (qReify v)
311
312 {- | @reifyInstances nm tys@ returns a list of visible instances of @nm tys@. That is,
313 if @nm@ is the name of a type class, then all instances of this class at the types @tys@
314 are returned. Alternatively, if @nm@ is the name of a data family or type family,
315 all instances of this family at the types @tys@ are returned.
316 -}
317 reifyInstances :: Name -> [Type] -> Q [InstanceDec]
318 reifyInstances cls tys = Q (qReifyInstances cls tys)
319
320 {- | @reifyRoles nm@ returns the list of roles associated with the parameters of
321 the tycon @nm@. Fails if @nm@ cannot be found or is not a tycon.
322 The returned list should never contain 'InferR'.
323 -}
324 reifyRoles :: Name -> Q [Role]
325 reifyRoles nm = Q (qReifyRoles nm)
326
327 -- | Is the list of instances returned by 'reifyInstances' nonempty?
328 isInstance :: Name -> [Type] -> Q Bool
329 isInstance nm tys = do { decs <- reifyInstances nm tys
330 ; return (not (null decs)) }
331
332 -- | The location at which this computation is spliced.
333 location :: Q Loc
334 location = Q qLocation
335
336 -- |The 'runIO' function lets you run an I\/O computation in the 'Q' monad.
337 -- Take care: you are guaranteed the ordering of calls to 'runIO' within
338 -- a single 'Q' computation, but not about the order in which splices are run.
339 --
340 -- Note: for various murky reasons, stdout and stderr handles are not
341 -- necesarily flushed when the compiler finishes running, so you should
342 -- flush them yourself.
343 runIO :: IO a -> Q a
344 runIO m = Q (qRunIO m)
345
346 -- | Record external files that runIO is using (dependent upon).
347 -- The compiler can then recognize that it should re-compile the file using this TH when the external file changes.
348 -- Note that ghc -M will still not know about these dependencies - it does not execute TH.
349 -- Expects an absolute file path.
350 addDependentFile :: FilePath -> Q ()
351 addDependentFile fp = Q (qAddDependentFile fp)
352
353 -- | Add additional top-level declarations. The added declarations will be type
354 -- checked along with the current declaration group.
355 addTopDecls :: [Dec] -> Q ()
356 addTopDecls ds = Q (qAddTopDecls ds)
357
358 -- | Add a finalizer that will run in the Q monad after the current module has
359 -- been type checked. This only makes sense when run within a top-level splice.
360 addModFinalizer :: Q () -> Q ()
361 addModFinalizer act = Q (qAddModFinalizer (unQ act))
362
363 -- | Get state from the Q monad.
364 getQ :: Typeable a => Q (Maybe a)
365 getQ = Q qGetQ
366
367 -- | Replace the state in the Q monad.
368 putQ :: Typeable a => a -> Q ()
369 putQ x = Q (qPutQ x)
370
371 instance Quasi Q where
372 qNewName = newName
373 qReport = report
374 qRecover = recover
375 qReify = reify
376 qReifyInstances = reifyInstances
377 qReifyRoles = reifyRoles
378 qLookupName = lookupName
379 qLocation = location
380 qRunIO = runIO
381 qAddDependentFile = addDependentFile
382 qAddTopDecls = addTopDecls
383 qAddModFinalizer = addModFinalizer
384 qGetQ = getQ
385 qPutQ = putQ
386
387
388 ----------------------------------------------------
389 -- The following operations are used solely in DsMeta when desugaring brackets
390 -- They are not necessary for the user, who can use ordinary return and (>>=) etc
391
392 returnQ :: a -> Q a
393 returnQ = return
394
395 bindQ :: Q a -> (a -> Q b) -> Q b
396 bindQ = (>>=)
397
398 sequenceQ :: [Q a] -> Q [a]
399 sequenceQ = sequence
400
401
402 -----------------------------------------------------
403 --
404 -- The Lift class
405 --
406 -----------------------------------------------------
407
408 class Lift t where
409 lift :: t -> Q Exp
410
411 instance Lift Integer where
412 lift x = return (LitE (IntegerL x))
413
414 instance Lift Int where
415 lift x= return (LitE (IntegerL (fromIntegral x)))
416
417 instance Lift Char where
418 lift x = return (LitE (CharL x))
419
420 instance Lift Bool where
421 lift True = return (ConE trueName)
422 lift False = return (ConE falseName)
423
424 instance Lift a => Lift (Maybe a) where
425 lift Nothing = return (ConE nothingName)
426 lift (Just x) = liftM (ConE justName `AppE`) (lift x)
427
428 instance (Lift a, Lift b) => Lift (Either a b) where
429 lift (Left x) = liftM (ConE leftName `AppE`) (lift x)
430 lift (Right y) = liftM (ConE rightName `AppE`) (lift y)
431
432 instance Lift a => Lift [a] where
433 lift xs = do { xs' <- mapM lift xs; return (ListE xs') }
434
435 liftString :: String -> Q Exp
436 -- Used in TcExpr to short-circuit the lifting for strings
437 liftString s = return (LitE (StringL s))
438
439 instance (Lift a, Lift b) => Lift (a, b) where
440 lift (a, b)
441 = liftM TupE $ sequence [lift a, lift b]
442
443 instance (Lift a, Lift b, Lift c) => Lift (a, b, c) where
444 lift (a, b, c)
445 = liftM TupE $ sequence [lift a, lift b, lift c]
446
447 instance (Lift a, Lift b, Lift c, Lift d) => Lift (a, b, c, d) where
448 lift (a, b, c, d)
449 = liftM TupE $ sequence [lift a, lift b, lift c, lift d]
450
451 instance (Lift a, Lift b, Lift c, Lift d, Lift e)
452 => Lift (a, b, c, d, e) where
453 lift (a, b, c, d, e)
454 = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e]
455
456 instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f)
457 => Lift (a, b, c, d, e, f) where
458 lift (a, b, c, d, e, f)
459 = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f]
460
461 instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f, Lift g)
462 => Lift (a, b, c, d, e, f, g) where
463 lift (a, b, c, d, e, f, g)
464 = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f, lift g]
465
466 -- TH has a special form for literal strings,
467 -- which we should take advantage of.
468 -- NB: the lhs of the rule has no args, so that
469 -- the rule will apply to a 'lift' all on its own
470 -- which happens to be the way the type checker
471 -- creates it.
472 {-# RULES "TH:liftString" lift = \s -> return (LitE (StringL s)) #-}
473
474
475 trueName, falseName :: Name
476 trueName = mkNameG DataName "ghc-prim" "GHC.Types" "True"
477 falseName = mkNameG DataName "ghc-prim" "GHC.Types" "False"
478
479 nothingName, justName :: Name
480 nothingName = mkNameG DataName "base" "Data.Maybe" "Nothing"
481 justName = mkNameG DataName "base" "Data.Maybe" "Just"
482
483 leftName, rightName :: Name
484 leftName = mkNameG DataName "base" "Data.Either" "Left"
485 rightName = mkNameG DataName "base" "Data.Either" "Right"
486
487
488 -----------------------------------------------------
489 -- Names and uniques
490 -----------------------------------------------------
491
492 newtype ModName = ModName String -- Module name
493 deriving (Eq,Ord,Typeable,Data)
494
495 newtype PkgName = PkgName String -- package name
496 deriving (Eq,Ord,Typeable,Data)
497
498 newtype OccName = OccName String
499 deriving (Eq,Ord,Typeable,Data)
500
501 mkModName :: String -> ModName
502 mkModName s = ModName s
503
504 modString :: ModName -> String
505 modString (ModName m) = m
506
507
508 mkPkgName :: String -> PkgName
509 mkPkgName s = PkgName s
510
511 pkgString :: PkgName -> String
512 pkgString (PkgName m) = m
513
514
515 -----------------------------------------------------
516 -- OccName
517 -----------------------------------------------------
518
519 mkOccName :: String -> OccName
520 mkOccName s = OccName s
521
522 occString :: OccName -> String
523 occString (OccName occ) = occ
524
525
526 -----------------------------------------------------
527 -- Names
528 -----------------------------------------------------
529 --
530 -- For "global" names ('NameG') we need a totally unique name,
531 -- so we must include the name-space of the thing
532 --
533 -- For unique-numbered things ('NameU'), we've got a unique reference
534 -- anyway, so no need for name space
535 --
536 -- For dynamically bound thing ('NameS') we probably want them to
537 -- in a context-dependent way, so again we don't want the name
538 -- space. For example:
539 --
540 -- > let v = mkName "T" in [| data $v = $v |]
541 --
542 -- Here we use the same Name for both type constructor and data constructor
543 --
544 --
545 -- NameL and NameG are bound *outside* the TH syntax tree
546 -- either globally (NameG) or locally (NameL). Ex:
547 --
548 -- > f x = $(h [| (map, x) |])
549 --
550 -- The 'map' will be a NameG, and 'x' wil be a NameL
551 --
552 -- These Names should never appear in a binding position in a TH syntax tree
553
554 {- $namecapture #namecapture#
555 Much of 'Name' API is concerned with the problem of /name capture/, which
556 can be seen in the following example.
557
558 > f expr = [| let x = 0 in $expr |]
559 > ...
560 > g x = $( f [| x |] )
561 > h y = $( f [| y |] )
562
563 A naive desugaring of this would yield:
564
565 > g x = let x = 0 in x
566 > h y = let x = 0 in y
567
568 All of a sudden, @g@ and @h@ have different meanings! In this case,
569 we say that the @x@ in the RHS of @g@ has been /captured/
570 by the binding of @x@ in @f@.
571
572 What we actually want is for the @x@ in @f@ to be distinct from the
573 @x@ in @g@, so we get the following desugaring:
574
575 > g x = let x' = 0 in x
576 > h y = let x' = 0 in y
577
578 which avoids name capture as desired.
579
580 In the general case, we say that a @Name@ can be captured if
581 the thing it refers to can be changed by adding new declarations.
582 -}
583
584 {- |
585 An abstract type representing names in the syntax tree.
586
587 'Name's can be constructed in several ways, which come with different
588 name-capture guarantees (see "Language.Haskell.TH.Syntax#namecapture" for
589 an explanation of name capture):
590
591 * the built-in syntax @'f@ and @''T@ can be used to construct names,
592 The expression @'f@ gives a @Name@ which refers to the value @f@
593 currently in scope, and @''T@ gives a @Name@ which refers to the
594 type @T@ currently in scope. These names can never be captured.
595
596 * 'lookupValueName' and 'lookupTypeName' are similar to @'f@ and
597 @''T@ respectively, but the @Name@s are looked up at the point
598 where the current splice is being run. These names can never be
599 captured.
600
601 * 'newName' monadically generates a new name, which can never
602 be captured.
603
604 * 'mkName' generates a capturable name.
605
606 Names constructed using @newName@ and @mkName@ may be used in bindings
607 (such as @let x = ...@ or @\x -> ...@), but names constructed using
608 @lookupValueName@, @lookupTypeName@, @'f@, @''T@ may not.
609 -}
610 data Name = Name OccName NameFlavour deriving (Typeable, Data)
611
612 data NameFlavour
613 = NameS -- ^ An unqualified name; dynamically bound
614 | NameQ ModName -- ^ A qualified name; dynamically bound
615 | NameU Int# -- ^ A unique local name
616 | NameL Int# -- ^ Local name bound outside of the TH AST
617 | NameG NameSpace PkgName ModName -- ^ Global name bound outside of the TH AST:
618 -- An original name (occurrences only, not binders)
619 -- Need the namespace too to be sure which
620 -- thing we are naming
621 deriving ( Typeable )
622
623 -- |
624 -- Although the NameFlavour type is abstract, the Data instance is not. The reason for this
625 -- is that currently we use Data to serialize values in annotations, and in order for that to
626 -- work for Template Haskell names introduced via the 'x syntax we need gunfold on NameFlavour
627 -- to work. Bleh!
628 --
629 -- The long term solution to this is to use the binary package for annotation serialization and
630 -- then remove this instance. However, to do _that_ we need to wait on binary to become stable, since
631 -- boot libraries cannot be upgraded separately from GHC itself.
632 --
633 -- This instance cannot be derived automatically due to bug #2701
634 instance Data NameFlavour where
635 gfoldl _ z NameS = z NameS
636 gfoldl k z (NameQ mn) = z NameQ `k` mn
637 gfoldl k z (NameU i) = z (\(I# i') -> NameU i') `k` (I# i)
638 gfoldl k z (NameL i) = z (\(I# i') -> NameL i') `k` (I# i)
639 gfoldl k z (NameG ns p m) = z NameG `k` ns `k` p `k` m
640 gunfold k z c = case constrIndex c of
641 1 -> z NameS
642 2 -> k $ z NameQ
643 3 -> k $ z (\(I# i) -> NameU i)
644 4 -> k $ z (\(I# i) -> NameL i)
645 5 -> k $ k $ k $ z NameG
646 _ -> error "gunfold: NameFlavour"
647 toConstr NameS = con_NameS
648 toConstr (NameQ _) = con_NameQ
649 toConstr (NameU _) = con_NameU
650 toConstr (NameL _) = con_NameL
651 toConstr (NameG _ _ _) = con_NameG
652 dataTypeOf _ = ty_NameFlavour
653
654 con_NameS, con_NameQ, con_NameU, con_NameL, con_NameG :: Data.Constr
655 con_NameS = mkConstr ty_NameFlavour "NameS" [] Data.Prefix
656 con_NameQ = mkConstr ty_NameFlavour "NameQ" [] Data.Prefix
657 con_NameU = mkConstr ty_NameFlavour "NameU" [] Data.Prefix
658 con_NameL = mkConstr ty_NameFlavour "NameL" [] Data.Prefix
659 con_NameG = mkConstr ty_NameFlavour "NameG" [] Data.Prefix
660
661 ty_NameFlavour :: Data.DataType
662 ty_NameFlavour = mkDataType "Language.Haskell.TH.Syntax.NameFlavour"
663 [con_NameS, con_NameQ, con_NameU,
664 con_NameL, con_NameG]
665
666 data NameSpace = VarName -- ^ Variables
667 | DataName -- ^ Data constructors
668 | TcClsName -- ^ Type constructors and classes; Haskell has them
669 -- in the same name space for now.
670 deriving( Eq, Ord, Data, Typeable )
671
672 type Uniq = Int
673
674 -- | The name without its module prefix
675 nameBase :: Name -> String
676 nameBase (Name occ _) = occString occ
677
678 -- | Module prefix of a name, if it exists
679 nameModule :: Name -> Maybe String
680 nameModule (Name _ (NameQ m)) = Just (modString m)
681 nameModule (Name _ (NameG _ _ m)) = Just (modString m)
682 nameModule _ = Nothing
683
684 {- |
685 Generate a capturable name. Occurrences of such names will be
686 resolved according to the Haskell scoping rules at the occurrence
687 site.
688
689 For example:
690
691 > f = [| pi + $(varE (mkName "pi")) |]
692 > ...
693 > g = let pi = 3 in $f
694
695 In this case, @g@ is desugared to
696
697 > g = Prelude.pi + 3
698
699 Note that @mkName@ may be used with qualified names:
700
701 > mkName "Prelude.pi"
702
703 See also 'Language.Haskell.TH.Lib.dyn' for a useful combinator. The above example could
704 be rewritten using 'dyn' as
705
706 > f = [| pi + $(dyn "pi") |]
707 -}
708 mkName :: String -> Name
709 -- The string can have a '.', thus "Foo.baz",
710 -- giving a dynamically-bound qualified name,
711 -- in which case we want to generate a NameQ
712 --
713 -- Parse the string to see if it has a "." in it
714 -- so we know whether to generate a qualified or unqualified name
715 -- It's a bit tricky because we need to parse
716 --
717 -- > Foo.Baz.x as Qual Foo.Baz x
718 --
719 -- So we parse it from back to front
720 mkName str
721 = split [] (reverse str)
722 where
723 split occ [] = Name (mkOccName occ) NameS
724 split occ ('.':rev) | not (null occ),
725 not (null rev), head rev /= '.'
726 = Name (mkOccName occ) (NameQ (mkModName (reverse rev)))
727 -- The 'not (null occ)' guard ensures that
728 -- mkName "&." = Name "&." NameS
729 -- The 'rev' guards ensure that
730 -- mkName ".&" = Name ".&" NameS
731 -- mkName "Data.Bits..&" = Name ".&" (NameQ "Data.Bits")
732 -- This rather bizarre case actually happened; (.&.) is in Data.Bits
733 split occ (c:rev) = split (c:occ) rev
734
735 -- | Only used internally
736 mkNameU :: String -> Uniq -> Name
737 mkNameU s (I# u) = Name (mkOccName s) (NameU u)
738
739 -- | Only used internally
740 mkNameL :: String -> Uniq -> Name
741 mkNameL s (I# u) = Name (mkOccName s) (NameL u)
742
743 -- | Used for 'x etc, but not available to the programmer
744 mkNameG :: NameSpace -> String -> String -> String -> Name
745 mkNameG ns pkg modu occ
746 = Name (mkOccName occ) (NameG ns (mkPkgName pkg) (mkModName modu))
747
748 mkNameG_v, mkNameG_tc, mkNameG_d :: String -> String -> String -> Name
749 mkNameG_v = mkNameG VarName
750 mkNameG_tc = mkNameG TcClsName
751 mkNameG_d = mkNameG DataName
752
753 instance Eq Name where
754 v1 == v2 = cmpEq (v1 `compare` v2)
755
756 instance Ord Name where
757 (Name o1 f1) `compare` (Name o2 f2) = (f1 `compare` f2) `thenCmp`
758 (o1 `compare` o2)
759
760 instance Eq NameFlavour where
761 f1 == f2 = cmpEq (f1 `compare` f2)
762
763 instance Ord NameFlavour where
764 -- NameS < NameQ < NameU < NameL < NameG
765 NameS `compare` NameS = EQ
766 NameS `compare` _ = LT
767
768 (NameQ _) `compare` NameS = GT
769 (NameQ m1) `compare` (NameQ m2) = m1 `compare` m2
770 (NameQ _) `compare` _ = LT
771
772 (NameU _) `compare` NameS = GT
773 (NameU _) `compare` (NameQ _) = GT
774 (NameU u1) `compare` (NameU u2) | isTrue# (u1 <# u2) = LT
775 | isTrue# (u1 ==# u2) = EQ
776 | otherwise = GT
777 (NameU _) `compare` _ = LT
778
779 (NameL _) `compare` NameS = GT
780 (NameL _) `compare` (NameQ _) = GT
781 (NameL _) `compare` (NameU _) = GT
782 (NameL u1) `compare` (NameL u2) | isTrue# (u1 <# u2) = LT
783 | isTrue# (u1 ==# u2) = EQ
784 | otherwise = GT
785 (NameL _) `compare` _ = LT
786
787 (NameG ns1 p1 m1) `compare` (NameG ns2 p2 m2) = (ns1 `compare` ns2) `thenCmp`
788 (p1 `compare` p2) `thenCmp`
789 (m1 `compare` m2)
790 (NameG _ _ _) `compare` _ = GT
791
792 data NameIs = Alone | Applied | Infix
793
794 showName :: Name -> String
795 showName = showName' Alone
796
797 showName' :: NameIs -> Name -> String
798 showName' ni nm
799 = case ni of
800 Alone -> nms
801 Applied
802 | pnam -> nms
803 | otherwise -> "(" ++ nms ++ ")"
804 Infix
805 | pnam -> "`" ++ nms ++ "`"
806 | otherwise -> nms
807 where
808 -- For now, we make the NameQ and NameG print the same, even though
809 -- NameQ is a qualified name (so what it means depends on what the
810 -- current scope is), and NameG is an original name (so its meaning
811 -- should be independent of what's in scope.
812 -- We may well want to distinguish them in the end.
813 -- Ditto NameU and NameL
814 nms = case nm of
815 Name occ NameS -> occString occ
816 Name occ (NameQ m) -> modString m ++ "." ++ occString occ
817 Name occ (NameG _ _ m) -> modString m ++ "." ++ occString occ
818 Name occ (NameU u) -> occString occ ++ "_" ++ show (I# u)
819 Name occ (NameL u) -> occString occ ++ "_" ++ show (I# u)
820
821 pnam = classify nms
822
823 -- True if we are function style, e.g. f, [], (,)
824 -- False if we are operator style, e.g. +, :+
825 classify "" = False -- shouldn't happen; . operator is handled below
826 classify (x:xs) | isAlpha x || (x `elem` "_[]()") =
827 case dropWhile (/='.') xs of
828 (_:xs') -> classify xs'
829 [] -> True
830 | otherwise = False
831
832 instance Show Name where
833 show = showName
834
835 -- Tuple data and type constructors
836 -- | Tuple data constructor
837 tupleDataName :: Int -> Name
838 -- | Tuple type constructor
839 tupleTypeName :: Int -> Name
840
841 tupleDataName 0 = mk_tup_name 0 DataName
842 tupleDataName 1 = error "tupleDataName 1"
843 tupleDataName n = mk_tup_name (n-1) DataName
844
845 tupleTypeName 0 = mk_tup_name 0 TcClsName
846 tupleTypeName 1 = error "tupleTypeName 1"
847 tupleTypeName n = mk_tup_name (n-1) TcClsName
848
849 mk_tup_name :: Int -> NameSpace -> Name
850 mk_tup_name n_commas space
851 = Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
852 where
853 occ = mkOccName ('(' : replicate n_commas ',' ++ ")")
854 tup_mod = mkModName "GHC.Tuple"
855
856 -- Unboxed tuple data and type constructors
857 -- | Unboxed tuple data constructor
858 unboxedTupleDataName :: Int -> Name
859 -- | Unboxed tuple type constructor
860 unboxedTupleTypeName :: Int -> Name
861
862 unboxedTupleDataName 0 = error "unboxedTupleDataName 0"
863 unboxedTupleDataName 1 = error "unboxedTupleDataName 1"
864 unboxedTupleDataName n = mk_unboxed_tup_name (n-1) DataName
865
866 unboxedTupleTypeName 0 = error "unboxedTupleTypeName 0"
867 unboxedTupleTypeName 1 = error "unboxedTupleTypeName 1"
868 unboxedTupleTypeName n = mk_unboxed_tup_name (n-1) TcClsName
869
870 mk_unboxed_tup_name :: Int -> NameSpace -> Name
871 mk_unboxed_tup_name n_commas space
872 = Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
873 where
874 occ = mkOccName ("(#" ++ replicate n_commas ',' ++ "#)")
875 tup_mod = mkModName "GHC.Tuple"
876
877
878
879 -----------------------------------------------------
880 -- Locations
881 -----------------------------------------------------
882
883 data Loc
884 = Loc { loc_filename :: String
885 , loc_package :: String
886 , loc_module :: String
887 , loc_start :: CharPos
888 , loc_end :: CharPos }
889
890 type CharPos = (Int, Int) -- ^ Line and character position
891
892
893 -----------------------------------------------------
894 --
895 -- The Info returned by reification
896 --
897 -----------------------------------------------------
898
899 -- | Obtained from 'reify' in the 'Q' Monad.
900 data Info
901 =
902 -- | A class, with a list of its visible instances
903 ClassI
904 Dec
905 [InstanceDec]
906
907 -- | A class method
908 | ClassOpI
909 Name
910 Type
911 ParentName
912 Fixity
913
914 -- | A \"plain\" type constructor. \"Fancier\" type constructors are returned using 'PrimTyConI' or 'FamilyI' as appropriate
915 | TyConI
916 Dec
917
918 -- | A type or data family, with a list of its visible instances. A closed
919 -- type family is returned with 0 instances.
920 | FamilyI
921 Dec
922 [InstanceDec]
923
924 -- | A \"primitive\" type constructor, which can't be expressed with a 'Dec'. Examples: @(->)@, @Int#@.
925 | PrimTyConI
926 Name
927 Arity
928 Unlifted
929
930 -- | A data constructor
931 | DataConI
932 Name
933 Type
934 ParentName
935 Fixity
936
937 {- |
938 A \"value\" variable (as opposed to a type variable, see 'TyVarI').
939
940 The @Maybe Dec@ field contains @Just@ the declaration which
941 defined the variable -- including the RHS of the declaration --
942 or else @Nothing@, in the case where the RHS is unavailable to
943 the compiler. At present, this value is _always_ @Nothing@:
944 returning the RHS has not yet been implemented because of
945 lack of interest.
946 -}
947 | VarI
948 Name
949 Type
950 (Maybe Dec)
951 Fixity
952
953 {- |
954 A type variable.
955
956 The @Type@ field contains the type which underlies the variable.
957 At present, this is always @'VarT' theName@, but future changes
958 may permit refinement of this.
959 -}
960 | TyVarI -- Scoped type variable
961 Name
962 Type -- What it is bound to
963 deriving( Show, Data, Typeable )
964
965 {- |
966 In 'ClassOpI' and 'DataConI', name of the parent class or type
967 -}
968 type ParentName = Name
969
970 -- | In 'PrimTyConI', arity of the type constructor
971 type Arity = Int
972
973 -- | In 'PrimTyConI', is the type constructor unlifted?
974 type Unlifted = Bool
975
976 -- | 'InstanceDec' desribes a single instance of a class or type function.
977 -- It is just a 'Dec', but guaranteed to be one of the following:
978 --
979 -- * 'InstanceD' (with empty @['Dec']@)
980 --
981 -- * 'DataInstD' or 'NewtypeInstD' (with empty derived @['Name']@)
982 --
983 -- * 'TySynInstD'
984 type InstanceDec = Dec
985
986 data Fixity = Fixity Int FixityDirection
987 deriving( Eq, Show, Data, Typeable )
988 data FixityDirection = InfixL | InfixR | InfixN
989 deriving( Eq, Show, Data, Typeable )
990
991 -- | Highest allowed operator precedence for 'Fixity' constructor (answer: 9)
992 maxPrecedence :: Int
993 maxPrecedence = (9::Int)
994
995 -- | Default fixity: @infixl 9@
996 defaultFixity :: Fixity
997 defaultFixity = Fixity maxPrecedence InfixL
998
999
1000 {-
1001 Note [Unresolved infix]
1002 ~~~~~~~~~~~~~~~~~~~~~~~
1003 -}
1004 {- $infix #infix#
1005 When implementing antiquotation for quasiquoters, one often wants
1006 to parse strings into expressions:
1007
1008 > parse :: String -> Maybe Exp
1009
1010 But how should we parse @a + b * c@? If we don't know the fixities of
1011 @+@ and @*@, we don't know whether to parse it as @a + (b * c)@ or @(a
1012 + b) * c@.
1013
1014 In cases like this, use 'UInfixE' or 'UInfixP', which stand for
1015 \"unresolved infix expression\" and \"unresolved infix pattern\". When
1016 the compiler is given a splice containing a tree of @UInfixE@
1017 applications such as
1018
1019 > UInfixE
1020 > (UInfixE e1 op1 e2)
1021 > op2
1022 > (UInfixE e3 op3 e4)
1023
1024 it will look up and the fixities of the relevant operators and
1025 reassociate the tree as necessary.
1026
1027 * trees will not be reassociated across 'ParensE' or 'ParensP',
1028 which are of use for parsing expressions like
1029
1030 > (a + b * c) + d * e
1031
1032 * 'InfixE' and 'InfixP' expressions are never reassociated.
1033
1034 * The 'UInfixE' constructor doesn't support sections. Sections
1035 such as @(a *)@ have no ambiguity, so 'InfixE' suffices. For longer
1036 sections such as @(a + b * c -)@, use an 'InfixE' constructor for the
1037 outer-most section, and use 'UInfixE' constructors for all
1038 other operators:
1039
1040 > InfixE
1041 > Just (UInfixE ...a + b * c...)
1042 > op
1043 > Nothing
1044
1045 Sections such as @(a + b +)@ and @((a + b) +)@ should be rendered
1046 into 'Exp's differently:
1047
1048 > (+ a + b) ---> InfixE Nothing + (Just $ UInfixE a + b)
1049 > -- will result in a fixity error if (+) is left-infix
1050 > (+ (a + b)) ---> InfixE Nothing + (Just $ ParensE $ UInfixE a + b)
1051 > -- no fixity errors
1052
1053 * Quoted expressions such as
1054
1055 > [| a * b + c |] :: Q Exp
1056 > [p| a : b : c |] :: Q Pat
1057
1058 will never contain 'UInfixE', 'UInfixP', 'ParensE', or 'ParensP'
1059 constructors.
1060
1061 -}
1062
1063 -----------------------------------------------------
1064 --
1065 -- The main syntax data types
1066 --
1067 -----------------------------------------------------
1068
1069 data Lit = CharL Char
1070 | StringL String
1071 | IntegerL Integer -- ^ Used for overloaded and non-overloaded
1072 -- literals. We don't have a good way to
1073 -- represent non-overloaded literals at
1074 -- the moment. Maybe that doesn't matter?
1075 | RationalL Rational -- Ditto
1076 | IntPrimL Integer
1077 | WordPrimL Integer
1078 | FloatPrimL Rational
1079 | DoublePrimL Rational
1080 | StringPrimL [Word8] -- ^ A primitive C-style string, type Addr#
1081 deriving( Show, Eq, Data, Typeable )
1082
1083 -- We could add Int, Float, Double etc, as we do in HsLit,
1084 -- but that could complicate the
1085 -- suppposedly-simple TH.Syntax literal type
1086
1087 -- | Pattern in Haskell given in @{}@
1088 data Pat
1089 = LitP Lit -- ^ @{ 5 or 'c' }@
1090 | VarP Name -- ^ @{ x }@
1091 | TupP [Pat] -- ^ @{ (p1,p2) }@
1092 | UnboxedTupP [Pat] -- ^ @{ (# p1,p2 #) }@
1093 | ConP Name [Pat] -- ^ @data T1 = C1 t1 t2; {C1 p1 p1} = e@
1094 | InfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
1095 | UInfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
1096 --
1097 -- See "Language.Haskell.TH.Syntax#infix"
1098 | ParensP Pat -- ^ @{(p)}@
1099 --
1100 -- See "Language.Haskell.TH.Syntax#infix"
1101 | TildeP Pat -- ^ @{ ~p }@
1102 | BangP Pat -- ^ @{ !p }@
1103 | AsP Name Pat -- ^ @{ x \@ p }@
1104 | WildP -- ^ @{ _ }@
1105 | RecP Name [FieldPat] -- ^ @f (Pt { pointx = x }) = g x@
1106 | ListP [ Pat ] -- ^ @{ [1,2,3] }@
1107 | SigP Pat Type -- ^ @{ p :: t }@
1108 | ViewP Exp Pat -- ^ @{ e -> p }@
1109 deriving( Show, Eq, Data, Typeable )
1110
1111 type FieldPat = (Name,Pat)
1112
1113 data Match = Match Pat Body [Dec] -- ^ @case e of { pat -> body where decs }@
1114 deriving( Show, Eq, Data, Typeable )
1115 data Clause = Clause [Pat] Body [Dec]
1116 -- ^ @f { p1 p2 = body where decs }@
1117 deriving( Show, Eq, Data, Typeable )
1118
1119 data Exp
1120 = VarE Name -- ^ @{ x }@
1121 | ConE Name -- ^ @data T1 = C1 t1 t2; p = {C1} e1 e2 @
1122 | LitE Lit -- ^ @{ 5 or 'c'}@
1123 | AppE Exp Exp -- ^ @{ f x }@
1124
1125 | InfixE (Maybe Exp) Exp (Maybe Exp) -- ^ @{x + y} or {(x+)} or {(+ x)} or {(+)}@
1126
1127 -- It's a bit gruesome to use an Exp as the
1128 -- operator, but how else can we distinguish
1129 -- constructors from non-constructors?
1130 -- Maybe there should be a var-or-con type?
1131 -- Or maybe we should leave it to the String itself?
1132
1133 | UInfixE Exp Exp Exp -- ^ @{x + y}@
1134 --
1135 -- See "Language.Haskell.TH.Syntax#infix"
1136 | ParensE Exp -- ^ @{ (e) }@
1137 --
1138 -- See "Language.Haskell.TH.Syntax#infix"
1139 | LamE [Pat] Exp -- ^ @{ \ p1 p2 -> e }@
1140 | LamCaseE [Match] -- ^ @{ \case m1; m2 }@
1141 | TupE [Exp] -- ^ @{ (e1,e2) } @
1142 | UnboxedTupE [Exp] -- ^ @{ (# e1,e2 #) } @
1143 | CondE Exp Exp Exp -- ^ @{ if e1 then e2 else e3 }@
1144 | MultiIfE [(Guard, Exp)] -- ^ @{ if | g1 -> e1 | g2 -> e2 }@
1145 | LetE [Dec] Exp -- ^ @{ let x=e1; y=e2 in e3 }@
1146 | CaseE Exp [Match] -- ^ @{ case e of m1; m2 }@
1147 | DoE [Stmt] -- ^ @{ do { p <- e1; e2 } }@
1148 | CompE [Stmt] -- ^ @{ [ (x,y) | x <- xs, y <- ys ] }@
1149 --
1150 -- The result expression of the comprehension is
1151 -- the /last/ of the @'Stmt'@s, and should be a 'NoBindS'.
1152 --
1153 -- E.g. translation:
1154 --
1155 -- > [ f x | x <- xs ]
1156 --
1157 -- > CompE [BindS (VarP x) (VarE xs), NoBindS (AppE (VarE f) (VarE x))]
1158
1159 | ArithSeqE Range -- ^ @{ [ 1 ,2 .. 10 ] }@
1160 | ListE [ Exp ] -- ^ @{ [1,2,3] }@
1161 | SigE Exp Type -- ^ @{ e :: t }@
1162 | RecConE Name [FieldExp] -- ^ @{ T { x = y, z = w } }@
1163 | RecUpdE Exp [FieldExp] -- ^ @{ (f x) { z = w } }@
1164 deriving( Show, Eq, Data, Typeable )
1165
1166 type FieldExp = (Name,Exp)
1167
1168 -- Omitted: implicit parameters
1169
1170 data Body
1171 = GuardedB [(Guard,Exp)] -- ^ @f p { | e1 = e2
1172 -- | e3 = e4 }
1173 -- where ds@
1174 | NormalB Exp -- ^ @f p { = e } where ds@
1175 deriving( Show, Eq, Data, Typeable )
1176
1177 data Guard
1178 = NormalG Exp -- ^ @f x { | odd x } = x@
1179 | PatG [Stmt] -- ^ @f x { | Just y <- x, Just z <- y } = z@
1180 deriving( Show, Eq, Data, Typeable )
1181
1182 data Stmt
1183 = BindS Pat Exp
1184 | LetS [ Dec ]
1185 | NoBindS Exp
1186 | ParS [[Stmt]]
1187 deriving( Show, Eq, Data, Typeable )
1188
1189 data Range = FromR Exp | FromThenR Exp Exp
1190 | FromToR Exp Exp | FromThenToR Exp Exp Exp
1191 deriving( Show, Eq, Data, Typeable )
1192
1193 data Dec
1194 = FunD Name [Clause] -- ^ @{ f p1 p2 = b where decs }@
1195 | ValD Pat Body [Dec] -- ^ @{ p = b where decs }@
1196 | DataD Cxt Name [TyVarBndr]
1197 [Con] [Name] -- ^ @{ data Cxt x => T x = A x | B (T x)
1198 -- deriving (Z,W)}@
1199 | NewtypeD Cxt Name [TyVarBndr]
1200 Con [Name] -- ^ @{ newtype Cxt x => T x = A (B x)
1201 -- deriving (Z,W)}@
1202 | TySynD Name [TyVarBndr] Type -- ^ @{ type T x = (x,x) }@
1203 | ClassD Cxt Name [TyVarBndr]
1204 [FunDep] [Dec] -- ^ @{ class Eq a => Ord a where ds }@
1205 | InstanceD Cxt Type [Dec] -- ^ @{ instance Show w => Show [w]
1206 -- where ds }@
1207 | SigD Name Type -- ^ @{ length :: [a] -> Int }@
1208 | ForeignD Foreign -- ^ @{ foreign import ... }
1209 --{ foreign export ... }@
1210
1211 | InfixD Fixity Name -- ^ @{ infix 3 foo }@
1212
1213 -- | pragmas
1214 | PragmaD Pragma -- ^ @{ {\-# INLINE [1] foo #-\} }@
1215
1216 -- | type families (may also appear in [Dec] of 'ClassD' and 'InstanceD')
1217 | FamilyD FamFlavour Name
1218 [TyVarBndr] (Maybe Kind) -- ^ @{ type family T a b c :: * }@
1219
1220 | DataInstD Cxt Name [Type]
1221 [Con] [Name] -- ^ @{ data instance Cxt x => T [x] = A x
1222 -- | B (T x)
1223 -- deriving (Z,W)}@
1224 | NewtypeInstD Cxt Name [Type]
1225 Con [Name] -- ^ @{ newtype instance Cxt x => T [x] = A (B x)
1226 -- deriving (Z,W)}@
1227 | TySynInstD Name TySynEqn -- ^ @{ type instance ... }@
1228
1229 | ClosedTypeFamilyD Name
1230 [TyVarBndr] (Maybe Kind)
1231 [TySynEqn] -- ^ @{ type family F a b :: * where ... }@
1232
1233 | RoleAnnotD Name [Role] -- ^ @{ type role T nominal representational }@
1234 deriving( Show, Eq, Data, Typeable )
1235
1236 -- | One equation of a type family instance or closed type family. The
1237 -- arguments are the left-hand-side type patterns and the right-hand-side
1238 -- result.
1239 data TySynEqn = TySynEqn [Type] Type
1240 deriving( Show, Eq, Data, Typeable )
1241
1242 data FunDep = FunDep [Name] [Name]
1243 deriving( Show, Eq, Data, Typeable )
1244
1245 data FamFlavour = TypeFam | DataFam
1246 deriving( Show, Eq, Data, Typeable )
1247
1248 data Foreign = ImportF Callconv Safety String Name Type
1249 | ExportF Callconv String Name Type
1250 deriving( Show, Eq, Data, Typeable )
1251
1252 data Callconv = CCall | StdCall
1253 deriving( Show, Eq, Data, Typeable )
1254
1255 data Safety = Unsafe | Safe | Interruptible
1256 deriving( Show, Eq, Data, Typeable )
1257
1258 data Pragma = InlineP Name Inline RuleMatch Phases
1259 | SpecialiseP Name Type (Maybe Inline) Phases
1260 | SpecialiseInstP Type
1261 | RuleP String [RuleBndr] Exp Exp Phases
1262 | AnnP AnnTarget Exp
1263 deriving( Show, Eq, Data, Typeable )
1264
1265 data Inline = NoInline
1266 | Inline
1267 | Inlinable
1268 deriving (Show, Eq, Data, Typeable)
1269
1270 data RuleMatch = ConLike
1271 | FunLike
1272 deriving (Show, Eq, Data, Typeable)
1273
1274 data Phases = AllPhases
1275 | FromPhase Int
1276 | BeforePhase Int
1277 deriving (Show, Eq, Data, Typeable)
1278
1279 data RuleBndr = RuleVar Name
1280 | TypedRuleVar Name Type
1281 deriving (Show, Eq, Data, Typeable)
1282
1283 data AnnTarget = ModuleAnnotation
1284 | TypeAnnotation Name
1285 | ValueAnnotation Name
1286 deriving (Show, Eq, Data, Typeable)
1287
1288 type Cxt = [Pred] -- ^ @(Eq a, Ord b)@
1289
1290 data Pred = ClassP Name [Type] -- ^ @Eq (Int, a)@
1291 | EqualP Type Type -- ^ @F a ~ Bool@
1292 deriving( Show, Eq, Data, Typeable )
1293
1294 data Strict = IsStrict | NotStrict | Unpacked
1295 deriving( Show, Eq, Data, Typeable )
1296
1297 data Con = NormalC Name [StrictType] -- ^ @C Int a@
1298 | RecC Name [VarStrictType] -- ^ @C { v :: Int, w :: a }@
1299 | InfixC StrictType Name StrictType -- ^ @Int :+ a@
1300 | ForallC [TyVarBndr] Cxt Con -- ^ @forall a. Eq a => C [a]@
1301 deriving( Show, Eq, Data, Typeable )
1302
1303 type StrictType = (Strict, Type)
1304 type VarStrictType = (Name, Strict, Type)
1305
1306 data Type = ForallT [TyVarBndr] Cxt Type -- ^ @forall \<vars\>. \<ctxt\> -> \<type\>@
1307 | AppT Type Type -- ^ @T a b@
1308 | SigT Type Kind -- ^ @t :: k@
1309 | VarT Name -- ^ @a@
1310 | ConT Name -- ^ @T@
1311 | PromotedT Name -- ^ @'T@
1312
1313 -- See Note [Representing concrete syntax in types]
1314 | TupleT Int -- ^ @(,), (,,), etc.@
1315 | UnboxedTupleT Int -- ^ @(#,#), (#,,#), etc.@
1316 | ArrowT -- ^ @->@
1317 | ListT -- ^ @[]@
1318 | PromotedTupleT Int -- ^ @'(), '(,), '(,,), etc.@
1319 | PromotedNilT -- ^ @'[]@
1320 | PromotedConsT -- ^ @(':)@
1321 | StarT -- ^ @*@
1322 | ConstraintT -- ^ @Constraint@
1323 | LitT TyLit -- ^ @0,1,2, etc.@
1324 deriving( Show, Eq, Data, Typeable )
1325
1326 data TyVarBndr = PlainTV Name -- ^ @a@
1327 | KindedTV Name Kind -- ^ @(a :: k)@
1328 deriving( Show, Eq, Data, Typeable )
1329
1330 data TyLit = NumTyLit Integer -- ^ @2@
1331 | StrTyLit String -- ^ @"Hello"@
1332 deriving ( Show, Eq, Data, Typeable )
1333
1334 -- | Role annotations
1335 data Role = NominalR -- ^ @nominal@
1336 | RepresentationalR -- ^ @representational@
1337 | PhantomR -- ^ @phantom@
1338 | InferR -- ^ @_@
1339 deriving( Show, Eq, Data, Typeable )
1340
1341 -- | To avoid duplication between kinds and types, they
1342 -- are defined to be the same. Naturally, you would never
1343 -- have a type be 'StarT' and you would never have a kind
1344 -- be 'SigT', but many of the other constructors are shared.
1345 -- Note that the kind @Bool@ is denoted with 'ConT', not
1346 -- 'PromotedT'. Similarly, tuple kinds are made with 'TupleT',
1347 -- not 'PromotedTupleT'.
1348
1349 type Kind = Type
1350
1351 {- Note [Representing concrete syntax in types]
1352 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1353 Haskell has a rich concrete syntax for types, including
1354 t1 -> t2, (t1,t2), [t], and so on
1355 In TH we represent all of this using AppT, with a distinguished
1356 type constructor at the head. So,
1357 Type TH representation
1358 -----------------------------------------------
1359 t1 -> t2 ArrowT `AppT` t2 `AppT` t2
1360 [t] ListT `AppT` t
1361 (t1,t2) TupleT 2 `AppT` t1 `AppT` t2
1362 '(t1,t2) PromotedTupleT 2 `AppT` t1 `AppT` t2
1363
1364 But if the original HsSyn used prefix application, we won't use
1365 these special TH constructors. For example
1366 [] t ConT "[]" `AppT` t
1367 (->) t ConT "->" `AppT` t
1368 In this way we can faithfully represent in TH whether the original
1369 HsType used concrete syntax or not.
1370
1371 The one case that doesn't fit this pattern is that of promoted lists
1372 '[ Maybe, IO ] PromotedListT 2 `AppT` t1 `AppT` t2
1373 but it's very smelly because there really is no type constructor
1374 corresponding to PromotedListT. So we encode HsExplicitListTy with
1375 PromotedConsT and PromotedNilT (which *do* have underlying type
1376 constructors):
1377 '[ Maybe, IO ] PromotedConsT `AppT` Maybe `AppT`
1378 (PromotedConsT `AppT` IO `AppT` PromotedNilT)
1379 -}
1380
1381 -----------------------------------------------------
1382 -- Internal helper functions
1383 -----------------------------------------------------
1384
1385 cmpEq :: Ordering -> Bool
1386 cmpEq EQ = True
1387 cmpEq _ = False
1388
1389 thenCmp :: Ordering -> Ordering -> Ordering
1390 thenCmp EQ o2 = o2
1391 thenCmp o1 _ = o1
1392