]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_session/src/parse.rs
Auto merge of #83759 - SkiFire13:fix-diag, r=estebank
[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::lint::{BufferedEarlyLint, BuiltinLintDiagnostics, Lint, LintId};
5 use rustc_ast::node_id::NodeId;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_data_structures::sync::{Lock, Lrc};
8 use rustc_errors::{emitter::SilentEmitter, ColorConfig, Handler};
9 use rustc_errors::{error_code, Applicability, DiagnosticBuilder};
10 use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures};
11 use rustc_span::edition::Edition;
12 use rustc_span::hygiene::ExpnId;
13 use rustc_span::source_map::{FilePathMapping, SourceMap};
14 use rustc_span::{MultiSpan, Span, Symbol};
15
16 use std::str;
17
18 /// The set of keys (and, optionally, values) that define the compilation
19 /// environment of the crate, used to drive conditional compilation.
20 pub type CrateConfig = FxHashSet<(Symbol, Option<Symbol>)>;
21
22 /// Collected spans during parsing for places where a certain feature was
23 /// used and should be feature gated accordingly in `check_crate`.
24 #[derive(Default)]
25 pub struct GatedSpans {
26     pub spans: Lock<FxHashMap<Symbol, Vec<Span>>>,
27 }
28
29 impl GatedSpans {
30     /// Feature gate the given `span` under the given `feature`
31     /// which is same `Symbol` used in `active.rs`.
32     pub fn gate(&self, feature: Symbol, span: Span) {
33         self.spans.borrow_mut().entry(feature).or_default().push(span);
34     }
35
36     /// Ungate the last span under the given `feature`.
37     /// Panics if the given `span` wasn't the last one.
38     ///
39     /// Using this is discouraged unless you have a really good reason to.
40     pub fn ungate_last(&self, feature: Symbol, span: Span) {
41         let removed_span = self.spans.borrow_mut().entry(feature).or_default().pop().unwrap();
42         debug_assert_eq!(span, removed_span);
43     }
44
45     /// Is the provided `feature` gate ungated currently?
46     ///
47     /// Using this is discouraged unless you have a really good reason to.
48     pub fn is_ungated(&self, feature: Symbol) -> bool {
49         self.spans.borrow().get(&feature).map_or(true, |spans| spans.is_empty())
50     }
51
52     /// Prepend the given set of `spans` onto the set in `self`.
53     pub fn merge(&self, mut spans: FxHashMap<Symbol, Vec<Span>>) {
54         let mut inner = self.spans.borrow_mut();
55         for (gate, mut gate_spans) in inner.drain() {
56             spans.entry(gate).or_default().append(&mut gate_spans);
57         }
58         *inner = spans;
59     }
60 }
61
62 #[derive(Default)]
63 pub struct SymbolGallery {
64     /// All symbols occurred and their first occurrence span.
65     pub symbols: Lock<FxHashMap<Symbol, Span>>,
66 }
67
68 impl SymbolGallery {
69     /// Insert a symbol and its span into symbol gallery.
70     /// If the symbol has occurred before, ignore the new occurance.
71     pub fn insert(&self, symbol: Symbol, span: Span) {
72         self.symbols.lock().entry(symbol).or_insert(span);
73     }
74 }
75
76 /// Construct a diagnostic for a language feature error due to the given `span`.
77 /// The `feature`'s `Symbol` is the one you used in `active.rs` and `rustc_span::symbols`.
78 pub fn feature_err<'a>(
79     sess: &'a ParseSess,
80     feature: Symbol,
81     span: impl Into<MultiSpan>,
82     explain: &str,
83 ) -> DiagnosticBuilder<'a> {
84     feature_err_issue(sess, feature, span, GateIssue::Language, explain)
85 }
86
87 /// Construct a diagnostic for a feature gate error.
88 ///
89 /// This variant allows you to control whether it is a library or language feature.
90 /// Almost always, you want to use this for a language feature. If so, prefer `feature_err`.
91 pub fn feature_err_issue<'a>(
92     sess: &'a ParseSess,
93     feature: Symbol,
94     span: impl Into<MultiSpan>,
95     issue: GateIssue,
96     explain: &str,
97 ) -> DiagnosticBuilder<'a> {
98     let mut err = sess.span_diagnostic.struct_span_err_with_code(span, explain, error_code!(E0658));
99
100     if let Some(n) = find_feature_issue(feature, issue) {
101         err.note(&format!(
102             "see issue #{} <https://github.com/rust-lang/rust/issues/{}> for more information",
103             n, n,
104         ));
105     }
106
107     // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
108     if sess.unstable_features.is_nightly_build() {
109         err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature));
110     }
111
112     err
113 }
114
115 /// Info about a parsing session.
116 pub struct ParseSess {
117     pub span_diagnostic: Handler,
118     pub unstable_features: UnstableFeatures,
119     pub config: CrateConfig,
120     pub edition: Edition,
121     pub missing_fragment_specifiers: Lock<FxHashMap<Span, NodeId>>,
122     /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
123     pub raw_identifier_spans: Lock<Vec<Span>>,
124     source_map: Lrc<SourceMap>,
125     pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
126     /// Contains the spans of block expressions that could have been incomplete based on the
127     /// operation token that followed it, but that the parser cannot identify without further
128     /// analysis.
129     pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
130     pub gated_spans: GatedSpans,
131     pub symbol_gallery: SymbolGallery,
132     /// The parser has reached `Eof` due to an unclosed brace. Used to silence unnecessary errors.
133     pub reached_eof: Lock<bool>,
134     /// Environment variables accessed during the build and their values when they exist.
135     pub env_depinfo: Lock<FxHashSet<(Symbol, Option<Symbol>)>>,
136     /// All the type ascriptions expressions that have had a suggestion for likely path typo.
137     pub type_ascription_path_suggestions: Lock<FxHashSet<Span>>,
138     /// Whether cfg(version) should treat the current release as incomplete
139     pub assume_incomplete_release: bool,
140     /// Spans passed to `proc_macro::quote_span`. Each span has a numerical
141     /// identifier represented by its position in the vector.
142     pub proc_macro_quoted_spans: Lock<Vec<Span>>,
143 }
144
145 impl ParseSess {
146     /// Used for testing.
147     pub fn new(file_path_mapping: FilePathMapping) -> Self {
148         let sm = Lrc::new(SourceMap::new(file_path_mapping));
149         let handler = Handler::with_tty_emitter(ColorConfig::Auto, true, None, Some(sm.clone()));
150         ParseSess::with_span_handler(handler, sm)
151     }
152
153     pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self {
154         Self {
155             span_diagnostic: handler,
156             unstable_features: UnstableFeatures::from_environment(None),
157             config: FxHashSet::default(),
158             edition: ExpnId::root().expn_data().edition,
159             missing_fragment_specifiers: Default::default(),
160             raw_identifier_spans: Lock::new(Vec::new()),
161             source_map,
162             buffered_lints: Lock::new(vec![]),
163             ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
164             gated_spans: GatedSpans::default(),
165             symbol_gallery: SymbolGallery::default(),
166             reached_eof: Lock::new(false),
167             env_depinfo: Default::default(),
168             type_ascription_path_suggestions: Default::default(),
169             assume_incomplete_release: false,
170             proc_macro_quoted_spans: Default::default(),
171         }
172     }
173
174     pub fn with_silent_emitter() -> Self {
175         let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
176         let handler = Handler::with_emitter(false, None, Box::new(SilentEmitter));
177         ParseSess::with_span_handler(handler, sm)
178     }
179
180     #[inline]
181     pub fn source_map(&self) -> &SourceMap {
182         &self.source_map
183     }
184
185     pub fn clone_source_map(&self) -> Lrc<SourceMap> {
186         self.source_map.clone()
187     }
188
189     pub fn buffer_lint(
190         &self,
191         lint: &'static Lint,
192         span: impl Into<MultiSpan>,
193         node_id: NodeId,
194         msg: &str,
195     ) {
196         self.buffered_lints.with_lock(|buffered_lints| {
197             buffered_lints.push(BufferedEarlyLint {
198                 span: span.into(),
199                 node_id,
200                 msg: msg.into(),
201                 lint_id: LintId::of(lint),
202                 diagnostic: BuiltinLintDiagnostics::Normal,
203             });
204         });
205     }
206
207     pub fn buffer_lint_with_diagnostic(
208         &self,
209         lint: &'static Lint,
210         span: impl Into<MultiSpan>,
211         node_id: NodeId,
212         msg: &str,
213         diagnostic: BuiltinLintDiagnostics,
214     ) {
215         self.buffered_lints.with_lock(|buffered_lints| {
216             buffered_lints.push(BufferedEarlyLint {
217                 span: span.into(),
218                 node_id,
219                 msg: msg.into(),
220                 lint_id: LintId::of(lint),
221                 diagnostic,
222             });
223         });
224     }
225
226     /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
227     /// parser to continue parsing the following operation as part of the same expression.
228     pub fn expr_parentheses_needed(
229         &self,
230         err: &mut DiagnosticBuilder<'_>,
231         span: Span,
232         alt_snippet: Option<String>,
233     ) {
234         if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
235             err.span_suggestion(
236                 span,
237                 "parentheses are required to parse this as an expression",
238                 format!("({})", snippet),
239                 Applicability::MachineApplicable,
240             );
241         }
242     }
243
244     pub fn save_proc_macro_span(&self, span: Span) -> usize {
245         let mut spans = self.proc_macro_quoted_spans.lock();
246         spans.push(span);
247         return spans.len() - 1;
248     }
249
250     pub fn proc_macro_quoted_spans(&self) -> Vec<Span> {
251         self.proc_macro_quoted_spans.lock().clone()
252     }
253 }