]> git.lizzy.rs Git - rust.git/blob - src/librustc_session/parse.rs
Refactor non_ascii_idents lints, exclude ascii pair for confusable_idents lint.
[rust.git] / src / librustc_session / 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, OnceCell};
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::collections::BTreeMap;
17 use std::path::PathBuf;
18 use std::str;
19
20 /// The set of keys (and, optionally, values) that define the compilation
21 /// environment of the crate, used to drive conditional compilation.
22 pub type CrateConfig = FxHashSet<(Symbol, Option<Symbol>)>;
23
24 /// Collected spans during parsing for places where a certain feature was
25 /// used and should be feature gated accordingly in `check_crate`.
26 #[derive(Default)]
27 pub struct GatedSpans {
28     pub spans: Lock<FxHashMap<Symbol, Vec<Span>>>,
29 }
30
31 impl GatedSpans {
32     /// Feature gate the given `span` under the given `feature`
33     /// which is same `Symbol` used in `active.rs`.
34     pub fn gate(&self, feature: Symbol, span: Span) {
35         self.spans.borrow_mut().entry(feature).or_default().push(span);
36     }
37
38     /// Ungate the last span under the given `feature`.
39     /// Panics if the given `span` wasn't the last one.
40     ///
41     /// Using this is discouraged unless you have a really good reason to.
42     pub fn ungate_last(&self, feature: Symbol, span: Span) {
43         let removed_span = self.spans.borrow_mut().entry(feature).or_default().pop().unwrap();
44         debug_assert_eq!(span, removed_span);
45     }
46
47     /// Is the provided `feature` gate ungated currently?
48     ///
49     /// Using this is discouraged unless you have a really good reason to.
50     pub fn is_ungated(&self, feature: Symbol) -> bool {
51         self.spans.borrow().get(&feature).map_or(true, |spans| spans.is_empty())
52     }
53
54     /// Prepend the given set of `spans` onto the set in `self`.
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 occurrance span.
67     pub symbols: Lock<BTreeMap<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 occurance.
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 pub fn feature_err<'a>(
81     sess: &'a ParseSess,
82     feature: Symbol,
83     span: impl Into<MultiSpan>,
84     explain: &str,
85 ) -> DiagnosticBuilder<'a> {
86     feature_err_issue(sess, feature, span, GateIssue::Language, explain)
87 }
88
89 /// Construct a diagnostic for a feature gate error.
90 ///
91 /// This variant allows you to control whether it is a library or language feature.
92 /// Almost always, you want to use this for a language feature. If so, prefer `feature_err`.
93 pub fn feature_err_issue<'a>(
94     sess: &'a ParseSess,
95     feature: Symbol,
96     span: impl Into<MultiSpan>,
97     issue: GateIssue,
98     explain: &str,
99 ) -> DiagnosticBuilder<'a> {
100     let mut err = sess.span_diagnostic.struct_span_err_with_code(span, explain, error_code!(E0658));
101
102     if let Some(n) = find_feature_issue(feature, issue) {
103         err.note(&format!(
104             "see issue #{} <https://github.com/rust-lang/rust/issues/{}> for more information",
105             n, n,
106         ));
107     }
108
109     // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
110     if sess.unstable_features.is_nightly_build() {
111         err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature));
112     }
113
114     err
115 }
116
117 /// Info about a parsing session.
118 pub struct ParseSess {
119     pub span_diagnostic: Handler,
120     pub unstable_features: UnstableFeatures,
121     pub config: CrateConfig,
122     pub edition: Edition,
123     pub missing_fragment_specifiers: Lock<FxHashMap<Span, NodeId>>,
124     /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
125     pub raw_identifier_spans: Lock<Vec<Span>>,
126     /// Used to determine and report recursive module inclusions.
127     pub included_mod_stack: Lock<Vec<PathBuf>>,
128     source_map: Lrc<SourceMap>,
129     pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
130     /// Contains the spans of block expressions that could have been incomplete based on the
131     /// operation token that followed it, but that the parser cannot identify without further
132     /// analysis.
133     pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
134     pub injected_crate_name: OnceCell<Symbol>,
135     pub gated_spans: GatedSpans,
136     pub symbol_gallery: SymbolGallery,
137     /// The parser has reached `Eof` due to an unclosed brace. Used to silence unnecessary errors.
138     pub reached_eof: Lock<bool>,
139 }
140
141 impl ParseSess {
142     pub fn new(file_path_mapping: FilePathMapping) -> Self {
143         let sm = Lrc::new(SourceMap::new(file_path_mapping));
144         let handler = Handler::with_tty_emitter(ColorConfig::Auto, true, None, Some(sm.clone()));
145         ParseSess::with_span_handler(handler, sm)
146     }
147
148     pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self {
149         Self {
150             span_diagnostic: handler,
151             unstable_features: UnstableFeatures::from_environment(),
152             config: FxHashSet::default(),
153             edition: ExpnId::root().expn_data().edition,
154             missing_fragment_specifiers: Default::default(),
155             raw_identifier_spans: Lock::new(Vec::new()),
156             included_mod_stack: Lock::new(vec![]),
157             source_map,
158             buffered_lints: Lock::new(vec![]),
159             ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
160             injected_crate_name: OnceCell::new(),
161             gated_spans: GatedSpans::default(),
162             symbol_gallery: SymbolGallery::default(),
163             reached_eof: Lock::new(false),
164         }
165     }
166
167     pub fn with_silent_emitter() -> Self {
168         let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
169         let handler = Handler::with_emitter(false, None, Box::new(SilentEmitter));
170         ParseSess::with_span_handler(handler, sm)
171     }
172
173     #[inline]
174     pub fn source_map(&self) -> &SourceMap {
175         &self.source_map
176     }
177
178     pub fn clone_source_map(&self) -> Lrc<SourceMap> {
179         self.source_map.clone()
180     }
181
182     pub fn buffer_lint(
183         &self,
184         lint: &'static Lint,
185         span: impl Into<MultiSpan>,
186         node_id: NodeId,
187         msg: &str,
188     ) {
189         self.buffered_lints.with_lock(|buffered_lints| {
190             buffered_lints.push(BufferedEarlyLint {
191                 span: span.into(),
192                 node_id,
193                 msg: msg.into(),
194                 lint_id: LintId::of(lint),
195                 diagnostic: BuiltinLintDiagnostics::Normal,
196             });
197         });
198     }
199
200     pub fn buffer_lint_with_diagnostic(
201         &self,
202         lint: &'static Lint,
203         span: impl Into<MultiSpan>,
204         node_id: NodeId,
205         msg: &str,
206         diagnostic: BuiltinLintDiagnostics,
207     ) {
208         self.buffered_lints.with_lock(|buffered_lints| {
209             buffered_lints.push(BufferedEarlyLint {
210                 span: span.into(),
211                 node_id,
212                 msg: msg.into(),
213                 lint_id: LintId::of(lint),
214                 diagnostic,
215             });
216         });
217     }
218
219     /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
220     /// parser to continue parsing the following operation as part of the same expression.
221     pub fn expr_parentheses_needed(
222         &self,
223         err: &mut DiagnosticBuilder<'_>,
224         span: Span,
225         alt_snippet: Option<String>,
226     ) {
227         if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
228             err.span_suggestion(
229                 span,
230                 "parentheses are required to parse this as an expression",
231                 format!("({})", snippet),
232                 Applicability::MachineApplicable,
233             );
234         }
235     }
236 }