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