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