[project @ 1997-09-04 20:21:37 by sof]
[ghc-hetmet.git] / ghc / compiler / coreSyn / CoreLint.lhs
index d7f70ca..9a43628 100644 (file)
@@ -13,21 +13,25 @@ module CoreLint (
 
 IMP_Ubiq()
 
+import CmdLineOpts      ( opt_D_show_passes, opt_PprUserLength, opt_DoCoreLinting )
 import CoreSyn
 
 import Bag
-import Kind            ( hasMoreBoxityInfo, Kind{-instance-} )
+import Kind            ( hasMoreBoxityInfo, Kind{-instance-}, 
+                         isTypeKind, isBoxedTypeKind {- TEMP --SOF -} )
 import Literal         ( literalType, Literal{-instance-} )
-import Id              ( idType, isBottomingId,
+import Id              ( idType, isBottomingId, dataConRepType, isDataCon, isNewCon,
                          dataConArgTys, GenId{-instances-},
                          emptyIdSet, mkIdSet, intersectIdSets,
-                         unionIdSets, elementOfIdSet, IdSet(..)
+                         unionIdSets, elementOfIdSet, SYN_IE(IdSet),
+                         SYN_IE(Id)
                        )
 import Maybes          ( catMaybes )
-import Name            ( isLocallyDefined, getSrcLoc, Name{-instance NamedThing-} )
-import Outputable      ( Outputable(..){-instance * []-} )
+import Name            ( isLocallyDefined, getSrcLoc, Name{-instance NamedThing-},
+                         NamedThing(..) )
 import PprCore
-import PprStyle                ( PprStyle(..) )
+import Outputable      ( PprStyle(..), Outputable(..), pprErrorsStyle, printErrs )
+import ErrUtils                ( doIfSet, ghcExit )
 import PprType         ( GenType, GenTyVar, TyCon )
 import Pretty
 import PrimOp          ( primOpType, PrimOp(..) )
@@ -38,13 +42,12 @@ import Type         ( mkFunTy,getFunTy_maybe,mkForAllTy,mkForAllTys,getForAllTy_maybe,
                          getForAllTyExpandingDicts_maybe,
                          isPrimType,typeKind,instantiateTy,splitSigmaTy,
                          mkForAllUsageTy,getForAllUsageTy,instantiateUsage,
-                         maybeAppDataTyConExpandingDicts, eqTy
---                       ,expandTy -- ToDo:rm
+                         maybeAppDataTyConExpandingDicts, eqTy, SYN_IE(Type)
                        )
-import TyCon           ( isPrimTyCon )
+import TyCon           ( isPrimTyCon, isDataTyCon )
 import TyVar           ( tyVarKind, GenTyVar{-instances-} )
 import Unique          ( Unique )
-import Usage           ( GenUsage )
+import Usage           ( GenUsage, SYN_IE(Usage) )
 import Util            ( zipEqual, pprTrace, pprPanic, assertPanic, panic )
 
 infixr 9 `thenL`, `seqL`, `thenMaybeL`, `seqMaybeL`
@@ -84,25 +87,33 @@ Outstanding issues:
     --
 
 \begin{code}
-lintCoreBindings
-       :: PprStyle -> String -> Bool -> [CoreBinding] -> [CoreBinding]
+lintCoreBindings :: String -> Bool -> [CoreBinding] -> IO ()
 
-lintCoreBindings sty whoDunnit spec_done binds
+lintCoreBindings whoDunnit spec_done binds
+  | not opt_DoCoreLinting
+  = return ()
+
+lintCoreBindings whoDunnit spec_done binds
   = case (initL (lint_binds binds) spec_done) of
-      Nothing  -> binds
-      Just msg ->
-       pprPanic "" (ppAboves [
-         ppStr ("*** Core Lint Errors: in " ++ whoDunnit ++ " ***"),
-         msg sty,
-         ppStr "*** Offending Program ***",
-         ppAboves (map (pprCoreBinding sty) binds),
-         ppStr "*** End of Offense ***"
-       ])
+      Nothing       -> doIfSet opt_D_show_passes
+                       (hPutStr stderr ("*** Core Linted result of " ++ whoDunnit ++ "\n"))
+
+      Just bad_news -> printErrs (display bad_news)    >>
+                      ghcExit 1
   where
     lint_binds [] = returnL ()
     lint_binds (bind:binds)
       = lintCoreBinding bind `thenL` \binders ->
        addInScopeVars binders (lint_binds binds)
+
+    display bad_news
+      = vcat [
+               text ("*** Core Lint Errors: in result of " ++ whoDunnit ++ " ***"),
+               bad_news pprErrorsStyle,
+               ptext SLIT("*** Offending Program ***"),
+               pprCoreBindings pprErrorsStyle binds,
+               ptext SLIT("*** End of Offense ***")
+       ]
 \end{code}
 
 %************************************************************************
@@ -125,10 +136,10 @@ lintUnfolding locn expr
       Nothing  -> Just expr
       Just msg ->
         pprTrace "WARNING: Discarded bad unfolding from interface:\n"
-       (ppAboves [msg PprForUser,
-                  ppStr "*** Bad unfolding ***",
+       (vcat [msg (PprForUser opt_PprUserLength),
+                  ptext SLIT("*** Bad unfolding ***"),
                   ppr PprDebug expr,
-                  ppStr "*** End unfolding ***"])
+                  ptext SLIT("*** End unfolding ***")])
        Nothing
 \end{code}
 
@@ -186,8 +197,9 @@ lintCoreExpr :: CoreExpr -> LintM (Maybe Type)      -- Nothing if error found
 lintCoreExpr (Var var) = checkInScope var `seqL` returnL (Just (idType var))
 lintCoreExpr (Lit lit) = returnL (Just (literalType lit))
 lintCoreExpr (SCC _ expr) = lintCoreExpr expr
-lintCoreExpr (Coerce _ ty expr)
-  = lintCoreExpr expr `seqL` returnL (Just ty)
+lintCoreExpr e@(Coerce coercion ty expr)
+  = lintCoercion e coercion    `seqL`
+    lintCoreExpr expr `seqL` returnL (Just ty)
 
 lintCoreExpr (Let binds body)
   = lintCoreBinding binds `thenL` \binders ->
@@ -198,14 +210,9 @@ lintCoreExpr (Let binds body)
        (addInScopeVars binders (lintCoreExpr body))
 
 lintCoreExpr e@(Con con args)
-  = lintCoreArgs {-False-} e unoverloaded_ty args
+  = checkL (isDataCon con) (mkConErrMsg e)     `seqL`
+    lintCoreArgs {-False-} e (dataConRepType con) args
     -- Note: we don't check for primitive types in these arguments
-  where
-       -- Constructors are special in that they aren't passed their
-       -- dictionary arguments, so we swizzle them out of the
-       -- constructor type before handing over to lintCorArgs
-    unoverloaded_ty = mkForAllTys tyvars tau
-    (tyvars, theta, tau) = splitSigmaTy (idType con)
 
 lintCoreExpr e@(Prim op args)
   = lintCoreArgs {-True-} e (primOpType op) args
@@ -264,7 +271,7 @@ lintCoreArg :: {-Bool ->-} CoreExpr -> Type -> CoreArg -> LintM (Maybe Type)
 
 lintCoreArg e ty (LitArg lit)
   = -- Make sure function type matches argument
-    case (getFunTyExpandingDicts_maybe ty) of
+    case (getFunTyExpandingDicts_maybe False{-no peeking in newtypes-} ty) of
       Just (arg,res) | (lit_ty `eqTy` arg) -> returnL(Just res)
       _ -> addErrL (mkAppMsg ty lit_ty e) `seqL` returnL Nothing
   where
@@ -274,7 +281,7 @@ lintCoreArg e ty (VarArg v)
   = -- Make sure variable is bound
     checkInScope v `seqL`
     -- Make sure function type matches argument
-    case (getFunTyExpandingDicts_maybe ty) of
+    case (getFunTyExpandingDicts_maybe False{-as above-} ty) of
       Just (arg,res) | (var_ty `eqTy` arg) -> returnL(Just res)
       _ -> addErrL (mkAppMsg ty var_ty e) `seqL` returnL Nothing
   where
@@ -282,8 +289,6 @@ lintCoreArg e ty (VarArg v)
 
 lintCoreArg e ty a@(TyArg arg_ty)
   = -- ToDo: Check that ty is well-kinded and has no unbound tyvars
-    checkIfSpecDoneL (not (isPrimType arg_ty)) (mkSpecTyAppMsg a)
-    `seqL`
     case (getForAllTyExpandingDicts_maybe ty) of
       Nothing -> addErrL (mkTyAppMsg SLIT("Illegal") ty arg_ty e) `seqL` returnL Nothing
 
@@ -300,7 +305,7 @@ lintCoreArg e ty a@(TyArg arg_ty)
         then
            returnL(Just(instantiateTy [(tyvar,arg_ty)] body))
        else
-           pprTrace "lintCoreArg:kinds:" (ppCat [ppr PprDebug tyvar_kind, ppr PprDebug argty_kind]) $
+           pprTrace "lintCoreArg:kinds:" (hsep [ppr PprDebug tyvar_kind, ppr PprDebug argty_kind]) $
            addErrL (mkTyAppMsg SLIT("Kinds not right in") ty arg_ty e) `seqL` returnL Nothing
        
 lintCoreArg e ty (UsageArg u)
@@ -362,11 +367,9 @@ lintCoreAlts whole_alts@(PrimAlts alts deflt) ty --tycon
        where
          check ty = checkTys first_ty ty (mkCaseAltMsg whole_alts)
 
-lintAlgAlt scrut_ty {-tycon-ToDo: use it!-} (con,args,rhs)
+lintAlgAlt scrut_ty (con,args,rhs)
   = (case maybeAppDataTyConExpandingDicts scrut_ty of
-      Nothing ->
-        addErrL (mkAlgAltMsg1 scrut_ty)
-      Just (tycon, tys_applied, cons) ->
+      Just (tycon, tys_applied, cons) | isDataTyCon tycon ->
         let
           arg_tys = dataConArgTys con tys_applied
         in
@@ -375,6 +378,8 @@ lintAlgAlt scrut_ty {-tycon-ToDo: use it!-} (con,args,rhs)
                                                                 `seqL`
         mapL check (zipEqual "lintAlgAlt" arg_tys args)         `seqL`
         returnL ()
+
+      other -> addErrL (mkAlgAltMsg1 scrut_ty)
     )                                                           `seqL`
     addInScopeVars args        (
         lintCoreExpr rhs
@@ -400,6 +405,21 @@ lintDeflt deflt@(BindDefault binder rhs) ty
 
 %************************************************************************
 %*                                                                     *
+\subsection[lint-coercion]{Coercion}
+%*                                                                     *
+%************************************************************************
+
+\begin{code}
+lintCoercion e (CoerceIn  con) = check_con e con
+lintCoercion e (CoerceOut con) = check_con e con
+
+check_con e con = checkL (isNewCon con)
+                        (mkCoerceErrMsg e)
+\end{code}
+
+
+%************************************************************************
+%*                                                                     *
 \subsection[lint-monad]{The Lint monad}
 %*                                                                     *
 %************************************************************************
@@ -411,7 +431,7 @@ type LintM a = Bool         -- True <=> specialisation has been done
            -> Bag ErrMsg       -- Error messages so far
            -> (a, Bag ErrMsg)  -- Result and error messages (if any)
 
-type ErrMsg = PprStyle -> Pretty
+type ErrMsg = PprStyle -> Doc
 
 data LintLocInfo
   = RhsOf Id           -- The variable bound
@@ -421,24 +441,24 @@ data LintLocInfo
 
 instance Outputable LintLocInfo where
     ppr sty (RhsOf v)
-      = ppBesides [ppr sty (getSrcLoc v), ppStr ": [RHS of ", pp_binders sty [v], ppStr "]"]
+      = hcat [ppr sty (getSrcLoc v), ptext SLIT(": [RHS of "), pp_binders sty [v], char ']']
 
     ppr sty (LambdaBodyOf b)
-      = ppBesides [ppr sty (getSrcLoc b),
-               ppStr ": [in body of lambda with binder ", pp_binder sty b, ppStr "]"]
+      = hcat [ppr sty (getSrcLoc b),
+               ptext SLIT(": [in body of lambda with binder "), pp_binder sty b, char ']']
 
     ppr sty (BodyOfLetRec bs)
-      = ppBesides [ppr sty (getSrcLoc (head bs)),
-               ppStr ": [in body of letrec with binders ", pp_binders sty bs, ppStr "]"]
+      = hcat [ppr sty (getSrcLoc (head bs)),
+               ptext SLIT(": [in body of letrec with binders "), pp_binders sty bs, char ']']
 
     ppr sty (ImportedUnfolding locn)
-      = ppBeside (ppr sty locn) (ppStr ": [in an imported unfolding]")
+      = (<>) (ppr sty locn) (ptext SLIT(": [in an imported unfolding]"))
 
-pp_binders :: PprStyle -> [Id] -> Pretty
-pp_binders sty bs = ppInterleave ppComma (map (pp_binder sty) bs)
+pp_binders :: PprStyle -> [Id] -> Doc
+pp_binders sty bs = sep (punctuate comma (map (pp_binder sty) bs))
 
-pp_binder :: PprStyle -> Id -> Pretty
-pp_binder sty b = ppCat [ppr sty b, ppStr "::", ppr sty (idType b)]
+pp_binder :: PprStyle -> Id -> Doc
+pp_binder sty b = hsep [ppr sty b, text "::", ppr sty (idType b)]
 \end{code}
 
 \begin{code}
@@ -449,7 +469,7 @@ initL m spec_done
        Nothing
     else
        Just ( \ sty ->
-         ppAboves [ msg sty | msg <- bagToList errs ]
+         vcat [ msg sty | msg <- bagToList errs ]
        )
     }
 
@@ -515,7 +535,7 @@ addErr :: Bag ErrMsg -> ErrMsg -> [LintLocInfo] -> Bag ErrMsg
 addErr errs_so_far msg locs
   = ASSERT (not (null locs))
     errs_so_far `snocBag` ( \ sty ->
-    ppHang (ppr sty (head locs)) 4 (msg sty)
+    hang (ppr sty (head locs)) 4 (msg sty)
     )
 
 addLoc :: LintLocInfo -> LintM a -> LintM a
@@ -549,7 +569,7 @@ checkInScope id spec loc scope errs
        id_name = getName id
     in
     if isLocallyDefined id_name && not (id `elementOfIdSet` scope) then
-      ((),addErr errs (\sty -> ppCat [ppr sty id, ppStr "is out of scope"]) loc)
+      ((),addErr errs (\sty -> hsep [ppr sty id, ptext SLIT("is out of scope")]) loc)
     else
       ((),errs)
 
@@ -559,115 +579,124 @@ checkTys ty1 ty2 msg spec loc scope errs
 \end{code}
 
 \begin{code}
+mkConErrMsg e sty
+  = ($$) (ptext SLIT("Application of newtype constructor:"))
+           (ppr sty e)
+
+mkCoerceErrMsg e sty
+  = ($$) (ptext SLIT("Coercion using a datatype constructor:"))
+        (ppr sty e)
+
+
 mkCaseAltMsg :: CoreCaseAlts -> ErrMsg
 mkCaseAltMsg alts sty
-  = ppAbove (ppStr "Type of case alternatives not the same:")
+  = ($$) (ptext SLIT("Type of case alternatives not the same:"))
            (ppr sty alts)
 
 mkCaseDataConMsg :: CoreExpr -> ErrMsg
 mkCaseDataConMsg expr sty
-  = ppAbove (ppStr "A case scrutinee not of data constructor type:")
+  = ($$) (ptext SLIT("A case scrutinee not of data constructor type:"))
            (pp_expr sty expr)
 
 mkCaseNotPrimMsg :: TyCon -> ErrMsg
 mkCaseNotPrimMsg tycon sty
-  = ppAbove (ppStr "A primitive case on a non-primitive type:")
+  = ($$) (ptext SLIT("A primitive case on a non-primitive type:"))
            (ppr sty tycon)
 
 mkCasePrimMsg :: TyCon -> ErrMsg
 mkCasePrimMsg tycon sty
-  = ppAbove (ppStr "An algebraic case on a primitive type:")
+  = ($$) (ptext SLIT("An algebraic case on a primitive type:"))
            (ppr sty tycon)
 
 mkCaseAbstractMsg :: TyCon -> ErrMsg
 mkCaseAbstractMsg tycon sty
-  = ppAbove (ppStr "An algebraic case on some weird type:")
+  = ($$) (ptext SLIT("An algebraic case on some weird type:"))
            (ppr sty tycon)
 
 mkDefltMsg :: CoreCaseDefault -> ErrMsg
 mkDefltMsg deflt sty
-  = ppAbove (ppStr "Binder in case default doesn't match type of scrutinee:")
+  = ($$) (ptext SLIT("Binder in case default doesn't match type of scrutinee:"))
            (ppr sty deflt)
 
 mkAppMsg :: Type -> Type -> CoreExpr -> ErrMsg
 mkAppMsg fun arg expr sty
-  = ppAboves [ppStr "Argument value doesn't match argument type:",
-             ppHang (ppStr "Fun type:") 4 (ppr sty fun),
-             ppHang (ppStr "Arg type:") 4 (ppr sty arg),
-             ppHang (ppStr "Expression:") 4 (pp_expr sty expr)]
+  = vcat [ptext SLIT("Argument value doesn't match argument type:"),
+             hang (ptext SLIT("Fun type:")) 4 (ppr sty fun),
+             hang (ptext SLIT("Arg type:")) 4 (ppr sty arg),
+             hang (ptext SLIT("Expression:")) 4 (pp_expr sty expr)]
 
 mkTyAppMsg :: FAST_STRING -> Type -> Type -> CoreExpr -> ErrMsg
 mkTyAppMsg msg ty arg expr sty
-  = ppAboves [ppCat [ppPStr msg, ppStr "type application:"],
-             ppHang (ppStr "Exp type:")   4 (ppr sty ty),
-             ppHang (ppStr "Arg type:")   4 (ppr sty arg),
-             ppHang (ppStr "Expression:") 4 (pp_expr sty expr)]
+  = vcat [hsep [ptext msg, ptext SLIT("type application:")],
+             hang (ptext SLIT("Exp type:"))   4 (ppr sty ty),
+             hang (ptext SLIT("Arg type:"))   4 (ppr sty arg),
+             hang (ptext SLIT("Expression:")) 4 (pp_expr sty expr)]
 
 mkUsageAppMsg :: Type -> Usage -> CoreExpr -> ErrMsg
 mkUsageAppMsg ty u expr sty
-  = ppAboves [ppStr "Illegal usage application:",
-             ppHang (ppStr "Exp type:") 4 (ppr sty ty),
-             ppHang (ppStr "Usage exp:") 4 (ppr sty u),
-             ppHang (ppStr "Expression:") 4 (pp_expr sty expr)]
+  = vcat [ptext SLIT("Illegal usage application:"),
+             hang (ptext SLIT("Exp type:")) 4 (ppr sty ty),
+             hang (ptext SLIT("Usage exp:")) 4 (ppr sty u),
+             hang (ptext SLIT("Expression:")) 4 (pp_expr sty expr)]
 
 mkAlgAltMsg1 :: Type -> ErrMsg
 mkAlgAltMsg1 ty sty
-  = ppAbove (ppStr "In some case statement, type of scrutinee is not a data type:")
+  = ($$) (text "In some case statement, type of scrutinee is not a data type:")
            (ppr sty ty)
---         (ppAbove (ppr sty ty) (ppr sty (expandTy ty))) -- ToDo: rm
+--         (($$) (ppr sty ty) (ppr sty (expandTy ty))) -- ToDo: rm
 
 mkAlgAltMsg2 :: Type -> Id -> ErrMsg
 mkAlgAltMsg2 ty con sty
-  = ppAboves [
-       ppStr "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
+  = vcat [
+       text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
        ppr sty ty,
        ppr sty con
     ]
 
 mkAlgAltMsg3 :: Id -> [Id] -> ErrMsg
 mkAlgAltMsg3 con alts sty
-  = ppAboves [
-       ppStr "In some algebraic case alternative, number of arguments doesn't match constructor:",
+  = vcat [
+       text "In some algebraic case alternative, number of arguments doesn't match constructor:",
        ppr sty con,
        ppr sty alts
     ]
 
 mkAlgAltMsg4 :: Type -> Id -> ErrMsg
 mkAlgAltMsg4 ty arg sty
-  = ppAboves [
-       ppStr "In some algebraic case alternative, type of argument doesn't match data constructor:",
+  = vcat [
+       text "In some algebraic case alternative, type of argument doesn't match data constructor:",
        ppr sty ty,
        ppr sty arg
     ]
 
 mkPrimAltMsg :: (Literal, CoreExpr) -> ErrMsg
 mkPrimAltMsg alt sty
-  = ppAbove
-    (ppStr "In a primitive case alternative, type of literal doesn't match type of scrutinee:")
+  = ($$)
+    (text "In a primitive case alternative, type of literal doesn't match type of scrutinee:")
            (ppr sty alt)
 
 mkRhsMsg :: Id -> Type -> ErrMsg
 mkRhsMsg binder ty sty
-  = ppAboves
-    [ppCat [ppStr "The type of this binder doesn't match the type of its RHS:",
+  = vcat
+    [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
            ppr sty binder],
-     ppCat [ppStr "Binder's type:", ppr sty (idType binder)],
-     ppCat [ppStr "Rhs type:", ppr sty ty]]
+     hsep [ptext SLIT("Binder's type:"), ppr sty (idType binder)],
+     hsep [ptext SLIT("Rhs type:"), ppr sty ty]]
 
 mkRhsPrimMsg :: Id -> CoreExpr -> ErrMsg
 mkRhsPrimMsg binder rhs sty
-  = ppAboves [ppCat [ppStr "The type of this binder is primitive:",
+  = vcat [hsep [ptext SLIT("The type of this binder is primitive:"),
                     ppr sty binder],
-             ppCat [ppStr "Binder's type:", ppr sty (idType binder)]
+             hsep [ptext SLIT("Binder's type:"), ppr sty (idType binder)]
             ]
 
 mkSpecTyAppMsg :: CoreArg -> ErrMsg
 mkSpecTyAppMsg arg sty
-  = ppAbove
-      (ppStr "Unboxed types in a type application (after specialisation):")
+  = ($$)
+      (ptext SLIT("Unboxed types in a type application (after specialisation):"))
       (ppr sty arg)
 
-pp_expr :: PprStyle -> CoreExpr -> Pretty
+pp_expr :: PprStyle -> CoreExpr -> Doc
 pp_expr sty expr
   = pprCoreExpr sty (pprBigCoreBinder sty) (pprTypedCoreBinder sty) (pprTypedCoreBinder sty) expr
 \end{code}