2 use rustc_ast::tokenstream::TokenStream;
3 use rustc_parse::{new_parser_from_source_str, parser::Parser, source_file_to_stream};
4 use rustc_session::parse::ParseSess;
5 use rustc_span::create_default_session_if_not_set_then;
6 use rustc_span::source_map::{FilePathMapping, SourceMap};
7 use rustc_span::{BytePos, Span};
9 use rustc_data_structures::sync::Lrc;
10 use rustc_errors::emitter::EmitterWriter;
11 use rustc_errors::{Handler, MultiSpan, PResult};
14 use std::io::prelude::*;
15 use std::iter::Peekable;
16 use std::path::{Path, PathBuf};
18 use std::sync::{Arc, Mutex};
20 /// Map string to parser (via tts).
21 fn string_to_parser(ps: &ParseSess, source_str: String) -> Parser<'_> {
22 new_parser_from_source_str(ps, PathBuf::from("bogofile").into(), source_str)
25 pub(crate) fn with_error_checking_parse<'a, T, F>(s: String, ps: &'a ParseSess, f: F) -> T
27 F: FnOnce(&mut Parser<'a>) -> PResult<'a, T>,
29 let mut p = string_to_parser(&ps, s);
30 let x = f(&mut p).unwrap();
31 p.sess.span_diagnostic.abort_if_errors();
35 /// Maps a string to tts, using a made-up filename.
36 pub(crate) fn string_to_stream(source_str: String) -> TokenStream {
37 let ps = ParseSess::new(FilePathMapping::empty());
38 source_file_to_stream(
40 ps.source_map().new_source_file(PathBuf::from("bogofile").into(), source_str),
46 /// Parses a string, returns a crate.
47 pub(crate) fn string_to_crate(source_str: String) -> ast::Crate {
48 let ps = ParseSess::new(FilePathMapping::empty());
49 with_error_checking_parse(source_str, &ps, |p| p.parse_crate_mod())
52 /// Does the given string match the pattern? whitespace in the first string
53 /// may be deleted or replaced with other whitespace to match the pattern.
54 /// This function is relatively Unicode-ignorant; fortunately, the careful design
55 /// of UTF-8 mitigates this ignorance. It doesn't do NKF-normalization(?).
56 pub(crate) fn matches_codepattern(a: &str, b: &str) -> bool {
57 let mut a_iter = a.chars().peekable();
58 let mut b_iter = b.chars().peekable();
61 let (a, b) = match (a_iter.peek(), b_iter.peek()) {
62 (None, None) => return true,
63 (None, _) => return false,
65 if rustc_lexer::is_whitespace(a) {
66 break; // Trailing whitespace check is out of loop for borrowck.
71 (Some(&a), Some(&b)) => (a, b),
74 if rustc_lexer::is_whitespace(a) && rustc_lexer::is_whitespace(b) {
75 // Skip whitespace for `a` and `b`.
76 scan_for_non_ws_or_end(&mut a_iter);
77 scan_for_non_ws_or_end(&mut b_iter);
78 } else if rustc_lexer::is_whitespace(a) {
79 // Skip whitespace for `a`.
80 scan_for_non_ws_or_end(&mut a_iter);
89 // Check if a has *only* trailing whitespace.
90 a_iter.all(rustc_lexer::is_whitespace)
93 /// Advances the given peekable `Iterator` until it reaches a non-whitespace character.
94 fn scan_for_non_ws_or_end<I: Iterator<Item = char>>(iter: &mut Peekable<I>) {
95 while iter.peek().copied().map(rustc_lexer::is_whitespace) == Some(true) {
100 /// Identifies a position in the text by the n'th occurrence of a string.
102 string: &'static str,
112 pub(crate) struct Shared<T: Write> {
113 pub data: Arc<Mutex<T>>,
116 impl<T: Write> Write for Shared<T> {
117 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
118 self.data.lock().unwrap().write(buf)
121 fn flush(&mut self) -> io::Result<()> {
122 self.data.lock().unwrap().flush()
126 fn test_harness(file_text: &str, span_labels: Vec<SpanLabel>, expected_output: &str) {
127 create_default_session_if_not_set_then(|_| {
128 let output = Arc::new(Mutex::new(Vec::new()));
130 let fallback_bundle =
131 rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
132 let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
133 source_map.new_source_file(Path::new("test.rs").to_owned().into(), file_text.to_owned());
135 let primary_span = make_span(&file_text, &span_labels[0].start, &span_labels[0].end);
136 let mut msp = MultiSpan::from_span(primary_span);
137 for span_label in span_labels {
138 let span = make_span(&file_text, &span_label.start, &span_label.end);
139 msp.push_span_label(span, span_label.label);
140 println!("span: {:?} label: {:?}", span, span_label.label);
141 println!("text: {:?}", source_map.span_to_snippet(span));
144 let emitter = EmitterWriter::new(
145 Box::new(Shared { data: output.clone() }),
146 Some(source_map.clone()),
155 let handler = Handler::with_emitter(true, None, Box::new(emitter));
156 handler.span_err(msp, "foo");
159 expected_output.chars().next() == Some('\n'),
160 "expected output should begin with newline"
162 let expected_output = &expected_output[1..];
164 let bytes = output.lock().unwrap();
165 let actual_output = str::from_utf8(&bytes).unwrap();
166 println!("expected output:\n------\n{}------", expected_output);
167 println!("actual output:\n------\n{}------", actual_output);
169 assert!(expected_output == actual_output)
173 fn make_span(file_text: &str, start: &Position, end: &Position) -> Span {
174 let start = make_pos(file_text, start);
175 let end = make_pos(file_text, end) + end.string.len(); // just after matching thing ends
176 assert!(start <= end);
177 Span::with_root_ctxt(BytePos(start as u32), BytePos(end as u32))
180 fn make_pos(file_text: &str, pos: &Position) -> usize {
181 let mut remainder = file_text;
183 for _ in 0..pos.count {
184 if let Some(n) = remainder.find(&pos.string) {
186 remainder = &remainder[n + 1..];
188 panic!("failed to find {} instances of {:?} in {:?}", pos.count, pos.string, file_text);
202 start: Position { string: "{", count: 1 },
203 end: Position { string: "}", count: 1 },
229 start: Position { string: "{", count: 1 },
230 end: Position { string: "}", count: 1 },
259 start: Position { string: "X0", count: 1 },
260 end: Position { string: "X2", count: 1 },
261 label: "`X` is a good letter",
264 start: Position { string: "Y0", count: 1 },
265 end: Position { string: "Y2", count: 1 },
266 label: "`Y` is a good letter too",
279 | ||____^__- `Y` is a good letter too
281 | `X` is a good letter
298 start: Position { string: "X0", count: 1 },
299 end: Position { string: "X1", count: 1 },
300 label: "`X` is a good letter",
303 start: Position { string: "Y0", count: 1 },
304 end: Position { string: "Y1", count: 1 },
305 label: "`Y` is a good letter too",
317 | ||____-__^ `X` is a good letter
319 | `Y` is a good letter too
326 fn different_overlap() {
338 start: Position { string: "Y0", count: 1 },
339 end: Position { string: "X2", count: 1 },
340 label: "`X` is a good letter",
343 start: Position { string: "Z1", count: 1 },
344 end: Position { string: "X3", count: 1 },
345 label: "`Y` is a good letter too",
357 | ||____^ `X` is a good letter
359 | |_____- `Y` is a good letter too
366 fn triple_overlap() {
377 start: Position { string: "X0", count: 1 },
378 end: Position { string: "X2", count: 1 },
379 label: "`X` is a good letter",
382 start: Position { string: "Y0", count: 1 },
383 end: Position { string: "Y2", count: 1 },
384 label: "`Y` is a good letter too",
387 start: Position { string: "Z0", count: 1 },
388 end: Position { string: "Z2", count: 1 },
403 | |||____^__-__- `Z` label
405 | |____| `Y` is a good letter too
406 | `X` is a good letter
413 fn triple_exact_overlap() {
424 start: Position { string: "X0", count: 1 },
425 end: Position { string: "X2", count: 1 },
426 label: "`X` is a good letter",
429 start: Position { string: "X0", count: 1 },
430 end: Position { string: "X2", count: 1 },
431 label: "`Y` is a good letter too",
434 start: Position { string: "X0", count: 1 },
435 end: Position { string: "X2", count: 1 },
448 | | `X` is a good letter
449 | |____`Y` is a good letter too
469 start: Position { string: "Y0", count: 1 },
470 end: Position { string: "X1", count: 1 },
471 label: "`X` is a good letter",
474 start: Position { string: "Y1", count: 1 },
475 end: Position { string: "Z2", count: 1 },
476 label: "`Y` is a good letter too",
479 start: Position { string: "X2", count: 1 },
480 end: Position { string: "Y3", count: 1 },
493 | | `X` is a good letter
495 | |____-______- `Y` is a good letter too
506 fn non_overlaping() {
518 start: Position { string: "X0", count: 1 },
519 end: Position { string: "X1", count: 1 },
520 label: "`X` is a good letter",
523 start: Position { string: "Y2", count: 1 },
524 end: Position { string: "Z3", count: 1 },
525 label: "`Y` is a good letter too",
534 | |____^ `X` is a good letter
538 | |__________- `Y` is a good letter too
545 fn overlaping_start_and_end() {
557 start: Position { string: "Y0", count: 1 },
558 end: Position { string: "X1", count: 1 },
559 label: "`X` is a good letter",
562 start: Position { string: "Z1", count: 1 },
563 end: Position { string: "Z3", count: 1 },
564 label: "`Y` is a good letter too",
576 | | `X` is a good letter
579 | |___________- `Y` is a good letter too
586 fn multiple_labels_primary_without_message() {
595 start: Position { string: "b", count: 1 },
596 end: Position { string: "}", count: 1 },
600 start: Position { string: "a", count: 1 },
601 end: Position { string: "d", count: 1 },
602 label: "`a` is a good letter",
605 start: Position { string: "c", count: 1 },
606 end: Position { string: "c", count: 1 },
615 | ----^^^^-^^-- `a` is a good letter
622 fn multiple_labels_secondary_without_message() {
631 start: Position { string: "a", count: 1 },
632 end: Position { string: "d", count: 1 },
633 label: "`a` is a good letter",
636 start: Position { string: "b", count: 1 },
637 end: Position { string: "}", count: 1 },
646 | ^^^^-------^^ `a` is a good letter
653 fn multiple_labels_primary_without_message_2() {
662 start: Position { string: "b", count: 1 },
663 end: Position { string: "}", count: 1 },
664 label: "`b` is a good letter",
667 start: Position { string: "a", count: 1 },
668 end: Position { string: "d", count: 1 },
672 start: Position { string: "c", count: 1 },
673 end: Position { string: "c", count: 1 },
684 | `b` is a good letter
691 fn multiple_labels_secondary_without_message_2() {
700 start: Position { string: "a", count: 1 },
701 end: Position { string: "d", count: 1 },
705 start: Position { string: "b", count: 1 },
706 end: Position { string: "}", count: 1 },
707 label: "`b` is a good letter",
717 | `b` is a good letter
724 fn multiple_labels_secondary_without_message_3() {
733 start: Position { string: "a", count: 1 },
734 end: Position { string: "b", count: 1 },
735 label: "`a` is a good letter",
738 start: Position { string: "c", count: 1 },
739 end: Position { string: "d", count: 1 },
750 | `a` is a good letter
757 fn multiple_labels_without_message() {
766 start: Position { string: "a", count: 1 },
767 end: Position { string: "d", count: 1 },
771 start: Position { string: "b", count: 1 },
772 end: Position { string: "}", count: 1 },
788 fn multiple_labels_without_message_2() {
797 start: Position { string: "b", count: 1 },
798 end: Position { string: "}", count: 1 },
802 start: Position { string: "a", count: 1 },
803 end: Position { string: "d", count: 1 },
807 start: Position { string: "c", count: 1 },
808 end: Position { string: "c", count: 1 },
824 fn multiple_labels_with_message() {
833 start: Position { string: "a", count: 1 },
834 end: Position { string: "d", count: 1 },
835 label: "`a` is a good letter",
838 start: Position { string: "b", count: 1 },
839 end: Position { string: "}", count: 1 },
840 label: "`b` is a good letter",
850 | | `b` is a good letter
851 | `a` is a good letter
858 fn single_label_with_message() {
866 start: Position { string: "a", count: 1 },
867 end: Position { string: "d", count: 1 },
868 label: "`a` is a good letter",
875 | ^^^^^^^^^^^^^ `a` is a good letter
882 fn single_label_without_message() {
890 start: Position { string: "a", count: 1 },
891 end: Position { string: "d", count: 1 },
928 start: Position { string: "Y0", count: 1 },
929 end: Position { string: "X1", count: 1 },
930 label: "`X` is a good letter",
933 start: Position { string: "Z1", count: 1 },
934 end: Position { string: "Z3", count: 1 },
935 label: "`Y` is a good letter too",
947 | | `X` is a good letter
954 | |___________- `Y` is a good letter too
961 fn long_snippet_multiple_spans() {
983 start: Position { string: "Y0", count: 1 },
984 end: Position { string: "Y3", count: 1 },
985 label: "`Y` is a good letter",
988 start: Position { string: "Z1", count: 1 },
989 end: Position { string: "Z2", count: 1 },
990 label: "`Z` is a good letter too",
1008 | ||__________- `Z` is a good letter too
1012 | |_______^ `Y` is a good letter