• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 rustc_ast::node_id::NodeId;
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
11 use rustc_data_structures::sync::{AppendOnlyVec, AtomicBool, Lock, Lrc};
12 use rustc_errors::{emitter::SilentEmitter, ColorConfig, Handler};
13 use rustc_errors::{
14     fallback_fluent_bundle, Diagnostic, DiagnosticBuilder, DiagnosticId, DiagnosticMessage,
15     EmissionGuarantee, ErrorGuaranteed, IntoDiagnostic, MultiSpan, Noted, 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 rustc_ast::attr::AttrIdGenerator;
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 = FxIndexSet<(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`.
gate(&self, feature: Symbol, span: Span)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.
ungate_last(&self, feature: Symbol, span: Span)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     /// Prepend the given set of `spans` onto the set in `self`.
merge(&self, mut spans: FxHashMap<Symbol, Vec<Span>>)55     pub fn merge(&self, mut spans: FxHashMap<Symbol, Vec<Span>>) {
56         let mut inner = self.spans.borrow_mut();
57         for (gate, mut gate_spans) in inner.drain() {
58             spans.entry(gate).or_default().append(&mut gate_spans);
59         }
60         *inner = spans;
61     }
62 }
63 
64 #[derive(Default)]
65 pub struct SymbolGallery {
66     /// All symbols occurred and their first occurrence span.
67     pub symbols: Lock<FxHashMap<Symbol, Span>>,
68 }
69 
70 impl SymbolGallery {
71     /// Insert a symbol and its span into symbol gallery.
72     /// If the symbol has occurred before, ignore the new occurrence.
insert(&self, symbol: Symbol, span: Span)73     pub fn insert(&self, symbol: Symbol, span: Span) {
74         self.symbols.lock().entry(symbol).or_insert(span);
75     }
76 }
77 
78 /// Construct a diagnostic for a language feature error due to the given `span`.
79 /// The `feature`'s `Symbol` is the one you used in `active.rs` and `rustc_span::symbols`.
80 #[track_caller]
feature_err( sess: &ParseSess, feature: Symbol, span: impl Into<MultiSpan>, explain: impl Into<DiagnosticMessage>, ) -> DiagnosticBuilder<'_, ErrorGuaranteed>81 pub fn feature_err(
82     sess: &ParseSess,
83     feature: Symbol,
84     span: impl Into<MultiSpan>,
85     explain: impl Into<DiagnosticMessage>,
86 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
87     feature_err_issue(sess, feature, span, GateIssue::Language, explain)
88 }
89 
90 /// Construct a diagnostic for a feature gate error.
91 ///
92 /// This variant allows you to control whether it is a library or language feature.
93 /// Almost always, you want to use this for a language feature. If so, prefer `feature_err`.
94 #[track_caller]
feature_err_issue( sess: &ParseSess, feature: Symbol, span: impl Into<MultiSpan>, issue: GateIssue, explain: impl Into<DiagnosticMessage>, ) -> DiagnosticBuilder<'_, ErrorGuaranteed>95 pub fn feature_err_issue(
96     sess: &ParseSess,
97     feature: Symbol,
98     span: impl Into<MultiSpan>,
99     issue: GateIssue,
100     explain: impl Into<DiagnosticMessage>,
101 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
102     let span = span.into();
103 
104     // Cancel an earlier warning for this same error, if it exists.
105     if let Some(span) = span.primary_span() {
106         if let Some(err) = sess.span_diagnostic.steal_diagnostic(span, StashKey::EarlySyntaxWarning)
107         {
108             err.cancel()
109         }
110     }
111 
112     let mut err = sess.create_err(FeatureGateError { span, explain: explain.into() });
113     add_feature_diagnostics_for_issue(&mut err, sess, feature, issue);
114     err
115 }
116 
117 /// Construct a future incompatibility diagnostic for a feature gate.
118 ///
119 /// This diagnostic is only a warning and *does not cause compilation to fail*.
feature_warn(sess: &ParseSess, feature: Symbol, span: Span, explain: &'static str)120 pub fn feature_warn(sess: &ParseSess, feature: Symbol, span: Span, explain: &'static str) {
121     feature_warn_issue(sess, feature, span, GateIssue::Language, explain);
122 }
123 
124 /// Construct a future incompatibility diagnostic for a feature gate.
125 ///
126 /// This diagnostic is only a warning and *does not cause compilation to fail*.
127 ///
128 /// This variant allows you to control whether it is a library or language feature.
129 /// Almost always, you want to use this for a language feature. If so, prefer `feature_warn`.
130 #[allow(rustc::diagnostic_outside_of_impl)]
131 #[allow(rustc::untranslatable_diagnostic)]
feature_warn_issue( sess: &ParseSess, feature: Symbol, span: Span, issue: GateIssue, explain: &'static str, )132 pub fn feature_warn_issue(
133     sess: &ParseSess,
134     feature: Symbol,
135     span: Span,
136     issue: GateIssue,
137     explain: &'static str,
138 ) {
139     let mut err = sess.span_diagnostic.struct_span_warn(span, explain);
140     add_feature_diagnostics_for_issue(&mut err, sess, feature, issue);
141 
142     // Decorate this as a future-incompatibility lint as in rustc_middle::lint::struct_lint_level
143     let lint = UNSTABLE_SYNTAX_PRE_EXPANSION;
144     let future_incompatible = lint.future_incompatible.as_ref().unwrap();
145     err.code(DiagnosticId::Lint {
146         name: lint.name_lower(),
147         has_future_breakage: false,
148         is_force_warn: false,
149     });
150     err.warn(lint.desc);
151     err.note(format!("for more information, see {}", future_incompatible.reference));
152 
153     // A later feature_err call can steal and cancel this warning.
154     err.stash(span, StashKey::EarlySyntaxWarning);
155 }
156 
157 /// Adds the diagnostics for a feature to an existing error.
add_feature_diagnostics(err: &mut Diagnostic, sess: &ParseSess, feature: Symbol)158 pub fn add_feature_diagnostics(err: &mut Diagnostic, sess: &ParseSess, feature: Symbol) {
159     add_feature_diagnostics_for_issue(err, sess, feature, GateIssue::Language);
160 }
161 
162 /// Adds the diagnostics for a feature to an existing error.
163 ///
164 /// This variant allows you to control whether it is a library or language feature.
165 /// Almost always, you want to use this for a language feature. If so, prefer
166 /// `add_feature_diagnostics`.
add_feature_diagnostics_for_issue( err: &mut Diagnostic, sess: &ParseSess, feature: Symbol, issue: GateIssue, )167 pub fn add_feature_diagnostics_for_issue(
168     err: &mut Diagnostic,
169     sess: &ParseSess,
170     feature: Symbol,
171     issue: GateIssue,
172 ) {
173     if let Some(n) = find_feature_issue(feature, issue) {
174         err.subdiagnostic(FeatureDiagnosticForIssue { n });
175     }
176 
177     // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
178     if sess.unstable_features.is_nightly_build() {
179         err.subdiagnostic(FeatureDiagnosticHelp { feature });
180     }
181 }
182 
183 /// Info about a parsing session.
184 pub struct ParseSess {
185     pub span_diagnostic: Handler,
186     pub unstable_features: UnstableFeatures,
187     pub config: CrateConfig,
188     pub check_config: CrateCheckConfig,
189     pub edition: Edition,
190     /// Places where raw identifiers were used. This is used to avoid complaining about idents
191     /// clashing with keywords in new editions.
192     pub raw_identifier_spans: AppendOnlyVec<Span>,
193     /// Places where identifiers that contain invalid Unicode codepoints but that look like they
194     /// should be. Useful to avoid bad tokenization when encountering emoji. We group them to
195     /// provide a single error per unique incorrect identifier.
196     pub bad_unicode_identifiers: Lock<FxHashMap<Symbol, Vec<Span>>>,
197     source_map: Lrc<SourceMap>,
198     pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
199     /// Contains the spans of block expressions that could have been incomplete based on the
200     /// operation token that followed it, but that the parser cannot identify without further
201     /// analysis.
202     pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
203     pub gated_spans: GatedSpans,
204     pub symbol_gallery: SymbolGallery,
205     /// The parser has reached `Eof` due to an unclosed brace. Used to silence unnecessary errors.
206     pub reached_eof: AtomicBool,
207     /// Environment variables accessed during the build and their values when they exist.
208     pub env_depinfo: Lock<FxHashSet<(Symbol, Option<Symbol>)>>,
209     /// File paths accessed during the build.
210     pub file_depinfo: Lock<FxHashSet<Symbol>>,
211     /// Whether cfg(version) should treat the current release as incomplete
212     pub assume_incomplete_release: bool,
213     /// Spans passed to `proc_macro::quote_span`. Each span has a numerical
214     /// identifier represented by its position in the vector.
215     pub proc_macro_quoted_spans: AppendOnlyVec<Span>,
216     /// Used to generate new `AttrId`s. Every `AttrId` is unique.
217     pub attr_id_generator: AttrIdGenerator,
218 }
219 
220 impl ParseSess {
221     /// Used for testing.
new(locale_resources: Vec<&'static str>, file_path_mapping: FilePathMapping) -> Self222     pub fn new(locale_resources: Vec<&'static str>, file_path_mapping: FilePathMapping) -> Self {
223         let fallback_bundle = fallback_fluent_bundle(locale_resources, false);
224         let sm = Lrc::new(SourceMap::new(file_path_mapping));
225         let handler = Handler::with_tty_emitter(
226             ColorConfig::Auto,
227             true,
228             None,
229             Some(sm.clone()),
230             None,
231             fallback_bundle,
232         );
233         ParseSess::with_span_handler(handler, sm)
234     }
235 
with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self236     pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self {
237         Self {
238             span_diagnostic: handler,
239             unstable_features: UnstableFeatures::from_environment(None),
240             config: FxIndexSet::default(),
241             check_config: CrateCheckConfig::default(),
242             edition: ExpnId::root().expn_data().edition,
243             raw_identifier_spans: Default::default(),
244             bad_unicode_identifiers: Lock::new(Default::default()),
245             source_map,
246             buffered_lints: Lock::new(vec![]),
247             ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
248             gated_spans: GatedSpans::default(),
249             symbol_gallery: SymbolGallery::default(),
250             reached_eof: AtomicBool::new(false),
251             env_depinfo: Default::default(),
252             file_depinfo: Default::default(),
253             assume_incomplete_release: false,
254             proc_macro_quoted_spans: Default::default(),
255             attr_id_generator: AttrIdGenerator::new(),
256         }
257     }
258 
with_silent_emitter(fatal_note: Option<String>) -> Self259     pub fn with_silent_emitter(fatal_note: Option<String>) -> Self {
260         let fallback_bundle = fallback_fluent_bundle(Vec::new(), false);
261         let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
262         let fatal_handler =
263             Handler::with_tty_emitter(ColorConfig::Auto, false, None, None, None, fallback_bundle);
264         let handler = Handler::with_emitter(
265             false,
266             None,
267             Box::new(SilentEmitter { fatal_handler, fatal_note }),
268         );
269         ParseSess::with_span_handler(handler, sm)
270     }
271 
272     #[inline]
source_map(&self) -> &SourceMap273     pub fn source_map(&self) -> &SourceMap {
274         &self.source_map
275     }
276 
clone_source_map(&self) -> Lrc<SourceMap>277     pub fn clone_source_map(&self) -> Lrc<SourceMap> {
278         self.source_map.clone()
279     }
280 
buffer_lint( &self, lint: &'static Lint, span: impl Into<MultiSpan>, node_id: NodeId, msg: impl Into<DiagnosticMessage>, )281     pub fn buffer_lint(
282         &self,
283         lint: &'static Lint,
284         span: impl Into<MultiSpan>,
285         node_id: NodeId,
286         msg: impl Into<DiagnosticMessage>,
287     ) {
288         self.buffered_lints.with_lock(|buffered_lints| {
289             buffered_lints.push(BufferedEarlyLint {
290                 span: span.into(),
291                 node_id,
292                 msg: msg.into(),
293                 lint_id: LintId::of(lint),
294                 diagnostic: BuiltinLintDiagnostics::Normal,
295             });
296         });
297     }
298 
buffer_lint_with_diagnostic( &self, lint: &'static Lint, span: impl Into<MultiSpan>, node_id: NodeId, msg: impl Into<DiagnosticMessage>, diagnostic: BuiltinLintDiagnostics, )299     pub fn buffer_lint_with_diagnostic(
300         &self,
301         lint: &'static Lint,
302         span: impl Into<MultiSpan>,
303         node_id: NodeId,
304         msg: impl Into<DiagnosticMessage>,
305         diagnostic: BuiltinLintDiagnostics,
306     ) {
307         self.buffered_lints.with_lock(|buffered_lints| {
308             buffered_lints.push(BufferedEarlyLint {
309                 span: span.into(),
310                 node_id,
311                 msg: msg.into(),
312                 lint_id: LintId::of(lint),
313                 diagnostic,
314             });
315         });
316     }
317 
save_proc_macro_span(&self, span: Span) -> usize318     pub fn save_proc_macro_span(&self, span: Span) -> usize {
319         self.proc_macro_quoted_spans.push(span)
320     }
321 
proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> + '_322     pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> + '_ {
323         // This is equivalent to `.iter().copied().enumerate()`, but that isn't possible for
324         // AppendOnlyVec, so we resort to this scheme.
325         self.proc_macro_quoted_spans.iter_enumerated()
326     }
327 
328     #[track_caller]
create_err<'a>( &'a self, err: impl IntoDiagnostic<'a>, ) -> DiagnosticBuilder<'a, ErrorGuaranteed>329     pub fn create_err<'a>(
330         &'a self,
331         err: impl IntoDiagnostic<'a>,
332     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
333         err.into_diagnostic(&self.span_diagnostic)
334     }
335 
336     #[track_caller]
emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed337     pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
338         self.create_err(err).emit()
339     }
340 
341     #[track_caller]
create_warning<'a>( &'a self, warning: impl IntoDiagnostic<'a, ()>, ) -> DiagnosticBuilder<'a, ()>342     pub fn create_warning<'a>(
343         &'a self,
344         warning: impl IntoDiagnostic<'a, ()>,
345     ) -> DiagnosticBuilder<'a, ()> {
346         warning.into_diagnostic(&self.span_diagnostic)
347     }
348 
349     #[track_caller]
emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>)350     pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) {
351         self.create_warning(warning).emit()
352     }
353 
create_note<'a>( &'a self, note: impl IntoDiagnostic<'a, Noted>, ) -> DiagnosticBuilder<'a, Noted>354     pub fn create_note<'a>(
355         &'a self,
356         note: impl IntoDiagnostic<'a, Noted>,
357     ) -> DiagnosticBuilder<'a, Noted> {
358         note.into_diagnostic(&self.span_diagnostic)
359     }
360 
emit_note<'a>(&'a self, note: impl IntoDiagnostic<'a, Noted>) -> Noted361     pub fn emit_note<'a>(&'a self, note: impl IntoDiagnostic<'a, Noted>) -> Noted {
362         self.create_note(note).emit()
363     }
364 
create_fatal<'a>( &'a self, fatal: impl IntoDiagnostic<'a, !>, ) -> DiagnosticBuilder<'a, !>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 
emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> !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     #[track_caller]
struct_err( &self, msg: impl Into<DiagnosticMessage>, ) -> DiagnosticBuilder<'_, ErrorGuaranteed>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]
struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()>386     pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
387         self.span_diagnostic.struct_warn(msg)
388     }
389 
390     #[rustc_lint_diagnostics]
struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !>391     pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
392         self.span_diagnostic.struct_fatal(msg)
393     }
394 
395     #[rustc_lint_diagnostics]
struct_diagnostic<G: EmissionGuarantee>( &self, msg: impl Into<DiagnosticMessage>, ) -> DiagnosticBuilder<'_, G>396     pub fn struct_diagnostic<G: EmissionGuarantee>(
397         &self,
398         msg: impl Into<DiagnosticMessage>,
399     ) -> DiagnosticBuilder<'_, G> {
400         self.span_diagnostic.struct_diagnostic(msg)
401     }
402 }
403