HsExpr.hs 98.7 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
import PlaceHolder ( PostTc,PostRn,DataId,DataIdPost,
25
                     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
Ian Lynagh's avatar
Ian Lynagh committed
41
import Outputable
42
import FastString
43
import Type
44 45

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

50 51 52
import GHCi.RemoteTypes ( ForeignRef )
import qualified Language.Haskell.TH as TH (Q)

Austin Seipp's avatar
Austin Seipp committed
53 54 55
{-
************************************************************************
*                                                                      *
56
\subsection{Expressions proper}
Austin Seipp's avatar
Austin Seipp committed
57 58 59
*                                                                      *
************************************************************************
-}
60

61 62
-- * Expressions proper

63
-- | Located Haskell Expression
64
type LHsExpr id = Located (HsExpr id)
Alan Zimmerman's avatar
Alan Zimmerman committed
65 66
  -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
  --   in a list
67

68 69
  -- For details on above see note [Api annotations] in ApiAnnotation

70
-------------------------
71 72 73
-- | Post-Type checking Expression
--
-- PostTcExpr is an evidence expression attached to the syntax tree by the
74
-- type checker (c.f. postTcType).
75
type PostTcExpr  = HsExpr Id
76 77 78 79

-- | Post-Type checking Table
--
-- We use a PostTcTable where there are a bunch of pieces of evidence, more
80
-- than is convenient to keep individually.
81
type PostTcTable = [(Name, PostTcExpr)]
82 83

noPostTcExpr :: PostTcExpr
84
noPostTcExpr = HsLit (HsString NoSourceText (fsLit "noPostTcExpr"))
85 86 87 88 89

noPostTcTable :: PostTcTable
noPostTcTable = []

-------------------------
90 91 92
-- | Syntax Expression
--
-- SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier,
Ian Lynagh's avatar
Ian Lynagh committed
93
-- by the renamer.  It's used for rebindable syntax.
94 95 96
--
-- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for
--      @(>>=)@, and then instantiated by the type checker with its type args
97
--      etc
98 99 100 101 102 103 104 105 106 107 108 109 110 111
--
-- 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)
112

113 114 115
-- | This is used for rebindable-syntax pieces that are too polymorphic
-- for tcSyntaxOp (trS_fmap and the mzip in ParStmt)
noExpr :: HsExpr id
116
noExpr = HsLit (HsString (SourceText  "noExpr") (fsLit "noExpr"))
117

Ian Lynagh's avatar
Ian Lynagh committed
118 119
noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after,
                              -- (if the syntax slot makes no sense)
120 121
noSyntaxExpr = SyntaxExpr { syn_expr      = HsLit (HsString NoSourceText
                                                        (fsLit "noSyntaxExpr"))
122 123 124 125 126 127 128 129 130 131 132 133
                          , 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

134
instance (OutputableBndrId id) => Outputable (SyntaxExpr id) where
135 136 137 138 139 140
  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
141 142
      then ppr expr <> braces (pprWithCommas ppr arg_wraps)
                    <> braces (ppr res_wrap)
143 144
      else ppr expr

145
-- | Command Syntax Table (for Arrow syntax)
146
type CmdSyntaxTable id = [(Name, HsExpr id)]
147
-- See Note [CmdSyntaxTable]
148

Austin Seipp's avatar
Austin Seipp committed
149
{-
150 151 152 153 154
Note [CmdSyntaxtable]
~~~~~~~~~~~~~~~~~~~~~
Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps
track of the methods needed for a Cmd.

155
* Before the renamer, this list is an empty list
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182

* 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
183
-}
184

185 186 187 188 189 190 191 192 193 194 195
-- | 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)

196
  deriving Data
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 262 263 264 265 266 267 268 269 270 271 272 273 274

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.
-}

275
-- | A Haskell expression.
276
data HsExpr id
277
  = HsVar     (Located id)   -- ^ Variable
278

279 280
                             -- See Note [Located RdrNames]

281 282 283 284 285 286 287
  | 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.
288

