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