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