Make datatype contexts an extension (on by default) (DatatypeContexts)
[ghc-hetmet.git] / compiler / parser / RdrHsSyn.lhs
1 %
2 % (c) The University of Glasgow, 1996-2003
3
4 Functions over HsSyn specialised to RdrName.
5
6 \begin{code}
7 module RdrHsSyn (
8         extractHsTyRdrTyVars, 
9         extractHsRhoRdrTyVars, extractGenericPatTyVars,
10  
11         mkHsOpApp, 
12         mkHsIntegral, mkHsFractional, mkHsIsString,
13         mkHsDo, mkHsSplice, mkTopSpliceDecl,
14         mkClassDecl, mkTyData, mkTyFamily, mkTySynonym,
15         splitCon, mkInlinePragma,       
16         mkRecConstrOrUpdate, -- HsExp -> [HsFieldUpdate] -> P HsExp
17
18         cvBindGroup,
19         cvBindsAndSigs,
20         cvTopDecls,
21         placeHolderPunRhs,
22
23         -- Stuff to do with Foreign declarations
24         mkImport,
25         parseCImport,
26         mkExport,
27         mkExtName,           -- RdrName -> CLabelString
28         mkGadtDecl,          -- [Located RdrName] -> LHsType RdrName -> ConDecl RdrName
29         mkSimpleConDecl, 
30         mkDeprecatedGadtRecordDecl,
31
32         -- Bunch of functions in the parser monad for 
33         -- checking and constructing values
34         checkPrecP,           -- Int -> P Int
35         checkContext,         -- HsType -> P HsContext
36         checkPred,            -- HsType -> P HsPred
37         checkTyVars,          -- [LHsType RdrName] -> P ()
38         checkKindSigs,        -- [LTyClDecl RdrName] -> P ()
39         checkInstType,        -- HsType -> P HsType
40         checkPattern,         -- HsExp -> P HsPat
41         bang_RDR,
42         checkPatterns,        -- SrcLoc -> [HsExp] -> P [HsPat]
43         checkDo,              -- [Stmt] -> P [Stmt]
44         checkMDo,             -- [Stmt] -> P [Stmt]
45         checkValDef,          -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
46         checkValSig,          -- (SrcLoc, HsExp, HsRhs, [HsDecl]) -> P HsDecl
47         parseError,         
48         parseErrorSDoc,     
49     ) where
50
51 import HsSyn            -- Lots of it
52 import Class            ( FunDep )
53 import TypeRep          ( Kind )
54 import RdrName          ( RdrName, isRdrTyVar, isRdrTc, mkUnqual, rdrNameOcc, 
55                           isRdrDataCon, isUnqual, getRdrName, setRdrNameSpace )
56 import BasicTypes       ( maxPrecedence, Activation(..), RuleMatchInfo,
57                           InlinePragma(..) )
58 import Lexer
59 import TysWiredIn       ( unitTyCon ) 
60 import ForeignCall
61 import OccName          ( srcDataName, varName, isDataOcc, isTcOcc, 
62                           occNameString )
63 import PrelNames        ( forall_tv_RDR )
64 import DynFlags
65 import SrcLoc
66 import OrdList          ( OrdList, fromOL )
67 import Bag              ( Bag, emptyBag, consBag, foldrBag )
68 import Outputable
69 import FastString
70 import Maybes
71
72 import Control.Applicative ((<$>))       
73 import Control.Monad
74 import Text.ParserCombinators.ReadP as ReadP
75 import Data.List        ( nubBy )
76 import Data.Char
77
78 #include "HsVersions.h"
79 \end{code}
80
81
82 %************************************************************************
83 %*                                                                      *
84 \subsection{A few functions over HsSyn at RdrName}
85 %*                                                                    *
86 %************************************************************************
87
88 extractHsTyRdrNames finds the free variables of a HsType
89 It's used when making the for-alls explicit.
90
91 \begin{code}
92 extractHsTyRdrTyVars :: LHsType RdrName -> [Located RdrName]
93 extractHsTyRdrTyVars ty = nubBy eqLocated (extract_lty ty [])
94
95 extractHsTysRdrTyVars :: [LHsType RdrName] -> [Located RdrName]
96 extractHsTysRdrTyVars ty = nubBy eqLocated (extract_ltys ty [])
97
98 extractHsRhoRdrTyVars :: LHsContext RdrName -> LHsType RdrName -> [Located RdrName]
99 -- This one takes the context and tau-part of a 
100 -- sigma type and returns their free type variables
101 extractHsRhoRdrTyVars ctxt ty 
102  = nubBy eqLocated $ extract_lctxt ctxt (extract_lty ty [])
103
104 extract_lctxt :: Located [LHsPred RdrName] -> [Located RdrName] -> [Located RdrName]
105 extract_lctxt ctxt acc = foldr (extract_pred . unLoc) acc (unLoc ctxt)
106
107 extract_pred :: HsPred RdrName -> [Located RdrName] -> [Located RdrName]
108 extract_pred (HsClassP _   tys) acc = extract_ltys tys acc
109 extract_pred (HsEqualP ty1 ty2) acc = extract_lty ty1 (extract_lty ty2 acc)
110 extract_pred (HsIParam _   ty ) acc = extract_lty ty acc
111
112 extract_ltys :: [LHsType RdrName] -> [Located RdrName] -> [Located RdrName]
113 extract_ltys tys acc = foldr extract_lty acc tys
114
115 extract_lty :: LHsType RdrName -> [Located RdrName] -> [Located RdrName]
116 extract_lty (L loc ty) acc 
117   = case ty of
118       HsTyVar tv                -> extract_tv loc tv acc
119       HsBangTy _ ty             -> extract_lty ty acc
120       HsRecTy flds              -> foldr (extract_lty . cd_fld_type) acc flds
121       HsAppTy ty1 ty2           -> extract_lty ty1 (extract_lty ty2 acc)
122       HsListTy ty               -> extract_lty ty acc
123       HsPArrTy ty               -> extract_lty ty acc
124       HsTupleTy _ tys           -> extract_ltys tys acc
125       HsFunTy ty1 ty2           -> extract_lty ty1 (extract_lty ty2 acc)
126       HsPredTy p                -> extract_pred p acc
127       HsOpTy ty1 (L loc tv) ty2 -> extract_tv loc tv (extract_lty ty1 (extract_lty ty2 acc))
128       HsParTy ty                -> extract_lty ty acc
129       HsNumTy _                 -> acc
130       HsQuasiQuoteTy {}         -> acc  -- Quasi quotes mention no type variables
131       HsSpliceTy {}             -> acc  -- Type splices mention no type variables
132       HsKindSig ty _            -> extract_lty ty acc
133       HsForAllTy _ [] cx ty     -> extract_lctxt cx (extract_lty ty acc)
134       HsForAllTy _ tvs cx ty    -> acc ++ (filter ((`notElem` locals) . unLoc) $
135                                            extract_lctxt cx (extract_lty ty []))
136                                 where
137                                    locals = hsLTyVarNames tvs
138       HsDocTy ty _              -> extract_lty ty acc
139
140 extract_tv :: SrcSpan -> RdrName -> [Located RdrName] -> [Located RdrName]
141 extract_tv loc tv acc | isRdrTyVar tv = L loc tv : acc
142                       | otherwise     = acc
143
144 extractGenericPatTyVars :: LHsBinds RdrName -> [Located RdrName]
145 -- Get the type variables out of the type patterns in a bunch of
146 -- possibly-generic bindings in a class declaration
147 extractGenericPatTyVars binds
148   = nubBy eqLocated (foldrBag get [] binds)
149   where
150     get (L _ (FunBind { fun_matches = MatchGroup ms _ })) acc = foldr (get_m.unLoc) acc ms
151     get _                                                 acc = acc
152
153     get_m (Match (L _ (TypePat ty) : _) _ _) acc = extract_lty ty acc
154     get_m _                                        acc = acc
155 \end{code}
156
157
158 %************************************************************************
159 %*                                                                      *
160 \subsection{Construction functions for Rdr stuff}
161 %*                                                                    *
162 %************************************************************************
163
164 mkClassDecl builds a RdrClassDecl, filling in the names for tycon and datacon
165 by deriving them from the name of the class.  We fill in the names for the
166 tycon and datacon corresponding to the class, by deriving them from the
167 name of the class itself.  This saves recording the names in the interface
168 file (which would be equally good).
169
170 Similarly for mkConDecl, mkClassOpSig and default-method names.
171
172         *** See "THE NAMING STORY" in HsDecls ****
173   
174 \begin{code}
175 mkClassDecl :: SrcSpan
176             -> Located (Maybe (LHsContext RdrName), LHsType RdrName)
177             -> Located [Located (FunDep RdrName)]
178             -> Located (OrdList (LHsDecl RdrName))
179             -> P (LTyClDecl RdrName)
180
181 mkClassDecl loc (L _ (mcxt, tycl_hdr)) fds where_cls
182   = do { let (binds, sigs, ats, docs) = cvBindsAndSigs (unLoc where_cls)
183        ; let cxt = fromMaybe (noLoc []) mcxt
184        ; (cls, tparams) <- checkTyClHdr tycl_hdr
185        ; tyvars <- checkTyVars tparams      -- Only type vars allowed
186        ; checkKindSigs ats
187        ; return (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls, tcdTyVars = tyvars,
188                                     tcdFDs = unLoc fds, tcdSigs = sigs, tcdMeths = binds,
189                                     tcdATs   = ats, tcdDocs  = docs })) }
190
191 mkTyData :: SrcSpan
192          -> NewOrData
193          -> Bool                -- True <=> data family instance
194          -> Located (Maybe (LHsContext RdrName), LHsType RdrName)
195          -> Maybe Kind
196          -> [LConDecl RdrName]
197          -> Maybe [LHsType RdrName]
198          -> P (LTyClDecl RdrName)
199 mkTyData loc new_or_data is_family (L _ (mcxt, tycl_hdr)) ksig data_cons maybe_deriv
200   = do { (tc, tparams) <- checkTyClHdr tycl_hdr
201
202        ; checkDatatypeContext mcxt
203        ; let cxt = fromMaybe (noLoc []) mcxt
204        ; (tyvars, typats) <- checkTParams is_family tparams
205        ; return (L loc (TyData { tcdND = new_or_data, tcdCtxt = cxt, tcdLName = tc,
206                                  tcdTyVars = tyvars, tcdTyPats = typats, 
207                                  tcdCons = data_cons, 
208                                  tcdKindSig = ksig, tcdDerivs = maybe_deriv })) }
209
210 mkTySynonym :: SrcSpan 
211             -> Bool             -- True <=> type family instances
212             -> LHsType RdrName  -- LHS
213             -> LHsType RdrName  -- RHS
214             -> P (LTyClDecl RdrName)
215 mkTySynonym loc is_family lhs rhs
216   = do { (tc, tparams) <- checkTyClHdr lhs
217        ; (tyvars, typats) <- checkTParams is_family tparams
218        ; return (L loc (TySynonym tc tyvars typats rhs)) }
219
220 mkTyFamily :: SrcSpan
221            -> FamilyFlavour
222            -> LHsType RdrName   -- LHS
223            -> Maybe Kind        -- Optional kind signature
224            -> P (LTyClDecl RdrName)
225 mkTyFamily loc flavour lhs ksig
226   = do { (tc, tparams) <- checkTyClHdr lhs
227        ; tyvars <- checkTyVars tparams
228        ; return (L loc (TyFamily flavour tc tyvars ksig)) }
229
230 mkTopSpliceDecl :: LHsExpr RdrName -> HsDecl RdrName
231 -- If the user wrote
232 --      [pads| ... ]   then return a QuasiQuoteD
233 --      $(e)           then return a SpliceD
234 -- but if she wrote, say,
235 --      f x            then behave as if she'd written $(f x)
236 --                     ie a SpliceD
237 mkTopSpliceDecl (L _ (HsQuasiQuoteE qq))            = QuasiQuoteD qq
238 mkTopSpliceDecl (L _ (HsSpliceE (HsSplice _ expr))) = SpliceD (SpliceDecl expr       Explicit)
239 mkTopSpliceDecl other_expr                          = SpliceD (SpliceDecl other_expr Implicit)
240 \end{code}
241
242 %************************************************************************
243 %*                                                                      *
244 \subsection[cvBinds-etc]{Converting to @HsBinds@, etc.}
245 %*                                                                      *
246 %************************************************************************
247
248 Function definitions are restructured here. Each is assumed to be recursive
249 initially, and non recursive definitions are discovered by the dependency
250 analyser.
251
252
253 \begin{code}
254 --  | Groups together bindings for a single function
255 cvTopDecls :: OrdList (LHsDecl RdrName) -> [LHsDecl RdrName]
256 cvTopDecls decls = go (fromOL decls)
257   where
258     go :: [LHsDecl RdrName] -> [LHsDecl RdrName]
259     go []                   = []
260     go (L l (ValD b) : ds)  = L l' (ValD b') : go ds'
261                             where (L l' b', ds') = getMonoBind (L l b) ds
262     go (d : ds)             = d : go ds
263
264 -- Declaration list may only contain value bindings and signatures.
265 cvBindGroup :: OrdList (LHsDecl RdrName) -> HsValBinds RdrName
266 cvBindGroup binding
267   = case cvBindsAndSigs binding of
268       (mbs, sigs, tydecls, _) -> ASSERT( null tydecls )
269                                  ValBindsIn mbs sigs
270
271 cvBindsAndSigs :: OrdList (LHsDecl RdrName)
272   -> (Bag (LHsBind RdrName), [LSig RdrName], [LTyClDecl RdrName], [LDocDecl])
273 -- Input decls contain just value bindings and signatures
274 -- and in case of class or instance declarations also
275 -- associated type declarations. They might also contain Haddock comments.
276 cvBindsAndSigs  fb = go (fromOL fb)
277   where
278     go []                  = (emptyBag, [], [], [])
279     go (L l (SigD s) : ds) = (bs, L l s : ss, ts, docs)
280                            where (bs, ss, ts, docs) = go ds
281     go (L l (ValD b) : ds) = (b' `consBag` bs, ss, ts, docs)
282                            where (b', ds')    = getMonoBind (L l b) ds
283                                  (bs, ss, ts, docs) = go ds'
284     go (L l (TyClD t): ds) = (bs, ss, L l t : ts, docs)
285                            where (bs, ss, ts, docs) = go ds
286     go (L l (DocD d) : ds) =  (bs, ss, ts, (L l d) : docs)
287                            where (bs, ss, ts, docs) = go ds
288     go (L _ d : _)        = pprPanic "cvBindsAndSigs" (ppr d)
289
290 -----------------------------------------------------------------------------
291 -- Group function bindings into equation groups
292
293 getMonoBind :: LHsBind RdrName -> [LHsDecl RdrName]
294   -> (LHsBind RdrName, [LHsDecl RdrName])
295 -- Suppose      (b',ds') = getMonoBind b ds
296 --      ds is a list of parsed bindings
297 --      b is a MonoBinds that has just been read off the front
298
299 -- Then b' is the result of grouping more equations from ds that
300 -- belong with b into a single MonoBinds, and ds' is the depleted
301 -- list of parsed bindings.
302 --
303 -- All Haddock comments between equations inside the group are 
304 -- discarded.
305 --
306 -- No AndMonoBinds or EmptyMonoBinds here; just single equations
307
308 getMonoBind (L loc1 (FunBind { fun_id = fun_id1@(L _ f1), fun_infix = is_infix1,
309                                fun_matches = MatchGroup mtchs1 _ })) binds
310   | has_args mtchs1
311   = go is_infix1 mtchs1 loc1 binds []
312   where
313     go is_infix mtchs loc 
314        (L loc2 (ValD (FunBind { fun_id = L _ f2, fun_infix = is_infix2,
315                                 fun_matches = MatchGroup mtchs2 _ })) : binds) _
316         | f1 == f2 = go (is_infix || is_infix2) (mtchs2 ++ mtchs) 
317                         (combineSrcSpans loc loc2) binds []
318     go is_infix mtchs loc (doc_decl@(L loc2 (DocD _)) : binds) doc_decls 
319         = let doc_decls' = doc_decl : doc_decls  
320           in go is_infix mtchs (combineSrcSpans loc loc2) binds doc_decls'
321     go is_infix mtchs loc binds doc_decls
322         = (L loc (makeFunBind fun_id1 is_infix (reverse mtchs)), (reverse doc_decls) ++ binds)
323         -- Reverse the final matches, to get it back in the right order
324         -- Do the same thing with the trailing doc comments
325
326 getMonoBind bind binds = (bind, binds)
327
328 has_args :: [LMatch RdrName] -> Bool
329 has_args []                           = panic "RdrHsSyn:has_args"
330 has_args ((L _ (Match args _ _)) : _) = not (null args)
331         -- Don't group together FunBinds if they have
332         -- no arguments.  This is necessary now that variable bindings
333         -- with no arguments are now treated as FunBinds rather
334         -- than pattern bindings (tests/rename/should_fail/rnfail002).
335 \end{code}
336
337 %************************************************************************
338 %*                                                                      *
339 \subsection[PrefixToHS-utils]{Utilities for conversion}
340 %*                                                                      *
341 %************************************************************************
342
343
344 \begin{code}
345 -----------------------------------------------------------------------------
346 -- splitCon
347
348 -- When parsing data declarations, we sometimes inadvertently parse
349 -- a constructor application as a type (eg. in data T a b = C a b `D` E a b)
350 -- This function splits up the type application, adds any pending
351 -- arguments, and converts the type constructor back into a data constructor.
352
353 splitCon :: LHsType RdrName
354       -> P (Located RdrName, HsConDeclDetails RdrName)
355 -- This gets given a "type" that should look like
356 --      C Int Bool
357 -- or   C { x::Int, y::Bool }
358 -- and returns the pieces
359 splitCon ty
360  = split ty []
361  where
362    split (L _ (HsAppTy t u)) ts = split t (u : ts)
363    split (L l (HsTyVar tc))  ts = do data_con <- tyConToDataCon l tc
364                                      return (data_con, mk_rest ts)
365    split (L l _) _              = parseError l "parse error in data/newtype declaration"
366
367    mk_rest [L _ (HsRecTy flds)] = RecCon flds
368    mk_rest ts                   = PrefixCon ts
369
370 mkDeprecatedGadtRecordDecl :: SrcSpan 
371                            -> Located RdrName
372                            -> [ConDeclField RdrName]
373                            -> LHsType RdrName
374                            ->  P (LConDecl  RdrName)
375 -- This one uses the deprecated syntax
376 --    C { x,y ::Int } :: T a b
377 -- We give it a RecCon details right away
378 mkDeprecatedGadtRecordDecl loc (L con_loc con) flds res_ty
379   = do { data_con <- tyConToDataCon con_loc con
380        ; return (L loc (ConDecl { con_old_rec  = True
381                                 , con_name     = data_con
382                                 , con_explicit = Implicit
383                                 , con_qvars    = []
384                                 , con_cxt      = noLoc []
385                                 , con_details  = RecCon flds
386                                 , con_res      = ResTyGADT res_ty
387                                 , con_doc      = Nothing })) }
388
389 mkSimpleConDecl :: Located RdrName -> [LHsTyVarBndr RdrName]
390                 -> LHsContext RdrName -> HsConDeclDetails RdrName
391                 -> ConDecl RdrName
392
393 mkSimpleConDecl name qvars cxt details
394   = ConDecl { con_old_rec  = False
395             , con_name     = name
396             , con_explicit = Explicit
397             , con_qvars    = qvars
398             , con_cxt      = cxt
399             , con_details  = details
400             , con_res      = ResTyH98
401             , con_doc      = Nothing }
402
403 mkGadtDecl :: [Located RdrName]
404            -> LHsType RdrName     -- Always a HsForAllTy
405            -> [ConDecl RdrName]
406 -- We allow C,D :: ty
407 -- and expand it as if it had been 
408 --    C :: ty; D :: ty
409 -- (Just like type signatures in general.)
410 mkGadtDecl names (L _ (HsForAllTy imp qvars cxt tau))
411   = [mk_gadt_con name | name <- names]
412   where
413     (details, res_ty)           -- See Note [Sorting out the result type]
414       = case tau of
415           L _ (HsFunTy (L _ (HsRecTy flds)) res_ty) -> (RecCon flds,  res_ty)
416           _other                                    -> (PrefixCon [], tau)
417
418     mk_gadt_con name
419        = ConDecl { con_old_rec  = False
420                  , con_name     = name
421                  , con_explicit = imp
422                  , con_qvars    = qvars
423                  , con_cxt      = cxt
424                  , con_details  = details
425                  , con_res      = ResTyGADT res_ty
426                  , con_doc      = Nothing }
427 mkGadtDecl _ other_ty = pprPanic "mkGadtDecl" (ppr other_ty)
428
429 tyConToDataCon :: SrcSpan -> RdrName -> P (Located RdrName)
430 tyConToDataCon loc tc
431   | isTcOcc (rdrNameOcc tc)
432   = return (L loc (setRdrNameSpace tc srcDataName))
433   | otherwise
434   = parseErrorSDoc loc (msg $$ extra)
435   where
436     msg = text "Not a data constructor:" <+> quotes (ppr tc)
437     extra | tc == forall_tv_RDR
438           = text "Perhaps you intended to use -XExistentialQuantification"
439           | otherwise = empty
440 \end{code}
441
442 Note [Sorting out the result type]
443 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
444 In a GADT declaration which is not a record, we put the whole constr
445 type into the ResTyGADT for now; the renamer will unravel it once it
446 has sorted out operator fixities. Consider for example
447      C :: a :*: b -> a :*: b -> a :+: b
448 Initially this type will parse as
449       a :*: (b -> (a :*: (b -> (a :+: b))))
450
451 so it's hard to split up the arguments until we've done the precedence
452 resolution (in the renamer) On the other hand, for a record
453         { x,y :: Int } -> a :*: b
454 there is no doubt.  AND we need to sort records out so that
455 we can bring x,y into scope.  So:
456    * For PrefixCon we keep all the args in the ResTyGADT
457    * For RecCon we do not
458
459 \begin{code}
460 ----------------------------------------------------------------------------
461 -- Various Syntactic Checks
462
463 checkInstType :: LHsType RdrName -> P (LHsType RdrName)
464 checkInstType (L l t)
465   = case t of
466         HsForAllTy exp tvs ctxt ty -> do
467                 dict_ty <- checkDictTy ty
468                 return (L l (HsForAllTy exp tvs ctxt dict_ty))
469
470         HsParTy ty -> checkInstType ty
471
472         ty ->   do dict_ty <- checkDictTy (L l ty)
473                    return (L l (HsForAllTy Implicit [] (noLoc []) dict_ty))
474
475 checkDictTy :: LHsType RdrName -> P (LHsType RdrName)
476 checkDictTy (L spn ty) = check ty []
477   where
478   check (HsTyVar tc)            args | isRdrTc tc = done tc args
479   check (HsOpTy t1 (L _ tc) t2) args | isRdrTc tc = done tc (t1:t2:args)
480   check (HsAppTy l r) args = check (unLoc l) (r:args)
481   check (HsParTy t)   args = check (unLoc t) args
482   check _ _ = parseError spn "Malformed instance header"
483
484   done tc args = return (L spn (HsPredTy (HsClassP tc args)))
485
486 checkTParams :: Bool      -- Type/data family
487              -> [LHsType RdrName]
488              -> P ([LHsTyVarBndr RdrName], Maybe [LHsType RdrName])
489 -- checkTParams checks the type parameters of a data/newtype declaration
490 -- There are two cases:
491 --
492 --  a) Vanilla data/newtype decl. In that case 
493 --        - the type parameters should all be type variables
494 --        - they may have a kind annotation
495 --
496 --  b) Family data/newtype decl.  In that case
497 --        - The type parameters may be arbitrary types
498 --        - We find the type-varaible binders by find the 
499 --          free type vars of those types
500 --        - We make them all kind-sig-free binders (UserTyVar)
501 --          If there are kind sigs in the type parameters, they
502 --          will fix the binder's kind when we kind-check the 
503 --          type parameters
504 checkTParams is_family tparams
505   | not is_family        -- Vanilla case (a)
506   = do { tyvars <- checkTyVars tparams
507        ; return (tyvars, Nothing) }
508   | otherwise            -- Family case (b)
509   = do { let tyvars = userHsTyVarBndrs (extractHsTysRdrTyVars tparams)
510        ; return (tyvars, Just tparams) }
511
512 checkTyVars :: [LHsType RdrName] -> P [LHsTyVarBndr RdrName]
513 -- Check whether the given list of type parameters are all type variables
514 -- (possibly with a kind signature).  If the second argument is `False',
515 -- only type variables are allowed and we raise an error on encountering a
516 -- non-variable; otherwise, we allow non-variable arguments and return the
517 -- entire list of parameters.
518 checkTyVars tparms = mapM chk tparms
519   where
520         -- Check that the name space is correct!
521     chk (L l (HsKindSig (L _ (HsTyVar tv)) k))
522         | isRdrTyVar tv    = return (L l (KindedTyVar tv k))
523     chk (L l (HsTyVar tv))
524         | isRdrTyVar tv    = return (L l (UserTyVar tv placeHolderKind))
525     chk (L l _)            =
526           parseError l "Type found where type variable expected"
527
528 checkDatatypeContext :: Maybe (LHsContext RdrName) -> P ()
529 checkDatatypeContext Nothing = return ()
530 checkDatatypeContext (Just (L loc _))
531     = do allowed <- extension datatypeContextsEnabled
532          unless allowed $
533              parseError loc "Illegal datatype context (use -XDatatypeContexts)"
534
535 checkTyClHdr :: LHsType RdrName
536              -> P (Located RdrName,          -- the head symbol (type or class name)
537                    [LHsType RdrName])        -- parameters of head symbol
538 -- Well-formedness check and decomposition of type and class heads.
539 -- Decomposes   T ty1 .. tyn   into    (T, [ty1, ..., tyn])
540 --              Int :*: Bool   into    (:*:, [Int, Bool])
541 -- returning the pieces
542 checkTyClHdr ty
543   = goL ty []
544   where
545     goL (L l ty) acc = go l ty acc
546
547     go l (HsTyVar tc) acc 
548         | isRdrTc tc         = return (L l tc, acc)
549                                      
550     go _ (HsOpTy t1 ltc@(L _ tc) t2) acc
551         | isRdrTc tc         = return (ltc, t1:t2:acc)
552     go _ (HsParTy ty)    acc = goL ty acc
553     go _ (HsAppTy t1 t2) acc = goL t1 (t2:acc)
554     go l _               _   = parseError l "Malformed head of type or class declaration"
555
556 -- Check that associated type declarations of a class are all kind signatures.
557 --
558 checkKindSigs :: [LTyClDecl RdrName] -> P ()
559 checkKindSigs = mapM_ check
560   where
561     check (L l tydecl) 
562       | isFamilyDecl tydecl
563         || isSynDecl tydecl  = return ()
564       | otherwise            = 
565         parseError l "Type declaration in a class must be a kind signature or synonym default"
566
567 checkContext :: LHsType RdrName -> P (LHsContext RdrName)
568 checkContext (L l t)
569   = check t
570  where
571   check (HsTupleTy _ ts)        -- (Eq a, Ord b) shows up as a tuple type
572     = do ctx <- mapM checkPred ts
573          return (L l ctx)
574
575   check (HsParTy ty)    -- to be sure HsParTy doesn't get into the way
576     = check (unLoc ty)
577
578   check (HsTyVar t)     -- Empty context shows up as a unit type ()
579     | t == getRdrName unitTyCon = return (L l [])
580
581   check t 
582     = do p <- checkPred (L l t)
583          return (L l [p])
584
585
586 checkPred :: LHsType RdrName -> P (LHsPred RdrName)
587 -- Watch out.. in ...deriving( Show )... we use checkPred on 
588 -- the list of partially applied predicates in the deriving,
589 -- so there can be zero args.
590 checkPred (L spn (HsPredTy (HsIParam n ty)))
591   = return (L spn (HsIParam n ty))
592 checkPred (L spn ty)
593   = check spn ty []
594   where
595     checkl (L l ty) args = check l ty args
596
597     check _loc (HsPredTy pred@(HsEqualP _ _)) 
598                                        args | null args
599                                             = return $ L spn pred
600     check _loc (HsTyVar t)             args | not (isRdrTyVar t) 
601                                             = return (L spn (HsClassP t args))
602     check _loc (HsAppTy l r)           args = checkl l (r:args)
603     check _loc (HsOpTy l (L loc tc) r) args = check loc (HsTyVar tc) (l:r:args)
604     check _loc (HsParTy t)             args = checkl t args
605     check loc _                        _    = parseError loc  
606                                                 "malformed class assertion"
607
608 ---------------------------------------------------------------------------
609 -- Checking statements in a do-expression
610 --      We parse   do { e1 ; e2 ; }
611 --      as [ExprStmt e1, ExprStmt e2]
612 -- checkDo (a) checks that the last thing is an ExprStmt
613 --         (b) returns it separately
614 -- same comments apply for mdo as well
615
616 checkDo, checkMDo :: SrcSpan -> [LStmt RdrName] -> P ([LStmt RdrName], LHsExpr RdrName)
617
618 checkDo  = checkDoMDo "a " "'do'"
619 checkMDo = checkDoMDo "an " "'mdo'"
620
621 checkDoMDo :: String -> String -> SrcSpan -> [LStmt RdrName] -> P ([LStmt RdrName], LHsExpr RdrName)
622 checkDoMDo _   nm loc []   = parseError loc ("Empty " ++ nm ++ " construct")
623 checkDoMDo pre nm _   ss   = do
624   check ss
625   where 
626         check  []                     = panic "RdrHsSyn:checkDoMDo"
627         check  [L _ (ExprStmt e _ _)] = return ([], e)
628         check  [L l _] = parseError l ("The last statement in " ++ pre ++ nm ++
629                                          " construct must be an expression")
630         check (s:ss) = do
631           (ss',e') <-  check ss
632           return ((s:ss'),e')
633
634 -- -------------------------------------------------------------------------
635 -- Checking Patterns.
636
637 -- We parse patterns as expressions and check for valid patterns below,
638 -- converting the expression into a pattern at the same time.
639
640 checkPattern :: LHsExpr RdrName -> P (LPat RdrName)
641 checkPattern e = checkLPat e
642
643 checkPatterns :: [LHsExpr RdrName] -> P [LPat RdrName]
644 checkPatterns es = mapM checkPattern es
645
646 checkLPat :: LHsExpr RdrName -> P (LPat RdrName)
647 checkLPat e@(L l _) = checkPat l e []
648
649 checkPat :: SrcSpan -> LHsExpr RdrName -> [LPat RdrName] -> P (LPat RdrName)
650 checkPat loc (L l (HsVar c)) args
651   | isRdrDataCon c = return (L loc (ConPatIn (L l c) (PrefixCon args)))
652 checkPat loc e args     -- OK to let this happen even if bang-patterns
653                         -- are not enabled, because there is no valid
654                         -- non-bang-pattern parse of (C ! e)
655   | Just (e', args') <- splitBang e
656   = do  { args'' <- checkPatterns args'
657         ; checkPat loc e' (args'' ++ args) }
658 checkPat loc (L _ (HsApp f x)) args
659   = do { x <- checkLPat x; checkPat loc f (x:args) }
660 checkPat loc (L _ e) []
661   = do { pState <- getPState
662        ; p <- checkAPat (dflags pState) loc e
663        ; return (L loc p) }
664 checkPat loc _ _
665   = patFail loc
666
667 checkAPat :: DynFlags -> SrcSpan -> HsExpr RdrName -> P (Pat RdrName)
668 checkAPat dynflags loc e = case e of
669    EWildPat -> return (WildPat placeHolderType)
670    HsVar x  -> return (VarPat x)
671    HsLit l  -> return (LitPat l)
672
673    -- Overloaded numeric patterns (e.g. f 0 x = x)
674    -- Negation is recorded separately, so that the literal is zero or +ve
675    -- NB. Negative *primitive* literals are already handled by the lexer
676    HsOverLit pos_lit          -> return (mkNPat pos_lit Nothing)
677    NegApp (L _ (HsOverLit pos_lit)) _ 
678                         -> return (mkNPat pos_lit (Just noSyntaxExpr))
679    
680    SectionR (L _ (HsVar bang)) e        -- (! x)
681         | bang == bang_RDR 
682         -> do { bang_on <- extension bangPatEnabled
683               ; if bang_on then checkLPat e >>= (return . BangPat)
684                 else parseError loc "Illegal bang-pattern (use -XBangPatterns)" }
685
686    ELazyPat e         -> checkLPat e >>= (return . LazyPat)
687    EAsPat n e         -> checkLPat e >>= (return . AsPat n)
688    -- view pattern is well-formed if the pattern is
689    EViewPat expr patE -> checkLPat patE >>= (return . (\p -> ViewPat expr p placeHolderType))
690    ExprWithTySig e t  -> do e <- checkLPat e
691                             -- Pattern signatures are parsed as sigtypes,
692                             -- but they aren't explicit forall points.  Hence
693                             -- we have to remove the implicit forall here.
694                             let t' = case t of 
695                                        L _ (HsForAllTy Implicit _ (L _ []) ty) -> ty
696                                        other -> other
697                             return (SigPatIn e t')
698    
699    -- n+k patterns
700    OpApp (L nloc (HsVar n)) (L _ (HsVar plus)) _ 
701          (L _ (HsOverLit lit@(OverLit {ol_val = HsIntegral {}})))
702                       | dopt Opt_NPlusKPatterns dynflags && (plus == plus_RDR)
703                       -> return (mkNPlusKPat (L nloc n) lit)
704    
705    OpApp l op _fix r  -> do l <- checkLPat l
706                             r <- checkLPat r
707                             case op of
708                                L cl (HsVar c) | isDataOcc (rdrNameOcc c)
709                                       -> return (ConPatIn (L cl c) (InfixCon l r))
710                                _ -> patFail loc
711    
712    HsPar e            -> checkLPat e >>= (return . ParPat)
713    ExplicitList _ es  -> do ps <- mapM checkLPat es
714                             return (ListPat ps placeHolderType)
715    ExplicitPArr _ es  -> do ps <- mapM checkLPat es
716                             return (PArrPat ps placeHolderType)
717    
718    ExplicitTuple es b 
719      | all tupArgPresent es  -> do ps <- mapM checkLPat [e | Present e <- es]
720                                    return (TuplePat ps b placeHolderType)
721      | otherwise -> parseError loc "Illegal tuple section in pattern"
722    
723    RecordCon c _ (HsRecFields fs dd)
724                       -> do fs <- mapM checkPatField fs
725                             return (ConPatIn c (RecCon (HsRecFields fs dd)))
726    HsQuasiQuoteE q    -> return (QuasiQuotePat q)
727 -- Generics 
728    HsType ty          -> return (TypePat ty) 
729    _                  -> patFail loc
730
731 placeHolderPunRhs :: LHsExpr RdrName
732 -- The RHS of a punned record field will be filled in by the renamer
733 -- It's better not to make it an error, in case we want to print it when debugging
734 placeHolderPunRhs = noLoc (HsVar pun_RDR)
735
736 plus_RDR, bang_RDR, pun_RDR :: RdrName
737 plus_RDR = mkUnqual varName (fsLit "+") -- Hack
738 bang_RDR = mkUnqual varName (fsLit "!") -- Hack
739 pun_RDR  = mkUnqual varName (fsLit "pun-right-hand-side")
740
741 checkPatField :: HsRecField RdrName (LHsExpr RdrName) -> P (HsRecField RdrName (LPat RdrName))
742 checkPatField fld = do  { p <- checkLPat (hsRecFieldArg fld)
743                         ; return (fld { hsRecFieldArg = p }) }
744
745 patFail :: SrcSpan -> P a
746 patFail loc = parseError loc "Parse error in pattern"
747
748
749 ---------------------------------------------------------------------------
750 -- Check Equation Syntax
751
752 checkValDef :: LHsExpr RdrName
753             -> Maybe (LHsType RdrName)
754             -> Located (GRHSs RdrName)
755             -> P (HsBind RdrName)
756
757 checkValDef lhs (Just sig) grhss
758         -- x :: ty = rhs  parses as a *pattern* binding
759   = checkPatBind (L (combineLocs lhs sig) (ExprWithTySig lhs sig)) grhss
760
761 checkValDef lhs opt_sig grhss
762   = do  { mb_fun <- isFunLhs lhs
763         ; case mb_fun of
764             Just (fun, is_infix, pats) -> checkFunBind (getLoc lhs)
765                                                 fun is_infix pats opt_sig grhss
766             Nothing -> checkPatBind lhs grhss }
767
768 checkFunBind :: SrcSpan
769              -> Located RdrName
770              -> Bool
771              -> [LHsExpr RdrName]
772              -> Maybe (LHsType RdrName)
773              -> Located (GRHSs RdrName)
774              -> P (HsBind RdrName)
775 checkFunBind lhs_loc fun is_infix pats opt_sig (L rhs_span grhss)
776   = do  ps <- checkPatterns pats
777         let match_span = combineSrcSpans lhs_loc rhs_span
778         return (makeFunBind fun is_infix [L match_span (Match ps opt_sig grhss)])
779         -- The span of the match covers the entire equation.  
780         -- That isn't quite right, but it'll do for now.
781
782 makeFunBind :: Located id -> Bool -> [LMatch id] -> HsBind id
783 -- Like HsUtils.mkFunBind, but we need to be able to set the fixity too
784 makeFunBind fn is_infix ms 
785   = FunBind { fun_id = fn, fun_infix = is_infix, fun_matches = mkMatchGroup ms,
786               fun_co_fn = idHsWrapper, bind_fvs = placeHolderNames, fun_tick = Nothing }
787
788 checkPatBind :: LHsExpr RdrName
789              -> Located (GRHSs RdrName)
790              -> P (HsBind RdrName)
791 checkPatBind lhs (L _ grhss)
792   = do  { lhs <- checkPattern lhs
793         ; return (PatBind lhs grhss placeHolderType placeHolderNames) }
794
795 checkValSig
796         :: LHsExpr RdrName
797         -> LHsType RdrName
798         -> P (Sig RdrName)
799 checkValSig (L l (HsVar v)) ty 
800   | isUnqual v && not (isDataOcc (rdrNameOcc v))
801   = return (TypeSig (L l v) ty)
802 checkValSig lhs@(L l _)         _
803   | looks_like_foreign lhs
804   = parseError l "Invalid type signature; perhaps you meant to use -XForeignFunctionInterface?"
805   | otherwise
806   = parseError l "Invalid type signature: should be of form <variable> :: <type>"
807   where
808     -- A common error is to forget the ForeignFunctionInterface flag
809     -- so check for that, and suggest.  cf Trac #3805
810     -- Sadly 'foreign import' still barfs 'parse error' because 'import' is a keyword
811     looks_like_foreign (L _ (HsVar v))     = v == foreign_RDR
812     looks_like_foreign (L _ (HsApp lhs _)) = looks_like_foreign lhs
813     looks_like_foreign _                   = False
814
815     foreign_RDR = mkUnqual varName (fsLit "foreign")
816 \end{code}
817
818
819 \begin{code}
820         -- The parser left-associates, so there should 
821         -- not be any OpApps inside the e's
822 splitBang :: LHsExpr RdrName -> Maybe (LHsExpr RdrName, [LHsExpr RdrName])
823 -- Splits (f ! g a b) into (f, [(! g), a, b])
824 splitBang (L loc (OpApp l_arg bang@(L _ (HsVar op)) _ r_arg))
825   | op == bang_RDR = Just (l_arg, L loc (SectionR bang arg1) : argns)
826   where
827     (arg1,argns) = split_bang r_arg []
828     split_bang (L _ (HsApp f e)) es = split_bang f (e:es)
829     split_bang e                 es = (e,es)
830 splitBang _ = Nothing
831
832 isFunLhs :: LHsExpr RdrName 
833          -> P (Maybe (Located RdrName, Bool, [LHsExpr RdrName]))
834 -- A variable binding is parsed as a FunBind.
835 -- Just (fun, is_infix, arg_pats) if e is a function LHS
836 --
837 -- The whole LHS is parsed as a single expression.  
838 -- Any infix operators on the LHS will parse left-associatively
839 -- E.g.         f !x y !z
840 --      will parse (rather strangely) as 
841 --              (f ! x y) ! z
842 --      It's up to isFunLhs to sort out the mess
843 --
844 -- a .!. !b 
845
846 isFunLhs e = go e []
847  where
848    go (L loc (HsVar f)) es 
849         | not (isRdrDataCon f)   = return (Just (L loc f, False, es))
850    go (L _ (HsApp f e)) es       = go f (e:es)
851    go (L _ (HsPar e))   es@(_:_) = go e es
852
853         -- For infix function defns, there should be only one infix *function*
854         -- (though there may be infix *datacons* involved too).  So we don't
855         -- need fixity info to figure out which function is being defined.
856         --      a `K1` b `op` c `K2` d
857         -- must parse as
858         --      (a `K1` b) `op` (c `K2` d)
859         -- The renamer checks later that the precedences would yield such a parse.
860         -- 
861         -- There is a complication to deal with bang patterns.
862         --
863         -- ToDo: what about this?
864         --              x + 1 `op` y = ...
865
866    go e@(L loc (OpApp l (L loc' (HsVar op)) fix r)) es
867         | Just (e',es') <- splitBang e
868         = do { bang_on <- extension bangPatEnabled
869              ; if bang_on then go e' (es' ++ es)
870                else return (Just (L loc' op, True, (l:r:es))) }
871                 -- No bangs; behave just like the next case
872         | not (isRdrDataCon op)         -- We have found the function!
873         = return (Just (L loc' op, True, (l:r:es)))
874         | otherwise                     -- Infix data con; keep going
875         = do { mb_l <- go l es
876              ; case mb_l of
877                  Just (op', True, j : k : es')
878                     -> return (Just (op', True, j : op_app : es'))
879                     where
880                       op_app = L loc (OpApp k (L loc' (HsVar op)) fix r)
881                  _ -> return Nothing }
882    go _ _ = return Nothing
883
884 ---------------------------------------------------------------------------
885 -- Miscellaneous utilities
886
887 checkPrecP :: Located Int -> P Int
888 checkPrecP (L l i)
889  | 0 <= i && i <= maxPrecedence = return i
890  | otherwise                    = parseError l "Precedence out of range"
891
892 mkRecConstrOrUpdate 
893         :: LHsExpr RdrName 
894         -> SrcSpan
895         -> ([HsRecField RdrName (LHsExpr RdrName)], Bool)
896         -> P (HsExpr RdrName)
897
898 mkRecConstrOrUpdate (L l (HsVar c)) _ (fs,dd) | isRdrDataCon c
899   = return (RecordCon (L l c) noPostTcExpr (mk_rec_fields fs dd))
900 mkRecConstrOrUpdate exp loc (fs,dd)
901   | null fs   = parseError loc "Empty record update"
902   | otherwise = return (RecordUpd exp (mk_rec_fields fs dd) [] [] [])
903
904 mk_rec_fields :: [HsRecField id arg] -> Bool -> HsRecFields id arg
905 mk_rec_fields fs False = HsRecFields { rec_flds = fs, rec_dotdot = Nothing }
906 mk_rec_fields fs True  = HsRecFields { rec_flds = fs, rec_dotdot = Just (length fs) }
907
908 mkInlinePragma :: Maybe Activation -> RuleMatchInfo -> Bool -> InlinePragma
909 -- The Maybe is because the user can omit the activation spec (and usually does)
910 mkInlinePragma mb_act match_info inl 
911   = InlinePragma { inl_inline = inl
912                  , inl_sat    = Nothing
913                  , inl_act    = act
914                  , inl_rule   = match_info }
915   where
916     act = case mb_act of
917             Just act -> act
918             Nothing | inl       -> AlwaysActive
919                     | otherwise -> NeverActive
920         -- If no specific phase is given then:
921         --   NOINLINE => NeverActive
922         --   INLINE   => Active
923
924 -----------------------------------------------------------------------------
925 -- utilities for foreign declarations
926
927 -- construct a foreign import declaration
928 --
929 mkImport :: CCallConv
930          -> Safety 
931          -> (Located FastString, Located RdrName, LHsType RdrName) 
932          -> P (HsDecl RdrName)
933 mkImport cconv safety (L loc entity, v, ty)
934   | cconv == PrimCallConv                      = do
935   let funcTarget = CFunction (StaticTarget entity Nothing)
936       importSpec = CImport PrimCallConv safety nilFS funcTarget
937   return (ForD (ForeignImport v ty importSpec))
938
939   | otherwise = do
940     case parseCImport cconv safety (mkExtName (unLoc v)) (unpackFS entity) of
941       Nothing         -> parseError loc "Malformed entity string"
942       Just importSpec -> return (ForD (ForeignImport v ty importSpec))
943
944 -- the string "foo" is ambigous: either a header or a C identifier.  The
945 -- C identifier case comes first in the alternatives below, so we pick
946 -- that one.
947 parseCImport :: CCallConv -> Safety -> FastString -> String
948              -> Maybe ForeignImport
949 parseCImport cconv safety nm str =
950  listToMaybe $ map fst $ filter (null.snd) $ 
951      readP_to_S parse str
952  where
953    parse = do
954        skipSpaces
955        r <- choice [
956           string "dynamic" >> return (mk nilFS (CFunction DynamicTarget)),
957           string "wrapper" >> return (mk nilFS CWrapper),
958           optional (string "static" >> skipSpaces) >> 
959            (mk nilFS <$> cimp nm) +++
960            (do h <- munch1 hdr_char; skipSpaces; mk (mkFastString h) <$> cimp nm)
961          ]
962        skipSpaces
963        return r
964
965    mk = CImport cconv safety
966
967    hdr_char c = not (isSpace c) -- header files are filenames, which can contain
968                                 -- pretty much any char (depending on the platform),
969                                 -- so just accept any non-space character
970    id_char  c = isAlphaNum c || c == '_'
971
972    cimp nm = (ReadP.char '&' >> skipSpaces >> CLabel <$> cid)
973              +++ ((\c -> CFunction (StaticTarget c Nothing)) <$> cid)
974           where 
975             cid = return nm +++
976                   (do c  <- satisfy (\c -> isAlpha c || c == '_')
977                       cs <-  many (satisfy id_char)
978                       return (mkFastString (c:cs)))
979
980
981 -- construct a foreign export declaration
982 --
983 mkExport :: CCallConv
984          -> (Located FastString, Located RdrName, LHsType RdrName) 
985          -> P (HsDecl RdrName)
986 mkExport cconv (L _ entity, v, ty) = return $
987   ForD (ForeignExport v ty (CExport (CExportStatic entity' cconv)))
988   where
989     entity' | nullFS entity = mkExtName (unLoc v)
990             | otherwise     = entity
991
992 -- Supplying the ext_name in a foreign decl is optional; if it
993 -- isn't there, the Haskell name is assumed. Note that no transformation
994 -- of the Haskell name is then performed, so if you foreign export (++),
995 -- it's external name will be "++". Too bad; it's important because we don't
996 -- want z-encoding (e.g. names with z's in them shouldn't be doubled)
997 --
998 mkExtName :: RdrName -> CLabelString
999 mkExtName rdrNm = mkFastString (occNameString (rdrNameOcc rdrNm))
1000 \end{code}
1001
1002
1003 -----------------------------------------------------------------------------
1004 -- Misc utils
1005
1006 \begin{code}
1007 parseError :: SrcSpan -> String -> P a
1008 parseError span s = parseErrorSDoc span (text s)
1009
1010 parseErrorSDoc :: SrcSpan -> SDoc -> P a
1011 parseErrorSDoc span s = failSpanMsgP span s
1012 \end{code}