Tweak API Annotations for ConDeclGADT
[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 = noLoc $ 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, [AddAnn])
643 mkGadtDecl names ty
644 = (ConDeclGADT { con_g_ext = noExt
645 , con_names = names
646 , con_forall = L l $ 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 , anns1 ++ anns2)
653 where
654 (ty'@(L l _),anns1) = peel_parens ty []
655 (tvs, rho) = splitLHsForAllTy ty'
656 (mcxt, tau, anns2) = split_rho rho []
657
658 split_rho (L _ (HsQualTy { hst_ctxt = cxt, hst_body = tau })) ann
659 = (Just cxt, tau, ann)
660 split_rho (L l (HsParTy _ ty)) ann = split_rho ty (ann++mkParensApiAnn l)
661 split_rho tau ann = (Nothing, tau, ann)
662
663 (args, res_ty) = split_tau tau
664 args' = nudgeHsSrcBangs args
665
666 -- See Note [GADT abstract syntax] in HsDecls
667 split_tau (L _ (HsFunTy _ (L loc (HsRecTy _ rf)) res_ty))
668 = (RecCon (L loc rf), res_ty)
669 split_tau tau = (PrefixCon [], tau)
670
671 peel_parens (L l (HsParTy _ ty)) ann = peel_parens ty
672 (ann++mkParensApiAnn l)
673 peel_parens ty ann = (ty, ann)
674
675 nudgeHsSrcBangs :: HsConDeclDetails GhcPs -> HsConDeclDetails GhcPs
676 -- ^ This function ensures that fields with strictness or packedness
677 -- annotations put these annotations on an outer 'HsBangTy'.
678 --
679 -- The problem is that in the parser, strictness and packedness annotations
680 -- bind more tightly that docstrings. However, the expectation downstream of
681 -- the parser (by functions such as 'getBangType' and 'getBangStrictness')
682 -- is that docstrings bind more tightly so that 'HsBangTy' may end up as the
683 -- top-level type.
684 --
685 -- See #15206
686 nudgeHsSrcBangs details
687 = case details of
688 PrefixCon as -> PrefixCon (map go as)
689 RecCon r -> RecCon r
690 InfixCon a1 a2 -> InfixCon (go a1) (go a2)
691 where
692 go (L l (HsDocTy _ (L _ (HsBangTy _ s lty)) lds)) =
693 L l (HsBangTy noExt s (addCLoc lty lds (HsDocTy noExt lty lds)))
694 go lty = lty
695
696
697 setRdrNameSpace :: RdrName -> NameSpace -> RdrName
698 -- ^ This rather gruesome function is used mainly by the parser.
699 -- When parsing:
700 --
701 -- > data T a = T | T1 Int
702 --
703 -- we parse the data constructors as /types/ because of parser ambiguities,
704 -- so then we need to change the /type constr/ to a /data constr/
705 --
706 -- The exact-name case /can/ occur when parsing:
707 --
708 -- > data [] a = [] | a : [a]
709 --
710 -- For the exact-name case we return an original name.
711 setRdrNameSpace (Unqual occ) ns = Unqual (setOccNameSpace ns occ)
712 setRdrNameSpace (Qual m occ) ns = Qual m (setOccNameSpace ns occ)
713 setRdrNameSpace (Orig m occ) ns = Orig m (setOccNameSpace ns occ)
714 setRdrNameSpace (Exact n) ns
715 | Just thing <- wiredInNameTyThing_maybe n
716 = setWiredInNameSpace thing ns
717 -- Preserve Exact Names for wired-in things,
718 -- notably tuples and lists
719
720 | isExternalName n
721 = Orig (nameModule n) occ
722
723 | otherwise -- This can happen when quoting and then
724 -- splicing a fixity declaration for a type
725 = Exact (mkSystemNameAt (nameUnique n) occ (nameSrcSpan n))
726 where
727 occ = setOccNameSpace ns (nameOccName n)
728
729 setWiredInNameSpace :: TyThing -> NameSpace -> RdrName
730 setWiredInNameSpace (ATyCon tc) ns
731 | isDataConNameSpace ns
732 = ty_con_data_con tc
733 | isTcClsNameSpace ns
734 = Exact (getName tc) -- No-op
735
736 setWiredInNameSpace (AConLike (RealDataCon dc)) ns
737 | isTcClsNameSpace ns
738 = data_con_ty_con dc
739 | isDataConNameSpace ns
740 = Exact (getName dc) -- No-op
741
742 setWiredInNameSpace thing ns
743 = pprPanic "setWiredinNameSpace" (pprNameSpace ns <+> ppr thing)
744
745 ty_con_data_con :: TyCon -> RdrName
746 ty_con_data_con tc
747 | isTupleTyCon tc
748 , Just dc <- tyConSingleDataCon_maybe tc
749 = Exact (getName dc)
750
751 | tc `hasKey` listTyConKey
752 = Exact nilDataConName
753
754 | otherwise -- See Note [setRdrNameSpace for wired-in names]
755 = Unqual (setOccNameSpace srcDataName (getOccName tc))
756
757 data_con_ty_con :: DataCon -> RdrName
758 data_con_ty_con dc
759 | let tc = dataConTyCon dc
760 , isTupleTyCon tc
761 = Exact (getName tc)
762
763 | dc `hasKey` nilDataConKey
764 = Exact listTyConName
765
766 | otherwise -- See Note [setRdrNameSpace for wired-in names]
767 = Unqual (setOccNameSpace tcClsName (getOccName dc))
768
769
770 {- Note [setRdrNameSpace for wired-in names]
771 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
772 In GHC.Types, which declares (:), we have
773 infixr 5 :
774 The ambiguity about which ":" is meant is resolved by parsing it as a
775 data constructor, but then using dataTcOccs to try the type constructor too;
776 and that in turn calls setRdrNameSpace to change the name-space of ":" to
777 tcClsName. There isn't a corresponding ":" type constructor, but it's painful
778 to make setRdrNameSpace partial, so we just make an Unqual name instead. It
779 really doesn't matter!
780 -}
781
782 checkTyVarsP :: SDoc -> SDoc -> Located RdrName -> [LHsType GhcPs]
783 -> P (LHsQTyVars GhcPs)
784 -- Same as checkTyVars, but in the P monad
785 checkTyVarsP pp_what equals_or_where tc tparms
786 = eitherToP $ checkTyVars pp_what equals_or_where tc tparms
787
788 eitherToP :: Either (SrcSpan, SDoc) a -> P a
789 -- Adapts the Either monad to the P monad
790 eitherToP (Left (loc, doc)) = parseErrorSDoc loc doc
791 eitherToP (Right thing) = return thing
792
793 checkTyVars :: SDoc -> SDoc -> Located RdrName -> [LHsType GhcPs]
794 -> Either (SrcSpan, SDoc) (LHsQTyVars GhcPs)
795 -- Check whether the given list of type parameters are all type variables
796 -- (possibly with a kind signature)
797 -- We use the Either monad because it's also called (via mkATDefault) from
798 -- Convert.hs
799 checkTyVars pp_what equals_or_where tc tparms
800 = do { tvs <- mapM chk tparms
801 ; return (mkHsQTvs tvs) }
802 where
803 chk (L _ (HsParTy _ ty)) = chk ty
804
805 -- Check that the name space is correct!
806 chk (L l (HsKindSig _ (L lv (HsTyVar _ _ (L _ tv))) k))
807 | isRdrTyVar tv = return (L l (KindedTyVar noExt (L lv tv) k))
808 chk (L l (HsTyVar _ _ (L ltv tv)))
809 | isRdrTyVar tv = return (L l (UserTyVar noExt (L ltv tv)))
810 chk t@(L loc _)
811 = Left (loc,
812 vcat [ text "Unexpected type" <+> quotes (ppr t)
813 , text "In the" <+> pp_what <+> ptext (sLit "declaration for") <+> quotes (ppr tc)
814 , vcat[ (text "A" <+> pp_what <+> ptext (sLit "declaration should have form"))
815 , nest 2 (pp_what <+> ppr tc
816 <+> hsep (map text (takeList tparms allNameStrings))
817 <+> equals_or_where) ] ])
818
819 whereDots, equalsDots :: SDoc
820 -- Second argument to checkTyVars
821 whereDots = text "where ..."
822 equalsDots = text "= ..."
823
824 checkDatatypeContext :: Maybe (LHsContext GhcPs) -> P ()
825 checkDatatypeContext Nothing = return ()
826 checkDatatypeContext (Just (L loc c))
827 = do allowed <- extension datatypeContextsEnabled
828 unless allowed $
829 parseErrorSDoc loc
830 (text "Illegal datatype context (use DatatypeContexts):" <+>
831 pprHsContext c)
832
833 checkRecordSyntax :: Outputable a => Located a -> P (Located a)
834 checkRecordSyntax lr@(L loc r)
835 = do allowed <- extension traditionalRecordSyntaxEnabled
836 if allowed
837 then return lr
838 else parseErrorSDoc loc
839 (text "Illegal record syntax (use TraditionalRecordSyntax):" <+>
840 ppr r)
841
842 -- | Check if the gadt_constrlist is empty. Only raise parse error for
843 -- `data T where` to avoid affecting existing error message, see #8258.
844 checkEmptyGADTs :: Located ([AddAnn], [LConDecl GhcPs])
845 -> P (Located ([AddAnn], [LConDecl GhcPs]))
846 checkEmptyGADTs gadts@(L span (_, [])) -- Empty GADT declaration.
847 = do opts <- fmap options getPState
848 if LangExt.GADTSyntax `extopt` opts -- GADTs implies GADTSyntax
849 then return gadts
850 else parseErrorSDoc span $ vcat
851 [ text "Illegal keyword 'where' in data declaration"
852 , text "Perhaps you intended to use GADTs or a similar language"
853 , text "extension to enable syntax: data T where"
854 ]
855 checkEmptyGADTs gadts = return gadts -- Ordinary GADT declaration.
856
857 checkTyClHdr :: Bool -- True <=> class header
858 -- False <=> type header
859 -> LHsType GhcPs
860 -> P (Located RdrName, -- the head symbol (type or class name)
861 [LHsType GhcPs], -- parameters of head symbol
862 LexicalFixity, -- the declaration is in infix format
863 [AddAnn]) -- API Annotation for HsParTy when stripping parens
864 -- Well-formedness check and decomposition of type and class heads.
865 -- Decomposes T ty1 .. tyn into (T, [ty1, ..., tyn])
866 -- Int :*: Bool into (:*:, [Int, Bool])
867 -- returning the pieces
868 checkTyClHdr is_cls ty
869 = goL ty [] [] Prefix
870 where
871 goL (L l ty) acc ann fix = go l ty acc ann fix
872
873 -- workaround to define '*' despite StarIsType
874 go _ (HsParTy _ (L l (HsStarTy _ isUni))) acc ann fix
875 = do { warnStarBndr l
876 ; let name = mkOccName tcClsName (if isUni then "★" else "*")
877 ; return (L l (Unqual name), acc, fix, ann) }
878
879 go l (HsTyVar _ _ (L _ tc)) acc ann fix
880 | isRdrTc tc = return (L l tc, acc, fix, ann)
881 go _ (HsOpTy _ t1 ltc@(L _ tc) t2) acc ann _fix
882 | isRdrTc tc = return (ltc, t1:t2:acc, Infix, ann)
883 go l (HsParTy _ ty) acc ann fix = goL ty acc (ann ++mkParensApiAnn l) fix
884 go _ (HsAppTy _ t1 t2) acc ann fix = goL t1 (t2:acc) ann fix
885
886 go l (HsTupleTy _ HsBoxedOrConstraintTuple ts) [] ann fix
887 = return (L l (nameRdrName tup_name), ts, fix, ann)
888 where
889 arity = length ts
890 tup_name | is_cls = cTupleTyConName arity
891 | otherwise = getName (tupleTyCon Boxed arity)
892 -- See Note [Unit tuples] in HsTypes (TODO: is this still relevant?)
893 go l _ _ _ _
894 = parseErrorSDoc l (text "Malformed head of type or class declaration:"
895 <+> ppr ty)
896
897 -- | Yield a parse error if we have a function applied directly to a do block
898 -- etc. and BlockArguments is not enabled.
899 checkBlockArguments :: LHsExpr GhcPs -> P ()
900 checkBlockArguments expr = case unLoc expr of
901 HsDo _ DoExpr _ -> check "do block"
902 HsDo _ MDoExpr _ -> check "mdo block"
903 HsLam {} -> check "lambda expression"
904 HsCase {} -> check "case expression"
905 HsLamCase {} -> check "lambda-case expression"
906 HsLet {} -> check "let expression"
907 HsIf {} -> check "if expression"
908 HsProc {} -> check "proc expression"
909 _ -> return ()
910 where
911 check element = do
912 pState <- getPState
913 unless (extopt LangExt.BlockArguments (options pState)) $
914 parseErrorSDoc (getLoc expr) $
915 text "Unexpected " <> text element <> text " in function application:"
916 $$ nest 4 (ppr expr)
917 $$ text "You could write it with parentheses"
918 $$ text "Or perhaps you meant to enable BlockArguments?"
919
920 -- | Validate the context constraints and break up a context into a list
921 -- of predicates.
922 --
923 -- @
924 -- (Eq a, Ord b) --> [Eq a, Ord b]
925 -- Eq a --> [Eq a]
926 -- (Eq a) --> [Eq a]
927 -- (((Eq a))) --> [Eq a]
928 -- @
929 checkContext :: LHsType GhcPs -> P ([AddAnn],LHsContext GhcPs)
930 checkContext (L l orig_t)
931 = check [] (L l orig_t)
932 where
933 check anns (L lp (HsTupleTy _ HsBoxedOrConstraintTuple ts))
934 -- (Eq a, Ord b) shows up as a tuple type. Only boxed tuples can
935 -- be used as context constraints.
936 = return (anns ++ mkParensApiAnn lp,L l ts) -- Ditto ()
937
938 check anns (L lp1 (HsParTy _ ty))
939 -- to be sure HsParTy doesn't get into the way
940 = check anns' ty
941 where anns' = if l == lp1 then anns
942 else (anns ++ mkParensApiAnn lp1)
943
944 -- no need for anns, returning original
945 check _anns t = checkNoDocs msg t *> return ([],L l [L l orig_t])
946
947 msg = text "data constructor context"
948
949 -- | Check recursively if there are any 'HsDocTy's in the given type.
950 -- This only works on a subset of types produced by 'btype_no_ops'
951 checkNoDocs :: SDoc -> LHsType GhcPs -> P ()
952 checkNoDocs msg ty = go ty
953 where
954 go (L _ (HsAppTy _ t1 t2)) = go t1 *> go t2
955 go (L l (HsDocTy _ t ds)) = parseErrorSDoc l $ hsep
956 [ text "Unexpected haddock", quotes (ppr ds)
957 , text "on", msg, quotes (ppr t) ]
958 go _ = pure ()
959
960 -- -------------------------------------------------------------------------
961 -- Checking Patterns.
962
963 -- We parse patterns as expressions and check for valid patterns below,
964 -- converting the expression into a pattern at the same time.
965
966 checkPattern :: SDoc -> LHsExpr GhcPs -> P (LPat GhcPs)
967 checkPattern msg e = checkLPat msg e
968
969 checkPatterns :: SDoc -> [LHsExpr GhcPs] -> P [LPat GhcPs]
970 checkPatterns msg es = mapM (checkPattern msg) es
971
972 checkLPat :: SDoc -> LHsExpr GhcPs -> P (LPat GhcPs)
973 checkLPat msg e@(L l _) = checkPat msg l e []
974
975 checkPat :: SDoc -> SrcSpan -> LHsExpr GhcPs -> [LPat GhcPs]
976 -> P (LPat GhcPs)
977 checkPat _ loc (L l e@(HsVar _ (L _ c))) args
978 | isRdrDataCon c = return (L loc (ConPatIn (L l c) (PrefixCon args)))
979 | not (null args) && patIsRec c =
980 patFail (text "Perhaps you intended to use RecursiveDo") l e
981 checkPat msg loc e args -- OK to let this happen even if bang-patterns
982 -- are not enabled, because there is no valid
983 -- non-bang-pattern parse of (C ! e)
984 | Just (e', args') <- splitBang e
985 = do { args'' <- checkPatterns msg args'
986 ; checkPat msg loc e' (args'' ++ args) }
987 checkPat msg loc (L _ (HsApp _ f e)) args
988 = do p <- checkLPat msg e
989 checkPat msg loc f (p : args)
990 checkPat msg loc (L _ e) []
991 = do p <- checkAPat msg loc e
992 return (L loc p)
993 checkPat msg loc e _
994 = patFail msg loc (unLoc e)
995
996 checkAPat :: SDoc -> SrcSpan -> HsExpr GhcPs -> P (Pat GhcPs)
997 checkAPat msg loc e0 = do
998 pState <- getPState
999 let opts = options pState
1000 case e0 of
1001 EWildPat _ -> return (WildPat noExt)
1002 HsVar _ x -> return (VarPat noExt x)
1003 HsLit _ (HsStringPrim _ _) -- (#13260)
1004 -> parseErrorSDoc loc (text "Illegal unboxed string literal in pattern:" $$ ppr e0)
1005
1006 HsLit _ l -> return (LitPat noExt l)
1007
1008 -- Overloaded numeric patterns (e.g. f 0 x = x)
1009 -- Negation is recorded separately, so that the literal is zero or +ve
1010 -- NB. Negative *primitive* literals are already handled by the lexer
1011 HsOverLit _ pos_lit -> return (mkNPat (L loc pos_lit) Nothing)
1012 NegApp _ (L l (HsOverLit _ pos_lit)) _
1013 -> return (mkNPat (L l pos_lit) (Just noSyntaxExpr))
1014
1015 SectionR _ (L lb (HsVar _ (L _ bang))) e -- (! x)
1016 | bang == bang_RDR
1017 -> do { hintBangPat loc e0
1018 ; e' <- checkLPat msg e
1019 ; addAnnotation loc AnnBang lb
1020 ; return (BangPat noExt e') }
1021
1022 ELazyPat _ e -> checkLPat msg e >>= (return . (LazyPat noExt))
1023 EAsPat _ n e -> checkLPat msg e >>= (return . (AsPat noExt) n)
1024 -- view pattern is well-formed if the pattern is
1025 EViewPat _ expr patE -> checkLPat msg patE >>=
1026 (return . (\p -> ViewPat noExt expr p))
1027 ExprWithTySig t e -> do e <- checkLPat msg e
1028 return (SigPat t e)
1029
1030 -- n+k patterns
1031 OpApp _ (L nloc (HsVar _ (L _ n))) (L _ (HsVar _ (L _ plus)))
1032 (L lloc (HsOverLit _ lit@(OverLit {ol_val = HsIntegral {}})))
1033 | extopt LangExt.NPlusKPatterns opts && (plus == plus_RDR)
1034 -> return (mkNPlusKPat (L nloc n) (L lloc lit))
1035
1036 OpApp _ l (L cl (HsVar _ (L _ c))) r
1037 | isDataOcc (rdrNameOcc c) -> do
1038 l <- checkLPat msg l
1039 r <- checkLPat msg r
1040 return (ConPatIn (L cl c) (InfixCon l r))
1041
1042 OpApp {} -> patFail msg loc e0
1043
1044 ExplicitList _ _ es -> do ps <- mapM (checkLPat msg) es
1045 return (ListPat noExt ps)
1046
1047 HsPar _ e -> checkLPat msg e >>= (return . (ParPat noExt))
1048
1049 ExplicitTuple _ es b
1050 | all tupArgPresent es -> do ps <- mapM (checkLPat msg)
1051 [e | L _ (Present _ e) <- es]
1052 return (TuplePat noExt ps b)
1053 | otherwise -> parseErrorSDoc loc (text "Illegal tuple section in pattern:" $$ ppr e0)
1054
1055 ExplicitSum _ alt arity expr -> do
1056 p <- checkLPat msg expr
1057 return (SumPat noExt p alt arity)
1058
1059 RecordCon { rcon_con_name = c, rcon_flds = HsRecFields fs dd }
1060 -> do fs <- mapM (checkPatField msg) fs
1061 return (ConPatIn c (RecCon (HsRecFields fs dd)))
1062 HsSpliceE _ s | not (isTypedSplice s)
1063 -> return (SplicePat noExt s)
1064 _ -> patFail msg loc e0
1065
1066 placeHolderPunRhs :: LHsExpr GhcPs
1067 -- The RHS of a punned record field will be filled in by the renamer
1068 -- It's better not to make it an error, in case we want to print it when debugging
1069 placeHolderPunRhs = noLoc (HsVar noExt (noLoc pun_RDR))
1070
1071 plus_RDR, bang_RDR, pun_RDR :: RdrName
1072 plus_RDR = mkUnqual varName (fsLit "+") -- Hack
1073 bang_RDR = mkUnqual varName (fsLit "!") -- Hack
1074 pun_RDR = mkUnqual varName (fsLit "pun-right-hand-side")
1075
1076 checkPatField :: SDoc -> LHsRecField GhcPs (LHsExpr GhcPs)
1077 -> P (LHsRecField GhcPs (LPat GhcPs))
1078 checkPatField msg (L l fld) = do p <- checkLPat msg (hsRecFieldArg fld)
1079 return (L l (fld { hsRecFieldArg = p }))
1080
1081 patFail :: SDoc -> SrcSpan -> HsExpr GhcPs -> P a
1082 patFail msg loc e = parseErrorSDoc loc err
1083 where err = text "Parse error in pattern:" <+> ppr e
1084 $$ msg
1085
1086 patIsRec :: RdrName -> Bool
1087 patIsRec e = e == mkUnqual varName (fsLit "rec")
1088
1089
1090 ---------------------------------------------------------------------------
1091 -- Check Equation Syntax
1092
1093 checkValDef :: SDoc
1094 -> SrcStrictness
1095 -> LHsExpr GhcPs
1096 -> Maybe (LHsType GhcPs)
1097 -> Located (a,GRHSs GhcPs (LHsExpr GhcPs))
1098 -> P ([AddAnn],HsBind GhcPs)
1099
1100 checkValDef msg _strictness lhs (Just sig) grhss
1101 -- x :: ty = rhs parses as a *pattern* binding
1102 = checkPatBind msg (L (combineLocs lhs sig)
1103 (ExprWithTySig (mkLHsSigWcType sig) lhs)) grhss
1104
1105 checkValDef msg strictness lhs Nothing g@(L l (_,grhss))
1106 = do { mb_fun <- isFunLhs lhs
1107 ; case mb_fun of
1108 Just (fun, is_infix, pats, ann) ->
1109 checkFunBind msg strictness ann (getLoc lhs)
1110 fun is_infix pats (L l grhss)
1111 Nothing -> checkPatBind msg lhs g }
1112
1113 checkFunBind :: SDoc
1114 -> SrcStrictness
1115 -> [AddAnn]
1116 -> SrcSpan
1117 -> Located RdrName
1118 -> LexicalFixity
1119 -> [LHsExpr GhcPs]
1120 -> Located (GRHSs GhcPs (LHsExpr GhcPs))
1121 -> P ([AddAnn],HsBind GhcPs)
1122 checkFunBind msg strictness ann lhs_loc fun is_infix pats (L rhs_span grhss)
1123 = do ps <- checkPatterns msg pats
1124 let match_span = combineSrcSpans lhs_loc rhs_span
1125 -- Add back the annotations stripped from any HsPar values in the lhs
1126 -- mapM_ (\a -> a match_span) ann
1127 return (ann, makeFunBind fun
1128 [L match_span (Match { m_ext = noExt
1129 , m_ctxt = FunRhs { mc_fun = fun
1130 , mc_fixity = is_infix
1131 , mc_strictness = strictness }
1132 , m_pats = ps
1133 , m_grhss = grhss })])
1134 -- The span of the match covers the entire equation.
1135 -- That isn't quite right, but it'll do for now.
1136
1137 makeFunBind :: Located RdrName -> [LMatch GhcPs (LHsExpr GhcPs)]
1138 -> HsBind GhcPs
1139 -- Like HsUtils.mkFunBind, but we need to be able to set the fixity too
1140 makeFunBind fn ms
1141 = FunBind { fun_ext = noExt,
1142 fun_id = fn,
1143 fun_matches = mkMatchGroup FromSource ms,
1144 fun_co_fn = idHsWrapper,
1145 fun_tick = [] }
1146
1147 checkPatBind :: SDoc
1148 -> LHsExpr GhcPs
1149 -> Located (a,GRHSs GhcPs (LHsExpr GhcPs))
1150 -> P ([AddAnn],HsBind GhcPs)
1151 checkPatBind msg lhs (L _ (_,grhss))
1152 = do { lhs <- checkPattern msg lhs
1153 ; return ([],PatBind noExt lhs grhss
1154 ([],[])) }
1155
1156 checkValSigLhs :: LHsExpr GhcPs -> P (Located RdrName)
1157 checkValSigLhs (L _ (HsVar _ lrdr@(L _ v)))
1158 | isUnqual v
1159 , not (isDataOcc (rdrNameOcc v))
1160 = return lrdr
1161
1162 checkValSigLhs lhs@(L l _)
1163 = parseErrorSDoc l ((text "Invalid type signature:" <+>
1164 ppr lhs <+> text ":: ...")
1165 $$ text hint)
1166 where
1167 hint | foreign_RDR `looks_like` lhs
1168 = "Perhaps you meant to use ForeignFunctionInterface?"
1169 | default_RDR `looks_like` lhs
1170 = "Perhaps you meant to use DefaultSignatures?"
1171 | pattern_RDR `looks_like` lhs
1172 = "Perhaps you meant to use PatternSynonyms?"
1173 | otherwise
1174 = "Should be of form <variable> :: <type>"
1175
1176 -- A common error is to forget the ForeignFunctionInterface flag
1177 -- so check for that, and suggest. cf Trac #3805
1178 -- Sadly 'foreign import' still barfs 'parse error' because 'import' is a keyword
1179 looks_like s (L _ (HsVar _ (L _ v))) = v == s
1180 looks_like s (L _ (HsApp _ lhs _)) = looks_like s lhs
1181 looks_like _ _ = False
1182
1183 foreign_RDR = mkUnqual varName (fsLit "foreign")
1184 default_RDR = mkUnqual varName (fsLit "default")
1185 pattern_RDR = mkUnqual varName (fsLit "pattern")
1186
1187
1188 checkDoAndIfThenElse :: LHsExpr GhcPs
1189 -> Bool
1190 -> LHsExpr GhcPs
1191 -> Bool
1192 -> LHsExpr GhcPs
1193 -> P ()
1194 checkDoAndIfThenElse guardExpr semiThen thenExpr semiElse elseExpr
1195 | semiThen || semiElse
1196 = do pState <- getPState
1197 unless (extopt LangExt.DoAndIfThenElse (options pState)) $ do
1198 parseErrorSDoc (combineLocs guardExpr elseExpr)
1199 (text "Unexpected semi-colons in conditional:"
1200 $$ nest 4 expr
1201 $$ text "Perhaps you meant to use DoAndIfThenElse?")
1202 | otherwise = return ()
1203 where pprOptSemi True = semi
1204 pprOptSemi False = empty
1205 expr = text "if" <+> ppr guardExpr <> pprOptSemi semiThen <+>
1206 text "then" <+> ppr thenExpr <> pprOptSemi semiElse <+>
1207 text "else" <+> ppr elseExpr
1208
1209
1210 -- The parser left-associates, so there should
1211 -- not be any OpApps inside the e's
1212 splitBang :: LHsExpr GhcPs -> Maybe (LHsExpr GhcPs, [LHsExpr GhcPs])
1213 -- Splits (f ! g a b) into (f, [(! g), a, b])
1214 splitBang (L _ (OpApp _ l_arg bang@(L _ (HsVar _ (L _ op))) r_arg))
1215 | op == bang_RDR = Just (l_arg, L l' (SectionR noExt bang arg1) : argns)
1216 where
1217 l' = combineLocs bang arg1
1218 (arg1,argns) = split_bang r_arg []
1219 split_bang (L _ (HsApp _ f e)) es = split_bang f (e:es)
1220 split_bang e es = (e,es)
1221 splitBang _ = Nothing
1222
1223 isFunLhs :: LHsExpr GhcPs
1224 -> P (Maybe (Located RdrName, LexicalFixity, [LHsExpr GhcPs],[AddAnn]))
1225 -- A variable binding is parsed as a FunBind.
1226 -- Just (fun, is_infix, arg_pats) if e is a function LHS
1227 --
1228 -- The whole LHS is parsed as a single expression.
1229 -- Any infix operators on the LHS will parse left-associatively
1230 -- E.g. f !x y !z
1231 -- will parse (rather strangely) as
1232 -- (f ! x y) ! z
1233 -- It's up to isFunLhs to sort out the mess
1234 --
1235 -- a .!. !b
1236
1237 isFunLhs e = go e [] []
1238 where
1239 go (L loc (HsVar _ (L _ f))) es ann
1240 | not (isRdrDataCon f) = return (Just (L loc f, Prefix, es, ann))
1241 go (L _ (HsApp _ f e)) es ann = go f (e:es) ann
1242 go (L l (HsPar _ e)) es@(_:_) ann = go e es (ann ++ mkParensApiAnn l)
1243
1244 -- Things of the form `!x` are also FunBinds
1245 -- See Note [FunBind vs PatBind]
1246 go (L _ (SectionR _ (L _ (HsVar _ (L _ bang))) (L l (HsVar _ (L _ var)))))
1247 [] ann
1248 | bang == bang_RDR
1249 , not (isRdrDataCon var) = return (Just (L l var, Prefix, [], ann))
1250
1251 -- For infix function defns, there should be only one infix *function*
1252 -- (though there may be infix *datacons* involved too). So we don't
1253 -- need fixity info to figure out which function is being defined.
1254 -- a `K1` b `op` c `K2` d
1255 -- must parse as
1256 -- (a `K1` b) `op` (c `K2` d)
1257 -- The renamer checks later that the precedences would yield such a parse.
1258 --
1259 -- There is a complication to deal with bang patterns.
1260 --
1261 -- ToDo: what about this?
1262 -- x + 1 `op` y = ...
1263
1264 go e@(L loc (OpApp _ l (L loc' (HsVar _ (L _ op))) r)) es ann
1265 | Just (e',es') <- splitBang e
1266 = do { bang_on <- extension bangPatEnabled
1267 ; if bang_on then go e' (es' ++ es) ann
1268 else return (Just (L loc' op, Infix, (l:r:es), ann)) }
1269 -- No bangs; behave just like the next case
1270 | not (isRdrDataCon op) -- We have found the function!
1271 = return (Just (L loc' op, Infix, (l:r:es), ann))
1272 | otherwise -- Infix data con; keep going
1273 = do { mb_l <- go l es ann
1274 ; case mb_l of
1275 Just (op', Infix, j : k : es', ann')
1276 -> return (Just (op', Infix, j : op_app : es', ann'))
1277 where
1278 op_app = L loc (OpApp noExt k
1279 (L loc' (HsVar noExt (L loc' op))) r)
1280 _ -> return Nothing }
1281 go _ _ _ = return Nothing
1282
1283 -- | Transform a list of 'atype' with 'strict_mark' into
1284 -- HsOpTy's of 'eqTyCon_RDR':
1285 --
1286 -- [~a, ~b, c, ~d] ==> (~a) ~ ((b c) ~ d)
1287 --
1288 -- See Note [Parsing ~]
1289 splitTilde :: [LHsType GhcPs] -> P (LHsType GhcPs)
1290 splitTilde [] = panic "splitTilde"
1291 splitTilde (x:xs) = go x xs
1292 where
1293 -- We accumulate applications in the LHS until we encounter a laziness
1294 -- annotation. For example, if we have [Foo, x, y, ~Bar, z], the 'lhs'
1295 -- accumulator will become '(Foo x) y'. Then we strip the laziness
1296 -- annotation off 'Bar' and process the tail [Bar, z] recursively.
1297 --
1298 -- This leaves us with 'lhs = (Foo x) y' and 'rhs = Bar z'.
1299 -- In case the tail contained more laziness annotations, they would be
1300 -- processed similarly. This makes '~' right-associative.
1301 go lhs [] = return lhs
1302 go lhs (x:xs)
1303 | L loc (HsBangTy _ (HsSrcBang NoSourceText NoSrcUnpack SrcLazy) t) <- x
1304 = do { rhs <- splitTilde (t:xs)
1305 ; let r = mkLHsOpTy lhs (tildeOp loc) rhs
1306 ; moveAnnotations loc (getLoc r)
1307 ; return r }
1308 | otherwise
1309 = go (mkHsAppTy lhs x) xs
1310
1311 tildeOp loc = L (srcSpanFirstCharacter loc) eqTyCon_RDR
1312
1313 -- | Either an operator or an operand.
1314 data TyEl = TyElOpr RdrName | TyElOpd (HsType GhcPs)
1315
1316 -- | Merge a /reversed/ and /non-empty/ soup of operators and operands
1317 -- into a type.
1318 --
1319 -- User input: @F x y + G a b * X@
1320 -- Input to 'mergeOps': [X, *, b, a, G, +, y, x, F]
1321 -- Output corresponds to what the user wrote assuming all operators are of the
1322 -- same fixity and right-associative.
1323 --
1324 -- It's a bit silly that we're doing it at all, as the renamer will have to
1325 -- rearrange this, and it'd be easier to keep things separate.
1326 mergeOps :: [Located TyEl] -> P (LHsType GhcPs)
1327 mergeOps = go [] id
1328 where
1329 -- clause (a):
1330 -- when we encounter an operator, we must have accumulated
1331 -- something for its rhs, and there must be something left
1332 -- to build its lhs.
1333 go acc ops_acc (L l (TyElOpr op):xs) =
1334 if null acc || null xs
1335 then failOpFewArgs (L l op)
1336 else do { a <- splitTilde acc
1337 ; go [] (\c -> mkLHsOpTy c (L l op) (ops_acc a)) xs }
1338
1339 -- clause (b):
1340 -- whenever an operand is encountered, it is added to the accumulator
1341 go acc ops_acc (L l (TyElOpd a):xs) = go (L l a:acc) ops_acc xs
1342
1343 -- clause (c):
1344 -- at this point we know that 'acc' is non-empty because
1345 -- there are three options when 'acc' can be empty:
1346 -- 1. 'mergeOps' was called with an empty list, and this
1347 -- should never happen
1348 -- 2. 'mergeOps' was called with a list where the head is an
1349 -- operator, this is handled by clause (a)
1350 -- 3. 'mergeOps' was called with a list where the head is an
1351 -- operand, this is handled by clause (b)
1352 go acc ops_acc [] =
1353 do { a <- splitTilde acc
1354 ; return (ops_acc a) }
1355
1356 ---------------------------------------------------------------------------
1357 -- Check for monad comprehensions
1358 --
1359 -- If the flag MonadComprehensions is set, return a `MonadComp' context,
1360 -- otherwise use the usual `ListComp' context
1361
1362 checkMonadComp :: P (HsStmtContext Name)
1363 checkMonadComp = do
1364 pState <- getPState
1365 return $ if extopt LangExt.MonadComprehensions (options pState)
1366 then MonadComp
1367 else ListComp
1368
1369 -- -------------------------------------------------------------------------
1370 -- Checking arrow syntax.
1371
1372 -- We parse arrow syntax as expressions and check for valid syntax below,
1373 -- converting the expression into a pattern at the same time.
1374
1375 checkCommand :: LHsExpr GhcPs -> P (LHsCmd GhcPs)
1376 checkCommand lc = locMap checkCmd lc
1377
1378 locMap :: (SrcSpan -> a -> P b) -> Located a -> P (Located b)
1379 locMap f (L l a) = f l a >>= (\b -> return $ L l b)
1380
1381 checkCmd :: SrcSpan -> HsExpr GhcPs -> P (HsCmd GhcPs)
1382 checkCmd _ (HsArrApp _ e1 e2 haat b) =
1383 return $ HsCmdArrApp noExt e1 e2 haat b
1384 checkCmd _ (HsArrForm _ e mf args) =
1385 return $ HsCmdArrForm noExt e Prefix mf args
1386 checkCmd _ (HsApp _ e1 e2) =
1387 checkCommand e1 >>= (\c -> return $ HsCmdApp noExt c e2)
1388 checkCmd _ (HsLam _ mg) =
1389 checkCmdMatchGroup mg >>= (\mg' -> return $ HsCmdLam noExt mg')
1390 checkCmd _ (HsPar _ e) =
1391 checkCommand e >>= (\c -> return $ HsCmdPar noExt c)
1392 checkCmd _ (HsCase _ e mg) =
1393 checkCmdMatchGroup mg >>= (\mg' -> return $ HsCmdCase noExt e mg')
1394 checkCmd _ (HsIf _ cf ep et ee) = do
1395 pt <- checkCommand et
1396 pe <- checkCommand ee
1397 return $ HsCmdIf noExt cf ep pt pe
1398 checkCmd _ (HsLet _ lb e) =
1399 checkCommand e >>= (\c -> return $ HsCmdLet noExt lb c)
1400 checkCmd _ (HsDo _ DoExpr (L l stmts)) =
1401 mapM checkCmdLStmt stmts >>=
1402 (\ss -> return $ HsCmdDo noExt (L l ss) )
1403
1404 checkCmd _ (OpApp _ eLeft op eRight) = do
1405 -- OpApp becomes a HsCmdArrForm with a (Just fixity) in it
1406 c1 <- checkCommand eLeft
1407 c2 <- checkCommand eRight
1408 let arg1 = L (getLoc c1) $ HsCmdTop noExt c1
1409 arg2 = L (getLoc c2) $ HsCmdTop noExt c2
1410 return $ HsCmdArrForm noExt op Infix Nothing [arg1, arg2]
1411
1412 checkCmd l e = cmdFail l e
1413
1414 checkCmdLStmt :: ExprLStmt GhcPs -> P (CmdLStmt GhcPs)
1415 checkCmdLStmt = locMap checkCmdStmt
1416
1417 checkCmdStmt :: SrcSpan -> ExprStmt GhcPs -> P (CmdStmt GhcPs)
1418 checkCmdStmt _ (LastStmt x e s r) =
1419 checkCommand e >>= (\c -> return $ LastStmt x c s r)
1420 checkCmdStmt _ (BindStmt x pat e b f) =
1421 checkCommand e >>= (\c -> return $ BindStmt x pat c b f)
1422 checkCmdStmt _ (BodyStmt x e t g) =
1423 checkCommand e >>= (\c -> return $ BodyStmt x c t g)
1424 checkCmdStmt _ (LetStmt x bnds) = return $ LetStmt x bnds
1425 checkCmdStmt _ stmt@(RecStmt { recS_stmts = stmts }) = do
1426 ss <- mapM checkCmdLStmt stmts
1427 return $ stmt { recS_ext = noExt, recS_stmts = ss }
1428 checkCmdStmt _ (XStmtLR _) = panic "checkCmdStmt"
1429 checkCmdStmt l stmt = cmdStmtFail l stmt
1430
1431 checkCmdMatchGroup :: MatchGroup GhcPs (LHsExpr GhcPs)
1432 -> P (MatchGroup GhcPs (LHsCmd GhcPs))
1433 checkCmdMatchGroup mg@(MG { mg_alts = L l ms }) = do
1434 ms' <- mapM (locMap $ const convert) ms
1435 return $ mg { mg_ext = noExt, mg_alts = L l ms' }
1436 where convert match@(Match { m_grhss = grhss }) = do
1437 grhss' <- checkCmdGRHSs grhss
1438 return $ match { m_ext = noExt, m_grhss = grhss'}
1439 convert (XMatch _) = panic "checkCmdMatchGroup.XMatch"
1440 checkCmdMatchGroup (XMatchGroup {}) = panic "checkCmdMatchGroup"
1441
1442 checkCmdGRHSs :: GRHSs GhcPs (LHsExpr GhcPs) -> P (GRHSs GhcPs (LHsCmd GhcPs))
1443 checkCmdGRHSs (GRHSs x grhss binds) = do
1444 grhss' <- mapM checkCmdGRHS grhss
1445 return $ GRHSs x grhss' binds
1446 checkCmdGRHSs (XGRHSs _) = panic "checkCmdGRHSs"
1447
1448 checkCmdGRHS :: LGRHS GhcPs (LHsExpr GhcPs) -> P (LGRHS GhcPs (LHsCmd GhcPs))
1449 checkCmdGRHS = locMap $ const convert
1450 where
1451 convert (GRHS x stmts e) = do
1452 c <- checkCommand e
1453 -- cmdStmts <- mapM checkCmdLStmt stmts
1454 return $ GRHS x {- cmdStmts -} stmts c
1455 convert (XGRHS _) = panic "checkCmdGRHS"
1456
1457
1458 cmdFail :: SrcSpan -> HsExpr GhcPs -> P a
1459 cmdFail loc e = parseErrorSDoc loc (text "Parse error in command:" <+> ppr e)
1460 cmdStmtFail :: SrcSpan -> Stmt GhcPs (LHsExpr GhcPs) -> P a
1461 cmdStmtFail loc e = parseErrorSDoc loc
1462 (text "Parse error in command statement:" <+> ppr e)
1463
1464 ---------------------------------------------------------------------------
1465 -- Miscellaneous utilities
1466
1467 checkPrecP :: Located (SourceText,Int) -> P (Located (SourceText,Int))
1468 checkPrecP (L l (src,i))
1469 | 0 <= i && i <= maxPrecedence = return (L l (src,i))
1470 | otherwise
1471 = parseErrorSDoc l (text ("Precedence out of range: " ++ show i))
1472
1473 mkRecConstrOrUpdate
1474 :: LHsExpr GhcPs
1475 -> SrcSpan
1476 -> ([LHsRecField GhcPs (LHsExpr GhcPs)], Bool)
1477 -> P (HsExpr GhcPs)
1478
1479 mkRecConstrOrUpdate (L l (HsVar _ (L _ c))) _ (fs,dd)
1480 | isRdrDataCon c
1481 = return (mkRdrRecordCon (L l c) (mk_rec_fields fs dd))
1482 mkRecConstrOrUpdate exp@(L l _) _ (fs,dd)
1483 | dd = parseErrorSDoc l (text "You cannot use `..' in a record update")
1484 | otherwise = return (mkRdrRecordUpd exp (map (fmap mk_rec_upd_field) fs))
1485
1486 mkRdrRecordUpd :: LHsExpr GhcPs -> [LHsRecUpdField GhcPs] -> HsExpr GhcPs
1487 mkRdrRecordUpd exp flds
1488 = RecordUpd { rupd_ext = noExt
1489 , rupd_expr = exp
1490 , rupd_flds = flds }
1491
1492 mkRdrRecordCon :: Located RdrName -> HsRecordBinds GhcPs -> HsExpr GhcPs
1493 mkRdrRecordCon con flds
1494 = RecordCon { rcon_ext = noExt, rcon_con_name = con, rcon_flds = flds }
1495
1496 mk_rec_fields :: [LHsRecField id arg] -> Bool -> HsRecFields id arg
1497 mk_rec_fields fs False = HsRecFields { rec_flds = fs, rec_dotdot = Nothing }
1498 mk_rec_fields fs True = HsRecFields { rec_flds = fs, rec_dotdot = Just (length fs) }
1499
1500 mk_rec_upd_field :: HsRecField GhcPs (LHsExpr GhcPs) -> HsRecUpdField GhcPs
1501 mk_rec_upd_field (HsRecField (L loc (FieldOcc _ rdr)) arg pun)
1502 = HsRecField (L loc (Unambiguous noExt rdr)) arg pun
1503 mk_rec_upd_field (HsRecField (L _ (XFieldOcc _)) _ _)
1504 = panic "mk_rec_upd_field"
1505
1506 mkInlinePragma :: SourceText -> (InlineSpec, RuleMatchInfo) -> Maybe Activation
1507 -> InlinePragma
1508 -- The (Maybe Activation) is because the user can omit
1509 -- the activation spec (and usually does)
1510 mkInlinePragma src (inl, match_info) mb_act
1511 = InlinePragma { inl_src = src -- Note [Pragma source text] in BasicTypes
1512 , inl_inline = inl
1513 , inl_sat = Nothing
1514 , inl_act = act
1515 , inl_rule = match_info }
1516 where
1517 act = case mb_act of
1518 Just act -> act
1519 Nothing -> -- No phase specified
1520 case inl of
1521 NoInline -> NeverActive
1522 _other -> AlwaysActive
1523
1524 -----------------------------------------------------------------------------
1525 -- utilities for foreign declarations
1526
1527 -- construct a foreign import declaration
1528 --
1529 mkImport :: Located CCallConv
1530 -> Located Safety
1531 -> (Located StringLiteral, Located RdrName, LHsSigType GhcPs)
1532 -> P (HsDecl GhcPs)
1533 mkImport cconv safety (L loc (StringLiteral esrc entity), v, ty) =
1534 case cconv of
1535 L _ CCallConv -> mkCImport
1536 L _ CApiConv -> mkCImport
1537 L _ StdCallConv -> mkCImport
1538 L _ PrimCallConv -> mkOtherImport
1539 L _ JavaScriptCallConv -> mkOtherImport
1540 where
1541 -- Parse a C-like entity string of the following form:
1542 -- "[static] [chname] [&] [cid]" | "dynamic" | "wrapper"
1543 -- If 'cid' is missing, the function name 'v' is used instead as symbol
1544 -- name (cf section 8.5.1 in Haskell 2010 report).
1545 mkCImport = do
1546 let e = unpackFS entity
1547 case parseCImport cconv safety (mkExtName (unLoc v)) e (L loc esrc) of
1548 Nothing -> parseErrorSDoc loc (text "Malformed entity string")
1549 Just importSpec -> returnSpec importSpec
1550
1551 -- currently, all the other import conventions only support a symbol name in
1552 -- the entity string. If it is missing, we use the function name instead.
1553 mkOtherImport = returnSpec importSpec
1554 where
1555 entity' = if nullFS entity
1556 then mkExtName (unLoc v)
1557 else entity
1558 funcTarget = CFunction (StaticTarget esrc entity' Nothing True)
1559 importSpec = CImport cconv safety Nothing funcTarget (L loc esrc)
1560
1561 returnSpec spec = return $ ForD noExt $ ForeignImport
1562 { fd_i_ext = noExt
1563 , fd_name = v
1564 , fd_sig_ty = ty
1565 , fd_fi = spec
1566 }
1567
1568
1569
1570 -- the string "foo" is ambiguous: either a header or a C identifier. The
1571 -- C identifier case comes first in the alternatives below, so we pick
1572 -- that one.
1573 parseCImport :: Located CCallConv -> Located Safety -> FastString -> String
1574 -> Located SourceText
1575 -> Maybe ForeignImport
1576 parseCImport cconv safety nm str sourceText =
1577 listToMaybe $ map fst $ filter (null.snd) $
1578 readP_to_S parse str
1579 where
1580 parse = do
1581 skipSpaces
1582 r <- choice [
1583 string "dynamic" >> return (mk Nothing (CFunction DynamicTarget)),
1584 string "wrapper" >> return (mk Nothing CWrapper),
1585 do optional (token "static" >> skipSpaces)
1586 ((mk Nothing <$> cimp nm) +++
1587 (do h <- munch1 hdr_char
1588 skipSpaces
1589 mk (Just (Header (SourceText h) (mkFastString h)))
1590 <$> cimp nm))
1591 ]
1592 skipSpaces
1593 return r
1594
1595 token str = do _ <- string str
1596 toks <- look
1597 case toks of
1598 c : _
1599 | id_char c -> pfail
1600 _ -> return ()
1601
1602 mk h n = CImport cconv safety h n sourceText
1603
1604 hdr_char c = not (isSpace c) -- header files are filenames, which can contain
1605 -- pretty much any char (depending on the platform),
1606 -- so just accept any non-space character
1607 id_first_char c = isAlpha c || c == '_'
1608 id_char c = isAlphaNum c || c == '_'
1609
1610 cimp nm = (ReadP.char '&' >> skipSpaces >> CLabel <$> cid)
1611 +++ (do isFun <- case cconv of
1612 L _ CApiConv ->
1613 option True
1614 (do token "value"
1615 skipSpaces
1616 return False)
1617 _ -> return True
1618 cid' <- cid
1619 return (CFunction (StaticTarget NoSourceText cid'
1620 Nothing isFun)))
1621 where
1622 cid = return nm +++
1623 (do c <- satisfy id_first_char
1624 cs <- many (satisfy id_char)
1625 return (mkFastString (c:cs)))
1626
1627
1628 -- construct a foreign export declaration
1629 --
1630 mkExport :: Located CCallConv
1631 -> (Located StringLiteral, Located RdrName, LHsSigType GhcPs)
1632 -> P (HsDecl GhcPs)
1633 mkExport (L lc cconv) (L le (StringLiteral esrc entity), v, ty)
1634 = return $ ForD noExt $
1635 ForeignExport { fd_e_ext = noExt, fd_name = v, fd_sig_ty = ty
1636 , fd_fe = CExport (L lc (CExportStatic esrc entity' cconv))
1637 (L le esrc) }
1638 where
1639 entity' | nullFS entity = mkExtName (unLoc v)
1640 | otherwise = entity
1641
1642 -- Supplying the ext_name in a foreign decl is optional; if it
1643 -- isn't there, the Haskell name is assumed. Note that no transformation
1644 -- of the Haskell name is then performed, so if you foreign export (++),
1645 -- it's external name will be "++". Too bad; it's important because we don't
1646 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
1647 --
1648 mkExtName :: RdrName -> CLabelString
1649 mkExtName rdrNm = mkFastString (occNameString (rdrNameOcc rdrNm))
1650
1651 --------------------------------------------------------------------------------
1652 -- Help with module system imports/exports
1653
1654 data ImpExpSubSpec = ImpExpAbs
1655 | ImpExpAll
1656 | ImpExpList [Located ImpExpQcSpec]
1657 | ImpExpAllWith [Located ImpExpQcSpec]
1658
1659 data ImpExpQcSpec = ImpExpQcName (Located RdrName)
1660 | ImpExpQcType (Located RdrName)
1661 | ImpExpQcWildcard
1662
1663 mkModuleImpExp :: Located ImpExpQcSpec -> ImpExpSubSpec -> P (IE GhcPs)
1664 mkModuleImpExp (L l specname) subs =
1665 case subs of
1666 ImpExpAbs
1667 | isVarNameSpace (rdrNameSpace name)
1668 -> return $ IEVar noExt (L l (ieNameFromSpec specname))
1669 | otherwise -> IEThingAbs noExt . L l <$> nameT
1670 ImpExpAll -> IEThingAll noExt . L l <$> nameT
1671 ImpExpList xs ->
1672 (\newName -> IEThingWith noExt (L l newName) NoIEWildcard (wrapped xs) [])
1673 <$> nameT
1674 ImpExpAllWith xs ->
1675 do allowed <- extension patternSynonymsEnabled
1676 if allowed
1677 then
1678 let withs = map unLoc xs
1679 pos = maybe NoIEWildcard IEWildcard
1680 (findIndex isImpExpQcWildcard withs)
1681 ies = wrapped $ filter (not . isImpExpQcWildcard . unLoc) xs
1682 in (\newName
1683 -> IEThingWith noExt (L l newName) pos ies []) <$> nameT
1684 else parseErrorSDoc l
1685 (text "Illegal export form (use PatternSynonyms to enable)")
1686 where
1687 name = ieNameVal specname
1688 nameT =
1689 if isVarNameSpace (rdrNameSpace name)
1690 then parseErrorSDoc l
1691 (text "Expecting a type constructor but found a variable,"
1692 <+> quotes (ppr name) <> text "."
1693 $$ if isSymOcc $ rdrNameOcc name
1694 then text "If" <+> quotes (ppr name) <+> text "is a type constructor"
1695 <+> text "then enable ExplicitNamespaces and use the 'type' keyword."
1696 else empty)
1697 else return $ ieNameFromSpec specname
1698
1699 ieNameVal (ImpExpQcName ln) = unLoc ln
1700 ieNameVal (ImpExpQcType ln) = unLoc ln
1701 ieNameVal (ImpExpQcWildcard) = panic "ieNameVal got wildcard"
1702
1703 ieNameFromSpec (ImpExpQcName ln) = IEName ln
1704 ieNameFromSpec (ImpExpQcType ln) = IEType ln
1705 ieNameFromSpec (ImpExpQcWildcard) = panic "ieName got wildcard"
1706
1707 wrapped = map (\(L l x) -> L l (ieNameFromSpec x))
1708
1709 mkTypeImpExp :: Located RdrName -- TcCls or Var name space
1710 -> P (Located RdrName)
1711 mkTypeImpExp name =
1712 do allowed <- extension explicitNamespacesEnabled
1713 if allowed
1714 then return (fmap (`setRdrNameSpace` tcClsName) name)
1715 else parseErrorSDoc (getLoc name)
1716 (text "Illegal keyword 'type' (use ExplicitNamespaces to enable)")
1717
1718 checkImportSpec :: Located [LIE GhcPs] -> P (Located [LIE GhcPs])
1719 checkImportSpec ie@(L _ specs) =
1720 case [l | (L l (IEThingWith _ _ (IEWildcard _) _ _)) <- specs] of
1721 [] -> return ie
1722 (l:_) -> importSpecError l
1723 where
1724 importSpecError l =
1725 parseErrorSDoc l
1726 (text "Illegal import form, this syntax can only be used to bundle"
1727 $+$ text "pattern synonyms with types in module exports.")
1728
1729 -- In the correct order
1730 mkImpExpSubSpec :: [Located ImpExpQcSpec] -> P ([AddAnn], ImpExpSubSpec)
1731 mkImpExpSubSpec [] = return ([], ImpExpList [])
1732 mkImpExpSubSpec [L _ ImpExpQcWildcard] =
1733 return ([], ImpExpAll)
1734 mkImpExpSubSpec xs =
1735 if (any (isImpExpQcWildcard . unLoc) xs)
1736 then return $ ([], ImpExpAllWith xs)
1737 else return $ ([], ImpExpList xs)
1738
1739 isImpExpQcWildcard :: ImpExpQcSpec -> Bool
1740 isImpExpQcWildcard ImpExpQcWildcard = True
1741 isImpExpQcWildcard _ = False
1742
1743 -----------------------------------------------------------------------------
1744 -- Warnings and failures
1745
1746 warnStarIsType :: SrcSpan -> P ()
1747 warnStarIsType span = addWarning Opt_WarnStarIsType span msg
1748 where
1749 msg = text "Using" <+> quotes (text "*")
1750 <+> text "(or its Unicode variant) to mean"
1751 <+> quotes (text "Data.Kind.Type")
1752 $$ text "relies on the StarIsType extension."
1753 $$ text "Suggested fix: use" <+> quotes (text "Type")
1754 <+> text "from" <+> quotes (text "Data.Kind") <+> text "instead."
1755
1756 warnStarBndr :: SrcSpan -> P ()
1757 warnStarBndr span = addWarning Opt_WarnStarBinder span msg
1758 where
1759 msg = text "Desugaring" <+> quotes (text "*") <+> text "in a binder"
1760 <+> text "position as a type operator despite StarIsType."
1761 $$ text "NB. To use (or export) this operator in"
1762 <+> text "modules with StarIsType,"
1763 $$ text " including the definition module, you must qualify it."
1764
1765 failOpFewArgs :: Located RdrName -> P a
1766 failOpFewArgs (L loc op) =
1767 do { star_is_type <- extension starIsTypeEnabled
1768 ; let msg = too_few $$ starInfo star_is_type op
1769 ; parseErrorSDoc loc msg }
1770 where
1771 too_few = text "Operator applied to too few arguments:" <+> ppr op
1772
1773 -----------------------------------------------------------------------------
1774 -- Misc utils
1775
1776 parseErrorSDoc :: SrcSpan -> SDoc -> P a
1777 parseErrorSDoc span s = failSpanMsgP span s
1778
1779 -- | Hint about bang patterns, assuming @BangPatterns@ is off.
1780 hintBangPat :: SrcSpan -> HsExpr GhcPs -> P ()
1781 hintBangPat span e = do
1782 bang_on <- extension bangPatEnabled
1783 unless bang_on $
1784 parseErrorSDoc span
1785 (text "Illegal bang-pattern (use BangPatterns):" $$ ppr e)
1786
1787 data SumOrTuple
1788 = Sum ConTag Arity (LHsExpr GhcPs)
1789 | Tuple [LHsTupArg GhcPs]
1790
1791 mkSumOrTuple :: Boxity -> SrcSpan -> SumOrTuple -> P (HsExpr GhcPs)
1792
1793 -- Tuple
1794 mkSumOrTuple boxity _ (Tuple es) = return (ExplicitTuple noExt es boxity)
1795
1796 -- Sum
1797 mkSumOrTuple Unboxed _ (Sum alt arity e) =
1798 return (ExplicitSum noExt alt arity e)
1799 mkSumOrTuple Boxed l (Sum alt arity (L _ e)) =
1800 parseErrorSDoc l (hang (text "Boxed sums not supported:") 2 (ppr_boxed_sum alt arity e))
1801 where
1802 ppr_boxed_sum :: ConTag -> Arity -> HsExpr GhcPs -> SDoc
1803 ppr_boxed_sum alt arity e =
1804 text "(" <+> ppr_bars (alt - 1) <+> ppr e <+> ppr_bars (arity - alt) <+> text ")"
1805
1806 ppr_bars n = hsep (replicate n (Outputable.char '|'))
1807
1808 mkLHsOpTy :: LHsType GhcPs -> Located RdrName -> LHsType GhcPs -> LHsType GhcPs
1809 mkLHsOpTy x op y =
1810 let loc = getLoc x `combineSrcSpans` getLoc op `combineSrcSpans` getLoc y
1811 in L loc (mkHsOpTy x op y)