2 % (c) The GRASP/AQUA Project, Glasgow University, 1999
4 \section[ParseUtil]{Parser Utilities}
8 parseError -- String -> Pa
10 , splitForConApp -- RdrNameHsType -> [RdrNameBangType]
11 -- -> P (RdrName, [RdrNameBangType])
13 , mkRecConstrOrUpdate -- HsExp -> [HsFieldUpdate] -> P HsExp
16 , mkExtName -- Maybe ExtName -> RdrName -> ExtName
18 , checkPrec -- String -> P String
19 , checkContext -- HsType -> P HsContext
20 , checkInstType -- HsType -> P HsType
21 , checkDataHeader -- HsQualType -> P (HsContext,HsName,[HsName])
22 , checkSimple -- HsType -> [HsName] -> P ((HsName,[HsName]))
23 , checkPattern -- HsExp -> P HsPat
24 , checkPatterns -- [HsExp] -> P [HsPat]
25 -- , checkExpr -- HsExp -> P HsExp
26 , checkValDef -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
27 , checkValSig -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
30 -- some built-in names (all :: RdrName)
31 , unitCon_RDR, unitTyCon_RDR, nilCon_RDR, listTyCon_RDR
32 , tupleCon_RDR, tupleTyCon_RDR, ubxTupleCon_RDR, ubxTupleTyCon_RDR
35 -- pseudo-keywords, in var and tyvar forms (all :: RdrName)
36 , as_var_RDR, hiding_var_RDR, qualified_var_RDR, forall_var_RDR
37 , export_var_RDR, label_var_RDR, dynamic_var_RDR, unsafe_var_RDR
38 , stdcall_var_RDR, ccall_var_RDR
40 , as_tyvar_RDR, hiding_tyvar_RDR, qualified_tyvar_RDR
41 , export_tyvar_RDR, label_tyvar_RDR, dynamic_tyvar_RDR
42 , unsafe_tyvar_RDR, stdcall_tyvar_RDR, ccall_tyvar_RDR
44 , minus_RDR, pling_RDR, dot_RDR
48 #include "HsVersions.h"
56 import PrelNames ( pRELUDE_Name, mkTupNameStr )
57 import OccName ( dataName, tcName, varName, tvName, setOccNameSpace, occNameUserString )
58 import CmdLineOpts ( opt_NoImplicitPrelude )
59 import StringBuffer ( lexemeToString )
60 import FastString ( unpackFS )
61 import BasicTypes ( Boxity(..) )
62 import UniqFM ( UniqFM, listToUFM, lookupUFM )
65 -----------------------------------------------------------------------------
68 parseError :: String -> P a
70 getSrcLocP `thenP` \ loc ->
71 failMsgP (hcat [ppr loc, text ": ", text s])
73 cbot = panic "CCall:result_ty"
75 -----------------------------------------------------------------------------
78 -- When parsing data declarations, we sometimes inadvertently parse
79 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
80 -- This function splits up the type application, adds any pending
81 -- arguments, and converts the type constructor back into a data constructor.
83 splitForConApp :: RdrNameHsType -> [RdrNameBangType]
84 -> P (RdrName, [RdrNameBangType])
86 splitForConApp t ts = split t ts
88 split (HsAppTy t u) ts = split t (Unbanged u : ts)
90 split (HsTyVar t) ts = returnP (con, ts)
91 where t_occ = rdrNameOcc t
92 con = setRdrNameOcc t (setOccNameSpace t_occ dataName)
94 split _ _ = parseError "Illegal data/newtype declaration"
96 ----------------------------------------------------------------------------
97 -- Various Syntactic Checks
99 callConvFM :: UniqFM CallConv
100 callConvFM = listToUFM $
101 map (\ (x,y) -> (_PK_ x,y))
102 [ ("stdcall", stdCallConv),
104 -- ("pascal", pascalCallConv),
105 -- ("fastcall", fastCallConv)
108 checkCallConv :: FAST_STRING -> P CallConv
110 case lookupUFM callConvFM s of
111 Nothing -> parseError ("unknown calling convention: `"
112 ++ unpackFS s ++ "'")
113 Just conv -> returnP conv
115 checkInstType :: RdrNameHsType -> P RdrNameHsType
118 HsForAllTy tvs ctxt ty ->
119 checkDictTy ty [] `thenP` \ dict_ty ->
120 returnP (HsForAllTy tvs ctxt dict_ty)
122 ty -> checkDictTy ty [] `thenP` \ dict_ty->
123 returnP (HsForAllTy Nothing [] dict_ty)
125 checkContext :: RdrNameHsType -> P RdrNameContext
126 checkContext (HsTupleTy _ ts)
127 = mapP (\t -> checkPred t []) ts `thenP` \ps ->
129 checkContext (HsTyVar t) -- empty contexts are allowed
130 | t == unitTyCon_RDR = returnP []
132 = checkPred t [] `thenP` \p ->
135 checkPred :: RdrNameHsType -> [RdrNameHsType]
136 -> P (HsPred RdrName)
137 checkPred (HsTyVar t) args@(_:_) | not (isRdrTyVar t)
138 = returnP (HsPClass t args)
139 checkPred (HsAppTy l r) args = checkPred l (r:args)
140 checkPred (HsPredTy (HsPIParam n ty)) [] = returnP (HsPIParam n ty)
141 checkPred _ _ = parseError "Illegal class assertion"
143 checkDictTy :: RdrNameHsType -> [RdrNameHsType] -> P RdrNameHsType
144 checkDictTy (HsTyVar t) args@(_:_) | not (isRdrTyVar t)
145 = returnP (mkHsDictTy t args)
146 checkDictTy (HsAppTy l r) args = checkDictTy l (r:args)
147 checkDictTy _ _ = parseError "Illegal class assertion"
149 checkDataHeader :: RdrNameHsType
150 -> P (RdrNameContext, RdrName, [RdrNameHsTyVar])
151 checkDataHeader (HsForAllTy Nothing cs t) =
152 checkSimple t [] `thenP` \(c,ts) ->
153 returnP (cs,c,map UserTyVar ts)
155 checkSimple t [] `thenP` \(c,ts) ->
156 returnP ([],c,map UserTyVar ts)
158 checkSimple :: RdrNameHsType -> [RdrName] -> P ((RdrName,[RdrName]))
159 checkSimple (HsAppTy l (HsTyVar a)) xs | isRdrTyVar a
160 = checkSimple l (a:xs)
161 checkSimple (HsTyVar t) xs | not (isRdrTyVar t) = returnP (t,xs)
162 checkSimple t _ = trace (showSDoc (ppr t)) $ parseError "Illegal data/newtype declaration"
164 ---------------------------------------------------------------------------
165 -- Checking Patterns.
167 -- We parse patterns as expressions and check for valid patterns below,
168 -- nverting the expression into a pattern at the same time.
170 checkPattern :: RdrNameHsExpr -> P RdrNamePat
171 checkPattern e = checkPat e []
173 checkPatterns :: [RdrNameHsExpr] -> P [RdrNamePat]
174 checkPatterns es = mapP checkPattern es
176 checkPat :: RdrNameHsExpr -> [RdrNamePat] -> P RdrNamePat
177 checkPat (HsVar c) args | isRdrDataCon c = returnP (ConPatIn c args)
178 checkPat (HsApp f x) args =
179 checkPat x [] `thenP` \x ->
181 checkPat e [] = case e of
182 EWildPat -> returnP WildPatIn
183 HsVar x -> returnP (VarPatIn x)
184 HsLit l -> returnP (LitPatIn l)
185 ELazyPat e -> checkPat e [] `thenP` (returnP . LazyPatIn)
186 EAsPat n e -> checkPat e [] `thenP` (returnP . AsPatIn n)
187 ExprWithTySig e t -> checkPat e [] `thenP` \e ->
188 -- pattern signatures are parsed as sigtypes,
189 -- but they aren't explicit forall points. Hence
190 -- we have to remove the implicit forall here.
192 HsForAllTy Nothing [] ty -> ty
195 returnP (SigPatIn e t')
197 OpApp (HsVar n) (HsVar plus) _ (HsLit k@(HsInt _)) | plus == plus_RDR
198 -> returnP (NPlusKPatIn n k)
200 OpApp l op fix r -> checkPat l [] `thenP` \l ->
201 checkPat r [] `thenP` \r ->
203 HsVar c -> returnP (ConOpPatIn l c fix r)
206 NegApp l r -> checkPat l [] `thenP` (returnP . NegPatIn)
207 HsPar e -> checkPat e [] `thenP` (returnP . ParPatIn)
208 ExplicitList es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
209 returnP (ListPatIn ps)
210 ExplicitTuple es b -> mapP (\e -> checkPat e []) es `thenP` \ps ->
211 returnP (TuplePatIn ps b)
212 RecordCon c fs -> mapP checkPatField fs `thenP` \fs ->
213 returnP (RecPatIn c fs)
216 checkPat _ _ = patFail
218 checkPatField :: (RdrName, RdrNameHsExpr, Bool)
219 -> P (RdrName, RdrNamePat, Bool)
220 checkPatField (n,e,b) =
221 checkPat e [] `thenP` \p ->
224 patFail = parseError "Parse error in pattern"
226 ---------------------------------------------------------------------------
227 -- Check Expression Syntax
230 We can get away without checkExpr if the renamer generates errors for
231 pattern syntax used in expressions (wildcards, as patterns and lazy
234 checkExpr :: RdrNameHsExpr -> P RdrNameHsExpr
235 checkExpr e = case e of
237 HsIPVar _ -> returnP e
239 HsLam match -> checkMatch match `thenP` (returnP.HsLam)
240 HsApp e1 e2 -> check2Exprs e1 e2 HsApp
241 OpApp e1 e2 fix e3 -> checkExpr e1 `thenP` \e1 ->
242 checkExpr e2 `thenP` \e2 ->
243 checkExpr e3 `thenP` \e3 ->
244 returnP (OpApp e1 e2 fix e3)
245 NegApp e neg -> checkExpr e `thenP` \e ->
246 returnP (NegApp e neg)
247 HsPar e -> check1Expr e HsPar
248 SectionL e1 e2 -> check2Exprs e1 e2 SectionL
249 SectionR e1 e2 -> check2Exprs e1 e2 SectionR
250 HsCase e alts -> mapP checkMatch alts `thenP` \alts ->
251 checkExpr e `thenP` \e ->
252 returnP (HsCase e alts)
253 HsIf e1 e2 e3 -> check3Exprs e1 e2 e3 HsIf
255 HsLet bs e -> check1Expr e (HsLet bs)
256 HsDo stmts -> mapP checkStmt stmts `thenP` (returnP . HsDo)
257 HsTuple es -> checkManyExprs es HsTuple
258 HsList es -> checkManyExprs es HsList
259 HsRecConstr c fields -> mapP checkField fields `thenP` \fields ->
260 returnP (HsRecConstr c fields)
261 HsRecUpdate e fields -> mapP checkField fields `thenP` \fields ->
262 checkExpr e `thenP` \e ->
263 returnP (HsRecUpdate e fields)
264 HsEnumFrom e -> check1Expr e HsEnumFrom
265 HsEnumFromTo e1 e2 -> check2Exprs e1 e2 HsEnumFromTo
266 HsEnumFromThen e1 e2 -> check2Exprs e1 e2 HsEnumFromThen
267 HsEnumFromThenTo e1 e2 e3 -> check3Exprs e1 e2 e3 HsEnumFromThenTo
268 HsListComp e stmts -> mapP checkStmt stmts `thenP` \stmts ->
269 checkExpr e `thenP` \e ->
270 returnP (HsListComp e stmts)
271 RdrNameHsExprTypeSig loc e ty -> checkExpr e `thenP` \e ->
272 returnP (RdrNameHsExprTypeSig loc e ty)
273 _ -> parseError "parse error in expression"
275 -- type signature for polymorphic recursion!!
276 check1Expr :: RdrNameHsExpr -> (RdrNameHsExpr -> a) -> P a
277 check1Expr e f = checkExpr e `thenP` (returnP . f)
279 check2Exprs :: RdrNameHsExpr -> RdrNameHsExpr -> (RdrNameHsExpr -> RdrNameHsExpr -> a) -> P a
280 check2Exprs e1 e2 f =
281 checkExpr e1 `thenP` \e1 ->
282 checkExpr e2 `thenP` \e2 ->
285 check3Exprs :: RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr -> (RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr -> a) -> P a
286 check3Exprs e1 e2 e3 f =
287 checkExpr e1 `thenP` \e1 ->
288 checkExpr e2 `thenP` \e2 ->
289 checkExpr e3 `thenP` \e3 ->
292 checkManyExprs es f =
293 mapP checkExpr es `thenP` \es ->
296 checkAlt (HsAlt loc p galts bs)
297 = checkGAlts galts `thenP` \galts -> returnP (HsAlt loc p galts bs)
299 checkGAlts (HsUnGuardedAlt e) = check1Expr e HsUnGuardedAlt
300 checkGAlts (HsGuardedAlts galts)
301 = mapP checkGAlt galts `thenP` (returnP . HsGuardedAlts)
303 checkGAlt (HsGuardedAlt loc e1 e2) = check2Exprs e1 e2 (HsGuardedAlt loc)
305 checkStmt (HsGenerator p e) = check1Expr e (HsGenerator p)
306 checkStmt (HsQualifier e) = check1Expr e HsQualifier
307 checkStmt s@(HsLetStmt bs) = returnP s
309 checkField (HsFieldUpdate n e) = check1Expr e (HsFieldUpdate n)
310 checkField e = returnP e
312 ---------------------------------------------------------------------------
313 -- Check Equation Syntax
317 -> Maybe RdrNameHsType
322 checkValDef lhs opt_sig grhss loc
323 = case isFunLhs lhs [] of
325 checkPatterns es `thenP` \ps ->
326 returnP (RdrValBinding (FunMonoBind f inf [Match [] ps opt_sig grhss] loc))
329 checkPattern lhs `thenP` \lhs ->
330 returnP (RdrValBinding (PatMonoBind lhs grhss loc))
337 checkValSig (HsVar v) ty loc = returnP (RdrSig (Sig v ty loc))
338 checkValSig other ty loc = parseError "Type signature given for an expression"
341 -- A variable binding is parsed as an RdrNameFunMonoBind.
342 -- See comments with HsBinds.MonoBinds
344 isFunLhs (OpApp l (HsVar op) fix r) es | not (isRdrDataCon op)
345 = Just (op, True, (l:r:es))
346 isFunLhs (HsVar f) es | not (isRdrDataCon f)
348 isFunLhs (HsApp f e) es = isFunLhs f (e:es)
349 isFunLhs (HsPar e) es = isFunLhs e es
350 isFunLhs _ _ = Nothing
352 ---------------------------------------------------------------------------
353 -- Miscellaneous utilities
355 checkPrec :: Integer -> P ()
356 checkPrec i | 0 <= i && i <= 9 = returnP ()
357 | otherwise = parseError "precedence out of range"
361 -> RdrNameHsRecordBinds
364 mkRecConstrOrUpdate (HsVar c) fs | isRdrDataCon c
365 = returnP (RecordCon c fs)
366 mkRecConstrOrUpdate exp fs@(_:_)
367 = returnP (RecordUpd exp fs)
368 mkRecConstrOrUpdate _ _
369 = parseError "Empty record update"
371 -- Supplying the ext_name in a foreign decl is optional ; if it
372 -- isn't there, the Haskell name is assumed. Note that no transformation
373 -- of the Haskell name is then performed, so if you foreign export (++),
374 -- it's external name will be "++". Too bad; it's important because we don't
375 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
376 -- (This is why we use occNameUserString.)
377 mkExtName :: Maybe ExtName -> RdrName -> ExtName
378 mkExtName Nothing rdrNm = ExtName (_PK_ (occNameUserString (rdrNameOcc rdrNm)))
380 mkExtName (Just x) _ = x
382 -----------------------------------------------------------------------------
383 -- group function bindings into equation groups
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.
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
394 -- don't group together FunMonoBinds if they have
395 -- no arguments. This is necessary now that variable bindings
396 -- with no arguments are now treated as FunMonoBinds rather
397 -- than pattern bindings (tests/rename/should_fail/rnfail002).
398 group (Just (FunMonoBind f inf1 mtchs ignore_srcloc))
399 (RdrValBinding (FunMonoBind f' _
400 [mtch@(Match _ (_:_) _ _)] loc)
402 | f == f' = group (Just (FunMonoBind f inf1 (mtch:mtchs) loc)) binds
404 group (Just so_far) binds
405 = RdrValBinding so_far `RdrAndBindings` group Nothing binds
406 group Nothing (bind:binds)
408 RdrValBinding b@(FunMonoBind _ _ _ _) -> group (Just b) binds
409 other -> bind `RdrAndBindings` group Nothing binds
411 -----------------------------------------------------------------------------
414 unitCon_RDR, unitTyCon_RDR, nilCon_RDR, listTyCon_RDR :: RdrName
415 tupleCon_RDR, tupleTyCon_RDR :: Int -> RdrName
416 ubxTupleCon_RDR, ubxTupleTyCon_RDR :: Int -> RdrName
419 | opt_NoImplicitPrelude = mkSrcUnqual dataName unitName
420 | otherwise = mkPreludeQual dataName pRELUDE_Name unitName
423 | opt_NoImplicitPrelude = mkSrcUnqual tcName unitName
424 | otherwise = mkPreludeQual tcName pRELUDE_Name unitName
427 | opt_NoImplicitPrelude = mkSrcUnqual dataName listName
428 | otherwise = mkPreludeQual dataName pRELUDE_Name listName
431 | opt_NoImplicitPrelude = mkSrcUnqual tcName listName
432 | otherwise = mkPreludeQual tcName pRELUDE_Name listName
435 | opt_NoImplicitPrelude = mkSrcUnqual tcName funName
436 | otherwise = mkPreludeQual tcName pRELUDE_Name funName
439 | opt_NoImplicitPrelude = mkSrcUnqual dataName (snd (mkTupNameStr Boxed arity))
440 | otherwise = mkPreludeQual dataName pRELUDE_Name
441 (snd (mkTupNameStr Boxed arity))
444 | opt_NoImplicitPrelude = mkSrcUnqual tcName (snd (mkTupNameStr Boxed arity))
445 | otherwise = mkPreludeQual tcName pRELUDE_Name
446 (snd (mkTupNameStr Boxed arity))
449 ubxTupleCon_RDR arity
450 | opt_NoImplicitPrelude = mkSrcUnqual dataName (snd (mkTupNameStr Unboxed arity))
451 | otherwise = mkPreludeQual dataName pRELUDE_Name
452 (snd (mkTupNameStr Unboxed arity))
454 ubxTupleTyCon_RDR arity
455 | opt_NoImplicitPrelude = mkSrcUnqual tcName (snd (mkTupNameStr Unboxed arity))
456 | otherwise = mkPreludeQual tcName pRELUDE_Name
457 (snd (mkTupNameStr Unboxed arity))
459 unitName = SLIT("()")
460 funName = SLIT("(->)")
461 listName = SLIT("[]")
464 hidingName = SLIT("hiding")
465 qualifiedName = SLIT("qualified")
466 forallName = SLIT("forall")
467 exportName = SLIT("export")
468 labelName = SLIT("label")
469 dynamicName = SLIT("dynamic")
470 unsafeName = SLIT("unsafe")
471 stdcallName = SLIT("stdcall")
472 ccallName = SLIT("ccall")
474 as_var_RDR = mkSrcUnqual varName asName
475 hiding_var_RDR = mkSrcUnqual varName hidingName
476 qualified_var_RDR = mkSrcUnqual varName qualifiedName
477 forall_var_RDR = mkSrcUnqual varName forallName
478 export_var_RDR = mkSrcUnqual varName exportName
479 label_var_RDR = mkSrcUnqual varName labelName
480 dynamic_var_RDR = mkSrcUnqual varName dynamicName
481 unsafe_var_RDR = mkSrcUnqual varName unsafeName
482 stdcall_var_RDR = mkSrcUnqual varName stdcallName
483 ccall_var_RDR = mkSrcUnqual varName ccallName
485 as_tyvar_RDR = mkSrcUnqual tvName asName
486 hiding_tyvar_RDR = mkSrcUnqual tvName hidingName
487 qualified_tyvar_RDR = mkSrcUnqual tvName qualifiedName
488 export_tyvar_RDR = mkSrcUnqual tvName exportName
489 label_tyvar_RDR = mkSrcUnqual tvName labelName
490 dynamic_tyvar_RDR = mkSrcUnqual tvName dynamicName
491 unsafe_tyvar_RDR = mkSrcUnqual tvName unsafeName
492 stdcall_tyvar_RDR = mkSrcUnqual tvName stdcallName
493 ccall_tyvar_RDR = mkSrcUnqual tvName ccallName
495 minus_RDR = mkSrcUnqual varName SLIT("-")
496 pling_RDR = mkSrcUnqual varName SLIT("!")
497 dot_RDR = mkSrcUnqual varName SLIT(".")
499 plus_RDR = mkSrcUnqual varName SLIT("+")