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