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