1 //! Contains `ParseSess` which holds state living beyond what one `Parser` might.
2 //! It also serves as an input to the parser itself.
4 use crate::ast::{CrateConfig, NodeId, Attribute};
5 use crate::early_buffered_lints::{BufferedEarlyLint, BufferedEarlyLintId};
6 use crate::source_map::{SourceMap, FilePathMapping};
7 use crate::feature_gate::UnstableFeatures;
9 use errors::{Applicability, emitter::SilentEmitter, Handler, ColorConfig, DiagnosticBuilder};
10 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
11 use rustc_data_structures::sync::{Lrc, Lock, Once};
12 use syntax_pos::{Symbol, Span, MultiSpan};
13 use syntax_pos::edition::Edition;
14 use syntax_pos::hygiene::ExpnId;
16 use std::path::PathBuf;
19 /// Collected spans during parsing for places where a certain feature was
20 /// used and should be feature gated accordingly in `check_crate`.
22 pub struct GatedSpans {
23 pub spans: Lock<FxHashMap<Symbol, Vec<Span>>>,
27 /// Feature gate the given `span` under the given `feature`
28 /// which is same `Symbol` used in `active.rs`.
29 pub fn gate(&self, feature: Symbol, span: Span) {
37 /// Ungate the last span under the given `feature`.
38 /// Panics if the given `span` wasn't the last one.
40 /// Using this is discouraged unless you have a really good reason to.
41 pub fn ungate_last(&self, feature: Symbol, span: Span) {
42 let removed_span = self.spans
48 debug_assert_eq!(span, removed_span);
51 /// Is the provided `feature` gate ungated currently?
53 /// Using this is discouraged unless you have a really good reason to.
54 pub fn is_ungated(&self, feature: Symbol) -> bool {
58 .map_or(true, |spans| spans.is_empty())
61 /// Prepend the given set of `spans` onto the set in `self`.
62 pub fn merge(&self, mut spans: FxHashMap<Symbol, Vec<Span>>) {
63 let mut inner = self.spans.borrow_mut();
64 for (gate, mut gate_spans) in inner.drain() {
65 spans.entry(gate).or_default().append(&mut gate_spans);
71 /// Info about a parsing session.
72 pub struct ParseSess {
73 pub span_diagnostic: Handler,
74 pub unstable_features: UnstableFeatures,
75 pub config: CrateConfig,
77 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
78 /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
79 pub raw_identifier_spans: Lock<Vec<Span>>,
80 /// Used to determine and report recursive module inclusions.
81 pub included_mod_stack: Lock<Vec<PathBuf>>,
82 source_map: Lrc<SourceMap>,
83 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
84 /// Contains the spans of block expressions that could have been incomplete based on the
85 /// operation token that followed it, but that the parser cannot identify without further
87 pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
88 pub injected_crate_name: Once<Symbol>,
89 pub gated_spans: GatedSpans,
90 /// The parser has reached `Eof` due to an unclosed brace. Used to silence unnecessary errors.
91 pub reached_eof: Lock<bool>,
92 /// Process the potential `cfg` attributes on a module.
93 /// Also determine if the module should be included in this configuration.
95 /// HACK(Centril): This is used to break a cyclic dependency between
96 /// the parser and cfg-stripping as defined in `syntax_expand::config`.
97 /// The dependency edge from the parser comes from `parse_item_mod`.
98 /// A principled solution to this hack would be to implement [#64197].
100 /// [#64197]: https://github.com/rust-lang/rust/issues/64197
101 pub process_cfg_mod: ProcessCfgMod,
104 pub type ProcessCfgMod = fn(&ParseSess, bool, &[Attribute]) -> (bool, Vec<Attribute>);
107 pub fn new(file_path_mapping: FilePathMapping, process_cfg_mod: ProcessCfgMod) -> Self {
108 let cm = Lrc::new(SourceMap::new(file_path_mapping));
109 let handler = Handler::with_tty_emitter(
115 ParseSess::with_span_handler(handler, cm, process_cfg_mod)
118 pub fn with_span_handler(
120 source_map: Lrc<SourceMap>,
121 process_cfg_mod: ProcessCfgMod,
124 span_diagnostic: handler,
126 unstable_features: UnstableFeatures::from_environment(),
127 config: FxHashSet::default(),
128 edition: ExpnId::root().expn_data().edition,
129 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
130 raw_identifier_spans: Lock::new(Vec::new()),
131 included_mod_stack: Lock::new(vec![]),
133 buffered_lints: Lock::new(vec![]),
134 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
135 injected_crate_name: Once::new(),
136 gated_spans: GatedSpans::default(),
137 reached_eof: Lock::new(false),
141 pub fn with_silent_emitter(process_cfg_mod: ProcessCfgMod) -> Self {
142 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
143 let handler = Handler::with_emitter(false, None, Box::new(SilentEmitter));
144 ParseSess::with_span_handler(handler, cm, process_cfg_mod)
148 pub fn source_map(&self) -> &SourceMap {
154 lint_id: BufferedEarlyLintId,
155 span: impl Into<MultiSpan>,
159 self.buffered_lints.with_lock(|buffered_lints| {
160 buffered_lints.push(BufferedEarlyLint{
169 /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
170 /// parser to continue parsing the following operation as part of the same expression.
171 pub fn expr_parentheses_needed(
173 err: &mut DiagnosticBuilder<'_>,
175 alt_snippet: Option<String>,
177 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
180 "parentheses are required to parse this as an expression",
181 format!("({})", snippet),
182 Applicability::MachineApplicable,