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