2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[HsExpr]{Abstract Haskell syntax: expressions}
9 #include "HsVersions.h"
12 import HsBinds ( HsBinds(..), nullBinds )
13 import HsLit ( HsLit, HsOverLit )
14 import BasicTypes ( Fixity(..) )
15 import HsTypes ( HsType, PostTcType, SyntaxName )
16 import HsImpExp ( isOperator )
19 import ForeignCall ( Safety )
20 import PprType ( pprParendType )
23 import DataCon ( DataCon )
24 import CStrings ( CLabelString, pprCLabelString )
25 import BasicTypes ( IPName, Boxity, tupleParens )
26 import SrcLoc ( SrcLoc )
31 %************************************************************************
33 \subsection{Expressions proper}
35 %************************************************************************
39 = HsVar id -- variable
40 | HsIPVar (IPName id) -- implicit parameter
41 | HsOverLit HsOverLit -- Overloaded literals; eliminated by type checker
42 | HsLit HsLit -- Simple (non-overloaded) literals
44 | HsLam (Match id pat) -- lambda
45 | HsApp (HsExpr id pat) -- application
48 -- Operator applications:
49 -- NB Bracketed ops such as (+) come out as Vars.
51 -- NB We need an expr for the operator in an OpApp/Section since
52 -- the typechecker may need to apply the operator to a few types.
54 | OpApp (HsExpr id pat) -- left operand
55 (HsExpr id pat) -- operator
56 Fixity -- Renamer adds fixity; bottom until then
57 (HsExpr id pat) -- right operand
59 -- We preserve prefix negation and parenthesis for the precedence parser.
60 -- They are eventually removed by the type checker.
62 | NegApp (HsExpr id pat) -- negated expr
63 SyntaxName -- Name of 'negate' (see RnEnv.lookupSyntaxName)
65 | HsPar (HsExpr id pat) -- parenthesised expr
67 | SectionL (HsExpr id pat) -- operand
68 (HsExpr id pat) -- operator
69 | SectionR (HsExpr id pat) -- operator
70 (HsExpr id pat) -- operand
72 | HsCase (HsExpr id pat)
76 | HsIf (HsExpr id pat) -- predicate
77 (HsExpr id pat) -- then part
78 (HsExpr id pat) -- else part
81 | HsLet (HsBinds id pat) -- let(rec)
84 | HsWith (HsExpr id pat) -- implicit parameter binding
85 [(IPName id, HsExpr id pat)]
86 Bool -- True <=> this was a 'with' binding
87 -- (tmp, until 'with' is removed)
90 [Stmt id pat] -- "do":one or more stmts
91 [id] -- Ids for [return,fail,>>=,>>]
93 -- Before type checking, used for rebindable syntax
94 PostTcType -- Type of the whole expression
97 | ExplicitList -- syntactic list
98 PostTcType -- Gives type of components of list
101 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
102 PostTcType -- type of elements of the parallel array
105 | ExplicitTuple -- tuple
107 -- NB: Unit is ExplicitTuple []
108 -- for tuples, we can get the types
109 -- direct from the components
113 -- Record construction
114 | RecordCon id -- The constructor
115 (HsRecordBinds id pat)
117 | RecordConOut DataCon
118 (HsExpr id pat) -- Data con Id applied to type args
119 (HsRecordBinds id pat)
123 | RecordUpd (HsExpr id pat)
124 (HsRecordBinds id pat)
126 | RecordUpdOut (HsExpr id pat) -- TRANSLATION
127 Type -- Type of *input* record
128 Type -- Type of *result* record (may differ from
129 -- type of input record)
130 (HsRecordBinds id pat)
132 | ExprWithTySig -- signature binding
135 | ArithSeqIn -- arithmetic sequence
136 (ArithSeqInfo id pat)
138 (HsExpr id pat) -- (typechecked, of course)
139 (ArithSeqInfo id pat)
140 | PArrSeqIn -- arith. sequence for parallel array
141 (ArithSeqInfo id pat) -- [:e1..e2:] or [:e1, e2..e3:]
143 (HsExpr id pat) -- (typechecked, of course)
144 (ArithSeqInfo id pat)
146 | HsCCall CLabelString -- call into the C world; string is
147 [HsExpr id pat] -- the C function; exprs are the
148 -- arguments to pass.
149 Safety -- True <=> might cause Haskell
150 -- garbage-collection (must generate
151 -- more paranoid code)
152 Bool -- True <=> it's really a "casm"
153 -- NOTE: this CCall is the *boxed*
154 -- version; the desugarer will convert
155 -- it into the unboxed "ccall#".
156 PostTcType -- The result type; will be *bottom*
157 -- until the typechecker gets ahold of it
159 | HsSCC FastString -- "set cost centre" (_scc_) annotation
160 (HsExpr id pat) -- expr whose cost is to be measured
164 These constructors only appear temporarily in the parser.
165 The renamer translates them into the Right Thing.
168 | EWildPat -- wildcard
170 | EAsPat id -- as pattern
173 | ELazyPat (HsExpr id pat) -- ~ pattern
175 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
178 Everything from here on appears only in typechecker output.
181 | TyLam -- TRANSLATION
184 | TyApp -- TRANSLATION
185 (HsExpr id pat) -- generated by Spec
188 -- DictLam and DictApp are "inverses"
196 type HsRecordBinds id pat
197 = [(id, HsExpr id pat, Bool)]
198 -- True <=> source code used "punning",
199 -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
202 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
203 @ClassDictLam dictvars methods expr@ is, therefore:
205 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
209 instance (Outputable id, Outputable pat) =>
210 Outputable (HsExpr id pat) where
211 ppr expr = pprExpr expr
215 pprExpr :: (Outputable id, Outputable pat)
216 => HsExpr id pat -> SDoc
218 pprExpr e = pprDeeper (ppr_expr e)
219 pprBinds b = pprDeeper (ppr b)
222 -- Put it in parens if it's an operator
223 | isOperator v = parens (ppr v)
226 ppr_expr (HsIPVar v) = ppr v
227 ppr_expr (HsLit lit) = ppr lit
228 ppr_expr (HsOverLit lit) = ppr lit
230 ppr_expr (HsLam match)
231 = hsep [char '\\', nest 2 (pprMatch LambdaExpr match)]
233 ppr_expr expr@(HsApp e1 e2)
234 = let (fun, args) = collect_args expr [] in
235 (ppr_expr fun) <+> (sep (map ppr_expr args))
237 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
238 collect_args fun args = (fun, args)
240 ppr_expr (OpApp e1 op fixity e2)
242 HsVar v -> pp_infixly v
245 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
246 pp_e2 = pprParendExpr e2
249 = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
252 = sep [pp_e1, hsep [pp_v_op, pp_e2]]
254 pp_v_op | isOperator v = ppr v
255 | otherwise = char '`' <> ppr v <> char '`'
256 -- Put it in backquotes if it's not an operator already
258 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
260 ppr_expr (HsPar e) = parens (ppr_expr e)
262 ppr_expr (SectionL expr op)
264 HsVar v -> pp_infixly v
267 pp_expr = pprParendExpr expr
269 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
270 4 (hsep [pp_expr, ptext SLIT("x_ )")])
271 pp_infixly v = parens (sep [pp_expr, ppr v])
273 ppr_expr (SectionR op expr)
275 HsVar v -> pp_infixly v
278 pp_expr = pprParendExpr expr
280 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
281 4 ((<>) pp_expr rparen)
283 = parens (sep [ppr v, pp_expr])
285 ppr_expr (HsCase expr matches _)
286 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
287 nest 2 (pprMatches CaseAlt matches) ]
289 ppr_expr (HsIf e1 e2 e3 _)
290 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
295 -- special case: let ... in let ...
296 ppr_expr (HsLet binds expr@(HsLet _ _))
297 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
300 ppr_expr (HsLet binds expr)
301 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
302 hang (ptext SLIT("in")) 2 (ppr expr)]
304 ppr_expr (HsWith expr binds is_with)
305 = sep [hang (ptext SLIT("let")) 2 (pp_ipbinds binds),
306 hang (ptext SLIT("in")) 2 (ppr expr)]
308 ppr_expr (HsDo do_or_list_comp stmts _ _ _) = pprDo do_or_list_comp stmts
310 ppr_expr (ExplicitList _ exprs)
311 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
313 ppr_expr (ExplicitPArr _ exprs)
314 = pabrackets (fsep (punctuate comma (map ppr_expr exprs)))
316 ppr_expr (ExplicitTuple exprs boxity)
317 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
319 ppr_expr (RecordCon con_id rbinds)
320 = pp_rbinds (ppr con_id) rbinds
321 ppr_expr (RecordConOut data_con con rbinds)
322 = pp_rbinds (ppr con) rbinds
324 ppr_expr (RecordUpd aexp rbinds)
325 = pp_rbinds (pprParendExpr aexp) rbinds
326 ppr_expr (RecordUpdOut aexp _ _ rbinds)
327 = pp_rbinds (pprParendExpr aexp) rbinds
329 ppr_expr (ExprWithTySig expr sig)
330 = hang (nest 2 (ppr_expr expr) <+> dcolon)
333 ppr_expr (ArithSeqIn info)
334 = brackets (ppr info)
335 ppr_expr (ArithSeqOut expr info)
336 = brackets (ppr info)
338 ppr_expr (PArrSeqIn info)
339 = pabrackets (ppr info)
340 ppr_expr (PArrSeqOut expr info)
341 = pabrackets (ppr info)
343 ppr_expr EWildPat = char '_'
344 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
345 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
347 ppr_expr (HsCCall fun args _ is_asm result_ty)
349 then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
350 else ptext SLIT("_ccall_") <+> pprCLabelString fun)
351 4 (sep (map pprParendExpr args))
353 ppr_expr (HsSCC lbl expr)
354 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl), pprParendExpr expr ]
356 ppr_expr (TyLam tyvars expr)
357 = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
360 ppr_expr (TyApp expr [ty])
361 = hang (ppr_expr expr) 4 (pprParendType ty)
363 ppr_expr (TyApp expr tys)
364 = hang (ppr_expr expr)
365 4 (brackets (interpp'SP tys))
367 ppr_expr (DictLam dictvars expr)
368 = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
371 ppr_expr (DictApp expr [dname])
372 = hang (ppr_expr expr) 4 (ppr dname)
374 ppr_expr (DictApp expr dnames)
375 = hang (ppr_expr expr)
376 4 (brackets (interpp'SP dnames))
378 ppr_expr (HsType id) = ppr id
380 -- add parallel array brackets around a document
382 pabrackets :: SDoc -> SDoc
383 pabrackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
386 Parenthesize unless very simple:
388 pprParendExpr :: (Outputable id, Outputable pat)
389 => HsExpr id pat -> SDoc
393 pp_as_was = pprExpr expr
400 HsIPVar _ -> pp_as_was
401 ExplicitList _ _ -> pp_as_was
402 ExplicitPArr _ _ -> pp_as_was
403 ExplicitTuple _ _ -> pp_as_was
406 _ -> parens pp_as_was
409 %************************************************************************
411 \subsection{Record binds}
413 %************************************************************************
416 pp_rbinds :: (Outputable id, Outputable pat)
418 -> HsRecordBinds id pat -> SDoc
420 pp_rbinds thing rbinds
422 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
424 pp_rbind (v, e, pun_flag)
425 = getPprStyle $ \ sty ->
426 if pun_flag && userStyle sty then
429 hsep [ppr v, char '=', ppr e]
433 pp_ipbinds :: (Outputable id, Outputable pat)
434 => [(IPName id, HsExpr id pat)] -> SDoc
435 pp_ipbinds pairs = hsep (punctuate semi (map pp_item pairs))
437 pp_item (id,rhs) = ppr id <+> equals <+> ppr_expr rhs
441 %************************************************************************
443 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
445 %************************************************************************
447 @Match@es are sets of pattern bindings and right hand sides for
448 functions, patterns or case branches. For example, if a function @g@
454 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
456 It is always the case that each element of an @[Match]@ list has the
457 same number of @pats@s inside it. This corresponds to saying that
458 a function defined by pattern matching must have the same number of
459 patterns in each equation.
464 [pat] -- The patterns
465 (Maybe (HsType id)) -- A type signature for the result of the match
466 -- Nothing after typechecking
470 -- GRHSs are used both for pattern bindings and for Matches
472 = GRHSs [GRHS id pat] -- Guarded RHSs
473 (HsBinds id pat) -- The where clause
474 PostTcType -- Type of RHS (after type checking)
477 = GRHS [Stmt id pat] -- The RHS is the final ResultStmt
478 -- I considered using a RetunStmt, but
479 -- it printed 'wrong' in error messages
482 mkSimpleMatch :: [pat] -> HsExpr id pat -> Type -> SrcLoc -> Match id pat
483 mkSimpleMatch pats rhs rhs_ty locn
484 = Match pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
486 unguardedRHS :: HsExpr id pat -> SrcLoc -> [GRHS id pat]
487 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
490 @getMatchLoc@ takes a @Match@ and returns the
491 source-location gotten from the GRHS inside.
492 THis is something of a nuisance, but no more.
495 getMatchLoc :: Match id pat -> SrcLoc
496 getMatchLoc (Match _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
499 We know the list must have at least one @Match@ in it.
502 pprMatches :: (Outputable id, Outputable pat)
503 => HsMatchContext id -> [Match id pat] -> SDoc
504 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
506 -- Exported to HsBinds, which can't see the defn of HsMatchContext
507 pprFunBind :: (Outputable id, Outputable pat)
508 => id -> [Match id pat] -> SDoc
509 pprFunBind fun matches = pprMatches (FunRhs fun) matches
511 -- Exported to HsBinds, which can't see the defn of HsMatchContext
512 pprPatBind :: (Outputable id, Outputable pat)
513 => pat -> GRHSs id pat -> SDoc
514 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
517 pprMatch :: (Outputable id, Outputable pat)
518 => HsMatchContext id -> Match id pat -> SDoc
519 pprMatch ctxt (Match pats maybe_ty grhss)
520 = pp_name ctxt <+> sep [sep (map ppr pats),
522 nest 2 (pprGRHSs ctxt grhss)]
524 pp_name (FunRhs fun) = ppr fun
525 pp_name other = empty
526 ppr_maybe_ty = case maybe_ty of
527 Just ty -> dcolon <+> ppr ty
531 pprGRHSs :: (Outputable id, Outputable pat)
532 => HsMatchContext id -> GRHSs id pat -> SDoc
533 pprGRHSs ctxt (GRHSs grhss binds ty)
534 = vcat (map (pprGRHS ctxt) grhss)
536 (if nullBinds binds then empty
537 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
540 pprGRHS :: (Outputable id, Outputable pat)
541 => HsMatchContext id -> GRHS id pat -> SDoc
543 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
546 pprGRHS ctxt (GRHS guarded locn)
547 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
549 ResultStmt expr _ = last guarded -- Last stmt should be a ResultStmt for guards
550 guards = init guarded
552 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
557 %************************************************************************
559 \subsection{Do stmts and list comprehensions}
561 %************************************************************************
565 = BindStmt pat (HsExpr id pat) SrcLoc
566 | LetStmt (HsBinds id pat)
567 | ResultStmt (HsExpr id pat) SrcLoc -- See notes that follow
568 | ExprStmt (HsExpr id pat) PostTcType SrcLoc -- See notes that follow
569 -- The type is the *element type* of the expression
570 | ParStmt [[Stmt id pat]] -- List comp only: parallel set of quals
571 | ParStmtOut [([id], [Stmt id pat])] -- PLC after renaming; the ids are the binders
572 -- bound by the stmts
575 ExprStmts and ResultStmts are a bit tricky, because what they mean
576 depends on the context. Consider the following contexts:
578 A do expression of type (m res_ty)
579 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
580 * ExprStmt E any_ty: do { ....; E; ... }
582 Translation: E >> ...
584 * ResultStmt E: do { ....; E }
588 A list comprehensions of type [elt_ty]
589 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
590 * ExprStmt E Bool: [ .. | .... E ]
592 [ .. | .... | ..., E | ... ]
594 Translation: if E then fail else ...
596 * ResultStmt E: [ E | ... ]
598 Translation: return E
600 A guard list, guarding a RHS of type rhs_ty
601 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
602 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
604 Translation: if E then fail else ...
606 * ResultStmt E: f x | ...guards... = E
610 Array comprehensions are handled like list comprehensions -=chak
613 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
614 consLetStmt EmptyBinds stmts = stmts
615 consLetStmt binds stmts = LetStmt binds : stmts
619 instance (Outputable id, Outputable pat) =>
620 Outputable (Stmt id pat) where
621 ppr stmt = pprStmt stmt
623 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
624 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
625 pprStmt (ExprStmt expr _ _) = ppr expr
626 pprStmt (ResultStmt expr _) = ppr expr
627 pprStmt (ParStmt stmtss)
628 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
629 pprStmt (ParStmtOut stmtss)
630 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
632 pprDo :: (Outputable id, Outputable pat)
633 => HsDoContext -> [Stmt id pat] -> SDoc
634 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
635 pprDo ListComp stmts = pprComp brackets stmts
636 pprDo PArrComp stmts = pprComp pabrackets stmts
638 pprComp :: (Outputable id, Outputable pat)
639 => (SDoc -> SDoc) -> [Stmt id pat] -> SDoc
640 pprComp brack stmts = brack $
641 hang (pprExpr expr <+> char '|')
644 ResultStmt expr _ = last stmts -- Last stmt should
645 quals = init stmts -- be an ResultStmt
648 %************************************************************************
650 \subsection{Enumerations and list comprehensions}
652 %************************************************************************
655 data ArithSeqInfo id pat
656 = From (HsExpr id pat)
657 | FromThen (HsExpr id pat)
659 | FromTo (HsExpr id pat)
661 | FromThenTo (HsExpr id pat)
667 instance (Outputable id, Outputable pat) =>
668 Outputable (ArithSeqInfo id pat) where
669 ppr (From e1) = hcat [ppr e1, pp_dotdot]
670 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
671 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
672 ppr (FromThenTo e1 e2 e3)
673 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
675 pp_dotdot = ptext SLIT(" .. ")
679 %************************************************************************
681 \subsection{HsMatchCtxt}
683 %************************************************************************
686 data HsMatchContext id -- Context of a Match or Stmt
687 = DoCtxt HsDoContext -- Do-stmt or list comprehension
688 | FunRhs id -- Function binding for f
689 | CaseAlt -- Guard on a case alternative
690 | LambdaExpr -- Lambda
691 | PatBindRhs -- Pattern binding
692 | RecUpd -- Record update
695 data HsDoContext = ListComp
697 | PArrComp -- parallel array comprehension
701 isDoExpr (DoCtxt DoExpr) = True
702 isDoExpr other = False
706 matchSeparator (FunRhs _) = ptext SLIT("=")
707 matchSeparator CaseAlt = ptext SLIT("->")
708 matchSeparator LambdaExpr = ptext SLIT("->")
709 matchSeparator PatBindRhs = ptext SLIT("=")
710 matchSeparator (DoCtxt _) = ptext SLIT("<-")
711 matchSeparator RecUpd = panic "When is this used?"
715 pprMatchContext (FunRhs fun) = ptext SLIT("In the definition of") <+> quotes (ppr fun)
716 pprMatchContext CaseAlt = ptext SLIT("In a case alternative")
717 pprMatchContext RecUpd = ptext SLIT("In a record-update construct")
718 pprMatchContext PatBindRhs = ptext SLIT("In a pattern binding")
719 pprMatchContext LambdaExpr = ptext SLIT("In a lambda abstraction")
720 pprMatchContext (DoCtxt DoExpr) = ptext SLIT("In a 'do' expression pattern binding")
721 pprMatchContext (DoCtxt ListComp) =
722 ptext SLIT("In a 'list comprehension' pattern binding")
723 pprMatchContext (DoCtxt PArrComp) =
724 ptext SLIT("In an 'array comprehension' pattern binding")
726 -- Used to generate the string for a *runtime* error message
727 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
728 matchContextErrString CaseAlt = "case"
729 matchContextErrString PatBindRhs = "pattern binding"
730 matchContextErrString RecUpd = "record update"
731 matchContextErrString LambdaExpr = "lambda"
732 matchContextErrString (DoCtxt DoExpr) = "'do' expression"
733 matchContextErrString (DoCtxt ListComp) = "list comprehension"
734 matchContextErrString (DoCtxt PArrComp) = "array comprehension"