2 % (c) The AQUA Project, Glasgow University, 1996-1998
4 \section[RdrHsSyn]{Specialisations of the @HsSyn@ syntax for the reader}
6 (Well, really, for specialisations involving @RdrName@s, even if
7 they are used somewhat later on in the compiler...)
16 extractHsRhoRdrTyVars, extractGenericPatTyVars,
18 mkHsOpApp, mkClassDecl,
19 mkHsNegApp, mkHsIntegral, mkHsFractional,
20 mkHsDo, mkHsSplice, mkSigDecls,
21 mkTyData, mkPrefixCon, mkRecCon,
22 mkRecConstrOrUpdate, -- HsExp -> [HsFieldUpdate] -> P HsExp
30 -- Stuff to do with Foreign declarations
32 , mkImport -- CallConv -> Safety
33 -- -> (FastString, RdrName, RdrNameHsType)
35 , mkExport -- CallConv
36 -- -> (FastString, RdrName, RdrNameHsType)
38 , mkExtName -- RdrName -> CLabelString
40 -- Bunch of functions in the parser monad for
41 -- checking and constructing values
42 , checkPrecP -- Int -> P Int
43 , checkContext -- HsType -> P HsContext
44 , checkPred -- HsType -> P HsPred
45 , checkTyClHdr -- HsType -> (name,[tyvar])
46 , checkInstType -- HsType -> P HsType
47 , checkPattern -- HsExp -> P HsPat
48 , checkPatterns -- SrcLoc -> [HsExp] -> P [HsPat]
49 , checkDo -- [Stmt] -> P [Stmt]
50 , checkMDo -- [Stmt] -> P [Stmt]
51 , checkValDef -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
52 , checkValSig -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
53 , parseError -- String -> Pa
56 #include "HsVersions.h"
58 import HsSyn -- Lots of it
60 import HscTypes ( ModIface(..), emptyModIface, mkIfaceVerCache )
61 import IfaceSyn ( IfaceDecl(..), IfaceIdInfo(..) )
62 import RdrName ( RdrName, isRdrTyVar, mkUnqual, rdrNameOcc,
63 isRdrTyVar, isRdrDataCon, isUnqual, getRdrName, isQual,
64 setRdrNameSpace, rdrNameModule )
65 import BasicTypes ( RecFlag(..), mapIPName, maxPrecedence, initialVersion )
66 import Lexer ( P, failSpanMsgP )
67 import HscTypes ( GenAvailInfo(..) )
68 import TysWiredIn ( unitTyCon )
69 import ForeignCall ( CCallConv, Safety, CCallTarget(..), CExportSpec(..),
70 DNCallSpec(..), DNKind(..))
71 import OccName ( OccName, srcDataName, varName, isDataOcc, isTcOcc,
72 occNameUserString, isValOcc )
73 import BasicTypes ( initialVersion )
74 import TyCon ( DataConDetails(..) )
75 import Module ( ModuleName )
77 import CStrings ( CLabelString )
78 import CmdLineOpts ( opt_InPackage )
79 import Bag ( Bag, emptyBag, snocBag, consBag, foldrBag )
84 import List ( isSuffixOf, nubBy )
88 %************************************************************************
90 \subsection{Type synonyms}
92 %************************************************************************
95 main_RDR_Unqual :: RdrName
96 main_RDR_Unqual = mkUnqual varName FSLIT("main")
97 -- We definitely don't want an Orig RdrName, because
98 -- main might, in principle, be imported into module Main
101 %************************************************************************
103 \subsection{A few functions over HsSyn at RdrName}
105 %************************************************************************
107 @extractHsTyRdrNames@ finds the free variables of a HsType
108 It's used when making the for-alls explicit.
111 extractHsTyRdrTyVars :: LHsType RdrName -> [Located RdrName]
112 extractHsTyRdrTyVars ty = nubBy eqLocated (extract_lty ty [])
114 extractHsRhoRdrTyVars :: LHsContext RdrName -> LHsType RdrName -> [Located RdrName]
115 -- This one takes the context and tau-part of a
116 -- sigma type and returns their free type variables
117 extractHsRhoRdrTyVars ctxt ty
118 = nubBy eqLocated $ extract_lctxt ctxt (extract_lty ty [])
120 extract_lctxt ctxt acc = foldr (extract_pred.unLoc) acc (unLoc ctxt)
122 extract_pred (HsClassP cls tys) acc = foldr extract_lty acc tys
123 extract_pred (HsIParam n ty) acc = extract_lty ty acc
125 extract_lty (L loc (HsTyVar tv)) acc
126 | isRdrTyVar tv = L loc tv : acc
128 extract_lty ty acc = extract_ty (unLoc ty) acc
130 extract_ty (HsAppTy ty1 ty2) acc = extract_lty ty1 (extract_lty ty2 acc)
131 extract_ty (HsListTy ty) acc = extract_lty ty acc
132 extract_ty (HsPArrTy ty) acc = extract_lty ty acc
133 extract_ty (HsTupleTy _ tys) acc = foldr extract_lty acc tys
134 extract_ty (HsFunTy ty1 ty2) acc = extract_lty ty1 (extract_lty ty2 acc)
135 extract_ty (HsPredTy p) acc = extract_pred (unLoc p) acc
136 extract_ty (HsOpTy ty1 nam ty2) acc = extract_lty ty1 (extract_lty ty2 acc)
137 extract_ty (HsParTy ty) acc = extract_lty ty acc
138 extract_ty (HsNumTy num) acc = acc
139 extract_ty (HsKindSig ty k) acc = extract_lty ty acc
140 extract_ty (HsForAllTy exp [] cx ty) acc = extract_lctxt cx (extract_lty ty acc)
141 extract_ty (HsForAllTy exp tvs cx ty)
142 acc = (filter ((`notElem` locals) . unLoc) $
143 extract_lctxt cx (extract_lty ty [])) ++ acc
145 locals = hsLTyVarNames tvs
147 extractGenericPatTyVars :: LHsBinds RdrName -> [Located RdrName]
148 -- Get the type variables out of the type patterns in a bunch of
149 -- possibly-generic bindings in a class declaration
150 extractGenericPatTyVars binds
151 = nubBy eqLocated (foldrBag get [] binds)
153 get (L _ (FunBind _ _ ms)) acc = foldr (get_m.unLoc) acc ms
156 get_m (Match (L _ (TypePat ty) : _) _ _) acc = extract_lty ty acc
157 get_m other acc = acc
161 %************************************************************************
163 \subsection{Construction functions for Rdr stuff}
165 %************************************************************************
167 mkClassDecl builds a RdrClassDecl, filling in the names for tycon and datacon
168 by deriving them from the name of the class. We fill in the names for the
169 tycon and datacon corresponding to the class, by deriving them from the
170 name of the class itself. This saves recording the names in the interface
171 file (which would be equally good).
173 Similarly for mkConDecl, mkClassOpSig and default-method names.
175 *** See "THE NAMING STORY" in HsDecls ****
178 mkClassDecl (cxt, cname, tyvars) fds sigs mbinds
179 = ClassDecl { tcdCtxt = cxt, tcdLName = cname, tcdTyVars = tyvars,
185 mkTyData new_or_data (context, tname, tyvars) data_cons maybe
186 = TyData { tcdND = new_or_data, tcdCtxt = context, tcdLName = tname,
187 tcdTyVars = tyvars, tcdCons = data_cons,
192 mkHsNegApp :: LHsExpr RdrName -> HsExpr RdrName
193 -- RdrName If the type checker sees (negate 3#) it will barf, because negate
194 -- can't take an unboxed arg. But that is exactly what it will see when
195 -- we write "-3#". So we have to do the negation right now!
196 mkHsNegApp (L loc e) = f e
197 where f (HsLit (HsIntPrim i)) = HsLit (HsIntPrim (-i))
198 f (HsLit (HsFloatPrim i)) = HsLit (HsFloatPrim (-i))
199 f (HsLit (HsDoublePrim i)) = HsLit (HsDoublePrim (-i))
200 f expr = NegApp (L loc e) placeHolderName
203 %************************************************************************
207 %************************************************************************
209 mkBootIface, and its boring helper functions, have two purposes:
210 a) HsSyn to IfaceSyn. The parser parses the former, but we're reading
211 an hi-boot file, and interfaces consist of the latter
212 b) Convert unqualifed names from the "current module" to qualified Orig
215 foo :: GHC.Base.Int -> GHC.Base.Int
217 This.foo :: GHC.Base.Int -> GHC.Base.Int
219 It assumes that everything is well kinded, of course.
222 mkBootIface :: ModuleName -> [HsDecl RdrName] -> ModIface
223 -- Make the ModIface for a hi-boot file
224 -- The decls are of very limited form
225 mkBootIface mod decls
226 = (emptyModIface opt_InPackage mod) {
228 mi_exports = [(mod, map mk_export decls')],
229 mi_decls = decls_w_vers,
230 mi_ver_fn = mkIfaceVerCache decls_w_vers }
232 decls' = map hsIfaceDecl decls
233 decls_w_vers = repeat initialVersion `zip` decls'
235 -- hi-boot declarations don't (currently)
236 -- expose constructors or class methods
237 mk_export decl | isValOcc occ = Avail occ
238 | otherwise = AvailTC occ [occ]
243 hsIfaceDecl :: HsDecl RdrName -> IfaceDecl
244 -- Change to Iface syntax, and replace unqualified names with
245 -- qualified Orig names from this module. Reason: normal
246 -- iface files have everything fully qualified, so it's convenient
247 -- for hi-boot files to look the same
249 -- NB: no constructors or class ops to worry about
250 hsIfaceDecl (SigD (Sig name ty))
251 = IfaceId { ifName = rdrNameOcc (unLoc name),
252 ifType = hsIfaceLType ty,
255 hsIfaceDecl (TyClD decl@(TySynonym {}))
256 = IfaceSyn { ifName = rdrNameOcc (tcdName decl),
257 ifTyVars = hsIfaceTvs (tcdTyVars decl),
258 ifSynRhs = hsIfaceLType (tcdSynRhs decl),
261 hsIfaceDecl (TyClD decl@(TyData {}))
262 = IfaceData { ifND = tcdND decl,
263 ifName = rdrNameOcc (tcdName decl),
264 ifTyVars = hsIfaceTvs (tcdTyVars decl),
265 ifCtxt = hsIfaceCtxt (unLoc (tcdCtxt decl)),
266 ifCons = Unknown, ifRec = NonRecursive,
267 ifVrcs = [], ifGeneric = False }
268 -- I'm not sure that [] is right for ifVrcs, but
269 -- since we don't use them I'm not going to fiddle
271 hsIfaceDecl (TyClD decl@(ClassDecl {}))
272 = IfaceClass { ifName = rdrNameOcc (tcdName decl),
273 ifTyVars = hsIfaceTvs (tcdTyVars decl),
274 ifCtxt = hsIfaceCtxt (unLoc (tcdCtxt decl)),
275 ifFDs = hsIfaceFDs (map unLoc (tcdFDs decl)),
276 ifSigs = [], -- Is this right??
277 ifRec = NonRecursive, ifVrcs = [] }
279 hsIfaceDecl decl = pprPanic "hsIfaceDecl" (ppr decl)
281 hsIfaceName rdr_name -- Qualify unqualifed occurrences
282 -- with the module name
283 | isUnqual rdr_name = LocalTop (rdrNameOcc rdr_name)
284 | otherwise = ExtPkg (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
286 hsIfaceLType :: LHsType RdrName -> IfaceType
287 hsIfaceLType = hsIfaceType . unLoc
289 hsIfaceType :: HsType RdrName -> IfaceType
290 hsIfaceType (HsForAllTy exp tvs cxt ty)
291 = foldr (IfaceForAllTy . hsIfaceTv) rho tvs'
293 rho = foldr (IfaceFunTy . IfacePredTy . hsIfaceLPred) tau (unLoc cxt)
294 tau = hsIfaceLType ty
296 Explicit -> map unLoc tvs
297 Implicit -> map (UserTyVar . unLoc) (extractHsRhoRdrTyVars cxt ty)
299 hsIfaceType ty@(HsTyVar _) = hs_tc_app ty []
300 hsIfaceType ty@(HsAppTy t1 t2) = hs_tc_app ty []
301 hsIfaceType (HsFunTy t1 t2) = IfaceFunTy (hsIfaceLType t1) (hsIfaceLType t2)
302 hsIfaceType (HsListTy t) = IfaceTyConApp IfaceListTc [hsIfaceLType t]
303 hsIfaceType (HsPArrTy t) = IfaceTyConApp IfacePArrTc [hsIfaceLType t]
304 hsIfaceType (HsTupleTy bx ts) = IfaceTyConApp (IfaceTupTc bx (length ts)) (hsIfaceLTypes ts)
305 hsIfaceType (HsOpTy t1 tc t2) = hs_tc_app (HsTyVar (unLoc tc)) (hsIfaceLTypes [t1, t2])
306 hsIfaceType (HsParTy t) = hsIfaceLType t
307 hsIfaceType (HsNumTy n) = panic "hsIfaceType:HsNum"
308 hsIfaceType (HsPredTy p) = IfacePredTy (hsIfaceLPred p)
309 hsIfaceType (HsKindSig t _) = hsIfaceLType t
312 hsIfaceLTypes tys = map (hsIfaceType.unLoc) tys
315 hsIfaceCtxt :: [LHsPred RdrName] -> [IfacePredType]
316 hsIfaceCtxt ctxt = map hsIfaceLPred ctxt
319 hsIfaceLPred :: LHsPred RdrName -> IfacePredType
320 hsIfaceLPred = hsIfacePred . unLoc
322 hsIfacePred :: HsPred RdrName -> IfacePredType
323 hsIfacePred (HsClassP cls ts) = IfaceClassP (hsIfaceName cls) (hsIfaceLTypes ts)
324 hsIfacePred (HsIParam ip t) = IfaceIParam (mapIPName rdrNameOcc ip) (hsIfaceLType t)
327 hs_tc_app :: HsType RdrName -> [IfaceType] -> IfaceType
328 hs_tc_app (HsAppTy t1 t2) args = hs_tc_app (unLoc t1) (hsIfaceLType t2 : args)
329 hs_tc_app (HsTyVar n) args
330 | isTcOcc (rdrNameOcc n) = IfaceTyConApp (IfaceTc (hsIfaceName n)) args
331 | otherwise = foldl IfaceAppTy (IfaceTyVar (rdrNameOcc n)) args
332 hs_tc_app ty args = foldl IfaceAppTy (hsIfaceType ty) args
335 hsIfaceTvs tvs = map (hsIfaceTv.unLoc) tvs
338 hsIfaceTv (UserTyVar n) = (rdrNameOcc n, IfaceLiftedTypeKind)
339 hsIfaceTv (KindedTyVar n k) = (rdrNameOcc n, toIfaceKind k)
342 hsIfaceFDs :: [([RdrName], [RdrName])] -> [([OccName], [OccName])]
343 hsIfaceFDs fds = [ (map rdrNameOcc xs, map rdrNameOcc ys)
348 %************************************************************************
350 \subsection[rdrBinding]{Bindings straight out of the parser}
352 %************************************************************************
356 = -- Value bindings havn't been united with their
358 RdrBindings [RdrBinding] -- Convenience for parsing
360 | RdrValBinding (LHsBind RdrName)
362 -- The remainder all fit into the main HsDecl form
363 | RdrHsDecl (LHsDecl RdrName)
366 %************************************************************************
368 \subsection[cvBinds-etc]{Converting to @HsBinds@, etc.}
370 %************************************************************************
372 Function definitions are restructured here. Each is assumed to be recursive
373 initially, and non recursive definitions are discovered by the dependency
378 cvTopDecls :: [RdrBinding] -> [LHsDecl RdrName]
379 -- Incoming bindings are in reverse order; result is in ordinary order
380 -- (a) flatten RdrBindings
381 -- (b) Group together bindings for a single function
385 go :: [LHsDecl RdrName] -> [RdrBinding] -> [LHsDecl RdrName]
387 go acc (RdrBindings ds1 : ds2) = go (go acc ds1) ds2
388 go acc (RdrHsDecl d : ds) = go (d : acc) ds
389 go acc (RdrValBinding b : ds) = go (L l (ValD b') : acc) ds'
391 (L l b', ds') = getMonoBind b ds
393 cvBindGroup :: [RdrBinding] -> HsBindGroup RdrName
395 = case (cvBindsAndSigs binding) of { (mbs, sigs) ->
396 HsBindGroup mbs sigs Recursive -- just one big group for now
399 cvBindsAndSigs :: [RdrBinding] -> (Bag (LHsBind RdrName), [LSig RdrName])
400 -- Input bindings are in *reverse* order,
401 -- and contain just value bindings and signatures
403 = go (emptyBag, []) fb
406 go acc (RdrBindings ds1 : ds2) = go (go acc ds1) ds2
407 go (bs, ss) (RdrHsDecl (L l (SigD s)) : ds) = go (bs, L l s : ss) ds
408 go (bs, ss) (RdrValBinding b : ds) = go (b' `consBag` bs, ss) ds'
410 (b',ds') = getMonoBind b ds
412 -----------------------------------------------------------------------------
413 -- Group function bindings into equation groups
415 getMonoBind :: LHsBind RdrName -> [RdrBinding] -> (LHsBind RdrName, [RdrBinding])
416 -- Suppose (b',ds') = getMonoBind b ds
417 -- ds is a *reversed* list of parsed bindings
418 -- b is a MonoBinds that has just been read off the front
420 -- Then b' is the result of grouping more equations from ds that
421 -- belong with b into a single MonoBinds, and ds' is the depleted
422 -- list of parsed bindings.
424 -- No AndMonoBinds or EmptyMonoBinds here; just single equations
426 getMonoBind (L loc (FunBind lf@(L _ f) inf mtchs)) binds
430 go mtchs1 loc1 (RdrValBinding (L loc2 (FunBind f2 inf2 mtchs2)) : binds)
431 | f == unLoc f2 = go (mtchs2 ++ mtchs1) loc binds
432 -- Remember binds is reversed, so glue mtchs2 on the front
433 -- and use loc2 as the final location
434 where loc = combineSrcSpans loc1 loc2
435 go mtchs1 loc binds = (L loc (FunBind lf inf mtchs1), binds)
437 getMonoBind bind binds = (bind, binds)
439 has_args ((L _ (Match args _ _)) : _) = not (null args)
440 -- Don't group together FunBinds if they have
441 -- no arguments. This is necessary now that variable bindings
442 -- with no arguments are now treated as FunBinds rather
443 -- than pattern bindings (tests/rename/should_fail/rnfail002).
447 emptyGroup = HsGroup { hs_valds = [HsBindGroup emptyBag [] Recursive],
448 hs_tyclds = [], hs_instds = [],
449 hs_fixds = [], hs_defds = [], hs_fords = [],
450 hs_depds = [] ,hs_ruleds = [] }
452 findSplice :: [LHsDecl a] -> (HsGroup a, Maybe (SpliceDecl a, [LHsDecl a]))
453 findSplice ds = addl emptyGroup ds
455 mkGroup :: [LHsDecl a] -> HsGroup a
456 mkGroup ds = addImpDecls emptyGroup ds
458 addImpDecls :: HsGroup a -> [LHsDecl a] -> HsGroup a
459 -- The decls are imported, and should not have a splice
460 addImpDecls group decls = case addl group decls of
461 (group', Nothing) -> group'
462 other -> panic "addImpDecls"
464 addl :: HsGroup a -> [LHsDecl a] -> (HsGroup a, Maybe (SpliceDecl a, [LHsDecl a]))
465 -- This stuff reverses the declarations (again) but it doesn't matter
468 addl gp [] = (gp, Nothing)
469 addl gp (L l d : ds) = add gp l d ds
472 add :: HsGroup a -> SrcSpan -> HsDecl a -> [LHsDecl a]
473 -> (HsGroup a, Maybe (SpliceDecl a, [LHsDecl a]))
475 add gp l (SpliceD e) ds = (gp, Just (e, ds))
477 -- Class declarations: pull out the fixity signatures to the top
478 add gp@(HsGroup {hs_tyclds = ts, hs_fixds = fs}) l (TyClD d) ds
480 let fsigs = [ L l f | L l (FixSig f) <- tcdSigs d ] in
481 addl (gp { hs_tyclds = L l d : ts, hs_fixds = fsigs ++ fs }) ds
483 addl (gp { hs_tyclds = L l d : ts }) ds
485 -- Signatures: fixity sigs go a different place than all others
486 add gp@(HsGroup {hs_fixds = ts}) l (SigD (FixSig f)) ds
487 = addl (gp {hs_fixds = L l f : ts}) ds
488 add gp@(HsGroup {hs_valds = ts}) l (SigD d) ds
489 = addl (gp {hs_valds = add_sig (L l d) ts}) ds
491 -- Value declarations: use add_bind
492 add gp@(HsGroup {hs_valds = ts}) l (ValD d) ds
493 = addl (gp { hs_valds = add_bind (L l d) ts }) ds
495 -- The rest are routine
496 add gp@(HsGroup {hs_instds = ts}) l (InstD d) ds
497 = addl (gp { hs_instds = L l d : ts }) ds
498 add gp@(HsGroup {hs_defds = ts}) l (DefD d) ds
499 = addl (gp { hs_defds = L l d : ts }) ds
500 add gp@(HsGroup {hs_fords = ts}) l (ForD d) ds
501 = addl (gp { hs_fords = L l d : ts }) ds
502 add gp@(HsGroup {hs_depds = ts}) l (DeprecD d) ds
503 = addl (gp { hs_depds = L l d : ts }) ds
504 add gp@(HsGroup {hs_ruleds = ts}) l (RuleD d) ds
505 = addl (gp { hs_ruleds = L l d : ts }) ds
507 add_bind b [HsBindGroup bs sigs r] = [HsBindGroup (bs `snocBag` b) sigs r]
508 add_sig s [HsBindGroup bs sigs r] = [HsBindGroup bs (s:sigs) r]
511 %************************************************************************
513 \subsection[PrefixToHS-utils]{Utilities for conversion}
515 %************************************************************************
519 -----------------------------------------------------------------------------
522 -- When parsing data declarations, we sometimes inadvertently parse
523 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
524 -- This function splits up the type application, adds any pending
525 -- arguments, and converts the type constructor back into a data constructor.
527 mkPrefixCon :: LHsType RdrName -> [LBangType RdrName]
528 -> P (Located RdrName, HsConDetails RdrName (LBangType RdrName))
532 split (L _ (HsAppTy t u)) ts = split t (unbangedType u : ts)
533 split (L l (HsTyVar tc)) ts = do data_con <- tyConToDataCon l tc
534 return (data_con, PrefixCon ts)
535 split (L l _) _ = parseError l "parse error in data/newtype declaration"
537 mkRecCon :: Located RdrName -> [([Located RdrName], LBangType RdrName)]
538 -> P (Located RdrName, HsConDetails RdrName (LBangType RdrName))
539 mkRecCon (L loc con) fields
540 = do data_con <- tyConToDataCon loc con
541 return (data_con, RecCon [ (l,t) | (ls,t) <- fields, l <- ls ])
543 tyConToDataCon :: SrcSpan -> RdrName -> P (Located RdrName)
544 tyConToDataCon loc tc
545 | isTcOcc (rdrNameOcc tc)
546 = return (L loc (setRdrNameSpace tc srcDataName))
548 = parseError loc (showSDoc (text "Not a constructor:" <+> quotes (ppr tc)))
550 ----------------------------------------------------------------------------
551 -- Various Syntactic Checks
553 checkInstType :: LHsType RdrName -> P (LHsType RdrName)
554 checkInstType (L l t)
556 HsForAllTy exp tvs ctxt ty -> do
557 dict_ty <- checkDictTy ty
558 return (L l (HsForAllTy exp tvs ctxt dict_ty))
560 HsParTy ty -> checkInstType ty
562 ty -> do dict_ty <- checkDictTy (L l ty)
563 return (L l (HsForAllTy Implicit [] (noLoc []) dict_ty))
565 checkTyVars :: [LHsType RdrName] -> P [LHsTyVarBndr RdrName]
569 -- Check that the name space is correct!
570 chk (L l (HsKindSig (L _ (HsTyVar tv)) k))
571 | isRdrTyVar tv = return (L l (KindedTyVar tv k))
572 chk (L l (HsTyVar tv))
573 | isRdrTyVar tv = return (L l (UserTyVar tv))
575 = parseError l "Type found where type variable expected"
577 checkTyClHdr :: LHsContext RdrName -> LHsType RdrName
578 -> P (LHsContext RdrName, Located RdrName, [LHsTyVarBndr RdrName])
579 -- The header of a type or class decl should look like
580 -- (C a, D b) => T a b
584 checkTyClHdr (L l cxt) ty
585 = do (tc, tvs) <- gol ty []
587 return (L l cxt, tc, tvs)
589 gol (L l ty) acc = go l ty acc
591 go l (HsTyVar tc) acc
592 | not (isRdrTyVar tc) = checkTyVars acc >>= \ tvs ->
594 go l (HsOpTy t1 tc t2) acc = checkTyVars (t1:t2:acc) >>= \ tvs ->
596 go l (HsParTy ty) acc = gol ty acc
597 go l (HsAppTy t1 t2) acc = gol t1 (t2:acc)
598 go l other acc = parseError l "Malformed LHS to type of class declaration"
600 -- The predicates in a type or class decl must all
601 -- be HsClassPs. They need not all be type variables,
602 -- even in Haskell 98. E.g. class (Monad m, Monad (t m)) => MonadT t m
603 chk_pred (L l (HsClassP _ args)) = return ()
605 = parseError l "Malformed context in type or class declaration"
608 checkContext :: LHsType RdrName -> P (LHsContext RdrName)
612 check (HsTupleTy _ ts) -- (Eq a, Ord b) shows up as a tuple type
613 = do ctx <- mapM checkPred ts
616 check (HsParTy ty) -- to be sure HsParTy doesn't get into the way
619 check (HsTyVar t) -- Empty context shows up as a unit type ()
620 | t == getRdrName unitTyCon = return (L l [])
623 = do p <- checkPred (L l t)
627 checkPred :: LHsType RdrName -> P (LHsPred RdrName)
628 -- Watch out.. in ...deriving( Show )... we use checkPred on
629 -- the list of partially applied predicates in the deriving,
630 -- so there can be zero args.
631 checkPred (L spn (HsPredTy (L _ (HsIParam n ty))) )
632 = return (L spn (HsIParam n ty))
636 checkl (L l ty) args = check l ty args
638 check loc (HsTyVar t) args | not (isRdrTyVar t)
639 = return (L spn (HsClassP t args))
640 check loc (HsAppTy l r) args = checkl l (r:args)
641 check loc (HsParTy t) args = checkl t args
642 check loc _ _ = parseError loc "malformed class assertion"
644 checkDictTy :: LHsType RdrName -> P (LHsType RdrName)
645 checkDictTy (L spn ty) = check ty []
647 check (HsTyVar t) args@(_:_) | not (isRdrTyVar t)
648 = return (L spn (HsPredTy (L spn (HsClassP t args))))
649 check (HsAppTy l r) args = check (unLoc l) (r:args)
650 check (HsParTy t) args = check (unLoc t) args
651 check _ _ = parseError spn "Malformed context in instance header"
653 ---------------------------------------------------------------------------
654 -- Checking statements in a do-expression
655 -- We parse do { e1 ; e2 ; }
656 -- as [ExprStmt e1, ExprStmt e2]
657 -- checkDo (a) checks that the last thing is an ExprStmt
658 -- (b) transforms it to a ResultStmt
659 -- same comments apply for mdo as well
661 checkDo = checkDoMDo "a " "'do'"
662 checkMDo = checkDoMDo "an " "'mdo'"
664 checkDoMDo :: String -> String -> SrcSpan -> [LStmt RdrName] -> P [LStmt RdrName]
665 checkDoMDo pre nm loc [] = parseError loc ("Empty " ++ nm ++ " construct")
666 checkDoMDo pre nm loc ss = do
669 check [L l (ExprStmt e _)] = return [L l (ResultStmt e)]
670 check [L l _] = parseError l ("The last statement in " ++ pre ++ nm ++
671 " construct must be an expression")
676 -- -------------------------------------------------------------------------
677 -- Checking Patterns.
679 -- We parse patterns as expressions and check for valid patterns below,
680 -- converting the expression into a pattern at the same time.
682 checkPattern :: LHsExpr RdrName -> P (LPat RdrName)
683 checkPattern e = checkLPat e
685 checkPatterns :: [LHsExpr RdrName] -> P [LPat RdrName]
686 checkPatterns es = mapM checkPattern es
688 checkLPat :: LHsExpr RdrName -> P (LPat RdrName)
689 checkLPat e@(L l _) = checkPat l e []
691 checkPat :: SrcSpan -> LHsExpr RdrName -> [LPat RdrName] -> P (LPat RdrName)
692 checkPat loc (L l (HsVar c)) args
693 | isRdrDataCon c = return (L loc (ConPatIn (L l c) (PrefixCon args)))
694 checkPat loc (L _ (HsApp f x)) args = do
696 checkPat loc f (x:args)
697 checkPat loc (L _ e) [] = do
700 checkPat loc pat _some_args
703 checkAPat loc e = case e of
704 EWildPat -> return (WildPat placeHolderType)
705 HsVar x | isQual x -> parseError loc ("Qualified variable in pattern: "
707 | otherwise -> return (VarPat x)
708 HsLit l -> return (LitPat l)
710 -- Overloaded numeric patterns (e.g. f 0 x = x)
711 -- Negation is recorded separately, so that the literal is zero or +ve
712 -- NB. Negative *primitive* literals are already handled by
713 -- RdrHsSyn.mkHsNegApp
714 HsOverLit pos_lit -> return (NPatIn pos_lit Nothing)
715 NegApp (L _ (HsOverLit pos_lit)) _
716 -> return (NPatIn pos_lit (Just placeHolderName))
718 ELazyPat e -> checkLPat e >>= (return . LazyPat)
719 EAsPat n e -> checkLPat e >>= (return . AsPat n)
720 ExprWithTySig e t -> checkLPat e >>= \e ->
721 -- Pattern signatures are parsed as sigtypes,
722 -- but they aren't explicit forall points. Hence
723 -- we have to remove the implicit forall here.
725 L _ (HsForAllTy Implicit _ (L _ []) ty) -> ty
728 return (SigPatIn e t')
731 OpApp (L nloc (HsVar n)) (L _ (HsVar plus)) _
732 (L _ (HsOverLit lit@(HsIntegral _ _)))
734 -> return (mkNPlusKPat (L nloc n) lit)
736 plus_RDR = mkUnqual varName FSLIT("+") -- Hack
738 OpApp l op fix r -> checkLPat l >>= \l ->
739 checkLPat r >>= \r ->
741 L cl (HsVar c) | isDataOcc (rdrNameOcc c)
742 -> return (ConPatIn (L cl c) (InfixCon l r))
745 HsPar e -> checkLPat e >>= (return . ParPat)
746 ExplicitList _ es -> mapM (\e -> checkLPat e) es >>= \ps ->
747 return (ListPat ps placeHolderType)
748 ExplicitPArr _ es -> mapM (\e -> checkLPat e) es >>= \ps ->
749 return (PArrPat ps placeHolderType)
751 ExplicitTuple es b -> mapM (\e -> checkLPat e) es >>= \ps ->
752 return (TuplePat ps b)
754 RecordCon c fs -> mapM checkPatField fs >>= \fs ->
755 return (ConPatIn c (RecCon fs))
757 HsType ty -> return (TypePat ty)
760 checkAPat loc _ = patFail loc
762 checkPatField :: (Located RdrName, LHsExpr RdrName) -> P (Located RdrName, LPat RdrName)
763 checkPatField (n,e) = do
767 patFail loc = parseError loc "Parse error in pattern"
770 ---------------------------------------------------------------------------
771 -- Check Equation Syntax
775 -> Maybe (LHsType RdrName)
777 -> P (HsBind RdrName)
779 checkValDef lhs opt_sig grhss
780 | Just (f,inf,es) <- isFunLhs lhs []
781 = if isQual (unLoc f)
782 then parseError (getLoc f) ("Qualified name in function definition: " ++
783 showRdrName (unLoc f))
784 else do ps <- checkPatterns es
785 return (FunBind f inf [L (getLoc f) (Match ps opt_sig grhss)])
786 -- TODO: span is wrong
788 lhs <- checkPattern lhs
789 return (PatBind lhs grhss)
795 checkValSig (L l (HsVar v)) ty | isUnqual v = return (Sig (L l v) ty)
796 checkValSig (L l other) ty
797 = parseError l "Type signature given for an expression"
799 mkSigDecls :: [LSig RdrName] -> RdrBinding
800 mkSigDecls sigs = RdrBindings [RdrHsDecl (L l (SigD sig)) | L l sig <- sigs]
803 -- A variable binding is parsed as a FunBind.
805 isFunLhs :: LHsExpr RdrName -> [LHsExpr RdrName]
806 -> Maybe (Located RdrName, Bool, [LHsExpr RdrName])
807 isFunLhs (L loc e) = isFunLhs' loc e
809 isFunLhs' loc (HsVar f) es
810 | not (isRdrDataCon f) = Just (L loc f, False, es)
811 isFunLhs' loc (HsApp f e) es = isFunLhs f (e:es)
812 isFunLhs' loc (HsPar e) es@(_:_) = isFunLhs e es
813 isFunLhs' loc (OpApp l (L loc' (HsVar op)) fix r) es
814 | not (isRdrDataCon op) = Just (L loc' op, True, (l:r:es))
816 case isFunLhs l es of
817 Just (op', True, j : k : es') ->
819 j : L loc (OpApp k (L loc' (HsVar op)) fix r) : es')
821 isFunLhs' _ _ _ = Nothing
823 ---------------------------------------------------------------------------
824 -- Miscellaneous utilities
826 checkPrecP :: Located Int -> P Int
828 | 0 <= i && i <= maxPrecedence = return i
829 | otherwise = parseError l "Precedence out of range"
834 -> HsRecordBinds RdrName
835 -> P (HsExpr RdrName)
837 mkRecConstrOrUpdate (L l (HsVar c)) loc fs | isRdrDataCon c
838 = return (RecordCon (L l c) fs)
839 mkRecConstrOrUpdate exp loc fs@(_:_)
840 = return (RecordUpd exp fs)
841 mkRecConstrOrUpdate _ loc []
842 = parseError loc "Empty record update"
844 -----------------------------------------------------------------------------
845 -- utilities for foreign declarations
847 -- supported calling conventions
849 data CallConv = CCall CCallConv -- ccall or stdcall
852 -- construct a foreign import declaration
856 -> (Located FastString, Located RdrName, LHsType RdrName)
857 -> P (HsDecl RdrName)
858 mkImport (CCall cconv) safety (entity, v, ty) = do
859 importSpec <- parseCImport entity cconv safety v
860 return (ForD (ForeignImport v ty importSpec False))
861 mkImport (DNCall ) _ (entity, v, ty) = do
862 spec <- parseDImport entity
863 return $ ForD (ForeignImport v ty (DNImport spec) False)
865 -- parse the entity string of a foreign import declaration for the `ccall' or
866 -- `stdcall' calling convention'
868 parseCImport :: Located FastString
873 parseCImport (L loc entity) cconv safety v
874 -- FIXME: we should allow white space around `dynamic' and `wrapper' -=chak
875 | entity == FSLIT ("dynamic") =
876 return $ CImport cconv safety nilFS nilFS (CFunction DynamicTarget)
877 | entity == FSLIT ("wrapper") =
878 return $ CImport cconv safety nilFS nilFS CWrapper
879 | otherwise = parse0 (unpackFS entity)
881 -- using the static keyword?
882 parse0 (' ': rest) = parse0 rest
883 parse0 ('s':'t':'a':'t':'i':'c':rest) = parse1 rest
884 parse0 rest = parse1 rest
885 -- check for header file name
886 parse1 "" = parse4 "" nilFS False nilFS
887 parse1 (' ':rest) = parse1 rest
888 parse1 str@('&':_ ) = parse2 str nilFS
889 parse1 str@('[':_ ) = parse3 str nilFS False
891 | ".h" `isSuffixOf` first = parse2 rest (mkFastString first)
892 | otherwise = parse4 str nilFS False nilFS
894 (first, rest) = break (\c -> c == ' ' || c == '&' || c == '[') str
895 -- check for address operator (indicating a label import)
896 parse2 "" header = parse4 "" header False nilFS
897 parse2 (' ':rest) header = parse2 rest header
898 parse2 ('&':rest) header = parse3 rest header True
899 parse2 str@('[':_ ) header = parse3 str header False
900 parse2 str header = parse4 str header False nilFS
901 -- check for library object name
902 parse3 (' ':rest) header isLbl = parse3 rest header isLbl
903 parse3 ('[':rest) header isLbl =
904 case break (== ']') rest of
905 (lib, ']':rest) -> parse4 rest header isLbl (mkFastString lib)
906 _ -> parseError loc "Missing ']' in entity"
907 parse3 str header isLbl = parse4 str header isLbl nilFS
908 -- check for name of C function
909 parse4 "" header isLbl lib = build (mkExtName (unLoc v)) header isLbl lib
910 parse4 (' ':rest) header isLbl lib = parse4 rest header isLbl lib
911 parse4 str header isLbl lib
912 | all (== ' ') rest = build (mkFastString first) header isLbl lib
913 | otherwise = parseError loc "Malformed entity string"
915 (first, rest) = break (== ' ') str
917 build cid header False lib = return $
918 CImport cconv safety header lib (CFunction (StaticTarget cid))
919 build cid header True lib = return $
920 CImport cconv safety header lib (CLabel cid )
923 -- Unravel a dotnet spec string.
925 parseDImport :: Located FastString -> P DNCallSpec
926 parseDImport (L loc entity) = parse0 comps
928 comps = words (unpackFS entity)
932 | x == "static" = parse1 True xs
933 | otherwise = parse1 False (x:xs)
936 parse1 isStatic (x:xs)
937 | x == "method" = parse2 isStatic DNMethod xs
938 | x == "field" = parse2 isStatic DNField xs
939 | x == "ctor" = parse2 isStatic DNConstructor xs
940 parse1 isStatic xs = parse2 isStatic DNMethod xs
943 parse2 isStatic kind (('[':x):xs) =
946 vs | last vs == ']' -> parse3 isStatic kind (init vs) xs
947 parse2 isStatic kind xs = parse3 isStatic kind "" xs
949 parse3 isStatic kind assem [x] =
950 return (DNCallSpec isStatic kind assem x
951 -- these will be filled in once known.
952 (error "FFI-dotnet-args")
953 (error "FFI-dotnet-result"))
954 parse3 _ _ _ _ = d'oh
956 d'oh = parseError loc "Malformed entity string"
958 -- construct a foreign export declaration
961 -> (Located FastString, Located RdrName, LHsType RdrName)
962 -> P (HsDecl RdrName)
963 mkExport (CCall cconv) (L loc entity, v, ty) = return $
964 ForD (ForeignExport v ty (CExport (CExportStatic entity' cconv)) False)
966 entity' | nullFastString entity = mkExtName (unLoc v)
968 mkExport DNCall (L loc entity, v, ty) =
969 parseError (getLoc v){-TODO: not quite right-}
970 "Foreign export is not yet supported for .NET"
972 -- Supplying the ext_name in a foreign decl is optional; if it
973 -- isn't there, the Haskell name is assumed. Note that no transformation
974 -- of the Haskell name is then performed, so if you foreign export (++),
975 -- it's external name will be "++". Too bad; it's important because we don't
976 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
977 -- (This is why we use occNameUserString.)
979 mkExtName :: RdrName -> CLabelString
980 mkExtName rdrNm = mkFastString (occNameUserString (rdrNameOcc rdrNm))
984 -----------------------------------------------------------------------------
988 showRdrName :: RdrName -> String
989 showRdrName r = showSDoc (ppr r)
991 parseError :: SrcSpan -> String -> P a
992 parseError span s = failSpanMsgP span s