HsExpr.hs 77.1 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 13

-- | Abstract Haskell syntax for expressions.
14 15
module HsExpr where

16
#include "HsVersions.h"
17 18

-- friends:
19 20 21
import HsDecls
import HsPat
import HsLit
22
import PlaceHolder ( PostTc,PostRn,DataId )
23 24
import HsTypes
import HsBinds
25 26

-- others:
27
import TcEvidence
28
import CoreSyn
29
import Var
30
import RdrName
31 32
import Name
import BasicTypes
33
import DataCon
34
import SrcLoc
35
import Util
36
import StaticFlags( opt_PprStyle_Debug )
Ian Lynagh's avatar
Ian Lynagh committed
37
import Outputable
38
import FastString
39
import Type
40 41 42

-- libraries:
import Data.Data hiding (Fixity)
43

Austin Seipp's avatar
Austin Seipp committed
44 45 46
{-
************************************************************************
*                                                                      *
47
\subsection{Expressions proper}
Austin Seipp's avatar
Austin Seipp committed
48 49 50
*                                                                      *
************************************************************************
-}
51

52 53
-- * Expressions proper

54
type LHsExpr id = Located (HsExpr id)
Alan Zimmerman's avatar
Alan Zimmerman committed
55 56
  -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
  --   in a list
57

58 59
  -- For details on above see note [Api annotations] in ApiAnnotation

60
-------------------------
61 62
-- | PostTcExpr is an evidence expression attached to the syntax tree by the
-- type checker (c.f. postTcType).
63
type PostTcExpr  = HsExpr Id
64 65
-- | We use a PostTcTable where there are a bunch of pieces of evidence, more
-- than is convenient to keep individually.
66
type PostTcTable = [(Name, PostTcExpr)]
67 68

noPostTcExpr :: PostTcExpr
69
noPostTcExpr = HsLit (HsString "" (fsLit "noPostTcExpr"))
70 71 72 73 74

noPostTcTable :: PostTcTable
noPostTcTable = []

-------------------------
75
-- | SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier,
Ian Lynagh's avatar
Ian Lynagh committed
76
-- by the renamer.  It's used for rebindable syntax.
77 78 79
--
-- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for
--      @(>>=)@, and then instantiated by the type checker with its type args
80
--      etc
81 82 83

type SyntaxExpr id = HsExpr id

Ian Lynagh's avatar
Ian Lynagh committed
84 85
noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after,
                              -- (if the syntax slot makes no sense)
86
noSyntaxExpr = HsLit (HsString "" (fsLit "noSyntaxExpr"))
87 88


89 90
type CmdSyntaxTable id = [(Name, SyntaxExpr id)]
-- See Note [CmdSyntaxTable]
91

Austin Seipp's avatar
Austin Seipp committed
92
{-
93 94 95 96 97
Note [CmdSyntaxtable]
~~~~~~~~~~~~~~~~~~~~~
Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps
track of the methods needed for a Cmd.

98
* Before the renamer, this list is an empty list
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125

* 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
126
-}
127

128
-- | A Haskell expression.
129
data HsExpr id
130 131
  = HsVar     id                        -- ^ Variable
  | HsIPVar   HsIPName                  -- ^ Implicit parameter
132
  | HsOverLit (HsOverLit id)            -- ^ Overloaded literals
133

134
  | HsLit     HsLit                     -- ^ Simple (non-overloaded) literals
135

136
  | HsLam     (MatchGroup id (LHsExpr id)) -- ^ Lambda abstraction. Currently always a single match
Alan Zimmerman's avatar
Alan Zimmerman committed
137 138 139
       --
       -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
       --       'ApiAnnotation.AnnRarrow',
140

141 142
       -- For details on above see note [Api annotations] in ApiAnnotation

143
  | HsLamCase (PostTc id Type) (MatchGroup id (LHsExpr id)) -- ^ Lambda-case
Alan Zimmerman's avatar
Alan Zimmerman committed
144 145 146 147
       --
       -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
       --           'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen',
       --           'ApiAnnotation.AnnClose'
Alan Zimmerman's avatar
Alan Zimmerman committed
148

149 150
       -- For details on above see note [Api annotations] in ApiAnnotation

151
  | HsApp     (LHsExpr id) (LHsExpr id) -- ^ Application
152

153
  -- | Operator applications:
154 155
  -- NB Bracketed ops such as (+) come out as Vars.

