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