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