156 157 158
  -- 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
159 160
  | OpApp       (LHsExpr id)    -- left operand
                (LHsExpr id)    -- operator
161
                (PostRn id Fixity) -- Renamer adds fixity; bottom until then
Ian Lynagh's avatar
Ian Lynagh committed
162 163
                (LHsExpr id)    -- right operand

164
  -- | Negation operator. Contains the negated expression and the name
Alan Zimmerman's avatar
Alan Zimmerman committed
165 166 167
  -- of 'negate'
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus'
168 169

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

Alan Zimmerman's avatar
Alan Zimmerman committed
173 174
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
  --             'ApiAnnotation.AnnClose' @')'@
175 176

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

179
  | SectionL    (LHsExpr id)    -- operand; see Note [Sections in HsSyn]
Ian Lynagh's avatar
Ian Lynagh committed
180
                (LHsExpr id)    -- operator
181
  | SectionR    (LHsExpr id)    -- operator; see Note [Sections in HsSyn]
Ian Lynagh's avatar
Ian Lynagh committed
182 183
                (LHsExpr id)    -- operand

184
  -- | Used for explicit tuples and sections thereof
Alan Zimmerman's avatar
Alan Zimmerman committed
185 186 187
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
  --         'ApiAnnotation.AnnClose'
188 189

  -- For details on above see note [Api annotations] in ApiAnnotation
190 191
  | ExplicitTuple
        [LHsTupArg id]
192 193
        Boxity

Alan Zimmerman's avatar
Alan Zimmerman committed
194
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
Alan Zimmerman's avatar
Alan Zimmerman committed
195 196
  --       'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
  --       'ApiAnnotation.AnnClose' @'}'@
197 198

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

Alan Zimmerman's avatar
Alan Zimmerman committed
202 203
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
  --       'ApiAnnotation.AnnSemi',
Alan Zimmerman's avatar
Alan Zimmerman committed
204
  --       'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
Alan Zimmerman's avatar
Alan Zimmerman committed
205
  --       'ApiAnnotation.AnnElse',
206 207

  -- For details on above see note [Api annotations] in ApiAnnotation
208
  | HsIf        (Maybe (SyntaxExpr id)) -- cond function
209 210
                                        -- Nothing => use the built-in 'if'
                                        -- See Note [Rebindable if]
211
                (LHsExpr id)    --  predicate
Ian Lynagh's avatar
Ian Lynagh committed
212 213 214
                (LHsExpr id)    --  then part
                (LHsExpr id)    --  else part

215
  -- | Multi-way if
Alan Zimmerman's avatar
Alan Zimmerman committed
216 217 218
  --
  -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf'
  --       'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
219 220

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

223
  -- | let(rec)
Alan Zimmerman's avatar
Alan Zimmerman committed
224 225
  --
  -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
Alan Zimmerman's avatar
Alan Zimmerman committed
226 227
  --       'ApiAnnotation.AnnOpen' @'{'@,
  --       'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
228 229

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
230
  | HsLet       (HsLocalBinds id)
Ian Lynagh's avatar
Ian Lynagh committed
231 232
                (LHsExpr  id)

Alan Zimmerman's avatar
Alan Zimmerman committed
233 234 235 236
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
  --             'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
  --             'ApiAnnotation.AnnVbar',
  --             'ApiAnnotation.AnnClose'
237 238

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

245
  -- | Syntactic list: [a,b,c,...]
Alan Zimmerman's avatar
Alan Zimmerman committed
246
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
247 248
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
  --              'ApiAnnotation.AnnClose' @']'@
249 250

  -- For details on above see note [Api annotations] in ApiAnnotation
251 252
  | ExplicitList
                (PostTc id Type)        -- Gives type of components of list
