]>
Commit | Line | Data |
---|---|---|
e74abb32 XL |
1 | //! Contains `ParseSess` which holds state living beyond what one `Parser` might. |
2 | //! It also serves as an input to the parser itself. | |
3 | ||
dfeec247 | 4 | use crate::lint::{BufferedEarlyLint, BuiltinLintDiagnostics, Lint, LintId}; |
74b04a01 | 5 | use rustc_ast::node_id::NodeId; |
dfeec247 | 6 | use rustc_data_structures::fx::{FxHashMap, FxHashSet}; |
fc512014 | 7 | use rustc_data_structures::sync::{Lock, Lrc}; |
dfeec247 XL |
8 | use rustc_errors::{emitter::SilentEmitter, ColorConfig, Handler}; |
9 | use rustc_errors::{error_code, Applicability, DiagnosticBuilder}; | |
10 | use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures}; | |
11 | use rustc_span::edition::Edition; | |
12 | use rustc_span::hygiene::ExpnId; | |
13 | use rustc_span::source_map::{FilePathMapping, SourceMap}; | |
14 | use rustc_span::{MultiSpan, Span, Symbol}; | |
e74abb32 | 15 | |
e74abb32 XL |
16 | use std::str; |
17 | ||
60c5eb7d XL |
18 | /// The set of keys (and, optionally, values) that define the compilation |
19 | /// environment of the crate, used to drive conditional compilation. | |
20 | pub type CrateConfig = FxHashSet<(Symbol, Option<Symbol>)>; | |
21 | ||
e74abb32 XL |
22 | /// Collected spans during parsing for places where a certain feature was |
23 | /// used and should be feature gated accordingly in `check_crate`. | |
24 | #[derive(Default)] | |
60c5eb7d XL |
25 | pub struct GatedSpans { |
26 | pub spans: Lock<FxHashMap<Symbol, Vec<Span>>>, | |
27 | } | |
28 | ||
29 | impl GatedSpans { | |
30 | /// Feature gate the given `span` under the given `feature` | |
31 | /// which is same `Symbol` used in `active.rs`. | |
32 | pub fn gate(&self, feature: Symbol, span: Span) { | |
dfeec247 | 33 | self.spans.borrow_mut().entry(feature).or_default().push(span); |
60c5eb7d XL |
34 | } |
35 | ||
36 | /// Ungate the last span under the given `feature`. | |
37 | /// Panics if the given `span` wasn't the last one. | |
38 | /// | |
39 | /// Using this is discouraged unless you have a really good reason to. | |
40 | pub fn ungate_last(&self, feature: Symbol, span: Span) { | |
dfeec247 | 41 | let removed_span = self.spans.borrow_mut().entry(feature).or_default().pop().unwrap(); |
60c5eb7d XL |
42 | debug_assert_eq!(span, removed_span); |
43 | } | |
44 | ||
45 | /// Is the provided `feature` gate ungated currently? | |
46 | /// | |
47 | /// Using this is discouraged unless you have a really good reason to. | |
48 | pub fn is_ungated(&self, feature: Symbol) -> bool { | |
dfeec247 | 49 | self.spans.borrow().get(&feature).map_or(true, |spans| spans.is_empty()) |
60c5eb7d XL |
50 | } |
51 | ||
52 | /// Prepend the given set of `spans` onto the set in `self`. | |
53 | pub fn merge(&self, mut spans: FxHashMap<Symbol, Vec<Span>>) { | |
54 | let mut inner = self.spans.borrow_mut(); | |
55 | for (gate, mut gate_spans) in inner.drain() { | |
56 | spans.entry(gate).or_default().append(&mut gate_spans); | |
57 | } | |
58 | *inner = spans; | |
59 | } | |
e74abb32 XL |
60 | } |
61 | ||
f9f354fc XL |
62 | #[derive(Default)] |
63 | pub struct SymbolGallery { | |
3dfed10e XL |
64 | /// All symbols occurred and their first occurrence span. |
65 | pub symbols: Lock<FxHashMap<Symbol, Span>>, | |
f9f354fc XL |
66 | } |
67 | ||
68 | impl SymbolGallery { | |
69 | /// Insert a symbol and its span into symbol gallery. | |
70 | /// If the symbol has occurred before, ignore the new occurance. | |
71 | pub fn insert(&self, symbol: Symbol, span: Span) { | |
72 | self.symbols.lock().entry(symbol).or_insert(span); | |
73 | } | |
74 | } | |
75 | ||
dfeec247 XL |
76 | /// Construct a diagnostic for a language feature error due to the given `span`. |
77 | /// The `feature`'s `Symbol` is the one you used in `active.rs` and `rustc_span::symbols`. | |
78 | pub fn feature_err<'a>( | |
79 | sess: &'a ParseSess, | |
80 | feature: Symbol, | |
81 | span: impl Into<MultiSpan>, | |
82 | explain: &str, | |
83 | ) -> DiagnosticBuilder<'a> { | |
84 | feature_err_issue(sess, feature, span, GateIssue::Language, explain) | |
85 | } | |
86 | ||
87 | /// Construct a diagnostic for a feature gate error. | |
88 | /// | |
89 | /// This variant allows you to control whether it is a library or language feature. | |
90 | /// Almost always, you want to use this for a language feature. If so, prefer `feature_err`. | |
91 | pub fn feature_err_issue<'a>( | |
92 | sess: &'a ParseSess, | |
93 | feature: Symbol, | |
94 | span: impl Into<MultiSpan>, | |
95 | issue: GateIssue, | |
96 | explain: &str, | |
97 | ) -> DiagnosticBuilder<'a> { | |
98 | let mut err = sess.span_diagnostic.struct_span_err_with_code(span, explain, error_code!(E0658)); | |
99 | ||
100 | if let Some(n) = find_feature_issue(feature, issue) { | |
101 | err.note(&format!( | |
74b04a01 XL |
102 | "see issue #{} <https://github.com/rust-lang/rust/issues/{}> for more information", |
103 | n, n, | |
dfeec247 XL |
104 | )); |
105 | } | |
106 | ||
107 | // #23973: do not suggest `#![feature(...)]` if we are in beta/stable | |
108 | if sess.unstable_features.is_nightly_build() { | |
109 | err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature)); | |
110 | } | |
111 | ||
112 | err | |
113 | } | |
114 | ||
e74abb32 XL |
115 | /// Info about a parsing session. |
116 | pub struct ParseSess { | |
117 | pub span_diagnostic: Handler, | |
60c5eb7d | 118 | pub unstable_features: UnstableFeatures, |
e74abb32 XL |
119 | pub config: CrateConfig, |
120 | pub edition: Edition, | |
b9856134 | 121 | pub missing_fragment_specifiers: Lock<FxHashMap<Span, NodeId>>, |
3c0e092e XL |
122 | /// Places where raw identifiers were used. This is used to avoid complaining about idents |
123 | /// clashing with keywords in new editions. | |
e74abb32 | 124 | pub raw_identifier_spans: Lock<Vec<Span>>, |
3c0e092e XL |
125 | /// Places where identifiers that contain invalid Unicode codepoints but that look like they |
126 | /// should be. Useful to avoid bad tokenization when encountering emoji. We group them to | |
127 | /// provide a single error per unique incorrect identifier. | |
128 | pub bad_unicode_identifiers: Lock<FxHashMap<Symbol, Vec<Span>>>, | |
e74abb32 XL |
129 | source_map: Lrc<SourceMap>, |
130 | pub buffered_lints: Lock<Vec<BufferedEarlyLint>>, | |
131 | /// Contains the spans of block expressions that could have been incomplete based on the | |
132 | /// operation token that followed it, but that the parser cannot identify without further | |
133 | /// analysis. | |
134 | pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>, | |
60c5eb7d | 135 | pub gated_spans: GatedSpans, |
f9f354fc | 136 | pub symbol_gallery: SymbolGallery, |
e74abb32 XL |
137 | /// The parser has reached `Eof` due to an unclosed brace. Used to silence unnecessary errors. |
138 | pub reached_eof: Lock<bool>, | |
f035d41b XL |
139 | /// Environment variables accessed during the build and their values when they exist. |
140 | pub env_depinfo: Lock<FxHashSet<(Symbol, Option<Symbol>)>>, | |
136023e0 XL |
141 | /// File paths accessed during the build. |
142 | pub file_depinfo: Lock<FxHashSet<Symbol>>, | |
3dfed10e XL |
143 | /// All the type ascriptions expressions that have had a suggestion for likely path typo. |
144 | pub type_ascription_path_suggestions: Lock<FxHashSet<Span>>, | |
5869c6ff XL |
145 | /// Whether cfg(version) should treat the current release as incomplete |
146 | pub assume_incomplete_release: bool, | |
17df50a5 XL |
147 | /// Spans passed to `proc_macro::quote_span`. Each span has a numerical |
148 | /// identifier represented by its position in the vector. | |
149 | pub proc_macro_quoted_spans: Lock<Vec<Span>>, | |
e74abb32 XL |
150 | } |
151 | ||
152 | impl ParseSess { | |
cdc7bbd5 | 153 | /// Used for testing. |
e74abb32 | 154 | pub fn new(file_path_mapping: FilePathMapping) -> Self { |
74b04a01 XL |
155 | let sm = Lrc::new(SourceMap::new(file_path_mapping)); |
156 | let handler = Handler::with_tty_emitter(ColorConfig::Auto, true, None, Some(sm.clone())); | |
157 | ParseSess::with_span_handler(handler, sm) | |
e74abb32 XL |
158 | } |
159 | ||
dfeec247 | 160 | pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self { |
e74abb32 XL |
161 | Self { |
162 | span_diagnostic: handler, | |
fc512014 | 163 | unstable_features: UnstableFeatures::from_environment(None), |
e74abb32 XL |
164 | config: FxHashSet::default(), |
165 | edition: ExpnId::root().expn_data().edition, | |
b9856134 | 166 | missing_fragment_specifiers: Default::default(), |
e74abb32 | 167 | raw_identifier_spans: Lock::new(Vec::new()), |
3c0e092e | 168 | bad_unicode_identifiers: Lock::new(Default::default()), |
e74abb32 XL |
169 | source_map, |
170 | buffered_lints: Lock::new(vec![]), | |
171 | ambiguous_block_expr_parse: Lock::new(FxHashMap::default()), | |
e74abb32 | 172 | gated_spans: GatedSpans::default(), |
f9f354fc | 173 | symbol_gallery: SymbolGallery::default(), |
e74abb32 | 174 | reached_eof: Lock::new(false), |
f035d41b | 175 | env_depinfo: Default::default(), |
136023e0 | 176 | file_depinfo: Default::default(), |
3dfed10e | 177 | type_ascription_path_suggestions: Default::default(), |
5869c6ff | 178 | assume_incomplete_release: false, |
17df50a5 | 179 | proc_macro_quoted_spans: Default::default(), |
e74abb32 XL |
180 | } |
181 | } | |
182 | ||
3c0e092e | 183 | pub fn with_silent_emitter(fatal_note: Option<String>) -> Self { |
74b04a01 | 184 | let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); |
3c0e092e XL |
185 | let fatal_handler = Handler::with_tty_emitter(ColorConfig::Auto, false, None, None); |
186 | let handler = Handler::with_emitter( | |
187 | false, | |
188 | None, | |
189 | Box::new(SilentEmitter { fatal_handler, fatal_note }), | |
190 | ); | |
74b04a01 | 191 | ParseSess::with_span_handler(handler, sm) |
60c5eb7d XL |
192 | } |
193 | ||
e74abb32 XL |
194 | #[inline] |
195 | pub fn source_map(&self) -> &SourceMap { | |
196 | &self.source_map | |
197 | } | |
198 | ||
f9f354fc XL |
199 | pub fn clone_source_map(&self) -> Lrc<SourceMap> { |
200 | self.source_map.clone() | |
201 | } | |
202 | ||
e74abb32 XL |
203 | pub fn buffer_lint( |
204 | &self, | |
dfeec247 | 205 | lint: &'static Lint, |
e74abb32 | 206 | span: impl Into<MultiSpan>, |
dfeec247 | 207 | node_id: NodeId, |
e74abb32 XL |
208 | msg: &str, |
209 | ) { | |
210 | self.buffered_lints.with_lock(|buffered_lints| { | |
dfeec247 | 211 | buffered_lints.push(BufferedEarlyLint { |
e74abb32 | 212 | span: span.into(), |
dfeec247 | 213 | node_id, |
e74abb32 | 214 | msg: msg.into(), |
dfeec247 XL |
215 | lint_id: LintId::of(lint), |
216 | diagnostic: BuiltinLintDiagnostics::Normal, | |
e74abb32 XL |
217 | }); |
218 | }); | |
219 | } | |
220 | ||
74b04a01 XL |
221 | pub fn buffer_lint_with_diagnostic( |
222 | &self, | |
223 | lint: &'static Lint, | |
224 | span: impl Into<MultiSpan>, | |
225 | node_id: NodeId, | |
226 | msg: &str, | |
227 | diagnostic: BuiltinLintDiagnostics, | |
228 | ) { | |
229 | self.buffered_lints.with_lock(|buffered_lints| { | |
230 | buffered_lints.push(BufferedEarlyLint { | |
231 | span: span.into(), | |
232 | node_id, | |
233 | msg: msg.into(), | |
234 | lint_id: LintId::of(lint), | |
235 | diagnostic, | |
236 | }); | |
237 | }); | |
238 | } | |
239 | ||
e74abb32 XL |
240 | /// Extend an error with a suggestion to wrap an expression with parentheses to allow the |
241 | /// parser to continue parsing the following operation as part of the same expression. | |
94222f64 XL |
242 | pub fn expr_parentheses_needed(&self, err: &mut DiagnosticBuilder<'_>, span: Span) { |
243 | err.multipart_suggestion( | |
244 | "parentheses are required to parse this as an expression", | |
245 | vec![(span.shrink_to_lo(), "(".to_string()), (span.shrink_to_hi(), ")".to_string())], | |
246 | Applicability::MachineApplicable, | |
247 | ); | |
e74abb32 | 248 | } |
17df50a5 XL |
249 | |
250 | pub fn save_proc_macro_span(&self, span: Span) -> usize { | |
251 | let mut spans = self.proc_macro_quoted_spans.lock(); | |
252 | spans.push(span); | |
253 | return spans.len() - 1; | |
254 | } | |
255 | ||
256 | pub fn proc_macro_quoted_spans(&self) -> Vec<Span> { | |
257 | self.proc_macro_quoted_spans.lock().clone() | |
258 | } | |
e74abb32 | 259 | } |