1 //! Contains `ParseSess` which holds state living beyond what one `Parser` might.
2 //! It also serves as an input to the parser itself.
4 use crate::config::CheckCfg;
5 use crate::errors::{FeatureDiagnosticForIssue, FeatureDiagnosticHelp, FeatureGateError};
7 builtin::UNSTABLE_SYNTAX_PRE_EXPANSION, BufferedEarlyLint, BuiltinLintDiagnostics, Lint, LintId,
9 use rustc_ast::node_id::NodeId;
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
11 use rustc_data_structures::sync::{Lock, Lrc};
12 use rustc_errors::{emitter::SilentEmitter, ColorConfig, Handler};
14 fallback_fluent_bundle, Diagnostic, DiagnosticBuilder, DiagnosticId, DiagnosticMessage,
15 EmissionGuarantee, ErrorGuaranteed, IntoDiagnostic, MultiSpan, Noted, StashKey,
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};
23 use rustc_ast::attr::AttrIdGenerator;
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>;
31 /// Collected spans during parsing for places where a certain feature was
32 /// used and should be feature gated accordingly in `check_crate`.
34 pub struct GatedSpans {
35 pub spans: Lock<FxHashMap<Symbol, Vec<Span>>>,
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);
45 /// Ungate the last span under the given `feature`.
46 /// Panics if the given `span` wasn't the last one.
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);
54 /// Is the provided `feature` gate ungated currently?
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())
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);
72 pub struct SymbolGallery {
73 /// All symbols occurred and their first occurrence span.
74 pub symbols: Lock<FxHashMap<Symbol, Span>>,
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);
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>(
90 span: impl Into<MultiSpan>,
92 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
93 feature_err_issue(sess, feature, span, GateIssue::Language, explain)
96 /// Construct a diagnostic for a feature gate error.
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`.
101 pub fn feature_err_issue<'a>(
104 span: impl Into<MultiSpan>,
107 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
108 let span = span.into();
110 // Cancel an earlier warning for this same error, if it exists.
111 if let Some(span) = span.primary_span() {
113 .steal_diagnostic(span, StashKey::EarlySyntaxWarning)
114 .map(|err| err.cancel());
117 let mut err = sess.create_err(FeatureGateError { span, explain });
118 add_feature_diagnostics_for_issue(&mut err, sess, feature, issue);
122 /// Construct a future incompatibility diagnostic for a feature gate.
124 /// This diagnostic is only a warning and *does not cause compilation to fail*.
125 pub fn feature_warn(sess: &ParseSess, feature: Symbol, span: Span, explain: &str) {
126 feature_warn_issue(sess, feature, span, GateIssue::Language, explain);
129 /// Construct a future incompatibility diagnostic for a feature gate.
131 /// This diagnostic is only a warning and *does not cause compilation to fail*.
133 /// This variant allows you to control whether it is a library or language feature.
134 /// Almost always, you want to use this for a language feature. If so, prefer `feature_warn`.
135 #[allow(rustc::diagnostic_outside_of_impl)]
136 #[allow(rustc::untranslatable_diagnostic)]
137 pub fn feature_warn_issue(
144 let mut err = sess.span_diagnostic.struct_span_warn(span, explain);
145 add_feature_diagnostics_for_issue(&mut err, sess, feature, issue);
147 // Decorate this as a future-incompatibility lint as in rustc_middle::lint::struct_lint_level
148 let lint = UNSTABLE_SYNTAX_PRE_EXPANSION;
149 let future_incompatible = lint.future_incompatible.as_ref().unwrap();
150 err.code(DiagnosticId::Lint {
151 name: lint.name_lower(),
152 has_future_breakage: false,
153 is_force_warn: false,
156 err.note(format!("for more information, see {}", future_incompatible.reference));
158 // A later feature_err call can steal and cancel this warning.
159 err.stash(span, StashKey::EarlySyntaxWarning);
162 /// Adds the diagnostics for a feature to an existing error.
163 pub fn add_feature_diagnostics(err: &mut Diagnostic, sess: &ParseSess, feature: Symbol) {
164 add_feature_diagnostics_for_issue(err, sess, feature, GateIssue::Language);
167 /// Adds the diagnostics for a feature to an existing error.
169 /// This variant allows you to control whether it is a library or language feature.
170 /// Almost always, you want to use this for a language feature. If so, prefer
171 /// `add_feature_diagnostics`.
172 pub fn add_feature_diagnostics_for_issue(
173 err: &mut Diagnostic,
178 if let Some(n) = find_feature_issue(feature, issue) {
179 err.subdiagnostic(FeatureDiagnosticForIssue { n });
182 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
183 if sess.unstable_features.is_nightly_build() {
184 err.subdiagnostic(FeatureDiagnosticHelp { feature });
188 /// Info about a parsing session.
189 pub struct ParseSess {
190 pub span_diagnostic: Handler,
191 pub unstable_features: UnstableFeatures,
192 pub config: CrateConfig,
193 pub check_config: CrateCheckConfig,
194 pub edition: Edition,
195 /// Places where raw identifiers were used. This is used to avoid complaining about idents
196 /// clashing with keywords in new editions.
197 pub raw_identifier_spans: Lock<Vec<Span>>,
198 /// Places where identifiers that contain invalid Unicode codepoints but that look like they
199 /// should be. Useful to avoid bad tokenization when encountering emoji. We group them to
200 /// provide a single error per unique incorrect identifier.
201 pub bad_unicode_identifiers: Lock<FxHashMap<Symbol, Vec<Span>>>,
202 source_map: Lrc<SourceMap>,
203 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
204 /// Contains the spans of block expressions that could have been incomplete based on the
205 /// operation token that followed it, but that the parser cannot identify without further
207 pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
208 pub gated_spans: GatedSpans,
209 pub symbol_gallery: SymbolGallery,
210 /// The parser has reached `Eof` due to an unclosed brace. Used to silence unnecessary errors.
211 pub reached_eof: Lock<bool>,
212 /// Environment variables accessed during the build and their values when they exist.
213 pub env_depinfo: Lock<FxHashSet<(Symbol, Option<Symbol>)>>,
214 /// File paths accessed during the build.
215 pub file_depinfo: Lock<FxHashSet<Symbol>>,
216 /// All the type ascriptions expressions that have had a suggestion for likely path typo.
217 pub type_ascription_path_suggestions: Lock<FxHashSet<Span>>,
218 /// Whether cfg(version) should treat the current release as incomplete
219 pub assume_incomplete_release: bool,
220 /// Spans passed to `proc_macro::quote_span`. Each span has a numerical
221 /// identifier represented by its position in the vector.
222 pub proc_macro_quoted_spans: Lock<Vec<Span>>,
223 /// Used to generate new `AttrId`s. Every `AttrId` is unique.
224 pub attr_id_generator: AttrIdGenerator,
228 /// Used for testing.
229 pub fn new(file_path_mapping: FilePathMapping) -> Self {
230 let fallback_bundle = fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
231 let sm = Lrc::new(SourceMap::new(file_path_mapping));
232 let handler = Handler::with_tty_emitter(
240 ParseSess::with_span_handler(handler, sm)
243 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self {
245 span_diagnostic: handler,
246 unstable_features: UnstableFeatures::from_environment(None),
247 config: FxIndexSet::default(),
248 check_config: CrateCheckConfig::default(),
249 edition: ExpnId::root().expn_data().edition,
250 raw_identifier_spans: Lock::new(Vec::new()),
251 bad_unicode_identifiers: Lock::new(Default::default()),
253 buffered_lints: Lock::new(vec![]),
254 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
255 gated_spans: GatedSpans::default(),
256 symbol_gallery: SymbolGallery::default(),
257 reached_eof: Lock::new(false),
258 env_depinfo: Default::default(),
259 file_depinfo: Default::default(),
260 type_ascription_path_suggestions: Default::default(),
261 assume_incomplete_release: false,
262 proc_macro_quoted_spans: Default::default(),
263 attr_id_generator: AttrIdGenerator::new(),
267 pub fn with_silent_emitter(fatal_note: Option<String>) -> Self {
268 let fallback_bundle = fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
269 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
271 Handler::with_tty_emitter(ColorConfig::Auto, false, None, None, None, fallback_bundle);
272 let handler = Handler::with_emitter(
275 Box::new(SilentEmitter { fatal_handler, fatal_note }),
277 ParseSess::with_span_handler(handler, sm)
281 pub fn source_map(&self) -> &SourceMap {
285 pub fn clone_source_map(&self) -> Lrc<SourceMap> {
286 self.source_map.clone()
292 span: impl Into<MultiSpan>,
296 self.buffered_lints.with_lock(|buffered_lints| {
297 buffered_lints.push(BufferedEarlyLint {
301 lint_id: LintId::of(lint),
302 diagnostic: BuiltinLintDiagnostics::Normal,
307 pub fn buffer_lint_with_diagnostic(
310 span: impl Into<MultiSpan>,
313 diagnostic: BuiltinLintDiagnostics,
315 self.buffered_lints.with_lock(|buffered_lints| {
316 buffered_lints.push(BufferedEarlyLint {
320 lint_id: LintId::of(lint),
326 pub fn save_proc_macro_span(&self, span: Span) -> usize {
327 let mut spans = self.proc_macro_quoted_spans.lock();
329 return spans.len() - 1;
332 pub fn proc_macro_quoted_spans(&self) -> Vec<Span> {
333 self.proc_macro_quoted_spans.lock().clone()
337 pub fn create_err<'a>(
339 err: impl IntoDiagnostic<'a>,
340 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
341 err.into_diagnostic(&self.span_diagnostic)
345 pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
346 self.create_err(err).emit()
350 pub fn create_warning<'a>(
352 warning: impl IntoDiagnostic<'a, ()>,
353 ) -> DiagnosticBuilder<'a, ()> {
354 warning.into_diagnostic(&self.span_diagnostic)
358 pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) {
359 self.create_warning(warning).emit()
362 pub fn create_note<'a>(
364 note: impl IntoDiagnostic<'a, Noted>,
365 ) -> DiagnosticBuilder<'a, Noted> {
366 note.into_diagnostic(&self.span_diagnostic)
369 pub fn emit_note<'a>(&'a self, note: impl IntoDiagnostic<'a, Noted>) -> Noted {
370 self.create_note(note).emit()
373 pub fn create_fatal<'a>(
375 fatal: impl IntoDiagnostic<'a, !>,
376 ) -> DiagnosticBuilder<'a, !> {
377 fatal.into_diagnostic(&self.span_diagnostic)
380 pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! {
381 self.create_fatal(fatal).emit()
384 #[rustc_lint_diagnostics]
388 msg: impl Into<DiagnosticMessage>,
389 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
390 self.span_diagnostic.struct_err(msg)
393 #[rustc_lint_diagnostics]
394 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
395 self.span_diagnostic.struct_warn(msg)
398 #[rustc_lint_diagnostics]
399 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
400 self.span_diagnostic.struct_fatal(msg)
403 #[rustc_lint_diagnostics]
404 pub fn struct_diagnostic<G: EmissionGuarantee>(
406 msg: impl Into<DiagnosticMessage>,
407 ) -> DiagnosticBuilder<'_, G> {
408 self.span_diagnostic.struct_diagnostic(msg)