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