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