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_first_line_string(&self, span: Span) -> String {
179 let file_lines = self.parse_sess.source_map().span_to_lines(span).ok();
184 .get_line(fl.lines[0].line_index)
185 .map_or_else(String::new, |s| s.to_string()),
186 None => String::new(),
190 pub(crate) fn line_of_byte_pos(&self, pos: BytePos) -> usize {
191 self.parse_sess.source_map().lookup_char_pos(pos).line
194 pub(crate) fn span_to_debug_info(&self, span: Span) -> String {
195 self.parse_sess.source_map().span_to_diagnostic_string(span)
198 pub(crate) fn inner(&self) -> &RawParseSess {
202 pub(crate) fn snippet_provider(&self, span: Span) -> SnippetProvider {
203 let source_file = self.parse_sess.source_map().lookup_char_pos(span.lo()).file;
204 SnippetProvider::new(
205 source_file.start_pos,
207 Lrc::clone(source_file.src.as_ref().unwrap()),
211 pub(crate) fn get_original_snippet(&self, file_name: &FileName) -> Option<Lrc<String>> {
214 .get_source_file(&file_name.into())
215 .and_then(|source_file| source_file.src.clone())
219 // Methods that should be restricted within the syntux module.
221 pub(super) fn emit_diagnostics(&self, diagnostics: Vec<Diagnostic>) {
222 for diagnostic in diagnostics {
223 self.parse_sess.span_diagnostic.emit_diagnostic(&diagnostic);
227 pub(crate) fn emit_or_cancel_diagnostic(&self, diagnostic: &mut Diagnostic) {
228 self.parse_sess.span_diagnostic.emit_diagnostic(diagnostic);
229 // The Handler will check whether the diagnostic should be emitted
230 // based on the user's rustfmt configuration and the originating file
231 // that caused the parser error. If the Handler determined it should skip
232 // emission then we need to ensure the diagnostic is cancelled.
233 if !diagnostic.cancelled() {
238 pub(super) fn can_reset_errors(&self) -> bool {
239 self.can_reset_errors.load(Ordering::Acquire)
242 pub(super) fn has_errors(&self) -> bool {
243 self.parse_sess.span_diagnostic.has_errors()
246 pub(super) fn reset_errors(&self) {
247 self.parse_sess.span_diagnostic.reset_err_count();
251 impl LineRangeUtils for ParseSess {
252 fn lookup_line_range(&self, span: Span) -> LineRange {
256 .span_to_snippet(span)
257 .unwrap_or_default();
258 let lo = self.parse_sess.source_map().lookup_line(span.lo()).unwrap();
259 let hi = self.parse_sess.source_map().lookup_line(span.hi()).unwrap();
262 lo.sf.name, hi.sf.name,
263 "span crossed file boundary: lo: {:?}, hi: {:?}",
267 // in case the span starts with a newline, the line range is off by 1 without the
269 let offset = 1 + if starts_with_newline(&snippet) { 1 } else { 0 };
270 // Line numbers start at 1
273 lo: lo.line + offset,
274 hi: hi.line + offset,
285 use crate::config::IgnoreList;
286 use crate::is_nightly_channel;
287 use crate::utils::mk_sp;
288 use rustc_span::{FileName as SourceMapFileName, MultiSpan, RealFileName, DUMMY_SP};
289 use std::path::PathBuf;
290 use std::sync::atomic::AtomicU32;
293 num_emitted_errors: Lrc<AtomicU32>,
296 impl Emitter for TestEmitter {
297 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
300 fn emit_diagnostic(&mut self, _db: &Diagnostic) {
301 self.num_emitted_errors.fetch_add(1, Ordering::Release);
305 fn build_diagnostic(level: DiagnosticLevel, span: Option<MultiSpan>) -> Diagnostic {
312 span: span.unwrap_or_else(MultiSpan::new),
319 num_emitted_errors: Lrc<AtomicU32>,
320 can_reset: Lrc<AtomicBool>,
321 source_map: Option<Lrc<SourceMap>>,
322 ignore_list: Option<IgnoreList>,
323 ) -> SilentOnIgnoredFilesEmitter {
324 let emitter_writer = TestEmitter { num_emitted_errors };
326 source_map.unwrap_or_else(|| Lrc::new(SourceMap::new(FilePathMapping::empty())));
327 let ignore_path_set = Lrc::new(
328 IgnorePathSet::from_ignore_list(&ignore_list.unwrap_or_default()).unwrap(),
330 SilentOnIgnoredFilesEmitter {
331 has_non_ignorable_parser_errors: false,
333 emitter: Box::new(emitter_writer),
339 fn get_ignore_list(config: &str) -> IgnoreList {
340 Config::from_toml(config, Path::new("")).unwrap().ignore()
344 fn handles_fatal_parse_error_in_ignored_file() {
345 let num_emitted_errors = Lrc::new(AtomicU32::new(0));
346 let can_reset_errors = Lrc::new(AtomicBool::new(false));
347 let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#);
348 let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
350 String::from(r#"extern "system" fn jni_symbol!( funcName ) ( ... ) -> {} "#);
351 source_map.new_source_file(
352 SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))),
355 let mut emitter = build_emitter(
356 Lrc::clone(&num_emitted_errors),
357 Lrc::clone(&can_reset_errors),
358 Some(Lrc::clone(&source_map)),
361 let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
362 let fatal_diagnostic = build_diagnostic(DiagnosticLevel::Fatal, Some(span));
363 emitter.emit_diagnostic(&fatal_diagnostic);
364 assert_eq!(num_emitted_errors.load(Ordering::Acquire), 1);
365 assert_eq!(can_reset_errors.load(Ordering::Acquire), false);
369 fn handles_recoverable_parse_error_in_ignored_file() {
370 if !is_nightly_channel!() {
373 let num_emitted_errors = Lrc::new(AtomicU32::new(0));
374 let can_reset_errors = Lrc::new(AtomicBool::new(false));
375 let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#);
376 let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
377 let source = String::from(r#"pub fn bar() { 1x; }"#);
378 source_map.new_source_file(
379 SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))),
382 let mut emitter = build_emitter(
383 Lrc::clone(&num_emitted_errors),
384 Lrc::clone(&can_reset_errors),
385 Some(Lrc::clone(&source_map)),
388 let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
389 let non_fatal_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(span));
390 emitter.emit_diagnostic(&non_fatal_diagnostic);
391 assert_eq!(num_emitted_errors.load(Ordering::Acquire), 0);
392 assert_eq!(can_reset_errors.load(Ordering::Acquire), true);
396 fn handles_recoverable_parse_error_in_non_ignored_file() {
397 if !is_nightly_channel!() {
400 let num_emitted_errors = Lrc::new(AtomicU32::new(0));
401 let can_reset_errors = Lrc::new(AtomicBool::new(false));
402 let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
403 let source = String::from(r#"pub fn bar() { 1x; }"#);
404 source_map.new_source_file(
405 SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))),
408 let mut emitter = build_emitter(
409 Lrc::clone(&num_emitted_errors),
410 Lrc::clone(&can_reset_errors),
411 Some(Lrc::clone(&source_map)),
414 let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
415 let non_fatal_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(span));
416 emitter.emit_diagnostic(&non_fatal_diagnostic);
417 assert_eq!(num_emitted_errors.load(Ordering::Acquire), 1);
418 assert_eq!(can_reset_errors.load(Ordering::Acquire), false);
422 fn handles_mix_of_recoverable_parse_error() {
423 if !is_nightly_channel!() {
426 let num_emitted_errors = Lrc::new(AtomicU32::new(0));
427 let can_reset_errors = Lrc::new(AtomicBool::new(false));
428 let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
429 let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#);
430 let bar_source = String::from(r#"pub fn bar() { 1x; }"#);
431 let foo_source = String::from(r#"pub fn foo() { 1x; }"#);
433 String::from(r#"extern "system" fn jni_symbol!( funcName ) ( ... ) -> {} "#);
434 source_map.new_source_file(
435 SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("bar.rs"))),
438 source_map.new_source_file(
439 SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))),
442 source_map.new_source_file(
443 SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("fatal.rs"))),
446 let mut emitter = build_emitter(
447 Lrc::clone(&num_emitted_errors),
448 Lrc::clone(&can_reset_errors),
449 Some(Lrc::clone(&source_map)),
452 let bar_span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
453 let foo_span = MultiSpan::from_span(mk_sp(BytePos(21), BytePos(22)));
454 let bar_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(bar_span));
455 let foo_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(foo_span));
456 let fatal_diagnostic = build_diagnostic(DiagnosticLevel::Fatal, None);
457 emitter.emit_diagnostic(&bar_diagnostic);
458 emitter.emit_diagnostic(&foo_diagnostic);
459 emitter.emit_diagnostic(&fatal_diagnostic);
460 assert_eq!(num_emitted_errors.load(Ordering::Acquire), 2);
461 assert_eq!(can_reset_errors.load(Ordering::Acquire), false);