253
                (Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromListN witness
Ian Lynagh's avatar
Ian Lynagh committed
254 255
                [LHsExpr id]

256
  -- | Syntactic parallel array: [:e1, ..., en:]
Alan Zimmerman's avatar
Alan Zimmerman committed
257
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
258
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
Alan Zimmerman's avatar
Alan Zimmerman committed
259 260
  --              'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnComma',
  --              'ApiAnnotation.AnnVbar'
Alan Zimmerman's avatar
Alan Zimmerman committed
261
  --              'ApiAnnotation.AnnClose' @':]'@
262 263

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

268
  -- | Record construction
Alan Zimmerman's avatar
Alan Zimmerman committed
269
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
270 271
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
  --         'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
272 273

  -- For details on above see note [Api annotations] in ApiAnnotation
Ian Lynagh's avatar
Ian Lynagh committed
274 275 276 277 278
  | RecordCon   (Located id)       -- The constructor.  After type checking
                                   -- it's the dataConWrapId of the constructor
                PostTcExpr         -- Data con Id applied to type args
                (HsRecordBinds id)

279
  -- | Record update
Alan Zimmerman's avatar
Alan Zimmerman committed
280
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
281 282
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
  --         'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
283 284

  -- For details on above see note [Api annotations] in ApiAnnotation
Ian Lynagh's avatar
Ian Lynagh committed
285 286
  | RecordUpd   (LHsExpr id)
                (HsRecordBinds id)
287 288
--              (HsMatchGroup Id)  -- Filled in by the type checker to be
--                                 -- a match that does the job
Ian Lynagh's avatar
Ian Lynagh committed
289
                [DataCon]          -- Filled in by the type checker to the
Thomas Schilling's avatar
Thomas Schilling committed
290
                                   -- _non-empty_ list of DataCons that have
Ian Lynagh's avatar
Ian Lynagh committed
291
                                   -- all the upd'd fields
292 293
                [PostTc id Type]   -- Argument types of *input* record type
                [PostTc id Type]   --              and  *output* record type
Ian Lynagh's avatar
Ian Lynagh committed
294 295 296
  -- For a type family, the arg types are of the *instance* tycon,
  -- not the family tycon

Alan Zimmerman's avatar
Alan Zimmerman committed
297 298 299
  -- | Expression with an explicit type signature. @e :: type@
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
300 301

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
302
  | ExprWithTySig
303
                (LHsExpr id)
Ian Lynagh's avatar
Ian Lynagh committed
304
                (LHsType id)
thomasw's avatar
thomasw committed
305 306 307 308
                (PostRn id [Name])      -- After renaming, the list of Names
                                        -- contains the named and unnamed
                                        -- wildcards brought in scope by the
                                        -- signature
Ian Lynagh's avatar
Ian Lynagh committed
309 310 311 312 313 314

  | ExprWithTySigOut                    -- TRANSLATION
                (LHsExpr id)
                (LHsType Name)          -- Retain the signature for
                                        -- round-tripping purposes

315
  -- | Arithmetic sequence
Alan Zimmerman's avatar
Alan Zimmerman committed
316
  --
Alan Zimmerman's avatar
Alan Zimmerman committed
317 318 319
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
  --              'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
  --              'ApiAnnotation.AnnClose' @']'@
320 321

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
322
  | ArithSeq
Ian Lynagh's avatar
Ian Lynagh committed
323
                PostTcExpr
324
                (Maybe (SyntaxExpr id))   -- For OverloadedLists, the fromList witness
Ian Lynagh's avatar
Ian Lynagh committed
325 326
                (ArithSeqInfo id)

327
  -- | Arithmetic sequence for parallel array
Alan Zimmerman's avatar
Alan Zimmerman committed
328 329 330 331 332 333 334
  --
  -- > [:e1..e2:] or [:e1, e2..e3:]
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
  --              'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
  --              'ApiAnnotation.AnnVbar',
  --              'ApiAnnotation.AnnClose' @':]'@
335 336

  -- For details on above see note [Api annotations] in ApiAnnotation
Austin Seipp's avatar
Austin Seipp committed
337
  | PArrSeq
Alan Zimmerman's avatar
Alan Zimmerman committed
338
                PostTcExpr
Ian Lynagh's avatar
Ian Lynagh committed
339 340
                (ArithSeqInfo id)

Alan Zimmerman's avatar
Alan Zimmerman committed
341 342 343
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# SCC'@,
  --             'ApiAnnotation.AnnVal' or 'ApiAnnotation.AnnValStr',
  --              'ApiAnnotation.AnnClose' @'\#-}'@
344 345

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
346 347 348 349 350 351
  | HsSCC       SourceText            -- Note [Pragma source text] in BasicTypes
                FastString            -- "set cost centre" SCC pragma
                (LHsExpr id)          -- expr whose cost is to be measured

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

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
354 355
  | HsCoreAnn   SourceText            -- Note [Pragma source text] in BasicTypes
                FastString            -- hdaume: core annotation
Ian Lynagh's avatar
Ian Lynagh committed
356 357
                (LHsExpr id)

358
  -----------------------------------------------------------
359
  -- MetaHaskell Extensions
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
360

Alan Zimmerman's avatar
Alan Zimmerman committed
361 362 363
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
  --         'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
  --         'ApiAnnotation.AnnClose'
364 365

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

368 369 370 371 372
    -- 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
373

374 375 376 377 378
  | 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
379

Alan Zimmerman's avatar
Alan Zimmerman committed
380 381
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
  --         'ApiAnnotation.AnnClose'
382 383

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

386 387 388
  -----------------------------------------------------------
  -- Arrow notation extension

389
  -- | @proc@ notation for Arrows
Alan Zimmerman's avatar
Alan Zimmerman committed
390 391 392
  --
  --  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc',
  --          'ApiAnnotation.AnnRarrow'
393 394

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

Facundo Domínguez's avatar
Facundo Domínguez committed
399 400
  ---------------------------------------
  -- static pointers extension
Alan Zimmerman's avatar
Alan Zimmerman committed
401
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic',
402 403

  -- For details on above see note [Api annotations] in ApiAnnotation
Facundo Domínguez's avatar
Facundo Domínguez committed
404 405
  | HsStatic    (LHsExpr id)

406 407
  ---------------------------------------
  -- The following are commands, not expressions proper
408
  -- They are only used in the parsing stage and are removed
409
  --    immediately in parser.RdrHsSyn.checkCommand
Alan Zimmerman's avatar
Alan Zimmerman committed
410 411 412 413

  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
  --          'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
  --          'ApiAnnotation.AnnRarrowtail'
414 415

  -- For details on above see note [Api annotations] in ApiAnnotation
416 417 418 419 420 421 422 423 424
  | 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
425 426
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@,
  --         'ApiAnnotation.AnnClose' @'|)'@
427 428

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

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
437 438 439
  ---------------------------------------
  -- Haskell program coverage (Hpc) Support

Ian Lynagh's avatar
Ian Lynagh committed
440
  | HsTick
441
     (Tickish id)
Ian Lynagh's avatar
Ian Lynagh committed
442
     (LHsExpr id)                       -- sub-expression
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
443 444

  | HsBinTick
Ian Lynagh's avatar
Ian Lynagh committed
445 446 447
     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
448

Alan Zimmerman's avatar
Alan Zimmerman committed
449
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
Alan Zimmerman's avatar
Alan Zimmerman committed
450 451 452
  --       'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@,
  --       'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal',
  --       'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal',
Alan Zimmerman's avatar
Alan Zimmerman committed
453
  --       'ApiAnnotation.AnnMinus',
Alan Zimmerman's avatar
Alan Zimmerman committed
454 455 456
  --       'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon',
  --       'ApiAnnotation.AnnVal',
  --       'ApiAnnotation.AnnClose' @'\#-}'@
457 458

  -- For details on above see note [Api annotations] in ApiAnnotation
Alan Zimmerman's avatar
Alan Zimmerman committed
459 460 461
  | HsTickPragma                      -- A pragma introduced tick
     SourceText                       -- Note [Pragma source text] in BasicTypes
     (FastString,(Int,Int),(Int,Int)) -- external span for this tick
Ian Lynagh's avatar
Ian Lynagh committed
462
     (LHsExpr id)
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
463 464 465 466

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

Ian Lynagh's avatar
Ian Lynagh committed
468
  | EWildPat                 -- wildcard
469

Alan Zimmerman's avatar
Alan Zimmerman committed
470
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt'
471 472

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

Alan Zimmerman's avatar
Alan Zimmerman committed
476
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow'
477 478

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

Alan Zimmerman's avatar
Alan Zimmerman committed
482
  -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
483 484

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

Ian Lynagh's avatar
Ian Lynagh committed
487
  | HsType      (LHsType id) -- Explicit type argument; e.g  f {| Int |} x y
488

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
489 490
  ---------------------------------------
  -- Finally, HsWrap appears only in typechecker output
491

Ian Lynagh's avatar
Ian Lynagh committed
492 493
  |  HsWrap     HsWrapper    -- TRANSLATION
                (HsExpr id)
494
  |  HsUnboundVar RdrName
495 496
  deriving (Typeable)
deriving instance (DataId id) => Data (HsExpr id)
497

498
-- | HsTupArg is used for tuple sections
499
--  (,a,) is represented by  ExplicitTuple [Missing ty1, Present a, Missing ty3]
500
--  Which in turn stands for (\x:ty1 \y:ty2. (x,a,y))
501
type LHsTupArg id = Located (HsTupArg id)
Alan Zimmerman's avatar
Alan Zimmerman committed
502
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma'
503 504

-- For details on above see note [Api annotations] in ApiAnnotation
505
data HsTupArg id
506 507 508 509
  = Present (LHsExpr id)     -- ^ The argument
  | Missing (PostTc id Type) -- ^ The argument is missing, but this is its type
  deriving (Typeable)
deriving instance (DataId id) => Data (HsTupArg id)
510

511 512 513
tupArgPresent :: LHsTupArg id -> Bool
tupArgPresent (L _ (Present {})) = True
tupArgPresent (L _ (Missing {})) = False
514

Austin Seipp's avatar
Austin Seipp committed
515
{-
516 517 518 519 520 521 522
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)'

523
  * HsPars are pretty printed as '( .. )' regardless of whether
524 525 526 527 528 529 530 531
    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
532 533
         HsPar (SectionR ...)
The parser parses sections in a wider variety of situations
534
(See Note [Parsing sections]), but the renamer checks for those
535
parens.  This invariant makes pretty-printing easier; we don't need
536 537
a special case for adding the parens round sections.

538 539 540 541 542 543
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?
544
Because we allow an 'if' to return *unboxed* results, thus
545 546 547 548 549
  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".
Austin Seipp's avatar
Austin Seipp committed
550
-}
551

