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