289 290 291
  | HsConLikeOut ConLike     -- ^ After typechecker only; must be different
                             -- HsVar for pretty printing

292
  | HsRecFld (AmbiguousFieldOcc id) -- ^ Variable pointing to record selector
293
                                    -- Not in use after typechecking
294

295 296 297 298 299
  | HsOverLabel (Maybe id) FastString
     -- ^ Overloaded label (Note [Overloaded labels] in GHC.OverloadedLabels)
     --   @Just id@ means @RebindableSyntax@ is in use, and gives the id of the
     --   in-scope 'fromLabel'.
     --   NB: Not in use after typechecking
300 301

  | HsIPVar   HsIPName       -- ^ Implicit parameter (not in use after typechecking)
302 303 304
  | HsOverLit (HsOverLit id) -- ^ Overloaded literals

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

306
  | HsLam     (MatchGroup id (LHsExpr id)) -- ^ Lambda abstraction. Currently always a single match
Alan Zimmerman's avatar
Alan Zimmerman committed
307 308 309
       --
       -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
       --       'ApiAnnotation.AnnRarrow',
310

311 312
       -- For details on above see note [Api annotations] in ApiAnnotation

Simon Peyton Jones's avatar
Simon Peyton Jones committed
313
  | HsLamCase (MatchGroup id (LHsExpr id)) -- ^ Lambda-case
Alan Zimmerman's avatar
Alan Zimmerman committed
314 315 316 317
       --
       -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
       --           'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen',
       --           'ApiAnnotation.AnnClose'
Alan Zimmerman's avatar
Alan Zimmerman committed
318

319 320
       -- For details on above see note [Api annotations] in ApiAnnotation

321
  | HsApp     (LHsExpr id) (LHsExpr id) -- ^ Application
322

323 324 325 326 327 328 329 330 331 332
  | 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


333
  -- | Operator applications:
334 335
  -- NB Bracketed ops such as (+) come out as Vars.

336 337 338
  -- 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
339 340
  | OpApp       (LHsExpr id)    -- left operand
                (LHsExpr id)    -- operator
341
                (PostRn id Fixity) -- Renamer adds fixity; bottom until then
Ian Lynagh's avatar
Ian Lynagh committed
342 343
                (LHsExpr id)    -- right operand

344
  -- | Negation operator. Contains the negated expression and the name
Alan Zimmerman's avatar
Alan Zimmerman committed
345 346 347
  -- of 'negate'
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus'
348 349

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

Alan Zimmerman's avatar
Alan Zimmerman committed
353 354
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
  --             'ApiAnnotation.AnnClose' @')'@
355 356

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

359
  | SectionL    (LHsExpr id)    -- operand; see Note [Sections in HsSyn]
Ian Lynagh's avatar
Ian Lynagh committed
360
                (LHsExpr id)    -- operator
361
  | SectionR    (LHsExpr id)    -- operator; see Note [Sections in HsSyn]
Ian Lynagh's avatar
Ian Lynagh committed
362 363
                (LHsExpr id)    -- operand

364
  -- | Used for explicit tuples and sections thereof
Alan Zimmerman's avatar
Alan Zimmerman committed
365 366 367
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
  --         'ApiAnnotation.AnnClose'
368 369

  -- For details on above see note [Api annotations] in ApiAnnotation
370 371
  | ExplicitTuple
        [LHsTupArg id]
372 373
        Boxity