552
instance OutputableBndr id => Outputable (HsExpr id) where
553
    ppr expr = pprExpr expr
554

555
-----------------------
Ian Lynagh's avatar
Ian Lynagh committed
556
-- pprExpr, pprLExpr, pprBinds call pprDeeper;
557 558
-- the underscore versions do not
pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc
559 560 561
pprLExpr (L _ e) = pprExpr e

pprExpr :: OutputableBndr id => HsExpr id -> SDoc
Ian Lynagh's avatar
Ian Lynagh committed
562 563 564 565 566 567 568 569 570 571 572 573
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 (...)
isQuietHsExpr (HsPar _) = True
-- applications don't display anything themselves
isQuietHsExpr (HsApp _ _) = True
isQuietHsExpr (OpApp _ _ _ _) = True
isQuietHsExpr _ = False
574

Ian Lynagh's avatar
Ian Lynagh committed
575 576
pprBinds :: (OutputableBndr idL, OutputableBndr idR)
         => HsLocalBindsLR idL idR -> SDoc
577
pprBinds b = pprDeeper (ppr b)
578

579
-----------------------
580 581
ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc
ppr_lexpr e = ppr_expr (unLoc e)
582

583
ppr_expr :: forall id. OutputableBndr id => HsExpr id -> SDoc
584
ppr_expr (HsVar v)       = pprPrefixOcc v
585
ppr_expr (HsIPVar v)     = ppr v
586 587
ppr_expr (HsLit lit)     = ppr lit
ppr_expr (HsOverLit lit) = ppr lit
Ian Lynagh's avatar
Ian Lynagh committed
588
ppr_expr (HsPar e)       = parens (ppr_lexpr e)
589

