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 :: [RdrNameHsType] -> P [RdrNameHsTyVar]
117 checkTyVars tvs = mapP chk tvs
119 chk (HsKindSig (HsTyVar tv) k) = returnP (IfaceTyVar tv k)
120 chk (HsTyVar tv) = returnP (UserTyVar tv)
121 chk other = parseError "Type found where type variable expected"
123 checkContext :: RdrNameHsType -> P RdrNameContext
124 checkContext (HsTupleTy _ ts) -- (Eq a, Ord b) shows up as a tuple type
127 checkContext (HsTyVar t) -- Empty context shows up as a unit type ()
128 | t == unitTyCon_RDR = returnP []
131 = checkPred t `thenP` \p ->
134 checkPred :: RdrNameHsType -> P (HsPred RdrName)
135 -- Watch out.. in ...deriving( Show )... we use checkPred on
136 -- the list of partially applied predicates in the deriving,
137 -- so there can be zero args.
138 checkPred (HsPredTy (HsIParam n ty)) = returnP (HsIParam n ty)
142 go (HsTyVar t) args | not (isRdrTyVar t)
143 = returnP (HsClassP t args)
144 go (HsAppTy l r) args = go l (r:args)
145 go _ _ = parseError "Illegal class assertion"
147 checkDictTy :: RdrNameHsType -> [RdrNameHsType] -> P RdrNameHsType
148 checkDictTy (HsTyVar t) args@(_:_) | not (isRdrTyVar t)
149 = returnP (mkHsDictTy t args)
150 checkDictTy (HsAppTy l r) args = checkDictTy l (r:args)
151 checkDictTy _ _ = parseError "Malformed context in instance header"
154 ---------------------------------------------------------------------------
155 -- Checking statements in a do-expression
156 -- We parse do { e1 ; e2 ; }
157 -- as [ExprStmt e1, ExprStmt e2]
158 -- checkDo (a) checks that the last thing is an ExprStmt
159 -- (b) transforms it to a ResultStmt
161 checkDo [] = parseError "Empty 'do' construct"
162 checkDo [ExprStmt e _ l] = returnP [ResultStmt e l]
163 checkDo [s] = parseError "The last statement in a 'do' construct must be an expression"
164 checkDo (s:ss) = checkDo ss `thenP` \ ss' ->
167 ---------------------------------------------------------------------------
168 -- Checking Patterns.
170 -- We parse patterns as expressions and check for valid patterns below,
171 -- converting the expression into a pattern at the same time.
173 checkPattern :: SrcLoc -> RdrNameHsExpr -> P RdrNamePat
174 checkPattern loc e = setSrcLocP loc (checkPat e [])
176 checkPatterns :: SrcLoc -> [RdrNameHsExpr] -> P [RdrNamePat]
177 checkPatterns loc es = mapP (checkPattern loc) es
179 checkPat :: RdrNameHsExpr -> [RdrNamePat] -> P RdrNamePat
180 checkPat (HsVar c) args | isRdrDataCon c = returnP (ConPatIn c args)
181 checkPat (HsApp f x) args =
182 checkPat x [] `thenP` \x ->
184 checkPat e [] = case e of
185 EWildPat -> returnP WildPatIn
186 HsVar x -> returnP (VarPatIn x)
187 HsLit l -> returnP (LitPatIn l)
188 HsOverLit l -> returnP (NPatIn l)
189 ELazyPat e -> checkPat e [] `thenP` (returnP . LazyPatIn)
190 EAsPat n e -> checkPat e [] `thenP` (returnP . AsPatIn n)
191 ExprWithTySig e t -> checkPat e [] `thenP` \e ->
192 -- Pattern signatures are parsed as sigtypes,
193 -- but they aren't explicit forall points. Hence
194 -- we have to remove the implicit forall here.
196 HsForAllTy Nothing [] ty -> ty
199 returnP (SigPatIn e t')
201 OpApp (HsVar n) (HsVar plus) _ (HsOverLit lit@(HsIntegral _ _))
203 -> returnP (mkNPlusKPat n lit)
205 plus_RDR = mkUnqual varName SLIT("+") -- Hack
207 OpApp l op fix r -> checkPat l [] `thenP` \l ->
208 checkPat r [] `thenP` \r ->
210 HsVar c -> returnP (ConOpPatIn l c fix r)
213 HsPar e -> checkPat e [] `thenP` (returnP . ParPatIn)
214 ExplicitList _ es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
215 returnP (ListPatIn ps)
216 ExplicitPArr _ es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
217 returnP (PArrPatIn ps)
219 ExplicitTuple es b -> mapP (\e -> checkPat e []) es `thenP` \ps ->
220 returnP (TuplePatIn ps b)
222 RecordCon c fs -> mapP checkPatField fs `thenP` \fs ->
223 returnP (RecPatIn c fs)
225 HsType ty -> returnP (TypePatIn ty)
228 checkPat _ _ = patFail
230 checkPatField :: (RdrName, RdrNameHsExpr, Bool)
231 -> P (RdrName, RdrNamePat, Bool)
232 checkPatField (n,e,b) =
233 checkPat e [] `thenP` \p ->
236 patFail = parseError "Parse error in pattern"
239 ---------------------------------------------------------------------------
240 -- Check Equation Syntax
244 -> Maybe RdrNameHsType
249 checkValDef lhs opt_sig grhss loc
250 = case isFunLhs lhs [] of
252 checkPatterns loc es `thenP` \ps ->
253 returnP (RdrValBinding (FunMonoBind f inf [Match ps opt_sig grhss] loc))
256 checkPattern loc lhs `thenP` \lhs ->
257 returnP (RdrValBinding (PatMonoBind lhs grhss loc))
264 checkValSig (HsVar v) ty loc = returnP (RdrSig (Sig v ty loc))
265 checkValSig other ty loc = parseError "Type signature given for an expression"
268 -- A variable binding is parsed as an RdrNameFunMonoBind.
269 -- See comments with HsBinds.MonoBinds
271 isFunLhs :: RdrNameHsExpr -> [RdrNameHsExpr] -> Maybe (RdrName, Bool, [RdrNameHsExpr])
272 isFunLhs (OpApp l (HsVar op) fix r) es | not (isRdrDataCon op)
273 = Just (op, True, (l:r:es))
275 = case isFunLhs l es of
276 Just (op', True, j : k : es') ->
277 Just (op', True, j : OpApp k (HsVar op) fix r : es')
279 isFunLhs (HsVar f) es | not (isRdrDataCon f)
281 isFunLhs (HsApp f e) es = isFunLhs f (e:es)
282 isFunLhs (HsPar e) es@(_:_) = isFunLhs e es
283 isFunLhs _ _ = Nothing
285 ---------------------------------------------------------------------------
286 -- Miscellaneous utilities
288 checkPrec :: Integer -> P ()
289 checkPrec i | 0 <= i && i <= 9 = returnP ()
290 | otherwise = parseError "Precedence out of range"
294 -> RdrNameHsRecordBinds
297 mkRecConstrOrUpdate (HsVar c) fs | isRdrDataCon c
298 = returnP (RecordCon c fs)
299 mkRecConstrOrUpdate exp fs@(_:_)
300 = returnP (RecordUpd exp fs)
301 mkRecConstrOrUpdate _ _
302 = parseError "Empty record update"
304 -----------------------------------------------------------------------------
305 -- utilities for foreign declarations
307 -- supported calling conventions
309 data CallConv = CCall CCallConv -- ccall or stdcall
312 -- construct a foreign import declaration
316 -> (FAST_STRING, RdrName, RdrNameHsType)
319 mkImport (CCall cconv) safety (entity, v, ty) loc =
320 parseCImport entity cconv safety v `thenP` \importSpec ->
321 returnP $ ForD (ForeignImport v ty importSpec False loc)
322 mkImport (DNCall ) _ (entity, v, ty) loc =
323 returnP $ ForD (ForeignImport v ty (DNImport (DNCallSpec entity)) False loc)
325 -- parse the entity string of a foreign import declaration for the `ccall' or
326 -- `stdcall' calling convention'
328 parseCImport :: FAST_STRING
333 parseCImport entity cconv safety v
334 -- FIXME: we should allow white space around `dynamic' and `wrapper' -=chak
335 | entity == SLIT ("dynamic") =
336 returnP $ CImport cconv safety _NIL_ _NIL_ (CFunction DynamicTarget)
337 | entity == SLIT ("wrapper") =
338 returnP $ CImport cconv safety _NIL_ _NIL_ CWrapper
339 | otherwise = parse0 (_UNPK_ entity)
341 -- using the static keyword?
342 parse0 (' ': rest) = parse0 rest
343 parse0 ('s':'t':'a':'t':'i':'c':rest) = parse1 rest
344 parse0 rest = parse1 rest
345 -- check for header file name
346 parse1 "" = parse4 "" _NIL_ False _NIL_
347 parse1 (' ':rest) = parse1 rest
348 parse1 str@('&':_ ) = parse2 str _NIL_
349 parse1 str@('[':_ ) = parse3 str _NIL_ False
351 | ".h" `isSuffixOf` first = parse2 rest (_PK_ first)
352 | otherwise = parse4 str _NIL_ False _NIL_
354 (first, rest) = break (\c -> c == ' ' || c == '&' || c == '[') str
355 -- check for address operator (indicating a label import)
356 parse2 "" header = parse4 "" header False _NIL_
357 parse2 (' ':rest) header = parse2 rest header
358 parse2 ('&':rest) header = parse3 rest header True
359 parse2 str@('[':_ ) header = parse3 str header False
360 parse2 str header = parse4 str header False _NIL_
361 -- check for library object name
362 parse3 (' ':rest) header isLbl = parse3 rest header isLbl
363 parse3 ('[':rest) header isLbl =
364 case break (== ']') rest of
365 (lib, ']':rest) -> parse4 rest header isLbl (_PK_ lib)
366 _ -> parseError "Missing ']' in entity"
367 parse3 str header isLbl = parse4 str header isLbl _NIL_
368 -- check for name of C function
369 parse4 "" header isLbl lib = build (mkExtName v) header isLbl lib
370 parse4 (' ':rest) header isLbl lib = parse4 rest header isLbl lib
371 parse4 str header isLbl lib
372 | all (== ' ') rest = build (_PK_ first) header isLbl lib
373 | otherwise = parseError "Malformed entity string"
375 (first, rest) = break (== ' ') str
377 build cid header False lib = returnP $
378 CImport cconv safety header lib (CFunction (StaticTarget cid))
379 build cid header True lib = returnP $
380 CImport cconv safety header lib (CLabel cid )
382 -- construct a foreign export declaration
385 -> (FAST_STRING, RdrName, RdrNameHsType)
388 mkExport (CCall cconv) (entity, v, ty) loc = returnP $
389 ForD (ForeignExport v ty (CExport (CExportStatic entity' cconv)) False loc)
391 entity' | nullFastString entity = mkExtName v
393 mkExport DNCall (entity, v, ty) loc =
394 parseError "Foreign export is not yet supported for .NET"
396 -- Supplying the ext_name in a foreign decl is optional; if it
397 -- isn't there, the Haskell name is assumed. Note that no transformation
398 -- of the Haskell name is then performed, so if you foreign export (++),
399 -- it's external name will be "++". Too bad; it's important because we don't
400 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
401 -- (This is why we use occNameUserString.)
403 mkExtName :: RdrName -> CLabelString
404 mkExtName rdrNm = _PK_ (occNameUserString (rdrNameOcc rdrNm))
406 -----------------------------------------------------------------------------
407 -- group function bindings into equation groups
409 -- we assume the bindings are coming in reverse order, so we take the srcloc
410 -- from the *last* binding in the group as the srcloc for the whole group.
412 groupBindings :: [RdrBinding] -> RdrBinding
413 groupBindings binds = group Nothing binds
414 where group :: Maybe RdrNameMonoBinds -> [RdrBinding] -> RdrBinding
415 group (Just bind) [] = RdrValBinding bind
416 group Nothing [] = RdrNullBind
418 -- don't group together FunMonoBinds if they have
419 -- no arguments. This is necessary now that variable bindings
420 -- with no arguments are now treated as FunMonoBinds rather
421 -- than pattern bindings (tests/rename/should_fail/rnfail002).
422 group (Just (FunMonoBind f inf1 mtchs ignore_srcloc))
423 (RdrValBinding (FunMonoBind f' _
424 [mtch@(Match (_:_) _ _)] loc)
426 | f == f' = group (Just (FunMonoBind f inf1 (mtch:mtchs) loc)) binds
428 group (Just so_far) binds
429 = RdrValBinding so_far `RdrAndBindings` group Nothing binds
430 group Nothing (bind:binds)
432 RdrValBinding b@(FunMonoBind _ _ _ _) -> group (Just b) binds
433 other -> bind `RdrAndBindings` group Nothing binds