374 375 376 377 378 379 380
  -- | Used for unboxed sum types
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(#'@,
  --          'ApiAnnotation.AnnVbar', 'ApiAnnotation.AnnClose' @'#)'@,
  --
  --  There will be multiple 'ApiAnnotation.AnnVbar', (1 - alternative) before
  --  the expression, (arity - alternative) after it
381
  | ExplicitSum
382 383
          ConTag --  Alternative (one-based)
          Arity  --  Sum arity
384 385 386
          (LHsExpr id)
          (PostTc id [Type])   -- the type arguments

Alan Zimmerman's avatar
Alan Zimmerman committed
387
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
Alan Zimmerman's avatar
Alan Zimmerman committed
388 389
  --       'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
  --       'ApiAnnotation.AnnClose' @'}'@
390 391

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

Alan Zimmerman's avatar
Alan Zimmerman committed
395 396
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
  --       'ApiAnnotation.AnnSemi',
Alan Zimmerman's avatar
Alan Zimmerman committed
397
  --       'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
Alan Zimmerman's avatar
Alan Zimmerman committed
398
  --       'ApiAnnotation.AnnElse',
399 400

  -- For details on above see note [Api annotations] in ApiAnnotation
401
  | HsIf        (Maybe (SyntaxExpr id)) -- cond function
402 403
                                        -- Nothing => use the built-in 'if'
                                        -- See Note [Rebindable if]
404
                (LHsExpr id)    --  predicate
Ian Lynagh's avatar
Ian Lynagh committed
405 406 407
                (LHsExpr id)    --  then part
                (LHsExpr id)    --  else part

408
  -- | Multi-way if
Alan Zimmerman's avatar
Alan Zimmerman committed
409 410 411
  --
  -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf'
  --       'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
412 413

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

416
  -- | let(rec)
Alan Zimmerman's avatar
Alan Zimmerman committed
417 418
  --
  -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
Alan Zimmerman's avatar
Alan Zimmerman committed
419 420
  --       'ApiAnnotation.AnnOpen' @'{'@,
  --       'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
421 422

  -- For details on above see note [Api annotations] in ApiAnnotation
423
  | HsLet       (LHsLocalBinds id)
Ian Lynagh's avatar
Ian Lynagh committed
424 425
                (LHsExpr  id)

Alan Zimmerman's avatar
Alan Zimmerman committed
426 427 428 429
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
  --             'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
  --             'ApiAnnotation.AnnVbar',
  --             'ApiAnnotation.AnnClose'
430 431

  -- For details on above see note [Api annotations] in ApiAnnotation
432 433 434 435 436
  | 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
437

438
  -- | Syntactic list: [a,b,c,...]
Alan Zimmerman's avatar
Alan Zimmerman committed
439
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
440 441
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
  --              'ApiAnnotation.AnnClose' @']'@
442 443

  -- For details on above see note [Api annotations] in ApiAnnotation
444 445
  | ExplicitList
                (PostTc id Type)        -- Gives type of components of list
446
                (Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromListN witness
Ian Lynagh's avatar
Ian Lynagh committed
447 448
                [LHsExpr id]

449
  -- | Syntactic parallel array: [:e1, ..., en:]
Alan Zimmerman's avatar
Alan Zimmerman committed
450
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
451
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
Alan Zimmerman's avatar
Alan Zimmerman committed
452 453
  --              'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnComma',
  --              'ApiAnnotation.AnnVbar'
Alan Zimmerman's avatar
Alan Zimmerman committed
454
  --              'ApiAnnotation.AnnClose' @':]'@
455 456

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

461
  -- | Record construction
Alan Zimmerman's avatar
Alan Zimmerman committed
462
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
463 464
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
  --         'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
465 466

  -- For details on above see note [Api annotations] in ApiAnnotation
467 468 469 470 471 472
  | 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
473

474
  -- | Record update
Alan Zimmerman's avatar
Alan Zimmerman committed
475
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
476 477
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
  --         'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
478 479

  -- For details on above see note [Api annotations] in ApiAnnotation
480 481 482 483
  | RecordUpd
      { rupd_expr :: LHsExpr id
      , rupd_flds :: [LHsRecUpdField id]
      , rupd_cons :: PostTc id [ConLike]
484 485 486
                -- Filled in by the type checker to the
                -- _non-empty_ list of DataCons that have
                -- all the upd'd fields
487 488 489 490 491 492 493

      , 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
494 495 496
  -- For a type family, the arg types are of the *instance* tycon,
  -- not the family tycon

Alan Zimmerman's avatar
Alan Zimmerman committed
497 498 499
  -- | Expression with an explicit type signature. @e :: type@
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
500 501

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
502
  | ExprWithTySig
503
                (LHsExpr id)
504
                (LHsSigWcType id)
Ian Lynagh's avatar
Ian Lynagh committed
505

506
  | ExprWithTySigOut              -- Post typechecking
Ian Lynagh's avatar
Ian Lynagh committed
507
                (LHsExpr id)
508 509 510
                (LHsSigWcType Name)  -- Retain the signature,
                                     -- as HsSigType Name, for
                                     -- round-tripping purposes
Ian Lynagh's avatar
Ian Lynagh committed
511

512
  -- | Arithmetic sequence
Alan Zimmerman's avatar
Alan Zimmerman committed
513
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
514 515 516
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
  --              'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
  --              'ApiAnnotation.AnnClose' @']'@
517 518

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
519
  | ArithSeq
Ian Lynagh's avatar
Ian Lynagh committed
520
                PostTcExpr
521
                (Maybe (SyntaxExpr id))   -- For OverloadedLists, the fromList witness
Ian Lynagh's avatar
Ian Lynagh committed
522 523
                (ArithSeqInfo id)

524
  -- | Arithmetic sequence for parallel array
Alan Zimmerman's avatar
Alan Zimmerman committed
525 526 527 528 529 530 531
  --
  -- > [:e1..e2:] or [:e1, e2..e3:]
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
  --              'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
  --              'ApiAnnotation.AnnVbar',
  --              'ApiAnnotation.AnnClose' @':]'@
532 533

  -- For details on above see note [Api annotations] in ApiAnnotation
Austin Seipp's avatar
Austin Seipp committed
534
  | PArrSeq
Alan Zimmerman's avatar
Alan Zimmerman committed
535
                PostTcExpr
Ian Lynagh's avatar
Ian Lynagh committed
536 537
                (ArithSeqInfo id)

Alan Zimmerman's avatar
Alan Zimmerman committed
538 539 540
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# SCC'@,
  --             'ApiAnnotation.AnnVal' or 'ApiAnnotation.AnnValStr',
  --              'ApiAnnotation.AnnClose' @'\#-}'@
541 542

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
543
  | HsSCC       SourceText            -- Note [Pragma source text] in BasicTypes
544 545
                StringLiteral         -- "set cost centre" SCC pragma
                (LHsExpr id)          -- expr whose cost is to be measured
Alan Zimmerman's avatar
Alan Zimmerman committed
546 547 548

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

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

555
  -----------------------------------------------------------
556
  -- MetaHaskell Extensions
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
557

Alan Zimmerman's avatar
Alan Zimmerman committed
558
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
559 560
  --         'ApiAnnotation.AnnOpenE','ApiAnnotation.AnnOpenEQ',
  --         'ApiAnnotation.AnnClose','ApiAnnotation.AnnCloseQ'
561 562

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

565 566 567 568 569
    -- 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
570

571 572 573 574 575
  | 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
576

Alan Zimmerman's avatar
Alan Zimmerman committed
577 578
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
  --         'ApiAnnotation.AnnClose'
579 580

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

583 584 585
  -----------------------------------------------------------
  -- Arrow notation extension

586
  -- | @proc@ notation for Arrows
Alan Zimmerman's avatar
Alan Zimmerman committed
587 588 589
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc',
  --          'ApiAnnotation.AnnRarrow'
590 591

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

596 597
  ---------------------------------------
  -- static pointers extension
Alan Zimmerman's avatar
Alan Zimmerman committed
598
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic',
599 600

  -- For details on above see note [Api annotations] in ApiAnnotation
601 602
  | HsStatic (PostRn id NameSet) -- Free variables of the body
             (LHsExpr id)        -- Body
603

604 605
  ---------------------------------------
  -- The following are commands, not expressions proper
606
  -- They are only used in the parsing stage and are removed
607
  --    immediately in parser.RdrHsSyn.checkCommand
Alan Zimmerman's avatar
Alan Zimmerman committed
608 609 610 611

  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
  --          'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
  --          'ApiAnnotation.AnnRarrowtail'
612 613

  -- For details on above see note [Api annotations] in ApiAnnotation
614 615 616 617 618 619 620 621 622
  | 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)

623 624
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpenB' @'(|'@,
  --         'ApiAnnotation.AnnCloseB' @'|)'@
625 626

  -- For details on above see note [Api annotations] in ApiAnnotation
627 628 629 630 631 632 633
  | 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
634

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
635 636 637
  ---------------------------------------
  -- Haskell program coverage (Hpc) Support

Ian Lynagh's avatar
Ian Lynagh committed
638
  | HsTick
639
     (Tickish id)
Ian Lynagh's avatar
Ian Lynagh committed
640
     (LHsExpr id)                       -- sub-expression
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
641 642

  | HsBinTick
Ian Lynagh's avatar
Ian Lynagh committed
643 644 645
     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
646

Alan Zimmerman's avatar
Alan Zimmerman committed
647
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
Alan Zimmerman's avatar
Alan Zimmerman committed
648 649 650
  --       'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@,
  --       'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal',
  --       'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal',
Alan Zimmerman's avatar
Alan Zimmerman committed
651
  --       'ApiAnnotation.AnnMinus',
Alan Zimmerman's avatar
Alan Zimmerman committed
652 653 654
  --       'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon',
  --       'ApiAnnotation.AnnVal',
  --       'ApiAnnotation.AnnClose' @'\#-}'@
655 656

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
657 658
  | HsTickPragma                      -- A pragma introduced tick
     SourceText                       -- Note [Pragma source text] in BasicTypes
659
     (StringLiteral,(Int,Int),(Int,Int))
660
                                      -- external span for this tick
661 662 663
     ((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
664
     (LHsExpr id)
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
665 666 667 668

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

Ian Lynagh's avatar
Ian Lynagh committed
670
  | EWildPat                 -- wildcard
671

Alan Zimmerman's avatar
Alan Zimmerman committed
672
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt'
673 674

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

Alan Zimmerman's avatar
Alan Zimmerman committed
678
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow'
679 680

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

Alan Zimmerman's avatar
Alan Zimmerman committed
684
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
685 686

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

689

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
690 691
  ---------------------------------------
  -- Finally, HsWrap appears only in typechecker output
692 693 694
  -- The contained Expr is *NOT* itself an HsWrap.
  -- See Note [Detecting forced eta expansion] in DsExpr. This invariant
  -- is maintained by HsUtils.mkHsWrap.
695

Ian Lynagh's avatar
Ian Lynagh committed
696 697
  |  HsWrap     HsWrapper    -- TRANSLATION
                (HsExpr id)
698

699
deriving instance (DataId id) => Data (HsExpr id)
700

701 702 703 704 705 706
-- | Located Haskell Tuple Argument
--
-- 'HsTupArg' is used for tuple sections
-- @(,a,)@ is represented by
-- @ExplicitTuple [Missing ty1, Present a, Missing ty3]@
-- Which in turn stands for @(\x:ty1 \y:ty2. (x,a,y))@
707
type LHsTupArg id = Located (HsTupArg id)
Alan Zimmerman's avatar
Alan Zimmerman committed
708
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma'
709 710

-- For details on above see note [Api annotations] in ApiAnnotation
711 712

-- | Haskell Tuple Argument
713
data HsTupArg id
714 715 716
  = 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)
717

718 719 720
tupArgPresent :: LHsTupArg id -> Bool
tupArgPresent (L _ (Present {})) = True
tupArgPresent (L _ (Missing {})) = False
721

Austin Seipp's avatar
Austin Seipp committed
722
{-
723 724 725 726
Note [Parens in HsSyn]
~~~~~~~~~~~~~~~~~~~~~~
HsPar (and ParPat in patterns, HsParTy in types) is used as follows

727
  * HsPar is required; the pretty printer does not add parens.
728 729 730 731

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

732 733 734 735 736 737 738 739 740 741
  * For ParPat and HsParTy the pretty printer does add parens but this should be
    a no-op for ParsedSource, based on the pretty printer round trip feature
    introduced in
    https://phabricator.haskell.org/rGHC499e43824bda967546ebf95ee33ec1f84a114a7c

  * ParPat and HsParTy are pretty printed as '( .. )' regardless of whether or
    not they are strictly necssary. This should be addressed when #13238 is
    completed, to be treated the same as HsPar.


742 743 744
Note [Sections in HsSyn]
~~~~~~~~~~~~~~~~~~~~~~~~
Sections should always appear wrapped in an HsPar, thus
745 746
         HsPar (SectionR ...)
The parser parses sections in a wider variety of situations
747
(See Note [Parsing sections]), but the renamer checks for those
748
parens.  This invariant makes pretty-printing easier; we don't need
749 750
a special case for adding the parens round sections.

751 752 753 754 755 756
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?
757
Because we allow an 'if' to return *unboxed* results, thus
758 759 760 761 762
  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
763 764 765

Note [Record Update HsWrapper]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
766 767 768 769
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
770 771

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

775
  foo = (Just True) { x = False }
Matthew Pickering's avatar
Matthew Pickering committed
776
then `foo` desugars to something like
777 778 779 780
  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
781

782 783 784 785 786 787 788 789 790 791
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
792
-}
793

794
instance (OutputableBndrId id) => Outputable (HsExpr id) where
795
    ppr expr = pprExpr expr
796

797
-----------------------
Ian Lynagh's avatar
Ian Lynagh committed
798
-- pprExpr, pprLExpr, pprBinds call pprDeeper;
799
-- the underscore versions do not
800
pprLExpr :: (OutputableBndrId id) => LHsExpr id -> SDoc
801 802
pprLExpr (L _ e) = pprExpr e

803
pprExpr :: (OutputableBndrId id) => HsExpr id -> SDoc
Ian Lynagh's avatar
Ian Lynagh committed
804 805 806 807 808 809 810
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 (...)
811
isQuietHsExpr (HsPar _)          = True
Ian Lynagh's avatar
Ian Lynagh committed
812
-- applications don't display anything themselves
813 814 815 816
isQuietHsExpr (HsApp _ _)        = True
isQuietHsExpr (HsAppType _ _)    = True
isQuietHsExpr (HsAppTypeOut _ _) = True
isQuietHsExpr (OpApp _ _ _ _)    = True
Ian Lynagh's avatar
Ian Lynagh committed
817
isQuietHsExpr _ = False
818

819
pprBinds :: (OutputableBndrId idL, OutputableBndrId idR)
Ian Lynagh's avatar
Ian Lynagh committed
820
         => HsLocalBindsLR idL idR -> SDoc
821
pprBinds b = pprDeeper (ppr b)
822

823
-----------------------
824
ppr_lexpr :: (OutputableBndrId id) => LHsExpr id -> SDoc
825
ppr_lexpr e = ppr_expr (unLoc e)
826

827
ppr_expr :: forall id. (OutputableBndrId id) => HsExpr id -> SDoc
828
ppr_expr (HsVar (L _ v))  = pprPrefixOcc v
829
ppr_expr (HsUnboundVar uv)= pprPrefixOcc (unboundVarOcc uv)
830
ppr_expr (HsConLikeOut c) = pprPrefixOcc c
831
ppr_expr (HsIPVar v)      = ppr v
832
ppr_expr (HsOverLabel _ l)= char '#' <> ppr l
833 834 835
ppr_expr (HsLit lit)      = ppr lit
ppr_expr (HsOverLit lit)  = ppr lit
ppr_expr (HsPar e)        = parens (ppr_lexpr e)
836

837 838 839 840
ppr_expr (HsCoreAnn stc (StringLiteral sta s) e)
  = vcat [pprWithSourceText stc (text "{-# CORE")
          <+> pprWithSourceText sta (doubleQuotes $ ftext s) <+> text "#-}"
         , ppr_lexpr e]
841

842 843 844
ppr_expr e@(HsApp {})        = ppr_apps e []
ppr_expr e@(HsAppType {})    = ppr_apps e []
ppr_expr e@(HsAppTypeOut {}) = ppr_apps e []
845

Ian Lynagh's avatar
Ian Lynagh committed
846
ppr_expr (OpApp e1 op _ e2)
847 848 849 850 851
  | Just pp_op <- should_print_infix (unLoc op)
  = pp_infixly pp_op
  | otherwise
  = pp_prefixly

852
  where
853 854 855 856 857
    should_print_infix (HsVar (L _ v)) = Just (pprInfixOcc v)
    should_print_infix (HsConLikeOut c)= Just (pprInfixOcc (conLikeName c))
    should_print_infix (HsRecFld f)    = Just (pprInfixOcc f)
    should_print_infix (HsUnboundVar h@TrueExprHole{})
                                       = Just (pprInfixOcc (unboundVarOcc h))
858
    should_print_infix EWildPat        = Just (text "`_`")
859 860 861
    should_print_infix (HsWrap _ e)    = should_print_infix e
    should_print_infix _               = Nothing

Ian Lynagh's avatar
Ian Lynagh committed
862
    pp_e1 = pprDebugParendExpr e1   -- In debug mode, add parens
863
    pp_e2 = pprDebugParendExpr e2   -- to make precedence clear
864 865

    pp_prefixly
866
      = hang (ppr op) 2 (sep [pp_e1, pp_e2])
867

868 869
    pp_infixly pp_op
      = hang pp_e1 2 (sep [pp_op, nest 2 pp_e2])
870

871
ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
872

873
ppr_expr (SectionL expr op)
874
  = case unLoc op of
875 876 877
      HsVar (L _ v)  -> pp_infixly v
      HsConLikeOut c -> pp_infixly (conLikeName c)
      _              -> pp_prefixly
878
  where
879
    pp_expr = pprDebugParendExpr expr
880

881
    pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
882
                       4 (hsep [pp_expr, text "x_ )"])
883
    pp_infixly v = (sep [pp_expr, pprInfixOcc v])
884

885
ppr_expr (SectionR op expr)
886
  = case unLoc op of
887 888 889
      HsVar (L _ v)  -> pp_infixly v
      HsConLikeOut c -> pp_infixly (conLikeName c)
      _              -> pp_prefixly
890
  where
891
    pp_expr = pprDebugParendExpr expr
892

893
    pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, text "x_"])
894
                       4 (pp_expr <> rparen)
895
    pp_infixly v = sep [pprInfixOcc v, pp_expr]
896

897
ppr_expr (ExplicitTuple exprs boxity)
898
  = tupleParens (boxityTupleSort boxity) (fcat (ppr_tup_args $ map unLoc exprs))
899 900 901
  where
    ppr_tup_args []               = []
    ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es
902
    ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es
903 904 905 906 907

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

908 909 910 911 912
ppr_expr (ExplicitSum alt arity expr _)
  = text "(#" <+> ppr_bars (alt - 1) <+> ppr expr <+> ppr_bars (arity - alt) <+> text "#)"
  where
    ppr_bars n = hsep (replicate n (char '|'))

913
ppr_expr (HsLam matches)
914
  = pprMatches matches
915

Simon Peyton Jones's avatar
Simon Peyton Jones committed
916
ppr_expr (HsLamCase matches)
917 918
  = sep [ sep [text "\\case"],
          nest 2 (pprMatches matches) ]
919

920
ppr_expr (HsCase expr matches@(MG { mg_alts = L _ [_] }))
921
  = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")],
922 923 924 925
          nest 2 (pprMatches matches) <+> char '}']
ppr_expr (HsCase expr matches)
  = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of")],
          nest 2 (pprMatches matches) ]
