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