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()),
156 let handler = Handler::with_emitter(true, None, Box::new(emitter));
157 handler.span_err(msp, "foo");
160 expected_output.chars().next() == Some('\n'),
161 "expected output should begin with newline"
163 let expected_output = &expected_output[1..];
165 let bytes = output.lock().unwrap();
166 let actual_output = str::from_utf8(&bytes).unwrap();
167 println!("expected output:\n------\n{}------", expected_output);
168 println!("actual output:\n------\n{}------", actual_output);
170 assert!(expected_output == actual_output)
174 fn make_span(file_text: &str, start: &Position, end: &Position) -> Span {
175 let start = make_pos(file_text, start);
176 let end = make_pos(file_text, end) + end.string.len(); // just after matching thing ends
177 assert!(start <= end);
178 Span::with_root_ctxt(BytePos(start as u32), BytePos(end as u32))
181 fn make_pos(file_text: &str, pos: &Position) -> usize {
182 let mut remainder = file_text;
184 for _ in 0..pos.count {
185 if let Some(n) = remainder.find(&pos.string) {
187 remainder = &remainder[n + 1..];
189 panic!("failed to find {} instances of {:?} in {:?}", pos.count, pos.string, file_text);
203 start: Position { string: "{", count: 1 },
204 end: Position { string: "}", count: 1 },
230 start: Position { string: "{", count: 1 },
231 end: Position { string: "}", count: 1 },
260 start: Position { string: "X0", count: 1 },
261 end: Position { string: "X2", count: 1 },
262 label: "`X` is a good letter",
265 start: Position { string: "Y0", count: 1 },
266 end: Position { string: "Y2", count: 1 },
267 label: "`Y` is a good letter too",
280 | ||____^__- `Y` is a good letter too
282 | `X` is a good letter
299 start: Position { string: "X0", count: 1 },
300 end: Position { string: "X1", count: 1 },
301 label: "`X` is a good letter",
304 start: Position { string: "Y0", count: 1 },
305 end: Position { string: "Y1", count: 1 },
306 label: "`Y` is a good letter too",
318 | ||____-__^ `X` is a good letter
320 | `Y` is a good letter too
327 fn different_overlap() {
339 start: Position { string: "Y0", count: 1 },
340 end: Position { string: "X2", count: 1 },
341 label: "`X` is a good letter",
344 start: Position { string: "Z1", count: 1 },
345 end: Position { string: "X3", count: 1 },
346 label: "`Y` is a good letter too",
358 | ||____^ `X` is a good letter
360 | |_____- `Y` is a good letter too
367 fn triple_overlap() {
378 start: Position { string: "X0", count: 1 },
379 end: Position { string: "X2", count: 1 },
380 label: "`X` is a good letter",
383 start: Position { string: "Y0", count: 1 },
384 end: Position { string: "Y2", count: 1 },
385 label: "`Y` is a good letter too",
388 start: Position { string: "Z0", count: 1 },
389 end: Position { string: "Z2", count: 1 },
404 | |||____^__-__- `Z` label
406 | |____| `Y` is a good letter too
407 | `X` is a good letter
414 fn triple_exact_overlap() {
425 start: Position { string: "X0", count: 1 },
426 end: Position { string: "X2", count: 1 },
427 label: "`X` is a good letter",
430 start: Position { string: "X0", count: 1 },
431 end: Position { string: "X2", count: 1 },
432 label: "`Y` is a good letter too",
435 start: Position { string: "X0", count: 1 },
436 end: Position { string: "X2", count: 1 },
449 | | `X` is a good letter
450 | |____`Y` is a good letter too
470 start: Position { string: "Y0", count: 1 },
471 end: Position { string: "X1", count: 1 },
472 label: "`X` is a good letter",
475 start: Position { string: "Y1", count: 1 },
476 end: Position { string: "Z2", count: 1 },
477 label: "`Y` is a good letter too",
480 start: Position { string: "X2", count: 1 },
481 end: Position { string: "Y3", count: 1 },
494 | | `X` is a good letter
496 | |____-______- `Y` is a good letter too
507 fn non_overlaping() {
519 start: Position { string: "X0", count: 1 },
520 end: Position { string: "X1", count: 1 },
521 label: "`X` is a good letter",
524 start: Position { string: "Y2", count: 1 },
525 end: Position { string: "Z3", count: 1 },
526 label: "`Y` is a good letter too",
535 | |____^ `X` is a good letter
539 | |__________- `Y` is a good letter too
546 fn overlaping_start_and_end() {
558 start: Position { string: "Y0", count: 1 },
559 end: Position { string: "X1", count: 1 },
560 label: "`X` is a good letter",
563 start: Position { string: "Z1", count: 1 },
564 end: Position { string: "Z3", count: 1 },
565 label: "`Y` is a good letter too",
577 | | `X` is a good letter
580 | |___________- `Y` is a good letter too
587 fn multiple_labels_primary_without_message() {
596 start: Position { string: "b", count: 1 },
597 end: Position { string: "}", count: 1 },
601 start: Position { string: "a", count: 1 },
602 end: Position { string: "d", count: 1 },
603 label: "`a` is a good letter",
606 start: Position { string: "c", count: 1 },
607 end: Position { string: "c", count: 1 },
616 | ----^^^^-^^-- `a` is a good letter
623 fn multiple_labels_secondary_without_message() {
632 start: Position { string: "a", count: 1 },
633 end: Position { string: "d", count: 1 },
634 label: "`a` is a good letter",
637 start: Position { string: "b", count: 1 },
638 end: Position { string: "}", count: 1 },
647 | ^^^^-------^^ `a` is a good letter
654 fn multiple_labels_primary_without_message_2() {
663 start: Position { string: "b", count: 1 },
664 end: Position { string: "}", count: 1 },
665 label: "`b` is a good letter",
668 start: Position { string: "a", count: 1 },
669 end: Position { string: "d", count: 1 },
673 start: Position { string: "c", count: 1 },
674 end: Position { string: "c", count: 1 },
685 | `b` is a good letter
692 fn multiple_labels_secondary_without_message_2() {
701 start: Position { string: "a", count: 1 },
702 end: Position { string: "d", count: 1 },
706 start: Position { string: "b", count: 1 },
707 end: Position { string: "}", count: 1 },
708 label: "`b` is a good letter",
718 | `b` is a good letter
725 fn multiple_labels_secondary_without_message_3() {
734 start: Position { string: "a", count: 1 },
735 end: Position { string: "b", count: 1 },
736 label: "`a` is a good letter",
739 start: Position { string: "c", count: 1 },
740 end: Position { string: "d", count: 1 },
751 | `a` is a good letter
758 fn multiple_labels_without_message() {
767 start: Position { string: "a", count: 1 },
768 end: Position { string: "d", count: 1 },
772 start: Position { string: "b", count: 1 },
773 end: Position { string: "}", count: 1 },
789 fn multiple_labels_without_message_2() {
798 start: Position { string: "b", count: 1 },
799 end: Position { string: "}", count: 1 },
803 start: Position { string: "a", count: 1 },
804 end: Position { string: "d", count: 1 },
808 start: Position { string: "c", count: 1 },
809 end: Position { string: "c", count: 1 },
825 fn multiple_labels_with_message() {
834 start: Position { string: "a", count: 1 },
835 end: Position { string: "d", count: 1 },
836 label: "`a` is a good letter",
839 start: Position { string: "b", count: 1 },
840 end: Position { string: "}", count: 1 },
841 label: "`b` is a good letter",
851 | | `b` is a good letter
852 | `a` is a good letter
859 fn single_label_with_message() {
867 start: Position { string: "a", count: 1 },
868 end: Position { string: "d", count: 1 },
869 label: "`a` is a good letter",
876 | ^^^^^^^^^^^^^ `a` is a good letter
883 fn single_label_without_message() {
891 start: Position { string: "a", count: 1 },
892 end: Position { string: "d", count: 1 },
929 start: Position { string: "Y0", count: 1 },
930 end: Position { string: "X1", count: 1 },
931 label: "`X` is a good letter",
934 start: Position { string: "Z1", count: 1 },
935 end: Position { string: "Z3", count: 1 },
936 label: "`Y` is a good letter too",
948 | | `X` is a good letter
955 | |___________- `Y` is a good letter too
962 fn long_snippet_multiple_spans() {
984 start: Position { string: "Y0", count: 1 },
985 end: Position { string: "Y3", count: 1 },
986 label: "`Y` is a good letter",
989 start: Position { string: "Z1", count: 1 },
990 end: Position { string: "Z2", count: 1 },
991 label: "`Z` is a good letter too",
1009 | ||__________- `Z` is a good letter too
1013 | |_______^ `Y` is a good letter