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