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