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