git.iko.soy/rowtype-yoga/purescript-native
on golang help sign in
Merge branch 'master' into pure11
commitc95fe8edd472f216d8bc7dc5a9f0aa9844d11703 authorAndy Arvanitis <andyarvanitis@gmail.com> dateFri 30 Oct 2015, 18:46 (11 years ago) parentcd8e57f62192bd
53 files changed+652−449
examples/failing/1169.purs+12 examples/failing/1570.purs+6 examples/failing/EmptyClass.purs+7 examples/failing/ExtraRecordField.purs+1−2 examples/failing/MissingRecordField.purs+1−2 examples/failing/MutRec.purs+1 examples/passing/1570.purs+6 examples/passing/NakedConstraint.purs+1−1 examples/passing/TypedBinders.purs+6−1 psc/Main.hs+4−5 psci/PSCi.hs+5−5 purescript.cabal+3−1 src/Control/Monad/Logger.hs+74 src/Language/PureScript.hs+1 src/Language/PureScript/AST/Operators.hs+3−1 src/Language/PureScript/CodeGen/JS.hs+3−2 src/Language/PureScript/CodeGen/JS/Optimizer/Common.hs+2−1 src/Language/PureScript/CoreFn/Desugar.hs+4−3 src/Language/PureScript/Crash.hs+9 src/Language/PureScript/Docs/Convert.hs+1−1 src/Language/PureScript/Docs/RenderedCode/Render.hs+3−2 src/Language/PureScript/Environment.hs+2−1 src/Language/PureScript/Errors.hs+229−206 src/Language/PureScript/Externs.hs+22−21 src/Language/PureScript/Linter.hs+2−1 src/Language/PureScript/Linter/Exhaustive.hs+4−3 src/Language/PureScript/Make.hs+35−33 src/Language/PureScript/ModuleDependencies.hs+2−1 src/Language/PureScript/Parser/Declarations.hs+1−1 src/Language/PureScript/Pretty/JS.hs+3−2 src/Language/PureScript/Pretty/Kinds.hs+2−1 src/Language/PureScript/Pretty/Types.hs+13−6 src/Language/PureScript/Pretty/Values.hs+2−1 src/Language/PureScript/Sugar/BindingGroups.hs+17−15 src/Language/PureScript/Sugar/CaseDeclarations.hs+3−2 src/Language/PureScript/Sugar/DoNotation.hs+2−1 src/Language/PureScript/Sugar/Names.hs+8−3 src/Language/PureScript/Sugar/Names/Exports.hs+8−7 src/Language/PureScript/Sugar/Names/Imports.hs+7−6 src/Language/PureScript/Sugar/Operators.hs+3−2 src/Language/PureScript/Sugar/TypeClasses.hs+9−8 src/Language/PureScript/Sugar/TypeClasses/Deriving.hs+4−3 src/Language/PureScript/Sugar/TypeDeclarations.hs+14−20 src/Language/PureScript/TypeChecker.hs+15−14 src/Language/PureScript/TypeChecker/Entailment.hs+3−2 src/Language/PureScript/TypeChecker/Kinds.hs+4−3 src/Language/PureScript/TypeChecker/Monad.hs+1−1 src/Language/PureScript/TypeChecker/Skolems.hs+11−5 src/Language/PureScript/TypeChecker/Subsumption.hs+12−4 src/Language/PureScript/TypeChecker/Types.hs+52−43 src/Language/PureScript/TypeChecker/Unify.hs+3−2 tests/Main.hs+3−3 tests/common/TestsSetup.hs+3−1
examples/failing/1169.pursnew file+12
@@ -0,0 +1,12 @@
1+-- @shouldFailWith IncorrectConstructorArity
2+module Test where
3+
4+data Outer a = Outer a
5+
6+data Inner a b = Inner a b
7+
8+test1 :: forall a b. Outer (Inner a b) -> Boolean
9+test1 (Outer (Inner _)) = true
10+
11+test2 :: forall a b. Inner a b -> Boolean
12+test2 (Inner _) = true
examples/failing/1570.pursnew file+6
@@ -0,0 +1,6 @@
1+-- @shouldFailWith ExpectedType
2+module M where
3+
4+data F a = F a
5+
6+test = \(x :: F) -> x
examples/failing/EmptyClass.pursnew file+7
@@ -0,0 +1,7 @@
1+-- @shouldFailWith ErrorParsingModule
2+module Main where
3+
4+class Foo x where
5+
6+bar :: String
7+bar = "hello"
examples/failing/ExtraRecordField.purs+1−2
@@ -1,5 +1,4 @@
1−-- @shouldFailWith PropertyIsMissing
2−-- TODO: Make this fail with a new error ExtraProperty instead.
1+-- @shouldFailWith AdditionalProperty
32module ExtraRecordField where
43
54import Prelude ((<>))
examples/failing/MissingRecordField.purs+1−2
@@ -1,5 +1,4 @@
1−-- @shouldFailWith TypesDoNotUnify
2−-- TODO: Update type checker to make this fail with PropertyIsMissing instead.
1+-- @shouldFailWith PropertyIsMissing
32module MissingRecordField where
43
54import Prelude ((>))
examples/failing/MutRec.purs+1
@@ -1,4 +1,5 @@
11-- @shouldFailWith CycleInDeclaration
2+-- @shouldFailWith CycleInDeclaration
23module MutRec where
34
45import Prelude
examples/passing/1570.pursnew file+6
@@ -0,0 +1,6 @@
1+module Main where
2+
3+test :: forall a. a -> a
4+test = \(x :: a) -> x
5+
6+main = Control.Monad.Eff.Console.log "Done"
examples/passing/NakedConstraint.purs+1−1
@@ -2,7 +2,7 @@ module Main where
22
33import Control.Monad.Eff.Console
44
5−class Partial where
5+class Partial
66
77data List a = Nil | Cons a (List a)
88
examples/passing/TypedBinders.purs+6−1
@@ -54,9 +54,14 @@ test3 n = case n of
5454test4 :: Tuple Int Int -> Tuple Int Int
5555test4 = (\(Tuple a b :: Tuple Int Int) -> Tuple b a)
5656
57+type Int1 = Int
58+
59+test5 :: Int1 -> Int1
60+test5 = \(x :: Int1) -> x
61+
5762main = do
5863 let t1 = test
5964 t2 = test2 id
6065 t3 = test3 1
6166 t4 = test4 (Tuple 1 0)
62− Control.Monad.Eff.Console.log "Done"
67+ Control.Monad.Eff.Console.log "Done"
psc/Main.hs+4−5
@@ -71,15 +71,14 @@ compile (PSCMakeOptions inputGlob inputForeignGlob outputDir opts usePrefix) = d
7171 hPutStrLn stderr (P.prettyPrintMultipleWarnings (P.optionsVerboseErrors opts) warnings)
7272 let filePathMap = M.fromList $ map (\(fp, P.Module _ _ mn _ _) -> (mn, fp)) ms
7373 makeActions = buildMakeActions outputDir filePathMap foreigns usePrefix
74− e <- runMake opts $ P.make makeActions (map snd ms)
74+ (e, warnings') <- runMake opts $ P.make makeActions (map snd ms)
75+ when (P.nonEmpty warnings') $
76+ hPutStrLn stderr (P.prettyPrintMultipleWarnings (P.optionsVerboseErrors opts) warnings')
7577 case e of
7678 Left errs -> do
7779 hPutStrLn stderr (P.prettyPrintMultipleErrors (P.optionsVerboseErrors opts) errs)
7880 exitFailure
79− Right (_, warnings') -> do
80− when (P.nonEmpty warnings') $
81− hPutStrLn stderr (P.prettyPrintMultipleWarnings (P.optionsVerboseErrors opts) warnings')
82− exitSuccess
81+ Right _ -> exitSuccess
8382
8483warnFileTypeNotFound :: String -> IO ()
8584warnFileTypeNotFound = hPutStrLn stderr . ("psc: No files found using pattern: " ++)
psci/PSCi.hs+5−5
@@ -71,7 +71,7 @@ supportModule :: P.Module
7171supportModule =
7272 case P.parseModulesFromFiles id [("", code)] of
7373 Right [(_, P.Module ss cs _ ds exps)] -> P.Module ss cs supportModuleName ds exps
74− _ -> error "Support module could not be parsed"
74+ _ -> P.internalError "Support module could not be parsed"
7575 where
7676 code :: String
7777 code = unlines
@@ -254,7 +254,7 @@ modulesDir = ".psci_modules" ++ pathSeparator : "node_modules"
254254-- | This is different than the runMake in 'Language.PureScript.Make' in that it specifies the
255255-- options and ignores the warning messages.
256256runMake :: P.Make a -> IO (Either P.MultipleErrors a)
257−runMake mk = fmap (fmap fst) $ P.runMake P.defaultOptions mk
257+runMake mk = fmap fst $ P.runMake P.defaultOptions mk
258258
259259makeIO :: (IOError -> P.ErrorMessage) -> IO a -> P.Make a
260260makeIO f io = do
@@ -390,7 +390,7 @@ printModuleSignatures moduleName env =
390390 findType envNames m@(_, mIdent) = (mIdent, M.lookup m envNames)
391391 showType :: (P.Ident, Maybe (P.Type, P.NameKind, P.NameVisibility)) -> String
392392 showType (mIdent, Just (mType, _, _)) = show mIdent ++ " :: " ++ P.prettyPrintType mType
393− showType _ = error "The impossible happened in printModuleSignatures."
393+ showType _ = P.internalError "The impossible happened in printModuleSignatures."
394394
395395-- |
396396-- Browse a module and displays its signature (if module exists).
@@ -425,7 +425,7 @@ handleKindOf typ = do
425425 case M.lookup (P.Qualified (Just mName) $ P.ProperName "IT") (P.typeSynonyms env') of
426426 Just (_, typ') -> do
427427 let chk = P.CheckState env' 0 0 (Just mName)
428− k = fst . runWriter . runExceptT $ L.runStateT (P.unCheck (P.kindOf mName typ')) chk
428+ k = fst . runWriter . runExceptT $ L.runStateT (P.unCheck (P.kindOf typ')) chk
429429 case k of
430430 Left errStack -> PSCI . outputStrLn . P.prettyPrintMultipleErrors False $ errStack
431431 Right (kind, _) -> PSCI . outputStrLn . P.prettyPrintKind $ kind
@@ -482,7 +482,7 @@ handleCommand (KindOf typ) = handleKindOf typ
482482handleCommand (BrowseModule moduleName) = handleBrowse moduleName
483483handleCommand (ShowInfo QueryLoaded) = handleShowLoadedModules
484484handleCommand (ShowInfo QueryImport) = handleShowImportedModules
485−handleCommand QuitPSCi = error "`handleCommand QuitPSCi` was called. This is a bug."
485+handleCommand QuitPSCi = P.internalError "`handleCommand QuitPSCi` was called. This is a bug."
486486
487487whenFileExists :: FilePath -> (FilePath -> PSCI ()) -> PSCI ()
488488whenFileExists filePath f = do
purescript.cabal+3−1
@@ -1,5 +1,5 @@
11name: purescript
2−version: 0.7.5
2+version: 0.7.5.3
33cabal-version: >=1.8
44build-type: Simple
55license: MIT
@@ -80,6 +80,7 @@ library
8080 Language.PureScript.AST.Traversals
8181 Language.PureScript.AST.Exported
8282 Language.PureScript.Bundle
83+ Language.PureScript.Crash
8384 Language.PureScript.Externs
8485 Language.PureScript.CodeGen
8586 Language.PureScript.CodeGen.JS
@@ -185,6 +186,7 @@ library
185186 Language.PureScript.Publish.ErrorsWarnings
186187 Language.PureScript.Publish.BoxesHelpers
187188
189+ Control.Monad.Logger
188190 Control.Monad.Unify
189191 Control.Monad.Supply
190192 Control.Monad.Supply.Class
src/Control/Monad/Logger.hsnew file+74
@@ -0,0 +1,74 @@
1+-----------------------------------------------------------------------------
2+--
3+-- Module : Control.Monad.Logger
4+-- Author : Phil Freeman
5+-- License : MIT (http://opensource.org/licenses/MIT)
6+--
7+-- Maintainer : Phil Freeman <paf31@cantab.net>
8+-- Stability : experimental
9+-- Portability :
10+--
11+-- | A replacement for WriterT IO which uses mutable references.
12+--
13+-----------------------------------------------------------------------------
14+
15+{-# LANGUAGE CPP #-}
16+{-# LANGUAGE FlexibleInstances #-}
17+{-# LANGUAGE MultiParamTypeClasses #-}
18+{-# LANGUAGE TypeFamilies #-}
19+
20+module Control.Monad.Logger where
21+
22+import Data.IORef
23+
24+#if __GLASGOW_HASKELL__ < 710
25+import Data.Monoid
26+import Control.Applicative
27+#endif
28+import Control.Monad (ap)
29+import Control.Monad.IO.Class
30+import Control.Monad.Writer.Class
31+import Control.Monad.Base (MonadBase(..))
32+import Control.Monad.Trans.Control (MonadBaseControl(..))
33+
34+-- | A replacement for WriterT IO which uses mutable references.
35+data Logger w a = Logger { runLogger :: IORef w -> IO a }
36+
37+-- | Run a Logger computation, starting with an empty log.
38+runLogger' :: (Monoid w) => Logger w a -> IO (a, w)
39+runLogger' l = do
40+ r <- newIORef mempty
41+ a <- runLogger l r
42+ w <- readIORef r
43+ return (a, w)
44+
45+instance Functor (Logger w) where
46+ fmap f (Logger l) = Logger $ \r -> fmap f (l r)
47+
48+instance (Monoid w) => Applicative (Logger w) where
49+ pure = Logger . const . pure
50+ (<*>) = ap
51+
52+instance (Monoid w) => Monad (Logger w) where
53+ return = pure
54+ Logger l >>= f = Logger $ \r -> l r >>= \a -> runLogger (f a) r
55+
56+instance (Monoid w) => MonadIO (Logger w) where
57+ liftIO = Logger . const
58+
59+instance (Monoid w) => MonadWriter w (Logger w) where
60+ tell w = Logger $ \r -> atomicModifyIORef' r $ \w' -> (mappend w' w, ())
61+ listen l = Logger $ \r -> do
62+ (a, w) <- liftIO (runLogger' l)
63+ atomicModifyIORef' r $ \w' -> (mappend w' w, (a, w))
64+ pass l = Logger $ \r -> do
65+ ((a, f), w) <- liftIO (runLogger' l)
66+ atomicModifyIORef' r $ \w' -> (mappend w' (f w), a)
67+
68+instance (Monoid w) => MonadBase IO (Logger w) where
69+ liftBase = liftIO
70+
71+instance (Monoid w) => MonadBaseControl IO (Logger w) where
72+ type StM (Logger w) a = a
73+ liftBaseWith f = Logger $ \r -> liftBaseWith $ \q -> f (q . flip runLogger r)
74+ restoreM = return
src/Language/PureScript.hs+1
@@ -26,6 +26,7 @@ module Language.PureScript
2626import Data.Version (Version)
2727
2828import Language.PureScript.AST as P
29+import Language.PureScript.Crash as P
2930import Language.PureScript.Comments as P
3031import Language.PureScript.Environment as P
3132import Language.PureScript.Errors as P hiding (indent)
src/Language/PureScript/AST/Operators.hs+3−1
@@ -21,6 +21,8 @@ import qualified Data.Data as D
2121import Data.Aeson ((.=))
2222import qualified Data.Aeson as A
2323
24+import Language.PureScript.Crash
25+
2426-- |
2527-- A precedence level for an infix operator
2628--
@@ -40,7 +42,7 @@ readAssoc :: String -> Associativity
4042readAssoc "infixl" = Infixl
4143readAssoc "infixr" = Infixr
4244readAssoc "infix" = Infix
43−readAssoc _ = error "readAssoc: no parse"
45+readAssoc _ = internalError "readAssoc: no parse"
4446
4547instance A.ToJSON Associativity where
4648 toJSON = A.toJSON . showAssoc
src/Language/PureScript/CodeGen/JS.hs+3−2
@@ -38,6 +38,7 @@ import Control.Monad (replicateM, forM)
3838import Control.Monad.Reader (MonadReader, asks)
3939import Control.Monad.Supply.Class
4040
41+import Language.PureScript.Crash
4142import Language.PureScript.AST.SourcePos
4243import Language.PureScript.CodeGen.JS.AST as AST
4344import Language.PureScript.CodeGen.JS.Common as Common
@@ -272,7 +273,7 @@ moduleToJs (Module coms mn imps exps foreigns decls) foreign_ = do
272273 go (v:vs) done' (b:bs) = do
273274 done'' <- go vs done' bs
274275 binderToJs v done'' b
275− go _ _ _ = error "Invalid arguments to bindersToJs"
276+ go _ _ _ = internalError "Invalid arguments to bindersToJs"
276277
277278 failedPatternError :: [String] -> JS
278279 failedPatternError names = JSUnary JSNew $ JSApp (JSVar "Error") [JSBinary Add (JSStringLiteral errorMessage) (JSArrayLiteral $ zipWith valueError names vals)]
@@ -322,7 +323,7 @@ moduleToJs (Module coms mn imps exps foreigns decls) foreign_ = do
322323 js <- binderToJs argVar done'' binder
323324 return (JSVariableIntroduction argVar (Just (JSAccessor (identToJs field) (JSVar varName))) : js)
324325 binderToJs _ _ ConstructorBinder{} =
325− error "binderToJs: Invalid ConstructorBinder in binderToJs"
326+ internalError "binderToJs: Invalid ConstructorBinder in binderToJs"
326327 binderToJs varName done (NamedBinder _ ident binder) = do
327328 js <- binderToJs varName done binder
328329 return (JSVariableIntroduction (identToJs ident) (Just (JSVar varName)) : js)
src/Language/PureScript/CodeGen/JS/Optimizer/Common.hs+2−1
@@ -17,6 +17,7 @@ module Language.PureScript.CodeGen.JS.Optimizer.Common where
1717
1818import Data.Maybe (fromMaybe)
1919
20+import Language.PureScript.Crash
2021import Language.PureScript.CodeGen.JS.AST
2122
2223applyAll :: [a -> a] -> a -> a
@@ -63,7 +64,7 @@ targetVariable :: JS -> String
6364targetVariable (JSVar var) = var
6465targetVariable (JSAccessor _ tgt) = targetVariable tgt
6566targetVariable (JSIndexer _ tgt) = targetVariable tgt
66−targetVariable _ = error "Invalid argument to targetVariable"
67+targetVariable _ = internalError "Invalid argument to targetVariable"
6768
6869isUpdated :: String -> JS -> Bool
6970isUpdated var1 = everythingOnJS (||) check
src/Language/PureScript/CoreFn/Desugar.hs+4−3
@@ -21,6 +21,7 @@ import qualified Data.Map as M
2121
2222import Control.Arrow (second, (***))
2323
24+import Language.PureScript.Crash
2425import Language.PureScript.AST.SourcePos
2526import Language.PureScript.AST.Traversals
2627import Language.PureScript.CoreFn.Ann
@@ -41,7 +42,7 @@ import qualified Language.PureScript.AST as A
4142--
4243moduleToCoreFn :: Environment -> A.Module -> Module Ann
4344moduleToCoreFn _ (A.Module _ _ _ _ Nothing) =
44− error "Module exports were not elaborated before moduleToCoreFn"
45+ internalError "Module exports were not elaborated before moduleToCoreFn"
4546moduleToCoreFn env (A.Module _ coms mn decls (Just exps)) =
4647 let imports = nub $ mapMaybe importToCoreFn decls ++ findQualModules decls
4748 exps' = nub $ concatMap exportToCoreFn exps
@@ -98,7 +99,7 @@ moduleToCoreFn env (A.Module _ coms mn decls (Just exps)) =
9899 exprToCoreFn ss com ty (A.Abs (Left name) v) =
99100 Abs (ss, com, ty, Nothing) name (exprToCoreFn ss [] Nothing v)
100101 exprToCoreFn _ _ _ (A.Abs _ _) =
101− error "Abs with Binder argument was not desugared before exprToCoreFn mn"
102+ internalError "Abs with Binder argument was not desugared before exprToCoreFn mn"
102103 exprToCoreFn ss com ty (A.App v1 v2) =
103104 App (ss, com, ty, Nothing) (exprToCoreFn ss [] Nothing v1) (exprToCoreFn ss [] Nothing v2)
104105 exprToCoreFn ss com ty (A.Var ident) =
@@ -193,7 +194,7 @@ moduleToCoreFn env (A.Module _ coms mn decls (Just exps)) =
193194 numConstructors ty = length $ filter (((==) `on` typeConstructor) ty) $ M.toList $ dataConstructors env
194195 typeConstructor :: (Qualified ProperName, (DataDeclType, ProperName, Type, [Ident])) -> (ModuleName, ProperName)
195196 typeConstructor (Qualified (Just mn') _, (_, tyCtor, _, _)) = (mn', tyCtor)
196− typeConstructor _ = error "Invalid argument to typeConstructor"
197+ typeConstructor _ = internalError "Invalid argument to typeConstructor"
197198
198199-- |
199200-- Find module names from qualified references to values. This is used to
src/Language/PureScript/Crash.hsnew file+9
@@ -0,0 +1,9 @@
1+module Language.PureScript.Crash where
2+
3+-- | Exit with an error message and a crash report link.
4+internalError :: String -> a
5+internalError =
6+ error
7+ . ("An internal error ocurred during compilation: " ++)
8+ . (++ "\nPlease report this at https://github.com/purescript/purescript/issues")
9+ . show
src/Language/PureScript/Docs/Convert.hs+1−1
@@ -157,7 +157,7 @@ convertDeclaration (P.TypeClassDeclaration _ args implies ds) title =
157157 convertClassMember (P.TypeDeclaration ident' ty) =
158158 ChildDeclaration (P.showIdent ident') Nothing Nothing (ChildTypeClassMember ty)
159159 convertClassMember _ =
160− error "Invalid argument to convertClassMember."
160+ P.internalError "convertDeclaration: Invalid argument to convertClassMember."
161161convertDeclaration (P.TypeInstanceDeclaration _ constraints className tys _) title =
162162 Just (Left (classNameString : typeNameStrings, AugmentChild childDecl))
163163 where
src/Language/PureScript/Docs/RenderedCode/Render.hs+3−2
@@ -22,6 +22,7 @@ import Data.Maybe (fromMaybe)
2222import Control.Arrow ((<+>))
2323import Control.PatternArrows
2424
25+import Language.PureScript.Crash
2526import Language.PureScript.Names
2627import Language.PureScript.Types
2728import Language.PureScript.Kinds
@@ -163,7 +164,7 @@ renderKind = kind . prettyPrintKind
163164--
164165renderTypeAtom :: Type -> RenderedCode
165166renderTypeAtom =
166− fromMaybe (error "Incomplete pattern") . pattern matchTypeAtom () . preprocessType defaultRenderTypeOptions
167+ fromMaybe (internalError "Incomplete pattern") . pattern matchTypeAtom () . preprocessType defaultRenderTypeOptions
167168
168169
169170-- |
@@ -181,4 +182,4 @@ defaultRenderTypeOptions = RenderTypeOptions { prettyPrintObjects = True }
181182
182183renderTypeWithOptions :: RenderTypeOptions -> Type -> RenderedCode
183184renderTypeWithOptions opts =
184− fromMaybe (error "Incomplete pattern") . pattern matchType () . preprocessType opts
185+ fromMaybe (internalError "Incomplete pattern") . pattern matchType () . preprocessType opts
src/Language/PureScript/Environment.hs+2−1
@@ -25,6 +25,7 @@ import qualified Data.Map as M
2525import qualified Data.Text as T
2626import qualified Data.Aeson as A
2727
28+import Language.PureScript.Crash
2829import Language.PureScript.Kinds
2930import Language.PureScript.Names
3031import Language.PureScript.TypeClassDictionaries
@@ -252,7 +253,7 @@ primTypes = M.fromList [ (primName "Function" , (FunKind Star (FunKind Star Star
252253--
253254lookupConstructor :: Environment -> Qualified ProperName -> (DataDeclType, ProperName, Type, [Ident])
254255lookupConstructor env ctor =
255− fromMaybe (error "Data constructor not found") $ ctor `M.lookup` dataConstructors env
256+ fromMaybe (internalError "Data constructor not found") $ ctor `M.lookup` dataConstructors env
256257
257258-- |
258259-- Checks whether a data constructor is for a newtype.
src/Language/PureScript/Errors.hs+229−206
@@ -20,7 +20,7 @@
2020module Language.PureScript.Errors where
2121
2222import Data.Either (lefts, rights)
23−import Data.List (intercalate, transpose, nub, nubBy, partition)
23+import Data.List (intercalate, transpose, nub, nubBy)
2424import Data.Function (on)
2525#if __GLASGOW_HASKELL__ < 710
2626import Data.Foldable (fold, foldMap)
@@ -41,8 +41,8 @@ import Control.Applicative ((<$>), (<*>), Applicative, pure)
4141import Control.Monad.Trans.State.Lazy
4242import Control.Arrow(first)
4343
44+import Language.PureScript.Crash
4445import Language.PureScript.AST
45−import Language.PureScript.Environment (isObject, isFunction)
4646import Language.PureScript.Pretty
4747import Language.PureScript.Types
4848import Language.PureScript.Names
@@ -56,19 +56,16 @@ import Text.Parsec.Error (Message(..))
5656
5757-- | A type of error messages
5858data SimpleErrorMessage
59− = ErrorParsingExterns P.ParseError
60− | ErrorParsingFFIModule FilePath
59+ = ErrorParsingFFIModule FilePath
6160 | ErrorParsingModule P.ParseError
6261 | MissingFFIModule ModuleName
6362 | MultipleFFIModules ModuleName [FilePath]
6463 | UnnecessaryFFIModule ModuleName FilePath
65− | InvalidExternsFile FilePath
6664 | CannotGetFileInfo FilePath
6765 | CannotReadFile FilePath
6866 | CannotWriteFile FilePath
6967 | InfiniteType Type
7068 | InfiniteKind Kind
71− | CannotReorderOperators
7269 | MultipleFixities Ident
7370 | OrphanTypeDeclaration Ident
7471 | OrphanFixityDeclaration String
@@ -108,11 +105,9 @@ data SimpleErrorMessage
108105 | CycleInTypeSynonym (Maybe ProperName)
109106 | CycleInModules [ModuleName]
110107 | NameIsUndefined Ident
111− | NameNotInScope Ident
112108 | UndefinedTypeVariable ProperName
113109 | PartiallyAppliedSynonym (Qualified ProperName)
114110 | EscapedSkolem (Maybe Expr)
115− | UnspecifiedSkolemScope
116111 | TypesDoNotUnify Type Type
117112 | KindsDoNotUnify Kind Kind
118113 | ConstrainedTypeUnified Type Type
@@ -126,23 +121,23 @@ data SimpleErrorMessage
126121 | ArgListLengthsDiffer Ident
127122 | OverlappingArgNames (Maybe Ident)
128123 | MissingClassMember Ident
129− | ExtraneousClassMember Ident
124+ | ExtraneousClassMember Ident (Qualified ProperName)
130125 | ExpectedType Type Kind
131126 | IncorrectConstructorArity (Qualified ProperName)
132− | SubsumptionCheckFailed
133127 | ExprDoesNotHaveType Expr Type
134− | PropertyIsMissing String Type
128+ | PropertyIsMissing String
129+ | AdditionalProperty String
135130 | CannotApplyFunction Type Expr
136131 | TypeSynonymInstance
137132 | OrphanInstance Ident (Qualified ProperName) [Type]
138− | InvalidNewtype
133+ | InvalidNewtype ProperName
139134 | InvalidInstanceHead Type
140135 | TransitiveExportError DeclarationRef [DeclarationRef]
141136 | ShadowedName Ident
142137 | ShadowedTypeVar String
143138 | UnusedTypeVar String
144139 | WildcardInferredType Type
145− | MissingTypeDeclaration Ident
140+ | MissingTypeDeclaration Ident Type
146141 | NotExhaustivePattern [[Binder]] Bool
147142 | OverlappingPattern [[Binder]] Bool
148143 | IncompleteExhaustivityCheck
@@ -153,14 +148,15 @@ data SimpleErrorMessage
153148
154149-- | Error message hints, providing more detailed information about failure.
155150data ErrorMessageHint
156− = NotYetDefined [Ident]
157− | ErrorUnifyingTypes Type Type
151+ = ErrorUnifyingTypes Type Type
158152 | ErrorInExpression Expr
159153 | ErrorInModule ModuleName
160154 | ErrorInInstance (Qualified ProperName) [Type]
161155 | ErrorInSubsumption Type Type
156+ | ErrorCheckingAccessor Expr String
162157 | ErrorCheckingType Expr Type
163158 | ErrorCheckingKind Type
159+ | ErrorCheckingGuard
164160 | ErrorInferringType Expr
165161 | ErrorInApplication Expr Type Expr
166162 | ErrorInDataConstructor ProperName
@@ -196,19 +192,16 @@ instance UnificationError Kind ErrorMessage where
196192--
197193errorCode :: ErrorMessage -> String
198194errorCode em = case unwrapErrorMessage em of
199− ErrorParsingExterns{} -> "ErrorParsingExterns"
200195 ErrorParsingFFIModule{} -> "ErrorParsingFFIModule"
201196 ErrorParsingModule{} -> "ErrorParsingModule"
202197 MissingFFIModule{} -> "MissingFFIModule"
203198 MultipleFFIModules{} -> "MultipleFFIModules"
204199 UnnecessaryFFIModule{} -> "UnnecessaryFFIModule"
205− InvalidExternsFile{} -> "InvalidExternsFile"
206200 CannotGetFileInfo{} -> "CannotGetFileInfo"
207201 CannotReadFile{} -> "CannotReadFile"
208202 CannotWriteFile{} -> "CannotWriteFile"
209203 InfiniteType{} -> "InfiniteType"
210204 InfiniteKind{} -> "InfiniteKind"
211− CannotReorderOperators -> "CannotReorderOperators"
212205 MultipleFixities{} -> "MultipleFixities"
213206 OrphanTypeDeclaration{} -> "OrphanTypeDeclaration"
214207 OrphanFixityDeclaration{} -> "OrphanFixityDeclaration"
@@ -248,11 +241,9 @@ errorCode em = case unwrapErrorMessage em of
248241 CycleInTypeSynonym{} -> "CycleInTypeSynonym"
249242 CycleInModules{} -> "CycleInModules"
250243 NameIsUndefined{} -> "NameIsUndefined"
251− NameNotInScope{} -> "NameNotInScope"
252244 UndefinedTypeVariable{} -> "UndefinedTypeVariable"
253245 PartiallyAppliedSynonym{} -> "PartiallyAppliedSynonym"
254246 EscapedSkolem{} -> "EscapedSkolem"
255− UnspecifiedSkolemScope -> "UnspecifiedSkolemScope"
256247 TypesDoNotUnify{} -> "TypesDoNotUnify"
257248 KindsDoNotUnify{} -> "KindsDoNotUnify"
258249 ConstrainedTypeUnified{} -> "ConstrainedTypeUnified"
@@ -269,13 +260,13 @@ errorCode em = case unwrapErrorMessage em of
269260 ExtraneousClassMember{} -> "ExtraneousClassMember"
270261 ExpectedType{} -> "ExpectedType"
271262 IncorrectConstructorArity{} -> "IncorrectConstructorArity"
272− SubsumptionCheckFailed -> "SubsumptionCheckFailed"
273263 ExprDoesNotHaveType{} -> "ExprDoesNotHaveType"
274264 PropertyIsMissing{} -> "PropertyIsMissing"
265+ AdditionalProperty{} -> "AdditionalProperty"
275266 CannotApplyFunction{} -> "CannotApplyFunction"
276267 TypeSynonymInstance -> "TypeSynonymInstance"
277268 OrphanInstance{} -> "OrphanInstance"
278− InvalidNewtype -> "InvalidNewtype"
269+ InvalidNewtype{} -> "InvalidNewtype"
279270 InvalidInstanceHead{} -> "InvalidInstanceHead"
280271 TransitiveExportError{} -> "TransitiveExportError"
281272 ShadowedName{} -> "ShadowedName"
@@ -362,7 +353,6 @@ onTypesInErrorMessageM f (ErrorMessage hints simple) = ErrorMessage <$> traverse
362353 gSimple (TypesDoNotUnify t1 t2) = TypesDoNotUnify <$> f t1 <*> f t2
363354 gSimple (ConstrainedTypeUnified t1 t2) = ConstrainedTypeUnified <$> f t1 <*> f t2
364355 gSimple (ExprDoesNotHaveType e t) = ExprDoesNotHaveType e <$> f t
365− gSimple (PropertyIsMissing s t) = PropertyIsMissing s <$> f t
366356 gSimple (CannotApplyFunction t e) = CannotApplyFunction <$> f t <*> pure e
367357 gSimple (InvalidInstanceHead t) = InvalidInstanceHead <$> f t
368358 gSimple other = pure other
@@ -377,17 +367,18 @@ onTypesInErrorMessageM f (ErrorMessage hints simple) = ErrorMessage <$> traverse
377367-- Pretty print a single error, simplifying if necessary
378368--
379369prettyPrintSingleError :: Bool -> Level -> ErrorMessage -> State UnknownMap Box.Box
380−prettyPrintSingleError full level e = prettyPrintErrorMessage . positionHintsFirst . reverseHints <$> onTypesInErrorMessageM replaceUnknowns (if full then e else simplifyErrorMessage e)
381− where
370+prettyPrintSingleError full level e = prettyPrintErrorMessage <$> onTypesInErrorMessageM replaceUnknowns (if full then e else simplifyErrorMessage e)
371+ where
382372
383373 -- Pretty print an ErrorMessage
384374 prettyPrintErrorMessage :: ErrorMessage -> Box.Box
385375 prettyPrintErrorMessage (ErrorMessage hints simple) =
386376 paras $
387− map renderHint hints ++
388− renderSimpleErrorMessage simple :
389− suggestions simple ++
390− [line $ "See " ++ wikiUri ++ " for more information, or to contribute content related to this " ++ levelText ++ "."]
377+ [ foldr renderHint (indent (renderSimpleErrorMessage simple)) hints
378+ , Box.moveDown 1 $ paras [ line $ "See " ++ wikiUri ++ " for more information, "
379+ , line $ "or to contribute content related to this " ++ levelText ++ "."
380+ ]
381+ ]
391382 where
392383 wikiUri :: String
393384 wikiUri = "https://github.com/purescript/purescript/wiki/Error-Code-" ++ errorCode e
@@ -405,12 +396,8 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage . positionHintsFir
405396 paras [ line "Unable to write file: "
406397 , indent . line $ path
407398 ]
408− renderSimpleErrorMessage (ErrorParsingExterns err) =
409− paras [ lineWithLevel "parsing externs files: "
410− , prettyPrintParseError err
411− ]
412399 renderSimpleErrorMessage (ErrorParsingFFIModule path) =
413− paras [ line "Unable to parse module from FFI file: "
400+ paras [ line "Unable to parse foreign module:"
414401 , indent . line $ path
415402 ]
416403 renderSimpleErrorMessage (ErrorParsingModule err) =
@@ -418,29 +405,22 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage . positionHintsFir
418405 , prettyPrintParseError err
419406 ]
420407 renderSimpleErrorMessage (MissingFFIModule mn) =
421− line $ "Missing FFI implementations for module " ++ runModuleName mn
408+ line $ "The foreign module implementation for module " ++ runModuleName mn ++ " is missing."
422409 renderSimpleErrorMessage (UnnecessaryFFIModule mn path) =
423− paras [ line $ "Unnecessary FFI implementations have been provided for module " ++ runModuleName mn ++ ": "
410+ paras [ line $ "An unnecessary foreign module implementation was provided for module " ++ runModuleName mn ++ ": "
424411 , indent . line $ path
412+ , line $ "Module " ++ runModuleName mn ++ " does not contain any foreign import declarations, so a foreign module is not necessary."
425413 ]
426414 renderSimpleErrorMessage (MultipleFFIModules mn paths) =
427− paras [ line $ "Multiple FFI implementations have been provided for module " ++ runModuleName mn ++ ": "
415+ paras [ line $ "Multiple foreign module implementations have been provided for module " ++ runModuleName mn ++ ": "
428416 , indent . paras $ map line paths
429417 ]
430− renderSimpleErrorMessage (InvalidExternsFile path) =
431− paras [ line "Externs file is invalid: "
432− , indent . line $ path
433− ]
434418 renderSimpleErrorMessage InvalidDoBind =
435− line "Bind statement cannot be the last statement in a do block. The last statement must be an expression."
419+ line "The last statement in a 'do' block must be an expression, but this block ends with a binder."
436420 renderSimpleErrorMessage InvalidDoLet =
437− line "Let statement cannot be the last statement in a do block. The last statement must be an expression."
438− renderSimpleErrorMessage CannotReorderOperators =
439− line "Unable to reorder operators"
440− renderSimpleErrorMessage UnspecifiedSkolemScope =
441− line "Skolem variable scope is unspecified"
421+ line "The last statement in a 'do' block must be an expression, but this block ends with a let binding."
442422 renderSimpleErrorMessage OverlappingNamesInLet =
443− line "Overlapping names in let binding."
423+ line "The same name was used more than once in a let binding."
444424 renderSimpleErrorMessage (InfiniteType ty) =
445425 paras [ line "An infinite type was inferred for an expression: "
446426 , indent $ typeAsBox ty
@@ -450,17 +430,17 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage . positionHintsFir
450430 , indent $ line $ prettyPrintKind ki
451431 ]
452432 renderSimpleErrorMessage (MultipleFixities name) =
453− line $ "Multiple fixity declarations for " ++ showIdent name
433+ line $ "There are multiple fixity/precedence declarations for " ++ showIdent name
454434 renderSimpleErrorMessage (OrphanTypeDeclaration nm) =
455− line $ "Orphan type declaration for " ++ showIdent nm
435+ line $ "The type declaration for " ++ showIdent nm ++ " should be followed by its definition."
456436 renderSimpleErrorMessage (OrphanFixityDeclaration op) =
457− line $ "Orphan fixity declaration for " ++ show op
437+ line $ "The fixity/precedence declaration for " ++ show op ++ " should appear in the same module as its definition."
458438 renderSimpleErrorMessage (RedefinedModule name filenames) =
459− paras [ line ("Module " ++ runModuleName name ++ " has been defined multiple times:")
439+ paras [ line ("The module " ++ runModuleName name ++ " has been defined multiple times:")
460440 , indent . paras $ map (line . displaySourceSpan) filenames
461441 ]
462442 renderSimpleErrorMessage (RedefinedIdent name) =
463− line $ "Name " ++ showIdent name ++ " has been defined multiple times"
443+ line $ "The value " ++ showIdent name ++ " has been defined multiple times"
464444 renderSimpleErrorMessage (UnknownModule mn) =
465445 line $ "Unknown module " ++ runModuleName mn
466446 renderSimpleErrorMessage (UnknownType name) =
@@ -474,25 +454,36 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage . positionHintsFir
474454 renderSimpleErrorMessage (UnknownDataConstructor dc tc) =
475455 line $ "Unknown data constructor " ++ showQualified runProperName dc ++ foldMap ((" for type constructor " ++) . showQualified runProperName) tc
476456 renderSimpleErrorMessage (UnknownImportType mn name) =
477− line $ "Module " ++ runModuleName mn ++ " does not export type " ++ runProperName name
457+ paras [ line $ "Cannot import type " ++ runProperName name ++ " from module " ++ runModuleName mn
458+ , line "It either does not exist or the module does not export it."
459+ ]
478460 renderSimpleErrorMessage (UnknownExportType name) =
479461 line $ "Cannot export unknown type " ++ runProperName name
480462 renderSimpleErrorMessage (UnknownImportTypeClass mn name) =
481− line $ "Module " ++ runModuleName mn ++ " does not export type class " ++ runProperName name
463+ paras [ line $ "Cannot import type class " ++ runProperName name ++ " from module " ++ runModuleName mn
464+ , line "It either does not exist or the module does not export it."
465+ ]
482466 renderSimpleErrorMessage (UnknownExportTypeClass name) =
483467 line $ "Cannot export unknown type class " ++ runProperName name
484468 renderSimpleErrorMessage (UnknownImportValue mn name) =
485− line $ "Module " ++ runModuleName mn ++ " does not export value " ++ showIdent name
469+ paras [ line $ "Cannot import value " ++ showIdent name ++ " from module " ++ runModuleName mn
470+ , line "It either does not exist or the module does not export it."
471+ ]
486472 renderSimpleErrorMessage (UnknownExportValue name) =
487473 line $ "Cannot export unknown value " ++ showIdent name
488474 renderSimpleErrorMessage (UnknownExportModule name) =
489− line $ "Cannot export unknown module " ++ runModuleName name ++ ", it either does not exist or has not been imported by the current module"
475+ paras [ line $ "Cannot export unknown module " ++ runModuleName name
476+ , line "It either does not exist or has not been imported by the current module."
477+ ]
490478 renderSimpleErrorMessage (UnknownImportDataConstructor mn tcon dcon) =
491479 line $ "Module " ++ runModuleName mn ++ " does not export data constructor " ++ runProperName dcon ++ " for type " ++ runProperName tcon
492480 renderSimpleErrorMessage (UnknownExportDataConstructor tcon dcon) =
493− line $ "Cannot export data constructor " ++ runProperName dcon ++ " for type " ++ runProperName tcon ++ " as it has not been declared"
481+ line $ "Cannot export data constructor " ++ runProperName dcon ++ " for type " ++ runProperName tcon ++ ", as it has not been declared."
494482 renderSimpleErrorMessage (ConflictingImport nm mn) =
495− line $ "Cannot declare " ++ show nm ++ " since another declaration of that name was imported from " ++ runModuleName mn
483+ paras [ line $ "Cannot declare " ++ show nm ++ ", since another declaration of that name was imported from module " ++ runModuleName mn
484+ , line $ "Consider hiding " ++ show nm ++ " when importing " ++ runModuleName mn ++ ":"
485+ , indent . line $ "import " ++ runModuleName mn ++ " hiding (" ++ nm ++ ")"
486+ ]
496487 renderSimpleErrorMessage (ConflictingImports nm m1 m2) =
497488 line $ "Conflicting imports for " ++ nm ++ " from modules " ++ runModuleName m1 ++ " and " ++ runModuleName m2
498489 renderSimpleErrorMessage (ConflictingTypeDecls nm) =
@@ -500,13 +491,13 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage . positionHintsFir
500491 renderSimpleErrorMessage (ConflictingCtorDecls nm) =
501492 line $ "Conflicting data constructor declarations for " ++ runProperName nm
502493 renderSimpleErrorMessage (TypeConflictsWithClass nm) =
503− line $ "Type " ++ runProperName nm ++ " conflicts with type class declaration of the same name"
494+ line $ "Type " ++ runProperName nm ++ " conflicts with a type class declaration with the same name."
504495 renderSimpleErrorMessage (CtorConflictsWithClass nm) =
505− line $ "Data constructor " ++ runProperName nm ++ " conflicts with type class declaration of the same name"
496+ line $ "Data constructor " ++ runProperName nm ++ " conflicts with a type class declaration with the same name."
506497 renderSimpleErrorMessage (ClassConflictsWithType nm) =
507− line $ "Type class " ++ runProperName nm ++ " conflicts with type declaration of the same name"
498+ line $ "Type class " ++ runProperName nm ++ " conflicts with a type declaration with the same name."
508499 renderSimpleErrorMessage (ClassConflictsWithCtor nm) =
509− line $ "Type class " ++ runProperName nm ++ " conflicts with data constructor declaration of the same name"
500+ line $ "Type class " ++ runProperName nm ++ " conflicts with a data constructor declaration with the same name."
510501 renderSimpleErrorMessage (DuplicateModuleName mn) =
511502 line $ "Module " ++ runModuleName mn ++ " has been defined multiple times."
512503 renderSimpleErrorMessage (DuplicateClassExport nm) =
@@ -514,19 +505,24 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage . positionHintsFir
514505 renderSimpleErrorMessage (DuplicateValueExport nm) =
515506 line $ "Duplicate export declaration for value " ++ showIdent nm
516507 renderSimpleErrorMessage (CycleInDeclaration nm) =
517− line $ "Cycle in declaration of " ++ showIdent nm
508+ line $ "The value of " ++ showIdent nm ++ " is undefined here, so this reference is not allowed."
518509 renderSimpleErrorMessage (CycleInModules mns) =
519− line $ "Cycle in module dependencies: " ++ intercalate ", " (map runModuleName mns)
520− renderSimpleErrorMessage (CycleInTypeSynonym pn) =
521− line $ "Cycle in type synonym" ++ foldMap ((" " ++) . runProperName) pn
510+ paras [ line $ "There is a cycle in module dependencies in these modules: "
511+ , indent $ paras (map (line . runModuleName) mns)
512+ ]
513+ renderSimpleErrorMessage (CycleInTypeSynonym name) =
514+ paras [ line $ case name of
515+ Just pn -> "A cycle appears in the definition of type synonym " ++ runProperName pn
516+ Nothing -> "A cycle appears in a set of type synonym definitions."
517+ , line "Cycles are disallowed because they can lead to loops in the type checker."
518+ , line "Consider using a 'newtype' instead."
519+ ]
522520 renderSimpleErrorMessage (NameIsUndefined ident) =
523− line $ showIdent ident ++ " is undefined"
524− renderSimpleErrorMessage (NameNotInScope ident) =
525− line $ showIdent ident ++ " may not be defined in the current scope"
521+ line $ "Value " ++ showIdent ident ++ " is undefined."
526522 renderSimpleErrorMessage (UndefinedTypeVariable name) =
527− line $ "Type variable " ++ runProperName name ++ " is undefined"
523+ line $ "Type variable " ++ runProperName name ++ " is undefined."
528524 renderSimpleErrorMessage (PartiallyAppliedSynonym name) =
529− paras [ line $ "Partially applied type synonym " ++ showQualified runProperName name
525+ paras [ line $ "Type synonym " ++ showQualified runProperName name ++ " is partially applied."
530526 , line "Type synonyms must be applied to all of their type arguments."
531527 ]
532528 renderSimpleErrorMessage (EscapedSkolem binding) =
@@ -535,70 +531,72 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage . positionHintsFir
535531 , indent $ prettyPrintValue expr
536532 ]) binding
537533 renderSimpleErrorMessage (TypesDoNotUnify t1 t2)
538− = paras [ line "Cannot unify type"
534+ = paras [ line "Could not match type"
539535 , indent $ typeAsBox t1
540536 , line "with type"
541537 , indent $ typeAsBox t2
542538 ]
543539 renderSimpleErrorMessage (KindsDoNotUnify k1 k2) =
544− paras [ line "Cannot unify kind"
540+ paras [ line "Could not match kind"
545541 , indent $ line $ prettyPrintKind k1
546542 , line "with kind"
547543 , indent $ line $ prettyPrintKind k2
548544 ]
549545 renderSimpleErrorMessage (ConstrainedTypeUnified t1 t2) =
550− paras [ line "Cannot unify constrained type"
546+ paras [ line "Could not match constrained type"
551547 , indent $ typeAsBox t1
552548 , line "with type"
553549 , indent $ typeAsBox t2
554550 ]
555551 renderSimpleErrorMessage (OverlappingInstances nm ts (d : ds)) =
556− paras [ line "Overlapping instances found for"
552+ paras [ line "Overlapping type class instances found for"
557553 , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
558554 , Box.vcat Box.left (map typeAtomAsBox ts)
559555 ]
560556 , line "The following instances were found:"
561557 , indent $ paras (line (showQualified showIdent d ++ " (chosen)") : map (line . showQualified showIdent) ds)
558+ , line "Overlapping type class instances can lead to different behavior based on the order of module imports, and for that reason are not recommended."
559+ , line "They may be disallowed completely in a future version of the compiler."
562560 ]
563− renderSimpleErrorMessage OverlappingInstances{} = error "OverlappingInstances: empty instance list"
561+ renderSimpleErrorMessage OverlappingInstances{} = internalError "OverlappingInstances: empty instance list"
564562 renderSimpleErrorMessage (NoInstanceFound nm ts) =
565− paras [ line "No instance found for"
563+ paras [ line "No type class instance was found for"
566564 , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
567565 , Box.vcat Box.left (map typeAtomAsBox ts)
568566 ]
569567 ]
570568 renderSimpleErrorMessage (PossiblyInfiniteInstance nm ts) =
571− paras [ line "Instance for"
569+ paras [ line "Type class instance for"
572570 , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
573571 , Box.vcat Box.left (map typeAtomAsBox ts)
574572 ]
575573 , line "is possibly infinite."
576574 ]
577575 renderSimpleErrorMessage (CannotDerive nm ts) =
578− paras [ line "Cannot derive an instance for"
576+ paras [ line "Cannot derive a type class instance for"
579577 , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
580578 , Box.vcat Box.left (map typeAtomAsBox ts)
581579 ]
582580 ]
583581 renderSimpleErrorMessage (CannotFindDerivingType nm) =
584− line $ "Cannot derive instance, because the type declaration for " ++ runProperName nm ++ " could not be found."
582+ line $ "Cannot derive a type class instance, because the type declaration for " ++ runProperName nm ++ " could not be found."
585583 renderSimpleErrorMessage (DuplicateLabel l expr) =
586− paras $ [ line $ "Duplicate label " ++ show l ++ " in row." ]
584+ paras $ [ line $ "Label " ++ show l ++ " appears more than once in a row type." ]
587585 <> foldMap (\expr' -> [ line "Relevant expression: "
588586 , indent $ prettyPrintValue expr'
589587 ]) expr
590588 renderSimpleErrorMessage (DuplicateTypeArgument name) =
591− line $ "Duplicate type argument " ++ show name
589+ line $ "Type argument " ++ show name ++ " appears more than once."
592590 renderSimpleErrorMessage (DuplicateValueDeclaration nm) =
593− line $ "Duplicate value declaration for " ++ showIdent nm
591+ line $ "Multiple value declarations exist for " ++ showIdent nm ++ "."
594592 renderSimpleErrorMessage (ArgListLengthsDiffer ident) =
595593 line $ "Argument list lengths differ in declaration " ++ showIdent ident
596594 renderSimpleErrorMessage (OverlappingArgNames ident) =
597595 line $ "Overlapping names in function/binder" ++ foldMap ((" in declaration" ++) . showIdent) ident
598596 renderSimpleErrorMessage (MissingClassMember ident) =
599− line $ "Member " ++ showIdent ident ++ " has not been implemented"
600− renderSimpleErrorMessage (ExtraneousClassMember ident) =
601− line $ "Member " ++ showIdent ident ++ " is not a member of the class being instantiated"
597+ line $ "Type class member " ++ showIdent ident ++ " has not been implemented."
598+ renderSimpleErrorMessage (ExtraneousClassMember ident className) =
599+ line $ showIdent ident ++ " is not a member of type class " ++ showQualified runProperName className
602600 renderSimpleErrorMessage (ExpectedType ty kind) =
603601 paras [ line "In a type-annotated expression x :: t, the type t must have kind *."
604602 , line "The error arises from the type"
@@ -608,29 +606,27 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage . positionHintsFir
608606 , line "instead."
609607 ]
610608 renderSimpleErrorMessage (IncorrectConstructorArity nm) =
611− line $ "Wrong number of arguments to constructor " ++ showQualified runProperName nm
612− renderSimpleErrorMessage SubsumptionCheckFailed = line "Unable to check type subsumption"
609+ line $ "Data constructor " ++ showQualified runProperName nm ++ " was given the wrong number of arguments in a case expression."
613610 renderSimpleErrorMessage (ExprDoesNotHaveType expr ty) =
614611 paras [ line "Expression"
615612 , indent $ prettyPrintValue expr
616613 , line "does not have type"
617614 , indent $ typeAsBox ty
618615 ]
619− renderSimpleErrorMessage (PropertyIsMissing prop row) =
620− paras [ line "Row"
621− , indent $ prettyPrintRowWith '(' ')' row
622− , line $ "lacks required property " ++ show prop
623− ]
616+ renderSimpleErrorMessage (PropertyIsMissing prop) =
617+ line $ "Type of expression lacks required label " ++ show prop ++ "."
618+ renderSimpleErrorMessage (AdditionalProperty prop) =
619+ line $ "Type of expression contains additional label " ++ show prop ++ "."
624620 renderSimpleErrorMessage (CannotApplyFunction fn arg) =
625− paras [ line "Cannot apply function of type"
621+ paras [ line "A function of type"
626622 , indent $ typeAsBox fn
627− , line "to argument"
623+ , line "can not be applied to the argument"
628624 , indent $ prettyPrintValue arg
629625 ]
630626 renderSimpleErrorMessage TypeSynonymInstance =
631− line "Type synonym instances are disallowed"
627+ line "Type class instances for type synonyms are disallowed."
632628 renderSimpleErrorMessage (OrphanInstance nm cnm ts) =
633− paras [ line $ "Instance " ++ showIdent nm ++ " for "
629+ paras [ line $ "Type class instance " ++ showIdent nm ++ " for "
634630 , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName cnm)
635631 , Box.vcat Box.left (map typeAtomAsBox ts)
636632 ]
@@ -638,39 +634,44 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage . positionHintsFir
638634 , line "An orphan instance is an instance which is defined in neither the class module nor the data type module."
639635 , line "Consider moving the instance, if possible, or using a newtype wrapper."
640636 ]
641− renderSimpleErrorMessage InvalidNewtype =
642− line "Newtypes must define a single constructor with a single argument"
637+ renderSimpleErrorMessage (InvalidNewtype name) =
638+ paras [ line $ "Newtype " ++ runProperName name ++ " is invalid."
639+ , line "Newtypes must define a single constructor with a single argument."
640+ ]
643641 renderSimpleErrorMessage (InvalidInstanceHead ty) =
644− paras [ line "Invalid type in class instance head:"
642+ paras [ line "Type class instance head is invalid due to use of type"
645643 , indent $ typeAsBox ty
644+ , line "All types appearing in instance declarations must be of the form T a_1 .. a_n, where each type a_i is of the same form."
646645 ]
647646 renderSimpleErrorMessage (TransitiveExportError x ys) =
648647 paras $ line ("An export for " ++ prettyPrintExport x ++ " requires the following to also be exported: ")
649648 : map (line . prettyPrintExport) ys
650649 renderSimpleErrorMessage (ShadowedName nm) =
651− line $ "Name '" ++ showIdent nm ++ "' was shadowed"
650+ line $ "Name '" ++ showIdent nm ++ "' was shadowed."
652651 renderSimpleErrorMessage (ShadowedTypeVar tv) =
653− line $ "Type variable '" ++ tv ++ "' was shadowed"
652+ line $ "Type variable '" ++ tv ++ "' was shadowed."
654653 renderSimpleErrorMessage (UnusedTypeVar tv) =
655− line $ "Type variable '" ++ tv ++ "' was declared but not used"
654+ line $ "Type variable '" ++ tv ++ "' was declared but not used."
656655 renderSimpleErrorMessage (ClassOperator className opName) =
657− paras [ line $ "Class '" ++ runProperName className ++ "' declares operator " ++ showIdent opName ++ "."
656+ paras [ line $ "Type class '" ++ runProperName className ++ "' declares operator " ++ showIdent opName ++ "."
658657 , line "This may be disallowed in the future - consider declaring a named member in the class and making the operator an alias:"
659658 , indent . line $ showIdent opName ++ " = someMember"
660659 ]
661660 renderSimpleErrorMessage (MisleadingEmptyTypeImport mn name) =
662− line $ "Importing type " ++ runProperName name ++ "(..) from " ++ runModuleName mn ++ " is misleading as it has no exported data constructors"
661+ line $ "Importing type " ++ runProperName name ++ "(..) from " ++ runModuleName mn ++ " is misleading as it has no exported data constructors."
663662 renderSimpleErrorMessage (ImportHidingModule name) =
664− line $ "Attempted to hide module " ++ runModuleName name ++ " in import expression, this is not permitted"
663+ paras [ line $ "'hiding' imports cannot be used to hide modules."
664+ , line $ "An attempt was made to hide the import of " ++ runModuleName name
665+ ]
665666 renderSimpleErrorMessage (WildcardInferredType ty) =
666− paras [ line "The wildcard type definition has the inferred type "
667+ paras [ line "Wildcard type definition has the inferred type "
667668 , indent $ typeAsBox ty
668669 ]
669− renderSimpleErrorMessage (MissingTypeDeclaration ident) =
670+ renderSimpleErrorMessage (MissingTypeDeclaration ident ty) =
670671 paras [ line $ "No type declaration was provided for the top-level declaration of " ++ showIdent ident ++ "."
671672 , line "It is good practice to provide type declarations as a form of documentation."
672− , line "Consider using a type wildcard to display the inferred type:"
673− , indent $ line $ showIdent ident ++ " :: _"
673+ , line $ "The inferred type of " ++ showIdent ident ++ " was:"
674+ , indent $ typeAsBox ty
674675 ]
675676 renderSimpleErrorMessage (NotExhaustivePattern bs b) =
676677 paras $ [ line "A case expression could not be determined to cover all inputs."
@@ -685,95 +686,130 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage . positionHintsFir
685686 [ line "..." | not b ]
686687 renderSimpleErrorMessage IncompleteExhaustivityCheck =
687688 paras [ line "An exhaustivity check was abandoned due to too many possible cases."
688− , line "You may want to decomposing your data types into smaller types."
689− ]
690−
691− renderHint :: ErrorMessageHint -> Box.Box
692− renderHint (NotYetDefined names) =
693− line $ "The following are not yet defined here: " ++ intercalate ", " (map showIdent names) ++ ":"
694− renderHint (ErrorUnifyingTypes t1 t2) =
695− paras [ lineWithLevel "unifying type "
696− , indent $ typeAsBox t1
697− , line "with type"
698− , indent $ typeAsBox t2
689+ , line "You may want to decompose your data types into smaller types."
690+ ]
691+
692+ renderHint :: ErrorMessageHint -> Box.Box -> Box.Box
693+ renderHint (ErrorUnifyingTypes t1 t2) detail =
694+ paras [ detail
695+ , Box.hsep 1 Box.top [ line "while trying to match type"
696+ , typeAsBox t1
697+ ]
698+ , Box.moveRight 2 $ Box.hsep 1 Box.top [ line "with type"
699+ , typeAsBox t2
700+ ]
701+ ]
702+ renderHint (ErrorInExpression expr) detail =
703+ paras [ detail
704+ , Box.hsep 1 Box.top [ Box.text "in the expression"
705+ , prettyPrintValue expr
706+ ]
707+ ]
708+ renderHint (ErrorInModule mn) detail =
709+ paras [ line $ "in module " ++ runModuleName mn
710+ , detail
711+ ]
712+ renderHint (ErrorInSubsumption t1 t2) detail =
713+ paras [ detail
714+ , Box.hsep 1 Box.top [ line "while checking that type"
715+ , typeAsBox t1
716+ ]
717+ , Box.moveRight 2 $ Box.hsep 1 Box.top [ line "is at least as general as type"
718+ , typeAsBox t2
719+ ]
720+ ]
721+ renderHint (ErrorInInstance nm ts) detail =
722+ paras [ detail
723+ , Box.hsep 1 Box.top [ line "in type class instance"
724+ , line (showQualified runProperName nm)
725+ , Box.vcat Box.left (map typeAtomAsBox ts)
726+ ]
727+ ]
728+ renderHint (ErrorCheckingKind ty) detail =
729+ paras [ detail
730+ , Box.hsep 1 Box.top [ line "while checking the kind of"
731+ , typeAsBox ty
732+ ]
733+ ]
734+ renderHint ErrorCheckingGuard detail =
735+ paras [ detail
736+ , line "while checking the type of a guard clause"
737+ ]
738+ renderHint (ErrorInferringType expr) detail =
739+ paras [ detail
740+ , Box.hsep 1 Box.top [ line "while inferring the type of"
741+ , prettyPrintValue expr
742+ ]
743+ ]
744+ renderHint (ErrorCheckingType expr ty) detail =
745+ paras [ detail
746+ , Box.hsep 1 Box.top [ line "while checking that expression"
747+ , prettyPrintValue expr
748+ ]
749+ , Box.moveRight 2 $ Box.hsep 1 Box.top [ line "has type"
750+ , typeAsBox ty
751+ ]
752+ ]
753+ renderHint (ErrorCheckingAccessor expr prop) detail =
754+ paras [ detail
755+ , Box.hsep 1 Box.top [ line "while checking type of property accessor"
756+ , prettyPrintValue (Accessor prop expr)
757+ ]
758+ ]
759+ renderHint (ErrorInApplication f t a) detail =
760+ paras [ detail
761+ , Box.hsep 1 Box.top [ line "while applying a function"
762+ , prettyPrintValue f
763+ ]
764+ , Box.moveRight 2 $ Box.hsep 1 Box.top [ line "of type"
765+ , typeAsBox t
766+ ]
767+ , Box.moveRight 2 $ Box.hsep 1 Box.top [ line "to argument"
768+ , prettyPrintValue a
769+ ]
770+ ]
771+ renderHint (ErrorInDataConstructor nm) detail =
772+ paras [ detail
773+ , line $ "in data constructor " ++ runProperName nm
774+ ]
775+ renderHint (ErrorInTypeConstructor nm) detail =
776+ paras [ detail
777+ , line $ "in type constructor " ++ runProperName nm
778+ ]
779+ renderHint (ErrorInBindingGroup nms) detail =
780+ paras [ detail
781+ , line $ "in binding group " ++ intercalate ", " (map showIdent nms)
782+ ]
783+ renderHint ErrorInDataBindingGroup detail =
784+ paras [ detail
785+ , line "in data binding group"
786+ ]
787+ renderHint (ErrorInTypeSynonym name) detail =
788+ paras [ detail
789+ , line $ "in type synonym " ++ runProperName name
790+ ]
791+ renderHint (ErrorInValueDeclaration n) detail =
792+ paras [ detail
793+ , line $ "in value declaration " ++ showIdent n
794+ ]
795+ renderHint (ErrorInTypeDeclaration n) detail =
796+ paras [ detail
797+ , line $ "in type declaration for " ++ showIdent n
798+ ]
799+ renderHint (ErrorInForeignImport nm) detail =
800+ paras [ detail
801+ , line $ "in foreign import " ++ showIdent nm
802+ ]
803+ renderHint (PositionedError srcSpan) detail =
804+ paras [ line $ "at " ++ displaySourceSpan srcSpan
805+ , detail
699806 ]
700− renderHint (ErrorInExpression expr) =
701− paras [ lineWithLevel "in expression:"
702− , indent $ prettyPrintValue expr
703− ]
704− renderHint (ErrorInModule mn) =
705− paras [ lineWithLevel $ "in module " ++ runModuleName mn ++ ":"
706− ]
707− renderHint (ErrorInSubsumption t1 t2) =
708− paras [ lineWithLevel "checking that type "
709− , indent $ typeAsBox t1
710− , line "subsumes type"
711− , indent $ typeAsBox t2
712− ]
713− renderHint (ErrorInInstance nm ts) =
714− paras [ lineWithLevel "in type class instance"
715− , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
716− , Box.vcat Box.left (map typeAtomAsBox ts)
717− ]
718− ]
719− renderHint (ErrorCheckingKind ty) =
720− paras [ lineWithLevel "checking kind of type "
721− , indent $ typeAsBox ty
722− ]
723− renderHint (ErrorInferringType expr) =
724− paras [ lineWithLevel "inferring type of value "
725− , indent $ prettyPrintValue expr
726− ]
727− renderHint (ErrorCheckingType expr ty) =
728− paras [ lineWithLevel "checking that value "
729− , indent $ prettyPrintValue expr
730− , line "has type"
731− , indent $ typeAsBox ty
732− ]
733− renderHint (ErrorInApplication f t a) =
734− paras [ lineWithLevel "applying function"
735− , indent $ prettyPrintValue f
736− , line "of type"
737− , indent $ typeAsBox t
738− , line "to argument"
739− , indent $ prettyPrintValue a
740− ]
741− renderHint (ErrorInDataConstructor nm) =
742− lineWithLevel $ "in data constructor " ++ runProperName nm ++ ":"
743− renderHint (ErrorInTypeConstructor nm) =
744− lineWithLevel $ "in type constructor " ++ runProperName nm ++ ":"
745− renderHint (ErrorInBindingGroup nms) =
746− lineWithLevel $ "in binding group " ++ intercalate ", " (map showIdent nms) ++ ":"
747− renderHint ErrorInDataBindingGroup =
748− lineWithLevel "in data binding group:"
749− renderHint (ErrorInTypeSynonym name) =
750− lineWithLevel $ "in type synonym " ++ runProperName name ++ ":"
751− renderHint (ErrorInValueDeclaration n) =
752− lineWithLevel $ "in value declaration " ++ showIdent n ++ ":"
753− renderHint (ErrorInTypeDeclaration n) =
754− lineWithLevel $ "in type declaration for " ++ showIdent n ++ ":"
755− renderHint (ErrorInForeignImport nm) =
756− lineWithLevel $ "in foreign import " ++ showIdent nm ++ ":"
757− renderHint (PositionedError srcSpan) =
758− lineWithLevel $ "at " ++ displaySourceSpan srcSpan ++ ":"
759−
760− lineWithLevel :: String -> Box.Box
761− lineWithLevel text = line $ show level ++ " " ++ text
762807
763808 levelText :: String
764809 levelText = case level of
765810 Error -> "error"
766811 Warning -> "warning"
767812
768− suggestions :: SimpleErrorMessage -> [Box.Box]
769− suggestions (ConflictingImport nm im) = [ line $ "Possible fix: hide " ++ show nm ++ " when importing " ++ runModuleName im ++ ":"
770− , indent . line $ "import " ++ runModuleName im ++ " hiding (" ++ nm ++ ")"
771− ]
772− suggestions (TypesDoNotUnify t1 t2)
773− | isObject t1 && isFunction t2 = [line "Note that function composition in PureScript is defined using (<<<)"]
774− | otherwise = []
775− suggestions _ = []
776−
777813 paras :: [Box.Box] -> Box.Box
778814 paras = Box.vcat Box.left
779815
@@ -786,19 +822,6 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage . positionHintsFir
786822 prettyPrintExport (ModuleRef name) = "module " ++ runModuleName name
787823 prettyPrintExport (PositionedDeclarationRef _ _ ref) = prettyPrintExport ref
788824
789− -- Hints get added at the front, so we need to reverse them before rendering
790− reverseHints :: ErrorMessage -> ErrorMessage
791− reverseHints (ErrorMessage hints simple) = ErrorMessage (reverse hints) simple
792−
793− -- | Put positional hints at the front of the list
794− positionHintsFirst :: ErrorMessage -> ErrorMessage
795− positionHintsFirst (ErrorMessage hints simple) = ErrorMessage (uncurry (++) $ partition (isPositionHint . hintCategory) hints) simple
796− where
797− isPositionHint :: HintCategory -> Bool
798− isPositionHint PositionHint = True
799− isPositionHint OtherHint = True
800− isPositionHint _ = False
801−
802825 -- | Simplify an error message
803826 simplifyErrorMessage :: ErrorMessage -> ErrorMessage
804827 simplifyErrorMessage (ErrorMessage hints simple) = ErrorMessage (simplifyHints hints) simple
src/Language/PureScript/Externs.hs+22−21
@@ -38,6 +38,7 @@ import Data.Aeson.TH
3838
3939import qualified Data.Map as M
4040
41+import Language.PureScript.Crash
4142import Language.PureScript.AST
4243import Language.PureScript.Environment
4344import Language.PureScript.Names
@@ -50,57 +51,57 @@ import Paths_purescript as Paths
5051-- | The data which will be serialized to an externs file
5152data ExternsFile = ExternsFile
5253 {
53− -- ^ The externs version
54+ -- | The externs version
5455 efVersion :: String
55− -- ^ Module name
56+ -- | Module name
5657 , efModuleName :: ModuleName
57− -- ^ List of module exports
58+ -- | List of module exports
5859 , efExports :: [DeclarationRef]
59− -- ^ List of module imports
60+ -- | List of module imports
6061 , efImports :: [ExternsImport]
61− -- ^ List of operators and their fixities
62+ -- | List of operators and their fixities
6263 , efFixities :: [ExternsFixity]
63− -- ^ List of type and value declaration
64+ -- | List of type and value declaration
6465 , efDeclarations :: [ExternsDeclaration]
6566 } deriving (Show, Read)
6667
6768-- | A module import in an externs file
6869data ExternsImport = ExternsImport
6970 {
70− -- ^ The imported module
71+ -- | The imported module
7172 eiModule :: ModuleName
72− -- ^ The import type: regular, qualified or hiding
73+ -- | The import type: regular, qualified or hiding
7374 , eiImportType :: ImportDeclarationType
74− -- ^ The imported-as name, for qualified imports
75+ -- | The imported-as name, for qualified imports
7576 , eiImportedAs :: Maybe ModuleName
7677 } deriving (Show, Read)
7778
7879-- | A fixity declaration in an externs file
7980data ExternsFixity = ExternsFixity
8081 {
81− -- ^ The associativity of the operator
82+ -- | The associativity of the operator
8283 efAssociativity :: Associativity
83− -- ^ The precedence level of the operator
84+ -- | The precedence level of the operator
8485 , efPrecedence :: Precedence
85− -- ^ The operator symbol
86+ -- | The operator symbol
8687 , efOperator :: String
8788 } deriving (Show, Read)
8889
8990-- | A type or value declaration appearing in an externs file
9091data ExternsDeclaration =
91− -- ^ A type declaration
92+ -- | A type declaration
9293 EDType
9394 { edTypeName :: ProperName
9495 , edTypeKind :: Kind
9596 , edTypeDeclarationKind :: TypeKind
9697 }
97− -- ^ A type synonym
98+ -- | A type synonym
9899 | EDTypeSynonym
99100 { edTypeSynonymName :: ProperName
100101 , edTypeSynonymArguments :: [(String, Maybe Kind)]
101102 , edTypeSynonymType :: Type
102103 }
103− -- ^ A data construtor
104+ -- | A data construtor
104105 | EDDataConstructor
105106 { edDataCtorName :: ProperName
106107 , edDataCtorOrigin :: DataDeclType
@@ -108,19 +109,19 @@ data ExternsDeclaration =
108109 , edDataCtorType :: Type
109110 , edDataCtorFields :: [Ident]
110111 }
111− -- ^ A value declaration
112+ -- | A value declaration
112113 | EDValue
113114 { edValueName :: Ident
114115 , edValueType :: Type
115116 }
116− -- ^ A type class declaration
117+ -- | A type class declaration
117118 | EDClass
118119 { edClassName :: ProperName
119120 , edClassTypeArguments :: [(String, Maybe Kind)]
120121 , edClassMembers :: [(Ident, Type)]
121122 , edClassConstraints :: [Constraint]
122123 }
123− -- ^ An instance declaration
124+ -- | An instance declaration
124125 | EDInstance
125126 { edInstanceClassName :: Qualified ProperName
126127 , edInstanceName :: Ident
@@ -152,7 +153,7 @@ applyExternsFileToEnvironment ExternsFile{..} = flip (foldl' applyDecl) efDeclar
152153
153154-- | Generate an externs file for all declarations in a module
154155moduleToExternsFile :: Module -> Environment -> ExternsFile
155−moduleToExternsFile (Module _ _ _ _ Nothing) _ = error "moduleToExternsFile: module exports were not elaborated"
156+moduleToExternsFile (Module _ _ _ _ Nothing) _ = internalError "moduleToExternsFile: module exports were not elaborated"
156157moduleToExternsFile (Module _ _ mn ds (Just exps)) env = ExternsFile{..}
157158 where
158159 efVersion = showVersion Paths.version
@@ -181,7 +182,7 @@ moduleToExternsFile (Module _ _ mn ds (Just exps)) env = ExternsFile{..}
181182 toExternsDeclaration (PositionedDeclarationRef _ _ r) = toExternsDeclaration r
182183 toExternsDeclaration (TypeRef pn dctors) =
183184 case Qualified (Just mn) pn `M.lookup` types env of
184− Nothing -> error "toExternsDeclaration: no kind in toExternsDeclaration"
185+ Nothing -> internalError "toExternsDeclaration: no kind in toExternsDeclaration"
185186 Just (kind, TypeSynonym)
186187 | Just (args, synTy) <- Qualified (Just mn) pn `M.lookup` typeSynonyms env -> [ EDType pn kind TypeSynonym, EDTypeSynonym pn args synTy ]
187188 Just (kind, ExternData) -> [ EDType pn kind ExternData ]
@@ -190,7 +191,7 @@ moduleToExternsFile (Module _ _ mn ds (Just exps)) env = ExternsFile{..}
190191 | dctor <- fromMaybe (map fst tys) dctors
191192 , (dty, _, ty, args) <- maybeToList (M.lookup (Qualified (Just mn) dctor) (dataConstructors env))
192193 ]
193− _ -> error "toExternsDeclaration: Invalid input"
194+ _ -> internalError "toExternsDeclaration: Invalid input"
194195 toExternsDeclaration (ValueRef ident)
195196 | Just (ty, _, _) <- (mn, ident) `M.lookup` names env
196197 = [ EDValue ident ty ]
src/Language/PureScript/Linter.hs+2−1
@@ -30,6 +30,7 @@ import Control.Applicative
3030#endif
3131import Control.Monad.Writer.Class
3232
33+import Language.PureScript.Crash
3334import Language.PureScript.AST
3435import Language.PureScript.Names
3536import Language.PureScript.Errors
@@ -50,7 +51,7 @@ lint (Module _ _ mn ds _) = censor (addHint (ErrorInModule mn)) $ mapM_ lintDecl
5051 getDeclIdent (ValueDeclaration ident _ _ _) = Just ident
5152 getDeclIdent (ExternDeclaration ident _) = Just ident
5253 getDeclIdent (TypeInstanceDeclaration ident _ _ _ _) = Just ident
53− getDeclIdent (BindingGroupDeclaration _) = error "lint: binding groups should not be desugared yet."
54+ getDeclIdent (BindingGroupDeclaration _) = internalError "lint: binding groups should not be desugared yet."
5455 getDeclIdent _ = Nothing
5556
5657 lintDeclaration :: Declaration -> m ()
src/Language/PureScript/Linter/Exhaustive.hs+4−3
@@ -38,6 +38,7 @@ import Control.Applicative
3838import Control.Arrow (first, second)
3939import Control.Monad.Writer.Class
4040
41+import Language.PureScript.Crash
4142import Language.PureScript.AST.Binders
4243import Language.PureScript.AST.Declarations
4344import Language.PureScript.Environment
@@ -92,7 +93,7 @@ getConstructors env defmn n = extractConstructors lnte
9293
9394 extractConstructors :: Maybe (Kind, TypeKind) -> [(ProperName, [Type])]
9495 extractConstructors (Just (_, DataType _ pt)) = pt
95− extractConstructors _ = error "Data name not in the scope of the current environment in extractConstructors"
96+ extractConstructors _ = internalError "Data name not in the scope of the current environment in extractConstructors"
9697
9798-- |
9899-- Replicates a wildcard binder
@@ -197,7 +198,7 @@ missingCasesMultiple env mn = go
197198 where
198199 (miss1, pr1) = missingCasesSingle env mn x y
199200 (miss2, pr2) = go xs ys
200− go _ _ = error "Argument lengths did not match in missingCasesMultiple."
201+ go _ _ = internalError "Argument lengths did not match in missingCasesMultiple."
201202
202203-- |
203204-- Guard handling
@@ -245,7 +246,7 @@ checkExhaustive env mn numArgs cas = makeResult . first nub $ foldl' step ([init
245246 step :: ([[Binder]], (Either RedudancyError Bool, [[Binder]])) -> CaseAlternative -> ([[Binder]], (Either RedudancyError Bool, [[Binder]]))
246247 step (uncovered, (nec, redundant)) ca =
247248 let (missed, pr) = unzip (map (missingAlternative env mn ca) uncovered)
248− (missed', approx) = splitAt 10000 (concat missed)
249+ (missed', approx) = splitAt 10000 (nub (concat missed))
249250 cond = liftA2 (&&) (or <$> sequenceA pr) nec
250251 in (missed', ( if null approx
251252 then cond
src/Language/PureScript/Make.hs+35−33
@@ -43,9 +43,10 @@ import Control.Applicative
4343#endif
4444import Control.Monad
4545import Control.Monad.Error.Class (MonadError(..))
46+import Control.Monad.Writer.Class (MonadWriter(..))
4647import Control.Monad.Trans.Except
4748import Control.Monad.Reader
48−import Control.Monad.Writer.Strict
49+import Control.Monad.Logger
4950import Control.Monad.Supply
5051import Control.Monad.Base (MonadBase(..))
5152import Control.Monad.Trans.Control (MonadBaseControl(..))
@@ -58,6 +59,7 @@ import Data.Time.Clock
5859import Data.String (fromString)
5960import Data.Foldable (for_)
6061#if __GLASGOW_HASKELL__ < 710
62+import Data.Monoid (mempty, mconcat)
6163import Data.Traversable (traverse)
6264#endif
6365import Data.Traversable (for)
@@ -72,6 +74,7 @@ import System.Directory
7274import System.FilePath ((</>), takeDirectory)
7375import System.IO.Error (tryIOError)
7476
77+import Language.PureScript.Crash
7578import Language.PureScript.AST
7679import Language.PureScript.Externs
7780import Language.PureScript.Environment
@@ -166,7 +169,7 @@ make MakeActions{..} ms = do
166169 barriers <- zip (map getModuleName sorted) <$> replicateM (length ms) ((,) <$> C.newEmptyMVar <*> C.newEmptyMVar)
167170
168171 for_ sorted $ \m -> fork $ do
169− let deps = fromMaybe (error "make: module not found in dependency graph.") (lookup (getModuleName m) graph)
172+ let deps = fromMaybe (internalError "make: module not found in dependency graph.") (lookup (getModuleName m) graph)
170173 buildModule barriers (importPrim m) (deps `inOrderOf` map getModuleName sorted)
171174
172175 -- Wait for all threads to complete, and collect errors.
@@ -176,8 +179,7 @@ make MakeActions{..} ms = do
176179 unless (null errors) $ throwError (mconcat errors)
177180
178181 -- Bundle up all the externs and return them as an Environment
179− (warnings, externs) <- unzip . fromMaybe (error "make: externs were missing but no errors reported.") . sequence <$> for barriers (takeMVar . fst . snd)
180− tell (mconcat warnings)
182+ (_, externs) <- unzip . fromMaybe (internalError "make: externs were missing but no errors reported.") . sequence <$> for barriers (takeMVar . fst . snd)
181183 return $ foldl' (flip applyExternsFileToEnvironment) initEnvironment externs
182184
183185 where
@@ -205,21 +207,21 @@ make MakeActions{..} ms = do
205207 -- We need to wait for dependencies to be built, before checking if the current
206208 -- module should be rebuilt, so the first thing to do is to wait on the
207209 -- MVars for the module's dependencies.
208− mexterns <- fmap unzip . sequence <$> mapM (readMVar . fst . fromMaybe (error "make: no barrier") . flip lookup barriers) deps
210+ mexterns <- fmap unzip . sequence <$> mapM (readMVar . fst . fromMaybe (internalError "make: no barrier") . flip lookup barriers) deps
209211
210− outputTimestamp <- getOutputTimestamp moduleName
211− dependencyTimestamp <- maximumMaybe <$> mapM (fmap shouldExist . getOutputTimestamp) deps
212− inputTimestamp <- getInputTimestamp moduleName
212+ case mexterns of
213+ Just (_, externs) -> do
214+ outputTimestamp <- getOutputTimestamp moduleName
215+ dependencyTimestamp <- maximumMaybe <$> mapM (fmap shouldExist . getOutputTimestamp) deps
216+ inputTimestamp <- getInputTimestamp moduleName
213217
214− let shouldRebuild = case (inputTimestamp, dependencyTimestamp, outputTimestamp) of
215− (Right (Just t1), Just t3, Just t2) -> t1 > t2 || t3 > t2
216− (Right (Just t1), Nothing, Just t2) -> t1 > t2
217− (Left RebuildNever, _, Just _) -> False
218− _ -> True
218+ let shouldRebuild = case (inputTimestamp, dependencyTimestamp, outputTimestamp) of
219+ (Right (Just t1), Just t3, Just t2) -> t1 > t2 || t3 > t2
220+ (Right (Just t1), Nothing, Just t2) -> t1 > t2
221+ (Left RebuildNever, _, Just _) -> False
222+ _ -> True
219223
220− let rebuild =
221− case mexterns of
222− Just (_, externs) -> do
224+ let rebuild = do
223225 (exts, warnings) <- listen $ do
224226 progress $ CompilingModule moduleName
225227 let env = foldl' (flip applyExternsFileToEnvironment) initEnvironment externs
@@ -235,20 +237,20 @@ make MakeActions{..} ms = do
235237 evalSupplyT nextVar $ codegen renamed env' $ encode exts
236238 return exts
237239 markComplete (Just (warnings, exts)) Nothing
238− Nothing -> markComplete Nothing Nothing
239−
240− if shouldRebuild
241− then rebuild
242− else do
243− mexts <- decodeExterns . snd <$> readExterns moduleName
244− case mexts of
245− Just exts -> markComplete (Just (mempty, exts)) Nothing
246− Nothing -> rebuild
240+
241+ if shouldRebuild
242+ then rebuild
243+ else do
244+ mexts <- decodeExterns . snd <$> readExterns moduleName
245+ case mexts of
246+ Just exts -> markComplete (Just (mempty, exts)) Nothing
247+ Nothing -> rebuild
248+ Nothing -> markComplete Nothing Nothing
247249 where
248250 markComplete :: Maybe (MultipleErrors, ExternsFile) -> Maybe MultipleErrors -> m ()
249251 markComplete externs errors = do
250− putMVar (fst $ fromMaybe (error "make: no barrier") $ lookup moduleName barriers) externs
251− putMVar (snd $ fromMaybe (error "make: no barrier") $ lookup moduleName barriers) errors
252+ putMVar (fst $ fromMaybe (internalError "make: no barrier") $ lookup moduleName barriers) externs
253+ putMVar (snd $ fromMaybe (internalError "make: no barrier") $ lookup moduleName barriers) errors
252254
253255 maximumMaybe :: (Ord a) => [a] -> Maybe a
254256 maximumMaybe [] = Nothing
@@ -257,7 +259,7 @@ make MakeActions{..} ms = do
257259 -- Make sure a dependency exists
258260 shouldExist :: Maybe UTCTime -> UTCTime
259261 shouldExist (Just t) = t
260− shouldExist _ = error "make: dependency should already have been built."
262+ shouldExist _ = internalError "make: dependency should already have been built."
261263
262264 decodeExterns :: B.ByteString -> Maybe ExternsFile
263265 decodeExterns bs = do
@@ -283,22 +285,22 @@ importPrim = addDefaultImport (ModuleName [ProperName C.prim])
283285-- |
284286-- A monad for running make actions
285287--
286−newtype Make a = Make { unMake :: ReaderT Options (WriterT MultipleErrors (ExceptT MultipleErrors IO)) a }
288+newtype Make a = Make { unMake :: ReaderT Options (ExceptT MultipleErrors (Logger MultipleErrors)) a }
287289 deriving (Functor, Applicative, Monad, MonadIO, MonadError MultipleErrors, MonadWriter MultipleErrors, MonadReader Options)
288290
289291instance MonadBase IO Make where
290292 liftBase = liftIO
291293
292294instance MonadBaseControl IO Make where
293− type StM Make a = Either MultipleErrors (a, MultipleErrors)
295+ type StM Make a = Either MultipleErrors a
294296 liftBaseWith f = Make $ liftBaseWith $ \q -> f (q . unMake)
295297 restoreM = Make . restoreM
296298
297299-- |
298300-- Execute a 'Make' monad, returning either errors, or the result of the compile plus any warnings.
299301--
300−runMake :: Options -> Make a -> IO (Either MultipleErrors (a, MultipleErrors))
301−runMake opts = runExceptT . runWriterT . flip runReaderT opts . unMake
302+runMake :: Options -> Make a -> IO (Either MultipleErrors a, MultipleErrors)
303+runMake opts = runLogger' . runExceptT . flip runReaderT opts . unMake
302304
303305makeIO :: (IOError -> ErrorMessage) -> IO a -> Make a
304306makeIO f io = do
@@ -324,7 +326,7 @@ buildMakeActions outputDir filePathMap foreigns usePrefix =
324326
325327 getInputTimestamp :: ModuleName -> Make (Either RebuildPolicy (Maybe UTCTime))
326328 getInputTimestamp mn = do
327− let path = fromMaybe (error "Module has no filename in 'make'") $ M.lookup mn filePathMap
329+ let path = fromMaybe (internalError "Module has no filename in 'make'") $ M.lookup mn filePathMap
328330 e1 <- traverseEither getTimestamp path
329331 fPath <- maybe (return Nothing) getTimestamp $ M.lookup mn foreigns
330332 return $ fmap (max fPath) e1
src/Language/PureScript/ModuleDependencies.hs+2−1
@@ -25,6 +25,7 @@ import Data.Graph
2525import Data.List (nub)
2626import Data.Maybe (fromMaybe, mapMaybe)
2727
28+import Language.PureScript.Crash
2829import Language.PureScript.AST
2930import Language.PureScript.Names
3031import Language.PureScript.Types
@@ -43,7 +44,7 @@ sortModules ms = do
4344 ms' <- mapM toModule $ stronglyConnComp verts
4445 let (graph, fromVertex, toVertex) = graphFromEdges verts
4546 moduleGraph = do (_, mn, _) <- verts
46− let v = fromMaybe (error "sortModules: vertex not found") (toVertex mn)
47+ let v = fromMaybe (internalError "sortModules: vertex not found") (toVertex mn)
4748 deps = reachable graph v
4849 toKey i = case fromVertex i of (_, key, _) -> key
4950 return (mn, filter (/= mn) (map toKey deps))
src/Language/PureScript/Parser/Declarations.hs+1−1
@@ -201,7 +201,7 @@ parseTypeClassDeclaration = do
201201 idents <- P.many (indented *> kindedIdent)
202202 members <- P.option [] . P.try $ do
203203 indented *> reserved "where"
204− mark (P.many (same *> positioned parseTypeDeclaration))
204+ indented *> mark (P.many (same *> positioned parseTypeDeclaration))
205205 return $ TypeClassDeclaration className idents implies members
206206
207207parseInstanceDeclaration :: TokenParser (TypeInstanceBody -> Declaration)
src/Language/PureScript/Pretty/JS.hs+3−2
@@ -30,6 +30,7 @@ import Control.Monad.State
3030import Control.PatternArrows
3131import qualified Control.Arrow as A
3232
33+import Language.PureScript.Crash
3334import Language.PureScript.CodeGen.JS.AST
3435import Language.PureScript.CodeGen.JS.Common
3536import Language.PureScript.Pretty.Common
@@ -251,13 +252,13 @@ prettyStatements sts = do
251252-- Generate a pretty-printed string representing a Javascript expression
252253--
253254prettyPrintJS1 :: JS -> String
254−prettyPrintJS1 = fromMaybe (error "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyPrintJS'
255+prettyPrintJS1 = fromMaybe (internalError "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyPrintJS'
255256
256257-- |
257258-- Generate a pretty-printed string representing a collection of Javascript expressions at the same indentation level
258259--
259260prettyPrintJS :: [JS] -> String
260−prettyPrintJS = fromMaybe (error "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyStatements
261+prettyPrintJS = fromMaybe (internalError "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyStatements
261262
262263-- |
263264-- Generate an indented, pretty-printed string representing a Javascript expression
src/Language/PureScript/Pretty/Kinds.hs+2−1
@@ -22,6 +22,7 @@ import Data.Maybe (fromMaybe)
2222import Control.Arrow (ArrowPlus(..))
2323import Control.PatternArrows
2424
25+import Language.PureScript.Crash
2526import Language.PureScript.Kinds
2627import Language.PureScript.Pretty.Common
2728
@@ -47,7 +48,7 @@ funKind = mkPattern match
4748
4849-- | Generate a pretty-printed string representing a Kind
4950prettyPrintKind :: Kind -> String
50−prettyPrintKind = fromMaybe (error "Incomplete pattern") . pattern matchKind ()
51+prettyPrintKind = fromMaybe (internalError "Incomplete pattern") . pattern matchKind ()
5152 where
5253 matchKind :: Pattern () Kind String
5354 matchKind = buildPrettyPrinter operators (typeLiterals <+> fmap parens matchKind)
src/Language/PureScript/Pretty/Types.hs+13−6
@@ -27,6 +27,7 @@ import Data.Maybe (fromMaybe)
2727import Control.Arrow ((<+>))
2828import Control.PatternArrows
2929
30+import Language.PureScript.Crash
3031import Language.PureScript.Types
3132import Language.PureScript.Names
3233import Language.PureScript.Kinds
@@ -45,14 +46,13 @@ typeLiterals = mkPattern match
4546 match (TypeConstructor ctor) = Just $ text $ runProperName $ disqualify ctor
4647 match (TUnknown u) = Just $ text $ '_' : show u
4748 match (Skolem name s _) = Just $ text $ name ++ show s
48− match (ConstrainedType deps ty) = Just $ constraintsAsBox deps ty
4949 match REmpty = Just $ text "()"
5050 match row@RCons{} = Just $ prettyPrintRowWith '(' ')' row
5151 match _ = Nothing
5252
53−constraintsAsBox :: [(Qualified ProperName, [Type])] -> Type -> Box
54−constraintsAsBox [(pn, tys)] ty = text "(" <> constraintAsBox pn tys <> text ") => " <> typeAsBox ty
55−constraintsAsBox xs ty = vcat left (zipWith (\i (pn, tys) -> text (if i == 0 then "( " else ", ") <> constraintAsBox pn tys) [0 :: Int ..] xs) `before` (text ") => " <> typeAsBox ty)
53+constraintsAsBox :: [(Qualified ProperName, [Type])] -> Box -> Box
54+constraintsAsBox [(pn, tys)] ty = text "(" <> constraintAsBox pn tys <> text ") => " <> ty
55+constraintsAsBox xs ty = vcat left (zipWith (\i (pn, tys) -> text (if i == 0 then "( " else ", ") <> constraintAsBox pn tys) [0 :: Int ..] xs) `before` (text ") => " <> ty)
5656
5757constraintAsBox :: Qualified ProperName -> [Type] -> Box
5858constraintAsBox pn tys = hsep 1 left (text (runProperName (disqualify pn)) : map typeAtomAsBox tys)
@@ -114,6 +114,12 @@ insertPlaceholders = everywhereOnTypesTopDown convertForAlls . everywhereOnTypes
114114 go idents other = PrettyPrintForAll idents other
115115 convertForAlls other = other
116116
117+constrained :: Pattern () Type ([Constraint], Type)
118+constrained = mkPattern match
119+ where
120+ match (ConstrainedType deps ty) = Just (deps, ty)
121+ match _ = Nothing
122+
117123matchTypeAtom :: Pattern () Type Box
118124matchTypeAtom = typeLiterals <+> fmap ((`before` text ")") . (text "(" <>)) matchType
119125
@@ -125,6 +131,7 @@ matchType = buildPrettyPrinter operators matchTypeAtom
125131 OperatorTable [ [ AssocL typeApp $ \f x -> f `beforeWithSpace` x ]
126132 , [ AssocR appliedFunction $ \arg ret -> (arg <> text " ") `before` (text "-> " <> ret)
127133 ]
134+ , [ Wrap constrained $ \deps ty -> constraintsAsBox deps ty ]
128135 , [ Wrap forall_ $ \idents ty -> text ("forall " ++ unwords idents ++ ". ") <> ty ]
129136 , [ Wrap kinded $ \k ty -> ty `before` (text (" :: " ++ prettyPrintKind k)) ]
130137 ]
@@ -136,14 +143,14 @@ forall_ = mkPattern match
136143 match _ = Nothing
137144
138145typeAtomAsBox :: Type -> Box
139−typeAtomAsBox = fromMaybe (error "Incomplete pattern") . pattern matchTypeAtom () . insertPlaceholders
146+typeAtomAsBox = fromMaybe (internalError "Incomplete pattern") . pattern matchTypeAtom () . insertPlaceholders
140147
141148-- | Generate a pretty-printed string representing a Type, as it should appear inside parentheses
142149prettyPrintTypeAtom :: Type -> String
143150prettyPrintTypeAtom = render . typeAtomAsBox
144151
145152typeAsBox :: Type -> Box
146−typeAsBox = fromMaybe (error "Incomplete pattern") . pattern matchType () . insertPlaceholders
153+typeAsBox = fromMaybe (internalError "Incomplete pattern") . pattern matchType () . insertPlaceholders
147154
148155-- | Generate a pretty-printed string representing a Type
149156prettyPrintType :: Type -> String
src/Language/PureScript/Pretty/Values.hs+2−1
@@ -25,6 +25,7 @@ import Data.List (intercalate)
2525
2626import Control.Arrow (second)
2727
28+import Language.PureScript.Crash
2829import Language.PureScript.AST
2930import Language.PureScript.Names
3031import Language.PureScript.Pretty.Common
@@ -103,7 +104,7 @@ prettyPrintDeclaration (BindingGroupDeclaration ds) =
103104 where
104105 toDecl (nm, t, e) = ValueDeclaration nm t [] (Right e)
105106prettyPrintDeclaration (PositionedDeclaration _ _ d) = prettyPrintDeclaration d
106−prettyPrintDeclaration _ = error "Invalid argument to prettyPrintDeclaration"
107+prettyPrintDeclaration _ = internalError "Invalid argument to prettyPrintDeclaration"
107108
108109prettyPrintCaseAlternative :: CaseAlternative -> Box
109110prettyPrintCaseAlternative (CaseAlternative binders result) =
src/Language/PureScript/Sugar/BindingGroups.hs+17−15
@@ -16,6 +16,7 @@
1616
1717{-# LANGUAGE FlexibleContexts #-}
1818{-# LANGUAGE CPP #-}
19+{-# LANGUAGE ScopedTypeVariables #-}
1920
2021module Language.PureScript.Sugar.BindingGroups (
2122 createBindingGroups,
@@ -28,6 +29,7 @@ import Data.Graph
2829import Data.List (nub, intersect)
2930import Data.Maybe (isJust, mapMaybe)
3031#if __GLASGOW_HASKELL__ < 710
32+import Data.Foldable (foldMap)
3133import Control.Applicative
3234#endif
3335import Control.Monad ((<=<))
@@ -35,6 +37,7 @@ import Control.Monad.Error.Class (MonadError(..))
3537
3638import qualified Data.Set as S
3739
40+import Language.PureScript.Crash
3841import Language.PureScript.AST
3942import Language.PureScript.Names
4043import Language.PureScript.Types
@@ -53,20 +56,20 @@ createBindingGroupsModule = mapM $ \(Module ss coms name ds exps) -> Module ss c
5356collapseBindingGroupsModule :: [Module] -> [Module]
5457collapseBindingGroupsModule = map $ \(Module ss coms name ds exps) -> Module ss coms name (collapseBindingGroups ds) exps
5558
56−createBindingGroups :: (Functor m, Applicative m, MonadError MultipleErrors m) => ModuleName -> [Declaration] -> m [Declaration]
59+createBindingGroups :: forall m. (Functor m, Applicative m, MonadError MultipleErrors m) => ModuleName -> [Declaration] -> m [Declaration]
5760createBindingGroups moduleName = mapM f <=< handleDecls
5861
5962 where
6063 (f, _, _) = everywhereOnValuesTopDownM return handleExprs return
6164
62− handleExprs :: (Functor m, MonadError MultipleErrors m) => Expr -> m Expr
65+ handleExprs :: Expr -> m Expr
6366 handleExprs (Let ds val) = flip Let val <$> handleDecls ds
6467 handleExprs other = return other
6568
6669 -- |
6770 -- Replace all sets of mutually-recursive declarations with binding groups
6871 --
69− handleDecls :: (Functor m, MonadError MultipleErrors m) => [Declaration] -> m [Declaration]
72+ handleDecls :: [Declaration] -> m [Declaration]
7073 handleDecls ds = do
7174 let values = filter isValueDecl ds
7275 dataDecls = filter isDataDecl ds
@@ -145,19 +148,19 @@ usedProperNames moduleName =
145148getIdent :: Declaration -> Ident
146149getIdent (ValueDeclaration ident _ _ _) = ident
147150getIdent (PositionedDeclaration _ _ d) = getIdent d
148−getIdent _ = error "Expected ValueDeclaration"
151+getIdent _ = internalError "Expected ValueDeclaration"
149152
150153getProperName :: Declaration -> ProperName
151154getProperName (DataDeclaration _ pn _ _) = pn
152155getProperName (TypeSynonymDeclaration pn _ _) = pn
153156getProperName (PositionedDeclaration _ _ d) = getProperName d
154−getProperName _ = error "Expected DataDeclaration"
157+getProperName _ = internalError "Expected DataDeclaration"
155158
156159-- |
157160-- Convert a group of mutually-recursive dependencies into a BindingGroupDeclaration (or simple ValueDeclaration).
158161--
159162--
160−toBindingGroup :: (Functor m, MonadError MultipleErrors m) => ModuleName -> SCC Declaration -> m Declaration
163+toBindingGroup :: forall m. (Functor m, MonadError MultipleErrors m) => ModuleName -> SCC Declaration -> m Declaration
161164toBindingGroup _ (AcyclicSCC d) = return d
162165toBindingGroup moduleName (CyclicSCC ds') =
163166 -- Once we have a mutually-recursive group of declarations, we need to sort
@@ -177,15 +180,14 @@ toBindingGroup moduleName (CyclicSCC ds') =
177180 valueVerts :: [(Declaration, Ident, [Ident])]
178181 valueVerts = map (\d -> (d, getIdent d, usedImmediateIdents moduleName d `intersect` idents)) ds'
179182
180− toBinding :: (MonadError MultipleErrors m) => SCC Declaration -> m (Ident, NameKind, Expr)
183+ toBinding :: SCC Declaration -> m (Ident, NameKind, Expr)
181184 toBinding (AcyclicSCC d) = return $ fromValueDecl d
182− toBinding (CyclicSCC ~(d:ds)) = cycleError d ds
185+ toBinding (CyclicSCC ds) = throwError $ foldMap cycleError ds
183186
184− cycleError :: (MonadError MultipleErrors m) => Declaration -> [Declaration] -> m a
185− cycleError (PositionedDeclaration p _ d) ds = rethrowWithPosition p $ cycleError d ds
186− cycleError (ValueDeclaration n _ _ (Right _)) [] = throwError . errorMessage $ CycleInDeclaration n
187− cycleError d ds@(_:_) = rethrow (addHint (NotYetDefined (map getIdent ds))) $ cycleError d []
188− cycleError _ _ = error "Expected ValueDeclaration"
187+ cycleError :: Declaration -> MultipleErrors
188+ cycleError (PositionedDeclaration p _ d) = onErrorMessages (withPosition p) $ cycleError d
189+ cycleError (ValueDeclaration n _ _ (Right _)) = errorMessage $ CycleInDeclaration n
190+ cycleError _ = internalError "cycleError: Expected ValueDeclaration"
189191
190192toDataBindingGroup :: (MonadError MultipleErrors m) => SCC Declaration -> m Declaration
191193toDataBindingGroup (AcyclicSCC d) = return d
@@ -203,6 +205,6 @@ isTypeSynonym _ = Nothing
203205
204206fromValueDecl :: Declaration -> (Ident, NameKind, Expr)
205207fromValueDecl (ValueDeclaration ident nameKind [] (Right val)) = (ident, nameKind, val)
206−fromValueDecl ValueDeclaration{} = error "Binders should have been desugared"
208+fromValueDecl ValueDeclaration{} = internalError "Binders should have been desugared"
207209fromValueDecl (PositionedDeclaration _ _ d) = fromValueDecl d
208−fromValueDecl _ = error "Expected ValueDeclaration"
210+fromValueDecl _ = internalError "Expected ValueDeclaration"
src/Language/PureScript/Sugar/CaseDeclarations.hs+3−2
@@ -23,6 +23,7 @@ module Language.PureScript.Sugar.CaseDeclarations (
2323 desugarCasesModule
2424) where
2525
26+import Language.PureScript.Crash
2627import Data.Maybe (catMaybes)
2728import Data.List (nub, groupBy)
2829
@@ -112,7 +113,7 @@ toDecls [ValueDeclaration ident nameKind bs (Right val)] | all isVarBinder bs =
112113 fromVarBinder (VarBinder name) = return name
113114 fromVarBinder (PositionedBinder _ _ b) = fromVarBinder b
114115 fromVarBinder (TypedBinder _ b) = fromVarBinder b
115− fromVarBinder _ = error "fromVarBinder: Invalid argument"
116+ fromVarBinder _ = internalError "fromVarBinder: Invalid argument"
116117toDecls ds@(ValueDeclaration ident _ bs result : _) = do
117118 let tuples = map toTuple ds
118119 unless (all ((== length bs) . length . fst) tuples) $
@@ -129,7 +130,7 @@ toDecls ds = return ds
129130toTuple :: Declaration -> ([Binder], Either [(Guard, Expr)] Expr)
130131toTuple (ValueDeclaration _ _ bs result) = (bs, result)
131132toTuple (PositionedDeclaration _ _ d) = toTuple d
132−toTuple _ = error "Not a value declaration"
133+toTuple _ = internalError "Not a value declaration"
133134
134135makeCaseDeclaration :: forall m. (Functor m, Applicative m, MonadSupply m, MonadError MultipleErrors m) => Ident -> [([Binder], Either [(Guard, Expr)] Expr)] -> m Declaration
135136makeCaseDeclaration ident alternatives = do
src/Language/PureScript/Sugar/DoNotation.hs+2−1
@@ -22,6 +22,7 @@ module Language.PureScript.Sugar.DoNotation (
2222 desugarDoModule
2323) where
2424
25+import Language.PureScript.Crash
2526import Language.PureScript.Names
2627import Language.PureScript.AST
2728import Language.PureScript.Errors
@@ -56,7 +57,7 @@ desugarDo d =
5657 replace other = return other
5758
5859 go :: [DoNotationElement] -> m Expr
59− go [] = error "The impossible happened in desugarDo"
60+ go [] = internalError "The impossible happened in desugarDo"
6061 go [DoNotationValue val] = return val
6162 go (DoNotationValue val : rest) = do
6263 rest' <- go rest
src/Language/PureScript/Sugar/Names.hs+8−3
@@ -22,14 +22,16 @@ import Data.List (find, nub)
2222import Data.Maybe (fromMaybe, mapMaybe)
2323
2424#if __GLASGOW_HASKELL__ < 710
25+import Data.Monoid (mempty)
2526import Control.Applicative (Applicative(..), (<$>), (<*>))
2627#endif
2728import Control.Monad
2829import Control.Monad.Error.Class (MonadError(..))
29−import Control.Monad.Writer (MonadWriter(..))
30+import Control.Monad.Writer (MonadWriter(..), censor)
3031
3132import qualified Data.Map as M
3233
34+import Language.PureScript.Crash
3335import Language.PureScript.AST
3436import Language.PureScript.Names
3537import Language.PureScript.Types
@@ -46,10 +48,13 @@ import Language.PureScript.Sugar.Names.Exports
4648--
4749desugarImports :: forall m. (Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) => [ExternsFile] -> [Module] -> m [Module]
4850desugarImports externs modules = do
49− env <- foldM externsEnv primEnv externs
51+ env <- silence $ foldM externsEnv primEnv externs
5052 env' <- foldM updateEnv env modules
5153 mapM (renameInModule' env') modules
5254 where
55+ silence :: m a -> m a
56+ silence = censor (const mempty)
57+
5358 -- | Create an environment from a collection of externs files
5459 externsEnv :: Env -> ExternsFile -> m Env
5560 externsEnv env ExternsFile{..} = do
@@ -99,7 +104,7 @@ desugarImports externs modules = do
99104 renameInModule' :: Env -> Module -> m Module
100105 renameInModule' env m@(Module _ _ mn _ _) =
101106 rethrow (addHint (ErrorInModule mn)) $ do
102− let (_, imps, exps) = fromMaybe (error "Module is missing in renameInModule'") $ M.lookup mn env
107+ let (_, imps, exps) = fromMaybe (internalError "Module is missing in renameInModule'") $ M.lookup mn env
103108 elaborateImports imps <$> renameInModule env imps (elaborateExports exps m)
104109
105110-- |
src/Language/PureScript/Sugar/Names/Exports.hs+8−7
@@ -33,6 +33,7 @@ import Control.Monad.Error.Class (MonadError(..))
3333
3434import qualified Data.Map as M
3535
36+import Language.PureScript.Crash
3637import Language.PureScript.AST
3738import Language.PureScript.Names
3839import Language.PureScript.Errors
@@ -52,7 +53,7 @@ findExportable (Module _ _ mn ds _) =
5253 where
5354 go exps'' (TypeDeclaration name _) = exportValue exps'' name mn
5455 go exps'' (PositionedDeclaration pos _ d) = rethrowWithPosition pos $ go exps'' d
55− go _ _ = error "Invalid declaration in TypeClassDeclaration"
56+ go _ _ = internalError "Invalid declaration in TypeClassDeclaration"
5657 updateExports exps (DataDeclaration _ tn _ dcs) = exportType exps tn (map fst dcs) mn
5758 updateExports exps (TypeSynonymDeclaration tn _ _) = exportType exps tn [] mn
5859 updateExports exps (ExternDataDeclaration tn _) = exportType exps tn [] mn
@@ -137,24 +138,24 @@ resolveExports env mn imps exps refs =
137138 resolveTypeExports tctors dctors = map go tctors
138139 where
139140 go :: Qualified ProperName -> ((ProperName, [ProperName]), ModuleName)
140− go (Qualified (Just mn'') name) = fromMaybe (error "Missing value in resolveTypeExports") $ do
141+ go (Qualified (Just mn'') name) = fromMaybe (internalError "Missing value in resolveTypeExports") $ do
141142 exps' <- envModuleExports <$> mn'' `M.lookup` env
142143 ((_, dctors'), mnOrig) <- find (\((name', _), _) -> name == name') (exportedTypes exps')
143144 let relevantDctors = mapMaybe (\(Qualified mn''' dctor) -> if mn''' == Just mnOrig then Just dctor else Nothing) dctors
144145 return ((name, intersect relevantDctors dctors'), mnOrig)
145− go (Qualified Nothing _) = error "Unqualified value in resolveTypeExports"
146+ go (Qualified Nothing _) = internalError "Unqualified value in resolveTypeExports"
146147
147148
148149 -- Looks up an imported class and re-qualifies it with the original module it
149150 -- came from.
150151 resolveClass :: Qualified ProperName -> (ProperName, ModuleName)
151− resolveClass className = splitQual $ fromMaybe (error "Missing value in resolveClass") $
152+ resolveClass className = splitQual $ fromMaybe (internalError "Missing value in resolveClass") $
152153 resolve exportedTypeClasses className
153154
154155 -- Looks up an imported value and re-qualifies it with the original module it
155156 -- came from.
156157 resolveValue :: Qualified Ident -> (Ident, ModuleName)
157− resolveValue ident = splitQual $ fromMaybe (error "Missing value in resolveValue") $
158+ resolveValue ident = splitQual $ fromMaybe (internalError "Missing value in resolveValue") $
158159 resolve exportedValues ident
159160
160161 resolve :: (Eq a) => (Exports -> [(a, ModuleName)]) -> Qualified a -> Maybe (Qualified a)
@@ -162,13 +163,13 @@ resolveExports env mn imps exps refs =
162163 exps' <- envModuleExports <$> mn'' `M.lookup` env
163164 mn''' <- snd <$> find ((== a) . fst) (f exps')
164165 return $ Qualified (Just mn''') a
165− resolve _ _ = error "Unqualified value in resolve"
166+ resolve _ _ = internalError "Unqualified value in resolve"
166167
167168 -- A partial function that takes a qualified value and extracts the value and
168169 -- qualified module components.
169170 splitQual :: Qualified a -> (a, ModuleName)
170171 splitQual (Qualified (Just mn'') a) = (a, mn'')
171− splitQual _ = error "Unqualified value in splitQual"
172+ splitQual _ = internalError "Unqualified value in splitQual"
172173
173174-- |
174175-- Filters the full list of exportable values, types, and classes for a module
src/Language/PureScript/Sugar/Names/Imports.hs+7−6
@@ -34,6 +34,7 @@ import Control.Monad.Writer (MonadWriter(..), censor)
3434
3535import qualified Data.Map as M
3636
37+import Language.PureScript.Crash
3738import Language.PureScript.AST
3839import Language.PureScript.Names
3940import Language.PureScript.Errors
@@ -115,7 +116,7 @@ resolveImport currentModule importModule exps imps impQual =
115116 checkImportExists UnknownImportTypeClass (fst `map` exportedTypeClasses exps) name
116117 --check (ModuleRef name) =
117118 -- checkImportExists (const UnknownModule) (exportedModules exps) name
118− check _ = error "Invalid argument to checkRefs"
119+ check _ = internalError "Invalid argument to checkRefs"
119120
120121 -- Check that an explicitly imported item exists in the module it is being imported from
121122 checkImportExists :: (Eq a) => (ModuleName -> a -> SimpleErrorMessage) -> [a] -> a -> m ()
@@ -171,13 +172,13 @@ resolveImport currentModule importModule exps imps impQual =
171172 importExplicit imp (TypeClassRef name) = do
172173 typeClasses' <- updateImports (importedTypeClasses imp) runProperName (exportedTypeClasses exps) name
173174 return $ imp { importedTypeClasses = typeClasses' }
174− importExplicit _ _ = error "Invalid argument to importExplicit"
175+ importExplicit _ _ = internalError "Invalid argument to importExplicit"
175176
176177 -- Find all exported data constructors for a given type
177178 allExportedDataConstructors :: ProperName -> [(ProperName, ModuleName)]
178179 allExportedDataConstructors name =
179180 case find ((== name) . fst . fst) (exportedTypes exps) of
180− Nothing -> error "Invalid state in allExportedDataConstructors"
181+ Nothing -> internalError "Invalid state in allExportedDataConstructors"
181182 Just ((_, dctors), mn) -> map (, mn) dctors
182183
183184 -- Add something to the Imports if it does not already exist there
@@ -191,7 +192,7 @@ resolveImport currentModule importModule exps imps impQual =
191192 -- If the name is not already present add it to the list, after looking up
192193 -- where it was originally defined
193194 Nothing ->
194− let mnOrig = fromMaybe (error "Invalid state in updateImports") (name `lookup` exps')
195+ let mnOrig = fromMaybe (internalError "Invalid state in updateImports") (name `lookup` exps')
195196 in return $ M.insert (Qualified impQual name) (Qualified (Just importModule) name, mnOrig) imps'
196197
197198 -- If the name already is present check whether it's a duplicate import
@@ -199,7 +200,7 @@ resolveImport currentModule importModule exps imps impQual =
199200 -- re-exports A, importing A and B in C should not result in a "conflicting
200201 -- import for `x`" error
201202 Just (Qualified (Just mn) _, mnOrig)
202− | mnOrig == fromMaybe (error "Invalid state in updateImports") (name `lookup` exps') -> return imps'
203+ | mnOrig == fromMaybe (internalError "Invalid state in updateImports") (name `lookup` exps') -> return imps'
203204 | otherwise -> throwError . errorMessage $ err
204205 where
205206 err = if currentModule `elem` [mn, importModule]
@@ -207,4 +208,4 @@ resolveImport currentModule importModule exps imps impQual =
207208 else ConflictingImports (render name) mn importModule
208209
209210 Just (Qualified Nothing _, _) ->
210− error "Invalid state in updateImports"
211+ internalError "Invalid state in updateImports"
src/Language/PureScript/Sugar/Operators.hs+3−2
@@ -29,6 +29,7 @@ module Language.PureScript.Sugar.Operators (
2929 desugarOperatorSections
3030) where
3131
32+import Language.PureScript.Crash
3233import Language.PureScript.AST
3334import Language.PureScript.Errors
3435import Language.PureScript.Names
@@ -93,7 +94,7 @@ collectFixities (Module _ _ moduleName ds _) = concatMap collect ds
9394 where
9495 collect :: Declaration -> [(Qualified Ident, SourceSpan, Fixity)]
9596 collect (PositionedDeclaration pos _ (FixityDeclaration fixity name)) = [(Qualified (Just moduleName) (Op name), pos, fixity)]
96− collect FixityDeclaration{} = error "Fixity without srcpos info"
97+ collect FixityDeclaration{} = internalError "Fixity without srcpos info"
9798 collect _ = []
9899
99100ensureNoDuplicates :: (MonadError MultipleErrors m) => [(Qualified Ident, SourceSpan)] -> m ()
@@ -129,7 +130,7 @@ matchOperators ops = parseChains
129130 extendChain (BinaryNoParens op l r) = Left l : Right op : extendChain r
130131 extendChain other = [Left other]
131132 bracketChain :: Chain -> m Expr
132− bracketChain = either (const . throwError . errorMessage $ CannotReorderOperators) return . P.parse (P.buildExpressionParser opTable parseValue <* P.eof) "operator expression"
133+ bracketChain = either (\_ -> internalError "matchOperators: cannot reorder operators") return . P.parse (P.buildExpressionParser opTable parseValue <* P.eof) "operator expression"
133134 opTable = [P.Infix (P.try (parseTicks >>= \op -> return (\t1 t2 -> App (App op t1) t2))) P.AssocLeft]
134135 : map (map (\(name, f, a) -> P.Infix (P.try (matchOp name) >> return f) (toAssoc a))) ops
135136 ++ [[ P.Infix (P.try (parseOp >>= \ident -> return (\t1 t2 -> App (App (Var ident) t1) t2))) P.AssocLeft ]]
src/Language/PureScript/Sugar/TypeClasses.hs+9−8
@@ -24,6 +24,7 @@ module Language.PureScript.Sugar.TypeClasses
2424 , superClassDictionaryNames
2525 ) where
2626
27+import Language.PureScript.Crash
2728import Language.PureScript.AST hiding (isExported)
2829import Language.PureScript.Environment
2930import Language.PureScript.Errors
@@ -75,7 +76,7 @@ desugarModule (Module ss coms name decls (Just exps)) = do
7576 | isTypeClassDeclaration d1 && not (isTypeClassDeclaration d2) = LT
7677 | not (isTypeClassDeclaration d1) && isTypeClassDeclaration d2 = GT
7778 | otherwise = EQ
78−desugarModule _ = error "Exports should have been elaborated in name desugaring"
79+desugarModule _ = internalError "Exports should have been elaborated in name desugaring"
7980
8081{- Desugar type class and type class instance declarations
8182--
@@ -177,7 +178,7 @@ desugarDecl mn exps = go
177178 go d@(TypeClassDeclaration name args implies members) = do
178179 modify (M.insert (mn, name) (args, implies, members))
179180 return (Nothing, d : typeClassDictionaryDeclaration name args implies members : map (typeClassMemberToDictionaryAccessor mn name args) members)
180− go (TypeInstanceDeclaration _ _ _ _ DerivedInstance) = error "Derived instanced should have been desugared"
181+ go (TypeInstanceDeclaration _ _ _ _ DerivedInstance) = internalError "Derived instanced should have been desugared"
181182 go d@(TypeInstanceDeclaration name deps className tys (ExplicitInstance members)) = do
182183 desugared <- desugarCases members
183184 dictDecl <- typeInstanceDictionaryDeclaration name mn deps className tys desugared
@@ -200,7 +201,7 @@ desugarDecl mn exps = go
200201
201202 isExported :: (ProperName -> [DeclarationRef] -> Bool) -> Qualified ProperName -> Bool
202203 isExported test (Qualified (Just mn') pn) = mn /= mn' || test pn exps
203− isExported _ _ = error "Names should have been qualified in name desugaring"
204+ isExported _ _ = internalError "Names should have been qualified in name desugaring"
204205
205206 matchesTypeRef :: ProperName -> DeclarationRef -> Bool
206207 matchesTypeRef pn (TypeRef pn' _) = pn == pn'
@@ -216,7 +217,7 @@ desugarDecl mn exps = go
216217memberToNameAndType :: Declaration -> (Ident, Type)
217218memberToNameAndType (TypeDeclaration ident ty) = (ident, ty)
218219memberToNameAndType (PositionedDeclaration _ _ d) = memberToNameAndType d
219−memberToNameAndType _ = error "Invalid declaration in type class definition"
220+memberToNameAndType _ = internalError "Invalid declaration in type class definition"
220221
221222typeClassDictionaryDeclaration :: ProperName -> [(String, Maybe Kind)] -> [Constraint] -> [Declaration] -> Declaration
222223typeClassDictionaryDeclaration name args implies members =
@@ -236,7 +237,7 @@ typeClassMemberToDictionaryAccessor mn name args (TypeDeclaration ident ty) =
236237 moveQuantifiersToFront (quantify (ConstrainedType [(className, map (TypeVar . fst) args)] ty))
237238typeClassMemberToDictionaryAccessor mn name args (PositionedDeclaration pos com d) =
238239 PositionedDeclaration pos com $ typeClassMemberToDictionaryAccessor mn name args d
239−typeClassMemberToDictionaryAccessor _ _ _ _ = error "Invalid declaration in type class definition"
240+typeClassMemberToDictionaryAccessor _ _ _ _ = internalError "Invalid declaration in type class definition"
240241
241242unit :: Type
242243unit = TypeApp tyObject REmpty
@@ -289,18 +290,18 @@ typeInstanceDictionaryDeclaration name mn deps className tys decls =
289290
290291 memberToValue :: (Functor m, Applicative m, MonadSupply m, MonadError MultipleErrors m) => [(Ident, Type)] -> Declaration -> Desugar m Expr
291292 memberToValue tys' (ValueDeclaration ident _ [] (Right val)) = do
292− _ <- maybe (throwError . errorMessage $ ExtraneousClassMember ident) return $ lookup ident tys'
293+ _ <- maybe (throwError . errorMessage $ ExtraneousClassMember ident className) return $ lookup ident tys'
293294 return val
294295 memberToValue tys' (PositionedDeclaration pos com d) = rethrowWithPosition pos $ do
295296 val <- memberToValue tys' d
296297 return (PositionedValue pos com val)
297− memberToValue _ _ = error "Invalid declaration in type instance definition"
298+ memberToValue _ _ = internalError "Invalid declaration in type instance definition"
298299
299300typeClassMemberName :: Declaration -> String
300301typeClassMemberName (TypeDeclaration ident _) = runIdent ident
301302typeClassMemberName (ValueDeclaration ident _ _ _) = runIdent ident
302303typeClassMemberName (PositionedDeclaration _ _ d) = typeClassMemberName d
303−typeClassMemberName _ = error "typeClassMemberName: Invalid declaration in type class definition"
304+typeClassMemberName _ = internalError "typeClassMemberName: Invalid declaration in type class definition"
304305
305306superClassDictionaryNames :: [Constraint] -> [String]
306307superClassDictionaryNames supers =
src/Language/PureScript/Sugar/TypeClasses/Deriving.hs+4−3
@@ -36,6 +36,7 @@ import Control.Monad (replicateM)
3636import Control.Monad.Supply.Class (MonadSupply, freshName)
3737import Control.Monad.Error.Class (MonadError(..))
3838
39+import Language.PureScript.Crash
3940import Language.PureScript.AST
4041import Language.PureScript.Environment
4142import Language.PureScript.Errors
@@ -116,7 +117,7 @@ mkSpineFunction mn (DataDeclaration _ _ _ args) = lamCase "$x" <$> mapM mkCtorCl
116117 $ decomposeRec rec
117118 toSpineFun i _ = lamNull $ App (mkGenVar C.toSpine) i
118119mkSpineFunction mn (PositionedDeclaration _ _ d) = mkSpineFunction mn d
119−mkSpineFunction _ _ = error "mkSpineFunction: expected DataDeclaration"
120+mkSpineFunction _ _ = internalError "mkSpineFunction: expected DataDeclaration"
120121
121122mkSignatureFunction :: ModuleName -> Declaration -> Expr
122123mkSignatureFunction _ (DataDeclaration _ _ _ args) = lamNull . mkSigProd $ map mkProdClause args
@@ -145,7 +146,7 @@ mkSignatureFunction _ (DataDeclaration _ _ _ args) = lamNull . mkSigProd $ map m
145146 mkProductSignature typ = lamNull $ App (mkGenVar C.toSignature)
146147 (TypedValue False (mkGenVar "anyProxy") (proxy typ))
147148mkSignatureFunction mn (PositionedDeclaration _ _ d) = mkSignatureFunction mn d
148−mkSignatureFunction _ _ = error "mkSignatureFunction: expected DataDeclaration"
149+mkSignatureFunction _ _ = internalError "mkSignatureFunction: expected DataDeclaration"
149150
150151mkFromSpineFunction :: forall m. (Functor m, MonadSupply m) => ModuleName -> Declaration -> m Expr
151152mkFromSpineFunction mn (DataDeclaration _ _ _ args) = lamCase "$x" <$> (addCatch <$> mapM mkAlternative args)
@@ -194,7 +195,7 @@ mkFromSpineFunction mn (DataDeclaration _ _ _ args) = lamCase "$x" <$> (addCatch
194195 mkRecFun xs = mkJust $ foldr (\s e -> lam s e) recLiteral (map fst xs)
195196 where recLiteral = ObjectLiteral $ map (\(s,_) -> (s,mkVar s)) xs
196197mkFromSpineFunction mn (PositionedDeclaration _ _ d) = mkFromSpineFunction mn d
197−mkFromSpineFunction _ _ = error "mkFromSpineFunction: expected DataDeclaration"
198+mkFromSpineFunction _ _ = internalError "mkFromSpineFunction: expected DataDeclaration"
198199
199200-- Helpers
200201
src/Language/PureScript/Sugar/TypeDeclarations.hs+14−20
@@ -25,9 +25,8 @@ module Language.PureScript.Sugar.TypeDeclarations (
2525#if __GLASGOW_HASKELL__ < 710
2626import Control.Applicative
2727#endif
28−import Control.Monad (forM, when)
28+import Control.Monad (forM)
2929import Control.Monad.Error.Class (MonadError(..))
30−import Control.Monad.Writer.Class (MonadWriter(tell))
3130
3231import Language.PureScript.AST
3332import Language.PureScript.Names
@@ -38,19 +37,19 @@ import Language.PureScript.Traversals
3837-- |
3938-- Replace all top level type declarations in a module with type annotations
4039--
41−desugarTypeDeclarationsModule :: forall m. (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) => [Module] -> m [Module]
40+desugarTypeDeclarationsModule :: forall m. (Functor m, Applicative m, MonadError MultipleErrors m) => [Module] -> m [Module]
4241desugarTypeDeclarationsModule ms = forM ms $ \(Module ss coms name ds exps) ->
4342 rethrow (addHint (ErrorInModule name)) $
44− Module ss coms name <$> desugarTypeDeclarations True ds <*> pure exps
43+ Module ss coms name <$> desugarTypeDeclarations ds <*> pure exps
4544 where
4645
47− desugarTypeDeclarations :: Bool -> [Declaration] -> m [Declaration]
48− desugarTypeDeclarations reqd (PositionedDeclaration pos com d : ds) = do
49− (d' : ds') <- rethrowWithPosition pos $ desugarTypeDeclarations reqd (d : ds)
46+ desugarTypeDeclarations :: [Declaration] -> m [Declaration]
47+ desugarTypeDeclarations (PositionedDeclaration pos com d : ds) = do
48+ (d' : ds') <- rethrowWithPosition pos $ desugarTypeDeclarations (d : ds)
5049 return (PositionedDeclaration pos com d' : ds')
51− desugarTypeDeclarations reqd (TypeDeclaration name ty : d : rest) = do
50+ desugarTypeDeclarations (TypeDeclaration name ty : d : rest) = do
5251 (_, nameKind, val) <- fromValueDeclaration d
53− desugarTypeDeclarations reqd (ValueDeclaration name nameKind [] (Right (TypedValue True val ty)) : rest)
52+ desugarTypeDeclarations (ValueDeclaration name nameKind [] (Right (TypedValue True val ty)) : rest)
5453 where
5554 fromValueDeclaration :: Declaration -> m (Ident, NameKind, Expr)
5655 fromValueDeclaration (ValueDeclaration name' nameKind [] (Right val)) | name == name' = return (name', nameKind, val)
@@ -58,19 +57,14 @@ desugarTypeDeclarationsModule ms = forM ms $ \(Module ss coms name ds exps) ->
5857 (ident, nameKind, val) <- rethrowWithPosition pos $ fromValueDeclaration d'
5958 return (ident, nameKind, PositionedValue pos com val)
6059 fromValueDeclaration _ = throwError . errorMessage $ OrphanTypeDeclaration name
61− desugarTypeDeclarations _ [TypeDeclaration name _] = throwError . errorMessage $ OrphanTypeDeclaration name
62− desugarTypeDeclarations reqd (ValueDeclaration name nameKind bs val : rest) = do
63− -- At the top level, match a type signature or emit a warning.
64− when reqd $ case val of
65− Right TypedValue{} -> return ()
66− Left _ -> error "desugarTypeDeclarations: cases were not desugared"
67− _ -> tell (addHint (ErrorInValueDeclaration name) $ errorMessage $ MissingTypeDeclaration name)
60+ desugarTypeDeclarations [TypeDeclaration name _] = throwError . errorMessage $ OrphanTypeDeclaration name
61+ desugarTypeDeclarations (ValueDeclaration name nameKind bs val : rest) = do
6862 let (_, f, _) = everywhereOnValuesTopDownM return go return
6963 f' (Left gs) = Left <$> mapM (pairM return f) gs
7064 f' (Right v) = Right <$> f v
71− (:) <$> (ValueDeclaration name nameKind bs <$> f' val) <*> desugarTypeDeclarations reqd rest
65+ (:) <$> (ValueDeclaration name nameKind bs <$> f' val) <*> desugarTypeDeclarations rest
7266 where
73− go (Let ds val') = Let <$> desugarTypeDeclarations False ds <*> pure val'
67+ go (Let ds val') = Let <$> desugarTypeDeclarations ds <*> pure val'
7468 go other = return other
75− desugarTypeDeclarations reqd (d:ds) = (:) d <$> desugarTypeDeclarations reqd ds
76− desugarTypeDeclarations _ [] = return []
69+ desugarTypeDeclarations (d:ds) = (:) d <$> desugarTypeDeclarations ds
70+ desugarTypeDeclarations [] = return []
src/Language/PureScript/TypeChecker.hs+15−14
@@ -38,6 +38,7 @@ import Control.Applicative ((<$>), (<*))
3838import Control.Monad.State
3939import Control.Monad.Error.Class (MonadError(..))
4040
41+import Language.PureScript.Crash
4142import Language.PureScript.Types
4243import Language.PureScript.Names
4344import Language.PureScript.Kinds
@@ -90,7 +91,7 @@ addTypeClass moduleName pn args implies ds =
9091 where
9192 toPair (TypeDeclaration ident ty) = (ident, ty)
9293 toPair (PositionedDeclaration _ _ d) = toPair d
93− toPair _ = error "Invalid declaration in TypeClassDeclaration"
94+ toPair _ = internalError "Invalid declaration in TypeClassDeclaration"
9495
9596addTypeClassDictionaries :: Maybe ModuleName -> M.Map (Qualified ProperName) (M.Map (Qualified Ident) TypeClassDictionaryInScope) -> Check ()
9697addTypeClassDictionaries mn entries =
@@ -147,8 +148,8 @@ typeCheckAll moduleName _ ds = mapM go ds <* mapM_ checkOrphanFixities ds
147148 where
148149 checkNewtype :: [(ProperName, [Type])] -> Check ()
149150 checkNewtype [(_, [_])] = return ()
150− checkNewtype [(_, _)] = throwError . errorMessage $ InvalidNewtype
151− checkNewtype _ = throwError . errorMessage $ InvalidNewtype
151+ checkNewtype [(_, _)] = throwError . errorMessage $ InvalidNewtype name
152+ checkNewtype _ = throwError . errorMessage $ InvalidNewtype name
152153 go (d@(DataBindingGroupDeclaration tys)) = do
153154 warnAndRethrow (addHint ErrorInDataBindingGroup) $ do
154155 let syns = mapMaybe toTypeSynonym tys
@@ -177,14 +178,14 @@ typeCheckAll moduleName _ ds = mapM go ds <* mapM_ checkOrphanFixities ds
177178 let args' = args `withKinds` kind
178179 addTypeSynonym moduleName name args' ty kind
179180 return $ TypeSynonymDeclaration name args ty
180− go (TypeDeclaration{}) = error "Type declarations should have been removed"
181+ go (TypeDeclaration{}) = internalError "Type declarations should have been removed"
181182 go (ValueDeclaration name nameKind [] (Right val)) =
182183 warnAndRethrow (addHint (ErrorInValueDeclaration name)) $ do
183184 valueIsNotDefined moduleName name
184185 [(_, (val', ty))] <- typesOf moduleName [(name, val)]
185186 addValue moduleName name ty nameKind
186187 return $ ValueDeclaration name nameKind [] $ Right val'
187− go (ValueDeclaration{}) = error "Binders were not desugared"
188+ go (ValueDeclaration{}) = internalError "Binders were not desugared"
188189 go (BindingGroupDeclaration vals) =
189190 warnAndRethrow (addHint (ErrorInBindingGroup (map (\(ident, _, _) -> ident) vals))) $ do
190191 forM_ (map (\(ident, _, _) -> ident) vals) $ \name ->
@@ -205,7 +206,7 @@ typeCheckAll moduleName _ ds = mapM go ds <* mapM_ checkOrphanFixities ds
205206 go (d@(ExternDeclaration name ty)) = do
206207 warnAndRethrow (addHint (ErrorInForeignImport name)) $ do
207208 env <- getEnv
208− kind <- kindOf moduleName ty
209+ kind <- kindOf ty
209210 guardWith (errorMessage (ExpectedType ty kind)) $ kind == Star
210211 case M.lookup (moduleName, name) (names env) of
211212 Just _ -> throwError . errorMessage $ RedefinedIdent name
@@ -245,7 +246,7 @@ typeCheckAll moduleName _ ds = mapM go ds <* mapM_ checkOrphanFixities ds
245246 memberName :: Declaration -> Ident
246247 memberName (ValueDeclaration ident _ _ _) = ident
247248 memberName (PositionedDeclaration _ _ d) = memberName d
248− memberName _ = error "checkInstanceMembers: Invalid declaration in type instance definition"
249+ memberName _ = internalError "checkInstanceMembers: Invalid declaration in type instance definition"
249250
250251 firstDuplicate :: (Eq a) => [a] -> Maybe a
251252 firstDuplicate (x : xs@(y : _))
@@ -261,10 +262,10 @@ typeCheckAll moduleName _ ds = mapM go ds <* mapM_ checkOrphanFixities ds
261262 checkType :: Type -> Bool
262263 checkType (TypeVar _) = False
263264 checkType (TypeConstructor (Qualified (Just mn'') _)) = moduleName == mn''
264− checkType (TypeConstructor (Qualified Nothing _)) = error "Unqualified type name in checkOrphanInstance"
265+ checkType (TypeConstructor (Qualified Nothing _)) = internalError "Unqualified type name in checkOrphanInstance"
265266 checkType (TypeApp t1 _) = checkType t1
266− checkType _ = error "Invalid type in instance in checkOrphanInstance"
267− checkOrphanInstance _ _ _ = error "Unqualified class name in checkOrphanInstance"
267+ checkType _ = internalError "Invalid type in instance in checkOrphanInstance"
268+ checkOrphanInstance _ _ _ = internalError "Unqualified class name in checkOrphanInstance"
268269
269270 -- |
270271 -- This function adds the argument kinds for a type constructor so that they may appear in the externs file,
@@ -274,14 +275,14 @@ typeCheckAll moduleName _ ds = mapM go ds <* mapM_ checkOrphanFixities ds
274275 withKinds [] _ = []
275276 withKinds (s@(_, Just _ ):ss) (FunKind _ k) = s : withKinds ss k
276277 withKinds ( (s, Nothing):ss) (FunKind k1 k2) = (s, Just k1) : withKinds ss k2
277− withKinds _ _ = error "Invalid arguments to peelKinds"
278+ withKinds _ _ = internalError "Invalid arguments to peelKinds"
278279
279280-- |
280281-- Type check an entire module and ensure all types and classes defined within the module that are
281282-- required by exported members are also exported.
282283--
283284typeCheckModule :: Module -> Check Module
284−typeCheckModule (Module _ _ _ _ Nothing) = error "exports should have been elaborated"
285+typeCheckModule (Module _ _ _ _ Nothing) = internalError "exports should have been elaborated"
285286typeCheckModule (Module ss coms mn decls (Just exps)) = warnAndRethrow (addHint (ErrorInModule mn)) $ do
286287 modify (\s -> s { checkCurrentModule = Just mn })
287288 decls' <- typeCheckAll mn exps decls
@@ -331,7 +332,7 @@ typeCheckModule (Module ss coms mn decls (Just exps)) = warnAndRethrow (addHint
331332 findTcons :: Type -> [DeclarationRef]
332333 findTcons = everythingOnTypes (++) go
333334 where
334− go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [TypeRef name (error "Data constructors unused in checkTypesAreExported")]
335+ go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [TypeRef name (internalError "Data constructors unused in checkTypesAreExported")]
335336 go _ = []
336337
337338 -- Check that all the classes defined in the current module that appear in member types have also
@@ -361,5 +362,5 @@ typeCheckModule (Module ss coms mn decls (Just exps)) = warnAndRethrow (addHint
361362 extractMemberName :: Declaration -> Ident
362363 extractMemberName (PositionedDeclaration _ _ d) = extractMemberName d
363364 extractMemberName (TypeDeclaration memberName _) = memberName
364− extractMemberName _ = error "Unexpected declaration in typeclass member list"
365+ extractMemberName _ = internalError "Unexpected declaration in typeclass member list"
365366 checkClassMembersAreExported _ = return ()
src/Language/PureScript/TypeChecker/Entailment.hs+3−2
@@ -35,6 +35,7 @@ import Control.Monad.State
3535import Control.Monad.Error.Class (MonadError(..))
3636import Control.Monad.Writer.Class (tell)
3737
38+import Language.PureScript.Crash
3839import Language.PureScript.AST
3940import Language.PureScript.Errors
4041import Language.PureScript.Names
@@ -53,11 +54,11 @@ entails moduleName context = solve
5354 where
5455 forClassName :: Qualified ProperName -> [Type] -> [TypeClassDictionaryInScope]
5556 forClassName cn@(Qualified (Just mn) _) tys = concatMap (findDicts cn) (Nothing : Just mn : map Just (mapMaybe ctorModules tys))
56− forClassName _ _ = error "forClassName: expected qualified class name"
57+ forClassName _ _ = internalError "forClassName: expected qualified class name"
5758
5859 ctorModules :: Type -> Maybe ModuleName
5960 ctorModules (TypeConstructor (Qualified (Just mn) _)) = Just mn
60− ctorModules (TypeConstructor (Qualified Nothing _)) = error "ctorModules: unqualified type name"
61+ ctorModules (TypeConstructor (Qualified Nothing _)) = internalError "ctorModules: unqualified type name"
6162 ctorModules (TypeApp ty _) = ctorModules ty
6263 ctorModules _ = Nothing
6364
src/Language/PureScript/TypeChecker/Kinds.hs+4−3
@@ -40,6 +40,7 @@ import Control.Monad.Error.Class (MonadError(..))
4040import Control.Monad.State
4141import Control.Monad.Unify
4242
43+import Language.PureScript.Crash
4344import Language.PureScript.Environment
4445import Language.PureScript.Errors
4546import Language.PureScript.Kinds
@@ -75,8 +76,8 @@ instance Unifiable Check Kind where
7576-- |
7677-- Infer the kind of a single type
7778--
78−kindOf :: ModuleName -> Type -> Check Kind
79−kindOf _ ty = fst <$> kindOfWithScopedVars ty
79+kindOf :: Type -> Check Kind
80+kindOf ty = fst <$> kindOfWithScopedVars ty
8081
8182-- |
8283-- Infer the kind of a single type, returning the kinds of any scoped type variables
@@ -220,4 +221,4 @@ infer' other = (, []) <$> go other
220221 k <- go ty
221222 k =?= Star
222223 return Star
223− go _ = error "Invalid argument to infer"
224+ go _ = internalError "Invalid argument to infer"
src/Language/PureScript/TypeChecker/Monad.hs+1−1
@@ -153,7 +153,7 @@ checkVisibility :: (e ~ MultipleErrors, Functor m, MonadState CheckState m, Mona
153153checkVisibility currentModule name@(Qualified _ var) = do
154154 vis <- getVisibility currentModule name
155155 case vis of
156− Undefined -> throwError . errorMessage $ NameNotInScope var
156+ Undefined -> throwError . errorMessage $ CycleInDeclaration var
157157 _ -> return ()
158158
159159-- |
src/Language/PureScript/TypeChecker/Skolems.hs+11−5
@@ -33,6 +33,7 @@ import Control.Applicative
3333import Control.Monad.Error.Class (MonadError(..))
3434import Control.Monad.Unify
3535
36+import Language.PureScript.Crash
3637import Language.PureScript.AST
3738import Language.PureScript.Errors
3839import Language.PureScript.TypeChecker.Monad
@@ -71,11 +72,16 @@ skolemize ident sko scope = replaceTypeVars ident (Skolem ident sko scope)
7172-- only example of scoped type variables.
7273--
7374skolemizeTypesInValue :: String -> Int -> SkolemScope -> Expr -> Expr
74−skolemizeTypesInValue ident sko scope = let (_, f, _) = everywhereOnValues id go id in f
75+skolemizeTypesInValue ident sko scope = let (_, f, _) = everywhereOnValues id onExpr onBinder in f
7576 where
76− go (SuperClassDictionary c ts) = SuperClassDictionary c (map (skolemize ident sko scope) ts)
77− go (TypedValue check val ty) = TypedValue check val (skolemize ident sko scope ty)
78− go other = other
77+ onExpr :: Expr -> Expr
78+ onExpr (SuperClassDictionary c ts) = SuperClassDictionary c (map (skolemize ident sko scope) ts)
79+ onExpr (TypedValue check val ty) = TypedValue check val (skolemize ident sko scope ty)
80+ onExpr other = other
81+
82+ onBinder :: Binder -> Binder
83+ onBinder (TypedBinder ty b) = TypedBinder (skolemize ident sko scope ty) b
84+ onBinder other = other
7985
8086-- |
8187-- Ensure skolem variables do not escape their scope
@@ -115,4 +121,4 @@ skolemEscapeCheck root@TypedValue{} =
115121 where
116122 go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = First (Just val)
117123 go' _ = mempty
118−skolemEscapeCheck _ = error "Untyped value passed to skolemEscapeCheck"
124+skolemEscapeCheck _ = internalError "Untyped value passed to skolemEscapeCheck"
src/Language/PureScript/TypeChecker/Subsumption.hs+12−4
@@ -20,9 +20,10 @@ module Language.PureScript.TypeChecker.Subsumption (
2020import Data.List (sortBy)
2121import Data.Ord (comparing)
2222
23−import Control.Monad.Error.Class (MonadError(..))
2423import Control.Monad.Unify
24+import Control.Monad.Error.Class (throwError)
2525
26+import Language.PureScript.Crash
2627import Language.PureScript.AST
2728import Language.PureScript.Environment
2829import Language.PureScript.Errors
@@ -50,7 +51,7 @@ subsumes' val ty1 (ForAll ident ty2 sco) =
5051 sko <- newSkolemConstant
5152 let sk = skolemize ident sko sco' ty2
5253 subsumes val ty1 sk
53− Nothing -> throwError . errorMessage $ UnspecifiedSkolemScope
54+ Nothing -> internalError "subsumes: unspecified skolem scope"
5455subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
5556 _ <- subsumes Nothing arg2 arg1
5657 _ <- subsumes Nothing ret1 ret2
@@ -77,10 +78,17 @@ subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject
7778 | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
7879 go ts1 ts2 r1' r2'
7980 | p1 < p2 = do rest <- fresh
80− r2' =?= RCons p1 ty1 rest
81+ -- What happens next is a bit of a hack.
82+ -- TODO: in the new type checker, object properties will probably be restricted to being monotypes
83+ -- in which case, this branch of the subsumes function should not even be necessary.
84+ case r2' of
85+ REmpty -> throwError . errorMessage $ AdditionalProperty p1
86+ _ -> r2' =?= RCons p1 ty1 rest
8187 go ts1 ((p2, ty2) : ts2) r1' rest
8288 | otherwise = do rest <- fresh
83− r1' =?= RCons p2 ty2 rest
89+ case r1' of
90+ REmpty -> throwError . errorMessage $ PropertyIsMissing p2
91+ _ -> r1' =?= RCons p2 ty2 rest
8492 go ((p1, ty1) : ts1) ts2 rest r2'
8593subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
8694subsumes' val ty1 ty2 = do
src/Language/PureScript/TypeChecker/Types.hs+52−43
@@ -50,7 +50,9 @@ import Control.Monad
5050import Control.Monad.State
5151import Control.Monad.Unify
5252import Control.Monad.Error.Class (MonadError(..))
53+import Control.Monad.Writer.Class (tell)
5354
55+import Language.PureScript.Crash
5456import Language.PureScript.AST
5557import Language.PureScript.Environment
5658import Language.PureScript.Errors
@@ -77,7 +79,7 @@ typesOf moduleName vals = do
7779 tys <- fmap tidyUp . liftUnifyWarnings replace $ do
7880 (untyped, typed, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName vals
7981 ds1 <- parU typed $ \e -> checkTypedBindingGroupElement moduleName e dict
80− ds2 <- forM untyped $ \e -> typeForBindingGroupElement e dict untypedDict
82+ ds2 <- forM untyped $ \e -> typeForBindingGroupElement True e dict untypedDict
8183 return $ ds1 ++ ds2
8284
8385 forM tys $ \(ident, (val, ty)) -> do
@@ -93,6 +95,7 @@ typesOf moduleName vals = do
9395 tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
9496 -- Replace all the wildcards types with their inferred types
9597 replace sub (ErrorMessage hints (WildcardInferredType ty)) = ErrorMessage hints $ WildcardInferredType (sub $? ty)
98+ replace sub (ErrorMessage hints (MissingTypeDeclaration name ty)) = ErrorMessage hints $ MissingTypeDeclaration name (varIfUnknown (sub $? ty))
9699 replace _ em = em
97100
98101type TypeData = M.Map (ModuleName, Ident) (Type, NameKind, NameVisibility)
@@ -134,11 +137,12 @@ checkTypedBindingGroupElement mn (ident, (val', ty, checkType)) dict = do
134137 else return (TypedValue False val' ty'')
135138 return (ident, (val'', ty''))
136139
137−typeForBindingGroupElement :: (Ident, Expr) -> TypeData -> UntypedData -> UnifyT Type Check (Ident, (Expr, Type))
138−typeForBindingGroupElement (ident, val) dict untypedDict = do
140+typeForBindingGroupElement :: Bool -> (Ident, Expr) -> TypeData -> UntypedData -> UnifyT Type Check (Ident, (Expr, Type))
141+typeForBindingGroupElement warn (ident, val) dict untypedDict = do
139142 -- Infer the type with the new names in scope
140143 TypedValue _ val' ty <- bindNames dict $ infer val
141− ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
144+ ty =?= fromMaybe (internalError "name not found in dictionary") (lookup ident untypedDict)
145+ when warn . tell . errorMessage $ MissingTypeDeclaration ident ty
142146 return (ident, (TypedValue True val' ty, ty))
143147
144148-- |
@@ -189,7 +193,7 @@ instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
189193 instantiatePolyTypeWithUnknowns val ty'
190194instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
191195 dicts <- getTypeClassDictionaries
192− (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
196+ (_, ty') <- instantiatePolyTypeWithUnknowns (internalError "Types under a constraint cannot themselves be constrained") ty
193197 return (foldl App val (map (flip TypeClassDictionary dicts) constraints), ty')
194198instantiatePolyTypeWithUnknowns val ty = return (val, ty)
195199
@@ -228,7 +232,7 @@ infer' (ObjectUpdate o ps) = do
228232 let oldTy = TypeApp tyObject $ rowFromList (oldTys, row)
229233 o' <- TypedValue True <$> check o oldTy <*> pure oldTy
230234 return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
231−infer' (Accessor prop val) = do
235+infer' (Accessor prop val) = rethrow (addHint (ErrorCheckingAccessor val prop)) $ do
232236 field <- fresh
233237 rest <- fresh
234238 typed <- check val (TypeApp tyObject (RCons prop field rest))
@@ -239,7 +243,7 @@ infer' (Abs (Left arg) ret) = do
239243 withBindingGroupVisible $ bindLocalVariables moduleName [(arg, ty, Defined)] $ do
240244 body@(TypedValue _ _ bodyTy) <- infer' ret
241245 return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
242−infer' (Abs (Right _) _) = error "Binder was not desugared"
246+infer' (Abs (Right _) _) = internalError "Binder was not desugared"
243247infer' (App f arg) = do
244248 f'@(TypedValue _ _ ft) <- infer f
245249 (ret, app) <- checkFunctionApplication f' ft arg Nothing
@@ -284,7 +288,7 @@ infer' (TypedValue checkType val ty) = do
284288 val' <- if checkType then withScopedTypeVars moduleName args (check val ty') else return val
285289 return $ TypedValue True val' ty'
286290infer' (PositionedValue pos _ val) = warnAndRethrowWithPosition pos $ infer' val
287−infer' _ = error "Invalid argument to infer"
291+infer' _ = internalError "Invalid argument to infer"
288292
289293inferLetBinding :: [Declaration] -> [Declaration] -> Expr -> (Expr -> UnifyT Type Check Expr) -> UnifyT Type Check ([Declaration], Expr)
290294inferLetBinding seen [] ret j = (,) seen <$> withBindingGroupVisible (j ret)
@@ -307,7 +311,7 @@ inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
307311 Just moduleName <- checkCurrentModule <$> get
308312 (untyped, typed, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName (map (\(i, _, v) -> (i, v)) ds)
309313 ds1' <- parU typed $ \e -> checkTypedBindingGroupElement moduleName e dict
310− ds2' <- forM untyped $ \e -> typeForBindingGroupElement e dict untypedDict
314+ ds2' <- forM untyped $ \e -> typeForBindingGroupElement False e dict untypedDict
311315 let ds' = [(ident, Private, val') | (ident, (val', _)) <- ds1' ++ ds2']
312316 bindNames dict $ do
313317 makeBindingGroupVisible
@@ -315,7 +319,7 @@ inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
315319inferLetBinding seen (PositionedDeclaration pos com d : ds) ret j = warnAndRethrowWithPosition pos $ do
316320 (d' : ds', val') <- inferLetBinding seen (d : ds) ret j
317321 return (PositionedDeclaration pos com d' : ds', val')
318−inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
322+inferLetBinding _ _ _ _ = internalError "Invalid argument to inferLetBinding"
319323
320324-- |
321325-- Infer the types of variables brought into scope by a binder
@@ -332,20 +336,19 @@ inferBinder val (ConstructorBinder ctor binders) = do
332336 env <- getEnv
333337 case M.lookup ctor (dataConstructors env) of
334338 Just (_, _, ty, _) -> do
335− (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
339+ (_, fn) <- instantiatePolyTypeWithUnknowns (internalError "Data constructor types cannot contain constraints") ty
336340 fn' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ fn
337− go binders fn'
338− where
339− go [] ty' = case (val, ty') of
340− (TypeConstructor _, TypeApp _ _) -> throwIncorrectArity
341− _ -> do
342− _ <- val =?= ty'
343− return M.empty
344− go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
345− M.union <$> inferBinder obj binder <*> go binders' ret
346− go _ _ = throwIncorrectArity
347− throwIncorrectArity = throwError . errorMessage $ IncorrectConstructorArity ctor
341+ let (args, ret) = peelArgs fn'
342+ unless (length args == length binders) . throwError . errorMessage $ IncorrectConstructorArity ctor
343+ ret =?= val
344+ M.unions <$> zipWithM inferBinder (reverse args) binders
348345 _ -> throwError . errorMessage $ UnknownDataConstructor ctor Nothing
346+ where
347+ peelArgs :: Type -> ([Type], Type)
348+ peelArgs = go []
349+ where
350+ go args (TypeApp (TypeApp fn arg) ret) | fn == tyFunction = go (arg : args) ret
351+ go args ret = (args, ret)
349352inferBinder val (ObjectBinder props) = do
350353 row <- fresh
351354 rest <- fresh
@@ -370,9 +373,15 @@ inferBinder val (NamedBinder name binder) = do
370373 return $ M.insert name val m
371374inferBinder val (PositionedBinder pos _ binder) =
372375 warnAndRethrowWithPosition pos $ inferBinder val binder
373−-- TODO: When adding support for polymorphic types, check subsumption here
374−-- and change the definition of `binderRequiresMonotype`
375−inferBinder val (TypedBinder ty binder) = val =?= ty >> inferBinder val binder
376+-- TODO: When adding support for polymorphic types, check subsumption here,
377+-- change the definition of `binderRequiresMonotype`,
378+-- and use `kindOfWithScopedVars`.
379+inferBinder val (TypedBinder ty binder) = do
380+ ty1 <- replaceAllTypeSynonyms <=< replaceTypeWildcards $ ty
381+ kind <- liftCheck $ kindOf ty1
382+ checkTypeKind ty1 kind
383+ val =?= ty1
384+ inferBinder val binder
376385
377386-- | Returns true if a binder requires its argument type to be a monotype.
378387-- | If this is the case, we need to instantiate any polymorphic types before checking binders.
@@ -409,7 +418,7 @@ checkBinders nvals ret (CaseAlternative binders result : bs) = do
409418 case result of
410419 Left gs -> do
411420 gs' <- forM gs $ \(grd, val) -> do
412− grd' <- check grd tyBoolean
421+ grd' <- rethrow (addHint ErrorCheckingGuard) $ check grd tyBoolean
413422 val' <- TypedValue True <$> check val ret <*> pure ret
414423 return (grd', val')
415424 return $ Left gs'
@@ -449,7 +458,7 @@ check' val t@(ConstrainedType constraints ty) = do
449458 newDictionaries :: [(Qualified ProperName, Integer)] -> Qualified Ident -> (Qualified ProperName, [Type]) -> Check [TypeClassDictionaryInScope]
450459 newDictionaries path name (className, instanceTy) = do
451460 tcs <- gets (typeClasses . checkEnv)
452− let (args, _, superclasses) = fromMaybe (error "newDictionaries: type class lookup failed") $ M.lookup className tcs
461+ let (args, _, superclasses) = fromMaybe (internalError "newDictionaries: type class lookup failed") $ M.lookup className tcs
453462 supDicts <- join <$> zipWithM (\(supName, supArgs) index ->
454463 newDictionaries ((supName, index) : path)
455464 name
@@ -484,7 +493,7 @@ check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) = do
484493 Just moduleName <- checkCurrentModule <$> get
485494 ret' <- withBindingGroupVisible $ bindLocalVariables moduleName [(arg, argTy, Defined)] $ check ret retTy
486495 return $ TypedValue True (Abs (Left arg) ret') ty
487−check' (Abs (Right _) _) _ = error "Binder was not desugared"
496+check' (Abs (Right _) _) _ = internalError "Binder was not desugared"
488497check' (App f arg) ret = do
489498 f'@(TypedValue _ _ ft) <- infer f
490499 (_, app) <- checkFunctionApplication f' ft arg (Just ret)
@@ -496,7 +505,7 @@ check' v@(Var var) ty = do
496505 ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< replaceTypeWildcards $ ty
497506 v' <- subsumes (Just v) repl ty'
498507 case v' of
499− Nothing -> throwError . errorMessage $ SubsumptionCheckFailed
508+ Nothing -> internalError "check: unable to check the subsumes relation."
500509 Just v'' -> return $ TypedValue True v'' ty'
501510check' (SuperClassDictionary className tys) _ = do
502511 {-
@@ -515,7 +524,7 @@ check' (TypedValue checkType val ty1) ty2 = do
515524 ty2' <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< replaceTypeWildcards $ ty2
516525 val' <- subsumes (Just val) ty1' ty2'
517526 case val' of
518− Nothing -> throwError . errorMessage $ SubsumptionCheckFailed
527+ Nothing -> internalError "check: unable to check the subsumes relation."
519528 Just _ -> do
520529 val''' <- if checkType then withScopedTypeVars moduleName args (check val ty2') else return val
521530 return $ TypedValue checkType val''' ty2'
@@ -528,24 +537,24 @@ check' (IfThenElse cond th el) ty = do
528537 th' <- check th ty
529538 el' <- check el ty
530539 return $ TypedValue True (IfThenElse cond' th' el') ty
531−check' (ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
540+check' e@(ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
532541 ensureNoDuplicateProperties ps
533− ps' <- checkProperties ps row False
542+ ps' <- checkProperties e ps row False
534543 return $ TypedValue True (ObjectLiteral ps') t
535544check' (TypeClassDictionaryConstructorApp name ps) t = do
536545 ps' <- check' ps t
537546 return $ TypedValue True (TypeClassDictionaryConstructorApp name ps') t
538−check' (ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
547+check' e@(ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
539548 ensureNoDuplicateProperties ps
540549 -- We need to be careful to avoid duplicate labels here.
541− -- We check _obj_ agaist the type _t_ with the types in _ps_ replaced with unknowns.
550+ -- We check _obj_ against the type _t_ with the types in _ps_ replaced with unknowns.
542551 let (propsToCheck, rest) = rowToList row
543552 (removedProps, remainingProps) = partition (\(p, _) -> p `elem` map fst ps) propsToCheck
544553 us <- zip (map fst removedProps) <$> replicateM (length ps) fresh
545554 obj' <- check obj (TypeApp tyObject (rowFromList (us ++ remainingProps, rest)))
546− ps' <- checkProperties ps row True
555+ ps' <- checkProperties e ps row True
547556 return $ TypedValue True (ObjectUpdate obj' ps') t
548−check' (Accessor prop val) ty = do
557+check' (Accessor prop val) ty = rethrow (addHint (ErrorCheckingAccessor val prop)) $ do
549558 rest <- fresh
550559 val' <- check val (TypeApp tyObject (RCons prop ty rest))
551560 return $ TypedValue True (Accessor prop val') ty
@@ -557,7 +566,7 @@ check' v@(Constructor c) ty = do
557566 repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
558567 mv <- subsumes (Just v) repl ty
559568 case mv of
560− Nothing -> throwError . errorMessage $ SubsumptionCheckFailed
569+ Nothing -> internalError "check: unable to check the subsumes relation."
561570 Just v' -> return $ TypedValue True v' ty
562571check' (Let ds val) ty = do
563572 (ds', val') <- inferLetBinding [] ds val (`check` ty)
@@ -572,7 +581,7 @@ check' val ty = do
572581 TypedValue _ val' ty' <- infer val
573582 mt <- subsumes (Just val') ty' ty
574583 case mt of
575− Nothing -> throwError . errorMessage $ SubsumptionCheckFailed
584+ Nothing -> internalError "check: unable to check the subsumes relation."
576585 Just v' -> return $ TypedValue True v' ty
577586
578587-- |
@@ -580,8 +589,8 @@ check' val ty = do
580589--
581590-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
582591--
583−checkProperties :: [(String, Expr)] -> Type -> Bool -> UnifyT Type Check [(String, Expr)]
584−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
592+checkProperties :: Expr -> [(String, Expr)] -> Type -> Bool -> UnifyT Type Check [(String, Expr)]
593+checkProperties expr ps row lax = let (ts, r') = rowToList row in go ps ts r' where
585594 go [] [] REmpty = return []
586595 go [] [] u@(TUnknown _)
587596 | lax = return []
@@ -589,8 +598,8 @@ checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
589598 return []
590599 go [] [] Skolem{} | lax = return []
591600 go [] ((p, _): _) _ | lax = return []
592− | otherwise = throwError . errorMessage $ PropertyIsMissing p row
593− go ((p,_):_) [] REmpty = throwError . errorMessage $ PropertyIsMissing p row
601+ | otherwise = throwError . errorMessage $ PropertyIsMissing p
602+ go ((p,_):_) [] REmpty = throwError . errorMessage $ AdditionalProperty p
594603 go ((p,v):ps') ts r =
595604 case lookup p ts of
596605 Nothing -> do
@@ -603,7 +612,7 @@ checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
603612 v' <- check v ty
604613 ps'' <- go ps' (delete (p, ty) ts) r
605614 return $ (p, v') : ps''
606− go _ _ _ = throwError . errorMessage $ ExprDoesNotHaveType (ObjectLiteral ps) (TypeApp tyObject row)
615+ go _ _ _ = throwError . errorMessage $ ExprDoesNotHaveType expr (TypeApp tyObject row)
607616
608617-- |
609618-- Check the type of a function application, rethrowing errors to provide a better error message
src/Language/PureScript/TypeChecker/Unify.hs+3−2
@@ -36,6 +36,7 @@ import Control.Monad.Unify
3636import Control.Monad.Writer
3737import Control.Monad.Error.Class (MonadError(..))
3838
39+import Language.PureScript.Crash
3940import Language.PureScript.Errors
4041import Language.PureScript.TypeChecker.Monad
4142import Language.PureScript.TypeChecker.Skolems
@@ -74,12 +75,12 @@ unifyTypes t1 t2 = rethrow (addHint (ErrorUnifyingTypes t1 t2)) $
7475 let sk1 = skolemize ident1 sko sc1' ty1
7576 let sk2 = skolemize ident2 sko sc2' ty2
7677 sk1 `unifyTypes` sk2
77− _ -> error "Skolemized type variable was not given a scope"
78+ _ -> internalError "unifyTypes: unspecified skolem scope"
7879 unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
7980 sko <- newSkolemConstant
8081 let sk = skolemize ident sko sc ty1
8182 sk `unifyTypes` ty2
82− unifyTypes' ForAll{} _ = throwError . errorMessage $ UnspecifiedSkolemScope
83+ unifyTypes' ForAll{} _ = internalError "unifyTypes: unspecified skolem scope"
8384 unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
8485 unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
8586 unifyTypes' ty1@(TypeConstructor c1) ty2@(TypeConstructor c2) =
tests/Main.hs+3−3
@@ -78,7 +78,7 @@ modulesDir :: FilePath
7878modulesDir = ".test_modules" </> "node_modules"
7979
8080makeActions :: M.Map P.ModuleName FilePath -> P.MakeActions P.Make
81−makeActions foreigns = (P.buildMakeActions modulesDir (error "makeActions: input file map was read.") foreigns False)
81+makeActions foreigns = (P.buildMakeActions modulesDir (P.internalError "makeActions: input file map was read.") foreigns False)
8282 { P.getInputTimestamp = getInputTimestamp
8383 , P.getOutputTimestamp = getOutputTimestamp
8484 }
@@ -94,7 +94,7 @@ makeActions foreigns = (P.buildMakeActions modulesDir (error "makeActions: input
9494 getOutputTimestamp mn = do
9595 let filePath = modulesDir </> P.runModuleName mn
9696 exists <- liftIO $ doesDirectoryExist filePath
97− return (if exists then Just (error "getOutputTimestamp: read timestamp") else Nothing)
97+ return (if exists then Just (P.internalError "getOutputTimestamp: read timestamp") else Nothing)
9898
9999readInput :: [FilePath] -> IO [(FilePath, String)]
100100readInput inputFiles = forM inputFiles $ \inputFile -> do
@@ -104,7 +104,7 @@ readInput inputFiles = forM inputFiles $ \inputFile -> do
104104type TestM = WriterT [(FilePath, String)] IO
105105
106106runTest :: P.Make a -> IO (Either P.MultipleErrors a)
107−runTest = fmap (fmap fst) . P.runMake P.defaultOptions
107+runTest = fmap fst . P.runMake P.defaultOptions
108108
109109compile :: [FilePath] -> M.Map P.ModuleName FilePath -> IO (Either P.MultipleErrors P.Environment)
110110compile inputFiles foreigns = runTest $ do
tests/common/TestsSetup.hs+3−1
@@ -28,6 +28,8 @@ import System.Process
2828import System.Directory
2929import System.Info
3030
31+import Language.PureScript.Crash
32+
3133findNodeProcess :: IO (Maybe String)
3234findNodeProcess = runMaybeT . msum $ map (MaybeT . findExecutable) names
3335 where
@@ -35,7 +37,7 @@ findNodeProcess = runMaybeT . msum $ map (MaybeT . findExecutable) names
3537
3638fetchSupportCode :: IO ()
3739fetchSupportCode = do
38− node <- fromMaybe (error "cannot find node executable") <$> findNodeProcess
40+ node <- fromMaybe (internalError "cannot find node executable") <$> findNodeProcess
3941 setCurrentDirectory "tests/support"
4042 if System.Info.os == "mingw32"
4143 then callProcess "setup-win.cmd" []