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