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