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, tcClsName,
58 occNameSpace, setOccNameSpace, occNameUserString )
59 import CmdLineOpts ( opt_NoImplicitPrelude )
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 =
91 -- check that we've got a type constructor at the head
92 if occNameSpace t_occ /= tcClsName
94 (showSDoc (text "not a constructor: `" <>
96 else returnP (con, ts)
97 where t_occ = rdrNameOcc t
98 con = setRdrNameOcc t (setOccNameSpace t_occ dataName)
100 split _ _ = parseError "Illegal data/newtype declaration"
102 ----------------------------------------------------------------------------
103 -- Various Syntactic Checks
105 callConvFM :: UniqFM CallConv
106 callConvFM = listToUFM $
107 map (\ (x,y) -> (_PK_ x,y))
108 [ ("stdcall", stdCallConv),
110 -- ("pascal", pascalCallConv),
111 -- ("fastcall", fastCallConv)
114 checkCallConv :: FAST_STRING -> P CallConv
116 case lookupUFM callConvFM s of
117 Nothing -> parseError ("unknown calling convention: `"
118 ++ unpackFS s ++ "'")
119 Just conv -> returnP conv
121 checkInstType :: RdrNameHsType -> P RdrNameHsType
124 HsForAllTy tvs ctxt ty ->
125 checkDictTy ty [] `thenP` \ dict_ty ->
126 returnP (HsForAllTy tvs ctxt dict_ty)
128 ty -> checkDictTy ty [] `thenP` \ dict_ty->
129 returnP (HsForAllTy Nothing [] dict_ty)
131 checkContext :: RdrNameHsType -> P RdrNameContext
132 checkContext (HsTupleTy _ ts)
133 = mapP (\t -> checkPred t []) ts `thenP` \ps ->
135 checkContext (HsTyVar t) -- empty contexts are allowed
136 | t == unitTyCon_RDR = returnP []
138 = checkPred t [] `thenP` \p ->
141 checkPred :: RdrNameHsType -> [RdrNameHsType]
142 -> P (HsPred RdrName)
143 checkPred (HsTyVar t) args@(_:_) | not (isRdrTyVar t)
144 = returnP (HsPClass t args)
145 checkPred (HsAppTy l r) args = checkPred l (r:args)
146 checkPred (HsPredTy (HsPIParam n ty)) [] = returnP (HsPIParam n ty)
147 checkPred _ _ = parseError "Illegal class assertion"
149 checkDictTy :: RdrNameHsType -> [RdrNameHsType] -> P RdrNameHsType
150 checkDictTy (HsTyVar t) args@(_:_) | not (isRdrTyVar t)
151 = returnP (mkHsDictTy t args)
152 checkDictTy (HsAppTy l r) args = checkDictTy l (r:args)
153 checkDictTy _ _ = parseError "Illegal class assertion"
155 checkDataHeader :: RdrNameHsType
156 -> P (RdrNameContext, RdrName, [RdrNameHsTyVar])
157 checkDataHeader (HsForAllTy Nothing cs t) =
158 checkSimple t [] `thenP` \(c,ts) ->
159 returnP (cs,c,map UserTyVar ts)
161 checkSimple t [] `thenP` \(c,ts) ->
162 returnP ([],c,map UserTyVar ts)
164 checkSimple :: RdrNameHsType -> [RdrName] -> P ((RdrName,[RdrName]))
165 checkSimple (HsAppTy l (HsTyVar a)) xs | isRdrTyVar a
166 = checkSimple l (a:xs)
167 checkSimple (HsTyVar t) xs | not (isRdrTyVar t) = returnP (t,xs)
168 checkSimple t _ = trace (showSDoc (ppr t)) $ parseError "Illegal data/newtype declaration"
170 ---------------------------------------------------------------------------
171 -- Checking Patterns.
173 -- We parse patterns as expressions and check for valid patterns below,
174 -- nverting the expression into a pattern at the same time.
176 checkPattern :: RdrNameHsExpr -> P RdrNamePat
177 checkPattern e = checkPat e []
179 checkPatterns :: [RdrNameHsExpr] -> P [RdrNamePat]
180 checkPatterns es = mapP checkPattern es
182 checkPat :: RdrNameHsExpr -> [RdrNamePat] -> P RdrNamePat
183 checkPat (HsVar c) args | isRdrDataCon c = returnP (ConPatIn c args)
184 checkPat (HsApp f x) args =
185 checkPat x [] `thenP` \x ->
187 checkPat e [] = case e of
188 EWildPat -> returnP WildPatIn
189 HsVar x -> returnP (VarPatIn x)
190 HsLit l -> returnP (LitPatIn l)
191 ELazyPat e -> checkPat e [] `thenP` (returnP . LazyPatIn)
192 EAsPat n e -> checkPat e [] `thenP` (returnP . AsPatIn n)
193 ExprWithTySig e t -> checkPat e [] `thenP` \e ->
194 -- pattern signatures are parsed as sigtypes,
195 -- but they aren't explicit forall points. Hence
196 -- we have to remove the implicit forall here.
198 HsForAllTy Nothing [] ty -> ty
201 returnP (SigPatIn e t')
203 OpApp (HsVar n) (HsVar plus) _ (HsLit k@(HsInt _)) | plus == plus_RDR
204 -> returnP (NPlusKPatIn n k)
206 OpApp l op fix r -> checkPat l [] `thenP` \l ->
207 checkPat r [] `thenP` \r ->
209 HsVar c -> returnP (ConOpPatIn l c fix r)
212 NegApp l r -> checkPat l [] `thenP` (returnP . NegPatIn)
213 HsPar e -> checkPat e [] `thenP` (returnP . ParPatIn)
214 ExplicitList es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
215 returnP (ListPatIn ps)
216 ExplicitTuple es b -> mapP (\e -> checkPat e []) es `thenP` \ps ->
217 returnP (TuplePatIn ps b)
218 RecordCon c fs -> mapP checkPatField fs `thenP` \fs ->
219 returnP (RecPatIn c fs)
222 checkPat _ _ = patFail
224 checkPatField :: (RdrName, RdrNameHsExpr, Bool)
225 -> P (RdrName, RdrNamePat, Bool)
226 checkPatField (n,e,b) =
227 checkPat e [] `thenP` \p ->
230 patFail = parseError "Parse error in pattern"
232 ---------------------------------------------------------------------------
233 -- Check Expression Syntax
236 We can get away without checkExpr if the renamer generates errors for
237 pattern syntax used in expressions (wildcards, as patterns and lazy
240 checkExpr :: RdrNameHsExpr -> P RdrNameHsExpr
241 checkExpr e = case e of
243 HsIPVar _ -> returnP e
245 HsLam match -> checkMatch match `thenP` (returnP.HsLam)
246 HsApp e1 e2 -> check2Exprs e1 e2 HsApp
247 OpApp e1 e2 fix e3 -> checkExpr e1 `thenP` \e1 ->
248 checkExpr e2 `thenP` \e2 ->
249 checkExpr e3 `thenP` \e3 ->
250 returnP (OpApp e1 e2 fix e3)
251 NegApp e neg -> checkExpr e `thenP` \e ->
252 returnP (NegApp e neg)
253 HsPar e -> check1Expr e HsPar
254 SectionL e1 e2 -> check2Exprs e1 e2 SectionL
255 SectionR e1 e2 -> check2Exprs e1 e2 SectionR
256 HsCase e alts -> mapP checkMatch alts `thenP` \alts ->
257 checkExpr e `thenP` \e ->
258 returnP (HsCase e alts)
259 HsIf e1 e2 e3 -> check3Exprs e1 e2 e3 HsIf
261 HsLet bs e -> check1Expr e (HsLet bs)
262 HsDo stmts -> mapP checkStmt stmts `thenP` (returnP . HsDo)
263 HsTuple es -> checkManyExprs es HsTuple
264 HsList es -> checkManyExprs es HsList
265 HsRecConstr c fields -> mapP checkField fields `thenP` \fields ->
266 returnP (HsRecConstr c fields)
267 HsRecUpdate e fields -> mapP checkField fields `thenP` \fields ->
268 checkExpr e `thenP` \e ->
269 returnP (HsRecUpdate e fields)
270 HsEnumFrom e -> check1Expr e HsEnumFrom
271 HsEnumFromTo e1 e2 -> check2Exprs e1 e2 HsEnumFromTo
272 HsEnumFromThen e1 e2 -> check2Exprs e1 e2 HsEnumFromThen
273 HsEnumFromThenTo e1 e2 e3 -> check3Exprs e1 e2 e3 HsEnumFromThenTo
274 HsListComp e stmts -> mapP checkStmt stmts `thenP` \stmts ->
275 checkExpr e `thenP` \e ->
276 returnP (HsListComp e stmts)
277 RdrNameHsExprTypeSig loc e ty -> checkExpr e `thenP` \e ->
278 returnP (RdrNameHsExprTypeSig loc e ty)
279 _ -> parseError "parse error in expression"
281 -- type signature for polymorphic recursion!!
282 check1Expr :: RdrNameHsExpr -> (RdrNameHsExpr -> a) -> P a
283 check1Expr e f = checkExpr e `thenP` (returnP . f)
285 check2Exprs :: RdrNameHsExpr -> RdrNameHsExpr -> (RdrNameHsExpr -> RdrNameHsExpr -> a) -> P a
286 check2Exprs e1 e2 f =
287 checkExpr e1 `thenP` \e1 ->
288 checkExpr e2 `thenP` \e2 ->
291 check3Exprs :: RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr -> (RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr -> a) -> P a
292 check3Exprs e1 e2 e3 f =
293 checkExpr e1 `thenP` \e1 ->
294 checkExpr e2 `thenP` \e2 ->
295 checkExpr e3 `thenP` \e3 ->
298 checkManyExprs es f =
299 mapP checkExpr es `thenP` \es ->
302 checkAlt (HsAlt loc p galts bs)
303 = checkGAlts galts `thenP` \galts -> returnP (HsAlt loc p galts bs)
305 checkGAlts (HsUnGuardedAlt e) = check1Expr e HsUnGuardedAlt
306 checkGAlts (HsGuardedAlts galts)
307 = mapP checkGAlt galts `thenP` (returnP . HsGuardedAlts)
309 checkGAlt (HsGuardedAlt loc e1 e2) = check2Exprs e1 e2 (HsGuardedAlt loc)
311 checkStmt (HsGenerator p e) = check1Expr e (HsGenerator p)
312 checkStmt (HsQualifier e) = check1Expr e HsQualifier
313 checkStmt s@(HsLetStmt bs) = returnP s
315 checkField (HsFieldUpdate n e) = check1Expr e (HsFieldUpdate n)
316 checkField e = returnP e
318 ---------------------------------------------------------------------------
319 -- Check Equation Syntax
323 -> Maybe RdrNameHsType
328 checkValDef lhs opt_sig grhss loc
329 = case isFunLhs lhs [] of
331 checkPatterns es `thenP` \ps ->
332 returnP (RdrValBinding (FunMonoBind f inf [Match [] ps opt_sig grhss] loc))
335 checkPattern lhs `thenP` \lhs ->
336 returnP (RdrValBinding (PatMonoBind lhs grhss loc))
343 checkValSig (HsVar v) ty loc = returnP (RdrSig (Sig v ty loc))
344 checkValSig other ty loc = parseError "Type signature given for an expression"
347 -- A variable binding is parsed as an RdrNameFunMonoBind.
348 -- See comments with HsBinds.MonoBinds
350 isFunLhs (OpApp l (HsVar op) fix r) es | not (isRdrDataCon op)
351 = Just (op, True, (l:r:es))
352 isFunLhs (HsVar f) es | not (isRdrDataCon f)
354 isFunLhs (HsApp f e) es = isFunLhs f (e:es)
355 isFunLhs (HsPar e) es = isFunLhs e es
356 isFunLhs _ _ = Nothing
358 ---------------------------------------------------------------------------
359 -- Miscellaneous utilities
361 checkPrec :: Integer -> P ()
362 checkPrec i | 0 <= i && i <= 9 = returnP ()
363 | otherwise = parseError "precedence out of range"
367 -> RdrNameHsRecordBinds
370 mkRecConstrOrUpdate (HsVar c) fs | isRdrDataCon c
371 = returnP (RecordCon c fs)
372 mkRecConstrOrUpdate exp fs@(_:_)
373 = returnP (RecordUpd exp fs)
374 mkRecConstrOrUpdate _ _
375 = parseError "Empty record update"
377 -- Supplying the ext_name in a foreign decl is optional ; if it
378 -- isn't there, the Haskell name is assumed. Note that no transformation
379 -- of the Haskell name is then performed, so if you foreign export (++),
380 -- it's external name will be "++". Too bad; it's important because we don't
381 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
382 -- (This is why we use occNameUserString.)
383 mkExtName :: Maybe ExtName -> RdrName -> ExtName
384 mkExtName Nothing rdrNm = ExtName (_PK_ (occNameUserString (rdrNameOcc rdrNm)))
386 mkExtName (Just x) _ = x
388 -----------------------------------------------------------------------------
389 -- group function bindings into equation groups
391 -- we assume the bindings are coming in reverse order, so we take the srcloc
392 -- from the *last* binding in the group as the srcloc for the whole group.
394 groupBindings :: [RdrBinding] -> RdrBinding
395 groupBindings binds = group Nothing binds
396 where group :: Maybe RdrNameMonoBinds -> [RdrBinding] -> RdrBinding
397 group (Just bind) [] = RdrValBinding bind
398 group Nothing [] = RdrNullBind
400 -- don't group together FunMonoBinds if they have
401 -- no arguments. This is necessary now that variable bindings
402 -- with no arguments are now treated as FunMonoBinds rather
403 -- than pattern bindings (tests/rename/should_fail/rnfail002).
404 group (Just (FunMonoBind f inf1 mtchs ignore_srcloc))
405 (RdrValBinding (FunMonoBind f' _
406 [mtch@(Match _ (_:_) _ _)] loc)
408 | f == f' = group (Just (FunMonoBind f inf1 (mtch:mtchs) loc)) binds
410 group (Just so_far) binds
411 = RdrValBinding so_far `RdrAndBindings` group Nothing binds
412 group Nothing (bind:binds)
414 RdrValBinding b@(FunMonoBind _ _ _ _) -> group (Just b) binds
415 other -> bind `RdrAndBindings` group Nothing binds
417 -----------------------------------------------------------------------------
420 unitCon_RDR, unitTyCon_RDR, nilCon_RDR, listTyCon_RDR :: RdrName
421 tupleCon_RDR, tupleTyCon_RDR :: Int -> RdrName
422 ubxTupleCon_RDR, ubxTupleTyCon_RDR :: Int -> RdrName
425 | opt_NoImplicitPrelude = mkSrcUnqual dataName unitName
426 | otherwise = mkPreludeQual dataName pRELUDE_Name unitName
429 | opt_NoImplicitPrelude = mkSrcUnqual tcName unitName
430 | otherwise = mkPreludeQual tcName pRELUDE_Name unitName
433 | opt_NoImplicitPrelude = mkSrcUnqual dataName listName
434 | otherwise = mkPreludeQual dataName pRELUDE_Name listName
437 | opt_NoImplicitPrelude = mkSrcUnqual tcName listName
438 | otherwise = mkPreludeQual tcName pRELUDE_Name listName
441 | opt_NoImplicitPrelude = mkSrcUnqual tcName funName
442 | otherwise = mkPreludeQual tcName pRELUDE_Name funName
445 | opt_NoImplicitPrelude = mkSrcUnqual dataName (snd (mkTupNameStr Boxed arity))
446 | otherwise = mkPreludeQual dataName pRELUDE_Name
447 (snd (mkTupNameStr Boxed arity))
450 | opt_NoImplicitPrelude = mkSrcUnqual tcName (snd (mkTupNameStr Boxed arity))
451 | otherwise = mkPreludeQual tcName pRELUDE_Name
452 (snd (mkTupNameStr Boxed arity))
455 ubxTupleCon_RDR arity
456 | opt_NoImplicitPrelude = mkSrcUnqual dataName (snd (mkTupNameStr Unboxed arity))
457 | otherwise = mkPreludeQual dataName pRELUDE_Name
458 (snd (mkTupNameStr Unboxed arity))
460 ubxTupleTyCon_RDR arity
461 | opt_NoImplicitPrelude = mkSrcUnqual tcName (snd (mkTupNameStr Unboxed arity))
462 | otherwise = mkPreludeQual tcName pRELUDE_Name
463 (snd (mkTupNameStr Unboxed arity))
465 unitName = SLIT("()")
466 funName = SLIT("(->)")
467 listName = SLIT("[]")
470 hidingName = SLIT("hiding")
471 qualifiedName = SLIT("qualified")
472 forallName = SLIT("forall")
473 exportName = SLIT("export")
474 labelName = SLIT("label")
475 dynamicName = SLIT("dynamic")
476 unsafeName = SLIT("unsafe")
477 stdcallName = SLIT("stdcall")
478 ccallName = SLIT("ccall")
480 as_var_RDR = mkSrcUnqual varName asName
481 hiding_var_RDR = mkSrcUnqual varName hidingName
482 qualified_var_RDR = mkSrcUnqual varName qualifiedName
483 forall_var_RDR = mkSrcUnqual varName forallName
484 export_var_RDR = mkSrcUnqual varName exportName
485 label_var_RDR = mkSrcUnqual varName labelName
486 dynamic_var_RDR = mkSrcUnqual varName dynamicName
487 unsafe_var_RDR = mkSrcUnqual varName unsafeName
488 stdcall_var_RDR = mkSrcUnqual varName stdcallName
489 ccall_var_RDR = mkSrcUnqual varName ccallName
491 as_tyvar_RDR = mkSrcUnqual tvName asName
492 hiding_tyvar_RDR = mkSrcUnqual tvName hidingName
493 qualified_tyvar_RDR = mkSrcUnqual tvName qualifiedName
494 export_tyvar_RDR = mkSrcUnqual tvName exportName
495 label_tyvar_RDR = mkSrcUnqual tvName labelName
496 dynamic_tyvar_RDR = mkSrcUnqual tvName dynamicName
497 unsafe_tyvar_RDR = mkSrcUnqual tvName unsafeName
498 stdcall_tyvar_RDR = mkSrcUnqual tvName stdcallName
499 ccall_tyvar_RDR = mkSrcUnqual tvName ccallName
501 minus_RDR = mkSrcUnqual varName SLIT("-")
502 pling_RDR = mkSrcUnqual varName SLIT("!")
503 dot_RDR = mkSrcUnqual varName SLIT(".")
505 plus_RDR = mkSrcUnqual varName SLIT("+")