c18d8012468332636583f33b419e9674f9447575
[packages/template-haskell.git] / Language / Haskell / TH / Syntax.hs
1 {-# LANGUAGE UnboxedTuples #-}
2 {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
3 -- The -fno-warn-warnings-deprecations flag is a temporary kludge.
4 -- While working on this module you are encouraged to remove it and fix
5 -- any warnings in the module. See
6 -- http://hackage.haskell.org/trac/ghc/wiki/WorkingConventions#Warnings
7 -- for details
8
9 -----------------------------------------------------------------------------
10 -- |
11 -- Module : Language.Haskell.Syntax
12 -- Copyright : (c) The University of Glasgow 2003
13 -- License : BSD-style (see the file libraries/base/LICENSE)
14 --
15 -- Maintainer : libraries@haskell.org
16 -- Stability : experimental
17 -- Portability : portable
18 --
19 -- Abstract syntax definitions for Template Haskell.
20 --
21 -----------------------------------------------------------------------------
22
23 module Language.Haskell.TH.Syntax(
24 Quasi(..), Lift(..), liftString,
25
26 Q, runQ,
27 report, recover, reify,
28 lookupTypeName, lookupValueName,
29 location, runIO, addDependentFile,
30 isInstance, reifyInstances,
31
32 -- * Names
33 Name(..), mkName, newName, nameBase, nameModule,
34 showName, showName', NameIs(..),
35
36 -- * The algebraic data types
37 -- $infix
38 Dec(..), Exp(..), Con(..), Type(..), TyVarBndr(..), Kind, Cxt,
39 TyLit(..),
40 Pred(..), Match(..), Clause(..), Body(..), Guard(..), Stmt(..),
41 Range(..), Lit(..), Pat(..), FieldExp, FieldPat,
42 Strict(..), Foreign(..), Callconv(..), Safety(..), Pragma(..),
43 Inline(..), InlineSpec(..), StrictType, VarStrictType, FunDep(..),
44 FamFlavour(..), Info(..), Loc(..), CharPos,
45 Fixity(..), FixityDirection(..), defaultFixity, maxPrecedence,
46
47 -- * Internal functions
48 returnQ, bindQ, sequenceQ,
49 NameFlavour(..), NameSpace (..),
50 mkNameG_v, mkNameG_d, mkNameG_tc, Uniq, mkNameL, mkNameU,
51 tupleTypeName, tupleDataName,
52 unboxedTupleTypeName, unboxedTupleDataName,
53 OccName, mkOccName, occString,
54 ModName, mkModName, modString,
55 PkgName, mkPkgName, pkgString
56 ) where
57
58 import GHC.Base ( Int(..), Int#, (<#), (==#) )
59
60 import Language.Haskell.TH.Syntax.Internals
61 import Data.Data (Data(..), Typeable, mkConstr, mkDataType, constrIndex)
62 import qualified Data.Data as Data
63 import Control.Applicative( Applicative(..) )
64 import Data.IORef
65 import System.IO.Unsafe ( unsafePerformIO )
66 import Control.Monad (liftM)
67 import System.IO ( hPutStrLn, stderr )
68 import Data.Char ( isAlpha )
69
70 -----------------------------------------------------
71 --
72 -- The Quasi class
73 --
74 -----------------------------------------------------
75
76 class (Monad m, Applicative m) => Quasi m where
77 qNewName :: String -> m Name
78 -- ^ Fresh names
79
80 -- Error reporting and recovery
81 qReport :: Bool -> String -> m () -- ^ Report an error (True) or warning (False)
82 -- ...but carry on; use 'fail' to stop
83 qRecover :: m a -- ^ the error handler
84 -> m a -- ^ action which may fail
85 -> m a -- ^ Recover from the monadic 'fail'
86
87 -- Inspect the type-checker's environment
88 qLookupName :: Bool -> String -> m (Maybe Name)
89 -- True <=> type namespace, False <=> value namespace
90 qReify :: Name -> m Info
91 qReifyInstances :: Name -> [Type] -> m [Dec]
92 -- Is (n tys) an instance?
93 -- Returns list of matching instance Decs
94 -- (with empty sub-Decs)
95 -- Works for classes and type functions
96
97 qLocation :: m Loc
98
99 qRunIO :: IO a -> m a
100 -- ^ Input/output (dangerous)
101
102 qAddDependentFile :: FilePath -> m ()
103
104 -----------------------------------------------------
105 -- The IO instance of Quasi
106 --
107 -- This instance is used only when running a Q
108 -- computation in the IO monad, usually just to
109 -- print the result. There is no interesting
110 -- type environment, so reification isn't going to
111 -- work.
112 --
113 -----------------------------------------------------
114
115 instance Quasi IO where
116 qNewName s = do { n <- readIORef counter
117 ; writeIORef counter (n+1)
118 ; return (mkNameU s n) }
119
120 qReport True msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
121 qReport False msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
122
123 qLookupName _ _ = badIO "lookupName"
124 qReify _ = badIO "reify"
125 qReifyInstances _ _ = badIO "classInstances"
126 qLocation = badIO "currentLocation"
127 qRecover _ _ = badIO "recover" -- Maybe we could fix this?
128 qAddDependentFile _ = badIO "addDependentFile"
129
130 qRunIO m = m
131
132 badIO :: String -> IO a
133 badIO op = do { qReport True ("Can't do `" ++ op ++ "' in the IO monad")
134 ; fail "Template Haskell failure" }
135
136 -- Global variable to generate unique symbols
137 counter :: IORef Int
138 {-# NOINLINE counter #-}
139 counter = unsafePerformIO (newIORef 0)
140
141
142 -----------------------------------------------------
143 --
144 -- The Q monad
145 --
146 -----------------------------------------------------
147
148 newtype Q a = Q { unQ :: forall m. Quasi m => m a }
149
150 runQ :: Quasi m => Q a -> m a
151 runQ (Q m) = m
152
153 instance Monad Q where
154 return x = Q (return x)
155 Q m >>= k = Q (m >>= \x -> unQ (k x))
156 Q m >> Q n = Q (m >> n)
157 fail s = report True s >> Q (fail "Q monad failure")
158
159 instance Functor Q where
160 fmap f (Q x) = Q (fmap f x)
161
162 instance Applicative Q where
163 pure x = Q (pure x)
164 Q f <*> Q x = Q (f <*> x)
165
166 ----------------------------------------------------
167 -- Packaged versions for the programmer, hiding the Quasi-ness
168 newName :: String -> Q Name
169 newName s = Q (qNewName s)
170
171 report :: Bool -> String -> Q ()
172 report b s = Q (qReport b s)
173
174 recover :: Q a -- ^ recover with this one
175 -> Q a -- ^ failing action
176 -> Q a
177 recover (Q r) (Q m) = Q (qRecover r m)
178
179 -- We don't export lookupName; the Bool isn't a great API
180 -- Instead we export lookupTypeName, lookupValueName
181 lookupName :: Bool -> String -> Q (Maybe Name)
182 lookupName ns s = Q (qLookupName ns s)
183
184 lookupTypeName, lookupValueName :: String -> Q (Maybe Name)
185 lookupTypeName s = Q (qLookupName True s)
186 lookupValueName s = Q (qLookupName False s)
187
188 -- | 'reify' looks up information about the 'Name'
189 reify :: Name -> Q Info
190 reify v = Q (qReify v)
191
192 -- | 'classInstances' looks up instaces of a class
193 reifyInstances :: Name -> [Type] -> Q [Dec]
194 reifyInstances cls tys = Q (qReifyInstances cls tys)
195
196 isInstance :: Name -> [Type] -> Q Bool
197 isInstance nm tys = do { decs <- reifyInstances nm tys
198 ; return (not (null decs)) }
199
200 -- | 'location' gives you the 'Location' at which this
201 -- computation is spliced.
202 location :: Q Loc
203 location = Q qLocation
204
205 -- |The 'runIO' function lets you run an I\/O computation in the 'Q' monad.
206 -- Take care: you are guaranteed the ordering of calls to 'runIO' within
207 -- a single 'Q' computation, but not about the order in which splices are run.
208 --
209 -- Note: for various murky reasons, stdout and stderr handles are not
210 -- necesarily flushed when the compiler finishes running, so you should
211 -- flush them yourself.
212 runIO :: IO a -> Q a
213 runIO m = Q (qRunIO m)
214
215 -- | Record external files that runIO is using (dependent upon).
216 -- The compiler can then recognize that it should re-compile the file using this TH when the external file changes.
217 -- Note that ghc -M will still not know about these dependencies - it does not execute TH.
218 -- Expects an absolute file path.
219 addDependentFile :: FilePath -> Q ()
220 addDependentFile fp = Q (qAddDependentFile fp)
221
222 instance Quasi Q where
223 qNewName = newName
224 qReport = report
225 qRecover = recover
226 qReify = reify
227 qReifyInstances = reifyInstances
228 qLookupName = lookupName
229 qLocation = location
230 qRunIO = runIO
231 qAddDependentFile = addDependentFile
232
233
234 ----------------------------------------------------
235 -- The following operations are used solely in DsMeta when desugaring brackets
236 -- They are not necessary for the user, who can use ordinary return and (>>=) etc
237
238 returnQ :: a -> Q a
239 returnQ = return
240
241 bindQ :: Q a -> (a -> Q b) -> Q b
242 bindQ = (>>=)
243
244 sequenceQ :: [Q a] -> Q [a]
245 sequenceQ = sequence
246
247
248 -----------------------------------------------------
249 --
250 -- The Lift class
251 --
252 -----------------------------------------------------
253
254 class Lift t where
255 lift :: t -> Q Exp
256
257 instance Lift Integer where
258 lift x = return (LitE (IntegerL x))
259
260 instance Lift Int where
261 lift x= return (LitE (IntegerL (fromIntegral x)))
262
263 instance Lift Char where
264 lift x = return (LitE (CharL x))
265
266 instance Lift Bool where
267 lift True = return (ConE trueName)
268 lift False = return (ConE falseName)
269
270 instance Lift a => Lift (Maybe a) where
271 lift Nothing = return (ConE nothingName)
272 lift (Just x) = liftM (ConE justName `AppE`) (lift x)
273
274 instance (Lift a, Lift b) => Lift (Either a b) where
275 lift (Left x) = liftM (ConE leftName `AppE`) (lift x)
276 lift (Right y) = liftM (ConE rightName `AppE`) (lift y)
277
278 instance Lift a => Lift [a] where
279 lift xs = do { xs' <- mapM lift xs; return (ListE xs') }
280
281 liftString :: String -> Q Exp
282 -- Used in TcExpr to short-circuit the lifting for strings
283 liftString s = return (LitE (StringL s))
284
285 instance (Lift a, Lift b) => Lift (a, b) where
286 lift (a, b)
287 = liftM TupE $ sequence [lift a, lift b]
288
289 instance (Lift a, Lift b, Lift c) => Lift (a, b, c) where
290 lift (a, b, c)
291 = liftM TupE $ sequence [lift a, lift b, lift c]
292
293 instance (Lift a, Lift b, Lift c, Lift d) => Lift (a, b, c, d) where
294 lift (a, b, c, d)
295 = liftM TupE $ sequence [lift a, lift b, lift c, lift d]
296
297 instance (Lift a, Lift b, Lift c, Lift d, Lift e)
298 => Lift (a, b, c, d, e) where
299 lift (a, b, c, d, e)
300 = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e]
301
302 instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f)
303 => Lift (a, b, c, d, e, f) where
304 lift (a, b, c, d, e, f)
305 = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f]
306
307 instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f, Lift g)
308 => Lift (a, b, c, d, e, f, g) where
309 lift (a, b, c, d, e, f, g)
310 = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f, lift g]
311
312 -- TH has a special form for literal strings,
313 -- which we should take advantage of.
314 -- NB: the lhs of the rule has no args, so that
315 -- the rule will apply to a 'lift' all on its own
316 -- which happens to be the way the type checker
317 -- creates it.
318 {-# RULES "TH:liftString" lift = \s -> return (LitE (StringL s)) #-}
319
320
321 trueName, falseName :: Name
322 trueName = mkNameG DataName "ghc-prim" "GHC.Types" "True"
323 falseName = mkNameG DataName "ghc-prim" "GHC.Types" "False"
324
325 nothingName, justName :: Name
326 nothingName = mkNameG DataName "base" "Data.Maybe" "Nothing"
327 justName = mkNameG DataName "base" "Data.Maybe" "Just"
328
329 leftName, rightName :: Name
330 leftName = mkNameG DataName "base" "Data.Either" "Left"
331 rightName = mkNameG DataName "base" "Data.Either" "Right"
332
333
334 -----------------------------------------------------
335 -- Names and uniques
336 -----------------------------------------------------
337
338 mkModName :: String -> ModName
339 mkModName s = ModName s
340
341 modString :: ModName -> String
342 modString (ModName m) = m
343
344
345 mkPkgName :: String -> PkgName
346 mkPkgName s = PkgName s
347
348 pkgString :: PkgName -> String
349 pkgString (PkgName m) = m
350
351
352 -----------------------------------------------------
353 -- OccName
354 -----------------------------------------------------
355
356 mkOccName :: String -> OccName
357 mkOccName s = OccName s
358
359 occString :: OccName -> String
360 occString (OccName occ) = occ
361
362
363 -----------------------------------------------------
364 -- Names
365 -----------------------------------------------------
366
367 -- |
368 -- For "global" names ('NameG') we need a totally unique name,
369 -- so we must include the name-space of the thing
370 --
371 -- For unique-numbered things ('NameU'), we've got a unique reference
372 -- anyway, so no need for name space
373 --
374 -- For dynamically bound thing ('NameS') we probably want them to
375 -- in a context-dependent way, so again we don't want the name
376 -- space. For example:
377 --
378 -- > let v = mkName "T" in [| data $v = $v |]
379 --
380 -- Here we use the same Name for both type constructor and data constructor
381 --
382 --
383 -- NameL and NameG are bound *outside* the TH syntax tree
384 -- either globally (NameG) or locally (NameL). Ex:
385 --
386 -- > f x = $(h [| (map, x) |])
387 --
388 -- The 'map' will be a NameG, and 'x' wil be a NameL
389 --
390 -- These Names should never appear in a binding position in a TH syntax tree
391 data Name = Name OccName NameFlavour deriving (Typeable, Data)
392
393 data NameFlavour
394 = NameS -- ^ An unqualified name; dynamically bound
395 | NameQ ModName -- ^ A qualified name; dynamically bound
396 | NameU Int# -- ^ A unique local name
397 | NameL Int# -- ^ Local name bound outside of the TH AST
398 | NameG NameSpace PkgName ModName -- ^ Global name bound outside of the TH AST:
399 -- An original name (occurrences only, not binders)
400 -- Need the namespace too to be sure which
401 -- thing we are naming
402 deriving ( Typeable )
403
404 -- |
405 -- Although the NameFlavour type is abstract, the Data instance is not. The reason for this
406 -- is that currently we use Data to serialize values in annotations, and in order for that to
407 -- work for Template Haskell names introduced via the 'x syntax we need gunfold on NameFlavour
408 -- to work. Bleh!
409 --
410 -- The long term solution to this is to use the binary package for annotation serialization and
411 -- then remove this instance. However, to do _that_ we need to wait on binary to become stable, since
412 -- boot libraries cannot be upgraded seperately from GHC itself.
413 --
414 -- This instance cannot be derived automatically due to bug #2701
415 instance Data NameFlavour where
416 gfoldl _ z NameS = z NameS
417 gfoldl k z (NameQ mn) = z NameQ `k` mn
418 gfoldl k z (NameU i) = z (\(I# i') -> NameU i') `k` (I# i)
419 gfoldl k z (NameL i) = z (\(I# i') -> NameL i') `k` (I# i)
420 gfoldl k z (NameG ns p m) = z NameG `k` ns `k` p `k` m
421 gunfold k z c = case constrIndex c of
422 1 -> z NameS
423 2 -> k $ z NameQ
424 3 -> k $ z (\(I# i) -> NameU i)
425 4 -> k $ z (\(I# i) -> NameL i)
426 5 -> k $ k $ k $ z NameG
427 _ -> error "gunfold: NameFlavour"
428 toConstr NameS = con_NameS
429 toConstr (NameQ _) = con_NameQ
430 toConstr (NameU _) = con_NameU
431 toConstr (NameL _) = con_NameL
432 toConstr (NameG _ _ _) = con_NameG
433 dataTypeOf _ = ty_NameFlavour
434
435 con_NameS, con_NameQ, con_NameU, con_NameL, con_NameG :: Data.Constr
436 con_NameS = mkConstr ty_NameFlavour "NameS" [] Data.Prefix
437 con_NameQ = mkConstr ty_NameFlavour "NameQ" [] Data.Prefix
438 con_NameU = mkConstr ty_NameFlavour "NameU" [] Data.Prefix
439 con_NameL = mkConstr ty_NameFlavour "NameL" [] Data.Prefix
440 con_NameG = mkConstr ty_NameFlavour "NameG" [] Data.Prefix
441
442 ty_NameFlavour :: Data.DataType
443 ty_NameFlavour = mkDataType "Language.Haskell.TH.Syntax.NameFlavour"
444 [con_NameS, con_NameQ, con_NameU,
445 con_NameL, con_NameG]
446
447 data NameSpace = VarName -- ^ Variables
448 | DataName -- ^ Data constructors
449 | TcClsName -- ^ Type constructors and classes; Haskell has them
450 -- in the same name space for now.
451 deriving( Eq, Ord, Data, Typeable )
452
453 type Uniq = Int
454
455 -- | Base, unqualified name.
456 nameBase :: Name -> String
457 nameBase (Name occ _) = occString occ
458
459 nameModule :: Name -> Maybe String
460 nameModule (Name _ (NameQ m)) = Just (modString m)
461 nameModule (Name _ (NameG _ _ m)) = Just (modString m)
462 nameModule _ = Nothing
463
464 mkName :: String -> Name
465 -- ^ The string can have a '.', thus "Foo.baz",
466 -- giving a dynamically-bound qualified name,
467 -- in which case we want to generate a NameQ
468 --
469 -- Parse the string to see if it has a "." in it
470 -- so we know whether to generate a qualified or unqualified name
471 -- It's a bit tricky because we need to parse
472 --
473 -- > Foo.Baz.x as Qual Foo.Baz x
474 --
475 -- So we parse it from back to front
476 mkName str
477 = split [] (reverse str)
478 where
479 split occ [] = Name (mkOccName occ) NameS
480 split occ ('.':rev) | not (null occ),
481 not (null rev), head rev /= '.'
482 = Name (mkOccName occ) (NameQ (mkModName (reverse rev)))
483 -- The 'not (null occ)' guard ensures that
484 -- mkName "&." = Name "&." NameS
485 -- The 'rev' guards ensure that
486 -- mkName ".&" = Name ".&" NameS
487 -- mkName "Data.Bits..&" = Name ".&" (NameQ "Data.Bits")
488 -- This rather bizarre case actually happened; (.&.) is in Data.Bits
489 split occ (c:rev) = split (c:occ) rev
490
491 -- | Only used internally
492 mkNameU :: String -> Uniq -> Name
493 mkNameU s (I# u) = Name (mkOccName s) (NameU u)
494
495 -- | Only used internally
496 mkNameL :: String -> Uniq -> Name
497 mkNameL s (I# u) = Name (mkOccName s) (NameL u)
498
499 -- | Used for 'x etc, but not available to the programmer
500 mkNameG :: NameSpace -> String -> String -> String -> Name
501 mkNameG ns pkg modu occ
502 = Name (mkOccName occ) (NameG ns (mkPkgName pkg) (mkModName modu))
503
504 mkNameG_v, mkNameG_tc, mkNameG_d :: String -> String -> String -> Name
505 mkNameG_v = mkNameG VarName
506 mkNameG_tc = mkNameG TcClsName
507 mkNameG_d = mkNameG DataName
508
509 instance Eq Name where
510 v1 == v2 = cmpEq (v1 `compare` v2)
511
512 instance Ord Name where
513 (Name o1 f1) `compare` (Name o2 f2) = (f1 `compare` f2) `thenCmp`
514 (o1 `compare` o2)
515
516 instance Eq NameFlavour where
517 f1 == f2 = cmpEq (f1 `compare` f2)
518
519 instance Ord NameFlavour where
520 -- NameS < NameQ < NameU < NameL < NameG
521 NameS `compare` NameS = EQ
522 NameS `compare` _ = LT
523
524 (NameQ _) `compare` NameS = GT
525 (NameQ m1) `compare` (NameQ m2) = m1 `compare` m2
526 (NameQ _) `compare` _ = LT
527
528 (NameU _) `compare` NameS = GT
529 (NameU _) `compare` (NameQ _) = GT
530 (NameU u1) `compare` (NameU u2) | u1 <# u2 = LT
531 | u1 ==# u2 = EQ
532 | otherwise = GT
533 (NameU _) `compare` _ = LT
534
535 (NameL _) `compare` NameS = GT
536 (NameL _) `compare` (NameQ _) = GT
537 (NameL _) `compare` (NameU _) = GT
538 (NameL u1) `compare` (NameL u2) | u1 <# u2 = LT
539 | u1 ==# u2 = EQ
540 | otherwise = GT
541 (NameL _) `compare` _ = LT
542
543 (NameG ns1 p1 m1) `compare` (NameG ns2 p2 m2) = (ns1 `compare` ns2) `thenCmp`
544 (p1 `compare` p2) `thenCmp`
545 (m1 `compare` m2)
546 (NameG _ _ _) `compare` _ = GT
547
548 data NameIs = Alone | Applied | Infix
549
550 showName :: Name -> String
551 showName = showName' Alone
552
553 showName' :: NameIs -> Name -> String
554 showName' ni nm
555 = case ni of
556 Alone -> nms
557 Applied
558 | pnam -> nms
559 | otherwise -> "(" ++ nms ++ ")"
560 Infix
561 | pnam -> "`" ++ nms ++ "`"
562 | otherwise -> nms
563 where
564 -- For now, we make the NameQ and NameG print the same, even though
565 -- NameQ is a qualified name (so what it means depends on what the
566 -- current scope is), and NameG is an original name (so its meaning
567 -- should be independent of what's in scope.
568 -- We may well want to distinguish them in the end.
569 -- Ditto NameU and NameL
570 nms = case nm of
571 Name occ NameS -> occString occ
572 Name occ (NameQ m) -> modString m ++ "." ++ occString occ
573 Name occ (NameG _ _ m) -> modString m ++ "." ++ occString occ
574 Name occ (NameU u) -> occString occ ++ "_" ++ show (I# u)
575 Name occ (NameL u) -> occString occ ++ "_" ++ show (I# u)
576
577 pnam = classify nms
578
579 -- True if we are function style, e.g. f, [], (,)
580 -- False if we are operator style, e.g. +, :+
581 classify "" = False -- shouldn't happen; . operator is handled below
582 classify (x:xs) | isAlpha x || (x `elem` "_[]()") =
583 case dropWhile (/='.') xs of
584 (_:xs') -> classify xs'
585 [] -> True
586 | otherwise = False
587
588 instance Show Name where
589 show = showName
590
591 -- Tuple data and type constructors
592 tupleDataName :: Int -> Name -- ^ Data constructor
593 tupleTypeName :: Int -> Name -- ^ Type constructor
594
595 tupleDataName 0 = mk_tup_name 0 DataName
596 tupleDataName 1 = error "tupleDataName 1"
597 tupleDataName n = mk_tup_name (n-1) DataName
598
599 tupleTypeName 0 = mk_tup_name 0 TcClsName
600 tupleTypeName 1 = error "tupleTypeName 1"
601 tupleTypeName n = mk_tup_name (n-1) TcClsName
602
603 mk_tup_name :: Int -> NameSpace -> Name
604 mk_tup_name n_commas space
605 = Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
606 where
607 occ = mkOccName ('(' : replicate n_commas ',' ++ ")")
608 tup_mod = mkModName "GHC.Tuple"
609
610 -- Unboxed tuple data and type constructors
611 unboxedTupleDataName :: Int -> Name -- ^ Data constructor
612 unboxedTupleTypeName :: Int -> Name -- ^ Type constructor
613
614 unboxedTupleDataName 0 = error "unboxedTupleDataName 0"
615 unboxedTupleDataName 1 = error "unboxedTupleDataName 1"
616 unboxedTupleDataName n = mk_unboxed_tup_name (n-1) DataName
617
618 unboxedTupleTypeName 0 = error "unboxedTupleTypeName 0"
619 unboxedTupleTypeName 1 = error "unboxedTupleTypeName 1"
620 unboxedTupleTypeName n = mk_unboxed_tup_name (n-1) TcClsName
621
622 mk_unboxed_tup_name :: Int -> NameSpace -> Name
623 mk_unboxed_tup_name n_commas space
624 = Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
625 where
626 occ = mkOccName ("(#" ++ replicate n_commas ',' ++ "#)")
627 tup_mod = mkModName "GHC.Tuple"
628
629
630
631 -----------------------------------------------------
632 -- Locations
633 -----------------------------------------------------
634
635 data Loc
636 = Loc { loc_filename :: String
637 , loc_package :: String
638 , loc_module :: String
639 , loc_start :: CharPos
640 , loc_end :: CharPos }
641
642 type CharPos = (Int, Int) -- Line and character position
643
644
645 -----------------------------------------------------
646 --
647 -- The Info returned by reification
648 --
649 -----------------------------------------------------
650
651 -- | Obtained from 'reify' in the 'Q' Monad.
652 data Info
653 = -- | A class is reified to its declaration
654 -- and a list of its instances
655 ClassI
656 Dec -- Declaration of the class
657 [InstanceDec] -- The instances of that class
658
659 | ClassOpI
660 Name -- The class op itself
661 Type -- Type of the class-op (fully polymoprhic)
662 Name -- Name of the parent class
663 Fixity
664
665 | TyConI
666 Dec
667
668 | FamilyI -- Type/data families
669 Dec
670 [InstanceDec]
671
672 | PrimTyConI -- Ones that can't be expressed with a data type
673 -- decl, such as (->), Int#
674 Name
675 Int -- Arity
676 Bool -- False => lifted type; True => unlifted
677
678 | DataConI
679 Name -- The data con itself
680 Type -- Type of the constructor (fully polymorphic)
681 Name -- Name of the parent TyCon
682 Fixity
683
684 | VarI
685 Name -- The variable itself
686 Type
687 (Maybe Dec) -- Nothing for lambda-bound variables, and
688 -- for anything else TH can't figure out
689 -- E.g. [| let x = 1 in $(do { d <- reify 'x; .. }) |]
690 Fixity
691
692 | TyVarI -- Scoped type variable
693 Name
694 Type -- What it is bound to
695 deriving( Show, Data, Typeable )
696
697 -- | 'InstanceDec' desribes a single instance of a class or type function
698 -- It is just a 'Dec', but guaranteed to be one of the following:
699 -- InstanceD (with empty [Dec])
700 -- DataInstD or NewtypeInstD (with empty derived [Name])
701 -- TySynInstD
702 type InstanceDec = Dec
703
704 data Fixity = Fixity Int FixityDirection
705 deriving( Eq, Show, Data, Typeable )
706 data FixityDirection = InfixL | InfixR | InfixN
707 deriving( Eq, Show, Data, Typeable )
708
709 maxPrecedence :: Int
710 maxPrecedence = (9::Int)
711
712 defaultFixity :: Fixity
713 defaultFixity = Fixity maxPrecedence InfixL
714
715
716 -----------------------------------------------------
717 --
718 -- The main syntax data types
719 --
720 -----------------------------------------------------
721
722 {- $infix #infix#
723 Note [Unresolved infix]
724 ~~~~~~~~~~~~~~~~~~~~~~~
725
726 When implementing antiquotation for quasiquoters, one often wants
727 to parse strings into expressions:
728
729 > parse :: String -> Maybe 'Exp'
730
731 But how should we parse @a + b * c@? If we don't know the fixities of
732 @+@ and @*@, we don't know whether to parse it as @a + (b * c)@ or @(a
733 + b) * c@.
734
735 In cases like this, use 'UInfixE' or 'UInfixP', which stand for
736 \"unresolved infix expression\" and \"unresolved infix pattern\". When
737 the compiler is given a splice containing a tree of @UInfixE@
738 applications such as
739
740 > UInfixE
741 > (UInfixE e1 op1 e2)
742 > op2
743 > (UInfixE e3 op3 e4)
744
745 it will look up and the fixities of the relevant operators and
746 reassociate the tree as necessary.
747
748 * trees will not be reassociated across 'ParensE' or 'ParensP',
749 which are of use for parsing expressions like
750
751 > (a + b * c) + d * e
752
753 * 'InfixE' and 'InfixP' expressions are never reassociated.
754
755 * The 'UInfixE' constructor doesn't support sections. Sections
756 such as @(a *)@ have no ambiguity, so 'InfixE' suffices. For longer
757 sections such as @(a + b * c -)@, use an 'InfixE' constructor for the
758 outer-most section, and use 'UInfixE' constructors for all
759 other operators:
760
761 > InfixE
762 > Just (UInfixE ...a + b * c...)
763 > op
764 > Nothing
765
766 Sections such as @(a + b +)@ and @((a + b) +)@ should be rendered
767 into 'Exp's differently:
768
769 > (+ a + b) ---> InfixE Nothing + (Just $ UInfixE a + b)
770 > -- will result in a fixity error if (+) is left-infix
771 > (+ (a + b)) ---> InfixE Nothing + (Just $ ParensE $ UInfixE a + b)
772 > -- no fixity errors
773
774 * Quoted expressions such as
775
776 > [| a * b + c |] :: Q Exp
777 > [p| a : b : c |] :: Q Pat
778
779 will never contain 'UInfixE', 'UInfixP', 'ParensE', or 'ParensP'
780 constructors.
781
782 -}
783
784 data Lit = CharL Char
785 | StringL String
786 | IntegerL Integer -- ^ Used for overloaded and non-overloaded
787 -- literals. We don't have a good way to
788 -- represent non-overloaded literals at
789 -- the moment. Maybe that doesn't matter?
790 | RationalL Rational -- Ditto
791 | IntPrimL Integer
792 | WordPrimL Integer
793 | FloatPrimL Rational
794 | DoublePrimL Rational
795 | StringPrimL String -- ^ A primitive C-style string, type Addr#
796 deriving( Show, Eq, Data, Typeable )
797
798 -- We could add Int, Float, Double etc, as we do in HsLit,
799 -- but that could complicate the
800 -- suppposedly-simple TH.Syntax literal type
801
802 -- | Pattern in Haskell given in @{}@
803 data Pat
804 = LitP Lit -- ^ @{ 5 or 'c' }@
805 | VarP Name -- ^ @{ x }@
806 | TupP [Pat] -- ^ @{ (p1,p2) }@
807 | UnboxedTupP [Pat] -- ^ @{ (# p1,p2 #) }@
808 | ConP Name [Pat] -- ^ @data T1 = C1 t1 t2; {C1 p1 p1} = e@
809 | InfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
810 | UInfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
811 --
812 -- See Note [Unresolved infix] at "Language.Haskell.TH.Syntax#infix"
813 | ParensP Pat -- ^ @{(p)}@
814 --
815 -- See Note [Unresolved infix] at "Language.Haskell.TH.Syntax#infix"
816 | TildeP Pat -- ^ @{ ~p }@
817 | BangP Pat -- ^ @{ !p }@
818 | AsP Name Pat -- ^ @{ x \@ p }@
819 | WildP -- ^ @{ _ }@
820 | RecP Name [FieldPat] -- ^ @f (Pt { pointx = x }) = g x@
821 | ListP [ Pat ] -- ^ @{ [1,2,3] }@
822 | SigP Pat Type -- ^ @{ p :: t }@
823 | ViewP Exp Pat -- ^ @{ e -> p }@
824 deriving( Show, Eq, Data, Typeable )
825
826 type FieldPat = (Name,Pat)
827
828 data Match = Match Pat Body [Dec] -- ^ @case e of { pat -> body where decs }@
829 deriving( Show, Eq, Data, Typeable )
830 data Clause = Clause [Pat] Body [Dec]
831 -- ^ @f { p1 p2 = body where decs }@
832 deriving( Show, Eq, Data, Typeable )
833
834 -- | The 'CompE' constructor represents a list comprehension, and
835 -- takes a ['Stmt']. The result expression of the comprehension is
836 -- the *last* of these, and should be a 'NoBindS'.
837 --
838 -- E.g. translation:
839 --
840 -- > [ f x | x <- xs ]
841 --
842 -- > CompE [BindS (VarP x) (VarE xs), NoBindS (AppE (VarE f) (VarE x))]
843 data Exp
844 = VarE Name -- ^ @{ x }@
845 | ConE Name -- ^ @data T1 = C1 t1 t2; p = {C1} e1 e2 @
846 | LitE Lit -- ^ @{ 5 or 'c'}@
847 | AppE Exp Exp -- ^ @{ f x }@
848
849 | InfixE (Maybe Exp) Exp (Maybe Exp) -- ^ @{x + y} or {(x+)} or {(+ x)} or {(+)}@
850 --
851 -- It's a bit gruesome to use an Exp as the
852 -- operator, but how else can we distinguish
853 -- constructors from non-constructors?
854 -- Maybe there should be a var-or-con type?
855 -- Or maybe we should leave it to the String itself?
856
857 | UInfixE Exp Exp Exp -- ^ @{x + y}@
858 --
859 -- See Note [Unresolved infix] at "Language.Haskell.TH.Syntax#infix"
860 | ParensE Exp -- ^ @{ (e) }@
861 --
862 -- See Note [Unresolved infix] at "Language.Haskell.TH.Syntax#infix"
863 | LamE [Pat] Exp -- ^ @{ \ p1 p2 -> e }@
864 | TupE [Exp] -- ^ @{ (e1,e2) } @
865 | UnboxedTupE [Exp] -- ^ @{ (# e1,e2 #) } @
866 | CondE Exp Exp Exp -- ^ @{ if e1 then e2 else e3 }@
867 | LetE [Dec] Exp -- ^ @{ let x=e1; y=e2 in e3 }@
868 | CaseE Exp [Match] -- ^ @{ case e of m1; m2 }@
869 | DoE [Stmt] -- ^ @{ do { p <- e1; e2 } }@
870 | CompE [Stmt] -- ^ @{ [ (x,y) | x <- xs, y <- ys ] }@
871 | ArithSeqE Range -- ^ @{ [ 1 ,2 .. 10 ] }@
872 | ListE [ Exp ] -- ^ @{ [1,2,3] }@
873 | SigE Exp Type -- ^ @{ e :: t }@
874 | RecConE Name [FieldExp] -- ^ @{ T { x = y, z = w } }@
875 | RecUpdE Exp [FieldExp] -- ^ @{ (f x) { z = w } }@
876 deriving( Show, Eq, Data, Typeable )
877
878 type FieldExp = (Name,Exp)
879
880 -- Omitted: implicit parameters
881
882 data Body
883 = GuardedB [(Guard,Exp)] -- ^ @f p { | e1 = e2 | e3 = e4 } where ds@
884 | NormalB Exp -- ^ @f p { = e } where ds@
885 deriving( Show, Eq, Data, Typeable )
886
887 data Guard
888 = NormalG Exp
889 | PatG [Stmt]
890 deriving( Show, Eq, Data, Typeable )
891
892 data Stmt
893 = BindS Pat Exp
894 | LetS [ Dec ]
895 | NoBindS Exp
896 | ParS [[Stmt]]
897 deriving( Show, Eq, Data, Typeable )
898
899 data Range = FromR Exp | FromThenR Exp Exp
900 | FromToR Exp Exp | FromThenToR Exp Exp Exp
901 deriving( Show, Eq, Data, Typeable )
902
903 data Dec
904 = FunD Name [Clause] -- ^ @{ f p1 p2 = b where decs }@
905 | ValD Pat Body [Dec] -- ^ @{ p = b where decs }@
906 | DataD Cxt Name [TyVarBndr]
907 [Con] [Name] -- ^ @{ data Cxt x => T x = A x | B (T x)
908 -- deriving (Z,W)}@
909 | NewtypeD Cxt Name [TyVarBndr]
910 Con [Name] -- ^ @{ newtype Cxt x => T x = A (B x)
911 -- deriving (Z,W)}@
912 | TySynD Name [TyVarBndr] Type -- ^ @{ type T x = (x,x) }@
913 | ClassD Cxt Name [TyVarBndr]
914 [FunDep] [Dec] -- ^ @{ class Eq a => Ord a where ds }@
915 | InstanceD Cxt Type [Dec] -- ^ @{ instance Show w => Show [w]
916 -- where ds }@
917 | SigD Name Type -- ^ @{ length :: [a] -> Int }@
918 | ForeignD Foreign
919
920 | InfixD Fixity Name -- ^ @{ infix 3 foo }@
921
922 -- | pragmas
923 | PragmaD Pragma -- ^ @{ {-# INLINE [1] foo #-} }@
924
925 -- | type families (may also appear in [Dec] of 'ClassD' and 'InstanceD')
926 | FamilyD FamFlavour Name
927 [TyVarBndr] (Maybe Kind) -- ^ @{ type family T a b c :: * }@
928
929 | DataInstD Cxt Name [Type]
930 [Con] [Name] -- ^ @{ data instance Cxt x => T [x] = A x
931 -- | B (T x)
932 -- deriving (Z,W)}@
933 | NewtypeInstD Cxt Name [Type]
934 Con [Name] -- ^ @{ newtype instance Cxt x => T [x] = A (B x)
935 -- deriving (Z,W)}@
936 | TySynInstD Name [Type] Type -- ^ @{ type instance T (Maybe x) = (x,x) }@
937 deriving( Show, Eq, Data, Typeable )
938
939 data FunDep = FunDep [Name] [Name]
940 deriving( Show, Eq, Data, Typeable )
941
942 data FamFlavour = TypeFam | DataFam
943 deriving( Show, Eq, Data, Typeable )
944
945 data Foreign = ImportF Callconv Safety String Name Type
946 | ExportF Callconv String Name Type
947 deriving( Show, Eq, Data, Typeable )
948
949 data Callconv = CCall | StdCall
950 deriving( Show, Eq, Data, Typeable )
951
952 data Safety = Unsafe | Safe | Interruptible
953 deriving( Show, Eq, Data, Typeable )
954
955 data Pragma = InlineP Name InlineSpec
956 | SpecialiseP Name Type (Maybe InlineSpec)
957 deriving( Show, Eq, Data, Typeable )
958
959 data Inline = NoInline
960 | Inline
961 | Inlinable
962 deriving (Show, Eq, Data, Typeable)
963
964 data InlineSpec
965 = InlineSpec Inline
966 Bool -- False: fun-like; True: constructor-like
967 (Maybe (Bool, Int)) -- False: before phase; True: from phase
968 deriving( Show, Eq, Data, Typeable )
969
970 type Cxt = [Pred] -- ^ @(Eq a, Ord b)@
971
972 data Pred = ClassP Name [Type] -- ^ @Eq (Int, a)@
973 | EqualP Type Type -- ^ @F a ~ Bool@
974 deriving( Show, Eq, Data, Typeable )
975
976 data Strict = IsStrict | NotStrict | Unpacked
977 deriving( Show, Eq, Data, Typeable )
978
979 data Con = NormalC Name [StrictType] -- ^ @C Int a@
980 | RecC Name [VarStrictType] -- ^ @C { v :: Int, w :: a }@
981 | InfixC StrictType Name StrictType -- ^ @Int :+ a@
982 | ForallC [TyVarBndr] Cxt Con -- ^ @forall a. Eq a => C [a]@
983 deriving( Show, Eq, Data, Typeable )
984
985 type StrictType = (Strict, Type)
986 type VarStrictType = (Name, Strict, Type)
987
988 data Type = ForallT [TyVarBndr] Cxt Type -- ^ @forall <vars>. <ctxt> -> <type>@
989 | AppT Type Type -- ^ @T a b@
990 | SigT Type Kind -- ^ @t :: k@
991 | VarT Name -- ^ @a@
992 | ConT Name -- ^ @T@
993 | PromotedT Name -- ^ @'T@
994
995 -- See Note [Representing concrete syntax in types]
996 | TupleT Int -- ^ @(,), (,,), etc.@
997 | UnboxedTupleT Int -- ^ @(#,#), (#,,#), etc.@
998 | ArrowT -- ^ @->@
999 | ListT -- ^ @[]@
1000 | PromotedTupleT Int -- ^ @'(), '(,), '(,,), etc.@
1001 | PromotedNilT -- ^ @'[]@
1002 | PromotedConsT -- ^ @(':)@
1003 | StarT -- ^ @*@
1004 | ConstraintT -- ^ @Constraint@
1005 | LitT TyLit -- ^ @0,1,2, etc.@
1006 deriving( Show, Eq, Data, Typeable )
1007
1008 data TyVarBndr = PlainTV Name -- ^ @a@
1009 | KindedTV Name Kind -- ^ @(a :: k)@
1010 deriving( Show, Eq, Data, Typeable )
1011
1012 data TyLit = NumTyLit Integer -- ^ @2@
1013 | StrTyLit String -- ^ @"Hello"@
1014 deriving ( Show, Eq, Data, Typeable )
1015
1016 -- | To avoid duplication between kinds and types, they
1017 -- are defined to be the same. Naturally, you would never
1018 -- have a type be 'StarT' and you would never have a kind
1019 -- be 'SigT', but many of the other constructors are shared.
1020 -- Note that the kind @Bool@ is denoted with 'ConT', not
1021 -- 'PromotedT'. Similarly, tuple kinds are made with 'TupleT',
1022 -- not 'PromotedTupleT'.
1023
1024 type Kind = Type
1025
1026 {- Note [Representing concrete syntax in types]
1027 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1028 Haskell has a rich concrete syntax for types, including
1029 t1 -> t2, (t1,t2), [t], and so on
1030 In TH we represent all of this using AppT, with a distinguished
1031 type construtor at the head. So,
1032 Type TH representation
1033 -----------------------------------------------
1034 t1 -> t2 ArrowT `AppT` t2 `AppT` t2
1035 [t] ListT `AppT` t
1036 (t1,t2) TupleT 2 `AppT` t1 `AppT` t2
1037 '(t1,t2) PromotedTupleT 2 `AppT` t1 `AppT` t2
1038
1039 But if the original HsSyn used prefix application, we won't use
1040 these special TH constructors. For example
1041 [] t ConT "[]" `AppT` t
1042 (->) t ConT "->" `AppT` t
1043 In this way we can faithfully represent in TH whether the original
1044 HsType used concrete syntax or not.
1045
1046 The one case that doesn't fit this pattern is that of promoted lists
1047 '[ Maybe, IO ] PromotedListT 2 `AppT` t1 `AppT` t2
1048 but it's very smelly because there really is no type constructor
1049 corresponding to PromotedListT. So we encode HsExplicitListTy with
1050 PromotedConsT and PromotedNilT (which *do* have underlying type
1051 constructors):
1052 '[ Maybe, IO ] PromotedConsT `AppT` Maybe `AppT`
1053 (PromotedConsT `AppT` IO `AppT` PromotedNilT)
1054 -}
1055
1056 -----------------------------------------------------
1057 -- Internal helper functions
1058 -----------------------------------------------------
1059
1060 cmpEq :: Ordering -> Bool
1061 cmpEq EQ = True
1062 cmpEq _ = False
1063
1064 thenCmp :: Ordering -> Ordering -> Ordering
1065 thenCmp EQ o2 = o2
1066 thenCmp o1 _ = o1
1067