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