HsExpr.hs 89.4 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2 3 4 5
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}

6
{-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-}
7 8 9 10 11
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
                                      -- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
12
{-# LANGUAGE ExistentialQuantification #-}
13
{-# LANGUAGE DeriveFunctor #-}
14 15

-- | Abstract Haskell syntax for expressions.
16 17
module HsExpr where

18
#include "HsVersions.h"
19 20

-- friends:
21 22 23
import HsDecls
import HsPat
import HsLit
24 25
import PlaceHolder ( PostTc,PostRn,DataId,DataIdPost,
                     NameOrRdrName,OutputableBndrId )
26 27
import HsTypes
import HsBinds
28 29

-- others:
30
import TcEvidence
31
import CoreSyn
32
import Var
33
import DynFlags ( gopt, GeneralFlag(Opt_PrintExplicitCoercions) )
34
import Name
35
import NameSet
36
import RdrName  ( GlobalRdrEnv )
37
import BasicTypes
Matthew Pickering's avatar
Matthew Pickering committed
38
import ConLike
39
import SrcLoc
40
import Util
41
import StaticFlags( opt_PprStyle_Debug )
Ian Lynagh's avatar
Ian Lynagh committed
42
import Outputable
43
import FastString
44
import Type
45 46

-- libraries:
47
import Data.Data hiding (Fixity(..))
Simon Marlow's avatar
Simon Marlow committed
48
import Data.Maybe (isNothing)
49

Austin Seipp's avatar
Austin Seipp committed
50 51 52
{-
************************************************************************
*                                                                      *
53
\subsection{Expressions proper}
Austin Seipp's avatar
Austin Seipp committed
54 55 56
*                                                                      *
************************************************************************
-}
57

58 59
-- * Expressions proper

60
type LHsExpr id = Located (HsExpr id)
Alan Zimmerman's avatar
Alan Zimmerman committed
61 62
  -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
  --   in a list
63

64 65
  -- For details on above see note [Api annotations] in ApiAnnotation

66
-------------------------
67 68
-- | PostTcExpr is an evidence expression attached to the syntax tree by the
-- type checker (c.f. postTcType).
69
type PostTcExpr  = HsExpr Id
70 71
-- | We use a PostTcTable where there are a bunch of pieces of evidence, more
-- than is convenient to keep individually.
72
type PostTcTable = [(Name, PostTcExpr)]
73 74

noPostTcExpr :: PostTcExpr
75
noPostTcExpr = HsLit (HsString "" (fsLit "noPostTcExpr"))
76 77 78 79 80

noPostTcTable :: PostTcTable
noPostTcTable = []

-------------------------
81
-- | SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier,
Ian Lynagh's avatar
Ian Lynagh committed
82
-- by the renamer.  It's used for rebindable syntax.
83 84 85
--
-- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for
--      @(>>=)@, and then instantiated by the type checker with its type args
86
--      etc
87 88 89 90 91 92 93 94 95 96 97 98 99 100
--
-- This should desugar to
--
-- > syn_res_wrap $ syn_expr (syn_arg_wraps[0] arg0)
-- >                         (syn_arg_wraps[1] arg1) ...
--
-- where the actual arguments come from elsewhere in the AST.
-- This could be defined using @PostRn@ and @PostTc@ and such, but it's
-- harder to get it all to work out that way. ('noSyntaxExpr' is hard to
-- write, for example.)
data SyntaxExpr id = SyntaxExpr { syn_expr      :: HsExpr id
                                , syn_arg_wraps :: [HsWrapper]
                                , syn_res_wrap  :: HsWrapper }
deriving instance (DataId id) => Data (SyntaxExpr id)
101

102 103 104 105
-- | This is used for rebindable-syntax pieces that are too polymorphic
-- for tcSyntaxOp (trS_fmap and the mzip in ParStmt)
noExpr :: HsExpr id
noExpr = HsLit (HsString "" (fsLit "noExpr"))
106

Ian Lynagh's avatar
Ian Lynagh committed
107 108
noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after,
                              -- (if the syntax slot makes no sense)
109 110 111 112 113 114 115 116 117 118 119 120 121
noSyntaxExpr = SyntaxExpr { syn_expr      = HsLit (HsString "" (fsLit "noSyntaxExpr"))
                          , syn_arg_wraps = []
                          , syn_res_wrap  = WpHole }

-- | Make a 'SyntaxExpr Name' (the "rn" is because this is used in the
-- renamer), missing its HsWrappers.
mkRnSyntaxExpr :: Name -> SyntaxExpr Name
mkRnSyntaxExpr name = SyntaxExpr { syn_expr      = HsVar $ noLoc name
                                 , syn_arg_wraps = []
                                 , syn_res_wrap  = WpHole }
  -- don't care about filling in syn_arg_wraps because we're clearly
  -- not past the typechecker

122
instance (OutputableBndrId id) => Outputable (SyntaxExpr id) where
123 124 125 126 127 128
  ppr (SyntaxExpr { syn_expr      = expr
                  , syn_arg_wraps = arg_wraps
                  , syn_res_wrap  = res_wrap })
    = sdocWithDynFlags $ \ dflags ->
      getPprStyle $ \s ->
      if debugStyle s || gopt Opt_PrintExplicitCoercions dflags
129 130
      then ppr expr <> braces (pprWithCommas ppr arg_wraps)
                    <> braces (ppr res_wrap)
131 132 133
      else ppr expr

type CmdSyntaxTable id = [(Name, HsExpr id)]
134
-- See Note [CmdSyntaxTable]
135

Austin Seipp's avatar
Austin Seipp committed
136
{-
137 138 139 140 141
Note [CmdSyntaxtable]
~~~~~~~~~~~~~~~~~~~~~
Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps
track of the methods needed for a Cmd.

142
* Before the renamer, this list is an empty list
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169

* After the renamer, it takes the form @[(std_name, HsVar actual_name)]@
  For example, for the 'arr' method
   * normal case:            (GHC.Control.Arrow.arr, HsVar GHC.Control.Arrow.arr)
   * with rebindable syntax: (GHC.Control.Arrow.arr, arr_22)
             where @arr_22@ is whatever 'arr' is in scope

* After the type checker, it takes the form [(std_name, <expression>)]
  where <expression> is the evidence for the method.  This evidence is
  instantiated with the class, but is still polymorphic in everything
  else.  For example, in the case of 'arr', the evidence has type
         forall b c. (b->c) -> a b c
  where 'a' is the ambient type of the arrow.  This polymorphism is
  important because the desugarer uses the same evidence at multiple
  different types.

This is Less Cool than what we normally do for rebindable syntax, which is to
make fully-instantiated piece of evidence at every use site.  The Cmd way
is Less Cool because
  * The renamer has to predict which methods are needed.
    See the tedious RnExpr.methodNamesCmd.

  * The desugarer has to know the polymorphic type of the instantiated
    method. This is checked by Inst.tcSyntaxName, but is less flexible
    than the rest of rebindable syntax, where the type is less
    pre-ordained.  (And this flexibility is useful; for example we can
    typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.)
Austin Seipp's avatar
Austin Seipp committed
170
-}
171

172 173 174 175 176 177 178 179 180 181 182
-- | An unbound variable; used for treating out-of-scope variables as
-- expression holes
data UnboundVar
  = OutOfScope OccName GlobalRdrEnv  -- ^ An (unqualified) out-of-scope
                                     -- variable, together with the GlobalRdrEnv
                                     -- with respect to which it is unbound

                                     -- See Note [OutOfScope and GlobalRdrEnv]

  | TrueExprHole OccName             -- ^ A "true" expression hole (_ or _x)

183
  deriving Data
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 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 251 252 253 254 255 256 257 258 259 260 261

instance Outputable UnboundVar where
    ppr = ppr . unboundVarOcc

unboundVarOcc :: UnboundVar -> OccName
unboundVarOcc (OutOfScope occ _) = occ
unboundVarOcc (TrueExprHole occ) = occ

{-
Note [OutOfScope and GlobalRdrEnv]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To understand why we bundle a GlobalRdrEnv with an out-of-scope variable,
consider the following module:

    module A where

    foo :: ()
    foo = bar

    bat :: [Double]
    bat = [1.2, 3.4]

    $(return [])

    bar = ()
    bad = False

When A is compiled, the renamer determines that `bar` is not in scope in the
declaration of `foo` (since `bar` is declared in the following inter-splice
group).  Once it has finished typechecking the entire module, the typechecker
then generates the associated error message, which specifies both the type of
`bar` and a list of possible in-scope alternatives:

    A.hs:6:7: error:
        • Variable not in scope: bar :: ()
        • ‘bar’ (line 13) is not in scope before the splice on line 11
          Perhaps you meant ‘bat’ (line 9)

When it calls RnEnv.unknownNameSuggestions to identify these alternatives, the
typechecker must provide a GlobalRdrEnv.  If it provided the current one, which
contains top-level declarations for the entire module, the error message would
incorrectly suggest the out-of-scope `bar` and `bad` as possible alternatives
for `bar` (see Trac #11680).  Instead, the typechecker must use the same
GlobalRdrEnv the renamer used when it determined that `bar` is out-of-scope.

To obtain this GlobalRdrEnv, can the typechecker simply use the out-of-scope
`bar`'s location to either reconstruct it (from the current GlobalRdrEnv) or to
look it up in some global store?  Unfortunately, no.  The problem is that
location information is not always sufficient for this task.  This is most
apparent when dealing with the TH function addTopDecls, which adds its
declarations to the FOLLOWING inter-splice group.  Consider these declarations:

    ex9 = cat               -- cat is NOT in scope here

    $(do -------------------------------------------------------------
        ds <- [d| f = cab   -- cat and cap are both in scope here
                  cat = ()
                |]
        addTopDecls ds
        [d| g = cab         -- only cap is in scope here
            cap = True
          |])

    ex10 = cat              -- cat is NOT in scope here

    $(return []) -----------------------------------------------------

    ex11 = cat              -- cat is in scope

Here, both occurrences of `cab` are out-of-scope, and so the typechecker needs
the GlobalRdrEnvs which were used when they were renamed.  These GlobalRdrEnvs
are different (`cat` is present only in the GlobalRdrEnv for f's `cab'), but the
locations of the two `cab`s are the same (they are both created in the same
splice).  Thus, we must include some additional information with each `cab` to
allow the typechecker to obtain the correct GlobalRdrEnv.  Clearly, the simplest
information to use is the GlobalRdrEnv itself.
-}

262
-- | A Haskell expression.
263
data HsExpr id
264
  = HsVar     (Located id)   -- ^ Variable
265

266 267
                             -- See Note [Located RdrNames]

268 269 270 271 272 273 274
  | HsUnboundVar UnboundVar  -- ^ Unbound variable; also used for "holes"
                             --   (_ or _x).
                             -- Turned from HsVar to HsUnboundVar by the
                             --   renamer, when it finds an out-of-scope
                             --   variable or hole.
                             -- Turned into HsVar by type checker, to support
                             --   deferred type errors.
275

276
  | HsRecFld (AmbiguousFieldOcc id) -- ^ Variable pointing to record selector
Adam Gundry's avatar
Adam Gundry committed
277

Adam Gundry's avatar
Adam Gundry committed
278 279
  | HsOverLabel FastString   -- ^ Overloaded label (See Note [Overloaded labels]
                             --   in GHC.OverloadedLabels)
280 281 282 283
  | HsIPVar   HsIPName       -- ^ Implicit parameter
  | HsOverLit (HsOverLit id) -- ^ Overloaded literals

  | HsLit     HsLit          -- ^ Simple (non-overloaded) literals
284

285
  | HsLam     (MatchGroup id (LHsExpr id)) -- ^ Lambda abstraction. Currently always a single match
Alan Zimmerman's avatar
Alan Zimmerman committed
286 287 288
       --
       -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
       --       'ApiAnnotation.AnnRarrow',
289

290 291
       -- For details on above see note [Api annotations] in ApiAnnotation

Simon Peyton Jones's avatar
Simon Peyton Jones committed
292
  | HsLamCase (MatchGroup id (LHsExpr id)) -- ^ Lambda-case
Alan Zimmerman's avatar
Alan Zimmerman committed
293 294 295 296
       --
       -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
       --           'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen',
       --           'ApiAnnotation.AnnClose'
Alan Zimmerman's avatar
Alan Zimmerman committed
297

298 299
       -- For details on above see note [Api annotations] in ApiAnnotation

300
  | HsApp     (LHsExpr id) (LHsExpr id) -- ^ Application
301

302 303 304 305 306 307 308 309 310 311
  | HsAppType (LHsExpr id) (LHsWcType id) -- ^ Visible type application
       --
       -- Explicit type argument; e.g  f @Int x y
       -- NB: Has wildcards, but no implicit quantification
       --
       -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt',

  | HsAppTypeOut (LHsExpr id) (LHsWcType Name) -- just for pretty-printing


312
  -- | Operator applications:
313 314
  -- NB Bracketed ops such as (+) come out as Vars.

315 316 317
  -- NB We need an expr for the operator in an OpApp/Section since
  -- the typechecker may need to apply the operator to a few types.

Ian Lynagh's avatar
Ian Lynagh committed
318 319
  | OpApp       (LHsExpr id)    -- left operand
                (LHsExpr id)    -- operator
320
                (PostRn id Fixity) -- Renamer adds fixity; bottom until then
Ian Lynagh's avatar
Ian Lynagh committed
321 322
                (LHsExpr id)    -- right operand

323
  -- | Negation operator. Contains the negated expression and the name
Alan Zimmerman's avatar
Alan Zimmerman committed
324 325 326
  -- of 'negate'
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus'
327 328

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
329 330 331
  | NegApp      (LHsExpr id)
                (SyntaxExpr id)

Alan Zimmerman's avatar
Alan Zimmerman committed
332 333
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
  --             'ApiAnnotation.AnnClose' @')'@
334 335

  -- For details on above see note [Api annotations] in ApiAnnotation
336
  | HsPar       (LHsExpr id)    -- ^ Parenthesised expr; see Note [Parens in HsSyn]
Ian Lynagh's avatar
Ian Lynagh committed
337

338
  | SectionL    (LHsExpr id)    -- operand; see Note [Sections in HsSyn]
Ian Lynagh's avatar
Ian Lynagh committed
339
                (LHsExpr id)    -- operator
340
  | SectionR    (LHsExpr id)    -- operator; see Note [Sections in HsSyn]
Ian Lynagh's avatar
Ian Lynagh committed
341 342
                (LHsExpr id)    -- operand

343
  -- | Used for explicit tuples and sections thereof
Alan Zimmerman's avatar
Alan Zimmerman committed
344 345 346
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
  --         'ApiAnnotation.AnnClose'
347 348

  -- For details on above see note [Api annotations] in ApiAnnotation
349 350
  | ExplicitTuple
        [LHsTupArg id]
351 352
        Boxity

Alan Zimmerman's avatar
Alan Zimmerman committed
353
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
Alan Zimmerman's avatar
Alan Zimmerman committed
354 355
  --       'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
  --       'ApiAnnotation.AnnClose' @'}'@
356 357

  -- For details on above see note [Api annotations] in ApiAnnotation
Ian Lynagh's avatar
Ian Lynagh committed
358
  | HsCase      (LHsExpr id)
359
                (MatchGroup id (LHsExpr id))
Ian Lynagh's avatar
Ian Lynagh committed
360

Alan Zimmerman's avatar
Alan Zimmerman committed
361 362
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
  --       'ApiAnnotation.AnnSemi',
Alan Zimmerman's avatar
Alan Zimmerman committed
363
  --       'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
Alan Zimmerman's avatar
Alan Zimmerman committed
364
  --       'ApiAnnotation.AnnElse',
365 366

  -- For details on above see note [Api annotations] in ApiAnnotation
367
  | HsIf        (Maybe (SyntaxExpr id)) -- cond function
368 369
                                        -- Nothing => use the built-in 'if'
                                        -- See Note [Rebindable if]
370
                (LHsExpr id)    --  predicate
Ian Lynagh's avatar
Ian Lynagh committed
371 372 373
                (LHsExpr id)    --  then part
                (LHsExpr id)    --  else part

374
  -- | Multi-way if
Alan Zimmerman's avatar
Alan Zimmerman committed
375 376 377
  --
  -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf'
  --       'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
378 379

  -- For details on above see note [Api annotations] in ApiAnnotation
380
  | HsMultiIf   (PostTc id Type) [LGRHS id (LHsExpr id)]
381

382
  -- | let(rec)
Alan Zimmerman's avatar
Alan Zimmerman committed
383 384
  --
  -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
Alan Zimmerman's avatar
Alan Zimmerman committed
385 386
  --       'ApiAnnotation.AnnOpen' @'{'@,
  --       'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
387 388

  -- For details on above see note [Api annotations] in ApiAnnotation
389
  | HsLet       (Located (HsLocalBinds id))
Ian Lynagh's avatar
Ian Lynagh committed
390 391
                (LHsExpr  id)

Alan Zimmerman's avatar
Alan Zimmerman committed
392 393 394 395
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
  --             'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
  --             'ApiAnnotation.AnnVbar',
  --             'ApiAnnotation.AnnClose'
396 397

  -- For details on above see note [Api annotations] in ApiAnnotation
398 399 400 401 402
  | HsDo        (HsStmtContext Name)     -- The parameterisation is unimportant
                                         -- because in this context we never use
                                         -- the PatGuard or ParStmt variant
                (Located [ExprLStmt id]) -- "do":one or more stmts
                (PostTc id Type)         -- Type of the whole expression
Ian Lynagh's avatar
Ian Lynagh committed
403

404
  -- | Syntactic list: [a,b,c,...]
Alan Zimmerman's avatar
Alan Zimmerman committed
405
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
406 407
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
  --              'ApiAnnotation.AnnClose' @']'@
408 409

  -- For details on above see note [Api annotations] in ApiAnnotation
410 411
  | ExplicitList
                (PostTc id Type)        -- Gives type of components of list
412
                (Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromListN witness
Ian Lynagh's avatar
Ian Lynagh committed
413 414
                [LHsExpr id]

415
  -- | Syntactic parallel array: [:e1, ..., en:]
Alan Zimmerman's avatar
Alan Zimmerman committed
416
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
417
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
Alan Zimmerman's avatar
Alan Zimmerman committed
418 419
  --              'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnComma',
  --              'ApiAnnotation.AnnVbar'
Alan Zimmerman's avatar
Alan Zimmerman committed
420
  --              'ApiAnnotation.AnnClose' @':]'@
421 422

  -- For details on above see note [Api annotations] in ApiAnnotation
423 424
  | ExplicitPArr
                (PostTc id Type)   -- type of elements of the parallel array
Ian Lynagh's avatar
Ian Lynagh committed
425 426
                [LHsExpr id]

427
  -- | Record construction
Alan Zimmerman's avatar
Alan Zimmerman committed
428
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
429 430
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
  --         'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
431 432

  -- For details on above see note [Api annotations] in ApiAnnotation
433 434 435 436 437 438
  | RecordCon
      { rcon_con_name :: Located id         -- The constructor name;
                                            --  not used after type checking
      , rcon_con_like :: PostTc id ConLike  -- The data constructor or pattern synonym
      , rcon_con_expr :: PostTcExpr         -- Instantiated constructor function
      , rcon_flds     :: HsRecordBinds id } -- The fields
Ian Lynagh's avatar
Ian Lynagh committed
439

440
  -- | Record update
Alan Zimmerman's avatar
Alan Zimmerman committed
441
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
442 443
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
  --         'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
444 445

  -- For details on above see note [Api annotations] in ApiAnnotation
446 447 448 449
  | RecordUpd
      { rupd_expr :: LHsExpr id
      , rupd_flds :: [LHsRecUpdField id]
      , rupd_cons :: PostTc id [ConLike]
450 451 452
                -- Filled in by the type checker to the
                -- _non-empty_ list of DataCons that have
                -- all the upd'd fields
453 454 455 456 457 458 459

      , rupd_in_tys  :: PostTc id [Type]  -- Argument types of *input* record type
      , rupd_out_tys :: PostTc id [Type]  --              and  *output* record type
                                          -- The original type can be reconstructed
                                          -- with conLikeResTy
      , rupd_wrap :: PostTc id HsWrapper  -- See note [Record Update HsWrapper]
      }
Ian Lynagh's avatar
Ian Lynagh committed
460 461 462
  -- For a type family, the arg types are of the *instance* tycon,
  -- not the family tycon

Alan Zimmerman's avatar
Alan Zimmerman committed
463 464 465
  -- | Expression with an explicit type signature. @e :: type@
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
466 467

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
468
  | ExprWithTySig
469
                (LHsExpr id)
470
                (LHsSigWcType id)
Ian Lynagh's avatar
Ian Lynagh committed
471

472
  | ExprWithTySigOut              -- Post typechecking
Ian Lynagh's avatar
Ian Lynagh committed
473
                (LHsExpr id)
474 475 476
                (LHsSigWcType Name)  -- Retain the signature,
                                     -- as HsSigType Name, for
                                     -- round-tripping purposes
Ian Lynagh's avatar
Ian Lynagh committed
477

478
  -- | Arithmetic sequence
Alan Zimmerman's avatar
Alan Zimmerman committed
479
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
480 481 482
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
  --              'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
  --              'ApiAnnotation.AnnClose' @']'@
483 484

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
485
  | ArithSeq
Ian Lynagh's avatar
Ian Lynagh committed
486
                PostTcExpr
487
                (Maybe (SyntaxExpr id))   -- For OverloadedLists, the fromList witness
Ian Lynagh's avatar
Ian Lynagh committed
488 489
                (ArithSeqInfo id)

490
  -- | Arithmetic sequence for parallel array
Alan Zimmerman's avatar
Alan Zimmerman committed
491 492 493 494 495 496 497
  --
  -- > [:e1..e2:] or [:e1, e2..e3:]
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
  --              'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
  --              'ApiAnnotation.AnnVbar',
  --              'ApiAnnotation.AnnClose' @':]'@
498 499

  -- For details on above see note [Api annotations] in ApiAnnotation
Austin Seipp's avatar
Austin Seipp committed
500
  | PArrSeq
Alan Zimmerman's avatar
Alan Zimmerman committed
501
                PostTcExpr
Ian Lynagh's avatar
Ian Lynagh committed
502 503
                (ArithSeqInfo id)

Alan Zimmerman's avatar
Alan Zimmerman committed
504 505 506
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# SCC'@,
  --             'ApiAnnotation.AnnVal' or 'ApiAnnotation.AnnValStr',
  --              'ApiAnnotation.AnnClose' @'\#-}'@
507 508

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
509
  | HsSCC       SourceText            -- Note [Pragma source text] in BasicTypes
510 511
                StringLiteral         -- "set cost centre" SCC pragma
                (LHsExpr id)          -- expr whose cost is to be measured
Alan Zimmerman's avatar
Alan Zimmerman committed
512 513 514

  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CORE'@,
  --             'ApiAnnotation.AnnVal', 'ApiAnnotation.AnnClose' @'\#-}'@
515 516

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
517
  | HsCoreAnn   SourceText            -- Note [Pragma source text] in BasicTypes
518
                StringLiteral         -- hdaume: core annotation
Ian Lynagh's avatar
Ian Lynagh committed
519 520
                (LHsExpr id)

521
  -----------------------------------------------------------
522
  -- MetaHaskell Extensions
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
523

Alan Zimmerman's avatar
Alan Zimmerman committed
524 525 526
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
  --         'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
  --         'ApiAnnotation.AnnClose'
527 528

  -- For details on above see note [Api annotations] in ApiAnnotation
529
  | HsBracket    (HsBracket id)
530

531 532 533 534 535
    -- See Note [Pending Splices]
  | HsRnBracketOut
      (HsBracket Name)     -- Output of the renamer is the *original* renamed
                           -- expression, plus
      [PendingRnSplice]    -- _renamed_ splices to be type checked
gmainland's avatar
gmainland committed
536

537 538 539 540 541
  | HsTcBracketOut
      (HsBracket Name)     -- Output of the type checker is the *original*
                           -- renamed expression, plus
      [PendingTcSplice]    -- _typechecked_ splices to be
                           -- pasted back in by the desugarer
542

Alan Zimmerman's avatar
Alan Zimmerman committed
543 544
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
  --         'ApiAnnotation.AnnClose'
545 546

  -- For details on above see note [Api annotations] in ApiAnnotation
547
  | HsSpliceE  (HsSplice id)
548

549 550 551
  -----------------------------------------------------------
  -- Arrow notation extension

552
  -- | @proc@ notation for Arrows
Alan Zimmerman's avatar
Alan Zimmerman committed
553 554 555
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc',
  --          'ApiAnnotation.AnnRarrow'
556 557

  -- For details on above see note [Api annotations] in ApiAnnotation
Ian Lynagh's avatar
Ian Lynagh committed
558 559 560
  | HsProc      (LPat id)               -- arrow abstraction, proc
                (LHsCmdTop id)          -- body of the abstraction
                                        -- always has an empty stack
561

Facundo Domínguez's avatar
Facundo Domínguez committed
562 563
  ---------------------------------------
  -- static pointers extension
Alan Zimmerman's avatar
Alan Zimmerman committed
564
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic',
565 566

  -- For details on above see note [Api annotations] in ApiAnnotation
567 568
  | HsStatic (PostRn id NameSet) -- Free variables of the body
             (LHsExpr id)        -- Body
Facundo Domínguez's avatar
Facundo Domínguez committed
569

570 571
  ---------------------------------------
  -- The following are commands, not expressions proper
572
  -- They are only used in the parsing stage and are removed
573
  --    immediately in parser.RdrHsSyn.checkCommand
Alan Zimmerman's avatar
Alan Zimmerman committed
574 575 576 577

  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
  --          'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
  --          'ApiAnnotation.AnnRarrowtail'
578 579

  -- For details on above see note [Api annotations] in ApiAnnotation
580 581 582 583 584 585 586 587 588
  | HsArrApp             -- Arrow tail, or arrow application (f -< arg)
        (LHsExpr id)     -- arrow expression, f
        (LHsExpr id)     -- input expression, arg
        (PostTc id Type) -- type of the arrow expressions f,
                         -- of the form a t t', where arg :: t
        HsArrAppType     -- higher-order (-<<) or first-order (-<)
        Bool             -- True => right-to-left (f -< arg)
                         -- False => left-to-right (arg >- f)

Alan Zimmerman's avatar
Alan Zimmerman committed
589 590
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@,
  --         'ApiAnnotation.AnnClose' @'|)'@
591 592

  -- For details on above see note [Api annotations] in ApiAnnotation
593 594 595 596 597 598 599
  | HsArrForm            -- Command formation,  (| e cmd1 .. cmdn |)
        (LHsExpr id)     -- the operator
                         -- after type-checking, a type abstraction to be
                         -- applied to the type of the local environment tuple
        (Maybe Fixity)   -- fixity (filled in by the renamer), for forms that
                         -- were converted from OpApp's by the renamer
        [LHsCmdTop id]   -- argument commands
600

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
601 602 603
  ---------------------------------------
  -- Haskell program coverage (Hpc) Support

Ian Lynagh's avatar
Ian Lynagh committed
604
  | HsTick
605
     (Tickish id)
Ian Lynagh's avatar
Ian Lynagh committed
606
     (LHsExpr id)                       -- sub-expression
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
607 608

  | HsBinTick
Ian Lynagh's avatar
Ian Lynagh committed
609 610 611
     Int                                -- module-local tick number for True
     Int                                -- module-local tick number for False
     (LHsExpr id)                       -- sub-expression
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
612

Alan Zimmerman's avatar
Alan Zimmerman committed
613
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
Alan Zimmerman's avatar
Alan Zimmerman committed
614 615 616
  --       'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@,
  --       'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal',
  --       'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal',
Alan Zimmerman's avatar
Alan Zimmerman committed
617
  --       'ApiAnnotation.AnnMinus',
Alan Zimmerman's avatar
Alan Zimmerman committed
618 619 620
  --       'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon',
  --       'ApiAnnotation.AnnVal',
  --       'ApiAnnotation.AnnClose' @'\#-}'@
621 622

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
623 624
  | HsTickPragma                      -- A pragma introduced tick
     SourceText                       -- Note [Pragma source text] in BasicTypes
625
     (StringLiteral,(Int,Int),(Int,Int))
626
                                      -- external span for this tick
627 628 629
     ((SourceText,SourceText),(SourceText,SourceText))
        -- Source text for the four integers used in the span.
        -- See note [Pragma source text] in BasicTypes
Ian Lynagh's avatar
Ian Lynagh committed
630
     (LHsExpr id)
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
631 632 633 634

  ---------------------------------------
  -- These constructors only appear temporarily in the parser.
  -- The renamer translates them into the Right Thing.
635

Ian Lynagh's avatar
Ian Lynagh committed
636
  | EWildPat                 -- wildcard
637

Alan Zimmerman's avatar
Alan Zimmerman committed
638
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt'
639 640

  -- For details on above see note [Api annotations] in ApiAnnotation
Ian Lynagh's avatar
Ian Lynagh committed
641 642
  | EAsPat      (Located id) -- as pattern
                (LHsExpr id)
643

Alan Zimmerman's avatar
Alan Zimmerman committed
644
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow'
645 646

  -- For details on above see note [Api annotations] in ApiAnnotation
Ian Lynagh's avatar
Ian Lynagh committed
647 648
  | EViewPat    (LHsExpr id) -- view pattern
                (LHsExpr id)
649

Alan Zimmerman's avatar
Alan Zimmerman committed
650
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
651 652

  -- For details on above see note [Api annotations] in ApiAnnotation
Ian Lynagh's avatar
Ian Lynagh committed
653
  | ELazyPat    (LHsExpr id) -- ~ pattern
654

655

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
656 657
  ---------------------------------------
  -- Finally, HsWrap appears only in typechecker output
658

Ian Lynagh's avatar
Ian Lynagh committed
659 660
  |  HsWrap     HsWrapper    -- TRANSLATION
                (HsExpr id)
661

662
deriving instance (DataId id) => Data (HsExpr id)
663

664
-- | HsTupArg is used for tuple sections
665
--  (,a,) is represented by  ExplicitTuple [Missing ty1, Present a, Missing ty3]
666
--  Which in turn stands for (\x:ty1 \y:ty2. (x,a,y))
667
type LHsTupArg id = Located (HsTupArg id)
Alan Zimmerman's avatar
Alan Zimmerman committed
668
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma'
669 670

-- For details on above see note [Api annotations] in ApiAnnotation
671
data HsTupArg id
672 673 674
  = Present (LHsExpr id)     -- ^ The argument
  | Missing (PostTc id Type) -- ^ The argument is missing, but this is its type
deriving instance (DataId id) => Data (HsTupArg id)
675

676 677 678
tupArgPresent :: LHsTupArg id -> Bool
tupArgPresent (L _ (Present {})) = True
tupArgPresent (L _ (Missing {})) = False
679

Austin Seipp's avatar
Austin Seipp committed
680
{-
681 682 683 684 685 686 687
Note [Parens in HsSyn]
~~~~~~~~~~~~~~~~~~~~~~
HsPar (and ParPat in patterns, HsParTy in types) is used as follows

  * Generally HsPar is optional; the pretty printer adds parens where
    necessary.  Eg (HsApp f (HsApp g x)) is fine, and prints 'f (g x)'

688
  * HsPars are pretty printed as '( .. )' regardless of whether
689 690 691 692 693 694 695 696
    or not they are strictly necssary

  * HsPars are respected when rearranging operator fixities.
    So   a * (b + c)  means what it says (where the parens are an HsPar)

Note [Sections in HsSyn]
~~~~~~~~~~~~~~~~~~~~~~~~
Sections should always appear wrapped in an HsPar, thus
697 698
         HsPar (SectionR ...)
The parser parses sections in a wider variety of situations
699
(See Note [Parsing sections]), but the renamer checks for those
700
parens.  This invariant makes pretty-printing easier; we don't need
701 702
a special case for adding the parens round sections.

703 704 705 706 707 708
Note [Rebindable if]
~~~~~~~~~~~~~~~~~~~~
The rebindable syntax for 'if' is a bit special, because when
rebindable syntax is *off* we do not want to treat
   (if c then t else e)
as if it was an application (ifThenElse c t e).  Why not?
709
Because we allow an 'if' to return *unboxed* results, thus
710 711 712 713 714
  if blah then 3# else 4#
whereas that would not be possible using a all to a polymorphic function
(because you can't call a polymorphic function at an unboxed type).

So we use Nothing to mean "use the old built-in typing rule".
Matthew Pickering's avatar
Matthew Pickering committed
715 716 717

Note [Record Update HsWrapper]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
718 719 720 721
There is a wrapper in RecordUpd which is used for the *required*
constraints for pattern synonyms. This wrapper is created in the
typechecking and is then directly used in the desugaring without
modification.
Matthew Pickering's avatar
Matthew Pickering committed
722 723

For example, if we have the record pattern synonym P,
724 725
  pattern P :: (Show a) => a -> Maybe a
  pattern P{x} = Just x
Matthew Pickering's avatar
Matthew Pickering committed
726

727
  foo = (Just True) { x = False }
Matthew Pickering's avatar
Matthew Pickering committed
728
then `foo` desugars to something like
729 730 731 732
  foo = case Just True of
          P x -> P False
hence we need to provide the correct dictionaries to P's matcher on
the RHS so that we can build the expression.
Matthew Pickering's avatar
Matthew Pickering committed
733

734 735 736 737 738 739 740 741 742 743
Note [Located RdrNames]
~~~~~~~~~~~~~~~~~~~~~~~
A number of syntax elements have seemingly redundant locations attached to them.
This is deliberate, to allow transformations making use of the API Annotations
to easily correlate a Located Name in the RenamedSource with a Located RdrName
in the ParsedSource.

There are unfortunately enough differences between the ParsedSource and the
RenamedSource that the API Annotations cannot be used directly with
RenamedSource, so this allows a simple mapping to be used based on the location.
Austin Seipp's avatar
Austin Seipp committed
744
-}
745

746
instance (OutputableBndrId id) => Outputable (HsExpr id) where
747
    ppr expr = pprExpr expr
748

749
-----------------------
Ian Lynagh's avatar
Ian Lynagh committed
750
-- pprExpr, pprLExpr, pprBinds call pprDeeper;
751
-- the underscore versions do not
752
pprLExpr :: (OutputableBndrId id) => LHsExpr id -> SDoc
753 754
pprLExpr (L _ e) = pprExpr e

755
pprExpr :: (OutputableBndrId id) => HsExpr id -> SDoc
Ian Lynagh's avatar
Ian Lynagh committed
756 757 758 759 760 761 762
pprExpr e | isAtomicHsExpr e || isQuietHsExpr e =            ppr_expr e
          | otherwise                           = pprDeeper (ppr_expr e)

isQuietHsExpr :: HsExpr id -> Bool
-- Parentheses do display something, but it gives little info and
-- if we go deeper when we go inside them then we get ugly things
-- like (...)
763
isQuietHsExpr (HsPar _)          = True
Ian Lynagh's avatar
Ian Lynagh committed
764
-- applications don't display anything themselves
765 766 767 768
isQuietHsExpr (HsApp _ _)        = True
isQuietHsExpr (HsAppType _ _)    = True
isQuietHsExpr (HsAppTypeOut _ _) = True
isQuietHsExpr (OpApp _ _ _ _)    = True
Ian Lynagh's avatar
Ian Lynagh committed
769
isQuietHsExpr _ = False
770

771
pprBinds :: (OutputableBndrId idL, OutputableBndrId idR)
Ian Lynagh's avatar
Ian Lynagh committed
772
         => HsLocalBindsLR idL idR -> SDoc
773
pprBinds b = pprDeeper (ppr b)
774

775
-----------------------
776
ppr_lexpr :: (OutputableBndrId id) => LHsExpr id -> SDoc
777
ppr_lexpr e = ppr_expr (unLoc e)
778

779
ppr_expr :: forall id. (OutputableBndrId id) => HsExpr id -> SDoc
780
ppr_expr (HsVar (L _ v))  = pprPrefixOcc v
781
ppr_expr (HsUnboundVar uv)= pprPrefixOcc (unboundVarOcc uv)
782
ppr_expr (HsIPVar v)      = ppr v
Adam Gundry's avatar
Adam Gundry committed
783
ppr_expr (HsOverLabel l)  = char '#' <> ppr l
784 785 786
ppr_expr (HsLit lit)      = ppr lit
ppr_expr (HsOverLit lit)  = ppr lit
ppr_expr (HsPar e)        = parens (ppr_lexpr e)
787

788
ppr_expr (HsCoreAnn _ (StringLiteral _ s) e)
789
  = vcat [text "HsCoreAnn" <+> ftext s, ppr_lexpr e]
790

791 792 793
ppr_expr e@(HsApp {})        = ppr_apps e []
ppr_expr e@(HsAppType {})    = ppr_apps e []
ppr_expr e@(HsAppTypeOut {}) = ppr_apps e []
794

Ian Lynagh's avatar
Ian Lynagh committed
795
ppr_expr (OpApp e1 op _ e2)
796
  = case unLoc op of
797
      HsVar (L _ v) -> pp_infixly v
798
      HsRecFld f    -> pp_infixly f
799
      _             -> pp_prefixly
800
  where
Ian Lynagh's avatar
Ian Lynagh committed
801
    pp_e1 = pprDebugParendExpr e1   -- In debug mode, add parens
802
    pp_e2 = pprDebugParendExpr e2   -- to make precedence clear
803 804

    pp_prefixly
805
      = hang (ppr op) 2 (sep [pp_e1, pp_e2])
806 807

    pp_infixly v
808
      = sep [pp_e1, sep [pprInfixOcc v, nest 2 pp_e2]]
809

810
ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
811

812
ppr_expr (SectionL expr op)
813
  = case unLoc op of
814 815
      HsVar (L _ v) -> pp_infixly v
      _             -> pp_prefixly
816
  where
817
    pp_expr = pprDebugParendExpr expr
818

819
    pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
820
                       4 (hsep [pp_expr, text "x_ )"])
821
    pp_infixly v = (sep [pp_expr, pprInfixOcc v])
822

823
ppr_expr (SectionR op expr)
824
  = case unLoc op of
825 826
      HsVar (L _ v) -> pp_infixly v
      _             -> pp_prefixly
827
  where
828
    pp_expr = pprDebugParendExpr expr
829

830
    pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, text "x_"])
831
                       4 (pp_expr <> rparen)
832
    pp_infixly v = sep [pprInfixOcc v, pp_expr]
833

834
ppr_expr (ExplicitTuple exprs boxity)
835
  = tupleParens (boxityTupleSort boxity) (fcat (ppr_tup_args $ map unLoc exprs))
836 837 838
  where
    ppr_tup_args []               = []
    ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es
839
    ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es
840 841 842 843 844

    punc (Present {} : _) = comma <> space
    punc (Missing {} : _) = comma
    punc []               = empty

845
ppr_expr (HsLam matches)
846
  = pprMatches matches
847

Simon Peyton Jones's avatar
Simon Peyton Jones committed
848
ppr_expr (HsLamCase matches)
849
  = sep [ sep [text "\\case {"],
850
          nest 2 (pprMatches matches <+> char '}') ]
851

852
ppr_expr (HsCase expr matches)
853
  = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")],
854
          nest 2 (pprMatches matches <+> char '}') ]
855

856
ppr_expr (HsIf _ e1 e2 e3)
857
  = sep [hsep [text "if", nest 2 (ppr e1), ptext (sLit "then")],
Ian Lynagh's avatar
Ian Lynagh committed
858
         nest 4 (ppr e2),