Alan Zimmerman's avatar
Alan Zimmerman committed
590
ppr_expr (HsCoreAnn _ s e)
Ian Lynagh's avatar
Ian Lynagh committed
591
  = vcat [ptext (sLit "HsCoreAnn") <+> ftext s, ppr_lexpr e]
592

593 594
ppr_expr (HsApp e1 e2)
  = let (fun, args) = collect_args e1 [e2] in
595
    hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args))
596
  where
597 598
    collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args)
    collect_args fun args = (fun, args)
599

Ian Lynagh's avatar
Ian Lynagh committed
600
ppr_expr (OpApp e1 op _ e2)
601
  = case unLoc op of
602
      HsVar v -> pp_infixly v
Ian Lynagh's avatar
Ian Lynagh committed
603
      _       -> pp_prefixly
604
  where
Ian Lynagh's avatar
Ian Lynagh committed
605
    pp_e1 = pprDebugParendExpr e1   -- In debug mode, add parens
606
    pp_e2 = pprDebugParendExpr e2   -- to make precedence clear
607 608

    pp_prefixly
609
      = hang (ppr op) 2 (sep [pp_e1, pp_e2])
610 611

    pp_infixly v
612
      = sep [pp_e1, sep [pprInfixOcc v, nest 2 pp_e2]]
