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