[project @ 1998-12-02 13:17:09 by simonm]
[ghc-hetmet.git] / ghc / compiler / rename / RnExpr.lhs
index 8c98852..7749aea 100644 (file)
@@ -1,5 +1,5 @@
 %
-% (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
+% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
 %
 \section[RnExpr]{Renaming of expressions}
 
@@ -10,15 +10,15 @@ general, all of these functions return a renamed thing, and a set of
 free variables.
 
 \begin{code}
-#include "HsVersions.h"
-
 module RnExpr (
        rnMatch, rnGRHSsAndBinds, rnPat,
        checkPrecMatch
    ) where
 
-IMP_Ubiq()
-IMPORT_DELOOPER(RnLoop)                -- break the RnPass/RnExpr/RnBinds loops
+#include "HsVersions.h"
+
+import {-# SOURCE #-} RnBinds  ( rnBinds ) 
+import {-# SOURCE #-} RnSource ( rnHsSigType )
 
 import HsSyn
 import RdrHsSyn
@@ -26,27 +26,23 @@ import RnHsSyn
 import RnMonad
 import RnEnv
 import CmdLineOpts     ( opt_GlasgowExts )
-import BasicTypes      ( Fixity(..), FixityDirection(..) )
-import PrelInfo                ( numClass_RDR, fractionalClass_RDR, eqClass_RDR, ccallableClass_RDR,
-                         creturnableClass_RDR, monadZeroClass_RDR, enumClass_RDR, ordClass_RDR,
-                         ratioDataCon_RDR, negate_RDR
+import BasicTypes      ( Fixity(..), FixityDirection(..), IfaceFlavour(..) )
+import PrelInfo                ( numClass_RDR, fractionalClass_RDR, eqClass_RDR, 
+                         ccallableClass_RDR, creturnableClass_RDR, 
+                         monadZeroClass_RDR, enumClass_RDR, ordClass_RDR,
+                         ratioDataCon_RDR, negate_RDR, assertErr_RDR,
+                         ioDataCon_RDR
                        )
 import TysPrim         ( charPrimTyCon, addrPrimTyCon, intPrimTyCon, 
                          floatPrimTyCon, doublePrimTyCon
                        )
-import TyCon           ( TyCon )
-import Id              ( GenId )
-import ErrUtils                ( addErrLoc, addShortErrLocLine )
-import Name
-import Pretty
-import UniqFM          ( lookupUFM{-, ufmToList ToDo:rm-} )
-import UniqSet         ( emptyUniqSet, unitUniqSet,
-                         unionUniqSets, unionManyUniqSets,
-                         SYN_IE(UniqSet)
-                       )
-import Util            ( Ord3(..), removeDups, panic, pprPanic, assertPanic )
+import Name            ( nameUnique, isLocallyDefined, NamedThing(..) )
+import NameSet
+import UniqFM          ( isNullUFM )
+import UniqSet         ( emptyUniqSet, UniqSet )
+import Unique          ( assertIdKey )
+import Util            ( removeDups )
 import Outputable
-
 \end{code}
 
 
@@ -116,14 +112,14 @@ rnPat (NPlusKPatIn name lit)
     returnRn (NPlusKPatIn name' lit)
 
 rnPat (ListPatIn pats)
-  = addImplicitOccRn listType_name     `thenRn_` 
+  = addImplicitOccRn listTyCon_name    `thenRn_` 
     mapRn rnPat pats                   `thenRn` \ patslist ->
     returnRn (ListPatIn patslist)
 
-rnPat (TuplePatIn pats)
-  = addImplicitOccRn (tupleType_name (length pats))    `thenRn_` 
+rnPat (TuplePatIn pats boxed)
+  = addImplicitOccRn (tupleTyCon_name boxed (length pats)) `thenRn_`
     mapRn rnPat pats                                   `thenRn` \ patslist ->
-    returnRn (TuplePatIn patslist)
+    returnRn (TuplePatIn patslist boxed)
 
 rnPat (RecPatIn con rpats)
   = lookupOccRn con    `thenRn` \ con' ->
@@ -138,17 +134,35 @@ rnPat (RecPatIn con rpats)
 ************************************************************************
 
 \begin{code}
-rnMatch :: RdrNameMatch -> RnMS s (RenamedMatch, FreeVars)
+rnMatch, rnMatch1 :: RdrNameMatch -> RnMS s (RenamedMatch, FreeVars)
+
+-- The only tricky bit here is that we want to do a single
+-- bindLocalsRn for all the matches together, so that we spot
+-- the repeated variable in
+--     f x x = 1
 
-rnMatch (PatMatch pat match)
-  = bindLocalsRn "pattern" binders     $ \ new_binders ->
-    rnPat pat                          `thenRn` \ pat' ->
-    rnMatch match                      `thenRn` \ (match', fvMatch) ->
-    returnRn (PatMatch pat' match', fvMatch `minusNameSet` mkNameSet new_binders)
+rnMatch match
+  = pushSrcLocRn (getMatchLoc match) $
+    bindLocalsRn "pattern" (get_binders        match)  $ \ new_binders ->
+    rnMatch1 match                             `thenRn` \ (match', fvs) ->
+    let
+       binder_set     = mkNameSet new_binders
+       unused_binders = binder_set `minusNameSet` fvs
+       net_fvs        = fvs `minusNameSet` binder_set
+    in
+    warnUnusedMatches unused_binders           `thenRn_`
+    
+    returnRn (match', net_fvs)
  where
-    binders = collectPatBinders pat
+    get_binders (GRHSMatch _)       = []
+    get_binders (PatMatch pat match) = collectPatBinders pat ++ get_binders match
 
-rnMatch (GRHSMatch grhss_and_binds)
+rnMatch1 (PatMatch pat match)
+  = rnPat pat                          `thenRn` \ pat' ->
+    rnMatch1 match                     `thenRn` \ (match', fvs) ->
+    returnRn (PatMatch pat' match', fvs)
+
+rnMatch1 (GRHSMatch grhss_and_binds)
   = rnGRHSsAndBinds grhss_and_binds `thenRn` \ (grhss_and_binds', fvs) ->
     returnRn (GRHSMatch grhss_and_binds', fvs)
 \end{code}
@@ -174,32 +188,23 @@ rnGRHSsAndBinds (GRHSsAndBindsIn grhss binds)
        rnGRHSs grhss  `thenRn` \ (grhss', fvss) ->
        returnRn (grhs' : grhss', fvs `unionNameSets` fvss)
 
-    rnGRHS (GRHS guard expr locn)
+    rnGRHS (GRHS guarded locn)
       = pushSrcLocRn locn $                
-       (if not (opt_GlasgowExts || is_standard_guard guard) then
-               addWarnRn (nonStdGuardErr guard)
+       (if not (opt_GlasgowExts || is_standard_guard guarded) then
+               addWarnRn (nonStdGuardErr guarded)
         else
                returnRn ()
        )               `thenRn_`
 
-       (rnStmts rnExpr guard   $ \ guard' ->
-               -- This nested thing deals with scope and
-               -- the free vars of the guard, and knocking off the
-               -- free vars of the rhs that are bound by the guard
-
-       rnExpr expr     `thenRn` \ (expr',  fvse) ->
-       returnRn (GRHS guard' expr' locn, fvse))
-
-    rnGRHS (OtherwiseGRHS expr locn)
-      = pushSrcLocRn locn $
-       rnExpr expr     `thenRn` \ (expr', fvs) ->
-       returnRn (GRHS [] expr' locn, fvs)
+       rnStmts rnExpr guarded  `thenRn` \ (guarded', fvs) ->
+       returnRn (GRHS guarded' locn, fvs)
 
        -- Standard Haskell 1.4 guards are just a single boolean
        -- expression, rather than a list of qualifiers as in the
        -- Glasgow extension
-    is_standard_guard [GuardStmt _ _] = True
-    is_standard_guard other          = False
+    is_standard_guard [ExprStmt _ _]                = True
+    is_standard_guard [GuardStmt _ _, ExprStmt _ _] = True
+    is_standard_guard other                        = False
 \end{code}
 
 %************************************************************************
@@ -210,15 +215,23 @@ rnGRHSsAndBinds (GRHSsAndBindsIn grhss binds)
 
 \begin{code}
 rnExprs :: [RdrNameHsExpr] -> RnMS s ([RenamedHsExpr], FreeVars)
-rnExprs ls =
- rnExprs' ls [] `thenRn` \  (exprs, fvExprs) ->
- returnRn (exprs, unionManyNameSets fvExprs)
-
-rnExprs' [] acc = returnRn ([], acc)
-rnExprs' (expr:exprs) acc
-  = rnExpr expr                `thenRn` \ (expr', fvExpr) ->
-    rnExprs' exprs (fvExpr:acc)        `thenRn` \ (exprs', fvExprs) ->
+rnExprs ls = rnExprs' ls emptyUniqSet
+ where
+  rnExprs' [] acc = returnRn ([], acc)
+  rnExprs' (expr:exprs) acc
+   = rnExpr expr               `thenRn` \ (expr', fvExpr) ->
+
+       -- Now we do a "seq" on the free vars because typically it's small
+       -- or empty, especially in very long lists of constants
+    let
+       acc' = acc `unionNameSets` fvExpr
+    in
+    (grubby_seqNameSet acc' rnExprs') exprs acc'       `thenRn` \ (exprs', fvExprs) ->
     returnRn (expr':exprs', fvExprs)
+
+-- Grubby little function to do "seq" on namesets; replace by proper seq when GHC can do seq
+grubby_seqNameSet ns result | isNullUFM ns = result
+                           | otherwise    = result
 \end{code}
 
 Variables. We look up the variable and return the resulting name.  The
@@ -232,10 +245,16 @@ free-var set iff if it's a LocallyDefined Name.
 rnExpr :: RdrNameHsExpr -> RnMS s (RenamedHsExpr, FreeVars)
 
 rnExpr (HsVar v)
-  = lookupOccRn v      `thenRn` \ vname ->
-    returnRn (HsVar vname, if isLocallyDefined vname
-                          then unitNameSet vname
-                          else emptyUniqSet)
+  = lookupOccRn v      `thenRn` \ name ->
+    if nameUnique name == assertIdKey then
+       -- We expand it to (GHCerr.assert__ location)
+        mkAssertExpr  `thenRn` \ expr ->
+       returnRn (expr, emptyUniqSet)
+    else
+        -- The normal case
+       returnRn (HsVar name, if isLocallyDefined name
+                            then unitNameSet name
+                            else emptyUniqSet)
 
 rnExpr (HsLit lit) 
   = litOccurrence lit          `thenRn_`
@@ -262,8 +281,8 @@ rnExpr (OpApp e1 op@(HsVar op_name) _ e2)
     lookupFixity op_name               `thenRn` \ fixity ->
     getModeRn                          `thenRn` \ mode -> 
     (case mode of
-       SourceMode      -> mkOpAppRn e1' op' fixity e2'
-       InterfaceMode _ -> returnRn (OpApp e1' op' fixity e2')
+       SourceMode        -> mkOpAppRn e1' op' fixity e2'
+       InterfaceMode _ _ -> returnRn (OpApp e1' op' fixity e2')
     )                                  `thenRn` \ final_e -> 
 
     returnRn (final_e,
@@ -290,8 +309,10 @@ rnExpr (SectionR op expr)
     returnRn (SectionR op' expr', fvs_op `unionNameSets` fvs_expr)
 
 rnExpr (CCall fun args may_gc is_casm fake_result_ty)
+       -- Check out the comment on RnIfaces.getNonWiredDataDecl about ccalls
   = lookupImplicitOccRn ccallableClass_RDR     `thenRn_`
     lookupImplicitOccRn creturnableClass_RDR   `thenRn_`
+    lookupImplicitOccRn ioDataCon_RDR          `thenRn_`
     rnExprs args                               `thenRn` \ (args', fvs_args) ->
     returnRn (CCall fun args' may_gc is_casm fake_result_ty, fvs_args)
 
@@ -313,23 +334,23 @@ rnExpr (HsLet binds expr)
 rnExpr (HsDo do_or_lc stmts src_loc)
   = pushSrcLocRn src_loc $
     lookupImplicitOccRn monadZeroClass_RDR     `thenRn_`       -- Forces Monad to come too
-    (rnStmts rnExpr stmts                      $ \ stmts' ->
-    returnRn (HsDo do_or_lc stmts' src_loc, emptyNameSet))
+    rnStmts rnExpr stmts                       `thenRn` \ (stmts', fvs) ->
+    returnRn (HsDo do_or_lc stmts' src_loc, fvs)
 
 rnExpr (ExplicitList exps)
-  = addImplicitOccRn listType_name     `thenRn_` 
+  = addImplicitOccRn listTyCon_name    `thenRn_` 
     rnExprs exps                       `thenRn` \ (exps', fvs) ->
     returnRn  (ExplicitList exps', fvs)
 
-rnExpr (ExplicitTuple exps)
-  = addImplicitOccRn (tupleType_name (length exps))    `thenRn_` 
-    rnExprs exps                                       `thenRn` \ (exps', fvExps) ->
-    returnRn (ExplicitTuple exps', fvExps)
+rnExpr (ExplicitTuple exps boxed)
+  = addImplicitOccRn (tupleTyCon_name boxed (length exps)) `thenRn_` 
+    rnExprs exps                               `thenRn` \ (exps', fvExps) ->
+    returnRn (ExplicitTuple exps' boxed, fvExps)
 
-rnExpr (RecordCon (HsVar con) rbinds)
-  = lookupOccRn con                    `thenRn` \ conname ->
+rnExpr (RecordCon con_id rbinds)
+  = lookupOccRn con_id                         `thenRn` \ conname ->
     rnRbinds "construction" rbinds     `thenRn` \ (rbinds', fvRbinds) ->
-    returnRn (RecordCon (HsVar conname) rbinds', fvRbinds)
+    returnRn (RecordCon conname rbinds', fvRbinds)
 
 rnExpr (RecordUpd expr rbinds)
   = rnExpr expr                        `thenRn` \ (expr', fvExpr) ->
@@ -337,8 +358,8 @@ rnExpr (RecordUpd expr rbinds)
     returnRn (RecordUpd expr' rbinds', fvExpr `unionNameSets` fvRbinds)
 
 rnExpr (ExprWithTySig expr pty)
-  = rnExpr expr                                                `thenRn` \ (expr', fvExpr) ->
-    rnHsSigType (\ sty -> text "an expression") pty    `thenRn` \ pty' ->
+  = rnExpr expr                                        `thenRn` \ (expr', fvExpr) ->
+    rnHsSigType (text "an expression") pty     `thenRn` \ pty' ->
     returnRn (ExprWithTySig expr' pty', fvExpr)
 
 rnExpr (HsIf p b1 b2 src_loc)
@@ -387,7 +408,7 @@ rnRbinds str rbinds
     mapAndUnzipRn rn_rbind rbinds      `thenRn` \ (rbinds', fvRbind_s) ->
     returnRn (rbinds', unionManyNameSets fvRbind_s)
   where
-    (_, dup_fields) = removeDups cmp [ f | (f,_,_) <- rbinds ]
+    (_, dup_fields) = removeDups compare [ f | (f,_,_) <- rbinds ]
 
     field_dup_err dups = addErrRn (dupFieldErr str dups)
 
@@ -400,7 +421,7 @@ rnRpats rpats
   = mapRn field_dup_err dup_fields     `thenRn_`
     mapRn rn_rpat rpats
   where
-    (_, dup_fields) = removeDups cmp [ f | (f,_,_) <- rpats ]
+    (_, dup_fields) = removeDups compare [ f | (f,_,_) <- rpats ]
 
     field_dup_err dups = addErrRn (dupFieldErr "pattern" dups)
 
@@ -429,18 +450,19 @@ type RnExprTy s = RdrNameHsExpr -> RnMS s (RenamedHsExpr, FreeVars)
 
 rnStmts :: RnExprTy s
        -> [RdrNameStmt] 
-       -> ([RenamedStmt] -> RnMS s (a, FreeVars))
-       -> RnMS s (a, FreeVars)
+       -> RnMS s ([RenamedStmt], FreeVars)
 
-rnStmts rn_expr [] thing_inside 
-  = thing_inside []
+rnStmts rn_expr []
+  = returnRn ([], emptyNameSet)
 
-rnStmts rn_expr (stmt:stmts) thing_inside
+rnStmts rn_expr (stmt:stmts)
   = rnStmt rn_expr stmt                                $ \ stmt' ->
-    rnStmts rn_expr stmts                      $ \ stmts' ->
-    thing_inside (stmt' : stmts')
+    rnStmts rn_expr stmts                      `thenRn` \ (stmts', fvs) ->
+    returnRn (stmt' : stmts', fvs)
 
-rnStmt :: RnExprTy s -> RdrNameStmt -> (RenamedStmt -> RnMS s (a, FreeVars)) -> RnMS s (a, FreeVars)
+rnStmt :: RnExprTy s -> RdrNameStmt
+       -> (RenamedStmt -> RnMS s (a, FreeVars))
+       -> RnMS s (a, FreeVars)
 -- Because of mutual recursion we have to pass in rnExpr.
 
 rnStmt rn_expr (BindStmt pat expr src_loc) thing_inside
@@ -523,7 +545,9 @@ mkOpAppRn e1@(NegApp neg_arg neg_op)
     (nofix_error, rearrange_me) = compareFixity fix_neg fix2
 
 mkOpAppRn e1 op fix e2                         -- Default case, no rearrangment
-  = ASSERT( right_op_ok fix e2 )
+  = ASSERT( if right_op_ok fix e2 then True
+           else pprPanic "mkOpAppRn" (vcat [ppr e1, text "---", ppr op, text "---", ppr fix, text "---", ppr e2])
+    )
     returnRn (OpApp e1 op fix e2)
 
 get (HsVar n) = n
@@ -629,10 +653,10 @@ compareFixity :: Fixity -> Fixity
              -> (Bool,         -- Error please
                  Bool)         -- Associate to the right: a op1 (b op2 c)
 compareFixity (Fixity prec1 dir1) (Fixity prec2 dir2)
-  = case prec1 `cmp` prec2 of
-       GT_ -> left
-       LT_ -> right
-       EQ_ -> case (dir1, dir2) of
+  = case prec1 `compare` prec2 of
+       GT -> left
+       LT -> right
+       EQ -> case (dir1, dir2) of
                        (InfixR, InfixR) -> right
                        (InfixL, InfixL) -> left
                        _                -> error_please
@@ -653,14 +677,14 @@ are made available.
 
 \begin{code}
 litOccurrence (HsChar _)
-  = addImplicitOccRn charType_name
+  = addImplicitOccRn charTyCon_name
 
 litOccurrence (HsCharPrim _)
   = addImplicitOccRn (getName charPrimTyCon)
 
 litOccurrence (HsString _)
-  = addImplicitOccRn listType_name     `thenRn_`
-    addImplicitOccRn charType_name
+  = addImplicitOccRn listTyCon_name    `thenRn_`
+    addImplicitOccRn charTyCon_name
 
 litOccurrence (HsStringPrim _)
   = addImplicitOccRn (getName addrPrimTyCon)
@@ -673,7 +697,9 @@ litOccurrence (HsFrac _)
     lookupImplicitOccRn ratioDataCon_RDR
        -- We have to make sure that the Ratio type is imported with
        -- its constructor, because literals of type Ratio t are
-       -- built with that constructor. 
+       -- built with that constructor.
+       -- The Rational type is needed too, but that will come in
+       -- when fractionalClass does.
     
 litOccurrence (HsIntPrim _)
   = addImplicitOccRn (getName intPrimTyCon)
@@ -688,6 +714,28 @@ litOccurrence (HsLitLit _)
   = lookupImplicitOccRn ccallableClass_RDR
 \end{code}
 
+%************************************************************************
+%*                                                                     *
+\subsubsection{Assertion utils}
+%*                                                                     *
+%************************************************************************
+
+\begin{code}
+mkAssertExpr :: RnMS s RenamedHsExpr
+mkAssertExpr =
+  newImportedGlobalName mod occ HiFile `thenRn` \ name ->
+  addOccurrenceName name              `thenRn_`
+  getSrcLocRn                          `thenRn` \ sloc ->
+  let
+   expr = HsApp (HsVar name)
+               (HsLit (HsString (_PK_ (showSDoc (ppr sloc)))))
+  in
+  returnRn expr
+
+  where
+   mod = rdrNameModule assertErr_RDR
+   occ = rdrNameOcc assertErr_RDR
+\end{code}
 
 %************************************************************************
 %*                                                                     *
@@ -696,28 +744,29 @@ litOccurrence (HsLitLit _)
 %************************************************************************
 
 \begin{code}
-dupFieldErr str (dup:rest) sty
-  = hcat [ptext SLIT("duplicate field name `"), 
-               ppr sty dup, 
-              ptext SLIT("' in record "), text str]
+dupFieldErr str (dup:rest)
+  = hsep [ptext SLIT("duplicate field name"), 
+          quotes (ppr dup),
+         ptext SLIT("in record"), text str]
 
-negPatErr pat  sty
-  = sep [ptext SLIT("prefix `-' not applied to literal in pattern"), ppr sty pat]
+negPatErr pat 
+  = sep [ptext SLIT("prefix `-' not applied to literal in pattern"), quotes (ppr pat)]
 
-precParseNegPatErr op sty 
+precParseNegPatErr op 
   = hang (ptext SLIT("precedence parsing error"))
-      4 (hcat [ptext SLIT("prefix `-' has lower precedence than "), 
-                   pp_op sty op, 
-                   ptext SLIT(" in pattern")])
+      4 (hsep [ptext SLIT("prefix `-' has lower precedence than"), 
+              quotes (pp_op op), 
+              ptext SLIT("in pattern")])
 
-precParseErr op1 op2  sty
+precParseErr op1 op2 
   = hang (ptext SLIT("precedence parsing error"))
-      4 (hcat [ptext SLIT("cannot mix "), pp_op sty op1, ptext SLIT(" and "), pp_op sty op2,
-                   ptext SLIT(" in the same infix expression")])
+      4 (hsep [ptext SLIT("cannot mix"), quotes (pp_op op1), ptext SLIT("and"), 
+              quotes (pp_op op2),
+              ptext SLIT("in the same infix expression")])
 
-nonStdGuardErr guard sty
+nonStdGuardErr guard
   = hang (ptext SLIT("accepting non-standard pattern guards (-fglasgow-exts to suppress this message)"))
-      4 (ppr sty guard)
+      4 (ppr guard)
 
-pp_op sty (op, fix) = hcat [ppr sty op, space, parens (ppr sty fix)]
+pp_op (op, fix) = hcat [ppr op, space, parens (ppr fix)]
 \end{code}