7e61172d84726ef7d229708574791a410dd48cd5
[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 checkTyVars :: SDoc -> SDoc -> Located RdrName -> [LHsType RdrName]
643 -> Either (SrcSpan, SDoc) (LHsQTyVars RdrName)
644 -- Check whether the given list of type parameters are all type variables
645 -- (possibly with a kind signature)
646 -- We use the Either monad because it's also called (via mkATDefault) from
647 -- Convert.hs
648 checkTyVars pp_what equals_or_where tc tparms
649 = do { tvs <- mapM chk tparms
650 ; return (mkHsQTvs tvs) }
651 where
652
653 chk (L _ (HsParTy ty)) = chk ty
654 chk (L _ (HsAppsTy [HsAppPrefix ty])) = chk ty
655
656 -- Check that the name space is correct!
657 chk (L l (HsKindSig (L _ (HsAppsTy [HsAppPrefix (L lv (HsTyVar (L _ tv)))])) k))
658 | isRdrTyVar tv = return (L l (KindedTyVar (L lv tv) k))
659 chk (L l (HsTyVar (L ltv tv)))
660 | isRdrTyVar tv = return (L l (UserTyVar (L ltv tv)))
661 chk t@(L loc _)
662 = Left (loc,
663 vcat [ ptext (sLit "Unexpected type") <+> quotes (ppr t)
664 , ptext (sLit "In the") <+> pp_what <+> ptext (sLit "declaration for") <+> quotes (ppr tc)
665 , vcat[ (ptext (sLit "A") <+> pp_what <+> ptext (sLit "declaration should have form"))
666 , nest 2 (pp_what <+> ppr tc
667 <+> hsep (map text (takeList tparms allNameStrings))
668 <+> equals_or_where) ] ])
669
670 whereDots, equalsDots :: SDoc
671 -- Second argument to checkTyVars
672 whereDots = ptext (sLit "where ...")
673 equalsDots = ptext (sLit "= ...")
674
675 checkDatatypeContext :: Maybe (LHsContext RdrName) -> P ()
676 checkDatatypeContext Nothing = return ()
677 checkDatatypeContext (Just (L loc c))
678 = do allowed <- extension datatypeContextsEnabled
679 unless allowed $
680 parseErrorSDoc loc
681 (text "Illegal datatype context (use DatatypeContexts):" <+>
682 pprHsContext c)
683
684 checkRecordSyntax :: Outputable a => Located a -> P (Located a)
685 checkRecordSyntax lr@(L loc r)
686 = do allowed <- extension traditionalRecordSyntaxEnabled
687 if allowed
688 then return lr
689 else parseErrorSDoc loc
690 (text "Illegal record syntax (use TraditionalRecordSyntax):" <+>
691 ppr r)
692
693 checkTyClHdr :: Bool -- True <=> class header
694 -- False <=> type header
695 -> LHsType RdrName
696 -> P (Located RdrName, -- the head symbol (type or class name)
697 [LHsType RdrName], -- parameters of head symbol
698 [AddAnn]) -- API Annotation for HsParTy when stripping parens
699 -- Well-formedness check and decomposition of type and class heads.
700 -- Decomposes T ty1 .. tyn into (T, [ty1, ..., tyn])
701 -- Int :*: Bool into (:*:, [Int, Bool])
702 -- returning the pieces
703 checkTyClHdr is_cls ty
704 = goL ty [] []
705 where
706 goL (L l ty) acc ann = go l ty acc ann
707
708 go l (HsTyVar (L _ tc)) acc ann
709 | isRdrTc tc = return (L l tc, acc, ann)
710 go _ (HsOpTy t1 ltc@(L _ tc) t2) acc ann
711 | isRdrTc tc = return (ltc, t1:t2:acc, ann)
712 go l (HsParTy ty) acc ann = goL ty acc (ann ++ mkParensApiAnn l)
713 go _ (HsAppTy t1 t2) acc ann = goL t1 (t2:acc) ann
714 go _ (HsAppsTy ts) acc ann
715 | Just (head, args) <- getAppsTyHead_maybe ts = goL head (args ++ acc) ann
716
717 go _ (HsAppsTy [HsAppInfix (L loc star)]) [] ann
718 | occNameFS (rdrNameOcc star) == fsLit "*"
719 = return (L loc (nameRdrName starKindTyConName), [], ann)
720 | occNameFS (rdrNameOcc star) == fsLit "★"
721 = return (L loc (nameRdrName unicodeStarKindTyConName), [], ann)
722
723 go l (HsTupleTy HsBoxedOrConstraintTuple ts) [] ann
724 = return (L l (nameRdrName tup_name), ts, ann)
725 where
726 arity = length ts
727 tup_name | is_cls = cTupleTyConName arity
728 | otherwise = getName (tupleTyCon Boxed arity)
729 -- See Note [Unit tuples] in HsTypes (TODO: is this still relevant?)
730 go l _ _ _
731 = parseErrorSDoc l (text "Malformed head of type or class declaration:"
732 <+> ppr ty)
733
734 checkContext :: LHsType RdrName -> P ([AddAnn],LHsContext RdrName)
735 checkContext (L l orig_t)
736 = check [] (L l orig_t)
737 where
738 check anns (L lp (HsTupleTy _ ts)) -- (Eq a, Ord b) shows up as a tuple type
739 = return (anns ++ mkParensApiAnn lp,L l ts) -- Ditto ()
740
741 -- don't let HsAppsTy get in the way
742 check anns (L _ (HsAppsTy [HsAppPrefix ty]))
743 = check anns ty
744
745 check anns (L lp1 (HsParTy ty))-- to be sure HsParTy doesn't get into the way
746 = check anns' ty
747 where anns' = if l == lp1 then anns
748 else (anns ++ mkParensApiAnn lp1)
749
750 check _anns _
751 = return ([],L l [L l orig_t]) -- no need for anns, returning original
752
753 -- -------------------------------------------------------------------------
754 -- Checking Patterns.
755
756 -- We parse patterns as expressions and check for valid patterns below,
757 -- converting the expression into a pattern at the same time.
758
759 checkPattern :: SDoc -> LHsExpr RdrName -> P (LPat RdrName)
760 checkPattern msg e = checkLPat msg e
761
762 checkPatterns :: SDoc -> [LHsExpr RdrName] -> P [LPat RdrName]
763 checkPatterns msg es = mapM (checkPattern msg) es
764
765 checkLPat :: SDoc -> LHsExpr RdrName -> P (LPat RdrName)
766 checkLPat msg e@(L l _) = checkPat msg l e []
767
768 checkPat :: SDoc -> SrcSpan -> LHsExpr RdrName -> [LPat RdrName]
769 -> P (LPat RdrName)
770 checkPat _ loc (L l (HsVar (L _ c))) args
771 | isRdrDataCon c = return (L loc (ConPatIn (L l c) (PrefixCon args)))
772 checkPat msg loc e args -- OK to let this happen even if bang-patterns
773 -- are not enabled, because there is no valid
774 -- non-bang-pattern parse of (C ! e)
775 | Just (e', args') <- splitBang e
776 = do { args'' <- checkPatterns msg args'
777 ; checkPat msg loc e' (args'' ++ args) }
778 checkPat msg loc (L _ (HsApp f e)) args
779 = do p <- checkLPat msg e
780 checkPat msg loc f (p : args)
781 checkPat msg loc (L _ e) []
782 = do p <- checkAPat msg loc e
783 return (L loc p)
784 checkPat msg loc e _
785 = patFail msg loc (unLoc e)
786
787 checkAPat :: SDoc -> SrcSpan -> HsExpr RdrName -> P (Pat RdrName)
788 checkAPat msg loc e0 = do
789 pState <- getPState
790 let dynflags = dflags pState
791 case e0 of
792 EWildPat -> return (WildPat placeHolderType)
793 HsVar x -> return (VarPat x)
794 HsLit l -> return (LitPat l)
795
796 -- Overloaded numeric patterns (e.g. f 0 x = x)
797 -- Negation is recorded separately, so that the literal is zero or +ve
798 -- NB. Negative *primitive* literals are already handled by the lexer
799 HsOverLit pos_lit -> return (mkNPat (L loc pos_lit) Nothing)
800 NegApp (L l (HsOverLit pos_lit)) _
801 -> return (mkNPat (L l pos_lit) (Just noSyntaxExpr))
802
803 SectionR (L lb (HsVar (L _ bang))) e -- (! x)
804 | bang == bang_RDR
805 -> do { bang_on <- extension bangPatEnabled
806 ; if bang_on then do { e' <- checkLPat msg e
807 ; addAnnotation loc AnnBang lb
808 ; return (BangPat e') }
809 else parseErrorSDoc loc (text "Illegal bang-pattern (use BangPatterns):" $$ ppr e0) }
810
811 ELazyPat e -> checkLPat msg e >>= (return . LazyPat)
812 EAsPat n e -> checkLPat msg e >>= (return . AsPat n)
813 -- view pattern is well-formed if the pattern is
814 EViewPat expr patE -> checkLPat msg patE >>=
815 (return . (\p -> ViewPat expr p placeHolderType))
816 ExprWithTySig e t -> do e <- checkLPat msg e
817 return (SigPatIn e t)
818
819 -- n+k patterns
820 OpApp (L nloc (HsVar (L _ n))) (L _ (HsVar (L _ plus))) _
821 (L lloc (HsOverLit lit@(OverLit {ol_val = HsIntegral {}})))
822 | xopt LangExt.NPlusKPatterns dynflags && (plus == plus_RDR)
823 -> return (mkNPlusKPat (L nloc n) (L lloc lit))
824
825 OpApp l op _fix r -> do l <- checkLPat msg l
826 r <- checkLPat msg r
827 case op of
828 L cl (HsVar (L _ c)) | isDataOcc (rdrNameOcc c)
829 -> return (ConPatIn (L cl c) (InfixCon l r))
830 _ -> patFail msg loc e0
831
832 HsPar e -> checkLPat msg e >>= (return . ParPat)
833 ExplicitList _ _ es -> do ps <- mapM (checkLPat msg) es
834 return (ListPat ps placeHolderType Nothing)
835 ExplicitPArr _ es -> do ps <- mapM (checkLPat msg) es
836 return (PArrPat ps placeHolderType)
837
838 ExplicitTuple es b
839 | all tupArgPresent es -> do ps <- mapM (checkLPat msg)
840 [e | L _ (Present e) <- es]
841 return (TuplePat ps b [])
842 | otherwise -> parseErrorSDoc loc (text "Illegal tuple section in pattern:" $$ ppr e0)
843
844 RecordCon { rcon_con_name = c, rcon_flds = HsRecFields fs dd }
845 -> do fs <- mapM (checkPatField msg) fs
846 return (ConPatIn c (RecCon (HsRecFields fs dd)))
847 HsSpliceE s | not (isTypedSplice s)
848 -> return (SplicePat s)
849 _ -> patFail msg loc e0
850
851 placeHolderPunRhs :: LHsExpr RdrName
852 -- The RHS of a punned record field will be filled in by the renamer
853 -- It's better not to make it an error, in case we want to print it when debugging
854 placeHolderPunRhs = noLoc (HsVar (noLoc pun_RDR))
855
856 plus_RDR, bang_RDR, pun_RDR :: RdrName
857 plus_RDR = mkUnqual varName (fsLit "+") -- Hack
858 bang_RDR = mkUnqual varName (fsLit "!") -- Hack
859 pun_RDR = mkUnqual varName (fsLit "pun-right-hand-side")
860
861 checkPatField :: SDoc -> LHsRecField RdrName (LHsExpr RdrName)
862 -> P (LHsRecField RdrName (LPat RdrName))
863 checkPatField msg (L l fld) = do p <- checkLPat msg (hsRecFieldArg fld)
864 return (L l (fld { hsRecFieldArg = p }))
865
866 patFail :: SDoc -> SrcSpan -> HsExpr RdrName -> P a
867 patFail msg loc e = parseErrorSDoc loc err
868 where err = text "Parse error in pattern:" <+> ppr e
869 $$ msg
870
871
872 ---------------------------------------------------------------------------
873 -- Check Equation Syntax
874
875 checkValDef :: SDoc
876 -> LHsExpr RdrName
877 -> Maybe (LHsType RdrName)
878 -> Located (a,GRHSs RdrName (LHsExpr RdrName))
879 -> P ([AddAnn],HsBind RdrName)
880
881 checkValDef msg lhs (Just sig) grhss
882 -- x :: ty = rhs parses as a *pattern* binding
883 = checkPatBind msg (L (combineLocs lhs sig)
884 (ExprWithTySig lhs (mkLHsSigWcType sig))) grhss
885
886 checkValDef msg lhs opt_sig g@(L l (_,grhss))
887 = do { mb_fun <- isFunLhs lhs
888 ; case mb_fun of
889 Just (fun, is_infix, pats, ann) ->
890 checkFunBind msg ann (getLoc lhs)
891 fun is_infix pats opt_sig (L l grhss)
892 Nothing -> checkPatBind msg lhs g }
893
894 checkFunBind :: SDoc
895 -> [AddAnn]
896 -> SrcSpan
897 -> Located RdrName
898 -> Bool
899 -> [LHsExpr RdrName]
900 -> Maybe (LHsType RdrName)
901 -> Located (GRHSs RdrName (LHsExpr RdrName))
902 -> P ([AddAnn],HsBind RdrName)
903 checkFunBind msg ann lhs_loc fun is_infix pats opt_sig (L rhs_span grhss)
904 = do ps <- checkPatterns msg pats
905 let match_span = combineSrcSpans lhs_loc rhs_span
906 -- Add back the annotations stripped from any HsPar values in the lhs
907 -- mapM_ (\a -> a match_span) ann
908 return (ann, makeFunBind fun
909 [L match_span (Match { m_fixity = FunBindMatch fun is_infix
910 , m_pats = ps
911 , m_type = opt_sig
912 , m_grhss = grhss })])
913 -- The span of the match covers the entire equation.
914 -- That isn't quite right, but it'll do for now.
915
916 makeFunBind :: Located RdrName -> [LMatch RdrName (LHsExpr RdrName)]
917 -> HsBind RdrName
918 -- Like HsUtils.mkFunBind, but we need to be able to set the fixity too
919 makeFunBind fn ms
920 = FunBind { fun_id = fn,
921 fun_matches = mkMatchGroup FromSource ms,
922 fun_co_fn = idHsWrapper,
923 bind_fvs = placeHolderNames,
924 fun_tick = [] }
925
926 checkPatBind :: SDoc
927 -> LHsExpr RdrName
928 -> Located (a,GRHSs RdrName (LHsExpr RdrName))
929 -> P ([AddAnn],HsBind RdrName)
930 checkPatBind msg lhs (L _ (_,grhss))
931 = do { lhs <- checkPattern msg lhs
932 ; return ([],PatBind lhs grhss placeHolderType placeHolderNames
933 ([],[])) }
934
935 checkValSigLhs :: LHsExpr RdrName -> P (Located RdrName)
936 checkValSigLhs (L _ (HsVar lrdr@(L _ v)))
937 | isUnqual v
938 , not (isDataOcc (rdrNameOcc v))
939 = return lrdr
940
941 checkValSigLhs lhs@(L l _)
942 = parseErrorSDoc l ((text "Invalid type signature:" <+>
943 ppr lhs <+> text ":: ...")
944 $$ text hint)
945 where
946 hint | foreign_RDR `looks_like` lhs
947 = "Perhaps you meant to use ForeignFunctionInterface?"
948 | default_RDR `looks_like` lhs
949 = "Perhaps you meant to use DefaultSignatures?"
950 | pattern_RDR `looks_like` lhs
951 = "Perhaps you meant to use PatternSynonyms?"
952 | otherwise
953 = "Should be of form <variable> :: <type>"
954
955 -- A common error is to forget the ForeignFunctionInterface flag
956 -- so check for that, and suggest. cf Trac #3805
957 -- Sadly 'foreign import' still barfs 'parse error' because 'import' is a keyword
958 looks_like s (L _ (HsVar (L _ v))) = v == s
959 looks_like s (L _ (HsApp lhs _)) = looks_like s lhs
960 looks_like _ _ = False
961
962 foreign_RDR = mkUnqual varName (fsLit "foreign")
963 default_RDR = mkUnqual varName (fsLit "default")
964 pattern_RDR = mkUnqual varName (fsLit "pattern")
965
966
967 checkDoAndIfThenElse :: LHsExpr RdrName
968 -> Bool
969 -> LHsExpr RdrName
970 -> Bool
971 -> LHsExpr RdrName
972 -> P ()
973 checkDoAndIfThenElse guardExpr semiThen thenExpr semiElse elseExpr
974 | semiThen || semiElse
975 = do pState <- getPState
976 unless (xopt LangExt.DoAndIfThenElse (dflags pState)) $ do
977 parseErrorSDoc (combineLocs guardExpr elseExpr)
978 (text "Unexpected semi-colons in conditional:"
979 $$ nest 4 expr
980 $$ text "Perhaps you meant to use DoAndIfThenElse?")
981 | otherwise = return ()
982 where pprOptSemi True = semi
983 pprOptSemi False = empty
984 expr = text "if" <+> ppr guardExpr <> pprOptSemi semiThen <+>
985 text "then" <+> ppr thenExpr <> pprOptSemi semiElse <+>
986 text "else" <+> ppr elseExpr
987
988
989 -- The parser left-associates, so there should
990 -- not be any OpApps inside the e's
991 splitBang :: LHsExpr RdrName -> Maybe (LHsExpr RdrName, [LHsExpr RdrName])
992 -- Splits (f ! g a b) into (f, [(! g), a, b])
993 splitBang (L _ (OpApp l_arg bang@(L _ (HsVar (L _ op))) _ r_arg))
994 | op == bang_RDR = Just (l_arg, L l' (SectionR bang arg1) : argns)
995 where
996 l' = combineLocs bang arg1
997 (arg1,argns) = split_bang r_arg []
998 split_bang (L _ (HsApp f e)) es = split_bang f (e:es)
999 split_bang e es = (e,es)
1000 splitBang _ = Nothing
1001
1002 isFunLhs :: LHsExpr RdrName
1003 -> P (Maybe (Located RdrName, Bool, [LHsExpr RdrName],[AddAnn]))
1004 -- A variable binding is parsed as a FunBind.
1005 -- Just (fun, is_infix, arg_pats) if e is a function LHS
1006 --
1007 -- The whole LHS is parsed as a single expression.
1008 -- Any infix operators on the LHS will parse left-associatively
1009 -- E.g. f !x y !z
1010 -- will parse (rather strangely) as
1011 -- (f ! x y) ! z
1012 -- It's up to isFunLhs to sort out the mess
1013 --
1014 -- a .!. !b
1015
1016 isFunLhs e = go e [] []
1017 where
1018 go (L loc (HsVar (L _ f))) es ann
1019 | not (isRdrDataCon f) = return (Just (L loc f, False, es, ann))
1020 go (L _ (HsApp f e)) es ann = go f (e:es) ann
1021 go (L l (HsPar e)) es@(_:_) ann = go e es (ann ++ mkParensApiAnn l)
1022
1023 -- For infix function defns, there should be only one infix *function*
1024 -- (though there may be infix *datacons* involved too). So we don't
1025 -- need fixity info to figure out which function is being defined.
1026 -- a `K1` b `op` c `K2` d
1027 -- must parse as
1028 -- (a `K1` b) `op` (c `K2` d)
1029 -- The renamer checks later that the precedences would yield such a parse.
1030 --
1031 -- There is a complication to deal with bang patterns.
1032 --
1033 -- ToDo: what about this?
1034 -- x + 1 `op` y = ...
1035
1036 go e@(L loc (OpApp l (L loc' (HsVar (L _ op))) fix r)) es ann
1037 | Just (e',es') <- splitBang e
1038 = do { bang_on <- extension bangPatEnabled
1039 ; if bang_on then go e' (es' ++ es) ann
1040 else return (Just (L loc' op, True, (l:r:es), ann)) }
1041 -- No bangs; behave just like the next case
1042 | not (isRdrDataCon op) -- We have found the function!
1043 = return (Just (L loc' op, True, (l:r:es), ann))
1044 | otherwise -- Infix data con; keep going
1045 = do { mb_l <- go l es ann
1046 ; case mb_l of
1047 Just (op', True, j : k : es', ann')
1048 -> return (Just (op', True, j : op_app : es', ann'))
1049 where
1050 op_app = L loc (OpApp k (L loc' (HsVar (L loc' op))) fix r)
1051 _ -> return Nothing }
1052 go _ _ _ = return Nothing
1053
1054
1055 -- | Transform btype_no_ops with strict_mark's into HsEqTy's
1056 -- (((~a) ~b) c) ~d ==> ((~a) ~ (b c)) ~ d
1057 splitTilde :: LHsType RdrName -> LHsType RdrName
1058 splitTilde t = go t
1059 where go (L loc (HsAppTy t1 t2))
1060 | L _ (HsBangTy (HsSrcBang Nothing NoSrcUnpack SrcLazy) t2') <- t2
1061 = L loc (HsEqTy (go t1) t2')
1062 | otherwise
1063 = case go t1 of
1064 (L _ (HsEqTy tl tr)) ->
1065 L loc (HsEqTy tl (L (combineLocs tr t2) (HsAppTy tr t2)))
1066 t -> L loc (HsAppTy t t2)
1067
1068 go t = t
1069
1070 -- | Transform tyapps with strict_marks into uses of twiddle
1071 -- [~a, ~b, c, ~d] ==> (~a) ~ b c ~ d
1072 splitTildeApps :: [HsAppType RdrName] -> [HsAppType RdrName]
1073 splitTildeApps [] = []
1074 splitTildeApps (t : rest) = t : concatMap go rest
1075 where go (HsAppPrefix
1076 (L loc (HsBangTy
1077 (HsSrcBang Nothing NoSrcUnpack SrcLazy)
1078 ty)))
1079 = [HsAppInfix (L tilde_loc eqTyCon_RDR), HsAppPrefix ty]
1080 where
1081 tilde_loc = srcSpanFirstCharacter loc
1082
1083 go t = [t]
1084
1085
1086
1087 ---------------------------------------------------------------------------
1088 -- Check for monad comprehensions
1089 --
1090 -- If the flag MonadComprehensions is set, return a `MonadComp' context,
1091 -- otherwise use the usual `ListComp' context
1092
1093 checkMonadComp :: P (HsStmtContext Name)
1094 checkMonadComp = do
1095 pState <- getPState
1096 return $ if xopt LangExt.MonadComprehensions (dflags pState)
1097 then MonadComp
1098 else ListComp
1099
1100 -- -------------------------------------------------------------------------
1101 -- Checking arrow syntax.
1102
1103 -- We parse arrow syntax as expressions and check for valid syntax below,
1104 -- converting the expression into a pattern at the same time.
1105
1106 checkCommand :: LHsExpr RdrName -> P (LHsCmd RdrName)
1107 checkCommand lc = locMap checkCmd lc
1108
1109 locMap :: (SrcSpan -> a -> P b) -> Located a -> P (Located b)
1110 locMap f (L l a) = f l a >>= (\b -> return $ L l b)
1111
1112 checkCmd :: SrcSpan -> HsExpr RdrName -> P (HsCmd RdrName)
1113 checkCmd _ (HsArrApp e1 e2 ptt haat b) =
1114 return $ HsCmdArrApp e1 e2 ptt haat b
1115 checkCmd _ (HsArrForm e mf args) =
1116 return $ HsCmdArrForm e mf args
1117 checkCmd _ (HsApp e1 e2) =
1118 checkCommand e1 >>= (\c -> return $ HsCmdApp c e2)
1119 checkCmd _ (HsLam mg) =
1120 checkCmdMatchGroup mg >>= (\mg' -> return $ HsCmdLam mg')
1121 checkCmd _ (HsPar e) =
1122 checkCommand e >>= (\c -> return $ HsCmdPar c)
1123 checkCmd _ (HsCase e mg) =
1124 checkCmdMatchGroup mg >>= (\mg' -> return $ HsCmdCase e mg')
1125 checkCmd _ (HsIf cf ep et ee) = do
1126 pt <- checkCommand et
1127 pe <- checkCommand ee
1128 return $ HsCmdIf cf ep pt pe
1129 checkCmd _ (HsLet lb e) =
1130 checkCommand e >>= (\c -> return $ HsCmdLet lb c)
1131 checkCmd _ (HsDo DoExpr (L l stmts) ty) =
1132 mapM checkCmdLStmt stmts >>= (\ss -> return $ HsCmdDo (L l ss) ty)
1133
1134 checkCmd _ (OpApp eLeft op _fixity eRight) = do
1135 -- OpApp becomes a HsCmdArrForm with a (Just fixity) in it
1136 c1 <- checkCommand eLeft
1137 c2 <- checkCommand eRight
1138 let arg1 = L (getLoc c1) $ HsCmdTop c1 placeHolderType placeHolderType []
1139 arg2 = L (getLoc c2) $ HsCmdTop c2 placeHolderType placeHolderType []
1140 return $ HsCmdArrForm op Nothing [arg1, arg2]
1141
1142 checkCmd l e = cmdFail l e
1143
1144 checkCmdLStmt :: ExprLStmt RdrName -> P (CmdLStmt RdrName)
1145 checkCmdLStmt = locMap checkCmdStmt
1146
1147 checkCmdStmt :: SrcSpan -> ExprStmt RdrName -> P (CmdStmt RdrName)
1148 checkCmdStmt _ (LastStmt e s r) =
1149 checkCommand e >>= (\c -> return $ LastStmt c s r)
1150 checkCmdStmt _ (BindStmt pat e b f) =
1151 checkCommand e >>= (\c -> return $ BindStmt pat c b f)
1152 checkCmdStmt _ (BodyStmt e t g ty) =
1153 checkCommand e >>= (\c -> return $ BodyStmt c t g ty)
1154 checkCmdStmt _ (LetStmt bnds) = return $ LetStmt bnds
1155 checkCmdStmt _ stmt@(RecStmt { recS_stmts = stmts }) = do
1156 ss <- mapM checkCmdLStmt stmts
1157 return $ stmt { recS_stmts = ss }
1158 checkCmdStmt l stmt = cmdStmtFail l stmt
1159
1160 checkCmdMatchGroup :: MatchGroup RdrName (LHsExpr RdrName) -> P (MatchGroup RdrName (LHsCmd RdrName))
1161 checkCmdMatchGroup mg@(MG { mg_alts = L l ms }) = do
1162 ms' <- mapM (locMap $ const convert) ms
1163 return $ mg { mg_alts = L l ms' }
1164 where convert (Match mf pat mty grhss) = do
1165 grhss' <- checkCmdGRHSs grhss
1166 return $ Match mf pat mty grhss'
1167
1168 checkCmdGRHSs :: GRHSs RdrName (LHsExpr RdrName) -> P (GRHSs RdrName (LHsCmd RdrName))
1169 checkCmdGRHSs (GRHSs grhss binds) = do
1170 grhss' <- mapM checkCmdGRHS grhss
1171 return $ GRHSs grhss' binds
1172
1173 checkCmdGRHS :: LGRHS RdrName (LHsExpr RdrName) -> P (LGRHS RdrName (LHsCmd RdrName))
1174 checkCmdGRHS = locMap $ const convert
1175 where
1176 convert (GRHS stmts e) = do
1177 c <- checkCommand e
1178 -- cmdStmts <- mapM checkCmdLStmt stmts
1179 return $ GRHS {- cmdStmts -} stmts c
1180
1181
1182 cmdFail :: SrcSpan -> HsExpr RdrName -> P a
1183 cmdFail loc e = parseErrorSDoc loc (text "Parse error in command:" <+> ppr e)
1184 cmdStmtFail :: SrcSpan -> Stmt RdrName (LHsExpr RdrName) -> P a
1185 cmdStmtFail loc e = parseErrorSDoc loc
1186 (text "Parse error in command statement:" <+> ppr e)
1187
1188 ---------------------------------------------------------------------------
1189 -- Miscellaneous utilities
1190
1191 checkPrecP :: Located Int -> P (Located Int)
1192 checkPrecP (L l i)
1193 | 0 <= i && i <= maxPrecedence = return (L l i)
1194 | otherwise
1195 = parseErrorSDoc l (text ("Precedence out of range: " ++ show i))
1196
1197 mkRecConstrOrUpdate
1198 :: LHsExpr RdrName
1199 -> SrcSpan
1200 -> ([LHsRecField RdrName (LHsExpr RdrName)], Bool)
1201 -> P (HsExpr RdrName)
1202
1203 mkRecConstrOrUpdate (L l (HsVar (L _ c))) _ (fs,dd)
1204 | isRdrDataCon c
1205 = return (mkRdrRecordCon (L l c) (mk_rec_fields fs dd))
1206 mkRecConstrOrUpdate exp@(L l _) _ (fs,dd)
1207 | dd = parseErrorSDoc l (text "You cannot use `..' in a record update")
1208 | otherwise = return (mkRdrRecordUpd exp (map (fmap mk_rec_upd_field) fs))
1209
1210 mkRdrRecordUpd :: LHsExpr RdrName -> [LHsRecUpdField RdrName] -> HsExpr RdrName
1211 mkRdrRecordUpd exp flds
1212 = RecordUpd { rupd_expr = exp
1213 , rupd_flds = flds
1214 , rupd_cons = PlaceHolder, rupd_in_tys = PlaceHolder
1215 , rupd_out_tys = PlaceHolder, rupd_wrap = PlaceHolder }
1216
1217 mkRdrRecordCon :: Located RdrName -> HsRecordBinds RdrName -> HsExpr RdrName
1218 mkRdrRecordCon con flds
1219 = RecordCon { rcon_con_name = con, rcon_flds = flds
1220 , rcon_con_expr = noPostTcExpr, rcon_con_like = PlaceHolder }
1221
1222 mk_rec_fields :: [LHsRecField id arg] -> Bool -> HsRecFields id arg
1223 mk_rec_fields fs False = HsRecFields { rec_flds = fs, rec_dotdot = Nothing }
1224 mk_rec_fields fs True = HsRecFields { rec_flds = fs, rec_dotdot = Just (length fs) }
1225
1226 mk_rec_upd_field :: HsRecField RdrName (LHsExpr RdrName) -> HsRecUpdField RdrName
1227 mk_rec_upd_field (HsRecField (L loc (FieldOcc rdr _)) arg pun)
1228 = HsRecField (L loc (Unambiguous rdr PlaceHolder)) arg pun
1229
1230 mkInlinePragma :: String -> (InlineSpec, RuleMatchInfo) -> Maybe Activation
1231 -> InlinePragma
1232 -- The (Maybe Activation) is because the user can omit
1233 -- the activation spec (and usually does)
1234 mkInlinePragma src (inl, match_info) mb_act
1235 = InlinePragma { inl_src = src -- Note [Pragma source text] in BasicTypes
1236 , inl_inline = inl
1237 , inl_sat = Nothing
1238 , inl_act = act
1239 , inl_rule = match_info }
1240 where
1241 act = case mb_act of
1242 Just act -> act
1243 Nothing -> -- No phase specified
1244 case inl of
1245 NoInline -> NeverActive
1246 _other -> AlwaysActive
1247
1248 -----------------------------------------------------------------------------
1249 -- utilities for foreign declarations
1250
1251 -- construct a foreign import declaration
1252 --
1253 mkImport :: Located CCallConv
1254 -> Located Safety
1255 -> (Located StringLiteral, Located RdrName, LHsSigType RdrName)
1256 -> P (HsDecl RdrName)
1257 mkImport (L lc cconv) (L ls safety) (L loc (StringLiteral esrc entity), v, ty)
1258 | cconv == PrimCallConv = do
1259 let funcTarget = CFunction (StaticTarget esrc entity Nothing True)
1260 importSpec = CImport (L lc PrimCallConv) (L ls safety) Nothing funcTarget
1261 (L loc (unpackFS entity))
1262 return (ForD (ForeignImport { fd_name = v, fd_sig_ty = ty
1263 , fd_co = noForeignImportCoercionYet
1264 , fd_fi = importSpec }))
1265 | cconv == JavaScriptCallConv = do
1266 let funcTarget = CFunction (StaticTarget esrc entity Nothing True)
1267 importSpec = CImport (L lc JavaScriptCallConv) (L ls safety) Nothing
1268 funcTarget (L loc (unpackFS entity))
1269 return (ForD (ForeignImport { fd_name = v, fd_sig_ty = ty
1270 , fd_co = noForeignImportCoercionYet
1271 , fd_fi = importSpec }))
1272 | otherwise = do
1273 case parseCImport (L lc cconv) (L ls safety) (mkExtName (unLoc v))
1274 (unpackFS entity) (L loc (unpackFS entity)) of
1275 Nothing -> parseErrorSDoc loc (text "Malformed entity string")
1276 Just importSpec -> return (ForD (ForeignImport { fd_name = v, fd_sig_ty = ty
1277 , fd_co = noForeignImportCoercionYet
1278 , fd_fi = importSpec }))
1279
1280 -- the string "foo" is ambigous: either a header or a C identifier. The
1281 -- C identifier case comes first in the alternatives below, so we pick
1282 -- that one.
1283 parseCImport :: Located CCallConv -> Located Safety -> FastString -> String
1284 -> Located SourceText
1285 -> Maybe ForeignImport
1286 parseCImport cconv safety nm str sourceText =
1287 listToMaybe $ map fst $ filter (null.snd) $
1288 readP_to_S parse str
1289 where
1290 parse = do
1291 skipSpaces
1292 r <- choice [
1293 string "dynamic" >> return (mk Nothing (CFunction DynamicTarget)),
1294 string "wrapper" >> return (mk Nothing CWrapper),
1295 do optional (token "static" >> skipSpaces)
1296 ((mk Nothing <$> cimp nm) +++
1297 (do h <- munch1 hdr_char
1298 skipSpaces
1299 mk (Just (Header h (mkFastString h))) <$> cimp nm))
1300 ]
1301 skipSpaces
1302 return r
1303
1304 token str = do _ <- string str
1305 toks <- look
1306 case toks of
1307 c : _
1308 | id_char c -> pfail
1309 _ -> return ()
1310
1311 mk h n = CImport cconv safety h n sourceText
1312
1313 hdr_char c = not (isSpace c) -- header files are filenames, which can contain
1314 -- pretty much any char (depending on the platform),
1315 -- so just accept any non-space character
1316 id_first_char c = isAlpha c || c == '_'
1317 id_char c = isAlphaNum c || c == '_'
1318
1319 cimp nm = (ReadP.char '&' >> skipSpaces >> CLabel <$> cid)
1320 +++ (do isFun <- case cconv of
1321 L _ CApiConv ->
1322 option True
1323 (do token "value"
1324 skipSpaces
1325 return False)
1326 _ -> return True
1327 cid' <- cid
1328 return (CFunction (StaticTarget (unpackFS cid') cid'
1329 Nothing isFun)))
1330 where
1331 cid = return nm +++
1332 (do c <- satisfy id_first_char
1333 cs <- many (satisfy id_char)
1334 return (mkFastString (c:cs)))
1335
1336
1337 -- construct a foreign export declaration
1338 --
1339 mkExport :: Located CCallConv
1340 -> (Located StringLiteral, Located RdrName, LHsSigType RdrName)
1341 -> P (HsDecl RdrName)
1342 mkExport (L lc cconv) (L le (StringLiteral esrc entity), v, ty)
1343 = return $ ForD $
1344 ForeignExport { fd_name = v, fd_sig_ty = ty
1345 , fd_co = noForeignExportCoercionYet
1346 , fd_fe = CExport (L lc (CExportStatic esrc entity' cconv))
1347 (L le (unpackFS entity)) }
1348 where
1349 entity' | nullFS entity = mkExtName (unLoc v)
1350 | otherwise = entity
1351
1352 -- Supplying the ext_name in a foreign decl is optional; if it
1353 -- isn't there, the Haskell name is assumed. Note that no transformation
1354 -- of the Haskell name is then performed, so if you foreign export (++),
1355 -- it's external name will be "++". Too bad; it's important because we don't
1356 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
1357 --
1358 mkExtName :: RdrName -> CLabelString
1359 mkExtName rdrNm = mkFastString (occNameString (rdrNameOcc rdrNm))
1360
1361 --------------------------------------------------------------------------------
1362 -- Help with module system imports/exports
1363
1364 data ImpExpSubSpec = ImpExpAbs
1365 | ImpExpAll
1366 | ImpExpList [Located RdrName]
1367 | ImpExpAllWith [Located (Maybe RdrName)]
1368
1369 mkModuleImpExp :: Located RdrName -> ImpExpSubSpec -> P (IE RdrName)
1370 mkModuleImpExp n@(L l name) subs =
1371 case subs of
1372 ImpExpAbs
1373 | isVarNameSpace (rdrNameSpace name) -> return $ IEVar n
1374 | otherwise -> return $ IEThingAbs (L l name)
1375 ImpExpAll -> return $ IEThingAll (L l name)
1376 ImpExpList xs ->
1377 return $ IEThingWith (L l name) NoIEWildcard xs []
1378 ImpExpAllWith xs ->
1379 do allowed <- extension patternSynonymsEnabled
1380 if allowed
1381 then
1382 let withs = map unLoc xs
1383 pos = maybe NoIEWildcard IEWildcard
1384 (findIndex isNothing withs)
1385 ies = [L l n | L l (Just n) <- xs]
1386 in return (IEThingWith (L l name) pos ies [])
1387 else parseErrorSDoc l
1388 (text "Illegal export form (use PatternSynonyms to enable)")
1389
1390 mkTypeImpExp :: Located RdrName -- TcCls or Var name space
1391 -> P (Located RdrName)
1392 mkTypeImpExp name =
1393 do allowed <- extension explicitNamespacesEnabled
1394 if allowed
1395 then return (fmap (`setRdrNameSpace` tcClsName) name)
1396 else parseErrorSDoc (getLoc name)
1397 (text "Illegal keyword 'type' (use ExplicitNamespaces to enable)")
1398
1399 checkImportSpec :: Located [LIE RdrName] -> P (Located [LIE RdrName])
1400 checkImportSpec ie@(L _ specs) =
1401 case [l | (L l (IEThingWith _ (IEWildcard _) _ _)) <- specs] of
1402 [] -> return ie
1403 (l:_) -> importSpecError l
1404 where
1405 importSpecError l =
1406 parseErrorSDoc l
1407 (text "Illegal import form, this syntax can only be used to bundle"
1408 $+$ text "pattern synonyms with types in module exports.")
1409
1410 -- In the correct order
1411 mkImpExpSubSpec :: [Located (Maybe RdrName)] -> P ([AddAnn], ImpExpSubSpec)
1412 mkImpExpSubSpec [] = return ([], ImpExpList [])
1413 mkImpExpSubSpec [L l Nothing] =
1414 return ([\s -> addAnnotation l AnnDotdot s], ImpExpAll)
1415 mkImpExpSubSpec xs =
1416 if (any (isNothing . unLoc) xs)
1417 then return $ ([], ImpExpAllWith xs)
1418 else return $ ([], ImpExpList ([L l x | L l (Just x) <- xs]))
1419
1420
1421 -----------------------------------------------------------------------------
1422 -- Misc utils
1423
1424 parseErrorSDoc :: SrcSpan -> SDoc -> P a
1425 parseErrorSDoc span s = failSpanMsgP span s