[project @ 1999-07-14 14:40:20 by simonpj]
[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 The renamer translates them into the Right Thing.
158
159 \begin{code}
160   | EWildPat                    -- wildcard
161
162   | EAsPat      id              -- as pattern
163                 (HsExpr id pat)
164
165   | ELazyPat    (HsExpr id pat) -- ~ pattern
166 \end{code}
167
168 Everything from here on appears only in typechecker output.
169
170 \begin{code}
171   | TyLam                       -- TRANSLATION
172                 [TyVar]
173                 (HsExpr id pat)
174   | TyApp                       -- TRANSLATION
175                 (HsExpr id pat) -- generated by Spec
176                 [Type]
177
178   -- DictLam and DictApp are "inverses"
179   |  DictLam
180                 [id]
181                 (HsExpr id pat)
182   |  DictApp
183                 (HsExpr id pat)
184                 [id]
185
186 type HsRecordBinds id pat
187   = [(id, HsExpr id pat, Bool)]
188         -- True <=> source code used "punning",
189         -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
190 \end{code}
191
192 A @Dictionary@, unless of length 0 or 1, becomes a tuple.  A
193 @ClassDictLam dictvars methods expr@ is, therefore:
194 \begin{verbatim}
195 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
196 \end{verbatim}
197
198 \begin{code}
199 instance (Outputable id, Outputable pat) =>
200                 Outputable (HsExpr id pat) where
201     ppr expr = pprExpr expr
202 \end{code}
203
204 \begin{code}
205 pprExpr :: (Outputable id, Outputable pat)
206         => HsExpr id pat -> SDoc
207
208 pprExpr e = pprDeeper (ppr_expr e)
209 pprBinds b = pprDeeper (ppr b)
210
211 ppr_expr (HsVar v) = ppr v
212
213 ppr_expr (HsLit    lit)   = ppr lit
214 ppr_expr (HsLitOut lit _) = ppr lit
215
216 ppr_expr (HsLam match)
217   = hsep [char '\\', nest 2 (pprMatch (True,empty) match)]
218
219 ppr_expr expr@(HsApp e1 e2)
220   = let (fun, args) = collect_args expr [] in
221     (ppr_expr fun) <+> (sep (map ppr_expr args))
222   where
223     collect_args (HsApp fun arg) args = collect_args fun (arg:args)
224     collect_args fun             args = (fun, args)
225
226 ppr_expr (OpApp e1 op fixity e2)
227   = case op of
228       HsVar v -> pp_infixly v
229       _       -> pp_prefixly
230   where
231     pp_e1 = pprParendExpr e1            -- Add parens to make precedence clear
232     pp_e2 = pprParendExpr e2
233
234     pp_prefixly
235       = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
236
237     pp_infixly v
238       = sep [pp_e1, hsep [pp_v_op, pp_e2]]
239       where
240         pp_v = ppr v
241         pp_v_op | isLexId (_PK_ (showSDoc pp_v)) = char '`' <> pp_v <> char '`'
242                 | otherwise                      = pp_v 
243         -- Put it in backquotes if it's not an operator already
244         -- We use (showSDoc pp_v), rather than isSymOcc (getOccName v) simply so
245         -- that we don't need NamedThing in the context of all these funcions.
246         -- Gruesome, but simple.
247
248 ppr_expr (NegApp e _)
249   = char '-' <+> pprParendExpr e
250
251 ppr_expr (HsPar e) = parens (ppr_expr e)
252
253 ppr_expr (SectionL expr op)
254   = case op of
255       HsVar v -> pp_infixly v
256       _       -> pp_prefixly
257   where
258     pp_expr = pprParendExpr expr
259
260     pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
261                        4 (hsep [pp_expr, ptext SLIT("x_ )")])
262     pp_infixly v = parens (sep [pp_expr, ppr v])
263
264 ppr_expr (SectionR op expr)
265   = case op of
266       HsVar v -> pp_infixly v
267       _       -> pp_prefixly
268   where
269     pp_expr = pprParendExpr expr
270
271     pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
272                        4 ((<>) pp_expr rparen)
273     pp_infixly v
274       = parens (sep [ppr v, pp_expr])
275
276 ppr_expr (HsCase expr matches _)
277   = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
278             nest 2 (pprMatches (True, empty) matches) ]
279
280 ppr_expr (HsIf e1 e2 e3 _)
281   = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
282            nest 4 (pprExpr e2),
283            ptext SLIT("else"),
284            nest 4 (pprExpr e3)]
285
286 -- special case: let ... in let ...
287 ppr_expr (HsLet binds expr@(HsLet _ _))
288   = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
289          pprExpr expr]
290
291 ppr_expr (HsLet binds expr)
292   = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
293          hang (ptext SLIT("in"))  2 (ppr expr)]
294
295 ppr_expr (HsDo do_or_list_comp stmts _)            = pprDo do_or_list_comp stmts
296 ppr_expr (HsDoOut do_or_list_comp stmts _ _ _ _ _) = pprDo do_or_list_comp stmts
297
298 ppr_expr (ExplicitList exprs)
299   = brackets (fsep (punctuate comma (map ppr_expr exprs)))
300 ppr_expr (ExplicitListOut ty exprs)
301   = hcat [ brackets (fsep (punctuate comma (map ppr_expr exprs))),
302            ifNotPprForUser ((<>) space (parens (pprType ty))) ]
303
304 ppr_expr (ExplicitTuple exprs True)
305   = parens (sep (punctuate comma (map ppr_expr exprs)))
306
307 ppr_expr (ExplicitTuple exprs False)
308   = ptext SLIT("(#") <> sep (punctuate comma (map ppr_expr exprs)) <> ptext SLIT("#)")
309
310 ppr_expr (HsCon con_id tys args)
311   = ppr con_id <+> sep (map pprParendType tys ++
312                         map pprParendExpr args)
313
314 ppr_expr (RecordCon con_id rbinds)
315   = pp_rbinds (ppr con_id) rbinds
316 ppr_expr (RecordConOut data_con con rbinds)
317   = pp_rbinds (ppr con) rbinds
318
319 ppr_expr (RecordUpd aexp rbinds)
320   = pp_rbinds (pprParendExpr aexp) rbinds
321 ppr_expr (RecordUpdOut aexp _ _ rbinds)
322   = pp_rbinds (pprParendExpr aexp) rbinds
323
324 ppr_expr (ExprWithTySig expr sig)
325   = hang (nest 2 (ppr_expr expr) <+> dcolon)
326          4 (ppr sig)
327
328 ppr_expr (ArithSeqIn info)
329   = brackets (ppr info)
330 ppr_expr (ArithSeqOut expr info)
331   = brackets (ppr info)
332
333 ppr_expr EWildPat = char '_'
334 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
335 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
336
337 ppr_expr (CCall fun args _ is_asm result_ty)
338   = hang (if is_asm
339           then ptext SLIT("_casm_ ``") <> ptext fun <> ptext SLIT("''")
340           else ptext SLIT("_ccall_") <+> ptext fun)
341        4 (sep (map pprParendExpr args))
342
343 ppr_expr (HsSCC lbl expr)
344   = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ptext lbl), pprParendExpr expr ]
345
346 ppr_expr (TyLam tyvars expr)
347   = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
348          4 (ppr_expr expr)
349
350 ppr_expr (TyApp expr [ty])
351   = hang (ppr_expr expr) 4 (pprParendType ty)
352
353 ppr_expr (TyApp expr tys)
354   = hang (ppr_expr expr)
355          4 (brackets (interpp'SP tys))
356
357 ppr_expr (DictLam dictvars expr)
358   = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
359          4 (ppr_expr expr)
360
361 ppr_expr (DictApp expr [dname])
362   = hang (ppr_expr expr) 4 (ppr dname)
363
364 ppr_expr (DictApp expr dnames)
365   = hang (ppr_expr expr)
366          4 (brackets (interpp'SP dnames))
367
368 \end{code}
369
370 Parenthesize unless very simple:
371 \begin{code}
372 pprParendExpr :: (Outputable id, Outputable pat)
373               => HsExpr id pat -> SDoc
374
375 pprParendExpr expr
376   = let
377         pp_as_was = pprExpr expr
378     in
379     case expr of
380       HsLit l               -> ppr l
381       HsLitOut l _          -> ppr l
382
383       HsVar _               -> pp_as_was
384       ExplicitList _        -> pp_as_was
385       ExplicitListOut _ _   -> pp_as_was
386       ExplicitTuple _ _     -> pp_as_was
387       HsPar _               -> pp_as_was
388
389       _                     -> parens pp_as_was
390 \end{code}
391
392 %************************************************************************
393 %*                                                                      *
394 \subsection{Record binds}
395 %*                                                                      *
396 %************************************************************************
397
398 \begin{code}
399 pp_rbinds :: (Outputable id, Outputable pat)
400               => SDoc 
401               -> HsRecordBinds id pat -> SDoc
402
403 pp_rbinds thing rbinds
404   = hang thing 
405          4 (braces (hsep (punctuate comma (map (pp_rbind) rbinds))))
406   where
407     pp_rbind (v, e, pun_flag) 
408       = getPprStyle $ \ sty ->
409         if pun_flag && userStyle sty then
410            ppr v
411         else
412            hsep [ppr v, char '=', ppr e]
413 \end{code}
414
415 %************************************************************************
416 %*                                                                      *
417 \subsection{Do stmts and list comprehensions}
418 %*                                                                      *
419 %************************************************************************
420
421 \begin{code}
422 data StmtCtxt   -- Context of a Stmt
423   = DoStmt              -- Do Statment
424   | ListComp            -- List comprehension
425   | CaseAlt             -- Guard on a case alternative
426   | PatBindRhs          -- Guard on a pattern binding
427   | FunRhs Name         -- Guard on a function defn for f
428   | LambdaBody          -- Body of a lambda abstraction
429                 
430 pprDo DoStmt stmts
431   = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
432 pprDo ListComp stmts
433   = brackets $
434     hang (pprExpr expr <+> char '|')
435        4 (interpp'SP quals)
436   where
437     ReturnStmt expr = last stmts        -- Last stmt should be a ReturnStmt for list comps
438     quals           = init stmts
439 \end{code}
440
441 \begin{code}
442 data Stmt id pat
443   = BindStmt    pat
444                 (HsExpr id pat)
445                 SrcLoc
446
447   | LetStmt     (HsBinds id pat)
448
449   | GuardStmt   (HsExpr id pat)         -- List comps only
450                 SrcLoc
451
452   | ExprStmt    (HsExpr id pat)         -- Do stmts; and guarded things at the end
453                 SrcLoc
454
455   | ReturnStmt  (HsExpr id pat)         -- List comps only, at the end
456 \end{code}
457
458 \begin{code}
459 instance (Outputable id, Outputable pat) =>
460                 Outputable (Stmt id pat) where
461     ppr stmt = pprStmt stmt
462
463 pprStmt (BindStmt pat expr _)
464  = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
465 pprStmt (LetStmt binds)
466  = hsep [ptext SLIT("let"), pprBinds binds]
467 pprStmt (ExprStmt expr _)
468  = ppr expr
469 pprStmt (GuardStmt expr _)
470  = ppr expr
471 pprStmt (ReturnStmt expr)
472  = hsep [ptext SLIT("return"), ppr expr]    
473 \end{code}
474
475 %************************************************************************
476 %*                                                                      *
477 \subsection{Enumerations and list comprehensions}
478 %*                                                                      *
479 %************************************************************************
480
481 \begin{code}
482 data ArithSeqInfo id pat
483   = From            (HsExpr id pat)
484   | FromThen        (HsExpr id pat)
485                     (HsExpr id pat)
486   | FromTo          (HsExpr id pat)
487                     (HsExpr id pat)
488   | FromThenTo      (HsExpr id pat)
489                     (HsExpr id pat)
490                     (HsExpr id pat)
491 \end{code}
492
493 \begin{code}
494 instance (Outputable id, Outputable pat) =>
495                 Outputable (ArithSeqInfo id pat) where
496     ppr (From e1)               = hcat [ppr e1, pp_dotdot]
497     ppr (FromThen e1 e2)        = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
498     ppr (FromTo e1 e3)  = hcat [ppr e1, pp_dotdot, ppr e3]
499     ppr (FromThenTo e1 e2 e3)
500       = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
501
502 pp_dotdot = ptext SLIT(" .. ")
503 \end{code}