git.iko.soy/rowtype-yoga/purescript-native
on golang help sign in
Merge pull request #1516 from purescript/hints

Hints

commitcb63bd4f34436032e6e462cc44d91ff5a81b2013 authorPhil Freeman <paf31@cantab.net> dateTue 13 Oct 2015, 16:44 (11 years ago) parent0c35b8331a03b7
23 files changed+344−392
.gitignore+1 psci/PSCi.hs+2−2 src/Language/PureScript/Errors.hs+235−278 src/Language/PureScript/Linter.hs+4−4 src/Language/PureScript/Linter/Exhaustive.hs+29−20 src/Language/PureScript/Make.hs+3−3 src/Language/PureScript/Parser/Declarations.hs+1−1 src/Language/PureScript/Pretty/Values.hs+2−1 src/Language/PureScript/Sugar/BindingGroups.hs+1−1 src/Language/PureScript/Sugar/CaseDeclarations.hs+1−1 src/Language/PureScript/Sugar/Names.hs+1−1 src/Language/PureScript/Sugar/Names/Exports.hs+2−2 src/Language/PureScript/Sugar/Names/Imports.hs+1−1 src/Language/PureScript/Sugar/Operators.hs+1−1 src/Language/PureScript/Sugar/TypeClasses.hs+1−1 src/Language/PureScript/Sugar/TypeDeclarations.hs+37−33 src/Language/PureScript/TypeChecker.hs+8−8 src/Language/PureScript/TypeChecker/Kinds.hs+2−2 src/Language/PureScript/TypeChecker/Skolems.hs+1−1 src/Language/PureScript/TypeChecker/Subsumption.hs+1−1 src/Language/PureScript/TypeChecker/Synonyms.hs+1−1 src/Language/PureScript/TypeChecker/Types.hs+8−28 src/Language/PureScript/TypeChecker/Unify.hs+1−1
.gitignore+1
@@ -15,3 +15,4 @@ node_modules
1515tmp/
1616.stack-work/
1717tests/support/flattened/
18+output
psci/PSCi.hs+2−2
@@ -464,7 +464,7 @@ handleCommand (LoadFile filePath) = whenFileExists filePath $ \absPath -> do
464464 Right mods -> PSCI . lift $ modify (updateModules (map ((,) (Right absPath)) mods))
465465handleCommand (LoadForeign filePath) = whenFileExists filePath $ \absPath -> do
466466 foreignsOrError <- psciIO . runMake $ do
467− foreignFile <- makeIO (const (P.SimpleErrorWrapper $ P.CannotReadFile absPath)) (readFile absPath)
467+ foreignFile <- makeIO (const (P.ErrorMessage [] $ P.CannotReadFile absPath)) (readFile absPath)
468468 P.parseForeignModulesFromFiles [(absPath, foreignFile)]
469469 case foreignsOrError of
470470 Left err -> PSCI $ outputStrLn $ P.prettyPrintMultipleErrors False err
@@ -533,7 +533,7 @@ loop PSCiOptions{..} = do
533533 historyFilename <- getHistoryFilename
534534 let settings = defaultSettings { historyFile = Just historyFilename }
535535 foreignsOrError <- runMake $ do
536− foreignFilesContent <- forM foreignFiles (\inFile -> (inFile,) <$> makeIO (const (P.SimpleErrorWrapper $ P.CannotReadFile inFile)) (readFile inFile))
536+ foreignFilesContent <- forM foreignFiles (\inFile -> (inFile,) <$> makeIO (const (P.ErrorMessage [] $ P.CannotReadFile inFile)) (readFile inFile))
537537 P.parseForeignModulesFromFiles foreignFilesContent
538538 case foreignsOrError of
539539 Left errs -> putStrLn (P.prettyPrintMultipleErrors False errs) >> exitFailure
src/Language/PureScript/Errors.hs+235−278
@@ -20,10 +20,11 @@
2020module Language.PureScript.Errors where
2121
2222import Data.Either (lefts, rights)
23−import Data.List (intercalate, transpose, nub)
23+import Data.List (intercalate, transpose, nub, nubBy, partition)
2424import Data.Function (on)
2525#if __GLASGOW_HASKELL__ < 710
2626import Data.Foldable (fold, foldMap)
27+import Data.Traversable (traverse)
2728#else
2829import Data.Foldable (fold)
2930#endif
@@ -53,9 +54,7 @@ import qualified Text.Parsec as P
5354import qualified Text.Parsec.Error as PE
5455import Text.Parsec.Error (Message(..))
5556
56−-- |
57−-- A type of error messages
58−--
57+-- | A type of error messages
5958data SimpleErrorMessage
6059 = ErrorParsingExterns P.ParseError
6160 | ErrorParsingFFIModule FilePath
@@ -142,45 +141,54 @@ data SimpleErrorMessage
142141 | ShadowedTypeVar String
143142 | UnusedTypeVar String
144143 | WildcardInferredType Type
144+ | MissingTypeDeclaration Ident
145145 | NotExhaustivePattern [[Binder]] Bool
146146 | OverlappingPattern [[Binder]] Bool
147147 | IncompleteExhaustivityCheck
148148 | ClassOperator ProperName Ident
149149 | MisleadingEmptyTypeImport ModuleName ProperName
150150 | ImportHidingModule ModuleName
151− deriving (Show)
152−
153−-- |
154−-- Wrapper of simpler errors
155−--
156−data ErrorMessage
157− = NotYetDefined [Ident] ErrorMessage
158− | ErrorUnifyingTypes Type Type ErrorMessage
159− | ErrorInExpression Expr ErrorMessage
160− | ErrorInModule ModuleName ErrorMessage
161− | ErrorInInstance (Qualified ProperName) [Type] ErrorMessage
162− | ErrorInSubsumption Type Type ErrorMessage
163− | ErrorCheckingType Expr Type ErrorMessage
164− | ErrorCheckingKind Type ErrorMessage
165− | ErrorInferringType Expr ErrorMessage
166− | ErrorInApplication Expr Type Expr ErrorMessage
167− | ErrorInDataConstructor ProperName ErrorMessage
168− | ErrorInTypeConstructor ProperName ErrorMessage
169− | ErrorInBindingGroup [Ident] ErrorMessage
170− | ErrorInDataBindingGroup ErrorMessage
171− | ErrorInTypeSynonym ProperName ErrorMessage
172− | ErrorInValueDeclaration Ident ErrorMessage
173− | ErrorInTypeDeclaration Ident ErrorMessage
174− | ErrorInForeignImport Ident ErrorMessage
175− | PositionedError SourceSpan ErrorMessage
176− | SimpleErrorWrapper SimpleErrorMessage
177− deriving (Show)
151+ deriving Show
152+
153+-- | Error message hints, providing more detailed information about failure.
154+data ErrorMessageHint
155+ = NotYetDefined [Ident]
156+ | ErrorUnifyingTypes Type Type
157+ | ErrorInExpression Expr
158+ | ErrorInModule ModuleName
159+ | ErrorInInstance (Qualified ProperName) [Type]
160+ | ErrorInSubsumption Type Type
161+ | ErrorCheckingType Expr Type
162+ | ErrorCheckingKind Type
163+ | ErrorInferringType Expr
164+ | ErrorInApplication Expr Type Expr
165+ | ErrorInDataConstructor ProperName
166+ | ErrorInTypeConstructor ProperName
167+ | ErrorInBindingGroup [Ident]
168+ | ErrorInDataBindingGroup
169+ | ErrorInTypeSynonym ProperName
170+ | ErrorInValueDeclaration Ident
171+ | ErrorInTypeDeclaration Ident
172+ | ErrorInForeignImport Ident
173+ | PositionedError SourceSpan
174+ deriving Show
175+
176+-- | Categories of hints
177+data HintCategory
178+ = ExprHint
179+ | KindHint
180+ | CheckHint
181+ | PositionHint
182+ | OtherHint
183+ deriving (Show, Eq)
184+
185+data ErrorMessage = ErrorMessage [ErrorMessageHint] SimpleErrorMessage deriving (Show)
178186
179187instance UnificationError Type ErrorMessage where
180− occursCheckFailed t = SimpleErrorWrapper $ InfiniteType t
188+ occursCheckFailed t = ErrorMessage [] $ InfiniteType t
181189
182190instance UnificationError Kind ErrorMessage where
183− occursCheckFailed k = SimpleErrorWrapper $ InfiniteKind k
191+ occursCheckFailed k = ErrorMessage [] $ InfiniteKind k
184192
185193-- |
186194-- Get the error code for a particular error type
@@ -272,6 +280,7 @@ errorCode em = case unwrapErrorMessage em of
272280 ShadowedTypeVar{} -> "ShadowedTypeVar"
273281 UnusedTypeVar{} -> "UnusedTypeVar"
274282 WildcardInferredType{} -> "WildcardInferredType"
283+ MissingTypeDeclaration{} -> "MissingTypeDeclaration"
275284 NotExhaustivePattern{} -> "NotExhaustivePattern"
276285 OverlappingPattern{} -> "OverlappingPattern"
277286 IncompleteExhaustivityCheck{} -> "IncompleteExhaustivityCheck"
@@ -299,7 +308,7 @@ nonEmpty = not . null . runMultipleErrors
299308-- Create an error set from a single simple error message
300309--
301310errorMessage :: SimpleErrorMessage -> MultipleErrors
302−errorMessage err = MultipleErrors [SimpleErrorWrapper err]
311+errorMessage err = MultipleErrors [ErrorMessage [] err]
303312
304313
305314-- |
@@ -308,12 +317,14 @@ errorMessage err = MultipleErrors [SimpleErrorWrapper err]
308317singleError :: ErrorMessage -> MultipleErrors
309318singleError = MultipleErrors . pure
310319
311−-- |
312−-- Lift a function on ErrorMessage to a function on MultipleErrors
313−--
320+-- | Lift a function on ErrorMessage to a function on MultipleErrors
314321onErrorMessages :: (ErrorMessage -> ErrorMessage) -> MultipleErrors -> MultipleErrors
315322onErrorMessages f = MultipleErrors . map f . runMultipleErrors
316323
324+-- | Add a hint to an error message
325+addHint :: ErrorMessageHint -> MultipleErrors -> MultipleErrors
326+addHint hint = onErrorMessages $ \(ErrorMessage hints se) -> ErrorMessage (hint : hints) se
327+
317328-- | The various types of things which might need to be relabelled in errors messages.
318329data LabelType = TypeLabel | SkolemLabel String deriving (Show, Read, Eq, Ord)
319330
@@ -327,27 +338,7 @@ data Level = Error | Warning deriving Show
327338-- Extract nested error messages from wrapper errors
328339--
329340unwrapErrorMessage :: ErrorMessage -> SimpleErrorMessage
330−unwrapErrorMessage em = case em of
331− (ErrorCheckingKind _ err) -> unwrapErrorMessage err
332− (ErrorCheckingType _ _ err) -> unwrapErrorMessage err
333− (ErrorInApplication _ _ _ err) -> unwrapErrorMessage err
334− (ErrorInBindingGroup _ err) -> unwrapErrorMessage err
335− (ErrorInDataBindingGroup err) -> unwrapErrorMessage err
336− (ErrorInDataConstructor _ err) -> unwrapErrorMessage err
337− (ErrorInExpression _ err) -> unwrapErrorMessage err
338− (ErrorInForeignImport _ err) -> unwrapErrorMessage err
339− (ErrorInInstance _ _ err) -> unwrapErrorMessage err
340− (ErrorInModule _ err) -> unwrapErrorMessage err
341− (ErrorInSubsumption _ _ err) -> unwrapErrorMessage err
342− (ErrorInTypeConstructor _ err) -> unwrapErrorMessage err
343− (ErrorInTypeSynonym _ err) -> unwrapErrorMessage err
344− (ErrorInValueDeclaration _ err) -> unwrapErrorMessage err
345− (ErrorInTypeDeclaration _ err) -> unwrapErrorMessage err
346− (ErrorInferringType _ err) -> unwrapErrorMessage err
347− (ErrorUnifyingTypes _ _ err) -> unwrapErrorMessage err
348− (NotYetDefined _ err) -> unwrapErrorMessage err
349− (PositionedError _ err) -> unwrapErrorMessage err
350− (SimpleErrorWrapper sem) -> sem
341+unwrapErrorMessage (ErrorMessage _ se) = se
351342
352343replaceUnknowns :: Type -> State UnknownMap Type
353344replaceUnknowns = everywhereOnTypesM replaceTypes
@@ -363,7 +354,7 @@ replaceUnknowns = everywhereOnTypesM replaceTypes
363354 replaceTypes other = return other
364355
365356onTypesInErrorMessageM :: (Applicative m) => (Type -> m Type) -> ErrorMessage -> m ErrorMessage
366−onTypesInErrorMessageM f = g
357+onTypesInErrorMessageM f (ErrorMessage hints simple) = ErrorMessage <$> traverse gHint hints <*> gSimple simple
367358 where
368359 gSimple (InfiniteType t) = InfiniteType <$> f t
369360 gSimple (TypesDoNotUnify t1 t2) = TypesDoNotUnify <$> f t1 <*> f t2
@@ -373,204 +364,191 @@ onTypesInErrorMessageM f = g
373364 gSimple (CannotApplyFunction t e) = CannotApplyFunction <$> f t <*> pure e
374365 gSimple (InvalidInstanceHead t) = InvalidInstanceHead <$> f t
375366 gSimple other = pure other
376− g (ErrorInSubsumption t1 t2 em) = ErrorInSubsumption <$> f t1 <*> f t2 <*> g em
377− g (ErrorUnifyingTypes t1 t2 e) = ErrorUnifyingTypes <$> f t1 <*> f t2 <*> g e
378− g (ErrorCheckingType e t em) = ErrorCheckingType e <$> f t <*> g em
379− g (ErrorCheckingKind t em) = ErrorCheckingKind <$> f t <*> g em
380− g (ErrorInApplication e1 t1 e2 em) = ErrorInApplication e1 <$> f t1 <*> pure e2 <*> g em
381− g (NotYetDefined x e) = NotYetDefined x <$> g e
382− g (ErrorInExpression x e) = ErrorInExpression x <$> g e
383− g (ErrorInModule x e) = ErrorInModule x <$> g e
384− g (ErrorInInstance x y e) = ErrorInInstance x y <$> g e
385− g (ErrorInferringType x e) = ErrorInferringType x <$> g e
386− g (ErrorInDataConstructor x e) = ErrorInDataConstructor x <$> g e
387− g (ErrorInTypeConstructor x e) = ErrorInTypeConstructor x <$> g e
388− g (ErrorInBindingGroup x e) = ErrorInBindingGroup x <$> g e
389− g (ErrorInDataBindingGroup e) = ErrorInDataBindingGroup <$> g e
390− g (ErrorInTypeSynonym x e) = ErrorInTypeSynonym x <$> g e
391− g (ErrorInValueDeclaration x e) = ErrorInValueDeclaration x <$> g e
392− g (ErrorInTypeDeclaration x e) = ErrorInTypeDeclaration x <$> g e
393− g (ErrorInForeignImport x e) = ErrorInForeignImport x <$> g e
394− g (PositionedError x e) = PositionedError x <$> g e
395− g (SimpleErrorWrapper sem) = SimpleErrorWrapper <$> gSimple sem
367+ gHint (ErrorInSubsumption t1 t2) = ErrorInSubsumption <$> f t1 <*> f t2
368+ gHint (ErrorUnifyingTypes t1 t2) = ErrorUnifyingTypes <$> f t1 <*> f t2
369+ gHint (ErrorCheckingType e t) = ErrorCheckingType e <$> f t
370+ gHint (ErrorCheckingKind t) = ErrorCheckingKind <$> f t
371+ gHint (ErrorInApplication e1 t1 e2) = ErrorInApplication e1 <$> f t1 <*> pure e2
372+ gHint other = pure other
396373
397374-- |
398375-- Pretty print a single error, simplifying if necessary
399376--
400377prettyPrintSingleError :: Bool -> Level -> ErrorMessage -> State UnknownMap Box.Box
401−prettyPrintSingleError full level e = prettyPrintErrorMessage <$> onTypesInErrorMessageM replaceUnknowns (if full then e else simplifyErrorMessage e)
378+prettyPrintSingleError full level e = prettyPrintErrorMessage . positionHintsFirst . reverseHints <$> onTypesInErrorMessageM replaceUnknowns (if full then e else simplifyErrorMessage e)
402379 where
403− -- |
380+
404381 -- Pretty print an ErrorMessage
405− --
406382 prettyPrintErrorMessage :: ErrorMessage -> Box.Box
407− prettyPrintErrorMessage em =
383+ prettyPrintErrorMessage (ErrorMessage hints simple) =
408384 paras $
409− go em:suggestions em ++
385+ map renderHint hints ++
386+ renderSimpleErrorMessage simple :
387+ suggestions simple ++
410388 [line $ "See " ++ wikiUri ++ " for more information, or to contribute content related to this " ++ levelText ++ "."]
411389 where
412390 wikiUri :: String
413391 wikiUri = "https://github.com/purescript/purescript/wiki/Error-Code-" ++ errorCode e
414392
415− go :: ErrorMessage -> Box.Box
416− goSimple (CannotGetFileInfo path) =
393+ renderSimpleErrorMessage :: SimpleErrorMessage -> Box.Box
394+ renderSimpleErrorMessage (CannotGetFileInfo path) =
417395 paras [ line "Unable to read file info: "
418396 , indent . line $ path
419397 ]
420− goSimple (CannotReadFile path) =
398+ renderSimpleErrorMessage (CannotReadFile path) =
421399 paras [ line "Unable to read file: "
422400 , indent . line $ path
423401 ]
424− goSimple (CannotWriteFile path) =
402+ renderSimpleErrorMessage (CannotWriteFile path) =
425403 paras [ line "Unable to write file: "
426404 , indent . line $ path
427405 ]
428− goSimple (ErrorParsingExterns err) =
406+ renderSimpleErrorMessage (ErrorParsingExterns err) =
429407 paras [ lineWithLevel "parsing externs files: "
430408 , prettyPrintParseError err
431409 ]
432− goSimple (ErrorParsingFFIModule path) =
410+ renderSimpleErrorMessage (ErrorParsingFFIModule path) =
433411 paras [ line "Unable to parse module from FFI file: "
434412 , indent . line $ path
435413 ]
436− goSimple (ErrorParsingModule err) =
414+ renderSimpleErrorMessage (ErrorParsingModule err) =
437415 paras [ line "Unable to parse module: "
438416 , prettyPrintParseError err
439417 ]
440− goSimple (MissingFFIModule mn) =
418+ renderSimpleErrorMessage (MissingFFIModule mn) =
441419 line $ "Missing FFI implementations for module " ++ runModuleName mn
442− goSimple (UnnecessaryFFIModule mn path) =
420+ renderSimpleErrorMessage (UnnecessaryFFIModule mn path) =
443421 paras [ line $ "Unnecessary FFI implementations have been provided for module " ++ runModuleName mn ++ ": "
444422 , indent . line $ path
445423 ]
446− goSimple (MultipleFFIModules mn paths) =
424+ renderSimpleErrorMessage (MultipleFFIModules mn paths) =
447425 paras [ line $ "Multiple FFI implementations have been provided for module " ++ runModuleName mn ++ ": "
448426 , indent . paras $ map line paths
449427 ]
450− goSimple (InvalidExternsFile path) =
428+ renderSimpleErrorMessage (InvalidExternsFile path) =
451429 paras [ line "Externs file is invalid: "
452430 , indent . line $ path
453431 ]
454− goSimple InvalidDoBind =
432+ renderSimpleErrorMessage InvalidDoBind =
455433 line "Bind statement cannot be the last statement in a do block. The last statement must be an expression."
456− goSimple InvalidDoLet =
434+ renderSimpleErrorMessage InvalidDoLet =
457435 line "Let statement cannot be the last statement in a do block. The last statement must be an expression."
458− goSimple CannotReorderOperators =
436+ renderSimpleErrorMessage CannotReorderOperators =
459437 line "Unable to reorder operators"
460− goSimple UnspecifiedSkolemScope =
438+ renderSimpleErrorMessage UnspecifiedSkolemScope =
461439 line "Skolem variable scope is unspecified"
462− goSimple OverlappingNamesInLet =
440+ renderSimpleErrorMessage OverlappingNamesInLet =
463441 line "Overlapping names in let binding."
464− goSimple (InfiniteType ty) =
442+ renderSimpleErrorMessage (InfiniteType ty) =
465443 paras [ line "An infinite type was inferred for an expression: "
466444 , indent $ typeAsBox ty
467445 ]
468− goSimple (InfiniteKind ki) =
446+ renderSimpleErrorMessage (InfiniteKind ki) =
469447 paras [ line "An infinite kind was inferred for a type: "
470448 , indent $ kindAsBox ki
471449 ]
472− goSimple (MultipleFixities name) =
450+ renderSimpleErrorMessage (MultipleFixities name) =
473451 line $ "Multiple fixity declarations for " ++ showIdent name
474− goSimple (OrphanTypeDeclaration nm) =
452+ renderSimpleErrorMessage (OrphanTypeDeclaration nm) =
475453 line $ "Orphan type declaration for " ++ showIdent nm
476− goSimple (OrphanFixityDeclaration op) =
454+ renderSimpleErrorMessage (OrphanFixityDeclaration op) =
477455 line $ "Orphan fixity declaration for " ++ show op
478− goSimple (RedefinedModule name filenames) =
456+ renderSimpleErrorMessage (RedefinedModule name filenames) =
479457 paras [ line ("Module " ++ runModuleName name ++ " has been defined multiple times:")
480458 , indent . paras $ map (line . displaySourceSpan) filenames
481459 ]
482− goSimple (RedefinedIdent name) =
460+ renderSimpleErrorMessage (RedefinedIdent name) =
483461 line $ "Name " ++ showIdent name ++ " has been defined multiple times"
484− goSimple (UnknownModule mn) =
462+ renderSimpleErrorMessage (UnknownModule mn) =
485463 line $ "Unknown module " ++ runModuleName mn
486− goSimple (UnknownType name) =
464+ renderSimpleErrorMessage (UnknownType name) =
487465 line $ "Unknown type " ++ showQualified runProperName name
488− goSimple (UnknownTypeClass name) =
466+ renderSimpleErrorMessage (UnknownTypeClass name) =
489467 line $ "Unknown type class " ++ showQualified runProperName name
490− goSimple (UnknownValue name) =
468+ renderSimpleErrorMessage (UnknownValue name) =
491469 line $ "Unknown value " ++ showQualified showIdent name
492− goSimple (UnknownTypeConstructor name) =
470+ renderSimpleErrorMessage (UnknownTypeConstructor name) =
493471 line $ "Unknown type constructor " ++ showQualified runProperName name
494− goSimple (UnknownDataConstructor dc tc) =
472+ renderSimpleErrorMessage (UnknownDataConstructor dc tc) =
495473 line $ "Unknown data constructor " ++ showQualified runProperName dc ++ foldMap ((" for type constructor " ++) . showQualified runProperName) tc
496− goSimple (UnknownImportType mn name) =
474+ renderSimpleErrorMessage (UnknownImportType mn name) =
497475 line $ "Module " ++ runModuleName mn ++ " does not export type " ++ runProperName name
498− goSimple (UnknownExportType name) =
476+ renderSimpleErrorMessage (UnknownExportType name) =
499477 line $ "Cannot export unknown type " ++ runProperName name
500− goSimple (UnknownImportTypeClass mn name) =
478+ renderSimpleErrorMessage (UnknownImportTypeClass mn name) =
501479 line $ "Module " ++ runModuleName mn ++ " does not export type class " ++ runProperName name
502− goSimple (UnknownExportTypeClass name) =
480+ renderSimpleErrorMessage (UnknownExportTypeClass name) =
503481 line $ "Cannot export unknown type class " ++ runProperName name
504− goSimple (UnknownImportValue mn name) =
482+ renderSimpleErrorMessage (UnknownImportValue mn name) =
505483 line $ "Module " ++ runModuleName mn ++ " does not export value " ++ showIdent name
506− goSimple (UnknownExportValue name) =
484+ renderSimpleErrorMessage (UnknownExportValue name) =
507485 line $ "Cannot export unknown value " ++ showIdent name
508− goSimple (UnknownExportModule name) =
486+ renderSimpleErrorMessage (UnknownExportModule name) =
509487 line $ "Cannot export unknown module " ++ runModuleName name ++ ", it either does not exist or has not been imported by the current module"
510− goSimple (UnknownImportDataConstructor mn tcon dcon) =
488+ renderSimpleErrorMessage (UnknownImportDataConstructor mn tcon dcon) =
511489 line $ "Module " ++ runModuleName mn ++ " does not export data constructor " ++ runProperName dcon ++ " for type " ++ runProperName tcon
512− goSimple (UnknownExportDataConstructor tcon dcon) =
490+ renderSimpleErrorMessage (UnknownExportDataConstructor tcon dcon) =
513491 line $ "Cannot export data constructor " ++ runProperName dcon ++ " for type " ++ runProperName tcon ++ " as it has not been declared"
514− goSimple (ConflictingImport nm mn) =
492+ renderSimpleErrorMessage (ConflictingImport nm mn) =
515493 line $ "Cannot declare " ++ show nm ++ " since another declaration of that name was imported from " ++ runModuleName mn
516− goSimple (ConflictingImports nm m1 m2) =
494+ renderSimpleErrorMessage (ConflictingImports nm m1 m2) =
517495 line $ "Conflicting imports for " ++ nm ++ " from modules " ++ runModuleName m1 ++ " and " ++ runModuleName m2
518− goSimple (ConflictingTypeDecls nm) =
496+ renderSimpleErrorMessage (ConflictingTypeDecls nm) =
519497 line $ "Conflicting type declarations for " ++ runProperName nm
520− goSimple (ConflictingCtorDecls nm) =
498+ renderSimpleErrorMessage (ConflictingCtorDecls nm) =
521499 line $ "Conflicting data constructor declarations for " ++ runProperName nm
522− goSimple (TypeConflictsWithClass nm) =
500+ renderSimpleErrorMessage (TypeConflictsWithClass nm) =
523501 line $ "Type " ++ runProperName nm ++ " conflicts with type class declaration of the same name"
524− goSimple (CtorConflictsWithClass nm) =
502+ renderSimpleErrorMessage (CtorConflictsWithClass nm) =
525503 line $ "Data constructor " ++ runProperName nm ++ " conflicts with type class declaration of the same name"
526− goSimple (ClassConflictsWithType nm) =
504+ renderSimpleErrorMessage (ClassConflictsWithType nm) =
527505 line $ "Type class " ++ runProperName nm ++ " conflicts with type declaration of the same name"
528− goSimple (ClassConflictsWithCtor nm) =
506+ renderSimpleErrorMessage (ClassConflictsWithCtor nm) =
529507 line $ "Type class " ++ runProperName nm ++ " conflicts with data constructor declaration of the same name"
530− goSimple (DuplicateClassExport nm) =
508+ renderSimpleErrorMessage (DuplicateClassExport nm) =
531509 line $ "Duplicate export declaration for type class " ++ runProperName nm
532− goSimple (DuplicateValueExport nm) =
510+ renderSimpleErrorMessage (DuplicateValueExport nm) =
533511 line $ "Duplicate export declaration for value " ++ showIdent nm
534− goSimple (CycleInDeclaration nm) =
512+ renderSimpleErrorMessage (CycleInDeclaration nm) =
535513 line $ "Cycle in declaration of " ++ showIdent nm
536− goSimple (CycleInModules mns) =
514+ renderSimpleErrorMessage (CycleInModules mns) =
537515 line $ "Cycle in module dependencies: " ++ intercalate ", " (map runModuleName mns)
538− goSimple (CycleInTypeSynonym pn) =
516+ renderSimpleErrorMessage (CycleInTypeSynonym pn) =
539517 line $ "Cycle in type synonym" ++ foldMap ((" " ++) . runProperName) pn
540− goSimple (NameIsUndefined ident) =
518+ renderSimpleErrorMessage (NameIsUndefined ident) =
541519 line $ showIdent ident ++ " is undefined"
542− goSimple (NameNotInScope ident) =
520+ renderSimpleErrorMessage (NameNotInScope ident) =
543521 line $ showIdent ident ++ " may not be defined in the current scope"
544− goSimple (UndefinedTypeVariable name) =
522+ renderSimpleErrorMessage (UndefinedTypeVariable name) =
545523 line $ "Type variable " ++ runProperName name ++ " is undefined"
546− goSimple (PartiallyAppliedSynonym name) =
524+ renderSimpleErrorMessage (PartiallyAppliedSynonym name) =
547525 paras [ line $ "Partially applied type synonym " ++ showQualified runProperName name
548526 , line "Type synonyms must be applied to all of their type arguments."
549527 ]
550− goSimple (EscapedSkolem binding) =
528+ renderSimpleErrorMessage (EscapedSkolem binding) =
551529 paras $ [ line "A type variable has escaped its scope." ]
552530 <> foldMap (\expr -> [ line "Relevant expression: "
553531 , indent $ prettyPrintValue expr
554532 ]) binding
555− goSimple (TypesDoNotUnify t1 t2)
533+ renderSimpleErrorMessage (TypesDoNotUnify t1 t2)
556534 = paras [ line "Cannot unify type"
557535 , indent $ typeAsBox t1
558536 , line "with type"
559537 , indent $ typeAsBox t2
560538 ]
561− goSimple (KindsDoNotUnify k1 k2) =
539+ renderSimpleErrorMessage (KindsDoNotUnify k1 k2) =
562540 paras [ line "Cannot unify kind"
563541 , indent $ kindAsBox k1
564542 , line "with kind"
565543 , indent $ kindAsBox k2
566544 ]
567− goSimple (ConstrainedTypeUnified t1 t2) =
545+ renderSimpleErrorMessage (ConstrainedTypeUnified t1 t2) =
568546 paras [ line "Cannot unify constrained type"
569547 , indent $ typeAsBox t1
570548 , line "with type"
571549 , indent $ typeAsBox t2
572550 ]
573− goSimple (OverlappingInstances nm ts (d : ds)) =
551+ renderSimpleErrorMessage (OverlappingInstances nm ts (d : ds)) =
574552 paras [ line "Overlapping instances found for"
575553 , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
576554 , Box.vcat Box.left (map typeAtomAsBox ts)
@@ -578,46 +556,46 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage <$> onTypesInError
578556 , line "The following instances were found:"
579557 , indent $ paras (line (showQualified showIdent d ++ " (chosen)") : map (line . showQualified showIdent) ds)
580558 ]
581− goSimple OverlappingInstances{} = error "OverlappingInstances: empty instance list"
582− goSimple (NoInstanceFound nm ts) =
559+ renderSimpleErrorMessage OverlappingInstances{} = error "OverlappingInstances: empty instance list"
560+ renderSimpleErrorMessage (NoInstanceFound nm ts) =
583561 paras [ line "No instance found for"
584562 , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
585563 , Box.vcat Box.left (map typeAtomAsBox ts)
586564 ]
587565 ]
588− goSimple (PossiblyInfiniteInstance nm ts) =
566+ renderSimpleErrorMessage (PossiblyInfiniteInstance nm ts) =
589567 paras [ line "Instance for"
590568 , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
591569 , Box.vcat Box.left (map typeAtomAsBox ts)
592570 ]
593571 , line "is possibly infinite."
594572 ]
595− goSimple (CannotDerive nm ts) =
573+ renderSimpleErrorMessage (CannotDerive nm ts) =
596574 paras [ line "Cannot derive an instance for"
597575 , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
598576 , Box.vcat Box.left (map typeAtomAsBox ts)
599577 ]
600578 ]
601− goSimple (CannotFindDerivingType nm) =
579+ renderSimpleErrorMessage (CannotFindDerivingType nm) =
602580 line $ "Cannot derive instance, because the type declaration for " ++ runProperName nm ++ " could not be found."
603− goSimple (DuplicateLabel l expr) =
581+ renderSimpleErrorMessage (DuplicateLabel l expr) =
604582 paras $ [ line $ "Duplicate label " ++ show l ++ " in row." ]
605583 <> foldMap (\expr' -> [ line "Relevant expression: "
606584 , indent $ prettyPrintValue expr'
607585 ]) expr
608− goSimple (DuplicateTypeArgument name) =
586+ renderSimpleErrorMessage (DuplicateTypeArgument name) =
609587 line $ "Duplicate type argument " ++ show name
610− goSimple (DuplicateValueDeclaration nm) =
588+ renderSimpleErrorMessage (DuplicateValueDeclaration nm) =
611589 line $ "Duplicate value declaration for " ++ showIdent nm
612− goSimple (ArgListLengthsDiffer ident) =
590+ renderSimpleErrorMessage (ArgListLengthsDiffer ident) =
613591 line $ "Argument list lengths differ in declaration " ++ showIdent ident
614− goSimple (OverlappingArgNames ident) =
592+ renderSimpleErrorMessage (OverlappingArgNames ident) =
615593 line $ "Overlapping names in function/binder" ++ foldMap ((" in declaration" ++) . showIdent) ident
616− goSimple (MissingClassMember ident) =
594+ renderSimpleErrorMessage (MissingClassMember ident) =
617595 line $ "Member " ++ showIdent ident ++ " has not been implemented"
618− goSimple (ExtraneousClassMember ident) =
596+ renderSimpleErrorMessage (ExtraneousClassMember ident) =
619597 line $ "Member " ++ showIdent ident ++ " is not a member of the class being instantiated"
620− goSimple (ExpectedType ty kind) =
598+ renderSimpleErrorMessage (ExpectedType ty kind) =
621599 paras [ line "In a type-annotated expression x :: t, the type t must have kind *."
622600 , line "The error arises from the type"
623601 , indent $ typeAsBox ty
@@ -625,29 +603,29 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage <$> onTypesInError
625603 , indent $ kindAsBox kind
626604 , line "instead."
627605 ]
628− goSimple (IncorrectConstructorArity nm) =
606+ renderSimpleErrorMessage (IncorrectConstructorArity nm) =
629607 line $ "Wrong number of arguments to constructor " ++ showQualified runProperName nm
630− goSimple SubsumptionCheckFailed = line "Unable to check type subsumption"
631− goSimple (ExprDoesNotHaveType expr ty) =
608+ renderSimpleErrorMessage SubsumptionCheckFailed = line "Unable to check type subsumption"
609+ renderSimpleErrorMessage (ExprDoesNotHaveType expr ty) =
632610 paras [ line "Expression"
633611 , indent $ prettyPrintValue expr
634612 , line "does not have type"
635613 , indent $ typeAsBox ty
636614 ]
637− goSimple (PropertyIsMissing prop row) =
615+ renderSimpleErrorMessage (PropertyIsMissing prop row) =
638616 paras [ line "Row"
639617 , indent $ prettyPrintRowWith '(' ')' row
640618 , line $ "lacks required property " ++ show prop
641619 ]
642− goSimple (CannotApplyFunction fn arg) =
620+ renderSimpleErrorMessage (CannotApplyFunction fn arg) =
643621 paras [ line "Cannot apply function of type"
644622 , indent $ typeAsBox fn
645623 , line "to argument"
646624 , indent $ prettyPrintValue arg
647625 ]
648− goSimple TypeSynonymInstance =
626+ renderSimpleErrorMessage TypeSynonymInstance =
649627 line "Type synonym instances are disallowed"
650− goSimple (OrphanInstance nm cnm ts) =
628+ renderSimpleErrorMessage (OrphanInstance nm cnm ts) =
651629 paras [ line $ "Instance " ++ showIdent nm ++ " for "
652630 , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName cnm)
653631 , Box.vcat Box.left (map typeAtomAsBox ts)
@@ -656,146 +634,124 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage <$> onTypesInError
656634 , line "An orphan instance is an instance which is defined in neither the class module nor the data type module."
657635 , line "Consider moving the instance, if possible, or using a newtype wrapper."
658636 ]
659− goSimple InvalidNewtype =
637+ renderSimpleErrorMessage InvalidNewtype =
660638 line "Newtypes must define a single constructor with a single argument"
661− goSimple (InvalidInstanceHead ty) =
639+ renderSimpleErrorMessage (InvalidInstanceHead ty) =
662640 paras [ line "Invalid type in class instance head:"
663641 , indent $ typeAsBox ty
664642 ]
665− goSimple (TransitiveExportError x ys) =
643+ renderSimpleErrorMessage (TransitiveExportError x ys) =
666644 paras $ line ("An export for " ++ prettyPrintExport x ++ " requires the following to also be exported: ")
667645 : map (line . prettyPrintExport) ys
668− goSimple (ShadowedName nm) =
646+ renderSimpleErrorMessage (ShadowedName nm) =
669647 line $ "Name '" ++ showIdent nm ++ "' was shadowed"
670− goSimple (ShadowedTypeVar tv) =
648+ renderSimpleErrorMessage (ShadowedTypeVar tv) =
671649 line $ "Type variable '" ++ tv ++ "' was shadowed"
672− goSimple (UnusedTypeVar tv) =
650+ renderSimpleErrorMessage (UnusedTypeVar tv) =
673651 line $ "Type variable '" ++ tv ++ "' was declared but not used"
674− goSimple (ClassOperator className opName) =
652+ renderSimpleErrorMessage (ClassOperator className opName) =
675653 paras [ line $ "Class '" ++ runProperName className ++ "' declares operator " ++ showIdent opName ++ "."
676654 , line "This may be disallowed in the future - consider declaring a named member in the class and making the operator an alias:"
677655 , indent . line $ showIdent opName ++ " = someMember"
678656 ]
679− goSimple (MisleadingEmptyTypeImport mn name) =
657+ renderSimpleErrorMessage (MisleadingEmptyTypeImport mn name) =
680658 line $ "Importing type " ++ runProperName name ++ "(..) from " ++ runModuleName mn ++ " is misleading as it has no exported data constructors"
681− goSimple (ImportHidingModule name) =
659+ renderSimpleErrorMessage (ImportHidingModule name) =
682660 line $ "Attempted to hide module " ++ runModuleName name ++ " in import expression, this is not permitted"
683− goSimple (WildcardInferredType ty) =
661+ renderSimpleErrorMessage (WildcardInferredType ty) =
684662 paras [ line "The wildcard type definition has the inferred type "
685663 , indent $ typeAsBox ty
686664 ]
687− goSimple (NotExhaustivePattern bs b) =
665+ renderSimpleErrorMessage (MissingTypeDeclaration ident) =
666+ paras [ line $ "No type declaration was provided for the top-level declaration of " ++ showIdent ident ++ "."
667+ , line "It is good practice to provide type declarations as a form of documentation."
668+ , line "Consider using a type wildcard to display the inferred type:"
669+ , indent $ line $ showIdent ident ++ " :: _"
670+ ]
671+ renderSimpleErrorMessage (NotExhaustivePattern bs b) =
688672 paras $ [ line "A case expression could not be determined to cover all inputs."
689673 , line "The following additional cases are required to cover all inputs:\n"
690674 , Box.hsep 1 Box.left (map (paras . map (line . prettyPrintBinderAtom)) (transpose bs))
691675 ] ++
692676 [ line "..." | not b ]
693− goSimple (OverlappingPattern bs b) =
677+ renderSimpleErrorMessage (OverlappingPattern bs b) =
694678 paras $ [ line "A case expression contains unreachable cases:\n"
695679 , Box.hsep 1 Box.left (map (paras . map (line . prettyPrintBinderAtom)) (transpose bs))
696680 ] ++
697681 [ line "..." | not b ]
698− goSimple IncompleteExhaustivityCheck =
682+ renderSimpleErrorMessage IncompleteExhaustivityCheck =
699683 paras [ line "An exhaustivity check was abandoned due to too many possible cases."
700684 , line "You may want to decomposing your data types into smaller types."
701685 ]
702− go (NotYetDefined names err) =
703− paras [ line $ "The following are not yet defined here: " ++ intercalate ", " (map showIdent names) ++ ":"
704− , go err
705− ]
706− go (ErrorUnifyingTypes t1 t2 err) =
686+
687+ renderHint :: ErrorMessageHint -> Box.Box
688+ renderHint (NotYetDefined names) =
689+ line $ "The following are not yet defined here: " ++ intercalate ", " (map showIdent names) ++ ":"
690+ renderHint (ErrorUnifyingTypes t1 t2) =
707691 paras [ lineWithLevel "unifying type "
708692 , indent $ typeAsBox t1
709693 , line "with type"
710694 , indent $ typeAsBox t2
711− , go err
712695 ]
713− go (ErrorInExpression expr err) =
696+ renderHint (ErrorInExpression expr) =
714697 paras [ lineWithLevel "in expression:"
715698 , indent $ prettyPrintValue expr
716− , go err
717699 ]
718− go (ErrorInModule mn err) =
700+ renderHint (ErrorInModule mn) =
719701 paras [ lineWithLevel $ "in module " ++ runModuleName mn ++ ":"
720− , go err
721702 ]
722− go (ErrorInSubsumption t1 t2 err) =
703+ renderHint (ErrorInSubsumption t1 t2) =
723704 paras [ lineWithLevel "checking that type "
724705 , indent $ typeAsBox t1
725706 , line "subsumes type"
726707 , indent $ typeAsBox t2
727− , go err
728708 ]
729− go (ErrorInInstance nm ts err) =
709+ renderHint (ErrorInInstance nm ts) =
730710 paras [ lineWithLevel "in type class instance"
731711 , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
732712 , Box.vcat Box.left (map typeAtomAsBox ts)
733713 ]
734− , go err
735714 ]
736− go (ErrorCheckingKind ty err) =
715+ renderHint (ErrorCheckingKind ty) =
737716 paras [ lineWithLevel "checking kind of type "
738717 , indent $ typeAsBox ty
739− , go err
740718 ]
741− go (ErrorInferringType expr err) =
719+ renderHint (ErrorInferringType expr) =
742720 paras [ lineWithLevel "inferring type of value "
743721 , indent $ prettyPrintValue expr
744− , go err
745722 ]
746− go (ErrorCheckingType expr ty err) =
723+ renderHint (ErrorCheckingType expr ty) =
747724 paras [ lineWithLevel "checking that value "
748725 , indent $ prettyPrintValue expr
749726 , line "has type"
750727 , indent $ typeAsBox ty
751− , go err
752728 ]
753− go (ErrorInApplication f t a err) =
729+ renderHint (ErrorInApplication f t a) =
754730 paras [ lineWithLevel "applying function"
755731 , indent $ prettyPrintValue f
756732 , line "of type"
757733 , indent $ typeAsBox t
758734 , line "to argument"
759735 , indent $ prettyPrintValue a
760− , go err
761− ]
762− go (ErrorInDataConstructor nm err) =
763− paras [ lineWithLevel $ "in data constructor " ++ runProperName nm ++ ":"
764− , go err
765736 ]
766− go (ErrorInTypeConstructor nm err) =
767− paras [ lineWithLevel $ "in type constructor " ++ runProperName nm ++ ":"
768− , go err
769− ]
770− go (ErrorInBindingGroup nms err) =
771− paras [ lineWithLevel $ "in binding group " ++ intercalate ", " (map showIdent nms) ++ ":"
772− , go err
773− ]
774− go (ErrorInDataBindingGroup err) =
775− paras [ lineWithLevel "in data binding group:"
776− , go err
777− ]
778− go (ErrorInTypeSynonym name err) =
779− paras [ lineWithLevel $ "in type synonym " ++ runProperName name ++ ":"
780− , go err
781− ]
782− go (ErrorInValueDeclaration n err) =
783− paras [ lineWithLevel $ "in value declaration " ++ showIdent n ++ ":"
784− , go err
785− ]
786− go (ErrorInTypeDeclaration n err) =
787− paras [ lineWithLevel $ "in type declaration for " ++ showIdent n ++ ":"
788− , go err
789− ]
790− go (ErrorInForeignImport nm err) =
791− paras [ lineWithLevel $ "in foreign import " ++ showIdent nm ++ ":"
792− , go err
793− ]
794− go (PositionedError srcSpan err) =
795− paras [ lineWithLevel $ "at " ++ displaySourceSpan srcSpan ++ ":"
796− , go err
797− ]
798− go (SimpleErrorWrapper sem) = goSimple sem
737+ renderHint (ErrorInDataConstructor nm) =
738+ lineWithLevel $ "in data constructor " ++ runProperName nm ++ ":"
739+ renderHint (ErrorInTypeConstructor nm) =
740+ lineWithLevel $ "in type constructor " ++ runProperName nm ++ ":"
741+ renderHint (ErrorInBindingGroup nms) =
742+ lineWithLevel $ "in binding group " ++ intercalate ", " (map showIdent nms) ++ ":"
743+ renderHint ErrorInDataBindingGroup =
744+ lineWithLevel "in data binding group:"
745+ renderHint (ErrorInTypeSynonym name) =
746+ lineWithLevel $ "in type synonym " ++ runProperName name ++ ":"
747+ renderHint (ErrorInValueDeclaration n) =
748+ lineWithLevel $ "in value declaration " ++ showIdent n ++ ":"
749+ renderHint (ErrorInTypeDeclaration n) =
750+ lineWithLevel $ "in type declaration for " ++ showIdent n ++ ":"
751+ renderHint (ErrorInForeignImport nm) =
752+ lineWithLevel $ "in foreign import " ++ showIdent nm ++ ":"
753+ renderHint (PositionedError srcSpan) =
754+ lineWithLevel $ "at " ++ displaySourceSpan srcSpan ++ ":"
799755
800756 lineWithLevel :: String -> Box.Box
801757 lineWithLevel text = line $ show level ++ " " ++ text
@@ -805,23 +761,19 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage <$> onTypesInError
805761 Error -> "error"
806762 Warning -> "warning"
807763
808− suggestions :: ErrorMessage -> [Box.Box]
809− suggestions = suggestions' . unwrapErrorMessage
810− where
811− suggestions' (ConflictingImport nm im) = [ line $ "Possible fix: hide " ++ show nm ++ " when importing " ++ runModuleName im ++ ":"
764+ suggestions :: SimpleErrorMessage -> [Box.Box]
765+ suggestions (ConflictingImport nm im) = [ line $ "Possible fix: hide " ++ show nm ++ " when importing " ++ runModuleName im ++ ":"
812766 , indent . line $ "import " ++ runModuleName im ++ " hiding (" ++ nm ++ ")"
813767 ]
814− suggestions' (TypesDoNotUnify t1 t2)
815− | isObject t1 && isFunction t2 = [line "Note that function composition in PureScript is defined using (<<<)"]
816− | otherwise = []
817− suggestions' _ = []
768+ suggestions (TypesDoNotUnify t1 t2)
769+ | isObject t1 && isFunction t2 = [line "Note that function composition in PureScript is defined using (<<<)"]
770+ | otherwise = []
771+ suggestions _ = []
818772
819773 paras :: [Box.Box] -> Box.Box
820774 paras = Box.vcat Box.left
821775
822− -- |
823776 -- Pretty print and export declaration
824− --
825777 prettyPrintExport :: DeclarationRef -> String
826778 prettyPrintExport (TypeRef pn _) = runProperName pn
827779 prettyPrintExport (ValueRef ident) = showIdent ident
@@ -830,38 +782,44 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage <$> onTypesInError
830782 prettyPrintExport (ModuleRef name) = "module " ++ runModuleName name
831783 prettyPrintExport (PositionedDeclarationRef _ _ ref) = prettyPrintExport ref
832784
833− -- |
834− -- Simplify an error message
835− --
836− simplifyErrorMessage :: ErrorMessage -> ErrorMessage
837− simplifyErrorMessage = unwrap Nothing
785+ -- Hints get added at the front, so we need to reverse them before rendering
786+ reverseHints :: ErrorMessage -> ErrorMessage
787+ reverseHints (ErrorMessage hints simple) = ErrorMessage (reverse hints) simple
788+
789+ -- | Put positional hints at the front of the list
790+ positionHintsFirst :: ErrorMessage -> ErrorMessage
791+ positionHintsFirst (ErrorMessage hints simple) = ErrorMessage (uncurry (++) $ partition (isPositionHint . hintCategory) hints) simple
838792 where
839− unwrap :: Maybe SourceSpan -> ErrorMessage -> ErrorMessage
840− unwrap pos (ErrorInExpression _ err) = unwrap pos err
841− unwrap pos (ErrorInInstance name ts err) = ErrorInInstance name ts (unwrap pos err)
842− unwrap pos (ErrorInSubsumption t1 t2 err) = ErrorInSubsumption t1 t2 (unwrap pos err)
843− unwrap pos (ErrorUnifyingTypes _ _ err) = unwrap pos err
844− unwrap pos (ErrorInferringType _ err) = unwrap pos err
845− unwrap pos (ErrorCheckingType _ _ err) = unwrap pos err
846− unwrap pos (ErrorCheckingKind ty err) = ErrorCheckingKind ty (unwrap pos err)
847− unwrap pos (ErrorInModule mn err) = ErrorInModule mn (unwrap pos err)
848− unwrap pos (ErrorInApplication _ _ _ err) = unwrap pos err
849− unwrap pos (ErrorInDataConstructor nm err) = ErrorInDataConstructor nm (unwrap pos err)
850− unwrap pos (ErrorInTypeConstructor nm err) = ErrorInTypeConstructor nm (unwrap pos err)
851− unwrap pos (ErrorInBindingGroup nms err) = ErrorInBindingGroup nms (unwrap pos err)
852− unwrap pos (ErrorInDataBindingGroup err) = ErrorInDataBindingGroup (unwrap pos err)
853− unwrap pos (ErrorInTypeSynonym nm err) = ErrorInTypeSynonym nm (unwrap pos err)
854− unwrap pos (ErrorInValueDeclaration nm err) = ErrorInValueDeclaration nm (unwrap pos err)
855− unwrap pos (ErrorInTypeDeclaration nm err) = ErrorInTypeDeclaration nm (unwrap pos err)
856− unwrap pos (ErrorInForeignImport nm err) = ErrorInForeignImport nm (unwrap pos err)
857− unwrap pos (NotYetDefined ns err) = NotYetDefined ns (unwrap pos err)
858− unwrap _ (PositionedError pos err) = unwrap (Just pos) err
859− unwrap pos other = wrap pos other
860−
861− wrap :: Maybe SourceSpan -> ErrorMessage -> ErrorMessage
862− wrap Nothing = id
863− wrap (Just pos) = PositionedError pos
793+ isPositionHint :: HintCategory -> Bool
794+ isPositionHint PositionHint = True
795+ isPositionHint OtherHint = True
796+ isPositionHint _ = False
864797
798+ -- | Simplify an error message
799+ simplifyErrorMessage :: ErrorMessage -> ErrorMessage
800+ simplifyErrorMessage (ErrorMessage hints simple) = ErrorMessage (simplifyHints hints) simple
801+ where
802+ -- Take the last instance of each "hint category"
803+ simplifyHints :: [ErrorMessageHint] -> [ErrorMessageHint]
804+ simplifyHints = reverse . nubBy categoriesEqual . reverse
805+
806+ -- Don't remove hints in the "other" category
807+ categoriesEqual :: ErrorMessageHint -> ErrorMessageHint -> Bool
808+ categoriesEqual x y =
809+ case (hintCategory x, hintCategory y) of
810+ (OtherHint, _) -> False
811+ (_, OtherHint) -> False
812+ (c1, c2) -> c1 == c2
813+
814+ hintCategory :: ErrorMessageHint -> HintCategory
815+ hintCategory ErrorCheckingType{} = ExprHint
816+ hintCategory ErrorInferringType{} = ExprHint
817+ hintCategory ErrorInExpression{} = ExprHint
818+ hintCategory ErrorUnifyingTypes{} = CheckHint
819+ hintCategory ErrorInSubsumption{} = CheckHint
820+ hintCategory ErrorInApplication{} = CheckHint
821+ hintCategory PositionedError{} = PositionHint
822+ hintCategory _ = OtherHint
865823
866824-- |
867825-- Pretty print multiple errors
@@ -988,8 +946,7 @@ warnAndRethrowWithPosition :: (MonadError MultipleErrors m, MonadWriter Multiple
988946warnAndRethrowWithPosition pos = rethrowWithPosition pos . warnWithPosition pos
989947
990948withPosition :: SourceSpan -> ErrorMessage -> ErrorMessage
991−withPosition _ (PositionedError pos err) = withPosition pos err
992−withPosition pos err = PositionedError pos err
949+withPosition pos (ErrorMessage hints se) = ErrorMessage (PositionedError pos : hints) se
993950
994951-- |
995952-- Collect errors in in parallel
src/Language/PureScript/Linter.hs+4−4
@@ -40,7 +40,7 @@ import Language.PureScript.Linter.Exhaustive as L
4040-- |
4141-- | Right now, this pass only performs a shadowing check.
4242lint :: forall m. (Applicative m, MonadWriter MultipleErrors m) => Module -> m ()
43−lint (Module _ _ mn ds _) = censor (onErrorMessages (ErrorInModule mn)) $ mapM_ lintDeclaration ds
43+lint (Module _ _ mn ds _) = censor (addHint (ErrorInModule mn)) $ mapM_ lintDeclaration ds
4444 where
4545 moduleNames :: S.Set Ident
4646 moduleNames = S.fromList (nub (mapMaybe getDeclIdent ds))
@@ -58,9 +58,9 @@ lint (Module _ _ mn ds _) = censor (onErrorMessages (ErrorInModule mn)) $ mapM_
5858 let (f, _, _, _, _) = everythingWithContextOnValues moduleNames mempty mappend stepD stepE stepB def def
5959
6060 f' :: Declaration -> MultipleErrors
61− f' (PositionedDeclaration pos _ dec) = onErrorMessages (PositionedError pos) (f' dec)
62− f' dec@(ValueDeclaration name _ _ _) = onErrorMessages (ErrorInValueDeclaration name) (f dec <> checkTypeVarsInDecl dec)
63− f' (TypeDeclaration name ty) = onErrorMessages (ErrorInTypeDeclaration name) (checkTypeVars ty)
61+ f' (PositionedDeclaration pos _ dec) = addHint (PositionedError pos) (f' dec)
62+ f' dec@(ValueDeclaration name _ _ _) = addHint (ErrorInValueDeclaration name) (f dec <> checkTypeVarsInDecl dec)
63+ f' (TypeDeclaration name ty) = addHint (ErrorInTypeDeclaration name) (checkTypeVars ty)
6464 f' dec = f dec <> checkTypeVarsInDecl dec
6565
6666 in tell (f' d)
src/Language/PureScript/Linter/Exhaustive.hs+29−20
@@ -46,8 +46,6 @@ import Language.PureScript.Kinds
4646import Language.PureScript.Types as P
4747import Language.PureScript.Errors
4848
49−import Language.PureScript.AST.Traversals (everywhereOnValuesTopDownM)
50−
5149-- | There are two modes of failure for the redudancy check:
5250--
5351-- 1. Exhaustivity was incomeplete due to too many cases, so we couldn't determine redundancy.
@@ -273,28 +271,39 @@ checkExhaustive env mn numArgs cas = makeResult . first nub $ foldl' step ([init
273271-- Exhaustivity checking over a list of declarations
274272--
275273checkExhaustiveDecls :: forall m. (Applicative m, MonadWriter MultipleErrors m) => Environment -> ModuleName -> [Declaration] -> m ()
276−checkExhaustiveDecls env mn ds =
277− let (f, _, _) = everywhereOnValuesTopDownM return checkExpr return
274+checkExhaustiveDecls env mn = mapM_ onDecl
275+ where
276+ onDecl :: Declaration -> m ()
277+ onDecl (BindingGroupDeclaration bs) = mapM_ (onDecl . convert) bs
278+ where
279+ convert :: (Ident, NameKind, Expr) -> Declaration
280+ convert (name, nk, e) = ValueDeclaration name nk [] (Right e)
281+ onDecl (ValueDeclaration name _ _ (Right e)) = censor (addHint (ErrorInValueDeclaration name)) (onExpr e)
282+ onDecl (PositionedDeclaration pos _ dec) = censor (addHint (PositionedError pos)) (onDecl dec)
283+ onDecl _ = return ()
278284
279− f' :: Declaration -> m Declaration
280− f' d@(BindingGroupDeclaration bs) = mapM_ (f' . convert) bs >> return d
281− where
282− convert :: (Ident, NameKind, Expr) -> Declaration
283− convert (name, nk, e) = ValueDeclaration name nk [] (Right e)
284− f' d@(ValueDeclaration name _ _ _) = censor (onErrorMessages (ErrorInValueDeclaration name)) $ f d
285− f' (PositionedDeclaration pos com dec) = PositionedDeclaration pos com <$> censor (onErrorMessages (PositionedError pos)) (f' dec)
286− -- Don't generate two warnings for desugared dictionaries.
287− f' d@TypeInstanceDeclaration{} = return d
288− f' d = f d
285+ onExpr :: Expr -> m ()
286+ onExpr (UnaryMinus e) = onExpr e
287+ onExpr (ArrayLiteral es) = mapM_ onExpr es
288+ onExpr (ObjectLiteral es) = mapM_ (onExpr . snd) es
289+ onExpr (TypeClassDictionaryConstructorApp _ e) = onExpr e
290+ onExpr (Accessor _ e) = onExpr e
291+ onExpr (ObjectUpdate o es) = onExpr o >> mapM_ (onExpr . snd) es
292+ onExpr (Abs _ e) = onExpr e
293+ onExpr (App e1 e2) = onExpr e1 >> onExpr e2
294+ onExpr (IfThenElse e1 e2 e3) = onExpr e1 >> onExpr e2 >> onExpr e3
295+ onExpr (Case es cas) = checkExhaustive env mn (length es) cas >> mapM_ onExpr es >> mapM_ onCaseAlternative cas
296+ onExpr (TypedValue _ e _) = onExpr e
297+ onExpr (Let ds e) = mapM_ onDecl ds >> onExpr e
298+ onExpr (PositionedValue pos _ e) = censor (addHint (PositionedError pos)) (onExpr e)
299+ onExpr _ = return ()
289300
290− in mapM_ f' ds
291− where
292− checkExpr :: Expr -> m Expr
293− checkExpr c@(Case expr cas) = checkExhaustive env mn (length expr) cas >> return c
294− checkExpr other = return other
301+ onCaseAlternative :: CaseAlternative -> m ()
302+ onCaseAlternative (CaseAlternative _ (Left es)) = mapM_ (\(e, g) -> onExpr e >> onExpr g) es
303+ onCaseAlternative (CaseAlternative _ (Right e)) = onExpr e
295304
296305-- |
297306-- Exhaustivity checking over a single module
298307--
299308checkExhaustiveModule :: forall m. (Applicative m, MonadWriter MultipleErrors m) => Environment -> Module -> m ()
300−checkExhaustiveModule env (Module _ _ mn ds _) = censor (onErrorMessages (ErrorInModule mn)) $ checkExhaustiveDecls env mn ds
309+checkExhaustiveModule env (Module _ _ mn ds _) = censor (addHint (ErrorInModule mn)) $ checkExhaustiveDecls env mn ds
src/Language/PureScript/Make.hs+3−3
@@ -305,15 +305,15 @@ buildMakeActions outputDir filePathMap foreigns usePrefix =
305305 requiresForeign = not . null . CF.moduleForeign
306306
307307 getTimestamp :: FilePath -> Make (Maybe UTCTime)
308− getTimestamp path = makeIO (const (SimpleErrorWrapper $ CannotGetFileInfo path)) $ do
308+ getTimestamp path = makeIO (const (ErrorMessage [] $ CannotGetFileInfo path)) $ do
309309 exists <- doesFileExist path
310310 traverse (const $ getModificationTime path) $ guard exists
311311
312312 readTextFile :: FilePath -> Make B.ByteString
313− readTextFile path = makeIO (const (SimpleErrorWrapper $ CannotReadFile path)) $ B.readFile path
313+ readTextFile path = makeIO (const (ErrorMessage [] $ CannotReadFile path)) $ B.readFile path
314314
315315 writeTextFile :: FilePath -> B.ByteString -> Make ()
316− writeTextFile path text = makeIO (const (SimpleErrorWrapper $ CannotWriteFile path)) $ do
316+ writeTextFile path text = makeIO (const (ErrorMessage [] $ CannotWriteFile path)) $ do
317317 mkdirp path
318318 B.writeFile path text
319319 where
src/Language/PureScript/Parser/Declarations.hs+1−1
@@ -293,7 +293,7 @@ parseModulesFromFiles toFilePath input = do
293293 collect vss = [ (k, v) | (k, vs) <- vss, v <- vs ]
294294
295295toPositionedError :: P.ParseError -> ErrorMessage
296−toPositionedError perr = PositionedError (SourceSpan name start end) (SimpleErrorWrapper (ErrorParsingModule perr))
296+toPositionedError perr = ErrorMessage [ PositionedError (SourceSpan name start end) ] (ErrorParsingModule perr)
297297 where
298298 name = (P.sourceName . P.errorPos) perr
299299 start = (toSourcePos . P.errorPos) perr
src/Language/PureScript/Pretty/Values.hs+2−1
@@ -70,6 +70,7 @@ prettyPrintValue (Do els) =
7070 text "do " <> vcat left (map prettyPrintDoNotationElement els)
7171prettyPrintValue (TypeClassDictionary (name, tys) _) = foldl1 beforeWithSpace $ text ("#dict " ++ runProperName (disqualify name)) : map typeAtomAsBox tys
7272prettyPrintValue (SuperClassDictionary name _) = text $ "#dict " ++ runProperName (disqualify name)
73+prettyPrintValue (TypedValue _ val _) = prettyPrintValue val
7374prettyPrintValue (PositionedValue _ _ val) = prettyPrintValue val
7475prettyPrintValue expr = prettyPrintValueAtom expr
7576
@@ -88,7 +89,7 @@ prettyPrintValueAtom (Constructor name) = text $ runProperName (disqualify name)
8889prettyPrintValueAtom (Var ident) = text $ showIdent (disqualify ident)
8990prettyPrintValueAtom (OperatorSection op (Right val)) = ((text "(" <> prettyPrintValue op) `beforeWithSpace` prettyPrintValue val) `before` text ")"
9091prettyPrintValueAtom (OperatorSection op (Left val)) = ((text "(" <> prettyPrintValue val) `beforeWithSpace` prettyPrintValue op) `before` text ")"
91−prettyPrintValueAtom (TypedValue _ val _) = prettyPrintValue val
92+prettyPrintValueAtom (TypedValue _ val _) = prettyPrintValueAtom val
9293prettyPrintValueAtom (PositionedValue _ _ val) = prettyPrintValueAtom val
9394prettyPrintValueAtom expr = (text "(" <> prettyPrintValue expr) `before` text ")"
9495
src/Language/PureScript/Sugar/BindingGroups.hs+1−1
@@ -184,7 +184,7 @@ toBindingGroup moduleName (CyclicSCC ds') =
184184 cycleError :: (MonadError MultipleErrors m) => Declaration -> [Declaration] -> m a
185185 cycleError (PositionedDeclaration p _ d) ds = rethrowWithPosition p $ cycleError d ds
186186 cycleError (ValueDeclaration n _ _ (Right _)) [] = throwError . errorMessage $ CycleInDeclaration n
187− cycleError d ds@(_:_) = rethrow (onErrorMessages (NotYetDefined (map getIdent ds))) $ cycleError d []
187+ cycleError d ds@(_:_) = rethrow (addHint (NotYetDefined (map getIdent ds))) $ cycleError d []
188188 cycleError _ _ = error "Expected ValueDeclaration"
189189
190190toDataBindingGroup :: (MonadError MultipleErrors m) => SCC Declaration -> m Declaration
src/Language/PureScript/Sugar/CaseDeclarations.hs+1−1
@@ -50,7 +50,7 @@ isLeft (Right _) = False
5050--
5151desugarCasesModule :: (Functor m, Applicative m, MonadSupply m, MonadError MultipleErrors m) => [Module] -> m [Module]
5252desugarCasesModule ms = forM ms $ \(Module ss coms name ds exps) ->
53− rethrow (onErrorMessages (ErrorInModule name)) $
53+ rethrow (addHint (ErrorInModule name)) $
5454 Module ss coms name <$> (desugarCases <=< desugarAbs $ ds) <*> pure exps
5555
5656desugarAbs :: (Functor m, Applicative m, MonadSupply m, MonadError MultipleErrors m) => [Declaration] -> m [Declaration]
src/Language/PureScript/Sugar/Names.hs+1−1
@@ -98,7 +98,7 @@ desugarImports externs modules = do
9898
9999 renameInModule' :: Env -> Module -> m Module
100100 renameInModule' env m@(Module _ _ mn _ _) =
101− rethrow (onErrorMessages (ErrorInModule mn)) $ do
101+ rethrow (addHint (ErrorInModule mn)) $ do
102102 let (_, imps, exps) = fromMaybe (error "Module is missing in renameInModule'") $ M.lookup mn env
103103 elaborateImports imps <$> renameInModule env imps (elaborateExports exps m)
104104
src/Language/PureScript/Sugar/Names/Exports.hs+2−2
@@ -43,7 +43,7 @@ import Language.PureScript.Sugar.Names.Env
4343--
4444findExportable :: forall m. (Applicative m, MonadError MultipleErrors m) => Module -> m Exports
4545findExportable (Module _ _ mn ds _) =
46− rethrow (onErrorMessages (ErrorInModule mn)) $ foldM updateExports nullExports ds
46+ rethrow (addHint (ErrorInModule mn)) $ foldM updateExports nullExports ds
4747 where
4848 updateExports :: Exports -> Declaration -> m Exports
4949 updateExports exps (TypeClassDeclaration tcn _ _ ds') = do
@@ -67,7 +67,7 @@ findExportable (Module _ _ mn ds _) =
6767--
6868resolveExports :: forall m. (Applicative m, MonadError MultipleErrors m) => Env -> ModuleName -> Imports -> Exports -> [DeclarationRef] -> m Exports
6969resolveExports env mn imps exps refs =
70− rethrow (onErrorMessages (ErrorInModule mn)) $ do
70+ rethrow (addHint (ErrorInModule mn)) $ do
7171 filtered <- filterModule mn exps refs
7272 foldM elaborateModuleExports filtered refs
7373
src/Language/PureScript/Sugar/Names/Imports.hs+1−1
@@ -64,7 +64,7 @@ findImports = foldM (go Nothing) M.empty
6464--
6565resolveImports :: (Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) => Env -> Module -> m Imports
6666resolveImports env (Module _ _ currentModule decls _) =
67− censor (onErrorMessages (ErrorInModule currentModule)) $ do
67+ censor (addHint (ErrorInModule currentModule)) $ do
6868 scope <- M.insert currentModule [(Nothing, Implicit, Nothing)] <$> findImports decls
6969 foldM (resolveModuleImport currentModule env) nullImports (M.toList scope)
7070
src/Language/PureScript/Sugar/Operators.hs+1−1
@@ -102,7 +102,7 @@ ensureNoDuplicates m = go $ sortBy (compare `on` fst) m
102102 go [] = return ()
103103 go [_] = return ()
104104 go ((x@(Qualified (Just mn) name), _) : (y, pos) : _) | x == y =
105− rethrow (onErrorMessages (ErrorInModule mn)) $
105+ rethrow (addHint (ErrorInModule mn)) $
106106 rethrowWithPosition pos $
107107 throwError . errorMessage $ MultipleFixities name
108108 go (_ : rest) = go rest
src/Language/PureScript/Sugar/TypeClasses.hs+1−1
@@ -243,7 +243,7 @@ unit = TypeApp tyObject REmpty
243243
244244typeInstanceDictionaryDeclaration :: (Functor m, Applicative m, MonadSupply m, MonadError MultipleErrors m) => Ident -> ModuleName -> [Constraint] -> Qualified ProperName -> [Type] -> [Declaration] -> Desugar m Declaration
245245typeInstanceDictionaryDeclaration name mn deps className tys decls =
246− rethrow (onErrorMessages (ErrorInInstance className tys)) $ do
246+ rethrow (addHint (ErrorInInstance className tys)) $ do
247247 m <- get
248248
249249 -- Lookup the type arguments and member types for the type class
src/Language/PureScript/Sugar/TypeDeclarations.hs+37−33
@@ -15,18 +15,19 @@
1515-----------------------------------------------------------------------------
1616
1717{-# LANGUAGE FlexibleContexts #-}
18+{-# LANGUAGE ScopedTypeVariables #-}
1819{-# LANGUAGE CPP #-}
1920
2021module Language.PureScript.Sugar.TypeDeclarations (
21− desugarTypeDeclarations,
2222 desugarTypeDeclarationsModule
2323) where
2424
2525#if __GLASGOW_HASKELL__ < 710
2626import Control.Applicative
2727#endif
28−import Control.Monad (forM)
28+import Control.Monad (forM, when)
2929import Control.Monad.Error.Class (MonadError(..))
30+import Control.Monad.Writer.Class (MonadWriter(tell))
3031
3132import Language.PureScript.AST
3233import Language.PureScript.Names
@@ -37,36 +38,39 @@ import Language.PureScript.Traversals
3738-- |
3839-- Replace all top level type declarations in a module with type annotations
3940--
40−desugarTypeDeclarationsModule :: (Functor m, Applicative m, MonadError MultipleErrors m) => [Module] -> m [Module]
41+desugarTypeDeclarationsModule :: forall m. (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) => [Module] -> m [Module]
4142desugarTypeDeclarationsModule ms = forM ms $ \(Module ss coms name ds exps) ->
42− rethrow (onErrorMessages (ErrorInModule name)) $
43− Module ss coms name <$> desugarTypeDeclarations ds <*> pure exps
44−
45−-- |
46−-- Replace all top level type declarations with type annotations
47−--
48−desugarTypeDeclarations :: (Functor m, Applicative m, MonadError MultipleErrors m) => [Declaration] -> m [Declaration]
49−desugarTypeDeclarations (PositionedDeclaration pos com d : ds) = do
50− (d' : ds') <- rethrowWithPosition pos $ desugarTypeDeclarations (d : ds)
51− return (PositionedDeclaration pos com d' : ds')
52−desugarTypeDeclarations (TypeDeclaration name ty : d : rest) = do
53− (_, nameKind, val) <- fromValueDeclaration d
54− desugarTypeDeclarations (ValueDeclaration name nameKind [] (Right (TypedValue True val ty)) : rest)
43+ rethrow (addHint (ErrorInModule name)) $
44+ Module ss coms name <$> desugarTypeDeclarations True ds <*> pure exps
5545 where
56− fromValueDeclaration :: (Functor m, Applicative m, MonadError MultipleErrors m) => Declaration -> m (Ident, NameKind, Expr)
57− fromValueDeclaration (ValueDeclaration name' nameKind [] (Right val)) | name == name' = return (name', nameKind, val)
58− fromValueDeclaration (PositionedDeclaration pos com d') = do
59− (ident, nameKind, val) <- rethrowWithPosition pos $ fromValueDeclaration d'
60− return (ident, nameKind, PositionedValue pos com val)
61− fromValueDeclaration _ = throwError . errorMessage $ OrphanTypeDeclaration name
62−desugarTypeDeclarations [TypeDeclaration name _] = throwError . errorMessage $ OrphanTypeDeclaration name
63−desugarTypeDeclarations (ValueDeclaration name nameKind bs val : rest) = do
64− let (_, f, _) = everywhereOnValuesTopDownM return go return
65− f' (Left gs) = Left <$> mapM (pairM return f) gs
66− f' (Right v) = Right <$> f v
67− (:) <$> (ValueDeclaration name nameKind bs <$> f' val) <*> desugarTypeDeclarations rest
68− where
69− go (Let ds val') = Let <$> desugarTypeDeclarations ds <*> pure val'
70− go other = return other
71−desugarTypeDeclarations (d:ds) = (:) d <$> desugarTypeDeclarations ds
72−desugarTypeDeclarations [] = return []
46+
47+ desugarTypeDeclarations :: Bool -> [Declaration] -> m [Declaration]
48+ desugarTypeDeclarations reqd (PositionedDeclaration pos com d : ds) = do
49+ (d' : ds') <- rethrowWithPosition pos $ desugarTypeDeclarations reqd (d : ds)
50+ return (PositionedDeclaration pos com d' : ds')
51+ desugarTypeDeclarations reqd (TypeDeclaration name ty : d : rest) = do
52+ (_, nameKind, val) <- fromValueDeclaration d
53+ desugarTypeDeclarations reqd (ValueDeclaration name nameKind [] (Right (TypedValue True val ty)) : rest)
54+ where
55+ fromValueDeclaration :: Declaration -> m (Ident, NameKind, Expr)
56+ fromValueDeclaration (ValueDeclaration name' nameKind [] (Right val)) | name == name' = return (name', nameKind, val)
57+ fromValueDeclaration (PositionedDeclaration pos com d') = do
58+ (ident, nameKind, val) <- rethrowWithPosition pos $ fromValueDeclaration d'
59+ return (ident, nameKind, PositionedValue pos com val)
60+ 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)
68+ let (_, f, _) = everywhereOnValuesTopDownM return go return
69+ f' (Left gs) = Left <$> mapM (pairM return f) gs
70+ f' (Right v) = Right <$> f v
71+ (:) <$> (ValueDeclaration name nameKind bs <$> f' val) <*> desugarTypeDeclarations reqd rest
72+ where
73+ go (Let ds val') = Let <$> desugarTypeDeclarations False ds <*> pure val'
74+ go other = return other
75+ desugarTypeDeclarations reqd (d:ds) = (:) d <$> desugarTypeDeclarations reqd ds
76+ desugarTypeDeclarations _ [] = return []
src/Language/PureScript/TypeChecker.hs+8−8
@@ -51,7 +51,7 @@ addDataType moduleName dtype name args dctors ctorKind = do
5151 env <- getEnv
5252 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (ctorKind, DataType args dctors) (types env) }
5353 forM_ dctors $ \(dctor, tys) ->
54− warnAndRethrow (onErrorMessages (ErrorInDataConstructor dctor)) $
54+ warnAndRethrow (addHint (ErrorInDataConstructor dctor)) $
5555 addDataConstructor moduleName dtype name (map fst args) dctor tys
5656
5757addDataConstructor :: ModuleName -> DataDeclType -> ProperName -> [String] -> ProperName -> [Type] -> Check ()
@@ -137,7 +137,7 @@ typeCheckAll mainModuleName moduleName _ ds = mapM go ds <* mapM_ checkOrphanFix
137137 where
138138 go :: Declaration -> Check Declaration
139139 go (DataDeclaration dtype name args dctors) = do
140− warnAndRethrow (onErrorMessages (ErrorInTypeConstructor name)) $ do
140+ warnAndRethrow (addHint (ErrorInTypeConstructor name)) $ do
141141 when (dtype == Newtype) $ checkNewtype dctors
142142 checkDuplicateTypeArguments $ map fst args
143143 ctorKind <- kindsOf True moduleName name args (concatMap snd dctors)
@@ -150,7 +150,7 @@ typeCheckAll mainModuleName moduleName _ ds = mapM go ds <* mapM_ checkOrphanFix
150150 checkNewtype [(_, _)] = throwError . errorMessage $ InvalidNewtype
151151 checkNewtype _ = throwError . errorMessage $ InvalidNewtype
152152 go (d@(DataBindingGroupDeclaration tys)) = do
153− warnAndRethrow (onErrorMessages ErrorInDataBindingGroup) $ do
153+ warnAndRethrow (addHint ErrorInDataBindingGroup) $ do
154154 let syns = mapMaybe toTypeSynonym tys
155155 let dataDecls = mapMaybe toDataDecl tys
156156 (syn_ks, data_ks) <- kindsOfAll moduleName syns (map (\(_, name, args, dctors) -> (name, args, concatMap snd dctors)) dataDecls)
@@ -171,7 +171,7 @@ typeCheckAll mainModuleName moduleName _ ds = mapM go ds <* mapM_ checkOrphanFix
171171 toDataDecl (PositionedDeclaration _ _ d') = toDataDecl d'
172172 toDataDecl _ = Nothing
173173 go (TypeSynonymDeclaration name args ty) = do
174− warnAndRethrow (onErrorMessages (ErrorInTypeSynonym name)) $ do
174+ warnAndRethrow (addHint (ErrorInTypeSynonym name)) $ do
175175 checkDuplicateTypeArguments $ map fst args
176176 kind <- kindsOf False moduleName name args [ty]
177177 let args' = args `withKinds` kind
@@ -179,14 +179,14 @@ typeCheckAll mainModuleName moduleName _ ds = mapM go ds <* mapM_ checkOrphanFix
179179 return $ TypeSynonymDeclaration name args ty
180180 go (TypeDeclaration{}) = error "Type declarations should have been removed"
181181 go (ValueDeclaration name nameKind [] (Right val)) =
182− warnAndRethrow (onErrorMessages (ErrorInValueDeclaration name)) $ do
182+ warnAndRethrow (addHint (ErrorInValueDeclaration name)) $ do
183183 valueIsNotDefined moduleName name
184184 [(_, (val', ty))] <- typesOf mainModuleName moduleName [(name, val)]
185185 addValue moduleName name ty nameKind
186186 return $ ValueDeclaration name nameKind [] $ Right val'
187187 go (ValueDeclaration{}) = error "Binders were not desugared"
188188 go (BindingGroupDeclaration vals) =
189− warnAndRethrow (onErrorMessages (ErrorInBindingGroup (map (\(ident, _, _) -> ident) vals))) $ do
189+ warnAndRethrow (addHint (ErrorInBindingGroup (map (\(ident, _, _) -> ident) vals))) $ do
190190 forM_ (map (\(ident, _, _) -> ident) vals) $ \name ->
191191 valueIsNotDefined moduleName name
192192 tys <- typesOf mainModuleName moduleName $ map (\(ident, _, ty) -> (ident, ty)) vals
@@ -203,7 +203,7 @@ typeCheckAll mainModuleName moduleName _ ds = mapM go ds <* mapM_ checkOrphanFix
203203 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, ExternData) (types env) }
204204 return d
205205 go (d@(ExternDeclaration name ty)) = do
206− warnAndRethrow (onErrorMessages (ErrorInForeignImport name)) $ do
206+ warnAndRethrow (addHint (ErrorInForeignImport name)) $ do
207207 env <- getEnv
208208 kind <- kindOf moduleName ty
209209 guardWith (errorMessage (ExpectedType ty kind)) $ kind == Star
@@ -269,7 +269,7 @@ typeCheckAll mainModuleName moduleName _ ds = mapM go ds <* mapM_ checkOrphanFix
269269--
270270typeCheckModule :: Maybe ModuleName -> Module -> Check Module
271271typeCheckModule _ (Module _ _ _ _ Nothing) = error "exports should have been elaborated"
272−typeCheckModule mainModuleName (Module ss coms mn decls (Just exps)) = warnAndRethrow (onErrorMessages (ErrorInModule mn)) $ do
272+typeCheckModule mainModuleName (Module ss coms mn decls (Just exps)) = warnAndRethrow (addHint (ErrorInModule mn)) $ do
273273 modify (\s -> s { checkCurrentModule = Just mn })
274274 decls' <- typeCheckAll mainModuleName mn exps decls
275275 forM_ exps $ \e -> do
src/Language/PureScript/TypeChecker/Kinds.hs+2−2
@@ -83,7 +83,7 @@ kindOf _ ty = fst <$> kindOfWithScopedVars ty
8383--
8484kindOfWithScopedVars :: Type -> Check (Kind, [(String, Kind)])
8585kindOfWithScopedVars ty =
86− rethrow (onErrorMessages (ErrorCheckingKind ty)) $
86+ rethrow (addHint (ErrorCheckingKind ty)) $
8787 fmap tidyUp . liftUnify $ infer ty
8888 where
8989 tidyUp ((k, args), sub) = ( starIfUnknown (sub $? k)
@@ -161,7 +161,7 @@ starIfUnknown k = k
161161-- Infer a kind for a type
162162--
163163infer :: Type -> UnifyT Kind Check (Kind, [(String, Kind)])
164−infer ty = rethrow (onErrorMessages (ErrorCheckingKind ty)) $ infer' ty
164+infer ty = rethrow (addHint (ErrorCheckingKind ty)) $ infer' ty
165165
166166infer' :: Type -> UnifyT Kind Check (Kind, [(String, Kind)])
167167infer' (ForAll ident ty _) = do
src/Language/PureScript/TypeChecker/Skolems.hs+1−1
@@ -92,7 +92,7 @@ skolemEscapeCheck root@TypedValue{} =
9292 let (_, f, _, _, _) = everythingWithContextOnValues [] [] (++) def go def def def
9393 in case f root of
9494 [] -> return ()
95− ((binding, val) : _) -> throwError . singleError $ ErrorInExpression val $ SimpleErrorWrapper $ EscapedSkolem binding
95+ ((binding, val) : _) -> throwError . singleError $ ErrorMessage [ ErrorInExpression val ] $ EscapedSkolem binding
9696 where
9797 def s _ = (s, [])
9898
src/Language/PureScript/TypeChecker/Subsumption.hs+1−1
@@ -37,7 +37,7 @@ import Language.PureScript.Types
3737-- Check whether one type subsumes another, rethrowing errors to provide a better error message
3838--
3939subsumes :: Maybe Expr -> Type -> Type -> UnifyT Type Check (Maybe Expr)
40−subsumes val ty1 ty2 = rethrow (onErrorMessages (ErrorInSubsumption ty1 ty2)) $ subsumes' val ty1 ty2
40+subsumes val ty1 ty2 = rethrow (addHint (ErrorInSubsumption ty1 ty2)) $ subsumes' val ty1 ty2
4141
4242-- |
4343-- Check whether one type subsumes another
src/Language/PureScript/TypeChecker/Synonyms.hs+1−1
@@ -50,7 +50,7 @@ buildTypeSubstitution m = go 0 []
5050 where
5151 go :: Int -> [Type] -> Type -> Either ErrorMessage (Maybe Type)
5252 go c args (TypeConstructor ctor) | M.lookup ctor m == Just c = return (Just $ SaturatedTypeSynonym ctor args)
53− go c _ (TypeConstructor ctor) | M.lookup ctor m > Just c = throwError $ SimpleErrorWrapper $ PartiallyAppliedSynonym ctor
53+ go c _ (TypeConstructor ctor) | M.lookup ctor m > Just c = throwError $ ErrorMessage [] $ PartiallyAppliedSynonym ctor
5454 go c args (TypeApp f arg) = go (c + 1) (arg:args) f
5555 go _ _ _ = return Nothing
5656
src/Language/PureScript/TypeChecker/Types.hs+8−28
@@ -103,7 +103,7 @@ typesOf mainModuleName moduleName vals = do
103103 -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
104104 tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
105105 -- Replace all the wildcards types with their inferred types
106− replace sub (SimpleErrorWrapper (WildcardInferredType ty)) = SimpleErrorWrapper $ WildcardInferredType (sub $? ty)
106+ replace sub (ErrorMessage hints (WildcardInferredType ty)) = ErrorMessage hints $ WildcardInferredType (sub $? ty)
107107 replace _ em = em
108108 -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
109109 checkMain nm ty = when (Just moduleName == mainModuleName && nm == Ident C.main) $ do
@@ -214,7 +214,7 @@ instantiatePolyTypeWithUnknowns val ty = return (val, ty)
214214-- Infer a type for a value, rethrowing any error to provide a more useful error message
215215--
216216infer :: Expr -> UnifyT Type Check Expr
217−infer val = rethrow (onErrorMessages (ErrorInferringType val)) $ infer' val
217+infer val = rethrow (addHint (ErrorInferringType val)) $ infer' val
218218
219219-- |
220220-- Infer a type for a value
@@ -246,15 +246,10 @@ infer' (ObjectUpdate o ps) = do
246246 o' <- TypedValue True <$> check o oldTy <*> pure oldTy
247247 return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
248248infer' (Accessor prop val) = do
249− typed@(TypedValue _ _ objTy) <- infer val
250− propTy <- inferProperty objTy prop
251− case propTy of
252− Nothing -> do
253− field <- fresh
254− rest <- fresh
255− _ <- subsumes Nothing objTy (TypeApp tyObject (RCons prop field rest))
256− return $ TypedValue True (Accessor prop typed) field
257− Just ty -> return $ TypedValue True (Accessor prop typed) ty
249+ field <- fresh
250+ rest <- fresh
251+ typed <- check val (TypeApp tyObject (RCons prop field rest))
252+ return $ TypedValue True (Accessor prop typed) field
258253infer' (Abs (Left arg) ret) = do
259254 ty <- fresh
260255 Just moduleName <- checkCurrentModule <$> get
@@ -339,21 +334,6 @@ inferLetBinding seen (PositionedDeclaration pos com d : ds) ret j = warnAndRethr
339334 return (PositionedDeclaration pos com d' : ds', val')
340335inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
341336
342−-- |
343−-- Infer the type of a property inside a record with a given type
344−--
345−inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
346−inferProperty (TypeApp obj row) prop | obj == tyObject = do
347− let (props, _) = rowToList row
348− return $ lookup prop props
349−inferProperty (SaturatedTypeSynonym name args) prop = do
350− replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
351− inferProperty replaced prop
352−inferProperty (ForAll ident ty _) prop = do
353− replaced <- replaceVarWithUnknown ident ty
354− inferProperty replaced prop
355−inferProperty _ _ = return Nothing
356−
357337-- |
358338-- Infer the types of variables brought into scope by a binder
359339--
@@ -457,7 +437,7 @@ checkBinders nvals ret (CaseAlternative binders result : bs) = do
457437-- Check the type of a value, rethrowing errors to provide a better error message
458438--
459439check :: Expr -> Type -> UnifyT Type Check Expr
460−check val ty = rethrow (onErrorMessages (ErrorCheckingType val ty)) $ check' val ty
440+check val ty = rethrow (addHint (ErrorCheckingType val ty)) $ check' val ty
461441
462442-- |
463443-- Check the type of a value
@@ -646,7 +626,7 @@ checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
646626-- Check the type of a function application, rethrowing errors to provide a better error message
647627--
648628checkFunctionApplication :: Expr -> Type -> Expr -> Maybe Type -> UnifyT Type Check (Type, Expr)
649−checkFunctionApplication fn fnTy arg ret = rethrow (onErrorMessages (ErrorInApplication fn fnTy arg)) $ do
629+checkFunctionApplication fn fnTy arg ret = rethrow (addHint (ErrorInApplication fn fnTy arg)) $ do
650630 subst <- unifyCurrentSubstitution <$> UnifyT get
651631 checkFunctionApplication' fn (subst $? fnTy) arg (($?) subst <$> ret)
652632
src/Language/PureScript/TypeChecker/Unify.hs+1−1
@@ -63,7 +63,7 @@ instance Unifiable Check Type where
6363-- Unify two types, updating the current substitution
6464--
6565unifyTypes :: Type -> Type -> UnifyT Type Check ()
66−unifyTypes t1 t2 = rethrow (onErrorMessages (ErrorUnifyingTypes t1 t2)) $
66+unifyTypes t1 t2 = rethrow (addHint (ErrorUnifyingTypes t1 t2)) $
6767 unifyTypes' t1 t2
6868 where
6969 unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()