613

614
ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
615

616
ppr_expr (SectionL expr op)
617
  = case unLoc op of
618
      HsVar v -> pp_infixly v
Ian Lynagh's avatar
Ian Lynagh committed
619
      _       -> pp_prefixly
620
  where
621
    pp_expr = pprDebugParendExpr expr
622

623
    pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
Ian Lynagh's avatar
Ian Lynagh committed
624
                       4 (hsep [pp_expr, ptext (sLit "x_ )")])
625
    pp_infixly v = (sep [pp_expr, pprInfixOcc v])
626

627
ppr_expr (SectionR op expr)
628
  = case unLoc op of
629
      HsVar v -> pp_infixly v
Ian Lynagh's avatar
Ian Lynagh committed
630
      _       -> pp_prefixly
631
  where
632
    pp_expr = pprDebugParendExpr expr
633

Ian Lynagh's avatar
Ian Lynagh committed
634
    pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext (sLit "x_")])
635
                       4 (pp_expr <> rparen)
636
    pp_infixly v = sep [pprInfixOcc v, pp_expr]
637

638
ppr_expr (ExplicitTuple exprs boxity)
639 640
  = tupleParens (boxityNormalTupleSort boxity)
                (fcat (ppr_tup_args $ map unLoc exprs))
641 642 643
  where
    ppr_tup_args []               = []
    ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es
644
    ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es
645 646 647 648 649

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

650
--avoid using PatternSignatures for stage1 code portability
651 652
ppr_expr (HsLam matches)
  = pprMatches (LambdaExpr :: HsMatchContext id) matches
653

654 655 656 657
ppr_expr (HsLamCase _ matches)
  = sep [ sep [ptext (sLit "\\case {")],
          nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ]

658
ppr_expr (HsCase expr matches)
659
  = sep [ sep [ptext (sLit "case"), nest 4 (ppr expr), ptext (sLit "of {")],
660
          nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ]
661

662
ppr_expr (HsIf _ e1 e2 e3)
Ian Lynagh's avatar
Ian Lynagh committed
663
  = sep [hsep [ptext (sLit "if"), nest 2 (ppr e1), ptext (sLit "then")],
Ian Lynagh's avatar
Ian Lynagh committed
664
         nest 4 (ppr e2),
Ian Lynagh's avatar
Ian Lynagh committed
665
         ptext (sLit "else"),
Ian Lynagh's avatar
Ian Lynagh committed
666
         nest 4 (ppr e3)]
667

668 669 670 671 672 673
ppr_expr (HsMultiIf _ alts)
  = sep $ ptext (sLit "if") : map ppr_alt alts
  where ppr_alt (L _ (GRHS guards expr)) =
          sep [ char '|' <+> interpp'SP guards
              , ptext (sLit "->") <+> pprDeeper (ppr expr) ]

674
-- special case: let ... in let ...
675
ppr_expr (HsLet binds expr@(L _ (HsLet _ _)))
Ian Lynagh's avatar
Ian Lynagh committed
676
  = sep [hang (ptext (sLit "let")) 2 (hsep [pprBinds binds, ptext (sLit "in")]),
Ian Lynagh's avatar
Ian Lynagh committed
677
         ppr_lexpr expr]
678

679
ppr_expr (HsLet binds expr)
Ian Lynagh's avatar
Ian Lynagh committed
680 681
  = sep [hang (ptext (sLit "let")) 2 (pprBinds binds),
         hang (ptext (sLit "in"))  2 (ppr expr)]
682

683
ppr_expr (HsDo do_or_list_comp stmts _) = pprDo do_or_list_comp stmts
684

685
ppr_expr (ExplicitList _ _ exprs)
686
  = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
687

chak's avatar
chak committed
688
ppr_expr (ExplicitPArr _ exprs)
689
  = paBrackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
chak's avatar
chak committed
690

Ian Lynagh's avatar
Ian Lynagh committed
691
ppr_expr (RecordCon con_id _ rbinds)
692
  = hang (ppr con_id) 2 (ppr rbinds)
693

694
ppr_expr (RecordUpd aexp rbinds _ _ _)
695
  = hang (pprLExpr aexp) 2 (ppr rbinds)
696

thomasw's avatar
thomasw committed
697
ppr_expr (ExprWithTySig expr sig _)
698
  = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
