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
14 , mkIfaceExports -- :: [RdrNameTyClDecl] -> [RdrExportItem]
17 , mkImport -- CallConv -> Safety
18 -- -> (FastString, RdrName, RdrNameHsType)
21 , mkExport -- CallConv
22 -- -> (FastString, RdrName, RdrNameHsType)
25 , mkExtName -- RdrName -> CLabelString
27 , checkPrec -- String -> P String
28 , checkContext -- HsType -> P HsContext
29 , checkPred -- HsType -> P HsPred
30 , checkTyVars -- [HsTyVar] -> P [HsType]
31 , checkTyClHdr -- HsType -> (name,[tyvar])
32 , checkInstType -- HsType -> P HsType
33 , checkPattern -- HsExp -> P HsPat
34 , checkPatterns -- SrcLoc -> [HsExp] -> P [HsPat]
35 , checkDo -- [Stmt] -> P [Stmt]
36 , checkValDef -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
37 , checkValSig -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
40 #include "HsVersions.h"
42 import List ( isSuffixOf )
45 import HscTypes ( RdrAvailInfo, GenAvailInfo(..) )
46 import HsSyn -- Lots of it
47 import ForeignCall ( CCallConv, Safety, CCallTarget(..), CExportSpec(..),
52 import PrelNames ( unitTyCon_RDR )
53 import OccName ( dataName, varName, tcClsName, isDataOcc,
54 occNameSpace, setOccNameSpace, occNameUserString )
55 import CStrings ( CLabelString )
59 -----------------------------------------------------------------------------
62 parseError :: String -> P a
64 getSrcLocP `thenP` \ loc ->
65 failMsgP (hcat [ppr loc, text ": ", text s])
68 -----------------------------------------------------------------------------
71 -- When parsing data declarations, we sometimes inadvertently parse
72 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
73 -- This function splits up the type application, adds any pending
74 -- arguments, and converts the type constructor back into a data constructor.
76 mkVanillaCon :: RdrNameHsType -> [RdrNameBangType] -> P (RdrName, RdrNameConDetails)
81 split (HsAppTy t u) ts = split t (unbangedType u : ts)
82 split (HsTyVar tc) ts = tyConToDataCon tc `thenP` \ data_con ->
83 returnP (data_con, VanillaCon ts)
84 split _ _ = parseError "Illegal data/newtype declaration"
86 mkRecCon :: RdrName -> [([RdrName],RdrNameBangType)] -> P (RdrName, RdrNameConDetails)
88 = tyConToDataCon con `thenP` \ data_con ->
89 returnP (data_con, RecCon fields)
91 tyConToDataCon :: RdrName -> P RdrName
93 | occNameSpace tc_occ == tcClsName
94 = returnP (setRdrNameOcc tc (setOccNameSpace tc_occ dataName))
96 = parseError (showSDoc (text "Not a constructor:" <+> quotes (ppr tc)))
98 tc_occ = rdrNameOcc tc
101 ----------------------------------------------------------------------------
102 -- Various Syntactic Checks
104 checkInstType :: RdrNameHsType -> P RdrNameHsType
107 HsForAllTy tvs ctxt ty ->
108 checkDictTy ty [] `thenP` \ dict_ty ->
109 returnP (HsForAllTy tvs ctxt dict_ty)
111 HsParTy ty -> checkInstType 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 checkTyClHdr :: RdrNameHsType -> P (RdrName, [RdrNameHsTyVar])
124 -- The header of a type or class decl should look like
125 -- (C a, D b) => T a b
133 | not (isRdrTyVar tc) = checkTyVars acc `thenP` \ tvs ->
135 go (HsOpTy t1 (HsTyOp tc) t2) acc
136 = checkTyVars (t1:t2:acc) `thenP` \ tvs ->
138 go (HsParTy ty) acc = go ty acc
139 go (HsAppTy t1 t2) acc = go t1 (t2:acc)
140 go other acc = parseError "Malformed LHS to type of class declaration"
142 checkContext :: RdrNameHsType -> P RdrNameContext
143 checkContext (HsTupleTy _ ts) -- (Eq a, Ord b) shows up as a tuple type
146 checkContext (HsParTy ty) -- to be sure HsParTy doesn't get into the way
149 checkContext (HsTyVar t) -- Empty context shows up as a unit type ()
150 | t == unitTyCon_RDR = returnP []
153 = checkPred t `thenP` \p ->
156 checkPred :: RdrNameHsType -> P (HsPred RdrName)
157 -- Watch out.. in ...deriving( Show )... we use checkPred on
158 -- the list of partially applied predicates in the deriving,
159 -- so there can be zero args.
160 checkPred (HsPredTy (HsIParam n ty)) = returnP (HsIParam n ty)
164 go (HsTyVar t) args | not (isRdrTyVar t)
165 = returnP (HsClassP t args)
166 go (HsAppTy l r) args = go l (r:args)
167 go (HsParTy t) args = go t args
168 go _ _ = parseError "Illegal class assertion"
170 checkDictTy :: RdrNameHsType -> [RdrNameHsType] -> P RdrNameHsType
171 checkDictTy (HsTyVar t) args@(_:_) | not (isRdrTyVar t)
172 = returnP (mkHsDictTy t args)
173 checkDictTy (HsAppTy l r) args = checkDictTy l (r:args)
174 checkDictTy (HsParTy t) args = checkDictTy t args
175 checkDictTy _ _ = parseError "Malformed context in instance header"
178 ---------------------------------------------------------------------------
179 -- Checking statements in a do-expression
180 -- We parse do { e1 ; e2 ; }
181 -- as [ExprStmt e1, ExprStmt e2]
182 -- checkDo (a) checks that the last thing is an ExprStmt
183 -- (b) transforms it to a ResultStmt
185 checkDo [] = parseError "Empty 'do' construct"
186 checkDo [ExprStmt e _ l] = returnP [ResultStmt e l]
187 checkDo [s] = parseError "The last statement in a 'do' construct must be an expression"
188 checkDo (s:ss) = checkDo ss `thenP` \ ss' ->
191 ---------------------------------------------------------------------------
192 -- Checking Patterns.
194 -- We parse patterns as expressions and check for valid patterns below,
195 -- converting the expression into a pattern at the same time.
197 checkPattern :: SrcLoc -> RdrNameHsExpr -> P RdrNamePat
198 checkPattern loc e = setSrcLocP loc (checkPat e [])
200 checkPatterns :: SrcLoc -> [RdrNameHsExpr] -> P [RdrNamePat]
201 checkPatterns loc es = mapP (checkPattern loc) es
203 checkPat :: RdrNameHsExpr -> [RdrNamePat] -> P RdrNamePat
204 checkPat (HsVar c) args | isRdrDataCon c = returnP (ConPatIn c args)
205 checkPat (HsApp f x) args =
206 checkPat x [] `thenP` \x ->
208 checkPat e [] = case e of
209 EWildPat -> returnP WildPatIn
210 HsVar x -> returnP (VarPatIn x)
211 HsLit l -> returnP (LitPatIn l)
212 HsOverLit l -> returnP (NPatIn l Nothing)
213 ELazyPat e -> checkPat e [] `thenP` (returnP . LazyPatIn)
214 EAsPat n e -> checkPat e [] `thenP` (returnP . AsPatIn n)
215 ExprWithTySig e t -> checkPat e [] `thenP` \e ->
216 -- Pattern signatures are parsed as sigtypes,
217 -- but they aren't explicit forall points. Hence
218 -- we have to remove the implicit forall here.
220 HsForAllTy Nothing [] ty -> ty
223 returnP (SigPatIn e t')
225 -- Translate out NegApps of literals in patterns. We negate
226 -- the Integer here, and add back the call to 'negate' when
227 -- we typecheck the pattern.
228 -- NB. Negative *primitive* literals are already handled by
229 -- RdrHsSyn.mkHsNegApp
230 NegApp (HsOverLit lit) neg -> returnP (NPatIn lit (Just neg))
232 OpApp (HsVar n) (HsVar plus) _ (HsOverLit lit@(HsIntegral _ _))
234 -> returnP (mkNPlusKPat n lit)
236 plus_RDR = mkUnqual varName FSLIT("+") -- Hack
238 OpApp l op fix r -> checkPat l [] `thenP` \l ->
239 checkPat r [] `thenP` \r ->
241 HsVar c | isDataOcc (rdrNameOcc c)
242 -> returnP (ConOpPatIn l c fix r)
245 HsPar e -> checkPat e [] `thenP` (returnP . ParPatIn)
246 ExplicitList _ es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
247 returnP (ListPatIn ps)
248 ExplicitPArr _ es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
249 returnP (PArrPatIn ps)
251 ExplicitTuple es b -> mapP (\e -> checkPat e []) es `thenP` \ps ->
252 returnP (TuplePatIn ps b)
254 RecordCon c fs -> mapP checkPatField fs `thenP` \fs ->
255 returnP (RecPatIn c fs)
257 HsType ty -> returnP (TypePatIn ty)
260 checkPat _ _ = patFail
262 checkPatField :: (RdrName, RdrNameHsExpr, Bool)
263 -> P (RdrName, RdrNamePat, Bool)
264 checkPatField (n,e,b) =
265 checkPat e [] `thenP` \p ->
268 patFail = parseError "Parse error in pattern"
271 ---------------------------------------------------------------------------
272 -- Check Equation Syntax
276 -> Maybe RdrNameHsType
281 checkValDef lhs opt_sig grhss loc
282 = case isFunLhs lhs [] of
284 checkPatterns loc es `thenP` \ps ->
285 returnP (RdrValBinding (FunMonoBind f inf [Match ps opt_sig grhss] loc))
288 checkPattern loc lhs `thenP` \lhs ->
289 returnP (RdrValBinding (PatMonoBind lhs grhss loc))
296 checkValSig (HsVar v) ty loc = returnP (RdrSig (Sig v ty loc))
297 checkValSig other ty loc = parseError "Type signature given for an expression"
300 -- A variable binding is parsed as an RdrNameFunMonoBind.
301 -- See comments with HsBinds.MonoBinds
303 isFunLhs :: RdrNameHsExpr -> [RdrNameHsExpr] -> Maybe (RdrName, Bool, [RdrNameHsExpr])
304 isFunLhs (OpApp l (HsVar op) fix r) es | not (isRdrDataCon op)
305 = Just (op, True, (l:r:es))
307 = case isFunLhs l es of
308 Just (op', True, j : k : es') ->
309 Just (op', True, j : OpApp k (HsVar op) fix r : es')
311 isFunLhs (HsVar f) es | not (isRdrDataCon f)
313 isFunLhs (HsApp f e) es = isFunLhs f (e:es)
314 isFunLhs (HsPar e) es@(_:_) = isFunLhs e es
315 isFunLhs _ _ = Nothing
317 ---------------------------------------------------------------------------
318 -- Miscellaneous utilities
320 checkPrec :: Integer -> P ()
321 checkPrec i | 0 <= i && i <= 9 = returnP ()
322 | otherwise = parseError "Precedence out of range"
326 -> RdrNameHsRecordBinds
329 mkRecConstrOrUpdate (HsVar c) fs | isRdrDataCon c
330 = returnP (RecordCon c fs)
331 mkRecConstrOrUpdate exp fs@(_:_)
332 = returnP (RecordUpd exp fs)
333 mkRecConstrOrUpdate _ _
334 = parseError "Empty record update"
336 -----------------------------------------------------------------------------
337 -- utilities for foreign declarations
339 -- supported calling conventions
341 data CallConv = CCall CCallConv -- ccall or stdcall
344 -- construct a foreign import declaration
348 -> (FastString, RdrName, RdrNameHsType)
351 mkImport (CCall cconv) safety (entity, v, ty) loc =
352 parseCImport entity cconv safety v `thenP` \importSpec ->
353 returnP $ ForD (ForeignImport v ty importSpec False loc)
354 mkImport (DNCall ) _ (entity, v, ty) loc =
355 returnP $ ForD (ForeignImport v ty (DNImport (DNCallSpec entity)) False loc)
357 -- parse the entity string of a foreign import declaration for the `ccall' or
358 -- `stdcall' calling convention'
360 parseCImport :: FastString
365 parseCImport entity cconv safety v
366 -- FIXME: we should allow white space around `dynamic' and `wrapper' -=chak
367 | entity == FSLIT ("dynamic") =
368 returnP $ CImport cconv safety nilFS nilFS (CFunction DynamicTarget)
369 | entity == FSLIT ("wrapper") =
370 returnP $ CImport cconv safety nilFS nilFS CWrapper
371 | otherwise = parse0 (unpackFS entity)
373 -- using the static keyword?
374 parse0 (' ': rest) = parse0 rest
375 parse0 ('s':'t':'a':'t':'i':'c':rest) = parse1 rest
376 parse0 rest = parse1 rest
377 -- check for header file name
378 parse1 "" = parse4 "" nilFS False nilFS
379 parse1 (' ':rest) = parse1 rest
380 parse1 str@('&':_ ) = parse2 str nilFS
381 parse1 str@('[':_ ) = parse3 str nilFS False
383 | ".h" `isSuffixOf` first = parse2 rest (mkFastString first)
384 | otherwise = parse4 str nilFS False nilFS
386 (first, rest) = break (\c -> c == ' ' || c == '&' || c == '[') str
387 -- check for address operator (indicating a label import)
388 parse2 "" header = parse4 "" header False nilFS
389 parse2 (' ':rest) header = parse2 rest header
390 parse2 ('&':rest) header = parse3 rest header True
391 parse2 str@('[':_ ) header = parse3 str header False
392 parse2 str header = parse4 str header False nilFS
393 -- check for library object name
394 parse3 (' ':rest) header isLbl = parse3 rest header isLbl
395 parse3 ('[':rest) header isLbl =
396 case break (== ']') rest of
397 (lib, ']':rest) -> parse4 rest header isLbl (mkFastString lib)
398 _ -> parseError "Missing ']' in entity"
399 parse3 str header isLbl = parse4 str header isLbl nilFS
400 -- check for name of C function
401 parse4 "" header isLbl lib = build (mkExtName v) header isLbl lib
402 parse4 (' ':rest) header isLbl lib = parse4 rest header isLbl lib
403 parse4 str header isLbl lib
404 | all (== ' ') rest = build (mkFastString first) header isLbl lib
405 | otherwise = parseError "Malformed entity string"
407 (first, rest) = break (== ' ') str
409 build cid header False lib = returnP $
410 CImport cconv safety header lib (CFunction (StaticTarget cid))
411 build cid header True lib = returnP $
412 CImport cconv safety header lib (CLabel cid )
414 -- construct a foreign export declaration
417 -> (FastString, RdrName, RdrNameHsType)
420 mkExport (CCall cconv) (entity, v, ty) loc = returnP $
421 ForD (ForeignExport v ty (CExport (CExportStatic entity' cconv)) False loc)
423 entity' | nullFastString entity = mkExtName v
425 mkExport DNCall (entity, v, ty) loc =
426 parseError "Foreign export is not yet supported for .NET"
428 -- Supplying the ext_name in a foreign decl is optional; if it
429 -- isn't there, the Haskell name is assumed. Note that no transformation
430 -- of the Haskell name is then performed, so if you foreign export (++),
431 -- it's external name will be "++". Too bad; it's important because we don't
432 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
433 -- (This is why we use occNameUserString.)
435 mkExtName :: RdrName -> CLabelString
436 mkExtName rdrNm = mkFastString (occNameUserString (rdrNameOcc rdrNm))
438 -----------------------------------------------------------------------------
439 -- group function bindings into equation groups
441 -- we assume the bindings are coming in reverse order, so we take the srcloc
442 -- from the *last* binding in the group as the srcloc for the whole group.
444 groupBindings :: [RdrBinding] -> RdrBinding
445 groupBindings binds = group Nothing binds
446 where group :: Maybe RdrNameMonoBinds -> [RdrBinding] -> RdrBinding
447 group (Just bind) [] = RdrValBinding bind
448 group Nothing [] = RdrNullBind
450 -- don't group together FunMonoBinds if they have
451 -- no arguments. This is necessary now that variable bindings
452 -- with no arguments are now treated as FunMonoBinds rather
453 -- than pattern bindings (tests/rename/should_fail/rnfail002).
454 group (Just (FunMonoBind f inf1 mtchs ignore_srcloc))
455 (RdrValBinding (FunMonoBind f' _
456 [mtch@(Match (_:_) _ _)] loc)
458 | f == f' = group (Just (FunMonoBind f inf1 (mtch:mtchs) loc)) binds
460 group (Just so_far) binds
461 = RdrValBinding so_far `RdrAndBindings` group Nothing binds
462 group Nothing (bind:binds)
464 RdrValBinding b@(FunMonoBind _ _ _ _) -> group (Just b) binds
465 other -> bind `RdrAndBindings` group Nothing binds
467 -- ---------------------------------------------------------------------------
468 -- Make the export list for an interface
470 mkIfaceExports :: [RdrNameTyClDecl] -> [RdrAvailInfo]
471 mkIfaceExports decls = map getExport decls
472 where getExport d = case d of
473 TyData{} -> tc_export
474 ClassDecl{} -> tc_export
477 tc_export = AvailTC (rdrNameOcc (tcdName d))
478 (map (rdrNameOcc.fst) (tyClDeclNames d))
479 var_export = Avail (rdrNameOcc (tcdName d))