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 ExprParenthesesNeeded, FeatureDiagnosticForIssue, FeatureDiagnosticHelp, FeatureGateError,
9 builtin::UNSTABLE_SYNTAX_PRE_EXPANSION, BufferedEarlyLint, BuiltinLintDiagnostics, Lint, LintId,
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};
16 fallback_fluent_bundle, AddToDiagnostic, Diagnostic, DiagnosticBuilder, DiagnosticId,
17 DiagnosticMessage, EmissionGuarantee, ErrorGuaranteed, IntoDiagnostic, MultiSpan, StashKey,
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};
25 use rustc_ast::attr::AttrIdGenerator;
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>;
33 /// Collected spans during parsing for places where a certain feature was
34 /// used and should be feature gated accordingly in `check_crate`.
36 pub struct GatedSpans {
37 pub spans: Lock<FxHashMap<Symbol, Vec<Span>>>,
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);
47 /// Ungate the last span under the given `feature`.
48 /// Panics if the given `span` wasn't the last one.
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);
56 /// Is the provided `feature` gate ungated currently?
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())
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);
74 pub struct SymbolGallery {
75 /// All symbols occurred and their first occurrence span.
76 pub symbols: Lock<FxHashMap<Symbol, Span>>,
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);
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>(
92 span: impl Into<MultiSpan>,
94 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
95 feature_err_issue(sess, feature, span, GateIssue::Language, explain)
98 /// Construct a diagnostic for a feature gate error.
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>(
105 span: impl Into<MultiSpan>,
108 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
109 let span = span.into();
111 // Cancel an earlier warning for this same error, if it exists.
112 if let Some(span) = span.primary_span() {
114 .steal_diagnostic(span, StashKey::EarlySyntaxWarning)
115 .map(|err| err.cancel());
118 let mut err = sess.create_err(FeatureGateError { span, explain });
119 add_feature_diagnostics_for_issue(&mut err, sess, feature, issue);
123 /// Construct a future incompatibility diagnostic for a feature gate.
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);
130 /// Construct a future incompatibility diagnostic for a feature gate.
132 /// This diagnostic is only a warning and *does not cause compilation to fail*.
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>(
145 let mut err = sess.span_diagnostic.struct_span_warn(span, explain);
146 add_feature_diagnostics_for_issue(&mut err, sess, feature, issue);
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,
157 err.note(format!("for more information, see {}", future_incompatible.reference));
159 // A later feature_err call can steal and cancel this warning.
160 err.stash(span, StashKey::EarlySyntaxWarning);
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);
168 /// Adds the diagnostics for a feature to an existing error.
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,
179 if let Some(n) = find_feature_issue(feature, issue) {
180 err.subdiagnostic(FeatureDiagnosticForIssue { n });
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 });
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
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,
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(
241 ParseSess::with_span_handler(handler, sm)
244 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> 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()),
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(),
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()));
272 Handler::with_tty_emitter(ColorConfig::Auto, false, None, None, None, fallback_bundle);
273 let handler = Handler::with_emitter(
276 Box::new(SilentEmitter { fatal_handler, fatal_note }),
278 ParseSess::with_span_handler(handler, sm)
282 pub fn source_map(&self) -> &SourceMap {
286 pub fn clone_source_map(&self) -> Lrc<SourceMap> {
287 self.source_map.clone()
293 span: impl Into<MultiSpan>,
297 self.buffered_lints.with_lock(|buffered_lints| {
298 buffered_lints.push(BufferedEarlyLint {
302 lint_id: LintId::of(lint),
303 diagnostic: BuiltinLintDiagnostics::Normal,
308 pub fn buffer_lint_with_diagnostic(
311 span: impl Into<MultiSpan>,
314 diagnostic: BuiltinLintDiagnostics,
316 self.buffered_lints.with_lock(|buffered_lints| {
317 buffered_lints.push(BufferedEarlyLint {
321 lint_id: LintId::of(lint),
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);
333 pub fn save_proc_macro_span(&self, span: Span) -> usize {
334 let mut spans = self.proc_macro_quoted_spans.lock();
336 return spans.len() - 1;
339 pub fn proc_macro_quoted_spans(&self) -> Vec<Span> {
340 self.proc_macro_quoted_spans.lock().clone()
343 pub fn create_err<'a>(
345 err: impl IntoDiagnostic<'a>,
346 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
347 err.into_diagnostic(&self.span_diagnostic)
350 pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
351 self.create_err(err).emit()
354 pub fn create_warning<'a>(
356 warning: impl IntoDiagnostic<'a, ()>,
357 ) -> DiagnosticBuilder<'a, ()> {
358 warning.into_diagnostic(&self.span_diagnostic)
361 pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) {
362 self.create_warning(warning).emit()
365 pub fn create_fatal<'a>(
367 fatal: impl IntoDiagnostic<'a, !>,
368 ) -> DiagnosticBuilder<'a, !> {
369 fatal.into_diagnostic(&self.span_diagnostic)
372 pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! {
373 self.create_fatal(fatal).emit()
376 #[rustc_lint_diagnostics]
379 msg: impl Into<DiagnosticMessage>,
380 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
381 self.span_diagnostic.struct_err(msg)
384 #[rustc_lint_diagnostics]
385 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
386 self.span_diagnostic.struct_warn(msg)
389 #[rustc_lint_diagnostics]
390 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
391 self.span_diagnostic.struct_fatal(msg)
394 #[rustc_lint_diagnostics]
395 pub fn struct_diagnostic<G: EmissionGuarantee>(
397 msg: impl Into<DiagnosticMessage>,
398 ) -> DiagnosticBuilder<'_, G> {
399 self.span_diagnostic.struct_diagnostic(msg)