926

927
ppr_expr (HsIf _ e1 e2 e3)
928
  = sep [hsep [text "if", nest 2 (ppr e1), ptext (sLit "then")],
Ian Lynagh's avatar
Ian Lynagh committed
929
         nest 4 (ppr e2),
930
         text "else",
Ian Lynagh's avatar
Ian Lynagh committed
931
         nest 4 (ppr e3)]
932

933
ppr_expr (HsMultiIf _ alts)
934
  = hang (text "if") 3  (vcat (map ppr_alt alts))
935
  where ppr_alt (L _ (GRHS guards expr)) =
936 937 938 939 940 941
          hang vbar 2 (ppr_one one_alt)
          where
            ppr_one [] = panic "ppr_exp HsMultiIf"
            ppr_one (h:t) = hang h 2 (sep t)
            one_alt = [ interpp'SP guards
                      , text "->" <+> pprDeeper (ppr expr) ]
942

943
-- special case: let ... in let ...
944
ppr_expr (HsLet (L _ binds) expr@(L _ (HsLet _ _)))
945
  = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
Ian Lynagh's avatar
Ian Lynagh committed
946
         ppr_lexpr expr]
947

948
ppr_expr (HsLet (L _ binds) expr)
949 950
  = sep [hang (text "let") 2 (pprBinds binds),
         hang (text "in")  2 (ppr expr)]
