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_derivds = ts}) l (DerivD d) ds
316 = addl (gp { hs_derivds = L l d : ts }) ds
317 add gp@(HsGroup {hs_defds = ts}) l (DefD d) ds
318 = addl (gp { hs_defds = L l d : ts }) ds
319 add gp@(HsGroup {hs_fords = ts}) l (ForD d) ds
320 = addl (gp { hs_fords = L l d : ts }) ds
321 add gp@(HsGroup {hs_depds = ts}) l (DeprecD d) ds
322 = addl (gp { hs_depds = L l d : ts }) ds
323 add gp@(HsGroup {hs_ruleds = ts}) l (RuleD d) ds
324 = addl (gp { hs_ruleds = L l d : ts }) ds
326 add_bind b (ValBindsIn bs sigs) = ValBindsIn (bs `snocBag` b) sigs
327 add_sig s (ValBindsIn bs sigs) = ValBindsIn bs (s:sigs)
330 %************************************************************************
332 \subsection[PrefixToHS-utils]{Utilities for conversion}
334 %************************************************************************
338 -----------------------------------------------------------------------------
341 -- When parsing data declarations, we sometimes inadvertently parse
342 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
343 -- This function splits up the type application, adds any pending
344 -- arguments, and converts the type constructor back into a data constructor.
346 mkPrefixCon :: LHsType RdrName -> [LBangType RdrName]
347 -> P (Located RdrName, HsConDetails RdrName (LBangType RdrName))
351 split (L _ (HsAppTy t u)) ts = split t (u : ts)
352 split (L l (HsTyVar tc)) ts = do data_con <- tyConToDataCon l tc
353 return (data_con, PrefixCon ts)
354 split (L l _) _ = parseError l "parse error in data/newtype declaration"
356 mkRecCon :: Located RdrName -> [([Located RdrName], LBangType RdrName)]
357 -> P (Located RdrName, HsConDetails RdrName (LBangType RdrName))
358 mkRecCon (L loc con) fields
359 = do data_con <- tyConToDataCon loc con
360 return (data_con, RecCon [ (l,t) | (ls,t) <- fields, l <- ls ])
362 tyConToDataCon :: SrcSpan -> RdrName -> P (Located RdrName)
363 tyConToDataCon loc tc
364 | isTcOcc (rdrNameOcc tc)
365 = return (L loc (setRdrNameSpace tc srcDataName))
367 = parseError loc (showSDoc (text "Not a constructor:" <+> quotes (ppr tc)))
369 ----------------------------------------------------------------------------
370 -- Various Syntactic Checks
372 checkInstType :: LHsType RdrName -> P (LHsType RdrName)
373 checkInstType (L l t)
375 HsForAllTy exp tvs ctxt ty -> do
376 dict_ty <- checkDictTy ty
377 return (L l (HsForAllTy exp tvs ctxt dict_ty))
379 HsParTy ty -> checkInstType ty
381 ty -> do dict_ty <- checkDictTy (L l ty)
382 return (L l (HsForAllTy Implicit [] (noLoc []) dict_ty))
384 -- Check whether the given list of type parameters are all type variables
385 -- (possibly with a kind signature). If the second argument is `False',
386 -- only type variables are allowed and we raise an error on encountering a
387 -- non-variable; otherwise, we allow non-variable arguments and return the
388 -- entire list of parameters.
390 checkTyVars :: [LHsType RdrName] -> P ()
391 checkTyVars tparms = mapM_ chk tparms
393 -- Check that the name space is correct!
394 chk (L l (HsKindSig (L _ (HsTyVar tv)) k))
395 | isRdrTyVar tv = return ()
396 chk (L l (HsTyVar tv))
397 | isRdrTyVar tv = return ()
399 parseError l "Type found where type variable expected"
401 -- Check whether the type arguments in a type synonym head are simply
402 -- variables. If not, we have a type equation of a type function and return
403 -- all patterns. If yes, we return 'Nothing' as the third component to
404 -- indicate a vanilla type synonym.
406 checkSynHdr :: LHsType RdrName
407 -> Bool -- is type instance?
408 -> P (Located RdrName, -- head symbol
409 [LHsTyVarBndr RdrName], -- parameters
410 [LHsType RdrName]) -- type patterns
411 checkSynHdr ty isTyInst =
412 do { (_, tc, tvs, tparms) <- checkTyClHdr (noLoc []) ty
413 ; unless isTyInst $ checkTyVars tparms
414 ; return (tc, tvs, tparms) }
417 -- Well-formedness check and decomposition of type and class heads.
419 checkTyClHdr :: LHsContext RdrName -> LHsType RdrName
420 -> P (LHsContext RdrName, -- the type context
421 Located RdrName, -- the head symbol (type or class name)
422 [LHsTyVarBndr RdrName], -- free variables of the non-context part
423 [LHsType RdrName]) -- parameters of head symbol
424 -- The header of a type or class decl should look like
425 -- (C a, D b) => T a b
429 -- With associated types, we can also have non-variable parameters; ie,
431 -- The unaltered parameter list is returned in the fourth component of the
435 -- ('()', 'T', ['a'], ['Int', '[a]'])
436 checkTyClHdr (L l cxt) ty
437 = do (tc, tvs, parms) <- gol ty []
439 return (L l cxt, tc, tvs, parms)
441 gol (L l ty) acc = go l ty acc
443 go l (HsTyVar tc) acc
444 | not (isRdrTyVar tc) = do
445 tvs <- extractTyVars acc
446 return (L l tc, tvs, acc)
447 go l (HsOpTy t1 tc t2) acc = do
448 tvs <- extractTyVars (t1:t2:acc)
449 return (tc, tvs, acc)
450 go l (HsParTy ty) acc = gol ty acc
451 go l (HsAppTy t1 t2) acc = gol t1 (t2:acc)
453 parseError l "Malformed head of type or class declaration"
455 -- The predicates in a type or class decl must all
456 -- be HsClassPs. They need not all be type variables,
457 -- even in Haskell 98. E.g. class (Monad m, Monad (t m)) => MonadT t m
458 chk_pred (L l (HsClassP _ args)) = return ()
460 = parseError l "Malformed context in type or class declaration"
462 -- Extract the type variables of a list of type parameters.
464 -- * Type arguments can be complex type terms (needed for associated type
467 extractTyVars :: [LHsType RdrName] -> P [LHsTyVarBndr RdrName]
468 extractTyVars tvs = collects [] tvs
470 -- Collect all variables (1st arg serves as an accumulator)
471 collect tvs (L l (HsForAllTy _ _ _ _)) =
472 parseError l "Forall type not allowed as type parameter"
473 collect tvs (L l (HsTyVar tv))
474 | isRdrTyVar tv = return $ L l (UserTyVar tv) : tvs
475 | otherwise = return tvs
476 collect tvs (L l (HsBangTy _ _ )) =
477 parseError l "Bang-style type annotations not allowed as type parameter"
478 collect tvs (L l (HsAppTy t1 t2 )) = do
479 tvs' <- collect tvs t2
481 collect tvs (L l (HsFunTy t1 t2 )) = do
482 tvs' <- collect tvs t2
484 collect tvs (L l (HsListTy t )) = collect tvs t
485 collect tvs (L l (HsPArrTy t )) = collect tvs t
486 collect tvs (L l (HsTupleTy _ ts )) = collects tvs ts
487 collect tvs (L l (HsOpTy t1 _ t2 )) = do
488 tvs' <- collect tvs t2
490 collect tvs (L l (HsParTy t )) = collect tvs t
491 collect tvs (L l (HsNumTy t )) = return tvs
492 collect tvs (L l (HsPredTy t )) =
493 parseError l "Predicate not allowed as type parameter"
494 collect tvs (L l (HsKindSig (L _ (HsTyVar tv)) k))
496 return $ L l (KindedTyVar tv k) : tvs
498 parseError l "Kind signature only allowed for type variables"
499 collect tvs (L l (HsSpliceTy t )) =
500 parseError l "Splice not allowed as type parameter"
502 -- Collect all variables of a list of types
503 collects tvs [] = return tvs
504 collects tvs (t:ts) = do
505 tvs' <- collects tvs ts
508 -- Check that associated type declarations of a class are all kind signatures.
510 checkKindSigs :: [LTyClDecl RdrName] -> P ()
511 checkKindSigs = mapM_ check
514 | isKindSigDecl tydecl
515 || isSynDecl tydecl = return ()
517 parseError l "Type declaration in a class must be a kind signature or synonym default"
519 checkContext :: LHsType RdrName -> P (LHsContext RdrName)
523 check (HsTupleTy _ ts) -- (Eq a, Ord b) shows up as a tuple type
524 = do ctx <- mapM checkPred ts
527 check (HsParTy ty) -- to be sure HsParTy doesn't get into the way
530 check (HsTyVar t) -- Empty context shows up as a unit type ()
531 | t == getRdrName unitTyCon = return (L l [])
534 = do p <- checkPred (L l t)
538 checkPred :: LHsType RdrName -> P (LHsPred RdrName)
539 -- Watch out.. in ...deriving( Show )... we use checkPred on
540 -- the list of partially applied predicates in the deriving,
541 -- so there can be zero args.
542 checkPred (L spn (HsPredTy (HsIParam n ty)))
543 = return (L spn (HsIParam n ty))
547 checkl (L l ty) args = check l ty args
549 check _loc (HsTyVar t) args | not (isRdrTyVar t)
550 = return (L spn (HsClassP t args))
551 check _loc (HsAppTy l r) args = checkl l (r:args)
552 check _loc (HsOpTy l (L loc tc) r) args = check loc (HsTyVar tc) (l:r:args)
553 check _loc (HsParTy t) args = checkl t args
554 check loc _ _ = parseError loc "malformed class assertion"
556 checkDictTy :: LHsType RdrName -> P (LHsType RdrName)
557 checkDictTy (L spn ty) = check ty []
559 check (HsTyVar t) args | not (isRdrTyVar t)
560 = return (L spn (HsPredTy (HsClassP t args)))
561 check (HsAppTy l r) args = check (unLoc l) (r:args)
562 check (HsParTy t) args = check (unLoc t) args
563 check _ _ = parseError spn "Malformed context in instance header"
566 ---------------------------------------------------------------------------
567 -- Checking stand-alone deriving declarations
569 checkDerivDecl :: LDerivDecl RdrName -> P (LDerivDecl RdrName)
570 checkDerivDecl d@(L loc _) =
571 do glaExtOn <- extension glaExtsEnabled
572 if glaExtOn then return d
573 else parseError loc "Illegal stand-alone deriving declaration (use -fglasgow-exts)"
575 ---------------------------------------------------------------------------
576 -- Checking statements in a do-expression
577 -- We parse do { e1 ; e2 ; }
578 -- as [ExprStmt e1, ExprStmt e2]
579 -- checkDo (a) checks that the last thing is an ExprStmt
580 -- (b) returns it separately
581 -- same comments apply for mdo as well
583 checkDo = checkDoMDo "a " "'do'"
584 checkMDo = checkDoMDo "an " "'mdo'"
586 checkDoMDo :: String -> String -> SrcSpan -> [LStmt RdrName] -> P ([LStmt RdrName], LHsExpr RdrName)
587 checkDoMDo pre nm loc [] = parseError loc ("Empty " ++ nm ++ " construct")
588 checkDoMDo pre nm loc ss = do
591 check [L l (ExprStmt e _ _)] = return ([], e)
592 check [L l _] = parseError l ("The last statement in " ++ pre ++ nm ++
593 " construct must be an expression")
598 -- -------------------------------------------------------------------------
599 -- Checking Patterns.
601 -- We parse patterns as expressions and check for valid patterns below,
602 -- converting the expression into a pattern at the same time.
604 checkPattern :: LHsExpr RdrName -> P (LPat RdrName)
605 checkPattern e = checkLPat e
607 checkPatterns :: [LHsExpr RdrName] -> P [LPat RdrName]
608 checkPatterns es = mapM checkPattern es
610 checkLPat :: LHsExpr RdrName -> P (LPat RdrName)
611 checkLPat e@(L l _) = checkPat l e []
613 checkPat :: SrcSpan -> LHsExpr RdrName -> [LPat RdrName] -> P (LPat RdrName)
614 checkPat loc (L l (HsVar c)) args
615 | isRdrDataCon c = return (L loc (ConPatIn (L l c) (PrefixCon args)))
616 checkPat loc e args -- OK to let this happen even if bang-patterns
617 -- are not enabled, because there is no valid
618 -- non-bang-pattern parse of (C ! e)
619 | Just (e', args') <- splitBang e
620 = do { args'' <- checkPatterns args'
621 ; checkPat loc e' (args'' ++ args) }
622 checkPat loc (L _ (HsApp f x)) args
623 = do { x <- checkLPat x; checkPat loc f (x:args) }
624 checkPat loc (L _ e) []
625 = do { p <- checkAPat loc e; return (L loc p) }
626 checkPat loc pat _some_args
629 checkAPat loc e = case e of
630 EWildPat -> return (WildPat placeHolderType)
631 HsVar x | isQual x -> parseError loc ("Qualified variable in pattern: "
633 | otherwise -> return (VarPat x)
634 HsLit l -> return (LitPat l)
636 -- Overloaded numeric patterns (e.g. f 0 x = x)
637 -- Negation is recorded separately, so that the literal is zero or +ve
638 -- NB. Negative *primitive* literals are already handled by
639 -- RdrHsSyn.mkHsNegApp
640 HsOverLit pos_lit -> return (mkNPat pos_lit Nothing)
641 NegApp (L _ (HsOverLit pos_lit)) _
642 -> return (mkNPat pos_lit (Just noSyntaxExpr))
644 SectionR (L _ (HsVar bang)) e -- (! x)
646 -> do { bang_on <- extension bangPatEnabled
647 ; if bang_on then checkLPat e >>= (return . BangPat)
648 else parseError loc "Illegal bang-pattern (use -fbang-patterns)" }
650 ELazyPat e -> checkLPat e >>= (return . LazyPat)
651 EAsPat n e -> checkLPat e >>= (return . AsPat n)
652 ExprWithTySig e t -> checkLPat e >>= \e ->
653 -- Pattern signatures are parsed as sigtypes,
654 -- but they aren't explicit forall points. Hence
655 -- we have to remove the implicit forall here.
657 L _ (HsForAllTy Implicit _ (L _ []) ty) -> ty
660 return (SigPatIn e t')
663 OpApp (L nloc (HsVar n)) (L _ (HsVar plus)) _
664 (L _ (HsOverLit lit@(HsIntegral _ _)))
666 -> return (mkNPlusKPat (L nloc n) lit)
668 OpApp l op fix r -> checkLPat l >>= \l ->
669 checkLPat r >>= \r ->
671 L cl (HsVar c) | isDataOcc (rdrNameOcc c)
672 -> return (ConPatIn (L cl c) (InfixCon l r))
675 HsPar e -> checkLPat e >>= (return . ParPat)
676 ExplicitList _ es -> mapM (\e -> checkLPat e) es >>= \ps ->
677 return (ListPat ps placeHolderType)
678 ExplicitPArr _ es -> mapM (\e -> checkLPat e) es >>= \ps ->
679 return (PArrPat ps placeHolderType)
681 ExplicitTuple es b -> mapM (\e -> checkLPat e) es >>= \ps ->
682 return (TuplePat ps b placeHolderType)
684 RecordCon c _ fs -> mapM checkPatField fs >>= \fs ->
685 return (ConPatIn c (RecCon fs))
687 HsType ty -> return (TypePat ty)
690 plus_RDR, bang_RDR :: RdrName
691 plus_RDR = mkUnqual varName FSLIT("+") -- Hack
692 bang_RDR = mkUnqual varName FSLIT("!") -- Hack
694 checkPatField :: (Located RdrName, LHsExpr RdrName) -> P (Located RdrName, LPat RdrName)
695 checkPatField (n,e) = do
699 patFail loc = parseError loc "Parse error in pattern"
702 ---------------------------------------------------------------------------
703 -- Check Equation Syntax
705 checkValDef :: LHsExpr RdrName
706 -> Maybe (LHsType RdrName)
707 -> Located (GRHSs RdrName)
708 -> P (HsBind RdrName)
710 checkValDef lhs (Just sig) grhss
711 -- x :: ty = rhs parses as a *pattern* binding
712 = checkPatBind (L (combineLocs lhs sig) (ExprWithTySig lhs sig)) grhss
714 checkValDef lhs opt_sig grhss
715 = do { mb_fun <- isFunLhs lhs
717 Just (fun, is_infix, pats) -> checkFunBind (getLoc lhs)
718 fun is_infix pats opt_sig grhss
719 Nothing -> checkPatBind lhs grhss }
721 checkFunBind lhs_loc fun is_infix pats opt_sig (L rhs_span grhss)
723 = parseError (getLoc fun) ("Qualified name in function definition: " ++
724 showRdrName (unLoc fun))
726 = do ps <- checkPatterns pats
727 let match_span = combineSrcSpans lhs_loc rhs_span
728 return (makeFunBind fun is_infix [L match_span (Match ps opt_sig grhss)])
729 -- The span of the match covers the entire equation.
730 -- That isn't quite right, but it'll do for now.
732 makeFunBind :: Located id -> Bool -> [LMatch id] -> HsBind id
733 -- Like HsUtils.mkFunBind, but we need to be able to set the fixity too
734 makeFunBind fn is_infix ms
735 = FunBind { fun_id = fn, fun_infix = is_infix, fun_matches = mkMatchGroup ms,
736 fun_co_fn = idHsWrapper, bind_fvs = placeHolderNames }
738 checkPatBind lhs (L _ grhss)
739 = do { lhs <- checkPattern lhs
740 ; return (PatBind lhs grhss placeHolderType placeHolderNames) }
746 checkValSig (L l (HsVar v)) ty
747 | isUnqual v && not (isDataOcc (rdrNameOcc v))
748 = return (TypeSig (L l v) ty)
749 checkValSig (L l other) ty
750 = parseError l "Invalid type signature"
752 mkGadtDecl :: Located RdrName
753 -> LHsType RdrName -- assuming HsType
755 mkGadtDecl name (L _ (HsForAllTy _ qvars cxt ty)) = mk_gadt_con name qvars cxt ty
756 mkGadtDecl name ty = mk_gadt_con name [] (noLoc []) ty
758 mk_gadt_con name qvars cxt ty
759 = ConDecl { con_name = name
760 , con_explicit = Implicit
763 , con_details = PrefixCon []
764 , con_res = ResTyGADT ty }
765 -- NB: we put the whole constr type into the ResTyGADT for now;
766 -- the renamer will unravel it once it has sorted out
769 -- A variable binding is parsed as a FunBind.
772 -- The parser left-associates, so there should
773 -- not be any OpApps inside the e's
774 splitBang :: LHsExpr RdrName -> Maybe (LHsExpr RdrName, [LHsExpr RdrName])
775 -- Splits (f ! g a b) into (f, [(! g), a, g])
776 splitBang (L loc (OpApp l_arg bang@(L loc' (HsVar op)) _ r_arg))
777 | op == bang_RDR = Just (l_arg, L loc (SectionR bang arg1) : argns)
779 (arg1,argns) = split_bang r_arg []
780 split_bang (L _ (HsApp f e)) es = split_bang f (e:es)
781 split_bang e es = (e,es)
782 splitBang other = Nothing
784 isFunLhs :: LHsExpr RdrName
785 -> P (Maybe (Located RdrName, Bool, [LHsExpr RdrName]))
786 -- Just (fun, is_infix, arg_pats) if e is a function LHS
789 go (L loc (HsVar f)) es
790 | not (isRdrDataCon f) = return (Just (L loc f, False, es))
791 go (L _ (HsApp f e)) es = go f (e:es)
792 go (L _ (HsPar e)) es@(_:_) = go e es
794 -- For infix function defns, there should be only one infix *function*
795 -- (though there may be infix *datacons* involved too). So we don't
796 -- need fixity info to figure out which function is being defined.
797 -- a `K1` b `op` c `K2` d
799 -- (a `K1` b) `op` (c `K2` d)
800 -- The renamer checks later that the precedences would yield such a parse.
802 -- There is a complication to deal with bang patterns.
804 -- ToDo: what about this?
805 -- x + 1 `op` y = ...
807 go e@(L loc (OpApp l (L loc' (HsVar op)) fix r)) es
808 | Just (e',es') <- splitBang e
809 = do { bang_on <- extension bangPatEnabled
810 ; if bang_on then go e' (es' ++ es)
811 else return (Just (L loc' op, True, (l:r:es))) }
812 -- No bangs; behave just like the next case
813 | not (isRdrDataCon op) -- We have found the function!
814 = return (Just (L loc' op, True, (l:r:es)))
815 | otherwise -- Infix data con; keep going
816 = do { mb_l <- go l es
818 Just (op', True, j : k : es')
819 -> return (Just (op', True, j : op_app : es'))
821 op_app = L loc (OpApp k (L loc' (HsVar op)) fix r)
822 _ -> return Nothing }
823 go _ _ = return Nothing
825 ---------------------------------------------------------------------------
826 -- Miscellaneous utilities
828 checkPrecP :: Located Int -> P Int
830 | 0 <= i && i <= maxPrecedence = return i
831 | otherwise = parseError l "Precedence out of range"
836 -> HsRecordBinds RdrName
837 -> P (HsExpr RdrName)
839 mkRecConstrOrUpdate (L l (HsVar c)) loc fs | isRdrDataCon c
840 = return (RecordCon (L l c) noPostTcExpr fs)
841 mkRecConstrOrUpdate exp loc fs@(_:_)
842 = return (RecordUpd exp fs placeHolderType placeHolderType)
843 mkRecConstrOrUpdate _ loc []
844 = parseError loc "Empty record update"
846 mkInlineSpec :: Maybe Activation -> Bool -> InlineSpec
847 -- The Maybe is becuase the user can omit the activation spec (and usually does)
848 mkInlineSpec Nothing True = alwaysInlineSpec -- INLINE
849 mkInlineSpec Nothing False = neverInlineSpec -- NOINLINE
850 mkInlineSpec (Just act) inl = Inline act inl
853 -----------------------------------------------------------------------------
854 -- utilities for foreign declarations
856 -- supported calling conventions
858 data CallConv = CCall CCallConv -- ccall or stdcall
861 -- construct a foreign import declaration
865 -> (Located FastString, Located RdrName, LHsType RdrName)
866 -> P (HsDecl RdrName)
867 mkImport (CCall cconv) safety (entity, v, ty) = do
868 importSpec <- parseCImport entity cconv safety v
869 return (ForD (ForeignImport v ty importSpec))
870 mkImport (DNCall ) _ (entity, v, ty) = do
871 spec <- parseDImport entity
872 return $ ForD (ForeignImport v ty (DNImport spec))
874 -- parse the entity string of a foreign import declaration for the `ccall' or
875 -- `stdcall' calling convention'
877 parseCImport :: Located FastString
882 parseCImport (L loc entity) cconv safety v
883 -- FIXME: we should allow white space around `dynamic' and `wrapper' -=chak
884 | entity == FSLIT ("dynamic") =
885 return $ CImport cconv safety nilFS nilFS (CFunction DynamicTarget)
886 | entity == FSLIT ("wrapper") =
887 return $ CImport cconv safety nilFS nilFS CWrapper
888 | otherwise = parse0 (unpackFS entity)
890 -- using the static keyword?
891 parse0 (' ': rest) = parse0 rest
892 parse0 ('s':'t':'a':'t':'i':'c':rest) = parse1 rest
893 parse0 rest = parse1 rest
894 -- check for header file name
895 parse1 "" = parse4 "" nilFS False nilFS
896 parse1 (' ':rest) = parse1 rest
897 parse1 str@('&':_ ) = parse2 str nilFS
898 parse1 str@('[':_ ) = parse3 str nilFS False
900 | ".h" `isSuffixOf` first = parse2 rest (mkFastString first)
901 | otherwise = parse4 str nilFS False nilFS
903 (first, rest) = break (\c -> c == ' ' || c == '&' || c == '[') str
904 -- check for address operator (indicating a label import)
905 parse2 "" header = parse4 "" header False nilFS
906 parse2 (' ':rest) header = parse2 rest header
907 parse2 ('&':rest) header = parse3 rest header True
908 parse2 str@('[':_ ) header = parse3 str header False
909 parse2 str header = parse4 str header False nilFS
910 -- check for library object name
911 parse3 (' ':rest) header isLbl = parse3 rest header isLbl
912 parse3 ('[':rest) header isLbl =
913 case break (== ']') rest of
914 (lib, ']':rest) -> parse4 rest header isLbl (mkFastString lib)
915 _ -> parseError loc "Missing ']' in entity"
916 parse3 str header isLbl = parse4 str header isLbl nilFS
917 -- check for name of C function
918 parse4 "" header isLbl lib = build (mkExtName (unLoc v)) header isLbl lib
919 parse4 (' ':rest) header isLbl lib = parse4 rest header isLbl lib
920 parse4 str header isLbl lib
921 | all (== ' ') rest = build (mkFastString first) header isLbl lib
922 | otherwise = parseError loc "Malformed entity string"
924 (first, rest) = break (== ' ') str
926 build cid header False lib = return $
927 CImport cconv safety header lib (CFunction (StaticTarget cid))
928 build cid header True lib = return $
929 CImport cconv safety header lib (CLabel cid )
932 -- Unravel a dotnet spec string.
934 parseDImport :: Located FastString -> P DNCallSpec
935 parseDImport (L loc entity) = parse0 comps
937 comps = words (unpackFS entity)
941 | x == "static" = parse1 True xs
942 | otherwise = parse1 False (x:xs)
945 parse1 isStatic (x:xs)
946 | x == "method" = parse2 isStatic DNMethod xs
947 | x == "field" = parse2 isStatic DNField xs
948 | x == "ctor" = parse2 isStatic DNConstructor xs
949 parse1 isStatic xs = parse2 isStatic DNMethod xs
952 parse2 isStatic kind (('[':x):xs) =
955 vs | last vs == ']' -> parse3 isStatic kind (init vs) xs
956 parse2 isStatic kind xs = parse3 isStatic kind "" xs
958 parse3 isStatic kind assem [x] =
959 return (DNCallSpec isStatic kind assem x
960 -- these will be filled in once known.
961 (error "FFI-dotnet-args")
962 (error "FFI-dotnet-result"))
963 parse3 _ _ _ _ = d'oh
965 d'oh = parseError loc "Malformed entity string"
967 -- construct a foreign export declaration
970 -> (Located FastString, Located RdrName, LHsType RdrName)
971 -> P (HsDecl RdrName)
972 mkExport (CCall cconv) (L loc entity, v, ty) = return $
973 ForD (ForeignExport v ty (CExport (CExportStatic entity' cconv)))
975 entity' | nullFS entity = mkExtName (unLoc v)
977 mkExport DNCall (L loc entity, v, ty) =
978 parseError (getLoc v){-TODO: not quite right-}
979 "Foreign export is not yet supported for .NET"
981 -- Supplying the ext_name in a foreign decl is optional; if it
982 -- isn't there, the Haskell name is assumed. Note that no transformation
983 -- of the Haskell name is then performed, so if you foreign export (++),
984 -- it's external name will be "++". Too bad; it's important because we don't
985 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
987 mkExtName :: RdrName -> CLabelString
988 mkExtName rdrNm = mkFastString (occNameString (rdrNameOcc rdrNm))
992 -----------------------------------------------------------------------------
996 showRdrName :: RdrName -> String
997 showRdrName r = showSDoc (ppr r)
999 parseError :: SrcSpan -> String -> P a
1000 parseError span s = failSpanMsgP span s