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