Fix derived Ix instances for one-constructor GADTs
[ghc.git] / compiler / hsSyn / HsExpr.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 -}
5
6 {-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-}
7 {-# LANGUAGE StandaloneDeriving #-}
8 {-# LANGUAGE FlexibleContexts #-}
9 {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
10 -- in module PlaceHolder
11 {-# LANGUAGE ConstraintKinds #-}
12 {-# LANGUAGE ExistentialQuantification #-}
13 {-# LANGUAGE DeriveFunctor #-}
14
15 -- | Abstract Haskell syntax for expressions.
16 module HsExpr where
17
18 #include "HsVersions.h"
19
20 -- friends:
21 import HsDecls
22 import HsPat
23 import HsLit
24 import PlaceHolder ( PostTc,PostRn,DataId,DataIdPost,
25 NameOrRdrName,OutputableBndrId )
26 import HsTypes
27 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
38 import ConLike
39 import SrcLoc
40 import Util
41 import StaticFlags( opt_PprStyle_Debug )
42 import Outputable
43 import FastString
44 import Type
45
46 -- libraries:
47 import Data.Data hiding (Fixity(..))
48 import qualified Data.Data as Data (Fixity(..))
49 import Data.Maybe (isNothing)
50
51 #ifdef GHCI
52 import GHCi.RemoteTypes ( ForeignRef )
53 import qualified Language.Haskell.TH as TH (Q)
54 #endif
55
56 {-
57 ************************************************************************
58 * *
59 \subsection{Expressions proper}
60 * *
61 ************************************************************************
62 -}
63
64 -- * Expressions proper
65
66 -- | Located Haskell Expression
67 type LHsExpr id = Located (HsExpr id)
68 -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
69 -- in a list
70
71 -- For details on above see note [Api annotations] in ApiAnnotation
72
73 -------------------------
74 -- | Post-Type checking Expression
75 --
76 -- PostTcExpr is an evidence expression attached to the syntax tree by the
77 -- type checker (c.f. postTcType).
78 type PostTcExpr = HsExpr Id
79
80 -- | Post-Type checking Table
81 --
82 -- We use a PostTcTable where there are a bunch of pieces of evidence, more
83 -- than is convenient to keep individually.
84 type PostTcTable = [(Name, PostTcExpr)]
85
86 noPostTcExpr :: PostTcExpr
87 noPostTcExpr = HsLit (HsString "" (fsLit "noPostTcExpr"))
88
89 noPostTcTable :: PostTcTable
90 noPostTcTable = []
91
92 -------------------------
93 -- | Syntax Expression
94 --
95 -- SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier,
96 -- by the renamer. It's used for rebindable syntax.
97 --
98 -- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for
99 -- @(>>=)@, and then instantiated by the type checker with its type args
100 -- etc
101 --
102 -- This should desugar to
103 --
104 -- > syn_res_wrap $ syn_expr (syn_arg_wraps[0] arg0)
105 -- > (syn_arg_wraps[1] arg1) ...
106 --
107 -- where the actual arguments come from elsewhere in the AST.
108 -- This could be defined using @PostRn@ and @PostTc@ and such, but it's
109 -- harder to get it all to work out that way. ('noSyntaxExpr' is hard to
110 -- write, for example.)
111 data SyntaxExpr id = SyntaxExpr { syn_expr :: HsExpr id
112 , syn_arg_wraps :: [HsWrapper]
113 , syn_res_wrap :: HsWrapper }
114 deriving instance (DataId id) => Data (SyntaxExpr id)
115
116 -- | This is used for rebindable-syntax pieces that are too polymorphic
117 -- for tcSyntaxOp (trS_fmap and the mzip in ParStmt)
118 noExpr :: HsExpr id
119 noExpr = HsLit (HsString "" (fsLit "noExpr"))
120
121 noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after,
122 -- (if the syntax slot makes no sense)
123 noSyntaxExpr = SyntaxExpr { syn_expr = HsLit (HsString "" (fsLit "noSyntaxExpr"))
124 , syn_arg_wraps = []
125 , syn_res_wrap = WpHole }
126
127 -- | Make a 'SyntaxExpr Name' (the "rn" is because this is used in the
128 -- renamer), missing its HsWrappers.
129 mkRnSyntaxExpr :: Name -> SyntaxExpr Name
130 mkRnSyntaxExpr name = SyntaxExpr { syn_expr = HsVar $ noLoc name
131 , syn_arg_wraps = []
132 , syn_res_wrap = WpHole }
133 -- don't care about filling in syn_arg_wraps because we're clearly
134 -- not past the typechecker
135
136 instance (OutputableBndrId id) => Outputable (SyntaxExpr id) where
137 ppr (SyntaxExpr { syn_expr = expr
138 , syn_arg_wraps = arg_wraps
139 , syn_res_wrap = res_wrap })
140 = sdocWithDynFlags $ \ dflags ->
141 getPprStyle $ \s ->
142 if debugStyle s || gopt Opt_PrintExplicitCoercions dflags
143 then ppr expr <> braces (pprWithCommas ppr arg_wraps)
144 <> braces (ppr res_wrap)
145 else ppr expr
146
147 -- | Command Syntax Table (for Arrow syntax)
148 type CmdSyntaxTable id = [(Name, HsExpr id)]
149 -- See Note [CmdSyntaxTable]
150
151 {-
152 Note [CmdSyntaxtable]
153 ~~~~~~~~~~~~~~~~~~~~~
154 Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps
155 track of the methods needed for a Cmd.
156
157 * Before the renamer, this list is an empty list
158
159 * After the renamer, it takes the form @[(std_name, HsVar actual_name)]@
160 For example, for the 'arr' method
161 * normal case: (GHC.Control.Arrow.arr, HsVar GHC.Control.Arrow.arr)
162 * with rebindable syntax: (GHC.Control.Arrow.arr, arr_22)
163 where @arr_22@ is whatever 'arr' is in scope
164
165 * After the type checker, it takes the form [(std_name, <expression>)]
166 where <expression> is the evidence for the method. This evidence is
167 instantiated with the class, but is still polymorphic in everything
168 else. For example, in the case of 'arr', the evidence has type
169 forall b c. (b->c) -> a b c
170 where 'a' is the ambient type of the arrow. This polymorphism is
171 important because the desugarer uses the same evidence at multiple
172 different types.
173
174 This is Less Cool than what we normally do for rebindable syntax, which is to
175 make fully-instantiated piece of evidence at every use site. The Cmd way
176 is Less Cool because
177 * The renamer has to predict which methods are needed.
178 See the tedious RnExpr.methodNamesCmd.
179
180 * The desugarer has to know the polymorphic type of the instantiated
181 method. This is checked by Inst.tcSyntaxName, but is less flexible
182 than the rest of rebindable syntax, where the type is less
183 pre-ordained. (And this flexibility is useful; for example we can
184 typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.)
185 -}
186
187 -- | An unbound variable; used for treating out-of-scope variables as
188 -- expression holes
189 data UnboundVar
190 = OutOfScope OccName GlobalRdrEnv -- ^ An (unqualified) out-of-scope
191 -- variable, together with the GlobalRdrEnv
192 -- with respect to which it is unbound
193
194 -- See Note [OutOfScope and GlobalRdrEnv]
195
196 | TrueExprHole OccName -- ^ A "true" expression hole (_ or _x)
197
198 deriving Data
199
200 instance Outputable UnboundVar where
201 ppr = ppr . unboundVarOcc
202
203 unboundVarOcc :: UnboundVar -> OccName
204 unboundVarOcc (OutOfScope occ _) = occ
205 unboundVarOcc (TrueExprHole occ) = occ
206
207 {-
208 Note [OutOfScope and GlobalRdrEnv]
209 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
210 To understand why we bundle a GlobalRdrEnv with an out-of-scope variable,
211 consider the following module:
212
213 module A where
214
215 foo :: ()
216 foo = bar
217
218 bat :: [Double]
219 bat = [1.2, 3.4]
220
221 $(return [])
222
223 bar = ()
224 bad = False
225
226 When A is compiled, the renamer determines that `bar` is not in scope in the
227 declaration of `foo` (since `bar` is declared in the following inter-splice
228 group). Once it has finished typechecking the entire module, the typechecker
229 then generates the associated error message, which specifies both the type of
230 `bar` and a list of possible in-scope alternatives:
231
232 A.hs:6:7: error:
233 • Variable not in scope: bar :: ()
234 • ‘bar’ (line 13) is not in scope before the splice on line 11
235 Perhaps you meant ‘bat’ (line 9)
236
237 When it calls RnEnv.unknownNameSuggestions to identify these alternatives, the
238 typechecker must provide a GlobalRdrEnv. If it provided the current one, which
239 contains top-level declarations for the entire module, the error message would
240 incorrectly suggest the out-of-scope `bar` and `bad` as possible alternatives
241 for `bar` (see Trac #11680). Instead, the typechecker must use the same
242 GlobalRdrEnv the renamer used when it determined that `bar` is out-of-scope.
243
244 To obtain this GlobalRdrEnv, can the typechecker simply use the out-of-scope
245 `bar`'s location to either reconstruct it (from the current GlobalRdrEnv) or to
246 look it up in some global store? Unfortunately, no. The problem is that
247 location information is not always sufficient for this task. This is most
248 apparent when dealing with the TH function addTopDecls, which adds its
249 declarations to the FOLLOWING inter-splice group. Consider these declarations:
250
251 ex9 = cat -- cat is NOT in scope here
252
253 $(do -------------------------------------------------------------
254 ds <- [d| f = cab -- cat and cap are both in scope here
255 cat = ()
256 |]
257 addTopDecls ds
258 [d| g = cab -- only cap is in scope here
259 cap = True
260 |])
261
262 ex10 = cat -- cat is NOT in scope here
263
264 $(return []) -----------------------------------------------------
265
266 ex11 = cat -- cat is in scope
267
268 Here, both occurrences of `cab` are out-of-scope, and so the typechecker needs
269 the GlobalRdrEnvs which were used when they were renamed. These GlobalRdrEnvs
270 are different (`cat` is present only in the GlobalRdrEnv for f's `cab'), but the
271 locations of the two `cab`s are the same (they are both created in the same
272 splice). Thus, we must include some additional information with each `cab` to
273 allow the typechecker to obtain the correct GlobalRdrEnv. Clearly, the simplest
274 information to use is the GlobalRdrEnv itself.
275 -}
276
277 -- | A Haskell expression.
278 data HsExpr id
279 = HsVar (Located id) -- ^ Variable
280
281 -- See Note [Located RdrNames]
282
283 | HsUnboundVar UnboundVar -- ^ Unbound variable; also used for "holes"
284 -- (_ or _x).
285 -- Turned from HsVar to HsUnboundVar by the
286 -- renamer, when it finds an out-of-scope
287 -- variable or hole.
288 -- Turned into HsVar by type checker, to support
289 -- deferred type errors.
290
291 | HsRecFld (AmbiguousFieldOcc id) -- ^ Variable pointing to record selector
292
293 | HsOverLabel FastString -- ^ Overloaded label (See Note [Overloaded labels]
294 -- in GHC.OverloadedLabels)
295 | HsIPVar HsIPName -- ^ Implicit parameter
296 | HsOverLit (HsOverLit id) -- ^ Overloaded literals
297
298 | HsLit HsLit -- ^ Simple (non-overloaded) literals
299
300 | HsLam (MatchGroup id (LHsExpr id)) -- ^ Lambda abstraction. Currently always a single match
301 --
302 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
303 -- 'ApiAnnotation.AnnRarrow',
304
305 -- For details on above see note [Api annotations] in ApiAnnotation
306
307 | HsLamCase (MatchGroup id (LHsExpr id)) -- ^ Lambda-case
308 --
309 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
310 -- 'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen',
311 -- 'ApiAnnotation.AnnClose'
312
313 -- For details on above see note [Api annotations] in ApiAnnotation
314
315 | HsApp (LHsExpr id) (LHsExpr id) -- ^ Application
316
317 | HsAppType (LHsExpr id) (LHsWcType id) -- ^ Visible type application
318 --
319 -- Explicit type argument; e.g f @Int x y
320 -- NB: Has wildcards, but no implicit quantification
321 --
322 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt',
323
324 | HsAppTypeOut (LHsExpr id) (LHsWcType Name) -- just for pretty-printing
325
326
327 -- | Operator applications:
328 -- NB Bracketed ops such as (+) come out as Vars.
329
330 -- NB We need an expr for the operator in an OpApp/Section since
331 -- the typechecker may need to apply the operator to a few types.
332
333 | OpApp (LHsExpr id) -- left operand
334 (LHsExpr id) -- operator
335 (PostRn id Fixity) -- Renamer adds fixity; bottom until then
336 (LHsExpr id) -- right operand
337
338 -- | Negation operator. Contains the negated expression and the name
339 -- of 'negate'
340 --
341 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus'
342
343 -- For details on above see note [Api annotations] in ApiAnnotation
344 | NegApp (LHsExpr id)
345 (SyntaxExpr id)
346
347 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
348 -- 'ApiAnnotation.AnnClose' @')'@
349
350 -- For details on above see note [Api annotations] in ApiAnnotation
351 | HsPar (LHsExpr id) -- ^ Parenthesised expr; see Note [Parens in HsSyn]
352
353 | SectionL (LHsExpr id) -- operand; see Note [Sections in HsSyn]
354 (LHsExpr id) -- operator
355 | SectionR (LHsExpr id) -- operator; see Note [Sections in HsSyn]
356 (LHsExpr id) -- operand
357
358 -- | Used for explicit tuples and sections thereof
359 --
360 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
361 -- 'ApiAnnotation.AnnClose'
362
363 -- For details on above see note [Api annotations] in ApiAnnotation
364 | ExplicitTuple
365 [LHsTupArg id]
366 Boxity
367
368 | ExplicitSum
369 ConTag -- Alternative (one-based)
370 Arity -- Sum arity
371 (LHsExpr id)
372 (PostTc id [Type]) -- the type arguments
373
374 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
375 -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
376 -- 'ApiAnnotation.AnnClose' @'}'@
377
378 -- For details on above see note [Api annotations] in ApiAnnotation
379 | HsCase (LHsExpr id)
380 (MatchGroup id (LHsExpr id))
381
382 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
383 -- 'ApiAnnotation.AnnSemi',
384 -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
385 -- 'ApiAnnotation.AnnElse',
386
387 -- For details on above see note [Api annotations] in ApiAnnotation
388 | HsIf (Maybe (SyntaxExpr id)) -- cond function
389 -- Nothing => use the built-in 'if'
390 -- See Note [Rebindable if]
391 (LHsExpr id) -- predicate
392 (LHsExpr id) -- then part
393 (LHsExpr id) -- else part
394
395 -- | Multi-way if
396 --
397 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf'
398 -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
399
400 -- For details on above see note [Api annotations] in ApiAnnotation
401 | HsMultiIf (PostTc id Type) [LGRHS id (LHsExpr id)]
402
403 -- | let(rec)
404 --
405 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
406 -- 'ApiAnnotation.AnnOpen' @'{'@,
407 -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
408
409 -- For details on above see note [Api annotations] in ApiAnnotation
410 | HsLet (Located (HsLocalBinds id))
411 (LHsExpr id)
412
413 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
414 -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
415 -- 'ApiAnnotation.AnnVbar',
416 -- 'ApiAnnotation.AnnClose'
417
418 -- For details on above see note [Api annotations] in ApiAnnotation
419 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
420 -- because in this context we never use
421 -- the PatGuard or ParStmt variant
422 (Located [ExprLStmt id]) -- "do":one or more stmts
423 (PostTc id Type) -- Type of the whole expression
424
425 -- | Syntactic list: [a,b,c,...]
426 --
427 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
428 -- 'ApiAnnotation.AnnClose' @']'@
429
430 -- For details on above see note [Api annotations] in ApiAnnotation
431 | ExplicitList
432 (PostTc id Type) -- Gives type of components of list
433 (Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromListN witness
434 [LHsExpr id]
435
436 -- | Syntactic parallel array: [:e1, ..., en:]
437 --
438 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
439 -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnComma',
440 -- 'ApiAnnotation.AnnVbar'
441 -- 'ApiAnnotation.AnnClose' @':]'@
442
443 -- For details on above see note [Api annotations] in ApiAnnotation
444 | ExplicitPArr
445 (PostTc id Type) -- type of elements of the parallel array
446 [LHsExpr id]
447
448 -- | Record construction
449 --
450 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
451 -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
452
453 -- For details on above see note [Api annotations] in ApiAnnotation
454 | RecordCon
455 { rcon_con_name :: Located id -- The constructor name;
456 -- not used after type checking
457 , rcon_con_like :: PostTc id ConLike -- The data constructor or pattern synonym
458 , rcon_con_expr :: PostTcExpr -- Instantiated constructor function
459 , rcon_flds :: HsRecordBinds id } -- The fields
460
461 -- | Record update
462 --
463 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
464 -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
465
466 -- For details on above see note [Api annotations] in ApiAnnotation
467 | RecordUpd
468 { rupd_expr :: LHsExpr id
469 , rupd_flds :: [LHsRecUpdField id]
470 , rupd_cons :: PostTc id [ConLike]
471 -- Filled in by the type checker to the
472 -- _non-empty_ list of DataCons that have
473 -- all the upd'd fields
474
475 , rupd_in_tys :: PostTc id [Type] -- Argument types of *input* record type
476 , rupd_out_tys :: PostTc id [Type] -- and *output* record type
477 -- The original type can be reconstructed
478 -- with conLikeResTy
479 , rupd_wrap :: PostTc id HsWrapper -- See note [Record Update HsWrapper]
480 }
481 -- For a type family, the arg types are of the *instance* tycon,
482 -- not the family tycon
483
484 -- | Expression with an explicit type signature. @e :: type@
485 --
486 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
487
488 -- For details on above see note [Api annotations] in ApiAnnotation
489 | ExprWithTySig
490 (LHsExpr id)
491 (LHsSigWcType id)
492
493 | ExprWithTySigOut -- Post typechecking
494 (LHsExpr id)
495 (LHsSigWcType Name) -- Retain the signature,
496 -- as HsSigType Name, for
497 -- round-tripping purposes
498
499 -- | Arithmetic sequence
500 --
501 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
502 -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
503 -- 'ApiAnnotation.AnnClose' @']'@
504
505 -- For details on above see note [Api annotations] in ApiAnnotation
506 | ArithSeq
507 PostTcExpr
508 (Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromList witness
509 (ArithSeqInfo id)
510
511 -- | Arithmetic sequence for parallel array
512 --
513 -- > [:e1..e2:] or [:e1, e2..e3:]
514 --
515 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
516 -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
517 -- 'ApiAnnotation.AnnVbar',
518 -- 'ApiAnnotation.AnnClose' @':]'@
519
520 -- For details on above see note [Api annotations] in ApiAnnotation
521 | PArrSeq
522 PostTcExpr
523 (ArithSeqInfo id)
524
525 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# SCC'@,
526 -- 'ApiAnnotation.AnnVal' or 'ApiAnnotation.AnnValStr',
527 -- 'ApiAnnotation.AnnClose' @'\#-}'@
528
529 -- For details on above see note [Api annotations] in ApiAnnotation
530 | HsSCC SourceText -- Note [Pragma source text] in BasicTypes
531 StringLiteral -- "set cost centre" SCC pragma
532 (LHsExpr id) -- expr whose cost is to be measured
533
534 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CORE'@,
535 -- 'ApiAnnotation.AnnVal', 'ApiAnnotation.AnnClose' @'\#-}'@
536
537 -- For details on above see note [Api annotations] in ApiAnnotation
538 | HsCoreAnn SourceText -- Note [Pragma source text] in BasicTypes
539 StringLiteral -- hdaume: core annotation
540 (LHsExpr id)
541
542 -----------------------------------------------------------
543 -- MetaHaskell Extensions
544
545 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
546 -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
547 -- 'ApiAnnotation.AnnClose'
548
549 -- For details on above see note [Api annotations] in ApiAnnotation
550 | HsBracket (HsBracket id)
551
552 -- See Note [Pending Splices]
553 | HsRnBracketOut
554 (HsBracket Name) -- Output of the renamer is the *original* renamed
555 -- expression, plus
556 [PendingRnSplice] -- _renamed_ splices to be type checked
557
558 | HsTcBracketOut
559 (HsBracket Name) -- Output of the type checker is the *original*
560 -- renamed expression, plus
561 [PendingTcSplice] -- _typechecked_ splices to be
562 -- pasted back in by the desugarer
563
564 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
565 -- 'ApiAnnotation.AnnClose'
566
567 -- For details on above see note [Api annotations] in ApiAnnotation
568 | HsSpliceE (HsSplice id)
569
570 -----------------------------------------------------------
571 -- Arrow notation extension
572
573 -- | @proc@ notation for Arrows
574 --
575 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc',
576 -- 'ApiAnnotation.AnnRarrow'
577
578 -- For details on above see note [Api annotations] in ApiAnnotation
579 | HsProc (LPat id) -- arrow abstraction, proc
580 (LHsCmdTop id) -- body of the abstraction
581 -- always has an empty stack
582
583 ---------------------------------------
584 -- static pointers extension
585 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic',
586
587 -- For details on above see note [Api annotations] in ApiAnnotation
588 | HsStatic (PostRn id NameSet) -- Free variables of the body
589 (LHsExpr id) -- Body
590
591 ---------------------------------------
592 -- The following are commands, not expressions proper
593 -- They are only used in the parsing stage and are removed
594 -- immediately in parser.RdrHsSyn.checkCommand
595
596 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
597 -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
598 -- 'ApiAnnotation.AnnRarrowtail'
599
600 -- For details on above see note [Api annotations] in ApiAnnotation
601 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
602 (LHsExpr id) -- arrow expression, f
603 (LHsExpr id) -- input expression, arg
604 (PostTc id Type) -- type of the arrow expressions f,
605 -- of the form a t t', where arg :: t
606 HsArrAppType -- higher-order (-<<) or first-order (-<)
607 Bool -- True => right-to-left (f -< arg)
608 -- False => left-to-right (arg >- f)
609
610 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@,
611 -- 'ApiAnnotation.AnnClose' @'|)'@
612
613 -- For details on above see note [Api annotations] in ApiAnnotation
614 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
615 (LHsExpr id) -- the operator
616 -- after type-checking, a type abstraction to be
617 -- applied to the type of the local environment tuple
618 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
619 -- were converted from OpApp's by the renamer
620 [LHsCmdTop id] -- argument commands
621
622 ---------------------------------------
623 -- Haskell program coverage (Hpc) Support
624
625 | HsTick
626 (Tickish id)
627 (LHsExpr id) -- sub-expression
628
629 | HsBinTick
630 Int -- module-local tick number for True
631 Int -- module-local tick number for False
632 (LHsExpr id) -- sub-expression
633
634 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
635 -- 'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@,
636 -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal',
637 -- 'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal',
638 -- 'ApiAnnotation.AnnMinus',
639 -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon',
640 -- 'ApiAnnotation.AnnVal',
641 -- 'ApiAnnotation.AnnClose' @'\#-}'@
642
643 -- For details on above see note [Api annotations] in ApiAnnotation
644 | HsTickPragma -- A pragma introduced tick
645 SourceText -- Note [Pragma source text] in BasicTypes
646 (StringLiteral,(Int,Int),(Int,Int))
647 -- external span for this tick
648 ((SourceText,SourceText),(SourceText,SourceText))
649 -- Source text for the four integers used in the span.
650 -- See note [Pragma source text] in BasicTypes
651 (LHsExpr id)
652
653 ---------------------------------------
654 -- These constructors only appear temporarily in the parser.
655 -- The renamer translates them into the Right Thing.
656
657 | EWildPat -- wildcard
658
659 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt'
660
661 -- For details on above see note [Api annotations] in ApiAnnotation
662 | EAsPat (Located id) -- as pattern
663 (LHsExpr id)
664
665 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow'
666
667 -- For details on above see note [Api annotations] in ApiAnnotation
668 | EViewPat (LHsExpr id) -- view pattern
669 (LHsExpr id)
670
671 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
672
673 -- For details on above see note [Api annotations] in ApiAnnotation
674 | ELazyPat (LHsExpr id) -- ~ pattern
675
676
677 ---------------------------------------
678 -- Finally, HsWrap appears only in typechecker output
679
680 | HsWrap HsWrapper -- TRANSLATION
681 (HsExpr id)
682
683 deriving instance (DataId id) => Data (HsExpr id)
684
685 -- | Located Haskell Tuple Argument
686 --
687 -- 'HsTupArg' is used for tuple sections
688 -- @(,a,)@ is represented by
689 -- @ExplicitTuple [Missing ty1, Present a, Missing ty3]@
690 -- Which in turn stands for @(\x:ty1 \y:ty2. (x,a,y))@
691 type LHsTupArg id = Located (HsTupArg id)
692 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma'
693
694 -- For details on above see note [Api annotations] in ApiAnnotation
695
696 -- | Haskell Tuple Argument
697 data HsTupArg id
698 = Present (LHsExpr id) -- ^ The argument
699 | Missing (PostTc id Type) -- ^ The argument is missing, but this is its type
700 deriving instance (DataId id) => Data (HsTupArg id)
701
702 tupArgPresent :: LHsTupArg id -> Bool
703 tupArgPresent (L _ (Present {})) = True
704 tupArgPresent (L _ (Missing {})) = False
705
706 {-
707 Note [Parens in HsSyn]
708 ~~~~~~~~~~~~~~~~~~~~~~
709 HsPar (and ParPat in patterns, HsParTy in types) is used as follows
710
711 * Generally HsPar is optional; the pretty printer adds parens where
712 necessary. Eg (HsApp f (HsApp g x)) is fine, and prints 'f (g x)'
713
714 * HsPars are pretty printed as '( .. )' regardless of whether
715 or not they are strictly necssary
716
717 * HsPars are respected when rearranging operator fixities.
718 So a * (b + c) means what it says (where the parens are an HsPar)
719
720 Note [Sections in HsSyn]
721 ~~~~~~~~~~~~~~~~~~~~~~~~
722 Sections should always appear wrapped in an HsPar, thus
723 HsPar (SectionR ...)
724 The parser parses sections in a wider variety of situations
725 (See Note [Parsing sections]), but the renamer checks for those
726 parens. This invariant makes pretty-printing easier; we don't need
727 a special case for adding the parens round sections.
728
729 Note [Rebindable if]
730 ~~~~~~~~~~~~~~~~~~~~
731 The rebindable syntax for 'if' is a bit special, because when
732 rebindable syntax is *off* we do not want to treat
733 (if c then t else e)
734 as if it was an application (ifThenElse c t e). Why not?
735 Because we allow an 'if' to return *unboxed* results, thus
736 if blah then 3# else 4#
737 whereas that would not be possible using a all to a polymorphic function
738 (because you can't call a polymorphic function at an unboxed type).
739
740 So we use Nothing to mean "use the old built-in typing rule".
741
742 Note [Record Update HsWrapper]
743 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
744 There is a wrapper in RecordUpd which is used for the *required*
745 constraints for pattern synonyms. This wrapper is created in the
746 typechecking and is then directly used in the desugaring without
747 modification.
748
749 For example, if we have the record pattern synonym P,
750 pattern P :: (Show a) => a -> Maybe a
751 pattern P{x} = Just x
752
753 foo = (Just True) { x = False }
754 then `foo` desugars to something like
755 foo = case Just True of
756 P x -> P False
757 hence we need to provide the correct dictionaries to P's matcher on
758 the RHS so that we can build the expression.
759
760 Note [Located RdrNames]
761 ~~~~~~~~~~~~~~~~~~~~~~~
762 A number of syntax elements have seemingly redundant locations attached to them.
763 This is deliberate, to allow transformations making use of the API Annotations
764 to easily correlate a Located Name in the RenamedSource with a Located RdrName
765 in the ParsedSource.
766
767 There are unfortunately enough differences between the ParsedSource and the
768 RenamedSource that the API Annotations cannot be used directly with
769 RenamedSource, so this allows a simple mapping to be used based on the location.
770 -}
771
772 instance (OutputableBndrId id) => Outputable (HsExpr id) where
773 ppr expr = pprExpr expr
774
775 -----------------------
776 -- pprExpr, pprLExpr, pprBinds call pprDeeper;
777 -- the underscore versions do not
778 pprLExpr :: (OutputableBndrId id) => LHsExpr id -> SDoc
779 pprLExpr (L _ e) = pprExpr e
780
781 pprExpr :: (OutputableBndrId id) => HsExpr id -> SDoc
782 pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e
783 | otherwise = pprDeeper (ppr_expr e)
784
785 isQuietHsExpr :: HsExpr id -> Bool
786 -- Parentheses do display something, but it gives little info and
787 -- if we go deeper when we go inside them then we get ugly things
788 -- like (...)
789 isQuietHsExpr (HsPar _) = True
790 -- applications don't display anything themselves
791 isQuietHsExpr (HsApp _ _) = True
792 isQuietHsExpr (HsAppType _ _) = True
793 isQuietHsExpr (HsAppTypeOut _ _) = True
794 isQuietHsExpr (OpApp _ _ _ _) = True
795 isQuietHsExpr _ = False
796
797 pprBinds :: (OutputableBndrId idL, OutputableBndrId idR)
798 => HsLocalBindsLR idL idR -> SDoc
799 pprBinds b = pprDeeper (ppr b)
800
801 -----------------------
802 ppr_lexpr :: (OutputableBndrId id) => LHsExpr id -> SDoc
803 ppr_lexpr e = ppr_expr (unLoc e)
804
805 ppr_expr :: forall id. (OutputableBndrId id) => HsExpr id -> SDoc
806 ppr_expr (HsVar (L _ v)) = pprPrefixOcc v
807 ppr_expr (HsUnboundVar uv)= pprPrefixOcc (unboundVarOcc uv)
808 ppr_expr (HsIPVar v) = ppr v
809 ppr_expr (HsOverLabel l) = char '#' <> ppr l
810 ppr_expr (HsLit lit) = ppr lit
811 ppr_expr (HsOverLit lit) = ppr lit
812 ppr_expr (HsPar e) = parens (ppr_lexpr e)
813
814 ppr_expr (HsCoreAnn _ (StringLiteral _ s) e)
815 = vcat [text "HsCoreAnn" <+> ftext s, ppr_lexpr e]
816
817 ppr_expr e@(HsApp {}) = ppr_apps e []
818 ppr_expr e@(HsAppType {}) = ppr_apps e []
819 ppr_expr e@(HsAppTypeOut {}) = ppr_apps e []
820
821 ppr_expr (OpApp e1 op _ e2)
822 = case unLoc op of
823 HsVar (L _ v) -> pp_infixly v
824 HsRecFld f -> pp_infixly f
825 _ -> pp_prefixly
826 where
827 pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
828 pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
829
830 pp_prefixly
831 = hang (ppr op) 2 (sep [pp_e1, pp_e2])
832
833 pp_infixly v
834 = sep [pp_e1, sep [pprInfixOcc v, nest 2 pp_e2]]
835
836 ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
837
838 ppr_expr (SectionL expr op)
839 = case unLoc op of
840 HsVar (L _ v) -> pp_infixly v
841 _ -> pp_prefixly
842 where
843 pp_expr = pprDebugParendExpr expr
844
845 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
846 4 (hsep [pp_expr, text "x_ )"])
847 pp_infixly v = (sep [pp_expr, pprInfixOcc v])
848
849 ppr_expr (SectionR op expr)
850 = case unLoc op of
851 HsVar (L _ v) -> pp_infixly v
852 _ -> pp_prefixly
853 where
854 pp_expr = pprDebugParendExpr expr
855
856 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, text "x_"])
857 4 (pp_expr <> rparen)
858 pp_infixly v = sep [pprInfixOcc v, pp_expr]
859
860 ppr_expr (ExplicitTuple exprs boxity)
861 = tupleParens (boxityTupleSort boxity) (fcat (ppr_tup_args $ map unLoc exprs))
862 where
863 ppr_tup_args [] = []
864 ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es
865 ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es
866
867 punc (Present {} : _) = comma <> space
868 punc (Missing {} : _) = comma
869 punc [] = empty
870
871 ppr_expr (ExplicitSum alt arity expr _)
872 = text "(#" <+> ppr_bars (alt - 1) <+> ppr expr <+> ppr_bars (arity - alt) <+> text "#)"
873 where
874 ppr_bars n = hsep (replicate n (char '|'))
875
876 ppr_expr (HsLam matches)
877 = pprMatches matches
878
879 ppr_expr (HsLamCase matches)
880 = sep [ sep [text "\\case {"],
881 nest 2 (pprMatches matches <+> char '}') ]
882
883 ppr_expr (HsCase expr matches)
884 = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")],
885 nest 2 (pprMatches matches <+> char '}') ]
886
887 ppr_expr (HsIf _ e1 e2 e3)
888 = sep [hsep [text "if", nest 2 (ppr e1), ptext (sLit "then")],
889 nest 4 (ppr e2),
890 text "else",
891 nest 4 (ppr e3)]
892
893 ppr_expr (HsMultiIf _ alts)
894 = sep $ text "if" : map ppr_alt alts
895 where ppr_alt (L _ (GRHS guards expr)) =
896 sep [ vbar <+> interpp'SP guards
897 , text "->" <+> pprDeeper (ppr expr) ]
898
899 -- special case: let ... in let ...
900 ppr_expr (HsLet (L _ binds) expr@(L _ (HsLet _ _)))
901 = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
902 ppr_lexpr expr]
903
904 ppr_expr (HsLet (L _ binds) expr)
905 = sep [hang (text "let") 2 (pprBinds binds),
906 hang (text "in") 2 (ppr expr)]
907
908 ppr_expr (HsDo do_or_list_comp (L _ stmts) _) = pprDo do_or_list_comp stmts
909
910 ppr_expr (ExplicitList _ _ exprs)
911 = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
912
913 ppr_expr (ExplicitPArr _ exprs)
914 = paBrackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
915
916 ppr_expr (RecordCon { rcon_con_name = con_id, rcon_flds = rbinds })
917 = hang (ppr con_id) 2 (ppr rbinds)
918
919 ppr_expr (RecordUpd { rupd_expr = L _ aexp, rupd_flds = rbinds })
920 = hang (pprParendExpr aexp) 2 (braces (fsep (punctuate comma (map ppr rbinds))))
921
922 ppr_expr (ExprWithTySig expr sig)
923 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
924 4 (ppr sig)
925 ppr_expr (ExprWithTySigOut expr sig)
926 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
927 4 (ppr sig)
928
929 ppr_expr (ArithSeq _ _ info) = brackets (ppr info)
930 ppr_expr (PArrSeq _ info) = paBrackets (ppr info)
931
932 ppr_expr EWildPat = char '_'
933 ppr_expr (ELazyPat e) = char '~' <> pprParendLExpr e
934 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendLExpr e
935 ppr_expr (EViewPat p e) = ppr p <+> text "->" <+> ppr e
936
937 ppr_expr (HsSCC _ (StringLiteral _ lbl) expr)
938 = sep [ text "{-# SCC" <+> doubleQuotes (ftext lbl) <+> ptext (sLit "#-}"),
939 pprParendLExpr expr ]
940
941 ppr_expr (HsWrap co_fn e)
942 = pprHsWrapper co_fn (\parens -> if parens then pprParendExpr e
943 else pprExpr e)
944
945 ppr_expr (HsSpliceE s) = pprSplice s
946 ppr_expr (HsBracket b) = pprHsBracket b
947 ppr_expr (HsRnBracketOut e []) = ppr e
948 ppr_expr (HsRnBracketOut e ps) = ppr e $$ text "pending(rn)" <+> ppr ps
949 ppr_expr (HsTcBracketOut e []) = ppr e
950 ppr_expr (HsTcBracketOut e ps) = ppr e $$ text "pending(tc)" <+> ppr ps
951
952 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
953 = hsep [text "proc", ppr pat, ptext (sLit "->"), ppr cmd]
954
955 ppr_expr (HsStatic _ e)
956 = hsep [text "static", pprParendLExpr e]
957
958 ppr_expr (HsTick tickish exp)
959 = pprTicks (ppr exp) $
960 ppr tickish <+> ppr_lexpr exp
961 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
962 = pprTicks (ppr exp) $
963 hcat [text "bintick<",
964 ppr tickIdTrue,
965 text ",",
966 ppr tickIdFalse,
967 text ">(",
968 ppr exp, text ")"]
969 ppr_expr (HsTickPragma _ externalSrcLoc _ exp)
970 = pprTicks (ppr exp) $
971 hcat [text "tickpragma<",
972 pprExternalSrcLoc externalSrcLoc,
973 text ">(",
974 ppr exp,
975 text ")"]
976
977 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
978 = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
979 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
980 = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
981 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
982 = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
983 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
984 = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
985
986 ppr_expr (HsArrForm (L _ (HsVar (L _ v))) (Just _) [arg1, arg2])
987 = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]]
988 ppr_expr (HsArrForm op _ args)
989 = hang (text "(|" <+> ppr_lexpr op)
990 4 (sep (map (pprCmdArg.unLoc) args) <+> text "|)")
991 ppr_expr (HsRecFld f) = ppr f
992
993 -- We must tiresomely make the "id" parameter to the LHsWcType existential
994 -- because it's different in the HsAppType case and the HsAppTypeOut case
995 -- | Located Haskell Wildcard Type Expression
996 data LHsWcTypeX = forall id. (OutputableBndrId id) => LHsWcTypeX (LHsWcType id)
997
998 ppr_apps :: (OutputableBndrId id)
999 => HsExpr id
1000 -> [Either (LHsExpr id) LHsWcTypeX]
1001 -> SDoc
1002 ppr_apps (HsApp (L _ fun) arg) args
1003 = ppr_apps fun (Left arg : args)
1004 ppr_apps (HsAppType (L _ fun) arg) args
1005 = ppr_apps fun (Right (LHsWcTypeX arg) : args)
1006 ppr_apps (HsAppTypeOut (L _ fun) arg) args
1007 = ppr_apps fun (Right (LHsWcTypeX arg) : args)
1008 ppr_apps fun args = hang (ppr_expr fun) 2 (sep (map pp args))
1009 where
1010 pp (Left arg) = pprParendLExpr arg
1011 pp (Right (LHsWcTypeX (HsWC { hswc_body = L _ arg })))
1012 = char '@' <> pprParendHsType arg
1013
1014 pprExternalSrcLoc :: (StringLiteral,(Int,Int),(Int,Int)) -> SDoc
1015 pprExternalSrcLoc (StringLiteral _ src,(n1,n2),(n3,n4))
1016 = ppr (src,(n1,n2),(n3,n4))
1017
1018 {-
1019 HsSyn records exactly where the user put parens, with HsPar.
1020 So generally speaking we print without adding any parens.
1021 However, some code is internally generated, and in some places
1022 parens are absolutely required; so for these places we use
1023 pprParendLExpr (but don't print double parens of course).
1024
1025 For operator applications we don't add parens, because the operator
1026 fixities should do the job, except in debug mode (-dppr-debug) so we
1027 can see the structure of the parse tree.
1028 -}
1029
1030 pprDebugParendExpr :: (OutputableBndrId id) => LHsExpr id -> SDoc
1031 pprDebugParendExpr expr
1032 = getPprStyle (\sty ->
1033 if debugStyle sty then pprParendLExpr expr
1034 else pprLExpr expr)
1035
1036 pprParendLExpr :: (OutputableBndrId id) => LHsExpr id -> SDoc
1037 pprParendLExpr (L _ e) = pprParendExpr e
1038
1039 pprParendExpr :: (OutputableBndrId id) => HsExpr id -> SDoc
1040 pprParendExpr expr
1041 | hsExprNeedsParens expr = parens (pprExpr expr)
1042 | otherwise = pprExpr expr
1043 -- Using pprLExpr makes sure that we go 'deeper'
1044 -- I think that is usually (always?) right
1045
1046 hsExprNeedsParens :: HsExpr id -> Bool
1047 -- True of expressions for which '(e)' and 'e'
1048 -- mean the same thing
1049 hsExprNeedsParens (ArithSeq {}) = False
1050 hsExprNeedsParens (PArrSeq {}) = False
1051 hsExprNeedsParens (HsLit {}) = False
1052 hsExprNeedsParens (HsOverLit {}) = False
1053 hsExprNeedsParens (HsVar {}) = False
1054 hsExprNeedsParens (HsUnboundVar {}) = False
1055 hsExprNeedsParens (HsIPVar {}) = False
1056 hsExprNeedsParens (HsOverLabel {}) = False
1057 hsExprNeedsParens (ExplicitTuple {}) = False
1058 hsExprNeedsParens (ExplicitList {}) = False
1059 hsExprNeedsParens (ExplicitPArr {}) = False
1060 hsExprNeedsParens (HsPar {}) = False
1061 hsExprNeedsParens (HsBracket {}) = False
1062 hsExprNeedsParens (HsRnBracketOut {}) = False
1063 hsExprNeedsParens (HsTcBracketOut {}) = False
1064 hsExprNeedsParens (HsDo sc _ _)
1065 | isListCompExpr sc = False
1066 hsExprNeedsParens (HsRecFld{}) = False
1067 hsExprNeedsParens _ = True
1068
1069
1070 isAtomicHsExpr :: HsExpr id -> Bool
1071 -- True of a single token
1072 isAtomicHsExpr (HsVar {}) = True
1073 isAtomicHsExpr (HsLit {}) = True
1074 isAtomicHsExpr (HsOverLit {}) = True
1075 isAtomicHsExpr (HsIPVar {}) = True
1076 isAtomicHsExpr (HsOverLabel {}) = True
1077 isAtomicHsExpr (HsUnboundVar {}) = True
1078 isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
1079 isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
1080 isAtomicHsExpr (HsRecFld{}) = True
1081 isAtomicHsExpr _ = False
1082
1083 {-
1084 ************************************************************************
1085 * *
1086 \subsection{Commands (in arrow abstractions)}
1087 * *
1088 ************************************************************************
1089
1090 We re-use HsExpr to represent these.
1091 -}
1092
1093 -- | Located Haskell Command (for arrow syntax)
1094 type LHsCmd id = Located (HsCmd id)
1095
1096 -- | Haskell Command (e.g. a "statement" in an Arrow proc block)
1097 data HsCmd id
1098 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
1099 -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
1100 -- 'ApiAnnotation.AnnRarrowtail'
1101
1102 -- For details on above see note [Api annotations] in ApiAnnotation
1103 = HsCmdArrApp -- Arrow tail, or arrow application (f -< arg)
1104 (LHsExpr id) -- arrow expression, f
1105 (LHsExpr id) -- input expression, arg
1106 (PostTc id Type) -- type of the arrow expressions f,
1107 -- of the form a t t', where arg :: t
1108 HsArrAppType -- higher-order (-<<) or first-order (-<)
1109 Bool -- True => right-to-left (f -< arg)
1110 -- False => left-to-right (arg >- f)
1111
1112 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@,
1113 -- 'ApiAnnotation.AnnClose' @'|)'@
1114
1115 -- For details on above see note [Api annotations] in ApiAnnotation
1116 | HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |)
1117 (LHsExpr id) -- the operator
1118 -- after type-checking, a type abstraction to be
1119 -- applied to the type of the local environment tuple
1120 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
1121 -- were converted from OpApp's by the renamer
1122 [LHsCmdTop id] -- argument commands
1123
1124 | HsCmdApp (LHsCmd id)
1125 (LHsExpr id)
1126
1127 | HsCmdLam (MatchGroup id (LHsCmd id)) -- kappa
1128 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
1129 -- 'ApiAnnotation.AnnRarrow',
1130
1131 -- For details on above see note [Api annotations] in ApiAnnotation
1132
1133 | HsCmdPar (LHsCmd id) -- parenthesised command
1134 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
1135 -- 'ApiAnnotation.AnnClose' @')'@
1136
1137 -- For details on above see note [Api annotations] in ApiAnnotation
1138
1139 | HsCmdCase (LHsExpr id)
1140 (MatchGroup id (LHsCmd id)) -- bodies are HsCmd's
1141 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
1142 -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
1143 -- 'ApiAnnotation.AnnClose' @'}'@
1144
1145 -- For details on above see note [Api annotations] in ApiAnnotation
1146
1147 | HsCmdIf (Maybe (SyntaxExpr id)) -- cond function
1148 (LHsExpr id) -- predicate
1149 (LHsCmd id) -- then part
1150 (LHsCmd id) -- else part
1151 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
1152 -- 'ApiAnnotation.AnnSemi',
1153 -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
1154 -- 'ApiAnnotation.AnnElse',
1155
1156 -- For details on above see note [Api annotations] in ApiAnnotation
1157
1158 | HsCmdLet (Located (HsLocalBinds id)) -- let(rec)
1159 (LHsCmd id)
1160 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
1161 -- 'ApiAnnotation.AnnOpen' @'{'@,
1162 -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
1163
1164 -- For details on above see note [Api annotations] in ApiAnnotation
1165
1166 | HsCmdDo (Located [CmdLStmt id])
1167 (PostTc id Type) -- Type of the whole expression
1168 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
1169 -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
1170 -- 'ApiAnnotation.AnnVbar',
1171 -- 'ApiAnnotation.AnnClose'
1172
1173 -- For details on above see note [Api annotations] in ApiAnnotation
1174
1175 | HsCmdWrap HsWrapper
1176 (HsCmd id) -- If cmd :: arg1 --> res
1177 -- wrap :: arg1 "->" arg2
1178 -- Then (HsCmdWrap wrap cmd) :: arg2 --> res
1179 deriving instance (DataId id) => Data (HsCmd id)
1180
1181 -- | Haskell Array Application Type
1182 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
1183 deriving Data
1184
1185
1186 {- | Top-level command, introducing a new arrow.
1187 This may occur inside a proc (where the stack is empty) or as an
1188 argument of a command-forming operator.
1189 -}
1190
1191 -- | Located Haskell Top-level Command
1192 type LHsCmdTop id = Located (HsCmdTop id)
1193
1194 -- | Haskell Top-level Command
1195 data HsCmdTop id
1196 = HsCmdTop (LHsCmd id)
1197 (PostTc id Type) -- Nested tuple of inputs on the command's stack
1198 (PostTc id Type) -- return type of the command
1199 (CmdSyntaxTable id) -- See Note [CmdSyntaxTable]
1200 deriving instance (DataId id) => Data (HsCmdTop id)
1201
1202 instance (OutputableBndrId id) => Outputable (HsCmd id) where
1203 ppr cmd = pprCmd cmd
1204
1205 -----------------------
1206 -- pprCmd and pprLCmd call pprDeeper;
1207 -- the underscore versions do not
1208 pprLCmd :: (OutputableBndrId id) => LHsCmd id -> SDoc
1209 pprLCmd (L _ c) = pprCmd c
1210
1211 pprCmd :: (OutputableBndrId id) => HsCmd id -> SDoc
1212 pprCmd c | isQuietHsCmd c = ppr_cmd c
1213 | otherwise = pprDeeper (ppr_cmd c)
1214
1215 isQuietHsCmd :: HsCmd id -> Bool
1216 -- Parentheses do display something, but it gives little info and
1217 -- if we go deeper when we go inside them then we get ugly things
1218 -- like (...)
1219 isQuietHsCmd (HsCmdPar _) = True
1220 -- applications don't display anything themselves
1221 isQuietHsCmd (HsCmdApp _ _) = True
1222 isQuietHsCmd _ = False
1223
1224 -----------------------
1225 ppr_lcmd :: (OutputableBndrId id) => LHsCmd id -> SDoc
1226 ppr_lcmd c = ppr_cmd (unLoc c)
1227
1228 ppr_cmd :: forall id. (OutputableBndrId id) => HsCmd id -> SDoc
1229 ppr_cmd (HsCmdPar c) = parens (ppr_lcmd c)
1230
1231 ppr_cmd (HsCmdApp c e)
1232 = let (fun, args) = collect_args c [e] in
1233 hang (ppr_lcmd fun) 2 (sep (map pprParendLExpr args))
1234 where
1235 collect_args (L _ (HsCmdApp fun arg)) args = collect_args fun (arg:args)
1236 collect_args fun args = (fun, args)
1237
1238 ppr_cmd (HsCmdLam matches)
1239 = pprMatches matches
1240
1241 ppr_cmd (HsCmdCase expr matches)
1242 = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")],
1243 nest 2 (pprMatches matches <+> char '}') ]
1244
1245 ppr_cmd (HsCmdIf _ e ct ce)
1246 = sep [hsep [text "if", nest 2 (ppr e), ptext (sLit "then")],
1247 nest 4 (ppr ct),
1248 text "else",
1249 nest 4 (ppr ce)]
1250
1251 -- special case: let ... in let ...
1252 ppr_cmd (HsCmdLet (L _ binds) cmd@(L _ (HsCmdLet _ _)))
1253 = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
1254 ppr_lcmd cmd]
1255
1256 ppr_cmd (HsCmdLet (L _ binds) cmd)
1257 = sep [hang (text "let") 2 (pprBinds binds),
1258 hang (text "in") 2 (ppr cmd)]
1259
1260 ppr_cmd (HsCmdDo (L _ stmts) _) = pprDo ArrowExpr stmts
1261
1262 ppr_cmd (HsCmdWrap w cmd)
1263 = pprHsWrapper w (\_ -> parens (ppr_cmd cmd))
1264 ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp True)
1265 = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
1266 ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp False)
1267 = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
1268 ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp True)
1269 = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
1270 ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp False)
1271 = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
1272
1273 ppr_cmd (HsCmdArrForm (L _ (HsVar (L _ v))) (Just _) [arg1, arg2])
1274 = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]]
1275 ppr_cmd (HsCmdArrForm op _ args)
1276 = hang (text "(|" <> ppr_lexpr op)
1277 4 (sep (map (pprCmdArg.unLoc) args) <> text "|)")
1278
1279 pprCmdArg :: (OutputableBndrId id) => HsCmdTop id -> SDoc
1280 pprCmdArg (HsCmdTop cmd@(L _ (HsCmdArrForm _ Nothing [])) _ _ _)
1281 = ppr_lcmd cmd
1282 pprCmdArg (HsCmdTop cmd _ _ _)
1283 = parens (ppr_lcmd cmd)
1284
1285 instance (OutputableBndrId id) => Outputable (HsCmdTop id) where
1286 ppr = pprCmdArg
1287
1288 {-
1289 ************************************************************************
1290 * *
1291 \subsection{Record binds}
1292 * *
1293 ************************************************************************
1294 -}
1295
1296 -- | Haskell Record Bindings
1297 type HsRecordBinds id = HsRecFields id (LHsExpr id)
1298
1299 {-
1300 ************************************************************************
1301 * *
1302 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
1303 * *
1304 ************************************************************************
1305
1306 @Match@es are sets of pattern bindings and right hand sides for
1307 functions, patterns or case branches. For example, if a function @g@
1308 is defined as:
1309 \begin{verbatim}
1310 g (x,y) = y
1311 g ((x:ys),y) = y+1,
1312 \end{verbatim}
1313 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
1314
1315 It is always the case that each element of an @[Match]@ list has the
1316 same number of @pats@s inside it. This corresponds to saying that
1317 a function defined by pattern matching must have the same number of
1318 patterns in each equation.
1319 -}
1320
1321 data MatchGroup id body
1322 = MG { mg_alts :: Located [LMatch id body] -- The alternatives
1323 , mg_arg_tys :: [PostTc id Type] -- Types of the arguments, t1..tn
1324 , mg_res_ty :: PostTc id Type -- Type of the result, tr
1325 , mg_origin :: Origin }
1326 -- The type is the type of the entire group
1327 -- t1 -> ... -> tn -> tr
1328 -- where there are n patterns
1329 deriving instance (Data body,DataId id) => Data (MatchGroup id body)
1330
1331 -- | Located Match
1332 type LMatch id body = Located (Match id body)
1333 -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a
1334 -- list
1335
1336 -- For details on above see note [Api annotations] in ApiAnnotation
1337 data Match id body
1338 = Match {
1339 m_ctxt :: HsMatchContext (NameOrRdrName id),
1340 -- See note [m_ctxt in Match]
1341 m_pats :: [LPat id], -- The patterns
1342 m_type :: (Maybe (LHsType id)),
1343 -- A type signature for the result of the match
1344 -- Nothing after typechecking
1345 -- NB: No longer supported
1346 m_grhss :: (GRHSs id body)
1347 }
1348 deriving instance (Data body,DataId id) => Data (Match id body)
1349
1350 {-
1351 Note [m_ctxt in Match]
1352 ~~~~~~~~~~~~~~~~~~~~~~
1353
1354 A Match can occur in a number of contexts, such as a FunBind, HsCase, HsLam and
1355 so on.
1356
1357 In order to simplify tooling processing and pretty print output, the provenance
1358 is captured in an HsMatchContext.
1359
1360 This is particularly important for the API Annotations for a multi-equation
1361 FunBind.
1362
1363 The parser initially creates a FunBind with a single Match in it for
1364 every function definition it sees.
1365
1366 These are then grouped together by getMonoBind into a single FunBind,
1367 where all the Matches are combined.
1368
1369 In the process, all the original FunBind fun_id's bar one are
1370 discarded, including the locations.
1371
1372 This causes a problem for source to source conversions via API
1373 Annotations, so the original fun_ids and infix flags are preserved in
1374 the Match, when it originates from a FunBind.
1375
1376 Example infix function definition requiring individual API Annotations
1377
1378 (&&& ) [] [] = []
1379 xs &&& [] = xs
1380 ( &&& ) [] ys = ys
1381
1382
1383
1384 -}
1385
1386
1387 isInfixMatch :: Match id body -> Bool
1388 isInfixMatch match = case m_ctxt match of
1389 FunRhs _ Infix -> True
1390 _ -> False
1391
1392 isEmptyMatchGroup :: MatchGroup id body -> Bool
1393 isEmptyMatchGroup (MG { mg_alts = ms }) = null $ unLoc ms
1394
1395 -- | Is there only one RHS in this list of matches?
1396 isSingletonMatchGroup :: [LMatch id body] -> Bool
1397 isSingletonMatchGroup matches
1398 | [L _ match] <- matches
1399 , Match { m_grhss = GRHSs { grhssGRHSs = [_] } } <- match
1400 = True
1401 | otherwise
1402 = False
1403
1404 matchGroupArity :: MatchGroup id body -> Arity
1405 -- Precondition: MatchGroup is non-empty
1406 -- This is called before type checking, when mg_arg_tys is not set
1407 matchGroupArity (MG { mg_alts = alts })
1408 | L _ (alt1:_) <- alts = length (hsLMatchPats alt1)
1409 | otherwise = panic "matchGroupArity"
1410
1411 hsLMatchPats :: LMatch id body -> [LPat id]
1412 hsLMatchPats (L _ (Match _ pats _ _)) = pats
1413
1414 -- | Guarded Right-Hand Sides
1415 --
1416 -- GRHSs are used both for pattern bindings and for Matches
1417 --
1418 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
1419 -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere',
1420 -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose'
1421 -- 'ApiAnnotation.AnnRarrow','ApiAnnotation.AnnSemi'
1422
1423 -- For details on above see note [Api annotations] in ApiAnnotation
1424 data GRHSs id body
1425 = GRHSs {
1426 grhssGRHSs :: [LGRHS id body], -- ^ Guarded RHSs
1427 grhssLocalBinds :: Located (HsLocalBinds id) -- ^ The where clause
1428 }
1429 deriving instance (Data body,DataId id) => Data (GRHSs id body)
1430
1431 -- | Located Guarded Right-Hand Side
1432 type LGRHS id body = Located (GRHS id body)
1433
1434 -- | Guarded Right Hand Side.
1435 data GRHS id body = GRHS [GuardLStmt id] -- Guards
1436 body -- Right hand side
1437 deriving instance (Data body,DataId id) => Data (GRHS id body)
1438
1439 -- We know the list must have at least one @Match@ in it.
1440
1441 pprMatches :: (OutputableBndrId idR, Outputable body)
1442 => MatchGroup idR body -> SDoc
1443 pprMatches MG { mg_alts = matches }
1444 = vcat (map pprMatch (map unLoc (unLoc matches)))
1445 -- Don't print the type; it's only a place-holder before typechecking
1446
1447 -- Exported to HsBinds, which can't see the defn of HsMatchContext
1448 pprFunBind :: (OutputableBndrId idR, Outputable body)
1449 => MatchGroup idR body -> SDoc
1450 pprFunBind matches = pprMatches matches
1451
1452 -- Exported to HsBinds, which can't see the defn of HsMatchContext
1453 pprPatBind :: forall bndr id body. (OutputableBndrId bndr,
1454 OutputableBndrId id, Outputable body)
1455 => LPat bndr -> GRHSs id body -> SDoc
1456 pprPatBind pat (grhss)
1457 = sep [ppr pat, nest 2 (pprGRHSs (PatBindRhs :: HsMatchContext id) grhss)]
1458
1459 pprMatch :: (OutputableBndrId idR, Outputable body) => Match idR body -> SDoc
1460 pprMatch match
1461 = sep [ sep (herald : map (nest 2 . pprParendLPat) other_pats)
1462 , nest 2 ppr_maybe_ty
1463 , nest 2 (pprGRHSs ctxt (m_grhss match)) ]
1464 where
1465 ctxt = m_ctxt match
1466 (herald, other_pats)
1467 = case ctxt of
1468 FunRhs (L _ fun) fixity
1469 | fixity == Prefix -> (pprPrefixOcc fun, m_pats match)
1470 -- f x y z = e
1471 -- Not pprBndr; the AbsBinds will
1472 -- have printed the signature
1473
1474 | null pats2 -> (pp_infix, [])
1475 -- x &&& y = e
1476
1477 | otherwise -> (parens pp_infix, pats2)
1478 -- (x &&& y) z = e
1479 where
1480 pp_infix = pprParendLPat pat1 <+> pprInfixOcc fun <+> pprParendLPat pat2
1481
1482 LambdaExpr -> (char '\\', m_pats match)
1483
1484 _ -> ASSERT( null pats1 )
1485 (ppr pat1, []) -- No parens around the single pat
1486
1487 (pat1:pats1) = m_pats match
1488 (pat2:pats2) = pats1
1489 ppr_maybe_ty = case m_type match of
1490 Just ty -> dcolon <+> ppr ty
1491 Nothing -> empty
1492
1493
1494 pprGRHSs :: (OutputableBndrId idR, Outputable body)
1495 => HsMatchContext idL -> GRHSs idR body -> SDoc
1496 pprGRHSs ctxt (GRHSs grhss (L _ binds))
1497 = vcat (map (pprGRHS ctxt . unLoc) grhss)
1498 $$ ppUnless (isEmptyLocalBinds binds)
1499 (text "where" $$ nest 4 (pprBinds binds))
1500
1501 pprGRHS :: (OutputableBndrId idR, Outputable body)
1502 => HsMatchContext idL -> GRHS idR body -> SDoc
1503 pprGRHS ctxt (GRHS [] body)
1504 = pp_rhs ctxt body
1505
1506 pprGRHS ctxt (GRHS guards body)
1507 = sep [vbar <+> interpp'SP guards, pp_rhs ctxt body]
1508
1509 pp_rhs :: Outputable body => HsMatchContext idL -> body -> SDoc
1510 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
1511
1512 {-
1513 ************************************************************************
1514 * *
1515 \subsection{Do stmts and list comprehensions}
1516 * *
1517 ************************************************************************
1518 -}
1519
1520 -- | Located @do@ block Statement
1521 type LStmt id body = Located (StmtLR id id body)
1522
1523 -- | Located Statement with separate Left and Right id's
1524 type LStmtLR idL idR body = Located (StmtLR idL idR body)
1525
1526 -- | @do@ block Statement
1527 type Stmt id body = StmtLR id id body
1528
1529 -- | Command Located Statement
1530 type CmdLStmt id = LStmt id (LHsCmd id)
1531
1532 -- | Command Statement
1533 type CmdStmt id = Stmt id (LHsCmd id)
1534
1535 -- | Expression Located Statement
1536 type ExprLStmt id = LStmt id (LHsExpr id)
1537
1538 -- | Expression Statement
1539 type ExprStmt id = Stmt id (LHsExpr id)
1540
1541 -- | Guard Located Statement
1542 type GuardLStmt id = LStmt id (LHsExpr id)
1543
1544 -- | Guard Statement
1545 type GuardStmt id = Stmt id (LHsExpr id)
1546
1547 -- | Ghci Located Statemnt
1548 type GhciLStmt id = LStmt id (LHsExpr id)
1549
1550 -- | Ghci Statement
1551 type GhciStmt id = Stmt id (LHsExpr id)
1552
1553 -- The SyntaxExprs in here are used *only* for do-notation and monad
1554 -- comprehensions, which have rebindable syntax. Otherwise they are unused.
1555 -- | API Annotations when in qualifier lists or guards
1556 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
1557 -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnThen',
1558 -- 'ApiAnnotation.AnnBy','ApiAnnotation.AnnBy',
1559 -- 'ApiAnnotation.AnnGroup','ApiAnnotation.AnnUsing'
1560
1561 -- For details on above see note [Api annotations] in ApiAnnotation
1562 data StmtLR idL idR body -- body should always be (LHs**** idR)
1563 = LastStmt -- Always the last Stmt in ListComp, MonadComp, PArrComp,
1564 -- and (after the renamer) DoExpr, MDoExpr
1565 -- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff
1566 body
1567 Bool -- True <=> return was stripped by ApplicativeDo
1568 (SyntaxExpr idR) -- The return operator, used only for
1569 -- MonadComp For ListComp, PArrComp, we
1570 -- use the baked-in 'return' For DoExpr,
1571 -- MDoExpr, we don't apply a 'return' at
1572 -- all See Note [Monad Comprehensions] |
1573 -- - 'ApiAnnotation.AnnKeywordId' :
1574 -- 'ApiAnnotation.AnnLarrow'
1575
1576 -- For details on above see note [Api annotations] in ApiAnnotation
1577 | BindStmt (LPat idL)
1578 body
1579 (SyntaxExpr idR) -- The (>>=) operator; see Note [The type of bind in Stmts]
1580 (SyntaxExpr idR) -- The fail operator
1581 -- The fail operator is noSyntaxExpr
1582 -- if the pattern match can't fail
1583
1584 (PostTc idR Type) -- result type of the function passed to bind;
1585 -- that is, S in (>>=) :: Q -> (R -> S) -> T
1586
1587 -- | 'ApplicativeStmt' represents an applicative expression built with
1588 -- <$> and <*>. It is generated by the renamer, and is desugared into the
1589 -- appropriate applicative expression by the desugarer, but it is intended
1590 -- to be invisible in error messages.
1591 --
1592 -- For full details, see Note [ApplicativeDo] in RnExpr
1593 --
1594 | ApplicativeStmt
1595 [ ( SyntaxExpr idR
1596 , ApplicativeArg idL idR) ]
1597 -- [(<$>, e1), (<*>, e2), ..., (<*>, en)]
1598 (Maybe (SyntaxExpr idR)) -- 'join', if necessary
1599 (PostTc idR Type) -- Type of the body
1600
1601 | BodyStmt body -- See Note [BodyStmt]
1602 (SyntaxExpr idR) -- The (>>) operator
1603 (SyntaxExpr idR) -- The `guard` operator; used only in MonadComp
1604 -- See notes [Monad Comprehensions]
1605 (PostTc idR Type) -- Element type of the RHS (used for arrows)
1606
1607 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet'
1608 -- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@,
1609
1610 -- For details on above see note [Api annotations] in ApiAnnotation
1611 | LetStmt (Located (HsLocalBindsLR idL idR))
1612
1613 -- ParStmts only occur in a list/monad comprehension
1614 | ParStmt [ParStmtBlock idL idR]
1615 (HsExpr idR) -- Polymorphic `mzip` for monad comprehensions
1616 (SyntaxExpr idR) -- The `>>=` operator
1617 -- See notes [Monad Comprehensions]
1618 (PostTc idR Type) -- S in (>>=) :: Q -> (R -> S) -> T
1619 -- After renaming, the ids are the binders
1620 -- bound by the stmts and used after themp
1621
1622 | TransStmt {
1623 trS_form :: TransForm,
1624 trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group'
1625 -- which generates the tuples to be grouped
1626
1627 trS_bndrs :: [(idR, idR)], -- See Note [TransStmt binder map]
1628
1629 trS_using :: LHsExpr idR,
1630 trS_by :: Maybe (LHsExpr idR), -- "by e" (optional)
1631 -- Invariant: if trS_form = GroupBy, then grp_by = Just e
1632
1633 trS_ret :: SyntaxExpr idR, -- The monomorphic 'return' function for
1634 -- the inner monad comprehensions
1635 trS_bind :: SyntaxExpr idR, -- The '(>>=)' operator
1636 trS_bind_arg_ty :: PostTc idR Type, -- R in (>>=) :: Q -> (R -> S) -> T
1637 trS_fmap :: HsExpr idR -- The polymorphic 'fmap' function for desugaring
1638 -- Only for 'group' forms
1639 -- Just a simple HsExpr, because it's
1640 -- too polymorphic for tcSyntaxOp
1641 } -- See Note [Monad Comprehensions]
1642
1643 -- Recursive statement (see Note [How RecStmt works] below)
1644 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRec'
1645
1646 -- For details on above see note [Api annotations] in ApiAnnotation
1647 | RecStmt
1648 { recS_stmts :: [LStmtLR idL idR body]
1649
1650 -- The next two fields are only valid after renaming
1651 , recS_later_ids :: [idR] -- The ids are a subset of the variables bound by the
1652 -- stmts that are used in stmts that follow the RecStmt
1653
1654 , recS_rec_ids :: [idR] -- Ditto, but these variables are the "recursive" ones,
1655 -- that are used before they are bound in the stmts of
1656 -- the RecStmt.
1657 -- An Id can be in both groups
1658 -- Both sets of Ids are (now) treated monomorphically
1659 -- See Note [How RecStmt works] for why they are separate
1660
1661 -- Rebindable syntax
1662 , recS_bind_fn :: SyntaxExpr idR -- The bind function
1663 , recS_ret_fn :: SyntaxExpr idR -- The return function
1664 , recS_mfix_fn :: SyntaxExpr idR -- The mfix function
1665 , recS_bind_ty :: PostTc idR Type -- S in (>>=) :: Q -> (R -> S) -> T
1666
1667 -- These fields are only valid after typechecking
1668 , recS_later_rets :: [PostTcExpr] -- (only used in the arrow version)
1669 , recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1
1670 -- with recS_later_ids and recS_rec_ids,
1671 -- and are the expressions that should be
1672 -- returned by the recursion.
1673 -- They may not quite be the Ids themselves,
1674 -- because the Id may be *polymorphic*, but
1675 -- the returned thing has to be *monomorphic*,
1676 -- so they may be type applications
1677
1678 , recS_ret_ty :: PostTc idR Type -- The type of
1679 -- do { stmts; return (a,b,c) }
1680 -- With rebindable syntax the type might not
1681 -- be quite as simple as (m (tya, tyb, tyc)).
1682 }
1683 deriving instance (Data body, DataId idL, DataId idR)
1684 => Data (StmtLR idL idR body)
1685
1686 data TransForm -- The 'f' below is the 'using' function, 'e' is the by function
1687 = ThenForm -- then f or then f by e (depending on trS_by)
1688 | GroupForm -- then group using f or then group by e using f (depending on trS_by)
1689 deriving Data
1690
1691 -- | Parenthesised Statement Block
1692 data ParStmtBlock idL idR
1693 = ParStmtBlock
1694 [ExprLStmt idL]
1695 [idR] -- The variables to be returned
1696 (SyntaxExpr idR) -- The return operator
1697 deriving instance (DataId idL, DataId idR) => Data (ParStmtBlock idL idR)
1698
1699 -- | Applicative Argument
1700 data ApplicativeArg idL idR
1701 = ApplicativeArgOne -- pat <- expr (pat must be irrefutable)
1702 (LPat idL)
1703 (LHsExpr idL)
1704 | ApplicativeArgMany -- do { stmts; return vars }
1705 [ExprLStmt idL] -- stmts
1706 (HsExpr idL) -- return (v1,..,vn), or just (v1,..,vn)
1707 (LPat idL) -- (v1,...,vn)
1708 deriving instance (DataId idL, DataId idR) => Data (ApplicativeArg idL idR)
1709
1710 {-
1711 Note [The type of bind in Stmts]
1712 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1713 Some Stmts, notably BindStmt, keep the (>>=) bind operator.
1714 We do NOT assume that it has type
1715 (>>=) :: m a -> (a -> m b) -> m b
1716 In some cases (see Trac #303, #1537) it might have a more
1717 exotic type, such as
1718 (>>=) :: m i j a -> (a -> m j k b) -> m i k b
1719 So we must be careful not to make assumptions about the type.
1720 In particular, the monad may not be uniform throughout.
1721
1722 Note [TransStmt binder map]
1723 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1724 The [(idR,idR)] in a TransStmt behaves as follows:
1725
1726 * Before renaming: []
1727
1728 * After renaming:
1729 [ (x27,x27), ..., (z35,z35) ]
1730 These are the variables
1731 bound by the stmts to the left of the 'group'
1732 and used either in the 'by' clause,
1733 or in the stmts following the 'group'
1734 Each item is a pair of identical variables.
1735
1736 * After typechecking:
1737 [ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ]
1738 Each pair has the same unique, but different *types*.
1739
1740 Note [BodyStmt]
1741 ~~~~~~~~~~~~~~~
1742 BodyStmts are a bit tricky, because what they mean
1743 depends on the context. Consider the following contexts:
1744
1745 A do expression of type (m res_ty)
1746 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1747 * BodyStmt E any_ty: do { ....; E; ... }
1748 E :: m any_ty
1749 Translation: E >> ...
1750
1751 A list comprehensions of type [elt_ty]
1752 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1753 * BodyStmt E Bool: [ .. | .... E ]
1754 [ .. | ..., E, ... ]
1755 [ .. | .... | ..., E | ... ]
1756 E :: Bool
1757 Translation: if E then fail else ...
1758
1759 A guard list, guarding a RHS of type rhs_ty
1760 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1761 * BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs...
1762 E :: Bool
1763 Translation: if E then fail else ...
1764
1765 A monad comprehension of type (m res_ty)
1766 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1767 * BodyStmt E Bool: [ .. | .... E ]
1768 E :: Bool
1769 Translation: guard E >> ...
1770
1771 Array comprehensions are handled like list comprehensions.
1772
1773 Note [How RecStmt works]
1774 ~~~~~~~~~~~~~~~~~~~~~~~~
1775 Example:
1776 HsDo [ BindStmt x ex
1777
1778 , RecStmt { recS_rec_ids = [a, c]
1779 , recS_stmts = [ BindStmt b (return (a,c))
1780 , LetStmt a = ...b...
1781 , BindStmt c ec ]
1782 , recS_later_ids = [a, b]
1783
1784 , return (a b) ]
1785
1786 Here, the RecStmt binds a,b,c; but
1787 - Only a,b are used in the stmts *following* the RecStmt,
1788 - Only a,c are used in the stmts *inside* the RecStmt
1789 *before* their bindings
1790
1791 Why do we need *both* rec_ids and later_ids? For monads they could be
1792 combined into a single set of variables, but not for arrows. That
1793 follows from the types of the respective feedback operators:
1794
1795 mfix :: MonadFix m => (a -> m a) -> m a
1796 loop :: ArrowLoop a => a (b,d) (c,d) -> a b c
1797
1798 * For mfix, the 'a' covers the union of the later_ids and the rec_ids
1799 * For 'loop', 'c' is the later_ids and 'd' is the rec_ids
1800
1801 Note [Typing a RecStmt]
1802 ~~~~~~~~~~~~~~~~~~~~~~~
1803 A (RecStmt stmts) types as if you had written
1804
1805 (v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) ->
1806 do { stmts
1807 ; return (v1,..vn, r1, ..., rm) })
1808
1809 where v1..vn are the later_ids
1810 r1..rm are the rec_ids
1811
1812 Note [Monad Comprehensions]
1813 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1814 Monad comprehensions require separate functions like 'return' and
1815 '>>=' for desugaring. These functions are stored in the statements
1816 used in monad comprehensions. For example, the 'return' of the 'LastStmt'
1817 expression is used to lift the body of the monad comprehension:
1818
1819 [ body | stmts ]
1820 =>
1821 stmts >>= \bndrs -> return body
1822
1823 In transform and grouping statements ('then ..' and 'then group ..') the
1824 'return' function is required for nested monad comprehensions, for example:
1825
1826 [ body | stmts, then f, rest ]
1827 =>
1828 f [ env | stmts ] >>= \bndrs -> [ body | rest ]
1829
1830 BodyStmts require the 'Control.Monad.guard' function for boolean
1831 expressions:
1832
1833 [ body | exp, stmts ]
1834 =>
1835 guard exp >> [ body | stmts ]
1836
1837 Parallel statements require the 'Control.Monad.Zip.mzip' function:
1838
1839 [ body | stmts1 | stmts2 | .. ]
1840 =>
1841 mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body
1842
1843 In any other context than 'MonadComp', the fields for most of these
1844 'SyntaxExpr's stay bottom.
1845 -}
1846
1847 instance (OutputableBndrId idL) => Outputable (ParStmtBlock idL idR) where
1848 ppr (ParStmtBlock stmts _ _) = interpp'SP stmts
1849
1850 instance (OutputableBndrId idL, OutputableBndrId idR, Outputable body)
1851 => Outputable (StmtLR idL idR body) where
1852 ppr stmt = pprStmt stmt
1853
1854 pprStmt :: forall idL idR body . (OutputableBndrId idL, OutputableBndrId idR,
1855 Outputable body)
1856 => (StmtLR idL idR body) -> SDoc
1857 pprStmt (LastStmt expr ret_stripped _)
1858 = ifPprDebug (text "[last]") <+>
1859 (if ret_stripped then text "return" else empty) <+>
1860 ppr expr
1861 pprStmt (BindStmt pat expr _ _ _) = hsep [ppr pat, larrow, ppr expr]
1862 pprStmt (LetStmt (L _ binds)) = hsep [text "let", pprBinds binds]
1863 pprStmt (BodyStmt expr _ _ _) = ppr expr
1864 pprStmt (ParStmt stmtss _ _ _) = sep (punctuate (text " | ") (map ppr stmtss))
1865
1866 pprStmt (TransStmt { trS_stmts = stmts, trS_by = by, trS_using = using, trS_form = form })
1867 = sep $ punctuate comma (map ppr stmts ++ [pprTransStmt by using form])
1868
1869 pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids
1870 , recS_later_ids = later_ids })
1871 = text "rec" <+>
1872 vcat [ ppr_do_stmts segment
1873 , ifPprDebug (vcat [ text "rec_ids=" <> ppr rec_ids
1874 , text "later_ids=" <> ppr later_ids])]
1875
1876 pprStmt (ApplicativeStmt args mb_join _)
1877 = getPprStyle $ \style ->
1878 if userStyle style
1879 then pp_for_user
1880 else pp_debug
1881 where
1882 -- make all the Applicative stuff invisible in error messages by
1883 -- flattening the whole ApplicativeStmt nest back to a sequence
1884 -- of statements.
1885 pp_for_user = vcat $ punctuate semi $ concatMap flattenArg args
1886
1887 -- ppr directly rather than transforming here, because we need to
1888 -- inject a "return" which is hard when we're polymorphic in the id
1889 -- type.
1890 flattenStmt :: ExprLStmt idL -> [SDoc]
1891 flattenStmt (L _ (ApplicativeStmt args _ _)) = concatMap flattenArg args
1892 flattenStmt stmt = [ppr stmt]
1893
1894 flattenArg (_, ApplicativeArgOne pat expr) =
1895 [ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
1896 :: ExprStmt idL)]
1897 flattenArg (_, ApplicativeArgMany stmts _ _) =
1898 concatMap flattenStmt stmts
1899
1900 pp_debug =
1901 let
1902 ap_expr = sep (punctuate (text " |") (map pp_arg args))
1903 in
1904 if isNothing mb_join
1905 then ap_expr
1906 else text "join" <+> parens ap_expr
1907
1908 pp_arg (_, ApplicativeArgOne pat expr) =
1909 ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
1910 :: ExprStmt idL)
1911 pp_arg (_, ApplicativeArgMany stmts return pat) =
1912 ppr pat <+>
1913 text "<-" <+>
1914 ppr (HsDo DoExpr (noLoc
1915 (stmts ++ [noLoc (LastStmt (noLoc return) False noSyntaxExpr)]))
1916 (error "pprStmt"))
1917
1918 pprTransformStmt :: (OutputableBndrId id)
1919 => [id] -> LHsExpr id -> Maybe (LHsExpr id) -> SDoc
1920 pprTransformStmt bndrs using by
1921 = sep [ text "then" <+> ifPprDebug (braces (ppr bndrs))
1922 , nest 2 (ppr using)
1923 , nest 2 (pprBy by)]
1924
1925 pprTransStmt :: Outputable body => Maybe body -> body -> TransForm -> SDoc
1926 pprTransStmt by using ThenForm
1927 = sep [ text "then", nest 2 (ppr using), nest 2 (pprBy by)]
1928 pprTransStmt by using GroupForm
1929 = sep [ text "then group", nest 2 (pprBy by), nest 2 (ptext (sLit "using") <+> ppr using)]
1930
1931 pprBy :: Outputable body => Maybe body -> SDoc
1932 pprBy Nothing = empty
1933 pprBy (Just e) = text "by" <+> ppr e
1934
1935 pprDo :: (OutputableBndrId id, Outputable body)
1936 => HsStmtContext any -> [LStmt id body] -> SDoc
1937 pprDo DoExpr stmts = text "do" <+> ppr_do_stmts stmts
1938 pprDo GhciStmtCtxt stmts = text "do" <+> ppr_do_stmts stmts
1939 pprDo ArrowExpr stmts = text "do" <+> ppr_do_stmts stmts
1940 pprDo MDoExpr stmts = text "mdo" <+> ppr_do_stmts stmts
1941 pprDo ListComp stmts = brackets $ pprComp stmts
1942 pprDo PArrComp stmts = paBrackets $ pprComp stmts
1943 pprDo MonadComp stmts = brackets $ pprComp stmts
1944 pprDo _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
1945
1946 ppr_do_stmts :: (OutputableBndrId idL, OutputableBndrId idR, Outputable body)
1947 => [LStmtLR idL idR body] -> SDoc
1948 -- Print a bunch of do stmts, with explicit braces and semicolons,
1949 -- so that we are not vulnerable to layout bugs
1950 ppr_do_stmts stmts
1951 = lbrace <+> pprDeeperList vcat (punctuate semi (map ppr stmts))
1952 <+> rbrace
1953
1954 pprComp :: (OutputableBndrId id, Outputable body)
1955 => [LStmt id body] -> SDoc
1956 pprComp quals -- Prints: body | qual1, ..., qualn
1957 | Just (initStmts, L _ (LastStmt body _ _)) <- snocView quals
1958 = if null initStmts
1959 -- If there are no statements in a list comprehension besides the last
1960 -- one, we simply treat it like a normal list. This does arise
1961 -- occasionally in code that GHC generates, e.g., in implementations of
1962 -- 'range' for derived 'Ix' instances for product datatypes with exactly
1963 -- one constructor (e.g., see Trac #12583).
1964 then ppr body
1965 else hang (ppr body <+> vbar) 2 (pprQuals initStmts)
1966 | otherwise
1967 = pprPanic "pprComp" (pprQuals quals)
1968
1969 pprQuals :: (OutputableBndrId id, Outputable body)
1970 => [LStmt id body] -> SDoc
1971 -- Show list comprehension qualifiers separated by commas
1972 pprQuals quals = interpp'SP quals
1973
1974 {-
1975 ************************************************************************
1976 * *
1977 Template Haskell quotation brackets
1978 * *
1979 ************************************************************************
1980 -}
1981
1982 -- | Haskell Splice
1983 data HsSplice id
1984 = HsTypedSplice -- $$z or $$(f 4)
1985 id -- A unique name to identify this splice point
1986 (LHsExpr id) -- See Note [Pending Splices]
1987
1988 | HsUntypedSplice -- $z or $(f 4)
1989 id -- A unique name to identify this splice point
1990 (LHsExpr id) -- See Note [Pending Splices]
1991
1992 | HsQuasiQuote -- See Note [Quasi-quote overview] in TcSplice
1993 id -- Splice point
1994 id -- Quoter
1995 SrcSpan -- The span of the enclosed string
1996 FastString -- The enclosed string
1997
1998 | HsSpliced -- See Note [Delaying modFinalizers in untyped splices] in
1999 -- RnSplice.
2000 -- This is the result of splicing a splice. It is produced by
2001 -- the renamer and consumed by the typechecker. It lives only
2002 -- between the two.
2003 ThModFinalizers -- TH finalizers produced by the splice.
2004 (HsSplicedThing id) -- The result of splicing
2005 deriving Typeable
2006
2007 deriving instance (DataId id) => Data (HsSplice id)
2008
2009 isTypedSplice :: HsSplice id -> Bool
2010 isTypedSplice (HsTypedSplice {}) = True
2011 isTypedSplice _ = False -- Quasi-quotes are untyped splices
2012
2013 -- | Finalizers produced by a splice with
2014 -- 'Language.Haskell.TH.Syntax.addModFinalizer'
2015 --
2016 -- See Note [Delaying modFinalizers in untyped splices] in RnSplice. For how
2017 -- this is used.
2018 --
2019 #ifdef GHCI
2020 newtype ThModFinalizers = ThModFinalizers [ForeignRef (TH.Q ())]
2021 #else
2022 data ThModFinalizers = ThModFinalizers
2023 #endif
2024
2025 -- A Data instance which ignores the argument of 'ThModFinalizers'.
2026 #ifdef GHCI
2027 instance Data ThModFinalizers where
2028 gunfold _ z _ = z $ ThModFinalizers []
2029 toConstr a = mkConstr (dataTypeOf a) "ThModFinalizers" [] Data.Prefix
2030 dataTypeOf a = mkDataType "HsExpr.ThModFinalizers" [toConstr a]
2031 #else
2032 instance Data ThModFinalizers where
2033 gunfold _ z _ = z ThModFinalizers
2034 toConstr a = mkConstr (dataTypeOf a) "ThModFinalizers" [] Data.Prefix
2035 dataTypeOf a = mkDataType "HsExpr.ThModFinalizers" [toConstr a]
2036 #endif
2037
2038 -- | Haskell Spliced Thing
2039 --
2040 -- Values that can result from running a splice.
2041 data HsSplicedThing id
2042 = HsSplicedExpr (HsExpr id) -- ^ Haskell Spliced Expression
2043 | HsSplicedTy (HsType id) -- ^ Haskell Spliced Type
2044 | HsSplicedPat (Pat id) -- ^ Haskell Spilced Pattern
2045 deriving Typeable
2046
2047 deriving instance (DataId id) => Data (HsSplicedThing id)
2048
2049 -- See Note [Pending Splices]
2050 type SplicePointName = Name
2051
2052 -- | Pending Renamer Splice
2053 data PendingRnSplice
2054 = PendingRnSplice UntypedSpliceFlavour SplicePointName (LHsExpr Name)
2055 deriving Data
2056
2057 data UntypedSpliceFlavour
2058 = UntypedExpSplice
2059 | UntypedPatSplice
2060 | UntypedTypeSplice
2061 | UntypedDeclSplice
2062 deriving Data
2063
2064 -- | Pending Type-checker Splice
2065 data PendingTcSplice
2066 = PendingTcSplice SplicePointName (LHsExpr Id)
2067 deriving Data
2068
2069
2070 {-
2071 Note [Pending Splices]
2072 ~~~~~~~~~~~~~~~~~~~~~~
2073 When we rename an untyped bracket, we name and lift out all the nested
2074 splices, so that when the typechecker hits the bracket, it can
2075 typecheck those nested splices without having to walk over the untyped
2076 bracket code. So for example
2077 [| f $(g x) |]
2078 looks like
2079
2080 HsBracket (HsApp (HsVar "f") (HsSpliceE _ (g x)))
2081
2082 which the renamer rewrites to
2083
2084 HsRnBracketOut (HsApp (HsVar f) (HsSpliceE sn (g x)))
2085 [PendingRnSplice UntypedExpSplice sn (g x)]
2086
2087 * The 'sn' is the Name of the splice point, the SplicePointName
2088
2089 * The PendingRnExpSplice gives the splice that splice-point name maps to;
2090 and the typechecker can now conveniently find these sub-expressions
2091
2092 * The other copy of the splice, in the second argument of HsSpliceE
2093 in the renamed first arg of HsRnBracketOut
2094 is used only for pretty printing
2095
2096 There are four varieties of pending splices generated by the renamer,
2097 distinguished by their UntypedSpliceFlavour
2098
2099 * Pending expression splices (UntypedExpSplice), e.g.,
2100 [|$(f x) + 2|]
2101
2102 UntypedExpSplice is also used for
2103 * quasi-quotes, where the pending expression expands to
2104 $(quoter "...blah...")
2105 (see RnSplice.makePending, HsQuasiQuote case)
2106
2107 * cross-stage lifting, where the pending expression expands to
2108 $(lift x)
2109 (see RnSplice.checkCrossStageLifting)
2110
2111 * Pending pattern splices (UntypedPatSplice), e.g.,
2112 [| \$(f x) -> x |]
2113
2114 * Pending type splices (UntypedTypeSplice), e.g.,
2115 [| f :: $(g x) |]
2116
2117 * Pending declaration (UntypedDeclSplice), e.g.,
2118 [| let $(f x) in ... |]
2119
2120 There is a fifth variety of pending splice, which is generated by the type
2121 checker:
2122
2123 * Pending *typed* expression splices, (PendingTcSplice), e.g.,
2124 [||1 + $$(f 2)||]
2125
2126 It would be possible to eliminate HsRnBracketOut and use HsBracketOut for the
2127 output of the renamer. However, when pretty printing the output of the renamer,
2128 e.g., in a type error message, we *do not* want to print out the pending
2129 splices. In contrast, when pretty printing the output of the type checker, we
2130 *do* want to print the pending splices. So splitting them up seems to make
2131 sense, although I hate to add another constructor to HsExpr.
2132 -}
2133
2134 instance OutputableBndrId id => Outputable (HsSplicedThing id) where
2135 ppr (HsSplicedExpr e) = ppr_expr e
2136 ppr (HsSplicedTy t) = ppr t
2137 ppr (HsSplicedPat p) = ppr p
2138
2139 instance (OutputableBndrId id) => Outputable (HsSplice id) where
2140 ppr s = pprSplice s
2141
2142 pprPendingSplice :: (OutputableBndrId id)
2143 => SplicePointName -> LHsExpr id -> SDoc
2144 pprPendingSplice n e = angleBrackets (ppr n <> comma <+> ppr e)
2145
2146 pprSplice :: (OutputableBndrId id) => HsSplice id -> SDoc
2147 pprSplice (HsTypedSplice n e) = ppr_splice (text "$$") n e
2148 pprSplice (HsUntypedSplice n e) = ppr_splice (text "$") n e
2149 pprSplice (HsQuasiQuote n q _ s) = ppr_quasi n q s
2150 pprSplice (HsSpliced _ thing) = ppr thing
2151
2152 ppr_quasi :: OutputableBndr id => id -> id -> FastString -> SDoc
2153 ppr_quasi n quoter quote = ifPprDebug (brackets (ppr n)) <>
2154 char '[' <> ppr quoter <> vbar <>
2155 ppr quote <> text "|]"
2156
2157 ppr_splice :: (OutputableBndrId id) => SDoc -> id -> LHsExpr id -> SDoc
2158 ppr_splice herald n e
2159 = herald <> ifPprDebug (brackets (ppr n)) <> eDoc
2160 where
2161 -- We use pprLExpr to match pprParendLExpr:
2162 -- Using pprLExpr makes sure that we go 'deeper'
2163 -- I think that is usually (always?) right
2164 pp_as_was = pprLExpr e
2165 eDoc = case unLoc e of
2166 HsPar _ -> pp_as_was
2167 HsVar _ -> pp_as_was
2168 _ -> parens pp_as_was
2169
2170 -- | Haskell Bracket
2171 data HsBracket id = ExpBr (LHsExpr id) -- [| expr |]
2172 | PatBr (LPat id) -- [p| pat |]
2173 | DecBrL [LHsDecl id] -- [d| decls |]; result of parser
2174 | DecBrG (HsGroup id) -- [d| decls |]; result of renamer
2175 | TypBr (LHsType id) -- [t| type |]
2176 | VarBr Bool id -- True: 'x, False: ''T
2177 -- (The Bool flag is used only in pprHsBracket)
2178 | TExpBr (LHsExpr id) -- [|| expr ||]
2179 deriving instance (DataId id) => Data (HsBracket id)
2180
2181 isTypedBracket :: HsBracket id -> Bool
2182 isTypedBracket (TExpBr {}) = True
2183 isTypedBracket _ = False
2184
2185 instance (OutputableBndrId id) => Outputable (HsBracket id) where
2186 ppr = pprHsBracket
2187
2188
2189 pprHsBracket :: (OutputableBndrId id) => HsBracket id -> SDoc
2190 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
2191 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
2192 pprHsBracket (DecBrG gp) = thBrackets (char 'd') (ppr gp)
2193 pprHsBracket (DecBrL ds) = thBrackets (char 'd') (vcat (map ppr ds))
2194 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
2195 pprHsBracket (VarBr True n) = char '\'' <> ppr n
2196 pprHsBracket (VarBr False n) = text "''" <> ppr n
2197 pprHsBracket (TExpBr e) = thTyBrackets (ppr e)
2198
2199 thBrackets :: SDoc -> SDoc -> SDoc
2200 thBrackets pp_kind pp_body = char '[' <> pp_kind <> vbar <+>
2201 pp_body <+> text "|]"
2202
2203 thTyBrackets :: SDoc -> SDoc
2204 thTyBrackets pp_body = text "[||" <+> pp_body <+> ptext (sLit "||]")
2205
2206 instance Outputable PendingRnSplice where
2207 ppr (PendingRnSplice _ n e) = pprPendingSplice n e
2208
2209 instance Outputable PendingTcSplice where
2210 ppr (PendingTcSplice n e) = pprPendingSplice n e
2211
2212 {-
2213 ************************************************************************
2214 * *
2215 \subsection{Enumerations and list comprehensions}
2216 * *
2217 ************************************************************************
2218 -}
2219
2220 -- | Arithmetic Sequence Information
2221 data ArithSeqInfo id
2222 = From (LHsExpr id)
2223 | FromThen (LHsExpr id)
2224 (LHsExpr id)
2225 | FromTo (LHsExpr id)
2226 (LHsExpr id)
2227 | FromThenTo (LHsExpr id)
2228 (LHsExpr id)
2229 (LHsExpr id)
2230 deriving instance (DataId id) => Data (ArithSeqInfo id)
2231
2232 instance (OutputableBndrId id) => Outputable (ArithSeqInfo id) where
2233 ppr (From e1) = hcat [ppr e1, pp_dotdot]
2234 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
2235 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
2236 ppr (FromThenTo e1 e2 e3)
2237 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
2238
2239 pp_dotdot :: SDoc
2240 pp_dotdot = text " .. "
2241
2242 {-
2243 ************************************************************************
2244 * *
2245 \subsection{HsMatchCtxt}
2246 * *
2247 ************************************************************************
2248 -}
2249
2250 data FunctionFixity = Prefix | Infix deriving (Typeable,Data,Eq)
2251
2252 instance Outputable FunctionFixity where
2253 ppr Prefix = text "Prefix"
2254 ppr Infix = text "Infix"
2255
2256 -- | Haskell Match Context
2257 --
2258 -- Context of a Match
2259 data HsMatchContext id
2260 = FunRhs (Located id) FunctionFixity -- ^Function binding for f, fixity
2261 | LambdaExpr -- ^Patterns of a lambda
2262 | CaseAlt -- ^Patterns and guards on a case alternative
2263 | IfAlt -- ^Guards of a multi-way if alternative
2264 | ProcExpr -- ^Patterns of a proc
2265 | PatBindRhs -- ^A pattern binding eg [y] <- e = e
2266
2267 | RecUpd -- ^Record update [used only in DsExpr to
2268 -- tell matchWrapper what sort of
2269 -- runtime error message to generate]
2270
2271 | StmtCtxt (HsStmtContext id) -- ^Pattern of a do-stmt, list comprehension,
2272 -- pattern guard, etc
2273
2274 | ThPatSplice -- ^A Template Haskell pattern splice
2275 | ThPatQuote -- ^A Template Haskell pattern quotation [p| (a,b) |]
2276 | PatSyn -- ^A pattern synonym declaration
2277 deriving Functor
2278 deriving instance (DataIdPost id) => Data (HsMatchContext id)
2279
2280 -- | Haskell Statement Context
2281 data HsStmtContext id
2282 = ListComp
2283 | MonadComp
2284 | PArrComp -- ^Parallel array comprehension
2285
2286 | DoExpr -- ^do { ... }
2287 | MDoExpr -- ^mdo { ... } ie recursive do-expression
2288 | ArrowExpr -- ^do-notation in an arrow-command context
2289
2290 | GhciStmtCtxt -- ^A command-line Stmt in GHCi pat <- rhs
2291 | PatGuard (HsMatchContext id) -- ^Pattern guard for specified thing
2292 | ParStmtCtxt (HsStmtContext id) -- ^A branch of a parallel stmt
2293 | TransStmtCtxt (HsStmtContext id) -- ^A branch of a transform stmt
2294 deriving Functor
2295 deriving instance (DataIdPost id) => Data (HsStmtContext id)
2296
2297 isListCompExpr :: HsStmtContext id -> Bool
2298 -- Uses syntax [ e | quals ]
2299 isListCompExpr ListComp = True
2300 isListCompExpr PArrComp = True
2301 isListCompExpr MonadComp = True
2302 isListCompExpr (ParStmtCtxt c) = isListCompExpr c
2303 isListCompExpr (TransStmtCtxt c) = isListCompExpr c
2304 isListCompExpr _ = False
2305
2306 isMonadCompExpr :: HsStmtContext id -> Bool
2307 isMonadCompExpr MonadComp = True
2308 isMonadCompExpr (ParStmtCtxt ctxt) = isMonadCompExpr ctxt
2309 isMonadCompExpr (TransStmtCtxt ctxt) = isMonadCompExpr ctxt
2310 isMonadCompExpr _ = False
2311
2312 matchSeparator :: HsMatchContext id -> SDoc
2313 matchSeparator (FunRhs {}) = text "="
2314 matchSeparator CaseAlt = text "->"
2315 matchSeparator IfAlt = text "->"
2316 matchSeparator LambdaExpr = text "->"
2317 matchSeparator ProcExpr = text "->"
2318 matchSeparator PatBindRhs = text "="
2319 matchSeparator (StmtCtxt _) = text "<-"
2320 matchSeparator RecUpd = panic "unused"
2321 matchSeparator ThPatSplice = panic "unused"
2322 matchSeparator ThPatQuote = panic "unused"
2323 matchSeparator PatSyn = panic "unused"
2324
2325 pprMatchContext :: (Outputable (NameOrRdrName id),Outputable id)
2326 => HsMatchContext id -> SDoc
2327 pprMatchContext ctxt
2328 | want_an ctxt = text "an" <+> pprMatchContextNoun ctxt
2329 | otherwise = text "a" <+> pprMatchContextNoun ctxt
2330 where
2331 want_an (FunRhs {}) = True -- Use "an" in front
2332 want_an ProcExpr = True
2333 want_an _ = False
2334
2335 pprMatchContextNoun :: (Outputable (NameOrRdrName id),Outputable id)
2336 => HsMatchContext id -> SDoc
2337 pprMatchContextNoun (FunRhs (L _ fun) _) = text "equation for"
2338 <+> quotes (ppr fun)
2339 pprMatchContextNoun CaseAlt = text "case alternative"
2340 pprMatchContextNoun IfAlt = text "multi-way if alternative"
2341 pprMatchContextNoun RecUpd = text "record-update construct"
2342 pprMatchContextNoun ThPatSplice = text "Template Haskell pattern splice"
2343 pprMatchContextNoun ThPatQuote = text "Template Haskell pattern quotation"
2344 pprMatchContextNoun PatBindRhs = text "pattern binding"
2345 pprMatchContextNoun LambdaExpr = text "lambda abstraction"
2346 pprMatchContextNoun ProcExpr = text "arrow abstraction"
2347 pprMatchContextNoun (StmtCtxt ctxt) = text "pattern binding in"
2348 $$ pprStmtContext ctxt
2349 pprMatchContextNoun PatSyn = text "pattern synonym declaration"
2350
2351 -----------------
2352 pprAStmtContext, pprStmtContext :: (Outputable id,
2353 Outputable (NameOrRdrName id))
2354 => HsStmtContext id -> SDoc
2355 pprAStmtContext ctxt = article <+> pprStmtContext ctxt
2356 where
2357 pp_an = text "an"
2358 pp_a = text "a"
2359 article = case ctxt of
2360 MDoExpr -> pp_an
2361 PArrComp -> pp_an
2362 GhciStmtCtxt -> pp_an
2363 _ -> pp_a
2364
2365
2366 -----------------
2367 pprStmtContext GhciStmtCtxt = text "interactive GHCi command"
2368 pprStmtContext DoExpr = text "'do' block"
2369 pprStmtContext MDoExpr = text "'mdo' block"
2370 pprStmtContext ArrowExpr = text "'do' block in an arrow command"
2371 pprStmtContext ListComp = text "list comprehension"
2372 pprStmtContext MonadComp = text "monad comprehension"
2373 pprStmtContext PArrComp = text "array comprehension"
2374 pprStmtContext (PatGuard ctxt) = text "pattern guard for" $$ pprMatchContext ctxt
2375
2376 -- Drop the inner contexts when reporting errors, else we get
2377 -- Unexpected transform statement
2378 -- in a transformed branch of
2379 -- transformed branch of
2380 -- transformed branch of monad comprehension
2381 pprStmtContext (ParStmtCtxt c)
2382 | opt_PprStyle_Debug = sep [text "parallel branch of", pprAStmtContext c]
2383 | otherwise = pprStmtContext c
2384 pprStmtContext (TransStmtCtxt c)
2385 | opt_PprStyle_Debug = sep [text "transformed branch of", pprAStmtContext c]
2386 | otherwise = pprStmtContext c
2387
2388
2389 -- Used to generate the string for a *runtime* error message
2390 matchContextErrString :: Outputable id
2391 => HsMatchContext id -> SDoc
2392 matchContextErrString (FunRhs (L _ fun) _) = text "function" <+> ppr fun
2393 matchContextErrString CaseAlt = text "case"
2394 matchContextErrString IfAlt = text "multi-way if"
2395 matchContextErrString PatBindRhs = text "pattern binding"
2396 matchContextErrString RecUpd = text "record update"
2397 matchContextErrString LambdaExpr = text "lambda"
2398 matchContextErrString ProcExpr = text "proc"
2399 matchContextErrString ThPatSplice = panic "matchContextErrString" -- Not used at runtime
2400 matchContextErrString ThPatQuote = panic "matchContextErrString" -- Not used at runtime
2401 matchContextErrString PatSyn = panic "matchContextErrString" -- Not used at runtime
2402 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
2403 matchContextErrString (StmtCtxt (TransStmtCtxt c)) = matchContextErrString (StmtCtxt c)
2404 matchContextErrString (StmtCtxt (PatGuard _)) = text "pattern guard"
2405 matchContextErrString (StmtCtxt GhciStmtCtxt) = text "interactive GHCi command"
2406 matchContextErrString (StmtCtxt DoExpr) = text "'do' block"
2407 matchContextErrString (StmtCtxt ArrowExpr) = text "'do' block"
2408 matchContextErrString (StmtCtxt MDoExpr) = text "'mdo' block"
2409 matchContextErrString (StmtCtxt ListComp) = text "list comprehension"
2410 matchContextErrString (StmtCtxt MonadComp) = text "monad comprehension"
2411 matchContextErrString (StmtCtxt PArrComp) = text "array comprehension"
2412
2413 pprMatchInCtxt :: (OutputableBndrId idR,
2414 Outputable (NameOrRdrName (NameOrRdrName idR)),
2415 Outputable body)
2416 => Match idR body -> SDoc
2417 pprMatchInCtxt match = hang (text "In" <+> pprMatchContext (m_ctxt match)
2418 <> colon)
2419 4 (pprMatch match)
2420
2421 pprStmtInCtxt :: (OutputableBndrId idL, OutputableBndrId idR, Outputable body)
2422 => HsStmtContext idL -> StmtLR idL idR body -> SDoc
2423 pprStmtInCtxt ctxt (LastStmt e _ _)
2424 | isListCompExpr ctxt -- For [ e | .. ], do not mutter about "stmts"
2425 = hang (text "In the expression:") 2 (ppr e)
2426
2427 pprStmtInCtxt ctxt stmt
2428 = hang (text "In a stmt of" <+> pprAStmtContext ctxt <> colon)
2429 2 (ppr_stmt stmt)
2430 where
2431 -- For Group and Transform Stmts, don't print the nested stmts!
2432 ppr_stmt (TransStmt { trS_by = by, trS_using = using
2433 , trS_form = form }) = pprTransStmt by using form
2434 ppr_stmt stmt = pprStmt stmt