never executed always true always false
1
2 {-# LANGUAGE ConstraintKinds #-}
3 {-# LANGUAGE DataKinds #-}
4 {-# LANGUAGE DeriveDataTypeable #-}
5 {-# LANGUAGE ExistentialQuantification #-}
6 {-# LANGUAGE FlexibleContexts #-}
7 {-# LANGUAGE FlexibleInstances #-}
8 {-# LANGUAGE ScopedTypeVariables #-}
9 {-# LANGUAGE TypeApplications #-}
10 {-# LANGUAGE TypeFamilyDependencies #-}
11 {-# LANGUAGE UndecidableInstances #-} -- Wrinkle in Note [Trees That Grow]
12 -- in module Language.Haskell.Syntax.Extension
13
14 {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
15
16 {-
17 (c) The University of Glasgow 2006
18 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
19 -}
20
21 -- See Note [Language.Haskell.Syntax.* Hierarchy] for why not GHC.Hs.*
22
23 -- | Abstract Haskell syntax for expressions.
24 module Language.Haskell.Syntax.Expr where
25
26 import GHC.Prelude
27
28 import Language.Haskell.Syntax.Decls
29 import Language.Haskell.Syntax.Pat
30 import Language.Haskell.Syntax.Lit
31 import Language.Haskell.Syntax.Extension
32 import Language.Haskell.Syntax.Type
33 import Language.Haskell.Syntax.Binds
34
35 -- others:
36 import GHC.Tc.Types.Evidence
37 import GHC.Core.DataCon (FieldLabelString)
38 import GHC.Types.Name
39 import GHC.Types.Basic
40 import GHC.Types.Fixity
41 import GHC.Types.SourceText
42 import GHC.Types.SrcLoc
43 import GHC.Unit.Module (ModuleName)
44 import GHC.Utils.Outputable
45 import GHC.Utils.Panic
46 import GHC.Data.FastString
47 import GHC.Core.Type
48
49 -- libraries:
50 import Data.Data hiding (Fixity(..))
51 import qualified Data.Data as Data (Fixity(..))
52
53 import GHCi.RemoteTypes ( ForeignRef )
54 import qualified Language.Haskell.TH as TH (Q)
55
56 {- Note [RecordDotSyntax field updates]
57 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
58 The extensions @OverloadedRecordDot@ @OverloadedRecordUpdate@ together
59 enable record updates like @a{foo.bar.baz = 1}@. Introducing this
60 syntax slightly complicates parsing. This note explains how it's done.
61
62 In the event a record is being constructed or updated, it's this
63 production that's in play:
64 @
65 aexp1 -> aexp1 '{' fbinds '}' {
66 ...
67 mkHsRecordPV ... $1 (snd $3)
68 }
69 @
70 @fbinds@ is a list of field bindings. @mkHsRecordPV@ is a function of
71 the @DisambECP b@ typeclass, see Note [Ambiguous syntactic
72 categories].
73
74 The "normal" rules for an @fbind@ are:
75 @
76 fbind
77 : qvar '=' texp
78 | qvar
79 @
80 These rules compute values of @LHsRecField GhcPs (Located b)@. They
81 apply in the context of record construction, record updates, record
82 patterns and record expressions. That is, @b@ ranges over @HsExpr
83 GhcPs@, @HsPat GhcPs@ and @HsCmd GhcPs@.
84
85 When @OverloadedRecordDot@ and @OverloadedRecordUpdate@ are both
86 enabled, two additional @fbind@ rules are admitted:
87 @
88 | field TIGHT_INFIX_PROJ fieldToUpdate '=' texp
89 | field TIGHT_INFIX_PROJ fieldToUpdate
90 @
91
92 These rules only make sense when parsing record update expressions
93 (that is, patterns and commands cannot be parsed by these rules and
94 neither record constructions).
95
96 The results of these new rules cannot be represented by @LHsRecField
97 GhcPs (LHsExpr GhcPs)@ values as the type is defined today. We
98 minimize modifying existing code by having these new rules calculate
99 @LHsRecProj GhcPs (LHsExpr GhcPs)@ ("record projection") values
100 instead:
101 @
102 newtype FieldLabelStrings = FieldLabelStrings [XRec p (DotFieldOcc p)]
103 type RecProj arg = HsFieldBind FieldLabelStrings arg
104 type LHsRecProj p arg = XRec p (RecProj arg)
105 @
106
107 The @fbind@ rule is then given the type @fbind :: { forall b.
108 DisambECP b => PV (Fbind b) }@ accomodating both alternatives:
109 @
110 type Fbind b = Either
111 (LHsRecField GhcPs (LocatedA b))
112 ( LHsRecProj GhcPs (LocatedA b))
113 @
114
115 In @data HsExpr p@, the @RecordUpd@ constuctor indicates regular
116 updates vs. projection updates by means of the @rupd_flds@ member
117 type, an @Either@ instance:
118 @
119 | RecordUpd
120 { rupd_ext :: XRecordUpd p
121 , rupd_expr :: LHsExpr p
122 , rupd_flds :: Either [LHsRecUpdField p] [LHsRecUpdProj p]
123 }
124 @
125 Here,
126 @
127 type RecUpdProj p = RecProj p (LHsExpr p)
128 type LHsRecUpdProj p = XRec p (RecUpdProj p)
129 @
130 and @Left@ values indicating regular record update, @Right@ values
131 updates desugared to @setField@s.
132
133 If @OverloadedRecordUpdate@ is enabled, any updates parsed as
134 @LHsRecField GhcPs@ values are converted to @LHsRecUpdProj GhcPs@
135 values (see function @mkRdrRecordUpd@ in 'GHC.Parser.PostProcess').
136 -}
137
138 -- | RecordDotSyntax field updates
139
140 type LFieldLabelStrings p = XRec p (FieldLabelStrings p)
141
142 newtype FieldLabelStrings p =
143 FieldLabelStrings [XRec p (DotFieldOcc p)]
144
145 instance (UnXRec p, Outputable (XRec p FieldLabelString)) => Outputable (FieldLabelStrings p) where
146 ppr (FieldLabelStrings flds) =
147 hcat (punctuate dot (map (ppr . unXRec @p) flds))
148
149 instance (UnXRec p, Outputable (XRec p FieldLabelString)) => OutputableBndr (FieldLabelStrings p) where
150 pprInfixOcc = pprFieldLabelStrings
151 pprPrefixOcc = pprFieldLabelStrings
152
153 instance (UnXRec p, Outputable (XRec p FieldLabelString)) => OutputableBndr (Located (FieldLabelStrings p)) where
154 pprInfixOcc = pprInfixOcc . unLoc
155 pprPrefixOcc = pprInfixOcc . unLoc
156
157 pprFieldLabelStrings :: forall p. (UnXRec p, Outputable (XRec p FieldLabelString)) => FieldLabelStrings p -> SDoc
158 pprFieldLabelStrings (FieldLabelStrings flds) =
159 hcat (punctuate dot (map (ppr . unXRec @p) flds))
160
161 instance Outputable(XRec p FieldLabelString) => Outputable (DotFieldOcc p) where
162 ppr (DotFieldOcc _ s) = ppr s
163 ppr XDotFieldOcc{} = text "XDotFieldOcc"
164
165 -- Field projection updates (e.g. @foo.bar.baz = 1@). See Note
166 -- [RecordDotSyntax field updates].
167 type RecProj p arg = HsFieldBind (LFieldLabelStrings p) arg
168
169 -- The phantom type parameter @p@ is for symmetry with @LHsRecField p
170 -- arg@ in the definition of @data Fbind@ (see GHC.Parser.Process).
171 type LHsRecProj p arg = XRec p (RecProj p arg)
172
173 -- These two synonyms are used in the definition of syntax @RecordUpd@
174 -- below.
175 type RecUpdProj p = RecProj p (LHsExpr p)
176 type LHsRecUpdProj p = XRec p (RecUpdProj p)
177
178 {-
179 ************************************************************************
180 * *
181 \subsection{Expressions proper}
182 * *
183 ************************************************************************
184 -}
185
186 -- * Expressions proper
187
188 -- | Located Haskell Expression
189 type LHsExpr p = XRec p (HsExpr p)
190 -- ^ May have 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnComma' when
191 -- in a list
192
193 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
194
195 -------------------------
196 {- Note [NoSyntaxExpr]
197 ~~~~~~~~~~~~~~~~~~~~~~
198 Syntax expressions can be missing (NoSyntaxExprRn or NoSyntaxExprTc)
199 for several reasons:
200
201 1. As described in Note [Rebindable if]
202
203 2. In order to suppress "not in scope: xyz" messages when a bit of
204 rebindable syntax does not apply. For example, when using an irrefutable
205 pattern in a BindStmt, we don't need a `fail` operator.
206
207 3. Rebindable syntax might just not make sense. For example, a BodyStmt
208 contains the syntax for `guard`, but that's used only in monad comprehensions.
209 If we had more of a whiz-bang type system, we might be able to rule this
210 case out statically.
211 -}
212
213 -- | Syntax Expression
214 --
215 -- SyntaxExpr is represents the function used in interpreting rebindable
216 -- syntax. In the parser, we have no information to supply; in the renamer,
217 -- we have the name of the function (but see
218 -- Note [Monad fail : Rebindable syntax, overloaded strings] for a wrinkle)
219 -- and in the type-checker we have a more elaborate structure 'SyntaxExprTc'.
220 --
221 -- In some contexts, rebindable syntax is not implemented, and so we have
222 -- constructors to represent that possibility in both the renamer and
223 -- typechecker instantiations.
224 --
225 -- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for
226 -- @(>>=)@, and then instantiated by the type checker with its type args
227 -- etc
228 type family SyntaxExpr p
229
230 -- | Command Syntax Table (for Arrow syntax)
231 type CmdSyntaxTable p = [(Name, HsExpr p)]
232 -- See Note [CmdSyntaxTable]
233
234 {-
235 Note [CmdSyntaxTable]
236 ~~~~~~~~~~~~~~~~~~~~~
237 Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps
238 track of the methods needed for a Cmd.
239
240 * Before the renamer, this list is an empty list
241
242 * After the renamer, it takes the form @[(std_name, HsVar actual_name)]@
243 For example, for the 'arr' method
244 * normal case: (GHC.Control.Arrow.arr, HsVar GHC.Control.Arrow.arr)
245 * with rebindable syntax: (GHC.Control.Arrow.arr, arr_22)
246 where @arr_22@ is whatever 'arr' is in scope
247
248 * After the type checker, it takes the form [(std_name, <expression>)]
249 where <expression> is the evidence for the method. This evidence is
250 instantiated with the class, but is still polymorphic in everything
251 else. For example, in the case of 'arr', the evidence has type
252 forall b c. (b->c) -> a b c
253 where 'a' is the ambient type of the arrow. This polymorphism is
254 important because the desugarer uses the same evidence at multiple
255 different types.
256
257 This is Less Cool than what we normally do for rebindable syntax, which is to
258 make fully-instantiated piece of evidence at every use site. The Cmd way
259 is Less Cool because
260 * The renamer has to predict which methods are needed.
261 See the tedious GHC.Rename.Expr.methodNamesCmd.
262
263 * The desugarer has to know the polymorphic type of the instantiated
264 method. This is checked by Inst.tcSyntaxName, but is less flexible
265 than the rest of rebindable syntax, where the type is less
266 pre-ordained. (And this flexibility is useful; for example we can
267 typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.)
268 -}
269
270 {-
271 Note [Record selectors in the AST]
272 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
273 Here is how record selectors are expressed in GHC's AST:
274
275 Example data type
276 data T = MkT { size :: Int }
277
278 Record selectors:
279 | GhcPs | GhcRn | GhcTc |
280 ----------------------------------------------------------------------------------|
281 size (assuming one | HsVar | HsRecSel | HsRecSel |
282 'size' in scope) | | | |
283 ----------------------|--------------|----------------------|---------------------|
284 .size (assuming | HsProjection | getField @"size" | getField @"size" |
285 OverloadedRecordDot) | | | |
286 ----------------------|--------------|----------------------|---------------------|
287 e.size (assuming | HsGetField | getField @"size" e | getField @"size" e |
288 OverloadedRecordDot) | | | |
289
290 NB 1: DuplicateRecordFields makes no difference to the first row of
291 this table, except that if 'size' is a field of more than one data
292 type, then a naked use of the record selector 'size' may well be
293 ambiguous. You have to use a qualified name. And there is no way to do
294 this if both data types are declared in the same module.
295
296 NB 2: The notation getField @"size" e is short for
297 HsApp (HsAppType (HsVar "getField") (HsWC (HsTyLit (HsStrTy "size")) [])) e.
298 We track the original parsed syntax via HsExpanded.
299
300 -}
301
302 {-
303 Note [Non-overloaded record field selectors]
304 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
305 Consider
306 data T = MkT { x,y :: Int }
307 f r x = x + y r
308
309 This parses with HsVar for x, y, r on the RHS of f. Later, the renamer
310 recognises that y in the RHS of f is really a record selector, and
311 changes it to a HsRecSel. In contrast x is locally bound, shadowing
312 the record selector, and stays as an HsVar.
313
314 The renamer adds the Name of the record selector into the XCFieldOcc
315 extension field, The typechecker keeps HsRecSel as HsRecSel, and
316 transforms the record-selector Name to an Id.
317 -}
318
319 -- | A Haskell expression.
320 data HsExpr p
321 = HsVar (XVar p)
322 (LIdP p) -- ^ Variable
323 -- See Note [Located RdrNames]
324
325 | HsUnboundVar (XUnboundVar p)
326 OccName -- ^ Unbound variable; also used for "holes"
327 -- (_ or _x).
328 -- Turned from HsVar to HsUnboundVar by the
329 -- renamer, when it finds an out-of-scope
330 -- variable or hole.
331 -- The (XUnboundVar p) field becomes an HoleExprRef
332 -- after typechecking; this is where the
333 -- erroring expression will be written after
334 -- solving. See Note [Holes] in GHC.Tc.Types.Constraint.
335
336
337 | HsRecSel (XRecSel p)
338 (FieldOcc p) -- ^ Variable pointing to record selector
339 -- See Note [Non-overloaded record field selectors] and
340 -- Note [Record selectors in the AST]
341
342 | HsOverLabel (XOverLabel p) FastString
343 -- ^ Overloaded label (Note [Overloaded labels] in GHC.OverloadedLabels)
344
345 | HsIPVar (XIPVar p)
346 HsIPName -- ^ Implicit parameter (not in use after typechecking)
347 | HsOverLit (XOverLitE p)
348 (HsOverLit p) -- ^ Overloaded literals
349
350 | HsLit (XLitE p)
351 (HsLit p) -- ^ Simple (non-overloaded) literals
352
353 | HsLam (XLam p)
354 (MatchGroup p (LHsExpr p))
355 -- ^ Lambda abstraction. Currently always a single match
356 --
357 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnLam',
358 -- 'GHC.Parser.Annotation.AnnRarrow',
359
360 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
361
362 | HsLamCase (XLamCase p) (MatchGroup p (LHsExpr p)) -- ^ Lambda-case
363 --
364 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnLam',
365 -- 'GHC.Parser.Annotation.AnnCase','GHC.Parser.Annotation.AnnOpen',
366 -- 'GHC.Parser.Annotation.AnnClose'
367
368 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
369
370 | HsApp (XApp p) (LHsExpr p) (LHsExpr p) -- ^ Application
371
372 | HsAppType (XAppTypeE p) -- After typechecking: the type argument
373 (LHsExpr p)
374 (LHsWcType (NoGhcTc p)) -- ^ Visible type application
375 --
376 -- Explicit type argument; e.g f @Int x y
377 -- NB: Has wildcards, but no implicit quantification
378 --
379 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnAt',
380
381 -- | Operator applications:
382 -- NB Bracketed ops such as (+) come out as Vars.
383
384 -- NB Sadly, we need an expr for the operator in an OpApp/Section since
385 -- the renamer may turn a HsVar into HsRecSel or HsUnboundVar
386
387 | OpApp (XOpApp p)
388 (LHsExpr p) -- left operand
389 (LHsExpr p) -- operator
390 (LHsExpr p) -- right operand
391
392 -- | Negation operator. Contains the negated expression and the name
393 -- of 'negate'
394 --
395 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnMinus'
396
397 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
398 | NegApp (XNegApp p)
399 (LHsExpr p)
400 (SyntaxExpr p)
401
402 -- | - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen' @'('@,
403 -- 'GHC.Parser.Annotation.AnnClose' @')'@
404
405 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
406 | HsPar (XPar p)
407 !(LHsToken "(" p)
408 (LHsExpr p) -- ^ Parenthesised expr; see Note [Parens in HsSyn]
409 !(LHsToken ")" p)
410
411 | SectionL (XSectionL p)
412 (LHsExpr p) -- operand; see Note [Sections in HsSyn]
413 (LHsExpr p) -- operator
414 | SectionR (XSectionR p)
415 (LHsExpr p) -- operator; see Note [Sections in HsSyn]
416 (LHsExpr p) -- operand
417
418 -- | Used for explicit tuples and sections thereof
419 --
420 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen',
421 -- 'GHC.Parser.Annotation.AnnClose'
422
423 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
424 -- Note [ExplicitTuple]
425 | ExplicitTuple
426 (XExplicitTuple p)
427 [HsTupArg p]
428 Boxity
429
430 -- | Used for unboxed sum types
431 --
432 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen' @'(#'@,
433 -- 'GHC.Parser.Annotation.AnnVbar', 'GHC.Parser.Annotation.AnnClose' @'#)'@,
434 --
435 -- There will be multiple 'GHC.Parser.Annotation.AnnVbar', (1 - alternative) before
436 -- the expression, (arity - alternative) after it
437 | ExplicitSum
438 (XExplicitSum p)
439 ConTag -- Alternative (one-based)
440 Arity -- Sum arity
441 (LHsExpr p)
442
443 -- | - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnCase',
444 -- 'GHC.Parser.Annotation.AnnOf','GHC.Parser.Annotation.AnnOpen' @'{'@,
445 -- 'GHC.Parser.Annotation.AnnClose' @'}'@
446
447 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
448 | HsCase (XCase p)
449 (LHsExpr p)
450 (MatchGroup p (LHsExpr p))
451
452 -- | - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnIf',
453 -- 'GHC.Parser.Annotation.AnnSemi',
454 -- 'GHC.Parser.Annotation.AnnThen','GHC.Parser.Annotation.AnnSemi',
455 -- 'GHC.Parser.Annotation.AnnElse',
456
457 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
458 | HsIf (XIf p) -- GhcPs: this is a Bool; False <=> do not use
459 -- rebindable syntax
460 (LHsExpr p) -- predicate
461 (LHsExpr p) -- then part
462 (LHsExpr p) -- else part
463
464 -- | Multi-way if
465 --
466 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnIf'
467 -- 'GHC.Parser.Annotation.AnnOpen','GHC.Parser.Annotation.AnnClose',
468
469 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
470 | HsMultiIf (XMultiIf p) [LGRHS p (LHsExpr p)]
471
472 -- | let(rec)
473 --
474 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnLet',
475 -- 'GHC.Parser.Annotation.AnnOpen' @'{'@,
476 -- 'GHC.Parser.Annotation.AnnClose' @'}'@,'GHC.Parser.Annotation.AnnIn'
477
478 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
479 | HsLet (XLet p)
480 !(LHsToken "let" p)
481 (HsLocalBinds p)
482 !(LHsToken "in" p)
483 (LHsExpr p)
484
485 -- | - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnDo',
486 -- 'GHC.Parser.Annotation.AnnOpen', 'GHC.Parser.Annotation.AnnSemi',
487 -- 'GHC.Parser.Annotation.AnnVbar',
488 -- 'GHC.Parser.Annotation.AnnClose'
489
490 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
491 | HsDo (XDo p) -- Type of the whole expression
492 HsDoFlavour
493 (XRec p [ExprLStmt p]) -- "do":one or more stmts
494
495 -- | Syntactic list: [a,b,c,...]
496 --
497 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen' @'['@,
498 -- 'GHC.Parser.Annotation.AnnClose' @']'@
499
500 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
501 -- See Note [Empty lists]
502 | ExplicitList
503 (XExplicitList p) -- Gives type of components of list
504 [LHsExpr p]
505
506 -- | Record construction
507 --
508 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen' @'{'@,
509 -- 'GHC.Parser.Annotation.AnnDotdot','GHC.Parser.Annotation.AnnClose' @'}'@
510
511 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
512 | RecordCon
513 { rcon_ext :: XRecordCon p
514 , rcon_con :: XRec p (ConLikeP p) -- The constructor
515 , rcon_flds :: HsRecordBinds p } -- The fields
516
517 -- | Record update
518 --
519 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen' @'{'@,
520 -- 'GHC.Parser.Annotation.AnnDotdot','GHC.Parser.Annotation.AnnClose' @'}'@
521 -- 'GHC.Parser.Annotation.AnnComma, 'GHC.Parser.Annotation.AnnDot',
522 -- 'GHC.Parser.Annotation.AnnClose' @'}'@
523
524 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
525 | RecordUpd
526 { rupd_ext :: XRecordUpd p
527 , rupd_expr :: LHsExpr p
528 , rupd_flds :: Either [LHsRecUpdField p] [LHsRecUpdProj p]
529 }
530 -- For a type family, the arg types are of the *instance* tycon,
531 -- not the family tycon
532
533 -- | Record field selection e.g @z.x@.
534 --
535 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnDot'
536
537 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
538
539 -- This case only arises when the OverloadedRecordDot langauge
540 -- extension is enabled. See Note [Record Selectors in the AST].
541 | HsGetField {
542 gf_ext :: XGetField p
543 , gf_expr :: LHsExpr p
544 , gf_field :: XRec p (DotFieldOcc p)
545 }
546
547 -- | Record field selector. e.g. @(.x)@ or @(.x.y)@
548 --
549 -- This case only arises when the OverloadedRecordDot langauge
550 -- extensions is enabled. See Note [Record Selectors in the AST].
551
552 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpenP'
553 -- 'GHC.Parser.Annotation.AnnDot', 'GHC.Parser.Annotation.AnnCloseP'
554
555 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
556 | HsProjection {
557 proj_ext :: XProjection p
558 , proj_flds :: [XRec p (DotFieldOcc p)]
559 }
560
561 -- | Expression with an explicit type signature. @e :: type@
562 --
563 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnDcolon'
564
565 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
566 | ExprWithTySig
567 (XExprWithTySig p)
568
569 (LHsExpr p)
570 (LHsSigWcType (NoGhcTc p))
571
572 -- | Arithmetic sequence
573 --
574 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen' @'['@,
575 -- 'GHC.Parser.Annotation.AnnComma','GHC.Parser.Annotation.AnnDotdot',
576 -- 'GHC.Parser.Annotation.AnnClose' @']'@
577
578 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
579 | ArithSeq
580 (XArithSeq p)
581 (Maybe (SyntaxExpr p))
582 -- For OverloadedLists, the fromList witness
583 (ArithSeqInfo p)
584
585 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
586
587 -----------------------------------------------------------
588 -- MetaHaskell Extensions
589
590 -- | - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen',
591 -- 'GHC.Parser.Annotation.AnnOpenE','GHC.Parser.Annotation.AnnOpenEQ',
592 -- 'GHC.Parser.Annotation.AnnClose','GHC.Parser.Annotation.AnnCloseQ'
593
594 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
595 | HsBracket (XBracket p) (HsBracket p)
596
597 -- See Note [Pending Splices]
598 | HsRnBracketOut
599 (XRnBracketOut p)
600 (HsBracket (HsBracketRn p)) -- Output of the renamer is the *original* renamed
601 -- expression, plus
602 [PendingRnSplice' p] -- _renamed_ splices to be type checked
603
604 | HsTcBracketOut
605 (XTcBracketOut p)
606 (Maybe QuoteWrapper) -- The wrapper to apply type and dictionary argument
607 -- to the quote.
608 (HsBracket (HsBracketRn p)) -- Output of the type checker is the *original*
609 -- renamed expression, plus
610 [PendingTcSplice' p] -- _typechecked_ splices to be
611 -- pasted back in by the desugarer
612
613 -- | - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen',
614 -- 'GHC.Parser.Annotation.AnnClose'
615
616 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
617 | HsSpliceE (XSpliceE p) (HsSplice p)
618
619 -----------------------------------------------------------
620 -- Arrow notation extension
621
622 -- | @proc@ notation for Arrows
623 --
624 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnProc',
625 -- 'GHC.Parser.Annotation.AnnRarrow'
626
627 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
628 | HsProc (XProc p)
629 (LPat p) -- arrow abstraction, proc
630 (LHsCmdTop p) -- body of the abstraction
631 -- always has an empty stack
632
633 ---------------------------------------
634 -- static pointers extension
635 -- | - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnStatic',
636
637 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
638 | HsStatic (XStatic p) -- Free variables of the body
639 (LHsExpr p) -- Body
640
641 ---------------------------------------
642 -- Expressions annotated with pragmas, written as {-# ... #-}
643 | HsPragE (XPragE p) (HsPragE p) (LHsExpr p)
644
645 | XExpr !(XXExpr p)
646 -- Note [Trees That Grow] in Language.Haskell.Syntax.Extension for the
647 -- general idea, and Note [Rebindable syntax and HsExpansion] in GHC.Hs.Expr
648 -- for an example of how we use it.
649
650 -- | The AST used to hard-refer to GhcPass, which was a layer violation. For now,
651 -- we paper it over with this new extension point.
652 type family HsBracketRn p
653 type family PendingRnSplice' p
654 type family PendingTcSplice' p
655
656 -- ---------------------------------------------------------------------
657
658 data DotFieldOcc p
659 = DotFieldOcc
660 { dfoExt :: XCDotFieldOcc p
661 , dfoLabel :: XRec p FieldLabelString
662 }
663 | XDotFieldOcc !(XXDotFieldOcc p)
664
665 -- ---------------------------------------------------------------------
666
667 -- | A pragma, written as {-# ... #-}, that may appear within an expression.
668 data HsPragE p
669 = HsPragSCC (XSCC p)
670 SourceText -- Note [Pragma source text] in GHC.Types.SourceText
671 StringLiteral -- "set cost centre" SCC pragma
672
673 -- | - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen',
674 -- 'GHC.Parser.Annotation.AnnOpen' @'{-\# GENERATED'@,
675 -- 'GHC.Parser.Annotation.AnnVal','GHC.Parser.Annotation.AnnVal',
676 -- 'GHC.Parser.Annotation.AnnColon','GHC.Parser.Annotation.AnnVal',
677 -- 'GHC.Parser.Annotation.AnnMinus',
678 -- 'GHC.Parser.Annotation.AnnVal','GHC.Parser.Annotation.AnnColon',
679 -- 'GHC.Parser.Annotation.AnnVal',
680 -- 'GHC.Parser.Annotation.AnnClose' @'\#-}'@
681
682 | XHsPragE !(XXPragE p)
683
684 -- | Located Haskell Tuple Argument
685 --
686 -- 'HsTupArg' is used for tuple sections
687 -- @(,a,)@ is represented by
688 -- @ExplicitTuple [Missing ty1, Present a, Missing ty3]@
689 -- Which in turn stands for @(\x:ty1 \y:ty2. (x,a,y))@
690 type LHsTupArg id = XRec id (HsTupArg id)
691 -- | - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnComma'
692
693 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
694
695 -- | Haskell Tuple Argument
696 data HsTupArg id
697 = Present (XPresent id) (LHsExpr id) -- ^ The argument
698 | Missing (XMissing id) -- ^ The argument is missing, but this is its type
699 | XTupArg !(XXTupArg id) -- ^ Extension point; see Note [Trees That Grow]
700 -- in Language.Haskell.Syntax.Extension
701
702 {-
703 Note [Parens in HsSyn]
704 ~~~~~~~~~~~~~~~~~~~~~~
705 HsPar (and ParPat in patterns, HsParTy in types) is used as follows
706
707 * HsPar is required; the pretty printer does not add parens.
708
709 * HsPars are respected when rearranging operator fixities.
710 So a * (b + c) means what it says (where the parens are an HsPar)
711
712 * For ParPat and HsParTy the pretty printer does add parens but this should be
713 a no-op for ParsedSource, based on the pretty printer round trip feature
714 introduced in
715 https://phabricator.haskell.org/rGHC499e43824bda967546ebf95ee33ec1f84a114a7c
716
717 * ParPat and HsParTy are pretty printed as '( .. )' regardless of whether or
718 not they are strictly necessary. This should be addressed when #13238 is
719 completed, to be treated the same as HsPar.
720
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 NoSyntaxExpr to mean "use the old built-in typing rule".
743
744 A further complication is that, in the `deriving` code, we never want
745 to use rebindable syntax. So, even in GhcPs, we want to denote whether
746 to use rebindable syntax or not. This is done via the type instance
747 for XIf GhcPs.
748
749 Note [Record Update HsWrapper]
750 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
751 There is a wrapper in RecordUpd which is used for the *required*
752 constraints for pattern synonyms. This wrapper is created in the
753 typechecking and is then directly used in the desugaring without
754 modification.
755
756 For example, if we have the record pattern synonym P,
757 pattern P :: (Show a) => a -> Maybe a
758 pattern P{x} = Just x
759
760 foo = (Just True) { x = False }
761 then `foo` desugars to something like
762 foo = case Just True of
763 P x -> P False
764 hence we need to provide the correct dictionaries to P's matcher on
765 the RHS so that we can build the expression.
766
767 Note [Located RdrNames]
768 ~~~~~~~~~~~~~~~~~~~~~~~
769 A number of syntax elements have seemingly redundant locations
770 attached to them. This is deliberate, to allow transformations making
771 use of the exact print annotations to easily correlate a Located Name
772 in the RenamedSource with a Located RdrName in the ParsedSource.
773
774 There are unfortunately enough differences between the ParsedSource
775 and the RenamedSource that the exact print annotations cannot be used
776 directly with RenamedSource, so this allows a simple mapping to be
777 used based on the location.
778
779 Note [ExplicitTuple]
780 ~~~~~~~~~~~~~~~~~~~~
781 An ExplicitTuple is never just a data constructor like (,,,).
782 That is, the `[LHsTupArg p]` argument of `ExplicitTuple` has at least
783 one `Present` member (and is thus never empty).
784
785 A tuple data constructor like () or (,,,) is parsed as an `HsVar`, not an
786 `ExplicitTuple`, and stays that way. This is important for two reasons:
787
788 1. We don't need -XTupleSections for (,,,)
789 2. The type variables in (,,,) can be instantiated with visible type application.
790 That is,
791
792 (,,) :: forall a b c. a -> b -> c -> (a,b,c)
793 (True,,) :: forall {b} {c}. b -> c -> (Bool,b,c)
794
795 Note that the tuple section has *inferred* arguments, while the data
796 constructor has *specified* ones.
797 (See Note [Required, Specified, and Inferred for types] in GHC.Tc.TyCl
798 for background.)
799
800 Sadly, the grammar for this is actually ambiguous, and it's only thanks to the
801 preference of a shift in a shift/reduce conflict that the parser works as this
802 Note details. Search for a reference to this Note in GHC.Parser for further
803 explanation.
804
805 Note [Empty lists]
806 ~~~~~~~~~~~~~~~~~~
807 An empty list could be considered either a data constructor (stored with
808 HsVar) or an ExplicitList. This Note describes how empty lists flow through the
809 various phases and why.
810
811 Parsing
812 -------
813 An empty list is parsed by the sysdcon nonterminal. It thus comes to life via
814 HsVar nilDataCon (defined in GHC.Builtin.Types). A freshly-parsed (HsExpr GhcPs) empty list
815 is never a ExplicitList.
816
817 Renaming
818 --------
819 If -XOverloadedLists is enabled, we must type-check the empty list as if it
820 were a call to fromListN. (This is true regardless of the setting of
821 -XRebindableSyntax.) This is very easy if the empty list is an ExplicitList,
822 but an annoying special case if it's an HsVar. So the renamer changes a
823 HsVar nilDataCon to an ExplicitList [], but only if -XOverloadedLists is on.
824 (Why not always? Read on, dear friend.) This happens in the HsVar case of rnExpr.
825
826 Type-checking
827 -------------
828 We want to accept an expression like [] @Int. To do this, we must infer that
829 [] :: forall a. [a]. This is easy if [] is a HsVar with the right DataCon inside.
830 However, the type-checking for explicit lists works differently: [x,y,z] is never
831 polymorphic. Instead, we unify the types of x, y, and z together, and use the
832 unified type as the argument to the cons and nil constructors. Thus, treating
833 [] as an empty ExplicitList in the type-checker would prevent [] @Int from working.
834
835 However, if -XOverloadedLists is on, then [] @Int really shouldn't be allowed:
836 it's just like fromListN 0 [] @Int. Since
837 fromListN :: forall list. IsList list => Int -> [Item list] -> list
838 that expression really should be rejected. Thus, the renamer's behaviour is
839 exactly what we want: treat [] as a datacon when -XNoOverloadedLists, and as
840 an empty ExplicitList when -XOverloadedLists.
841
842 See also #13680, which requested [] @Int to work.
843 -}
844
845
846 -----------------------
847 pprExternalSrcLoc :: (StringLiteral,(Int,Int),(Int,Int)) -> SDoc
848 pprExternalSrcLoc (StringLiteral _ src _,(n1,n2),(n3,n4))
849 = ppr (src,(n1,n2),(n3,n4))
850
851 {-
852 HsSyn records exactly where the user put parens, with HsPar.
853 So generally speaking we print without adding any parens.
854 However, some code is internally generated, and in some places
855 parens are absolutely required; so for these places we use
856 pprParendLExpr (but don't print double parens of course).
857
858 For operator applications we don't add parens, because the operator
859 fixities should do the job, except in debug mode (-dppr-debug) so we
860 can see the structure of the parse tree.
861 -}
862
863 {-
864 ************************************************************************
865 * *
866 \subsection{Commands (in arrow abstractions)}
867 * *
868 ************************************************************************
869
870 We re-use HsExpr to represent these.
871 -}
872
873 -- | Located Haskell Command (for arrow syntax)
874 type LHsCmd id = XRec id (HsCmd id)
875
876 -- | Haskell Command (e.g. a "statement" in an Arrow proc block)
877 data HsCmd id
878 -- | - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.Annlarrowtail',
879 -- 'GHC.Parser.Annotation.Annrarrowtail','GHC.Parser.Annotation.AnnLarrowtail',
880 -- 'GHC.Parser.Annotation.AnnRarrowtail'
881
882 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
883 = HsCmdArrApp -- Arrow tail, or arrow application (f -< arg)
884 (XCmdArrApp id) -- type of the arrow expressions f,
885 -- of the form a t t', where arg :: t
886 (LHsExpr id) -- arrow expression, f
887 (LHsExpr id) -- input expression, arg
888 HsArrAppType -- higher-order (-<<) or first-order (-<)
889 Bool -- True => right-to-left (f -< arg)
890 -- False => left-to-right (arg >- f)
891
892 -- | - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpenB' @'(|'@,
893 -- 'GHC.Parser.Annotation.AnnCloseB' @'|)'@
894
895 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
896 | HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |)
897 (XCmdArrForm id)
898 (LHsExpr id) -- The operator.
899 -- After type-checking, a type abstraction to be
900 -- applied to the type of the local environment tuple
901 LexicalFixity -- Whether the operator appeared prefix or infix when
902 -- parsed.
903 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
904 -- were converted from OpApp's by the renamer
905 [LHsCmdTop id] -- argument commands
906
907 | HsCmdApp (XCmdApp id)
908 (LHsCmd id)
909 (LHsExpr id)
910
911 | HsCmdLam (XCmdLam id)
912 (MatchGroup id (LHsCmd id)) -- kappa
913 -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnLam',
914 -- 'GHC.Parser.Annotation.AnnRarrow',
915
916 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
917
918 | HsCmdPar (XCmdPar id)
919 !(LHsToken "(" id)
920 (LHsCmd id) -- parenthesised command
921 !(LHsToken ")" id)
922 -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnOpen' @'('@,
923 -- 'GHC.Parser.Annotation.AnnClose' @')'@
924
925 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
926
927 | HsCmdCase (XCmdCase id)
928 (LHsExpr id)
929 (MatchGroup id (LHsCmd id)) -- bodies are HsCmd's
930 -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnCase',
931 -- 'GHC.Parser.Annotation.AnnOf','GHC.Parser.Annotation.AnnOpen' @'{'@,
932 -- 'GHC.Parser.Annotation.AnnClose' @'}'@
933
934 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
935
936 | HsCmdLamCase (XCmdLamCase id)
937 (MatchGroup id (LHsCmd id)) -- bodies are HsCmd's
938 -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnLam',
939 -- 'GHC.Parser.Annotation.AnnCase','GHC.Parser.Annotation.AnnOpen' @'{'@,
940 -- 'GHC.Parser.Annotation.AnnClose' @'}'@
941
942 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
943
944 | HsCmdIf (XCmdIf id)
945 (SyntaxExpr id) -- cond function
946 (LHsExpr id) -- predicate
947 (LHsCmd id) -- then part
948 (LHsCmd id) -- else part
949 -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnIf',
950 -- 'GHC.Parser.Annotation.AnnSemi',
951 -- 'GHC.Parser.Annotation.AnnThen','GHC.Parser.Annotation.AnnSemi',
952 -- 'GHC.Parser.Annotation.AnnElse',
953
954 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
955
956 | HsCmdLet (XCmdLet id)
957 !(LHsToken "let" id)
958 (HsLocalBinds id) -- let(rec)
959 !(LHsToken "in" id)
960 (LHsCmd id)
961 -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnLet',
962 -- 'GHC.Parser.Annotation.AnnOpen' @'{'@,
963 -- 'GHC.Parser.Annotation.AnnClose' @'}'@,'GHC.Parser.Annotation.AnnIn'
964
965 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
966
967 | HsCmdDo (XCmdDo id) -- Type of the whole expression
968 (XRec id [CmdLStmt id])
969 -- ^ - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnDo',
970 -- 'GHC.Parser.Annotation.AnnOpen', 'GHC.Parser.Annotation.AnnSemi',
971 -- 'GHC.Parser.Annotation.AnnVbar',
972 -- 'GHC.Parser.Annotation.AnnClose'
973
974 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
975
976 | XCmd !(XXCmd id) -- Extension point; see Note [Trees That Grow]
977 -- in Language.Haskell.Syntax.Extension
978
979
980 -- | Haskell arrow application type.
981 data HsArrAppType
982 -- | First order arrow application '-<'
983 = HsHigherOrderApp
984 -- | Higher order arrow application '-<<'
985 | HsFirstOrderApp
986 deriving Data
987
988 pprHsArrType :: HsArrAppType -> SDoc
989 pprHsArrType HsHigherOrderApp = text "higher order arrow application"
990 pprHsArrType HsFirstOrderApp = text "first order arrow application"
991
992 {- | Top-level command, introducing a new arrow.
993 This may occur inside a proc (where the stack is empty) or as an
994 argument of a command-forming operator.
995 -}
996
997 -- | Located Haskell Top-level Command
998 type LHsCmdTop p = XRec p (HsCmdTop p)
999
1000 -- | Haskell Top-level Command
1001 data HsCmdTop p
1002 = HsCmdTop (XCmdTop p)
1003 (LHsCmd p)
1004 | XCmdTop !(XXCmdTop p) -- Extension point; see Note [Trees That Grow]
1005 -- in Language.Haskell.Syntax.Extension
1006
1007 -----------------------
1008
1009 {-
1010 ************************************************************************
1011 * *
1012 \subsection{Record binds}
1013 * *
1014 ************************************************************************
1015 -}
1016
1017 -- | Haskell Record Bindings
1018 type HsRecordBinds p = HsRecFields p (LHsExpr p)
1019
1020 {-
1021 ************************************************************************
1022 * *
1023 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
1024 * *
1025 ************************************************************************
1026
1027 @Match@es are sets of pattern bindings and right hand sides for
1028 functions, patterns or case branches. For example, if a function @g@
1029 is defined as:
1030 \begin{verbatim}
1031 g (x,y) = y
1032 g ((x:ys),y) = y+1,
1033 \end{verbatim}
1034 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
1035
1036 It is always the case that each element of an @[Match]@ list has the
1037 same number of @pats@s inside it. This corresponds to saying that
1038 a function defined by pattern matching must have the same number of
1039 patterns in each equation.
1040 -}
1041
1042 data MatchGroup p body
1043 = MG { mg_ext :: XMG p body -- Post-typechecker, types of args and result
1044 , mg_alts :: XRec p [LMatch p body] -- The alternatives
1045 , mg_origin :: Origin }
1046 -- The type is the type of the entire group
1047 -- t1 -> ... -> tn -> tr
1048 -- where there are n patterns
1049 | XMatchGroup !(XXMatchGroup p body)
1050
1051 data MatchGroupTc
1052 = MatchGroupTc
1053 { mg_arg_tys :: [Scaled Type] -- Types of the arguments, t1..tn
1054 , mg_res_ty :: Type -- Type of the result, tr
1055 } deriving Data
1056
1057 -- | Located Match
1058 type LMatch id body = XRec id (Match id body)
1059 -- ^ May have 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnSemi' when in a
1060 -- list
1061
1062 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1063 data Match p body
1064 = Match {
1065 m_ext :: XCMatch p body,
1066 m_ctxt :: HsMatchContext p,
1067 -- See note [m_ctxt in Match]
1068 m_pats :: [LPat p], -- The patterns
1069 m_grhss :: (GRHSs p body)
1070 }
1071 | XMatch !(XXMatch p body)
1072
1073 {-
1074 Note [m_ctxt in Match]
1075 ~~~~~~~~~~~~~~~~~~~~~~
1076
1077 A Match can occur in a number of contexts, such as a FunBind, HsCase, HsLam and
1078 so on.
1079
1080 In order to simplify tooling processing and pretty print output, the provenance
1081 is captured in an HsMatchContext.
1082
1083 This is particularly important for the exact print annotations for a
1084 multi-equation FunBind.
1085
1086 The parser initially creates a FunBind with a single Match in it for
1087 every function definition it sees.
1088
1089 These are then grouped together by getMonoBind into a single FunBind,
1090 where all the Matches are combined.
1091
1092 In the process, all the original FunBind fun_id's bar one are
1093 discarded, including the locations.
1094
1095 This causes a problem for source to source conversions via exact print
1096 annotations, so the original fun_ids and infix flags are preserved in
1097 the Match, when it originates from a FunBind.
1098
1099 Example infix function definition requiring individual exact print
1100 annotations
1101
1102 (&&& ) [] [] = []
1103 xs &&& [] = xs
1104 ( &&& ) [] ys = ys
1105
1106
1107
1108 -}
1109
1110
1111 isInfixMatch :: Match id body -> Bool
1112 isInfixMatch match = case m_ctxt match of
1113 FunRhs {mc_fixity = Infix} -> True
1114 _ -> False
1115
1116 -- | Guarded Right-Hand Sides
1117 --
1118 -- GRHSs are used both for pattern bindings and for Matches
1119 --
1120 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnVbar',
1121 -- 'GHC.Parser.Annotation.AnnEqual','GHC.Parser.Annotation.AnnWhere',
1122 -- 'GHC.Parser.Annotation.AnnOpen','GHC.Parser.Annotation.AnnClose'
1123 -- 'GHC.Parser.Annotation.AnnRarrow','GHC.Parser.Annotation.AnnSemi'
1124
1125 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1126 data GRHSs p body
1127 = GRHSs {
1128 grhssExt :: XCGRHSs p body,
1129 grhssGRHSs :: [LGRHS p body], -- ^ Guarded RHSs
1130 grhssLocalBinds :: HsLocalBinds p -- ^ The where clause
1131 }
1132 | XGRHSs !(XXGRHSs p body)
1133
1134 -- | Located Guarded Right-Hand Side
1135 type LGRHS id body = XRec id (GRHS id body)
1136
1137 -- | Guarded Right Hand Side.
1138 data GRHS p body = GRHS (XCGRHS p body)
1139 [GuardLStmt p] -- Guards
1140 body -- Right hand side
1141 | XGRHS !(XXGRHS p body)
1142
1143 -- We know the list must have at least one @Match@ in it.
1144
1145 {-
1146 ************************************************************************
1147 * *
1148 \subsection{Do stmts and list comprehensions}
1149 * *
1150 ************************************************************************
1151 -}
1152
1153 -- | Located @do@ block Statement
1154 type LStmt id body = XRec id (StmtLR id id body)
1155
1156 -- | Located Statement with separate Left and Right id's
1157 type LStmtLR idL idR body = XRec idL (StmtLR idL idR body)
1158
1159 -- | @do@ block Statement
1160 type Stmt id body = StmtLR id id body
1161
1162 -- | Command Located Statement
1163 type CmdLStmt id = LStmt id (LHsCmd id)
1164
1165 -- | Command Statement
1166 type CmdStmt id = Stmt id (LHsCmd id)
1167
1168 -- | Expression Located Statement
1169 type ExprLStmt id = LStmt id (LHsExpr id)
1170
1171 -- | Expression Statement
1172 type ExprStmt id = Stmt id (LHsExpr id)
1173
1174 -- | Guard Located Statement
1175 type GuardLStmt id = LStmt id (LHsExpr id)
1176
1177 -- | Guard Statement
1178 type GuardStmt id = Stmt id (LHsExpr id)
1179
1180 -- | Ghci Located Statement
1181 type GhciLStmt id = LStmt id (LHsExpr id)
1182
1183 -- | Ghci Statement
1184 type GhciStmt id = Stmt id (LHsExpr id)
1185
1186 -- The SyntaxExprs in here are used *only* for do-notation and monad
1187 -- comprehensions, which have rebindable syntax. Otherwise they are unused.
1188 -- | Exact print annotations when in qualifier lists or guards
1189 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnVbar',
1190 -- 'GHC.Parser.Annotation.AnnComma','GHC.Parser.Annotation.AnnThen',
1191 -- 'GHC.Parser.Annotation.AnnBy','GHC.Parser.Annotation.AnnBy',
1192 -- 'GHC.Parser.Annotation.AnnGroup','GHC.Parser.Annotation.AnnUsing'
1193
1194 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1195 data StmtLR idL idR body -- body should always be (LHs**** idR)
1196 = LastStmt -- Always the last Stmt in ListComp, MonadComp,
1197 -- and (after the renamer, see GHC.Rename.Expr.checkLastStmt) DoExpr, MDoExpr
1198 -- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff
1199 (XLastStmt idL idR body)
1200 body
1201 (Maybe Bool) -- Whether return was stripped
1202 -- Just True <=> return with a dollar was stripped by ApplicativeDo
1203 -- Just False <=> return without a dollar was stripped by ApplicativeDo
1204 -- Nothing <=> Nothing was stripped
1205 (SyntaxExpr idR) -- The return operator
1206 -- The return operator is used only for MonadComp
1207 -- For ListComp we use the baked-in 'return'
1208 -- For DoExpr, MDoExpr, we don't apply a 'return' at all
1209 -- See Note [Monad Comprehensions]
1210 -- - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnLarrow'
1211
1212 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1213 | BindStmt (XBindStmt idL idR body)
1214 -- ^ Post renaming has optional fail and bind / (>>=) operator.
1215 -- Post typechecking, also has multiplicity of the argument
1216 -- and the result type of the function passed to bind;
1217 -- that is, (P, S) in (>>=) :: Q -> (R # P -> S) -> T
1218 -- See Note [The type of bind in Stmts]
1219 (LPat idL)
1220 body
1221
1222 -- | 'ApplicativeStmt' represents an applicative expression built with
1223 -- '<$>' and '<*>'. It is generated by the renamer, and is desugared into the
1224 -- appropriate applicative expression by the desugarer, but it is intended
1225 -- to be invisible in error messages.
1226 --
1227 -- For full details, see Note [ApplicativeDo] in "GHC.Rename.Expr"
1228 --
1229 | ApplicativeStmt
1230 (XApplicativeStmt idL idR body) -- Post typecheck, Type of the body
1231 [ ( SyntaxExpr idR
1232 , ApplicativeArg idL) ]
1233 -- [(<$>, e1), (<*>, e2), ..., (<*>, en)]
1234 (Maybe (SyntaxExpr idR)) -- 'join', if necessary
1235
1236 | BodyStmt (XBodyStmt idL idR body) -- Post typecheck, element type
1237 -- of the RHS (used for arrows)
1238 body -- See Note [BodyStmt]
1239 (SyntaxExpr idR) -- The (>>) operator
1240 (SyntaxExpr idR) -- The `guard` operator; used only in MonadComp
1241 -- See notes [Monad Comprehensions]
1242
1243 -- | - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnLet'
1244 -- 'GHC.Parser.Annotation.AnnOpen' @'{'@,'GHC.Parser.Annotation.AnnClose' @'}'@,
1245
1246 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1247 | LetStmt (XLetStmt idL idR body) (HsLocalBindsLR idL idR)
1248
1249 -- ParStmts only occur in a list/monad comprehension
1250 | ParStmt (XParStmt idL idR body) -- Post typecheck,
1251 -- S in (>>=) :: Q -> (R -> S) -> T
1252 [ParStmtBlock idL idR]
1253 (HsExpr idR) -- Polymorphic `mzip` for monad comprehensions
1254 (SyntaxExpr idR) -- The `>>=` operator
1255 -- See notes [Monad Comprehensions]
1256 -- After renaming, the ids are the binders
1257 -- bound by the stmts and used after themp
1258
1259 | TransStmt {
1260 trS_ext :: XTransStmt idL idR body, -- Post typecheck,
1261 -- R in (>>=) :: Q -> (R -> S) -> T
1262 trS_form :: TransForm,
1263 trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group'
1264 -- which generates the tuples to be grouped
1265
1266 trS_bndrs :: [(IdP idR, IdP idR)], -- See Note [TransStmt binder map]
1267
1268 trS_using :: LHsExpr idR,
1269 trS_by :: Maybe (LHsExpr idR), -- "by e" (optional)
1270 -- Invariant: if trS_form = GroupBy, then grp_by = Just e
1271
1272 trS_ret :: SyntaxExpr idR, -- The monomorphic 'return' function for
1273 -- the inner monad comprehensions
1274 trS_bind :: SyntaxExpr idR, -- The '(>>=)' operator
1275 trS_fmap :: HsExpr idR -- The polymorphic 'fmap' function for desugaring
1276 -- Only for 'group' forms
1277 -- Just a simple HsExpr, because it's
1278 -- too polymorphic for tcSyntaxOp
1279 } -- See Note [Monad Comprehensions]
1280
1281 -- Recursive statement (see Note [How RecStmt works] below)
1282 -- | - 'GHC.Parser.Annotation.AnnKeywordId' : 'GHC.Parser.Annotation.AnnRec'
1283
1284 -- For details on above see note [exact print annotations] in GHC.Parser.Annotation
1285 | RecStmt
1286 { recS_ext :: XRecStmt idL idR body
1287 , recS_stmts :: XRec idR [LStmtLR idL idR body]
1288 -- Assume XRec is the same for idL and idR, pick one arbitrarily
1289
1290 -- The next two fields are only valid after renaming
1291 , recS_later_ids :: [IdP idR]
1292 -- The ids are a subset of the variables bound by the
1293 -- stmts that are used in stmts that follow the RecStmt
1294
1295 , recS_rec_ids :: [IdP idR]
1296 -- Ditto, but these variables are the "recursive" ones,
1297 -- that are used before they are bound in the stmts of
1298 -- the RecStmt.
1299 -- An Id can be in both groups
1300 -- Both sets of Ids are (now) treated monomorphically
1301 -- See Note [How RecStmt works] for why they are separate
1302
1303 -- Rebindable syntax
1304 , recS_bind_fn :: SyntaxExpr idR -- The bind function
1305 , recS_ret_fn :: SyntaxExpr idR -- The return function
1306 , recS_mfix_fn :: SyntaxExpr idR -- The mfix function
1307 }
1308 | XStmtLR !(XXStmtLR idL idR body)
1309
1310 data TransForm -- The 'f' below is the 'using' function, 'e' is the by function
1311 = ThenForm -- then f or then f by e (depending on trS_by)
1312 | GroupForm -- then group using f or then group by e using f (depending on trS_by)
1313 deriving Data
1314
1315 -- | Parenthesised Statement Block
1316 data ParStmtBlock idL idR
1317 = ParStmtBlock
1318 (XParStmtBlock idL idR)
1319 [ExprLStmt idL]
1320 [IdP idR] -- The variables to be returned
1321 (SyntaxExpr idR) -- The return operator
1322 | XParStmtBlock !(XXParStmtBlock idL idR)
1323
1324 -- | The fail operator
1325 --
1326 -- This is used for `.. <-` "bind statements" in do notation, including
1327 -- non-monadic "binds" in applicative.
1328 --
1329 -- The fail operator is 'Just expr' if it potentially fail monadically. if the
1330 -- pattern match cannot fail, or shouldn't fail monadically (regular incomplete
1331 -- pattern exception), it is 'Nothing'.
1332 --
1333 -- See Note [Monad fail : Rebindable syntax, overloaded strings] for the type of
1334 -- expression in the 'Just' case, and why it is so.
1335 --
1336 -- See Note [Failing pattern matches in Stmts] for which contexts for
1337 -- '@BindStmt@'s should use the monadic fail and which shouldn't.
1338 type FailOperator id = Maybe (SyntaxExpr id)
1339
1340 -- | Applicative Argument
1341 data ApplicativeArg idL
1342 = ApplicativeArgOne -- A single statement (BindStmt or BodyStmt)
1343 { xarg_app_arg_one :: XApplicativeArgOne idL
1344 -- ^ The fail operator, after renaming
1345 --
1346 -- The fail operator is needed if this is a BindStmt
1347 -- where the pattern can fail. E.g.:
1348 -- (Just a) <- stmt
1349 -- The fail operator will be invoked if the pattern
1350 -- match fails.
1351 -- It is also used for guards in MonadComprehensions.
1352 -- The fail operator is Nothing
1353 -- if the pattern match can't fail
1354 , app_arg_pattern :: LPat idL -- WildPat if it was a BodyStmt (see below)
1355 , arg_expr :: LHsExpr idL
1356 , is_body_stmt :: Bool
1357 -- ^ True <=> was a BodyStmt,
1358 -- False <=> was a BindStmt.
1359 -- See Note [Applicative BodyStmt]
1360 }
1361 | ApplicativeArgMany -- do { stmts; return vars }
1362 { xarg_app_arg_many :: XApplicativeArgMany idL
1363 , app_stmts :: [ExprLStmt idL] -- stmts
1364 , final_expr :: HsExpr idL -- return (v1,..,vn), or just (v1,..,vn)
1365 , bv_pattern :: LPat idL -- (v1,...,vn)
1366 , stmt_context :: HsDoFlavour
1367 -- ^ context of the do expression, used in pprArg
1368 }
1369 | XApplicativeArg !(XXApplicativeArg idL)
1370
1371 {-
1372 Note [The type of bind in Stmts]
1373 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1374 Some Stmts, notably BindStmt, keep the (>>=) bind operator.
1375 We do NOT assume that it has type
1376 (>>=) :: m a -> (a -> m b) -> m b
1377 In some cases (see #303, #1537) it might have a more
1378 exotic type, such as
1379 (>>=) :: m i j a -> (a -> m j k b) -> m i k b
1380 So we must be careful not to make assumptions about the type.
1381 In particular, the monad may not be uniform throughout.
1382
1383 Note [TransStmt binder map]
1384 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1385 The [(idR,idR)] in a TransStmt behaves as follows:
1386
1387 * Before renaming: []
1388
1389 * After renaming:
1390 [ (x27,x27), ..., (z35,z35) ]
1391 These are the variables
1392 bound by the stmts to the left of the 'group'
1393 and used either in the 'by' clause,
1394 or in the stmts following the 'group'
1395 Each item is a pair of identical variables.
1396
1397 * After typechecking:
1398 [ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ]
1399 Each pair has the same unique, but different *types*.
1400
1401 Note [BodyStmt]
1402 ~~~~~~~~~~~~~~~
1403 BodyStmts are a bit tricky, because what they mean
1404 depends on the context. Consider the following contexts:
1405
1406 A do expression of type (m res_ty)
1407 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1408 * BodyStmt E any_ty: do { ....; E; ... }
1409 E :: m any_ty
1410 Translation: E >> ...
1411
1412 A list comprehensions of type [elt_ty]
1413 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1414 * BodyStmt E Bool: [ .. | .... E ]
1415 [ .. | ..., E, ... ]
1416 [ .. | .... | ..., E | ... ]
1417 E :: Bool
1418 Translation: if E then fail else ...
1419
1420 A guard list, guarding a RHS of type rhs_ty
1421 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1422 * BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs...
1423 E :: Bool
1424 Translation: if E then fail else ...
1425
1426 A monad comprehension of type (m res_ty)
1427 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1428 * BodyStmt E Bool: [ .. | .... E ]
1429 E :: Bool
1430 Translation: guard E >> ...
1431
1432 Array comprehensions are handled like list comprehensions.
1433
1434 Note [How RecStmt works]
1435 ~~~~~~~~~~~~~~~~~~~~~~~~
1436 Example:
1437 HsDo [ BindStmt x ex
1438
1439 , RecStmt { recS_rec_ids = [a, c]
1440 , recS_stmts = [ BindStmt b (return (a,c))
1441 , LetStmt a = ...b...
1442 , BindStmt c ec ]
1443 , recS_later_ids = [a, b]
1444
1445 , return (a b) ]
1446
1447 Here, the RecStmt binds a,b,c; but
1448 - Only a,b are used in the stmts *following* the RecStmt,
1449 - Only a,c are used in the stmts *inside* the RecStmt
1450 *before* their bindings
1451
1452 Why do we need *both* rec_ids and later_ids? For monads they could be
1453 combined into a single set of variables, but not for arrows. That
1454 follows from the types of the respective feedback operators:
1455
1456 mfix :: MonadFix m => (a -> m a) -> m a
1457 loop :: ArrowLoop a => a (b,d) (c,d) -> a b c
1458
1459 * For mfix, the 'a' covers the union of the later_ids and the rec_ids
1460 * For 'loop', 'c' is the later_ids and 'd' is the rec_ids
1461
1462 Note [Typing a RecStmt]
1463 ~~~~~~~~~~~~~~~~~~~~~~~
1464 A (RecStmt stmts) types as if you had written
1465
1466 (v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) ->
1467 do { stmts
1468 ; return (v1,..vn, r1, ..., rm) })
1469
1470 where v1..vn are the later_ids
1471 r1..rm are the rec_ids
1472
1473 Note [Monad Comprehensions]
1474 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1475 Monad comprehensions require separate functions like 'return' and
1476 '>>=' for desugaring. These functions are stored in the statements
1477 used in monad comprehensions. For example, the 'return' of the 'LastStmt'
1478 expression is used to lift the body of the monad comprehension:
1479
1480 [ body | stmts ]
1481 =>
1482 stmts >>= \bndrs -> return body
1483
1484 In transform and grouping statements ('then ..' and 'then group ..') the
1485 'return' function is required for nested monad comprehensions, for example:
1486
1487 [ body | stmts, then f, rest ]
1488 =>
1489 f [ env | stmts ] >>= \bndrs -> [ body | rest ]
1490
1491 BodyStmts require the 'Control.Monad.guard' function for boolean
1492 expressions:
1493
1494 [ body | exp, stmts ]
1495 =>
1496 guard exp >> [ body | stmts ]
1497
1498 Parallel statements require the 'Control.Monad.Zip.mzip' function:
1499
1500 [ body | stmts1 | stmts2 | .. ]
1501 =>
1502 mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body
1503
1504 In any other context than 'MonadComp', the fields for most of these
1505 'SyntaxExpr's stay bottom.
1506
1507
1508 Note [Applicative BodyStmt]
1509
1510 (#12143) For the purposes of ApplicativeDo, we treat any BodyStmt
1511 as if it was a BindStmt with a wildcard pattern. For example,
1512
1513 do
1514 x <- A
1515 B
1516 return x
1517
1518 is transformed as if it were
1519
1520 do
1521 x <- A
1522 _ <- B
1523 return x
1524
1525 so it transforms to
1526
1527 (\(x,_) -> x) <$> A <*> B
1528
1529 But we have to remember when we treat a BodyStmt like a BindStmt,
1530 because in error messages we want to emit the original syntax the user
1531 wrote, not our internal representation. So ApplicativeArgOne has a
1532 Bool flag that is True when the original statement was a BodyStmt, so
1533 that we can pretty-print it correctly.
1534 -}
1535
1536
1537 {-
1538 ************************************************************************
1539 * *
1540 Template Haskell quotation brackets
1541 * *
1542 ************************************************************************
1543 -}
1544
1545 -- | Haskell Splice
1546 data HsSplice id
1547 = HsTypedSplice -- $$z or $$(f 4)
1548 (XTypedSplice id)
1549 SpliceDecoration -- Whether $$( ) variant found, for pretty printing
1550 (IdP id) -- A unique name to identify this splice point
1551 (LHsExpr id) -- See Note [Pending Splices]
1552
1553 | HsUntypedSplice -- $z or $(f 4)
1554 (XUntypedSplice id)
1555 SpliceDecoration -- Whether $( ) variant found, for pretty printing
1556 (IdP id) -- A unique name to identify this splice point
1557 (LHsExpr id) -- See Note [Pending Splices]
1558
1559 | HsQuasiQuote -- See Note [Quasi-quote overview] in GHC.Tc.Gen.Splice
1560 (XQuasiQuote id)
1561 (IdP id) -- Splice point
1562 (IdP id) -- Quoter
1563 SrcSpan -- The span of the enclosed string
1564 FastString -- The enclosed string
1565
1566 -- AZ:TODO: use XSplice instead of HsSpliced
1567 | HsSpliced -- See Note [Delaying modFinalizers in untyped splices] in
1568 -- GHC.Rename.Splice.
1569 -- This is the result of splicing a splice. It is produced by
1570 -- the renamer and consumed by the typechecker. It lives only
1571 -- between the two.
1572 (XSpliced id)
1573 ThModFinalizers -- TH finalizers produced by the splice.
1574 (HsSplicedThing id) -- The result of splicing
1575 | XSplice !(XXSplice id) -- Extension point; see Note [Trees That Grow]
1576 -- in Language.Haskell.Syntax.Extension
1577
1578 -- | A splice can appear with various decorations wrapped around it. This data
1579 -- type captures explicitly how it was originally written, for use in the pretty
1580 -- printer.
1581 data SpliceDecoration
1582 = DollarSplice -- ^ $splice or $$splice
1583 | BareSplice -- ^ bare splice
1584 deriving (Data, Eq, Show)
1585
1586 instance Outputable SpliceDecoration where
1587 ppr x = text $ show x
1588
1589
1590 isTypedSplice :: HsSplice id -> Bool
1591 isTypedSplice (HsTypedSplice {}) = True
1592 isTypedSplice _ = False -- Quasi-quotes are untyped splices
1593
1594 -- | Finalizers produced by a splice with
1595 -- 'Language.Haskell.TH.Syntax.addModFinalizer'
1596 --
1597 -- See Note [Delaying modFinalizers in untyped splices] in GHC.Rename.Splice. For how
1598 -- this is used.
1599 --
1600 newtype ThModFinalizers = ThModFinalizers [ForeignRef (TH.Q ())]
1601
1602 -- A Data instance which ignores the argument of 'ThModFinalizers'.
1603 instance Data ThModFinalizers where
1604 gunfold _ z _ = z $ ThModFinalizers []
1605 toConstr a = mkConstr (dataTypeOf a) "ThModFinalizers" [] Data.Prefix
1606 dataTypeOf a = mkDataType "HsExpr.ThModFinalizers" [toConstr a]
1607
1608 -- | Haskell Spliced Thing
1609 --
1610 -- Values that can result from running a splice.
1611 data HsSplicedThing id
1612 = HsSplicedExpr (HsExpr id) -- ^ Haskell Spliced Expression
1613 | HsSplicedTy (HsType id) -- ^ Haskell Spliced Type
1614 | HsSplicedPat (Pat id) -- ^ Haskell Spliced Pattern
1615
1616
1617 -- See Note [Pending Splices]
1618 type SplicePointName = Name
1619
1620 data UntypedSpliceFlavour
1621 = UntypedExpSplice
1622 | UntypedPatSplice
1623 | UntypedTypeSplice
1624 | UntypedDeclSplice
1625 deriving Data
1626
1627 -- | Haskell Bracket
1628 data HsBracket p
1629 = ExpBr (XExpBr p) (LHsExpr p) -- [| expr |]
1630 | PatBr (XPatBr p) (LPat p) -- [p| pat |]
1631 | DecBrL (XDecBrL p) [LHsDecl p] -- [d| decls |]; result of parser
1632 | DecBrG (XDecBrG p) (HsGroup p) -- [d| decls |]; result of renamer
1633 | TypBr (XTypBr p) (LHsType p) -- [t| type |]
1634 | VarBr (XVarBr p) Bool (LIdP p)
1635 -- True: 'x, False: ''T
1636 -- (The Bool flag is used only in pprHsBracket)
1637 | TExpBr (XTExpBr p) (LHsExpr p) -- [|| expr ||]
1638 | XBracket !(XXBracket p) -- Extension point; see Note [Trees That Grow]
1639 -- in Language.Haskell.Syntax.Extension
1640
1641 isTypedBracket :: HsBracket id -> Bool
1642 isTypedBracket (TExpBr {}) = True
1643 isTypedBracket _ = False
1644
1645 {-
1646 ************************************************************************
1647 * *
1648 \subsection{Enumerations and list comprehensions}
1649 * *
1650 ************************************************************************
1651 -}
1652
1653 -- | Arithmetic Sequence Information
1654 data ArithSeqInfo id
1655 = From (LHsExpr id)
1656 | FromThen (LHsExpr id)
1657 (LHsExpr id)
1658 | FromTo (LHsExpr id)
1659 (LHsExpr id)
1660 | FromThenTo (LHsExpr id)
1661 (LHsExpr id)
1662 (LHsExpr id)
1663 -- AZ: Should ArithSeqInfo have a TTG extension?
1664
1665 {-
1666 ************************************************************************
1667 * *
1668 \subsection{HsMatchCtxt}
1669 * *
1670 ************************************************************************
1671 -}
1672
1673 -- | Haskell Match Context
1674 --
1675 -- Context of a pattern match. This is more subtle than it would seem. See Note
1676 -- [Varieties of pattern matches].
1677 data HsMatchContext p
1678 = FunRhs { mc_fun :: LIdP p -- ^ function binder of @f@
1679 , mc_fixity :: LexicalFixity -- ^ fixing of @f@
1680 , mc_strictness :: SrcStrictness -- ^ was @f@ banged?
1681 -- See Note [FunBind vs PatBind]
1682 }
1683 -- ^A pattern matching on an argument of a
1684 -- function binding
1685 | LambdaExpr -- ^Patterns of a lambda
1686 | CaseAlt -- ^Patterns and guards on a case alternative
1687 | IfAlt -- ^Guards of a multi-way if alternative
1688 | ArrowMatchCtxt -- ^A pattern match inside arrow notation
1689 HsArrowMatchContext
1690 | PatBindRhs -- ^A pattern binding eg [y] <- e = e
1691 | PatBindGuards -- ^Guards of pattern bindings, e.g.,
1692 -- (Just b) | Just _ <- x = e
1693 -- | otherwise = e'
1694
1695 | RecUpd -- ^Record update [used only in GHC.HsToCore.Expr to
1696 -- tell matchWrapper what sort of
1697 -- runtime error message to generate]
1698
1699 | StmtCtxt (HsStmtContext p) -- ^Pattern of a do-stmt, list comprehension,
1700 -- pattern guard, etc
1701
1702 | ThPatSplice -- ^A Template Haskell pattern splice
1703 | ThPatQuote -- ^A Template Haskell pattern quotation [p| (a,b) |]
1704 | PatSyn -- ^A pattern synonym declaration
1705
1706 isPatSynCtxt :: HsMatchContext p -> Bool
1707 isPatSynCtxt ctxt =
1708 case ctxt of
1709 PatSyn -> True
1710 _ -> False
1711
1712 -- | Haskell Statement Context.
1713 data HsStmtContext p
1714 = HsDoStmt HsDoFlavour -- ^Context for HsDo (do-notation and comprehensions)
1715 | PatGuard (HsMatchContext p) -- ^Pattern guard for specified thing
1716 | ParStmtCtxt (HsStmtContext p) -- ^A branch of a parallel stmt
1717 | TransStmtCtxt (HsStmtContext p) -- ^A branch of a transform stmt
1718 | ArrowExpr -- ^do-notation in an arrow-command context
1719
1720 -- | Haskell arrow match context.
1721 data HsArrowMatchContext
1722 = ProcExpr -- ^ A proc expression
1723 | ArrowCaseAlt -- ^ A case alternative inside arrow notation
1724 | KappaExpr -- ^ An arrow kappa abstraction
1725
1726 data HsDoFlavour
1727 = DoExpr (Maybe ModuleName) -- ^[ModuleName.]do { ... }
1728 | MDoExpr (Maybe ModuleName) -- ^[ModuleName.]mdo { ... } ie recursive do-expression
1729 | GhciStmtCtxt -- ^A command-line Stmt in GHCi pat <- rhs
1730 | ListComp
1731 | MonadComp
1732
1733 qualifiedDoModuleName_maybe :: HsStmtContext p -> Maybe ModuleName
1734 qualifiedDoModuleName_maybe ctxt = case ctxt of
1735 HsDoStmt (DoExpr m) -> m
1736 HsDoStmt (MDoExpr m) -> m
1737 _ -> Nothing
1738
1739 isComprehensionContext :: HsStmtContext id -> Bool
1740 -- Uses comprehension syntax [ e | quals ]
1741 isComprehensionContext (ParStmtCtxt c) = isComprehensionContext c
1742 isComprehensionContext (TransStmtCtxt c) = isComprehensionContext c
1743 isComprehensionContext ArrowExpr = False
1744 isComprehensionContext (PatGuard _) = False
1745 isComprehensionContext (HsDoStmt flavour) = isDoComprehensionContext flavour
1746
1747 isDoComprehensionContext :: HsDoFlavour -> Bool
1748 isDoComprehensionContext GhciStmtCtxt = False
1749 isDoComprehensionContext (DoExpr _) = False
1750 isDoComprehensionContext (MDoExpr _) = False
1751 isDoComprehensionContext ListComp = True
1752 isDoComprehensionContext MonadComp = True
1753
1754 -- | Is this a monadic context?
1755 isMonadStmtContext :: HsStmtContext id -> Bool
1756 isMonadStmtContext (ParStmtCtxt ctxt) = isMonadStmtContext ctxt
1757 isMonadStmtContext (TransStmtCtxt ctxt) = isMonadStmtContext ctxt
1758 isMonadStmtContext (HsDoStmt flavour) = isMonadDoStmtContext flavour
1759 isMonadStmtContext (PatGuard _) = False
1760 isMonadStmtContext ArrowExpr = False
1761
1762 isMonadDoStmtContext :: HsDoFlavour -> Bool
1763 isMonadDoStmtContext ListComp = False
1764 isMonadDoStmtContext MonadComp = True
1765 isMonadDoStmtContext DoExpr{} = True
1766 isMonadDoStmtContext MDoExpr{} = True
1767 isMonadDoStmtContext GhciStmtCtxt = True
1768
1769 isMonadCompContext :: HsStmtContext id -> Bool
1770 isMonadCompContext (HsDoStmt flavour) = isMonadDoCompContext flavour
1771 isMonadCompContext (ParStmtCtxt _) = False
1772 isMonadCompContext (TransStmtCtxt _) = False
1773 isMonadCompContext (PatGuard _) = False
1774 isMonadCompContext ArrowExpr = False
1775
1776 isMonadDoCompContext :: HsDoFlavour -> Bool
1777 isMonadDoCompContext MonadComp = True
1778 isMonadDoCompContext ListComp = False
1779 isMonadDoCompContext GhciStmtCtxt = False
1780 isMonadDoCompContext (DoExpr _) = False
1781 isMonadDoCompContext (MDoExpr _) = False
1782
1783 matchSeparator :: HsMatchContext p -> SDoc
1784 matchSeparator (FunRhs {}) = text "="
1785 matchSeparator CaseAlt = text "->"
1786 matchSeparator IfAlt = text "->"
1787 matchSeparator LambdaExpr = text "->"
1788 matchSeparator (ArrowMatchCtxt{})= text "->"
1789 matchSeparator PatBindRhs = text "="
1790 matchSeparator PatBindGuards = text "="
1791 matchSeparator (StmtCtxt _) = text "<-"
1792 matchSeparator RecUpd = text "=" -- This can be printed by the pattern
1793 -- match checker trace
1794 matchSeparator ThPatSplice = panic "unused"
1795 matchSeparator ThPatQuote = panic "unused"
1796 matchSeparator PatSyn = panic "unused"
1797
1798 pprMatchContext :: (Outputable (IdP p), UnXRec p)
1799 => HsMatchContext p -> SDoc
1800 pprMatchContext ctxt
1801 | want_an ctxt = text "an" <+> pprMatchContextNoun ctxt
1802 | otherwise = text "a" <+> pprMatchContextNoun ctxt
1803 where
1804 want_an (FunRhs {}) = True -- Use "an" in front
1805 want_an (ArrowMatchCtxt ProcExpr) = True
1806 want_an (ArrowMatchCtxt KappaExpr) = True
1807 want_an _ = False
1808
1809 pprMatchContextNoun :: forall p. (Outputable (IdP p), UnXRec p)
1810 => HsMatchContext p -> SDoc
1811 pprMatchContextNoun (FunRhs {mc_fun=fun})
1812 = text "equation for"
1813 <+> quotes (ppr (unXRec @p fun))
1814 pprMatchContextNoun CaseAlt = text "case alternative"
1815 pprMatchContextNoun IfAlt = text "multi-way if alternative"
1816 pprMatchContextNoun RecUpd = text "record-update construct"
1817 pprMatchContextNoun ThPatSplice = text "Template Haskell pattern splice"
1818 pprMatchContextNoun ThPatQuote = text "Template Haskell pattern quotation"
1819 pprMatchContextNoun PatBindRhs = text "pattern binding"
1820 pprMatchContextNoun PatBindGuards = text "pattern binding guards"
1821 pprMatchContextNoun LambdaExpr = text "lambda abstraction"
1822 pprMatchContextNoun (ArrowMatchCtxt c)= pprArrowMatchContextNoun c
1823 pprMatchContextNoun (StmtCtxt ctxt) = text "pattern binding in"
1824 $$ pprAStmtContext ctxt
1825 pprMatchContextNoun PatSyn = text "pattern synonym declaration"
1826
1827 pprArrowMatchContextNoun :: HsArrowMatchContext -> SDoc
1828 pprArrowMatchContextNoun ProcExpr = text "arrow proc pattern"
1829 pprArrowMatchContextNoun ArrowCaseAlt = text "case alternative within arrow notation"
1830 pprArrowMatchContextNoun KappaExpr = text "arrow kappa abstraction"
1831
1832 -----------------
1833 pprAStmtContext, pprStmtContext :: (Outputable (IdP p), UnXRec p)
1834 => HsStmtContext p -> SDoc
1835 pprAStmtContext (HsDoStmt flavour) = pprAHsDoFlavour flavour
1836 pprAStmtContext ctxt = text "a" <+> pprStmtContext ctxt
1837
1838 -----------------
1839 pprStmtContext (HsDoStmt flavour) = pprHsDoFlavour flavour
1840 pprStmtContext (PatGuard ctxt) = text "pattern guard for" $$ pprMatchContext ctxt
1841 pprStmtContext ArrowExpr = text "'do' block in an arrow command"
1842
1843 -- Drop the inner contexts when reporting errors, else we get
1844 -- Unexpected transform statement
1845 -- in a transformed branch of
1846 -- transformed branch of
1847 -- transformed branch of monad comprehension
1848 pprStmtContext (ParStmtCtxt c) =
1849 ifPprDebug (sep [text "parallel branch of", pprAStmtContext c])
1850 (pprStmtContext c)
1851 pprStmtContext (TransStmtCtxt c) =
1852 ifPprDebug (sep [text "transformed branch of", pprAStmtContext c])
1853 (pprStmtContext c)
1854
1855 pprAHsDoFlavour, pprHsDoFlavour :: HsDoFlavour -> SDoc
1856 pprAHsDoFlavour flavour = article <+> pprHsDoFlavour flavour
1857 where
1858 pp_an = text "an"
1859 pp_a = text "a"
1860 article = case flavour of
1861 MDoExpr Nothing -> pp_an
1862 GhciStmtCtxt -> pp_an
1863 _ -> pp_a
1864 pprHsDoFlavour (DoExpr m) = prependQualified m (text "'do' block")
1865 pprHsDoFlavour (MDoExpr m) = prependQualified m (text "'mdo' block")
1866 pprHsDoFlavour ListComp = text "list comprehension"
1867 pprHsDoFlavour MonadComp = text "monad comprehension"
1868 pprHsDoFlavour GhciStmtCtxt = text "interactive GHCi command"
1869
1870 prependQualified :: Maybe ModuleName -> SDoc -> SDoc
1871 prependQualified Nothing t = t
1872 prependQualified (Just _) t = text "qualified" <+> t