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 -- translate out NegApps of literals in patterns.
202 -- NB. negative primitive literals are already handled by
203 -- RdrHsSyn.mkHsNegApp
204 NegApp (HsOverLit (HsIntegral i n)) _
205 -> returnP (NPatIn (HsIntegral (-i) n))
206 NegApp (HsOverLit (HsFractional f n)) _
207 -> returnP (NPatIn (HsFractional (-f) n))
209 OpApp (HsVar n) (HsVar plus) _ (HsOverLit lit@(HsIntegral _ _))
211 -> returnP (mkNPlusKPat n lit)
213 plus_RDR = mkUnqual varName SLIT("+") -- Hack
215 OpApp l op fix r -> checkPat l [] `thenP` \l ->
216 checkPat r [] `thenP` \r ->
218 HsVar c -> returnP (ConOpPatIn l c fix r)
221 HsPar e -> checkPat e [] `thenP` (returnP . ParPatIn)
222 ExplicitList _ es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
223 returnP (ListPatIn ps)
224 ExplicitPArr _ es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
225 returnP (PArrPatIn ps)
227 ExplicitTuple es b -> mapP (\e -> checkPat e []) es `thenP` \ps ->
228 returnP (TuplePatIn ps b)
230 RecordCon c fs -> mapP checkPatField fs `thenP` \fs ->
231 returnP (RecPatIn c fs)
233 HsType ty -> returnP (TypePatIn ty)
236 checkPat _ _ = patFail
238 checkPatField :: (RdrName, RdrNameHsExpr, Bool)
239 -> P (RdrName, RdrNamePat, Bool)
240 checkPatField (n,e,b) =
241 checkPat e [] `thenP` \p ->
244 patFail = parseError "Parse error in pattern"
247 ---------------------------------------------------------------------------
248 -- Check Equation Syntax
252 -> Maybe RdrNameHsType
257 checkValDef lhs opt_sig grhss loc
258 = case isFunLhs lhs [] of
260 checkPatterns loc es `thenP` \ps ->
261 returnP (RdrValBinding (FunMonoBind f inf [Match ps opt_sig grhss] loc))
264 checkPattern loc lhs `thenP` \lhs ->
265 returnP (RdrValBinding (PatMonoBind lhs grhss loc))
272 checkValSig (HsVar v) ty loc = returnP (RdrSig (Sig v ty loc))
273 checkValSig other ty loc = parseError "Type signature given for an expression"
276 -- A variable binding is parsed as an RdrNameFunMonoBind.
277 -- See comments with HsBinds.MonoBinds
279 isFunLhs :: RdrNameHsExpr -> [RdrNameHsExpr] -> Maybe (RdrName, Bool, [RdrNameHsExpr])
280 isFunLhs (OpApp l (HsVar op) fix r) es | not (isRdrDataCon op)
281 = Just (op, True, (l:r:es))
283 = case isFunLhs l es of
284 Just (op', True, j : k : es') ->
285 Just (op', True, j : OpApp k (HsVar op) fix r : es')
287 isFunLhs (HsVar f) es | not (isRdrDataCon f)
289 isFunLhs (HsApp f e) es = isFunLhs f (e:es)
290 isFunLhs (HsPar e) es@(_:_) = isFunLhs e es
291 isFunLhs _ _ = Nothing
293 ---------------------------------------------------------------------------
294 -- Miscellaneous utilities
296 checkPrec :: Integer -> P ()
297 checkPrec i | 0 <= i && i <= 9 = returnP ()
298 | otherwise = parseError "Precedence out of range"
302 -> RdrNameHsRecordBinds
305 mkRecConstrOrUpdate (HsVar c) fs | isRdrDataCon c
306 = returnP (RecordCon c fs)
307 mkRecConstrOrUpdate exp fs@(_:_)
308 = returnP (RecordUpd exp fs)
309 mkRecConstrOrUpdate _ _
310 = parseError "Empty record update"
312 -----------------------------------------------------------------------------
313 -- utilities for foreign declarations
315 -- supported calling conventions
317 data CallConv = CCall CCallConv -- ccall or stdcall
320 -- construct a foreign import declaration
324 -> (FAST_STRING, RdrName, RdrNameHsType)
327 mkImport (CCall cconv) safety (entity, v, ty) loc =
328 parseCImport entity cconv safety v `thenP` \importSpec ->
329 returnP $ ForD (ForeignImport v ty importSpec False loc)
330 mkImport (DNCall ) _ (entity, v, ty) loc =
331 returnP $ ForD (ForeignImport v ty (DNImport (DNCallSpec entity)) False loc)
333 -- parse the entity string of a foreign import declaration for the `ccall' or
334 -- `stdcall' calling convention'
336 parseCImport :: FAST_STRING
341 parseCImport entity cconv safety v
342 -- FIXME: we should allow white space around `dynamic' and `wrapper' -=chak
343 | entity == SLIT ("dynamic") =
344 returnP $ CImport cconv safety _NIL_ _NIL_ (CFunction DynamicTarget)
345 | entity == SLIT ("wrapper") =
346 returnP $ CImport cconv safety _NIL_ _NIL_ CWrapper
347 | otherwise = parse0 (_UNPK_ entity)
349 -- using the static keyword?
350 parse0 (' ': rest) = parse0 rest
351 parse0 ('s':'t':'a':'t':'i':'c':rest) = parse1 rest
352 parse0 rest = parse1 rest
353 -- check for header file name
354 parse1 "" = parse4 "" _NIL_ False _NIL_
355 parse1 (' ':rest) = parse1 rest
356 parse1 str@('&':_ ) = parse2 str _NIL_
357 parse1 str@('[':_ ) = parse3 str _NIL_ False
359 | ".h" `isSuffixOf` first = parse2 rest (_PK_ first)
360 | otherwise = parse4 str _NIL_ False _NIL_
362 (first, rest) = break (\c -> c == ' ' || c == '&' || c == '[') str
363 -- check for address operator (indicating a label import)
364 parse2 "" header = parse4 "" header False _NIL_
365 parse2 (' ':rest) header = parse2 rest header
366 parse2 ('&':rest) header = parse3 rest header True
367 parse2 str@('[':_ ) header = parse3 str header False
368 parse2 str header = parse4 str header False _NIL_
369 -- check for library object name
370 parse3 (' ':rest) header isLbl = parse3 rest header isLbl
371 parse3 ('[':rest) header isLbl =
372 case break (== ']') rest of
373 (lib, ']':rest) -> parse4 rest header isLbl (_PK_ lib)
374 _ -> parseError "Missing ']' in entity"
375 parse3 str header isLbl = parse4 str header isLbl _NIL_
376 -- check for name of C function
377 parse4 "" header isLbl lib = build (mkExtName v) header isLbl lib
378 parse4 (' ':rest) header isLbl lib = parse4 rest header isLbl lib
379 parse4 str header isLbl lib
380 | all (== ' ') rest = build (_PK_ first) header isLbl lib
381 | otherwise = parseError "Malformed entity string"
383 (first, rest) = break (== ' ') str
385 build cid header False lib = returnP $
386 CImport cconv safety header lib (CFunction (StaticTarget cid))
387 build cid header True lib = returnP $
388 CImport cconv safety header lib (CLabel cid )
390 -- construct a foreign export declaration
393 -> (FAST_STRING, RdrName, RdrNameHsType)
396 mkExport (CCall cconv) (entity, v, ty) loc = returnP $
397 ForD (ForeignExport v ty (CExport (CExportStatic entity' cconv)) False loc)
399 entity' | nullFastString entity = mkExtName v
401 mkExport DNCall (entity, v, ty) loc =
402 parseError "Foreign export is not yet supported for .NET"
404 -- Supplying the ext_name in a foreign decl is optional; if it
405 -- isn't there, the Haskell name is assumed. Note that no transformation
406 -- of the Haskell name is then performed, so if you foreign export (++),
407 -- it's external name will be "++". Too bad; it's important because we don't
408 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
409 -- (This is why we use occNameUserString.)
411 mkExtName :: RdrName -> CLabelString
412 mkExtName rdrNm = _PK_ (occNameUserString (rdrNameOcc rdrNm))
414 -----------------------------------------------------------------------------
415 -- group function bindings into equation groups
417 -- we assume the bindings are coming in reverse order, so we take the srcloc
418 -- from the *last* binding in the group as the srcloc for the whole group.
420 groupBindings :: [RdrBinding] -> RdrBinding
421 groupBindings binds = group Nothing binds
422 where group :: Maybe RdrNameMonoBinds -> [RdrBinding] -> RdrBinding
423 group (Just bind) [] = RdrValBinding bind
424 group Nothing [] = RdrNullBind
426 -- don't group together FunMonoBinds if they have
427 -- no arguments. This is necessary now that variable bindings
428 -- with no arguments are now treated as FunMonoBinds rather
429 -- than pattern bindings (tests/rename/should_fail/rnfail002).
430 group (Just (FunMonoBind f inf1 mtchs ignore_srcloc))
431 (RdrValBinding (FunMonoBind f' _
432 [mtch@(Match (_:_) _ _)] loc)
434 | f == f' = group (Just (FunMonoBind f inf1 (mtch:mtchs) loc)) binds
436 group (Just so_far) binds
437 = RdrValBinding so_far `RdrAndBindings` group Nothing binds
438 group Nothing (bind:binds)
440 RdrValBinding b@(FunMonoBind _ _ _ _) -> group (Just b) binds
441 other -> bind `RdrAndBindings` group Nothing binds