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