[project @ 2001-05-18 08:46:18 by simonpj]
[ghc-hetmet.git] / ghc / compiler / parser / ParseUtil.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1999
3 %
4 \section[ParseUtil]{Parser Utilities}
5
6 \begin{code}
7 module ParseUtil (
8           parseError            -- String -> Pa
9         , cbot                  -- a
10         , mkVanillaCon, mkRecCon,
11
12         , mkRecConstrOrUpdate   -- HsExp -> [HsFieldUpdate] -> P HsExp
13         , groupBindings
14         
15         , mkExtName             -- Maybe ExtName -> RdrName -> ExtName
16
17         , checkPrec             -- String -> P String
18         , checkContext          -- HsType -> P HsContext
19         , checkInstType         -- HsType -> P HsType
20         , checkDataHeader       -- HsQualType -> P (HsContext,HsName,[HsName])
21         , checkSimple           -- HsType -> [HsName] -> P ((HsName,[HsName]))
22         , checkPattern          -- HsExp -> P HsPat
23         , checkPatterns         -- SrcLoc -> [HsExp] -> P [HsPat]
24         , checkDo               -- [HsStmt] -> P [HsStmt]
25         , checkValDef           -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
26         , checkValSig           -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
27  ) where
28
29 #include "HsVersions.h"
30
31 import Lex
32 import HsSyn            -- Lots of it
33 import SrcLoc
34 import RdrHsSyn         ( RdrBinding(..),
35                           RdrNameHsType, RdrNameBangType, RdrNameContext,
36                           RdrNameHsTyVar, RdrNamePat, RdrNameHsExpr, RdrNameGRHSs,
37                           RdrNameHsRecordBinds, RdrNameMonoBinds, RdrNameConDetails
38                         )
39 import RdrName
40 import PrelNames        ( unitTyCon_RDR )
41 import CallConv
42 import OccName          ( dataName, varName, tcClsName,
43                           occNameSpace, setOccNameSpace, occNameUserString )
44 import FastString       ( unpackFS )
45 import UniqFM           ( UniqFM, listToUFM )
46 import Outputable
47
48 -----------------------------------------------------------------------------
49 -- Misc utils
50
51 parseError :: String -> P a
52 parseError s = 
53   getSrcLocP `thenP` \ loc ->
54   failMsgP (hcat [ppr loc, text ": ", text s])
55
56 cbot = panic "CCall:result_ty"
57
58 -----------------------------------------------------------------------------
59 -- mkVanillaCon
60
61 -- When parsing data declarations, we sometimes inadvertently parse
62 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
63 -- This function splits up the type application, adds any pending
64 -- arguments, and converts the type constructor back into a data constructor.
65
66 mkVanillaCon :: RdrNameHsType -> [RdrNameBangType] -> P (RdrName, RdrNameConDetails)
67
68 mkVanillaCon ty tys
69  = split ty tys
70  where
71    split (HsAppTy t u)  ts = split t (unbangedType u : ts)
72    split (HsTyVar tc)   ts = tyConToDataCon tc  `thenP` \ data_con ->
73                              returnP (data_con, VanillaCon ts)
74    split _               _ = parseError "Illegal data/newtype declaration"
75
76 mkRecCon :: RdrName -> [([RdrName],RdrNameBangType)] -> P (RdrName, RdrNameConDetails)
77 mkRecCon con fields
78   = tyConToDataCon con  `thenP` \ data_con ->
79     returnP (data_con, RecCon fields)
80
81 tyConToDataCon :: RdrName -> P RdrName
82 tyConToDataCon tc
83   | occNameSpace tc_occ == tcClsName
84   = returnP (setRdrNameOcc tc (setOccNameSpace tc_occ dataName))
85   | otherwise
86   = parseError (showSDoc (text "not a constructor:" <+> quotes (ppr tc)))
87   where 
88     tc_occ   = rdrNameOcc tc
89
90
91 ----------------------------------------------------------------------------
92 -- Various Syntactic Checks
93
94 callConvFM :: UniqFM CallConv
95 callConvFM = listToUFM $
96       map (\ (x,y) -> (_PK_ x,y))
97      [  ("stdcall",  stdCallConv),
98         ("ccall",    cCallConv)
99 --      ("pascal",   pascalCallConv),
100 --      ("fastcall", fastCallConv)
101      ]
102
103 checkInstType :: RdrNameHsType -> P RdrNameHsType
104 checkInstType t 
105   = case t of
106         HsForAllTy tvs ctxt ty ->
107                 checkDictTy ty [] `thenP` \ dict_ty ->
108                 returnP (HsForAllTy tvs ctxt dict_ty)
109
110         ty ->   checkDictTy ty [] `thenP` \ dict_ty->
111                 returnP (HsForAllTy Nothing [] dict_ty)
112
113 checkContext :: RdrNameHsType -> P RdrNameContext
114 checkContext (HsTupleTy _ ts) 
115   = mapP (\t -> checkPred t []) ts `thenP` \ps ->
116     returnP ps
117 checkContext (HsTyVar t) -- empty contexts are allowed
118   | t == unitTyCon_RDR = returnP []
119 checkContext t 
120   = checkPred t [] `thenP` \p ->
121     returnP [p]
122
123 checkPred :: RdrNameHsType -> [RdrNameHsType] 
124         -> P (HsPred RdrName)
125 checkPred (HsTyVar t) args@(_:_) | not (isRdrTyVar t) 
126         = returnP (HsClassP t args)
127 checkPred (HsAppTy l r) args = checkPred l (r:args)
128 checkPred (HsPredTy (HsIParam n ty)) [] = returnP (HsIParam n ty)
129 checkPred _ _ = parseError "Illegal class assertion"
130
131 checkDictTy :: RdrNameHsType -> [RdrNameHsType] -> P RdrNameHsType
132 checkDictTy (HsTyVar t) args@(_:_) | not (isRdrTyVar t) 
133         = returnP (mkHsDictTy t args)
134 checkDictTy (HsAppTy l r) args = checkDictTy l (r:args)
135 checkDictTy _ _ = parseError "Malformed context in instance header"
136
137 -- Put more comments!
138 -- Checks that the lhs of a datatype declaration
139 -- is of the form Context => T a b ... z
140 checkDataHeader :: RdrNameHsType 
141         -> P (RdrNameContext, RdrName, [RdrNameHsTyVar])
142
143 checkDataHeader (HsForAllTy Nothing cs t) =
144    checkSimple t []          `thenP` \(c,ts) ->
145    returnP (cs,c,map UserTyVar ts)
146 checkDataHeader t =
147    checkSimple t []          `thenP` \(c,ts) ->
148    returnP ([],c,map UserTyVar ts)
149
150 -- Checks the type part of the lhs of a datatype declaration
151 checkSimple :: RdrNameHsType -> [RdrName] -> P ((RdrName,[RdrName]))
152 checkSimple (HsAppTy l (HsTyVar a)) xs | isRdrTyVar a 
153    = checkSimple l (a:xs)
154 checkSimple (HsTyVar tycon) xs | not (isRdrTyVar tycon) = returnP (tycon,xs)
155
156 checkSimple (HsOpTy (HsTyVar t1) tycon (HsTyVar t2)) [] 
157   | not (isRdrTyVar tycon) && isRdrTyVar t1 && isRdrTyVar t2
158   = returnP (tycon,[t1,t2])
159
160 checkSimple t _ = parseError "Illegal left hand side in data/newtype declaration"
161
162 ---------------------------------------------------------------------------
163 -- Checking statements in a do-expression
164 --      We parse   do { e1 ; e2 ; }
165 --      as [ExprStmt e1, ExprStmt e2]
166 -- checkDo (a) checks that the last thing is an ExprStmt
167 --         (b) transforms it to a ResultStmt
168
169 checkDo []             = parseError "Empty 'do' construct"
170 checkDo [ExprStmt e l] = returnP [ResultStmt e l]
171 checkDo [s]            = parseError "The last statment in a 'do' construct must be an expression"
172 checkDo (s:ss)         = checkDo ss     `thenP` \ ss' ->
173                          returnP (s:ss')
174
175 ---------------------------------------------------------------------------
176 -- Checking Patterns.
177
178 -- We parse patterns as expressions and check for valid patterns below,
179 -- converting the expression into a pattern at the same time.
180
181 checkPattern :: SrcLoc -> RdrNameHsExpr -> P RdrNamePat
182 checkPattern loc e = setSrcLocP loc (checkPat e [])
183
184 checkPatterns :: SrcLoc -> [RdrNameHsExpr] -> P [RdrNamePat]
185 checkPatterns loc es = mapP (checkPattern loc) es
186
187 checkPat :: RdrNameHsExpr -> [RdrNamePat] -> P RdrNamePat
188 checkPat (HsVar c) args | isRdrDataCon c = returnP (ConPatIn c args)
189 checkPat (HsApp f x) args = 
190         checkPat x [] `thenP` \x ->
191         checkPat f (x:args)
192 checkPat e [] = case e of
193         EWildPat           -> returnP WildPatIn
194         HsVar x            -> returnP (VarPatIn x)
195         HsLit l            -> returnP (LitPatIn l)
196         HsOverLit l        -> returnP (NPatIn l)
197         ELazyPat e         -> checkPat e [] `thenP` (returnP . LazyPatIn)
198         EAsPat n e         -> checkPat e [] `thenP` (returnP . AsPatIn n)
199         ExprWithTySig e t  -> checkPat e [] `thenP` \e ->
200                               -- Pattern signatures are parsed as sigtypes,
201                               -- but they aren't explicit forall points.  Hence
202                               -- we have to remove the implicit forall here.
203                               let t' = case t of 
204                                           HsForAllTy Nothing [] ty -> ty
205                                           other -> other
206                               in
207                               returnP (SigPatIn e t')
208
209         OpApp (HsVar n) (HsVar plus) _ (HsOverLit lit@(HsIntegral k)) 
210                            | plus == plus_RDR
211                            -> returnP (NPlusKPatIn n lit)
212                            where
213                               plus_RDR = mkUnqual varName SLIT("+")     -- Hack
214
215         OpApp l op fix r   -> checkPat l [] `thenP` \l ->
216                               checkPat r [] `thenP` \r ->
217                               case op of
218                                  HsVar c -> returnP (ConOpPatIn l c fix r)
219                                  _ -> patFail
220
221         HsPar e            -> checkPat e [] `thenP` (returnP . ParPatIn)
222         ExplicitList es    -> mapP (\e -> checkPat e []) es `thenP` \ps ->
223                               returnP (ListPatIn ps)
224
225         ExplicitTuple es b -> mapP (\e -> checkPat e []) es `thenP` \ps ->
226                               returnP (TuplePatIn ps b)
227
228         RecordCon c fs     -> mapP checkPatField fs `thenP` \fs ->
229                               returnP (RecPatIn c fs)
230 -- Generics 
231         HsType ty          -> returnP (TypePatIn ty) 
232         _ -> patFail
233
234 checkPat _ _ = patFail
235
236 checkPatField :: (RdrName, RdrNameHsExpr, Bool) 
237         -> P (RdrName, RdrNamePat, Bool)
238 checkPatField (n,e,b) =
239         checkPat e [] `thenP` \p ->
240         returnP (n,p,b)
241
242 patFail = parseError "Parse error in pattern"
243
244
245 ---------------------------------------------------------------------------
246 -- Check Equation Syntax
247
248 checkValDef 
249         :: RdrNameHsExpr
250         -> Maybe RdrNameHsType
251         -> RdrNameGRHSs
252         -> SrcLoc
253         -> P RdrBinding
254
255 checkValDef lhs opt_sig grhss loc
256  = case isFunLhs lhs [] of
257            Just (f,inf,es) -> 
258                 checkPatterns loc es `thenP` \ps ->
259                 returnP (RdrValBinding (FunMonoBind f inf [Match [] ps opt_sig grhss] loc))
260
261            Nothing ->
262                 checkPattern loc lhs `thenP` \lhs ->
263                 returnP (RdrValBinding (PatMonoBind lhs grhss loc))
264
265 checkValSig
266         :: RdrNameHsExpr
267         -> RdrNameHsType
268         -> SrcLoc
269         -> P RdrBinding
270 checkValSig (HsVar v) ty loc = returnP (RdrSig (Sig v ty loc))
271 checkValSig other     ty loc = parseError "Type signature given for an expression"
272
273
274 -- A variable binding is parsed as an RdrNameFunMonoBind.
275 -- See comments with HsBinds.MonoBinds
276
277 isFunLhs :: RdrNameHsExpr -> [RdrNameHsExpr] -> Maybe (RdrName, Bool, [RdrNameHsExpr])
278 isFunLhs (OpApp l (HsVar op) fix r) es  | not (isRdrDataCon op)
279                                 = Just (op, True, (l:r:es))
280                                         | otherwise
281                                 = case isFunLhs l es of
282                                     Just (op', True, j : k : es') ->
283                                       Just (op', True, j : OpApp k (HsVar op) fix r : es')
284                                     _ -> Nothing
285 isFunLhs (HsVar f) es | not (isRdrDataCon f)
286                                 = Just (f,False,es)
287 isFunLhs (HsApp f e) es         = isFunLhs f (e:es)
288 isFunLhs (HsPar e)   es         = isFunLhs e es
289 isFunLhs _ _                    = Nothing
290
291 ---------------------------------------------------------------------------
292 -- Miscellaneous utilities
293
294 checkPrec :: Integer -> P ()
295 checkPrec i | 0 <= i && i <= 9 = returnP ()
296             | otherwise        = parseError "precedence out of range"
297
298 mkRecConstrOrUpdate 
299         :: RdrNameHsExpr 
300         -> RdrNameHsRecordBinds
301         -> P RdrNameHsExpr
302
303 mkRecConstrOrUpdate (HsVar c) fs | isRdrDataCon c
304   = returnP (RecordCon c fs)
305 mkRecConstrOrUpdate exp fs@(_:_) 
306   = returnP (RecordUpd exp fs)
307 mkRecConstrOrUpdate _ _
308   = parseError "Empty record update"
309
310 -- Supplying the ext_name in a foreign decl is optional ; if it
311 -- isn't there, the Haskell name is assumed. Note that no transformation
312 -- of the Haskell name is then performed, so if you foreign export (++),
313 -- it's external name will be "++". Too bad; it's important because we don't
314 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
315 -- (This is why we use occNameUserString.)
316
317 mkExtName :: Maybe ExtName -> RdrName -> ExtName
318 mkExtName Nothing rdrNm = ExtName (_PK_ (occNameUserString (rdrNameOcc rdrNm)))
319                                   Nothing
320 mkExtName (Just x) _    = x
321
322 -----------------------------------------------------------------------------
323 -- group function bindings into equation groups
324
325 -- we assume the bindings are coming in reverse order, so we take the srcloc
326 -- from the *last* binding in the group as the srcloc for the whole group.
327
328 groupBindings :: [RdrBinding] -> RdrBinding
329 groupBindings binds = group Nothing binds
330   where group :: Maybe RdrNameMonoBinds -> [RdrBinding] -> RdrBinding
331         group (Just bind) [] = RdrValBinding bind
332         group Nothing [] = RdrNullBind
333
334                 -- don't group together FunMonoBinds if they have
335                 -- no arguments.  This is necessary now that variable bindings
336                 -- with no arguments are now treated as FunMonoBinds rather
337                 -- than pattern bindings (tests/rename/should_fail/rnfail002).
338         group (Just (FunMonoBind f inf1 mtchs ignore_srcloc))
339                     (RdrValBinding (FunMonoBind f' _ 
340                                         [mtch@(Match _ (_:_) _ _)] loc)
341                         : binds)
342             | f == f' = group (Just (FunMonoBind f inf1 (mtch:mtchs) loc)) binds
343
344         group (Just so_far) binds
345             = RdrValBinding so_far `RdrAndBindings` group Nothing binds
346         group Nothing (bind:binds)
347             = case bind of
348                 RdrValBinding b@(FunMonoBind _ _ _ _) -> group (Just b) binds
349                 other -> bind `RdrAndBindings` group Nothing binds
350 \end{code}