]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_session/src/parse.rs
Auto merge of #100958 - mikebenfield:workaround, r=nikic
[rust.git] / compiler / rustc_session / src / parse.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::config::CheckCfg;
5 use crate::errors::{FeatureDiagnosticForIssue, FeatureDiagnosticHelp, FeatureGateError};
6 use crate::lint::{
7     builtin::UNSTABLE_SYNTAX_PRE_EXPANSION, BufferedEarlyLint, BuiltinLintDiagnostics, Lint, LintId,
8 };
9 use crate::SessionDiagnostic;
10 use rustc_ast::node_id::NodeId;
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_data_structures::sync::{Lock, Lrc};
13 use rustc_errors::{emitter::SilentEmitter, ColorConfig, Handler};
14 use rustc_errors::{
15     fallback_fluent_bundle, Applicability, Diagnostic, DiagnosticBuilder, DiagnosticId,
16     DiagnosticMessage, EmissionGuarantee, ErrorGuaranteed, MultiSpan, StashKey,
17 };
18 use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures};
19 use rustc_span::edition::Edition;
20 use rustc_span::hygiene::ExpnId;
21 use rustc_span::source_map::{FilePathMapping, SourceMap};
22 use rustc_span::{Span, Symbol};
23
24 use std::str;
25
26 /// The set of keys (and, optionally, values) that define the compilation
27 /// environment of the crate, used to drive conditional compilation.
28 pub type CrateConfig = FxHashSet<(Symbol, Option<Symbol>)>;
29 pub type CrateCheckConfig = CheckCfg<Symbol>;
30
31 /// Collected spans during parsing for places where a certain feature was
32 /// used and should be feature gated accordingly in `check_crate`.
33 #[derive(Default)]
34 pub struct GatedSpans {
35     pub spans: Lock<FxHashMap<Symbol, Vec<Span>>>,
36 }
37
38 impl GatedSpans {
39     /// Feature gate the given `span` under the given `feature`
40     /// which is same `Symbol` used in `active.rs`.
41     pub fn gate(&self, feature: Symbol, span: Span) {
42         self.spans.borrow_mut().entry(feature).or_default().push(span);
43     }
44
45     /// Ungate the last span under the given `feature`.
46     /// Panics if the given `span` wasn't the last one.
47     ///
48     /// Using this is discouraged unless you have a really good reason to.
49     pub fn ungate_last(&self, feature: Symbol, span: Span) {
50         let removed_span = self.spans.borrow_mut().entry(feature).or_default().pop().unwrap();
51         debug_assert_eq!(span, removed_span);
52     }
53
54     /// Is the provided `feature` gate ungated currently?
55     ///
56     /// Using this is discouraged unless you have a really good reason to.
57     pub fn is_ungated(&self, feature: Symbol) -> bool {
58         self.spans.borrow().get(&feature).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 #[derive(Default)]
72 pub struct SymbolGallery {
73     /// All symbols occurred and their first occurrence span.
74     pub symbols: Lock<FxHashMap<Symbol, Span>>,
75 }
76
77 impl SymbolGallery {
78     /// Insert a symbol and its span into symbol gallery.
79     /// If the symbol has occurred before, ignore the new occurrence.
80     pub fn insert(&self, symbol: Symbol, span: Span) {
81         self.symbols.lock().entry(symbol).or_insert(span);
82     }
83 }
84
85 /// Construct a diagnostic for a language feature error due to the given `span`.
86 /// The `feature`'s `Symbol` is the one you used in `active.rs` and `rustc_span::symbols`.
87 pub fn feature_err<'a>(
88     sess: &'a ParseSess,
89     feature: Symbol,
90     span: impl Into<MultiSpan>,
91     explain: &str,
92 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
93     feature_err_issue(sess, feature, span, GateIssue::Language, explain)
94 }
95
96 /// Construct a diagnostic for a feature gate error.
97 ///
98 /// This variant allows you to control whether it is a library or language feature.
99 /// Almost always, you want to use this for a language feature. If so, prefer `feature_err`.
100 pub fn feature_err_issue<'a>(
101     sess: &'a ParseSess,
102     feature: Symbol,
103     span: impl Into<MultiSpan>,
104     issue: GateIssue,
105     explain: &str,
106 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
107     let span = span.into();
108
109     // Cancel an earlier warning for this same error, if it exists.
110     if let Some(span) = span.primary_span() {
111         sess.span_diagnostic
112             .steal_diagnostic(span, StashKey::EarlySyntaxWarning)
113             .map(|err| err.cancel());
114     }
115
116     let mut err = sess.create_err(FeatureGateError { span, explain });
117     add_feature_diagnostics_for_issue(&mut err, sess, feature, issue);
118     err
119 }
120
121 /// Construct a future incompatibility diagnostic for a feature gate.
122 ///
123 /// This diagnostic is only a warning and *does not cause compilation to fail*.
124 pub fn feature_warn<'a>(sess: &'a ParseSess, feature: Symbol, span: Span, explain: &str) {
125     feature_warn_issue(sess, feature, span, GateIssue::Language, explain);
126 }
127
128 /// Construct a future incompatibility diagnostic for a feature gate.
129 ///
130 /// This diagnostic is only a warning and *does not cause compilation to fail*.
131 ///
132 /// This variant allows you to control whether it is a library or language feature.
133 /// Almost always, you want to use this for a language feature. If so, prefer `feature_warn`.
134 #[allow(rustc::diagnostic_outside_of_impl)]
135 #[allow(rustc::untranslatable_diagnostic)]
136 pub fn feature_warn_issue<'a>(
137     sess: &'a ParseSess,
138     feature: Symbol,
139     span: Span,
140     issue: GateIssue,
141     explain: &str,
142 ) {
143     let mut err = sess.span_diagnostic.struct_span_warn(span, explain);
144     add_feature_diagnostics_for_issue(&mut err, sess, feature, issue);
145
146     // Decorate this as a future-incompatibility lint as in rustc_middle::lint::struct_lint_level
147     let lint = UNSTABLE_SYNTAX_PRE_EXPANSION;
148     let future_incompatible = lint.future_incompatible.as_ref().unwrap();
149     err.code(DiagnosticId::Lint {
150         name: lint.name_lower(),
151         has_future_breakage: false,
152         is_force_warn: false,
153     });
154     err.warn(lint.desc);
155     err.note(format!("for more information, see {}", future_incompatible.reference));
156
157     // A later feature_err call can steal and cancel this warning.
158     err.stash(span, StashKey::EarlySyntaxWarning);
159 }
160
161 /// Adds the diagnostics for a feature to an existing error.
162 pub fn add_feature_diagnostics<'a>(err: &mut Diagnostic, sess: &'a ParseSess, feature: Symbol) {
163     add_feature_diagnostics_for_issue(err, sess, feature, GateIssue::Language);
164 }
165
166 /// Adds the diagnostics for a feature to an existing error.
167 ///
168 /// This variant allows you to control whether it is a library or language feature.
169 /// Almost always, you want to use this for a language feature. If so, prefer
170 /// `add_feature_diagnostics`.
171 pub fn add_feature_diagnostics_for_issue<'a>(
172     err: &mut Diagnostic,
173     sess: &'a ParseSess,
174     feature: Symbol,
175     issue: GateIssue,
176 ) {
177     if let Some(n) = find_feature_issue(feature, issue) {
178         err.subdiagnostic(FeatureDiagnosticForIssue { n });
179     }
180
181     // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
182     if sess.unstable_features.is_nightly_build() {
183         err.subdiagnostic(FeatureDiagnosticHelp { feature });
184     }
185 }
186
187 /// Info about a parsing session.
188 pub struct ParseSess {
189     pub span_diagnostic: Handler,
190     pub unstable_features: UnstableFeatures,
191     pub config: CrateConfig,
192     pub check_config: CrateCheckConfig,
193     pub edition: Edition,
194     /// Places where raw identifiers were used. This is used to avoid complaining about idents
195     /// clashing with keywords in new editions.
196     pub raw_identifier_spans: Lock<Vec<Span>>,
197     /// Places where identifiers that contain invalid Unicode codepoints but that look like they
198     /// should be. Useful to avoid bad tokenization when encountering emoji. We group them to
199     /// provide a single error per unique incorrect identifier.
200     pub bad_unicode_identifiers: Lock<FxHashMap<Symbol, Vec<Span>>>,
201     source_map: Lrc<SourceMap>,
202     pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
203     /// Contains the spans of block expressions that could have been incomplete based on the
204     /// operation token that followed it, but that the parser cannot identify without further
205     /// analysis.
206     pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
207     pub gated_spans: GatedSpans,
208     pub symbol_gallery: SymbolGallery,
209     /// The parser has reached `Eof` due to an unclosed brace. Used to silence unnecessary errors.
210     pub reached_eof: Lock<bool>,
211     /// Environment variables accessed during the build and their values when they exist.
212     pub env_depinfo: Lock<FxHashSet<(Symbol, Option<Symbol>)>>,
213     /// File paths accessed during the build.
214     pub file_depinfo: Lock<FxHashSet<Symbol>>,
215     /// All the type ascriptions expressions that have had a suggestion for likely path typo.
216     pub type_ascription_path_suggestions: Lock<FxHashSet<Span>>,
217     /// Whether cfg(version) should treat the current release as incomplete
218     pub assume_incomplete_release: bool,
219     /// Spans passed to `proc_macro::quote_span`. Each span has a numerical
220     /// identifier represented by its position in the vector.
221     pub proc_macro_quoted_spans: Lock<Vec<Span>>,
222 }
223
224 impl ParseSess {
225     /// Used for testing.
226     pub fn new(file_path_mapping: FilePathMapping) -> Self {
227         let fallback_bundle = fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
228         let sm = Lrc::new(SourceMap::new(file_path_mapping));
229         let handler = Handler::with_tty_emitter(
230             ColorConfig::Auto,
231             true,
232             None,
233             Some(sm.clone()),
234             None,
235             fallback_bundle,
236         );
237         ParseSess::with_span_handler(handler, sm)
238     }
239
240     pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self {
241         Self {
242             span_diagnostic: handler,
243             unstable_features: UnstableFeatures::from_environment(None),
244             config: FxHashSet::default(),
245             check_config: CrateCheckConfig::default(),
246             edition: ExpnId::root().expn_data().edition,
247             raw_identifier_spans: Lock::new(Vec::new()),
248             bad_unicode_identifiers: Lock::new(Default::default()),
249             source_map,
250             buffered_lints: Lock::new(vec![]),
251             ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
252             gated_spans: GatedSpans::default(),
253             symbol_gallery: SymbolGallery::default(),
254             reached_eof: Lock::new(false),
255             env_depinfo: Default::default(),
256             file_depinfo: Default::default(),
257             type_ascription_path_suggestions: Default::default(),
258             assume_incomplete_release: false,
259             proc_macro_quoted_spans: Default::default(),
260         }
261     }
262
263     pub fn with_silent_emitter(fatal_note: Option<String>) -> Self {
264         let fallback_bundle = fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
265         let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
266         let fatal_handler =
267             Handler::with_tty_emitter(ColorConfig::Auto, false, None, None, None, fallback_bundle);
268         let handler = Handler::with_emitter(
269             false,
270             None,
271             Box::new(SilentEmitter { fatal_handler, fatal_note }),
272         );
273         ParseSess::with_span_handler(handler, sm)
274     }
275
276     #[inline]
277     pub fn source_map(&self) -> &SourceMap {
278         &self.source_map
279     }
280
281     pub fn clone_source_map(&self) -> Lrc<SourceMap> {
282         self.source_map.clone()
283     }
284
285     pub fn buffer_lint(
286         &self,
287         lint: &'static Lint,
288         span: impl Into<MultiSpan>,
289         node_id: NodeId,
290         msg: &str,
291     ) {
292         self.buffered_lints.with_lock(|buffered_lints| {
293             buffered_lints.push(BufferedEarlyLint {
294                 span: span.into(),
295                 node_id,
296                 msg: msg.into(),
297                 lint_id: LintId::of(lint),
298                 diagnostic: BuiltinLintDiagnostics::Normal,
299             });
300         });
301     }
302
303     pub fn buffer_lint_with_diagnostic(
304         &self,
305         lint: &'static Lint,
306         span: impl Into<MultiSpan>,
307         node_id: NodeId,
308         msg: &str,
309         diagnostic: BuiltinLintDiagnostics,
310     ) {
311         self.buffered_lints.with_lock(|buffered_lints| {
312             buffered_lints.push(BufferedEarlyLint {
313                 span: span.into(),
314                 node_id,
315                 msg: msg.into(),
316                 lint_id: LintId::of(lint),
317                 diagnostic,
318             });
319         });
320     }
321
322     /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
323     /// parser to continue parsing the following operation as part of the same expression.
324     pub fn expr_parentheses_needed(&self, err: &mut Diagnostic, span: Span) {
325         err.multipart_suggestion(
326             "parentheses are required to parse this as an expression",
327             vec![(span.shrink_to_lo(), "(".to_string()), (span.shrink_to_hi(), ")".to_string())],
328             Applicability::MachineApplicable,
329         );
330     }
331
332     pub fn save_proc_macro_span(&self, span: Span) -> usize {
333         let mut spans = self.proc_macro_quoted_spans.lock();
334         spans.push(span);
335         return spans.len() - 1;
336     }
337
338     pub fn proc_macro_quoted_spans(&self) -> Vec<Span> {
339         self.proc_macro_quoted_spans.lock().clone()
340     }
341
342     pub fn create_err<'a>(
343         &'a self,
344         err: impl SessionDiagnostic<'a>,
345     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
346         err.into_diagnostic(self)
347     }
348
349     pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) -> ErrorGuaranteed {
350         self.create_err(err).emit()
351     }
352
353     pub fn create_warning<'a>(
354         &'a self,
355         warning: impl SessionDiagnostic<'a, ()>,
356     ) -> DiagnosticBuilder<'a, ()> {
357         warning.into_diagnostic(self)
358     }
359
360     pub fn emit_warning<'a>(&'a self, warning: impl SessionDiagnostic<'a, ()>) {
361         self.create_warning(warning).emit()
362     }
363
364     pub fn create_fatal<'a>(
365         &'a self,
366         fatal: impl SessionDiagnostic<'a, !>,
367     ) -> DiagnosticBuilder<'a, !> {
368         fatal.into_diagnostic(self)
369     }
370
371     pub fn emit_fatal<'a>(&'a self, fatal: impl SessionDiagnostic<'a, !>) -> ! {
372         self.create_fatal(fatal).emit()
373     }
374
375     #[rustc_lint_diagnostics]
376     #[allow(rustc::diagnostic_outside_of_impl)]
377     #[allow(rustc::untranslatable_diagnostic)]
378     pub fn struct_err(
379         &self,
380         msg: impl Into<DiagnosticMessage>,
381     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
382         self.span_diagnostic.struct_err(msg)
383     }
384
385     #[rustc_lint_diagnostics]
386     #[allow(rustc::diagnostic_outside_of_impl)]
387     #[allow(rustc::untranslatable_diagnostic)]
388     pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
389         self.span_diagnostic.struct_warn(msg)
390     }
391
392     #[rustc_lint_diagnostics]
393     #[allow(rustc::diagnostic_outside_of_impl)]
394     #[allow(rustc::untranslatable_diagnostic)]
395     pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
396         self.span_diagnostic.struct_fatal(msg)
397     }
398
399     #[rustc_lint_diagnostics]
400     #[allow(rustc::diagnostic_outside_of_impl)]
401     #[allow(rustc::untranslatable_diagnostic)]
402     pub fn struct_diagnostic<G: EmissionGuarantee>(
403         &self,
404         msg: impl Into<DiagnosticMessage>,
405     ) -> DiagnosticBuilder<'_, G> {
406         self.span_diagnostic.struct_diagnostic(msg)
407     }
408 }