2 % (c) The GRASP/AQUA Project, Glasgow University, 1999
4 \section[ParseUtil]{Parser Utilities}
8 parseError -- String -> Pa
9 , mkPrefixCon, 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 TysWiredIn ( unitTyCon )
48 import ForeignCall ( CCallConv, Safety, CCallTarget(..), CExportSpec(..),
53 import OccName ( dataName, varName, isDataOcc, isTcOcc, occNameUserString )
54 import CStrings ( CLabelString )
58 -----------------------------------------------------------------------------
61 parseError :: String -> P a
63 getSrcLocP `thenP` \ loc ->
64 failMsgP (hcat [ppr loc, text ": ", text s])
67 -----------------------------------------------------------------------------
70 -- When parsing data declarations, we sometimes inadvertently parse
71 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
72 -- This function splits up the type application, adds any pending
73 -- arguments, and converts the type constructor back into a data constructor.
75 mkPrefixCon :: RdrNameHsType -> [RdrNameBangType] -> P (RdrName, RdrNameConDetails)
80 split (HsAppTy t u) ts = split t (unbangedType u : ts)
81 split (HsTyVar tc) ts = tyConToDataCon tc `thenP` \ data_con ->
82 returnP (data_con, PrefixCon ts)
83 split _ _ = parseError "Illegal data/newtype declaration"
85 mkRecCon :: [([RdrName],RdrNameBangType)] -> RdrNameConDetails
87 = RecCon [ (l,t) | (ls,t) <- fields, l <- ls ]
89 tyConToDataCon :: RdrName -> P RdrName
91 | isTcOcc (rdrNameOcc tc)
92 = returnP (setRdrNameSpace tc dataName)
94 = parseError (showSDoc (text "Not a constructor:" <+> quotes (ppr tc)))
96 ----------------------------------------------------------------------------
97 -- Various Syntactic Checks
99 checkInstType :: RdrNameHsType -> P RdrNameHsType
102 HsForAllTy tvs ctxt ty ->
103 checkDictTy ty [] `thenP` \ dict_ty ->
104 returnP (HsForAllTy tvs ctxt dict_ty)
106 HsParTy ty -> checkInstType ty
108 ty -> checkDictTy ty [] `thenP` \ dict_ty->
109 returnP (HsForAllTy Nothing [] dict_ty)
111 checkTyVars :: [RdrNameHsType] -> P [RdrNameHsTyVar]
112 checkTyVars tvs = mapP chk tvs
114 chk (HsKindSig (HsTyVar tv) k) = returnP (IfaceTyVar tv k)
115 chk (HsTyVar tv) = returnP (UserTyVar tv)
116 chk other = parseError "Type found where type variable expected"
118 checkTyClHdr :: RdrNameHsType -> P (RdrName, [RdrNameHsTyVar])
119 -- The header of a type or class decl should look like
120 -- (C a, D b) => T a b
128 | not (isRdrTyVar tc) = checkTyVars acc `thenP` \ tvs ->
130 go (HsOpTy t1 (HsTyOp tc) t2) acc
131 = checkTyVars (t1:t2:acc) `thenP` \ tvs ->
133 go (HsParTy ty) acc = go ty acc
134 go (HsAppTy t1 t2) acc = go t1 (t2:acc)
135 go other acc = parseError "Malformed LHS to type of class declaration"
137 checkContext :: RdrNameHsType -> P RdrNameContext
138 checkContext (HsTupleTy _ ts) -- (Eq a, Ord b) shows up as a tuple type
141 checkContext (HsParTy ty) -- to be sure HsParTy doesn't get into the way
144 checkContext (HsTyVar t) -- Empty context shows up as a unit type ()
145 | t == getRdrName unitTyCon = returnP []
148 = checkPred t `thenP` \p ->
151 checkPred :: RdrNameHsType -> P (HsPred RdrName)
152 -- Watch out.. in ...deriving( Show )... we use checkPred on
153 -- the list of partially applied predicates in the deriving,
154 -- so there can be zero args.
155 checkPred (HsPredTy (HsIParam n ty)) = returnP (HsIParam n ty)
159 go (HsTyVar t) args | not (isRdrTyVar t)
160 = returnP (HsClassP t args)
161 go (HsAppTy l r) args = go l (r:args)
162 go (HsParTy t) args = go t args
163 go _ _ = parseError "Illegal class assertion"
165 checkDictTy :: RdrNameHsType -> [RdrNameHsType] -> P RdrNameHsType
166 checkDictTy (HsTyVar t) args@(_:_) | not (isRdrTyVar t)
167 = returnP (mkHsDictTy t args)
168 checkDictTy (HsAppTy l r) args = checkDictTy l (r:args)
169 checkDictTy (HsParTy t) args = checkDictTy t args
170 checkDictTy _ _ = parseError "Malformed context in instance header"
173 ---------------------------------------------------------------------------
174 -- Checking statements in a do-expression
175 -- We parse do { e1 ; e2 ; }
176 -- as [ExprStmt e1, ExprStmt e2]
177 -- checkDo (a) checks that the last thing is an ExprStmt
178 -- (b) transforms it to a ResultStmt
180 checkDo [] = parseError "Empty 'do' construct"
181 checkDo [ExprStmt e _ l] = returnP [ResultStmt e l]
182 checkDo [s] = parseError "The last statement in a 'do' construct must be an expression"
183 checkDo (s:ss) = checkDo ss `thenP` \ ss' ->
186 ---------------------------------------------------------------------------
187 -- Checking Patterns.
189 -- We parse patterns as expressions and check for valid patterns below,
190 -- converting the expression into a pattern at the same time.
192 checkPattern :: SrcLoc -> RdrNameHsExpr -> P RdrNamePat
193 checkPattern loc e = setSrcLocP loc (checkPat e [])
195 checkPatterns :: SrcLoc -> [RdrNameHsExpr] -> P [RdrNamePat]
196 checkPatterns loc es = mapP (checkPattern loc) es
198 checkPat :: RdrNameHsExpr -> [RdrNamePat] -> P RdrNamePat
199 checkPat (HsVar c) args | isRdrDataCon c = returnP (ConPatIn c (PrefixCon args))
200 checkPat (HsApp f x) args =
201 checkPat x [] `thenP` \x ->
203 checkPat e [] = case e of
204 EWildPat -> returnP (WildPat placeHolderType)
205 HsVar x -> returnP (VarPat x)
206 HsLit l -> returnP (LitPat l)
207 HsOverLit l -> returnP (NPatIn l Nothing)
208 ELazyPat e -> checkPat e [] `thenP` (returnP . LazyPat)
209 EAsPat n e -> checkPat e [] `thenP` (returnP . AsPat n)
210 ExprWithTySig e t -> checkPat e [] `thenP` \e ->
211 -- Pattern signatures are parsed as sigtypes,
212 -- but they aren't explicit forall points. Hence
213 -- we have to remove the implicit forall here.
215 HsForAllTy Nothing [] ty -> ty
218 returnP (SigPatIn e t')
220 -- Translate out NegApps of literals in patterns. We negate
221 -- the Integer here, and add back the call to 'negate' when
222 -- we typecheck the pattern.
223 -- NB. Negative *primitive* literals are already handled by
224 -- RdrHsSyn.mkHsNegApp
225 NegApp (HsOverLit lit) neg -> returnP (NPatIn lit (Just neg))
227 OpApp (HsVar n) (HsVar plus) _ (HsOverLit lit@(HsIntegral _ _))
229 -> returnP (mkNPlusKPat n lit)
231 plus_RDR = mkUnqual varName FSLIT("+") -- Hack
233 OpApp l op fix r -> checkPat l [] `thenP` \l ->
234 checkPat r [] `thenP` \r ->
236 HsVar c | isDataOcc (rdrNameOcc c)
237 -> returnP (ConPatIn c (InfixCon l r))
240 HsPar e -> checkPat e [] `thenP` (returnP . ParPat)
241 ExplicitList _ es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
242 returnP (ListPat ps placeHolderType)
243 ExplicitPArr _ es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
244 returnP (PArrPat ps placeHolderType)
246 ExplicitTuple es b -> mapP (\e -> checkPat e []) es `thenP` \ps ->
247 returnP (TuplePat ps b)
249 RecordCon c fs -> mapP checkPatField fs `thenP` \fs ->
250 returnP (ConPatIn c (RecCon fs))
252 HsType ty -> returnP (TypePat ty)
255 checkPat _ _ = patFail
257 checkPatField :: (RdrName, RdrNameHsExpr) -> P (RdrName, RdrNamePat)
258 checkPatField (n,e) = checkPat e [] `thenP` \p ->
261 patFail = parseError "Parse error in pattern"
264 ---------------------------------------------------------------------------
265 -- Check Equation Syntax
269 -> Maybe RdrNameHsType
274 checkValDef lhs opt_sig grhss loc
275 = case isFunLhs lhs [] of
277 checkPatterns loc es `thenP` \ps ->
278 returnP (RdrValBinding (FunMonoBind f inf [Match ps opt_sig grhss] loc))
281 checkPattern loc lhs `thenP` \lhs ->
282 returnP (RdrValBinding (PatMonoBind lhs grhss loc))
289 checkValSig (HsVar v) ty loc = returnP (RdrSig (Sig v ty loc))
290 checkValSig other ty loc = parseError "Type signature given for an expression"
293 -- A variable binding is parsed as an RdrNameFunMonoBind.
294 -- See comments with HsBinds.MonoBinds
296 isFunLhs :: RdrNameHsExpr -> [RdrNameHsExpr] -> Maybe (RdrName, Bool, [RdrNameHsExpr])
297 isFunLhs (OpApp l (HsVar op) fix r) es | not (isRdrDataCon op)
298 = Just (op, True, (l:r:es))
300 = case isFunLhs l es of
301 Just (op', True, j : k : es') ->
302 Just (op', True, j : OpApp k (HsVar op) fix r : es')
304 isFunLhs (HsVar f) es | not (isRdrDataCon f)
306 isFunLhs (HsApp f e) es = isFunLhs f (e:es)
307 isFunLhs (HsPar e) es@(_:_) = isFunLhs e es
308 isFunLhs _ _ = Nothing
310 ---------------------------------------------------------------------------
311 -- Miscellaneous utilities
313 checkPrec :: Integer -> P ()
314 checkPrec i | 0 <= i && i <= 9 = returnP ()
315 | otherwise = parseError "Precedence out of range"
319 -> RdrNameHsRecordBinds
322 mkRecConstrOrUpdate (HsVar c) fs | isRdrDataCon c
323 = returnP (RecordCon c fs)
324 mkRecConstrOrUpdate exp fs@(_:_)
325 = returnP (RecordUpd exp fs)
326 mkRecConstrOrUpdate _ _
327 = parseError "Empty record update"
329 -----------------------------------------------------------------------------
330 -- utilities for foreign declarations
332 -- supported calling conventions
334 data CallConv = CCall CCallConv -- ccall or stdcall
337 -- construct a foreign import declaration
341 -> (FastString, RdrName, RdrNameHsType)
344 mkImport (CCall cconv) safety (entity, v, ty) loc =
345 parseCImport entity cconv safety v `thenP` \importSpec ->
346 returnP $ ForD (ForeignImport v ty importSpec False loc)
347 mkImport (DNCall ) _ (entity, v, ty) loc =
348 returnP $ ForD (ForeignImport v ty (DNImport (DNCallSpec entity)) False loc)
350 -- parse the entity string of a foreign import declaration for the `ccall' or
351 -- `stdcall' calling convention'
353 parseCImport :: FastString
358 parseCImport entity cconv safety v
359 -- FIXME: we should allow white space around `dynamic' and `wrapper' -=chak
360 | entity == FSLIT ("dynamic") =
361 returnP $ CImport cconv safety nilFS nilFS (CFunction DynamicTarget)
362 | entity == FSLIT ("wrapper") =
363 returnP $ CImport cconv safety nilFS nilFS CWrapper
364 | otherwise = parse0 (unpackFS entity)
366 -- using the static keyword?
367 parse0 (' ': rest) = parse0 rest
368 parse0 ('s':'t':'a':'t':'i':'c':rest) = parse1 rest
369 parse0 rest = parse1 rest
370 -- check for header file name
371 parse1 "" = parse4 "" nilFS False nilFS
372 parse1 (' ':rest) = parse1 rest
373 parse1 str@('&':_ ) = parse2 str nilFS
374 parse1 str@('[':_ ) = parse3 str nilFS False
376 | ".h" `isSuffixOf` first = parse2 rest (mkFastString first)
377 | otherwise = parse4 str nilFS False nilFS
379 (first, rest) = break (\c -> c == ' ' || c == '&' || c == '[') str
380 -- check for address operator (indicating a label import)
381 parse2 "" header = parse4 "" header False nilFS
382 parse2 (' ':rest) header = parse2 rest header
383 parse2 ('&':rest) header = parse3 rest header True
384 parse2 str@('[':_ ) header = parse3 str header False
385 parse2 str header = parse4 str header False nilFS
386 -- check for library object name
387 parse3 (' ':rest) header isLbl = parse3 rest header isLbl
388 parse3 ('[':rest) header isLbl =
389 case break (== ']') rest of
390 (lib, ']':rest) -> parse4 rest header isLbl (mkFastString lib)
391 _ -> parseError "Missing ']' in entity"
392 parse3 str header isLbl = parse4 str header isLbl nilFS
393 -- check for name of C function
394 parse4 "" header isLbl lib = build (mkExtName v) header isLbl lib
395 parse4 (' ':rest) header isLbl lib = parse4 rest header isLbl lib
396 parse4 str header isLbl lib
397 | all (== ' ') rest = build (mkFastString first) header isLbl lib
398 | otherwise = parseError "Malformed entity string"
400 (first, rest) = break (== ' ') str
402 build cid header False lib = returnP $
403 CImport cconv safety header lib (CFunction (StaticTarget cid))
404 build cid header True lib = returnP $
405 CImport cconv safety header lib (CLabel cid )
407 -- construct a foreign export declaration
410 -> (FastString, RdrName, RdrNameHsType)
413 mkExport (CCall cconv) (entity, v, ty) loc = returnP $
414 ForD (ForeignExport v ty (CExport (CExportStatic entity' cconv)) False loc)
416 entity' | nullFastString entity = mkExtName v
418 mkExport DNCall (entity, v, ty) loc =
419 parseError "Foreign export is not yet supported for .NET"
421 -- Supplying the ext_name in a foreign decl is optional; if it
422 -- isn't there, the Haskell name is assumed. Note that no transformation
423 -- of the Haskell name is then performed, so if you foreign export (++),
424 -- it's external name will be "++". Too bad; it's important because we don't
425 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
426 -- (This is why we use occNameUserString.)
428 mkExtName :: RdrName -> CLabelString
429 mkExtName rdrNm = mkFastString (occNameUserString (rdrNameOcc rdrNm))
431 -----------------------------------------------------------------------------
432 -- group function bindings into equation groups
434 -- we assume the bindings are coming in reverse order, so we take the srcloc
435 -- from the *last* binding in the group as the srcloc for the whole group.
437 groupBindings :: [RdrBinding] -> RdrBinding
438 groupBindings binds = group Nothing binds
439 where group :: Maybe RdrNameMonoBinds -> [RdrBinding] -> RdrBinding
440 group (Just bind) [] = RdrValBinding bind
441 group Nothing [] = RdrNullBind
443 -- don't group together FunMonoBinds if they have
444 -- no arguments. This is necessary now that variable bindings
445 -- with no arguments are now treated as FunMonoBinds rather
446 -- than pattern bindings (tests/rename/should_fail/rnfail002).
447 group (Just (FunMonoBind f inf1 mtchs ignore_srcloc))
448 (RdrValBinding (FunMonoBind f' _
449 [mtch@(Match (_:_) _ _)] loc)
451 | f == f' = group (Just (FunMonoBind f inf1 (mtch:mtchs) loc)) binds
453 group (Just so_far) binds
454 = RdrValBinding so_far `RdrAndBindings` group Nothing binds
455 group Nothing (bind:binds)
457 RdrValBinding b@(FunMonoBind _ _ _ _) -> group (Just b) binds
458 other -> bind `RdrAndBindings` group Nothing binds
460 -- ---------------------------------------------------------------------------
461 -- Make the export list for an interface
463 mkIfaceExports :: [RdrNameTyClDecl] -> [RdrAvailInfo]
464 mkIfaceExports decls = map getExport decls
465 where getExport d = case d of
466 TyData{} -> tc_export
467 ClassDecl{} -> tc_export
470 tc_export = AvailTC (rdrNameOcc (tcdName d))
471 (map (rdrNameOcc.fst) (tyClDeclNames d))
472 var_export = Avail (rdrNameOcc (tcdName d))