2 use std::sync::atomic::{AtomicBool, Ordering};
4 use rustc_data_structures::sync::{Lrc, Send};
5 use rustc_errors::emitter::{Emitter, EmitterWriter};
6 use rustc_errors::{ColorConfig, Diagnostic, Handler, Level as DiagnosticLevel};
7 use rustc_session::parse::ParseSess as RawParseSess;
9 source_map::{FilePathMapping, SourceMap},
10 symbol, BytePos, Span,
13 use crate::config::file_lines::LineRange;
14 use crate::ignore_path::IgnorePathSet;
15 use crate::source_map::LineRangeUtils;
16 use crate::utils::starts_with_newline;
17 use crate::visitor::SnippetProvider;
18 use crate::{Config, ErrorKind, FileName};
20 /// ParseSess holds structs necessary for constructing a parser.
21 pub(crate) struct ParseSess {
22 parse_sess: RawParseSess,
23 ignore_path_set: Lrc<IgnorePathSet>,
24 can_reset_errors: Lrc<AtomicBool>,
27 /// Emitter which discards every error.
30 impl Emitter for SilentEmitter {
31 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
34 fn emit_diagnostic(&mut self, _db: &Diagnostic) {}
37 fn silent_emitter() -> Box<dyn Emitter + Send> {
38 Box::new(SilentEmitter {})
41 /// Emit errors against every files expect ones specified in the `ignore_path_set`.
42 struct SilentOnIgnoredFilesEmitter {
43 ignore_path_set: Lrc<IgnorePathSet>,
44 source_map: Lrc<SourceMap>,
45 emitter: Box<dyn Emitter + Send>,
46 has_non_ignorable_parser_errors: bool,
47 can_reset: Lrc<AtomicBool>,
50 impl SilentOnIgnoredFilesEmitter {
51 fn handle_non_ignoreable_error(&mut self, db: &Diagnostic) {
52 self.has_non_ignorable_parser_errors = true;
53 self.can_reset.store(false, Ordering::Release);
54 self.emitter.emit_diagnostic(db);
58 impl Emitter for SilentOnIgnoredFilesEmitter {
59 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
62 fn emit_diagnostic(&mut self, db: &Diagnostic) {
63 if db.level == DiagnosticLevel::Fatal {
64 return self.handle_non_ignoreable_error(db);
66 if let Some(primary_span) = &db.span.primary_span() {
67 let file_name = self.source_map.span_to_filename(*primary_span);
68 if let rustc_span::FileName::Real(rustc_span::RealFileName::LocalPath(ref path)) =
73 .is_match(&FileName::Real(path.to_path_buf()))
75 if !self.has_non_ignorable_parser_errors {
76 self.can_reset.store(true, Ordering::Release);
82 self.handle_non_ignoreable_error(db);
87 source_map: Lrc<SourceMap>,
88 ignore_path_set: Lrc<IgnorePathSet>,
89 can_reset: Lrc<AtomicBool>,
90 hide_parse_errors: bool,
92 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
93 let color_cfg = if supports_color {
99 let emitter = if hide_parse_errors {
102 Box::new(EmitterWriter::stderr(
104 Some(source_map.clone()),
111 Handler::with_emitter(
114 Box::new(SilentOnIgnoredFilesEmitter {
115 has_non_ignorable_parser_errors: false,
125 pub(crate) fn new(config: &Config) -> Result<ParseSess, ErrorKind> {
126 let ignore_path_set = match IgnorePathSet::from_ignore_list(&config.ignore()) {
127 Ok(ignore_path_set) => Lrc::new(ignore_path_set),
128 Err(e) => return Err(ErrorKind::InvalidGlobPattern(e)),
130 let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
131 let can_reset_errors = Lrc::new(AtomicBool::new(false));
133 let handler = default_handler(
134 Lrc::clone(&source_map),
135 Lrc::clone(&ignore_path_set),
136 Lrc::clone(&can_reset_errors),
137 config.hide_parse_errors(),
139 let parse_sess = RawParseSess::with_span_handler(handler, source_map);
148 pub(crate) fn default_submod_path(
151 relative: Option<symbol::Ident>,
153 ) -> Result<rustc_expand::module::ModulePathSuccess, rustc_expand::module::ModError<'_>> {
154 rustc_expand::module::default_submod_path(&self.parse_sess, id, relative, dir_path)
157 pub(crate) fn is_file_parsed(&self, path: &Path) -> bool {
160 .get_source_file(&rustc_span::FileName::Real(
161 rustc_span::RealFileName::LocalPath(path.to_path_buf()),
166 pub(crate) fn ignore_file(&self, path: &FileName) -> bool {
167 self.ignore_path_set.as_ref().is_match(path)
170 pub(crate) fn set_silent_emitter(&mut self) {
171 self.parse_sess.span_diagnostic = Handler::with_emitter(true, None, silent_emitter());
174 pub(crate) fn span_to_filename(&self, span: Span) -> FileName {
175 self.parse_sess.source_map().span_to_filename(span).into()
178 pub(crate) fn span_to_file_contents(&self, span: Span) -> Lrc<rustc_span::SourceFile> {
181 .lookup_source_file(span.data().lo)
184 pub(crate) fn span_to_first_line_string(&self, span: Span) -> String {
185 let file_lines = self.parse_sess.source_map().span_to_lines(span).ok();
190 .get_line(fl.lines[0].line_index)
191 .map_or_else(String::new, |s| s.to_string()),
192 None => String::new(),
196 pub(crate) fn line_of_byte_pos(&self, pos: BytePos) -> usize {
197 self.parse_sess.source_map().lookup_char_pos(pos).line
200 pub(crate) fn span_to_debug_info(&self, span: Span) -> String {
201 self.parse_sess.source_map().span_to_diagnostic_string(span)
204 pub(crate) fn inner(&self) -> &RawParseSess {
208 pub(crate) fn snippet_provider(&self, span: Span) -> SnippetProvider {
209 let source_file = self.parse_sess.source_map().lookup_char_pos(span.lo()).file;
210 SnippetProvider::new(
211 source_file.start_pos,
213 Lrc::clone(source_file.src.as_ref().unwrap()),
217 pub(crate) fn get_original_snippet(&self, file_name: &FileName) -> Option<Lrc<String>> {
220 .get_source_file(&file_name.into())
221 .and_then(|source_file| source_file.src.clone())
225 // Methods that should be restricted within the syntux module.
227 pub(super) fn emit_diagnostics(&self, diagnostics: Vec<Diagnostic>) {
228 for diagnostic in diagnostics {
229 self.parse_sess.span_diagnostic.emit_diagnostic(&diagnostic);
233 pub(crate) fn emit_or_cancel_diagnostic(&self, diagnostic: &mut Diagnostic) {
234 self.parse_sess.span_diagnostic.emit_diagnostic(diagnostic);
235 // The Handler will check whether the diagnostic should be emitted
236 // based on the user's rustfmt configuration and the originating file
237 // that caused the parser error. If the Handler determined it should skip
238 // emission then we need to ensure the diagnostic is cancelled.
239 if !diagnostic.cancelled() {
244 pub(super) fn can_reset_errors(&self) -> bool {
245 self.can_reset_errors.load(Ordering::Acquire)
248 pub(super) fn has_errors(&self) -> bool {
249 self.parse_sess.span_diagnostic.has_errors()
252 pub(super) fn reset_errors(&self) {
253 self.parse_sess.span_diagnostic.reset_err_count();
257 impl LineRangeUtils for ParseSess {
258 fn lookup_line_range(&self, span: Span) -> LineRange {
262 .span_to_snippet(span)
263 .unwrap_or_default();
264 let lo = self.parse_sess.source_map().lookup_line(span.lo()).unwrap();
265 let hi = self.parse_sess.source_map().lookup_line(span.hi()).unwrap();
268 lo.sf.name, hi.sf.name,
269 "span crossed file boundary: lo: {:?}, hi: {:?}",
273 // in case the span starts with a newline, the line range is off by 1 without the
275 let offset = 1 + if starts_with_newline(&snippet) { 1 } else { 0 };
276 // Line numbers start at 1
279 lo: lo.line + offset,
280 hi: hi.line + offset,
291 use crate::config::IgnoreList;
292 use crate::is_nightly_channel;
293 use crate::utils::mk_sp;
294 use rustc_span::{FileName as SourceMapFileName, MultiSpan, RealFileName, DUMMY_SP};
295 use std::path::PathBuf;
296 use std::sync::atomic::AtomicU32;
299 num_emitted_errors: Lrc<AtomicU32>,
302 impl Emitter for TestEmitter {
303 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
306 fn emit_diagnostic(&mut self, _db: &Diagnostic) {
307 self.num_emitted_errors.fetch_add(1, Ordering::Release);
311 fn build_diagnostic(level: DiagnosticLevel, span: Option<MultiSpan>) -> Diagnostic {
318 span: span.unwrap_or_else(MultiSpan::new),
325 num_emitted_errors: Lrc<AtomicU32>,
326 can_reset: Lrc<AtomicBool>,
327 source_map: Option<Lrc<SourceMap>>,
328 ignore_list: Option<IgnoreList>,
329 ) -> SilentOnIgnoredFilesEmitter {
330 let emitter_writer = TestEmitter { num_emitted_errors };
332 source_map.unwrap_or_else(|| Lrc::new(SourceMap::new(FilePathMapping::empty())));
333 let ignore_path_set = Lrc::new(
334 IgnorePathSet::from_ignore_list(&ignore_list.unwrap_or_default()).unwrap(),
336 SilentOnIgnoredFilesEmitter {
337 has_non_ignorable_parser_errors: false,
339 emitter: Box::new(emitter_writer),
345 fn get_ignore_list(config: &str) -> IgnoreList {
346 Config::from_toml(config, Path::new("")).unwrap().ignore()
350 fn handles_fatal_parse_error_in_ignored_file() {
351 let num_emitted_errors = Lrc::new(AtomicU32::new(0));
352 let can_reset_errors = Lrc::new(AtomicBool::new(false));
353 let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#);
354 let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
356 String::from(r#"extern "system" fn jni_symbol!( funcName ) ( ... ) -> {} "#);
357 source_map.new_source_file(
358 SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))),
361 let mut emitter = build_emitter(
362 Lrc::clone(&num_emitted_errors),
363 Lrc::clone(&can_reset_errors),
364 Some(Lrc::clone(&source_map)),
367 let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
368 let fatal_diagnostic = build_diagnostic(DiagnosticLevel::Fatal, Some(span));
369 emitter.emit_diagnostic(&fatal_diagnostic);
370 assert_eq!(num_emitted_errors.load(Ordering::Acquire), 1);
371 assert_eq!(can_reset_errors.load(Ordering::Acquire), false);
375 fn handles_recoverable_parse_error_in_ignored_file() {
376 if !is_nightly_channel!() {
379 let num_emitted_errors = Lrc::new(AtomicU32::new(0));
380 let can_reset_errors = Lrc::new(AtomicBool::new(false));
381 let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#);
382 let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
383 let source = String::from(r#"pub fn bar() { 1x; }"#);
384 source_map.new_source_file(
385 SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))),
388 let mut emitter = build_emitter(
389 Lrc::clone(&num_emitted_errors),
390 Lrc::clone(&can_reset_errors),
391 Some(Lrc::clone(&source_map)),
394 let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
395 let non_fatal_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(span));
396 emitter.emit_diagnostic(&non_fatal_diagnostic);
397 assert_eq!(num_emitted_errors.load(Ordering::Acquire), 0);
398 assert_eq!(can_reset_errors.load(Ordering::Acquire), true);
402 fn handles_recoverable_parse_error_in_non_ignored_file() {
403 if !is_nightly_channel!() {
406 let num_emitted_errors = Lrc::new(AtomicU32::new(0));
407 let can_reset_errors = Lrc::new(AtomicBool::new(false));
408 let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
409 let source = String::from(r#"pub fn bar() { 1x; }"#);
410 source_map.new_source_file(
411 SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))),
414 let mut emitter = build_emitter(
415 Lrc::clone(&num_emitted_errors),
416 Lrc::clone(&can_reset_errors),
417 Some(Lrc::clone(&source_map)),
420 let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
421 let non_fatal_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(span));
422 emitter.emit_diagnostic(&non_fatal_diagnostic);
423 assert_eq!(num_emitted_errors.load(Ordering::Acquire), 1);
424 assert_eq!(can_reset_errors.load(Ordering::Acquire), false);
428 fn handles_mix_of_recoverable_parse_error() {
429 if !is_nightly_channel!() {
432 let num_emitted_errors = Lrc::new(AtomicU32::new(0));
433 let can_reset_errors = Lrc::new(AtomicBool::new(false));
434 let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
435 let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#);
436 let bar_source = String::from(r#"pub fn bar() { 1x; }"#);
437 let foo_source = String::from(r#"pub fn foo() { 1x; }"#);
439 String::from(r#"extern "system" fn jni_symbol!( funcName ) ( ... ) -> {} "#);
440 source_map.new_source_file(
441 SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("bar.rs"))),
444 source_map.new_source_file(
445 SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))),
448 source_map.new_source_file(
449 SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("fatal.rs"))),
452 let mut emitter = build_emitter(
453 Lrc::clone(&num_emitted_errors),
454 Lrc::clone(&can_reset_errors),
455 Some(Lrc::clone(&source_map)),
458 let bar_span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
459 let foo_span = MultiSpan::from_span(mk_sp(BytePos(21), BytePos(22)));
460 let bar_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(bar_span));
461 let foo_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(foo_span));
462 let fatal_diagnostic = build_diagnostic(DiagnosticLevel::Fatal, None);
463 emitter.emit_diagnostic(&bar_diagnostic);
464 emitter.emit_diagnostic(&foo_diagnostic);
465 emitter.emit_diagnostic(&fatal_diagnostic);
466 assert_eq!(num_emitted_errors.load(Ordering::Acquire), 2);
467 assert_eq!(can_reset_errors.load(Ordering::Acquire), false);