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