2 % (c) The University of Glasgow, 1996-2003
4 Functions over HsSyn specialised to RdrName.
9 extractHsRhoRdrTyVars, extractGenericPatTyVars,
12 mkHsIntegral, mkHsFractional, mkHsIsString,
13 mkHsDo, mkHsSplice, mkTopSpliceDecl,
14 mkClassDecl, mkTyData, mkTyFamily, mkTySynonym,
15 splitCon, mkInlinePragma,
16 mkRecConstrOrUpdate, -- HsExp -> [HsFieldUpdate] -> P HsExp
23 -- Stuff to do with Foreign declarations
27 mkExtName, -- RdrName -> CLabelString
28 mkGadtDecl, -- [Located RdrName] -> LHsType RdrName -> ConDecl RdrName
30 mkDeprecatedGadtRecordDecl,
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
37 checkTyVars, -- [LHsType RdrName] -> P ()
38 checkKindSigs, -- [LTyClDecl RdrName] -> P ()
39 checkInstType, -- HsType -> P HsType
40 checkPattern, -- HsExp -> P HsPat
42 checkPatterns, -- SrcLoc -> [HsExp] -> P [HsPat]
43 checkDo, -- [Stmt] -> P [Stmt]
44 checkMDo, -- [Stmt] -> P [Stmt]
45 checkValDef, -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
46 checkValSig, -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
51 import HsSyn -- Lots of it
52 import Class ( FunDep )
53 import TypeRep ( Kind )
54 import RdrName ( RdrName, isRdrTyVar, isRdrTc, mkUnqual, rdrNameOcc,
55 isRdrDataCon, isUnqual, getRdrName, setRdrNameSpace )
56 import BasicTypes ( maxPrecedence, Activation(..), RuleMatchInfo,
59 import TysWiredIn ( unitTyCon )
61 import OccName ( srcDataName, varName, isDataOcc, isTcOcc,
63 import PrelNames ( forall_tv_RDR )
66 import OrdList ( OrdList, fromOL )
67 import Bag ( Bag, emptyBag, consBag, foldrBag )
72 import Control.Applicative ((<$>))
73 import Text.ParserCombinators.ReadP as ReadP
74 import Data.List ( nubBy )
77 #include "HsVersions.h"
81 %************************************************************************
83 \subsection{A few functions over HsSyn at RdrName}
85 %************************************************************************
87 extractHsTyRdrNames finds the free variables of a HsType
88 It's used when making the for-alls explicit.
91 extractHsTyRdrTyVars :: LHsType RdrName -> [Located RdrName]
92 extractHsTyRdrTyVars ty = nubBy eqLocated (extract_lty ty [])
94 extractHsTysRdrTyVars :: [LHsType RdrName] -> [Located RdrName]
95 extractHsTysRdrTyVars ty = nubBy eqLocated (extract_ltys ty [])
97 extractHsRhoRdrTyVars :: LHsContext RdrName -> LHsType RdrName -> [Located RdrName]
98 -- This one takes the context and tau-part of a
99 -- sigma type and returns their free type variables
100 extractHsRhoRdrTyVars ctxt ty
101 = nubBy eqLocated $ extract_lctxt ctxt (extract_lty ty [])
103 extract_lctxt :: Located [LHsPred RdrName] -> [Located RdrName] -> [Located RdrName]
104 extract_lctxt ctxt acc = foldr (extract_pred . unLoc) acc (unLoc ctxt)
106 extract_pred :: HsPred RdrName -> [Located RdrName] -> [Located RdrName]
107 extract_pred (HsClassP _ tys) acc = extract_ltys tys acc
108 extract_pred (HsEqualP ty1 ty2) acc = extract_lty ty1 (extract_lty ty2 acc)
109 extract_pred (HsIParam _ ty ) acc = extract_lty ty acc
111 extract_ltys :: [LHsType RdrName] -> [Located RdrName] -> [Located RdrName]
112 extract_ltys tys acc = foldr extract_lty acc tys
114 extract_lty :: LHsType RdrName -> [Located RdrName] -> [Located RdrName]
115 extract_lty (L loc ty) acc
117 HsTyVar tv -> extract_tv loc tv acc
118 HsBangTy _ ty -> extract_lty ty acc
119 HsRecTy flds -> foldr (extract_lty . cd_fld_type) acc flds
120 HsAppTy ty1 ty2 -> extract_lty ty1 (extract_lty ty2 acc)
121 HsListTy ty -> extract_lty ty acc
122 HsPArrTy ty -> extract_lty ty acc
123 HsTupleTy _ tys -> extract_ltys tys acc
124 HsFunTy ty1 ty2 -> extract_lty ty1 (extract_lty ty2 acc)
125 HsPredTy p -> extract_pred p acc
126 HsOpTy ty1 (L loc tv) ty2 -> extract_tv loc tv (extract_lty ty1 (extract_lty ty2 acc))
127 HsParTy ty -> extract_lty ty acc
129 HsQuasiQuoteTy {} -> acc -- Quasi quotes mention no type variables
130 HsSpliceTy {} -> acc -- Type splices mention no type variables
131 HsSpliceTyOut {} -> acc -- Type splices mention no type variables
132 HsKindSig ty _ -> extract_lty ty acc
133 HsForAllTy _ [] cx ty -> extract_lctxt cx (extract_lty ty acc)
134 HsForAllTy _ tvs cx ty -> acc ++ (filter ((`notElem` locals) . unLoc) $
135 extract_lctxt cx (extract_lty ty []))
137 locals = hsLTyVarNames tvs
138 HsDocTy ty _ -> extract_lty ty acc
140 extract_tv :: SrcSpan -> RdrName -> [Located RdrName] -> [Located RdrName]
141 extract_tv loc tv acc | isRdrTyVar tv = L loc tv : acc
144 extractGenericPatTyVars :: LHsBinds RdrName -> [Located RdrName]
145 -- Get the type variables out of the type patterns in a bunch of
146 -- possibly-generic bindings in a class declaration
147 extractGenericPatTyVars binds
148 = nubBy eqLocated (foldrBag get [] binds)
150 get (L _ (FunBind { fun_matches = MatchGroup ms _ })) acc = foldr (get_m.unLoc) acc ms
153 get_m (Match (L _ (TypePat ty) : _) _ _) acc = extract_lty ty acc
158 %************************************************************************
160 \subsection{Construction functions for Rdr stuff}
162 %************************************************************************
164 mkClassDecl builds a RdrClassDecl, filling in the names for tycon and datacon
165 by deriving them from the name of the class. We fill in the names for the
166 tycon and datacon corresponding to the class, by deriving them from the
167 name of the class itself. This saves recording the names in the interface
168 file (which would be equally good).
170 Similarly for mkConDecl, mkClassOpSig and default-method names.
172 *** See "THE NAMING STORY" in HsDecls ****
175 mkClassDecl :: SrcSpan
176 -> Located (LHsContext RdrName, LHsType RdrName)
177 -> Located [Located (FunDep RdrName)]
178 -> Located (OrdList (LHsDecl RdrName))
179 -> P (LTyClDecl RdrName)
181 mkClassDecl loc (L _ (cxt, tycl_hdr)) fds where_cls
182 = do { let (binds, sigs, ats, docs) = cvBindsAndSigs (unLoc where_cls)
183 ; (cls, tparams) <- checkTyClHdr tycl_hdr
184 ; tyvars <- checkTyVars tparams -- Only type vars allowed
186 ; return (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls, tcdTyVars = tyvars,
187 tcdFDs = unLoc fds, tcdSigs = sigs, tcdMeths = binds,
188 tcdATs = ats, tcdDocs = docs })) }
192 -> Bool -- True <=> data family instance
193 -> Located (LHsContext RdrName, LHsType RdrName)
195 -> [LConDecl RdrName]
196 -> Maybe [LHsType RdrName]
197 -> P (LTyClDecl RdrName)
198 mkTyData loc new_or_data is_family (L _ (cxt, tycl_hdr)) ksig data_cons maybe_deriv
199 = do { (tc, tparams) <- checkTyClHdr tycl_hdr
201 ; (tyvars, typats) <- checkTParams is_family tparams
202 ; return (L loc (TyData { tcdND = new_or_data, tcdCtxt = cxt, tcdLName = tc,
203 tcdTyVars = tyvars, tcdTyPats = typats,
205 tcdKindSig = ksig, tcdDerivs = maybe_deriv })) }
207 mkTySynonym :: SrcSpan
208 -> Bool -- True <=> type family instances
209 -> LHsType RdrName -- LHS
210 -> LHsType RdrName -- RHS
211 -> P (LTyClDecl RdrName)
212 mkTySynonym loc is_family lhs rhs
213 = do { (tc, tparams) <- checkTyClHdr lhs
214 ; (tyvars, typats) <- checkTParams is_family tparams
215 ; return (L loc (TySynonym tc tyvars typats rhs)) }
217 mkTyFamily :: SrcSpan
219 -> LHsType RdrName -- LHS
220 -> Maybe Kind -- Optional kind signature
221 -> P (LTyClDecl RdrName)
222 mkTyFamily loc flavour lhs ksig
223 = do { (tc, tparams) <- checkTyClHdr lhs
224 ; tyvars <- checkTyVars tparams
225 ; return (L loc (TyFamily flavour tc tyvars ksig)) }
227 mkTopSpliceDecl :: LHsExpr RdrName -> HsDecl RdrName
229 -- [pads| ... ] then return a QuasiQuoteD
230 -- $(e) then return a SpliceD
231 -- but if she wrote, say,
232 -- f x then behave as if she'd written $(f x)
234 mkTopSpliceDecl (L _ (HsQuasiQuoteE qq)) = QuasiQuoteD qq
235 mkTopSpliceDecl (L _ (HsSpliceE (HsSplice _ expr))) = SpliceD (SpliceDecl expr)
236 mkTopSpliceDecl other_expr = SpliceD (SpliceDecl other_expr)
239 %************************************************************************
241 \subsection[cvBinds-etc]{Converting to @HsBinds@, etc.}
243 %************************************************************************
245 Function definitions are restructured here. Each is assumed to be recursive
246 initially, and non recursive definitions are discovered by the dependency
251 -- | Groups together bindings for a single function
252 cvTopDecls :: OrdList (LHsDecl RdrName) -> [LHsDecl RdrName]
253 cvTopDecls decls = go (fromOL decls)
255 go :: [LHsDecl RdrName] -> [LHsDecl RdrName]
257 go (L l (ValD b) : ds) = L l' (ValD b') : go ds'
258 where (L l' b', ds') = getMonoBind (L l b) ds
259 go (d : ds) = d : go ds
261 -- Declaration list may only contain value bindings and signatures.
262 cvBindGroup :: OrdList (LHsDecl RdrName) -> HsValBinds RdrName
264 = case cvBindsAndSigs binding of
265 (mbs, sigs, tydecls, _) -> ASSERT( null tydecls )
268 cvBindsAndSigs :: OrdList (LHsDecl RdrName)
269 -> (Bag (LHsBind RdrName), [LSig RdrName], [LTyClDecl RdrName], [LDocDecl])
270 -- Input decls contain just value bindings and signatures
271 -- and in case of class or instance declarations also
272 -- associated type declarations. They might also contain Haddock comments.
273 cvBindsAndSigs fb = go (fromOL fb)
275 go [] = (emptyBag, [], [], [])
276 go (L l (SigD s) : ds) = (bs, L l s : ss, ts, docs)
277 where (bs, ss, ts, docs) = go ds
278 go (L l (ValD b) : ds) = (b' `consBag` bs, ss, ts, docs)
279 where (b', ds') = getMonoBind (L l b) ds
280 (bs, ss, ts, docs) = go ds'
281 go (L l (TyClD t): ds) = (bs, ss, L l t : ts, docs)
282 where (bs, ss, ts, docs) = go ds
283 go (L l (DocD d) : ds) = (bs, ss, ts, (L l d) : docs)
284 where (bs, ss, ts, docs) = go ds
285 go (L _ d : _) = pprPanic "cvBindsAndSigs" (ppr d)
287 -----------------------------------------------------------------------------
288 -- Group function bindings into equation groups
290 getMonoBind :: LHsBind RdrName -> [LHsDecl RdrName]
291 -> (LHsBind RdrName, [LHsDecl RdrName])
292 -- Suppose (b',ds') = getMonoBind b ds
293 -- ds is a list of parsed bindings
294 -- b is a MonoBinds that has just been read off the front
296 -- Then b' is the result of grouping more equations from ds that
297 -- belong with b into a single MonoBinds, and ds' is the depleted
298 -- list of parsed bindings.
300 -- All Haddock comments between equations inside the group are
303 -- No AndMonoBinds or EmptyMonoBinds here; just single equations
305 getMonoBind (L loc1 (FunBind { fun_id = fun_id1@(L _ f1), fun_infix = is_infix1,
306 fun_matches = MatchGroup mtchs1 _ })) binds
308 = go is_infix1 mtchs1 loc1 binds []
310 go is_infix mtchs loc
311 (L loc2 (ValD (FunBind { fun_id = L _ f2, fun_infix = is_infix2,
312 fun_matches = MatchGroup mtchs2 _ })) : binds) _
313 | f1 == f2 = go (is_infix || is_infix2) (mtchs2 ++ mtchs)
314 (combineSrcSpans loc loc2) binds []
315 go is_infix mtchs loc (doc_decl@(L loc2 (DocD _)) : binds) doc_decls
316 = let doc_decls' = doc_decl : doc_decls
317 in go is_infix mtchs (combineSrcSpans loc loc2) binds doc_decls'
318 go is_infix mtchs loc binds doc_decls
319 = (L loc (makeFunBind fun_id1 is_infix (reverse mtchs)), (reverse doc_decls) ++ binds)
320 -- Reverse the final matches, to get it back in the right order
321 -- Do the same thing with the trailing doc comments
323 getMonoBind bind binds = (bind, binds)
325 has_args :: [LMatch RdrName] -> Bool
326 has_args [] = panic "RdrHsSyn:has_args"
327 has_args ((L _ (Match args _ _)) : _) = not (null args)
328 -- Don't group together FunBinds if they have
329 -- no arguments. This is necessary now that variable bindings
330 -- with no arguments are now treated as FunBinds rather
331 -- than pattern bindings (tests/rename/should_fail/rnfail002).
334 %************************************************************************
336 \subsection[PrefixToHS-utils]{Utilities for conversion}
338 %************************************************************************
342 -----------------------------------------------------------------------------
345 -- When parsing data declarations, we sometimes inadvertently parse
346 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
347 -- This function splits up the type application, adds any pending
348 -- arguments, and converts the type constructor back into a data constructor.
350 splitCon :: LHsType RdrName
351 -> P (Located RdrName, HsConDeclDetails RdrName)
352 -- This gets given a "type" that should look like
354 -- or C { x::Int, y::Bool }
355 -- and returns the pieces
359 split (L _ (HsAppTy t u)) ts = split t (u : ts)
360 split (L l (HsTyVar tc)) ts = do data_con <- tyConToDataCon l tc
361 return (data_con, mk_rest ts)
362 split (L l _) _ = parseError l "parse error in data/newtype declaration"
364 mk_rest [L _ (HsRecTy flds)] = RecCon flds
365 mk_rest ts = PrefixCon ts
367 mkDeprecatedGadtRecordDecl :: SrcSpan
369 -> [ConDeclField RdrName]
371 -> P (LConDecl RdrName)
372 -- This one uses the deprecated syntax
373 -- C { x,y ::Int } :: T a b
374 -- We give it a RecCon details right away
375 mkDeprecatedGadtRecordDecl loc (L con_loc con) flds res_ty
376 = do { data_con <- tyConToDataCon con_loc con
377 ; return (L loc (ConDecl { con_old_rec = True
378 , con_name = data_con
379 , con_explicit = Implicit
382 , con_details = RecCon flds
383 , con_res = ResTyGADT res_ty
384 , con_doc = Nothing })) }
386 mkSimpleConDecl :: Located RdrName -> [LHsTyVarBndr RdrName]
387 -> LHsContext RdrName -> HsConDeclDetails RdrName
390 mkSimpleConDecl name qvars cxt details
391 = ConDecl { con_old_rec = False
393 , con_explicit = Explicit
396 , con_details = details
398 , con_doc = Nothing }
400 mkGadtDecl :: [Located RdrName]
401 -> LHsType RdrName -- Always a HsForAllTy
403 -- We allow C,D :: ty
404 -- and expand it as if it had been
406 -- (Just like type signatures in general.)
407 mkGadtDecl names (L _ (HsForAllTy imp qvars cxt tau))
408 = [mk_gadt_con name | name <- names]
410 (details, res_ty) -- See Note [Sorting out the result type]
412 L _ (HsFunTy (L _ (HsRecTy flds)) res_ty) -> (RecCon flds, res_ty)
413 _other -> (PrefixCon [], tau)
416 = ConDecl { con_old_rec = False
421 , con_details = details
422 , con_res = ResTyGADT res_ty
423 , con_doc = Nothing }
424 mkGadtDecl _ other_ty = pprPanic "mkGadtDecl" (ppr other_ty)
426 tyConToDataCon :: SrcSpan -> RdrName -> P (Located RdrName)
427 tyConToDataCon loc tc
428 | isTcOcc (rdrNameOcc tc)
429 = return (L loc (setRdrNameSpace tc srcDataName))
431 = parseErrorSDoc loc (msg $$ extra)
433 msg = text "Not a data constructor:" <+> quotes (ppr tc)
434 extra | tc == forall_tv_RDR
435 = text "Perhaps you intended to use -XExistentialQuantification"
439 Note [Sorting out the result type]
440 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
441 In a GADT declaration which is not a record, we put the whole constr
442 type into the ResTyGADT for now; the renamer will unravel it once it
443 has sorted out operator fixities. Consider for example
444 C :: a :*: b -> a :*: b -> a :+: b
445 Initially this type will parse as
446 a :*: (b -> (a :*: (b -> (a :+: b))))
448 so it's hard to split up the arguments until we've done the precedence
449 resolution (in the renamer) On the other hand, for a record
450 { x,y :: Int } -> a :*: b
451 there is no doubt. AND we need to sort records out so that
452 we can bring x,y into scope. So:
453 * For PrefixCon we keep all the args in the ResTyGADT
454 * For RecCon we do not
457 ----------------------------------------------------------------------------
458 -- Various Syntactic Checks
460 checkInstType :: LHsType RdrName -> P (LHsType RdrName)
461 checkInstType (L l t)
463 HsForAllTy exp tvs ctxt ty -> do
464 dict_ty <- checkDictTy ty
465 return (L l (HsForAllTy exp tvs ctxt dict_ty))
467 HsParTy ty -> checkInstType ty
469 ty -> do dict_ty <- checkDictTy (L l ty)
470 return (L l (HsForAllTy Implicit [] (noLoc []) dict_ty))
472 checkDictTy :: LHsType RdrName -> P (LHsType RdrName)
473 checkDictTy (L spn ty) = check ty []
475 check (HsTyVar tc) args | isRdrTc tc = done tc args
476 check (HsOpTy t1 (L _ tc) t2) args | isRdrTc tc = done tc (t1:t2:args)
477 check (HsAppTy l r) args = check (unLoc l) (r:args)
478 check (HsParTy t) args = check (unLoc t) args
479 check _ _ = parseError spn "Malformed instance header"
481 done tc args = return (L spn (HsPredTy (HsClassP tc args)))
483 checkTParams :: Bool -- Type/data family
485 -> P ([LHsTyVarBndr RdrName], Maybe [LHsType RdrName])
486 -- checkTParams checks the type parameters of a data/newtype declaration
487 -- There are two cases:
489 -- a) Vanilla data/newtype decl. In that case
490 -- - the type parameters should all be type variables
491 -- - they may have a kind annotation
493 -- b) Family data/newtype decl. In that case
494 -- - The type parameters may be arbitrary types
495 -- - We find the type-varaible binders by find the
496 -- free type vars of those types
497 -- - We make them all kind-sig-free binders (UserTyVar)
498 -- If there are kind sigs in the type parameters, they
499 -- will fix the binder's kind when we kind-check the
501 checkTParams is_family tparams
502 | not is_family -- Vanilla case (a)
503 = do { tyvars <- checkTyVars tparams
504 ; return (tyvars, Nothing) }
505 | otherwise -- Family case (b)
506 = do { let tyvars = [L l (UserTyVar tv)
507 | L l tv <- extractHsTysRdrTyVars tparams]
508 ; return (tyvars, Just tparams) }
510 checkTyVars :: [LHsType RdrName] -> P [LHsTyVarBndr RdrName]
511 -- Check whether the given list of type parameters are all type variables
512 -- (possibly with a kind signature). If the second argument is `False',
513 -- only type variables are allowed and we raise an error on encountering a
514 -- non-variable; otherwise, we allow non-variable arguments and return the
515 -- entire list of parameters.
516 checkTyVars tparms = mapM chk tparms
518 -- Check that the name space is correct!
519 chk (L l (HsKindSig (L _ (HsTyVar tv)) k))
520 | isRdrTyVar tv = return (L l (KindedTyVar tv k))
521 chk (L l (HsTyVar tv))
522 | isRdrTyVar tv = return (L l (UserTyVar tv))
524 parseError l "Type found where type variable expected"
526 checkTyClHdr :: LHsType RdrName
527 -> P (Located RdrName, -- the head symbol (type or class name)
528 [LHsType RdrName]) -- parameters of head symbol
529 -- Well-formedness check and decomposition of type and class heads.
530 -- Decomposes T ty1 .. tyn into (T, [ty1, ..., tyn])
531 -- Int :*: Bool into (:*:, [Int, Bool])
532 -- returning the pieces
536 goL (L l ty) acc = go l ty acc
538 go l (HsTyVar tc) acc
539 | isRdrTc tc = return (L l tc, acc)
541 go _ (HsOpTy t1 ltc@(L _ tc) t2) acc
542 | isRdrTc tc = return (ltc, t1:t2:acc)
543 go _ (HsParTy ty) acc = goL ty acc
544 go _ (HsAppTy t1 t2) acc = goL t1 (t2:acc)
545 go l _ _ = parseError l "Malformed head of type or class declaration"
547 -- Check that associated type declarations of a class are all kind signatures.
549 checkKindSigs :: [LTyClDecl RdrName] -> P ()
550 checkKindSigs = mapM_ check
553 | isFamilyDecl tydecl
554 || isSynDecl tydecl = return ()
556 parseError l "Type declaration in a class must be a kind signature or synonym default"
558 checkContext :: LHsType RdrName -> P (LHsContext RdrName)
562 check (HsTupleTy _ ts) -- (Eq a, Ord b) shows up as a tuple type
563 = do ctx <- mapM checkPred ts
566 check (HsParTy ty) -- to be sure HsParTy doesn't get into the way
569 check (HsTyVar t) -- Empty context shows up as a unit type ()
570 | t == getRdrName unitTyCon = return (L l [])
573 = do p <- checkPred (L l t)
577 checkPred :: LHsType RdrName -> P (LHsPred RdrName)
578 -- Watch out.. in ...deriving( Show )... we use checkPred on
579 -- the list of partially applied predicates in the deriving,
580 -- so there can be zero args.
581 checkPred (L spn (HsPredTy (HsIParam n ty)))
582 = return (L spn (HsIParam n ty))
586 checkl (L l ty) args = check l ty args
588 check _loc (HsPredTy pred@(HsEqualP _ _))
590 = return $ L spn pred
591 check _loc (HsTyVar t) args | not (isRdrTyVar t)
592 = return (L spn (HsClassP t args))
593 check _loc (HsAppTy l r) args = checkl l (r:args)
594 check _loc (HsOpTy l (L loc tc) r) args = check loc (HsTyVar tc) (l:r:args)
595 check _loc (HsParTy t) args = checkl t args
596 check loc _ _ = parseError loc
597 "malformed class assertion"
599 ---------------------------------------------------------------------------
600 -- Checking statements in a do-expression
601 -- We parse do { e1 ; e2 ; }
602 -- as [ExprStmt e1, ExprStmt e2]
603 -- checkDo (a) checks that the last thing is an ExprStmt
604 -- (b) returns it separately
605 -- same comments apply for mdo as well
607 checkDo, checkMDo :: SrcSpan -> [LStmt RdrName] -> P ([LStmt RdrName], LHsExpr RdrName)
609 checkDo = checkDoMDo "a " "'do'"
610 checkMDo = checkDoMDo "an " "'mdo'"
612 checkDoMDo :: String -> String -> SrcSpan -> [LStmt RdrName] -> P ([LStmt RdrName], LHsExpr RdrName)
613 checkDoMDo _ nm loc [] = parseError loc ("Empty " ++ nm ++ " construct")
614 checkDoMDo pre nm _ ss = do
617 check [] = panic "RdrHsSyn:checkDoMDo"
618 check [L _ (ExprStmt e _ _)] = return ([], e)
619 check [L l _] = parseError l ("The last statement in " ++ pre ++ nm ++
620 " construct must be an expression")
625 -- -------------------------------------------------------------------------
626 -- Checking Patterns.
628 -- We parse patterns as expressions and check for valid patterns below,
629 -- converting the expression into a pattern at the same time.
631 checkPattern :: LHsExpr RdrName -> P (LPat RdrName)
632 checkPattern e = checkLPat e
634 checkPatterns :: [LHsExpr RdrName] -> P [LPat RdrName]
635 checkPatterns es = mapM checkPattern es
637 checkLPat :: LHsExpr RdrName -> P (LPat RdrName)
638 checkLPat e@(L l _) = checkPat l e []
640 checkPat :: SrcSpan -> LHsExpr RdrName -> [LPat RdrName] -> P (LPat RdrName)
641 checkPat loc (L l (HsVar c)) args
642 | isRdrDataCon c = return (L loc (ConPatIn (L l c) (PrefixCon args)))
643 checkPat loc e args -- OK to let this happen even if bang-patterns
644 -- are not enabled, because there is no valid
645 -- non-bang-pattern parse of (C ! e)
646 | Just (e', args') <- splitBang e
647 = do { args'' <- checkPatterns args'
648 ; checkPat loc e' (args'' ++ args) }
649 checkPat loc (L _ (HsApp f x)) args
650 = do { x <- checkLPat x; checkPat loc f (x:args) }
651 checkPat loc (L _ e) []
652 = do { pState <- getPState
653 ; p <- checkAPat (dflags pState) loc e
658 checkAPat :: DynFlags -> SrcSpan -> HsExpr RdrName -> P (Pat RdrName)
659 checkAPat dynflags loc e = case e of
660 EWildPat -> return (WildPat placeHolderType)
661 HsVar x -> return (VarPat x)
662 HsLit l -> return (LitPat l)
664 -- Overloaded numeric patterns (e.g. f 0 x = x)
665 -- Negation is recorded separately, so that the literal is zero or +ve
666 -- NB. Negative *primitive* literals are already handled by the lexer
667 HsOverLit pos_lit -> return (mkNPat pos_lit Nothing)
668 NegApp (L _ (HsOverLit pos_lit)) _
669 -> return (mkNPat pos_lit (Just noSyntaxExpr))
671 SectionR (L _ (HsVar bang)) e -- (! x)
673 -> do { bang_on <- extension bangPatEnabled
674 ; if bang_on then checkLPat e >>= (return . BangPat)
675 else parseError loc "Illegal bang-pattern (use -XBangPatterns)" }
677 ELazyPat e -> checkLPat e >>= (return . LazyPat)
678 EAsPat n e -> checkLPat e >>= (return . AsPat n)
679 -- view pattern is well-formed if the pattern is
680 EViewPat expr patE -> checkLPat patE >>= (return . (\p -> ViewPat expr p placeHolderType))
681 ExprWithTySig e t -> do e <- checkLPat e
682 -- Pattern signatures are parsed as sigtypes,
683 -- but they aren't explicit forall points. Hence
684 -- we have to remove the implicit forall here.
686 L _ (HsForAllTy Implicit _ (L _ []) ty) -> ty
688 return (SigPatIn e t')
691 OpApp (L nloc (HsVar n)) (L _ (HsVar plus)) _
692 (L _ (HsOverLit lit@(OverLit {ol_val = HsIntegral {}})))
693 | dopt Opt_NPlusKPatterns dynflags && (plus == plus_RDR)
694 -> return (mkNPlusKPat (L nloc n) lit)
696 OpApp l op _fix r -> do l <- checkLPat l
699 L cl (HsVar c) | isDataOcc (rdrNameOcc c)
700 -> return (ConPatIn (L cl c) (InfixCon l r))
703 HsPar e -> checkLPat e >>= (return . ParPat)
704 ExplicitList _ es -> do ps <- mapM checkLPat es
705 return (ListPat ps placeHolderType)
706 ExplicitPArr _ es -> do ps <- mapM checkLPat es
707 return (PArrPat ps placeHolderType)
710 | all tupArgPresent es -> do ps <- mapM checkLPat [e | Present e <- es]
711 return (TuplePat ps b placeHolderType)
712 | otherwise -> parseError loc "Illegal tuple section in pattern"
714 RecordCon c _ (HsRecFields fs dd)
715 -> do fs <- mapM checkPatField fs
716 return (ConPatIn c (RecCon (HsRecFields fs dd)))
717 HsQuasiQuoteE q -> return (QuasiQuotePat q)
719 HsType ty -> return (TypePat ty)
722 placeHolderPunRhs :: HsExpr RdrName
723 -- The RHS of a punned record field will be filled in by the renamer
724 -- It's better not to make it an error, in case we want to print it when debugging
725 placeHolderPunRhs = HsVar pun_RDR
727 plus_RDR, bang_RDR, pun_RDR :: RdrName
728 plus_RDR = mkUnqual varName (fsLit "+") -- Hack
729 bang_RDR = mkUnqual varName (fsLit "!") -- Hack
730 pun_RDR = mkUnqual varName (fsLit "pun-right-hand-side")
732 checkPatField :: HsRecField RdrName (LHsExpr RdrName) -> P (HsRecField RdrName (LPat RdrName))
733 checkPatField fld = do { p <- checkLPat (hsRecFieldArg fld)
734 ; return (fld { hsRecFieldArg = p }) }
736 patFail :: SrcSpan -> P a
737 patFail loc = parseError loc "Parse error in pattern"
740 ---------------------------------------------------------------------------
741 -- Check Equation Syntax
743 checkValDef :: LHsExpr RdrName
744 -> Maybe (LHsType RdrName)
745 -> Located (GRHSs RdrName)
746 -> P (HsBind RdrName)
748 checkValDef lhs (Just sig) grhss
749 -- x :: ty = rhs parses as a *pattern* binding
750 = checkPatBind (L (combineLocs lhs sig) (ExprWithTySig lhs sig)) grhss
752 checkValDef lhs opt_sig grhss
753 = do { mb_fun <- isFunLhs lhs
755 Just (fun, is_infix, pats) -> checkFunBind (getLoc lhs)
756 fun is_infix pats opt_sig grhss
757 Nothing -> checkPatBind lhs grhss }
759 checkFunBind :: SrcSpan
763 -> Maybe (LHsType RdrName)
764 -> Located (GRHSs RdrName)
765 -> P (HsBind RdrName)
766 checkFunBind lhs_loc fun is_infix pats opt_sig (L rhs_span grhss)
767 = do ps <- checkPatterns pats
768 let match_span = combineSrcSpans lhs_loc rhs_span
769 return (makeFunBind fun is_infix [L match_span (Match ps opt_sig grhss)])
770 -- The span of the match covers the entire equation.
771 -- That isn't quite right, but it'll do for now.
773 makeFunBind :: Located id -> Bool -> [LMatch id] -> HsBind id
774 -- Like HsUtils.mkFunBind, but we need to be able to set the fixity too
775 makeFunBind fn is_infix ms
776 = FunBind { fun_id = fn, fun_infix = is_infix, fun_matches = mkMatchGroup ms,
777 fun_co_fn = idHsWrapper, bind_fvs = placeHolderNames, fun_tick = Nothing }
779 checkPatBind :: LHsExpr RdrName
780 -> Located (GRHSs RdrName)
781 -> P (HsBind RdrName)
782 checkPatBind lhs (L _ grhss)
783 = do { lhs <- checkPattern lhs
784 ; return (PatBind lhs grhss placeHolderType placeHolderNames) }
790 checkValSig (L l (HsVar v)) ty
791 | isUnqual v && not (isDataOcc (rdrNameOcc v))
792 = return (TypeSig (L l v) ty)
793 checkValSig lhs@(L l _) _
794 | looks_like_foreign lhs
795 = parseError l "Invalid type signature; perhaps you meant to use -XForeignFunctionInterface?"
797 = parseError l "Invalid type signature: should be of form <variable> :: <type>"
799 -- A common error is to forget the ForeignFunctionInterface flag
800 -- so check for that, and suggest. cf Trac #3805
801 -- Sadly 'foreign import' still barfs 'parse error' because 'import' is a keyword
802 looks_like_foreign (L _ (HsVar v)) = v == foreign_RDR
803 looks_like_foreign (L _ (HsApp lhs _)) = looks_like_foreign lhs
804 looks_like_foreign _ = False
806 foreign_RDR = mkUnqual varName (fsLit "foreign")
811 -- The parser left-associates, so there should
812 -- not be any OpApps inside the e's
813 splitBang :: LHsExpr RdrName -> Maybe (LHsExpr RdrName, [LHsExpr RdrName])
814 -- Splits (f ! g a b) into (f, [(! g), a, b])
815 splitBang (L loc (OpApp l_arg bang@(L _ (HsVar op)) _ r_arg))
816 | op == bang_RDR = Just (l_arg, L loc (SectionR bang arg1) : argns)
818 (arg1,argns) = split_bang r_arg []
819 split_bang (L _ (HsApp f e)) es = split_bang f (e:es)
820 split_bang e es = (e,es)
821 splitBang _ = Nothing
823 isFunLhs :: LHsExpr RdrName
824 -> P (Maybe (Located RdrName, Bool, [LHsExpr RdrName]))
825 -- A variable binding is parsed as a FunBind.
826 -- Just (fun, is_infix, arg_pats) if e is a function LHS
828 -- The whole LHS is parsed as a single expression.
829 -- Any infix operators on the LHS will parse left-associatively
831 -- will parse (rather strangely) as
833 -- It's up to isFunLhs to sort out the mess
839 go (L loc (HsVar f)) es
840 | not (isRdrDataCon f) = return (Just (L loc f, False, es))
841 go (L _ (HsApp f e)) es = go f (e:es)
842 go (L _ (HsPar e)) es@(_:_) = go e es
844 -- For infix function defns, there should be only one infix *function*
845 -- (though there may be infix *datacons* involved too). So we don't
846 -- need fixity info to figure out which function is being defined.
847 -- a `K1` b `op` c `K2` d
849 -- (a `K1` b) `op` (c `K2` d)
850 -- The renamer checks later that the precedences would yield such a parse.
852 -- There is a complication to deal with bang patterns.
854 -- ToDo: what about this?
855 -- x + 1 `op` y = ...
857 go e@(L loc (OpApp l (L loc' (HsVar op)) fix r)) es
858 | Just (e',es') <- splitBang e
859 = do { bang_on <- extension bangPatEnabled
860 ; if bang_on then go e' (es' ++ es)
861 else return (Just (L loc' op, True, (l:r:es))) }
862 -- No bangs; behave just like the next case
863 | not (isRdrDataCon op) -- We have found the function!
864 = return (Just (L loc' op, True, (l:r:es)))
865 | otherwise -- Infix data con; keep going
866 = do { mb_l <- go l es
868 Just (op', True, j : k : es')
869 -> return (Just (op', True, j : op_app : es'))
871 op_app = L loc (OpApp k (L loc' (HsVar op)) fix r)
872 _ -> return Nothing }
873 go _ _ = return Nothing
875 ---------------------------------------------------------------------------
876 -- Miscellaneous utilities
878 checkPrecP :: Located Int -> P Int
880 | 0 <= i && i <= maxPrecedence = return i
881 | otherwise = parseError l "Precedence out of range"
886 -> ([HsRecField RdrName (LHsExpr RdrName)], Bool)
887 -> P (HsExpr RdrName)
889 mkRecConstrOrUpdate (L l (HsVar c)) _ (fs,dd) | isRdrDataCon c
890 = return (RecordCon (L l c) noPostTcExpr (mk_rec_fields fs dd))
891 mkRecConstrOrUpdate exp loc (fs,dd)
892 | null fs = parseError loc "Empty record update"
893 | otherwise = return (RecordUpd exp (mk_rec_fields fs dd) [] [] [])
895 mk_rec_fields :: [HsRecField id arg] -> Bool -> HsRecFields id arg
896 mk_rec_fields fs False = HsRecFields { rec_flds = fs, rec_dotdot = Nothing }
897 mk_rec_fields fs True = HsRecFields { rec_flds = fs, rec_dotdot = Just (length fs) }
899 mkInlinePragma :: Maybe Activation -> RuleMatchInfo -> Bool -> InlinePragma
900 -- The Maybe is because the user can omit the activation spec (and usually does)
901 mkInlinePragma mb_act match_info inl
902 = InlinePragma { inl_inline = inl
905 , inl_rule = match_info }
909 Nothing | inl -> AlwaysActive
910 | otherwise -> NeverActive
911 -- If no specific phase is given then:
912 -- NOINLINE => NeverActive
915 -----------------------------------------------------------------------------
916 -- utilities for foreign declarations
918 -- construct a foreign import declaration
920 mkImport :: CCallConv
922 -> (Located FastString, Located RdrName, LHsType RdrName)
923 -> P (HsDecl RdrName)
924 mkImport cconv safety (L loc entity, v, ty)
925 | cconv == PrimCallConv = do
926 let funcTarget = CFunction (StaticTarget entity Nothing)
927 importSpec = CImport PrimCallConv safety nilFS funcTarget
928 return (ForD (ForeignImport v ty importSpec))
931 case parseCImport cconv safety (mkExtName (unLoc v)) (unpackFS entity) of
932 Nothing -> parseError loc "Malformed entity string"
933 Just importSpec -> return (ForD (ForeignImport v ty importSpec))
935 -- the string "foo" is ambigous: either a header or a C identifier. The
936 -- C identifier case comes first in the alternatives below, so we pick
938 parseCImport :: CCallConv -> Safety -> FastString -> String
939 -> Maybe ForeignImport
940 parseCImport cconv safety nm str =
941 listToMaybe $ map fst $ filter (null.snd) $
947 string "dynamic" >> return (mk nilFS (CFunction DynamicTarget)),
948 string "wrapper" >> return (mk nilFS CWrapper),
949 optional (string "static" >> skipSpaces) >>
950 (mk nilFS <$> cimp nm) +++
951 (do h <- munch1 hdr_char; skipSpaces; mk (mkFastString h) <$> cimp nm)
956 mk = CImport cconv safety
958 hdr_char c = not (isSpace c) -- header files are filenames, which can contain
959 -- pretty much any char (depending on the platform),
960 -- so just accept any non-space character
961 id_char c = isAlphaNum c || c == '_'
963 cimp nm = (ReadP.char '&' >> skipSpaces >> CLabel <$> cid)
964 +++ ((\c -> CFunction (StaticTarget c Nothing)) <$> cid)
967 (do c <- satisfy (\c -> isAlpha c || c == '_')
968 cs <- many (satisfy id_char)
969 return (mkFastString (c:cs)))
972 -- construct a foreign export declaration
974 mkExport :: CCallConv
975 -> (Located FastString, Located RdrName, LHsType RdrName)
976 -> P (HsDecl RdrName)
977 mkExport cconv (L _ entity, v, ty) = return $
978 ForD (ForeignExport v ty (CExport (CExportStatic entity' cconv)))
980 entity' | nullFS entity = mkExtName (unLoc v)
983 -- Supplying the ext_name in a foreign decl is optional; if it
984 -- isn't there, the Haskell name is assumed. Note that no transformation
985 -- of the Haskell name is then performed, so if you foreign export (++),
986 -- it's external name will be "++". Too bad; it's important because we don't
987 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
989 mkExtName :: RdrName -> CLabelString
990 mkExtName rdrNm = mkFastString (occNameString (rdrNameOcc rdrNm))
994 -----------------------------------------------------------------------------
998 parseError :: SrcSpan -> String -> P a
999 parseError span s = parseErrorSDoc span (text s)
1001 parseErrorSDoc :: SrcSpan -> SDoc -> P a
1002 parseErrorSDoc span s = failSpanMsgP span s