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