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;
6 builtin::UNSTABLE_SYNTAX_PRE_EXPANSION, BufferedEarlyLint, BuiltinLintDiagnostics, Lint, LintId,
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};
14 error_code, fallback_fluent_bundle, Applicability, Diagnostic, DiagnosticBuilder, DiagnosticId,
15 DiagnosticMessage, EmissionGuarantee, ErrorGuaranteed, MultiSpan, 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};
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>;
30 /// Collected spans during parsing for places where a certain feature was
31 /// used and should be feature gated accordingly in `check_crate`.
33 pub struct GatedSpans {
34 pub spans: Lock<FxHashMap<Symbol, Vec<Span>>>,
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);
44 /// Ungate the last span under the given `feature`.
45 /// Panics if the given `span` wasn't the last one.
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);
53 /// Is the provided `feature` gate ungated currently?
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())
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);
71 pub struct SymbolGallery {
72 /// All symbols occurred and their first occurrence span.
73 pub symbols: Lock<FxHashMap<Symbol, Span>>,
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);
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>(
89 span: impl Into<MultiSpan>,
91 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
92 feature_err_issue(sess, feature, span, GateIssue::Language, explain)
95 /// Construct a diagnostic for a feature gate error.
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>(
102 span: impl Into<MultiSpan>,
105 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
106 let span = span.into();
108 // Cancel an earlier warning for this same error, if it exists.
109 if let Some(span) = span.primary_span() {
111 .steal_diagnostic(span, StashKey::EarlySyntaxWarning)
112 .map(|err| err.cancel());
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);
120 /// Construct a future incompatibility diagnostic for a feature gate.
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);
127 /// Construct a future incompatibility diagnostic for a feature gate.
129 /// This diagnostic is only a warning and *does not cause compilation to fail*.
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>(
140 let mut err = sess.span_diagnostic.struct_span_warn(span, explain);
141 add_feature_diagnostics_for_issue(&mut err, sess, feature, issue);
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,
152 err.note(format!("for more information, see {}", future_incompatible.reference));
154 // A later feature_err call can steal and cancel this warning.
155 err.stash(span, StashKey::EarlySyntaxWarning);
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);
163 /// Adds the diagnostics for a feature to an existing error.
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,
174 if let Some(n) = find_feature_issue(feature, issue) {
176 "see issue #{n} <https://github.com/rust-lang/rust/issues/{n}> for more information"
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"));
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
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>>,
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(
236 ParseSess::with_span_handler(handler, sm)
239 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> 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()),
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(),
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()));
266 Handler::with_tty_emitter(ColorConfig::Auto, false, None, None, None, fallback_bundle);
267 let handler = Handler::with_emitter(
270 Box::new(SilentEmitter { fatal_handler, fatal_note }),
272 ParseSess::with_span_handler(handler, sm)
276 pub fn source_map(&self) -> &SourceMap {
280 pub fn clone_source_map(&self) -> Lrc<SourceMap> {
281 self.source_map.clone()
287 span: impl Into<MultiSpan>,
291 self.buffered_lints.with_lock(|buffered_lints| {
292 buffered_lints.push(BufferedEarlyLint {
296 lint_id: LintId::of(lint),
297 diagnostic: BuiltinLintDiagnostics::Normal,
302 pub fn buffer_lint_with_diagnostic(
305 span: impl Into<MultiSpan>,
308 diagnostic: BuiltinLintDiagnostics,
310 self.buffered_lints.with_lock(|buffered_lints| {
311 buffered_lints.push(BufferedEarlyLint {
315 lint_id: LintId::of(lint),
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,
331 pub fn save_proc_macro_span(&self, span: Span) -> usize {
332 let mut spans = self.proc_macro_quoted_spans.lock();
334 return spans.len() - 1;
337 pub fn proc_macro_quoted_spans(&self) -> Vec<Span> {
338 self.proc_macro_quoted_spans.lock().clone()
341 pub fn create_err<'a>(
343 err: impl SessionDiagnostic<'a>,
344 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
345 err.into_diagnostic(self)
348 pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) -> ErrorGuaranteed {
349 self.create_err(err).emit()
352 pub fn create_warning<'a>(
354 warning: impl SessionDiagnostic<'a, ()>,
355 ) -> DiagnosticBuilder<'a, ()> {
356 warning.into_diagnostic(self)
359 pub fn emit_warning<'a>(&'a self, warning: impl SessionDiagnostic<'a, ()>) {
360 self.create_warning(warning).emit()
363 pub fn create_fatal<'a>(
365 fatal: impl SessionDiagnostic<'a, !>,
366 ) -> DiagnosticBuilder<'a, !> {
367 fatal.into_diagnostic(self)
370 pub fn emit_fatal<'a>(&'a self, fatal: impl SessionDiagnostic<'a, !>) -> ! {
371 self.create_fatal(fatal).emit()
374 #[rustc_lint_diagnostics]
377 msg: impl Into<DiagnosticMessage>,
378 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
379 self.span_diagnostic.struct_err(msg)
382 #[rustc_lint_diagnostics]
383 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
384 self.span_diagnostic.struct_warn(msg)
387 #[rustc_lint_diagnostics]
388 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
389 self.span_diagnostic.struct_fatal(msg)
392 #[rustc_lint_diagnostics]
393 pub fn struct_diagnostic<G: EmissionGuarantee>(
395 msg: impl Into<DiagnosticMessage>,
396 ) -> DiagnosticBuilder<'_, G> {
397 self.span_diagnostic.struct_diagnostic(msg)