[project @ 2002-06-07 07:16:04 by chak]
[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         , mkIfaceExports      -- :: [RdrNameTyClDecl] -> [RdrExportItem]
15
16         , CallConv(..)
17         , mkImport            -- CallConv -> Safety 
18                               -- -> (FastString, RdrName, RdrNameHsType)
19                               -- -> SrcLoc 
20                               -- -> P RdrNameHsDecl
21         , mkExport            -- CallConv
22                               -- -> (FastString, RdrName, RdrNameHsType)
23                               -- -> SrcLoc 
24                               -- -> P RdrNameHsDecl
25         , mkExtName           -- RdrName -> CLabelString
26                               
27         , checkPrec           -- String -> P String
28         , checkContext        -- HsType -> P HsContext
29         , checkPred           -- HsType -> P HsPred
30         , checkTyVars         -- [HsTyVar] -> P [HsType]
31         , checkTyClHdr        -- HsType -> (name,[tyvar])
32         , checkInstType       -- HsType -> P HsType
33         , checkPattern        -- HsExp -> P HsPat
34         , checkPatterns       -- SrcLoc -> [HsExp] -> P [HsPat]
35         , checkDo             -- [Stmt] -> P [Stmt]
36         , checkValDef         -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
37         , checkValSig         -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
38  ) where
39
40 #include "HsVersions.h"
41
42 import List             ( isSuffixOf )
43
44 import Lex
45 import HscTypes         ( RdrAvailInfo, GenAvailInfo(..) )
46 import HsSyn            -- Lots of it
47 import ForeignCall      ( CCallConv, Safety, CCallTarget(..), CExportSpec(..),
48                           DNCallSpec(..))
49 import SrcLoc
50 import RdrHsSyn
51 import RdrName
52 import PrelNames        ( unitTyCon_RDR )
53 import OccName          ( dataName, varName, tcClsName, isDataOcc,
54                           occNameSpace, setOccNameSpace, occNameUserString )
55 import CStrings         ( CLabelString )
56 import FastString
57 import Outputable
58
59 -----------------------------------------------------------------------------
60 -- Misc utils
61
62 parseError :: String -> P a
63 parseError s = 
64   getSrcLocP `thenP` \ loc ->
65   failMsgP (hcat [ppr loc, text ": ", text s])
66
67
68 -----------------------------------------------------------------------------
69 -- mkVanillaCon
70
71 -- When parsing data declarations, we sometimes inadvertently parse
72 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
73 -- This function splits up the type application, adds any pending
74 -- arguments, and converts the type constructor back into a data constructor.
75
76 mkVanillaCon :: RdrNameHsType -> [RdrNameBangType] -> P (RdrName, RdrNameConDetails)
77
78 mkVanillaCon ty tys
79  = split ty tys
80  where
81    split (HsAppTy t u)  ts = split t (unbangedType u : ts)
82    split (HsTyVar tc)   ts = tyConToDataCon tc  `thenP` \ data_con ->
83                              returnP (data_con, VanillaCon ts)
84    split _               _ = parseError "Illegal data/newtype declaration"
85
86 mkRecCon :: RdrName -> [([RdrName],RdrNameBangType)] -> P (RdrName, RdrNameConDetails)
87 mkRecCon con fields
88   = tyConToDataCon con  `thenP` \ data_con ->
89     returnP (data_con, RecCon fields)
90
91 tyConToDataCon :: RdrName -> P RdrName
92 tyConToDataCon tc
93   | occNameSpace tc_occ == tcClsName
94   = returnP (setRdrNameOcc tc (setOccNameSpace tc_occ dataName))
95   | otherwise
96   = parseError (showSDoc (text "Not a constructor:" <+> quotes (ppr tc)))
97   where 
98     tc_occ   = rdrNameOcc tc
99
100
101 ----------------------------------------------------------------------------
102 -- Various Syntactic Checks
103
104 checkInstType :: RdrNameHsType -> P RdrNameHsType
105 checkInstType t 
106   = case t of
107         HsForAllTy tvs ctxt ty ->
108                 checkDictTy ty [] `thenP` \ dict_ty ->
109                 returnP (HsForAllTy tvs ctxt dict_ty)
110
111         HsParTy ty -> checkInstType ty
112
113         ty ->   checkDictTy ty [] `thenP` \ dict_ty->
114                 returnP (HsForAllTy Nothing [] dict_ty)
115
116 checkTyVars :: [RdrNameHsType] -> P [RdrNameHsTyVar]
117 checkTyVars tvs = mapP chk tvs
118                 where
119                   chk (HsKindSig (HsTyVar tv) k) = returnP (IfaceTyVar tv k)
120                   chk (HsTyVar tv)               = returnP (UserTyVar tv)
121                   chk other                      = parseError "Type found where type variable expected"
122
123 checkTyClHdr :: RdrNameHsType -> P (RdrName, [RdrNameHsTyVar])
124 -- The header of a type or class decl should look like
125 --      (C a, D b) => T a b
126 -- or   T a b
127 -- or   a + b
128 -- etc
129 checkTyClHdr ty
130   = go ty []
131   where
132     go (HsTyVar tc)    acc 
133         | not (isRdrTyVar tc) = checkTyVars acc         `thenP` \ tvs ->
134                                 returnP (tc, tvs)
135     go (HsOpTy t1 (HsTyOp tc) t2) acc  
136                               = checkTyVars (t1:t2:acc) `thenP` \ tvs ->
137                                 returnP (tc, tvs)
138     go (HsParTy ty)    acc    = go ty acc
139     go (HsAppTy t1 t2) acc    = go t1 (t2:acc)
140     go other           acc    = parseError "Malformed LHS to type of class declaration"
141
142 checkContext :: RdrNameHsType -> P RdrNameContext
143 checkContext (HsTupleTy _ ts)   -- (Eq a, Ord b) shows up as a tuple type
144   = mapP checkPred ts
145
146 checkContext (HsParTy ty)       -- to be sure HsParTy doesn't get into the way
147   = checkContext ty
148
149 checkContext (HsTyVar t)        -- Empty context shows up as a unit type ()
150   | t == unitTyCon_RDR = returnP []
151
152 checkContext t 
153   = checkPred t `thenP` \p ->
154     returnP [p]
155
156 checkPred :: RdrNameHsType -> P (HsPred RdrName)
157 -- Watch out.. in ...deriving( Show )... we use checkPred on 
158 -- the list of partially applied predicates in the deriving,
159 -- so there can be zero args.
160 checkPred (HsPredTy (HsIParam n ty)) = returnP (HsIParam n ty)
161 checkPred ty
162   = go ty []
163   where
164     go (HsTyVar t) args   | not (isRdrTyVar t) 
165                           = returnP (HsClassP t args)
166     go (HsAppTy l r) args = go l (r:args)
167     go (HsParTy t)   args = go t args
168     go _             _    = parseError "Illegal class assertion"
169
170 checkDictTy :: RdrNameHsType -> [RdrNameHsType] -> P RdrNameHsType
171 checkDictTy (HsTyVar t) args@(_:_) | not (isRdrTyVar t) 
172         = returnP (mkHsDictTy t args)
173 checkDictTy (HsAppTy l r) args = checkDictTy l (r:args)
174 checkDictTy (HsParTy t)   args = checkDictTy t args
175 checkDictTy _ _ = parseError "Malformed context in instance header"
176
177
178 ---------------------------------------------------------------------------
179 -- Checking statements in a do-expression
180 --      We parse   do { e1 ; e2 ; }
181 --      as [ExprStmt e1, ExprStmt e2]
182 -- checkDo (a) checks that the last thing is an ExprStmt
183 --         (b) transforms it to a ResultStmt
184
185 checkDo []               = parseError "Empty 'do' construct"
186 checkDo [ExprStmt e _ l] = returnP [ResultStmt e l]
187 checkDo [s]              = parseError "The last statement in a 'do' construct must be an expression"
188 checkDo (s:ss)           = checkDo ss   `thenP` \ ss' ->
189                            returnP (s:ss')
190
191 ---------------------------------------------------------------------------
192 -- Checking Patterns.
193
194 -- We parse patterns as expressions and check for valid patterns below,
195 -- converting the expression into a pattern at the same time.
196
197 checkPattern :: SrcLoc -> RdrNameHsExpr -> P RdrNamePat
198 checkPattern loc e = setSrcLocP loc (checkPat e [])
199
200 checkPatterns :: SrcLoc -> [RdrNameHsExpr] -> P [RdrNamePat]
201 checkPatterns loc es = mapP (checkPattern loc) es
202
203 checkPat :: RdrNameHsExpr -> [RdrNamePat] -> P RdrNamePat
204 checkPat (HsVar c) args | isRdrDataCon c = returnP (ConPatIn c args)
205 checkPat (HsApp f x) args = 
206         checkPat x [] `thenP` \x ->
207         checkPat f (x:args)
208 checkPat e [] = case e of
209         EWildPat           -> returnP WildPatIn
210         HsVar x            -> returnP (VarPatIn x)
211         HsLit l            -> returnP (LitPatIn l)
212         HsOverLit l        -> returnP (NPatIn l Nothing)
213         ELazyPat e         -> checkPat e [] `thenP` (returnP . LazyPatIn)
214         EAsPat n e         -> checkPat e [] `thenP` (returnP . AsPatIn n)
215         ExprWithTySig e t  -> checkPat e [] `thenP` \e ->
216                               -- Pattern signatures are parsed as sigtypes,
217                               -- but they aren't explicit forall points.  Hence
218                               -- we have to remove the implicit forall here.
219                               let t' = case t of 
220                                           HsForAllTy Nothing [] ty -> ty
221                                           other -> other
222                               in
223                               returnP (SigPatIn e t')
224
225         -- Translate out NegApps of literals in patterns. We negate
226         -- the Integer here, and add back the call to 'negate' when
227         -- we typecheck the pattern.
228         -- NB. Negative *primitive* literals are already handled by
229         --     RdrHsSyn.mkHsNegApp
230         NegApp (HsOverLit lit) neg -> returnP (NPatIn lit (Just neg))
231
232         OpApp (HsVar n) (HsVar plus) _ (HsOverLit lit@(HsIntegral _ _)) 
233                            | plus == plus_RDR
234                            -> returnP (mkNPlusKPat n lit)
235                            where
236                               plus_RDR = mkUnqual varName FSLIT("+")    -- Hack
237
238         OpApp l op fix r   -> checkPat l [] `thenP` \l ->
239                               checkPat r [] `thenP` \r ->
240                               case op of
241                                  HsVar c | isDataOcc (rdrNameOcc c)
242                                         -> returnP (ConOpPatIn l c fix r)
243                                  _ -> patFail
244
245         HsPar e            -> checkPat e [] `thenP` (returnP . ParPatIn)
246         ExplicitList _ es  -> mapP (\e -> checkPat e []) es `thenP` \ps ->
247                               returnP (ListPatIn ps)
248         ExplicitPArr _ es  -> mapP (\e -> checkPat e []) es `thenP` \ps ->
249                               returnP (PArrPatIn ps)
250
251         ExplicitTuple es b -> mapP (\e -> checkPat e []) es `thenP` \ps ->
252                               returnP (TuplePatIn ps b)
253
254         RecordCon c fs     -> mapP checkPatField fs `thenP` \fs ->
255                               returnP (RecPatIn c fs)
256 -- Generics 
257         HsType ty          -> returnP (TypePatIn ty) 
258         _                  -> patFail
259
260 checkPat _ _ = patFail
261
262 checkPatField :: (RdrName, RdrNameHsExpr, Bool) 
263         -> P (RdrName, RdrNamePat, Bool)
264 checkPatField (n,e,b) =
265         checkPat e [] `thenP` \p ->
266         returnP (n,p,b)
267
268 patFail = parseError "Parse error in pattern"
269
270
271 ---------------------------------------------------------------------------
272 -- Check Equation Syntax
273
274 checkValDef 
275         :: RdrNameHsExpr
276         -> Maybe RdrNameHsType
277         -> RdrNameGRHSs
278         -> SrcLoc
279         -> P RdrBinding
280
281 checkValDef lhs opt_sig grhss loc
282  = case isFunLhs lhs [] of
283            Just (f,inf,es) -> 
284                 checkPatterns loc es `thenP` \ps ->
285                 returnP (RdrValBinding (FunMonoBind f inf [Match ps opt_sig grhss] loc))
286
287            Nothing ->
288                 checkPattern loc lhs `thenP` \lhs ->
289                 returnP (RdrValBinding (PatMonoBind lhs grhss loc))
290
291 checkValSig
292         :: RdrNameHsExpr
293         -> RdrNameHsType
294         -> SrcLoc
295         -> P RdrBinding
296 checkValSig (HsVar v) ty loc = returnP (RdrSig (Sig v ty loc))
297 checkValSig other     ty loc = parseError "Type signature given for an expression"
298
299
300 -- A variable binding is parsed as an RdrNameFunMonoBind.
301 -- See comments with HsBinds.MonoBinds
302
303 isFunLhs :: RdrNameHsExpr -> [RdrNameHsExpr] -> Maybe (RdrName, Bool, [RdrNameHsExpr])
304 isFunLhs (OpApp l (HsVar op) fix r) es  | not (isRdrDataCon op)
305                                 = Just (op, True, (l:r:es))
306                                         | otherwise
307                                 = case isFunLhs l es of
308                                     Just (op', True, j : k : es') ->
309                                       Just (op', True, j : OpApp k (HsVar op) fix r : es')
310                                     _ -> Nothing
311 isFunLhs (HsVar f) es | not (isRdrDataCon f)
312                                 = Just (f,False,es)
313 isFunLhs (HsApp f e) es         = isFunLhs f (e:es)
314 isFunLhs (HsPar e)   es@(_:_)   = isFunLhs e es
315 isFunLhs _ _                    = Nothing
316
317 ---------------------------------------------------------------------------
318 -- Miscellaneous utilities
319
320 checkPrec :: Integer -> P ()
321 checkPrec i | 0 <= i && i <= 9 = returnP ()
322             | otherwise        = parseError "Precedence out of range"
323
324 mkRecConstrOrUpdate 
325         :: RdrNameHsExpr 
326         -> RdrNameHsRecordBinds
327         -> P RdrNameHsExpr
328
329 mkRecConstrOrUpdate (HsVar c) fs | isRdrDataCon c
330   = returnP (RecordCon c fs)
331 mkRecConstrOrUpdate exp fs@(_:_) 
332   = returnP (RecordUpd exp fs)
333 mkRecConstrOrUpdate _ _
334   = parseError "Empty record update"
335
336 -----------------------------------------------------------------------------
337 -- utilities for foreign declarations
338
339 -- supported calling conventions
340 --
341 data CallConv = CCall  CCallConv        -- ccall or stdcall
342               | DNCall                  -- .NET
343
344 -- construct a foreign import declaration
345 --
346 mkImport :: CallConv 
347          -> Safety 
348          -> (FastString, RdrName, RdrNameHsType) 
349          -> SrcLoc 
350          -> P RdrNameHsDecl
351 mkImport (CCall  cconv) safety (entity, v, ty) loc =
352   parseCImport entity cconv safety v                     `thenP` \importSpec ->
353   returnP $ ForD (ForeignImport v ty importSpec                     False loc)
354 mkImport (DNCall      ) _      (entity, v, ty) loc =
355   returnP $ ForD (ForeignImport v ty (DNImport (DNCallSpec entity)) False loc)
356
357 -- parse the entity string of a foreign import declaration for the `ccall' or
358 -- `stdcall' calling convention'
359 --
360 parseCImport :: FastString 
361              -> CCallConv 
362              -> Safety 
363              -> RdrName 
364              -> P ForeignImport
365 parseCImport entity cconv safety v
366   -- FIXME: we should allow white space around `dynamic' and `wrapper' -=chak
367   | entity == FSLIT ("dynamic") = 
368     returnP $ CImport cconv safety nilFS nilFS (CFunction DynamicTarget)
369   | entity == FSLIT ("wrapper") =
370     returnP $ CImport cconv safety nilFS nilFS CWrapper
371   | otherwise                  = parse0 (unpackFS entity)
372     where
373       -- using the static keyword?
374       parse0 (' ':                    rest) = parse0 rest
375       parse0 ('s':'t':'a':'t':'i':'c':rest) = parse1 rest
376       parse0                          rest  = parse1 rest
377       -- check for header file name
378       parse1     ""               = parse4 ""    nilFS        False nilFS
379       parse1     (' ':rest)       = parse1 rest
380       parse1 str@('&':_   )       = parse2 str   nilFS
381       parse1 str@('[':_   )       = parse3 str   nilFS        False
382       parse1 str
383         | ".h" `isSuffixOf` first = parse2 rest  (mkFastString first)
384         | otherwise               = parse4 str   nilFS        False nilFS
385         where
386           (first, rest) = break (\c -> c == ' ' || c == '&' || c == '[') str
387       -- check for address operator (indicating a label import)
388       parse2     ""         header = parse4 ""   header False nilFS
389       parse2     (' ':rest) header = parse2 rest header
390       parse2     ('&':rest) header = parse3 rest header True
391       parse2 str@('[':_   ) header = parse3 str  header False
392       parse2 str            header = parse4 str  header False nilFS
393       -- check for library object name
394       parse3 (' ':rest) header isLbl = parse3 rest header isLbl
395       parse3 ('[':rest) header isLbl = 
396         case break (== ']') rest of 
397           (lib, ']':rest)           -> parse4 rest header isLbl (mkFastString lib)
398           _                         -> parseError "Missing ']' in entity"
399       parse3 str        header isLbl = parse4 str  header isLbl nilFS
400       -- check for name of C function
401       parse4 ""         header isLbl lib = build (mkExtName v) header isLbl lib
402       parse4 (' ':rest) header isLbl lib = parse4 rest         header isLbl lib
403       parse4 str        header isLbl lib
404         | all (== ' ') rest              = build (mkFastString first)  header isLbl lib
405         | otherwise                      = parseError "Malformed entity string"
406         where
407           (first, rest) = break (== ' ') str
408       --
409       build cid header False lib = returnP $
410         CImport cconv safety header lib (CFunction (StaticTarget cid))
411       build cid header True  lib = returnP $
412         CImport cconv safety header lib (CLabel                  cid )
413
414 -- construct a foreign export declaration
415 --
416 mkExport :: CallConv
417          -> (FastString, RdrName, RdrNameHsType) 
418          -> SrcLoc 
419          -> P RdrNameHsDecl
420 mkExport (CCall  cconv) (entity, v, ty) loc = returnP $ 
421   ForD (ForeignExport v ty (CExport (CExportStatic entity' cconv)) False loc)
422   where
423     entity' | nullFastString entity = mkExtName v
424             | otherwise             = entity
425 mkExport DNCall (entity, v, ty) loc =
426   parseError "Foreign export is not yet supported for .NET"
427
428 -- Supplying the ext_name in a foreign decl is optional; if it
429 -- isn't there, the Haskell name is assumed. Note that no transformation
430 -- of the Haskell name is then performed, so if you foreign export (++),
431 -- it's external name will be "++". Too bad; it's important because we don't
432 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
433 -- (This is why we use occNameUserString.)
434 --
435 mkExtName :: RdrName -> CLabelString
436 mkExtName rdrNm = mkFastString (occNameUserString (rdrNameOcc rdrNm))
437
438 -----------------------------------------------------------------------------
439 -- group function bindings into equation groups
440
441 -- we assume the bindings are coming in reverse order, so we take the srcloc
442 -- from the *last* binding in the group as the srcloc for the whole group.
443
444 groupBindings :: [RdrBinding] -> RdrBinding
445 groupBindings binds = group Nothing binds
446   where group :: Maybe RdrNameMonoBinds -> [RdrBinding] -> RdrBinding
447         group (Just bind) [] = RdrValBinding bind
448         group Nothing [] = RdrNullBind
449
450                 -- don't group together FunMonoBinds if they have
451                 -- no arguments.  This is necessary now that variable bindings
452                 -- with no arguments are now treated as FunMonoBinds rather
453                 -- than pattern bindings (tests/rename/should_fail/rnfail002).
454         group (Just (FunMonoBind f inf1 mtchs ignore_srcloc))
455                     (RdrValBinding (FunMonoBind f' _ 
456                                         [mtch@(Match (_:_) _ _)] loc)
457                         : binds)
458             | f == f' = group (Just (FunMonoBind f inf1 (mtch:mtchs) loc)) binds
459
460         group (Just so_far) binds
461             = RdrValBinding so_far `RdrAndBindings` group Nothing binds
462         group Nothing (bind:binds)
463             = case bind of
464                 RdrValBinding b@(FunMonoBind _ _ _ _) -> group (Just b) binds
465                 other -> bind `RdrAndBindings` group Nothing binds
466
467 -- ---------------------------------------------------------------------------
468 -- Make the export list for an interface
469
470 mkIfaceExports :: [RdrNameTyClDecl] -> [RdrAvailInfo]
471 mkIfaceExports decls = map getExport decls
472   where getExport d = case d of
473                         TyData{}    -> tc_export
474                         ClassDecl{} -> tc_export
475                         _other      -> var_export
476           where 
477                 tc_export  = AvailTC (rdrNameOcc (tcdName d)) 
478                                 (map (rdrNameOcc.fst) (tyClDeclNames d))
479                 var_export = Avail (rdrNameOcc (tcdName d))
480 \end{code}