-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy patherror.rs
More file actions
963 lines (841 loc) · 29.2 KB
/
error.rs
File metadata and controls
963 lines (841 loc) · 29.2 KB
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
use std::fmt;
use std::ops::Range;
use std::sync::Arc;
use chumsky::error::Error as ChumskyError;
use chumsky::input::ValueInput;
use chumsky::label::LabelError;
use chumsky::util::MaybeRef;
use chumsky::DefaultExpected;
use itertools::Itertools;
use simplicity::elements;
use crate::lexer::Token;
use crate::parse::MatchPattern;
use crate::str::{AliasName, FunctionName, Identifier, JetName, ModuleName, WitnessName};
use crate::types::{ResolvedType, UIntType};
/// Area that an object spans inside a file.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct Span {
/// Position where the object starts, inclusively.
pub start: usize,
/// Position where the object ends, exclusively.
pub end: usize,
}
impl Span {
/// A dummy span.
#[cfg(feature = "arbitrary")]
pub(crate) const DUMMY: Self = Self::new(0, 0);
/// Create a new span.
///
/// ## Panics
///
/// Start comes after end.
pub const fn new(start: usize, end: usize) -> Self {
assert!(start <= end, "Start cannot come after end");
Self { start, end }
}
/// Return a slice from the given `file` that corresponds to the span.
pub fn to_slice<'a>(&self, file: &'a str) -> Option<&'a str> {
file.get(self.start..self.end)
}
}
impl chumsky::span::Span for Span {
type Context = ();
type Offset = usize;
fn new((): Self::Context, range: Range<Self::Offset>) -> Self {
Self {
start: range.start,
end: range.end,
}
}
fn context(&self) -> Self::Context {}
fn start(&self) -> Self::Offset {
self.start
}
fn end(&self) -> Self::Offset {
self.end
}
}
impl fmt::Display for Span {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}..{}", self.start, self.end)?;
Ok(())
}
}
impl From<chumsky::span::SimpleSpan> for Span {
fn from(span: chumsky::span::SimpleSpan) -> Self {
Self {
start: span.start,
end: span.end,
}
}
}
impl From<Range<usize>> for Span {
fn from(range: Range<usize>) -> Self {
Self::new(range.start, range.end)
}
}
impl From<&str> for Span {
fn from(s: &str) -> Self {
Span::new(0, s.len())
}
}
#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for Span {
fn arbitrary(_: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Self::DUMMY)
}
}
/// Helper trait to convert `Result<T, E>` into `Result<T, RichError>`.
pub trait WithSpan<T> {
/// Update the result with the affected span.
fn with_span<S: Into<Span>>(self, span: S) -> Result<T, RichError>;
}
impl<T, E: Into<Error>> WithSpan<T> for Result<T, E> {
fn with_span<S: Into<Span>>(self, span: S) -> Result<T, RichError> {
self.map_err(|e| e.into().with_span(span.into()))
}
}
/// Helper trait to update `Result<A, RichError>` with the affected source file.
pub trait WithFile<T> {
/// Update the result with the affected source file.
///
/// Enable pretty errors.
fn with_file<F: Into<Arc<str>>>(self, file: F) -> Result<T, RichError>;
}
impl<T> WithFile<T> for Result<T, RichError> {
fn with_file<F: Into<Arc<str>>>(self, file: F) -> Result<T, RichError> {
self.map_err(|e| e.with_file(file.into()))
}
}
/// An error enriched with context.
///
/// Records _what_ happened and _where_.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct RichError {
/// The error that occurred.
error: Error,
/// Area that the error spans inside the file.
span: Span,
/// File in which the error occurred.
///
/// Required to print pretty errors.
file: Option<Arc<str>>,
}
impl RichError {
/// Create a new error with context.
pub fn new(error: Error, span: Span) -> RichError {
RichError {
error,
span,
file: None,
}
}
/// Add the source file where the error occurred.
///
/// Enable pretty errors.
pub fn with_file(self, file: Arc<str>) -> Self {
Self {
error: self.error,
span: self.span,
file: Some(file),
}
}
/// Constructs an error that is very unlikely to be encountered, but indicates
/// a problem on the parsing side.
pub fn parsing_error(reason: &str) -> Self {
Self {
error: Error::CannotParse(reason.to_string()),
span: Span::new(0, 0),
file: None,
}
}
pub fn file(&self) -> &Option<Arc<str>> {
&self.file
}
pub fn error(&self) -> &Error {
&self.error
}
pub fn span(&self) -> &Span {
&self.span
}
}
impl fmt::Display for RichError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fn next_newline(s: &str) -> Option<(usize, usize)> {
let mut it = s.char_indices().peekable();
while let Some((i, ch)) = it.next() {
if ch == '\r' {
// Treat CRLF as one logical newline.
if matches!(it.peek(), Some((_, c)) if *c == '\n') {
it.next();
return Some((i, '\r'.len_utf8() + '\n'.len_utf8()));
}
// Support lone CR for compatibility with current lexer behavior.
return Some((i, ch.len_utf8()));
}
// Support LF newline.
if ch == '\n' {
return Some((i, ch.len_utf8()));
}
// Unicode newline support.
if ch == '\u{2028}' || ch == '\u{2029}' {
return Some((i, ch.len_utf8()));
}
}
None
}
fn get_line_col(file: &str, offset: usize) -> (usize, usize) {
let s = file.get(..offset).unwrap_or_default();
let mut line = 1usize;
let mut last_line_start = 0usize;
let mut rest = s;
let mut consumed = 0usize;
while let Some((i, nl_len)) = next_newline(rest) {
line += 1;
consumed += i + nl_len;
last_line_start = consumed;
rest = &rest[i + nl_len..];
}
let col = 1 + s[last_line_start..]
.chars()
.map(char::len_utf16)
.sum::<usize>();
(line, col)
}
fn split_lines_preserving_crlf(file: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut rest = file;
while let Some((i, nl_len)) = next_newline(rest) {
out.push(&rest[..i]);
rest = &rest[i + nl_len..];
}
out.push(rest);
out
}
match self.file {
Some(ref file) if !file.is_empty() => {
let (start_line, start_col) = get_line_col(file, self.span.start);
let (end_line, end_col) = get_line_col(file, self.span.end);
let start_line_index = start_line - 1;
let n_spanned_lines = end_line - start_line_index;
let line_num_width = end_line.to_string().len();
writeln!(f, "{:width$} |", " ", width = line_num_width)?;
let split_lines = split_lines_preserving_crlf(file);
let mut lines = split_lines.into_iter().skip(start_line_index).peekable();
let start_line_len = lines
.peek()
.map_or(0, |l| l.chars().map(char::len_utf16).sum::<usize>());
for (relative_line_index, line_str) in lines.take(n_spanned_lines).enumerate() {
let line_num = start_line_index + relative_line_index + 1;
write!(f, "{line_num:line_num_width$} |")?;
if !line_str.is_empty() {
write!(f, " {line_str}")?;
}
writeln!(f)?;
}
let is_multiline = end_line > start_line;
let (underline_start, underline_length) = match is_multiline {
// For multiline spans, preserve the existing display style:
// underline the full first displayed line.
true => (1, start_line_len),
false => (start_col, (end_col - start_col).max(1)),
};
write!(f, "{:width$} |", " ", width = line_num_width)?;
write!(f, "{:width$}", " ", width = underline_start)?;
write!(f, "{:^<width$} ", "", width = underline_length)?;
write!(f, "{}", self.error)
}
_ => {
write!(f, "{}", self.error)
}
}
}
}
impl std::error::Error for RichError {}
impl From<RichError> for Error {
fn from(error: RichError) -> Self {
error.error
}
}
impl From<RichError> for String {
fn from(error: RichError) -> Self {
error.to_string()
}
}
/// Implementation of traits for using inside `chumsky` parsers.
impl<'tokens, 'src: 'tokens, I> ChumskyError<'tokens, I> for RichError
where
I: ValueInput<'tokens, Token = Token<'src>, Span = Span>,
{
fn merge(self, other: Self) -> Self {
match (&self.error, &other.error) {
(Error::Grammar(_), Error::Grammar(_)) => other,
(Error::Grammar(_), _) => other,
(_, Error::Grammar(_)) => self,
_ => other,
}
}
}
impl<'tokens, 'src: 'tokens, I> LabelError<'tokens, I, DefaultExpected<'tokens, Token<'src>>>
for RichError
where
I: ValueInput<'tokens, Token = Token<'src>, Span = Span>,
{
fn expected_found<E>(
expected: E,
found: Option<MaybeRef<'tokens, Token<'src>>>,
span: Span,
) -> Self
where
E: IntoIterator<Item = DefaultExpected<'tokens, Token<'src>>>,
{
let expected_tokens: Vec<String> = expected
.into_iter()
.map(|t| match t {
DefaultExpected::Token(maybe) => maybe.to_string(),
DefaultExpected::Any => "anything".to_string(),
DefaultExpected::SomethingElse => "something else".to_string(),
DefaultExpected::EndOfInput => "end of input".to_string(),
_ => "UNEXPECTED_TOKEN".to_string(),
})
.collect();
let found_string = found.map(|t| t.to_string());
Self {
error: Error::Syntax {
expected: expected_tokens,
label: None,
found: found_string,
},
span,
file: None,
}
}
}
impl<'tokens, 'src: 'tokens, I> LabelError<'tokens, I, &'tokens str> for RichError
where
I: ValueInput<'tokens, Token = Token<'src>, Span = Span>,
{
fn expected_found<E>(
expected: E,
found: Option<MaybeRef<'tokens, Token<'src>>>,
span: Span,
) -> Self
where
E: IntoIterator<Item = &'tokens str>,
{
let expected_strings: Vec<String> = expected.into_iter().map(|s| s.to_string()).collect();
let found_string = found.map(|t| t.to_string());
Self {
error: Error::Syntax {
expected: expected_strings,
label: None,
found: found_string,
},
span,
file: None,
}
}
fn label_with(&mut self, label: &'tokens str) {
if let Error::Syntax {
label: ref mut l, ..
} = &mut self.error
{
*l = Some(label.to_string());
}
}
}
#[derive(Debug, Clone, Hash)]
pub struct ErrorCollector {
/// File in which the error occurred.
file: Arc<str>,
/// Collected errors.
errors: Vec<RichError>,
}
impl ErrorCollector {
pub fn new(file: Arc<str>) -> Self {
Self {
file,
errors: Vec::new(),
}
}
/// Extend existing errors with slice of new errors.
pub fn update(&mut self, errors: impl IntoIterator<Item = RichError>) {
let new_errors = errors
.into_iter()
.map(|err| err.with_file(Arc::clone(&self.file)));
self.errors.extend(new_errors);
}
pub fn get(&self) -> &[RichError] {
&self.errors
}
pub fn is_empty(&self) -> bool {
self.get().is_empty()
}
}
impl fmt::Display for ErrorCollector {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for err in self.get() {
writeln!(f, "{err}\n")?;
}
Ok(())
}
}
/// An individual error.
///
/// Records _what_ happened but not where.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum Error {
ArraySizeNonZero(usize),
ListBoundPow2(usize),
BitStringPow2(usize),
CannotParse(String),
Grammar(String),
Syntax {
expected: Vec<String>,
label: Option<String>,
found: Option<String>,
},
IncompatibleMatchArms(MatchPattern, MatchPattern),
// TODO: Remove CompileError once SimplicityHL has a type system
// The SimplicityHL compiler should never produce ill-typed Simplicity code
// The compiler can only be this precise if it knows a type system at least as expressive as Simplicity's
CannotCompile(String),
JetDoesNotExist(JetName),
InvalidCast(ResolvedType, ResolvedType),
MainNoInputs,
MainNoOutput,
MainRequired,
FunctionRedefined(FunctionName),
FunctionUndefined(FunctionName),
InvalidNumberOfArguments(usize, usize),
FunctionNotFoldable(FunctionName),
FunctionNotLoopable(FunctionName),
ExpressionUnexpectedType(ResolvedType),
ExpressionTypeMismatch(ResolvedType, ResolvedType),
ExpressionNotConstant,
IntegerOutOfBounds(UIntType),
UndefinedVariable(Identifier),
RedefinedAlias(AliasName),
RedefinedAliasAsBuiltin(AliasName),
UndefinedAlias(AliasName),
VariableReuseInPattern(Identifier),
WitnessReused(WitnessName),
WitnessTypeMismatch(WitnessName, ResolvedType, ResolvedType),
WitnessReassigned(WitnessName),
WitnessOutsideMain,
ModuleRedefined(ModuleName),
ArgumentMissing(WitnessName),
ArgumentTypeMismatch(WitnessName, ResolvedType, ResolvedType),
}
#[rustfmt::skip]
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::ArraySizeNonZero(size) => write!(
f,
"Expected a non-negative integer as array size, found {size}"
),
Error::ListBoundPow2(bound) => write!(
f,
"Expected a power of two greater than one (2, 4, 8, 16, 32, ...) as list bound, found {bound}"
),
Error::BitStringPow2(len) => write!(
f,
"Expected a valid bit string length (1, 2, 4, 8, 16, 32, 64, 128, 256), found {len}"
),
Error::CannotParse(description) => write!(
f,
"Cannot parse: {description}"
),
Error::Grammar(description) => write!(
f,
"Grammar error: {description}"
),
Error::Syntax { expected, label, found } => {
let found_text = found.clone().unwrap_or("end of input".to_string());
match (label, expected.len()) {
(Some(l), _) => write!(f, "Expected {}, found {}", l, found_text),
(None, 1) => {
let exp_text = expected.first().unwrap();
write!(f, "Expected '{}', found '{}'", exp_text, found_text)
}
(None, 0) => write!(f, "Unexpected {}", found_text),
(None, _) => {
let exp_text = expected.iter().map(|s| format!("'{}'", s)).join(", ");
write!(f, "Expected one of {}, found '{}'", exp_text, found_text)
}
}
}
Error::IncompatibleMatchArms(pattern1, pattern2) => write!(
f,
"Match arm `{pattern1}` is incompatible with arm `{pattern2}`"
),
Error::CannotCompile(description) => write!(
f,
"Failed to compile to Simplicity: {description}"
),
Error::JetDoesNotExist(name) => write!(
f,
"Jet `{name}` does not exist"
),
Error::InvalidCast(source, target) => write!(
f,
"Cannot cast values of type `{source}` as values of type `{target}`"
),
Error::MainNoInputs => write!(
f,
"Main function takes no input parameters"
),
Error::MainNoOutput => write!(
f,
"Main function produces no output"
),
Error::MainRequired => write!(
f,
"Main function is required"
),
Error::FunctionRedefined(name) => write!(
f,
"Function `{name}` was defined multiple times"
),
Error::FunctionUndefined(name) => write!(
f,
"Function `{name}` was called but not defined"
),
Error::InvalidNumberOfArguments(expected, found) => write!(
f,
"Expected {expected} arguments, found {found} arguments"
),
Error::FunctionNotFoldable(name) => write!(
f,
"Expected a signature like `fn {name}(element: E, accumulator: A) -> A` for a fold"
),
Error::FunctionNotLoopable(name) => write!(
f,
"Expected a signature like `fn {name}(accumulator: A, context: C, counter u{{1,2,4,8,16}}) -> Either<B, A>` for a for-while loop"
),
Error::ExpressionUnexpectedType(ty) => write!(
f,
"Expected expression of type `{ty}`; found something else"
),
Error::ExpressionTypeMismatch(expected, found) => write!(
f,
"Expected expression of type `{expected}`, found type `{found}`"
),
Error::ExpressionNotConstant => write!(
f,
"Expression cannot be evaluated at compile time"
),
Error::IntegerOutOfBounds(ty) => write!(
f,
"Value is out of bounds for type `{ty}`"
),
Error::UndefinedVariable(identifier) => write!(
f,
"Variable `{identifier}` is not defined"
),
Error::RedefinedAlias(identifier) => write!(
f,
"Type alias `{identifier}` was defined multiple times"
),
Error::RedefinedAliasAsBuiltin(identifier) => write!(
f,
"Type alias `{identifier}` is already exists as built-in alias"
),
Error::UndefinedAlias(identifier) => write!(
f,
"Type alias `{identifier}` is not defined"
),
Error::VariableReuseInPattern(identifier) => write!(
f,
"Variable `{identifier}` is used twice in the pattern"
),
Error::WitnessReused(name) => write!(
f,
"Witness `{name}` has been used before somewhere in the program"
),
Error::WitnessTypeMismatch(name, declared, assigned) => write!(
f,
"Witness `{name}` was declared with type `{declared}` but its assigned value is of type `{assigned}`"
),
Error::WitnessReassigned(name) => write!(
f,
"Witness `{name}` has already been assigned a value"
),
Error::WitnessOutsideMain => write!(
f,
"Witness expressions are not allowed outside the `main` function"
),
Error::ModuleRedefined(name) => write!(
f,
"Module `{name}` is defined twice"
),
Error::ArgumentMissing(name) => write!(
f,
"Parameter `{name}` is missing an argument"
),
Error::ArgumentTypeMismatch(name, declared, assigned) => write!(
f,
"Parameter `{name}` was declared with type `{declared}` but its assigned argument is of type `{assigned}`"
),
}
}
}
impl std::error::Error for Error {}
impl Error {
/// Update the error with the affected span.
pub fn with_span(self, span: Span) -> RichError {
RichError::new(self, span)
}
}
impl From<elements::hex::Error> for Error {
fn from(error: elements::hex::Error) -> Self {
Self::CannotParse(error.to_string())
}
}
impl From<std::num::ParseIntError> for Error {
fn from(error: std::num::ParseIntError) -> Self {
Self::CannotParse(error.to_string())
}
}
impl From<crate::num::ParseIntError> for Error {
fn from(error: crate::num::ParseIntError) -> Self {
Self::CannotParse(error.to_string())
}
}
impl From<simplicity::types::Error> for Error {
fn from(error: simplicity::types::Error) -> Self {
Self::CannotCompile(error.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
const FILE: &str = r#"let a1: List<u32, 5> = None;
let x: u32 = Left(
Right(0)
);"#;
const EMPTY_FILE: &str = "";
#[test]
fn display_single_line() {
let error = Error::ListBoundPow2(5)
.with_span(Span::new(13, 19))
.with_file(Arc::from(FILE));
let expected = r#"
|
1 | let a1: List<u32, 5> = None;
| ^^^^^^ Expected a power of two greater than one (2, 4, 8, 16, 32, ...) as list bound, found 5"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_multi_line() {
let error = Error::CannotParse(
"Expected value of type `u32`, got `Either<Either<_, u32>, _>`".to_string(),
)
.with_span(Span::new(41, FILE.len()))
.with_file(Arc::from(FILE));
let expected = r#"
|
2 | let x: u32 = Left(
3 | Right(0)
4 | );
| ^^^^^^^^^^^^^^^^^^ Cannot parse: Expected value of type `u32`, got `Either<Either<_, u32>, _>`"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_entire_file() {
let error = Error::CannotParse("This span covers the entire file".to_string())
.with_span(Span::from(FILE))
.with_file(Arc::from(FILE));
let expected = r#"
|
1 | let a1: List<u32, 5> = None;
2 | let x: u32 = Left(
3 | Right(0)
4 | );
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Cannot parse: This span covers the entire file"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_no_file() {
let error = Error::CannotParse("This error has no file".to_string())
.with_span(Span::from(EMPTY_FILE));
let expected = "Cannot parse: This error has no file";
assert_eq!(&expected, &error.to_string());
let error =
Error::CannotParse("This error has no file".to_string()).with_span(Span::new(5, 10));
assert_eq!(&expected, &error.to_string());
}
#[test]
fn display_empty_file() {
let error = Error::CannotParse("This error has an empty file".to_string())
.with_span(Span::from(EMPTY_FILE))
.with_file(Arc::from(EMPTY_FILE));
let expected = "Cannot parse: This error has an empty file";
assert_eq!(&expected, &error.to_string());
}
#[test]
fn display_with_utf16_chars() {
let file = "/*😀*/ let a: u8 = 65536;";
let error = Error::CannotParse("number too large to fit in target type".to_string())
.with_span(Span::new(21, 26))
.with_file(Arc::from(file));
let expected = r#"
|
1 | /*😀*/ let a: u8 = 65536;
| ^^^^^ Cannot parse: number too large to fit in target type"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn multiline_display_with_utf16_chars() {
let file = r#"/*😀 this symbol should not break the rendering*/
let a: u8 = 65536;
let x: u32 = Left(
Right(0)
);"#;
let error = Error::CannotParse("This span covers the entire file".to_string())
.with_span(Span::from(file))
.with_file(Arc::from(file));
let expected = r#"
|
1 | /*😀 this symbol should not break the rendering*/
2 | let a: u8 = 65536;
3 | let x: u32 = Left(
4 | Right(0)
5 | );
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Cannot parse: This span covers the entire file"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_with_unicode_separator() {
let file = "let a: u8 = 65536;\u{2028}let b: u8 = 0;";
let error = Error::CannotParse("number too large to fit in target type".to_string())
.with_span(Span::new(12, 17))
.with_file(Arc::from(file));
let expected = r#"
|
1 | let a: u8 = 65536;
| ^^^^^ Cannot parse: number too large to fit in target type"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_with_windows_crlf_newlines() {
let file = "let a: u8 = 65536;\r\nlet b: u8 = 0;";
let error = Error::CannotParse("number too large to fit in target type".to_string())
.with_span(Span::new(12, 17))
.with_file(Arc::from(file));
let expected = r#"
|
1 | let a: u8 = 65536;
| ^^^^^ Cannot parse: number too large to fit in target type"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_with_unix_lf_newlines() {
let file = "let a: u8 = 65536;\nlet b: u8 = 0;";
let error = Error::CannotParse("number too large to fit in target type".to_string())
.with_span(Span::new(12, 17))
.with_file(Arc::from(file));
let expected = r#"
|
1 | let a: u8 = 65536;
| ^^^^^ Cannot parse: number too large to fit in target type"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_with_mixed_newlines_on_second_line() {
let file = "line1\r\nline2\nline3";
let error = Error::CannotParse("err".to_string())
.with_span(Span::new(7, 12))
.with_file(Arc::from(file));
let expected = r#"
|
2 | line2
| ^^^^^ Cannot parse: err"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_does_not_insert_extra_blank_line_for_crlf() {
let file = "a\r\nb";
let error = Error::CannotParse("err".to_string())
.with_span(Span::new(3, 4))
.with_file(Arc::from(file));
let expected = r#"
|
2 | b
| ^ Cannot parse: err"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_handles_utf16_columns_after_newline() {
let file = "x\r\n😀ab";
let error = Error::CannotParse("err".to_string())
.with_span(Span::new(7, 9))
.with_file(Arc::from(file));
let expected = r#"
|
2 | 😀ab
| ^^ Cannot parse: err"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_span_as_point() {
let file = "fn main()";
let error = Error::Grammar("Error span at (0,0)".to_string())
.with_span(Span::new(0, 0))
.with_file(Arc::from(file));
let expected = r#"
|
1 | fn main()
| ^ Grammar error: Error span at (0,0)"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_span_as_point_on_trailing_empty_line() {
let file = "fn main(){\n let a:\n";
let error = Error::CannotParse("eof".to_string())
.with_span(Span::new(file.len(), file.len()))
.with_file(Arc::from(file));
let expected = r#"
|
3 |
| ^ Cannot parse: eof"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_zero_length_span_shows_single_caret() {
let file = "let a: u8 = 1;";
let error = Error::CannotParse("err".to_string())
.with_span(Span::new(12, 12))
.with_file(Arc::from(file));
let expected = r#"
|
1 | let a: u8 = 1;
| ^ Cannot parse: err"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_with_cr_only_newlines() {
let file = "let a: u8 = 0;\rlet b: u8 = 65536;";
let error = Error::CannotParse("number too large to fit in target type".to_string())
.with_span(Span::new(27, 32))
.with_file(Arc::from(file));
let expected = r#"
|
2 | let b: u8 = 65536;
| ^^^^^ Cannot parse: number too large to fit in target type"#;
assert_eq!(&expected[1..], &error.to_string());
}
#[test]
fn display_span_as_point_on_trailing_cr_only_empty_line() {
let file = "fn main(){\r let a:\r";
let error = Error::CannotParse("eof".to_string())
.with_span(Span::new(file.len(), file.len()))
.with_file(Arc::from(file));
let expected = r#"
|
3 |
| ^ Cannot parse: eof"#;
assert_eq!(&expected[1..], &error.to_string());
}
}