-
Notifications
You must be signed in to change notification settings - Fork 562
/
Errors.hs
2077 lines (1924 loc) · 104 KB
/
Errors.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE DeriveAnyClass #-}
module Language.PureScript.Errors
( module Language.PureScript.AST
, module Language.PureScript.Errors
) where
import Prelude
import Protolude (unsnoc)
import Control.Arrow ((&&&))
import Control.DeepSeq (NFData)
import Control.Lens (both, head1, over)
import Control.Monad (forM, unless)
import Control.Monad.Error.Class (MonadError(..))
import Control.Monad.Trans.State.Lazy (State, evalState, get, put)
import Control.Monad.Writer (Last(..), MonadWriter(..), censor)
import Data.Bifunctor (first, second)
import Data.Bitraversable (bitraverse)
import Data.Char (isSpace)
import Data.Containers.ListUtils (nubOrdOn)
import Data.Either (partitionEithers)
import Data.Foldable (fold)
import Data.Function (on)
import Data.Functor (($>))
import Data.Functor.Identity (Identity(..))
import Data.List (transpose, nubBy, partition, dropWhileEnd, sortOn, uncons)
import Data.List.NonEmpty qualified as NEL
import Data.List.NonEmpty (NonEmpty((:|)))
import Data.Maybe (maybeToList, fromMaybe, isJust, mapMaybe)
import Data.Map qualified as M
import Data.Ord (Down(..))
import Data.Set qualified as S
import Data.Text qualified as T
import Data.Text (Text)
import Data.Traversable (for)
import GHC.Generics (Generic)
import GHC.Stack qualified
import Language.PureScript.AST
import Language.PureScript.Bundle qualified as Bundle
import Language.PureScript.Constants.Libs qualified as C
import Language.PureScript.Constants.Prim qualified as C
import Language.PureScript.Crash (internalError)
import Language.PureScript.CST.Errors qualified as CST
import Language.PureScript.CST.Print qualified as CST
import Language.PureScript.Label (Label(..))
import Language.PureScript.Names
import Language.PureScript.Pretty (prettyPrintBinderAtom, prettyPrintLabel, prettyPrintObjectKey, prettyPrintSuggestedType, prettyPrintValue, typeAsBox, typeAtomAsBox, typeDiffAsBox)
import Language.PureScript.Pretty.Common (endWith)
import Language.PureScript.PSString (decodeStringWithReplacement)
import Language.PureScript.Roles (Role, displayRole)
import Language.PureScript.Traversals (sndM)
import Language.PureScript.Types (Constraint(..), ConstraintData(..), RowListItem(..), SourceConstraint, SourceType, Type(..), eraseForAllKindAnnotations, eraseKindApps, everywhereOnTypesTopDownM, getAnnForType, isMonoType, overConstraintArgs, rowFromList, rowToList, srcTUnknown)
import Language.PureScript.Publish.BoxesHelpers qualified as BoxHelpers
import System.Console.ANSI qualified as ANSI
import System.FilePath (makeRelative)
import Text.PrettyPrint.Boxes qualified as Box
import Witherable (wither)
-- | A type of error messages
data SimpleErrorMessage
= InternalCompilerError Text Text
| ModuleNotFound ModuleName
| ErrorParsingFFIModule FilePath (Maybe Bundle.ErrorMessage)
| ErrorParsingCSTModule CST.ParserError
| WarningParsingCSTModule CST.ParserWarning
| MissingFFIModule ModuleName
| UnnecessaryFFIModule ModuleName FilePath
| MissingFFIImplementations ModuleName [Ident]
| UnusedFFIImplementations ModuleName [Ident]
| InvalidFFIIdentifier ModuleName Text
| DeprecatedFFIPrime ModuleName Text
| DeprecatedFFICommonJSModule ModuleName FilePath
| UnsupportedFFICommonJSExports ModuleName [Text]
| UnsupportedFFICommonJSImports ModuleName [Text]
| FileIOError Text Text -- ^ A description of what we were trying to do, and the error which occurred
| InfiniteType SourceType
| InfiniteKind SourceType
| MultipleValueOpFixities (OpName 'ValueOpName)
| MultipleTypeOpFixities (OpName 'TypeOpName)
| OrphanTypeDeclaration Ident
| OrphanKindDeclaration (ProperName 'TypeName)
| OrphanRoleDeclaration (ProperName 'TypeName)
| RedefinedIdent Ident
| OverlappingNamesInLet Ident
| UnknownName (Qualified Name)
| UnknownImport ModuleName Name
| UnknownImportDataConstructor ModuleName (ProperName 'TypeName) (ProperName 'ConstructorName)
| UnknownExport Name
| UnknownExportDataConstructor (ProperName 'TypeName) (ProperName 'ConstructorName)
| ScopeConflict Name [ModuleName]
| ScopeShadowing Name (Maybe ModuleName) [ModuleName]
| DeclConflict Name Name
| ExportConflict (Qualified Name) (Qualified Name)
| DuplicateModule ModuleName
| DuplicateTypeClass (ProperName 'ClassName) SourceSpan
| DuplicateInstance Ident SourceSpan
| DuplicateTypeArgument Text
| InvalidDoBind
| InvalidDoLet
| CycleInDeclaration Ident
| CycleInTypeSynonym (NEL.NonEmpty (ProperName 'TypeName))
| CycleInTypeClassDeclaration (NEL.NonEmpty (Qualified (ProperName 'ClassName)))
| CycleInKindDeclaration (NEL.NonEmpty (Qualified (ProperName 'TypeName)))
| CycleInModules (NEL.NonEmpty ModuleName)
| NameIsUndefined Ident
| UndefinedTypeVariable (ProperName 'TypeName)
| PartiallyAppliedSynonym (Qualified (ProperName 'TypeName))
| EscapedSkolem Text (Maybe SourceSpan) SourceType
| TypesDoNotUnify SourceType SourceType
| KindsDoNotUnify SourceType SourceType
| ConstrainedTypeUnified SourceType SourceType
| OverlappingInstances (Qualified (ProperName 'ClassName)) [SourceType] [Qualified (Either SourceType Ident)]
| NoInstanceFound
SourceConstraint -- ^ constraint that could not be solved
[Qualified (Either SourceType Ident)] -- ^ a list of instances that stopped further progress in instance chains due to ambiguity
UnknownsHint -- ^ whether eliminating unknowns with annotations might help or if visible type applications are required
| AmbiguousTypeVariables SourceType [(Text, Int)]
| UnknownClass (Qualified (ProperName 'ClassName))
| PossiblyInfiniteInstance (Qualified (ProperName 'ClassName)) [SourceType]
| PossiblyInfiniteCoercibleInstance
| CannotDerive (Qualified (ProperName 'ClassName)) [SourceType]
| InvalidDerivedInstance (Qualified (ProperName 'ClassName)) [SourceType] Int
| ExpectedTypeConstructor (Qualified (ProperName 'ClassName)) [SourceType] SourceType
| InvalidNewtypeInstance (Qualified (ProperName 'ClassName)) [SourceType]
| MissingNewtypeSuperclassInstance (Qualified (ProperName 'ClassName)) (Qualified (ProperName 'ClassName)) [SourceType]
| UnverifiableSuperclassInstance (Qualified (ProperName 'ClassName)) (Qualified (ProperName 'ClassName)) [SourceType]
| CannotFindDerivingType (ProperName 'TypeName)
| DuplicateLabel Label (Maybe Expr)
| DuplicateValueDeclaration Ident
| ArgListLengthsDiffer Ident
| OverlappingArgNames (Maybe Ident)
| MissingClassMember (NEL.NonEmpty (Ident, SourceType))
| ExtraneousClassMember Ident (Qualified (ProperName 'ClassName))
| ExpectedType SourceType SourceType
-- | constructor name, expected argument count, actual argument count
| IncorrectConstructorArity (Qualified (ProperName 'ConstructorName)) Int Int
| ExprDoesNotHaveType Expr SourceType
| PropertyIsMissing Label
| AdditionalProperty Label
| OrphanInstance Ident (Qualified (ProperName 'ClassName)) (S.Set ModuleName) [SourceType]
| InvalidNewtype (ProperName 'TypeName)
| InvalidInstanceHead SourceType
| TransitiveExportError DeclarationRef [DeclarationRef]
| TransitiveDctorExportError DeclarationRef [ProperName 'ConstructorName]
| HiddenConstructors DeclarationRef (Qualified (ProperName 'ClassName))
| ShadowedName Ident
| ShadowedTypeVar Text
| UnusedTypeVar Text
| UnusedName Ident
| UnusedDeclaration Ident
| WildcardInferredType SourceType Context
| HoleInferredType Text SourceType Context (Maybe TypeSearch)
| MissingTypeDeclaration Ident SourceType
| MissingKindDeclaration KindSignatureFor (ProperName 'TypeName) SourceType
| OverlappingPattern [[Binder]] Bool
| IncompleteExhaustivityCheck
| ImportHidingModule ModuleName
| UnusedImport ModuleName (Maybe ModuleName)
| UnusedExplicitImport ModuleName [Name] (Maybe ModuleName) [DeclarationRef]
| UnusedDctorImport ModuleName (ProperName 'TypeName) (Maybe ModuleName) [DeclarationRef]
| UnusedDctorExplicitImport ModuleName (ProperName 'TypeName) [ProperName 'ConstructorName] (Maybe ModuleName) [DeclarationRef]
| DuplicateSelectiveImport ModuleName
| DuplicateImport ModuleName ImportDeclarationType (Maybe ModuleName)
| DuplicateImportRef Name
| DuplicateExportRef Name
| IntOutOfRange Integer Text Integer Integer
| ImplicitQualifiedImport ModuleName ModuleName [DeclarationRef]
| ImplicitQualifiedImportReExport ModuleName ModuleName [DeclarationRef]
| ImplicitImport ModuleName [DeclarationRef]
| HidingImport ModuleName [DeclarationRef]
| CaseBinderLengthDiffers Int [Binder]
| IncorrectAnonymousArgument
| InvalidOperatorInBinder (Qualified (OpName 'ValueOpName)) (Qualified Ident)
| CannotGeneralizeRecursiveFunction Ident SourceType
| CannotDeriveNewtypeForData (ProperName 'TypeName)
| ExpectedWildcard (ProperName 'TypeName)
| CannotUseBindWithDo Ident
-- | instance name, type class, expected argument count, actual argument count
| ClassInstanceArityMismatch Ident (Qualified (ProperName 'ClassName)) Int Int
-- | a user-defined warning raised by using the Warn type class
| UserDefinedWarning SourceType
| CannotDefinePrimModules ModuleName
| MixedAssociativityError (NEL.NonEmpty (Qualified (OpName 'AnyOpName), Associativity))
| NonAssociativeError (NEL.NonEmpty (Qualified (OpName 'AnyOpName)))
| QuantificationCheckFailureInKind Text
| QuantificationCheckFailureInType [Int] SourceType
| VisibleQuantificationCheckFailureInType Text
| UnsupportedTypeInKind SourceType
-- | Declared role was more permissive than inferred.
| RoleMismatch
Text -- ^ Type variable in question
Role -- ^ inferred role
Role -- ^ declared role
| InvalidCoercibleInstanceDeclaration [SourceType]
| UnsupportedRoleDeclaration
| RoleDeclarationArityMismatch (ProperName 'TypeName) Int Int
| DuplicateRoleDeclaration (ProperName 'TypeName)
| CannotDeriveInvalidConstructorArg (Qualified (ProperName 'ClassName)) [Qualified (ProperName 'ClassName)] Bool
| CannotSkipTypeApplication SourceType
| CannotApplyExpressionOfTypeOnType SourceType SourceType
deriving (Show, Generic, NFData)
data ErrorMessage = ErrorMessage
[ErrorMessageHint]
SimpleErrorMessage
deriving (Show, Generic, NFData)
newtype ErrorSuggestion = ErrorSuggestion Text
-- | Get the source span for an error
errorSpan :: ErrorMessage -> Maybe (NEL.NonEmpty SourceSpan)
errorSpan = findHint matchPE <> findHint matchRP
where
matchPE (PositionedError sss) = Just sss
matchPE _ = Nothing
matchRP (RelatedPositions sss) = Just sss
matchRP _ = Nothing
-- | Get the module name for an error
errorModule :: ErrorMessage -> Maybe ModuleName
errorModule = findHint matchModule
where
matchModule (ErrorInModule mn) = Just mn
matchModule _ = Nothing
findHint :: (ErrorMessageHint -> Maybe a) -> ErrorMessage -> Maybe a
findHint f (ErrorMessage hints _) = getLast . foldMap (Last . f) $ hints
-- | Remove the module name and span hints from an error
stripModuleAndSpan :: ErrorMessage -> ErrorMessage
stripModuleAndSpan (ErrorMessage hints e) = ErrorMessage (filter (not . shouldStrip) hints) e
where
shouldStrip (ErrorInModule _) = True
shouldStrip (PositionedError _) = True
shouldStrip _ = False
-- | Get the error code for a particular error type
errorCode :: ErrorMessage -> Text
errorCode em = case unwrapErrorMessage em of
InternalCompilerError{} -> "InternalCompilerError"
ModuleNotFound{} -> "ModuleNotFound"
ErrorParsingFFIModule{} -> "ErrorParsingFFIModule"
ErrorParsingCSTModule{} -> "ErrorParsingModule"
WarningParsingCSTModule{} -> "WarningParsingModule"
MissingFFIModule{} -> "MissingFFIModule"
UnnecessaryFFIModule{} -> "UnnecessaryFFIModule"
MissingFFIImplementations{} -> "MissingFFIImplementations"
UnusedFFIImplementations{} -> "UnusedFFIImplementations"
InvalidFFIIdentifier{} -> "InvalidFFIIdentifier"
DeprecatedFFIPrime{} -> "DeprecatedFFIPrime"
DeprecatedFFICommonJSModule {} -> "DeprecatedFFICommonJSModule"
UnsupportedFFICommonJSExports {} -> "UnsupportedFFICommonJSExports"
UnsupportedFFICommonJSImports {} -> "UnsupportedFFICommonJSImports"
FileIOError{} -> "FileIOError"
InfiniteType{} -> "InfiniteType"
InfiniteKind{} -> "InfiniteKind"
MultipleValueOpFixities{} -> "MultipleValueOpFixities"
MultipleTypeOpFixities{} -> "MultipleTypeOpFixities"
OrphanTypeDeclaration{} -> "OrphanTypeDeclaration"
OrphanKindDeclaration{} -> "OrphanKindDeclaration"
OrphanRoleDeclaration{} -> "OrphanRoleDeclaration"
RedefinedIdent{} -> "RedefinedIdent"
OverlappingNamesInLet{} -> "OverlappingNamesInLet"
UnknownName{} -> "UnknownName"
UnknownImport{} -> "UnknownImport"
UnknownImportDataConstructor{} -> "UnknownImportDataConstructor"
UnknownExport{} -> "UnknownExport"
UnknownExportDataConstructor{} -> "UnknownExportDataConstructor"
ScopeConflict{} -> "ScopeConflict"
ScopeShadowing{} -> "ScopeShadowing"
DeclConflict{} -> "DeclConflict"
ExportConflict{} -> "ExportConflict"
DuplicateModule{} -> "DuplicateModule"
DuplicateTypeClass{} -> "DuplicateTypeClass"
DuplicateInstance{} -> "DuplicateInstance"
DuplicateTypeArgument{} -> "DuplicateTypeArgument"
InvalidDoBind -> "InvalidDoBind"
InvalidDoLet -> "InvalidDoLet"
CycleInDeclaration{} -> "CycleInDeclaration"
CycleInTypeSynonym{} -> "CycleInTypeSynonym"
CycleInTypeClassDeclaration{} -> "CycleInTypeClassDeclaration"
CycleInKindDeclaration{} -> "CycleInKindDeclaration"
CycleInModules{} -> "CycleInModules"
NameIsUndefined{} -> "NameIsUndefined"
UndefinedTypeVariable{} -> "UndefinedTypeVariable"
PartiallyAppliedSynonym{} -> "PartiallyAppliedSynonym"
EscapedSkolem{} -> "EscapedSkolem"
TypesDoNotUnify{} -> "TypesDoNotUnify"
KindsDoNotUnify{} -> "KindsDoNotUnify"
ConstrainedTypeUnified{} -> "ConstrainedTypeUnified"
OverlappingInstances{} -> "OverlappingInstances"
NoInstanceFound{} -> "NoInstanceFound"
AmbiguousTypeVariables{} -> "AmbiguousTypeVariables"
UnknownClass{} -> "UnknownClass"
PossiblyInfiniteInstance{} -> "PossiblyInfiniteInstance"
PossiblyInfiniteCoercibleInstance -> "PossiblyInfiniteCoercibleInstance"
CannotDerive{} -> "CannotDerive"
InvalidNewtypeInstance{} -> "InvalidNewtypeInstance"
MissingNewtypeSuperclassInstance{} -> "MissingNewtypeSuperclassInstance"
UnverifiableSuperclassInstance{} -> "UnverifiableSuperclassInstance"
InvalidDerivedInstance{} -> "InvalidDerivedInstance"
ExpectedTypeConstructor{} -> "ExpectedTypeConstructor"
CannotFindDerivingType{} -> "CannotFindDerivingType"
DuplicateLabel{} -> "DuplicateLabel"
DuplicateValueDeclaration{} -> "DuplicateValueDeclaration"
ArgListLengthsDiffer{} -> "ArgListLengthsDiffer"
OverlappingArgNames{} -> "OverlappingArgNames"
MissingClassMember{} -> "MissingClassMember"
ExtraneousClassMember{} -> "ExtraneousClassMember"
ExpectedType{} -> "ExpectedType"
IncorrectConstructorArity{} -> "IncorrectConstructorArity"
ExprDoesNotHaveType{} -> "ExprDoesNotHaveType"
PropertyIsMissing{} -> "PropertyIsMissing"
AdditionalProperty{} -> "AdditionalProperty"
OrphanInstance{} -> "OrphanInstance"
InvalidNewtype{} -> "InvalidNewtype"
InvalidInstanceHead{} -> "InvalidInstanceHead"
TransitiveExportError{} -> "TransitiveExportError"
TransitiveDctorExportError{} -> "TransitiveDctorExportError"
HiddenConstructors{} -> "HiddenConstructors"
ShadowedName{} -> "ShadowedName"
UnusedName{} -> "UnusedName"
UnusedDeclaration{} -> "UnusedDeclaration"
ShadowedTypeVar{} -> "ShadowedTypeVar"
UnusedTypeVar{} -> "UnusedTypeVar"
WildcardInferredType{} -> "WildcardInferredType"
HoleInferredType{} -> "HoleInferredType"
MissingTypeDeclaration{} -> "MissingTypeDeclaration"
MissingKindDeclaration{} -> "MissingKindDeclaration"
OverlappingPattern{} -> "OverlappingPattern"
IncompleteExhaustivityCheck{} -> "IncompleteExhaustivityCheck"
ImportHidingModule{} -> "ImportHidingModule"
UnusedImport{} -> "UnusedImport"
UnusedExplicitImport{} -> "UnusedExplicitImport"
UnusedDctorImport{} -> "UnusedDctorImport"
UnusedDctorExplicitImport{} -> "UnusedDctorExplicitImport"
DuplicateSelectiveImport{} -> "DuplicateSelectiveImport"
DuplicateImport{} -> "DuplicateImport"
DuplicateImportRef{} -> "DuplicateImportRef"
DuplicateExportRef{} -> "DuplicateExportRef"
IntOutOfRange{} -> "IntOutOfRange"
ImplicitQualifiedImport{} -> "ImplicitQualifiedImport"
ImplicitQualifiedImportReExport{} -> "ImplicitQualifiedImportReExport"
ImplicitImport{} -> "ImplicitImport"
HidingImport{} -> "HidingImport"
CaseBinderLengthDiffers{} -> "CaseBinderLengthDiffers"
IncorrectAnonymousArgument -> "IncorrectAnonymousArgument"
InvalidOperatorInBinder{} -> "InvalidOperatorInBinder"
CannotGeneralizeRecursiveFunction{} -> "CannotGeneralizeRecursiveFunction"
CannotDeriveNewtypeForData{} -> "CannotDeriveNewtypeForData"
ExpectedWildcard{} -> "ExpectedWildcard"
CannotUseBindWithDo{} -> "CannotUseBindWithDo"
ClassInstanceArityMismatch{} -> "ClassInstanceArityMismatch"
UserDefinedWarning{} -> "UserDefinedWarning"
CannotDefinePrimModules{} -> "CannotDefinePrimModules"
MixedAssociativityError{} -> "MixedAssociativityError"
NonAssociativeError{} -> "NonAssociativeError"
QuantificationCheckFailureInKind {} -> "QuantificationCheckFailureInKind"
QuantificationCheckFailureInType {} -> "QuantificationCheckFailureInType"
VisibleQuantificationCheckFailureInType {} -> "VisibleQuantificationCheckFailureInType"
UnsupportedTypeInKind {} -> "UnsupportedTypeInKind"
RoleMismatch {} -> "RoleMismatch"
InvalidCoercibleInstanceDeclaration {} -> "InvalidCoercibleInstanceDeclaration"
UnsupportedRoleDeclaration {} -> "UnsupportedRoleDeclaration"
RoleDeclarationArityMismatch {} -> "RoleDeclarationArityMismatch"
DuplicateRoleDeclaration {} -> "DuplicateRoleDeclaration"
CannotDeriveInvalidConstructorArg{} -> "CannotDeriveInvalidConstructorArg"
CannotSkipTypeApplication{} -> "CannotSkipTypeApplication"
CannotApplyExpressionOfTypeOnType{} -> "CannotApplyExpressionOfTypeOnType"
-- | A stack trace for an error
newtype MultipleErrors = MultipleErrors
{ runMultipleErrors :: [ErrorMessage]
}
deriving stock (Show)
deriving newtype (Semigroup, Monoid, NFData)
-- | Check whether a collection of errors is empty or not.
nonEmpty :: MultipleErrors -> Bool
nonEmpty = not . null . runMultipleErrors
-- | Create an error set from a single simple error message
errorMessage :: SimpleErrorMessage -> MultipleErrors
errorMessage err = MultipleErrors [ErrorMessage [] err]
-- | Create an error set from a single simple error message and source annotation
errorMessage' :: SourceSpan -> SimpleErrorMessage -> MultipleErrors
errorMessage' ss err = MultipleErrors [ErrorMessage [positionedError ss] err]
-- | Create an error set from a single simple error message and source annotations
errorMessage'' :: NEL.NonEmpty SourceSpan -> SimpleErrorMessage -> MultipleErrors
errorMessage'' sss err = MultipleErrors [ErrorMessage [PositionedError sss] err]
-- | Create an error from multiple (possibly empty) source spans, reversed sorted.
errorMessage''' :: [SourceSpan] -> SimpleErrorMessage -> MultipleErrors
errorMessage''' sss err =
maybe (errorMessage err) (flip errorMessage'' err)
. NEL.nonEmpty
. sortOn Down
$ filter (/= NullSourceSpan) sss
-- | Create an error set from a single error message
singleError :: ErrorMessage -> MultipleErrors
singleError = MultipleErrors . pure
-- | Lift a function on ErrorMessage to a function on MultipleErrors
onErrorMessages :: (ErrorMessage -> ErrorMessage) -> MultipleErrors -> MultipleErrors
onErrorMessages f = MultipleErrors . map f . runMultipleErrors
-- | Add a hint to an error message
addHint :: ErrorMessageHint -> MultipleErrors -> MultipleErrors
addHint hint = addHints [hint]
-- | Add hints to an error message
addHints :: [ErrorMessageHint] -> MultipleErrors -> MultipleErrors
addHints hints = onErrorMessages $ \(ErrorMessage hints' se) -> ErrorMessage (hints ++ hints') se
-- | A map from rigid type variable name/unknown variable pairs to new variables.
data TypeMap = TypeMap
{ umSkolemMap :: M.Map Int (String, Int, Maybe SourceSpan)
-- ^ a map from skolems to their new names, including source and naming info
, umUnknownMap :: M.Map Int Int
-- ^ a map from unification variables to their new names
, umNextIndex :: Int
-- ^ unknowns and skolems share a source of names during renaming, to
-- avoid overlaps in error messages. This is the next label for either case.
} deriving Show
defaultUnknownMap :: TypeMap
defaultUnknownMap = TypeMap M.empty M.empty 0
-- | How critical the issue is
data Level = Error | Warning deriving Show
-- | Extract nested error messages from wrapper errors
unwrapErrorMessage :: ErrorMessage -> SimpleErrorMessage
unwrapErrorMessage (ErrorMessage _ se) = se
replaceUnknowns :: SourceType -> State TypeMap SourceType
replaceUnknowns = everywhereOnTypesTopDownM replaceTypes where
replaceTypes :: SourceType -> State TypeMap SourceType
replaceTypes (TUnknown ann u) = do
m <- get
case M.lookup u (umUnknownMap m) of
Nothing -> do
let u' = umNextIndex m
put $ m { umUnknownMap = M.insert u u' (umUnknownMap m), umNextIndex = u' + 1 }
return (TUnknown ann u')
Just u' -> return (TUnknown ann u')
-- We intentionally remove the kinds from skolems, because they are never
-- presented when pretty-printing. Any unknowns in those kinds shouldn't
-- appear in the list of unknowns unless used somewhere else.
replaceTypes (Skolem ann name _ s sko) = do
m <- get
case M.lookup s (umSkolemMap m) of
Nothing -> do
let s' = umNextIndex m
put $ m { umSkolemMap = M.insert s (T.unpack name, s', Just (fst ann)) (umSkolemMap m), umNextIndex = s' + 1 }
return (Skolem ann name Nothing s' sko)
Just (_, s', _) -> return (Skolem ann name Nothing s' sko)
replaceTypes other = return other
onTypesInErrorMessage :: (SourceType -> SourceType) -> ErrorMessage -> ErrorMessage
onTypesInErrorMessage f = runIdentity . onTypesInErrorMessageM (Identity . f)
onTypesInErrorMessageM :: Applicative m => (SourceType -> m SourceType) -> ErrorMessage -> m ErrorMessage
onTypesInErrorMessageM f (ErrorMessage hints simple) = ErrorMessage <$> traverse gHint hints <*> gSimple simple
where
gSimple (InfiniteType t) = InfiniteType <$> f t
gSimple (TypesDoNotUnify t1 t2) = TypesDoNotUnify <$> f t1 <*> f t2
gSimple (ConstrainedTypeUnified t1 t2) = ConstrainedTypeUnified <$> f t1 <*> f t2
gSimple (ExprDoesNotHaveType e t) = ExprDoesNotHaveType e <$> f t
gSimple (InvalidInstanceHead t) = InvalidInstanceHead <$> f t
gSimple (NoInstanceFound con ambig unks) = NoInstanceFound <$> overConstraintArgs (traverse f) con <*> pure ambig <*> pure unks
gSimple (AmbiguousTypeVariables t uis) = AmbiguousTypeVariables <$> f t <*> pure uis
gSimple (OverlappingInstances cl ts insts) = OverlappingInstances cl <$> traverse f ts <*> traverse (traverse $ bitraverse f pure) insts
gSimple (PossiblyInfiniteInstance cl ts) = PossiblyInfiniteInstance cl <$> traverse f ts
gSimple (CannotDerive cl ts) = CannotDerive cl <$> traverse f ts
gSimple (InvalidNewtypeInstance cl ts) = InvalidNewtypeInstance cl <$> traverse f ts
gSimple (MissingNewtypeSuperclassInstance cl1 cl2 ts) = MissingNewtypeSuperclassInstance cl1 cl2 <$> traverse f ts
gSimple (UnverifiableSuperclassInstance cl1 cl2 ts) = UnverifiableSuperclassInstance cl1 cl2 <$> traverse f ts
gSimple (InvalidDerivedInstance cl ts n) = InvalidDerivedInstance cl <$> traverse f ts <*> pure n
gSimple (ExpectedTypeConstructor cl ts ty) = ExpectedTypeConstructor cl <$> traverse f ts <*> f ty
gSimple (ExpectedType ty k) = ExpectedType <$> f ty <*> pure k
gSimple (OrphanInstance nm cl noms ts) = OrphanInstance nm cl noms <$> traverse f ts
gSimple (WildcardInferredType ty ctx) = WildcardInferredType <$> f ty <*> traverse (sndM f) ctx
gSimple (HoleInferredType name ty ctx env) = HoleInferredType name <$> f ty <*> traverse (sndM f) ctx <*> traverse (onTypeSearchTypesM f) env
gSimple (MissingTypeDeclaration nm ty) = MissingTypeDeclaration nm <$> f ty
gSimple (MissingKindDeclaration sig nm ty) = MissingKindDeclaration sig nm <$> f ty
gSimple (CannotGeneralizeRecursiveFunction nm ty) = CannotGeneralizeRecursiveFunction nm <$> f ty
gSimple (InvalidCoercibleInstanceDeclaration tys) = InvalidCoercibleInstanceDeclaration <$> traverse f tys
gSimple other = pure other
gHint (ErrorInSubsumption t1 t2) = ErrorInSubsumption <$> f t1 <*> f t2
gHint (ErrorUnifyingTypes t1 t2) = ErrorUnifyingTypes <$> f t1 <*> f t2
gHint (ErrorCheckingType e t) = ErrorCheckingType e <$> f t
gHint (ErrorCheckingKind t k) = ErrorCheckingKind <$> f t <*> f k
gHint (ErrorInferringKind t) = ErrorInferringKind <$> f t
gHint (ErrorInApplication e1 t1 e2) = ErrorInApplication e1 <$> f t1 <*> pure e2
gHint (ErrorInInstance cl ts) = ErrorInInstance cl <$> traverse f ts
gHint (ErrorSolvingConstraint con) = ErrorSolvingConstraint <$> overConstraintArgs (traverse f) con
gHint other = pure other
errorDocUri :: ErrorMessage -> Text
errorDocUri e = "https://github.com/purescript/documentation/blob/master/errors/" <> errorCode e <> ".md"
-- TODO Other possible suggestions:
-- WildcardInferredType - source span not small enough
-- DuplicateSelectiveImport - would require 2 ranges to remove and 1 insert
errorSuggestion :: SimpleErrorMessage -> Maybe ErrorSuggestion
errorSuggestion err =
case err of
UnusedImport{} -> emptySuggestion
DuplicateImport{} -> emptySuggestion
UnusedExplicitImport mn _ qual refs -> suggest $ importSuggestion mn refs qual
UnusedDctorImport mn _ qual refs -> suggest $ importSuggestion mn refs qual
UnusedDctorExplicitImport mn _ _ qual refs -> suggest $ importSuggestion mn refs qual
ImplicitImport mn refs -> suggest $ importSuggestion mn refs Nothing
ImplicitQualifiedImport mn asModule refs -> suggest $ importSuggestion mn refs (Just asModule)
ImplicitQualifiedImportReExport mn asModule refs -> suggest $ importSuggestion mn refs (Just asModule)
HidingImport mn refs -> suggest $ importSuggestion mn refs Nothing
MissingTypeDeclaration ident ty -> suggest $ showIdent ident <> " :: " <> T.pack (prettyPrintSuggestedTypeSimplified ty) <> "\n"
MissingKindDeclaration sig name ty -> suggest $ prettyPrintKindSignatureFor sig <> " " <> runProperName name <> " :: " <> T.pack (prettyPrintSuggestedTypeSimplified ty) <> "\n"
WildcardInferredType ty _ -> suggest $ T.pack (prettyPrintSuggestedTypeSimplified ty)
WarningParsingCSTModule pe -> do
let toks = CST.errToks pe
case CST.errType pe of
CST.WarnDeprecatedRowSyntax -> do
let kind = CST.printTokens $ drop 1 toks
sugg | " " `T.isPrefixOf` kind = "Row" <> kind
| otherwise = "Row " <> kind
suggest sugg
CST.WarnDeprecatedForeignKindSyntax -> suggest $ "data " <> CST.printTokens (drop 3 toks)
CST.WarnDeprecatedKindImportSyntax -> suggest $ CST.printTokens $ drop 1 toks
CST.WarnDeprecatedKindExportSyntax -> suggest $ CST.printTokens $ drop 1 toks
CST.WarnDeprecatedCaseOfOffsideSyntax -> Nothing
_ -> Nothing
where
emptySuggestion = Just $ ErrorSuggestion ""
suggest = Just . ErrorSuggestion
importSuggestion :: ModuleName -> [ DeclarationRef ] -> Maybe ModuleName -> Text
importSuggestion mn refs qual =
"import " <> runModuleName mn <> " (" <> T.intercalate ", " (mapMaybe prettyPrintRef refs) <> ")" <> qstr qual
qstr :: Maybe ModuleName -> Text
qstr (Just mn) = " as " <> runModuleName mn
qstr Nothing = ""
suggestionSpan :: ErrorMessage -> Maybe SourceSpan
suggestionSpan e =
-- The `NEL.head` is a bit arbitrary here, but I don't think we'll
-- have errors-with-suggestions that also have multiple source
-- spans. -garyb
getSpan (unwrapErrorMessage e) . NEL.head <$> errorSpan e
where
startOnly SourceSpan{spanName, spanStart} = SourceSpan {spanName, spanStart, spanEnd = spanStart}
getSpan simple ss =
case simple of
MissingTypeDeclaration{} -> startOnly ss
MissingKindDeclaration{} -> startOnly ss
_ -> ss
showSuggestion :: SimpleErrorMessage -> Text
showSuggestion suggestion = case errorSuggestion suggestion of
Just (ErrorSuggestion x) -> x
_ -> ""
ansiColor :: (ANSI.ColorIntensity, ANSI.Color) -> String
ansiColor (intensity, color) =
ANSI.setSGRCode [ANSI.SetColor ANSI.Foreground intensity color]
ansiColorReset :: String
ansiColorReset =
ANSI.setSGRCode [ANSI.Reset]
colorCode :: Maybe (ANSI.ColorIntensity, ANSI.Color) -> Text -> Text
colorCode codeColor code = case codeColor of
Nothing -> code
Just cc -> T.pack (ansiColor cc) <> code <> T.pack ansiColorReset
colorCodeBox :: Maybe (ANSI.ColorIntensity, ANSI.Color) -> Box.Box -> Box.Box
colorCodeBox codeColor b = case codeColor of
Nothing -> b
Just cc
| Box.rows b == 1 ->
Box.text (ansiColor cc) Box.<> b `endWith` Box.text ansiColorReset
| otherwise -> Box.hcat Box.left -- making two boxes, one for each side of the box so that it will set each row it's own color and will reset it afterwards
[ Box.vcat Box.top $ replicate (Box.rows b) $ Box.text $ ansiColor cc
, b
, Box.vcat Box.top $ replicate (Box.rows b) $ Box.text ansiColorReset
]
commasAndConjunction :: Text -> [Text] -> Text
commasAndConjunction conj = \case
[x] -> x
[x, y] -> x <> " " <> conj <> " " <> y
(unsnoc -> Just (rest, z)) -> foldMap (<> ", ") rest <> conj <> " " <> z
_ -> ""
-- | Default color intensity and color for code
defaultCodeColor :: (ANSI.ColorIntensity, ANSI.Color)
defaultCodeColor = (ANSI.Dull, ANSI.Yellow)
-- | `prettyPrintSingleError` Options
data PPEOptions = PPEOptions
{ ppeCodeColor :: Maybe (ANSI.ColorIntensity, ANSI.Color) -- ^ Color code with this color... or not
, ppeFull :: Bool -- ^ Should write a full error message?
, ppeLevel :: Level -- ^ Should this report an error or a warning?
, ppeShowDocs :: Bool -- ^ Should show a link to error message's doc page?
, ppeRelativeDirectory :: FilePath -- ^ FilePath to which the errors are relative
, ppeFileContents :: [(FilePath, Text)] -- ^ Unparsed contents of source files
}
-- | Default options for PPEOptions
defaultPPEOptions :: PPEOptions
defaultPPEOptions = PPEOptions
{ ppeCodeColor = Just defaultCodeColor
, ppeFull = False
, ppeLevel = Error
, ppeShowDocs = True
, ppeRelativeDirectory = mempty
, ppeFileContents = []
}
-- | Pretty print a single error, simplifying if necessary
prettyPrintSingleError :: PPEOptions -> ErrorMessage -> Box.Box
prettyPrintSingleError (PPEOptions codeColor full level showDocs relPath fileContents) e = flip evalState defaultUnknownMap $ do
em <- onTypesInErrorMessageM replaceUnknowns (if full then e else simplifyErrorMessage e)
um <- get
return (prettyPrintErrorMessage um em)
where
(markCode, markCodeBox) = (colorCode &&& colorCodeBox) codeColor
-- Pretty print an ErrorMessage
prettyPrintErrorMessage :: TypeMap -> ErrorMessage -> Box.Box
prettyPrintErrorMessage typeMap (ErrorMessage hints simple) =
paras $
[ foldr renderHint (indent (renderSimpleErrorMessage simple)) hints
] ++
maybe [] (return . Box.moveDown 1) typeInformation ++
[ Box.moveDown 1 $ paras
[ line $ "See " <> errorDocUri e <> " for more information, "
, line $ "or to contribute content related to this " <> levelText <> "."
]
| showDocs
]
where
typeInformation :: Maybe Box.Box
typeInformation | not (null types) = Just $ Box.hsep 1 Box.left [ line "where", paras types ]
| otherwise = Nothing
where
types :: [Box.Box]
types = map skolemInfo (M.elems (umSkolemMap typeMap)) ++
map unknownInfo (M.elems (umUnknownMap typeMap))
skolemInfo :: (String, Int, Maybe SourceSpan) -> Box.Box
skolemInfo (name, s, ss) =
paras $
line (markCode (T.pack (name <> show s)) <> " is a rigid type variable")
: foldMap (return . line . (" bound at " <>) . displayStartEndPos) ss
unknownInfo :: Int -> Box.Box
unknownInfo u = line $ markCode ("t" <> T.pack (show u)) <> " is an unknown type"
renderSimpleErrorMessage :: SimpleErrorMessage -> Box.Box
renderSimpleErrorMessage (InternalCompilerError ctx err) =
paras [ line "Internal compiler error:"
, indent $ line err
, line ctx
, line "Please report this at https://github.com/purescript/purescript/issues"
]
renderSimpleErrorMessage (ModuleNotFound mn) =
paras [ line $ "Module " <> markCode (runModuleName mn) <> " was not found."
, line $
if isBuiltinModuleName mn
then
"Module names in the Prim namespace are reserved for built-in modules, but this version of the compiler does not provide module " <> markCode (runModuleName mn) <> ". You may be able to fix this by updating your compiler to a newer version."
else
"Make sure the source file exists, and that it has been provided as an input to the compiler."
]
renderSimpleErrorMessage (FileIOError doWhat err) =
paras [ line $ "I/O error while trying to " <> doWhat
, indent . line $ err
]
renderSimpleErrorMessage (ErrorParsingFFIModule path extra) =
paras $ [ line "Unable to parse foreign module:"
, indent . lineS $ path
] ++
map (indent . lineS) (concatMap Bundle.printErrorMessage (maybeToList extra))
renderSimpleErrorMessage (ErrorParsingCSTModule err) =
paras [ line "Unable to parse module: "
, line $ T.pack $ CST.prettyPrintErrorMessage err
]
renderSimpleErrorMessage (WarningParsingCSTModule err) =
paras [ line $ T.pack $ CST.prettyPrintWarningMessage err
]
renderSimpleErrorMessage (MissingFFIModule mn) =
line $ "The foreign module implementation for module " <> markCode (runModuleName mn) <> " is missing."
renderSimpleErrorMessage (UnnecessaryFFIModule mn path) =
paras [ line $ "An unnecessary foreign module implementation was provided for module " <> markCode (runModuleName mn) <> ": "
, indent . lineS $ path
, line $ "Module " <> markCode (runModuleName mn) <> " does not contain any foreign import declarations, so a foreign module is not necessary."
]
renderSimpleErrorMessage (MissingFFIImplementations mn idents) =
paras [ line $ "The following values are not defined in the foreign module for module " <> markCode (runModuleName mn) <> ": "
, indent . paras $ map (line . runIdent) idents
]
renderSimpleErrorMessage (UnusedFFIImplementations mn idents) =
paras [ line $ "The following definitions in the foreign module for module " <> markCode (runModuleName mn) <> " are unused: "
, indent . paras $ map (line . runIdent) idents
]
renderSimpleErrorMessage (InvalidFFIIdentifier mn ident) =
paras [ line $ "In the FFI module for " <> markCode (runModuleName mn) <> ":"
, indent . paras $
[ line $ "The identifier " <> markCode ident <> " is not valid in PureScript."
, line "Note that exported identifiers in FFI modules must be valid PureScript identifiers."
]
]
renderSimpleErrorMessage (DeprecatedFFIPrime mn ident) =
paras [ line $ "In the FFI module for " <> markCode (runModuleName mn) <> ":"
, indent . paras $
[ line $ "The identifier " <> markCode ident <> " contains a prime (" <> markCode "'" <> ")."
, line "Primes are not allowed in identifiers exported from FFI modules."
]
]
renderSimpleErrorMessage (DeprecatedFFICommonJSModule mn path) =
paras [ line $ "A CommonJS foreign module implementation was provided for module " <> markCode (runModuleName mn) <> ": "
, indent . lineS $ path
, line "CommonJS foreign modules are no longer supported. Use native JavaScript/ECMAScript module syntax instead."
]
renderSimpleErrorMessage (UnsupportedFFICommonJSExports mn idents) =
paras [ line $ "The following CommonJS exports are not supported in the ES foreign module for module " <> markCode (runModuleName mn) <> ": "
, indent . paras $ map line idents
]
renderSimpleErrorMessage (UnsupportedFFICommonJSImports mn mids) =
paras [ line $ "The following CommonJS imports are not supported in the ES foreign module for module " <> markCode (runModuleName mn) <> ": "
, indent . paras $ map line mids
]
renderSimpleErrorMessage InvalidDoBind =
line "The last statement in a 'do' block must be an expression, but this block ends with a binder."
renderSimpleErrorMessage InvalidDoLet =
line "The last statement in a 'do' block must be an expression, but this block ends with a let binding."
renderSimpleErrorMessage (OverlappingNamesInLet name) =
line $ "The name " <> markCode (showIdent name) <> " was defined multiple times in a binding group"
renderSimpleErrorMessage (InfiniteType ty) =
paras [ line "An infinite type was inferred for an expression: "
, markCodeBox $ indent $ prettyType ty
]
renderSimpleErrorMessage (InfiniteKind ki) =
paras [ line "An infinite kind was inferred for a type: "
, markCodeBox $ indent $ prettyType ki
]
renderSimpleErrorMessage (MultipleValueOpFixities op) =
line $ "There are multiple fixity/precedence declarations for operator " <> markCode (showOp op)
renderSimpleErrorMessage (MultipleTypeOpFixities op) =
line $ "There are multiple fixity/precedence declarations for type operator " <> markCode (showOp op)
renderSimpleErrorMessage (OrphanTypeDeclaration nm) =
line $ "The type declaration for " <> markCode (showIdent nm) <> " should be followed by its definition."
renderSimpleErrorMessage (OrphanKindDeclaration nm) =
line $ "The kind declaration for " <> markCode (runProperName nm) <> " should be followed by its definition."
renderSimpleErrorMessage (OrphanRoleDeclaration nm) =
line $ "The role declaration for " <> markCode (runProperName nm) <> " should follow its definition."
renderSimpleErrorMessage (RedefinedIdent name) =
line $ "The value " <> markCode (showIdent name) <> " has been defined multiple times"
renderSimpleErrorMessage (UnknownName name@(Qualified (BySourcePos _) (IdentName (Ident i)))) | i `elem` [ C.S_bind, C.S_discard ] =
line $ "Unknown " <> printName name <> ". You're probably using do-notation, which the compiler replaces with calls to the " <> markCode "bind" <> " and " <> markCode "discard" <> " functions. Please import " <> markCode i <> " from module " <> markCode "Prelude"
renderSimpleErrorMessage (UnknownName name@(Qualified (BySourcePos _) (IdentName (Ident C.S_negate)))) =
line $ "Unknown " <> printName name <> ". You're probably using numeric negation (the unary " <> markCode "-" <> " operator), which the compiler replaces with calls to the " <> markCode C.S_negate <> " function. Please import " <> markCode C.S_negate <> " from module " <> markCode "Prelude"
renderSimpleErrorMessage (UnknownName name) =
line $ "Unknown " <> printName name
renderSimpleErrorMessage (UnknownImport mn name) =
paras [ line $ "Cannot import " <> printName (Qualified ByNullSourcePos name) <> " from module " <> markCode (runModuleName mn)
, line "It either does not exist or the module does not export it."
]
renderSimpleErrorMessage (UnknownImportDataConstructor mn tcon dcon) =
line $ "Module " <> runModuleName mn <> " does not export data constructor " <> markCode (runProperName dcon) <> " for type " <> markCode (runProperName tcon)
renderSimpleErrorMessage (UnknownExport name) =
line $ "Cannot export unknown " <> printName (Qualified ByNullSourcePos name)
renderSimpleErrorMessage (UnknownExportDataConstructor tcon dcon) =
line $ "Cannot export data constructor " <> markCode (runProperName dcon) <> " for type " <> markCode (runProperName tcon) <> ", as it has not been declared."
renderSimpleErrorMessage (ScopeConflict nm ms) =
paras [ line $ "Conflicting definitions are in scope for " <> printName (Qualified ByNullSourcePos nm) <> " from the following modules:"
, indent $ paras $ map (line . markCode . runModuleName) ms
]
renderSimpleErrorMessage (ScopeShadowing nm exmn ms) =
paras [ line $ "Shadowed definitions are in scope for " <> printName (Qualified ByNullSourcePos nm) <> " from the following open imports:"
, indent $ paras $ map (line . markCode . ("import " <>) . runModuleName) ms
, line $ "These will be ignored and the " <> case exmn of
Just exmn' -> "declaration from " <> markCode (runModuleName exmn') <> " will be used."
Nothing -> "local declaration will be used."
]
renderSimpleErrorMessage (DeclConflict new existing) =
line $ "Declaration for " <> printName (Qualified ByNullSourcePos new) <> " conflicts with an existing " <> nameType existing <> " of the same name."
renderSimpleErrorMessage (ExportConflict new existing) =
line $ "Export for " <> printName new <> " conflicts with " <> printName existing
renderSimpleErrorMessage (DuplicateModule mn) =
line $ "Module " <> markCode (runModuleName mn) <> " has been defined multiple times"
renderSimpleErrorMessage (DuplicateTypeClass pn ss) =
paras [ line ("Type class " <> markCode (runProperName pn) <> " has been defined multiple times:")
, indent $ line $ displaySourceSpan relPath ss
]
renderSimpleErrorMessage (DuplicateInstance pn ss) =
paras [ line ("Instance " <> markCode (showIdent pn) <> " has been defined multiple times:")
, indent $ line $ displaySourceSpan relPath ss
]
renderSimpleErrorMessage (CycleInDeclaration nm) =
line $ "The value of " <> markCode (showIdent nm) <> " is undefined here, so this reference is not allowed."
renderSimpleErrorMessage (CycleInModules mns) =
case mns of
mn :| [] ->
line $ "Module " <> markCode (runModuleName mn) <> " imports itself."
_ ->
paras [ line "There is a cycle in module dependencies in these modules: "
, indent $ paras (line . markCode . runModuleName <$> NEL.toList mns)
]
renderSimpleErrorMessage (CycleInTypeSynonym names) =
paras $ cycleError <>
[ line "Cycles are disallowed because they can lead to loops in the type checker."
, line "Consider using a 'newtype' instead."
]
where
cycleError = case names of
pn :| [] -> pure . line $ "A cycle appears in the definition of type synonym " <> markCode (runProperName pn)
_ -> [ line " A cycle appears in a set of type synonym definitions:"
, indent $ line $ "{" <> T.intercalate ", " (markCode . runProperName <$> NEL.toList names) <> "}"
]
renderSimpleErrorMessage (CycleInTypeClassDeclaration (name :| [])) =
paras [ line $ "A type class '" <> markCode (runProperName (disqualify name)) <> "' may not have itself as a superclass." ]
renderSimpleErrorMessage (CycleInTypeClassDeclaration names) =
paras [ line "A cycle appears in a set of type class definitions:"
, indent $ line $ "{" <> T.intercalate ", " (markCode . runProperName . disqualify <$> NEL.toList names) <> "}"
, line "Cycles are disallowed because they can lead to loops in the type checker."
]
renderSimpleErrorMessage (CycleInKindDeclaration (name :| [])) =
paras [ line $ "A kind declaration '" <> markCode (runProperName (disqualify name)) <> "' may not refer to itself in its own signature." ]
renderSimpleErrorMessage (CycleInKindDeclaration names) =
paras [ line "A cycle appears in a set of kind declarations:"
, indent $ line $ "{" <> T.intercalate ", " (markCode . runProperName . disqualify <$> NEL.toList names) <> "}"
, line "Kind declarations may not refer to themselves in their own signatures."
]
renderSimpleErrorMessage (NameIsUndefined ident) =
line $ "Value " <> markCode (showIdent ident) <> " is undefined."
renderSimpleErrorMessage (UndefinedTypeVariable name) =
line $ "Type variable " <> markCode (runProperName name) <> " is undefined."
renderSimpleErrorMessage (PartiallyAppliedSynonym name) =
paras [ line $ "Type synonym " <> markCode (showQualified runProperName name) <> " is partially applied."
, line "Type synonyms must be applied to all of their type arguments."
]
renderSimpleErrorMessage (EscapedSkolem name Nothing ty) =
paras [ line $ "The type variable " <> markCode name <> " has escaped its scope, appearing in the type"
, markCodeBox $ indent $ prettyType ty
]
renderSimpleErrorMessage (EscapedSkolem name (Just srcSpan) ty) =
paras [ line $ "The type variable " <> markCode name <> ", bound at"
, indent $ line $ displaySourceSpan relPath srcSpan
, line "has escaped its scope, appearing in the type"
, markCodeBox $ indent $ prettyType ty
]
renderSimpleErrorMessage (TypesDoNotUnify u1 u2)
= let (row1Box, row2Box) = printRows u1 u2
in paras [ line "Could not match type"
, row1Box
, line "with type"
, row2Box
]
renderSimpleErrorMessage (KindsDoNotUnify k1 k2) =
paras [ line "Could not match kind"
, markCodeBox $ indent $ prettyType k1
, line "with kind"
, markCodeBox $ indent $ prettyType k2
]
renderSimpleErrorMessage (ConstrainedTypeUnified t1 t2) =
paras [ line "Could not match constrained type"
, markCodeBox $ indent $ prettyType t1
, line "with type"
, markCodeBox $ indent $ prettyType t2
]
renderSimpleErrorMessage (OverlappingInstances _ _ []) = internalError "OverlappingInstances: empty instance list"
renderSimpleErrorMessage (OverlappingInstances nm ts ds) =
paras [ line "Overlapping type class instances found for"
, markCodeBox $ indent $ Box.hsep 1 Box.left
[ line (showQualified runProperName nm)
, Box.vcat Box.left (map prettyTypeAtom ts)
]
, line "The following instances were found:"
, indent $ paras (map prettyInstanceName ds)
]
renderSimpleErrorMessage (UnknownClass nm) =
paras [ line "No type class instance was found for class"
, markCodeBox $ indent $ line (showQualified runProperName nm)
, line "because the class was not in scope. Perhaps it was not exported."
]
renderSimpleErrorMessage (NoInstanceFound (Constraint _ C.Fail _ [ ty ] _) _ _) | Just box <- toTypelevelString ty =
paras [ line "Custom error:"
, indent box
]
renderSimpleErrorMessage (NoInstanceFound (Constraint _ C.Partial
_
_
(Just (PartialConstraintData bs b))) _ _) =
paras [ line "A case expression could not be determined to cover all inputs."
, line "The following additional cases are required to cover all inputs:"
, indent $ paras $
Box.hsep 1 Box.left
(map (paras . map (line . markCode)) (transpose bs))
: [line "..." | not b]
, line "Alternatively, add a Partial constraint to the type of the enclosing value."
]
renderSimpleErrorMessage (NoInstanceFound (Constraint _ C.Discard _ [ty] _) _ _) =
paras [ line "A result of type"
, markCodeBox $ indent $ prettyType ty
, line "was implicitly discarded in a do notation block."
, line ("You can use " <> markCode "_ <- ..." <> " to explicitly discard the result.")
]
renderSimpleErrorMessage (NoInstanceFound (Constraint _ nm _ ts _) ambiguous unks) =
paras $
[ line "No type class instance was found for"
, markCodeBox $ indent $ Box.hsep 1 Box.left
[ line (showQualified runProperName nm)
, Box.vcat Box.left (map prettyTypeAtom ts)
]
, paras $ let useMessage msg =
[ line msg
, indent $ paras (map prettyInstanceName ambiguous)
]
in case ambiguous of
[] -> []
[_] -> useMessage "The following instance partially overlaps the above constraint, which means the rest of its instance chain will not be considered:"
_ -> useMessage "The following instances partially overlap the above constraint, which means the rest of their instance chains will not be considered:"
] <> case unks of
NoUnknowns ->
[]
Unknowns ->
[ line "The instance head contains unknown type variables. Consider adding a type annotation." ]
UnknownsWithVtaRequiringArgs tyClassMembersRequiringVtas ->
let
renderSingleTyClassMember (tyClassMember, argsRequiringVtas) =
Box.moveRight 2 $ paras $
[ line $ markCode (showQualified showIdent tyClassMember) ]
<> case argsRequiringVtas of
[required] ->
[ Box.moveRight 2 $ line $ T.intercalate ", " required ]
options ->
[ Box.moveRight 2 $ line "One of the following sets of type variables:"
, Box.moveRight 2 $ paras $
map (\set -> Box.moveRight 2 $ line $ T.intercalate ", " set) options
]
in
[ paras
[ line "The instance head contains unknown type variables."
, Box.moveDown 1 $ paras $
[ line $ "Note: The following type class members found in the expression require visible type applications to be unambiguous (e.g. " <> markCode "tyClassMember @Int" <> ")."]
<> map renderSingleTyClassMember (NEL.toList tyClassMembersRequiringVtas)
]
]
renderSimpleErrorMessage (AmbiguousTypeVariables t uis) =
paras [ line "The inferred type"
, markCodeBox $ indent $ prettyType t
, line "has type variables which are not determined by those mentioned in the body of the type:"
, indent $ Box.hsep 1 Box.left
[ Box.vcat Box.left
[ line $ markCode (u <> T.pack (show i)) <> " could not be determined"
| (u, i) <- uis ]
]
, line "Consider adding a type annotation."
]
renderSimpleErrorMessage (PossiblyInfiniteInstance nm ts) =
paras [ line "Type class instance for"
, markCodeBox $ indent $ Box.hsep 1 Box.left
[ line (showQualified runProperName nm)
, Box.vcat Box.left (map prettyTypeAtom ts)
]
, line "is possibly infinite."
]
renderSimpleErrorMessage PossiblyInfiniteCoercibleInstance =
line $ "A " <> markCode "Coercible" <> " instance is possibly infinite."
renderSimpleErrorMessage (CannotDerive nm ts) =
paras [ line "Cannot derive a type class instance for"
, markCodeBox $ indent $ Box.hsep 1 Box.left
[ line (showQualified runProperName nm)
, Box.vcat Box.left (map prettyTypeAtom ts)
]
, line "since instances of this type class are not derivable."
]
renderSimpleErrorMessage (InvalidNewtypeInstance nm ts) =
paras [ line "Cannot derive newtype instance for"
, markCodeBox $ indent $ Box.hsep 1 Box.left
[ line (showQualified runProperName nm)
, Box.vcat Box.left (map prettyTypeAtom ts)
]
, line "Make sure this is a newtype."
]
renderSimpleErrorMessage (MissingNewtypeSuperclassInstance su cl ts) =
paras [ line "The derived newtype instance for"
, markCodeBox $ indent $ Box.hsep 1 Box.left