-
Notifications
You must be signed in to change notification settings - Fork 267
/
PrintError.hs
1692 lines (1620 loc) · 59.9 KB
/
PrintError.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 OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
module Unison.PrintError where
import Control.Lens ((%~))
import Control.Lens.Tuple (_1, _2, _3)
import Data.List (find, intersperse)
import Data.List.Extra (nubOrd)
import qualified Data.List.NonEmpty as Nel
import qualified Data.Map as Map
import Data.Sequence (Seq (..))
import qualified Data.Set as Set
import Data.Set.NonEmpty (NESet)
import qualified Data.Set.NonEmpty as NES
import qualified Data.Text as Text
import Data.Void (Void)
import qualified Text.Megaparsec as P
import qualified Unison.ABT as ABT
import Unison.Builtin.Decls (pattern TupleType')
import Unison.ConstructorReference (ConstructorReference, GConstructorReference (..))
import Unison.HashQualified (HashQualified)
import qualified Unison.HashQualified as HQ
import Unison.Kind (Kind)
import qualified Unison.Kind as Kind
import qualified Unison.Lexer as L
import Unison.Name (Name)
import qualified Unison.Name as Name
import Unison.NamePrinter (prettyHashQualified0)
import qualified Unison.Names as Names
import qualified Unison.Names.ResolutionResult as Names
import qualified Unison.NamesWithHistory as NamesWithHistory
import Unison.Parser (Annotated, ann)
import qualified Unison.Parser as Parser
import Unison.Parser.Ann (Ann (..))
import Unison.Prelude
import qualified Unison.PrettyPrintEnv as PPE
import qualified Unison.PrettyPrintEnv.Names as PPE
import qualified Unison.Reference as R
import Unison.Referent (Referent, pattern Ref)
import Unison.Result (Note (..))
import qualified Unison.Result as Result
import qualified Unison.Settings as Settings
import qualified Unison.Term as Term
import qualified Unison.TermPrinter as TermPrinter
import Unison.Type (Type)
import qualified Unison.Type as Type
import qualified Unison.Typechecker.Context as C
import Unison.Typechecker.TypeError
import qualified Unison.Typechecker.TypeVar as TypeVar
import qualified Unison.UnisonFile.Error as UF
import Unison.Util.AnnotatedText (AnnotatedText)
import qualified Unison.Util.AnnotatedText as AT
import Unison.Util.ColorText (Color)
import qualified Unison.Util.ColorText as Color
import Unison.Util.Monoid (intercalateMap)
import Unison.Util.Pretty (ColorText, Pretty)
import qualified Unison.Util.Pretty as Pr
import Unison.Util.Range (Range (..), startingLine)
import Unison.Var (Var)
import qualified Unison.Var as Var
type Env = PPE.PrettyPrintEnv
pattern Code = Color.Blue
pattern Type1 = Color.HiBlue
pattern Type2 = Color.Green
pattern ErrorSite = Color.HiRed
pattern TypeKeyword = Color.Yellow
pattern AbilityKeyword = Color.Green
pattern Identifier = Color.Bold
defaultWidth :: Pr.Width
defaultWidth = 60
-- Various links used in error messages, collected here for a quick overview
structuralVsUniqueDocsLink :: IsString a => Pretty a
structuralVsUniqueDocsLink = "https://www.unison-lang.org/learn/language-reference/unique-types/"
fromOverHere' ::
Ord a =>
String ->
[Maybe (Range, a)] ->
[Maybe (Range, a)] ->
Pretty (AnnotatedText a)
fromOverHere' s spots0 removing =
fromOverHere s (catMaybes spots0) (catMaybes removing)
fromOverHere ::
Ord a => String -> [(Range, a)] -> [(Range, a)] -> Pretty (AnnotatedText a)
fromOverHere src spots0 removing =
let spots = toList $ Set.fromList spots0 Set.\\ Set.fromList removing
in case length spots of
0 -> mempty
1 -> "\n from right here:\n\n" <> showSource src spots
_ -> "\n from these spots, respectively:\n\n" <> showSource src spots
showTypeWithProvenance ::
(Var v, Annotated a, Ord style) =>
Env ->
String ->
style ->
Type v a ->
Pretty (AnnotatedText style)
showTypeWithProvenance env src color typ =
style color (renderType' env typ)
<> ".\n"
<> fromOverHere' src [styleAnnotated color typ] []
styleAnnotated :: Annotated a => sty -> a -> Maybe (Range, sty)
styleAnnotated sty a = (,sty) <$> rangeForAnnotated a
style :: s -> String -> Pretty (AnnotatedText s)
style sty str = Pr.lit . AT.annotate sty $ fromString str
stylePretty :: Color -> Pretty ColorText -> Pretty ColorText
stylePretty = Pr.map . AT.annotate
describeStyle :: Color -> Pretty ColorText
describeStyle ErrorSite = "in " <> style ErrorSite "red"
describeStyle Type1 = "in " <> style Type1 "blue"
describeStyle Type2 = "in " <> style Type2 "green"
describeStyle _ = ""
-- Render an informational typechecking note
renderTypeInfo ::
forall v loc sty.
(Var v, Annotated loc, Ord loc, Show loc) =>
TypeInfo v loc ->
Env ->
Pretty (AnnotatedText sty)
renderTypeInfo i env = case i of
TopLevelComponent {..} -> case definitions of
[def] ->
Pr.wrap "🌟 I found and typechecked a definition:" <> Pr.newline
<> mconcat
(renderOne def)
[] -> mempty
_ ->
Pr.wrap "🎁 These mutually dependent definitions typechecked:"
<> Pr.newline
<> intercalateMap Pr.newline (foldMap ("\t" <>) . renderOne) definitions
where
renderOne :: IsString s => (v, Type v loc, RedundantTypeAnnotation) -> [s]
renderOne (v, typ, _) =
[fromString . Text.unpack $ Var.name v, " : ", renderType' env typ]
-- Render a type error
renderTypeError ::
forall v loc.
(Var v, Annotated loc, Ord loc, Show loc) =>
TypeError v loc ->
Env ->
String ->
Pretty ColorText
renderTypeError e env src = case e of
BooleanMismatch {..} ->
mconcat
[ Pr.wrap $
mconcat
[ preamble,
" ",
style Type1 "Boolean",
", but this one is ",
style Type2 (renderType' env foundType),
":"
],
Pr.lineSkip,
showSourceMaybes src [siteS],
fromOverHere' src [typeS] [siteS],
debugNoteLoc $
mconcat
[ "loc debug:",
"\n mismatchSite: ",
annotatedToEnglish mismatchSite,
"\n foundType: ",
annotatedToEnglish foundType,
"\n"
],
debugSummary note
]
where
siteS = styleAnnotated Type2 mismatchSite
typeS = styleAnnotated Type2 foundType
preamble = case getBooleanMismatch of
CondMismatch ->
"The condition for an "
<> style ErrorSite "if"
<> "-expression has to be"
AndMismatch ->
"The arguments to " <> style ErrorSite "&&" <> " have to be"
OrMismatch ->
"The arguments to " <> style ErrorSite "||" <> " have to be"
GuardMismatch ->
"The guard expression for a "
<> style ErrorSite "match"
<> "/"
<> style ErrorSite "with"
<> " has to be"
ExistentialMismatch {..} ->
mconcat
[ Pr.lines
[ Pr.wrap preamble,
"",
"Here, one is: " <> style Type1 (renderType' env expectedType),
"and another is: " <> style Type2 (renderType' env foundType),
""
],
Pr.lineSkip,
showSourceMaybes src [mismatchSiteS, expectedLocS],
fromOverHere'
src
[expectedTypeS, mismatchedTypeS]
[mismatchSiteS, expectedLocS],
intLiteralSyntaxTip mismatchSite expectedType,
debugNoteLoc $
mconcat
[ "\nloc debug:",
"\n mismatchSite: ",
annotatedToEnglish mismatchSite,
"\n foundType: ",
annotatedToEnglish foundType,
"\n expectedType: ",
annotatedToEnglish expectedType,
"\n expectedLoc: ",
annotatedToEnglish expectedLoc,
"\n"
],
debugSummary note
]
where
mismatchedTypeS = styleAnnotated Type2 foundType
mismatchSiteS = styleAnnotated Type2 mismatchSite
expectedTypeS = styleAnnotated Type1 expectedType
expectedLocS = styleAnnotated Type1 expectedLoc
preamble = case getExistentialMismatch of
IfBody ->
mconcat
[ "The ",
style ErrorSite "else",
" clause of an ",
style ErrorSite "if",
" expression needs to have the same type as the ",
style ErrorSite "then",
" clause."
]
VectorBody -> "The elements of a vector all need to have the same type."
CaseBody ->
mconcat
[ "Each case of a ",
style ErrorSite "match",
"/",
style ErrorSite "with",
" expression ",
"need to have the same type."
]
NotFunctionApplication {..} ->
mconcat
[ "This looks like a function call, but with a ",
style Type1 (renderType' env ft),
" where the function should be. Are you missing an operator?\n\n",
annotatedAsStyle Type1 src f,
debugSummary note
]
FunctionApplication {..} ->
let fte = Type.removePureEffects ft
fteFreeVars = Set.map TypeVar.underlying $ ABT.freeVars fte
showVar (v, _t) = Set.member v fteFreeVars
solvedVars' = filter showVar solvedVars
in mconcat
[ Pr.lines
[ Pr.wrap $
"The " <> ordinal argNum <> " argument to "
<> Pr.backticked (style ErrorSite (renderTerm env f)),
"",
" has type: " <> style Type2 (renderType' env foundType),
" but I expected: " <> style Type1 (renderType' env expectedType),
"",
showSourceMaybes
src
[ (,Type1) <$> rangeForAnnotated expectedType,
(,Type2) <$> rangeForAnnotated foundType,
(,Type2) <$> rangeForAnnotated arg,
(,ErrorSite) <$> rangeForAnnotated f
]
],
intLiteralSyntaxTip arg expectedType,
-- todo: factor this out and use in ExistentialMismatch and any other
-- "recursive subtypes" situations
case leafs of
Nothing -> mempty
Just (foundLeaf, expectedLeaf) ->
Pr.lines
[ "",
"The mismatch is because these types differ:\n",
Pr.indentN 2 $ style Type2 (renderType' env foundLeaf),
Pr.indentN 2 $ style Type1 (renderType' env expectedLeaf),
""
]
<> showSourceMaybes
src
[ (,Type1) <$> rangeForAnnotated expectedLeaf,
(,Type2) <$> rangeForAnnotated foundLeaf
],
case solvedVars' of
_ : _ ->
let go :: (v, C.Type v loc) -> Pretty ColorText
go (v, t) =
mconcat
[ " ",
renderVar v,
" = ",
style ErrorSite (renderType' env t),
", from here:\n\n",
showSourceMaybes
src
[(,ErrorSite) <$> rangeForAnnotated t],
"\n"
]
in mconcat
[ "\n",
"because the ",
style ErrorSite (renderTerm env f),
" function has type",
"\n\n",
" ",
renderType' env fte,
"\n\n",
"where:",
"\n\n",
mconcat (go <$> solvedVars')
]
[] -> mempty,
debugNoteLoc
. mconcat
$ [ "\nloc debug:",
style ErrorSite "\n f: ",
annotatedToEnglish f,
style Type2 "\n foundType: ",
annotatedToEnglish foundType,
style Type1 "\n expectedType: ",
annotatedToEnglish expectedType
-- , "\n expectedLoc: ", annotatedToEnglish expectedLoc
],
debugSummary note
]
Mismatch {..} ->
mconcat
[ Pr.lines
[ "I found a value of type: " <> style Type1 (renderType' env foundLeaf),
"where I expected to find: " <> style Type2 (renderType' env expectedLeaf)
],
"\n\n",
showSourceMaybes
src
[ -- these are overwriting the colored ranges for some reason?
-- (,Color.ForceShow) <$> rangeForAnnotated mismatchSite
-- , (,Color.ForceShow) <$> rangeForType foundType
-- , (,Color.ForceShow) <$> rangeForType expectedType
-- ,
(,Type1) <$> rangeForAnnotated mismatchSite,
(,Type2) <$> rangeForAnnotated expectedLeaf
],
fromOverHere'
src
[styleAnnotated Type1 foundLeaf]
[styleAnnotated Type1 mismatchSite],
intLiteralSyntaxTip mismatchSite expectedType,
debugNoteLoc
. mconcat
$ [ "\nloc debug:",
"\n mismatchSite: ",
annotatedToEnglish mismatchSite,
"\n foundType: ",
annotatedToEnglish foundType,
"\n foundLeaf: ",
annotatedToEnglish foundLeaf,
"\n expectedType: ",
annotatedToEnglish expectedType,
"\n expectedLeaf: ",
annotatedToEnglish expectedLeaf,
"\n"
],
debugSummary note
]
AbilityCheckFailure {..}
| [tv@(Type.Var' ev)] <- ambient,
ev `Set.member` foldMap Type.freeVars requested ->
mconcat
[ "I tried to infer a cyclic ability.",
"\n\n",
"The expression ",
describeStyle ErrorSite,
" was inferred to require the ",
case length requested of
1 -> "ability: "
_ -> "abilities: ",
"\n\n {",
commas (renderType' env) requested,
"}",
"\n\n",
"where `",
renderType' env tv,
"` is its overall abilities.",
"\n\n",
"I need a type signature to help figure this out.",
"\n\n",
annotatedAsErrorSite src abilityCheckFailureSite,
debugSummary note
]
AbilityCheckFailure {..}
| C.InSubtype {} :<| _ <- C.path note ->
mconcat
[ "The expression ",
describeStyle ErrorSite,
"\n\n",
" needs the abilities: {",
commas (renderType' env) requested,
"}\n",
" but was assumed to only require: {",
commas (renderType' env) ambient,
"}",
"\n\n",
"This is likely a result of using an un-annotated ",
"function as an argument with concrete abilities. ",
"Try adding an annotation to the function definition whose ",
"body is red.",
"\n\n",
annotatedAsErrorSite src abilityCheckFailureSite,
debugSummary note
]
AbilityCheckFailure {..} ->
mconcat
[ "The expression ",
describeStyle ErrorSite,
" ",
case toList requested of
[] -> error "unpossible"
[e] -> "needs the {" <> renderType' env e <> "} ability,"
requested ->
" needs these abilities: {"
<> commas (renderType' env) requested
<> "},",
" but ",
case toList ambient of
[] -> "this location does not have access to any abilities."
[e] ->
"this location only has access to the {"
<> renderType' env e
<> "} ability,"
ambient ->
"this location only has access to these abilities: "
<> "{"
<> commas (renderType' env) ambient
<> "}",
"\n\n",
annotatedAsErrorSite src abilityCheckFailureSite,
debugSummary note
]
UnguardedLetRecCycle vs locs _ ->
mconcat
[ "These definitions depend on each other cyclically but aren't guarded ",
"by a lambda: " <> intercalateMap ", " renderVar vs,
"\n",
showSourceMaybes src [(,ErrorSite) <$> rangeForAnnotated loc | loc <- locs]
]
UnknownType {..} ->
mconcat
[ if ann typeSite == Intrinsic
then "I don't know about the builtin type " <> style ErrorSite (renderVar unknownTypeV) <> ". "
else
if ann typeSite == External
then "I don't know about the type " <> style ErrorSite (renderVar unknownTypeV) <> ". "
else
"I don't know about the type " <> style ErrorSite (renderVar unknownTypeV) <> ":\n"
<> annotatedAsErrorSite src typeSite,
"Make sure it's imported and spelled correctly."
]
UnknownTerm {..} ->
let (correct, wrongTypes, wrongNames) =
foldr sep id suggestions ([], [], [])
sep (C.Suggestion name typ _ match) r =
case match of
C.Exact -> (_1 %~ ((name, typ) :)) . r
C.WrongType -> (_2 %~ ((name, typ) :)) . r
C.WrongName -> (_3 %~ ((name, typ) :)) . r
in mconcat
[ "I'm not sure what ",
style ErrorSite (Var.nameStr unknownTermV),
" means at ",
annotatedToEnglish termSite,
"\n\n",
annotatedAsErrorSite src termSite,
case expectedType of
Type.Var' (TypeVar.Existential {}) -> "\nThere are no constraints on its type. "
_ ->
"\nWhatever it is, it has a type that conforms to "
<> style Type1 (renderType' env expectedType)
<> ".\n",
-- ++ showTypeWithProvenance env src Type1 expectedType
case correct of
[] -> case wrongTypes of
[] -> case wrongNames of
[] -> mempty
wrongs -> formatWrongs wrongNameText wrongs
wrongs -> formatWrongs wrongTypeText wrongs
suggs ->
mconcat
[ "I found some terms in scope that have matching names and types. ",
"Maybe you meant one of these:\n\n",
intercalateMap "\n" formatSuggestion suggs
]
]
DuplicateDefinitions {..} ->
mconcat
[ Pr.wrap $
mconcat
[ "I found",
Pr.shown (length defns),
names,
"with multiple definitions:"
],
Pr.lineSkip,
Pr.spaced ((\(v, _locs) -> renderVar v) <$> defns),
debugSummary note
]
where
names =
case defns of
_ Nel.:| [] -> "name"
_ -> "names"
Other (C.cause -> C.HandlerOfUnexpectedType loc typ) ->
Pr.lines
[ Pr.wrap "The handler used here",
"",
annotatedAsErrorSite src loc,
Pr.wrap $
"has type " <> stylePretty ErrorSite (Pr.group (renderType' env typ))
<> "but I'm expecting a function of the form"
<> Pr.group (Pr.blue (renderType' env exHandler) <> ".")
]
where
exHandler :: C.Type v loc
exHandler =
fmap (const loc) $
Type.arrow
()
( Type.apps'
(Type.ref () Type.effectRef)
[Type.var () (Var.named "e"), Type.var () (Var.named "a")]
)
(Type.var () (Var.named "o"))
Other (C.cause -> C.PatternArityMismatch loc typ num) ->
Pr.lines
[ Pr.wrap "This pattern has the wrong number of arguments",
"",
annotatedAsErrorSite src loc,
"The constructor has type ",
"",
Pr.indentN 2 (stylePretty Type1 (Pr.group (renderType' env typ))),
"",
"but you supplied " <> (Pr.shown num) <> " arguments."
]
Other note ->
mconcat
[ "Sorry, you hit an error we didn't make a nice message for yet.\n\n",
"Here is a summary of the Note:\n",
summary note
]
where
wrongTypeText pl =
mconcat
[ "I found ",
pl "a term" "some terms",
" in scope with ",
pl "a " "",
"matching name",
pl "" "s",
" but ",
pl "a " "",
"different type",
pl "" "s",
". ",
"If ",
pl "this" "one of these",
" is what you meant, try using the fully qualified name and I might ",
"be able to give you a more illuminating error message: \n\n"
]
wrongNameText pl =
mconcat
[ "I found ",
pl "a term" "some terms",
" in scope with ",
pl "a " "",
"matching type",
pl "" "s",
" but ",
pl "a " "",
"different name",
pl "" "s",
". ",
"Maybe you meant ",
pl "this" "one of these",
":\n\n"
]
formatSuggestion :: (Text, C.Type v loc) -> Pretty ColorText
formatSuggestion (name, typ) =
" - " <> fromString (Text.unpack name) <> " : " <> renderType' env typ
formatWrongs txt wrongs =
let sz = length wrongs
pl a b = if sz == 1 then a else b
in mconcat [txt pl, intercalateMap "\n" formatSuggestion wrongs]
ordinal :: (IsString s) => Int -> s
ordinal n =
fromString $
show n ++ case last (show n) of
'1' -> "st"
'2' -> "nd"
'3' -> "rd"
_ -> "th"
debugNoteLoc a = if Settings.debugNoteLoc then a else mempty
debugSummary :: C.ErrorNote v loc -> Pretty ColorText
debugSummary note =
if Settings.debugNoteSummary then summary note else mempty
summary :: C.ErrorNote v loc -> Pretty ColorText
summary note =
mconcat
[ "\n",
" simple cause:\n",
" ",
simpleCause (C.cause note),
"\n"
-- This can be very slow to print in large file. This was taking several minutes to print out the path in a file when the error occurred deep in the file after many other let bindings - stew
-- , case toList (C.path note) of
-- [] -> " path: (empty)\n"
-- l -> " path:\n" <> mconcat (simplePath <$> l)
]
-- simplePath :: C.PathElement v loc -> Pretty ColorText
-- simplePath e = " " <> simplePath' e <> "\n"
-- simplePath' :: C.PathElement v loc -> Pretty ColorText
-- simplePath' = \case
-- C.InSynthesize e -> "InSynthesize e=" <> renderTerm env e
-- C.InEquate t1 t2 ->
-- "InEquate t1=" <> renderType' env t1 <>
-- ", t2=" <> renderType' env t2
-- C.InSubtype t1 t2 ->
-- "InSubtype t1=" <> renderType' env t1 <> ", t2=" <> renderType' env t2
-- C.InCheck e t ->
-- "InCheck e=" <> renderTerm env e <> "," <> " t=" <> renderType' env t
-- C.InInstantiateL v t ->
-- "InInstantiateL v=" <> renderVar v <> ", t=" <> renderType' env t
-- C.InInstantiateR t v ->
-- "InInstantiateR t=" <> renderType' env t <> " v=" <> renderVar v
-- C.InSynthesizeApp t e n ->
-- "InSynthesizeApp t="
-- <> renderType' env t
-- <> ", e="
-- <> renderTerm env e
-- <> ", n="
-- <> fromString (show n)
-- C.InFunctionCall vs f ft es ->
-- "InFunctionCall vs=["
-- <> commas renderVar vs
-- <> "]"
-- <> ", f="
-- <> renderTerm env f
-- <> ", ft="
-- <> renderType' env ft
-- <> ", es=["
-- <> commas (renderTerm env) es
-- <> "]"
-- C.InIfCond -> "InIfCond"
-- C.InIfBody loc -> "InIfBody thenBody=" <> annotatedToEnglish loc
-- C.InAndApp -> "InAndApp"
-- C.InOrApp -> "InOrApp"
-- C.InVectorApp loc -> "InVectorApp firstTerm=" <> annotatedToEnglish loc
-- C.InMatch loc -> "InMatch firstBody=" <> annotatedToEnglish loc
-- C.InMatchGuard -> "InMatchGuard"
-- C.InMatchBody -> "InMatchBody"
simpleCause :: C.Cause v loc -> Pretty ColorText
simpleCause = \case
C.TypeMismatch c ->
mconcat ["TypeMismatch\n", " context:\n", renderContext env c]
C.HandlerOfUnexpectedType loc typ ->
mconcat ["HandlerOfUnexpectedType\n", Pr.shown loc, "type:\n", renderType' env typ]
C.IllFormedType c ->
mconcat ["IllFormedType\n", " context:\n", renderContext env c]
C.UnguardedLetRecCycle vs _ts ->
"Unguarded cycle of definitions: "
<> foldMap renderVar vs
C.UnknownSymbol loc v ->
mconcat
[ "UnknownSymbol: ",
annotatedToEnglish loc,
" " <> renderVar v,
"\n\n",
annotatedAsErrorSite src loc
]
C.UnknownTerm loc v suggestions typ ->
mconcat
[ "UnknownTerm: ",
annotatedToEnglish loc,
" ",
renderVar v,
"\n\n",
annotatedAsErrorSite src loc,
"Suggestions: ",
mconcat (renderSuggestion env <$> suggestions),
"\n\n",
"Type: ",
renderType' env typ
]
C.AbilityCheckFailure ambient requested c ->
mconcat
[ "AbilityCheckFailure: ",
"ambient={",
commas (renderType' env) ambient,
"} requested={",
commas (renderType' env) requested,
"}\n",
renderContext env c
]
C.EffectConstructorWrongArgCount e a r ->
mconcat
[ "EffectConstructorWrongArgCount:",
" expected=",
(fromString . show) e,
", actual=",
(fromString . show) a,
", reference=",
showConstructor env r
]
C.MalformedEffectBind ctorType ctorResult es ->
mconcat
[ "MalformedEffectBind: ",
" ctorType=",
renderType' env ctorType,
" ctorResult=",
renderType' env ctorResult,
" effects=",
fromString (show es)
]
C.PatternArityMismatch loc typ args ->
mconcat
[ "PatternArityMismatch:\n",
" loc=",
annotatedToEnglish loc,
"\n",
" typ=",
renderType' env typ,
"\n",
" args=",
fromString (show args),
"\n"
]
C.DuplicateDefinitions vs ->
let go :: (v, [loc]) -> Pretty (AnnotatedText a)
go (v, locs) =
"["
<> renderVar v
<> mconcat (intersperse " : " $ annotatedToEnglish <$> locs)
<> "]"
in "DuplicateDefinitions:" <> mconcat (go <$> Nel.toList vs)
C.ConcatPatternWithoutConstantLength loc typ ->
mconcat
[ "ConcatPatternWithoutConstantLength:\n",
" loc=",
annotatedToEnglish loc,
"\n",
" typ=",
renderType' env typ,
"\n"
]
C.DataEffectMismatch actual rf _ ->
mconcat
[ "DataEffectMismatch:\n",
case actual of
C.Data -> " data type used as effect"
C.Effect -> " ability used as data type",
"\n",
" reference=",
showTypeRef env rf
]
renderCompilerBug ::
(Var v, Annotated loc, Ord loc, Show loc) =>
Env ->
String ->
C.CompilerBug v loc ->
Pretty ColorText
renderCompilerBug env _src bug = mconcat $ case bug of
C.UnknownDecl sort rf _decls ->
[ "UnknownDecl:\n",
case sort of
C.Data -> " data type"
C.Effect -> " ability",
"\n",
" reerence = ",
showTypeRef env rf
]
C.UnknownConstructor sort (ConstructorReference rf i) _decl ->
[ "UnknownConstructor:\n",
case sort of
C.Data -> " data type\n"
C.Effect -> " ability\n",
" reference = ",
showTypeRef env rf,
"\n",
" constructor index = ",
fromString (show i)
]
C.UndeclaredTermVariable v ctx ->
[ "UndeclaredTermVariable:\n ",
fromString $ renderVar' env ctx v
]
C.RetractFailure elem ctx ->
[ "RetractFailure:\n",
fromString $ show elem,
fromString $ show ctx
]
C.EmptyLetRec tm ->
[ "EmptyLetRec:\n",
renderTerm env tm
]
C.PatternMatchFailure -> ["PatternMatchFailure"]
C.EffectConstructorHadMultipleEffects es ->
[ "EffectConstructorHadMultipleEffects:\n ",
renderType' env es
]
C.FreeVarsInTypeAnnotation vs ->
[ "FreeVarsInTypeAnnotation:\n ",
intercalateMap ", " renderVar (toList vs)
]
C.UnannotatedReference rf ->
[ "UnannotatedReference:\n",
showTypeRef env rf -- term/type shouldn't matter, since unknown
]
C.MalformedPattern p ->
[ "MalformedPattern:\n",
fromString $ show p
]
C.UnknownTermReference rf ->
[ "UnknownTermReference:\n",
showTermRef env (Ref rf)
]
C.UnknownExistentialVariable v ctx ->
[ "UnknownExistentialVariable:\n",
fromString $ renderVar' env ctx v
]
C.IllegalContextExtension ctx el str ->
[ "IllegalContextExtension:\n",
" context:\n ",
fromString $ show ctx,
" element:\n ",
fromString $ show el,
fromString str
]
C.OtherBug str -> ["OtherBug:\n", fromString str]
renderContext ::
(Var v, Ord loc) => Env -> C.Context v loc -> Pretty (AnnotatedText a)
renderContext env ctx@(C.Context es) =
" Γ\n "
<> intercalateMap "\n " (showElem ctx . fst) (reverse es)
where
shortName :: (Var v, IsString loc) => v -> loc
shortName = fromString . Text.unpack . Var.name
showElem ::
(Var v, Ord loc) =>
C.Context v loc ->
C.Element v loc ->
Pretty (AnnotatedText a)
showElem _ctx (C.Var v) = case v of
TypeVar.Universal x -> "@" <> renderVar x
e -> Pr.shown e
showElem ctx (C.Solved _ v (Type.Monotype t)) =
"'" <> shortName v <> " = " <> renderType' env (C.apply ctx t)
showElem ctx (C.Ann v t) =
shortName v <> " : " <> renderType' env (C.apply ctx t)
showElem _ (C.Marker v) = "|" <> shortName v <> "|"
renderTerm :: (IsString s, Var v) => Env -> C.Term v loc -> s
renderTerm env e =
let s = Color.toPlain $ TermPrinter.pretty' (Just 80) env (TypeVar.lowerTerm e)
in if length s > Settings.renderTermMaxLength
then fromString (take Settings.renderTermMaxLength s <> "...")
else fromString s
-- | renders a type with no special styling
renderType' :: (IsString s, Var v) => Env -> Type v loc -> s
renderType' env typ =
fromString . Pr.toPlain defaultWidth $ renderType env (const id) typ
-- | `f` may do some styling based on `loc`.
-- | You can pass `(const id)` if no styling is needed, or call `renderType'`.
renderType ::
Var v =>
Env ->
(loc -> Pretty (AnnotatedText a) -> Pretty (AnnotatedText a)) ->
Type v loc ->
Pretty (AnnotatedText a)
renderType env f t = renderType0 env f (0 :: Int) (Type.removePureEffects t)
where
wrap :: (IsString a, Semigroup a) => a -> a -> Bool -> a -> a
wrap start end test s = if test then start <> s <> end else s
paren = wrap "(" ")"
curly = wrap "{" "}"
renderType0 env f p t = f (ABT.annotation t) $ case t of
Type.Ref' r -> showTypeRef env r
Type.Arrow' i (Type.Effect1' e o) ->
paren (p >= 2) $ go 2 i <> " ->{" <> go 1 e <> "} " <> go 1 o
Type.Arrow' i o -> paren (p >= 2) $ go 2 i <> " -> " <> go 1 o
Type.Ann' t k -> paren True $ go 1 t <> " : " <> renderKind k
TupleType' ts -> paren True $ commas (go 0) ts
Type.Apps' (Type.Ref' (R.Builtin "Sequence")) [arg] ->
"[" <> go 0 arg <> "]"
Type.Apps' f' args -> paren (p >= 3) $ spaces (go 3) (f' : args)
Type.Effects' es -> curly (p >= 3) $ commas (go 0) es
Type.Effect' es t -> case es of
[] -> go p t
_ -> "{" <> commas (go 0) es <> "} " <> go 3 t
Type.Effect1' e t -> paren (p >= 3) $ "{" <> go 0 e <> "}" <> go 3 t
Type.ForallsNamed' vs body ->
paren (p >= 1) $
if not Settings.debugRevealForalls
then go 0 body
else "forall " <> spaces renderVar vs <> " . " <> go 1 body
Type.Var' v -> renderVar v
_ -> error $ "pattern match failure in PrintError.renderType " ++ show t
where
go = renderType0 env f
renderSuggestion ::
(IsString s, Semigroup s, Var v) => Env -> C.Suggestion v loc -> s
renderSuggestion env sug =
fromString (Text.unpack $ C.suggestionName sug) <> " : "
<> renderType'
env
(C.suggestionType sug)
spaces :: (IsString a, Monoid a) => (b -> a) -> [b] -> a
spaces = intercalateMap " "
arrows :: (IsString a, Monoid a) => (b -> a) -> [b] -> a
arrows = intercalateMap " ->"
commas :: (IsString a, Monoid a) => (b -> a) -> [b] -> a
commas = intercalateMap ", "
renderVar :: (IsString a, Var v) => v -> a
renderVar = fromString . Text.unpack . Var.name
renderVar' :: (Var v, Annotated a) => Env -> C.Context v a -> v -> String
renderVar' env ctx v = case C.lookupSolved ctx v of
Nothing -> "unsolved"
Just t -> renderType' env $ Type.getPolytype t
prettyVar :: Var v => v -> Pretty ColorText
prettyVar = Pr.text . Var.name
renderKind :: Kind -> Pretty (AnnotatedText a)
renderKind Kind.Star = "*"
renderKind (Kind.Arrow k1 k2) = renderKind k1 <> " -> " <> renderKind k2
showTermRef :: IsString s => Env -> Referent -> s
showTermRef env r = fromString . HQ.toString $ PPE.termName env r
showTypeRef :: IsString s => Env -> R.Reference -> s
showTypeRef env r = fromString . HQ.toString $ PPE.typeName env r
-- todo: do something different/better if cid not found
showConstructor :: IsString s => Env -> ConstructorReference -> s
showConstructor env r =
fromString . HQ.toString $
PPE.patternName env r
styleInOverallType ::
(Var v, Annotated a, Eq a) =>
Env ->
C.Type v a ->
C.Type v a ->
Color ->
Pretty ColorText
styleInOverallType e overallType leafType c = renderType e f overallType
where
f loc s = if loc == ABT.annotation leafType then Color.style c <$> s else s
_posToEnglish :: IsString s => L.Pos -> s
_posToEnglish (L.Pos l c) =
fromString $ "Line " ++ show l ++ ", Column " ++ show c
rangeForToken :: L.Token a -> Range