829f9ab3c8b4b8ada5e8aef89918dc0cd5075abc
[ghc-hetmet.git] / ghc / compiler / hsSyn / HsExpr.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[HsExpr]{Abstract Haskell syntax: expressions}
5
6 \begin{code}
7 module HsExpr where
8
9 #include "HsVersions.h"
10
11 -- friends:
12 import {-# SOURCE #-} HsMatches ( pprMatches, pprMatch, Match )
13
14 import HsBinds          ( HsBinds(..) )
15 import HsLit            ( HsLit, HsOverLit )
16 import BasicTypes       ( Fixity(..) )
17 import HsTypes          ( HsType )
18
19 -- others:
20 import Name             ( Name, isLexSym ) 
21 import Outputable       
22 import PprType          ( pprType, pprParendType )
23 import Type             ( Type )
24 import Var              ( TyVar )
25 import DataCon          ( DataCon )
26 import CStrings         ( CLabelString, pprCLabelString )
27 import BasicTypes       ( Boxity, tupleParens )
28 import SrcLoc           ( SrcLoc )
29 \end{code}
30
31 %************************************************************************
32 %*                                                                      *
33 \subsection{Expressions proper}
34 %*                                                                      *
35 %************************************************************************
36
37 \begin{code}
38 data HsExpr id pat
39   = HsVar       id              -- variable
40   | HsIPVar     id              -- implicit parameter
41   | HsOverLit   (HsOverLit id)  -- Overloaded literals; eliminated by type checker
42   | HsLit       HsLit           -- Simple (non-overloaded) literals
43
44   | HsLam       (Match  id pat) -- lambda
45   | HsApp       (HsExpr id pat) -- application
46                 (HsExpr id pat)
47
48   -- Operator applications:
49   -- NB Bracketed ops such as (+) come out as Vars.
50
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.
53
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
58
59   -- We preserve prefix negation and parenthesis for the precedence parser.
60   -- They are eventually removed by the type checker.
61
62   | NegApp      (HsExpr id pat) -- negated expr
63                 id              -- the negate id (in a HsVar)
64
65   | HsPar       (HsExpr id pat) -- parenthesised expr
66
67   | SectionL    (HsExpr id pat) -- operand
68                 (HsExpr id pat) -- operator
69   | SectionR    (HsExpr id pat) -- operator
70                 (HsExpr id pat) -- operand
71                                 
72   | HsCase      (HsExpr id pat)
73                 [Match id pat]
74                 SrcLoc
75
76   | HsIf        (HsExpr id pat) --  predicate
77                 (HsExpr id pat) --  then part
78                 (HsExpr id pat) --  else part
79                 SrcLoc
80
81   | HsLet       (HsBinds id pat)        -- let(rec)
82                 (HsExpr  id pat)
83
84   | HsWith      (HsExpr id pat) -- implicit parameter binding
85                 [(id, HsExpr id pat)]
86
87   | HsDo        StmtCtxt
88                 [Stmt id pat]   -- "do":one or more stmts
89                 SrcLoc
90
91   | HsDoOut     StmtCtxt
92                 [Stmt id pat]   -- "do":one or more stmts
93                 id              -- id for return
94                 id              -- id for >>=
95                 id                              -- id for zero
96                 Type            -- Type of the whole expression
97                 SrcLoc
98
99   | ExplicitList                -- syntactic list
100                 [HsExpr id pat]
101   | ExplicitListOut             -- TRANSLATION
102                 Type    -- Gives type of components of list
103                 [HsExpr id pat]
104
105   | ExplicitTuple               -- tuple
106                 [HsExpr id pat]
107                                 -- NB: Unit is ExplicitTuple []
108                                 -- for tuples, we can get the types
109                                 -- direct from the components
110                 Boxity
111
112
113         -- Record construction
114   | RecordCon   id                              -- The constructor
115                 (HsRecordBinds id pat)
116
117   | RecordConOut DataCon
118                 (HsExpr id pat)         -- Data con Id applied to type args
119                 (HsRecordBinds id pat)
120
121
122         -- Record update
123   | RecordUpd   (HsExpr id pat)
124                 (HsRecordBinds id pat)
125
126   | RecordUpdOut (HsExpr id pat)        -- TRANSLATION
127                  Type                   -- Type of *result* record (may differ from
128                                                 -- type of input record)
129                  [id]                   -- Dicts needed for construction
130                  (HsRecordBinds id pat)
131
132   | ExprWithTySig                       -- signature binding
133                 (HsExpr id pat)
134                 (HsType id)
135   | ArithSeqIn                          -- arithmetic sequence
136                 (ArithSeqInfo id pat)
137   | ArithSeqOut
138                 (HsExpr id pat)         -- (typechecked, of course)
139                 (ArithSeqInfo id pat)
140
141   | HsCCall     CLabelString    -- call into the C world; string is
142                 [HsExpr id pat] -- the C function; exprs are the
143                                 -- arguments to pass.
144                 Bool            -- True <=> might cause Haskell
145                                 -- garbage-collection (must generate
146                                 -- more paranoid code)
147                 Bool            -- True <=> it's really a "casm"
148                                 -- NOTE: this CCall is the *boxed*
149                                 -- version; the desugarer will convert
150                                 -- it into the unboxed "ccall#".
151                 Type    -- The result type; will be *bottom*
152                                 -- until the typechecker gets ahold of it
153
154   | HsSCC       FAST_STRING     -- "set cost centre" (_scc_) annotation
155                 (HsExpr id pat) -- expr whose cost is to be measured
156 \end{code}
157
158 These constructors only appear temporarily in the parser.
159 The renamer translates them into the Right Thing.
160
161 \begin{code}
162   | EWildPat                    -- wildcard
163
164   | EAsPat      id              -- as pattern
165                 (HsExpr id pat)
166
167   | ELazyPat    (HsExpr id pat) -- ~ pattern
168 \end{code}
169
170 Everything from here on appears only in typechecker output.
171
172 \begin{code}
173   | TyLam                       -- TRANSLATION
174                 [TyVar]
175                 (HsExpr id pat)
176   | TyApp                       -- TRANSLATION
177                 (HsExpr id pat) -- generated by Spec
178                 [Type]
179
180   -- DictLam and DictApp are "inverses"
181   |  DictLam
182                 [id]
183                 (HsExpr id pat)
184   |  DictApp
185                 (HsExpr id pat)
186                 [id]
187
188 type HsRecordBinds id pat
189   = [(id, HsExpr id pat, Bool)]
190         -- True <=> source code used "punning",
191         -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
192 \end{code}
193
194 A @Dictionary@, unless of length 0 or 1, becomes a tuple.  A
195 @ClassDictLam dictvars methods expr@ is, therefore:
196 \begin{verbatim}
197 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
198 \end{verbatim}
199
200 \begin{code}
201 instance (Outputable id, Outputable pat) =>
202                 Outputable (HsExpr id pat) where
203     ppr expr = pprExpr expr
204 \end{code}
205
206 \begin{code}
207 pprExpr :: (Outputable id, Outputable pat)
208         => HsExpr id pat -> SDoc
209
210 pprExpr e = pprDeeper (ppr_expr e)
211 pprBinds b = pprDeeper (ppr b)
212
213 ppr_expr (HsVar v) 
214         -- Put it in parens if it's an operator
215   | isOperator v = parens (ppr v)
216   | otherwise    = ppr v
217
218 ppr_expr (HsIPVar v)     = {- char '?' <> -} ppr v
219 ppr_expr (HsLit lit)     = ppr lit
220 ppr_expr (HsOverLit lit) = ppr lit
221
222 ppr_expr (HsLam match)
223   = hsep [char '\\', nest 2 (pprMatch (True,empty) match)]
224
225 ppr_expr expr@(HsApp e1 e2)
226   = let (fun, args) = collect_args expr [] in
227     (ppr_expr fun) <+> (sep (map ppr_expr args))
228   where
229     collect_args (HsApp fun arg) args = collect_args fun (arg:args)
230     collect_args fun             args = (fun, args)
231
232 ppr_expr (OpApp e1 op fixity e2)
233   = case op of
234       HsVar v -> pp_infixly v
235       _       -> pp_prefixly
236   where
237     pp_e1 = pprParendExpr e1            -- Add parens to make precedence clear
238     pp_e2 = pprParendExpr e2
239
240     pp_prefixly
241       = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
242
243     pp_infixly v
244       = sep [pp_e1, hsep [pp_v_op, pp_e2]]
245       where
246         pp_v_op | isOperator v = ppr v
247                 | otherwise    = char '`' <> ppr v <> char '`'
248                 -- Put it in backquotes if it's not an operator already
249
250 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
251
252 ppr_expr (HsPar e) = parens (ppr_expr e)
253
254 ppr_expr (SectionL expr op)
255   = case op of
256       HsVar v -> pp_infixly v
257       _       -> pp_prefixly
258   where
259     pp_expr = pprParendExpr expr
260
261     pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
262                        4 (hsep [pp_expr, ptext SLIT("x_ )")])
263     pp_infixly v = parens (sep [pp_expr, ppr v])
264
265 ppr_expr (SectionR op expr)
266   = case op of
267       HsVar v -> pp_infixly v
268       _       -> pp_prefixly
269   where
270     pp_expr = pprParendExpr expr
271
272     pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
273                        4 ((<>) pp_expr rparen)
274     pp_infixly v
275       = parens (sep [ppr v, pp_expr])
276
277 ppr_expr (HsCase expr matches _)
278   = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
279             nest 2 (pprMatches (True, empty) matches) ]
280
281 ppr_expr (HsIf e1 e2 e3 _)
282   = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
283            nest 4 (pprExpr e2),
284            ptext SLIT("else"),
285            nest 4 (pprExpr e3)]
286
287 -- special case: let ... in let ...
288 ppr_expr (HsLet binds expr@(HsLet _ _))
289   = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
290          pprExpr expr]
291
292 ppr_expr (HsLet binds expr)
293   = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
294          hang (ptext SLIT("in"))  2 (ppr expr)]
295
296 ppr_expr (HsWith expr binds)
297   = hsep [ppr expr, ptext SLIT("with"), ppr binds]
298
299 ppr_expr (HsDo do_or_list_comp stmts _)            = pprDo do_or_list_comp stmts
300 ppr_expr (HsDoOut do_or_list_comp stmts _ _ _ _ _) = pprDo do_or_list_comp stmts
301
302 ppr_expr (ExplicitList exprs)
303   = brackets (fsep (punctuate comma (map ppr_expr exprs)))
304 ppr_expr (ExplicitListOut ty exprs)
305   = hcat [ brackets (fsep (punctuate comma (map ppr_expr exprs))),
306            ifNotPprForUser ((<>) space (parens (pprType ty))) ]
307
308 ppr_expr (ExplicitTuple exprs boxity)
309   = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
310
311 ppr_expr (RecordCon con_id rbinds)
312   = pp_rbinds (ppr con_id) rbinds
313 ppr_expr (RecordConOut data_con con rbinds)
314   = pp_rbinds (ppr con) rbinds
315
316 ppr_expr (RecordUpd aexp rbinds)
317   = pp_rbinds (pprParendExpr aexp) rbinds
318 ppr_expr (RecordUpdOut aexp _ _ rbinds)
319   = pp_rbinds (pprParendExpr aexp) rbinds
320
321 ppr_expr (ExprWithTySig expr sig)
322   = hang (nest 2 (ppr_expr expr) <+> dcolon)
323          4 (ppr sig)
324
325 ppr_expr (ArithSeqIn info)
326   = brackets (ppr info)
327 ppr_expr (ArithSeqOut expr info)
328   = brackets (ppr info)
329
330 ppr_expr EWildPat = char '_'
331 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
332 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
333
334 ppr_expr (HsCCall fun args _ is_asm result_ty)
335   = hang (if is_asm
336           then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
337           else ptext SLIT("_ccall_") <+> pprCLabelString fun)
338        4 (sep (map pprParendExpr args))
339
340 ppr_expr (HsSCC lbl expr)
341   = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ptext lbl), pprParendExpr expr ]
342
343 ppr_expr (TyLam tyvars expr)
344   = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
345          4 (ppr_expr expr)
346
347 ppr_expr (TyApp expr [ty])
348   = hang (ppr_expr expr) 4 (pprParendType ty)
349
350 ppr_expr (TyApp expr tys)
351   = hang (ppr_expr expr)
352          4 (brackets (interpp'SP tys))
353
354 ppr_expr (DictLam dictvars expr)
355   = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
356          4 (ppr_expr expr)
357
358 ppr_expr (DictApp expr [dname])
359   = hang (ppr_expr expr) 4 (ppr dname)
360
361 ppr_expr (DictApp expr dnames)
362   = hang (ppr_expr expr)
363          4 (brackets (interpp'SP dnames))
364
365 \end{code}
366
367 Parenthesize unless very simple:
368 \begin{code}
369 pprParendExpr :: (Outputable id, Outputable pat)
370               => HsExpr id pat -> SDoc
371
372 pprParendExpr expr
373   = let
374         pp_as_was = pprExpr expr
375     in
376     case expr of
377       HsLit l               -> ppr l
378       HsOverLit l           -> ppr l
379
380       HsVar _               -> pp_as_was
381       HsIPVar _             -> pp_as_was
382       ExplicitList _        -> pp_as_was
383       ExplicitListOut _ _   -> pp_as_was
384       ExplicitTuple _ _     -> pp_as_was
385       HsPar _               -> pp_as_was
386
387       _                     -> parens pp_as_was
388 \end{code}
389
390 \begin{code}
391 isOperator :: Outputable a => a -> Bool
392 isOperator v = isLexSym (_PK_ (showSDoc (ppr v)))
393         -- We use (showSDoc (ppr v)), rather than isSymOcc (getOccName v) simply so
394         -- that we don't need NamedThing in the context of all these functions.
395         -- Gruesome, but simple.
396 \end{code}
397
398 %************************************************************************
399 %*                                                                      *
400 \subsection{Record binds}
401 %*                                                                      *
402 %************************************************************************
403
404 \begin{code}
405 pp_rbinds :: (Outputable id, Outputable pat)
406               => SDoc 
407               -> HsRecordBinds id pat -> SDoc
408
409 pp_rbinds thing rbinds
410   = hang thing 
411          4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
412   where
413     pp_rbind (v, e, pun_flag) 
414       = getPprStyle $ \ sty ->
415         if pun_flag && userStyle sty then
416            ppr v
417         else
418            hsep [ppr v, char '=', ppr e]
419 \end{code}
420
421 %************************************************************************
422 %*                                                                      *
423 \subsection{Do stmts and list comprehensions}
424 %*                                                                      *
425 %************************************************************************
426
427 \begin{code}
428 data StmtCtxt   -- Context of a Stmt
429   = DoStmt              -- Do Statment
430   | ListComp            -- List comprehension
431   | CaseAlt             -- Guard on a case alternative
432   | PatBindRhs          -- Guard on a pattern binding
433   | FunRhs Name         -- Guard on a function defn for f
434   | LambdaBody          -- Body of a lambda abstraction
435                 
436 pprDo DoStmt stmts
437   = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
438 pprDo ListComp stmts
439   = brackets $
440     hang (pprExpr expr <+> char '|')
441        4 (interpp'SP quals)
442   where
443     ReturnStmt expr = last stmts        -- Last stmt should be a ReturnStmt for list comps
444     quals           = init stmts
445 \end{code}
446
447 \begin{code}
448 data Stmt id pat
449   = BindStmt    pat
450                 (HsExpr id pat)
451                 SrcLoc
452
453   | LetStmt     (HsBinds id pat)
454
455   | GuardStmt   (HsExpr id pat)         -- List comps only
456                 SrcLoc
457
458   | ExprStmt    (HsExpr id pat)         -- Do stmts; and guarded things at the end
459                 SrcLoc
460
461   | ReturnStmt  (HsExpr id pat)         -- List comps only, at the end
462
463 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
464 consLetStmt EmptyBinds stmts = stmts
465 consLetStmt binds      stmts = LetStmt binds : stmts
466 \end{code}
467
468 \begin{code}
469 instance (Outputable id, Outputable pat) =>
470                 Outputable (Stmt id pat) where
471     ppr stmt = pprStmt stmt
472
473 pprStmt (BindStmt pat expr _)
474  = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
475 pprStmt (LetStmt binds)
476  = hsep [ptext SLIT("let"), pprBinds binds]
477 pprStmt (ExprStmt expr _)
478  = ppr expr
479 pprStmt (GuardStmt expr _)
480  = ppr expr
481 pprStmt (ReturnStmt expr)
482  = hsep [ptext SLIT("return"), ppr expr]    
483 \end{code}
484
485 %************************************************************************
486 %*                                                                      *
487 \subsection{Enumerations and list comprehensions}
488 %*                                                                      *
489 %************************************************************************
490
491 \begin{code}
492 data ArithSeqInfo id pat
493   = From            (HsExpr id pat)
494   | FromThen        (HsExpr id pat)
495                     (HsExpr id pat)
496   | FromTo          (HsExpr id pat)
497                     (HsExpr id pat)
498   | FromThenTo      (HsExpr id pat)
499                     (HsExpr id pat)
500                     (HsExpr id pat)
501 \end{code}
502
503 \begin{code}
504 instance (Outputable id, Outputable pat) =>
505                 Outputable (ArithSeqInfo id pat) where
506     ppr (From e1)               = hcat [ppr e1, pp_dotdot]
507     ppr (FromThen e1 e2)        = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
508     ppr (FromTo e1 e3)  = hcat [ppr e1, pp_dotdot, ppr e3]
509     ppr (FromThenTo e1 e2 e3)
510       = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
511
512 pp_dotdot = ptext SLIT(" .. ")
513 \end{code}