951

952
ppr_expr (HsDo do_or_list_comp (L _ stmts) _) = pprDo do_or_list_comp stmts
953

954
ppr_expr (ExplicitList _ _ exprs)
955
  = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
956

957
ppr_expr (ExplicitPArr _ exprs)
958
  = paBrackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
959

960
ppr_expr (RecordCon { rcon_con_name = con_id, rcon_flds = rbinds })
Lemmih's avatar
Lemmih committed
961
  = hang (ppr con_id) 2 (ppr rbinds)
962

963
ppr_expr (RecordUpd { rupd_expr = L _ aexp, rupd_flds = rbinds })
964
  = hang (ppr aexp) 2 (braces (fsep (punctuate comma (map ppr rbinds))))
965

966
ppr_expr (ExprWithTySig expr sig)
967
  = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
Ian Lynagh's avatar
Ian Lynagh committed
968
         4 (ppr sig)
969 970
ppr_expr (ExprWithTySigOut expr sig)
  = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
Ian Lynagh's avatar
Ian Lynagh committed
971
         4 (ppr sig)
972

973
ppr_expr (ArithSeq _ _ info) = brackets (ppr info)
974
ppr_expr (PArrSeq  _ info) = paBrackets (ppr info)
975

Ian Lynagh's avatar
Ian Lynagh committed
976
ppr_expr EWildPat       = char '_'
977 978
ppr_expr (ELazyPat e)   = char '~' <> ppr e
ppr_expr (EAsPat v e)   = ppr v <> char '@' <> ppr e
979
ppr_expr (EViewPat p e) = ppr p <+> text "->" <+> ppr e
980

