2 % (c) The GRASP/AQUA Project, Glasgow University, 1999
4 \section[ParseUtil]{Parser Utilities}
8 parseError -- String -> Pa
9 , srcParseErr -- StringBuffer -> SrcLoc -> Message
11 , splitForConApp -- RdrNameHsType -> [RdrNameBangType]
12 -- -> P (RdrName, [RdrNameBangType])
14 , mkRecConstrOrUpdate -- HsExp -> [HsFieldUpdate] -> P HsExp
17 , mkExtName -- Maybe ExtName -> RdrName -> ExtName
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
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
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
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
45 , minus_RDR, pling_RDR, dot_RDR
49 #include "HsVersions.h"
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 )
63 import UniqFM ( UniqFM, listToUFM, lookupUFM )
66 -----------------------------------------------------------------------------
69 parseError :: String -> P a
71 getSrcLocP `thenP` \ loc ->
72 failMsgP (hcat [ppr loc, text ": ", text s])
74 srcParseErr :: StringBuffer -> SrcLoc -> Message
78 then ptext SLIT(": parse error (possibly incorrect indentation)")
79 else hcat [ptext SLIT(": parse error on input "),
80 char '`', text token, char '\'']
83 token = lexemeToString s
85 cbot = panic "CCall:result_ty"
87 -----------------------------------------------------------------------------
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.
95 splitForConApp :: RdrNameHsType -> [RdrNameBangType]
96 -> P (RdrName, [RdrNameBangType])
98 splitForConApp t ts = split t ts
100 split (MonoTyApp t u) ts = split t (Unbanged u : ts)
102 split (MonoTyVar t) ts = returnP (con, ts)
103 where t_occ = rdrNameOcc t
104 con = setRdrNameOcc t (setOccNameSpace t_occ dataName)
106 split _ _ = parseError "Illegal data/newtype declaration"
108 ----------------------------------------------------------------------------
109 -- Various Syntactic Checks
111 callConvFM :: UniqFM CallConv
112 callConvFM = listToUFM $
113 map (\ (x,y) -> (_PK_ x,y))
114 [ ("stdcall", stdCallConv),
116 -- ("pascal", pascalCallConv),
117 -- ("fastcall", fastCallConv)
120 checkCallConv :: FAST_STRING -> P CallConv
122 case lookupUFM callConvFM s of
123 Nothing -> parseError ("unknown calling convention: `"
124 ++ unpackFS s ++ "'")
125 Just conv -> returnP conv
127 checkInstType :: RdrNameHsType -> P RdrNameHsType
130 HsForAllTy tvs ctxt ty ->
131 checkAssertion ty [] `thenP` \(c,ts)->
132 returnP (HsForAllTy tvs ctxt (MonoDictTy c ts))
134 ty -> checkAssertion ty [] `thenP` \(c,ts)->
135 returnP (HsForAllTy Nothing [] (MonoDictTy c ts))
137 checkContext :: RdrNameHsType -> P RdrNameContext
138 checkContext (MonoTupleTy ts True)
139 = mapP (\t -> checkAssertion t []) ts `thenP` \cs ->
141 checkContext (MonoTyVar t) -- empty contexts are allowed
142 | t == unitTyCon_RDR = returnP []
144 = checkAssertion t [] `thenP` \c ->
147 checkAssertion :: RdrNameHsType -> [RdrNameHsType]
148 -> P (ClassAssertion RdrName)
149 checkAssertion (MonoTyVar t) args@(_:_) | not (isRdrTyVar t)
151 checkAssertion (MonoTyApp l r) args = checkAssertion l (r:args)
152 checkAssertion _ _ = parseError "Illegal class assertion"
154 checkDataHeader :: RdrNameHsType
155 -> P (RdrNameContext, RdrName, [RdrNameHsTyVar])
156 checkDataHeader (HsForAllTy Nothing cs t) =
157 checkSimple t [] `thenP` \(c,ts) ->
158 returnP (cs,c,map UserTyVar ts)
160 checkSimple t [] `thenP` \(c,ts) ->
161 returnP ([],c,map UserTyVar ts)
163 checkSimple :: RdrNameHsType -> [RdrName] -> P ((RdrName,[RdrName]))
164 checkSimple (MonoTyApp l (MonoTyVar a)) xs | isRdrTyVar a
165 = checkSimple l (a:xs)
166 checkSimple (MonoTyVar t) xs | not (isRdrTyVar t) = returnP (t,xs)
167 checkSimple t _ = trace (showSDoc (ppr t)) $ parseError "Illegal data/newtype declaration"
169 ---------------------------------------------------------------------------
170 -- Checking Patterns.
172 -- We parse patterns as expressions and check for valid patterns below,
173 -- nverting the expression into a pattern at the same time.
175 checkPattern :: RdrNameHsExpr -> P RdrNamePat
176 checkPattern e = checkPat e []
178 checkPatterns :: [RdrNameHsExpr] -> P [RdrNamePat]
179 checkPatterns es = mapP checkPattern es
181 checkPat :: RdrNameHsExpr -> [RdrNamePat] -> P RdrNamePat
182 checkPat (HsVar c) args | isRdrDataCon c = returnP (ConPatIn c args)
183 checkPat (HsApp f x) args =
184 checkPat x [] `thenP` \x ->
186 checkPat e [] = case e of
187 EWildPat -> returnP WildPatIn
188 HsVar x -> returnP (VarPatIn x)
189 HsLit l -> returnP (LitPatIn l)
190 ELazyPat e -> checkPat e [] `thenP` (returnP . LazyPatIn)
191 EAsPat n e -> checkPat e [] `thenP` (returnP . AsPatIn n)
192 ExprWithTySig e t -> checkPat e [] `thenP` \e ->
193 -- pattern signatures are parsed as sigtypes,
194 -- but they aren't explicit forall points. Hence
195 -- we have to remove the implicit forall here.
197 HsForAllTy Nothing [] ty -> ty
200 returnP (SigPatIn e t')
202 OpApp (HsVar n) (HsVar plus) _ (HsLit k@(HsInt _)) | plus == plus_RDR
203 -> returnP (NPlusKPatIn n k)
205 OpApp l op fix r -> checkPat l [] `thenP` \l ->
206 checkPat r [] `thenP` \r ->
208 HsVar c -> returnP (ConOpPatIn l c fix r)
211 NegApp l r -> checkPat l [] `thenP` (returnP . NegPatIn)
212 HsPar e -> checkPat e [] `thenP` (returnP . ParPatIn)
213 ExplicitList es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
214 returnP (ListPatIn ps)
215 ExplicitTuple es b -> mapP (\e -> checkPat e []) es `thenP` \ps ->
216 returnP (TuplePatIn ps b)
217 RecordCon c fs -> mapP checkPatField fs `thenP` \fs ->
218 returnP (RecPatIn c fs)
221 checkPat _ _ = patFail
223 checkPatField :: (RdrName, RdrNameHsExpr, Bool)
224 -> P (RdrName, RdrNamePat, Bool)
225 checkPatField (n,e,b) =
226 checkPat e [] `thenP` \p ->
229 patFail = parseError "Parse error in pattern"
231 ---------------------------------------------------------------------------
232 -- Check Expression Syntax
235 We can get away without checkExpr if the renamer generates errors for
236 pattern syntax used in expressions (wildcards, as patterns and lazy
239 checkExpr :: RdrNameHsExpr -> P RdrNameHsExpr
240 checkExpr e = case e of
243 HsLam match -> checkMatch match `thenP` (returnP.HsLam)
244 HsApp e1 e2 -> check2Exprs e1 e2 HsApp
245 OpApp e1 e2 fix e3 -> checkExpr e1 `thenP` \e1 ->
246 checkExpr e2 `thenP` \e2 ->
247 checkExpr e3 `thenP` \e3 ->
248 returnP (OpApp e1 e2 fix e3)
249 NegApp e neg -> checkExpr e `thenP` \e ->
250 returnP (NegApp e neg)
251 HsPar e -> check1Expr e HsPar
252 SectionL e1 e2 -> check2Exprs e1 e2 SectionL
253 SectionR e1 e2 -> check2Exprs e1 e2 SectionR
254 HsCase e alts -> mapP checkMatch alts `thenP` \alts ->
255 checkExpr e `thenP` \e ->
256 returnP (HsCase e alts)
257 HsIf e1 e2 e3 -> check3Exprs e1 e2 e3 HsIf
259 HsLet bs e -> check1Expr e (HsLet bs)
260 HsDo stmts -> mapP checkStmt stmts `thenP` (returnP . HsDo)
261 HsTuple es -> checkManyExprs es HsTuple
262 HsList es -> checkManyExprs es HsList
263 HsRecConstr c fields -> mapP checkField fields `thenP` \fields ->
264 returnP (HsRecConstr c fields)
265 HsRecUpdate e fields -> mapP checkField fields `thenP` \fields ->
266 checkExpr e `thenP` \e ->
267 returnP (HsRecUpdate e fields)
268 HsEnumFrom e -> check1Expr e HsEnumFrom
269 HsEnumFromTo e1 e2 -> check2Exprs e1 e2 HsEnumFromTo
270 HsEnumFromThen e1 e2 -> check2Exprs e1 e2 HsEnumFromThen
271 HsEnumFromThenTo e1 e2 e3 -> check3Exprs e1 e2 e3 HsEnumFromThenTo
272 HsListComp e stmts -> mapP checkStmt stmts `thenP` \stmts ->
273 checkExpr e `thenP` \e ->
274 returnP (HsListComp e stmts)
275 RdrNameHsExprTypeSig loc e ty -> checkExpr e `thenP` \e ->
276 returnP (RdrNameHsExprTypeSig loc e ty)
277 _ -> parseError "parse error in expression"
279 -- type signature for polymorphic recursion!!
280 check1Expr :: RdrNameHsExpr -> (RdrNameHsExpr -> a) -> P a
281 check1Expr e f = checkExpr e `thenP` (returnP . f)
283 check2Exprs :: RdrNameHsExpr -> RdrNameHsExpr -> (RdrNameHsExpr -> RdrNameHsExpr -> a) -> P a
284 check2Exprs e1 e2 f =
285 checkExpr e1 `thenP` \e1 ->
286 checkExpr e2 `thenP` \e2 ->
289 check3Exprs :: RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr -> (RdrNameHsExpr -> RdrNameHsExpr -> RdrNameHsExpr -> a) -> P a
290 check3Exprs e1 e2 e3 f =
291 checkExpr e1 `thenP` \e1 ->
292 checkExpr e2 `thenP` \e2 ->
293 checkExpr e3 `thenP` \e3 ->
296 checkManyExprs es f =
297 mapP checkExpr es `thenP` \es ->
300 checkAlt (HsAlt loc p galts bs)
301 = checkGAlts galts `thenP` \galts -> returnP (HsAlt loc p galts bs)
303 checkGAlts (HsUnGuardedAlt e) = check1Expr e HsUnGuardedAlt
304 checkGAlts (HsGuardedAlts galts)
305 = mapP checkGAlt galts `thenP` (returnP . HsGuardedAlts)
307 checkGAlt (HsGuardedAlt loc e1 e2) = check2Exprs e1 e2 (HsGuardedAlt loc)
309 checkStmt (HsGenerator p e) = check1Expr e (HsGenerator p)
310 checkStmt (HsQualifier e) = check1Expr e HsQualifier
311 checkStmt s@(HsLetStmt bs) = returnP s
313 checkField (HsFieldUpdate n e) = check1Expr e (HsFieldUpdate n)
314 checkField e = returnP e
316 ---------------------------------------------------------------------------
317 -- Check Equation Syntax
321 -> Maybe RdrNameHsType
324 -> P RdrNameMonoBinds
326 checkValDef lhs opt_sig grhss loc
327 = case isFunLhs lhs [] of
329 checkPatterns es `thenP` \ps ->
330 returnP (FunMonoBind f inf [Match [] ps opt_sig grhss] loc)
333 checkPattern lhs `thenP` \lhs ->
334 returnP (PatMonoBind lhs grhss loc)
336 -- A variable binding is parsed as an RdrNamePatBind.
338 isFunLhs (OpApp l (HsVar op) fix r) [] | not (isRdrDataCon op)
339 = Just (op, True, [l,r])
340 isFunLhs (HsVar f) es@(_:_) | not (isRdrDataCon f)
342 isFunLhs (HsApp f e) es = isFunLhs f (e:es)
343 isFunLhs (HsPar e) es = isFunLhs e es
344 isFunLhs _ _ = Nothing
346 ---------------------------------------------------------------------------
347 -- Miscellaneous utilities
349 checkPrec :: Integer -> P ()
350 checkPrec i | 0 <= i && i <= 9 = returnP ()
351 | otherwise = parseError "precedence out of range"
355 -> RdrNameHsRecordBinds
358 mkRecConstrOrUpdate (HsVar c) fs | isRdrDataCon c
359 = returnP (RecordCon c fs)
360 mkRecConstrOrUpdate exp fs@(_:_)
361 = returnP (RecordUpd exp fs)
362 mkRecConstrOrUpdate _ _
363 = parseError "Empty record update"
365 -- supplying the ext_name in a foreign decl is optional ; if it
366 -- isn't there, the Haskell name is assumed. Note that no transformation
367 -- of the Haskell name is then performed, so if you foreign export (++),
368 -- it's external name will be "++". Too bad.
369 mkExtName :: Maybe ExtName -> RdrName -> ExtName
370 mkExtName Nothing rdrNm = ExtName (occNameFS (rdrNameOcc rdrNm)) Nothing
371 mkExtName (Just x) _ = x
373 -----------------------------------------------------------------------------
374 -- group function bindings into equation groups
376 -- we assume the bindings are coming in reverse order, so we take the srcloc
377 -- from the *last* binding in the group as the srcloc for the whole group.
379 groupBindings :: [RdrBinding] -> RdrBinding
380 groupBindings binds = group Nothing binds
381 where group :: Maybe RdrNameMonoBinds -> [RdrBinding] -> RdrBinding
382 group (Just bind) [] = RdrValBinding bind
383 group Nothing [] = RdrNullBind
384 group (Just (FunMonoBind f inf1 mtchs ignore_srcloc))
385 (RdrValBinding (FunMonoBind f' _ [mtch] loc) : binds)
386 | f == f' = group (Just (FunMonoBind f inf1 (mtch:mtchs) loc)) binds
388 group (Just so_far) binds
389 = RdrValBinding so_far `RdrAndBindings` group Nothing binds
390 group Nothing (bind:binds)
392 RdrValBinding b@(FunMonoBind _ _ _ _) -> group (Just b) binds
393 other -> bind `RdrAndBindings` group Nothing binds
395 -----------------------------------------------------------------------------
398 unitCon_RDR, unitTyCon_RDR, nilCon_RDR, listTyCon_RDR :: RdrName
399 tupleCon_RDR, tupleTyCon_RDR :: Int -> RdrName
400 ubxTupleCon_RDR, ubxTupleTyCon_RDR :: Int -> RdrName
403 | opt_NoImplicitPrelude = mkSrcUnqual dataName unitName
404 | otherwise = mkPreludeQual dataName pRELUDE_Name unitName
407 | opt_NoImplicitPrelude = mkSrcUnqual tcName unitName
408 | otherwise = mkPreludeQual tcName pRELUDE_Name unitName
411 | opt_NoImplicitPrelude = mkSrcUnqual dataName listName
412 | otherwise = mkPreludeQual dataName pRELUDE_Name listName
415 | opt_NoImplicitPrelude = mkSrcUnqual tcName listName
416 | otherwise = mkPreludeQual tcName pRELUDE_Name listName
419 | opt_NoImplicitPrelude = mkSrcUnqual tcName funName
420 | otherwise = mkPreludeQual tcName pRELUDE_Name funName
423 | opt_NoImplicitPrelude = mkSrcUnqual dataName (snd (mkTupNameStr arity))
424 | otherwise = mkPreludeQual dataName pRELUDE_Name
425 (snd (mkTupNameStr arity))
428 | opt_NoImplicitPrelude = mkSrcUnqual tcName (snd (mkTupNameStr arity))
429 | otherwise = mkPreludeQual tcName pRELUDE_Name
430 (snd (mkTupNameStr arity))
433 ubxTupleCon_RDR arity
434 | opt_NoImplicitPrelude = mkSrcUnqual dataName (snd (mkUbxTupNameStr arity))
435 | otherwise = mkPreludeQual dataName pRELUDE_Name
436 (snd (mkUbxTupNameStr arity))
438 ubxTupleTyCon_RDR arity
439 | opt_NoImplicitPrelude = mkSrcUnqual tcName (snd (mkUbxTupNameStr arity))
440 | otherwise = mkPreludeQual tcName pRELUDE_Name
441 (snd (mkUbxTupNameStr arity))
443 unitName = SLIT("()")
444 funName = SLIT("(->)")
445 listName = SLIT("[]")
448 hidingName = SLIT("hiding")
449 qualifiedName = SLIT("qualified")
450 forallName = SLIT("forall")
451 exportName = SLIT("export")
452 labelName = SLIT("label")
453 dynamicName = SLIT("dynamic")
454 unsafeName = SLIT("unsafe")
455 stdcallName = SLIT("stdcall")
456 ccallName = SLIT("ccall")
458 as_var_RDR = mkSrcUnqual varName asName
459 hiding_var_RDR = mkSrcUnqual varName hidingName
460 qualified_var_RDR = mkSrcUnqual varName qualifiedName
461 forall_var_RDR = mkSrcUnqual varName forallName
462 export_var_RDR = mkSrcUnqual varName exportName
463 label_var_RDR = mkSrcUnqual varName labelName
464 dynamic_var_RDR = mkSrcUnqual varName dynamicName
465 unsafe_var_RDR = mkSrcUnqual varName unsafeName
466 stdcall_var_RDR = mkSrcUnqual varName stdcallName
467 ccall_var_RDR = mkSrcUnqual varName ccallName
469 as_tyvar_RDR = mkSrcUnqual tvName asName
470 hiding_tyvar_RDR = mkSrcUnqual tvName hidingName
471 qualified_tyvar_RDR = mkSrcUnqual tvName qualifiedName
472 export_tyvar_RDR = mkSrcUnqual tvName exportName
473 label_tyvar_RDR = mkSrcUnqual tvName labelName
474 dynamic_tyvar_RDR = mkSrcUnqual tvName dynamicName
475 unsafe_tyvar_RDR = mkSrcUnqual tvName unsafeName
476 stdcall_tyvar_RDR = mkSrcUnqual tvName stdcallName
477 ccall_tyvar_RDR = mkSrcUnqual tvName ccallName
479 minus_RDR = mkSrcUnqual varName SLIT("-")
480 pling_RDR = mkSrcUnqual varName SLIT("!")
481 dot_RDR = mkSrcUnqual varName SLIT(".")
483 plus_RDR = mkSrcUnqual varName SLIT("+")