]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/sess.rs
Auto merge of #66211 - kinnison:kinnison/fix-66159, r=GuillaumeGomez
[rust.git] / src / libsyntax / sess.rs
1 //! Contains `ParseSess` which holds state living beyond what one `Parser` might.
2 //! It also serves as an input to the parser itself.
3
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;
8
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;
15
16 use std::path::PathBuf;
17 use std::str;
18
19 /// Collected spans during parsing for places where a certain feature was
20 /// used and should be feature gated accordingly in `check_crate`.
21 #[derive(Default)]
22 pub struct GatedSpans {
23     pub spans: Lock<FxHashMap<Symbol, Vec<Span>>>,
24 }
25
26 impl GatedSpans {
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) {
30         self.spans
31             .borrow_mut()
32             .entry(feature)
33             .or_default()
34             .push(span);
35     }
36
37     /// Ungate the last span under the given `feature`.
38     /// Panics if the given `span` wasn't the last one.
39     ///
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
43             .borrow_mut()
44             .entry(feature)
45             .or_default()
46             .pop()
47             .unwrap();
48         debug_assert_eq!(span, removed_span);
49     }
50
51     /// Is the provided `feature` gate ungated currently?
52     ///
53     /// Using this is discouraged unless you have a really good reason to.
54     pub fn is_ungated(&self, feature: Symbol) -> bool {
55         self.spans
56             .borrow()
57             .get(&feature)
58             .map_or(true, |spans| spans.is_empty())
59     }
60
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);
66         }
67         *inner = spans;
68     }
69 }
70
71 /// Info about a parsing session.
72 pub struct ParseSess {
73     pub span_diagnostic: Handler,
74     pub unstable_features: UnstableFeatures,
75     pub config: CrateConfig,
76     pub edition: Edition,
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
86     /// analysis.
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.
94     ///
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].
99     ///
100     /// [#64197]: https://github.com/rust-lang/rust/issues/64197
101     pub process_cfg_mod: ProcessCfgMod,
102 }
103
104 pub type ProcessCfgMod = fn(&ParseSess, bool, &[Attribute]) -> (bool, Vec<Attribute>);
105
106 impl ParseSess {
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(
110             ColorConfig::Auto,
111             true,
112             None,
113             Some(cm.clone()),
114         );
115         ParseSess::with_span_handler(handler, cm, process_cfg_mod)
116     }
117
118     pub fn with_span_handler(
119         handler: Handler,
120         source_map: Lrc<SourceMap>,
121         process_cfg_mod: ProcessCfgMod,
122     ) -> Self {
123         Self {
124             span_diagnostic: handler,
125             process_cfg_mod,
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![]),
132             source_map,
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),
138         }
139     }
140
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)
145     }
146
147     #[inline]
148     pub fn source_map(&self) -> &SourceMap {
149         &self.source_map
150     }
151
152     pub fn buffer_lint(
153         &self,
154         lint_id: BufferedEarlyLintId,
155         span: impl Into<MultiSpan>,
156         id: NodeId,
157         msg: &str,
158     ) {
159         self.buffered_lints.with_lock(|buffered_lints| {
160             buffered_lints.push(BufferedEarlyLint{
161                 span: span.into(),
162                 id,
163                 msg: msg.into(),
164                 lint_id,
165             });
166         });
167     }
168
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(
172         &self,
173         err: &mut DiagnosticBuilder<'_>,
174         span: Span,
175         alt_snippet: Option<String>,
176     ) {
177         if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
178             err.span_suggestion(
179                 span,
180                 "parentheses are required to parse this as an expression",
181                 format!("({})", snippet),
182                 Applicability::MachineApplicable,
183             );
184         }
185     }
186 }