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