2 % (c) The University of Glasgow, 1996-2003
4 Functions over HsSyn specialised to RdrName.
9 extractHsRhoRdrTyVars, extractGenericPatTyVars,
11 mkHsOpApp, mkClassDecl,
12 mkHsNegApp, mkHsIntegral, mkHsFractional,
14 mkTyData, mkPrefixCon, mkRecCon,
15 mkRecConstrOrUpdate, -- HsExp -> [HsFieldUpdate] -> P HsExp
22 -- Stuff to do with Foreign declarations
24 , mkImport -- CallConv -> Safety
25 -- -> (FastString, RdrName, RdrNameHsType)
27 , mkExport -- CallConv
28 -- -> (FastString, RdrName, RdrNameHsType)
30 , mkExtName -- RdrName -> CLabelString
32 -- Bunch of functions in the parser monad for
33 -- checking and constructing values
34 , checkPrecP -- Int -> P Int
35 , checkContext -- HsType -> P HsContext
36 , checkPred -- HsType -> P HsPred
39 , checkInstType -- HsType -> P HsType
40 , checkPattern -- HsExp -> P HsPat
41 , checkPatterns -- SrcLoc -> [HsExp] -> P [HsPat]
42 , checkDo -- [Stmt] -> P [Stmt]
43 , checkMDo -- [Stmt] -> P [Stmt]
44 , checkValDef -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
45 , checkValSig -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
46 , parseError -- String -> Pa
49 #include "HsVersions.h"
51 import HsSyn -- Lots of it
52 import RdrName ( RdrName, isRdrTyVar, mkUnqual, rdrNameOcc,
53 isRdrTyVar, isRdrDataCon, isUnqual, getRdrName, isQual,
55 import BasicTypes ( RecFlag(..), maxPrecedence )
56 import Lexer ( P, failSpanMsgP )
57 import TysWiredIn ( unitTyCon )
58 import ForeignCall ( CCallConv, Safety, CCallTarget(..), CExportSpec(..),
59 DNCallSpec(..), DNKind(..), CLabelString )
60 import OccName ( srcDataName, varName, isDataOcc, isTcOcc,
63 import OrdList ( OrdList, fromOL )
64 import Bag ( Bag, emptyBag, snocBag, consBag, foldrBag )
69 import List ( isSuffixOf, nubBy )
73 %************************************************************************
75 \subsection{A few functions over HsSyn at RdrName}
77 %************************************************************************
79 extractHsTyRdrNames finds the free variables of a HsType
80 It's used when making the for-alls explicit.
83 extractHsTyRdrTyVars :: LHsType RdrName -> [Located RdrName]
84 extractHsTyRdrTyVars ty = nubBy eqLocated (extract_lty ty [])
86 extractHsRhoRdrTyVars :: LHsContext RdrName -> LHsType RdrName -> [Located RdrName]
87 -- This one takes the context and tau-part of a
88 -- sigma type and returns their free type variables
89 extractHsRhoRdrTyVars ctxt ty
90 = nubBy eqLocated $ extract_lctxt ctxt (extract_lty ty [])
92 extract_lctxt ctxt acc = foldr (extract_pred . unLoc) acc (unLoc ctxt)
94 extract_pred (HsClassP cls tys) acc = foldr extract_lty acc tys
95 extract_pred (HsIParam n ty) acc = extract_lty ty acc
97 extract_lty (L loc ty) acc
99 HsTyVar tv -> extract_tv loc tv acc
100 HsBangTy _ ty -> extract_lty ty acc
101 HsAppTy ty1 ty2 -> extract_lty ty1 (extract_lty ty2 acc)
102 HsListTy ty -> extract_lty ty acc
103 HsPArrTy ty -> extract_lty ty acc
104 HsTupleTy _ tys -> foldr extract_lty acc tys
105 HsFunTy ty1 ty2 -> extract_lty ty1 (extract_lty ty2 acc)
106 HsPredTy p -> extract_pred p acc
107 HsOpTy ty1 (L loc tv) ty2 -> extract_tv loc tv (extract_lty ty1 (extract_lty ty2 acc))
108 HsParTy ty -> extract_lty ty acc
110 HsSpliceTy _ -> acc -- Type splices mention no type variables
111 HsKindSig ty k -> extract_lty ty acc
112 HsForAllTy exp [] cx ty -> extract_lctxt cx (extract_lty ty acc)
113 HsForAllTy exp tvs cx ty -> acc ++ (filter ((`notElem` locals) . unLoc) $
114 extract_lctxt cx (extract_lty ty []))
116 locals = hsLTyVarNames tvs
118 extract_tv :: SrcSpan -> RdrName -> [Located RdrName] -> [Located RdrName]
119 extract_tv loc tv acc | isRdrTyVar tv = L loc tv : acc
122 extractGenericPatTyVars :: LHsBinds RdrName -> [Located RdrName]
123 -- Get the type variables out of the type patterns in a bunch of
124 -- possibly-generic bindings in a class declaration
125 extractGenericPatTyVars binds
126 = nubBy eqLocated (foldrBag get [] binds)
128 get (L _ (FunBind _ _ (MatchGroup ms _))) acc = foldr (get_m.unLoc) acc ms
131 get_m (Match (L _ (TypePat ty) : _) _ _) acc = extract_lty ty acc
132 get_m other acc = acc
136 %************************************************************************
138 \subsection{Construction functions for Rdr stuff}
140 %************************************************************************
142 mkClassDecl builds a RdrClassDecl, filling in the names for tycon and datacon
143 by deriving them from the name of the class. We fill in the names for the
144 tycon and datacon corresponding to the class, by deriving them from the
145 name of the class itself. This saves recording the names in the interface
146 file (which would be equally good).
148 Similarly for mkConDecl, mkClassOpSig and default-method names.
150 *** See "THE NAMING STORY" in HsDecls ****
153 mkClassDecl (cxt, cname, tyvars) fds sigs mbinds
154 = ClassDecl { tcdCtxt = cxt, tcdLName = cname, tcdTyVars = tyvars,
160 mkTyData new_or_data (L _ (context, tname, tyvars)) ksig data_cons maybe_deriv
161 = TyData { tcdND = new_or_data, tcdCtxt = context, tcdLName = tname,
162 tcdTyVars = tyvars, tcdCons = data_cons,
163 tcdKindSig = ksig, tcdDerivs = maybe_deriv }
167 mkHsNegApp :: LHsExpr RdrName -> HsExpr RdrName
168 -- RdrName If the type checker sees (negate 3#) it will barf, because negate
169 -- can't take an unboxed arg. But that is exactly what it will see when
170 -- we write "-3#". So we have to do the negation right now!
171 mkHsNegApp (L loc e) = f e
172 where f (HsLit (HsIntPrim i)) = HsLit (HsIntPrim (-i))
173 f (HsLit (HsFloatPrim i)) = HsLit (HsFloatPrim (-i))
174 f (HsLit (HsDoublePrim i)) = HsLit (HsDoublePrim (-i))
175 f expr = NegApp (L loc e) placeHolderName
178 %************************************************************************
180 \subsection[cvBinds-etc]{Converting to @HsBinds@, etc.}
182 %************************************************************************
184 Function definitions are restructured here. Each is assumed to be recursive
185 initially, and non recursive definitions are discovered by the dependency
190 -- | Groups together bindings for a single function
191 cvTopDecls :: OrdList (LHsDecl RdrName) -> [LHsDecl RdrName]
192 cvTopDecls decls = go (fromOL decls)
194 go :: [LHsDecl RdrName] -> [LHsDecl RdrName]
196 go (L l (ValD b) : ds) = L l' (ValD b') : go ds'
197 where (L l' b', ds') = getMonoBind (L l b) ds
198 go (d : ds) = d : go ds
200 cvBindGroup :: OrdList (LHsDecl RdrName) -> HsBindGroup RdrName
202 = case (cvBindsAndSigs binding) of { (mbs, sigs) ->
203 HsBindGroup mbs sigs Recursive -- just one big group for now
206 cvBindsAndSigs :: OrdList (LHsDecl RdrName)
207 -> (Bag (LHsBind RdrName), [LSig RdrName])
208 -- Input decls contain just value bindings and signatures
209 cvBindsAndSigs fb = go (fromOL fb)
211 go [] = (emptyBag, [])
212 go (L l (SigD s) : ds) = (bs, L l s : ss)
213 where (bs,ss) = go ds
214 go (L l (ValD b) : ds) = (b' `consBag` bs, ss)
215 where (b',ds') = getMonoBind (L l b) ds
218 -----------------------------------------------------------------------------
219 -- Group function bindings into equation groups
221 getMonoBind :: LHsBind RdrName -> [LHsDecl RdrName]
222 -> (LHsBind RdrName, [LHsDecl RdrName])
223 -- Suppose (b',ds') = getMonoBind b ds
224 -- ds is a *reversed* list of parsed bindings
225 -- b is a MonoBinds that has just been read off the front
227 -- Then b' is the result of grouping more equations from ds that
228 -- belong with b into a single MonoBinds, and ds' is the depleted
229 -- list of parsed bindings.
231 -- No AndMonoBinds or EmptyMonoBinds here; just single equations
234 getMonoBind (L loc (FunBind lf@(L _ f) inf (MatchGroup mtchs _))) binds
238 go mtchs1 loc1 (L loc2 (ValD (FunBind f2 inf2 (MatchGroup mtchs2 _))) : binds)
239 | f == unLoc f2 = go (mtchs2++mtchs1) loc binds
240 where loc = combineSrcSpans loc1 loc2
242 = (L loc (FunBind lf inf (mkMatchGroup (reverse mtchs1))), binds)
243 -- reverse the final matches, to get it back in the right order
245 getMonoBind bind binds = (bind, binds)
247 has_args ((L _ (Match args _ _)) : _) = not (null args)
248 -- Don't group together FunBinds if they have
249 -- no arguments. This is necessary now that variable bindings
250 -- with no arguments are now treated as FunBinds rather
251 -- than pattern bindings (tests/rename/should_fail/rnfail002).
255 emptyGroup = HsGroup { hs_valds = [HsBindGroup emptyBag [] Recursive],
256 hs_tyclds = [], hs_instds = [],
257 hs_fixds = [], hs_defds = [], hs_fords = [],
258 hs_depds = [] ,hs_ruleds = [] }
260 findSplice :: [LHsDecl a] -> (HsGroup a, Maybe (SpliceDecl a, [LHsDecl a]))
261 findSplice ds = addl emptyGroup ds
263 mkGroup :: [LHsDecl a] -> HsGroup a
264 mkGroup ds = addImpDecls emptyGroup ds
266 addImpDecls :: HsGroup a -> [LHsDecl a] -> HsGroup a
267 -- The decls are imported, and should not have a splice
268 addImpDecls group decls = case addl group decls of
269 (group', Nothing) -> group'
270 other -> panic "addImpDecls"
272 addl :: HsGroup a -> [LHsDecl a] -> (HsGroup a, Maybe (SpliceDecl a, [LHsDecl a]))
273 -- This stuff reverses the declarations (again) but it doesn't matter
276 addl gp [] = (gp, Nothing)
277 addl gp (L l d : ds) = add gp l d ds
280 add :: HsGroup a -> SrcSpan -> HsDecl a -> [LHsDecl a]
281 -> (HsGroup a, Maybe (SpliceDecl a, [LHsDecl a]))
283 add gp l (SpliceD e) ds = (gp, Just (e, ds))
285 -- Class declarations: pull out the fixity signatures to the top
286 add gp@(HsGroup {hs_tyclds = ts, hs_fixds = fs}) l (TyClD d) ds
288 let fsigs = [ L l f | L l (FixSig f) <- tcdSigs d ] in
289 addl (gp { hs_tyclds = L l d : ts, hs_fixds = fsigs ++ fs }) ds
291 addl (gp { hs_tyclds = L l d : ts }) ds
293 -- Signatures: fixity sigs go a different place than all others
294 add gp@(HsGroup {hs_fixds = ts}) l (SigD (FixSig f)) ds
295 = addl (gp {hs_fixds = L l f : ts}) ds
296 add gp@(HsGroup {hs_valds = ts}) l (SigD d) ds
297 = addl (gp {hs_valds = add_sig (L l d) ts}) ds
299 -- Value declarations: use add_bind
300 add gp@(HsGroup {hs_valds = ts}) l (ValD d) ds
301 = addl (gp { hs_valds = add_bind (L l d) ts }) ds
303 -- The rest are routine
304 add gp@(HsGroup {hs_instds = ts}) l (InstD d) ds
305 = addl (gp { hs_instds = L l d : ts }) ds
306 add gp@(HsGroup {hs_defds = ts}) l (DefD d) ds
307 = addl (gp { hs_defds = L l d : ts }) ds
308 add gp@(HsGroup {hs_fords = ts}) l (ForD d) ds
309 = addl (gp { hs_fords = L l d : ts }) ds
310 add gp@(HsGroup {hs_depds = ts}) l (DeprecD d) ds
311 = addl (gp { hs_depds = L l d : ts }) ds
312 add gp@(HsGroup {hs_ruleds = ts}) l (RuleD d) ds
313 = addl (gp { hs_ruleds = L l d : ts }) ds
315 add_bind b [HsBindGroup bs sigs r] = [HsBindGroup (bs `snocBag` b) sigs r]
316 add_sig s [HsBindGroup bs sigs r] = [HsBindGroup bs (s:sigs) r]
319 %************************************************************************
321 \subsection[PrefixToHS-utils]{Utilities for conversion}
323 %************************************************************************
327 -----------------------------------------------------------------------------
330 -- When parsing data declarations, we sometimes inadvertently parse
331 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
332 -- This function splits up the type application, adds any pending
333 -- arguments, and converts the type constructor back into a data constructor.
335 mkPrefixCon :: LHsType RdrName -> [LBangType RdrName]
336 -> P (Located RdrName, HsConDetails RdrName (LBangType RdrName))
340 split (L _ (HsAppTy t u)) ts = split t (u : ts)
341 split (L l (HsTyVar tc)) ts = do data_con <- tyConToDataCon l tc
342 return (data_con, PrefixCon ts)
343 split (L l _) _ = parseError l "parse error in data/newtype declaration"
345 mkRecCon :: Located RdrName -> [([Located RdrName], LBangType RdrName)]
346 -> P (Located RdrName, HsConDetails RdrName (LBangType RdrName))
347 mkRecCon (L loc con) fields
348 = do data_con <- tyConToDataCon loc con
349 return (data_con, RecCon [ (l,t) | (ls,t) <- fields, l <- ls ])
351 tyConToDataCon :: SrcSpan -> RdrName -> P (Located RdrName)
352 tyConToDataCon loc tc
353 | isTcOcc (rdrNameOcc tc)
354 = return (L loc (setRdrNameSpace tc srcDataName))
356 = parseError loc (showSDoc (text "Not a constructor:" <+> quotes (ppr tc)))
358 ----------------------------------------------------------------------------
359 -- Various Syntactic Checks
361 checkInstType :: LHsType RdrName -> P (LHsType RdrName)
362 checkInstType (L l t)
364 HsForAllTy exp tvs ctxt ty -> do
365 dict_ty <- checkDictTy ty
366 return (L l (HsForAllTy exp tvs ctxt dict_ty))
368 HsParTy ty -> checkInstType ty
370 ty -> do dict_ty <- checkDictTy (L l ty)
371 return (L l (HsForAllTy Implicit [] (noLoc []) dict_ty))
373 checkTyVars :: [LHsType RdrName] -> P [LHsTyVarBndr RdrName]
377 -- Check that the name space is correct!
378 chk (L l (HsKindSig (L _ (HsTyVar tv)) k))
379 | isRdrTyVar tv = return (L l (KindedTyVar tv k))
380 chk (L l (HsTyVar tv))
381 | isRdrTyVar tv = return (L l (UserTyVar tv))
383 = parseError l "Type found where type variable expected"
385 checkSynHdr :: LHsType RdrName -> P (Located RdrName, [LHsTyVarBndr RdrName])
386 checkSynHdr ty = do { (_, tc, tvs) <- checkTyClHdr (noLoc []) ty
389 checkTyClHdr :: LHsContext RdrName -> LHsType RdrName
390 -> P (LHsContext RdrName, Located RdrName, [LHsTyVarBndr RdrName])
391 -- The header of a type or class decl should look like
392 -- (C a, D b) => T a b
396 checkTyClHdr (L l cxt) ty
397 = do (tc, tvs) <- gol ty []
399 return (L l cxt, tc, tvs)
401 gol (L l ty) acc = go l ty acc
403 go l (HsTyVar tc) acc
404 | not (isRdrTyVar tc) = checkTyVars acc >>= \ tvs ->
406 go l (HsOpTy t1 tc t2) acc = checkTyVars (t1:t2:acc) >>= \ tvs ->
408 go l (HsParTy ty) acc = gol ty acc
409 go l (HsAppTy t1 t2) acc = gol t1 (t2:acc)
410 go l other acc = parseError l "Malformed LHS to type of class declaration"
412 -- The predicates in a type or class decl must all
413 -- be HsClassPs. They need not all be type variables,
414 -- even in Haskell 98. E.g. class (Monad m, Monad (t m)) => MonadT t m
415 chk_pred (L l (HsClassP _ args)) = return ()
417 = parseError l "Malformed context in type or class declaration"
420 checkContext :: LHsType RdrName -> P (LHsContext RdrName)
424 check (HsTupleTy _ ts) -- (Eq a, Ord b) shows up as a tuple type
425 = do ctx <- mapM checkPred ts
428 check (HsParTy ty) -- to be sure HsParTy doesn't get into the way
431 check (HsTyVar t) -- Empty context shows up as a unit type ()
432 | t == getRdrName unitTyCon = return (L l [])
435 = do p <- checkPred (L l t)
439 checkPred :: LHsType RdrName -> P (LHsPred RdrName)
440 -- Watch out.. in ...deriving( Show )... we use checkPred on
441 -- the list of partially applied predicates in the deriving,
442 -- so there can be zero args.
443 checkPred (L spn (HsPredTy (HsIParam n ty)))
444 = return (L spn (HsIParam n ty))
448 checkl (L l ty) args = check l ty args
450 check _loc (HsTyVar t) args | not (isRdrTyVar t)
451 = return (L spn (HsClassP t args))
452 check _loc (HsAppTy l r) args = checkl l (r:args)
453 check _loc (HsOpTy l (L loc tc) r) args = check loc (HsTyVar tc) (l:r:args)
454 check _loc (HsParTy t) args = checkl t args
455 check loc _ _ = parseError loc "malformed class assertion"
457 checkDictTy :: LHsType RdrName -> P (LHsType RdrName)
458 checkDictTy (L spn ty) = check ty []
460 check (HsTyVar t) args | not (isRdrTyVar t)
461 = return (L spn (HsPredTy (HsClassP t args)))
462 check (HsAppTy l r) args = check (unLoc l) (r:args)
463 check (HsParTy t) args = check (unLoc t) args
464 check _ _ = parseError spn "Malformed context in instance header"
466 ---------------------------------------------------------------------------
467 -- Checking statements in a do-expression
468 -- We parse do { e1 ; e2 ; }
469 -- as [ExprStmt e1, ExprStmt e2]
470 -- checkDo (a) checks that the last thing is an ExprStmt
471 -- (b) transforms it to a ResultStmt
472 -- same comments apply for mdo as well
474 checkDo = checkDoMDo "a " "'do'"
475 checkMDo = checkDoMDo "an " "'mdo'"
477 checkDoMDo :: String -> String -> SrcSpan -> [LStmt RdrName] -> P [LStmt RdrName]
478 checkDoMDo pre nm loc [] = parseError loc ("Empty " ++ nm ++ " construct")
479 checkDoMDo pre nm loc ss = do
482 check [L l (ExprStmt e _)] = return [L l (ResultStmt e)]
483 check [L l _] = parseError l ("The last statement in " ++ pre ++ nm ++
484 " construct must be an expression")
489 -- -------------------------------------------------------------------------
490 -- Checking Patterns.
492 -- We parse patterns as expressions and check for valid patterns below,
493 -- converting the expression into a pattern at the same time.
495 checkPattern :: LHsExpr RdrName -> P (LPat RdrName)
496 checkPattern e = checkLPat e
498 checkPatterns :: [LHsExpr RdrName] -> P [LPat RdrName]
499 checkPatterns es = mapM checkPattern es
501 checkLPat :: LHsExpr RdrName -> P (LPat RdrName)
502 checkLPat e@(L l _) = checkPat l e []
504 checkPat :: SrcSpan -> LHsExpr RdrName -> [LPat RdrName] -> P (LPat RdrName)
505 checkPat loc (L l (HsVar c)) args
506 | isRdrDataCon c = return (L loc (ConPatIn (L l c) (PrefixCon args)))
507 checkPat loc (L _ (HsApp f x)) args = do
509 checkPat loc f (x:args)
510 checkPat loc (L _ e) [] = do
513 checkPat loc pat _some_args
516 checkAPat loc e = case e of
517 EWildPat -> return (WildPat placeHolderType)
518 HsVar x | isQual x -> parseError loc ("Qualified variable in pattern: "
520 | otherwise -> return (VarPat x)
521 HsLit l -> return (LitPat l)
523 -- Overloaded numeric patterns (e.g. f 0 x = x)
524 -- Negation is recorded separately, so that the literal is zero or +ve
525 -- NB. Negative *primitive* literals are already handled by
526 -- RdrHsSyn.mkHsNegApp
527 HsOverLit pos_lit -> return (NPatIn pos_lit Nothing)
528 NegApp (L _ (HsOverLit pos_lit)) _
529 -> return (NPatIn pos_lit (Just placeHolderName))
531 ELazyPat e -> checkLPat e >>= (return . LazyPat)
532 EAsPat n e -> checkLPat e >>= (return . AsPat n)
533 ExprWithTySig e t -> checkLPat e >>= \e ->
534 -- Pattern signatures are parsed as sigtypes,
535 -- but they aren't explicit forall points. Hence
536 -- we have to remove the implicit forall here.
538 L _ (HsForAllTy Implicit _ (L _ []) ty) -> ty
541 return (SigPatIn e t')
544 OpApp (L nloc (HsVar n)) (L _ (HsVar plus)) _
545 (L _ (HsOverLit lit@(HsIntegral _ _)))
547 -> return (mkNPlusKPat (L nloc n) lit)
549 plus_RDR = mkUnqual varName FSLIT("+") -- Hack
551 OpApp l op fix r -> checkLPat l >>= \l ->
552 checkLPat r >>= \r ->
554 L cl (HsVar c) | isDataOcc (rdrNameOcc c)
555 -> return (ConPatIn (L cl c) (InfixCon l r))
558 HsPar e -> checkLPat e >>= (return . ParPat)
559 ExplicitList _ es -> mapM (\e -> checkLPat e) es >>= \ps ->
560 return (ListPat ps placeHolderType)
561 ExplicitPArr _ es -> mapM (\e -> checkLPat e) es >>= \ps ->
562 return (PArrPat ps placeHolderType)
564 ExplicitTuple es b -> mapM (\e -> checkLPat e) es >>= \ps ->
565 return (TuplePat ps b)
567 RecordCon c fs -> mapM checkPatField fs >>= \fs ->
568 return (ConPatIn c (RecCon fs))
570 HsType ty -> return (TypePat ty)
573 checkPatField :: (Located RdrName, LHsExpr RdrName) -> P (Located RdrName, LPat RdrName)
574 checkPatField (n,e) = do
578 patFail loc = parseError loc "Parse error in pattern"
581 ---------------------------------------------------------------------------
582 -- Check Equation Syntax
586 -> Maybe (LHsType RdrName)
587 -> Located (GRHSs RdrName)
588 -> P (HsBind RdrName)
590 checkValDef lhs opt_sig (L rhs_span grhss)
591 | Just (f,inf,es) <- isFunLhs lhs []
592 = if isQual (unLoc f)
593 then parseError (getLoc f) ("Qualified name in function definition: " ++
594 showRdrName (unLoc f))
595 else do ps <- checkPatterns es
596 let match_span = combineSrcSpans (getLoc lhs) rhs_span
597 return (FunBind f inf (mkMatchGroup [L match_span (Match ps opt_sig grhss)]))
598 -- The span of the match covers the entire equation.
599 -- That isn't quite right, but it'll do for now.
601 lhs <- checkPattern lhs
602 return (PatBind lhs grhss placeHolderType)
608 checkValSig (L l (HsVar v)) ty | isUnqual v = return (Sig (L l v) ty)
609 checkValSig (L l other) ty
610 = parseError l "Type signature given for an expression"
612 -- A variable binding is parsed as a FunBind.
614 isFunLhs :: LHsExpr RdrName -> [LHsExpr RdrName]
615 -> Maybe (Located RdrName, Bool, [LHsExpr RdrName])
616 isFunLhs (L loc e) = isFunLhs' loc e
618 isFunLhs' loc (HsVar f) es
619 | not (isRdrDataCon f) = Just (L loc f, False, es)
620 isFunLhs' loc (HsApp f e) es = isFunLhs f (e:es)
621 isFunLhs' loc (HsPar e) es@(_:_) = isFunLhs e es
622 isFunLhs' loc (OpApp l (L loc' (HsVar op)) fix r) es
623 | not (isRdrDataCon op) = Just (L loc' op, True, (l:r:es))
625 case isFunLhs l es of
626 Just (op', True, j : k : es') ->
628 j : L loc (OpApp k (L loc' (HsVar op)) fix r) : es')
630 isFunLhs' _ _ _ = Nothing
632 ---------------------------------------------------------------------------
633 -- Miscellaneous utilities
635 checkPrecP :: Located Int -> P Int
637 | 0 <= i && i <= maxPrecedence = return i
638 | otherwise = parseError l "Precedence out of range"
643 -> HsRecordBinds RdrName
644 -> P (HsExpr RdrName)
646 mkRecConstrOrUpdate (L l (HsVar c)) loc fs | isRdrDataCon c
647 = return (RecordCon (L l c) fs)
648 mkRecConstrOrUpdate exp loc fs@(_:_)
649 = return (RecordUpd exp fs)
650 mkRecConstrOrUpdate _ loc []
651 = parseError loc "Empty record update"
653 -----------------------------------------------------------------------------
654 -- utilities for foreign declarations
656 -- supported calling conventions
658 data CallConv = CCall CCallConv -- ccall or stdcall
661 -- construct a foreign import declaration
665 -> (Located FastString, Located RdrName, LHsType RdrName)
666 -> P (HsDecl RdrName)
667 mkImport (CCall cconv) safety (entity, v, ty) = do
668 importSpec <- parseCImport entity cconv safety v
669 return (ForD (ForeignImport v ty importSpec False))
670 mkImport (DNCall ) _ (entity, v, ty) = do
671 spec <- parseDImport entity
672 return $ ForD (ForeignImport v ty (DNImport spec) False)
674 -- parse the entity string of a foreign import declaration for the `ccall' or
675 -- `stdcall' calling convention'
677 parseCImport :: Located FastString
682 parseCImport (L loc entity) cconv safety v
683 -- FIXME: we should allow white space around `dynamic' and `wrapper' -=chak
684 | entity == FSLIT ("dynamic") =
685 return $ CImport cconv safety nilFS nilFS (CFunction DynamicTarget)
686 | entity == FSLIT ("wrapper") =
687 return $ CImport cconv safety nilFS nilFS CWrapper
688 | otherwise = parse0 (unpackFS entity)
690 -- using the static keyword?
691 parse0 (' ': rest) = parse0 rest
692 parse0 ('s':'t':'a':'t':'i':'c':rest) = parse1 rest
693 parse0 rest = parse1 rest
694 -- check for header file name
695 parse1 "" = parse4 "" nilFS False nilFS
696 parse1 (' ':rest) = parse1 rest
697 parse1 str@('&':_ ) = parse2 str nilFS
698 parse1 str@('[':_ ) = parse3 str nilFS False
700 | ".h" `isSuffixOf` first = parse2 rest (mkFastString first)
701 | otherwise = parse4 str nilFS False nilFS
703 (first, rest) = break (\c -> c == ' ' || c == '&' || c == '[') str
704 -- check for address operator (indicating a label import)
705 parse2 "" header = parse4 "" header False nilFS
706 parse2 (' ':rest) header = parse2 rest header
707 parse2 ('&':rest) header = parse3 rest header True
708 parse2 str@('[':_ ) header = parse3 str header False
709 parse2 str header = parse4 str header False nilFS
710 -- check for library object name
711 parse3 (' ':rest) header isLbl = parse3 rest header isLbl
712 parse3 ('[':rest) header isLbl =
713 case break (== ']') rest of
714 (lib, ']':rest) -> parse4 rest header isLbl (mkFastString lib)
715 _ -> parseError loc "Missing ']' in entity"
716 parse3 str header isLbl = parse4 str header isLbl nilFS
717 -- check for name of C function
718 parse4 "" header isLbl lib = build (mkExtName (unLoc v)) header isLbl lib
719 parse4 (' ':rest) header isLbl lib = parse4 rest header isLbl lib
720 parse4 str header isLbl lib
721 | all (== ' ') rest = build (mkFastString first) header isLbl lib
722 | otherwise = parseError loc "Malformed entity string"
724 (first, rest) = break (== ' ') str
726 build cid header False lib = return $
727 CImport cconv safety header lib (CFunction (StaticTarget cid))
728 build cid header True lib = return $
729 CImport cconv safety header lib (CLabel cid )
732 -- Unravel a dotnet spec string.
734 parseDImport :: Located FastString -> P DNCallSpec
735 parseDImport (L loc entity) = parse0 comps
737 comps = words (unpackFS entity)
741 | x == "static" = parse1 True xs
742 | otherwise = parse1 False (x:xs)
745 parse1 isStatic (x:xs)
746 | x == "method" = parse2 isStatic DNMethod xs
747 | x == "field" = parse2 isStatic DNField xs
748 | x == "ctor" = parse2 isStatic DNConstructor xs
749 parse1 isStatic xs = parse2 isStatic DNMethod xs
752 parse2 isStatic kind (('[':x):xs) =
755 vs | last vs == ']' -> parse3 isStatic kind (init vs) xs
756 parse2 isStatic kind xs = parse3 isStatic kind "" xs
758 parse3 isStatic kind assem [x] =
759 return (DNCallSpec isStatic kind assem x
760 -- these will be filled in once known.
761 (error "FFI-dotnet-args")
762 (error "FFI-dotnet-result"))
763 parse3 _ _ _ _ = d'oh
765 d'oh = parseError loc "Malformed entity string"
767 -- construct a foreign export declaration
770 -> (Located FastString, Located RdrName, LHsType RdrName)
771 -> P (HsDecl RdrName)
772 mkExport (CCall cconv) (L loc entity, v, ty) = return $
773 ForD (ForeignExport v ty (CExport (CExportStatic entity' cconv)) False)
775 entity' | nullFastString entity = mkExtName (unLoc v)
777 mkExport DNCall (L loc entity, v, ty) =
778 parseError (getLoc v){-TODO: not quite right-}
779 "Foreign export is not yet supported for .NET"
781 -- Supplying the ext_name in a foreign decl is optional; if it
782 -- isn't there, the Haskell name is assumed. Note that no transformation
783 -- of the Haskell name is then performed, so if you foreign export (++),
784 -- it's external name will be "++". Too bad; it's important because we don't
785 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
786 -- (This is why we use occNameUserString.)
788 mkExtName :: RdrName -> CLabelString
789 mkExtName rdrNm = mkFastString (occNameUserString (rdrNameOcc rdrNm))
793 -----------------------------------------------------------------------------
797 showRdrName :: RdrName -> String
798 showRdrName r = showSDoc (ppr r)
800 parseError :: SrcSpan -> String -> P a
801 parseError span s = failSpanMsgP span s