2 % (c) The GRASP/AQUA Project, Glasgow University, 1999
4 \section[ParseUtil]{Parser Utilities}
8 parseError -- String -> Pa
9 , mkVanillaCon, mkRecCon,
11 , mkRecConstrOrUpdate -- HsExp -> [HsFieldUpdate] -> P HsExp
15 , mkImport -- CallConv -> Safety
16 -- -> (FAST_STRING, RdrName, RdrNameHsType)
19 , mkExport -- CallConv
20 -- -> (FAST_STRING, RdrName, RdrNameHsType)
23 , mkExtName -- RdrName -> CLabelString
25 , checkPrec -- String -> P String
26 , checkContext -- HsType -> P HsContext
27 , checkPred -- HsType -> P HsPred
28 , checkTyVars -- [HsTyVar] -> P [HsType]
29 , checkInstType -- HsType -> P HsType
30 , checkPattern -- HsExp -> P HsPat
31 , checkPatterns -- SrcLoc -> [HsExp] -> P [HsPat]
32 , checkDo -- [Stmt] -> P [Stmt]
33 , checkValDef -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
34 , checkValSig -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
37 #include "HsVersions.h"
39 import List ( isSuffixOf )
42 import HsSyn -- Lots of it
43 import ForeignCall ( CCallConv, Safety, CCallTarget(..), CExportSpec(..),
46 import RdrHsSyn ( RdrBinding(..),
47 RdrNameHsType, RdrNameBangType, RdrNameContext,
48 RdrNameHsTyVar, RdrNamePat, RdrNameHsExpr,
49 RdrNameGRHSs, RdrNameHsRecordBinds,
50 RdrNameMonoBinds, RdrNameConDetails, RdrNameHsDecl,
54 import PrelNames ( unitTyCon_RDR )
55 import OccName ( dataName, varName, tcClsName,
56 occNameSpace, setOccNameSpace, occNameUserString )
57 import CStrings ( CLabelString )
58 import FastString ( nullFastString )
61 -----------------------------------------------------------------------------
64 parseError :: String -> P a
66 getSrcLocP `thenP` \ loc ->
67 failMsgP (hcat [ppr loc, text ": ", text s])
70 -----------------------------------------------------------------------------
73 -- When parsing data declarations, we sometimes inadvertently parse
74 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
75 -- This function splits up the type application, adds any pending
76 -- arguments, and converts the type constructor back into a data constructor.
78 mkVanillaCon :: RdrNameHsType -> [RdrNameBangType] -> P (RdrName, RdrNameConDetails)
83 split (HsAppTy t u) ts = split t (unbangedType u : ts)
84 split (HsTyVar tc) ts = tyConToDataCon tc `thenP` \ data_con ->
85 returnP (data_con, VanillaCon ts)
86 split _ _ = parseError "Illegal data/newtype declaration"
88 mkRecCon :: RdrName -> [([RdrName],RdrNameBangType)] -> P (RdrName, RdrNameConDetails)
90 = tyConToDataCon con `thenP` \ data_con ->
91 returnP (data_con, RecCon fields)
93 tyConToDataCon :: RdrName -> P RdrName
95 | occNameSpace tc_occ == tcClsName
96 = returnP (setRdrNameOcc tc (setOccNameSpace tc_occ dataName))
98 = parseError (showSDoc (text "Not a constructor:" <+> quotes (ppr tc)))
100 tc_occ = rdrNameOcc tc
103 ----------------------------------------------------------------------------
104 -- Various Syntactic Checks
106 checkInstType :: RdrNameHsType -> P RdrNameHsType
109 HsForAllTy tvs ctxt ty ->
110 checkDictTy ty [] `thenP` \ dict_ty ->
111 returnP (HsForAllTy tvs ctxt dict_ty)
113 ty -> checkDictTy ty [] `thenP` \ dict_ty->
114 returnP (HsForAllTy Nothing [] dict_ty)
116 checkTyVars :: [RdrNameHsTyVar] -> P [RdrNameHsType]
117 checkTyVars tvs = mapP chk tvs
119 chk (UserTyVar tv) = returnP (HsTyVar tv)
120 chk other = parseError "Illegal kinded type variable"
122 checkContext :: RdrNameHsType -> P RdrNameContext
123 checkContext (HsTupleTy _ ts) -- (Eq a, Ord b) shows up as a tuple type
126 checkContext (HsTyVar t) -- Empty context shows up as a unit type ()
127 | t == unitTyCon_RDR = returnP []
130 = checkPred t `thenP` \p ->
133 checkPred :: RdrNameHsType -> P (HsPred RdrName)
134 checkPred (HsPredTy (HsIParam n ty)) = returnP (HsIParam n ty)
135 checkPred (HsAppTy l r)
138 go (HsTyVar t) args | not (isRdrTyVar t)
139 = returnP (HsClassP t args)
140 go (HsAppTy l r) args = go l (r:args)
141 go _ _ = 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 "Malformed context in instance header"
150 ---------------------------------------------------------------------------
151 -- Checking statements in a do-expression
152 -- We parse do { e1 ; e2 ; }
153 -- as [ExprStmt e1, ExprStmt e2]
154 -- checkDo (a) checks that the last thing is an ExprStmt
155 -- (b) transforms it to a ResultStmt
157 checkDo [] = parseError "Empty 'do' construct"
158 checkDo [ExprStmt e _ l] = returnP [ResultStmt e l]
159 checkDo [s] = parseError "The last statement in a 'do' construct must be an expression"
160 checkDo (s:ss) = checkDo ss `thenP` \ ss' ->
163 ---------------------------------------------------------------------------
164 -- Checking Patterns.
166 -- We parse patterns as expressions and check for valid patterns below,
167 -- converting the expression into a pattern at the same time.
169 checkPattern :: SrcLoc -> RdrNameHsExpr -> P RdrNamePat
170 checkPattern loc e = setSrcLocP loc (checkPat e [])
172 checkPatterns :: SrcLoc -> [RdrNameHsExpr] -> P [RdrNamePat]
173 checkPatterns loc es = mapP (checkPattern loc) es
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 ->
180 checkPat e [] = case e of
181 EWildPat -> returnP WildPatIn
182 HsVar x -> returnP (VarPatIn x)
183 HsLit l -> returnP (LitPatIn l)
184 HsOverLit l -> returnP (NPatIn 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) _ (HsOverLit lit@(HsIntegral _ _))
199 -> returnP (mkNPlusKPat n lit)
201 plus_RDR = mkUnqual varName SLIT("+") -- Hack
203 OpApp l op fix r -> checkPat l [] `thenP` \l ->
204 checkPat r [] `thenP` \r ->
206 HsVar c -> returnP (ConOpPatIn l c fix r)
209 HsPar e -> checkPat e [] `thenP` (returnP . ParPatIn)
210 ExplicitList _ es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
211 returnP (ListPatIn ps)
212 ExplicitPArr _ es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
213 returnP (PArrPatIn ps)
215 ExplicitTuple es b -> mapP (\e -> checkPat e []) es `thenP` \ps ->
216 returnP (TuplePatIn ps b)
218 RecordCon c fs -> mapP checkPatField fs `thenP` \fs ->
219 returnP (RecPatIn c fs)
221 HsType ty -> returnP (TypePatIn ty)
224 checkPat _ _ = patFail
226 checkPatField :: (RdrName, RdrNameHsExpr, Bool)
227 -> P (RdrName, RdrNamePat, Bool)
228 checkPatField (n,e,b) =
229 checkPat e [] `thenP` \p ->
232 patFail = parseError "Parse error in pattern"
235 ---------------------------------------------------------------------------
236 -- Check Equation Syntax
240 -> Maybe RdrNameHsType
245 checkValDef lhs opt_sig grhss loc
246 = case isFunLhs lhs [] of
248 checkPatterns loc es `thenP` \ps ->
249 returnP (RdrValBinding (FunMonoBind f inf [Match ps opt_sig grhss] loc))
252 checkPattern loc lhs `thenP` \lhs ->
253 returnP (RdrValBinding (PatMonoBind lhs grhss loc))
260 checkValSig (HsVar v) ty loc = returnP (RdrSig (Sig v ty loc))
261 checkValSig other ty loc = parseError "Type signature given for an expression"
264 -- A variable binding is parsed as an RdrNameFunMonoBind.
265 -- See comments with HsBinds.MonoBinds
267 isFunLhs :: RdrNameHsExpr -> [RdrNameHsExpr] -> Maybe (RdrName, Bool, [RdrNameHsExpr])
268 isFunLhs (OpApp l (HsVar op) fix r) es | not (isRdrDataCon op)
269 = Just (op, True, (l:r:es))
271 = case isFunLhs l es of
272 Just (op', True, j : k : es') ->
273 Just (op', True, j : OpApp k (HsVar op) fix r : es')
275 isFunLhs (HsVar f) es | not (isRdrDataCon f)
277 isFunLhs (HsApp f e) es = isFunLhs f (e:es)
278 isFunLhs (HsPar e) es@(_:_) = isFunLhs e es
279 isFunLhs _ _ = Nothing
281 ---------------------------------------------------------------------------
282 -- Miscellaneous utilities
284 checkPrec :: Integer -> P ()
285 checkPrec i | 0 <= i && i <= 9 = returnP ()
286 | otherwise = parseError "Precedence out of range"
290 -> RdrNameHsRecordBinds
293 mkRecConstrOrUpdate (HsVar c) fs | isRdrDataCon c
294 = returnP (RecordCon c fs)
295 mkRecConstrOrUpdate exp fs@(_:_)
296 = returnP (RecordUpd exp fs)
297 mkRecConstrOrUpdate _ _
298 = parseError "Empty record update"
300 -----------------------------------------------------------------------------
301 -- utilities for foreign declarations
303 -- supported calling conventions
305 data CallConv = CCall CCallConv -- ccall or stdcall
308 -- construct a foreign import declaration
312 -> (FAST_STRING, RdrName, RdrNameHsType)
315 mkImport (CCall cconv) safety (entity, v, ty) loc =
316 parseCImport entity cconv safety v `thenP` \importSpec ->
317 returnP $ ForD (ForeignImport v ty importSpec False loc)
318 mkImport (DNCall ) _ (entity, v, ty) loc =
319 returnP $ ForD (ForeignImport v ty (DNImport (DNCallSpec entity)) False loc)
321 -- parse the entity string of a foreign import declaration for the `ccall' or
322 -- `stdcall' calling convention'
324 parseCImport :: FAST_STRING
329 parseCImport entity cconv safety v
330 -- FIXME: we should allow white space around `dynamic' and `wrapper' -=chak
331 | entity == SLIT ("dynamic") =
332 returnP $ CImport cconv safety _NIL_ _NIL_ (CFunction DynamicTarget)
333 | entity == SLIT ("wrapper") =
334 returnP $ CImport cconv safety _NIL_ _NIL_ CWrapper
335 | otherwise = parse0 (_UNPK_ entity)
337 -- using the static keyword?
338 parse0 (' ': rest) = parse0 rest
339 parse0 ('s':'t':'a':'t':'i':'c':rest) = parse1 rest
340 parse0 rest = parse1 rest
341 -- check for header file name
342 parse1 "" = parse4 "" _NIL_ False _NIL_
343 parse1 (' ':rest) = parse1 rest
344 parse1 str@('&':_ ) = parse2 str _NIL_
345 parse1 str@('[':_ ) = parse3 str _NIL_ False
347 | ".h" `isSuffixOf` first = parse2 rest (_PK_ first)
348 | otherwise = parse4 str _NIL_ False _NIL_
350 (first, rest) = break (\c -> c == ' ' || c == '&' || c == '[') str
351 -- check for address operator (indicating a label import)
352 parse2 "" header = parse4 "" header False _NIL_
353 parse2 (' ':rest) header = parse2 rest header
354 parse2 ('&':rest) header = parse3 rest header True
355 parse2 str@('[':_ ) header = parse3 str header False
356 parse2 str header = parse4 str header False _NIL_
357 -- check for library object name
358 parse3 (' ':rest) header isLbl = parse3 rest header isLbl
359 parse3 ('[':rest) header isLbl =
360 case break (== ']') rest of
361 (lib, ']':rest) -> parse4 rest header isLbl (_PK_ lib)
362 _ -> parseError "Missing ']' in entity"
363 parse3 str header isLbl = parse4 str header isLbl _NIL_
364 -- check for name of C function
365 parse4 "" header isLbl lib = build (mkExtName v) header isLbl lib
366 parse4 (' ':rest) header isLbl lib = parse4 rest header isLbl lib
367 parse4 str header isLbl lib
368 | all (== ' ') rest = build (_PK_ first) header isLbl lib
369 | otherwise = parseError "Malformed entity string"
371 (first, rest) = break (== ' ') str
373 build cid header False lib = returnP $
374 CImport cconv safety header lib (CFunction (StaticTarget cid))
375 build cid header True lib = returnP $
376 CImport cconv safety header lib (CLabel cid )
378 -- construct a foreign export declaration
381 -> (FAST_STRING, RdrName, RdrNameHsType)
384 mkExport (CCall cconv) (entity, v, ty) loc = returnP $
385 ForD (ForeignExport v ty (CExport (CExportStatic entity' cconv)) False loc)
387 entity' | nullFastString entity = mkExtName v
389 mkExport DNCall (entity, v, ty) loc =
390 parseError "Foreign export is not yet supported for .NET"
392 -- Supplying the ext_name in a foreign decl is optional; if it
393 -- isn't there, the Haskell name is assumed. Note that no transformation
394 -- of the Haskell name is then performed, so if you foreign export (++),
395 -- it's external name will be "++". Too bad; it's important because we don't
396 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
397 -- (This is why we use occNameUserString.)
399 mkExtName :: RdrName -> CLabelString
400 mkExtName rdrNm = _PK_ (occNameUserString (rdrNameOcc rdrNm))
402 -----------------------------------------------------------------------------
403 -- group function bindings into equation groups
405 -- we assume the bindings are coming in reverse order, so we take the srcloc
406 -- from the *last* binding in the group as the srcloc for the whole group.
408 groupBindings :: [RdrBinding] -> RdrBinding
409 groupBindings binds = group Nothing binds
410 where group :: Maybe RdrNameMonoBinds -> [RdrBinding] -> RdrBinding
411 group (Just bind) [] = RdrValBinding bind
412 group Nothing [] = RdrNullBind
414 -- don't group together FunMonoBinds if they have
415 -- no arguments. This is necessary now that variable bindings
416 -- with no arguments are now treated as FunMonoBinds rather
417 -- than pattern bindings (tests/rename/should_fail/rnfail002).
418 group (Just (FunMonoBind f inf1 mtchs ignore_srcloc))
419 (RdrValBinding (FunMonoBind f' _
420 [mtch@(Match (_:_) _ _)] loc)
422 | f == f' = group (Just (FunMonoBind f inf1 (mtch:mtchs) loc)) binds
424 group (Just so_far) binds
425 = RdrValBinding so_far `RdrAndBindings` group Nothing binds
426 group Nothing (bind:binds)
428 RdrValBinding b@(FunMonoBind _ _ _ _) -> group (Just b) binds
429 other -> bind `RdrAndBindings` group Nothing binds