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