Syntax.hs 61.2 KB
Newer Older
1
{-# LANGUAGE CPP, DeriveDataTypeable, PolymorphicComponents,
2 3
             DeriveGeneric, FlexibleInstances, DefaultSignatures,
             ScopedTypeVariables, Rank2Types #-}
4 5 6

{-# LANGUAGE RoleAnnotations #-}
{-# OPTIONS_GHC -fno-warn-inline-rule-shadowing #-}
7

8 9 10 11
#if MIN_VERSION_base(4,8,0)
#define HAS_NATURAL
#endif

12 13 14 15 16
-----------------------------------------------------------------------------
-- |
-- Module      :  Language.Haskell.Syntax
-- Copyright   :  (c) The University of Glasgow 2003
-- License     :  BSD-style (see the file libraries/base/LICENSE)
Jan Stolarek's avatar
Jan Stolarek committed
17
--
18 19 20 21 22 23 24 25
-- Maintainer  :  libraries@haskell.org
-- Stability   :  experimental
-- Portability :  portable
--
-- Abstract syntax definitions for Template Haskell.
--
-----------------------------------------------------------------------------

26 27 28 29 30
module Language.Haskell.TH.Syntax
    ( module Language.Haskell.TH.Syntax
      -- * Language extensions
    , module Language.Haskell.TH.LanguageExtensions
    ) where
31

32
import Data.Data hiding (Fixity(..))
33
import Data.IORef
34
import System.IO.Unsafe ( unsafePerformIO )
35
import Control.Monad (liftM)
36
import System.IO        ( hPutStrLn, stderr )
37
import Data.Char        ( isAlpha, isAlphaNum, isUpper )
38 39 40
import Data.Int
import Data.Word
import Data.Ratio
41
import GHC.Generics     ( Generic )
42
import GHC.Lexeme       ( startsVarSym, startsVarId )
43
import Language.Haskell.TH.LanguageExtensions
44

45 46 47 48
#ifdef HAS_NATURAL
import Numeric.Natural
#endif

49 50
-----------------------------------------------------
--
51
--              The Quasi class
52 53 54
--
-----------------------------------------------------

55
class (Applicative m, Monad m) => Quasi m where
56
  qNewName :: String -> m Name
57
        -- ^ Fresh names
58

59 60 61
        -- Error reporting and recovery
  qReport  :: Bool -> String -> m ()    -- ^ Report an error (True) or warning (False)
                                        -- ...but carry on; use 'fail' to stop
aavogt's avatar
aavogt committed
62 63
  qRecover :: m a -- ^ the error handler
           -> m a -- ^ action which may fail
64
           -> m a               -- ^ Recover from the monadic 'fail'
Jan Stolarek's avatar
Jan Stolarek committed
65

66
        -- Inspect the type-checker's environment
67 68 69
  qLookupName :: Bool -> String -> m (Maybe Name)
       -- True <=> type namespace, False <=> value namespace
  qReify          :: Name -> m Info
Ryan Scott's avatar
Ryan Scott committed
70
  qReifyFixity    :: Name -> m Fixity
71 72
  qReifyInstances :: Name -> [Type] -> m [Dec]
       -- Is (n tys) an instance?
Jan Stolarek's avatar
Jan Stolarek committed
73
       -- Returns list of matching instance Decs
74 75
       --    (with empty sub-Decs)
       -- Works for classes and type functions
76 77 78 79
  qReifyRoles         :: Name -> m [Role]
  qReifyAnnotations   :: Data a => AnnLookup -> m [a]
  qReifyModule        :: Module -> m ModuleInfo
  qReifyConStrictness :: Name -> m [DecidedStrictness]
80

81
  qLocation :: m Loc
82 83

  qRunIO :: IO a -> m a
aavogt's avatar
aavogt committed
84
  -- ^ Input/output (dangerous)
85

GregWeber's avatar
GregWeber committed
86
  qAddDependentFile :: FilePath -> m ()
87

88 89
  qAddTopDecls :: [Dec] -> m ()

90 91
  qAddModFinalizer :: Q () -> m ()

gmainland's avatar
gmainland committed
92 93 94 95
  qGetQ :: Typeable a => m (Maybe a)

  qPutQ :: Typeable a => a -> m ()

96 97 98
  qIsExtEnabled :: Extension -> m Bool
  qExtsEnabled :: m [Extension]

99
-----------------------------------------------------
100
--      The IO instance of Quasi
Jan Stolarek's avatar
Jan Stolarek committed
101
--
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
--  This instance is used only when running a Q
--  computation in the IO monad, usually just to
--  print the result.  There is no interesting
--  type environment, so reification isn't going to
--  work.
--
-----------------------------------------------------

instance Quasi IO where
  qNewName s = do { n <- readIORef counter
                 ; writeIORef counter (n+1)
                 ; return (mkNameU s n) }

  qReport True  msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
  qReport False msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
  qLookupName _ _       = badIO "lookupName"
  qReify _              = badIO "reify"
  qReifyFixity _        = badIO "reifyFixity"
  qReifyInstances _ _   = badIO "reifyInstances"
  qReifyRoles _         = badIO "reifyRoles"
  qReifyAnnotations _   = badIO "reifyAnnotations"
  qReifyModule _        = badIO "reifyModule"
  qReifyConStrictness _ = badIO "reifyConStrictness"
  qLocation             = badIO "currentLocation"
  qRecover _ _          = badIO "recover" -- Maybe we could fix this?
  qAddDependentFile _   = badIO "addDependentFile"
  qAddTopDecls _        = badIO "addTopDecls"
  qAddModFinalizer _    = badIO "addModFinalizer"
  qGetQ                 = badIO "getQ"
  qPutQ _               = badIO "putQ"
  qIsExtEnabled _       = badIO "isExtEnabled"
  qExtsEnabled          = badIO "extsEnabled"
135 136

  qRunIO m = m
Jan Stolarek's avatar
Jan Stolarek committed
137

138
badIO :: String -> IO a
139 140
badIO op = do   { qReport True ("Can't do `" ++ op ++ "' in the IO monad")
                ; fail "Template Haskell failure" }
141 142 143 144 145 146 147 148 149

-- Global variable to generate unique symbols
counter :: IORef Int
{-# NOINLINE counter #-}
counter = unsafePerformIO (newIORef 0)


-----------------------------------------------------
--
150
--              The Q monad
151 152 153 154 155
--
-----------------------------------------------------

newtype Q a = Q { unQ :: forall m. Quasi m => m a }

156 157 158 159 160
-- \"Runs\" the 'Q' monad. Normal users of Template Haskell
-- should not need this function, as the splice brackets @$( ... )@
-- are the usual way of running a 'Q' computation.
--
-- This function is primarily used in GHC internals, and for debugging
Jan Stolarek's avatar
Jan Stolarek committed
161
-- splices by running them in 'IO'.
162 163 164 165 166
--
-- Note that many functions in 'Q', such as 'reify' and other compiler
-- queries, are not supported when running 'Q' in 'IO'; these operations
-- simply fail at runtime. Indeed, the only operations guaranteed to succeed
-- are 'newName', 'runIO', 'reportError' and 'reportWarning'.
167 168 169 170 171
runQ :: Quasi m => Q a -> m a
runQ (Q m) = m

instance Monad Q where
  Q m >>= k  = Q (m >>= \x -> unQ (k x))
172
  (>>) = (*>)
173
  return     = pure
174
  fail s     = report True s >> Q (fail "Q monad failure")
175

176 177 178
instance Functor Q where
  fmap f (Q x) = Q (fmap f x)

Jan Stolarek's avatar
Jan Stolarek committed
179 180 181
instance Applicative Q where
  pure x = Q (pure x)
  Q f <*> Q x = Q (f <*> x)
182
  Q m *> Q n = Q (m *> n)
183

gmainland's avatar
gmainland committed
184 185
-----------------------------------------------------
--
186
--              The TExp type
gmainland's avatar
gmainland committed
187 188 189
--
-----------------------------------------------------

190
type role TExp nominal   -- See Note [Role of TExp]
191 192 193 194 195 196 197 198 199
newtype TExp a = TExp { unType :: Exp }

unTypeQ :: Q (TExp a) -> Q Exp
unTypeQ m = do { TExp e <- m
               ; return e }

unsafeTExpCoerce :: Q Exp -> Q (TExp a)
unsafeTExpCoerce m = do { e <- m
                        ; return (TExp e) }
gmainland's avatar
gmainland committed
200

201 202 203 204 205 206 207 208 209 210 211 212 213
{- Note [Role of TExp]
~~~~~~~~~~~~~~~~~~~~~~
TExp's argument must have a nominal role, not phantom as would
be inferred (Trac #8459).  Consider

  e :: TExp Age
  e = MkAge 3

  foo = $(coerce e) + 4::Int

The splice will evaluate to (MkAge 3) and you can't add that to
4::Int. So you can't coerce a (TExp Age) to a (TExp Int). -}

214 215
----------------------------------------------------
-- Packaged versions for the programmer, hiding the Quasi-ness
216

Jan Stolarek's avatar
Jan Stolarek committed
217 218
{- |
Generate a fresh name, which cannot be captured.
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

For example, this:

@f = $(do
  nm1 <- newName \"x\"
  let nm2 = 'mkName' \"x\"
  return ('LamE' ['VarP' nm1] (LamE [VarP nm2] ('VarE' nm1)))
 )@

will produce the splice

>f = \x0 -> \x -> x0

In particular, the occurrence @VarE nm1@ refers to the binding @VarP nm1@,
and is not captured by the binding @VarP nm2@.

Although names generated by @newName@ cannot /be captured/, they can
/capture/ other names. For example, this:

>g = $(do
>  nm1 <- newName "x"
>  let nm2 = mkName "x"
>  return (LamE [VarP nm2] (LamE [VarP nm1] (VarE nm2)))
> )

will produce the splice

>g = \x -> \x0 -> x0

since the occurrence @VarE nm2@ is captured by the innermost binding
of @x@, namely @VarP nm1@.
-}
251 252 253
newName :: String -> Q Name
newName s = Q (qNewName s)

Jan Stolarek's avatar
Jan Stolarek committed
254
-- | Report an error (True) or warning (False),
255
-- but carry on; use 'fail' to stop.
256 257
report  :: Bool -> String -> Q ()
report b s = Q (qReport b s)
258
{-# DEPRECATED report "Use reportError or reportWarning instead" #-} -- deprecated in 7.6
259 260 261 262 263 264 265 266

-- | Report an error to the user, but allow the current splice's computation to carry on. To abort the computation, use 'fail'.
reportError :: String -> Q ()
reportError = report True

-- | Report a warning to the user, and carry on.
reportWarning :: String -> Q ()
reportWarning = report False
267

268 269 270
-- | Recover from errors raised by 'reportError' or 'fail'.
recover :: Q a -- ^ handler to invoke on failure
        -> Q a -- ^ computation to run
aavogt's avatar
aavogt committed
271
        -> Q a
272 273
recover (Q r) (Q m) = Q (qRecover r m)

274 275 276 277 278
-- We don't export lookupName; the Bool isn't a great API
-- Instead we export lookupTypeName, lookupValueName
lookupName :: Bool -> String -> Q (Maybe Name)
lookupName ns s = Q (qLookupName ns s)

279 280
-- | Look up the given name in the (type namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
lookupTypeName :: String -> Q (Maybe Name)
281
lookupTypeName  s = Q (qLookupName True s)
282 283 284

-- | Look up the given name in the (value namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
lookupValueName :: String -> Q (Maybe Name)
285 286
lookupValueName s = Q (qLookupName False s)

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
{-
Note [Name lookup]
~~~~~~~~~~~~~~~~~~
-}
{- $namelookup #namelookup#
The functions 'lookupTypeName' and 'lookupValueName' provide
a way to query the current splice's context for what names
are in scope. The function 'lookupTypeName' queries the type
namespace, whereas 'lookupValueName' queries the value namespace,
but the functions are otherwise identical.

A call @lookupValueName s@ will check if there is a value
with name @s@ in scope at the current splice's location. If
there is, the @Name@ of this value is returned;
if not, then @Nothing@ is returned.

Jan Stolarek's avatar
Jan Stolarek committed
303
The returned name cannot be \"captured\".
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
For example:

> f = "global"
> g = $( do
>          Just nm <- lookupValueName "f"
>          [| let f = "local" in $( varE nm ) |]

In this case, @g = \"global\"@; the call to @lookupValueName@
returned the global @f@, and this name was /not/ captured by
the local definition of @f@.

The lookup is performed in the context of the /top-level/ splice
being run. For example:

> f = "global"
Jan Stolarek's avatar
Jan Stolarek committed
319
> g = $( [| let f = "local" in
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
>            $(do
>                Just nm <- lookupValueName "f"
>                varE nm
>             ) |] )

Again in this example, @g = \"global\"@, because the call to
@lookupValueName@ queries the context of the outer-most @$(...)@.

Operators should be queried without any surrounding parentheses, like so:

> lookupValueName "+"

Qualified names are also supported, like so:

> lookupValueName "Prelude.+"
> lookupValueName "Prelude.map"

-}


{- | 'reify' looks up information about the 'Name'.

It is sometimes useful to construct the argument name using 'lookupTypeName' or 'lookupValueName'
to ensure that we are reifying from the right namespace. For instance, in this context:

> data D = D

which @D@ does @reify (mkName \"D\")@ return information about? (Answer: @D@-the-type, but don't rely on it.)
To ensure we get information about @D@-the-value, use 'lookupValueName':

> do
>   Just nm <- lookupValueName "D"
>   reify nm

and to get information about @D@-the-type, use 'lookupTypeName'.
-}
356 357 358
reify :: Name -> Q Info
reify v = Q (qReify v)

Ryan Scott's avatar
Ryan Scott committed
359 360 361 362 363 364
{- | @reifyFixity nm@ returns the fixity of @nm@. If a fixity value cannot be
found, 'defaultFixity' is returned.
-}
reifyFixity :: Name -> Q Fixity
reifyFixity nm = Q (qReifyFixity nm)

Jan Stolarek's avatar
Jan Stolarek committed
365
{- | @reifyInstances nm tys@ returns a list of visible instances of @nm tys@. That is,
366 367 368 369 370
if @nm@ is the name of a type class, then all instances of this class at the types @tys@
are returned. Alternatively, if @nm@ is the name of a data family or type family,
all instances of this family at the types @tys@ are returned.
-}
reifyInstances :: Name -> [Type] -> Q [InstanceDec]
371
reifyInstances cls tys = Q (qReifyInstances cls tys)
372

373 374 375 376 377 378 379
{- | @reifyRoles nm@ returns the list of roles associated with the parameters of
the tycon @nm@. Fails if @nm@ cannot be found or is not a tycon.
The returned list should never contain 'InferR'.
-}
reifyRoles :: Name -> Q [Role]
reifyRoles nm = Q (qReifyRoles nm)

Austin Seipp's avatar
Austin Seipp committed
380 381 382 383 384 385 386
-- | @reifyAnnotations target@ returns the list of annotations
-- associated with @target@.  Only the annotations that are
-- appropriately typed is returned.  So if you have @Int@ and @String@
-- annotations for the same target, you have to call this function twice.
reifyAnnotations :: Data a => AnnLookup -> Q [a]
reifyAnnotations an = Q (qReifyAnnotations an)

387 388 389 390 391 392
-- | @reifyModule mod@ looks up information about module @mod@.  To
-- look up the current module, call this function with the return
-- value of @thisModule@.
reifyModule :: Module -> Q ModuleInfo
reifyModule m = Q (qReifyModule m)

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
-- | @reifyConStrictness nm@ looks up the strictness information for the fields
-- of the constructor with the name @nm@. Note that the strictness information
-- that 'reifyConStrictness' returns may not correspond to what is written in
-- the source code. For example, in the following data declaration:
--
-- @
-- data Pair a = Pair a a
-- @
--
-- 'reifyConStrictness' would return @['DecidedLazy', DecidedLazy]@ under most
-- circumstances, but it would return @['DecidedStrict', DecidedStrict]@ if the
-- @-XStrictData@ language extension was enabled.
reifyConStrictness :: Name -> Q [DecidedStrictness]
reifyConStrictness n = Q (qReifyConStrictness n)

408
-- | Is the list of instances returned by 'reifyInstances' nonempty?
409 410 411
isInstance :: Name -> [Type] -> Q Bool
isInstance nm tys = do { decs <- reifyInstances nm tys
                       ; return (not (null decs)) }
412

413
-- | The location at which this computation is spliced.
414 415
location :: Q Loc
location = Q qLocation
416

dons's avatar
dons committed
417
-- |The 'runIO' function lets you run an I\/O computation in the 'Q' monad.
Jan Stolarek's avatar
Jan Stolarek committed
418 419
-- Take care: you are guaranteed the ordering of calls to 'runIO' within
-- a single 'Q' computation, but not about the order in which splices are run.
420
--
Jan Stolarek's avatar
Jan Stolarek committed
421
-- Note: for various murky reasons, stdout and stderr handles are not
Gabor Greif's avatar
Gabor Greif committed
422
-- necessarily flushed when the compiler finishes running, so you should
423
-- flush them yourself.
424 425 426
runIO :: IO a -> Q a
runIO m = Q (qRunIO m)

GregWeber's avatar
GregWeber committed
427
-- | Record external files that runIO is using (dependent upon).
428 429 430
-- The compiler can then recognize that it should re-compile the Haskell file
-- when an external file changes.
--
GregWeber's avatar
GregWeber committed
431
-- Expects an absolute file path.
432 433 434 435 436 437
--
-- Notes:
--
--   * ghc -M does not know about these dependencies - it does not execute TH.
--
--   * The dependency is based on file content, not a modification time
GregWeber's avatar
GregWeber committed
438 439 440
addDependentFile :: FilePath -> Q ()
addDependentFile fp = Q (qAddDependentFile fp)

441 442 443 444 445
-- | Add additional top-level declarations. The added declarations will be type
-- checked along with the current declaration group.
addTopDecls :: [Dec] -> Q ()
addTopDecls ds = Q (qAddTopDecls ds)

446 447 448 449 450
-- | Add a finalizer that will run in the Q monad after the current module has
-- been type checked. This only makes sense when run within a top-level splice.
addModFinalizer :: Q () -> Q ()
addModFinalizer act = Q (qAddModFinalizer (unQ act))

451
-- | Get state from the 'Q' monad.
gmainland's avatar
gmainland committed
452 453 454
getQ :: Typeable a => Q (Maybe a)
getQ = Q qGetQ

455
-- | Replace the state in the 'Q' monad.
gmainland's avatar
gmainland committed
456 457 458
putQ :: Typeable a => a -> Q ()
putQ x = Q (qPutQ x)

459 460 461 462 463 464 465 466
-- | Determine whether the given language extension is enabled in the 'Q' monad.
isExtEnabled :: Extension -> Q Bool
isExtEnabled ext = Q (qIsExtEnabled ext)

-- | List all enabled language extensions.
extsEnabled :: Q [Extension]
extsEnabled = Q qExtsEnabled

467
instance Quasi Q where
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
  qNewName            = newName
  qReport             = report
  qRecover            = recover
  qReify              = reify
  qReifyFixity        = reifyFixity
  qReifyInstances     = reifyInstances
  qReifyRoles         = reifyRoles
  qReifyAnnotations   = reifyAnnotations
  qReifyModule        = reifyModule
  qReifyConStrictness = reifyConStrictness
  qLookupName         = lookupName
  qLocation           = location
  qRunIO              = runIO
  qAddDependentFile   = addDependentFile
  qAddTopDecls        = addTopDecls
  qAddModFinalizer    = addModFinalizer
  qGetQ               = getQ
  qPutQ               = putQ
  qIsExtEnabled       = isExtEnabled
  qExtsEnabled        = extsEnabled
488 489 490 491


----------------------------------------------------
-- The following operations are used solely in DsMeta when desugaring brackets
492
-- They are not necessary for the user, who can use ordinary return and (>>=) etc
493 494 495 496 497 498 499 500 501 502 503 504 505

returnQ :: a -> Q a
returnQ = return

bindQ :: Q a -> (a -> Q b) -> Q b
bindQ = (>>=)

sequenceQ :: [Q a] -> Q [a]
sequenceQ = sequence


-----------------------------------------------------
--
506
--              The Lift class
507 508 509
--
-----------------------------------------------------

Ryan Scott's avatar
Ryan Scott committed
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
-- | A 'Lift' instance can have any of its values turned into a Template
-- Haskell expression. This is needed when a value used within a Template
-- Haskell quotation is bound outside the Oxford brackets (@[| ... |]@) but not
-- at the top level. As an example:
--
-- > add1 :: Int -> Q Exp
-- > add1 x = [| x + 1 |]
--
-- Template Haskell has no way of knowing what value @x@ will take on at
-- splice-time, so it requires the type of @x@ to be an instance of 'Lift'.
--
-- 'Lift' instances can be derived automatically by use of the @-XDeriveLift@
-- GHC language extension:
--
-- > {-# LANGUAGE DeriveLift #-}
-- > module Foo where
-- >
-- > import Language.Haskell.TH.Syntax
-- >
-- > data Bar a = Bar1 a (Bar a) | Bar2 String
-- >   deriving Lift
531
class Lift t where
Ryan Scott's avatar
Ryan Scott committed
532 533
  -- | Turn a value into a Template Haskell expression, suitable for use in
  -- a splice.
534
  lift :: t -> Q Exp
535 536
  default lift :: Data t => t -> Q Exp
  lift = liftData
Jan Stolarek's avatar
Jan Stolarek committed
537

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
538
-- If you add any instances here, consider updating test th/TH_Lift
539 540 541 542
instance Lift Integer where
  lift x = return (LitE (IntegerL x))

instance Lift Int where
543 544
  lift x = return (LitE (IntegerL (fromIntegral x)))

545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
instance Lift Int8 where
  lift x = return (LitE (IntegerL (fromIntegral x)))

instance Lift Int16 where
  lift x = return (LitE (IntegerL (fromIntegral x)))

instance Lift Int32 where
  lift x = return (LitE (IntegerL (fromIntegral x)))

instance Lift Int64 where
  lift x = return (LitE (IntegerL (fromIntegral x)))

instance Lift Word where
  lift x = return (LitE (IntegerL (fromIntegral x)))

instance Lift Word8 where
  lift x = return (LitE (IntegerL (fromIntegral x)))

instance Lift Word16 where
  lift x = return (LitE (IntegerL (fromIntegral x)))

instance Lift Word32 where
  lift x = return (LitE (IntegerL (fromIntegral x)))

instance Lift Word64 where
  lift x = return (LitE (IntegerL (fromIntegral x)))
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
571

572
#ifdef HAS_NATURAL
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
573 574
instance Lift Natural where
  lift x = return (LitE (IntegerL (fromIntegral x)))
575
#endif
576 577 578 579 580 581 582 583 584

instance Integral a => Lift (Ratio a) where
  lift x = return (LitE (RationalL (toRational x)))

instance Lift Float where
  lift x = return (LitE (RationalL (toRational x)))

instance Lift Double where
  lift x = return (LitE (RationalL (toRational x)))
585 586 587 588 589 590 591 592

instance Lift Char where
  lift x = return (LitE (CharL x))

instance Lift Bool where
  lift True  = return (ConE trueName)
  lift False = return (ConE falseName)

593 594 595 596 597 598 599 600
instance Lift a => Lift (Maybe a) where
  lift Nothing  = return (ConE nothingName)
  lift (Just x) = liftM (ConE justName `AppE`) (lift x)

instance (Lift a, Lift b) => Lift (Either a b) where
  lift (Left x)  = liftM (ConE leftName  `AppE`) (lift x)
  lift (Right y) = liftM (ConE rightName `AppE`) (lift y)

601 602 603
instance Lift a => Lift [a] where
  lift xs = do { xs' <- mapM lift xs; return (ListE xs') }

604 605 606 607
liftString :: String -> Q Exp
-- Used in TcExpr to short-circuit the lifting for strings
liftString s = return (LitE (StringL s))

608 609 610
instance Lift () where
  lift () = return (ConE (tupleDataName 0))

611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
instance (Lift a, Lift b) => Lift (a, b) where
  lift (a, b)
    = liftM TupE $ sequence [lift a, lift b]

instance (Lift a, Lift b, Lift c) => Lift (a, b, c) where
  lift (a, b, c)
    = liftM TupE $ sequence [lift a, lift b, lift c]

instance (Lift a, Lift b, Lift c, Lift d) => Lift (a, b, c, d) where
  lift (a, b, c, d)
    = liftM TupE $ sequence [lift a, lift b, lift c, lift d]

instance (Lift a, Lift b, Lift c, Lift d, Lift e)
      => Lift (a, b, c, d, e) where
  lift (a, b, c, d, e)
    = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e]

instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f)
      => Lift (a, b, c, d, e, f) where
  lift (a, b, c, d, e, f)
    = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f]

instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f, Lift g)
      => Lift (a, b, c, d, e, f, g) where
  lift (a, b, c, d, e, f, g)
    = liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f, lift g]

638 639 640 641
-- TH has a special form for literal strings,
-- which we should take advantage of.
-- NB: the lhs of the rule has no args, so that
--     the rule will apply to a 'lift' all on its own
Jan Stolarek's avatar
Jan Stolarek committed
642
--     which happens to be the way the type checker
643 644 645 646 647
--     creates it.
{-# RULES "TH:liftString" lift = \s -> return (LitE (StringL s)) #-}


trueName, falseName :: Name
Ian Lynagh's avatar
Ian Lynagh committed
648 649
trueName  = mkNameG DataName "ghc-prim" "GHC.Types" "True"
falseName = mkNameG DataName "ghc-prim" "GHC.Types" "False"
650

651
nothingName, justName :: Name
652 653
nothingName = mkNameG DataName "base" "GHC.Base" "Nothing"
justName    = mkNameG DataName "base" "GHC.Base" "Just"
654 655 656 657 658

leftName, rightName :: Name
leftName  = mkNameG DataName "base" "Data.Either" "Left"
rightName = mkNameG DataName "base" "Data.Either" "Right"

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
-----------------------------------------------------
--
--              Generic Lift implementations
--
-----------------------------------------------------

-- | 'dataToQa' is an internal utility function for constructing generic
-- conversion functions from types with 'Data' instances to various
-- quasi-quoting representations.  See the source of 'dataToExpQ' and
-- 'dataToPatQ' for two example usages: @mkCon@, @mkLit@
-- and @appQ@ are overloadable to account for different syntax for
-- expressions and patterns; @antiQ@ allows you to override type-specific
-- cases, a common usage is just @const Nothing@, which results in
-- no overloading.
dataToQa  ::  forall a k q. Data a
          =>  (Name -> k)
          ->  (Lit -> Q q)
          ->  (k -> [Q q] -> Q q)
          ->  (forall b . Data b => b -> Maybe (Q q))
          ->  a
          ->  Q q
dataToQa mkCon mkLit appCon antiQ t =
    case antiQ t of
      Nothing ->
          case constrRep constr of
            AlgConstr _ ->
685
                appCon (mkCon funOrConName) conArgs
686
              where
687 688
                funOrConName :: Name
                funOrConName =
689 690 691 692 693 694 695 696 697 698 699 700 701
                    case showConstr constr of
                      "(:)"       -> Name (mkOccName ":")
                                          (NameG DataName
                                                (mkPkgName "ghc-prim")
                                                (mkModName "GHC.Types"))
                      con@"[]"    -> Name (mkOccName con)
                                          (NameG DataName
                                                (mkPkgName "ghc-prim")
                                                (mkModName "GHC.Types"))
                      con@('(':_) -> Name (mkOccName con)
                                          (NameG DataName
                                                (mkPkgName "ghc-prim")
                                                (mkModName "GHC.Tuple"))
702 703 704 705 706 707 708 709 710
                      -- It is possible for a Data instance to be defined such
                      -- that toConstr uses a Constr defined using a function,
                      -- not a data constructor. In such a case, we must take
                      -- care to build the Name using mkNameG_v (for values),
                      -- not mkNameG_d (for data constructors).
                      -- See Trac #10796.
                      fun@(x:_)   | startsVarSym x || startsVarId x
                                  -> mkNameG_v tyconPkg tyconMod fun
                      con         -> mkNameG_d tyconPkg tyconMod con
711 712 713 714
                  where
                    tycon :: TyCon
                    tycon = (typeRepTyCon . typeOf) t

715 716 717 718
                    tyconPkg, tyconMod :: String
                    tyconPkg = tyConPackage tycon
                    tyconMod = tyConModule  tycon

719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
                conArgs :: [Q q]
                conArgs = gmapQ (dataToQa mkCon mkLit appCon antiQ) t
            IntConstr n ->
                mkLit $ IntegerL n
            FloatConstr n ->
                mkLit $ RationalL n
            CharConstr c ->
                mkLit $ CharL c
        where
          constr :: Constr
          constr = toConstr t

      Just y -> y

-- | 'dataToExpQ' converts a value to a 'Q Exp' representation of the
-- same value, in the SYB style. It is generalized to take a function
-- override type-specific cases; see 'liftData' for a more commonly
-- used variant.
dataToExpQ  ::  Data a
            =>  (forall b . Data b => b -> Maybe (Q Exp))
            ->  a
            ->  Q Exp
741 742 743 744 745 746 747 748 749 750 751
dataToExpQ = dataToQa varOrConE litE (foldl appE)
    where
          -- Make sure that VarE is used if the Constr value relies on a
          -- function underneath the surface (instead of a constructor).
          -- See Trac #10796.
          varOrConE s =
            case nameSpace s of
                 Just VarName  -> return (VarE s)
                 Just DataName -> return (ConE s)
                 _ -> fail $ "Can't construct an expression from name "
                          ++ showName s
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
          appE x y = do { a <- x; b <- y; return (AppE a b)}
          litE c = return (LitE c)

-- | 'liftData' is a variant of 'lift' in the 'Lift' type class which
-- works for any type with a 'Data' instance.
liftData :: Data a => a -> Q Exp
liftData = dataToExpQ (const Nothing)

-- | 'dataToPatQ' converts a value to a 'Q Pat' representation of the same
-- value, in the SYB style. It takes a function to handle type-specific cases,
-- alternatively, pass @const Nothing@ to get default behavior.
dataToPatQ  ::  Data a
            =>  (forall b . Data b => b -> Maybe (Q Pat))
            ->  a
            ->  Q Pat
dataToPatQ = dataToQa id litP conP
    where litP l = return (LitP l)
769 770 771 772 773 774 775
          conP n ps =
            case nameSpace n of
                Just DataName -> do
                    ps' <- sequence ps
                    return (ConP n ps')
                _ -> fail $ "Can't construct a pattern from name "
                         ++ showName n
776 777

-----------------------------------------------------
778
--              Names and uniques
779 780
-----------------------------------------------------

781
newtype ModName = ModName String        -- Module name
782
 deriving (Show,Eq,Ord,Typeable,Data,Generic)
783

784
newtype PkgName = PkgName String        -- package name
785
 deriving (Show,Eq,Ord,Typeable,Data,Generic)
786

787 788
-- | Obtained from 'reifyModule' and 'thisModule'.
data Module = Module PkgName ModName -- package qualified module name
789
 deriving (Show,Eq,Ord,Typeable,Data,Generic)
790

791
newtype OccName = OccName String
792
 deriving (Show,Eq,Ord,Typeable,Data,Generic)
793

794
mkModName :: String -> ModName
795
mkModName s = ModName s
796 797

modString :: ModName -> String
798
modString (ModName m) = m
799

800 801

mkPkgName :: String -> PkgName
802
mkPkgName s = PkgName s
803 804

pkgString :: PkgName -> String
805
pkgString (PkgName m) = m
806 807


808
-----------------------------------------------------
809
--              OccName
810 811 812
-----------------------------------------------------

mkOccName :: String -> OccName
813
mkOccName s = OccName s
814 815

occString :: OccName -> String
816
occString (OccName occ) = occ
817 818 819


-----------------------------------------------------
820
--               Names
821
-----------------------------------------------------
Jan Stolarek's avatar
Jan Stolarek committed
822
--
aavogt's avatar
aavogt committed
823
-- For "global" names ('NameG') we need a totally unique name,
824 825
-- so we must include the name-space of the thing
--
aavogt's avatar
aavogt committed
826
-- For unique-numbered things ('NameU'), we've got a unique reference
827 828
-- anyway, so no need for name space
--
aavogt's avatar
aavogt committed
829
-- For dynamically bound thing ('NameS') we probably want them to
830 831
-- in a context-dependent way, so again we don't want the name
-- space.  For example:
aavogt's avatar
aavogt committed
832 833 834
--
-- > let v = mkName "T" in [| data $v = $v |]
--
835
-- Here we use the same Name for both type constructor and data constructor
aavogt's avatar
aavogt committed
836 837 838 839 840 841 842 843 844 845
--
--
-- NameL and NameG are bound *outside* the TH syntax tree
-- either globally (NameG) or locally (NameL). Ex:
--
-- > f x = $(h [| (map, x) |])
--
-- The 'map' will be a NameG, and 'x' wil be a NameL
--
-- These Names should never appear in a binding position in a TH syntax tree
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870

{- $namecapture #namecapture#
Much of 'Name' API is concerned with the problem of /name capture/, which
can be seen in the following example.

> f expr = [| let x = 0 in $expr |]
> ...
> g x = $( f [| x |] )
> h y = $( f [| y |] )

A naive desugaring of this would yield:

> g x = let x = 0 in x
> h y = let x = 0 in y

All of a sudden, @g@ and @h@ have different meanings! In this case,
we say that the @x@ in the RHS of @g@ has been /captured/
by the binding of @x@ in @f@.

What we actually want is for the @x@ in @f@ to be distinct from the
@x@ in @g@, so we get the following desugaring:

> g x = let x' = 0 in x
> h y = let x' = 0 in y

Jan Stolarek's avatar
Jan Stolarek committed
871
which avoids name capture as desired.
872 873 874 875 876 877 878 879 880 881 882 883

In the general case, we say that a @Name@ can be captured if
the thing it refers to can be changed by adding new declarations.
-}

{- |
An abstract type representing names in the syntax tree.

'Name's can be constructed in several ways, which come with different
name-capture guarantees (see "Language.Haskell.TH.Syntax#namecapture" for
an explanation of name capture):

Jan Stolarek's avatar
Jan Stolarek committed
884 885
  * the built-in syntax @'f@ and @''T@ can be used to construct names,
    The expression @'f@ gives a @Name@ which refers to the value @f@
886 887
    currently in scope, and @''T@ gives a @Name@ which refers to the
    type @T@ currently in scope. These names can never be captured.
Jan Stolarek's avatar
Jan Stolarek committed
888 889

  * 'lookupValueName' and 'lookupTypeName' are similar to @'f@ and
890 891 892 893 894 895
     @''T@ respectively, but the @Name@s are looked up at the point
     where the current splice is being run. These names can never be
     captured.

  * 'newName' monadically generates a new name, which can never
     be captured.
Jan Stolarek's avatar
Jan Stolarek committed
896

897 898 899 900 901 902
  * 'mkName' generates a capturable name.

Names constructed using @newName@ and @mkName@ may be used in bindings
(such as @let x = ...@ or @\x -> ...@), but names constructed using
@lookupValueName@, @lookupTypeName@, @'f@, @''T@ may not.
-}
903
data Name = Name OccName NameFlavour deriving (Typeable, Data, Eq, Generic)
904 905 906 907 908

instance Ord Name where
    -- check if unique is different before looking at strings
  (Name o1 f1) `compare` (Name o2 f2) = (f1 `compare` f2)   `thenCmp`
                                        (o1 `compare` o2)
909 910

data NameFlavour
aavogt's avatar
aavogt committed
911 912
  = NameS           -- ^ An unqualified name; dynamically bound
  | NameQ ModName   -- ^ A qualified name; dynamically bound
913 914
  | NameU !Int      -- ^ A unique local name
  | NameL !Int      -- ^ Local name bound outside of the TH AST
aavogt's avatar
aavogt committed
915 916
  | NameG NameSpace PkgName ModName -- ^ Global name bound outside of the TH AST:
                -- An original name (occurrences only, not binders)
917 918
                -- Need the namespace too to be sure which
                -- thing we are naming
919
  deriving ( Typeable, Data, Eq, Ord, Show, Generic )
920

921 922 923 924
data NameSpace = VarName        -- ^ Variables
               | DataName       -- ^ Data constructors
               | TcClsName      -- ^ Type constructors and classes; Haskell has them
                                -- in the same name space for now.
925
               deriving( Eq, Ord, Show, Data, Typeable, Generic )
926 927 928

type Uniq = Int

929 930 931 932 933 934 935 936 937 938
-- | The name without its module prefix.
--
-- ==== __Examples__
--
-- >>> nameBase ''Data.Either.Either
-- "Either"
-- >>> nameBase (mkName "foo")
-- "foo"
-- >>> nameBase (mkName "Module.foo")
-- "foo"
939 940 941
nameBase :: Name -> String
nameBase (Name occ _) = occString occ

942 943 944 945
-- | Module prefix of a name, if it exists.
--
-- ==== __Examples__
--
946
-- >>> nameModule ''Data.Either.Either
947 948 949 950 951
-- Just "Data.Either"
-- >>> nameModule (mkName "foo")
-- Nothing
-- >>> nameModule (mkName "Module.foo")
-- Just "Module"
952
nameModule :: Name -> Maybe String
Ian Lynagh's avatar
Ian Lynagh committed
953
nameModule (Name _ (NameQ m))     = Just (modString m)
954
nameModule (Name _ (NameG _ _ m)) = Just (modString m)
Ian Lynagh's avatar
Ian Lynagh committed
955
nameModule _                      = Nothing
956

957 958 959 960
-- | A name's package, if it exists.
--
-- ==== __Examples__
--
961
-- >>> namePackage ''Data.Either.Either
962 963 964 965 966 967 968 969 970
-- Just "base"
-- >>> namePackage (mkName "foo")
-- Nothing
-- >>> namePackage (mkName "Module.foo")
-- Nothing
namePackage :: Name -> Maybe String
namePackage (Name _ (NameG _ p _)) = Just (pkgString p)
namePackage _                      = Nothing

971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
-- | Returns whether a name represents an occurrence of a top-level variable
-- ('VarName'), data constructor ('DataName'), type constructor, or type class
-- ('TcClsName'). If we can't be sure, it returns 'Nothing'.
--
-- ==== __Examples__
--
-- >>> nameSpace 'Prelude.id
-- Just VarName
-- >>> nameSpace (mkName "id")
-- Nothing -- only works for top-level variable names
-- >>> nameSpace 'Data.Maybe.Just
-- Just DataName
-- >>> nameSpace ''Data.Maybe.Maybe
-- Just TcClsName
-- >>> nameSpace ''Data.Ord.Ord
-- Just TcClsName
nameSpace :: Name -> Maybe NameSpace
nameSpace (Name _ (NameG ns _ _)) = Just ns
nameSpace _                       = Nothing

Jan Stolarek's avatar
Jan Stolarek committed
991
{- |
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
Generate a capturable name. Occurrences of such names will be
resolved according to the Haskell scoping rules at the occurrence
site.

For example:

> f = [| pi + $(varE (mkName "pi")) |]
> ...
> g = let pi = 3 in $f

In this case, @g@ is desugared to

> g = Prelude.pi + 3

Note that @mkName@ may be used with qualified names:

> mkName "Prelude.pi"

See also 'Language.Haskell.TH.Lib.dyn' for a useful combinator. The above example could
be rewritten using 'dyn' as

> f = [| pi + $(dyn "pi") |]
-}
1015
mkName :: String -> Name
1016
-- The string can have a '.', thus "Foo.baz",
1017 1018 1019 1020 1021
-- giving a dynamically-bound qualified name,
-- in which case we want to generate a NameQ
--
-- Parse the string to see if it has a "." in it
-- so we know whether to generate a qualified or unqualified name
Jan Stolarek's avatar
Jan Stolarek committed
1022
-- It's a bit tricky because we need to parse
aavogt's avatar
aavogt committed
1023 1024 1025
--
-- > Foo.Baz.x   as    Qual Foo.Baz x
--
1026 1027 1028 1029 1030
-- So we parse it from back to front
mkName str
  = split [] (reverse str)
  where
    split occ []        = Name (mkOccName occ) NameS
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    split occ ('.':rev) | not (null occ)
                        , is_rev_mod_name rev
                        = Name (mkOccName occ) (NameQ (mkModName (reverse rev)))
        -- The 'not (null occ)' guard ensures that
        --      mkName "&." = Name "&." NameS
        -- The 'is_rev_mod' guards ensure that
        --      mkName ".&" = Name ".&" NameS
        --      mkName "^.." = Name "^.." NameS      -- Trac #8633
        --      mkName "Data.Bits..&" = Name ".&" (NameQ "Data.Bits")
        -- This rather bizarre case actually happened; (.&.) is in Data.Bits
1041
    split occ (c:rev)   = split (c:occ) rev
1042

1043 1044
    -- Recognises a reversed module name xA.yB.C,
    -- with at least one component,
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
    -- and each component looks like a module name
    --   (i.e. non-empty, starts with capital, all alpha)
    is_rev_mod_name rev_mod_str
      | (compt, rest) <- break (== '.') rev_mod_str
      , not (null compt), isUpper (last compt), all is_mod_char compt
      = case rest of
          []             -> True
          (_dot : rest') -> is_rev_mod_name rest'
      | otherwise
      = False

    is_mod_char c = isAlphaNum c || c == '_' || c == '\''

aavogt's avatar
aavogt committed
1058 1059
-- | Only used internally
mkNameU :: String -> Uniq -> Name
1060
mkNameU s u = Name (mkOccName s) (NameU u)
1061

aavogt's avatar
aavogt committed
1062 1063
-- | Only used internally
mkNameL :: String -> Uniq -> Name
1064
mkNameL s u = Name (mkOccName s) (NameL u)
1065

aavogt's avatar
aavogt committed
1066 1067 1068
-- | Used for 'x etc, but not available to the programmer
mkNameG :: NameSpace -> String -> String -> String -> Name
mkNameG ns pkg modu occ
Ian Lynagh's avatar
Ian Lynagh committed
1069
  = Name (mkOccName occ) (NameG ns (mkPkgName pkg) (mkModName modu))
1070

1071 1072 1073
mkNameS :: String -> Name
mkNameS n = Name (mkOccName n) NameS

1074
mkNameG_v, mkNameG_tc, mkNameG_d :: String -> String -> String -> Name
1075 1076 1077 1078
mkNameG_v  = mkNameG VarName
mkNameG_tc = mkNameG TcClsName
mkNameG_d  = mkNameG DataName

Ian Lynagh's avatar
Ian Lynagh committed
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
data NameIs = Alone | Applied | Infix

showName :: Name -> String
showName = showName' Alone

showName' :: NameIs -> Name -> String
showName' ni nm
 = case ni of
       Alone        -> nms
       Applied
        | pnam      -> nms
        | otherwise -> "(" ++ nms ++ ")"
       Infix
        | pnam      -> "`" ++ nms ++ "`"
        | otherwise -> nms
1094
    where
1095 1096 1097 1098 1099 1100
        -- For now, we make the NameQ and NameG print the same, even though
        -- NameQ is a qualified name (so what it means depends on what the
        -- current scope is), and NameG is an original name (so its meaning
        -- should be independent of what's in scope.
        -- We may well want to distinguish them in the end.
        -- Ditto NameU and NameL
1101
        nms = case nm of
Ian Lynagh's avatar
Ian Lynagh committed
1102 1103 1104
                    Name occ NameS         -> occString occ
                    Name occ (NameQ m)     -> modString m ++ "." ++ occString occ
                    Name occ (NameG _ _ m) -> modString m ++ "." ++ occString occ
1105 1106
                    Name occ (NameU u)     -> occString occ ++ "_" ++ show u
                    Name occ (NameL u)     -> occString occ ++ "_" ++ show u
1107 1108 1109

        pnam = classify nms

Ian Lynagh's avatar
Ian Lynagh committed
1110 1111
        -- True if we are function style, e.g. f, [], (,)
        -- False if we are operator style, e.g. +, :+
1112
        classify "" = False -- shouldn't happen; . operator is handled below
Ian Lynagh's avatar
Ian Lynagh committed
1113
        classify (x:xs) | isAlpha x || (x `elem` "_[]()") =
1114 1115 1116 1117
                            case dropWhile (/='.') xs of
                                  (_:xs') -> classify xs'
                                  []      -> True
                        | otherwise = False
1118

1119
instance Show Name where
Ian Lynagh's avatar
Ian Lynagh committed
1120
  show = showName
1121

1122
-- Tuple data and type constructors
1123 1124 1125 1126
-- | Tuple data constructor
tupleDataName :: Int -> Name
-- | Tuple type constructor
tupleTypeName :: Int -> Name
1127

1128
tupleDataName 0 = mk_tup_name 0 DataName
1129
tupleDataName 1 = error "tupleDataName 1"
1130
tupleDataName n = mk_tup_name (n-1) DataName
1131

1132
tupleTypeName 0 = mk_tup_name 0 TcClsName
1133
tupleTypeName 1 = error "tupleTypeName 1"
1134
tupleTypeName n = mk_tup_name (n-1) TcClsName
1135

Ian Lynagh's avatar
Ian Lynagh committed
1136
mk_tup_name :: Int -> NameSpace -> Name
1137
mk_tup_name n_commas space
Ian Lynagh's avatar
Ian Lynagh committed
1138
  = Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
1139 1140
  where
    occ = mkOccName ('(' : replicate n_commas ',' ++ ")")
Ian Lynagh's avatar
Ian Lynagh committed
1141
    tup_mod = mkModName "GHC.Tuple"
1142

1143
-- Unboxed tuple data and type constructors