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, mkInlineSpec,
15 mkRecConstrOrUpdate, -- HsExp -> [HsFieldUpdate] -> P HsExp
22 -- Stuff to do with Foreign declarations
24 mkImport, -- CallConv -> Safety
25 -- -> (FastString, RdrName, RdrNameHsType)
28 -- -> (FastString, RdrName, RdrNameHsType)
30 mkExtName, -- RdrName -> CLabelString
31 mkGadtDecl, -- Located RdrName -> LHsType RdrName -> ConDecl RdrName
33 -- Bunch of functions in the parser monad for
34 -- checking and constructing values
35 checkPrecP, -- Int -> P Int
36 checkContext, -- HsType -> P HsContext
37 checkPred, -- HsType -> P HsPred
38 checkTyClHdr, -- LHsContext RdrName -> LHsType RdrName -> P (LHsContext RdrName, Located RdrName, [LHsTyVarBndr RdrName], [LHsType RdrName])
39 checkTyVars, -- [LHsType RdrName] -> P ()
40 checkSynHdr, -- LHsType RdrName -> P (Located RdrName, [LHsTyVarBndr RdrName], [LHsType RdrName])
41 checkKindSigs, -- [LTyClDecl RdrName] -> P ()
42 checkInstType, -- HsType -> P HsType
43 checkDerivDecl, -- LDerivDecl RdrName -> P (LDerivDecl RdrName)
44 checkPattern, -- HsExp -> P HsPat
45 checkPatterns, -- SrcLoc -> [HsExp] -> P [HsPat]
46 checkDo, -- [Stmt] -> P [Stmt]
47 checkMDo, -- [Stmt] -> P [Stmt]
48 checkValDef, -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
49 checkValSig, -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
50 parseError, -- String -> Pa
53 #include "HsVersions.h"
55 import HsSyn -- Lots of it
56 import RdrName ( RdrName, isRdrTyVar, mkUnqual, rdrNameOcc,
57 isRdrDataCon, isUnqual, getRdrName, isQual,
59 import BasicTypes ( maxPrecedence, Activation, InlineSpec(..), alwaysInlineSpec, neverInlineSpec )
60 import Lexer ( P, failSpanMsgP, extension, glaExtsEnabled, bangPatEnabled )
61 import TysWiredIn ( unitTyCon )
62 import ForeignCall ( CCallConv, Safety, CCallTarget(..), CExportSpec(..),
63 DNCallSpec(..), DNKind(..), CLabelString )
64 import OccName ( srcDataName, varName, isDataOcc, isTcOcc,
67 import OrdList ( OrdList, fromOL )
68 import Bag ( Bag, emptyBag, snocBag, consBag, foldrBag )
73 import List ( isSuffixOf, nubBy )
74 import Monad ( unless )
78 %************************************************************************
80 \subsection{A few functions over HsSyn at RdrName}
82 %************************************************************************
84 extractHsTyRdrNames finds the free variables of a HsType
85 It's used when making the for-alls explicit.
88 extractHsTyRdrTyVars :: LHsType RdrName -> [Located RdrName]
89 extractHsTyRdrTyVars ty = nubBy eqLocated (extract_lty ty [])
91 extractHsRhoRdrTyVars :: LHsContext RdrName -> LHsType RdrName -> [Located RdrName]
92 -- This one takes the context and tau-part of a
93 -- sigma type and returns their free type variables
94 extractHsRhoRdrTyVars ctxt ty
95 = nubBy eqLocated $ extract_lctxt ctxt (extract_lty ty [])
97 extract_lctxt ctxt acc = foldr (extract_pred . unLoc) acc (unLoc ctxt)
99 extract_pred (HsClassP cls tys) acc = foldr extract_lty acc tys
100 extract_pred (HsIParam n ty) acc = extract_lty ty acc
102 extract_lty (L loc ty) acc
104 HsTyVar tv -> extract_tv loc tv acc
105 HsBangTy _ ty -> extract_lty ty acc
106 HsAppTy ty1 ty2 -> extract_lty ty1 (extract_lty ty2 acc)
107 HsListTy ty -> extract_lty ty acc
108 HsPArrTy ty -> extract_lty ty acc
109 HsTupleTy _ tys -> foldr extract_lty acc tys
110 HsFunTy ty1 ty2 -> extract_lty ty1 (extract_lty ty2 acc)
111 HsPredTy p -> extract_pred p acc
112 HsOpTy ty1 (L loc tv) ty2 -> extract_tv loc tv (extract_lty ty1 (extract_lty ty2 acc))
113 HsParTy ty -> extract_lty ty acc
115 HsSpliceTy _ -> acc -- Type splices mention no type variables
116 HsKindSig ty k -> extract_lty ty acc
117 HsForAllTy exp [] cx ty -> extract_lctxt cx (extract_lty ty acc)
118 HsForAllTy exp tvs cx ty -> acc ++ (filter ((`notElem` locals) . unLoc) $
119 extract_lctxt cx (extract_lty ty []))
121 locals = hsLTyVarNames tvs
123 extract_tv :: SrcSpan -> RdrName -> [Located RdrName] -> [Located RdrName]
124 extract_tv loc tv acc | isRdrTyVar tv = L loc tv : acc
127 extractGenericPatTyVars :: LHsBinds RdrName -> [Located RdrName]
128 -- Get the type variables out of the type patterns in a bunch of
129 -- possibly-generic bindings in a class declaration
130 extractGenericPatTyVars binds
131 = nubBy eqLocated (foldrBag get [] binds)
133 get (L _ (FunBind { fun_matches = MatchGroup ms _ })) acc = foldr (get_m.unLoc) acc ms
136 get_m (Match (L _ (TypePat ty) : _) _ _) acc = extract_lty ty acc
137 get_m other acc = acc
141 %************************************************************************
143 \subsection{Construction functions for Rdr stuff}
145 %************************************************************************
147 mkClassDecl builds a RdrClassDecl, filling in the names for tycon and datacon
148 by deriving them from the name of the class. We fill in the names for the
149 tycon and datacon corresponding to the class, by deriving them from the
150 name of the class itself. This saves recording the names in the interface
151 file (which would be equally good).
153 Similarly for mkConDecl, mkClassOpSig and default-method names.
155 *** See "THE NAMING STORY" in HsDecls ****
158 mkClassDecl (cxt, cname, tyvars) fds sigs mbinds ats
159 = ClassDecl { tcdCtxt = cxt, tcdLName = cname, tcdTyVars = tyvars,
166 mkTyData new_or_data (context, tname, tyvars, typats) ksig data_cons maybe_deriv
167 = TyData { tcdND = new_or_data, tcdCtxt = context, tcdLName = tname,
168 tcdTyVars = tyvars, tcdTyPats = typats, tcdCons = data_cons,
169 tcdKindSig = ksig, tcdDerivs = maybe_deriv }
173 mkHsNegApp :: LHsExpr RdrName -> HsExpr RdrName
174 -- RdrName If the type checker sees (negate 3#) it will barf, because negate
175 -- can't take an unboxed arg. But that is exactly what it will see when
176 -- we write "-3#". So we have to do the negation right now!
177 mkHsNegApp (L loc e) = f e
178 where f (HsLit (HsIntPrim i)) = HsLit (HsIntPrim (-i))
179 f (HsLit (HsFloatPrim i)) = HsLit (HsFloatPrim (-i))
180 f (HsLit (HsDoublePrim i)) = HsLit (HsDoublePrim (-i))
181 f expr = NegApp (L loc e) noSyntaxExpr
184 %************************************************************************
186 \subsection[cvBinds-etc]{Converting to @HsBinds@, etc.}
188 %************************************************************************
190 Function definitions are restructured here. Each is assumed to be recursive
191 initially, and non recursive definitions are discovered by the dependency
196 -- | Groups together bindings for a single function
197 cvTopDecls :: OrdList (LHsDecl RdrName) -> [LHsDecl RdrName]
198 cvTopDecls decls = go (fromOL decls)
200 go :: [LHsDecl RdrName] -> [LHsDecl RdrName]
202 go (L l (ValD b) : ds) = L l' (ValD b') : go ds'
203 where (L l' b', ds') = getMonoBind (L l b) ds
204 go (d : ds) = d : go ds
206 -- Declaration list may only contain value bindings and signatures
208 cvBindGroup :: OrdList (LHsDecl RdrName) -> HsValBinds RdrName
210 = case cvBindsAndSigs binding of
211 (mbs, sigs, []) -> -- list of type decls *always* empty
214 cvBindsAndSigs :: OrdList (LHsDecl RdrName)
215 -> (Bag (LHsBind RdrName), [LSig RdrName], [LTyClDecl RdrName])
216 -- Input decls contain just value bindings and signatures
217 -- and in case of class or instance declarations also
218 -- associated type declarations
219 cvBindsAndSigs fb = go (fromOL fb)
221 go [] = (emptyBag, [], [])
222 go (L l (SigD s) : ds) = (bs, L l s : ss, ts)
223 where (bs, ss, ts) = go ds
224 go (L l (ValD b) : ds) = (b' `consBag` bs, ss, ts)
225 where (b', ds') = getMonoBind (L l b) ds
226 (bs, ss, ts) = go ds'
227 go (L l (TyClD t): ds) = (bs, ss, L l t : ts)
228 where (bs, ss, ts) = go ds
230 -----------------------------------------------------------------------------
231 -- Group function bindings into equation groups
233 getMonoBind :: LHsBind RdrName -> [LHsDecl RdrName]
234 -> (LHsBind RdrName, [LHsDecl RdrName])
235 -- Suppose (b',ds') = getMonoBind b ds
236 -- ds is a list of parsed bindings
237 -- b is a MonoBinds that has just been read off the front
239 -- Then b' is the result of grouping more equations from ds that
240 -- belong with b into a single MonoBinds, and ds' is the depleted
241 -- list of parsed bindings.
243 -- No AndMonoBinds or EmptyMonoBinds here; just single equations
245 getMonoBind (L loc1 bind@(FunBind { fun_id = fun_id1@(L _ f1), fun_infix = is_infix1,
246 fun_matches = MatchGroup mtchs1 _ })) binds
248 = go is_infix1 mtchs1 loc1 binds
250 go is_infix mtchs loc
251 (L loc2 (ValD (FunBind { fun_id = L _ f2, fun_infix = is_infix2,
252 fun_matches = MatchGroup mtchs2 _ })) : binds)
253 | f1 == f2 = go (is_infix || is_infix2) (mtchs2 ++ mtchs)
254 (combineSrcSpans loc loc2) binds
255 go is_infix mtchs loc binds
256 = (L loc (makeFunBind fun_id1 is_infix (reverse mtchs)), binds)
257 -- Reverse the final matches, to get it back in the right order
259 getMonoBind bind binds = (bind, binds)
261 has_args ((L _ (Match args _ _)) : _) = not (null args)
262 -- Don't group together FunBinds if they have
263 -- no arguments. This is necessary now that variable bindings
264 -- with no arguments are now treated as FunBinds rather
265 -- than pattern bindings (tests/rename/should_fail/rnfail002).
269 findSplice :: [LHsDecl a] -> (HsGroup a, Maybe (SpliceDecl a, [LHsDecl a]))
270 findSplice ds = addl emptyRdrGroup ds
272 mkGroup :: [LHsDecl a] -> HsGroup a
273 mkGroup ds = addImpDecls emptyRdrGroup ds
275 addImpDecls :: HsGroup a -> [LHsDecl a] -> HsGroup a
276 -- The decls are imported, and should not have a splice
277 addImpDecls group decls = case addl group decls of
278 (group', Nothing) -> group'
279 other -> panic "addImpDecls"
281 addl :: HsGroup a -> [LHsDecl a] -> (HsGroup a, Maybe (SpliceDecl a, [LHsDecl a]))
282 -- This stuff reverses the declarations (again) but it doesn't matter
285 addl gp [] = (gp, Nothing)
286 addl gp (L l d : ds) = add gp l d ds
289 add :: HsGroup a -> SrcSpan -> HsDecl a -> [LHsDecl a]
290 -> (HsGroup a, Maybe (SpliceDecl a, [LHsDecl a]))
292 add gp l (SpliceD e) ds = (gp, Just (e, ds))
294 -- Class declarations: pull out the fixity signatures to the top
295 add gp@(HsGroup {hs_tyclds = ts, hs_fixds = fs}) l (TyClD d) ds
297 let fsigs = [ L l f | L l (FixSig f) <- tcdSigs d ] in
298 addl (gp { hs_tyclds = L l d : ts, hs_fixds = fsigs ++ fs }) ds
300 addl (gp { hs_tyclds = L l d : ts }) ds
302 -- Signatures: fixity sigs go a different place than all others
303 add gp@(HsGroup {hs_fixds = ts}) l (SigD (FixSig f)) ds
304 = addl (gp {hs_fixds = L l f : ts}) ds
305 add gp@(HsGroup {hs_valds = ts}) l (SigD d) ds
306 = addl (gp {hs_valds = add_sig (L l d) ts}) ds
308 -- Value declarations: use add_bind
309 add gp@(HsGroup {hs_valds = ts}) l (ValD d) ds
310 = addl (gp { hs_valds = add_bind (L l d) ts }) ds
312 -- The rest are routine
313 add gp@(HsGroup {hs_instds = ts}) l (InstD d) ds
314 = addl (gp { hs_instds = L l d : ts }) ds
315 add gp@(HsGroup {hs_defds = ts}) l (DefD d) ds
316 = addl (gp { hs_defds = L l d : ts }) ds
317 add gp@(HsGroup {hs_fords = ts}) l (ForD d) ds
318 = addl (gp { hs_fords = L l d : ts }) ds
319 add gp@(HsGroup {hs_depds = ts}) l (DeprecD d) ds
320 = addl (gp { hs_depds = L l d : ts }) ds
321 add gp@(HsGroup {hs_ruleds = ts}) l (RuleD d) ds
322 = addl (gp { hs_ruleds = L l d : ts }) ds
324 add_bind b (ValBindsIn bs sigs) = ValBindsIn (bs `snocBag` b) sigs
325 add_sig s (ValBindsIn bs sigs) = ValBindsIn bs (s:sigs)
328 %************************************************************************
330 \subsection[PrefixToHS-utils]{Utilities for conversion}
332 %************************************************************************
336 -----------------------------------------------------------------------------
339 -- When parsing data declarations, we sometimes inadvertently parse
340 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
341 -- This function splits up the type application, adds any pending
342 -- arguments, and converts the type constructor back into a data constructor.
344 mkPrefixCon :: LHsType RdrName -> [LBangType RdrName]
345 -> P (Located RdrName, HsConDetails RdrName (LBangType RdrName))
349 split (L _ (HsAppTy t u)) ts = split t (u : ts)
350 split (L l (HsTyVar tc)) ts = do data_con <- tyConToDataCon l tc
351 return (data_con, PrefixCon ts)
352 split (L l _) _ = parseError l "parse error in data/newtype declaration"
354 mkRecCon :: Located RdrName -> [([Located RdrName], LBangType RdrName)]
355 -> P (Located RdrName, HsConDetails RdrName (LBangType RdrName))
356 mkRecCon (L loc con) fields
357 = do data_con <- tyConToDataCon loc con
358 return (data_con, RecCon [ (l,t) | (ls,t) <- fields, l <- ls ])
360 tyConToDataCon :: SrcSpan -> RdrName -> P (Located RdrName)
361 tyConToDataCon loc tc
362 | isTcOcc (rdrNameOcc tc)
363 = return (L loc (setRdrNameSpace tc srcDataName))
365 = parseError loc (showSDoc (text "Not a constructor:" <+> quotes (ppr tc)))
367 ----------------------------------------------------------------------------
368 -- Various Syntactic Checks
370 checkInstType :: LHsType RdrName -> P (LHsType RdrName)
371 checkInstType (L l t)
373 HsForAllTy exp tvs ctxt ty -> do
374 dict_ty <- checkDictTy ty
375 return (L l (HsForAllTy exp tvs ctxt dict_ty))
377 HsParTy ty -> checkInstType ty
379 ty -> do dict_ty <- checkDictTy (L l ty)
380 return (L l (HsForAllTy Implicit [] (noLoc []) dict_ty))
382 -- Check whether the given list of type parameters are all type variables
383 -- (possibly with a kind signature). If the second argument is `False',
384 -- only type variables are allowed and we raise an error on encountering a
385 -- non-variable; otherwise, we allow non-variable arguments and return the
386 -- entire list of parameters.
388 checkTyVars :: [LHsType RdrName] -> P ()
389 checkTyVars tparms = mapM_ chk tparms
391 -- Check that the name space is correct!
392 chk (L l (HsKindSig (L _ (HsTyVar tv)) k))
393 | isRdrTyVar tv = return ()
394 chk (L l (HsTyVar tv))
395 | isRdrTyVar tv = return ()
397 parseError l "Type found where type variable expected"
399 -- Check whether the type arguments in a type synonym head are simply
400 -- variables. If not, we have a type equation of a type function and return
401 -- all patterns. If yes, we return 'Nothing' as the third component to
402 -- indicate a vanilla type synonym.
404 checkSynHdr :: LHsType RdrName
405 -> Bool -- is type instance?
406 -> P (Located RdrName, -- head symbol
407 [LHsTyVarBndr RdrName], -- parameters
408 [LHsType RdrName]) -- type patterns
409 checkSynHdr ty isTyInst =
410 do { (_, tc, tvs, tparms) <- checkTyClHdr (noLoc []) ty
411 ; unless isTyInst $ checkTyVars tparms
412 ; return (tc, tvs, tparms) }
415 -- Well-formedness check and decomposition of type and class heads.
417 checkTyClHdr :: LHsContext RdrName -> LHsType RdrName
418 -> P (LHsContext RdrName, -- the type context
419 Located RdrName, -- the head symbol (type or class name)
420 [LHsTyVarBndr RdrName], -- free variables of the non-context part
421 [LHsType RdrName]) -- parameters of head symbol
422 -- The header of a type or class decl should look like
423 -- (C a, D b) => T a b
427 -- With associated types, we can also have non-variable parameters; ie,
429 -- The unaltered parameter list is returned in the fourth component of the
433 -- ('()', 'T', ['a'], ['Int', '[a]'])
434 checkTyClHdr (L l cxt) ty
435 = do (tc, tvs, parms) <- gol ty []
437 return (L l cxt, tc, tvs, parms)
439 gol (L l ty) acc = go l ty acc
441 go l (HsTyVar tc) acc
442 | not (isRdrTyVar tc) = do
443 tvs <- extractTyVars acc
444 return (L l tc, tvs, acc)
445 go l (HsOpTy t1 tc t2) acc = do
446 tvs <- extractTyVars (t1:t2:acc)
447 return (tc, tvs, acc)
448 go l (HsParTy ty) acc = gol ty acc
449 go l (HsAppTy t1 t2) acc = gol t1 (t2:acc)
451 parseError l "Malformed head of type or class declaration"
453 -- The predicates in a type or class decl must all
454 -- be HsClassPs. They need not all be type variables,
455 -- even in Haskell 98. E.g. class (Monad m, Monad (t m)) => MonadT t m
456 chk_pred (L l (HsClassP _ args)) = return ()
458 = parseError l "Malformed context in type or class declaration"
460 -- Extract the type variables of a list of type parameters.
462 -- * Type arguments can be complex type terms (needed for associated type
465 extractTyVars :: [LHsType RdrName] -> P [LHsTyVarBndr RdrName]
466 extractTyVars tvs = collects [] tvs
468 -- Collect all variables (1st arg serves as an accumulator)
469 collect tvs (L l (HsForAllTy _ _ _ _)) =
470 parseError l "Forall type not allowed as type parameter"
471 collect tvs (L l (HsTyVar tv))
472 | isRdrTyVar tv = return $ L l (UserTyVar tv) : tvs
473 | otherwise = return tvs
474 collect tvs (L l (HsBangTy _ _ )) =
475 parseError l "Bang-style type annotations not allowed as type parameter"
476 collect tvs (L l (HsAppTy t1 t2 )) = do
477 tvs' <- collect tvs t2
479 collect tvs (L l (HsFunTy t1 t2 )) = do
480 tvs' <- collect tvs t2
482 collect tvs (L l (HsListTy t )) = collect tvs t
483 collect tvs (L l (HsPArrTy t )) = collect tvs t
484 collect tvs (L l (HsTupleTy _ ts )) = collects tvs ts
485 collect tvs (L l (HsOpTy t1 _ t2 )) = do
486 tvs' <- collect tvs t2
488 collect tvs (L l (HsParTy t )) = collect tvs t
489 collect tvs (L l (HsNumTy t )) = return tvs
490 collect tvs (L l (HsPredTy t )) =
491 parseError l "Predicate not allowed as type parameter"
492 collect tvs (L l (HsKindSig (L _ (HsTyVar tv)) k))
494 return $ L l (KindedTyVar tv k) : tvs
496 parseError l "Kind signature only allowed for type variables"
497 collect tvs (L l (HsSpliceTy t )) =
498 parseError l "Splice not allowed as type parameter"
500 -- Collect all variables of a list of types
501 collects tvs [] = return tvs
502 collects tvs (t:ts) = do
503 tvs' <- collects tvs ts
506 -- Check that associated type declarations of a class are all kind signatures.
508 checkKindSigs :: [LTyClDecl RdrName] -> P ()
509 checkKindSigs = mapM_ check
512 | isKindSigDecl tydecl
513 || isSynDecl tydecl = return ()
515 parseError l "Type declaration in a class must be a kind signature or synonym default"
517 checkContext :: LHsType RdrName -> P (LHsContext RdrName)
521 check (HsTupleTy _ ts) -- (Eq a, Ord b) shows up as a tuple type
522 = do ctx <- mapM checkPred ts
525 check (HsParTy ty) -- to be sure HsParTy doesn't get into the way
528 check (HsTyVar t) -- Empty context shows up as a unit type ()
529 | t == getRdrName unitTyCon = return (L l [])
532 = do p <- checkPred (L l t)
536 checkPred :: LHsType RdrName -> P (LHsPred RdrName)
537 -- Watch out.. in ...deriving( Show )... we use checkPred on
538 -- the list of partially applied predicates in the deriving,
539 -- so there can be zero args.
540 checkPred (L spn (HsPredTy (HsIParam n ty)))
541 = return (L spn (HsIParam n ty))
545 checkl (L l ty) args = check l ty args
547 check _loc (HsTyVar t) args | not (isRdrTyVar t)
548 = return (L spn (HsClassP t args))
549 check _loc (HsAppTy l r) args = checkl l (r:args)
550 check _loc (HsOpTy l (L loc tc) r) args = check loc (HsTyVar tc) (l:r:args)
551 check _loc (HsParTy t) args = checkl t args
552 check loc _ _ = parseError loc "malformed class assertion"
554 checkDictTy :: LHsType RdrName -> P (LHsType RdrName)
555 checkDictTy (L spn ty) = check ty []
557 check (HsTyVar t) args | not (isRdrTyVar t)
558 = return (L spn (HsPredTy (HsClassP t args)))
559 check (HsAppTy l r) args = check (unLoc l) (r:args)
560 check (HsParTy t) args = check (unLoc t) args
561 check _ _ = parseError spn "Malformed context in instance header"
564 ---------------------------------------------------------------------------
565 -- Checking stand-alone deriving declarations
567 checkDerivDecl :: LDerivDecl RdrName -> P (LDerivDecl RdrName)
568 checkDerivDecl d@(L loc _) =
569 do glaExtOn <- extension glaExtsEnabled
570 if glaExtOn then return d
571 else parseError loc "Illegal stand-alone deriving declaration (use -fglasgow-exts)"
573 ---------------------------------------------------------------------------
574 -- Checking statements in a do-expression
575 -- We parse do { e1 ; e2 ; }
576 -- as [ExprStmt e1, ExprStmt e2]
577 -- checkDo (a) checks that the last thing is an ExprStmt
578 -- (b) returns it separately
579 -- same comments apply for mdo as well
581 checkDo = checkDoMDo "a " "'do'"
582 checkMDo = checkDoMDo "an " "'mdo'"
584 checkDoMDo :: String -> String -> SrcSpan -> [LStmt RdrName] -> P ([LStmt RdrName], LHsExpr RdrName)
585 checkDoMDo pre nm loc [] = parseError loc ("Empty " ++ nm ++ " construct")
586 checkDoMDo pre nm loc ss = do
589 check [L l (ExprStmt e _ _)] = return ([], e)
590 check [L l _] = parseError l ("The last statement in " ++ pre ++ nm ++
591 " construct must be an expression")
596 -- -------------------------------------------------------------------------
597 -- Checking Patterns.
599 -- We parse patterns as expressions and check for valid patterns below,
600 -- converting the expression into a pattern at the same time.
602 checkPattern :: LHsExpr RdrName -> P (LPat RdrName)
603 checkPattern e = checkLPat e
605 checkPatterns :: [LHsExpr RdrName] -> P [LPat RdrName]
606 checkPatterns es = mapM checkPattern es
608 checkLPat :: LHsExpr RdrName -> P (LPat RdrName)
609 checkLPat e@(L l _) = checkPat l e []
611 checkPat :: SrcSpan -> LHsExpr RdrName -> [LPat RdrName] -> P (LPat RdrName)
612 checkPat loc (L l (HsVar c)) args
613 | isRdrDataCon c = return (L loc (ConPatIn (L l c) (PrefixCon args)))
614 checkPat loc e args -- OK to let this happen even if bang-patterns
615 -- are not enabled, because there is no valid
616 -- non-bang-pattern parse of (C ! e)
617 | Just (e', args') <- splitBang e
618 = do { args'' <- checkPatterns args'
619 ; checkPat loc e' (args'' ++ args) }
620 checkPat loc (L _ (HsApp f x)) args
621 = do { x <- checkLPat x; checkPat loc f (x:args) }
622 checkPat loc (L _ e) []
623 = do { p <- checkAPat loc e; return (L loc p) }
624 checkPat loc pat _some_args
627 checkAPat loc e = case e of
628 EWildPat -> return (WildPat placeHolderType)
629 HsVar x | isQual x -> parseError loc ("Qualified variable in pattern: "
631 | otherwise -> return (VarPat x)
632 HsLit l -> return (LitPat l)
634 -- Overloaded numeric patterns (e.g. f 0 x = x)
635 -- Negation is recorded separately, so that the literal is zero or +ve
636 -- NB. Negative *primitive* literals are already handled by
637 -- RdrHsSyn.mkHsNegApp
638 HsOverLit pos_lit -> return (mkNPat pos_lit Nothing)
639 NegApp (L _ (HsOverLit pos_lit)) _
640 -> return (mkNPat pos_lit (Just noSyntaxExpr))
642 SectionR (L _ (HsVar bang)) e -- (! x)
644 -> do { bang_on <- extension bangPatEnabled
645 ; if bang_on then checkLPat e >>= (return . BangPat)
646 else parseError loc "Illegal bang-pattern (use -fbang-patterns)" }
648 ELazyPat e -> checkLPat e >>= (return . LazyPat)
649 EAsPat n e -> checkLPat e >>= (return . AsPat n)
650 ExprWithTySig e t -> checkLPat e >>= \e ->
651 -- Pattern signatures are parsed as sigtypes,
652 -- but they aren't explicit forall points. Hence
653 -- we have to remove the implicit forall here.
655 L _ (HsForAllTy Implicit _ (L _ []) ty) -> ty
658 return (SigPatIn e t')
661 OpApp (L nloc (HsVar n)) (L _ (HsVar plus)) _
662 (L _ (HsOverLit lit@(HsIntegral _ _)))
664 -> return (mkNPlusKPat (L nloc n) lit)
666 OpApp l op fix r -> checkLPat l >>= \l ->
667 checkLPat r >>= \r ->
669 L cl (HsVar c) | isDataOcc (rdrNameOcc c)
670 -> return (ConPatIn (L cl c) (InfixCon l r))
673 HsPar e -> checkLPat e >>= (return . ParPat)
674 ExplicitList _ es -> mapM (\e -> checkLPat e) es >>= \ps ->
675 return (ListPat ps placeHolderType)
676 ExplicitPArr _ es -> mapM (\e -> checkLPat e) es >>= \ps ->
677 return (PArrPat ps placeHolderType)
679 ExplicitTuple es b -> mapM (\e -> checkLPat e) es >>= \ps ->
680 return (TuplePat ps b placeHolderType)
682 RecordCon c _ fs -> mapM checkPatField fs >>= \fs ->
683 return (ConPatIn c (RecCon fs))
685 HsType ty -> return (TypePat ty)
688 plus_RDR, bang_RDR :: RdrName
689 plus_RDR = mkUnqual varName FSLIT("+") -- Hack
690 bang_RDR = mkUnqual varName FSLIT("!") -- Hack
692 checkPatField :: (Located RdrName, LHsExpr RdrName) -> P (Located RdrName, LPat RdrName)
693 checkPatField (n,e) = do
697 patFail loc = parseError loc "Parse error in pattern"
700 ---------------------------------------------------------------------------
701 -- Check Equation Syntax
703 checkValDef :: LHsExpr RdrName
704 -> Maybe (LHsType RdrName)
705 -> Located (GRHSs RdrName)
706 -> P (HsBind RdrName)
708 checkValDef lhs (Just sig) grhss
709 -- x :: ty = rhs parses as a *pattern* binding
710 = checkPatBind (L (combineLocs lhs sig) (ExprWithTySig lhs sig)) grhss
712 checkValDef lhs opt_sig grhss
713 = do { mb_fun <- isFunLhs lhs
715 Just (fun, is_infix, pats) -> checkFunBind (getLoc lhs)
716 fun is_infix pats opt_sig grhss
717 Nothing -> checkPatBind lhs grhss }
719 checkFunBind lhs_loc fun is_infix pats opt_sig (L rhs_span grhss)
721 = parseError (getLoc fun) ("Qualified name in function definition: " ++
722 showRdrName (unLoc fun))
724 = do ps <- checkPatterns pats
725 let match_span = combineSrcSpans lhs_loc rhs_span
726 return (makeFunBind fun is_infix [L match_span (Match ps opt_sig grhss)])
727 -- The span of the match covers the entire equation.
728 -- That isn't quite right, but it'll do for now.
730 makeFunBind :: Located id -> Bool -> [LMatch id] -> HsBind id
731 -- Like HsUtils.mkFunBind, but we need to be able to set the fixity too
732 makeFunBind fn is_infix ms
733 = FunBind { fun_id = fn, fun_infix = is_infix, fun_matches = mkMatchGroup ms,
734 fun_co_fn = idHsWrapper, bind_fvs = placeHolderNames }
736 checkPatBind lhs (L _ grhss)
737 = do { lhs <- checkPattern lhs
738 ; return (PatBind lhs grhss placeHolderType placeHolderNames) }
744 checkValSig (L l (HsVar v)) ty
745 | isUnqual v && not (isDataOcc (rdrNameOcc v))
746 = return (TypeSig (L l v) ty)
747 checkValSig (L l other) ty
748 = parseError l "Invalid type signature"
750 mkGadtDecl :: Located RdrName
751 -> LHsType RdrName -- assuming HsType
753 mkGadtDecl name (L _ (HsForAllTy _ qvars cxt ty)) = mk_gadt_con name qvars cxt ty
754 mkGadtDecl name ty = mk_gadt_con name [] (noLoc []) ty
756 mk_gadt_con name qvars cxt ty
757 = ConDecl { con_name = name
758 , con_explicit = Implicit
761 , con_details = PrefixCon []
762 , con_res = ResTyGADT ty }
763 -- NB: we put the whole constr type into the ResTyGADT for now;
764 -- the renamer will unravel it once it has sorted out
767 -- A variable binding is parsed as a FunBind.
770 -- The parser left-associates, so there should
771 -- not be any OpApps inside the e's
772 splitBang :: LHsExpr RdrName -> Maybe (LHsExpr RdrName, [LHsExpr RdrName])
773 -- Splits (f ! g a b) into (f, [(! g), a, g])
774 splitBang (L loc (OpApp l_arg bang@(L loc' (HsVar op)) _ r_arg))
775 | op == bang_RDR = Just (l_arg, L loc (SectionR bang arg1) : argns)
777 (arg1,argns) = split_bang r_arg []
778 split_bang (L _ (HsApp f e)) es = split_bang f (e:es)
779 split_bang e es = (e,es)
780 splitBang other = Nothing
782 isFunLhs :: LHsExpr RdrName
783 -> P (Maybe (Located RdrName, Bool, [LHsExpr RdrName]))
784 -- Just (fun, is_infix, arg_pats) if e is a function LHS
787 go (L loc (HsVar f)) es
788 | not (isRdrDataCon f) = return (Just (L loc f, False, es))
789 go (L _ (HsApp f e)) es = go f (e:es)
790 go (L _ (HsPar e)) es@(_:_) = go e es
792 -- For infix function defns, there should be only one infix *function*
793 -- (though there may be infix *datacons* involved too). So we don't
794 -- need fixity info to figure out which function is being defined.
795 -- a `K1` b `op` c `K2` d
797 -- (a `K1` b) `op` (c `K2` d)
798 -- The renamer checks later that the precedences would yield such a parse.
800 -- There is a complication to deal with bang patterns.
802 -- ToDo: what about this?
803 -- x + 1 `op` y = ...
805 go e@(L loc (OpApp l (L loc' (HsVar op)) fix r)) es
806 | Just (e',es') <- splitBang e
807 = do { bang_on <- extension bangPatEnabled
808 ; if bang_on then go e' (es' ++ es)
809 else return (Just (L loc' op, True, (l:r:es))) }
810 -- No bangs; behave just like the next case
811 | not (isRdrDataCon op) -- We have found the function!
812 = return (Just (L loc' op, True, (l:r:es)))
813 | otherwise -- Infix data con; keep going
814 = do { mb_l <- go l es
816 Just (op', True, j : k : es')
817 -> return (Just (op', True, j : op_app : es'))
819 op_app = L loc (OpApp k (L loc' (HsVar op)) fix r)
820 _ -> return Nothing }
821 go _ _ = return 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) noPostTcExpr fs)
839 mkRecConstrOrUpdate exp loc fs@(_:_)
840 = return (RecordUpd exp fs placeHolderType placeHolderType)
841 mkRecConstrOrUpdate _ loc []
842 = parseError loc "Empty record update"
844 mkInlineSpec :: Maybe Activation -> Bool -> InlineSpec
845 -- The Maybe is becuase the user can omit the activation spec (and usually does)
846 mkInlineSpec Nothing True = alwaysInlineSpec -- INLINE
847 mkInlineSpec Nothing False = neverInlineSpec -- NOINLINE
848 mkInlineSpec (Just act) inl = Inline act inl
851 -----------------------------------------------------------------------------
852 -- utilities for foreign declarations
854 -- supported calling conventions
856 data CallConv = CCall CCallConv -- ccall or stdcall
859 -- construct a foreign import declaration
863 -> (Located FastString, Located RdrName, LHsType RdrName)
864 -> P (HsDecl RdrName)
865 mkImport (CCall cconv) safety (entity, v, ty) = do
866 importSpec <- parseCImport entity cconv safety v
867 return (ForD (ForeignImport v ty importSpec))
868 mkImport (DNCall ) _ (entity, v, ty) = do
869 spec <- parseDImport entity
870 return $ ForD (ForeignImport v ty (DNImport spec))
872 -- parse the entity string of a foreign import declaration for the `ccall' or
873 -- `stdcall' calling convention'
875 parseCImport :: Located FastString
880 parseCImport (L loc entity) cconv safety v
881 -- FIXME: we should allow white space around `dynamic' and `wrapper' -=chak
882 | entity == FSLIT ("dynamic") =
883 return $ CImport cconv safety nilFS nilFS (CFunction DynamicTarget)
884 | entity == FSLIT ("wrapper") =
885 return $ CImport cconv safety nilFS nilFS CWrapper
886 | otherwise = parse0 (unpackFS entity)
888 -- using the static keyword?
889 parse0 (' ': rest) = parse0 rest
890 parse0 ('s':'t':'a':'t':'i':'c':rest) = parse1 rest
891 parse0 rest = parse1 rest
892 -- check for header file name
893 parse1 "" = parse4 "" nilFS False nilFS
894 parse1 (' ':rest) = parse1 rest
895 parse1 str@('&':_ ) = parse2 str nilFS
896 parse1 str@('[':_ ) = parse3 str nilFS False
898 | ".h" `isSuffixOf` first = parse2 rest (mkFastString first)
899 | otherwise = parse4 str nilFS False nilFS
901 (first, rest) = break (\c -> c == ' ' || c == '&' || c == '[') str
902 -- check for address operator (indicating a label import)
903 parse2 "" header = parse4 "" header False nilFS
904 parse2 (' ':rest) header = parse2 rest header
905 parse2 ('&':rest) header = parse3 rest header True
906 parse2 str@('[':_ ) header = parse3 str header False
907 parse2 str header = parse4 str header False nilFS
908 -- check for library object name
909 parse3 (' ':rest) header isLbl = parse3 rest header isLbl
910 parse3 ('[':rest) header isLbl =
911 case break (== ']') rest of
912 (lib, ']':rest) -> parse4 rest header isLbl (mkFastString lib)
913 _ -> parseError loc "Missing ']' in entity"
914 parse3 str header isLbl = parse4 str header isLbl nilFS
915 -- check for name of C function
916 parse4 "" header isLbl lib = build (mkExtName (unLoc v)) header isLbl lib
917 parse4 (' ':rest) header isLbl lib = parse4 rest header isLbl lib
918 parse4 str header isLbl lib
919 | all (== ' ') rest = build (mkFastString first) header isLbl lib
920 | otherwise = parseError loc "Malformed entity string"
922 (first, rest) = break (== ' ') str
924 build cid header False lib = return $
925 CImport cconv safety header lib (CFunction (StaticTarget cid))
926 build cid header True lib = return $
927 CImport cconv safety header lib (CLabel cid )
930 -- Unravel a dotnet spec string.
932 parseDImport :: Located FastString -> P DNCallSpec
933 parseDImport (L loc entity) = parse0 comps
935 comps = words (unpackFS entity)
939 | x == "static" = parse1 True xs
940 | otherwise = parse1 False (x:xs)
943 parse1 isStatic (x:xs)
944 | x == "method" = parse2 isStatic DNMethod xs
945 | x == "field" = parse2 isStatic DNField xs
946 | x == "ctor" = parse2 isStatic DNConstructor xs
947 parse1 isStatic xs = parse2 isStatic DNMethod xs
950 parse2 isStatic kind (('[':x):xs) =
953 vs | last vs == ']' -> parse3 isStatic kind (init vs) xs
954 parse2 isStatic kind xs = parse3 isStatic kind "" xs
956 parse3 isStatic kind assem [x] =
957 return (DNCallSpec isStatic kind assem x
958 -- these will be filled in once known.
959 (error "FFI-dotnet-args")
960 (error "FFI-dotnet-result"))
961 parse3 _ _ _ _ = d'oh
963 d'oh = parseError loc "Malformed entity string"
965 -- construct a foreign export declaration
968 -> (Located FastString, Located RdrName, LHsType RdrName)
969 -> P (HsDecl RdrName)
970 mkExport (CCall cconv) (L loc entity, v, ty) = return $
971 ForD (ForeignExport v ty (CExport (CExportStatic entity' cconv)))
973 entity' | nullFS entity = mkExtName (unLoc v)
975 mkExport DNCall (L loc entity, v, ty) =
976 parseError (getLoc v){-TODO: not quite right-}
977 "Foreign export is not yet supported for .NET"
979 -- Supplying the ext_name in a foreign decl is optional; if it
980 -- isn't there, the Haskell name is assumed. Note that no transformation
981 -- of the Haskell name is then performed, so if you foreign export (++),
982 -- it's external name will be "++". Too bad; it's important because we don't
983 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
985 mkExtName :: RdrName -> CLabelString
986 mkExtName rdrNm = mkFastString (occNameString (rdrNameOcc rdrNm))
990 -----------------------------------------------------------------------------
994 showRdrName :: RdrName -> String
995 showRdrName r = showSDoc (ppr r)
997 parseError :: SrcSpan -> String -> P a
998 parseError span s = failSpanMsgP span s