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

Print type errors using boxes library, #929

commit875896643d48894f6c528d3356a8285b80d15421 authorPhil Freeman <paf31@cantab.net> dateTue 13 Oct 2015, 17:10 (11 years ago) parenteb83102cb63bd4
27 files changed+615−647
.gitignore+1 psci/PSCi.hs+2−2 src/Language/PureScript/Errors.hs+326−332 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/Names.hs+4 src/Language/PureScript/Parser/Declarations.hs+1−1 src/Language/PureScript/Pretty/Common.hs+11 src/Language/PureScript/Pretty/Kinds.hs+19−15 src/Language/PureScript/Pretty/Types.hs+56−35 src/Language/PureScript/Pretty/Values.hs+92−152 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+326−332
@@ -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,394 +364,394 @@ 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: "
430− , indent . prettyPrintParseError $ err
408+ , 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: "
438− , indent . prettyPrintParseError $ err
416+ , 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) =
447− paras $ [ line $ "Multiple FFI implementations have been provided for module " ++ runModuleName mn ++ ": " ]
448− ++ map (indent . line) paths
449− goSimple (InvalidExternsFile path) =
424+ renderSimpleErrorMessage (MultipleFFIModules mn paths) =
425+ paras [ line $ "Multiple FFI implementations have been provided for module " ++ runModuleName mn ++ ": "
426+ , indent . paras $ map line paths
427+ ]
428+ renderSimpleErrorMessage (InvalidExternsFile path) =
450429 paras [ line "Externs file is invalid: "
451430 , indent . line $ path
452431 ]
453− goSimple InvalidDoBind =
432+ renderSimpleErrorMessage InvalidDoBind =
454433 line "Bind statement cannot be the last statement in a do block. The last statement must be an expression."
455− goSimple InvalidDoLet =
434+ renderSimpleErrorMessage InvalidDoLet =
456435 line "Let statement cannot be the last statement in a do block. The last statement must be an expression."
457− goSimple CannotReorderOperators =
436+ renderSimpleErrorMessage CannotReorderOperators =
458437 line "Unable to reorder operators"
459− goSimple UnspecifiedSkolemScope =
438+ renderSimpleErrorMessage UnspecifiedSkolemScope =
460439 line "Skolem variable scope is unspecified"
461− goSimple OverlappingNamesInLet =
440+ renderSimpleErrorMessage OverlappingNamesInLet =
462441 line "Overlapping names in let binding."
463− goSimple (InfiniteType ty) =
442+ renderSimpleErrorMessage (InfiniteType ty) =
464443 paras [ line "An infinite type was inferred for an expression: "
465− , indent $ line $ prettyPrintType ty
444+ , indent $ typeAsBox ty
466445 ]
467− goSimple (InfiniteKind ki) =
446+ renderSimpleErrorMessage (InfiniteKind ki) =
468447 paras [ line "An infinite kind was inferred for a type: "
469− , indent $ line $ prettyPrintKind ki
448+ , indent $ kindAsBox ki
470449 ]
471− goSimple (MultipleFixities name) =
450+ renderSimpleErrorMessage (MultipleFixities name) =
472451 line $ "Multiple fixity declarations for " ++ showIdent name
473− goSimple (OrphanTypeDeclaration nm) =
452+ renderSimpleErrorMessage (OrphanTypeDeclaration nm) =
474453 line $ "Orphan type declaration for " ++ showIdent nm
475− goSimple (OrphanFixityDeclaration op) =
454+ renderSimpleErrorMessage (OrphanFixityDeclaration op) =
476455 line $ "Orphan fixity declaration for " ++ show op
477− goSimple (RedefinedModule name filenames) =
478− paras $ line ("Module " ++ runModuleName name ++ " has been defined multiple times:")
479− : map (indent . line . displaySourceSpan) filenames
480− goSimple (RedefinedIdent name) =
456+ renderSimpleErrorMessage (RedefinedModule name filenames) =
457+ paras [ line ("Module " ++ runModuleName name ++ " has been defined multiple times:")
458+ , indent . paras $ map (line . displaySourceSpan) filenames
459+ ]
460+ renderSimpleErrorMessage (RedefinedIdent name) =
481461 line $ "Name " ++ showIdent name ++ " has been defined multiple times"
482− goSimple (UnknownModule mn) =
462+ renderSimpleErrorMessage (UnknownModule mn) =
483463 line $ "Unknown module " ++ runModuleName mn
484− goSimple (UnknownType name) =
464+ renderSimpleErrorMessage (UnknownType name) =
485465 line $ "Unknown type " ++ showQualified runProperName name
486− goSimple (UnknownTypeClass name) =
466+ renderSimpleErrorMessage (UnknownTypeClass name) =
487467 line $ "Unknown type class " ++ showQualified runProperName name
488− goSimple (UnknownValue name) =
468+ renderSimpleErrorMessage (UnknownValue name) =
489469 line $ "Unknown value " ++ showQualified showIdent name
490− goSimple (UnknownTypeConstructor name) =
470+ renderSimpleErrorMessage (UnknownTypeConstructor name) =
491471 line $ "Unknown type constructor " ++ showQualified runProperName name
492− goSimple (UnknownDataConstructor dc tc) =
472+ renderSimpleErrorMessage (UnknownDataConstructor dc tc) =
493473 line $ "Unknown data constructor " ++ showQualified runProperName dc ++ foldMap ((" for type constructor " ++) . showQualified runProperName) tc
494− goSimple (UnknownImportType mn name) =
474+ renderSimpleErrorMessage (UnknownImportType mn name) =
495475 line $ "Module " ++ runModuleName mn ++ " does not export type " ++ runProperName name
496− goSimple (UnknownExportType name) =
476+ renderSimpleErrorMessage (UnknownExportType name) =
497477 line $ "Cannot export unknown type " ++ runProperName name
498− goSimple (UnknownImportTypeClass mn name) =
478+ renderSimpleErrorMessage (UnknownImportTypeClass mn name) =
499479 line $ "Module " ++ runModuleName mn ++ " does not export type class " ++ runProperName name
500− goSimple (UnknownExportTypeClass name) =
480+ renderSimpleErrorMessage (UnknownExportTypeClass name) =
501481 line $ "Cannot export unknown type class " ++ runProperName name
502− goSimple (UnknownImportValue mn name) =
482+ renderSimpleErrorMessage (UnknownImportValue mn name) =
503483 line $ "Module " ++ runModuleName mn ++ " does not export value " ++ showIdent name
504− goSimple (UnknownExportValue name) =
484+ renderSimpleErrorMessage (UnknownExportValue name) =
505485 line $ "Cannot export unknown value " ++ showIdent name
506− goSimple (UnknownExportModule name) =
486+ renderSimpleErrorMessage (UnknownExportModule name) =
507487 line $ "Cannot export unknown module " ++ runModuleName name ++ ", it either does not exist or has not been imported by the current module"
508− goSimple (UnknownImportDataConstructor mn tcon dcon) =
488+ renderSimpleErrorMessage (UnknownImportDataConstructor mn tcon dcon) =
509489 line $ "Module " ++ runModuleName mn ++ " does not export data constructor " ++ runProperName dcon ++ " for type " ++ runProperName tcon
510− goSimple (UnknownExportDataConstructor tcon dcon) =
490+ renderSimpleErrorMessage (UnknownExportDataConstructor tcon dcon) =
511491 line $ "Cannot export data constructor " ++ runProperName dcon ++ " for type " ++ runProperName tcon ++ " as it has not been declared"
512− goSimple (ConflictingImport nm mn) =
492+ renderSimpleErrorMessage (ConflictingImport nm mn) =
513493 line $ "Cannot declare " ++ show nm ++ " since another declaration of that name was imported from " ++ runModuleName mn
514− goSimple (ConflictingImports nm m1 m2) =
494+ renderSimpleErrorMessage (ConflictingImports nm m1 m2) =
515495 line $ "Conflicting imports for " ++ nm ++ " from modules " ++ runModuleName m1 ++ " and " ++ runModuleName m2
516− goSimple (ConflictingTypeDecls nm) =
496+ renderSimpleErrorMessage (ConflictingTypeDecls nm) =
517497 line $ "Conflicting type declarations for " ++ runProperName nm
518− goSimple (ConflictingCtorDecls nm) =
498+ renderSimpleErrorMessage (ConflictingCtorDecls nm) =
519499 line $ "Conflicting data constructor declarations for " ++ runProperName nm
520− goSimple (TypeConflictsWithClass nm) =
500+ renderSimpleErrorMessage (TypeConflictsWithClass nm) =
521501 line $ "Type " ++ runProperName nm ++ " conflicts with type class declaration of the same name"
522− goSimple (CtorConflictsWithClass nm) =
502+ renderSimpleErrorMessage (CtorConflictsWithClass nm) =
523503 line $ "Data constructor " ++ runProperName nm ++ " conflicts with type class declaration of the same name"
524− goSimple (ClassConflictsWithType nm) =
504+ renderSimpleErrorMessage (ClassConflictsWithType nm) =
525505 line $ "Type class " ++ runProperName nm ++ " conflicts with type declaration of the same name"
526− goSimple (ClassConflictsWithCtor nm) =
506+ renderSimpleErrorMessage (ClassConflictsWithCtor nm) =
527507 line $ "Type class " ++ runProperName nm ++ " conflicts with data constructor declaration of the same name"
528− goSimple (DuplicateClassExport nm) =
508+ renderSimpleErrorMessage (DuplicateClassExport nm) =
529509 line $ "Duplicate export declaration for type class " ++ runProperName nm
530− goSimple (DuplicateValueExport nm) =
510+ renderSimpleErrorMessage (DuplicateValueExport nm) =
531511 line $ "Duplicate export declaration for value " ++ showIdent nm
532− goSimple (CycleInDeclaration nm) =
512+ renderSimpleErrorMessage (CycleInDeclaration nm) =
533513 line $ "Cycle in declaration of " ++ showIdent nm
534− goSimple (CycleInModules mns) =
514+ renderSimpleErrorMessage (CycleInModules mns) =
535515 line $ "Cycle in module dependencies: " ++ intercalate ", " (map runModuleName mns)
536− goSimple (CycleInTypeSynonym pn) =
516+ renderSimpleErrorMessage (CycleInTypeSynonym pn) =
537517 line $ "Cycle in type synonym" ++ foldMap ((" " ++) . runProperName) pn
538− goSimple (NameIsUndefined ident) =
518+ renderSimpleErrorMessage (NameIsUndefined ident) =
539519 line $ showIdent ident ++ " is undefined"
540− goSimple (NameNotInScope ident) =
520+ renderSimpleErrorMessage (NameNotInScope ident) =
541521 line $ showIdent ident ++ " may not be defined in the current scope"
542− goSimple (UndefinedTypeVariable name) =
522+ renderSimpleErrorMessage (UndefinedTypeVariable name) =
543523 line $ "Type variable " ++ runProperName name ++ " is undefined"
544− goSimple (PartiallyAppliedSynonym name) =
524+ renderSimpleErrorMessage (PartiallyAppliedSynonym name) =
545525 paras [ line $ "Partially applied type synonym " ++ showQualified runProperName name
546526 , line "Type synonyms must be applied to all of their type arguments."
547527 ]
548− goSimple (EscapedSkolem binding) =
528+ renderSimpleErrorMessage (EscapedSkolem binding) =
549529 paras $ [ line "A type variable has escaped its scope." ]
550530 <> foldMap (\expr -> [ line "Relevant expression: "
551− , indent $ line $ prettyPrintValue expr
531+ , indent $ prettyPrintValue expr
552532 ]) binding
553− goSimple (TypesDoNotUnify t1 t2)
533+ renderSimpleErrorMessage (TypesDoNotUnify t1 t2)
554534 = paras [ line "Cannot unify type"
555− , indent $ line $ prettyPrintType t1
535+ , indent $ typeAsBox t1
556536 , line "with type"
557− , indent $ line $ prettyPrintType t2
537+ , indent $ typeAsBox t2
558538 ]
559− goSimple (KindsDoNotUnify k1 k2) =
539+ renderSimpleErrorMessage (KindsDoNotUnify k1 k2) =
560540 paras [ line "Cannot unify kind"
561− , indent $ line $ prettyPrintKind k1
541+ , indent $ kindAsBox k1
562542 , line "with kind"
563− , indent $ line $ prettyPrintKind k2
543+ , indent $ kindAsBox k2
564544 ]
565− goSimple (ConstrainedTypeUnified t1 t2) =
545+ renderSimpleErrorMessage (ConstrainedTypeUnified t1 t2) =
566546 paras [ line "Cannot unify constrained type"
567− , indent $ line $ prettyPrintType t1
547+ , indent $ typeAsBox t1
568548 , line "with type"
569− , indent $ line $ prettyPrintType t2
570− ]
571− goSimple (OverlappingInstances nm ts (d : ds)) =
572− paras [ line $ "Overlapping instances found for " ++ showQualified runProperName nm ++ " " ++ unwords (map prettyPrintTypeAtom ts) ++ ":"
549+ , indent $ typeAsBox t2
550+ ]
551+ renderSimpleErrorMessage (OverlappingInstances nm ts (d : ds)) =
552+ paras [ line "Overlapping instances found for"
553+ , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
554+ , Box.vcat Box.left (map typeAtomAsBox ts)
555+ ]
556+ , line "The following instances were found:"
573557 , indent $ paras (line (showQualified showIdent d ++ " (chosen)") : map (line . showQualified showIdent) ds)
574558 ]
575− goSimple OverlappingInstances{} = error "OverlappingInstances: empty instance list"
576− goSimple (NoInstanceFound nm ts) =
577− line $ "No instance found for " ++ showQualified runProperName nm ++ " " ++ unwords (map prettyPrintTypeAtom ts)
578− goSimple (PossiblyInfiniteInstance nm ts) =
579− line $ "Instance for " ++ showQualified runProperName nm ++ " " ++ unwords (map prettyPrintTypeAtom ts) ++ " is possibly infinite."
580− goSimple (CannotDerive nm ts) =
581− line $ "Cannot derive " ++ showQualified runProperName nm ++ " instance for " ++ unwords (map prettyPrintTypeAtom ts)
582− goSimple (CannotFindDerivingType nm) =
559+ renderSimpleErrorMessage OverlappingInstances{} = error "OverlappingInstances: empty instance list"
560+ renderSimpleErrorMessage (NoInstanceFound nm ts) =
561+ paras [ line "No instance found for"
562+ , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
563+ , Box.vcat Box.left (map typeAtomAsBox ts)
564+ ]
565+ ]
566+ renderSimpleErrorMessage (PossiblyInfiniteInstance nm ts) =
567+ paras [ line "Instance for"
568+ , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
569+ , Box.vcat Box.left (map typeAtomAsBox ts)
570+ ]
571+ , line "is possibly infinite."
572+ ]
573+ renderSimpleErrorMessage (CannotDerive nm ts) =
574+ paras [ line "Cannot derive an instance for"
575+ , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
576+ , Box.vcat Box.left (map typeAtomAsBox ts)
577+ ]
578+ ]
579+ renderSimpleErrorMessage (CannotFindDerivingType nm) =
583580 line $ "Cannot derive instance, because the type declaration for " ++ runProperName nm ++ " could not be found."
584− goSimple (DuplicateLabel l expr) =
581+ renderSimpleErrorMessage (DuplicateLabel l expr) =
585582 paras $ [ line $ "Duplicate label " ++ show l ++ " in row." ]
586583 <> foldMap (\expr' -> [ line "Relevant expression: "
587− , indent $ line $ prettyPrintValue expr'
584+ , indent $ prettyPrintValue expr'
588585 ]) expr
589− goSimple (DuplicateTypeArgument name) =
586+ renderSimpleErrorMessage (DuplicateTypeArgument name) =
590587 line $ "Duplicate type argument " ++ show name
591− goSimple (DuplicateValueDeclaration nm) =
588+ renderSimpleErrorMessage (DuplicateValueDeclaration nm) =
592589 line $ "Duplicate value declaration for " ++ showIdent nm
593− goSimple (ArgListLengthsDiffer ident) =
590+ renderSimpleErrorMessage (ArgListLengthsDiffer ident) =
594591 line $ "Argument list lengths differ in declaration " ++ showIdent ident
595− goSimple (OverlappingArgNames ident) =
592+ renderSimpleErrorMessage (OverlappingArgNames ident) =
596593 line $ "Overlapping names in function/binder" ++ foldMap ((" in declaration" ++) . showIdent) ident
597− goSimple (MissingClassMember ident) =
594+ renderSimpleErrorMessage (MissingClassMember ident) =
598595 line $ "Member " ++ showIdent ident ++ " has not been implemented"
599− goSimple (ExtraneousClassMember ident) =
596+ renderSimpleErrorMessage (ExtraneousClassMember ident) =
600597 line $ "Member " ++ showIdent ident ++ " is not a member of the class being instantiated"
601− goSimple (ExpectedType ty kind) =
598+ renderSimpleErrorMessage (ExpectedType ty kind) =
602599 paras [ line "In a type-annotated expression x :: t, the type t must have kind *."
603− , line $ "The error arises from the type " ++ prettyPrintType ty ++ " having the kind " ++ prettyPrintKind kind ++ " instead."
600+ , line "The error arises from the type"
601+ , indent $ typeAsBox ty
602+ , line "having the kind"
603+ , indent $ kindAsBox kind
604+ , line "instead."
604605 ]
605− goSimple (IncorrectConstructorArity nm) =
606+ renderSimpleErrorMessage (IncorrectConstructorArity nm) =
606607 line $ "Wrong number of arguments to constructor " ++ showQualified runProperName nm
607− goSimple SubsumptionCheckFailed = line "Unable to check type subsumption"
608− goSimple (ExprDoesNotHaveType expr ty) =
608+ renderSimpleErrorMessage SubsumptionCheckFailed = line "Unable to check type subsumption"
609+ renderSimpleErrorMessage (ExprDoesNotHaveType expr ty) =
609610 paras [ line "Expression"
610− , indent $ line $ prettyPrintValue expr
611+ , indent $ prettyPrintValue expr
611612 , line "does not have type"
612− , indent $ line $ prettyPrintType ty
613+ , indent $ typeAsBox ty
613614 ]
614− goSimple (PropertyIsMissing prop row) =
615− line $ "Row " ++ prettyPrintRow row ++ " lacks required property " ++ show prop
616− goSimple (CannotApplyFunction fn arg) =
615+ renderSimpleErrorMessage (PropertyIsMissing prop row) =
616+ paras [ line "Row"
617+ , indent $ prettyPrintRowWith '(' ')' row
618+ , line $ "lacks required property " ++ show prop
619+ ]
620+ renderSimpleErrorMessage (CannotApplyFunction fn arg) =
617621 paras [ line "Cannot apply function of type"
618− , indent $ line $ prettyPrintType fn
622+ , indent $ typeAsBox fn
619623 , line "to argument"
620− , indent $ line $ prettyPrintValue arg
624+ , indent $ prettyPrintValue arg
621625 ]
622− goSimple TypeSynonymInstance =
626+ renderSimpleErrorMessage TypeSynonymInstance =
623627 line "Type synonym instances are disallowed"
624− goSimple (OrphanInstance nm cnm ts) =
625− paras [ line $ "Instance " ++ showIdent nm ++ " for " ++ showQualified runProperName cnm ++ " " ++ unwords (map prettyPrintTypeAtom ts) ++ " is an orphan instance."
628+ renderSimpleErrorMessage (OrphanInstance nm cnm ts) =
629+ paras [ line $ "Instance " ++ showIdent nm ++ " for "
630+ , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName cnm)
631+ , Box.vcat Box.left (map typeAtomAsBox ts)
632+ ]
633+ , line "is an orphan instance."
626634 , line "An orphan instance is an instance which is defined in neither the class module nor the data type module."
627635 , line "Consider moving the instance, if possible, or using a newtype wrapper."
628636 ]
629− goSimple InvalidNewtype =
637+ renderSimpleErrorMessage InvalidNewtype =
630638 line "Newtypes must define a single constructor with a single argument"
631− goSimple (InvalidInstanceHead ty) =
639+ renderSimpleErrorMessage (InvalidInstanceHead ty) =
632640 paras [ line "Invalid type in class instance head:"
633− , indent $ line $ prettyPrintType ty
641+ , indent $ typeAsBox ty
634642 ]
635− goSimple (TransitiveExportError x ys) =
643+ renderSimpleErrorMessage (TransitiveExportError x ys) =
636644 paras $ line ("An export for " ++ prettyPrintExport x ++ " requires the following to also be exported: ")
637645 : map (line . prettyPrintExport) ys
638− goSimple (ShadowedName nm) =
646+ renderSimpleErrorMessage (ShadowedName nm) =
639647 line $ "Name '" ++ showIdent nm ++ "' was shadowed"
640− goSimple (ShadowedTypeVar tv) =
648+ renderSimpleErrorMessage (ShadowedTypeVar tv) =
641649 line $ "Type variable '" ++ tv ++ "' was shadowed"
642− goSimple (UnusedTypeVar tv) =
650+ renderSimpleErrorMessage (UnusedTypeVar tv) =
643651 line $ "Type variable '" ++ tv ++ "' was declared but not used"
644− goSimple (ClassOperator className opName) =
652+ renderSimpleErrorMessage (ClassOperator className opName) =
645653 paras [ line $ "Class '" ++ runProperName className ++ "' declares operator " ++ showIdent opName ++ "."
646− , indent $ line "This may be disallowed in the future - consider declaring a named member in the class and making the operator an alias:"
647− , indent $ line $ showIdent opName ++ " = someMember"
654+ , line "This may be disallowed in the future - consider declaring a named member in the class and making the operator an alias:"
655+ , indent . line $ showIdent opName ++ " = someMember"
648656 ]
649− goSimple (MisleadingEmptyTypeImport mn name) =
657+ renderSimpleErrorMessage (MisleadingEmptyTypeImport mn name) =
650658 line $ "Importing type " ++ runProperName name ++ "(..) from " ++ runModuleName mn ++ " is misleading as it has no exported data constructors"
651− goSimple (ImportHidingModule name) =
659+ renderSimpleErrorMessage (ImportHidingModule name) =
652660 line $ "Attempted to hide module " ++ runModuleName name ++ " in import expression, this is not permitted"
653− goSimple (WildcardInferredType ty) =
654− line $ "The wildcard type definition has the inferred type " ++ prettyPrintType ty
655− goSimple (NotExhaustivePattern bs b) =
661+ renderSimpleErrorMessage (WildcardInferredType ty) =
662+ paras [ line "The wildcard type definition has the inferred type "
663+ , indent $ typeAsBox ty
664+ ]
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) =
656672 paras $ [ line "A case expression could not be determined to cover all inputs."
657673 , line "The following additional cases are required to cover all inputs:\n"
658674 , Box.hsep 1 Box.left (map (paras . map (line . prettyPrintBinderAtom)) (transpose bs))
659675 ] ++
660676 [ line "..." | not b ]
661− goSimple (OverlappingPattern bs b) =
677+ renderSimpleErrorMessage (OverlappingPattern bs b) =
662678 paras $ [ line "A case expression contains unreachable cases:\n"
663679 , Box.hsep 1 Box.left (map (paras . map (line . prettyPrintBinderAtom)) (transpose bs))
664680 ] ++
665681 [ line "..." | not b ]
666− goSimple IncompleteExhaustivityCheck =
682+ renderSimpleErrorMessage IncompleteExhaustivityCheck =
667683 paras [ line "An exhaustivity check was abandoned due to too many possible cases."
668684 , line "You may want to decomposing your data types into smaller types."
669685 ]
670− go (NotYetDefined names err) =
671− paras [ line $ "The following are not yet defined here: " ++ intercalate ", " (map showIdent names) ++ ":"
672− , indent $ go err
673− ]
674− 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) =
675691 paras [ lineWithLevel "unifying type "
676− , indent $ line $ prettyPrintType t1
692+ , indent $ typeAsBox t1
677693 , line "with type"
678− , indent $ line $ prettyPrintType t2
679− , go err
694+ , indent $ typeAsBox t2
680695 ]
681− go (ErrorInExpression expr err) =
696+ renderHint (ErrorInExpression expr) =
682697 paras [ lineWithLevel "in expression:"
683− , indent $ line $ prettyPrintValue expr
684− , go err
698+ , indent $ prettyPrintValue expr
685699 ]
686− go (ErrorInModule mn err) =
700+ renderHint (ErrorInModule mn) =
687701 paras [ lineWithLevel $ "in module " ++ runModuleName mn ++ ":"
688− , go err
689702 ]
690− go (ErrorInSubsumption t1 t2 err) =
703+ renderHint (ErrorInSubsumption t1 t2) =
691704 paras [ lineWithLevel "checking that type "
692− , indent $ line $ prettyPrintType t1
705+ , indent $ typeAsBox t1
693706 , line "subsumes type"
694− , indent $ line $ prettyPrintType t2
695− , go err
707+ , indent $ typeAsBox t2
696708 ]
697− go (ErrorInInstance name ts err) =
698− paras [ lineWithLevel $ "in type class instance " ++ showQualified runProperName name ++ " " ++ unwords (map prettyPrintTypeAtom ts) ++ ":"
699− , go err
709+ renderHint (ErrorInInstance nm ts) =
710+ paras [ lineWithLevel "in type class instance"
711+ , indent $ Box.hsep 1 Box.left [ line (showQualified runProperName nm)
712+ , Box.vcat Box.left (map typeAtomAsBox ts)
713+ ]
700714 ]
701− go (ErrorCheckingKind ty err) =
715+ renderHint (ErrorCheckingKind ty) =
702716 paras [ lineWithLevel "checking kind of type "
703− , indent $ line $ prettyPrintType ty
704− , go err
717+ , indent $ typeAsBox ty
705718 ]
706− go (ErrorInferringType expr err) =
719+ renderHint (ErrorInferringType expr) =
707720 paras [ lineWithLevel "inferring type of value "
708− , indent $ line $ prettyPrintValue expr
709− , go err
721+ , indent $ prettyPrintValue expr
710722 ]
711− go (ErrorCheckingType expr ty err) =
723+ renderHint (ErrorCheckingType expr ty) =
712724 paras [ lineWithLevel "checking that value "
713− , indent $ line $ prettyPrintValue expr
725+ , indent $ prettyPrintValue expr
714726 , line "has type"
715− , indent $ line $ prettyPrintType ty
716− , go err
727+ , indent $ typeAsBox ty
717728 ]
718− go (ErrorInApplication f t a err) =
729+ renderHint (ErrorInApplication f t a) =
719730 paras [ lineWithLevel "applying function"
720− , indent $ line $ prettyPrintValue f
731+ , indent $ prettyPrintValue f
721732 , line "of type"
722− , indent $ line $ prettyPrintType t
733+ , indent $ typeAsBox t
723734 , line "to argument"
724− , indent $ line $ prettyPrintValue a
725− , go err
726− ]
727− go (ErrorInDataConstructor nm err) =
728− paras [ lineWithLevel $ "in data constructor " ++ runProperName nm ++ ":"
729− , go err
730− ]
731− go (ErrorInTypeConstructor nm err) =
732− paras [ lineWithLevel $ "in type constructor " ++ runProperName nm ++ ":"
733− , go err
734− ]
735− go (ErrorInBindingGroup nms err) =
736− paras [ lineWithLevel $ "in binding group " ++ intercalate ", " (map showIdent nms) ++ ":"
737− , go err
738− ]
739− go (ErrorInDataBindingGroup err) =
740− paras [ lineWithLevel "in data binding group:"
741− , go err
742− ]
743− go (ErrorInTypeSynonym name err) =
744− paras [ lineWithLevel $ "in type synonym " ++ runProperName name ++ ":"
745− , go err
746− ]
747− go (ErrorInValueDeclaration n err) =
748− paras [ lineWithLevel $ "in value declaration " ++ showIdent n ++ ":"
749− , go err
750− ]
751− go (ErrorInTypeDeclaration n err) =
752− paras [ lineWithLevel $ "in type declaration for " ++ showIdent n ++ ":"
753− , go err
754− ]
755− go (ErrorInForeignImport nm err) =
756− paras [ lineWithLevel $ "in foreign import " ++ showIdent nm ++ ":"
757− , go err
758− ]
759− go (PositionedError srcSpan err) =
760− paras [ lineWithLevel $ "at " ++ displaySourceSpan srcSpan ++ ":"
761− , indent $ go err
762− ]
763− go (SimpleErrorWrapper sem) = goSimple sem
735+ , indent $ prettyPrintValue a
736+ ]
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 ++ ":"
764755
765756 lineWithLevel :: String -> Box.Box
766757 lineWithLevel text = line $ show level ++ " " ++ text
@@ -770,23 +761,19 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage <$> onTypesInError
770761 Error -> "error"
771762 Warning -> "warning"
772763
773− suggestions :: ErrorMessage -> [Box.Box]
774− suggestions = suggestions' . unwrapErrorMessage
775− where
776− 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 ++ ":"
777766 , indent . line $ "import " ++ runModuleName im ++ " hiding (" ++ nm ++ ")"
778767 ]
779− suggestions' (TypesDoNotUnify t1 t2)
780− | isObject t1 && isFunction t2 = [line "Note that function composition in PureScript is defined using (<<<)"]
781− | otherwise = []
782− 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 _ = []
783772
784773 paras :: [Box.Box] -> Box.Box
785774 paras = Box.vcat Box.left
786775
787− -- |
788776 -- Pretty print and export declaration
789− --
790777 prettyPrintExport :: DeclarationRef -> String
791778 prettyPrintExport (TypeRef pn _) = runProperName pn
792779 prettyPrintExport (ValueRef ident) = showIdent ident
@@ -795,38 +782,44 @@ prettyPrintSingleError full level e = prettyPrintErrorMessage <$> onTypesInError
795782 prettyPrintExport (ModuleRef name) = "module " ++ runModuleName name
796783 prettyPrintExport (PositionedDeclarationRef _ _ ref) = prettyPrintExport ref
797784
798− -- |
799− -- Simplify an error message
800− --
801− simplifyErrorMessage :: ErrorMessage -> ErrorMessage
802− 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
803792 where
804− unwrap :: Maybe SourceSpan -> ErrorMessage -> ErrorMessage
805− unwrap pos (ErrorInExpression _ err) = unwrap pos err
806− unwrap pos (ErrorInInstance name ts err) = ErrorInInstance name ts (unwrap pos err)
807− unwrap pos (ErrorInSubsumption t1 t2 err) = ErrorInSubsumption t1 t2 (unwrap pos err)
808− unwrap pos (ErrorUnifyingTypes _ _ err) = unwrap pos err
809− unwrap pos (ErrorInferringType _ err) = unwrap pos err
810− unwrap pos (ErrorCheckingType _ _ err) = unwrap pos err
811− unwrap pos (ErrorCheckingKind ty err) = ErrorCheckingKind ty (unwrap pos err)
812− unwrap pos (ErrorInModule mn err) = ErrorInModule mn (unwrap pos err)
813− unwrap pos (ErrorInApplication _ _ _ err) = unwrap pos err
814− unwrap pos (ErrorInDataConstructor nm err) = ErrorInDataConstructor nm (unwrap pos err)
815− unwrap pos (ErrorInTypeConstructor nm err) = ErrorInTypeConstructor nm (unwrap pos err)
816− unwrap pos (ErrorInBindingGroup nms err) = ErrorInBindingGroup nms (unwrap pos err)
817− unwrap pos (ErrorInDataBindingGroup err) = ErrorInDataBindingGroup (unwrap pos err)
818− unwrap pos (ErrorInTypeSynonym nm err) = ErrorInTypeSynonym nm (unwrap pos err)
819− unwrap pos (ErrorInValueDeclaration nm err) = ErrorInValueDeclaration nm (unwrap pos err)
820− unwrap pos (ErrorInTypeDeclaration nm err) = ErrorInTypeDeclaration nm (unwrap pos err)
821− unwrap pos (ErrorInForeignImport nm err) = ErrorInForeignImport nm (unwrap pos err)
822− unwrap pos (NotYetDefined ns err) = NotYetDefined ns (unwrap pos err)
823− unwrap _ (PositionedError pos err) = unwrap (Just pos) err
824− unwrap pos other = wrap pos other
825−
826− wrap :: Maybe SourceSpan -> ErrorMessage -> ErrorMessage
827− wrap Nothing = id
828− wrap (Just pos) = PositionedError pos
793+ isPositionHint :: HintCategory -> Bool
794+ isPositionHint PositionHint = True
795+ isPositionHint OtherHint = True
796+ isPositionHint _ = False
829797
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
830823
831824-- |
832825-- Pretty print multiple errors
@@ -842,11 +835,11 @@ prettyPrintMultipleWarnings full = renderBox . prettyPrintMultipleWarningsBox fu
842835
843836-- | Pretty print warnings as a Box
844837prettyPrintMultipleWarningsBox :: Bool -> MultipleErrors -> Box.Box
845−prettyPrintMultipleWarningsBox full = flip evalState M.empty . prettyPrintMultipleErrorsWith Warning "Warning found:" "Multiple warnings found:" full
838+prettyPrintMultipleWarningsBox full = flip evalState M.empty . prettyPrintMultipleErrorsWith Warning "Warning found:" "Warning" full
846839
847840-- | Pretty print errors as a Box
848841prettyPrintMultipleErrorsBox :: Bool -> MultipleErrors -> Box.Box
849−prettyPrintMultipleErrorsBox full = flip evalState M.empty . prettyPrintMultipleErrorsWith Error "Error found:" "Multiple errors found:" full
842+prettyPrintMultipleErrorsBox full = flip evalState M.empty . prettyPrintMultipleErrorsWith Error "Error found:" "Error" full
850843
851844prettyPrintMultipleErrorsWith :: Level -> String -> String -> Bool -> MultipleErrors -> State UnknownMap Box.Box
852845prettyPrintMultipleErrorsWith level intro _ full (MultipleErrors [e]) = do
@@ -856,11 +849,12 @@ prettyPrintMultipleErrorsWith level intro _ full (MultipleErrors [e]) = do
856849 , result
857850 ]
858851prettyPrintMultipleErrorsWith level _ intro full (MultipleErrors es) = do
859− result <- forM es $ liftM (Box.moveRight 2) . prettyPrintSingleError full level
860− return $
861− Box.vcat Box.left [ Box.text intro
862− , Box.vsep 1 Box.left result
863− ]
852+ result <- forM es $ prettyPrintSingleError full level
853+ return $ Box.vsep 1 Box.left $ concat $ zipWith withIntro [1 :: Int ..] result
854+ where
855+ withIntro i err = [ Box.text (intro ++ " " ++ show i ++ " of " ++ show (length es) ++ ":")
856+ , Box.moveRight 2 err
857+ ]
864858
865859-- | Pretty print a Parsec ParseError as a Box
866860prettyPrintParseError :: P.ParseError -> Box.Box
@@ -910,8 +904,9 @@ prettyPrintParseErrorMessages msgOr msgUnknown msgExpecting msgUnExpected msgEnd
910904
911905 clean = nub . filter (not . null)
912906
907+-- | Indent to the right, and pad on top and bottom.
913908indent :: Box.Box -> Box.Box
914−indent = Box.moveRight 2
909+indent = Box.moveUp 1 . Box.moveDown 1 . Box.moveRight 2
915910
916911line :: String -> Box.Box
917912line = Box.text
@@ -951,8 +946,7 @@ warnAndRethrowWithPosition :: (MonadError MultipleErrors m, MonadWriter Multiple
951946warnAndRethrowWithPosition pos = rethrowWithPosition pos . warnWithPosition pos
952947
953948withPosition :: SourceSpan -> ErrorMessage -> ErrorMessage
954−withPosition _ (PositionedError pos err) = withPosition pos err
955−withPosition pos err = PositionedError pos err
949+withPosition pos (ErrorMessage hints se) = ErrorMessage (PositionedError pos : hints) se
956950
957951-- |
958952-- 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/Names.hs+4
@@ -104,6 +104,10 @@ qualify _ (Qualified (Just m) a) = (m, a)
104104mkQualified :: a -> ModuleName -> Qualified a
105105mkQualified name mn = Qualified (Just mn) name
106106
107+-- | Remove the module name from a qualified name
108+disqualify :: Qualified a -> a
109+disqualify (Qualified _ a) = a
110+
107111-- |
108112-- Checks whether a qualified value is actually qualified with a module reference
109113--
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/Common.hs+11
@@ -17,8 +17,11 @@ module Language.PureScript.Pretty.Common where
1717
1818import Control.Monad.State
1919import Data.List (intercalate)
20+
2021import Language.PureScript.Parser.Lexer (reservedPsNames, opChars)
2122
23+import Text.PrettyPrint.Boxes
24+
2225-- |
2326-- Wrap a string in parentheses
2427--
@@ -67,3 +70,11 @@ prettyPrintObjectKey :: String -> String
6770prettyPrintObjectKey s | s `elem` reservedPsNames = show s
6871 | any (`elem` opChars) s = show s
6972 | otherwise = s
73+
74+-- | Place a box before another, vertically when the first box takes up multiple lines.
75+before :: Box -> Box -> Box
76+before b1 b2 | rows b1 > 1 = b1 // b2
77+ | otherwise = b1 <> b2
78+
79+beforeWithSpace :: Box -> Box -> Box
80+beforeWithSpace b1 = before (b1 <> text " ")
src/Language/PureScript/Pretty/Kinds.hs+19−15
@@ -14,7 +14,8 @@
1414-----------------------------------------------------------------------------
1515
1616module Language.PureScript.Pretty.Kinds (
17− prettyPrintKind
17+ prettyPrintKind,
18+ kindAsBox
1819) where
1920
2021import Data.Maybe (fromMaybe)
@@ -23,14 +24,15 @@ import Control.Arrow (ArrowPlus(..))
2324import Control.PatternArrows
2425
2526import Language.PureScript.Kinds
26−import Language.PureScript.Pretty.Common
2727
28−typeLiterals :: Pattern () Kind String
28+import Text.PrettyPrint.Boxes (Box(), text, render, (<>))
29+
30+typeLiterals :: Pattern () Kind Box
2931typeLiterals = mkPattern match
3032 where
31− match Star = Just "*"
32− match Bang = Just "!"
33− match (KUnknown u) = Just $ 'u' : show u
33+ match Star = Just $ text "*"
34+ match Bang = Just $ text "!"
35+ match (KUnknown u) = Just $ text $ 'u' : show u
3436 match _ = Nothing
3537
3638matchRow :: Pattern () Kind ((), Kind)
@@ -45,15 +47,17 @@ funKind = mkPattern match
4547 match (FunKind arg ret) = Just (arg, ret)
4648 match _ = Nothing
4749
48−-- |
49−-- Generate a pretty-printed string representing a Kind
50−--
50+-- | Generate a pretty-printed string representing a Kind
5151prettyPrintKind :: Kind -> String
52−prettyPrintKind = fromMaybe (error "Incomplete pattern") . pattern matchKind ()
52+prettyPrintKind = render . kindAsBox
53+
54+kindAsBox :: Kind -> Box
55+kindAsBox = fromMaybe (error "Incomplete pattern") . pattern matchKind ()
5356 where
54− matchKind :: Pattern () Kind String
55− matchKind = buildPrettyPrinter operators (typeLiterals <+> fmap parens matchKind)
56− operators :: OperatorTable () Kind String
57+ matchKind :: Pattern () Kind Box
58+ matchKind = buildPrettyPrinter operators (typeLiterals <+> fmap ((text "(" <>) . (<> text ")")) matchKind)
59+
60+ operators :: OperatorTable () Kind Box
5761 operators =
58− OperatorTable [ [ Wrap matchRow $ \_ k -> "# " ++ k]
59− , [ AssocR funKind $ \arg ret -> arg ++ " -> " ++ ret ] ]
62+ OperatorTable [ [ Wrap matchRow $ \_ k -> text "# " <> k]
63+ , [ AssocR funKind $ \arg ret -> arg <> text " -> " <> ret ] ]
src/Language/PureScript/Pretty/Types.hs+56−35
@@ -14,13 +14,15 @@
1414-----------------------------------------------------------------------------
1515
1616module Language.PureScript.Pretty.Types (
17+ typeAsBox,
1718 prettyPrintType,
19+ typeAtomAsBox,
1820 prettyPrintTypeAtom,
21+ prettyPrintRowWith,
1922 prettyPrintRow
2023) where
2124
2225import Data.Maybe (fromMaybe)
23−import Data.List (intercalate)
2426
2527import Control.Arrow ((<+>))
2628import Control.PatternArrows
@@ -32,36 +34,54 @@ import Language.PureScript.Pretty.Common
3234import Language.PureScript.Pretty.Kinds
3335import Language.PureScript.Environment
3436
35−typeLiterals :: Pattern () Type String
37+import Text.PrettyPrint.Boxes hiding ((<+>))
38+
39+typeLiterals :: Pattern () Type Box
3640typeLiterals = mkPattern match
3741 where
38− match TypeWildcard = Just "_"
39− match (TypeVar var) = Just var
40− match (PrettyPrintObject row) = Just $ "{ " ++ prettyPrintRow row ++ " }"
41− match (TypeConstructor ctor) = Just $ showQualified runProperName ctor
42− match (TUnknown u) = Just $ '_' : show u
43− match (Skolem name s _) = Just $ name ++ show s
44− match (ConstrainedType deps ty) = Just $ "(" ++ intercalate ", " (map (\(pn, ty') -> showQualified runProperName pn ++ " " ++ unwords (map prettyPrintTypeAtom ty')) deps) ++ ") => " ++ prettyPrintType ty
45− match (SaturatedTypeSynonym name args) = Just $ showQualified runProperName name ++ "<" ++ intercalate "," (map prettyPrintTypeAtom args) ++ ">"
46− match REmpty = Just "()"
47− match row@RCons{} = Just $ '(' : prettyPrintRow row ++ ")"
42+ match TypeWildcard = Just $ text "_"
43+ match (TypeVar var) = Just $ text var
44+ match (PrettyPrintObject row) = Just $ prettyPrintRowWith '{' '}' row
45+ match (TypeConstructor ctor) = Just $ text $ runProperName $ disqualify ctor
46+ match (TUnknown u) = Just $ text $ '_' : show u
47+ match (Skolem name s _) = Just $ text $ name ++ show s
48+ match (ConstrainedType deps ty) = Just $ constraintsAsBox deps `before` (text ") => " <> typeAsBox ty)
49+ match REmpty = Just $ text "()"
50+ match row@RCons{} = Just $ prettyPrintRowWith '(' ')' row
4851 match _ = Nothing
4952
53+constraintsAsBox :: [(Qualified ProperName, [Type])] -> Box
54+constraintsAsBox = vcat left . zipWith (\i (pn, tys) -> text (if i == 0 then "( " else ", ") <> constraintAsBox pn tys) [0 :: Int ..]
55+ where
56+ constraintAsBox pn tys = hsep 1 left (text (runProperName (disqualify pn)) : map typeAtomAsBox tys)
57+
5058-- |
5159-- Generate a pretty-printed string representing a Row
5260--
53−prettyPrintRow :: Type -> String
54−prettyPrintRow = (\(tys, rest) -> intercalate ", " (map (uncurry nameAndTypeToPs) tys) ++ tailToPs rest) . toList []
61+prettyPrintRowWith :: Char -> Char -> Type -> Box
62+prettyPrintRowWith open close = uncurry listToBox . toList []
5563 where
56− nameAndTypeToPs :: String -> Type -> String
57− nameAndTypeToPs name ty = prettyPrintObjectKey name ++ " :: " ++ prettyPrintType ty
58− tailToPs :: Type -> String
59− tailToPs REmpty = ""
60− tailToPs other = " | " ++ prettyPrintType other
64+ nameAndTypeToPs :: Char -> String -> Type -> Box
65+ nameAndTypeToPs start name ty = text (start : ' ' : prettyPrintObjectKey name ++ " :: ") <> typeAsBox ty
66+
67+ tailToPs :: Type -> Box
68+ tailToPs REmpty = nullBox
69+ tailToPs other = text "| " <> typeAsBox other
70+
71+ listToBox :: [(String, Type)] -> Type -> Box
72+ listToBox [] REmpty = text [open, close]
73+ listToBox [] rest = text [ open, ' ' ] <> tailToPs rest <> text [ ' ', close ]
74+ listToBox ts rest = vcat left $
75+ zipWith (\(nm, ty) i -> nameAndTypeToPs (if i == 0 then open else ',') nm ty) ts [0 :: Int ..] ++
76+ [ tailToPs rest, text [close] ]
77+
6178 toList :: [(String, Type)] -> Type -> ([(String, Type)], Type)
6279 toList tys (RCons name ty row) = toList ((name, ty):tys) row
6380 toList tys r = (tys, r)
6481
82+prettyPrintRow :: Type -> String
83+prettyPrintRow = render . prettyPrintRowWith '(' ')'
84+
6585typeApp :: Pattern () Type (Type, Type)
6686typeApp = mkPattern match
6787 where
@@ -92,19 +112,19 @@ insertPlaceholders = everywhereOnTypesTopDown convertForAlls . everywhereOnTypes
92112 go idents other = PrettyPrintForAll idents other
93113 convertForAlls other = other
94114
95−matchTypeAtom :: Pattern () Type String
96−matchTypeAtom = typeLiterals <+> fmap parens matchType
115+matchTypeAtom :: Pattern () Type Box
116+matchTypeAtom = typeLiterals <+> fmap ((`before` text ")") . (text "(" <>)) matchType
97117
98−matchType :: Pattern () Type String
118+matchType :: Pattern () Type Box
99119matchType = buildPrettyPrinter operators matchTypeAtom
100120 where
101− operators :: OperatorTable () Type String
121+ operators :: OperatorTable () Type Box
102122 operators =
103− OperatorTable [ [ AssocL typeApp $ \f x -> f ++ " " ++ x ]
104− , [ AssocR appliedFunction $ \arg ret -> arg ++ " -> " ++ ret
123+ OperatorTable [ [ AssocL typeApp $ \f x -> f `beforeWithSpace` x ]
124+ , [ AssocR appliedFunction $ \arg ret -> (arg <> text " ") `before` (text "-> " <> ret)
105125 ]
106− , [ Wrap forall_ $ \idents ty -> "forall " ++ unwords idents ++ ". " ++ ty ]
107− , [ Wrap kinded $ \k ty -> ty ++ " :: " ++ prettyPrintKind k ]
126+ , [ Wrap forall_ $ \idents ty -> text ("forall " ++ unwords idents ++ ". ") <> ty ]
127+ , [ Wrap kinded $ \k ty -> ty `before` (text " :: " <> kindAsBox k) ]
108128 ]
109129
110130forall_ :: Pattern () Type ([String], Type)
@@ -113,15 +133,16 @@ forall_ = mkPattern match
113133 match (PrettyPrintForAll idents ty) = Just (idents, ty)
114134 match _ = Nothing
115135
116−-- |
117−-- Generate a pretty-printed string representing a Type, as it should appear inside parentheses
118−--
136+typeAtomAsBox :: Type -> Box
137+typeAtomAsBox = fromMaybe (error "Incomplete pattern") . pattern matchTypeAtom () . insertPlaceholders
138+
139+-- | Generate a pretty-printed string representing a Type, as it should appear inside parentheses
119140prettyPrintTypeAtom :: Type -> String
120−prettyPrintTypeAtom = fromMaybe (error "Incomplete pattern") . pattern matchTypeAtom () . insertPlaceholders
141+prettyPrintTypeAtom = render . typeAtomAsBox
121142
143+typeAsBox :: Type -> Box
144+typeAsBox = fromMaybe (error "Incomplete pattern") . pattern matchType () . insertPlaceholders
122145
123−-- |
124−-- Generate a pretty-printed string representing a Type
125−--
146+-- | Generate a pretty-printed string representing a Type
126147prettyPrintType :: Type -> String
127−prettyPrintType = fromMaybe (error "Incomplete pattern") . pattern matchType () . insertPlaceholders
148+prettyPrintType = render . typeAsBox
src/Language/PureScript/Pretty/Values.hs+92−152
@@ -21,173 +21,113 @@ module Language.PureScript.Pretty.Values (
2121 prettyPrintBinderAtom
2222) where
2323
24−import Data.Maybe (fromMaybe)
2524import Data.List (intercalate)
2625
27−import Control.Arrow ((<+>), runKleisli, second)
28−import Control.PatternArrows
29−import Control.Monad.State
30−#if __GLASGOW_HASKELL__ < 710
31−import Control.Applicative
32−#endif
26+import Control.Arrow (second)
3327
3428import Language.PureScript.AST
3529import Language.PureScript.Names
3630import Language.PureScript.Pretty.Common
37−import Language.PureScript.Pretty.Types (prettyPrintType, prettyPrintTypeAtom)
31+import Language.PureScript.Pretty.Types (typeAsBox, typeAtomAsBox)
3832
39−literals :: Pattern PrinterState Expr String
40−literals = mkPattern' match
33+import Text.PrettyPrint.Boxes
34+
35+-- | Render an aligned list of items separated with commas
36+list :: Char -> Char -> (a -> Box) -> [a] -> Box
37+list open close _ [] = text [open, close]
38+list open close f xs = vcat left (zipWith toLine [0 :: Int ..] xs ++ [ text [ close ] ])
4139 where
42− match :: Expr -> StateT PrinterState Maybe String
43− match (NumericLiteral n) = return $ either show show n
44− match (StringLiteral s) = return $ show s
45− match (CharLiteral c) = return $ show c
46− match (BooleanLiteral True) = return "true"
47− match (BooleanLiteral False) = return "false"
48− match (ArrayLiteral xs) = return $ "[" ++ intercalate ", " (map prettyPrintValue xs) ++ "]"
49− match (ObjectLiteral ps) = prettyPrintObject' $ second Just `map` ps
50− match (ObjectConstructor ps) = prettyPrintObject' ps
51− match (ObjectGetter prop) = return $ "(." ++ prop ++ ")"
52− match (TypeClassDictionaryConstructorApp className ps) = concat <$> sequence
53− [ return (showQualified runProperName className ++ "(\n")
54− , match ps
55− , return ")"
56− ]
57− match (Constructor name) = return $ showQualified runProperName name
58− match (Case values binders) = concat <$> sequence
59− [ return "case "
60− , unwords <$> forM values prettyPrintValue'
61− , return " of\n"
62− , withIndent $ prettyPrintMany prettyPrintCaseAlternative binders
63− , currentIndent
64− ]
65− match (Let ds val) = concat <$> sequence
66− [ return "let\n"
67− , withIndent $ prettyPrintMany prettyPrintDeclaration ds
68− , return "\n"
69− , currentIndent
70− , return "in "
71− , prettyPrintValue' val
72− ]
73− match (Var ident) = return $ showQualified showIdent ident
74− match (Do els) = concat <$> sequence
75− [ return "do\n"
76− , withIndent $ prettyPrintMany prettyPrintDoNotationElement els
77− , currentIndent
78− ]
79− match (OperatorSection op (Right val)) = return $ "(" ++ prettyPrintValue op ++ " " ++ prettyPrintValue val ++ ")"
80− match (OperatorSection op (Left val)) = return $ "(" ++ prettyPrintValue val ++ " " ++ prettyPrintValue op ++ ")"
81− match (TypeClassDictionary (name, tys) _) = return $ "<<dict " ++ showQualified runProperName name ++ " " ++ unwords (map prettyPrintTypeAtom tys) ++ ">>"
82− match (SuperClassDictionary name _) = return $ "<<superclass dict " ++ showQualified runProperName name ++ ">>"
83− match (TypedValue _ val _) = prettyPrintValue' val
84− match (PositionedValue _ _ val) = prettyPrintValue' val
85− match _ = mzero
86−
87−prettyPrintDeclaration :: Declaration -> StateT PrinterState Maybe String
88−prettyPrintDeclaration (TypeDeclaration ident ty) = return $ showIdent ident ++ " :: " ++ prettyPrintType ty
89−prettyPrintDeclaration (ValueDeclaration ident _ [] (Right val)) = concat <$> sequence
90− [ return $ showIdent ident ++ " = "
91− , prettyPrintValue' val
92− ]
40+ toLine i a = text [ if i == 0 then open else ',', ' ' ] <> f a
41+
42+prettyPrintObject :: [(String, Maybe Expr)] -> Box
43+prettyPrintObject = list '{' '}' prettyPrintObjectProperty
44+ where
45+ prettyPrintObjectProperty :: (String, Maybe Expr) -> Box
46+ prettyPrintObjectProperty (key, value) = text (prettyPrintObjectKey key ++ ": ") <> maybe (text "_") prettyPrintValue value
47+
48+-- | Pretty-print an expression
49+prettyPrintValue :: Expr -> Box
50+prettyPrintValue (IfThenElse cond th el) =
51+ (text "if " <> prettyPrintValueAtom cond)
52+ // moveRight 2 (vcat left [ text "then " <> prettyPrintValueAtom th
53+ , text "else " <> prettyPrintValueAtom el
54+ ])
55+prettyPrintValue (Accessor prop val) = prettyPrintValueAtom val <> text ("." ++ show prop)
56+prettyPrintValue (ObjectUpdate o ps) = prettyPrintValueAtom o <> text " " <> list '{' '}' (\(key, val) -> text (key ++ " = ") <> prettyPrintValue val) ps
57+prettyPrintValue (ObjectUpdater o ps) = maybe (text "_") prettyPrintValueAtom o <> text " " <> list '{' '}' (\(key, val) -> text (key ++ " = ") <> maybe (text "_") prettyPrintValue val) ps
58+prettyPrintValue (App val arg) = prettyPrintValueAtom val `beforeWithSpace` prettyPrintValueAtom arg
59+prettyPrintValue (Abs (Left arg) val) = text ('\\' : showIdent arg ++ " -> ") // moveRight 2 (prettyPrintValue val)
60+prettyPrintValue (TypeClassDictionaryConstructorApp className ps) =
61+ text (runProperName (disqualify className) ++ " ") <> prettyPrintValueAtom ps
62+prettyPrintValue (Case values binders) =
63+ (text "case " <> foldl1 beforeWithSpace (map prettyPrintValueAtom values) <> text " of") //
64+ moveRight 2 (vcat left (map prettyPrintCaseAlternative binders))
65+prettyPrintValue (Let ds val) =
66+ text "let" //
67+ moveRight 2 (vcat left (map prettyPrintDeclaration ds)) //
68+ (text "in " <> prettyPrintValue val)
69+prettyPrintValue (Do els) =
70+ text "do " <> vcat left (map prettyPrintDoNotationElement els)
71+prettyPrintValue (TypeClassDictionary (name, tys) _) = foldl1 beforeWithSpace $ text ("#dict " ++ runProperName (disqualify name)) : map typeAtomAsBox tys
72+prettyPrintValue (SuperClassDictionary name _) = text $ "#dict " ++ runProperName (disqualify name)
73+prettyPrintValue (TypedValue _ val _) = prettyPrintValue val
74+prettyPrintValue (PositionedValue _ _ val) = prettyPrintValue val
75+prettyPrintValue expr = prettyPrintValueAtom expr
76+
77+-- | Pretty-print an atomic expression, adding parentheses if necessary.
78+prettyPrintValueAtom :: Expr -> Box
79+prettyPrintValueAtom (NumericLiteral n) = text $ either show show n
80+prettyPrintValueAtom (StringLiteral s) = text $ show s
81+prettyPrintValueAtom (CharLiteral c) = text $ show c
82+prettyPrintValueAtom (BooleanLiteral True) = text "true"
83+prettyPrintValueAtom (BooleanLiteral False) = text "false"
84+prettyPrintValueAtom (ArrayLiteral xs) = list '[' ']' prettyPrintValue xs
85+prettyPrintValueAtom (ObjectLiteral ps) = prettyPrintObject $ second Just `map` ps
86+prettyPrintValueAtom (ObjectConstructor ps) = prettyPrintObject ps
87+prettyPrintValueAtom (ObjectGetter prop) = text $ "_." ++ show prop
88+prettyPrintValueAtom (Constructor name) = text $ runProperName (disqualify name)
89+prettyPrintValueAtom (Var ident) = text $ showIdent (disqualify ident)
90+prettyPrintValueAtom (OperatorSection op (Right val)) = ((text "(" <> prettyPrintValue op) `beforeWithSpace` prettyPrintValue val) `before` text ")"
91+prettyPrintValueAtom (OperatorSection op (Left val)) = ((text "(" <> prettyPrintValue val) `beforeWithSpace` prettyPrintValue op) `before` text ")"
92+prettyPrintValueAtom (TypedValue _ val _) = prettyPrintValueAtom val
93+prettyPrintValueAtom (PositionedValue _ _ val) = prettyPrintValueAtom val
94+prettyPrintValueAtom expr = (text "(" <> prettyPrintValue expr) `before` text ")"
95+
96+prettyPrintDeclaration :: Declaration -> Box
97+prettyPrintDeclaration (TypeDeclaration ident ty) =
98+ text (showIdent ident ++ " :: ") <> typeAsBox ty
99+prettyPrintDeclaration (ValueDeclaration ident _ [] (Right val)) =
100+ text (showIdent ident ++ " = ") <> prettyPrintValue val
93101prettyPrintDeclaration (PositionedDeclaration _ _ d) = prettyPrintDeclaration d
94102prettyPrintDeclaration _ = error "Invalid argument to prettyPrintDeclaration"
95103
96−prettyPrintCaseAlternative :: CaseAlternative -> StateT PrinterState Maybe String
104+prettyPrintCaseAlternative :: CaseAlternative -> Box
97105prettyPrintCaseAlternative (CaseAlternative binders result) =
98− concat <$> sequence
99− [ return (unwords (map prettyPrintBinderAtom binders))
100− , prettyPrintResult result
101− ]
106+ text (unwords (map prettyPrintBinderAtom binders)) <> prettyPrintResult result
102107 where
103− prettyPrintResult (Left gs) = concat <$> sequence
104− [ return "\n"
105− , withIndent $ prettyPrintMany prettyPrintGuardedValue gs
106− ]
107− prettyPrintResult (Right v) = (" -> " ++) <$> prettyPrintValue' v
108−
109− prettyPrintGuardedValue (grd, val) =
110− concat <$> sequence
111− [ return "| "
112− , prettyPrintValue' grd
113− , return " -> "
114− , prettyPrintValue' val
115− ]
116−
117−prettyPrintDoNotationElement :: DoNotationElement -> StateT PrinterState Maybe String
108+ prettyPrintResult :: Either [(Guard, Expr)] Expr -> Box
109+ prettyPrintResult (Left gs) =
110+ vcat left (map prettyPrintGuardedValue gs)
111+ prettyPrintResult (Right v) = text " -> " <> prettyPrintValue v
112+
113+ prettyPrintGuardedValue :: (Guard, Expr) -> Box
114+ prettyPrintGuardedValue (grd, val) = foldl1 before
115+ [ text " | "
116+ , prettyPrintValue grd
117+ , text " -> "
118+ , prettyPrintValue val
119+ ]
120+
121+prettyPrintDoNotationElement :: DoNotationElement -> Box
118122prettyPrintDoNotationElement (DoNotationValue val) =
119− prettyPrintValue' val
123+ prettyPrintValue val
120124prettyPrintDoNotationElement (DoNotationBind binder val) =
121− concat <$> sequence
122− [ return (prettyPrintBinder binder)
123− , return " <- "
124− , prettyPrintValue' val
125− ]
125+ text (prettyPrintBinder binder ++ " <- ") <> prettyPrintValue val
126126prettyPrintDoNotationElement (DoNotationLet ds) =
127− concat <$> sequence
128− [ return "let "
129− , withIndent $ prettyPrintMany prettyPrintDeclaration ds
130− ]
127+ text "let" //
128+ moveRight 2 (vcat left (map prettyPrintDeclaration ds))
131129prettyPrintDoNotationElement (PositionedDoNotationElement _ _ el) = prettyPrintDoNotationElement el
132130
133−prettyPrintObject' :: [(String, Maybe Expr)] -> StateT PrinterState Maybe String
134−prettyPrintObject' [] = return "{}"
135−prettyPrintObject' ps = return $ "{ " ++ intercalate ", " (map prettyPrintObjectProperty ps) ++ "}"
136− where
137− prettyPrintObjectProperty :: (String, Maybe Expr) -> String
138− prettyPrintObjectProperty (key, value) = prettyPrintObjectKey key ++ ": " ++ maybe "_" prettyPrintValue value
139−
140−ifThenElse :: Pattern PrinterState Expr ((Expr, Expr), Expr)
141−ifThenElse = mkPattern match
142− where
143− match (IfThenElse cond th el) = Just ((th, el), cond)
144− match _ = Nothing
145−
146−accessor :: Pattern PrinterState Expr (String, Expr)
147−accessor = mkPattern match
148− where
149− match (Accessor prop val) = Just (prop, val)
150− match _ = Nothing
151−
152−objectUpdate :: Pattern PrinterState Expr ([String], Expr)
153−objectUpdate = mkPattern match
154− where
155− match (ObjectUpdate o ps) = Just (flip map ps $ \(key, val) -> key ++ " = " ++ prettyPrintValue val, o)
156− match (ObjectUpdater o ps) = Just (flip map ps $ \(key, val) -> key ++ " = " ++ maybe "_" prettyPrintValue val, fromMaybe (Var (Qualified Nothing $ Ident "_")) o)
157− match _ = Nothing
158−
159−app :: Pattern PrinterState Expr (String, Expr)
160−app = mkPattern match
161− where
162− match (App val arg) = Just (prettyPrintValue arg, val)
163− match _ = Nothing
164−
165−lam :: Pattern PrinterState Expr (String, Expr)
166−lam = mkPattern match
167− where
168− match (Abs (Left arg) val) = Just (showIdent arg, val)
169− match _ = Nothing
170−
171−-- |
172−-- Generate a pretty-printed string representing an expression
173−--
174−prettyPrintValue :: Expr -> String
175−prettyPrintValue = fromMaybe (error "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyPrintValue'
176−
177−prettyPrintValue' :: Expr -> StateT PrinterState Maybe String
178−prettyPrintValue' = runKleisli $ runPattern matchValue
179− where
180− matchValue :: Pattern PrinterState Expr String
181− matchValue = buildPrettyPrinter operators (literals <+> fmap parens matchValue)
182− operators :: OperatorTable PrinterState Expr String
183− operators =
184− OperatorTable [ [ Wrap accessor $ \prop val -> val ++ "." ++ prop ]
185− , [ Wrap objectUpdate $ \ps val -> val ++ "{ " ++ intercalate ", " ps ++ " }" ]
186− , [ Wrap app $ \arg val -> val ++ "(" ++ arg ++ ")" ]
187− , [ Split lam $ \arg val -> "\\" ++ arg ++ " -> " ++ prettyPrintValue val ]
188− , [ Wrap ifThenElse $ \(th, el) cond -> "if " ++ cond ++ " then " ++ prettyPrintValue th ++ " else " ++ prettyPrintValue el ]
189− ]
190−
191131prettyPrintBinderAtom :: Binder -> String
192132prettyPrintBinderAtom NullBinder = "_"
193133prettyPrintBinderAtom (StringBinder str) = show str
@@ -196,7 +136,7 @@ prettyPrintBinderAtom (NumberBinder num) = either show show num
196136prettyPrintBinderAtom (BooleanBinder True) = "true"
197137prettyPrintBinderAtom (BooleanBinder False) = "false"
198138prettyPrintBinderAtom (VarBinder ident) = showIdent ident
199−prettyPrintBinderAtom (ConstructorBinder ctor []) = showQualified runProperName ctor
139+prettyPrintBinderAtom (ConstructorBinder ctor []) = runProperName (disqualify ctor)
200140prettyPrintBinderAtom (ObjectBinder bs) =
201141 "{ "
202142 ++ intercalate ", " (map prettyPrintObjectPropertyBinder bs)
@@ -216,7 +156,7 @@ prettyPrintBinderAtom b = parens (prettyPrintBinder b)
216156-- Generate a pretty-printed string representing a Binder
217157--
218158prettyPrintBinder :: Binder -> String
219−prettyPrintBinder (ConstructorBinder ctor []) = showQualified runProperName ctor
220−prettyPrintBinder (ConstructorBinder ctor args) = showQualified runProperName ctor ++ " " ++ unwords (map prettyPrintBinderAtom args)
159+prettyPrintBinder (ConstructorBinder ctor []) = runProperName (disqualify ctor)
160+prettyPrintBinder (ConstructorBinder ctor args) = runProperName (disqualify ctor) ++ " " ++ unwords (map prettyPrintBinderAtom args)
221161prettyPrintBinder (PositionedBinder _ _ binder) = prettyPrintBinder binder
222162prettyPrintBinder b = prettyPrintBinderAtom b
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 ()