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 , checkInstType -- HsType -> P HsType
28 , checkDataHeader -- HsQualType -> P (HsContext,HsName,[HsName])
29 , checkPattern -- HsExp -> P HsPat
30 , checkPatterns -- SrcLoc -> [HsExp] -> P [HsPat]
31 , checkDo -- [Stmt] -> P [Stmt]
32 , checkValDef -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
33 , checkValSig -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
36 #include "HsVersions.h"
38 import List ( isSuffixOf )
41 import HsSyn -- Lots of it
42 import ForeignCall ( CCallConv, Safety, CCallTarget(..), CExportSpec(..),
45 import RdrHsSyn ( RdrBinding(..),
46 RdrNameHsType, RdrNameBangType, RdrNameContext,
47 RdrNameHsTyVar, RdrNamePat, RdrNameHsExpr,
48 RdrNameGRHSs, RdrNameHsRecordBinds,
49 RdrNameMonoBinds, RdrNameConDetails, RdrNameHsDecl,
53 import PrelNames ( unitTyCon_RDR )
54 import OccName ( dataName, varName, tcClsName,
55 occNameSpace, setOccNameSpace, occNameUserString )
56 import CStrings ( CLabelString )
57 import FastString ( nullFastString )
60 -----------------------------------------------------------------------------
63 parseError :: String -> P a
65 getSrcLocP `thenP` \ loc ->
66 failMsgP (hcat [ppr loc, text ": ", text s])
69 -----------------------------------------------------------------------------
72 -- When parsing data declarations, we sometimes inadvertently parse
73 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
74 -- This function splits up the type application, adds any pending
75 -- arguments, and converts the type constructor back into a data constructor.
77 mkVanillaCon :: RdrNameHsType -> [RdrNameBangType] -> P (RdrName, RdrNameConDetails)
82 split (HsAppTy t u) ts = split t (unbangedType u : ts)
83 split (HsTyVar tc) ts = tyConToDataCon tc `thenP` \ data_con ->
84 returnP (data_con, VanillaCon ts)
85 split _ _ = parseError "Illegal data/newtype declaration"
87 mkRecCon :: RdrName -> [([RdrName],RdrNameBangType)] -> P (RdrName, RdrNameConDetails)
89 = tyConToDataCon con `thenP` \ data_con ->
90 returnP (data_con, RecCon fields)
92 tyConToDataCon :: RdrName -> P RdrName
94 | occNameSpace tc_occ == tcClsName
95 = returnP (setRdrNameOcc tc (setOccNameSpace tc_occ dataName))
97 = parseError (showSDoc (text "Not a constructor:" <+> quotes (ppr tc)))
99 tc_occ = rdrNameOcc tc
102 ----------------------------------------------------------------------------
103 -- Various Syntactic Checks
105 checkInstType :: RdrNameHsType -> P RdrNameHsType
108 HsForAllTy tvs ctxt ty ->
109 checkDictTy ty [] `thenP` \ dict_ty ->
110 returnP (HsForAllTy tvs ctxt dict_ty)
112 ty -> checkDictTy ty [] `thenP` \ dict_ty->
113 returnP (HsForAllTy Nothing [] dict_ty)
115 checkContext :: RdrNameHsType -> P RdrNameContext
116 checkContext (HsTupleTy _ ts) -- (Eq a, Ord b) shows up as a tuple type
117 = mapP (\t -> checkPred t []) ts `thenP` \ps ->
120 checkContext (HsTyVar t) -- Empty context shows up as a unit type ()
121 | t == unitTyCon_RDR = returnP []
124 = checkPred t [] `thenP` \p ->
127 checkPred :: RdrNameHsType -> [RdrNameHsType] -> P (HsPred RdrName)
128 checkPred (HsTyVar t) args | not (isRdrTyVar t)
129 = returnP (HsClassP t args)
130 checkPred (HsAppTy l r) args = checkPred l (r:args)
131 checkPred (HsPredTy (HsIParam n ty)) [] = returnP (HsIParam n ty)
132 checkPred _ _ = parseError "Illegal class assertion"
134 checkDictTy :: RdrNameHsType -> [RdrNameHsType] -> P RdrNameHsType
135 checkDictTy (HsTyVar t) args@(_:_) | not (isRdrTyVar t)
136 = returnP (mkHsDictTy t args)
137 checkDictTy (HsAppTy l r) args = checkDictTy l (r:args)
138 checkDictTy _ _ = parseError "Malformed context in instance header"
140 -- Put more comments!
141 -- Checks that the lhs of a datatype declaration
142 -- is of the form Context => T a b ... z
143 checkDataHeader :: String -- data/newtype/class
145 -> P (RdrNameContext, RdrName, [RdrNameHsTyVar])
147 checkDataHeader s (HsForAllTy Nothing cs t) =
148 checkSimple s t [] `thenP` \(c,ts) ->
149 returnP (cs,c,map UserTyVar ts)
150 checkDataHeader s t =
151 checkSimple s t [] `thenP` \(c,ts) ->
152 returnP ([],c,map UserTyVar ts)
154 -- Checks the type part of the lhs of
155 -- a data/newtype/class declaration
156 checkSimple :: String -> RdrNameHsType -> [RdrName] -> P ((RdrName,[RdrName]))
157 checkSimple s (HsAppTy l (HsTyVar a)) xs | isRdrTyVar a
158 = checkSimple s l (a:xs)
159 checkSimple s (HsTyVar tycon) xs | not (isRdrTyVar tycon) = returnP (tycon,xs)
161 checkSimple s (HsOpTy (HsTyVar t1) tycon (HsTyVar t2)) []
162 | not (isRdrTyVar tycon) && isRdrTyVar t1 && isRdrTyVar t2
163 = returnP (tycon,[t1,t2])
165 checkSimple s t _ = parseError ("Malformed " ++ s ++ " declaration")
167 ---------------------------------------------------------------------------
168 -- Checking statements in a do-expression
169 -- We parse do { e1 ; e2 ; }
170 -- as [ExprStmt e1, ExprStmt e2]
171 -- checkDo (a) checks that the last thing is an ExprStmt
172 -- (b) transforms it to a ResultStmt
174 checkDo [] = parseError "Empty 'do' construct"
175 checkDo [ExprStmt e _ l] = returnP [ResultStmt e l]
176 checkDo [s] = parseError "The last statement in a 'do' construct must be an expression"
177 checkDo (s:ss) = checkDo ss `thenP` \ ss' ->
180 ---------------------------------------------------------------------------
181 -- Checking Patterns.
183 -- We parse patterns as expressions and check for valid patterns below,
184 -- converting the expression into a pattern at the same time.
186 checkPattern :: SrcLoc -> RdrNameHsExpr -> P RdrNamePat
187 checkPattern loc e = setSrcLocP loc (checkPat e [])
189 checkPatterns :: SrcLoc -> [RdrNameHsExpr] -> P [RdrNamePat]
190 checkPatterns loc es = mapP (checkPattern loc) es
192 checkPat :: RdrNameHsExpr -> [RdrNamePat] -> P RdrNamePat
193 checkPat (HsVar c) args | isRdrDataCon c = returnP (ConPatIn c args)
194 checkPat (HsApp f x) args =
195 checkPat x [] `thenP` \x ->
197 checkPat e [] = case e of
198 EWildPat -> returnP WildPatIn
199 HsVar x -> returnP (VarPatIn x)
200 HsLit l -> returnP (LitPatIn l)
201 HsOverLit l -> returnP (NPatIn l)
202 ELazyPat e -> checkPat e [] `thenP` (returnP . LazyPatIn)
203 EAsPat n e -> checkPat e [] `thenP` (returnP . AsPatIn n)
204 ExprWithTySig e t -> checkPat e [] `thenP` \e ->
205 -- Pattern signatures are parsed as sigtypes,
206 -- but they aren't explicit forall points. Hence
207 -- we have to remove the implicit forall here.
209 HsForAllTy Nothing [] ty -> ty
212 returnP (SigPatIn e t')
214 OpApp (HsVar n) (HsVar plus) _ (HsOverLit lit@(HsIntegral _ _))
216 -> returnP (mkNPlusKPat n lit)
218 plus_RDR = mkUnqual varName SLIT("+") -- Hack
220 OpApp l op fix r -> checkPat l [] `thenP` \l ->
221 checkPat r [] `thenP` \r ->
223 HsVar c -> returnP (ConOpPatIn l c fix r)
226 HsPar e -> checkPat e [] `thenP` (returnP . ParPatIn)
227 ExplicitList _ es -> mapP (\e -> checkPat e []) es `thenP` \ps ->
228 returnP (ListPatIn ps)
230 ExplicitTuple es b -> mapP (\e -> checkPat e []) es `thenP` \ps ->
231 returnP (TuplePatIn ps b)
233 RecordCon c fs -> mapP checkPatField fs `thenP` \fs ->
234 returnP (RecPatIn c fs)
236 HsType ty -> returnP (TypePatIn ty)
239 checkPat _ _ = patFail
241 checkPatField :: (RdrName, RdrNameHsExpr, Bool)
242 -> P (RdrName, RdrNamePat, Bool)
243 checkPatField (n,e,b) =
244 checkPat e [] `thenP` \p ->
247 patFail = parseError "Parse error in pattern"
250 ---------------------------------------------------------------------------
251 -- Check Equation Syntax
255 -> Maybe RdrNameHsType
260 checkValDef lhs opt_sig grhss loc
261 = case isFunLhs lhs [] of
263 checkPatterns loc es `thenP` \ps ->
264 returnP (RdrValBinding (FunMonoBind f inf [Match ps opt_sig grhss] loc))
267 checkPattern loc lhs `thenP` \lhs ->
268 returnP (RdrValBinding (PatMonoBind lhs grhss loc))
275 checkValSig (HsVar v) ty loc = returnP (RdrSig (Sig v ty loc))
276 checkValSig other ty loc = parseError "Type signature given for an expression"
279 -- A variable binding is parsed as an RdrNameFunMonoBind.
280 -- See comments with HsBinds.MonoBinds
282 isFunLhs :: RdrNameHsExpr -> [RdrNameHsExpr] -> Maybe (RdrName, Bool, [RdrNameHsExpr])
283 isFunLhs (OpApp l (HsVar op) fix r) es | not (isRdrDataCon op)
284 = Just (op, True, (l:r:es))
286 = case isFunLhs l es of
287 Just (op', True, j : k : es') ->
288 Just (op', True, j : OpApp k (HsVar op) fix r : es')
290 isFunLhs (HsVar f) es | not (isRdrDataCon f)
292 isFunLhs (HsApp f e) es = isFunLhs f (e:es)
293 isFunLhs (HsPar e) es@(_:_) = isFunLhs e es
294 isFunLhs _ _ = Nothing
296 ---------------------------------------------------------------------------
297 -- Miscellaneous utilities
299 checkPrec :: Integer -> P ()
300 checkPrec i | 0 <= i && i <= 9 = returnP ()
301 | otherwise = parseError "Precedence out of range"
305 -> RdrNameHsRecordBinds
308 mkRecConstrOrUpdate (HsVar c) fs | isRdrDataCon c
309 = returnP (RecordCon c fs)
310 mkRecConstrOrUpdate exp fs@(_:_)
311 = returnP (RecordUpd exp fs)
312 mkRecConstrOrUpdate _ _
313 = parseError "Empty record update"
315 -----------------------------------------------------------------------------
316 -- utilities for foreign declarations
318 -- supported calling conventions
320 data CallConv = CCall CCallConv -- ccall or stdcall
323 -- construct a foreign import declaration
327 -> (FAST_STRING, RdrName, RdrNameHsType)
330 mkImport (CCall cconv) safety (entity, v, ty) loc =
331 parseCImport entity cconv safety v `thenP` \importSpec ->
332 returnP $ ForD (ForeignImport v ty importSpec False loc)
333 mkImport (DNCall ) _ (entity, v, ty) loc =
334 returnP $ ForD (ForeignImport v ty (DNImport (DNCallSpec entity)) False loc)
336 -- parse the entity string of a foreign import declaration for the `ccall' or
337 -- `stdcall' calling convention'
339 parseCImport :: FAST_STRING
344 parseCImport entity cconv safety v
345 -- FIXME: we should allow white space around `dynamic' and `wrapper' -=chak
346 | entity == SLIT ("dynamic") =
347 returnP $ CImport cconv safety _NIL_ _NIL_ (CFunction DynamicTarget)
348 | entity == SLIT ("wrapper") =
349 returnP $ CImport cconv safety _NIL_ _NIL_ CWrapper
350 | otherwise = parse0 (_UNPK_ entity)
352 -- using the static keyword?
353 parse0 (' ': rest) = parse0 rest
354 parse0 ('s':'t':'a':'t':'i':'c':rest) = parse1 rest
355 parse0 rest = parse1 rest
356 -- check for header file name
357 parse1 "" = parse4 "" _NIL_ False _NIL_
358 parse1 (' ':rest) = parse1 rest
359 parse1 str@('&':_ ) = parse2 str _NIL_
360 parse1 str@('[':_ ) = parse3 str _NIL_ False
362 | ".h" `isSuffixOf` first = parse2 rest (_PK_ first)
363 | otherwise = parse4 str _NIL_ False _NIL_
365 (first, rest) = break (\c -> c == ' ' || c == '&' || c == '[') str
366 -- check for address operator (indicating a label import)
367 parse2 "" header = parse4 "" header False _NIL_
368 parse2 (' ':rest) header = parse2 rest header
369 parse2 ('&':rest) header = parse3 rest header True
370 parse2 str@('[':_ ) header = parse3 str header False
371 parse2 str header = parse4 str header False _NIL_
372 -- check for library object name
373 parse3 (' ':rest) header isLbl = parse3 rest header isLbl
374 parse3 ('[':rest) header isLbl =
375 case break (== ']') rest of
376 (lib, ']':rest) -> parse4 rest header isLbl (_PK_ lib)
377 _ -> parseError "Missing ']' in entity"
378 parse3 str header isLbl = parse4 str header isLbl _NIL_
379 -- check for name of C function
380 parse4 "" header isLbl lib = build (mkExtName v) header isLbl lib
381 parse4 (' ':rest) header isLbl lib = parse4 rest header isLbl lib
382 parse4 str header isLbl lib
383 | all (== ' ') rest = build (_PK_ first) header isLbl lib
384 | otherwise = parseError "Malformed entity string"
386 (first, rest) = break (== ' ') str
388 build cid header False lib = returnP $
389 CImport cconv safety header lib (CFunction (StaticTarget cid))
390 build cid header True lib = returnP $
391 CImport cconv safety header lib (CLabel cid )
393 -- construct a foreign export declaration
396 -> (FAST_STRING, RdrName, RdrNameHsType)
399 mkExport (CCall cconv) (entity, v, ty) loc = returnP $
400 ForD (ForeignExport v ty (CExport (CExportStatic entity' cconv)) False loc)
402 entity' | nullFastString entity = mkExtName v
404 mkExport DNCall (entity, v, ty) loc =
405 parseError "Foreign export is not yet supported for .NET"
407 -- Supplying the ext_name in a foreign decl is optional; if it
408 -- isn't there, the Haskell name is assumed. Note that no transformation
409 -- of the Haskell name is then performed, so if you foreign export (++),
410 -- it's external name will be "++". Too bad; it's important because we don't
411 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
412 -- (This is why we use occNameUserString.)
414 mkExtName :: RdrName -> CLabelString
415 mkExtName rdrNm = _PK_ (occNameUserString (rdrNameOcc rdrNm))
417 -----------------------------------------------------------------------------
418 -- group function bindings into equation groups
420 -- we assume the bindings are coming in reverse order, so we take the srcloc
421 -- from the *last* binding in the group as the srcloc for the whole group.
423 groupBindings :: [RdrBinding] -> RdrBinding
424 groupBindings binds = group Nothing binds
425 where group :: Maybe RdrNameMonoBinds -> [RdrBinding] -> RdrBinding
426 group (Just bind) [] = RdrValBinding bind
427 group Nothing [] = RdrNullBind
429 -- don't group together FunMonoBinds if they have
430 -- no arguments. This is necessary now that variable bindings
431 -- with no arguments are now treated as FunMonoBinds rather
432 -- than pattern bindings (tests/rename/should_fail/rnfail002).
433 group (Just (FunMonoBind f inf1 mtchs ignore_srcloc))
434 (RdrValBinding (FunMonoBind f' _
435 [mtch@(Match (_:_) _ _)] loc)
437 | f == f' = group (Just (FunMonoBind f inf1 (mtch:mtchs) loc)) binds
439 group (Just so_far) binds
440 = RdrValBinding so_far `RdrAndBindings` group Nothing binds
441 group Nothing (bind:binds)
443 RdrValBinding b@(FunMonoBind _ _ _ _) -> group (Just b) binds
444 other -> bind `RdrAndBindings` group Nothing binds