[project @ 1999-09-01 14:08:19 by sof]
[ghc-hetmet.git] / ghc / compiler / parser / ParseUtil.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1999
3 %
4 \section[ParseUtil]{Parser Utilities}
5
6 \begin{code}
7 module ParseUtil (
8           parseError            -- String -> Pa
9         , srcParseErr           -- StringBuffer -> SrcLoc -> Message
10         , cbot                  -- a
11         , splitForConApp        -- RdrNameHsType -> [RdrNameBangType]
12                                 --     -> P (RdrName, [RdrNameBangType])
13
14         , mkRecConstrOrUpdate   -- HsExp -> [HsFieldUpdate] -> P HsExp
15         , groupBindings
16         
17         , mkExtName             -- Maybe ExtName -> RdrName -> ExtName
18
19         , checkPrec             -- String -> P String
20         , checkContext          -- HsType -> P HsContext
21         , checkInstType         -- HsType -> P HsType
22         , checkAssertion        -- HsType -> P HsAsst
23         , checkDataHeader       -- HsQualType -> P (HsContext,HsName,[HsName])
24         , checkSimple           -- HsType -> [HsName] -> P ((HsName,[HsName]))
25         , checkPattern          -- HsExp -> P HsPat
26         , checkPatterns         -- [HsExp] -> P [HsPat]
27         -- , checkExpr          -- HsExp -> P HsExp
28         , checkValDef           -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
29
30         
31         -- some built-in names (all :: RdrName)
32         , unitCon_RDR, unitTyCon_RDR, nilCon_RDR, listTyCon_RDR
33         , tupleCon_RDR, tupleTyCon_RDR, ubxTupleCon_RDR, ubxTupleTyCon_RDR
34         , funTyCon_RDR
35
36         -- pseudo-keywords, in var and tyvar forms (all :: RdrName)
37         , as_var_RDR, hiding_var_RDR, qualified_var_RDR, forall_var_RDR
38         , export_var_RDR, label_var_RDR, dynamic_var_RDR, unsafe_var_RDR
39         , stdcall_var_RDR, ccall_var_RDR
40
41         , as_tyvar_RDR, hiding_tyvar_RDR, qualified_tyvar_RDR
42         , export_tyvar_RDR, label_tyvar_RDR, dynamic_tyvar_RDR
43         , unsafe_tyvar_RDR, stdcall_tyvar_RDR, ccall_tyvar_RDR
44
45         , minus_RDR, pling_RDR, dot_RDR
46
47  ) where
48
49 #include "HsVersions.h"
50
51 import Lex
52 import HsSyn
53 import SrcLoc
54 import RdrHsSyn
55 import RdrName
56 import CallConv
57 import PrelMods         ( pRELUDE_Name, mkUbxTupNameStr, mkTupNameStr )
58 import OccName          ( dataName, tcName, varName, tvName, setOccNameSpace, occNameFS )
59 import CmdLineOpts      ( opt_NoImplicitPrelude )
60 import StringBuffer     ( lexemeToString )
61 import FastString       ( unpackFS )
62 import ErrUtils
63 import UniqFM           ( UniqFM, listToUFM, lookupUFM )
64 import Outputable
65
66 -----------------------------------------------------------------------------
67 -- Misc utils
68
69 parseError :: String -> P a
70 parseError s = 
71   getSrcLocP `thenP` \ loc ->
72   failMsgP (hcat [ppr loc, text ": ", text s])
73
74 srcParseErr :: StringBuffer -> SrcLoc -> Message
75 srcParseErr s l
76   = hcat [ppr l, ptext SLIT(": parse error on input "),
77           char '`', text (lexemeToString s), char '\'']
78
79 cbot = panic "CCall:result_ty"
80
81 -----------------------------------------------------------------------------
82 -- splitForConApp
83
84 -- When parsing data declarations, we sometimes inadvertently parse
85 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
86 -- This function splits up the type application, adds any pending
87 -- arguments, and converts the type constructor back into a data constructor.
88
89 splitForConApp :: RdrNameHsType -> [RdrNameBangType]
90         -> P (RdrName, [RdrNameBangType])
91
92 splitForConApp  t ts = split t ts
93  where
94         split (MonoTyApp t u) ts = split t (Unbanged u : ts)
95
96         split (MonoTyVar t)   ts  = returnP (con, ts)
97            where t_occ = rdrNameOcc t
98                  con   = setRdrNameOcc t (setOccNameSpace t_occ dataName)
99
100         split _ _ = parseError "Illegal data/newtype declaration"
101
102 ----------------------------------------------------------------------------
103 -- Various Syntactic Checks
104
105 callConvFM :: UniqFM CallConv
106 callConvFM = listToUFM $
107       map (\ (x,y) -> (_PK_ x,y))
108      [  ("stdcall",  stdCallConv),
109         ("ccall",    cCallConv)
110 --      ("pascal",   pascalCallConv),
111 --      ("fastcall", fastCallConv)
112      ]
113
114 checkCallConv :: FAST_STRING -> P CallConv
115 checkCallConv s = 
116   case lookupUFM callConvFM s of
117         Nothing -> parseError ("unknown calling convention: `"
118                                  ++ unpackFS s ++ "'")
119         Just conv -> returnP conv
120
121 checkInstType :: RdrNameHsType -> P RdrNameHsType
122 checkInstType t 
123   = case t of
124         HsForAllTy tvs ctxt ty ->
125                 checkAssertion ty [] `thenP` \(c,ts)->
126                 returnP (HsForAllTy tvs ctxt (MonoDictTy c ts))
127
128         ty ->   checkAssertion ty [] `thenP` \(c,ts)->
129                 returnP (HsForAllTy Nothing [] (MonoDictTy c ts))
130
131 checkContext :: RdrNameHsType -> P RdrNameContext
132 checkContext (MonoTupleTy ts True) 
133   = mapP (\t -> checkAssertion t []) ts `thenP` \cs ->
134     returnP cs
135 checkContext (MonoTyVar t) -- empty contexts are allowed
136   | t == unitTyCon_RDR = returnP []
137 checkContext t 
138   = checkAssertion t [] `thenP` \c ->
139     returnP [c]
140
141 checkAssertion :: RdrNameHsType -> [RdrNameHsType] 
142         -> P (ClassAssertion RdrName)
143 checkAssertion (MonoTyVar t) args@(_:_) | not (isRdrTyVar t) 
144         = returnP (t,args)
145 checkAssertion (MonoTyApp l r) args = checkAssertion l (r:args)
146 checkAssertion _ _ = parseError "Illegal class assertion"
147
148 checkDataHeader :: RdrNameHsType 
149         -> P (RdrNameContext, RdrName, [RdrNameHsTyVar])
150 checkDataHeader (HsForAllTy Nothing cs t) =
151    checkSimple t []          `thenP` \(c,ts) ->
152    returnP (cs,c,map UserTyVar ts)
153 checkDataHeader t =
154    checkSimple t []          `thenP` \(c,ts) ->
155    returnP ([],c,map UserTyVar ts)
156
157 checkSimple :: RdrNameHsType -> [RdrName] -> P ((RdrName,[RdrName]))
158 checkSimple (MonoTyApp l (MonoTyVar a)) xs | isRdrTyVar a 
159    = checkSimple l (a:xs)
160 checkSimple (MonoTyVar t) xs | not (isRdrTyVar t) = returnP (t,xs)
161 checkSimple t _ = trace (showSDoc (ppr t)) $ parseError "Illegal data/newtype declaration"
162
163 ---------------------------------------------------------------------------
164 -- Checking Patterns.
165
166 -- We parse patterns as expressions and check for valid patterns below,
167 -- nverting the expression into a pattern at the same time.
168
169 checkPattern :: RdrNameHsExpr -> P RdrNamePat
170 checkPattern e = checkPat e []
171
172 checkPatterns :: [RdrNameHsExpr] -> P [RdrNamePat]
173 checkPatterns es = mapP checkPattern es
174
175 checkPat :: RdrNameHsExpr -> [RdrNamePat] -> P RdrNamePat
176 checkPat (HsVar c) args | isRdrDataCon c = returnP (ConPatIn c args)
177 checkPat (HsApp f x) args = 
178         checkPat x [] `thenP` \x ->
179         checkPat f (x:args)
180 checkPat e [] = case e of
181         EWildPat           -> returnP WildPatIn
182         HsVar x            -> returnP (VarPatIn x)
183         HsLit l            -> returnP (LitPatIn l)
184         ELazyPat e         -> checkPat e [] `thenP` (returnP . LazyPatIn)
185         EAsPat n e         -> checkPat e [] `thenP` (returnP . AsPatIn n)
186         ExprWithTySig e t  -> checkPat e [] `thenP` \e ->
187                               -- pattern signatures are parsed as sigtypes,
188                               -- but they aren't explicit forall points.  Hence
189                               -- we have to remove the implicit forall here.
190                               let t' = case t of 
191                                           HsForAllTy Nothing [] ty -> ty
192                                           other -> other
193                               in
194                               returnP (SigPatIn e t')
195
196         OpApp (HsVar n) (HsVar plus) _ (HsLit k@(HsInt _)) | plus == plus_RDR
197                            -> returnP (NPlusKPatIn n k)
198
199         OpApp l op fix r   -> checkPat l [] `thenP` \l ->
200                               checkPat r [] `thenP` \r ->
201                               case op of
202                                  HsVar c -> returnP (ConOpPatIn l c fix r)
203                                  _ -> patFail
204
205         NegApp l r         -> checkPat l [] `thenP` (returnP . NegPatIn)
206         HsPar e            -> checkPat e [] `thenP` (returnP . ParPatIn)
207         ExplicitList es    -> mapP (\e -> checkPat e []) es `thenP` \ps ->
208                               returnP (ListPatIn ps)
209         ExplicitTuple es b -> mapP (\e -> checkPat e []) es `thenP` \ps ->
210                               returnP (TuplePatIn ps b)
211         RecordCon c fs     -> mapP checkPatField fs `thenP` \fs ->
212                               returnP (RecPatIn c fs)
213         _ -> patFail
214
215 checkPat _ _ = patFail
216
217 checkPatField :: (RdrName, RdrNameHsExpr, Bool) 
218         -> P (RdrName, RdrNamePat, Bool)
219 checkPatField (n,e,b) =
220         checkPat e [] `thenP` \p ->
221         returnP (n,p,b)
222
223 patFail = parseError "Parse error in pattern"
224
225 ---------------------------------------------------------------------------
226 -- Check Expression Syntax
227
228 {-
229 We can get away without checkExpr if the renamer generates errors for
230 pattern syntax used in expressions (wildcards, as patterns and lazy 
231 patterns).
232
233 checkExpr :: RdrNameHsExpr -> P RdrNameHsExpr
234 checkExpr e = case e of
235         HsVar _                   -> returnP e
236         HsLit _                   -> returnP e
237         HsLam match               -> checkMatch match `thenP` (returnP.HsLam)
238         HsApp e1 e2               -> check2Exprs e1 e2 HsApp
239         OpApp e1 e2 fix e3        -> checkExpr e1 `thenP` \e1 ->
240                                      checkExpr e2 `thenP` \e2 ->
241                                      checkExpr e3 `thenP` \e3 ->
242                                      returnP (OpApp e1 e2 fix e3)
243         NegApp e neg              -> checkExpr e `thenP` \e ->
244                                      returnP (NegApp e neg)
245         HsPar e                   -> check1Expr e HsPar
246         SectionL e1 e2            -> check2Exprs e1 e2 SectionL
247         SectionR e1 e2            -> check2Exprs e1 e2 SectionR
248         HsCase e alts             -> mapP checkMatch alts `thenP` \alts ->
249                                      checkExpr e `thenP` \e ->
250                                      returnP (HsCase e alts)
251         HsIf e1 e2 e3             -> check3Exprs e1 e2 e3 HsIf
252
253         HsLet bs e                -> check1Expr e (HsLet bs)
254         HsDo stmts                -> mapP checkStmt stmts `thenP` (returnP . HsDo)
255         HsTuple es                -> checkManyExprs es HsTuple
256         HsList es                 -> checkManyExprs es HsList
257         HsRecConstr c fields      -> mapP checkField fields `thenP` \fields ->
258                                      returnP (HsRecConstr c fields)
259         HsRecUpdate e fields      -> mapP checkField fields `thenP` \fields ->
260                                      checkExpr e `thenP` \e ->
261                                      returnP (HsRecUpdate e fields)
262         HsEnumFrom e              -> check1Expr e HsEnumFrom
263         HsEnumFromTo e1 e2        -> check2Exprs e1 e2 HsEnumFromTo
264         HsEnumFromThen e1 e2      -> check2Exprs e1 e2 HsEnumFromThen
265         HsEnumFromThenTo e1 e2 e3 -> check3Exprs e1 e2 e3 HsEnumFromThenTo
266         HsListComp e stmts        -> mapP checkStmt stmts `thenP` \stmts ->
267                                      checkExpr e `thenP` \e ->
268                                      returnP (HsListComp e stmts)
269         RdrNameHsExprTypeSig loc e ty     -> checkExpr e `thenP` \e ->
270                                      returnP (RdrNameHsExprTypeSig loc e ty)
271         _                         -> parseError "parse error in expression"
272
273 -- type signature for polymorphic recursion!!
274 check1Expr :: RdrNameHsExpr -> (RdrNameHsExpr -> a) -> P a
275 check1Expr e f = checkExpr e `thenP` (returnP . f)
276
277 check2Exprs :: RdrNameHsExpr -> RdrNameHsExpr -> (RdrNameHsExpr -> RdrNameHsExpr -> a) -> P a
278 check2Exprs e1 e2 f = 
279         checkExpr e1 `thenP` \e1 ->
280         checkExpr e2 `thenP` \e2 ->
281         returnP (f e1 e2)
282
283 check3Exprs :: RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr -> (RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr -> a) -> P a
284 check3Exprs e1 e2 e3 f = 
285         checkExpr e1 `thenP` \e1 ->
286         checkExpr e2 `thenP` \e2 ->
287         checkExpr e3 `thenP` \e3 ->
288         returnP (f e1 e2 e3)
289
290 checkManyExprs es f =
291         mapP checkExpr es `thenP` \es ->
292         returnP (f es) 
293
294 checkAlt (HsAlt loc p galts bs) 
295         = checkGAlts galts `thenP` \galts -> returnP (HsAlt loc p galts bs)
296
297 checkGAlts (HsUnGuardedAlt e) = check1Expr e HsUnGuardedAlt
298 checkGAlts (HsGuardedAlts galts) 
299     = mapP checkGAlt galts `thenP` (returnP . HsGuardedAlts)
300
301 checkGAlt (HsGuardedAlt loc e1 e2) = check2Exprs e1 e2 (HsGuardedAlt loc)
302
303 checkStmt (HsGenerator p e) = check1Expr e (HsGenerator p)
304 checkStmt (HsQualifier e)   = check1Expr e HsQualifier
305 checkStmt s@(HsLetStmt bs)  = returnP s
306
307 checkField (HsFieldUpdate n e) = check1Expr e (HsFieldUpdate n)
308 checkField e = returnP e
309 -}
310 ---------------------------------------------------------------------------
311 -- Check Equation Syntax
312
313 checkValDef 
314         :: RdrNameHsExpr
315         -> Maybe RdrNameHsType
316         -> RdrNameGRHSs
317         -> SrcLoc
318         -> P RdrNameMonoBinds
319
320 checkValDef lhs opt_sig grhss loc
321  = case isFunLhs lhs [] of
322            Just (f,inf,es) -> 
323                 checkPatterns es `thenP` \ps ->
324                 returnP (FunMonoBind f inf [Match [] ps opt_sig grhss] loc)
325
326            Nothing ->
327                 checkPattern lhs `thenP` \lhs ->
328                 returnP (PatMonoBind lhs grhss loc)
329
330 -- A variable binding is parsed as an RdrNamePatBind.
331
332 isFunLhs (OpApp l (HsVar op) fix r) []  | not (isRdrDataCon op)
333                                 = Just (op, True, [l,r])
334 isFunLhs (HsVar f) es@(_:_)  | not (isRdrDataCon f)
335                                 = Just (f,False,es)
336 isFunLhs (HsApp f e) es         = isFunLhs f (e:es)
337 isFunLhs (HsPar e)   es         = isFunLhs e es
338 isFunLhs _ _                    = Nothing
339
340 ---------------------------------------------------------------------------
341 -- Miscellaneous utilities
342
343 checkPrec :: Integer -> P ()
344 checkPrec i | 0 <= i && i <= 9 = returnP ()
345             | otherwise        = parseError "precedence out of range"
346
347 mkRecConstrOrUpdate 
348         :: RdrNameHsExpr 
349         -> RdrNameHsRecordBinds
350         -> P RdrNameHsExpr
351
352 mkRecConstrOrUpdate (HsVar c) fs | isRdrDataCon c
353   = returnP (RecordCon c fs)
354 mkRecConstrOrUpdate exp fs@(_:_) 
355   = returnP (RecordUpd exp fs)
356 mkRecConstrOrUpdate _ _
357   = parseError "Empty record update"
358
359 -- supplying the ext_name in a foreign decl is optional ; if it
360 -- isn't there, the Haskell name is assumed. Note that no transformation
361 -- of the Haskell name is then performed, so if you foreign export (++),
362 -- it's external name will be "++". Too bad.
363 mkExtName :: Maybe ExtName -> RdrName -> ExtName
364 mkExtName Nothing rdrNm = ExtName (occNameFS (rdrNameOcc rdrNm)) Nothing
365 mkExtName (Just x) _    = x
366
367 -----------------------------------------------------------------------------
368 -- group function bindings into equation groups
369
370 -- we assume the bindings are coming in reverse order, so we take the srcloc
371 -- from the *last* binding in the group as the srcloc for the whole group.
372
373 groupBindings :: [RdrBinding] -> RdrBinding
374 groupBindings binds = group Nothing binds
375   where group :: Maybe RdrNameMonoBinds -> [RdrBinding] -> RdrBinding
376         group (Just bind) [] = RdrValBinding bind
377         group Nothing [] = RdrNullBind
378         group (Just (FunMonoBind f inf1 mtchs ignore_srcloc))
379                     (RdrValBinding (FunMonoBind f' _ [mtch] loc) : binds)
380             | f == f' = group (Just (FunMonoBind f inf1 (mtch:mtchs) loc)) binds
381
382         group (Just so_far) binds
383             = RdrValBinding so_far `RdrAndBindings` group Nothing binds
384         group Nothing (bind:binds)
385             = case bind of
386                 RdrValBinding b@(FunMonoBind _ _ _ _) -> group (Just b) binds
387                 other -> bind `RdrAndBindings` group Nothing binds
388
389 -----------------------------------------------------------------------------
390 -- Built-in names
391
392 unitCon_RDR, unitTyCon_RDR, nilCon_RDR, listTyCon_RDR :: RdrName
393 tupleCon_RDR, tupleTyCon_RDR            :: Int -> RdrName
394 ubxTupleCon_RDR, ubxTupleTyCon_RDR      :: Int -> RdrName
395
396 unitCon_RDR
397         | opt_NoImplicitPrelude = mkSrcUnqual   dataName unitName
398         | otherwise             = mkPreludeQual dataName pRELUDE_Name unitName
399
400 unitTyCon_RDR
401         | opt_NoImplicitPrelude = mkSrcUnqual   tcName unitName
402         | otherwise             = mkPreludeQual tcName pRELUDE_Name unitName
403
404 nilCon_RDR
405         | opt_NoImplicitPrelude = mkSrcUnqual   dataName listName
406         | otherwise             = mkPreludeQual dataName pRELUDE_Name listName
407
408 listTyCon_RDR
409         | opt_NoImplicitPrelude = mkSrcUnqual   tcName listName
410         | otherwise             = mkPreludeQual tcName pRELUDE_Name listName
411
412 funTyCon_RDR
413         | opt_NoImplicitPrelude = mkSrcUnqual   tcName funName
414         | otherwise             = mkPreludeQual tcName pRELUDE_Name funName
415
416 tupleCon_RDR arity
417   | opt_NoImplicitPrelude = mkSrcUnqual   dataName (snd (mkTupNameStr arity))
418   | otherwise             = mkPreludeQual dataName pRELUDE_Name
419                                 (snd (mkTupNameStr arity))
420
421 tupleTyCon_RDR arity
422   | opt_NoImplicitPrelude = mkSrcUnqual   tcName (snd (mkTupNameStr arity))
423   | otherwise             = mkPreludeQual tcName pRELUDE_Name
424                                 (snd (mkTupNameStr arity))
425
426
427 ubxTupleCon_RDR arity
428   | opt_NoImplicitPrelude = mkSrcUnqual   dataName (snd (mkUbxTupNameStr arity))
429   | otherwise             = mkPreludeQual dataName pRELUDE_Name 
430                                 (snd (mkUbxTupNameStr arity))
431
432 ubxTupleTyCon_RDR arity
433   | opt_NoImplicitPrelude = mkSrcUnqual   tcName (snd (mkUbxTupNameStr arity))
434   | otherwise             = mkPreludeQual tcName pRELUDE_Name 
435                                 (snd (mkUbxTupNameStr arity))
436
437 unitName = SLIT("()")
438 funName  = SLIT("(->)")
439 listName = SLIT("[]")
440
441 asName              = SLIT("as")
442 hidingName          = SLIT("hiding")
443 qualifiedName       = SLIT("qualified")
444 forallName          = SLIT("forall")
445 exportName          = SLIT("export")
446 labelName           = SLIT("label")
447 dynamicName         = SLIT("dynamic")
448 unsafeName          = SLIT("unsafe")
449 stdcallName         = SLIT("stdcall")
450 ccallName           = SLIT("ccall")
451
452 as_var_RDR          = mkSrcUnqual varName asName
453 hiding_var_RDR      = mkSrcUnqual varName hidingName
454 qualified_var_RDR   = mkSrcUnqual varName qualifiedName
455 forall_var_RDR      = mkSrcUnqual varName forallName
456 export_var_RDR      = mkSrcUnqual varName exportName
457 label_var_RDR       = mkSrcUnqual varName labelName
458 dynamic_var_RDR     = mkSrcUnqual varName dynamicName
459 unsafe_var_RDR      = mkSrcUnqual varName unsafeName
460 stdcall_var_RDR     = mkSrcUnqual varName stdcallName
461 ccall_var_RDR       = mkSrcUnqual varName ccallName
462
463 as_tyvar_RDR        = mkSrcUnqual tvName asName
464 hiding_tyvar_RDR    = mkSrcUnqual tvName hidingName
465 qualified_tyvar_RDR = mkSrcUnqual tvName qualifiedName
466 export_tyvar_RDR    = mkSrcUnqual tvName exportName
467 label_tyvar_RDR     = mkSrcUnqual tvName labelName
468 dynamic_tyvar_RDR   = mkSrcUnqual tvName dynamicName
469 unsafe_tyvar_RDR    = mkSrcUnqual tvName unsafeName
470 stdcall_tyvar_RDR   = mkSrcUnqual tvName stdcallName
471 ccall_tyvar_RDR     = mkSrcUnqual tvName ccallName
472
473 minus_RDR           = mkSrcUnqual varName SLIT("-")
474 pling_RDR           = mkSrcUnqual varName SLIT("!")
475 dot_RDR             = mkSrcUnqual varName SLIT(".")
476
477 plus_RDR            = mkSrcUnqual varName SLIT("+")
478 \end{code}