Ian Lynagh's avatar
Ian Lynagh committed
699
         4 (ppr sig)
700 701
ppr_expr (ExprWithTySigOut expr sig)
  = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
Ian Lynagh's avatar
Ian Lynagh committed
702
         4 (ppr sig)
703

704
ppr_expr (ArithSeq _ _ info) = brackets (ppr info)
705
ppr_expr (PArrSeq  _ info) = paBrackets (ppr info)
chak's avatar
chak committed
706

Ian Lynagh's avatar
Ian Lynagh committed
707 708 709
ppr_expr EWildPat       = char '_'
ppr_expr (ELazyPat e)   = char '~' <> pprParendExpr e
ppr_expr (EAsPat v e)   = ppr v <> char '@' <> pprParendExpr e
Ian Lynagh's avatar
Ian Lynagh committed
710
ppr_expr (EViewPat p e) = ppr p <+> ptext (sLit "->") <+> ppr e
711

Alan Zimmerman's avatar
Alan Zimmerman committed
712
ppr_expr (HsSCC _ lbl expr)
713
  = sep [ ptext (sLit "{-# SCC") <+> doubleQuotes (ftext lbl) <+> ptext (sLit "#-}"),
Ian Lynagh's avatar
Ian Lynagh committed
714
          pprParendExpr expr ]
715

716
ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn
Ian Lynagh's avatar
Ian Lynagh committed
717
ppr_expr (HsType id)      = ppr id
chak's avatar
chak committed
718

719
ppr_expr (HsSpliceE s)         = pprSplice s
720
ppr_expr (HsBracket b)         = pprHsBracket b
721 722
ppr_expr (HsRnBracketOut e []) = ppr e
ppr_expr (HsRnBracketOut e ps) = ppr e $$ ptext (sLit "pending(rn)") <+> ppr ps
723 724
ppr_expr (HsTcBracketOut e []) = ppr e
ppr_expr (HsTcBracketOut e ps) = ppr e $$ ptext (sLit "pending(tc)") <+> ppr ps
725

726
ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
Ian Lynagh's avatar
Ian Lynagh committed
727
  = hsep [ptext (sLit "proc"), ppr pat, ptext (sLit "->"), ppr cmd]
728

Facundo Domínguez's avatar
Facundo Domínguez committed
729 730 731
ppr_expr (HsStatic e)
  = hsep [ptext (sLit "static"), pprParendExpr e]

732
ppr_expr (HsTick tickish exp)
733
  = pprTicks (ppr exp) $
Peter Wortmann's avatar
Peter Wortmann committed
734
    ppr tickish <+> ppr_lexpr exp
andy@galois.com's avatar
andy@galois.com committed
735
ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
736 737
  = pprTicks (ppr exp) $
    hcat [ptext (sLit "bintick<"),
Ian Lynagh's avatar
Ian Lynagh committed
738
          ppr tickIdTrue,
Ian Lynagh's avatar
Ian Lynagh committed
739
          ptext (sLit ","),
Ian Lynagh's avatar
Ian Lynagh committed
740
          ppr tickIdFalse,
Ian Lynagh's avatar
Ian Lynagh committed
741 742
          ptext (sLit ">("),
          ppr exp,ptext (sLit ")")]
Alan Zimmerman's avatar
Alan Zimmerman committed
743
ppr_expr (HsTickPragma _ externalSrcLoc exp)
744 745
  = pprTicks (ppr exp) $
    hcat [ptext (sLit "tickpragma<"),
Ian Lynagh's avatar
Ian Lynagh committed
746
          ppr externalSrcLoc,
Ian Lynagh's avatar
Ian Lynagh committed
747
          ptext (sLit ">("),
Ian Lynagh's avatar
Ian Lynagh committed
748
          ppr exp,
Ian Lynagh's avatar
Ian Lynagh committed
749
          ptext (sLit ")")]
andy@galois.com's avatar
andy@galois.com committed
750

751
ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
752
  = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
753
ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
754
  = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
755
ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
756
  = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
757
ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
758
  = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
759

760
ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
761
  = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]]
762
ppr_expr (HsArrForm op _ args)
763 764
  = hang (ptext (sLit "(|") <+> ppr_lexpr op)
         4 (sep (map (pprCmdArg.unLoc) args) <+> ptext (sLit "|)"))
765 766
ppr_expr (HsUnboundVar nm)
  = ppr nm
767

Austin Seipp's avatar
Austin Seipp committed
768
{-
769 770