Skip to main content

rustfmt_nightly/parse/
session.rs

1use std::path::Path;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicBool, Ordering};
4
5use rustc_data_structures::sync::IntoDynSyncSend;
6use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
7use rustc_errors::emitter::{DynEmitter, Emitter, SilentEmitter, stderr_destination};
8use rustc_errors::{ColorConfig, Diag, DiagCtxt, DiagInner, Level as DiagnosticLevel};
9use rustc_session::parse::ParseSess as RawParseSess;
10use rustc_span::{
11    BytePos, Span,
12    source_map::{FilePathMapping, SourceMap},
13    symbol,
14};
15
16use crate::config::file_lines::LineRange;
17use crate::config::options::Color;
18use crate::ignore_path::IgnorePathSet;
19use crate::parse::parser::{ModError, ModulePathSuccess};
20use crate::source_map::LineRangeUtils;
21use crate::utils::starts_with_newline;
22use crate::visitor::SnippetProvider;
23use crate::{Config, ErrorKind, FileName};
24
25/// ParseSess holds structs necessary for constructing a parser.
26pub(crate) struct ParseSess {
27    raw_psess: RawParseSess,
28    ignore_path_set: Arc<IgnorePathSet>,
29    can_reset_errors: Arc<AtomicBool>,
30}
31
32/// Emit errors against every files expect ones specified in the `ignore_path_set`.
33struct SilentOnIgnoredFilesEmitter {
34    ignore_path_set: IntoDynSyncSend<Arc<IgnorePathSet>>,
35    source_map: Arc<SourceMap>,
36    emitter: Box<DynEmitter>,
37    has_non_ignorable_parser_errors: bool,
38    can_reset: Arc<AtomicBool>,
39}
40
41impl SilentOnIgnoredFilesEmitter {
42    fn handle_non_ignoreable_error(&mut self, diag: DiagInner) {
43        self.has_non_ignorable_parser_errors = true;
44        self.can_reset.store(false, Ordering::Release);
45        self.emitter.emit_diagnostic(diag);
46    }
47}
48
49impl Emitter for SilentOnIgnoredFilesEmitter {
50    fn source_map(&self) -> Option<&SourceMap> {
51        None
52    }
53
54    fn emit_diagnostic(&mut self, diag: DiagInner) {
55        if diag.level() == DiagnosticLevel::Fatal {
56            return self.handle_non_ignoreable_error(diag);
57        }
58        if let Some(primary_span) = &diag.span.primary_span() {
59            let file_name = self.source_map.span_to_filename(*primary_span);
60            if let rustc_span::FileName::Real(real) = file_name {
61                if let Some(path) = real.local_path() {
62                    if self
63                        .ignore_path_set
64                        .is_match(&FileName::Real(path.to_path_buf()))
65                    {
66                        if !self.has_non_ignorable_parser_errors {
67                            self.can_reset.store(true, Ordering::Release);
68                        }
69                        return;
70                    }
71                }
72            }
73        }
74        self.handle_non_ignoreable_error(diag);
75    }
76}
77
78impl From<Color> for ColorConfig {
79    fn from(color: Color) -> Self {
80        match color {
81            Color::Auto => ColorConfig::Auto,
82            Color::Always => ColorConfig::Always,
83            Color::Never => ColorConfig::Never,
84        }
85    }
86}
87
88fn default_dcx(
89    source_map: Arc<SourceMap>,
90    ignore_path_set: Arc<IgnorePathSet>,
91    can_reset: Arc<AtomicBool>,
92    show_parse_errors: bool,
93    color: Color,
94) -> DiagCtxt {
95    let supports_color = term::stderr().map_or(false, |term| term.supports_color());
96    let emit_color = if supports_color {
97        ColorConfig::from(color)
98    } else {
99        ColorConfig::Never
100    };
101
102    let emitter: Box<DynEmitter> = if show_parse_errors {
103        Box::new(
104            AnnotateSnippetEmitter::new(stderr_destination(emit_color))
105                .sm(Some(source_map.clone())),
106        )
107    } else {
108        Box::new(SilentEmitter)
109    };
110    DiagCtxt::new(Box::new(SilentOnIgnoredFilesEmitter {
111        has_non_ignorable_parser_errors: false,
112        source_map,
113        emitter,
114        ignore_path_set: IntoDynSyncSend(ignore_path_set),
115        can_reset,
116    }))
117}
118
119impl ParseSess {
120    pub(crate) fn new(config: &Config) -> Result<ParseSess, ErrorKind> {
121        let ignore_path_set = match IgnorePathSet::from_ignore_list(&config.ignore()) {
122            Ok(ignore_path_set) => Arc::new(ignore_path_set),
123            Err(e) => return Err(ErrorKind::InvalidGlobPattern(e)),
124        };
125        let source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
126        let can_reset_errors = Arc::new(AtomicBool::new(false));
127
128        let dcx = default_dcx(
129            Arc::clone(&source_map),
130            Arc::clone(&ignore_path_set),
131            Arc::clone(&can_reset_errors),
132            config.show_parse_errors(),
133            config.color(),
134        );
135        let raw_psess = RawParseSess::with_dcx(dcx, source_map);
136
137        Ok(ParseSess {
138            raw_psess,
139            ignore_path_set,
140            can_reset_errors,
141        })
142    }
143
144    /// Determine the submodule path for the given module identifier.
145    ///
146    /// * `id` - The name of the module
147    /// * `relative` - If Some(symbol), the symbol name is a directory relative to the dir_path.
148    ///   If relative is Some, resolve the submodule at {dir_path}/{symbol}/{id}.rs
149    ///   or {dir_path}/{symbol}/{id}/mod.rs. if None, resolve the module at {dir_path}/{id}.rs.
150    /// *  `dir_path` - Module resolution will occur relative to this directory.
151    pub(crate) fn default_submod_path(
152        &self,
153        id: symbol::Ident,
154        relative: Option<symbol::Ident>,
155        dir_path: &Path,
156    ) -> Result<ModulePathSuccess, ModError<'_>> {
157        rustc_expand::module::default_submod_path(&self.raw_psess, id, relative, dir_path).or_else(
158            |e| {
159                // If resolving a module relative to {dir_path}/{symbol} fails because a file
160                // could not be found, then try to resolve the module relative to {dir_path}.
161                // If we still can't find the module after searching for it in {dir_path},
162                // surface the original error.
163                if matches!(e, ModError::FileNotFound(..)) && relative.is_some() {
164                    rustc_expand::module::default_submod_path(&self.raw_psess, id, None, dir_path)
165                        .map_err(|_| e)
166                } else {
167                    Err(e)
168                }
169            },
170        )
171    }
172
173    pub(crate) fn is_file_parsed(&self, path: &Path) -> bool {
174        self.raw_psess
175            .source_map()
176            .get_source_file(&rustc_span::FileName::Real(
177                self.raw_psess
178                    .source_map()
179                    .path_mapping()
180                    .to_real_filename(self.raw_psess.source_map().working_dir(), path),
181            ))
182            .is_some()
183    }
184
185    pub(crate) fn ignore_file(&self, path: &FileName) -> bool {
186        self.ignore_path_set.as_ref().is_match(path)
187    }
188
189    pub(crate) fn set_silent_emitter(&mut self) {
190        self.raw_psess.dcx().make_silent();
191    }
192
193    pub(crate) fn span_to_filename(&self, span: Span) -> FileName {
194        self.raw_psess.source_map().span_to_filename(span).into()
195    }
196
197    pub(crate) fn span_to_file_contents(&self, span: Span) -> Arc<rustc_span::SourceFile> {
198        self.raw_psess.source_map().lookup_source_file(span.lo())
199    }
200
201    pub(crate) fn span_to_first_line_string(&self, span: Span) -> String {
202        let file_lines = self.raw_psess.source_map().span_to_lines(span).ok();
203
204        match file_lines {
205            Some(fl) => fl
206                .file
207                .get_line(fl.lines[0].line_index)
208                .map_or_else(String::new, |s| s.to_string()),
209            None => String::new(),
210        }
211    }
212
213    pub(crate) fn line_of_byte_pos(&self, pos: BytePos) -> usize {
214        self.raw_psess.source_map().lookup_char_pos(pos).line
215    }
216
217    // TODO(calebcartwright): Preemptive, currently unused addition
218    // that will be used to support formatting scenarios that take original
219    // positions into account
220    /// Determines whether two byte positions are in the same source line.
221    #[allow(dead_code)]
222    pub(crate) fn byte_pos_same_line(&self, a: BytePos, b: BytePos) -> bool {
223        self.line_of_byte_pos(a) == self.line_of_byte_pos(b)
224    }
225
226    pub(crate) fn span_to_debug_info(&self, span: Span) -> String {
227        self.raw_psess.source_map().span_to_diagnostic_string(span)
228    }
229
230    pub(crate) fn inner(&self) -> &RawParseSess {
231        &self.raw_psess
232    }
233
234    pub(crate) fn snippet_provider(&self, span: Span) -> SnippetProvider {
235        let source_file = self.raw_psess.source_map().lookup_char_pos(span.lo()).file;
236        SnippetProvider::new(
237            source_file.start_pos,
238            source_file.end_position(),
239            Arc::clone(source_file.src.as_ref().unwrap()),
240        )
241    }
242
243    pub(crate) fn get_original_snippet(&self, filename: &FileName) -> Option<Arc<String>> {
244        let rustc_filename = match filename {
245            FileName::Real(path) => rustc_span::FileName::Real(
246                self.raw_psess
247                    .source_map()
248                    .path_mapping()
249                    .to_real_filename(self.raw_psess.source_map().working_dir(), path),
250            ),
251            FileName::Stdin => rustc_span::FileName::Custom("stdin".to_owned()),
252        };
253
254        self.raw_psess
255            .source_map()
256            .get_source_file(&rustc_filename)
257            .and_then(|source_file| source_file.src.clone())
258    }
259}
260
261// Methods that should be restricted within the parse module.
262impl ParseSess {
263    pub(super) fn emit_diagnostics(&self, diagnostics: Vec<Diag<'_>>) {
264        for diagnostic in diagnostics {
265            diagnostic.emit();
266        }
267    }
268
269    pub(super) fn can_reset_errors(&self) -> bool {
270        self.can_reset_errors.load(Ordering::Acquire)
271    }
272
273    pub(super) fn has_errors(&self) -> bool {
274        self.raw_psess.dcx().has_errors().is_some()
275    }
276
277    pub(super) fn reset_errors(&self) {
278        self.raw_psess.dcx().reset_err_count();
279    }
280}
281
282impl LineRangeUtils for ParseSess {
283    fn lookup_line_range(&self, span: Span) -> LineRange {
284        let snippet = self
285            .raw_psess
286            .source_map()
287            .span_to_snippet(span)
288            .unwrap_or_default();
289        let lo = self.raw_psess.source_map().lookup_line(span.lo()).unwrap();
290        let hi = self.raw_psess.source_map().lookup_line(span.hi()).unwrap();
291
292        debug_assert_eq!(
293            lo.sf.name, hi.sf.name,
294            "span crossed file boundary: lo: {lo:?}, hi: {hi:?}"
295        );
296
297        // in case the span starts with a newline, the line range is off by 1 without the
298        // adjustment below
299        let offset = 1 + if starts_with_newline(&snippet) { 1 } else { 0 };
300        // Line numbers start at 1
301        LineRange {
302            file: lo.sf.clone(),
303            lo: lo.line + offset,
304            hi: hi.line + offset,
305        }
306    }
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312
313    use rustfmt_config_proc_macro::nightly_only_test;
314
315    mod emitter {
316        use super::*;
317        use crate::config::IgnoreList;
318        use crate::utils::mk_sp;
319        use rustc_errors::MultiSpan;
320        use rustc_span::FileName as SourceMapFileName;
321        use std::path::PathBuf;
322        use std::sync::atomic::AtomicU32;
323
324        struct TestEmitter {
325            num_emitted_errors: Arc<AtomicU32>,
326        }
327
328        impl Emitter for TestEmitter {
329            fn source_map(&self) -> Option<&SourceMap> {
330                None
331            }
332
333            fn emit_diagnostic(&mut self, _diag: DiagInner) {
334                self.num_emitted_errors.fetch_add(1, Ordering::Release);
335            }
336        }
337
338        fn build_diagnostic(level: DiagnosticLevel, span: Option<MultiSpan>) -> DiagInner {
339            let mut diag = DiagInner::new(level, "");
340            diag.messages.clear();
341            if let Some(span) = span {
342                diag.span = span;
343            }
344            diag
345        }
346
347        fn build_emitter(
348            num_emitted_errors: Arc<AtomicU32>,
349            can_reset: Arc<AtomicBool>,
350            source_map: Option<Arc<SourceMap>>,
351            ignore_list: Option<IgnoreList>,
352        ) -> SilentOnIgnoredFilesEmitter {
353            let emitter_writer = TestEmitter { num_emitted_errors };
354            let source_map =
355                source_map.unwrap_or_else(|| Arc::new(SourceMap::new(FilePathMapping::empty())));
356            let ignore_path_set = Arc::new(
357                IgnorePathSet::from_ignore_list(&ignore_list.unwrap_or_default()).unwrap(),
358            );
359            SilentOnIgnoredFilesEmitter {
360                has_non_ignorable_parser_errors: false,
361                source_map,
362                emitter: Box::new(emitter_writer),
363                ignore_path_set: IntoDynSyncSend(ignore_path_set),
364                can_reset,
365            }
366        }
367
368        fn get_ignore_list(config: &str) -> IgnoreList {
369            Config::from_toml(config, Path::new("./rustfmt.toml"))
370                .unwrap()
371                .ignore()
372        }
373
374        fn filename(sm: &SourceMap, path: &str) -> SourceMapFileName {
375            SourceMapFileName::Real(
376                sm.path_mapping()
377                    .to_real_filename(sm.working_dir(), PathBuf::from(path)),
378            )
379        }
380
381        #[test]
382        fn handles_fatal_parse_error_in_ignored_file() {
383            let num_emitted_errors = Arc::new(AtomicU32::new(0));
384            let can_reset_errors = Arc::new(AtomicBool::new(false));
385            let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#);
386            let source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
387            let source =
388                String::from(r#"extern "system" fn jni_symbol!( funcName ) ( ... ) -> {} "#);
389            source_map.new_source_file(filename(&source_map, "foo.rs"), source);
390            let mut emitter = build_emitter(
391                Arc::clone(&num_emitted_errors),
392                Arc::clone(&can_reset_errors),
393                Some(Arc::clone(&source_map)),
394                Some(ignore_list),
395            );
396            let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
397            let fatal_diagnostic = build_diagnostic(DiagnosticLevel::Fatal, Some(span));
398            emitter.emit_diagnostic(fatal_diagnostic);
399            assert_eq!(num_emitted_errors.load(Ordering::Acquire), 1);
400            assert_eq!(can_reset_errors.load(Ordering::Acquire), false);
401        }
402
403        #[nightly_only_test]
404        #[test]
405        fn handles_recoverable_parse_error_in_ignored_file() {
406            let num_emitted_errors = Arc::new(AtomicU32::new(0));
407            let can_reset_errors = Arc::new(AtomicBool::new(false));
408            let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#);
409            let source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
410            let source = String::from(r#"pub fn bar() { 1x; }"#);
411            source_map.new_source_file(filename(&source_map, "foo.rs"), source);
412            let mut emitter = build_emitter(
413                Arc::clone(&num_emitted_errors),
414                Arc::clone(&can_reset_errors),
415                Some(Arc::clone(&source_map)),
416                Some(ignore_list),
417            );
418            let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
419            let non_fatal_diagnostic = build_diagnostic(DiagnosticLevel::Warning(None), Some(span));
420            emitter.emit_diagnostic(non_fatal_diagnostic);
421            assert_eq!(num_emitted_errors.load(Ordering::Acquire), 0);
422            assert_eq!(can_reset_errors.load(Ordering::Acquire), true);
423        }
424
425        #[nightly_only_test]
426        #[test]
427        fn handles_recoverable_parse_error_in_non_ignored_file() {
428            let num_emitted_errors = Arc::new(AtomicU32::new(0));
429            let can_reset_errors = Arc::new(AtomicBool::new(false));
430            let source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
431            let source = String::from(r#"pub fn bar() { 1x; }"#);
432            source_map.new_source_file(filename(&source_map, "foo.rs"), source);
433            let mut emitter = build_emitter(
434                Arc::clone(&num_emitted_errors),
435                Arc::clone(&can_reset_errors),
436                Some(Arc::clone(&source_map)),
437                None,
438            );
439            let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
440            let non_fatal_diagnostic = build_diagnostic(DiagnosticLevel::Warning(None), Some(span));
441            emitter.emit_diagnostic(non_fatal_diagnostic);
442            assert_eq!(num_emitted_errors.load(Ordering::Acquire), 1);
443            assert_eq!(can_reset_errors.load(Ordering::Acquire), false);
444        }
445
446        #[nightly_only_test]
447        #[test]
448        fn handles_mix_of_recoverable_parse_error() {
449            let num_emitted_errors = Arc::new(AtomicU32::new(0));
450            let can_reset_errors = Arc::new(AtomicBool::new(false));
451            let source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
452            let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#);
453            let bar_source = String::from(r#"pub fn bar() { 1x; }"#);
454            let foo_source = String::from(r#"pub fn foo() { 1x; }"#);
455            let fatal_source =
456                String::from(r#"extern "system" fn jni_symbol!( funcName ) ( ... ) -> {} "#);
457            source_map.new_source_file(filename(&source_map, "bar.rs"), bar_source);
458            source_map.new_source_file(filename(&source_map, "foo.rs"), foo_source);
459            source_map.new_source_file(filename(&source_map, "fatal.rs"), fatal_source);
460            let mut emitter = build_emitter(
461                Arc::clone(&num_emitted_errors),
462                Arc::clone(&can_reset_errors),
463                Some(Arc::clone(&source_map)),
464                Some(ignore_list),
465            );
466            let bar_span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
467            let foo_span = MultiSpan::from_span(mk_sp(BytePos(21), BytePos(22)));
468            let bar_diagnostic = build_diagnostic(DiagnosticLevel::Warning(None), Some(bar_span));
469            let foo_diagnostic = build_diagnostic(DiagnosticLevel::Warning(None), Some(foo_span));
470            let fatal_diagnostic = build_diagnostic(DiagnosticLevel::Fatal, None);
471            emitter.emit_diagnostic(bar_diagnostic);
472            emitter.emit_diagnostic(foo_diagnostic);
473            emitter.emit_diagnostic(fatal_diagnostic);
474            assert_eq!(num_emitted_errors.load(Ordering::Acquire), 2);
475            assert_eq!(can_reset_errors.load(Ordering::Acquire), false);
476        }
477    }
478}