981 982 983 984 985
ppr_expr (HsSCC st (StringLiteral stl lbl) expr)
  = sep [ pprWithSourceText st (text "{-# SCC")
         -- no doublequotes if stl empty, for the case where the SCC was written
         -- without quotes.
          <+> pprWithSourceText stl (ftext lbl) <+> text "#-}",
986
          ppr expr ]
987 988

ppr_expr (HsWrap co_fn e)
989 990
  = pprHsWrapper co_fn (\parens -> if parens then pprExpr e
                                             else pprExpr e)
991

992
ppr_expr (HsSpliceE s)         = pprSplice s
993
ppr_expr (HsBracket b)         = pprHsBracket b
994
ppr_expr (HsRnBracketOut e []) = ppr e
995
ppr_expr (HsRnBracketOut e ps) = ppr e $$ text "pending(rn)" <+> ppr ps
996
ppr_expr (HsTcBracketOut e []) = ppr e
997
ppr_expr (HsTcBracketOut e ps) = ppr e $$ text "pending(tc)" <+> ppr ps
998

999
ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
1000
  = hsep [text "proc", ppr pat, ptext (sLit "->"), ppr cmd]
1001

1002
ppr_expr (HsStatic _ e)
1003
  = hsep [text "static", ppr e]
1004

1005
ppr_expr (HsTick tickish exp)
1006
  = pprTicks (ppr exp) $
Peter Wortmann's avatar
Peter Wortmann committed
1007
    ppr tickish <+> ppr_lexpr exp
andy@galois.com's avatar
andy@galois.com committed
1008
ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
1009
  = pprTicks (ppr exp) $