Refactor the handling of quasi-quotes
[ghc.git] / compiler / parser / RdrHsSyn.hs
1 --
2 -- (c) The University of Glasgow 2002-2006
3 --
4
5 -- Functions over HsSyn specialised to RdrName.
6
7 {-# LANGUAGE CPP #-}
8 {-# LANGUAGE FlexibleContexts #-}
9
10 module RdrHsSyn (
11 mkHsOpApp,
12 mkHsIntegral, mkHsFractional, mkHsIsString,
13 mkHsDo, mkSpliceDecl,
14 mkRoleAnnotDecl,
15 mkClassDecl,
16 mkTyData, mkDataFamInst,
17 mkTySynonym, mkTyFamInstEqn,
18 mkTyFamInst,
19 mkFamDecl,
20 splitCon, mkInlinePragma,
21 mkPatSynMatchGroup,
22 mkRecConstrOrUpdate, -- HsExp -> [HsFieldUpdate] -> P HsExp
23 mkTyClD, mkInstD,
24
25 cvBindGroup,
26 cvBindsAndSigs,
27 cvTopDecls,
28 placeHolderPunRhs,
29
30 -- Stuff to do with Foreign declarations
31 mkImport,
32 parseCImport,
33 mkExport,
34 mkExtName, -- RdrName -> CLabelString
35 mkGadtDecl, -- [Located RdrName] -> LHsType RdrName -> ConDecl RdrName
36 mkSimpleConDecl,
37 mkDeprecatedGadtRecordDecl,
38 mkATDefault,
39
40 -- Bunch of functions in the parser monad for
41 -- checking and constructing values
42 checkPrecP, -- Int -> P Int
43 checkContext, -- HsType -> P HsContext
44 checkPattern, -- HsExp -> P HsPat
45 bang_RDR,
46 checkPatterns, -- SrcLoc -> [HsExp] -> P [HsPat]
47 checkMonadComp, -- P (HsStmtContext RdrName)
48 checkCommand, -- LHsExpr RdrName -> P (LHsCmd RdrName)
49 checkValDef, -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
50 checkValSig, -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
51 checkPartialTypeSignature,
52 checkNoPartialType,
53 checkValidPatSynSig,
54 checkDoAndIfThenElse,
55 checkRecordSyntax,
56 checkValidDefaults,
57 parseErrorSDoc,
58
59 -- Help with processing exports
60 ImpExpSubSpec(..),
61 mkModuleImpExp,
62 mkTypeImpExp
63
64 ) where
65
66 import HsSyn -- Lots of it
67 import Class ( FunDep )
68 import CoAxiom ( Role, fsFromRole )
69 import RdrName ( RdrName, isRdrTyVar, isRdrTc, mkUnqual, rdrNameOcc,
70 isRdrDataCon, isUnqual, getRdrName, setRdrNameSpace,
71 rdrNameSpace )
72 import OccName ( tcClsName, isVarNameSpace )
73 import Name ( Name )
74 import BasicTypes ( maxPrecedence, Activation(..), RuleMatchInfo,
75 InlinePragma(..), InlineSpec(..), Origin(..),
76 SourceText )
77 import TcEvidence ( idHsWrapper )
78 import Lexer
79 import TysWiredIn ( unitTyCon, unitDataCon )
80 import ForeignCall
81 import OccName ( srcDataName, varName, isDataOcc, isTcOcc,
82 occNameString )
83 import PrelNames ( forall_tv_RDR, allNameStrings )
84 import DynFlags
85 import SrcLoc
86 import OrdList ( OrdList, fromOL )
87 import Bag ( emptyBag, consBag )
88 import Outputable
89 import FastString
90 import Maybes
91 import Util
92 import ApiAnnotation
93
94 import Control.Applicative ((<$>))
95 import Control.Monad
96
97 import Text.ParserCombinators.ReadP as ReadP
98 import Data.Char
99
100 import Data.Data ( dataTypeOf, fromConstr, dataTypeConstrs )
101 import Data.List ( partition )
102 import qualified Data.Set as Set ( fromList, difference, member )
103
104 #include "HsVersions.h"
105
106
107 {- **********************************************************************
108
109 Construction functions for Rdr stuff
110
111 ********************************************************************* -}
112
113 -- | mkClassDecl builds a RdrClassDecl, filling in the names for tycon and
114 -- datacon by deriving them from the name of the class. We fill in the names
115 -- for the tycon and datacon corresponding to the class, by deriving them
116 -- from the name of the class itself. This saves recording the names in the
117 -- interface file (which would be equally good).
118
119 -- Similarly for mkConDecl, mkClassOpSig and default-method names.
120
121 -- *** See "THE NAMING STORY" in HsDecls ****
122
123 mkTyClD :: LTyClDecl n -> LHsDecl n
124 mkTyClD (L loc d) = L loc (TyClD d)
125
126 mkInstD :: LInstDecl n -> LHsDecl n
127 mkInstD (L loc d) = L loc (InstD d)
128
129 mkClassDecl :: SrcSpan
130 -> Located (Maybe (LHsContext RdrName), LHsType RdrName)
131 -> Located (a,[Located (FunDep (Located RdrName))])
132 -> OrdList (LHsDecl RdrName)
133 -> P (LTyClDecl RdrName)
134
135 mkClassDecl loc (L _ (mcxt, tycl_hdr)) fds where_cls
136 = do { (binds, sigs, ats, at_insts, _, docs) <- cvBindsAndSigs where_cls
137 ; let cxt = fromMaybe (noLoc []) mcxt
138 ; (cls, tparams,ann) <- checkTyClHdr tycl_hdr
139 ; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
140 -- Partial type signatures are not allowed in a class definition
141 ; checkNoPartialSigs sigs cls
142 ; tyvars <- checkTyVarsP (ptext (sLit "class")) whereDots cls tparams
143 ; at_defs <- mapM (eitherToP . mkATDefault) at_insts
144 ; return (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls, tcdTyVars = tyvars,
145 tcdFDs = snd (unLoc fds), tcdSigs = sigs,
146 tcdMeths = binds,
147 tcdATs = ats, tcdATDefs = at_defs, tcdDocs = docs,
148 tcdFVs = placeHolderNames })) }
149
150 mkATDefault :: LTyFamInstDecl RdrName
151 -> Either (SrcSpan, SDoc) (LTyFamDefltEqn RdrName)
152 -- Take a type-family instance declaration and turn it into
153 -- a type-family default equation for a class declaration
154 -- We parse things as the former and use this function to convert to the latter
155 --
156 -- We use the Either monad because this also called
157 -- from Convert.hs
158 mkATDefault (L loc (TyFamInstDecl { tfid_eqn = L _ e }))
159 | TyFamEqn { tfe_tycon = tc, tfe_pats = pats, tfe_rhs = rhs } <- e
160 = do { tvs <- checkTyVars (ptext (sLit "default")) equalsDots tc (hswb_cts pats)
161 ; return (L loc (TyFamEqn { tfe_tycon = tc
162 , tfe_pats = tvs
163 , tfe_rhs = rhs })) }
164
165 -- | Check that none of the given type signatures of the class definition
166 -- ('Located RdrName') are partial type signatures. An error will be reported
167 -- for each wildcard found in a (partial) type signature. We do this check
168 -- because we want the signatures in a class definition to be fully specified.
169 checkNoPartialSigs :: [LSig RdrName] -> Located RdrName -> P ()
170 checkNoPartialSigs sigs cls_name =
171 sequence_ [ whenIsJust mb_loc $ \loc -> parseErrorSDoc loc $ err sig
172 | L _ sig@(TypeSig _ ty _) <- sigs
173 , let mb_loc = maybeLocation $ findWildcards ty ]
174 where err sig =
175 vcat [ text "The type signature of a class method cannot be partial:"
176 , ppr sig
177 , text "In the class declaration for " <> quotes (ppr cls_name) ]
178
179 -- | Check that none of the given constructors contain a wildcard (like in a
180 -- partial type signature). An error will be reported for each wildcard found
181 -- in a (partial) constructor definition. We do this check because we want the
182 -- type of a constructor to be fully specified.
183 checkNoPartialCon :: [LConDecl RdrName] -> P ()
184 checkNoPartialCon con_decls =
185 sequence_ [ whenIsJust mb_loc $ \loc -> parseErrorSDoc loc $ err cd
186 | L _ cd@(ConDecl { con_cxt = cxt, con_res = res,
187 con_details = details }) <- con_decls
188 , let mb_loc = maybeLocation $
189 concatMap findWildcards (unLoc cxt) ++
190 containsWildcardRes res ++
191 concatMap findWildcards
192 (hsConDeclArgTys details) ]
193 where err con_decl = text "A constructor cannot have a partial type:" $$
194 ppr con_decl
195 containsWildcardRes (ResTyGADT _ ty) = findWildcards ty
196 containsWildcardRes ResTyH98 = notFound
197
198 -- | Check that the given type does not contain wildcards, and is thus not a
199 -- partial type. If it contains wildcards, report an error with the given
200 -- message.
201 checkNoPartialType :: SDoc -> LHsType RdrName -> P ()
202 checkNoPartialType context_msg ty =
203 whenFound (findWildcards ty) $ \loc -> parseErrorSDoc loc err
204 where err = text "Wildcard not allowed" $$ context_msg
205
206 -- | Represent wildcards found in a type. Used for reporting errors for types
207 -- that mustn't contain wildcards.
208 data FoundWildcard = Found { location :: SrcSpan }
209 | FoundNamed { location :: SrcSpan, _name :: RdrName }
210
211 -- | Indicate that no wildcards were found.
212 notFound :: [FoundWildcard]
213 notFound = []
214
215 -- | Call the function (second argument), accepting the location of the
216 -- wildcard, on the first wildcard that was found, if any.
217 whenFound :: [FoundWildcard] -> (SrcSpan -> P ()) -> P ()
218 whenFound (Found loc:_) f = f loc
219 whenFound (FoundNamed loc _:_) f = f loc
220 whenFound _ _ = return ()
221
222 -- | Extract the location of the first wildcard, if any.
223 maybeLocation :: [FoundWildcard] -> Maybe SrcSpan
224 maybeLocation fws = location <$> listToMaybe fws
225
226 -- | Extract the named wildcards from the wildcards that were found.
227 namedWildcards :: [FoundWildcard] -> [RdrName]
228 namedWildcards fws = [name | FoundNamed _ name <- fws]
229
230 -- | Split the found wildcards into a list of found unnamed wildcard and found
231 -- named wildcards.
232 splitUnnamedNamed :: [FoundWildcard] -> ([FoundWildcard], [FoundWildcard])
233 splitUnnamedNamed = partition (\f -> case f of { Found _ -> True ; _ -> False})
234
235 -- | Return a list of the wildcards found while traversing the given type.
236 findWildcards :: LHsType RdrName -> [FoundWildcard]
237 findWildcards (L l ty) = case ty of
238 (HsForAllTy _ xtr _ (L _ ctxt) x) -> (map Found $ maybeToList xtr) ++
239 concatMap go ctxt ++ go x
240 (HsAppTy x y) -> go x ++ go y
241 (HsFunTy x y) -> go x ++ go y
242 (HsListTy x) -> go x
243 (HsPArrTy x) -> go x
244 (HsTupleTy _ xs) -> concatMap go xs
245 (HsOpTy x _ y) -> go x ++ go y
246 (HsParTy x) -> go x
247 (HsIParamTy _ x) -> go x
248 (HsEqTy x y) -> go x ++ go y
249 (HsKindSig x y) -> go x ++ go y
250 (HsDocTy x _) -> go x
251 (HsBangTy _ x) -> go x
252 (HsRecTy xs) ->
253 concatMap (go . getBangType . cd_fld_type . unLoc) xs
254 (HsExplicitListTy _ xs) -> concatMap go xs
255 (HsExplicitTupleTy _ xs) -> concatMap go xs
256 (HsWrapTy _ x) -> go (noLoc x)
257 HsWildcardTy -> [Found l]
258 (HsNamedWildcardTy n) -> [FoundNamed l n]
259 -- HsTyVar, HsQuasiQuoteTy, HsSpliceTy, HsCoreTy, HsTyLit
260 _ -> notFound
261 where go = findWildcards
262
263 mkTyData :: SrcSpan
264 -> NewOrData
265 -> Maybe (Located CType)
266 -> Located (Maybe (LHsContext RdrName), LHsType RdrName)
267 -> Maybe (LHsKind RdrName)
268 -> [LConDecl RdrName]
269 -> Maybe (Located [LHsType RdrName])
270 -> P (LTyClDecl RdrName)
271 mkTyData loc new_or_data cType (L _ (mcxt, tycl_hdr)) ksig data_cons maybe_deriv
272 = do { (tc, tparams,ann) <- checkTyClHdr tycl_hdr
273 ; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
274 ; tyvars <- checkTyVarsP (ppr new_or_data) equalsDots tc tparams
275 ; defn <- mkDataDefn new_or_data cType mcxt ksig data_cons maybe_deriv
276 ; return (L loc (DataDecl { tcdLName = tc, tcdTyVars = tyvars,
277 tcdDataDefn = defn,
278 tcdFVs = placeHolderNames })) }
279
280 mkDataDefn :: NewOrData
281 -> Maybe (Located CType)
282 -> Maybe (LHsContext RdrName)
283 -> Maybe (LHsKind RdrName)
284 -> [LConDecl RdrName]
285 -> Maybe (Located [LHsType RdrName])
286 -> P (HsDataDefn RdrName)
287 mkDataDefn new_or_data cType mcxt ksig data_cons maybe_deriv
288 = do { checkDatatypeContext mcxt
289 ; checkNoPartialCon data_cons
290 ; whenIsJust maybe_deriv $
291 \(L _ deriv) -> mapM_ (checkNoPartialType (errDeriv deriv)) deriv
292 ; let cxt = fromMaybe (noLoc []) mcxt
293 ; return (HsDataDefn { dd_ND = new_or_data, dd_cType = cType
294 , dd_ctxt = cxt
295 , dd_cons = data_cons
296 , dd_kindSig = ksig
297 , dd_derivs = maybe_deriv }) }
298 where errDeriv deriv = text "In the deriving items:" <+>
299 pprHsContextNoArrow deriv
300
301
302 mkTySynonym :: SrcSpan
303 -> LHsType RdrName -- LHS
304 -> LHsType RdrName -- RHS
305 -> P (LTyClDecl RdrName)
306 mkTySynonym loc lhs rhs
307 = do { (tc, tparams,ann) <- checkTyClHdr lhs
308 ; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
309 ; tyvars <- checkTyVarsP (ptext (sLit "type")) equalsDots tc tparams
310 ; let err = text "In type synonym" <+> quotes (ppr tc) <>
311 colon <+> ppr rhs
312 ; checkNoPartialType err rhs
313 ; return (L loc (SynDecl { tcdLName = tc, tcdTyVars = tyvars
314 , tcdRhs = rhs, tcdFVs = placeHolderNames })) }
315
316 mkTyFamInstEqn :: LHsType RdrName
317 -> LHsType RdrName
318 -> P (TyFamInstEqn RdrName,[AddAnn])
319 mkTyFamInstEqn lhs rhs
320 = do { (tc, tparams,ann) <- checkTyClHdr lhs
321 ; let err xhs = hang (text "In type family instance equation of" <+>
322 quotes (ppr tc) <> colon)
323 2 (ppr xhs)
324 ; checkNoPartialType (err lhs) lhs
325 ; checkNoPartialType (err rhs) rhs
326 ; return (TyFamEqn { tfe_tycon = tc
327 , tfe_pats = mkHsWithBndrs tparams
328 , tfe_rhs = rhs },
329 ann) }
330
331 mkDataFamInst :: SrcSpan
332 -> NewOrData
333 -> Maybe (Located CType)
334 -> Located (Maybe (LHsContext RdrName), LHsType RdrName)
335 -> Maybe (LHsKind RdrName)
336 -> [LConDecl RdrName]
337 -> Maybe (Located [LHsType RdrName])
338 -> P (LInstDecl RdrName)
339 mkDataFamInst loc new_or_data cType (L _ (mcxt, tycl_hdr)) ksig data_cons maybe_deriv
340 = do { (tc, tparams,ann) <- checkTyClHdr tycl_hdr
341 ; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
342 ; defn <- mkDataDefn new_or_data cType mcxt ksig data_cons maybe_deriv
343 ; return (L loc (DataFamInstD (
344 DataFamInstDecl { dfid_tycon = tc, dfid_pats = mkHsWithBndrs tparams
345 , dfid_defn = defn, dfid_fvs = placeHolderNames }))) }
346
347 mkTyFamInst :: SrcSpan
348 -> LTyFamInstEqn RdrName
349 -> P (LInstDecl RdrName)
350 mkTyFamInst loc eqn
351 = return (L loc (TyFamInstD (TyFamInstDecl { tfid_eqn = eqn
352 , tfid_fvs = placeHolderNames })))
353
354 mkFamDecl :: SrcSpan
355 -> FamilyInfo RdrName
356 -> LHsType RdrName -- LHS
357 -> Maybe (LHsKind RdrName) -- Optional kind signature
358 -> P (LTyClDecl RdrName)
359 mkFamDecl loc info lhs ksig
360 = do { (tc, tparams,ann) <- checkTyClHdr lhs
361 ; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
362 ; tyvars <- checkTyVarsP (ppr info) equals_or_where tc tparams
363 ; return (L loc (FamDecl (FamilyDecl { fdInfo = info, fdLName = tc
364 , fdTyVars = tyvars, fdKindSig = ksig }))) }
365 where
366 equals_or_where = case info of
367 DataFamily -> empty
368 OpenTypeFamily -> empty
369 ClosedTypeFamily {} -> whereDots
370
371 mkSpliceDecl :: LHsExpr RdrName -> HsDecl RdrName
372 -- If the user wrote
373 -- [pads| ... ] then return a QuasiQuoteD
374 -- $(e) then return a SpliceD
375 -- but if she wrote, say,
376 -- f x then behave as if she'd written $(f x)
377 -- ie a SpliceD
378 mkSpliceDecl lexpr@(L loc expr)
379 | HsSpliceE splice <- expr = SpliceD (SpliceDecl (L loc splice) ExplicitSplice)
380 | otherwise = SpliceD (SpliceDecl (L loc splice) ImplicitSplice)
381 where
382 splice = mkUntypedSplice lexpr
383
384 mkRoleAnnotDecl :: SrcSpan
385 -> Located RdrName -- type being annotated
386 -> [Located (Maybe FastString)] -- roles
387 -> P (LRoleAnnotDecl RdrName)
388 mkRoleAnnotDecl loc tycon roles
389 = do { roles' <- mapM parse_role roles
390 ; return $ L loc $ RoleAnnotDecl tycon roles' }
391 where
392 role_data_type = dataTypeOf (undefined :: Role)
393 all_roles = map fromConstr $ dataTypeConstrs role_data_type
394 possible_roles = [(fsFromRole role, role) | role <- all_roles]
395
396 parse_role (L loc_role Nothing) = return $ L loc_role Nothing
397 parse_role (L loc_role (Just role))
398 = case lookup role possible_roles of
399 Just found_role -> return $ L loc_role $ Just found_role
400 Nothing ->
401 let nearby = fuzzyLookup (unpackFS role) (mapFst unpackFS possible_roles) in
402 parseErrorSDoc loc_role
403 (text "Illegal role name" <+> quotes (ppr role) $$
404 suggestions nearby)
405
406 suggestions [] = empty
407 suggestions [r] = text "Perhaps you meant" <+> quotes (ppr r)
408 -- will this last case ever happen??
409 suggestions list = hang (text "Perhaps you meant one of these:")
410 2 (pprWithCommas (quotes . ppr) list)
411
412 {- **********************************************************************
413
414 #cvBinds-etc# Converting to @HsBinds@, etc.
415
416 ********************************************************************* -}
417
418 -- | Function definitions are restructured here. Each is assumed to be recursive
419 -- initially, and non recursive definitions are discovered by the dependency
420 -- analyser.
421
422
423 -- | Groups together bindings for a single function
424 cvTopDecls :: OrdList (LHsDecl RdrName) -> [LHsDecl RdrName]
425 cvTopDecls decls = go (fromOL decls)
426 where
427 go :: [LHsDecl RdrName] -> [LHsDecl RdrName]
428 go [] = []
429 go (L l (ValD b) : ds) = L l' (ValD b') : go ds'
430 where (L l' b', ds') = getMonoBind (L l b) ds
431 go (d : ds) = d : go ds
432
433 -- Declaration list may only contain value bindings and signatures.
434 cvBindGroup :: OrdList (LHsDecl RdrName) -> P (HsValBinds RdrName)
435 cvBindGroup binding
436 = do { (mbs, sigs, fam_ds, tfam_insts, dfam_insts, _) <- cvBindsAndSigs binding
437 ; ASSERT( null fam_ds && null tfam_insts && null dfam_insts)
438 return $ ValBindsIn mbs sigs }
439
440 cvBindsAndSigs :: OrdList (LHsDecl RdrName)
441 -> P (LHsBinds RdrName, [LSig RdrName], [LFamilyDecl RdrName]
442 , [LTyFamInstDecl RdrName], [LDataFamInstDecl RdrName], [LDocDecl])
443 -- Input decls contain just value bindings and signatures
444 -- and in case of class or instance declarations also
445 -- associated type declarations. They might also contain Haddock comments.
446 cvBindsAndSigs fb = go (fromOL fb)
447 where
448 go [] = return (emptyBag, [], [], [], [], [])
449 go (L l (ValD b) : ds)
450 = do { (bs, ss, ts, tfis, dfis, docs) <- go ds'
451 ; return (b' `consBag` bs, ss, ts, tfis, dfis, docs) }
452 where
453 (b', ds') = getMonoBind (L l b) ds
454 go (L l decl : ds)
455 = do { (bs, ss, ts, tfis, dfis, docs) <- go ds
456 ; case decl of
457 SigD s
458 -> return (bs, L l s : ss, ts, tfis, dfis, docs)
459 TyClD (FamDecl t)
460 -> return (bs, ss, L l t : ts, tfis, dfis, docs)
461 InstD (TyFamInstD { tfid_inst = tfi })
462 -> return (bs, ss, ts, L l tfi : tfis, dfis, docs)
463 InstD (DataFamInstD { dfid_inst = dfi })
464 -> return (bs, ss, ts, tfis, L l dfi : dfis, docs)
465 DocD d
466 -> return (bs, ss, ts, tfis, dfis, L l d : docs)
467 SpliceD d
468 -> parseErrorSDoc l $
469 hang (text "Declaration splices are allowed only" <+>
470 text "at the top level:")
471 2 (ppr d)
472 _ -> pprPanic "cvBindsAndSigs" (ppr decl) }
473
474 -----------------------------------------------------------------------------
475 -- Group function bindings into equation groups
476
477 getMonoBind :: LHsBind RdrName -> [LHsDecl RdrName]
478 -> (LHsBind RdrName, [LHsDecl RdrName])
479 -- Suppose (b',ds') = getMonoBind b ds
480 -- ds is a list of parsed bindings
481 -- b is a MonoBinds that has just been read off the front
482
483 -- Then b' is the result of grouping more equations from ds that
484 -- belong with b into a single MonoBinds, and ds' is the depleted
485 -- list of parsed bindings.
486 --
487 -- All Haddock comments between equations inside the group are
488 -- discarded.
489 --
490 -- No AndMonoBinds or EmptyMonoBinds here; just single equations
491
492 getMonoBind (L loc1 (FunBind { fun_id = fun_id1@(L _ f1), fun_infix = is_infix1,
493 fun_matches = MG { mg_alts = mtchs1 } })) binds
494 | has_args mtchs1
495 = go is_infix1 mtchs1 loc1 binds []
496 where
497 go is_infix mtchs loc
498 (L loc2 (ValD (FunBind { fun_id = L _ f2, fun_infix = is_infix2,
499 fun_matches = MG { mg_alts = mtchs2 } })) : binds) _
500 | f1 == f2 = go (is_infix || is_infix2) (mtchs2 ++ mtchs)
501 (combineSrcSpans loc loc2) binds []
502 go is_infix mtchs loc (doc_decl@(L loc2 (DocD _)) : binds) doc_decls
503 = let doc_decls' = doc_decl : doc_decls
504 in go is_infix mtchs (combineSrcSpans loc loc2) binds doc_decls'
505 go is_infix mtchs loc binds doc_decls
506 = (L loc (makeFunBind fun_id1 is_infix (reverse mtchs)), (reverse doc_decls) ++ binds)
507 -- Reverse the final matches, to get it back in the right order
508 -- Do the same thing with the trailing doc comments
509
510 getMonoBind bind binds = (bind, binds)
511
512 has_args :: [LMatch RdrName (LHsExpr RdrName)] -> Bool
513 has_args [] = panic "RdrHsSyn:has_args"
514 has_args ((L _ (Match _ args _ _)) : _) = not (null args)
515 -- Don't group together FunBinds if they have
516 -- no arguments. This is necessary now that variable bindings
517 -- with no arguments are now treated as FunBinds rather
518 -- than pattern bindings (tests/rename/should_fail/rnfail002).
519
520 {- **********************************************************************
521
522 #PrefixToHS-utils# Utilities for conversion
523
524 ********************************************************************* -}
525
526 -----------------------------------------------------------------------------
527 -- splitCon
528
529 -- When parsing data declarations, we sometimes inadvertently parse
530 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
531 -- This function splits up the type application, adds any pending
532 -- arguments, and converts the type constructor back into a data constructor.
533
534 splitCon :: LHsType RdrName
535 -> P (Located RdrName, HsConDeclDetails RdrName)
536 -- This gets given a "type" that should look like
537 -- C Int Bool
538 -- or C { x::Int, y::Bool }
539 -- and returns the pieces
540 splitCon ty
541 = split ty []
542 where
543 split (L _ (HsAppTy t u)) ts = split t (u : ts)
544 split (L l (HsTyVar tc)) ts = do data_con <- tyConToDataCon l tc
545 return (data_con, mk_rest ts)
546 split (L l (HsTupleTy _ [])) [] = return (L l (getRdrName unitDataCon), PrefixCon [])
547 -- See Note [Unit tuples] in HsTypes
548 split (L l _) _ = parseErrorSDoc l (text "Cannot parse data constructor in a data/newtype declaration:" <+> ppr ty)
549
550 mk_rest [L l (HsRecTy flds)] = RecCon (L l flds)
551 mk_rest ts = PrefixCon ts
552
553 recordPatSynErr :: SrcSpan -> LPat RdrName -> P a
554 recordPatSynErr loc pat =
555 parseErrorSDoc loc $
556 text "record syntax not supported for pattern synonym declarations:" $$
557 ppr pat
558
559 mkPatSynMatchGroup :: Located RdrName
560 -> Located (OrdList (LHsDecl RdrName))
561 -> P (MatchGroup RdrName (LHsExpr RdrName))
562 mkPatSynMatchGroup (L _ patsyn_name) (L _ decls) =
563 do { matches <- mapM fromDecl (fromOL decls)
564 ; return $ mkMatchGroup FromSource matches }
565 where
566 fromDecl (L loc decl@(ValD (PatBind pat@(L _ (ConPatIn (L _ name) details)) rhs _ _ _))) =
567 do { unless (name == patsyn_name) $
568 wrongNameBindingErr loc decl
569 ; match <- case details of
570 PrefixCon pats -> return $ Match Nothing pats Nothing rhs
571 InfixCon pat1 pat2 ->
572 return $ Match Nothing [pat1, pat2] Nothing rhs
573 RecCon{} -> recordPatSynErr loc pat
574 ; return $ L loc match }
575 fromDecl (L loc decl) = extraDeclErr loc decl
576
577 extraDeclErr loc decl =
578 parseErrorSDoc loc $
579 text "pattern synonym 'where' clause must contain a single binding:" $$
580 ppr decl
581
582 wrongNameBindingErr loc decl =
583 parseErrorSDoc loc $
584 text "pattern synonym 'where' clause must bind the pattern synonym's name" <+>
585 quotes (ppr patsyn_name) $$ ppr decl
586
587 mkDeprecatedGadtRecordDecl :: SrcSpan
588 -> Located RdrName
589 -> Located [LConDeclField RdrName]
590 -> LHsType RdrName
591 -> P (LConDecl RdrName)
592 -- This one uses the deprecated syntax
593 -- C { x,y ::Int } :: T a b
594 -- We give it a RecCon details right away
595 mkDeprecatedGadtRecordDecl loc (L con_loc con) flds res_ty
596 = do { data_con <- tyConToDataCon con_loc con
597 ; return (L loc (ConDecl { con_old_rec = True
598 , con_names = [data_con]
599 , con_explicit = Implicit
600 , con_qvars = mkHsQTvs []
601 , con_cxt = noLoc []
602 , con_details = RecCon flds
603 , con_res = ResTyGADT loc res_ty
604 , con_doc = Nothing })) }
605
606 mkSimpleConDecl :: Located RdrName -> [LHsTyVarBndr RdrName]
607 -> LHsContext RdrName -> HsConDeclDetails RdrName
608 -> ConDecl RdrName
609
610 mkSimpleConDecl name qvars cxt details
611 = ConDecl { con_old_rec = False
612 , con_names = [name]
613 , con_explicit = Explicit
614 , con_qvars = mkHsQTvs qvars
615 , con_cxt = cxt
616 , con_details = details
617 , con_res = ResTyH98
618 , con_doc = Nothing }
619
620 mkGadtDecl :: [Located RdrName]
621 -> LHsType RdrName -- Always a HsForAllTy
622 -> P (ConDecl RdrName)
623 -- We allow C,D :: ty
624 -- and expand it as if it had been
625 -- C :: ty; D :: ty
626 -- (Just like type signatures in general.)
627 mkGadtDecl _ ty@(L _ (HsForAllTy _ (Just l) _ _ _))
628 = parseErrorSDoc l $
629 text "A constructor cannot have a partial type:" $$
630 ppr ty
631 mkGadtDecl names (L ls (HsForAllTy imp Nothing qvars cxt tau))
632 = return $ mk_gadt_con names
633 where
634 (details, res_ty) -- See Note [Sorting out the result type]
635 = case tau of
636 L _ (HsFunTy (L l (HsRecTy flds)) res_ty)
637 -> (RecCon (L l flds), res_ty)
638 _other -> (PrefixCon [], tau)
639
640 mk_gadt_con names
641 = ConDecl { con_old_rec = False
642 , con_names = names
643 , con_explicit = imp
644 , con_qvars = qvars
645 , con_cxt = cxt
646 , con_details = details
647 , con_res = ResTyGADT ls res_ty
648 , con_doc = Nothing }
649 mkGadtDecl _ other_ty = pprPanic "mkGadtDecl" (ppr other_ty)
650
651 tyConToDataCon :: SrcSpan -> RdrName -> P (Located RdrName)
652 tyConToDataCon loc tc
653 | isTcOcc (rdrNameOcc tc)
654 = return (L loc (setRdrNameSpace tc srcDataName))
655 | otherwise
656 = parseErrorSDoc loc (msg $$ extra)
657 where
658 msg = text "Not a data constructor:" <+> quotes (ppr tc)
659 extra | tc == forall_tv_RDR
660 = text "Perhaps you intended to use ExistentialQuantification"
661 | otherwise = empty
662
663 -- | Note [Sorting out the result type]
664 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
665 -- In a GADT declaration which is not a record, we put the whole constr
666 -- type into the ResTyGADT for now; the renamer will unravel it once it
667 -- has sorted out operator fixities. Consider for example
668 -- C :: a :*: b -> a :*: b -> a :+: b
669 -- Initially this type will parse as
670 -- a :*: (b -> (a :*: (b -> (a :+: b))))
671
672 -- so it's hard to split up the arguments until we've done the precedence
673 -- resolution (in the renamer) On the other hand, for a record
674 -- { x,y :: Int } -> a :*: b
675 -- there is no doubt. AND we need to sort records out so that
676 -- we can bring x,y into scope. So:
677 -- * For PrefixCon we keep all the args in the ResTyGADT
678 -- * For RecCon we do not
679
680 checkTyVarsP :: SDoc -> SDoc -> Located RdrName -> [LHsType RdrName] -> P (LHsTyVarBndrs RdrName)
681 -- Same as checkTyVars, but in the P monad
682 checkTyVarsP pp_what equals_or_where tc tparms
683 = eitherToP $ checkTyVars pp_what equals_or_where tc tparms
684
685 eitherToP :: Either (SrcSpan, SDoc) a -> P a
686 -- Adapts the Either monad to the P monad
687 eitherToP (Left (loc, doc)) = parseErrorSDoc loc doc
688 eitherToP (Right thing) = return thing
689 checkTyVars :: SDoc -> SDoc -> Located RdrName -> [LHsType RdrName]
690 -> Either (SrcSpan, SDoc) (LHsTyVarBndrs RdrName)
691 -- Check whether the given list of type parameters are all type variables
692 -- (possibly with a kind signature)
693 -- We use the Either monad because it's also called (via mkATDefault) from
694 -- Convert.hs
695 checkTyVars pp_what equals_or_where tc tparms
696 = do { tvs <- mapM chk tparms
697 ; return (mkHsQTvs tvs) }
698 where
699
700 -- Check that the name space is correct!
701 chk (L l (HsKindSig (L lv (HsTyVar tv)) k))
702 | isRdrTyVar tv = return (L l (KindedTyVar (L lv tv) k))
703 chk (L l (HsTyVar tv))
704 | isRdrTyVar tv = return (L l (UserTyVar tv))
705 chk t@(L loc _)
706 = Left (loc,
707 vcat [ ptext (sLit "Unexpected type") <+> quotes (ppr t)
708 , ptext (sLit "In the") <+> pp_what <+> ptext (sLit "declaration for") <+> quotes (ppr tc)
709 , vcat[ (ptext (sLit "A") <+> pp_what <+> ptext (sLit "declaration should have form"))
710 , nest 2 (pp_what <+> ppr tc
711 <+> hsep (map text (takeList tparms allNameStrings))
712 <+> equals_or_where) ] ])
713
714 whereDots, equalsDots :: SDoc
715 -- Second argument to checkTyVars
716 whereDots = ptext (sLit "where ...")
717 equalsDots = ptext (sLit "= ...")
718
719 checkDatatypeContext :: Maybe (LHsContext RdrName) -> P ()
720 checkDatatypeContext Nothing = return ()
721 checkDatatypeContext (Just (L loc c))
722 = do allowed <- extension datatypeContextsEnabled
723 unless allowed $
724 parseErrorSDoc loc
725 (text "Illegal datatype context (use DatatypeContexts):" <+>
726 pprHsContext c)
727 mapM_ (checkNoPartialType err) c
728 where err = text "In the context:" <+> pprHsContextNoArrow c
729
730 checkRecordSyntax :: Outputable a => Located a -> P (Located a)
731 checkRecordSyntax lr@(L loc r)
732 = do allowed <- extension traditionalRecordSyntaxEnabled
733 if allowed
734 then return lr
735 else parseErrorSDoc loc
736 (text "Illegal record syntax (use TraditionalRecordSyntax):" <+>
737 ppr r)
738
739 checkTyClHdr :: LHsType RdrName
740 -> P (Located RdrName, -- the head symbol (type or class name)
741 [LHsType RdrName], -- parameters of head symbol
742 [AddAnn]) -- API Annotation for HsParTy when stripping parens
743 -- Well-formedness check and decomposition of type and class heads.
744 -- Decomposes T ty1 .. tyn into (T, [ty1, ..., tyn])
745 -- Int :*: Bool into (:*:, [Int, Bool])
746 -- returning the pieces
747 checkTyClHdr ty
748 = goL ty [] []
749 where
750 goL (L l ty) acc ann = go l ty acc ann
751
752 go l (HsTyVar tc) acc ann
753 | isRdrTc tc = return (L l tc, acc, ann)
754 go _ (HsOpTy t1 (_, ltc@(L _ tc)) t2) acc ann
755 | isRdrTc tc = return (ltc, t1:t2:acc, ann)
756 go l (HsParTy ty) acc ann = goL ty acc (ann ++ mkParensApiAnn l)
757 go _ (HsAppTy t1 t2) acc ann = goL t1 (t2:acc) ann
758 go l (HsTupleTy _ []) [] ann = return (L l (getRdrName unitTyCon), [],ann)
759 -- See Note [Unit tuples] in HsTypes
760 go l _ _ _
761 = parseErrorSDoc l (text "Malformed head of type or class declaration:"
762 <+> ppr ty)
763
764 checkContext :: LHsType RdrName -> P (LHsContext RdrName)
765 checkContext (L l orig_t)
766 = check orig_t
767 where
768 check (HsTupleTy _ ts) -- (Eq a, Ord b) shows up as a tuple type
769 = return (L l ts) -- Ditto ()
770
771 check (HsParTy ty) -- to be sure HsParTy doesn't get into the way
772 = check (unLoc ty)
773
774 check _
775 = return (L l [L l orig_t])
776
777 -- -------------------------------------------------------------------------
778 -- Checking Patterns.
779
780 -- We parse patterns as expressions and check for valid patterns below,
781 -- converting the expression into a pattern at the same time.
782
783 checkPattern :: SDoc -> LHsExpr RdrName -> P (LPat RdrName)
784 checkPattern msg e = checkLPat msg e
785
786 checkPatterns :: SDoc -> [LHsExpr RdrName] -> P [LPat RdrName]
787 checkPatterns msg es = mapM (checkPattern msg) es
788
789 checkLPat :: SDoc -> LHsExpr RdrName -> P (LPat RdrName)
790 checkLPat msg e@(L l _) = checkPat msg l e []
791
792 checkPat :: SDoc -> SrcSpan -> LHsExpr RdrName -> [LPat RdrName]
793 -> P (LPat RdrName)
794 checkPat _ loc (L l (HsVar c)) args
795 | isRdrDataCon c = return (L loc (ConPatIn (L l c) (PrefixCon args)))
796 checkPat msg loc e args -- OK to let this happen even if bang-patterns
797 -- are not enabled, because there is no valid
798 -- non-bang-pattern parse of (C ! e)
799 | Just (e', args') <- splitBang e
800 = do { args'' <- checkPatterns msg args'
801 ; checkPat msg loc e' (args'' ++ args) }
802 checkPat msg loc (L _ (HsApp f e)) args
803 = do p <- checkLPat msg e
804 checkPat msg loc f (p : args)
805 checkPat msg loc (L _ e) []
806 = do p <- checkAPat msg loc e
807 return (L loc p)
808 checkPat msg loc e _
809 = patFail msg loc (unLoc e)
810
811 checkAPat :: SDoc -> SrcSpan -> HsExpr RdrName -> P (Pat RdrName)
812 checkAPat msg loc e0 = do
813 pState <- getPState
814 let dynflags = dflags pState
815 case e0 of
816 EWildPat -> return (WildPat placeHolderType)
817 HsVar x -> return (VarPat x)
818 HsLit l -> return (LitPat l)
819
820 -- Overloaded numeric patterns (e.g. f 0 x = x)
821 -- Negation is recorded separately, so that the literal is zero or +ve
822 -- NB. Negative *primitive* literals are already handled by the lexer
823 HsOverLit pos_lit -> return (mkNPat (L loc pos_lit) Nothing)
824 NegApp (L l (HsOverLit pos_lit)) _
825 -> return (mkNPat (L l pos_lit) (Just noSyntaxExpr))
826
827 SectionR (L lb (HsVar bang)) e -- (! x)
828 | bang == bang_RDR
829 -> do { bang_on <- extension bangPatEnabled
830 ; if bang_on then do { e' <- checkLPat msg e
831 ; addAnnotation loc AnnBang lb
832 ; return (BangPat e') }
833 else parseErrorSDoc loc (text "Illegal bang-pattern (use BangPatterns):" $$ ppr e0) }
834
835 ELazyPat e -> checkLPat msg e >>= (return . LazyPat)
836 EAsPat n e -> checkLPat msg e >>= (return . AsPat n)
837 -- view pattern is well-formed if the pattern is
838 EViewPat expr patE -> checkLPat msg patE >>=
839 (return . (\p -> ViewPat expr p placeHolderType))
840 ExprWithTySig e t _ -> do e <- checkLPat msg e
841 -- Pattern signatures are parsed as sigtypes,
842 -- but they aren't explicit forall points. Hence
843 -- we have to remove the implicit forall here.
844 let t' = case t of
845 L _ (HsForAllTy Implicit _ _
846 (L _ []) ty) -> ty
847 other -> other
848 return (SigPatIn e (mkHsWithBndrs t'))
849
850 -- n+k patterns
851 OpApp (L nloc (HsVar n)) (L _ (HsVar plus)) _
852 (L lloc (HsOverLit lit@(OverLit {ol_val = HsIntegral {}})))
853 | xopt Opt_NPlusKPatterns dynflags && (plus == plus_RDR)
854 -> return (mkNPlusKPat (L nloc n) (L lloc lit))
855
856 OpApp l op _fix r -> do l <- checkLPat msg l
857 r <- checkLPat msg r
858 case op of
859 L cl (HsVar c) | isDataOcc (rdrNameOcc c)
860 -> return (ConPatIn (L cl c) (InfixCon l r))
861 _ -> patFail msg loc e0
862
863 HsPar e -> checkLPat msg e >>= (return . ParPat)
864 ExplicitList _ _ es -> do ps <- mapM (checkLPat msg) es
865 return (ListPat ps placeHolderType Nothing)
866 ExplicitPArr _ es -> do ps <- mapM (checkLPat msg) es
867 return (PArrPat ps placeHolderType)
868
869 ExplicitTuple es b
870 | all tupArgPresent es -> do ps <- mapM (checkLPat msg)
871 [e | L _ (Present e) <- es]
872 return (TuplePat ps b [])
873 | otherwise -> parseErrorSDoc loc (text "Illegal tuple section in pattern:" $$ ppr e0)
874
875 RecordCon c _ (HsRecFields fs dd)
876 -> do fs <- mapM (checkPatField msg) fs
877 return (ConPatIn c (RecCon (HsRecFields fs dd)))
878 HsSpliceE s | not (isTypedSplice s)
879 -> return (SplicePat s)
880 _ -> patFail msg loc e0
881
882 placeHolderPunRhs :: LHsExpr RdrName
883 -- The RHS of a punned record field will be filled in by the renamer
884 -- It's better not to make it an error, in case we want to print it when debugging
885 placeHolderPunRhs = noLoc (HsVar pun_RDR)
886
887 plus_RDR, bang_RDR, pun_RDR :: RdrName
888 plus_RDR = mkUnqual varName (fsLit "+") -- Hack
889 bang_RDR = mkUnqual varName (fsLit "!") -- Hack
890 pun_RDR = mkUnqual varName (fsLit "pun-right-hand-side")
891
892 checkPatField :: SDoc -> LHsRecField RdrName (LHsExpr RdrName)
893 -> P (LHsRecField RdrName (LPat RdrName))
894 checkPatField msg (L l fld) = do p <- checkLPat msg (hsRecFieldArg fld)
895 return (L l (fld { hsRecFieldArg = p }))
896
897 patFail :: SDoc -> SrcSpan -> HsExpr RdrName -> P a
898 patFail msg loc e = parseErrorSDoc loc err
899 where err = text "Parse error in pattern:" <+> ppr e
900 $$ msg
901
902
903 ---------------------------------------------------------------------------
904 -- Check Equation Syntax
905
906 checkValDef :: SDoc
907 -> LHsExpr RdrName
908 -> Maybe (LHsType RdrName)
909 -> Located (a,GRHSs RdrName (LHsExpr RdrName))
910 -> P (HsBind RdrName)
911
912 checkValDef msg lhs (Just sig) grhss
913 -- x :: ty = rhs parses as a *pattern* binding
914 = checkPatBind msg (L (combineLocs lhs sig)
915 (ExprWithTySig lhs sig PlaceHolder)) grhss
916
917 checkValDef msg lhs opt_sig g@(L l (_,grhss))
918 = do { mb_fun <- isFunLhs lhs
919 ; case mb_fun of
920 Just (fun, is_infix, pats) -> checkFunBind msg (getLoc lhs)
921 fun is_infix pats opt_sig (L l grhss)
922 Nothing -> checkPatBind msg lhs g }
923
924 checkFunBind :: SDoc
925 -> SrcSpan
926 -> Located RdrName
927 -> Bool
928 -> [LHsExpr RdrName]
929 -> Maybe (LHsType RdrName)
930 -> Located (GRHSs RdrName (LHsExpr RdrName))
931 -> P (HsBind RdrName)
932 checkFunBind msg lhs_loc fun is_infix pats opt_sig (L rhs_span grhss)
933 = do ps <- checkPatterns msg pats
934 let match_span = combineSrcSpans lhs_loc rhs_span
935 return (makeFunBind fun is_infix
936 [L match_span (Match (Just (fun,is_infix)) ps opt_sig grhss)])
937 -- The span of the match covers the entire equation.
938 -- That isn't quite right, but it'll do for now.
939
940 makeFunBind :: Located RdrName -> Bool -> [LMatch RdrName (LHsExpr RdrName)]
941 -> HsBind RdrName
942 -- Like HsUtils.mkFunBind, but we need to be able to set the fixity too
943 makeFunBind fn is_infix ms
944 = FunBind { fun_id = fn, fun_infix = is_infix,
945 fun_matches = mkMatchGroup FromSource ms,
946 fun_co_fn = idHsWrapper,
947 bind_fvs = placeHolderNames,
948 fun_tick = [] }
949
950 checkPatBind :: SDoc
951 -> LHsExpr RdrName
952 -> Located (a,GRHSs RdrName (LHsExpr RdrName))
953 -> P (HsBind RdrName)
954 checkPatBind msg lhs (L _ (_,grhss))
955 = do { lhs <- checkPattern msg lhs
956 ; return (PatBind lhs grhss placeHolderType placeHolderNames
957 ([],[])) }
958
959 checkValSig
960 :: LHsExpr RdrName
961 -> LHsType RdrName
962 -> P (Sig RdrName)
963 checkValSig (L l (HsVar v)) ty
964 | isUnqual v && not (isDataOcc (rdrNameOcc v))
965 = return (TypeSig [L l v] ty PlaceHolder)
966 checkValSig lhs@(L l _) ty
967 = parseErrorSDoc l ((text "Invalid type signature:" <+>
968 ppr lhs <+> text "::" <+> ppr ty)
969 $$ text hint)
970 where
971 hint = if foreign_RDR `looks_like` lhs
972 then "Perhaps you meant to use ForeignFunctionInterface?"
973 else if default_RDR `looks_like` lhs
974 then "Perhaps you meant to use DefaultSignatures?"
975 else "Should be of form <variable> :: <type>"
976 -- A common error is to forget the ForeignFunctionInterface flag
977 -- so check for that, and suggest. cf Trac #3805
978 -- Sadly 'foreign import' still barfs 'parse error' because 'import' is a keyword
979 looks_like s (L _ (HsVar v)) = v == s
980 looks_like s (L _ (HsApp lhs _)) = looks_like s lhs
981 looks_like _ _ = False
982
983 foreign_RDR = mkUnqual varName (fsLit "foreign")
984 default_RDR = mkUnqual varName (fsLit "default")
985
986
987 -- | Check that the default declarations do not contain wildcards in their
988 -- types, which we do not want as the types in the default declarations must
989 -- be fully specified.
990 checkValidDefaults :: [LHsType RdrName] -> P (DefaultDecl RdrName)
991 checkValidDefaults tys = mapM_ (checkNoPartialType err) tys >> return ret
992 where ret = DefaultDecl tys
993 err = text "In declaration:" <+> ppr ret
994
995 -- | Check that the pattern synonym type signature does not contain wildcards.
996 checkValidPatSynSig :: Sig RdrName -> P (Sig RdrName)
997 checkValidPatSynSig psig@(PatSynSig _ _ prov req ty)
998 = mapM_ (checkNoPartialType err) (unLoc prov ++ unLoc req ++ [ty])
999 >> return psig
1000 where err = hang (text "In pattern synonym type signature: ")
1001 2 (ppr psig)
1002 checkValidPatSynSig sig = return sig
1003 -- Should only be called with a pattern synonym type signature
1004
1005 -- | Check the validity of a partial type signature. We check the following
1006 -- things:
1007 --
1008 -- * There should only be one extra-constraints wildcard in the type
1009 -- signature, i.e. the @_@ in @_ => a -> String@.
1010 -- This would be invalid: @(Eq a, _) => a -> (Num a, _) => a -> Bool@.
1011 -- Extra-constraints wildcards are only allowed in the top-level context.
1012 --
1013 -- * Named extra-constraints wildcards aren't allowed,
1014 -- e.g. invalid: @(Show a, _x) => a -> String@.
1015 --
1016 -- * There is only one extra-constraints wildcard in the context and it must
1017 -- come last, e.g. invalid: @(_, Show a) => a -> String@
1018 -- or @(_, Show a, _) => a -> String@.
1019 --
1020 -- * There should be no unnamed wildcards in the context.
1021 --
1022 -- * Named wildcards occurring in the context must also occur in the monotype.
1023 --
1024 -- An error is reported when an invalid wildcard is found.
1025 checkPartialTypeSignature :: LHsType RdrName -> P (LHsType RdrName)
1026 checkPartialTypeSignature fullTy = case fullTy of
1027
1028 (L l (HsForAllTy flag extra bndrs (L lc ctxtP) ty)) -> do
1029 -- Remove parens around types in the context
1030 let ctxt = map ignoreParens ctxtP
1031 -- Check that the type doesn't contain any more extra-constraints wildcards
1032 checkNoExtraConstraintsWildcard ty
1033 -- Named extra-constraints wildcards aren't allowed
1034 whenIsJust (firstMatch isNamedWildcardTy ctxt) $
1035 \(L l _) -> err hintNamed l fullTy
1036 -- There should be no more (extra-constraints) wildcards in the context.
1037 -- If there was one at the end of the context, it is by now already
1038 -- removed from the context and stored in the @extra@ field of the
1039 -- 'HsForAllTy' by 'HsTypes.mkHsForAllTy'.
1040 whenIsJust (firstMatch isWildcardTy ctxt) $
1041 \(L l _) -> err hintLast l fullTy
1042 -- Find all wildcards in the context and the monotype, then divide
1043 -- them in unnamed and named wildcards
1044 let (unnamedInCtxt, namedInCtxt) = splitUnnamedNamed $
1045 concatMap findWildcards ctxt
1046 (_ , namedInTy) = splitUnnamedNamed $
1047 findWildcards ty
1048 -- Unnamed wildcards aren't allowed in the context
1049 case unnamedInCtxt of
1050 (Found lc : _) -> err hintUnnamedConstraint lc fullTy
1051 _ -> return ()
1052 -- Calculcate the set of named wildcards in the context that aren't in the
1053 -- monotype (tau)
1054 let namedWildcardsNotInTau = Set.fromList (namedWildcards namedInCtxt)
1055 `Set.difference`
1056 Set.fromList (namedWildcards namedInTy)
1057 -- Search for the first named wildcard that we encountered in the
1058 -- context that isn't present in the monotype (we lose the order
1059 -- in which they occur when using the Set directly).
1060 case filter (\(FoundNamed _ name) -> Set.member name namedWildcardsNotInTau)
1061 namedInCtxt of
1062 (FoundNamed lc name:_) -> err (hintNamedNotInMonotype name) lc fullTy
1063 _ -> return ()
1064
1065 -- Return the checked type
1066 return $ L l (HsForAllTy flag extra bndrs (L lc ctxtP) ty)
1067
1068
1069 ty -> do
1070 checkNoExtraConstraintsWildcard ty
1071 return ty
1072
1073 where
1074 ignoreParens (L _ (HsParTy ty)) = ty
1075 ignoreParens ty = ty
1076
1077 firstMatch :: (HsType a -> Bool) -> HsContext a -> Maybe (LHsType a)
1078 firstMatch pred ctxt = listToMaybe (filter (pred . unLoc) ctxt)
1079
1080 err hintSDoc lc ty = parseErrorSDoc lc $
1081 text "Invalid partial type signature:" $$
1082 ppr ty $$ hintSDoc
1083 hintLast = sep [ text "An extra-constraints wildcard is only allowed"
1084 , text "at the end of the constraints" ]
1085 hintNamed = text "A named wildcard cannot occur as a constraint"
1086 hintNested = sep [ text "An extra-constraints wildcard is only allowed"
1087 , text "at the top-level of the signature" ]
1088 hintUnnamedConstraint
1089 = text "Wildcards are not allowed within the constraints"
1090 hintNamedNotInMonotype name
1091 = sep [ text "The named wildcard" <+> quotes (ppr name) <+>
1092 text "is only allowed in the constraints"
1093 , text "when it also occurs in the (mono)type" ]
1094
1095 checkNoExtraConstraintsWildcard (L _ ty) = go ty
1096 where
1097 -- Report nested (named) extra-constraints wildcards
1098 go' = go . unLoc
1099 go (HsAppTy x y) = go' x >> go' y
1100 go (HsFunTy x y) = go' x >> go' y
1101 go (HsListTy x) = go' x
1102 go (HsPArrTy x) = go' x
1103 go (HsTupleTy _ xs) = mapM_ go' xs
1104 go (HsOpTy x _ y) = go' x >> go' y
1105 go (HsParTy x) = go' x
1106 go (HsIParamTy _ x) = go' x
1107 go (HsEqTy x y) = go' x >> go' y
1108 go (HsKindSig x y) = go' x >> go' y
1109 go (HsDocTy x _) = go' x
1110 go (HsBangTy _ x) = go' x
1111 go (HsRecTy xs) = mapM_ (go' . getBangType . cd_fld_type . unLoc) xs
1112 go (HsExplicitListTy _ xs) = mapM_ go' xs
1113 go (HsExplicitTupleTy _ xs) = mapM_ go' xs
1114 go (HsWrapTy _ x) = go' (noLoc x)
1115 go (HsForAllTy _ (Just l) _ _ _) = err hintNested l ty
1116 go (HsForAllTy _ Nothing _ (L _ ctxt) x)
1117 | Just (L l _) <- firstMatch isWildcardTy ctxt
1118 = err hintNested l ty
1119 | Just (L l _) <- firstMatch isNamedWildcardTy ctxt
1120 = err hintNamed l ty
1121 | otherwise = go' x
1122 go _ = return ()
1123
1124
1125 checkDoAndIfThenElse :: LHsExpr RdrName
1126 -> Bool
1127 -> LHsExpr RdrName
1128 -> Bool
1129 -> LHsExpr RdrName
1130 -> P ()
1131 checkDoAndIfThenElse guardExpr semiThen thenExpr semiElse elseExpr
1132 | semiThen || semiElse
1133 = do pState <- getPState
1134 unless (xopt Opt_DoAndIfThenElse (dflags pState)) $ do
1135 parseErrorSDoc (combineLocs guardExpr elseExpr)
1136 (text "Unexpected semi-colons in conditional:"
1137 $$ nest 4 expr
1138 $$ text "Perhaps you meant to use DoAndIfThenElse?")
1139 | otherwise = return ()
1140 where pprOptSemi True = semi
1141 pprOptSemi False = empty
1142 expr = text "if" <+> ppr guardExpr <> pprOptSemi semiThen <+>
1143 text "then" <+> ppr thenExpr <> pprOptSemi semiElse <+>
1144 text "else" <+> ppr elseExpr
1145
1146
1147 -- The parser left-associates, so there should
1148 -- not be any OpApps inside the e's
1149 splitBang :: LHsExpr RdrName -> Maybe (LHsExpr RdrName, [LHsExpr RdrName])
1150 -- Splits (f ! g a b) into (f, [(! g), a, b])
1151 splitBang (L loc (OpApp l_arg bang@(L _ (HsVar op)) _ r_arg))
1152 | op == bang_RDR = Just (l_arg, L loc (SectionR bang arg1) : argns)
1153 where
1154 (arg1,argns) = split_bang r_arg []
1155 split_bang (L _ (HsApp f e)) es = split_bang f (e:es)
1156 split_bang e es = (e,es)
1157 splitBang _ = Nothing
1158
1159 isFunLhs :: LHsExpr RdrName
1160 -> P (Maybe (Located RdrName, Bool, [LHsExpr RdrName]))
1161 -- A variable binding is parsed as a FunBind.
1162 -- Just (fun, is_infix, arg_pats) if e is a function LHS
1163 --
1164 -- The whole LHS is parsed as a single expression.
1165 -- Any infix operators on the LHS will parse left-associatively
1166 -- E.g. f !x y !z
1167 -- will parse (rather strangely) as
1168 -- (f ! x y) ! z
1169 -- It's up to isFunLhs to sort out the mess
1170 --
1171 -- a .!. !b
1172
1173 isFunLhs e = go e []
1174 where
1175 go (L loc (HsVar f)) es
1176 | not (isRdrDataCon f) = return (Just (L loc f, False, es))
1177 go (L _ (HsApp f e)) es = go f (e:es)
1178 go (L _ (HsPar e)) es@(_:_) = go e es
1179
1180 -- For infix function defns, there should be only one infix *function*
1181 -- (though there may be infix *datacons* involved too). So we don't
1182 -- need fixity info to figure out which function is being defined.
1183 -- a `K1` b `op` c `K2` d
1184 -- must parse as
1185 -- (a `K1` b) `op` (c `K2` d)
1186 -- The renamer checks later that the precedences would yield such a parse.
1187 --
1188 -- There is a complication to deal with bang patterns.
1189 --
1190 -- ToDo: what about this?
1191 -- x + 1 `op` y = ...
1192
1193 go e@(L loc (OpApp l (L loc' (HsVar op)) fix r)) es
1194 | Just (e',es') <- splitBang e
1195 = do { bang_on <- extension bangPatEnabled
1196 ; if bang_on then go e' (es' ++ es)
1197 else return (Just (L loc' op, True, (l:r:es))) }
1198 -- No bangs; behave just like the next case
1199 | not (isRdrDataCon op) -- We have found the function!
1200 = return (Just (L loc' op, True, (l:r:es)))
1201 | otherwise -- Infix data con; keep going
1202 = do { mb_l <- go l es
1203 ; case mb_l of
1204 Just (op', True, j : k : es')
1205 -> return (Just (op', True, j : op_app : es'))
1206 where
1207 op_app = L loc (OpApp k (L loc' (HsVar op)) fix r)
1208 _ -> return Nothing }
1209 go _ _ = return Nothing
1210
1211
1212 ---------------------------------------------------------------------------
1213 -- Check for monad comprehensions
1214 --
1215 -- If the flag MonadComprehensions is set, return a `MonadComp' context,
1216 -- otherwise use the usual `ListComp' context
1217
1218 checkMonadComp :: P (HsStmtContext Name)
1219 checkMonadComp = do
1220 pState <- getPState
1221 return $ if xopt Opt_MonadComprehensions (dflags pState)
1222 then MonadComp
1223 else ListComp
1224
1225 -- -------------------------------------------------------------------------
1226 -- Checking arrow syntax.
1227
1228 -- We parse arrow syntax as expressions and check for valid syntax below,
1229 -- converting the expression into a pattern at the same time.
1230
1231 checkCommand :: LHsExpr RdrName -> P (LHsCmd RdrName)
1232 checkCommand lc = locMap checkCmd lc
1233
1234 locMap :: (SrcSpan -> a -> P b) -> Located a -> P (Located b)
1235 locMap f (L l a) = f l a >>= (\b -> return $ L l b)
1236
1237 checkCmd :: SrcSpan -> HsExpr RdrName -> P (HsCmd RdrName)
1238 checkCmd _ (HsArrApp e1 e2 ptt haat b) =
1239 return $ HsCmdArrApp e1 e2 ptt haat b
1240 checkCmd _ (HsArrForm e mf args) =
1241 return $ HsCmdArrForm e mf args
1242 checkCmd _ (HsApp e1 e2) =
1243 checkCommand e1 >>= (\c -> return $ HsCmdApp c e2)
1244 checkCmd _ (HsLam mg) =
1245 checkCmdMatchGroup mg >>= (\mg' -> return $ HsCmdLam mg')
1246 checkCmd _ (HsPar e) =
1247 checkCommand e >>= (\c -> return $ HsCmdPar c)
1248 checkCmd _ (HsCase e mg) =
1249 checkCmdMatchGroup mg >>= (\mg' -> return $ HsCmdCase e mg')
1250 checkCmd _ (HsIf cf ep et ee) = do
1251 pt <- checkCommand et
1252 pe <- checkCommand ee
1253 return $ HsCmdIf cf ep pt pe
1254 checkCmd _ (HsLet lb e) =
1255 checkCommand e >>= (\c -> return $ HsCmdLet lb c)
1256 checkCmd _ (HsDo DoExpr stmts ty) =
1257 mapM checkCmdLStmt stmts >>= (\ss -> return $ HsCmdDo ss ty)
1258
1259 checkCmd _ (OpApp eLeft op _fixity eRight) = do
1260 -- OpApp becomes a HsCmdArrForm with a (Just fixity) in it
1261 c1 <- checkCommand eLeft
1262 c2 <- checkCommand eRight
1263 let arg1 = L (getLoc c1) $ HsCmdTop c1 placeHolderType placeHolderType []
1264 arg2 = L (getLoc c2) $ HsCmdTop c2 placeHolderType placeHolderType []
1265 return $ HsCmdArrForm op Nothing [arg1, arg2]
1266
1267 checkCmd l e = cmdFail l e
1268
1269 checkCmdLStmt :: ExprLStmt RdrName -> P (CmdLStmt RdrName)
1270 checkCmdLStmt = locMap checkCmdStmt
1271
1272 checkCmdStmt :: SrcSpan -> ExprStmt RdrName -> P (CmdStmt RdrName)
1273 checkCmdStmt _ (LastStmt e r) =
1274 checkCommand e >>= (\c -> return $ LastStmt c r)
1275 checkCmdStmt _ (BindStmt pat e b f) =
1276 checkCommand e >>= (\c -> return $ BindStmt pat c b f)
1277 checkCmdStmt _ (BodyStmt e t g ty) =
1278 checkCommand e >>= (\c -> return $ BodyStmt c t g ty)
1279 checkCmdStmt _ (LetStmt bnds) = return $ LetStmt bnds
1280 checkCmdStmt _ stmt@(RecStmt { recS_stmts = stmts }) = do
1281 ss <- mapM checkCmdLStmt stmts
1282 return $ stmt { recS_stmts = ss }
1283 checkCmdStmt l stmt = cmdStmtFail l stmt
1284
1285 checkCmdMatchGroup :: MatchGroup RdrName (LHsExpr RdrName) -> P (MatchGroup RdrName (LHsCmd RdrName))
1286 checkCmdMatchGroup mg@(MG { mg_alts = ms }) = do
1287 ms' <- mapM (locMap $ const convert) ms
1288 return $ mg { mg_alts = ms' }
1289 where convert (Match mf pat mty grhss) = do
1290 grhss' <- checkCmdGRHSs grhss
1291 return $ Match mf pat mty grhss'
1292
1293 checkCmdGRHSs :: GRHSs RdrName (LHsExpr RdrName) -> P (GRHSs RdrName (LHsCmd RdrName))
1294 checkCmdGRHSs (GRHSs grhss binds) = do
1295 grhss' <- mapM checkCmdGRHS grhss
1296 return $ GRHSs grhss' binds
1297
1298 checkCmdGRHS :: LGRHS RdrName (LHsExpr RdrName) -> P (LGRHS RdrName (LHsCmd RdrName))
1299 checkCmdGRHS = locMap $ const convert
1300 where
1301 convert (GRHS stmts e) = do
1302 c <- checkCommand e
1303 -- cmdStmts <- mapM checkCmdLStmt stmts
1304 return $ GRHS {- cmdStmts -} stmts c
1305
1306
1307 cmdFail :: SrcSpan -> HsExpr RdrName -> P a
1308 cmdFail loc e = parseErrorSDoc loc (text "Parse error in command:" <+> ppr e)
1309 cmdStmtFail :: SrcSpan -> Stmt RdrName (LHsExpr RdrName) -> P a
1310 cmdStmtFail loc e = parseErrorSDoc loc
1311 (text "Parse error in command statement:" <+> ppr e)
1312
1313 ---------------------------------------------------------------------------
1314 -- Miscellaneous utilities
1315
1316 checkPrecP :: Located Int -> P (Located Int)
1317 checkPrecP (L l i)
1318 | 0 <= i && i <= maxPrecedence = return (L l i)
1319 | otherwise
1320 = parseErrorSDoc l (text ("Precedence out of range: " ++ show i))
1321
1322 mkRecConstrOrUpdate
1323 :: LHsExpr RdrName
1324 -> SrcSpan
1325 -> ([LHsRecField RdrName (LHsExpr RdrName)], Bool)
1326 -> P (HsExpr RdrName)
1327
1328 mkRecConstrOrUpdate (L l (HsVar c)) _ (fs,dd)
1329 | isRdrDataCon c
1330 = return (RecordCon (L l c) noPostTcExpr (mk_rec_fields fs dd))
1331 mkRecConstrOrUpdate exp _ (fs,dd)
1332 = return (RecordUpd exp (mk_rec_fields fs dd) [] [] [])
1333
1334 mk_rec_fields :: [LHsRecField id arg] -> Bool -> HsRecFields id arg
1335 mk_rec_fields fs False = HsRecFields { rec_flds = fs, rec_dotdot = Nothing }
1336 mk_rec_fields fs True = HsRecFields { rec_flds = fs, rec_dotdot = Just (length fs) }
1337
1338 mkInlinePragma :: String -> (InlineSpec, RuleMatchInfo) -> Maybe Activation
1339 -> InlinePragma
1340 -- The (Maybe Activation) is because the user can omit
1341 -- the activation spec (and usually does)
1342 mkInlinePragma src (inl, match_info) mb_act
1343 = InlinePragma { inl_src = src -- Note [Pragma source text] in BasicTypes
1344 , inl_inline = inl
1345 , inl_sat = Nothing
1346 , inl_act = act
1347 , inl_rule = match_info }
1348 where
1349 act = case mb_act of
1350 Just act -> act
1351 Nothing -> -- No phase specified
1352 case inl of
1353 NoInline -> NeverActive
1354 _other -> AlwaysActive
1355
1356 -----------------------------------------------------------------------------
1357 -- utilities for foreign declarations
1358
1359 -- construct a foreign import declaration
1360 --
1361 mkImport :: Located CCallConv
1362 -> Located Safety
1363 -> (Located FastString, Located RdrName, LHsType RdrName)
1364 -> P (HsDecl RdrName)
1365 mkImport (L lc cconv) (L ls safety) (L loc entity, v, ty)
1366 | Just loc <- maybeLocation $ findWildcards ty
1367 = parseErrorSDoc loc $
1368 text "Wildcard not allowed" $$
1369 text "In foreign import declaration" <+>
1370 quotes (ppr v) $$ ppr ty
1371 | cconv == PrimCallConv = do
1372 let funcTarget = CFunction (StaticTarget entity Nothing True)
1373 importSpec = CImport (L lc PrimCallConv) (L ls safety) Nothing funcTarget
1374 (L loc (unpackFS entity))
1375 return (ForD (ForeignImport v ty noForeignImportCoercionYet importSpec))
1376 | cconv == JavaScriptCallConv = do
1377 let funcTarget = CFunction (StaticTarget entity Nothing True)
1378 importSpec = CImport (L lc JavaScriptCallConv) (L ls safety) Nothing
1379 funcTarget (L loc (unpackFS entity))
1380 return (ForD (ForeignImport v ty noForeignImportCoercionYet importSpec))
1381 | otherwise = do
1382 case parseCImport (L lc cconv) (L ls safety) (mkExtName (unLoc v))
1383 (unpackFS entity) (L loc (unpackFS entity)) of
1384 Nothing -> parseErrorSDoc loc (text "Malformed entity string")
1385 Just importSpec -> return (ForD (ForeignImport v ty noForeignImportCoercionYet importSpec))
1386
1387 -- the string "foo" is ambigous: either a header or a C identifier. The
1388 -- C identifier case comes first in the alternatives below, so we pick
1389 -- that one.
1390 parseCImport :: Located CCallConv -> Located Safety -> FastString -> String
1391 -> Located SourceText
1392 -> Maybe ForeignImport
1393 parseCImport cconv safety nm str sourceText =
1394 listToMaybe $ map fst $ filter (null.snd) $
1395 readP_to_S parse str
1396 where
1397 parse = do
1398 skipSpaces
1399 r <- choice [
1400 string "dynamic" >> return (mk Nothing (CFunction DynamicTarget)),
1401 string "wrapper" >> return (mk Nothing CWrapper),
1402 do optional (token "static" >> skipSpaces)
1403 ((mk Nothing <$> cimp nm) +++
1404 (do h <- munch1 hdr_char
1405 skipSpaces
1406 mk (Just (Header (mkFastString h))) <$> cimp nm))
1407 ]
1408 skipSpaces
1409 return r
1410
1411 token str = do _ <- string str
1412 toks <- look
1413 case toks of
1414 c : _
1415 | id_char c -> pfail
1416 _ -> return ()
1417
1418 mk h n = CImport cconv safety h n sourceText
1419
1420 hdr_char c = not (isSpace c) -- header files are filenames, which can contain
1421 -- pretty much any char (depending on the platform),
1422 -- so just accept any non-space character
1423 id_first_char c = isAlpha c || c == '_'
1424 id_char c = isAlphaNum c || c == '_'
1425
1426 cimp nm = (ReadP.char '&' >> skipSpaces >> CLabel <$> cid)
1427 +++ (do isFun <- case cconv of
1428 L _ CApiConv ->
1429 option True
1430 (do token "value"
1431 skipSpaces
1432 return False)
1433 _ -> return True
1434 cid' <- cid
1435 return (CFunction (StaticTarget cid' Nothing isFun)))
1436 where
1437 cid = return nm +++
1438 (do c <- satisfy id_first_char
1439 cs <- many (satisfy id_char)
1440 return (mkFastString (c:cs)))
1441
1442
1443 -- construct a foreign export declaration
1444 --
1445 mkExport :: Located CCallConv
1446 -> (Located FastString, Located RdrName, LHsType RdrName)
1447 -> P (HsDecl RdrName)
1448 mkExport (L lc cconv) (L le entity, v, ty) = do
1449 checkNoPartialType (ptext (sLit "In foreign export declaration") <+>
1450 quotes (ppr v) $$ ppr ty) ty
1451 return $ ForD (ForeignExport v ty noForeignExportCoercionYet
1452 (CExport (L lc (CExportStatic entity' cconv))
1453 (L le (unpackFS entity))))
1454 where
1455 entity' | nullFS entity = mkExtName (unLoc v)
1456 | otherwise = entity
1457
1458 -- Supplying the ext_name in a foreign decl is optional; if it
1459 -- isn't there, the Haskell name is assumed. Note that no transformation
1460 -- of the Haskell name is then performed, so if you foreign export (++),
1461 -- it's external name will be "++". Too bad; it's important because we don't
1462 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
1463 --
1464 mkExtName :: RdrName -> CLabelString
1465 mkExtName rdrNm = mkFastString (occNameString (rdrNameOcc rdrNm))
1466
1467 --------------------------------------------------------------------------------
1468 -- Help with module system imports/exports
1469
1470 data ImpExpSubSpec = ImpExpAbs | ImpExpAll | ImpExpList [Located RdrName]
1471
1472 mkModuleImpExp :: Located RdrName -> ImpExpSubSpec -> IE RdrName
1473 mkModuleImpExp n@(L l name) subs =
1474 case subs of
1475 ImpExpAbs
1476 | isVarNameSpace (rdrNameSpace name) -> IEVar n
1477 | otherwise -> IEThingAbs (L l nameT)
1478 ImpExpAll -> IEThingAll (L l nameT)
1479 ImpExpList xs -> IEThingWith (L l nameT) xs
1480
1481 where
1482 nameT = setRdrNameSpace name tcClsName
1483
1484 mkTypeImpExp :: Located RdrName -> P (Located RdrName)
1485 mkTypeImpExp name =
1486 do allowed <- extension explicitNamespacesEnabled
1487 if allowed
1488 then return (fmap (`setRdrNameSpace` tcClsName) name)
1489 else parseErrorSDoc (getLoc name)
1490 (text "Illegal keyword 'type' (use ExplicitNamespaces to enable)")
1491
1492 -----------------------------------------------------------------------------
1493 -- Misc utils
1494
1495 parseErrorSDoc :: SrcSpan -> SDoc -> P a
1496 parseErrorSDoc span s = failSpanMsgP span s