Check if both branches of an Cmm if have the same target.
[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 {-# LANGUAGE TypeFamilies #-}
10 {-# LANGUAGE MagicHash #-}
11
12 module RdrHsSyn (
13 mkHsOpApp,
14 mkHsIntegral, mkHsFractional, mkHsIsString,
15 mkHsDo, mkSpliceDecl,
16 mkRoleAnnotDecl,
17 mkClassDecl,
18 mkTyData, mkDataFamInst,
19 mkTySynonym, mkTyFamInstEqn,
20 mkTyFamInst,
21 mkFamDecl, mkLHsSigType,
22 splitCon, mkInlinePragma,
23 mkPatSynMatchGroup,
24 mkRecConstrOrUpdate, -- HsExp -> [HsFieldUpdate] -> P HsExp
25 mkTyClD, mkInstD,
26 mkRdrRecordCon, mkRdrRecordUpd,
27 setRdrNameSpace,
28
29 cvBindGroup,
30 cvBindsAndSigs,
31 cvTopDecls,
32 placeHolderPunRhs,
33
34 -- Stuff to do with Foreign declarations
35 mkImport,
36 parseCImport,
37 mkExport,
38 mkExtName, -- RdrName -> CLabelString
39 mkGadtDecl, -- [Located RdrName] -> LHsType RdrName -> ConDecl RdrName
40 mkConDeclH98,
41 mkATDefault,
42
43 -- Bunch of functions in the parser monad for
44 -- checking and constructing values
45 checkBlockArguments,
46 checkPrecP, -- Int -> P Int
47 checkContext, -- HsType -> P HsContext
48 checkInfixConstr,
49 checkPattern, -- HsExp -> P HsPat
50 bang_RDR,
51 checkPatterns, -- SrcLoc -> [HsExp] -> P [HsPat]
52 checkMonadComp, -- P (HsStmtContext RdrName)
53 checkCommand, -- LHsExpr RdrName -> P (LHsCmd RdrName)
54 checkValDef, -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
55 checkValSigLhs,
56 checkDoAndIfThenElse,
57 checkRecordSyntax,
58 checkEmptyGADTs,
59 parseErrorSDoc, hintBangPat,
60 splitTilde, splitTildeApps,
61
62 -- Help with processing exports
63 ImpExpSubSpec(..),
64 ImpExpQcSpec(..),
65 mkModuleImpExp,
66 mkTypeImpExp,
67 mkImpExpSubSpec,
68 checkImportSpec,
69
70 SumOrTuple (..), mkSumOrTuple
71
72 ) where
73
74 import GhcPrelude
75 import HsSyn -- Lots of it
76 import Class ( FunDep )
77 import TyCon ( TyCon, isTupleTyCon, tyConSingleDataCon_maybe )
78 import DataCon ( DataCon, dataConTyCon )
79 import ConLike ( ConLike(..) )
80 import CoAxiom ( Role, fsFromRole )
81 import RdrName
82 import Name
83 import BasicTypes
84 import TcEvidence ( idHsWrapper )
85 import Lexer
86 import Lexeme ( isLexCon )
87 import Type ( TyThing(..) )
88 import TysWiredIn ( cTupleTyConName, tupleTyCon, tupleDataCon,
89 nilDataConName, nilDataConKey,
90 listTyConName, listTyConKey,
91 starKindTyConName, unicodeStarKindTyConName )
92 import ForeignCall
93 import PrelNames ( forall_tv_RDR, eqTyCon_RDR, allNameStrings )
94 import SrcLoc
95 import Unique ( hasKey )
96 import OrdList ( OrdList, fromOL )
97 import Bag ( emptyBag, consBag )
98 import Outputable
99 import FastString
100 import Maybes
101 import Util
102 import ApiAnnotation
103 import HsExtension ( noExt )
104 import Data.List
105 import qualified GHC.LanguageExtensions as LangExt
106 import MonadUtils
107
108 import Control.Monad
109 import Text.ParserCombinators.ReadP as ReadP
110 import Data.Char
111
112 import Data.Data ( dataTypeOf, fromConstr, dataTypeConstrs )
113
114 #include "HsVersions.h"
115
116
117 {- **********************************************************************
118
119 Construction functions for Rdr stuff
120
121 ********************************************************************* -}
122
123 -- | mkClassDecl builds a RdrClassDecl, filling in the names for tycon and
124 -- datacon by deriving them from the name of the class. We fill in the names
125 -- for the tycon and datacon corresponding to the class, by deriving them
126 -- from the name of the class itself. This saves recording the names in the
127 -- interface file (which would be equally good).
128
129 -- Similarly for mkConDecl, mkClassOpSig and default-method names.
130
131 -- *** See Note [The Naming story] in HsDecls ****
132
133 mkTyClD :: LTyClDecl (GhcPass p) -> LHsDecl (GhcPass p)
134 mkTyClD (L loc d) = L loc (TyClD noExt d)
135
136 mkInstD :: LInstDecl (GhcPass p) -> LHsDecl (GhcPass p)
137 mkInstD (L loc d) = L loc (InstD noExt d)
138
139 mkClassDecl :: SrcSpan
140 -> Located (Maybe (LHsContext GhcPs), LHsType GhcPs)
141 -> Located (a,[Located (FunDep (Located RdrName))])
142 -> OrdList (LHsDecl GhcPs)
143 -> P (LTyClDecl GhcPs)
144
145 mkClassDecl loc (L _ (mcxt, tycl_hdr)) fds where_cls
146 = do { (binds, sigs, ats, at_insts, _, docs) <- cvBindsAndSigs where_cls
147 ; let cxt = fromMaybe (noLoc []) mcxt
148 ; (cls, tparams, fixity, ann) <- checkTyClHdr True tycl_hdr
149 ; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
150 ; tyvars <- checkTyVarsP (text "class") whereDots cls tparams
151 ; at_defs <- mapM (eitherToP . mkATDefault) at_insts
152 ; return (L loc (ClassDecl { tcdCExt = noExt, tcdCtxt = cxt
153 , tcdLName = cls, tcdTyVars = tyvars
154 , tcdFixity = fixity
155 , tcdFDs = snd (unLoc fds)
156 , tcdSigs = mkClassOpSigs sigs
157 , tcdMeths = binds
158 , tcdATs = ats, tcdATDefs = at_defs
159 , tcdDocs = docs })) }
160
161 mkATDefault :: LTyFamInstDecl GhcPs
162 -> Either (SrcSpan, SDoc) (LTyFamDefltEqn GhcPs)
163 -- Take a type-family instance declaration and turn it into
164 -- a type-family default equation for a class declaration
165 -- We parse things as the former and use this function to convert to the latter
166 --
167 -- We use the Either monad because this also called
168 -- from Convert.hs
169 mkATDefault (L loc (TyFamInstDecl { tfid_eqn = HsIB { hsib_body = e }}))
170 | FamEqn { feqn_tycon = tc, feqn_pats = pats, feqn_fixity = fixity
171 , feqn_rhs = rhs } <- e
172 = do { tvs <- checkTyVars (text "default") equalsDots tc pats
173 ; return (L loc (FamEqn { feqn_ext = noExt
174 , feqn_tycon = tc
175 , feqn_pats = tvs
176 , feqn_fixity = fixity
177 , feqn_rhs = rhs })) }
178 mkATDefault (L _ (TyFamInstDecl (HsIB _ (XFamEqn _)))) = panic "mkATDefault"
179 mkATDefault (L _ (TyFamInstDecl (XHsImplicitBndrs _))) = panic "mkATDefault"
180
181 mkTyData :: SrcSpan
182 -> NewOrData
183 -> Maybe (Located CType)
184 -> Located (Maybe (LHsContext GhcPs), LHsType GhcPs)
185 -> Maybe (LHsKind GhcPs)
186 -> [LConDecl GhcPs]
187 -> HsDeriving GhcPs
188 -> P (LTyClDecl GhcPs)
189 mkTyData loc new_or_data cType (L _ (mcxt, tycl_hdr)) ksig data_cons maybe_deriv
190 = do { (tc, tparams, fixity, ann) <- checkTyClHdr False tycl_hdr
191 ; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
192 ; tyvars <- checkTyVarsP (ppr new_or_data) equalsDots tc tparams
193 ; defn <- mkDataDefn new_or_data cType mcxt ksig data_cons maybe_deriv
194 ; return (L loc (DataDecl { tcdDExt = noExt,
195 tcdLName = tc, tcdTyVars = tyvars,
196 tcdFixity = fixity,
197 tcdDataDefn = defn })) }
198
199 mkDataDefn :: NewOrData
200 -> Maybe (Located CType)
201 -> Maybe (LHsContext GhcPs)
202 -> Maybe (LHsKind GhcPs)
203 -> [LConDecl GhcPs]
204 -> HsDeriving GhcPs
205 -> P (HsDataDefn GhcPs)
206 mkDataDefn new_or_data cType mcxt ksig data_cons maybe_deriv
207 = do { checkDatatypeContext mcxt
208 ; let cxt = fromMaybe (noLoc []) mcxt
209 ; return (HsDataDefn { dd_ext = noExt
210 , dd_ND = new_or_data, dd_cType = cType
211 , dd_ctxt = cxt
212 , dd_cons = data_cons
213 , dd_kindSig = ksig
214 , dd_derivs = maybe_deriv }) }
215
216
217 mkTySynonym :: SrcSpan
218 -> LHsType GhcPs -- LHS
219 -> LHsType GhcPs -- RHS
220 -> P (LTyClDecl GhcPs)
221 mkTySynonym loc lhs rhs
222 = do { (tc, tparams, fixity, ann) <- checkTyClHdr False lhs
223 ; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
224 ; tyvars <- checkTyVarsP (text "type") equalsDots tc tparams
225 ; return (L loc (SynDecl { tcdSExt = noExt
226 , tcdLName = tc, tcdTyVars = tyvars
227 , tcdFixity = fixity
228 , tcdRhs = rhs })) }
229
230 mkTyFamInstEqn :: LHsType GhcPs
231 -> LHsType GhcPs
232 -> P (TyFamInstEqn GhcPs,[AddAnn])
233 mkTyFamInstEqn lhs rhs
234 = do { (tc, tparams, fixity, ann) <- checkTyClHdr False lhs
235 ; return (mkHsImplicitBndrs
236 (FamEqn { feqn_ext = noExt
237 , feqn_tycon = tc
238 , feqn_pats = tparams
239 , feqn_fixity = fixity
240 , feqn_rhs = rhs }),
241 ann) }
242
243 mkDataFamInst :: SrcSpan
244 -> NewOrData
245 -> Maybe (Located CType)
246 -> Located (Maybe (LHsContext GhcPs), LHsType GhcPs)
247 -> Maybe (LHsKind GhcPs)
248 -> [LConDecl GhcPs]
249 -> HsDeriving GhcPs
250 -> P (LInstDecl GhcPs)
251 mkDataFamInst loc new_or_data cType (L _ (mcxt, tycl_hdr)) ksig data_cons maybe_deriv
252 = do { (tc, tparams, fixity, ann) <- checkTyClHdr False tycl_hdr
253 ; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
254 ; defn <- mkDataDefn new_or_data cType mcxt ksig data_cons maybe_deriv
255 ; return (L loc (DataFamInstD noExt (DataFamInstDecl (mkHsImplicitBndrs
256 (FamEqn { feqn_ext = noExt
257 , feqn_tycon = tc
258 , feqn_pats = tparams
259 , feqn_fixity = fixity
260 , feqn_rhs = defn }))))) }
261
262 mkTyFamInst :: SrcSpan
263 -> TyFamInstEqn GhcPs
264 -> P (LInstDecl GhcPs)
265 mkTyFamInst loc eqn
266 = return (L loc (TyFamInstD noExt (TyFamInstDecl eqn)))
267
268 mkFamDecl :: SrcSpan
269 -> FamilyInfo GhcPs
270 -> LHsType GhcPs -- LHS
271 -> Located (FamilyResultSig GhcPs) -- Optional result signature
272 -> Maybe (LInjectivityAnn GhcPs) -- Injectivity annotation
273 -> P (LTyClDecl GhcPs)
274 mkFamDecl loc info lhs ksig injAnn
275 = do { (tc, tparams, fixity, ann) <- checkTyClHdr False lhs
276 ; mapM_ (\a -> a loc) ann -- Add any API Annotations to the top SrcSpan
277 ; tyvars <- checkTyVarsP (ppr info) equals_or_where tc tparams
278 ; return (L loc (FamDecl noExt (FamilyDecl
279 { fdExt = noExt
280 , fdInfo = info, fdLName = tc
281 , fdTyVars = tyvars
282 , fdFixity = fixity
283 , fdResultSig = ksig
284 , fdInjectivityAnn = injAnn }))) }
285 where
286 equals_or_where = case info of
287 DataFamily -> empty
288 OpenTypeFamily -> empty
289 ClosedTypeFamily {} -> whereDots
290
291 mkSpliceDecl :: LHsExpr GhcPs -> HsDecl GhcPs
292 -- If the user wrote
293 -- [pads| ... ] then return a QuasiQuoteD
294 -- $(e) then return a SpliceD
295 -- but if she wrote, say,
296 -- f x then behave as if she'd written $(f x)
297 -- ie a SpliceD
298 --
299 -- Typed splices are not allowed at the top level, thus we do not represent them
300 -- as spliced declaration. See #10945
301 mkSpliceDecl lexpr@(L loc expr)
302 | HsSpliceE _ splice@(HsUntypedSplice {}) <- expr
303 = SpliceD noExt (SpliceDecl noExt (L loc splice) ExplicitSplice)
304
305 | HsSpliceE _ splice@(HsQuasiQuote {}) <- expr
306 = SpliceD noExt (SpliceDecl noExt (L loc splice) ExplicitSplice)
307
308 | otherwise
309 = SpliceD noExt (SpliceDecl noExt (L loc (mkUntypedSplice NoParens lexpr))
310 ImplicitSplice)
311
312 mkRoleAnnotDecl :: SrcSpan
313 -> Located RdrName -- type being annotated
314 -> [Located (Maybe FastString)] -- roles
315 -> P (LRoleAnnotDecl GhcPs)
316 mkRoleAnnotDecl loc tycon roles
317 = do { roles' <- mapM parse_role roles
318 ; return $ L loc $ RoleAnnotDecl noExt tycon roles' }
319 where
320 role_data_type = dataTypeOf (undefined :: Role)
321 all_roles = map fromConstr $ dataTypeConstrs role_data_type
322 possible_roles = [(fsFromRole role, role) | role <- all_roles]
323
324 parse_role (L loc_role Nothing) = return $ L loc_role Nothing
325 parse_role (L loc_role (Just role))
326 = case lookup role possible_roles of
327 Just found_role -> return $ L loc_role $ Just found_role
328 Nothing ->
329 let nearby = fuzzyLookup (unpackFS role) (mapFst unpackFS possible_roles) in
330 parseErrorSDoc loc_role
331 (text "Illegal role name" <+> quotes (ppr role) $$
332 suggestions nearby)
333
334 suggestions [] = empty
335 suggestions [r] = text "Perhaps you meant" <+> quotes (ppr r)
336 -- will this last case ever happen??
337 suggestions list = hang (text "Perhaps you meant one of these:")
338 2 (pprWithCommas (quotes . ppr) list)
339
340 {- **********************************************************************
341
342 #cvBinds-etc# Converting to @HsBinds@, etc.
343
344 ********************************************************************* -}
345
346 -- | Function definitions are restructured here. Each is assumed to be recursive
347 -- initially, and non recursive definitions are discovered by the dependency
348 -- analyser.
349
350
351 -- | Groups together bindings for a single function
352 cvTopDecls :: OrdList (LHsDecl GhcPs) -> [LHsDecl GhcPs]
353 cvTopDecls decls = go (fromOL decls)
354 where
355 go :: [LHsDecl GhcPs] -> [LHsDecl GhcPs]
356 go [] = []
357 go (L l (ValD x b) : ds) = L l' (ValD x b') : go ds'
358 where (L l' b', ds') = getMonoBind (L l b) ds
359 go (d : ds) = d : go ds
360
361 -- Declaration list may only contain value bindings and signatures.
362 cvBindGroup :: OrdList (LHsDecl GhcPs) -> P (HsValBinds GhcPs)
363 cvBindGroup binding
364 = do { (mbs, sigs, fam_ds, tfam_insts, dfam_insts, _) <- cvBindsAndSigs binding
365 ; ASSERT( null fam_ds && null tfam_insts && null dfam_insts)
366 return $ ValBinds noExt mbs sigs }
367
368 cvBindsAndSigs :: OrdList (LHsDecl GhcPs)
369 -> P (LHsBinds GhcPs, [LSig GhcPs], [LFamilyDecl GhcPs]
370 , [LTyFamInstDecl GhcPs], [LDataFamInstDecl GhcPs], [LDocDecl])
371 -- Input decls contain just value bindings and signatures
372 -- and in case of class or instance declarations also
373 -- associated type declarations. They might also contain Haddock comments.
374 cvBindsAndSigs fb = go (fromOL fb)
375 where
376 go [] = return (emptyBag, [], [], [], [], [])
377 go (L l (ValD _ b) : ds)
378 = do { (bs, ss, ts, tfis, dfis, docs) <- go ds'
379 ; return (b' `consBag` bs, ss, ts, tfis, dfis, docs) }
380 where
381 (b', ds') = getMonoBind (L l b) ds
382 go (L l decl : ds)
383 = do { (bs, ss, ts, tfis, dfis, docs) <- go ds
384 ; case decl of
385 SigD _ s
386 -> return (bs, L l s : ss, ts, tfis, dfis, docs)
387 TyClD _ (FamDecl _ t)
388 -> return (bs, ss, L l t : ts, tfis, dfis, docs)
389 InstD _ (TyFamInstD { tfid_inst = tfi })
390 -> return (bs, ss, ts, L l tfi : tfis, dfis, docs)
391 InstD _ (DataFamInstD { dfid_inst = dfi })
392 -> return (bs, ss, ts, tfis, L l dfi : dfis, docs)
393 DocD _ d
394 -> return (bs, ss, ts, tfis, dfis, L l d : docs)
395 SpliceD _ d
396 -> parseErrorSDoc l $
397 hang (text "Declaration splices are allowed only" <+>
398 text "at the top level:")
399 2 (ppr d)
400 _ -> pprPanic "cvBindsAndSigs" (ppr decl) }
401
402 -----------------------------------------------------------------------------
403 -- Group function bindings into equation groups
404
405 getMonoBind :: LHsBind GhcPs -> [LHsDecl GhcPs]
406 -> (LHsBind GhcPs, [LHsDecl GhcPs])
407 -- Suppose (b',ds') = getMonoBind b ds
408 -- ds is a list of parsed bindings
409 -- b is a MonoBinds that has just been read off the front
410
411 -- Then b' is the result of grouping more equations from ds that
412 -- belong with b into a single MonoBinds, and ds' is the depleted
413 -- list of parsed bindings.
414 --
415 -- All Haddock comments between equations inside the group are
416 -- discarded.
417 --
418 -- No AndMonoBinds or EmptyMonoBinds here; just single equations
419
420 getMonoBind (L loc1 (FunBind { fun_id = fun_id1@(L _ f1),
421 fun_matches
422 = MG { mg_alts = L _ mtchs1 } })) binds
423 | has_args mtchs1
424 = go mtchs1 loc1 binds []
425 where
426 go mtchs loc
427 (L loc2 (ValD _ (FunBind { fun_id = L _ f2,
428 fun_matches
429 = MG { mg_alts = L _ mtchs2 } })) : binds) _
430 | f1 == f2 = go (mtchs2 ++ mtchs)
431 (combineSrcSpans loc loc2) binds []
432 go mtchs loc (doc_decl@(L loc2 (DocD {})) : binds) doc_decls
433 = let doc_decls' = doc_decl : doc_decls
434 in go mtchs (combineSrcSpans loc loc2) binds doc_decls'
435 go mtchs loc binds doc_decls
436 = ( L loc (makeFunBind fun_id1 (reverse mtchs))
437 , (reverse doc_decls) ++ binds)
438 -- Reverse the final matches, to get it back in the right order
439 -- Do the same thing with the trailing doc comments
440
441 getMonoBind bind binds = (bind, binds)
442
443 has_args :: [LMatch GhcPs (LHsExpr GhcPs)] -> Bool
444 has_args [] = panic "RdrHsSyn:has_args"
445 has_args ((L _ (Match { m_pats = args })) : _) = not (null args)
446 -- Don't group together FunBinds if they have
447 -- no arguments. This is necessary now that variable bindings
448 -- with no arguments are now treated as FunBinds rather
449 -- than pattern bindings (tests/rename/should_fail/rnfail002).
450 has_args ((L _ (XMatch _)) : _) = panic "has_args"
451
452 {- **********************************************************************
453
454 #PrefixToHS-utils# Utilities for conversion
455
456 ********************************************************************* -}
457
458 {- Note [Parsing data constructors is hard]
459 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
460 We parse the RHS of the constructor declaration
461 data T = C t1 t2
462 as a btype_no_ops (treating C as a type constructor) and then convert C to be
463 a data constructor. Reason: it might continue like this:
464 data T = C t1 t2 :% D Int
465 in which case C really /would/ be a type constructor. We can't resolve this
466 ambiguity till we come across the constructor oprerator :% (or not, more usually)
467
468 So the plan is:
469
470 * Parse the data constructor declration as a type (actually btype_no_ops)
471
472 * Use 'splitCon' to rejig it into the data constructor, the args, and possibly
473 extract a docstring for the constructor
474
475 * In doing so, we use 'tyConToDataCon' to convert the RdrName for
476 the data con, which has been parsed as a tycon, back to a datacon.
477 This is more than just adjusting the name space; for operators we
478 need to check that it begins with a colon. E.g.
479 data T = (+++)
480 will parse ok (since tycons can be operators), but we should reject
481 it (Trac #12051).
482 -}
483
484 splitCon :: LHsType GhcPs
485 -> P ( Located RdrName -- constructor name
486 , HsConDeclDetails GhcPs -- constructor field information
487 , Maybe LHsDocString -- docstring to go on the constructor
488 )
489 -- See Note [Parsing data constructors is hard]
490 -- This gets given a "type" that should look like
491 -- C Int Bool
492 -- or C { x::Int, y::Bool }
493 -- and returns the pieces
494 splitCon ty
495 = split apps' []
496 where
497 -- This is used somewhere where HsAppsTy is not used
498 unrollApps (L _ (HsAppTy _ t u)) = u : unrollApps t
499 unrollApps t = [t]
500
501 apps = unrollApps ty
502 oneDoc = [ () | L _ (HsDocTy{}) <- apps ] `lengthIs` 1
503
504 -- the trailing doc, if any, can be extracted first
505 (apps', trailing_doc)
506 = case apps of
507 L _ (HsDocTy _ t ds) : ts | oneDoc -> (t : ts, Just ds)
508 ts -> (ts, Nothing)
509
510 -- A comment on the constructor is handled a bit differently - it doesn't
511 -- remain an 'HsDocTy', but gets lifted out and returned as the third
512 -- element of the tuple.
513 split [ L _ (HsDocTy _ con con_doc) ] ts = do
514 (data_con, con_details, con_doc') <- split [con] ts
515 return (data_con, con_details, con_doc' `mplus` Just con_doc)
516 split [ L l (HsTyVar _ _ (L _ tc)) ] ts = do
517 data_con <- tyConToDataCon l tc
518 return (data_con, mk_rest ts, trailing_doc)
519 split [ L l (HsTupleTy _ HsBoxedOrConstraintTuple ts) ] []
520 = return ( L l (getRdrName (tupleDataCon Boxed (length ts)))
521 , PrefixCon ts
522 , trailing_doc
523 )
524 split [ L l _ ] _ = parseErrorSDoc l (text msg <+> ppr ty)
525 where msg = "Cannot parse data constructor in a data/newtype declaration:"
526 split (u : us) ts = split us (u : ts)
527 split _ _ = panic "RdrHsSyn:splitCon"
528
529 mk_rest [L _ (HsDocTy _ t@(L _ HsRecTy{}) _)] = mk_rest [t]
530 mk_rest [L l (HsRecTy _ flds)] = RecCon (L l flds)
531 mk_rest ts = PrefixCon ts
532
533 tyConToDataCon :: SrcSpan -> RdrName -> P (Located RdrName)
534 -- See Note [Parsing data constructors is hard]
535 -- Data constructor RHSs are parsed as types
536 tyConToDataCon loc tc
537 | isTcOcc occ
538 , isLexCon (occNameFS occ)
539 = return (L loc (setRdrNameSpace tc srcDataName))
540
541 | otherwise
542 = parseErrorSDoc loc (msg $$ extra)
543 where
544 occ = rdrNameOcc tc
545
546 msg = text "Not a data constructor:" <+> quotes (ppr tc)
547 extra | tc == forall_tv_RDR
548 = text "Perhaps you intended to use ExistentialQuantification"
549 | otherwise = empty
550
551 -- | Split a type to extract the trailing doc string (if there is one) from a
552 -- type produced by the 'btype_no_ops' production.
553 splitDocTy :: LHsType GhcPs -> (LHsType GhcPs, Maybe LHsDocString)
554 splitDocTy (L l (HsAppTy x t1 t2)) = (L l (HsAppTy x t1 t2'), ds)
555 where ~(t2', ds) = splitDocTy t2
556 splitDocTy (L _ (HsDocTy _ ty ds)) = (ty, Just ds)
557 splitDocTy ty = (ty, Nothing)
558
559 -- | Given a type that is a field to an infix data constructor, try to split
560 -- off a trailing docstring on the type, and check that there are no other
561 -- docstrings.
562 checkInfixConstr :: LHsType GhcPs -> P (LHsType GhcPs, Maybe LHsDocString)
563 checkInfixConstr ty = checkNoDocs msg ty' *> pure (ty', doc_string)
564 where (ty', doc_string) = splitDocTy ty
565 msg = text "infix constructor field"
566
567 mkPatSynMatchGroup :: Located RdrName
568 -> Located (OrdList (LHsDecl GhcPs))
569 -> P (MatchGroup GhcPs (LHsExpr GhcPs))
570 mkPatSynMatchGroup (L loc patsyn_name) (L _ decls) =
571 do { matches <- mapM fromDecl (fromOL decls)
572 ; when (null matches) (wrongNumberErr loc)
573 ; return $ mkMatchGroup FromSource matches }
574 where
575 fromDecl (L loc decl@(ValD _ (PatBind _
576 pat@(L _ (ConPatIn ln@(L _ name) details))
577 rhs _))) =
578 do { unless (name == patsyn_name) $
579 wrongNameBindingErr loc decl
580 ; match <- case details of
581 PrefixCon pats -> return $ Match { m_ext = noExt
582 , m_ctxt = ctxt, m_pats = pats
583 , m_grhss = rhs }
584 where
585 ctxt = FunRhs { mc_fun = ln, mc_fixity = Prefix, mc_strictness = NoSrcStrict }
586
587 InfixCon p1 p2 -> return $ Match { m_ext = noExt
588 , m_ctxt = ctxt
589 , m_pats = [p1, p2]
590 , m_grhss = rhs }
591 where
592 ctxt = FunRhs { mc_fun = ln, mc_fixity = Infix, mc_strictness = NoSrcStrict }
593
594 RecCon{} -> recordPatSynErr loc pat
595 ; return $ L loc match }
596 fromDecl (L loc decl) = extraDeclErr loc decl
597
598 extraDeclErr loc decl =
599 parseErrorSDoc loc $
600 text "pattern synonym 'where' clause must contain a single binding:" $$
601 ppr decl
602
603 wrongNameBindingErr loc decl =
604 parseErrorSDoc loc $
605 text "pattern synonym 'where' clause must bind the pattern synonym's name" <+>
606 quotes (ppr patsyn_name) $$ ppr decl
607
608 wrongNumberErr loc =
609 parseErrorSDoc loc $
610 text "pattern synonym 'where' clause cannot be empty" $$
611 text "In the pattern synonym declaration for: " <+> ppr (patsyn_name)
612
613 recordPatSynErr :: SrcSpan -> LPat GhcPs -> P a
614 recordPatSynErr loc pat =
615 parseErrorSDoc loc $
616 text "record syntax not supported for pattern synonym declarations:" $$
617 ppr pat
618
619 mkConDeclH98 :: Located RdrName -> Maybe [LHsTyVarBndr GhcPs]
620 -> Maybe (LHsContext GhcPs) -> HsConDeclDetails GhcPs
621 -> ConDecl GhcPs
622
623 mkConDeclH98 name mb_forall mb_cxt args
624 = ConDeclH98 { con_ext = noExt
625 , con_name = name
626 , con_forall = isJust mb_forall
627 , con_ex_tvs = mb_forall `orElse` []
628 , con_mb_cxt = mb_cxt
629 , con_args = args
630 , con_doc = Nothing }
631
632 mkGadtDecl :: [Located RdrName]
633 -> LHsType GhcPs -- Always a HsForAllTy
634 -> ConDecl GhcPs
635 mkGadtDecl names ty
636 = ConDeclGADT { con_g_ext = noExt
637 , con_names = names
638 , con_forall = isLHsForAllTy ty
639 , con_qvars = mkHsQTvs tvs
640 , con_mb_cxt = mcxt
641 , con_args = args
642 , con_res_ty = res_ty
643 , con_doc = Nothing }
644 where
645 (tvs, rho) = splitLHsForAllTy ty
646 (mcxt, tau) = split_rho rho
647
648 split_rho (L _ (HsQualTy { hst_ctxt = cxt, hst_body = tau }))
649 = (Just cxt, tau)
650 split_rho (L _ (HsParTy _ ty)) = split_rho ty
651 split_rho tau = (Nothing, tau)
652
653 (args, res_ty) = split_tau tau
654
655 -- See Note [GADT abstract syntax] in HsDecls
656 split_tau (L _ (HsFunTy _ (L loc (HsRecTy _ rf)) res_ty))
657 = (RecCon (L loc rf), res_ty)
658 split_tau (L _ (HsParTy _ ty)) = split_tau ty
659 split_tau tau = (PrefixCon [], tau)
660
661 setRdrNameSpace :: RdrName -> NameSpace -> RdrName
662 -- ^ This rather gruesome function is used mainly by the parser.
663 -- When parsing:
664 --
665 -- > data T a = T | T1 Int
666 --
667 -- we parse the data constructors as /types/ because of parser ambiguities,
668 -- so then we need to change the /type constr/ to a /data constr/
669 --
670 -- The exact-name case /can/ occur when parsing:
671 --
672 -- > data [] a = [] | a : [a]
673 --
674 -- For the exact-name case we return an original name.
675 setRdrNameSpace (Unqual occ) ns = Unqual (setOccNameSpace ns occ)
676 setRdrNameSpace (Qual m occ) ns = Qual m (setOccNameSpace ns occ)
677 setRdrNameSpace (Orig m occ) ns = Orig m (setOccNameSpace ns occ)
678 setRdrNameSpace (Exact n) ns
679 | Just thing <- wiredInNameTyThing_maybe n
680 = setWiredInNameSpace thing ns
681 -- Preserve Exact Names for wired-in things,
682 -- notably tuples and lists
683
684 | isExternalName n
685 = Orig (nameModule n) occ
686
687 | otherwise -- This can happen when quoting and then
688 -- splicing a fixity declaration for a type
689 = Exact (mkSystemNameAt (nameUnique n) occ (nameSrcSpan n))
690 where
691 occ = setOccNameSpace ns (nameOccName n)
692
693 setWiredInNameSpace :: TyThing -> NameSpace -> RdrName
694 setWiredInNameSpace (ATyCon tc) ns
695 | isDataConNameSpace ns
696 = ty_con_data_con tc
697 | isTcClsNameSpace ns
698 = Exact (getName tc) -- No-op
699
700 setWiredInNameSpace (AConLike (RealDataCon dc)) ns
701 | isTcClsNameSpace ns
702 = data_con_ty_con dc
703 | isDataConNameSpace ns
704 = Exact (getName dc) -- No-op
705
706 setWiredInNameSpace thing ns
707 = pprPanic "setWiredinNameSpace" (pprNameSpace ns <+> ppr thing)
708
709 ty_con_data_con :: TyCon -> RdrName
710 ty_con_data_con tc
711 | isTupleTyCon tc
712 , Just dc <- tyConSingleDataCon_maybe tc
713 = Exact (getName dc)
714
715 | tc `hasKey` listTyConKey
716 = Exact nilDataConName
717
718 | otherwise -- See Note [setRdrNameSpace for wired-in names]
719 = Unqual (setOccNameSpace srcDataName (getOccName tc))
720
721 data_con_ty_con :: DataCon -> RdrName
722 data_con_ty_con dc
723 | let tc = dataConTyCon dc
724 , isTupleTyCon tc
725 = Exact (getName tc)
726
727 | dc `hasKey` nilDataConKey
728 = Exact listTyConName
729
730 | otherwise -- See Note [setRdrNameSpace for wired-in names]
731 = Unqual (setOccNameSpace tcClsName (getOccName dc))
732
733
734 {- Note [setRdrNameSpace for wired-in names]
735 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
736 In GHC.Types, which declares (:), we have
737 infixr 5 :
738 The ambiguity about which ":" is meant is resolved by parsing it as a
739 data constructor, but then using dataTcOccs to try the type constructor too;
740 and that in turn calls setRdrNameSpace to change the name-space of ":" to
741 tcClsName. There isn't a corresponding ":" type constructor, but it's painful
742 to make setRdrNameSpace partial, so we just make an Unqual name instead. It
743 really doesn't matter!
744 -}
745
746 checkTyVarsP :: SDoc -> SDoc -> Located RdrName -> [LHsType GhcPs]
747 -> P (LHsQTyVars GhcPs)
748 -- Same as checkTyVars, but in the P monad
749 checkTyVarsP pp_what equals_or_where tc tparms
750 = eitherToP $ checkTyVars pp_what equals_or_where tc tparms
751
752 eitherToP :: Either (SrcSpan, SDoc) a -> P a
753 -- Adapts the Either monad to the P monad
754 eitherToP (Left (loc, doc)) = parseErrorSDoc loc doc
755 eitherToP (Right thing) = return thing
756
757 checkTyVars :: SDoc -> SDoc -> Located RdrName -> [LHsType GhcPs]
758 -> Either (SrcSpan, SDoc) (LHsQTyVars GhcPs)
759 -- Check whether the given list of type parameters are all type variables
760 -- (possibly with a kind signature)
761 -- We use the Either monad because it's also called (via mkATDefault) from
762 -- Convert.hs
763 checkTyVars pp_what equals_or_where tc tparms
764 = do { tvs <- mapM chk tparms
765 ; return (mkHsQTvs tvs) }
766 where
767 chk (L _ (HsParTy _ ty)) = chk ty
768
769 -- Check that the name space is correct!
770 chk (L l (HsKindSig _ (L lv (HsTyVar _ _ (L _ tv))) k))
771 | isRdrTyVar tv = return (L l (KindedTyVar noExt (L lv tv) k))
772 chk (L l (HsTyVar _ _ (L ltv tv)))
773 | isRdrTyVar tv = return (L l (UserTyVar noExt (L ltv tv)))
774 chk t@(L loc _)
775 = Left (loc,
776 vcat [ text "Unexpected type" <+> quotes (ppr t)
777 , text "In the" <+> pp_what <+> ptext (sLit "declaration for") <+> quotes (ppr tc)
778 , vcat[ (text "A" <+> pp_what <+> ptext (sLit "declaration should have form"))
779 , nest 2 (pp_what <+> ppr tc
780 <+> hsep (map text (takeList tparms allNameStrings))
781 <+> equals_or_where) ] ])
782
783 whereDots, equalsDots :: SDoc
784 -- Second argument to checkTyVars
785 whereDots = text "where ..."
786 equalsDots = text "= ..."
787
788 checkDatatypeContext :: Maybe (LHsContext GhcPs) -> P ()
789 checkDatatypeContext Nothing = return ()
790 checkDatatypeContext (Just (L loc c))
791 = do allowed <- extension datatypeContextsEnabled
792 unless allowed $
793 parseErrorSDoc loc
794 (text "Illegal datatype context (use DatatypeContexts):" <+>
795 pprHsContext c)
796
797 checkRecordSyntax :: Outputable a => Located a -> P (Located a)
798 checkRecordSyntax lr@(L loc r)
799 = do allowed <- extension traditionalRecordSyntaxEnabled
800 if allowed
801 then return lr
802 else parseErrorSDoc loc
803 (text "Illegal record syntax (use TraditionalRecordSyntax):" <+>
804 ppr r)
805
806 -- | Check if the gadt_constrlist is empty. Only raise parse error for
807 -- `data T where` to avoid affecting existing error message, see #8258.
808 checkEmptyGADTs :: Located ([AddAnn], [LConDecl GhcPs])
809 -> P (Located ([AddAnn], [LConDecl GhcPs]))
810 checkEmptyGADTs gadts@(L span (_, [])) -- Empty GADT declaration.
811 = do opts <- fmap options getPState
812 if LangExt.GADTSyntax `extopt` opts -- GADTs implies GADTSyntax
813 then return gadts
814 else parseErrorSDoc span $ vcat
815 [ text "Illegal keyword 'where' in data declaration"
816 , text "Perhaps you intended to use GADTs or a similar language"
817 , text "extension to enable syntax: data T where"
818 ]
819 checkEmptyGADTs gadts = return gadts -- Ordinary GADT declaration.
820
821 checkTyClHdr :: Bool -- True <=> class header
822 -- False <=> type header
823 -> LHsType GhcPs
824 -> P (Located RdrName, -- the head symbol (type or class name)
825 [LHsType GhcPs], -- parameters of head symbol
826 LexicalFixity, -- the declaration is in infix format
827 [AddAnn]) -- API Annotation for HsParTy when stripping parens
828 -- Well-formedness check and decomposition of type and class heads.
829 -- Decomposes T ty1 .. tyn into (T, [ty1, ..., tyn])
830 -- Int :*: Bool into (:*:, [Int, Bool])
831 -- returning the pieces
832 checkTyClHdr is_cls ty
833 = goL ty [] [] Prefix
834 where
835 goL (L l ty) acc ann fix = go l ty acc ann fix
836
837 go l (HsTyVar _ _ (L _ tc)) acc ann fix
838 | isRdrTc tc = return (L l tc, acc, fix, ann)
839 go _ (HsOpTy _ t1 ltc@(L _ tc) t2) acc ann _fix
840 | isRdrTc tc = return (ltc, t1:t2:acc, Infix, ann)
841 go l (HsParTy _ ty) acc ann fix = goL ty acc (ann ++mkParensApiAnn l) fix
842 go _ (HsAppTy _ t1 t2) acc ann fix = goL t1 (t2:acc) ann fix
843 go _ (HsAppsTy _ ts) acc ann _fix
844 | Just (head, args, fixity) <- getAppsTyHead_maybe ts
845 = goL head (args ++ acc) ann fixity
846
847 go _ (HsAppsTy _ [L _ (HsAppInfix _ (L loc star))]) [] ann fix
848 | isStar star
849 = return (L loc (nameRdrName starKindTyConName), [], fix, ann)
850 | isUniStar star
851 = return (L loc (nameRdrName unicodeStarKindTyConName), [], fix, ann)
852
853 go l (HsTupleTy _ HsBoxedOrConstraintTuple ts) [] ann fix
854 = return (L l (nameRdrName tup_name), ts, fix, ann)
855 where
856 arity = length ts
857 tup_name | is_cls = cTupleTyConName arity
858 | otherwise = getName (tupleTyCon Boxed arity)
859 -- See Note [Unit tuples] in HsTypes (TODO: is this still relevant?)
860 go l _ _ _ _
861 = parseErrorSDoc l (text "Malformed head of type or class declaration:"
862 <+> ppr ty)
863
864 -- | Yield a parse error if we have a function applied directly to a do block
865 -- etc. and BlockArguments is not enabled.
866 checkBlockArguments :: LHsExpr GhcPs -> P ()
867 checkBlockArguments expr = case unLoc expr of
868 HsDo _ DoExpr _ -> check "do block"
869 HsDo _ MDoExpr _ -> check "mdo block"
870 HsLam {} -> check "lambda expression"
871 HsCase {} -> check "case expression"
872 HsLamCase {} -> check "lambda-case expression"
873 HsLet {} -> check "let expression"
874 HsIf {} -> check "if expression"
875 HsProc {} -> check "proc expression"
876 _ -> return ()
877 where
878 check element = do
879 pState <- getPState
880 unless (extopt LangExt.BlockArguments (options pState)) $
881 parseErrorSDoc (getLoc expr) $
882 text "Unexpected " <> text element <> text " in function application:"
883 $$ nest 4 (ppr expr)
884 $$ text "You could write it with parentheses"
885 $$ text "Or perhaps you meant to enable BlockArguments?"
886
887 -- | Validate the context constraints and break up a context into a list
888 -- of predicates.
889 --
890 -- @
891 -- (Eq a, Ord b) --> [Eq a, Ord b]
892 -- Eq a --> [Eq a]
893 -- (Eq a) --> [Eq a]
894 -- (((Eq a))) --> [Eq a]
895 -- @
896 checkContext :: LHsType GhcPs -> P ([AddAnn],LHsContext GhcPs)
897 checkContext (L l orig_t)
898 = check [] (L l orig_t)
899 where
900 check anns (L lp (HsTupleTy _ HsBoxedOrConstraintTuple ts))
901 -- (Eq a, Ord b) shows up as a tuple type. Only boxed tuples can
902 -- be used as context constraints.
903 = return (anns ++ mkParensApiAnn lp,L l ts) -- Ditto ()
904
905 -- don't let HsAppsTy get in the way
906 check anns (L _ (HsAppsTy _ [L _ (HsAppPrefix _ ty)]))
907 = check anns ty
908
909 check anns (L lp1 (HsParTy _ ty))
910 -- to be sure HsParTy doesn't get into the way
911 = check anns' ty
912 where anns' = if l == lp1 then anns
913 else (anns ++ mkParensApiAnn lp1)
914
915 -- no need for anns, returning original
916 check _anns t = checkNoDocs msg t *> return ([],L l [L l orig_t])
917
918 msg = text "data constructor context"
919
920 -- | Check recursively if there are any 'HsDocTy's in the given type.
921 -- This only works on a subset of types produced by 'btype_no_ops'
922 checkNoDocs :: SDoc -> LHsType GhcPs -> P ()
923 checkNoDocs msg ty = go ty
924 where
925 go (L _ (HsAppTy _ t1 t2)) = go t1 *> go t2
926 go (L l (HsDocTy _ t ds)) = parseErrorSDoc l $ hsep
927 [ text "Unexpected haddock", quotes (ppr ds)
928 , text "on", msg, quotes (ppr t) ]
929 go _ = pure ()
930
931 -- -------------------------------------------------------------------------
932 -- Checking Patterns.
933
934 -- We parse patterns as expressions and check for valid patterns below,
935 -- converting the expression into a pattern at the same time.
936
937 checkPattern :: SDoc -> LHsExpr GhcPs -> P (LPat GhcPs)
938 checkPattern msg e = checkLPat msg e
939
940 checkPatterns :: SDoc -> [LHsExpr GhcPs] -> P [LPat GhcPs]
941 checkPatterns msg es = mapM (checkPattern msg) es
942
943 checkLPat :: SDoc -> LHsExpr GhcPs -> P (LPat GhcPs)
944 checkLPat msg e@(L l _) = checkPat msg l e []
945
946 checkPat :: SDoc -> SrcSpan -> LHsExpr GhcPs -> [LPat GhcPs]
947 -> P (LPat GhcPs)
948 checkPat _ loc (L l e@(HsVar _ (L _ c))) args
949 | isRdrDataCon c = return (L loc (ConPatIn (L l c) (PrefixCon args)))
950 | not (null args) && patIsRec c =
951 patFail (text "Perhaps you intended to use RecursiveDo") l e
952 checkPat msg loc e args -- OK to let this happen even if bang-patterns
953 -- are not enabled, because there is no valid
954 -- non-bang-pattern parse of (C ! e)
955 | Just (e', args') <- splitBang e
956 = do { args'' <- checkPatterns msg args'
957 ; checkPat msg loc e' (args'' ++ args) }
958 checkPat msg loc (L _ (HsApp _ f e)) args
959 = do p <- checkLPat msg e
960 checkPat msg loc f (p : args)
961 checkPat msg loc (L _ e) []
962 = do p <- checkAPat msg loc e
963 return (L loc p)
964 checkPat msg loc e _
965 = patFail msg loc (unLoc e)
966
967 checkAPat :: SDoc -> SrcSpan -> HsExpr GhcPs -> P (Pat GhcPs)
968 checkAPat msg loc e0 = do
969 pState <- getPState
970 let opts = options pState
971 case e0 of
972 EWildPat _ -> return (WildPat noExt)
973 HsVar _ x -> return (VarPat noExt x)
974 HsLit _ (HsStringPrim _ _) -- (#13260)
975 -> parseErrorSDoc loc (text "Illegal unboxed string literal in pattern:" $$ ppr e0)
976
977 HsLit _ l -> return (LitPat noExt l)
978
979 -- Overloaded numeric patterns (e.g. f 0 x = x)
980 -- Negation is recorded separately, so that the literal is zero or +ve
981 -- NB. Negative *primitive* literals are already handled by the lexer
982 HsOverLit _ pos_lit -> return (mkNPat (L loc pos_lit) Nothing)
983 NegApp _ (L l (HsOverLit _ pos_lit)) _
984 -> return (mkNPat (L l pos_lit) (Just noSyntaxExpr))
985
986 SectionR _ (L lb (HsVar _ (L _ bang))) e -- (! x)
987 | bang == bang_RDR
988 -> do { hintBangPat loc e0
989 ; e' <- checkLPat msg e
990 ; addAnnotation loc AnnBang lb
991 ; return (BangPat noExt e') }
992
993 ELazyPat _ e -> checkLPat msg e >>= (return . (LazyPat noExt))
994 EAsPat _ n e -> checkLPat msg e >>= (return . (AsPat noExt) n)
995 -- view pattern is well-formed if the pattern is
996 EViewPat _ expr patE -> checkLPat msg patE >>=
997 (return . (\p -> ViewPat noExt expr p))
998 ExprWithTySig t e -> do e <- checkLPat msg e
999 return (SigPat t e)
1000
1001 -- n+k patterns
1002 OpApp _ (L nloc (HsVar _ (L _ n))) (L _ (HsVar _ (L _ plus)))
1003 (L lloc (HsOverLit _ lit@(OverLit {ol_val = HsIntegral {}})))
1004 | extopt LangExt.NPlusKPatterns opts && (plus == plus_RDR)
1005 -> return (mkNPlusKPat (L nloc n) (L lloc lit))
1006
1007 OpApp _ l (L cl (HsVar _ (L _ c))) r
1008 | isDataOcc (rdrNameOcc c) -> do
1009 l <- checkLPat msg l
1010 r <- checkLPat msg r
1011 return (ConPatIn (L cl c) (InfixCon l r))
1012
1013 OpApp {} -> patFail msg loc e0
1014
1015 ExplicitList _ _ es -> do ps <- mapM (checkLPat msg) es
1016 return (ListPat noExt ps)
1017
1018 HsPar _ e -> checkLPat msg e >>= (return . (ParPat noExt))
1019
1020 ExplicitTuple _ es b
1021 | all tupArgPresent es -> do ps <- mapM (checkLPat msg)
1022 [e | L _ (Present _ e) <- es]
1023 return (TuplePat noExt ps b)
1024 | otherwise -> parseErrorSDoc loc (text "Illegal tuple section in pattern:" $$ ppr e0)
1025
1026 ExplicitSum _ alt arity expr -> do
1027 p <- checkLPat msg expr
1028 return (SumPat noExt p alt arity)
1029
1030 RecordCon { rcon_con_name = c, rcon_flds = HsRecFields fs dd }
1031 -> do fs <- mapM (checkPatField msg) fs
1032 return (ConPatIn c (RecCon (HsRecFields fs dd)))
1033 HsSpliceE _ s | not (isTypedSplice s)
1034 -> return (SplicePat noExt s)
1035 _ -> patFail msg loc e0
1036
1037 placeHolderPunRhs :: LHsExpr GhcPs
1038 -- The RHS of a punned record field will be filled in by the renamer
1039 -- It's better not to make it an error, in case we want to print it when debugging
1040 placeHolderPunRhs = noLoc (HsVar noExt (noLoc pun_RDR))
1041
1042 plus_RDR, bang_RDR, pun_RDR :: RdrName
1043 plus_RDR = mkUnqual varName (fsLit "+") -- Hack
1044 bang_RDR = mkUnqual varName (fsLit "!") -- Hack
1045 pun_RDR = mkUnqual varName (fsLit "pun-right-hand-side")
1046
1047 checkPatField :: SDoc -> LHsRecField GhcPs (LHsExpr GhcPs)
1048 -> P (LHsRecField GhcPs (LPat GhcPs))
1049 checkPatField msg (L l fld) = do p <- checkLPat msg (hsRecFieldArg fld)
1050 return (L l (fld { hsRecFieldArg = p }))
1051
1052 patFail :: SDoc -> SrcSpan -> HsExpr GhcPs -> P a
1053 patFail msg loc e = parseErrorSDoc loc err
1054 where err = text "Parse error in pattern:" <+> ppr e
1055 $$ msg
1056
1057 patIsRec :: RdrName -> Bool
1058 patIsRec e = e == mkUnqual varName (fsLit "rec")
1059
1060
1061 ---------------------------------------------------------------------------
1062 -- Check Equation Syntax
1063
1064 checkValDef :: SDoc
1065 -> SrcStrictness
1066 -> LHsExpr GhcPs
1067 -> Maybe (LHsType GhcPs)
1068 -> Located (a,GRHSs GhcPs (LHsExpr GhcPs))
1069 -> P ([AddAnn],HsBind GhcPs)
1070
1071 checkValDef msg _strictness lhs (Just sig) grhss
1072 -- x :: ty = rhs parses as a *pattern* binding
1073 = checkPatBind msg (L (combineLocs lhs sig)
1074 (ExprWithTySig (mkLHsSigWcType sig) lhs)) grhss
1075
1076 checkValDef msg strictness lhs Nothing g@(L l (_,grhss))
1077 = do { mb_fun <- isFunLhs lhs
1078 ; case mb_fun of
1079 Just (fun, is_infix, pats, ann) ->
1080 checkFunBind msg strictness ann (getLoc lhs)
1081 fun is_infix pats (L l grhss)
1082 Nothing -> checkPatBind msg lhs g }
1083
1084 checkFunBind :: SDoc
1085 -> SrcStrictness
1086 -> [AddAnn]
1087 -> SrcSpan
1088 -> Located RdrName
1089 -> LexicalFixity
1090 -> [LHsExpr GhcPs]
1091 -> Located (GRHSs GhcPs (LHsExpr GhcPs))
1092 -> P ([AddAnn],HsBind GhcPs)
1093 checkFunBind msg strictness ann lhs_loc fun is_infix pats (L rhs_span grhss)
1094 = do ps <- checkPatterns msg pats
1095 let match_span = combineSrcSpans lhs_loc rhs_span
1096 -- Add back the annotations stripped from any HsPar values in the lhs
1097 -- mapM_ (\a -> a match_span) ann
1098 return (ann, makeFunBind fun
1099 [L match_span (Match { m_ext = noExt
1100 , m_ctxt = FunRhs { mc_fun = fun
1101 , mc_fixity = is_infix
1102 , mc_strictness = strictness }
1103 , m_pats = ps
1104 , m_grhss = grhss })])
1105 -- The span of the match covers the entire equation.
1106 -- That isn't quite right, but it'll do for now.
1107
1108 makeFunBind :: Located RdrName -> [LMatch GhcPs (LHsExpr GhcPs)]
1109 -> HsBind GhcPs
1110 -- Like HsUtils.mkFunBind, but we need to be able to set the fixity too
1111 makeFunBind fn ms
1112 = FunBind { fun_ext = noExt,
1113 fun_id = fn,
1114 fun_matches = mkMatchGroup FromSource ms,
1115 fun_co_fn = idHsWrapper,
1116 fun_tick = [] }
1117
1118 checkPatBind :: SDoc
1119 -> LHsExpr GhcPs
1120 -> Located (a,GRHSs GhcPs (LHsExpr GhcPs))
1121 -> P ([AddAnn],HsBind GhcPs)
1122 checkPatBind msg lhs (L _ (_,grhss))
1123 = do { lhs <- checkPattern msg lhs
1124 ; return ([],PatBind noExt lhs grhss
1125 ([],[])) }
1126
1127 checkValSigLhs :: LHsExpr GhcPs -> P (Located RdrName)
1128 checkValSigLhs (L _ (HsVar _ lrdr@(L _ v)))
1129 | isUnqual v
1130 , not (isDataOcc (rdrNameOcc v))
1131 = return lrdr
1132
1133 checkValSigLhs lhs@(L l _)
1134 = parseErrorSDoc l ((text "Invalid type signature:" <+>
1135 ppr lhs <+> text ":: ...")
1136 $$ text hint)
1137 where
1138 hint | foreign_RDR `looks_like` lhs
1139 = "Perhaps you meant to use ForeignFunctionInterface?"
1140 | default_RDR `looks_like` lhs
1141 = "Perhaps you meant to use DefaultSignatures?"
1142 | pattern_RDR `looks_like` lhs
1143 = "Perhaps you meant to use PatternSynonyms?"
1144 | otherwise
1145 = "Should be of form <variable> :: <type>"
1146
1147 -- A common error is to forget the ForeignFunctionInterface flag
1148 -- so check for that, and suggest. cf Trac #3805
1149 -- Sadly 'foreign import' still barfs 'parse error' because 'import' is a keyword
1150 looks_like s (L _ (HsVar _ (L _ v))) = v == s
1151 looks_like s (L _ (HsApp _ lhs _)) = looks_like s lhs
1152 looks_like _ _ = False
1153
1154 foreign_RDR = mkUnqual varName (fsLit "foreign")
1155 default_RDR = mkUnqual varName (fsLit "default")
1156 pattern_RDR = mkUnqual varName (fsLit "pattern")
1157
1158
1159 checkDoAndIfThenElse :: LHsExpr GhcPs
1160 -> Bool
1161 -> LHsExpr GhcPs
1162 -> Bool
1163 -> LHsExpr GhcPs
1164 -> P ()
1165 checkDoAndIfThenElse guardExpr semiThen thenExpr semiElse elseExpr
1166 | semiThen || semiElse
1167 = do pState <- getPState
1168 unless (extopt LangExt.DoAndIfThenElse (options pState)) $ do
1169 parseErrorSDoc (combineLocs guardExpr elseExpr)
1170 (text "Unexpected semi-colons in conditional:"
1171 $$ nest 4 expr
1172 $$ text "Perhaps you meant to use DoAndIfThenElse?")
1173 | otherwise = return ()
1174 where pprOptSemi True = semi
1175 pprOptSemi False = empty
1176 expr = text "if" <+> ppr guardExpr <> pprOptSemi semiThen <+>
1177 text "then" <+> ppr thenExpr <> pprOptSemi semiElse <+>
1178 text "else" <+> ppr elseExpr
1179
1180
1181 -- The parser left-associates, so there should
1182 -- not be any OpApps inside the e's
1183 splitBang :: LHsExpr GhcPs -> Maybe (LHsExpr GhcPs, [LHsExpr GhcPs])
1184 -- Splits (f ! g a b) into (f, [(! g), a, b])
1185 splitBang (L _ (OpApp _ l_arg bang@(L _ (HsVar _ (L _ op))) r_arg))
1186 | op == bang_RDR = Just (l_arg, L l' (SectionR noExt bang arg1) : argns)
1187 where
1188 l' = combineLocs bang arg1
1189 (arg1,argns) = split_bang r_arg []
1190 split_bang (L _ (HsApp _ f e)) es = split_bang f (e:es)
1191 split_bang e es = (e,es)
1192 splitBang _ = Nothing
1193
1194 isFunLhs :: LHsExpr GhcPs
1195 -> P (Maybe (Located RdrName, LexicalFixity, [LHsExpr GhcPs],[AddAnn]))
1196 -- A variable binding is parsed as a FunBind.
1197 -- Just (fun, is_infix, arg_pats) if e is a function LHS
1198 --
1199 -- The whole LHS is parsed as a single expression.
1200 -- Any infix operators on the LHS will parse left-associatively
1201 -- E.g. f !x y !z
1202 -- will parse (rather strangely) as
1203 -- (f ! x y) ! z
1204 -- It's up to isFunLhs to sort out the mess
1205 --
1206 -- a .!. !b
1207
1208 isFunLhs e = go e [] []
1209 where
1210 go (L loc (HsVar _ (L _ f))) es ann
1211 | not (isRdrDataCon f) = return (Just (L loc f, Prefix, es, ann))
1212 go (L _ (HsApp _ f e)) es ann = go f (e:es) ann
1213 go (L l (HsPar _ e)) es@(_:_) ann = go e es (ann ++ mkParensApiAnn l)
1214
1215 -- Things of the form `!x` are also FunBinds
1216 -- See Note [FunBind vs PatBind]
1217 go (L _ (SectionR _ (L _ (HsVar _ (L _ bang))) (L l (HsVar _ (L _ var)))))
1218 [] ann
1219 | bang == bang_RDR
1220 , not (isRdrDataCon var) = return (Just (L l var, Prefix, [], ann))
1221
1222 -- For infix function defns, there should be only one infix *function*
1223 -- (though there may be infix *datacons* involved too). So we don't
1224 -- need fixity info to figure out which function is being defined.
1225 -- a `K1` b `op` c `K2` d
1226 -- must parse as
1227 -- (a `K1` b) `op` (c `K2` d)
1228 -- The renamer checks later that the precedences would yield such a parse.
1229 --
1230 -- There is a complication to deal with bang patterns.
1231 --
1232 -- ToDo: what about this?
1233 -- x + 1 `op` y = ...
1234
1235 go e@(L loc (OpApp _ l (L loc' (HsVar _ (L _ op))) r)) es ann
1236 | Just (e',es') <- splitBang e
1237 = do { bang_on <- extension bangPatEnabled
1238 ; if bang_on then go e' (es' ++ es) ann
1239 else return (Just (L loc' op, Infix, (l:r:es), ann)) }
1240 -- No bangs; behave just like the next case
1241 | not (isRdrDataCon op) -- We have found the function!
1242 = return (Just (L loc' op, Infix, (l:r:es), ann))
1243 | otherwise -- Infix data con; keep going
1244 = do { mb_l <- go l es ann
1245 ; case mb_l of
1246 Just (op', Infix, j : k : es', ann')
1247 -> return (Just (op', Infix, j : op_app : es', ann'))
1248 where
1249 op_app = L loc (OpApp noExt k
1250 (L loc' (HsVar noExt (L loc' op))) r)
1251 _ -> return Nothing }
1252 go _ _ _ = return Nothing
1253
1254
1255 -- | Transform btype_no_ops with strict_mark's into HsEqTy's
1256 -- (((~a) ~b) c) ~d ==> ((~a) ~ (b c)) ~ d
1257 splitTilde :: LHsType GhcPs -> P (LHsType GhcPs)
1258 splitTilde t = go t
1259 where go (L loc (HsAppTy _ t1 t2))
1260 | L lo (HsBangTy _ (HsSrcBang NoSourceText NoSrcUnpack SrcLazy) t2')
1261 <- t2
1262 = do
1263 moveAnnotations lo loc
1264 t1' <- go t1
1265 return (L loc (HsEqTy noExt t1' t2'))
1266 | otherwise
1267 = do
1268 t1' <- go t1
1269 case t1' of
1270 (L lo (HsEqTy _ tl tr)) -> do
1271 let lr = combineLocs tr t2
1272 moveAnnotations lo loc
1273 return (L loc (HsEqTy noExt tl
1274 (L lr (HsAppTy noExt tr t2))))
1275 t -> do
1276 return (L loc (HsAppTy noExt t t2))
1277
1278 go t = return t
1279
1280
1281 -- | Transform tyapps with strict_marks into uses of twiddle
1282 -- [~a, ~b, c, ~d] ==> (~a) ~ b c ~ d
1283 splitTildeApps :: [LHsAppType GhcPs] -> P [LHsAppType GhcPs]
1284 splitTildeApps [] = return []
1285 splitTildeApps (t : rest) = do
1286 rest' <- concatMapM go rest
1287 return (t : rest')
1288 where go (L l (HsAppPrefix _
1289 (L loc (HsBangTy noExt
1290 (HsSrcBang NoSourceText NoSrcUnpack SrcLazy)
1291 ty))))
1292 = addAnnotation l AnnTilde tilde_loc >>
1293 return
1294 [L tilde_loc (HsAppInfix noExt (L tilde_loc eqTyCon_RDR)),
1295 L l (HsAppPrefix noExt ty)]
1296 -- NOTE: no annotation is attached to an HsAppPrefix, so the
1297 -- surrounding SrcSpan is not critical
1298 where
1299 tilde_loc = srcSpanFirstCharacter loc
1300
1301 go t = return [t]
1302
1303
1304
1305 ---------------------------------------------------------------------------
1306 -- Check for monad comprehensions
1307 --
1308 -- If the flag MonadComprehensions is set, return a `MonadComp' context,
1309 -- otherwise use the usual `ListComp' context
1310
1311 checkMonadComp :: P (HsStmtContext Name)
1312 checkMonadComp = do
1313 pState <- getPState
1314 return $ if extopt LangExt.MonadComprehensions (options pState)
1315 then MonadComp
1316 else ListComp
1317
1318 -- -------------------------------------------------------------------------
1319 -- Checking arrow syntax.
1320
1321 -- We parse arrow syntax as expressions and check for valid syntax below,
1322 -- converting the expression into a pattern at the same time.
1323
1324 checkCommand :: LHsExpr GhcPs -> P (LHsCmd GhcPs)
1325 checkCommand lc = locMap checkCmd lc
1326
1327 locMap :: (SrcSpan -> a -> P b) -> Located a -> P (Located b)
1328 locMap f (L l a) = f l a >>= (\b -> return $ L l b)
1329
1330 checkCmd :: SrcSpan -> HsExpr GhcPs -> P (HsCmd GhcPs)
1331 checkCmd _ (HsArrApp _ e1 e2 haat b) =
1332 return $ HsCmdArrApp noExt e1 e2 haat b
1333 checkCmd _ (HsArrForm _ e mf args) =
1334 return $ HsCmdArrForm noExt e Prefix mf args
1335 checkCmd _ (HsApp _ e1 e2) =
1336 checkCommand e1 >>= (\c -> return $ HsCmdApp noExt c e2)
1337 checkCmd _ (HsLam _ mg) =
1338 checkCmdMatchGroup mg >>= (\mg' -> return $ HsCmdLam noExt mg')
1339 checkCmd _ (HsPar _ e) =
1340 checkCommand e >>= (\c -> return $ HsCmdPar noExt c)
1341 checkCmd _ (HsCase _ e mg) =
1342 checkCmdMatchGroup mg >>= (\mg' -> return $ HsCmdCase noExt e mg')
1343 checkCmd _ (HsIf _ cf ep et ee) = do
1344 pt <- checkCommand et
1345 pe <- checkCommand ee
1346 return $ HsCmdIf noExt cf ep pt pe
1347 checkCmd _ (HsLet _ lb e) =
1348 checkCommand e >>= (\c -> return $ HsCmdLet noExt lb c)
1349 checkCmd _ (HsDo _ DoExpr (L l stmts)) =
1350 mapM checkCmdLStmt stmts >>=
1351 (\ss -> return $ HsCmdDo noExt (L l ss) )
1352
1353 checkCmd _ (OpApp _ eLeft op eRight) = do
1354 -- OpApp becomes a HsCmdArrForm with a (Just fixity) in it
1355 c1 <- checkCommand eLeft
1356 c2 <- checkCommand eRight
1357 let arg1 = L (getLoc c1) $ HsCmdTop noExt c1
1358 arg2 = L (getLoc c2) $ HsCmdTop noExt c2
1359 return $ HsCmdArrForm noExt op Infix Nothing [arg1, arg2]
1360
1361 checkCmd l e = cmdFail l e
1362
1363 checkCmdLStmt :: ExprLStmt GhcPs -> P (CmdLStmt GhcPs)
1364 checkCmdLStmt = locMap checkCmdStmt
1365
1366 checkCmdStmt :: SrcSpan -> ExprStmt GhcPs -> P (CmdStmt GhcPs)
1367 checkCmdStmt _ (LastStmt x e s r) =
1368 checkCommand e >>= (\c -> return $ LastStmt x c s r)
1369 checkCmdStmt _ (BindStmt x pat e b f) =
1370 checkCommand e >>= (\c -> return $ BindStmt x pat c b f)
1371 checkCmdStmt _ (BodyStmt x e t g) =
1372 checkCommand e >>= (\c -> return $ BodyStmt x c t g)
1373 checkCmdStmt _ (LetStmt x bnds) = return $ LetStmt x bnds
1374 checkCmdStmt _ stmt@(RecStmt { recS_stmts = stmts }) = do
1375 ss <- mapM checkCmdLStmt stmts
1376 return $ stmt { recS_ext = noExt, recS_stmts = ss }
1377 checkCmdStmt _ (XStmtLR _) = panic "checkCmdStmt"
1378 checkCmdStmt l stmt = cmdStmtFail l stmt
1379
1380 checkCmdMatchGroup :: MatchGroup GhcPs (LHsExpr GhcPs)
1381 -> P (MatchGroup GhcPs (LHsCmd GhcPs))
1382 checkCmdMatchGroup mg@(MG { mg_alts = L l ms }) = do
1383 ms' <- mapM (locMap $ const convert) ms
1384 return $ mg { mg_ext = noExt, mg_alts = L l ms' }
1385 where convert match@(Match { m_grhss = grhss }) = do
1386 grhss' <- checkCmdGRHSs grhss
1387 return $ match { m_ext = noExt, m_grhss = grhss'}
1388 convert (XMatch _) = panic "checkCmdMatchGroup.XMatch"
1389 checkCmdMatchGroup (XMatchGroup {}) = panic "checkCmdMatchGroup"
1390
1391 checkCmdGRHSs :: GRHSs GhcPs (LHsExpr GhcPs) -> P (GRHSs GhcPs (LHsCmd GhcPs))
1392 checkCmdGRHSs (GRHSs x grhss binds) = do
1393 grhss' <- mapM checkCmdGRHS grhss
1394 return $ GRHSs x grhss' binds
1395 checkCmdGRHSs (XGRHSs _) = panic "checkCmdGRHSs"
1396
1397 checkCmdGRHS :: LGRHS GhcPs (LHsExpr GhcPs) -> P (LGRHS GhcPs (LHsCmd GhcPs))
1398 checkCmdGRHS = locMap $ const convert
1399 where
1400 convert (GRHS x stmts e) = do
1401 c <- checkCommand e
1402 -- cmdStmts <- mapM checkCmdLStmt stmts
1403 return $ GRHS x {- cmdStmts -} stmts c
1404 convert (XGRHS _) = panic "checkCmdGRHS"
1405
1406
1407 cmdFail :: SrcSpan -> HsExpr GhcPs -> P a
1408 cmdFail loc e = parseErrorSDoc loc (text "Parse error in command:" <+> ppr e)
1409 cmdStmtFail :: SrcSpan -> Stmt GhcPs (LHsExpr GhcPs) -> P a
1410 cmdStmtFail loc e = parseErrorSDoc loc
1411 (text "Parse error in command statement:" <+> ppr e)
1412
1413 ---------------------------------------------------------------------------
1414 -- Miscellaneous utilities
1415
1416 checkPrecP :: Located (SourceText,Int) -> P (Located (SourceText,Int))
1417 checkPrecP (L l (src,i))
1418 | 0 <= i && i <= maxPrecedence = return (L l (src,i))
1419 | otherwise
1420 = parseErrorSDoc l (text ("Precedence out of range: " ++ show i))
1421
1422 mkRecConstrOrUpdate
1423 :: LHsExpr GhcPs
1424 -> SrcSpan
1425 -> ([LHsRecField GhcPs (LHsExpr GhcPs)], Bool)
1426 -> P (HsExpr GhcPs)
1427
1428 mkRecConstrOrUpdate (L l (HsVar _ (L _ c))) _ (fs,dd)
1429 | isRdrDataCon c
1430 = return (mkRdrRecordCon (L l c) (mk_rec_fields fs dd))
1431 mkRecConstrOrUpdate exp@(L l _) _ (fs,dd)
1432 | dd = parseErrorSDoc l (text "You cannot use `..' in a record update")
1433 | otherwise = return (mkRdrRecordUpd exp (map (fmap mk_rec_upd_field) fs))
1434
1435 mkRdrRecordUpd :: LHsExpr GhcPs -> [LHsRecUpdField GhcPs] -> HsExpr GhcPs
1436 mkRdrRecordUpd exp flds
1437 = RecordUpd { rupd_ext = noExt
1438 , rupd_expr = exp
1439 , rupd_flds = flds }
1440
1441 mkRdrRecordCon :: Located RdrName -> HsRecordBinds GhcPs -> HsExpr GhcPs
1442 mkRdrRecordCon con flds
1443 = RecordCon { rcon_ext = noExt, rcon_con_name = con, rcon_flds = flds }
1444
1445 mk_rec_fields :: [LHsRecField id arg] -> Bool -> HsRecFields id arg
1446 mk_rec_fields fs False = HsRecFields { rec_flds = fs, rec_dotdot = Nothing }
1447 mk_rec_fields fs True = HsRecFields { rec_flds = fs, rec_dotdot = Just (length fs) }
1448
1449 mk_rec_upd_field :: HsRecField GhcPs (LHsExpr GhcPs) -> HsRecUpdField GhcPs
1450 mk_rec_upd_field (HsRecField (L loc (FieldOcc _ rdr)) arg pun)
1451 = HsRecField (L loc (Unambiguous noExt rdr)) arg pun
1452 mk_rec_upd_field (HsRecField (L _ (XFieldOcc _)) _ _)
1453 = panic "mk_rec_upd_field"
1454
1455 mkInlinePragma :: SourceText -> (InlineSpec, RuleMatchInfo) -> Maybe Activation
1456 -> InlinePragma
1457 -- The (Maybe Activation) is because the user can omit
1458 -- the activation spec (and usually does)
1459 mkInlinePragma src (inl, match_info) mb_act
1460 = InlinePragma { inl_src = src -- Note [Pragma source text] in BasicTypes
1461 , inl_inline = inl
1462 , inl_sat = Nothing
1463 , inl_act = act
1464 , inl_rule = match_info }
1465 where
1466 act = case mb_act of
1467 Just act -> act
1468 Nothing -> -- No phase specified
1469 case inl of
1470 NoInline -> NeverActive
1471 _other -> AlwaysActive
1472
1473 -----------------------------------------------------------------------------
1474 -- utilities for foreign declarations
1475
1476 -- construct a foreign import declaration
1477 --
1478 mkImport :: Located CCallConv
1479 -> Located Safety
1480 -> (Located StringLiteral, Located RdrName, LHsSigType GhcPs)
1481 -> P (HsDecl GhcPs)
1482 mkImport cconv safety (L loc (StringLiteral esrc entity), v, ty) =
1483 case cconv of
1484 L _ CCallConv -> mkCImport
1485 L _ CApiConv -> mkCImport
1486 L _ StdCallConv -> mkCImport
1487 L _ PrimCallConv -> mkOtherImport
1488 L _ JavaScriptCallConv -> mkOtherImport
1489 where
1490 -- Parse a C-like entity string of the following form:
1491 -- "[static] [chname] [&] [cid]" | "dynamic" | "wrapper"
1492 -- If 'cid' is missing, the function name 'v' is used instead as symbol
1493 -- name (cf section 8.5.1 in Haskell 2010 report).
1494 mkCImport = do
1495 let e = unpackFS entity
1496 case parseCImport cconv safety (mkExtName (unLoc v)) e (L loc esrc) of
1497 Nothing -> parseErrorSDoc loc (text "Malformed entity string")
1498 Just importSpec -> returnSpec importSpec
1499
1500 -- currently, all the other import conventions only support a symbol name in
1501 -- the entity string. If it is missing, we use the function name instead.
1502 mkOtherImport = returnSpec importSpec
1503 where
1504 entity' = if nullFS entity
1505 then mkExtName (unLoc v)
1506 else entity
1507 funcTarget = CFunction (StaticTarget esrc entity' Nothing True)
1508 importSpec = CImport cconv safety Nothing funcTarget (L loc esrc)
1509
1510 returnSpec spec = return $ ForD noExt $ ForeignImport
1511 { fd_i_ext = noExt
1512 , fd_name = v
1513 , fd_sig_ty = ty
1514 , fd_fi = spec
1515 }
1516
1517
1518
1519 -- the string "foo" is ambiguous: either a header or a C identifier. The
1520 -- C identifier case comes first in the alternatives below, so we pick
1521 -- that one.
1522 parseCImport :: Located CCallConv -> Located Safety -> FastString -> String
1523 -> Located SourceText
1524 -> Maybe ForeignImport
1525 parseCImport cconv safety nm str sourceText =
1526 listToMaybe $ map fst $ filter (null.snd) $
1527 readP_to_S parse str
1528 where
1529 parse = do
1530 skipSpaces
1531 r <- choice [
1532 string "dynamic" >> return (mk Nothing (CFunction DynamicTarget)),
1533 string "wrapper" >> return (mk Nothing CWrapper),
1534 do optional (token "static" >> skipSpaces)
1535 ((mk Nothing <$> cimp nm) +++
1536 (do h <- munch1 hdr_char
1537 skipSpaces
1538 mk (Just (Header (SourceText h) (mkFastString h)))
1539 <$> cimp nm))
1540 ]
1541 skipSpaces
1542 return r
1543
1544 token str = do _ <- string str
1545 toks <- look
1546 case toks of
1547 c : _
1548 | id_char c -> pfail
1549 _ -> return ()
1550
1551 mk h n = CImport cconv safety h n sourceText
1552
1553 hdr_char c = not (isSpace c) -- header files are filenames, which can contain
1554 -- pretty much any char (depending on the platform),
1555 -- so just accept any non-space character
1556 id_first_char c = isAlpha c || c == '_'
1557 id_char c = isAlphaNum c || c == '_'
1558
1559 cimp nm = (ReadP.char '&' >> skipSpaces >> CLabel <$> cid)
1560 +++ (do isFun <- case cconv of
1561 L _ CApiConv ->
1562 option True
1563 (do token "value"
1564 skipSpaces
1565 return False)
1566 _ -> return True
1567 cid' <- cid
1568 return (CFunction (StaticTarget NoSourceText cid'
1569 Nothing isFun)))
1570 where
1571 cid = return nm +++
1572 (do c <- satisfy id_first_char
1573 cs <- many (satisfy id_char)
1574 return (mkFastString (c:cs)))
1575
1576
1577 -- construct a foreign export declaration
1578 --
1579 mkExport :: Located CCallConv
1580 -> (Located StringLiteral, Located RdrName, LHsSigType GhcPs)
1581 -> P (HsDecl GhcPs)
1582 mkExport (L lc cconv) (L le (StringLiteral esrc entity), v, ty)
1583 = return $ ForD noExt $
1584 ForeignExport { fd_e_ext = noExt, fd_name = v, fd_sig_ty = ty
1585 , fd_fe = CExport (L lc (CExportStatic esrc entity' cconv))
1586 (L le esrc) }
1587 where
1588 entity' | nullFS entity = mkExtName (unLoc v)
1589 | otherwise = entity
1590
1591 -- Supplying the ext_name in a foreign decl is optional; if it
1592 -- isn't there, the Haskell name is assumed. Note that no transformation
1593 -- of the Haskell name is then performed, so if you foreign export (++),
1594 -- it's external name will be "++". Too bad; it's important because we don't
1595 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
1596 --
1597 mkExtName :: RdrName -> CLabelString
1598 mkExtName rdrNm = mkFastString (occNameString (rdrNameOcc rdrNm))
1599
1600 --------------------------------------------------------------------------------
1601 -- Help with module system imports/exports
1602
1603 data ImpExpSubSpec = ImpExpAbs
1604 | ImpExpAll
1605 | ImpExpList [Located ImpExpQcSpec]
1606 | ImpExpAllWith [Located ImpExpQcSpec]
1607
1608 data ImpExpQcSpec = ImpExpQcName (Located RdrName)
1609 | ImpExpQcType (Located RdrName)
1610 | ImpExpQcWildcard
1611
1612 mkModuleImpExp :: Located ImpExpQcSpec -> ImpExpSubSpec -> P (IE GhcPs)
1613 mkModuleImpExp (L l specname) subs =
1614 case subs of
1615 ImpExpAbs
1616 | isVarNameSpace (rdrNameSpace name)
1617 -> return $ IEVar noExt (L l (ieNameFromSpec specname))
1618 | otherwise -> IEThingAbs noExt . L l <$> nameT
1619 ImpExpAll -> IEThingAll noExt . L l <$> nameT
1620 ImpExpList xs ->
1621 (\newName -> IEThingWith noExt (L l newName) NoIEWildcard (wrapped xs) [])
1622 <$> nameT
1623 ImpExpAllWith xs ->
1624 do allowed <- extension patternSynonymsEnabled
1625 if allowed
1626 then
1627 let withs = map unLoc xs
1628 pos = maybe NoIEWildcard IEWildcard
1629 (findIndex isImpExpQcWildcard withs)
1630 ies = wrapped $ filter (not . isImpExpQcWildcard . unLoc) xs
1631 in (\newName
1632 -> IEThingWith noExt (L l newName) pos ies []) <$> nameT
1633 else parseErrorSDoc l
1634 (text "Illegal export form (use PatternSynonyms to enable)")
1635 where
1636 name = ieNameVal specname
1637 nameT =
1638 if isVarNameSpace (rdrNameSpace name)
1639 then parseErrorSDoc l
1640 (text "Expecting a type constructor but found a variable,"
1641 <+> quotes (ppr name) <> text "."
1642 $$ if isSymOcc $ rdrNameOcc name
1643 then text "If" <+> quotes (ppr name) <+> text "is a type constructor"
1644 <+> text "then enable ExplicitNamespaces and use the 'type' keyword."
1645 else empty)
1646 else return $ ieNameFromSpec specname
1647
1648 ieNameVal (ImpExpQcName ln) = unLoc ln
1649 ieNameVal (ImpExpQcType ln) = unLoc ln
1650 ieNameVal (ImpExpQcWildcard) = panic "ieNameVal got wildcard"
1651
1652 ieNameFromSpec (ImpExpQcName ln) = IEName ln
1653 ieNameFromSpec (ImpExpQcType ln) = IEType ln
1654 ieNameFromSpec (ImpExpQcWildcard) = panic "ieName got wildcard"
1655
1656 wrapped = map (\(L l x) -> L l (ieNameFromSpec x))
1657
1658 mkTypeImpExp :: Located RdrName -- TcCls or Var name space
1659 -> P (Located RdrName)
1660 mkTypeImpExp name =
1661 do allowed <- extension explicitNamespacesEnabled
1662 if allowed
1663 then return (fmap (`setRdrNameSpace` tcClsName) name)
1664 else parseErrorSDoc (getLoc name)
1665 (text "Illegal keyword 'type' (use ExplicitNamespaces to enable)")
1666
1667 checkImportSpec :: Located [LIE GhcPs] -> P (Located [LIE GhcPs])
1668 checkImportSpec ie@(L _ specs) =
1669 case [l | (L l (IEThingWith _ _ (IEWildcard _) _ _)) <- specs] of
1670 [] -> return ie
1671 (l:_) -> importSpecError l
1672 where
1673 importSpecError l =
1674 parseErrorSDoc l
1675 (text "Illegal import form, this syntax can only be used to bundle"
1676 $+$ text "pattern synonyms with types in module exports.")
1677
1678 -- In the correct order
1679 mkImpExpSubSpec :: [Located ImpExpQcSpec] -> P ([AddAnn], ImpExpSubSpec)
1680 mkImpExpSubSpec [] = return ([], ImpExpList [])
1681 mkImpExpSubSpec [L _ ImpExpQcWildcard] =
1682 return ([], ImpExpAll)
1683 mkImpExpSubSpec xs =
1684 if (any (isImpExpQcWildcard . unLoc) xs)
1685 then return $ ([], ImpExpAllWith xs)
1686 else return $ ([], ImpExpList xs)
1687
1688 isImpExpQcWildcard :: ImpExpQcSpec -> Bool
1689 isImpExpQcWildcard ImpExpQcWildcard = True
1690 isImpExpQcWildcard _ = False
1691
1692 -----------------------------------------------------------------------------
1693 -- Misc utils
1694
1695 parseErrorSDoc :: SrcSpan -> SDoc -> P a
1696 parseErrorSDoc span s = failSpanMsgP span s
1697
1698 -- | Hint about bang patterns, assuming @BangPatterns@ is off.
1699 hintBangPat :: SrcSpan -> HsExpr GhcPs -> P ()
1700 hintBangPat span e = do
1701 bang_on <- extension bangPatEnabled
1702 unless bang_on $
1703 parseErrorSDoc span
1704 (text "Illegal bang-pattern (use BangPatterns):" $$ ppr e)
1705
1706 data SumOrTuple
1707 = Sum ConTag Arity (LHsExpr GhcPs)
1708 | Tuple [LHsTupArg GhcPs]
1709
1710 mkSumOrTuple :: Boxity -> SrcSpan -> SumOrTuple -> P (HsExpr GhcPs)
1711
1712 -- Tuple
1713 mkSumOrTuple boxity _ (Tuple es) = return (ExplicitTuple noExt es boxity)
1714
1715 -- Sum
1716 mkSumOrTuple Unboxed _ (Sum alt arity e) =
1717 return (ExplicitSum noExt alt arity e)
1718 mkSumOrTuple Boxed l (Sum alt arity (L _ e)) =
1719 parseErrorSDoc l (hang (text "Boxed sums not supported:") 2 (ppr_boxed_sum alt arity e))
1720 where
1721 ppr_boxed_sum :: ConTag -> Arity -> HsExpr GhcPs -> SDoc
1722 ppr_boxed_sum alt arity e =
1723 text "(" <+> ppr_bars (alt - 1) <+> ppr e <+> ppr_bars (arity - alt) <+> text ")"
1724
1725 ppr_bars n = hsep (replicate n (Outputable.char '|'))