1 use rustc_parse::{source_file_to_stream, new_parser_from_source_str, parser::Parser};
3 use syntax::tokenstream::TokenStream;
4 use syntax::sess::ParseSess;
5 use syntax::source_map::{SourceMap, FilePathMapping};
6 use syntax::with_default_globals;
7 use syntax_pos::{BytePos, Span, MultiSpan};
9 use errors::emitter::EmitterWriter;
10 use errors::{PResult, Handler};
11 use rustc_data_structures::sync::Lrc;
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 crate fn with_error_checking_parse<'a, T, F>(s: String, ps: &'a ParseSess, f: F) -> T where
26 F: FnOnce(&mut Parser<'a>) -> PResult<'a, T>,
28 let mut p = string_to_parser(&ps, s);
29 let x = f(&mut p).unwrap();
30 p.sess.span_diagnostic.abort_if_errors();
34 /// Maps a string to tts, using a made-up filename.
35 crate fn string_to_stream(source_str: String) -> TokenStream {
36 let ps = ParseSess::new(FilePathMapping::empty());
37 source_file_to_stream(
39 ps.source_map().new_source_file(PathBuf::from("bogofile").into(),
44 /// Parses a string, returns a crate.
45 crate fn string_to_crate(source_str : String) -> ast::Crate {
46 let ps = ParseSess::new(FilePathMapping::empty());
47 with_error_checking_parse(source_str, &ps, |p| {
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 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(|c| rustc_lexer::is_whitespace(c)) == Some(true) {
100 /// Identifies a position in the text by the n'th occurrence of a string.
102 string: &'static str,
112 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 with_default_globals(|| {
128 let output = Arc::new(Mutex::new(Vec::new()));
130 let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
131 source_map.new_source_file(Path::new("test.rs").to_owned().into(), file_text.to_owned());
133 let primary_span = make_span(&file_text, &span_labels[0].start, &span_labels[0].end);
134 let mut msp = MultiSpan::from_span(primary_span);
135 for span_label in span_labels {
136 let span = make_span(&file_text, &span_label.start, &span_label.end);
137 msp.push_span_label(span, span_label.label.to_string());
138 println!("span: {:?} label: {:?}", span, span_label.label);
139 println!("text: {:?}", source_map.span_to_snippet(span));
142 let emitter = EmitterWriter::new(
143 Box::new(Shared { data: output.clone() }),
144 Some(source_map.clone()),
151 let handler = Handler::with_emitter(true, None, Box::new(emitter));
152 handler.span_err(msp, "foo");
154 assert!(expected_output.chars().next() == Some('\n'),
155 "expected output should begin with newline");
156 let expected_output = &expected_output[1..];
158 let bytes = output.lock().unwrap();
159 let actual_output = str::from_utf8(&bytes).unwrap();
160 println!("expected output:\n------\n{}------", expected_output);
161 println!("actual output:\n------\n{}------", actual_output);
163 assert!(expected_output == actual_output)
167 fn make_span(file_text: &str, start: &Position, end: &Position) -> Span {
168 let start = make_pos(file_text, start);
169 let end = make_pos(file_text, end) + end.string.len(); // just after matching thing ends
170 assert!(start <= end);
171 Span::with_root_ctxt(BytePos(start as u32), BytePos(end as u32))
174 fn make_pos(file_text: &str, pos: &Position) -> usize {
175 let mut remainder = file_text;
177 for _ in 0..pos.count {
178 if let Some(n) = remainder.find(&pos.string) {
180 remainder = &remainder[n + 1..];
182 panic!("failed to find {} instances of {:?} in {:?}",
275 label: "`X` is a good letter",
286 label: "`Y` is a good letter too",
299 | ||____^__- `Y` is a good letter too
301 | `X` is a good letter
324 label: "`X` is a good letter",
335 label: "`Y` is a good letter too",
347 | ||____-__^ `X` is a good letter
349 | `Y` is a good letter too
355 fn different_overlap() {
374 label: "`X` is a good letter",
385 label: "`Y` is a good letter too",
397 | ||____^ `X` is a good letter
399 | |_____- `Y` is a good letter too
405 fn triple_overlap() {
423 label: "`X` is a good letter",
434 label: "`Y` is a good letter too",
459 | |||____^__-__- `Z` label
461 | |____| `Y` is a good letter too
462 | `X` is a good letter
468 fn triple_exact_overlap() {
486 label: "`X` is a good letter",
497 label: "`Y` is a good letter too",
520 | | `X` is a good letter
521 | |____`Y` is a good letter too
547 label: "`X` is a good letter",
558 label: "`Y` is a good letter too",
581 | | `X` is a good letter
583 | |____-______- `Y` is a good letter too
593 fn non_overlaping() {
612 label: "`X` is a good letter",
623 label: "`Y` is a good letter too",
632 | |____^ `X` is a good letter
636 | |__________- `Y` is a good letter too
642 fn overlaping_start_and_end() {
661 label: "`X` is a good letter",
672 label: "`Y` is a good letter too",
684 | | `X` is a good letter
687 | |___________- `Y` is a good letter too
693 fn multiple_labels_primary_without_message() {
720 label: "`a` is a good letter",
739 | ----^^^^-^^-- `a` is a good letter
745 fn multiple_labels_secondary_without_message() {
761 label: "`a` is a good letter",
780 | ^^^^-------^^ `a` is a good letter
786 fn multiple_labels_primary_without_message_2() {
802 label: "`b` is a good letter",
834 | `b` is a good letter
840 fn multiple_labels_secondary_without_message_2() {
867 label: "`b` is a good letter",
877 | `b` is a good letter
883 fn multiple_labels_secondary_without_message_3() {
899 label: "`a` is a good letter",
920 | `a` is a good letter
926 fn multiple_labels_without_message() {
967 fn multiple_labels_without_message_2() {
1019 fn multiple_labels_with_message() {
1035 label: "`a` is a good letter",
1046 label: "`b` is a good letter",
1056 | | `b` is a good letter
1057 | `a` is a good letter
1063 fn single_label_with_message() {
1079 label: "`a` is a good letter",
1087 | ^^^^^^^^^^^^^ `a` is a good letter
1093 fn single_label_without_message() {
1152 label: "`X` is a good letter",
1163 label: "`Y` is a good letter too",
1175 | | `X` is a good letter
1182 | |___________- `Y` is a good letter too
1188 fn long_snippet_multiple_spans() {
1217 label: "`Y` is a good letter",
1228 label: "`Z` is a good letter too",
1246 | ||__________- `Z` is a good letter too
1250 | |_______^ `Y` is a good letter