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