]> git.lizzy.rs Git - rust.git/blob - src/librustc_session/parse.rs
Rollup merge of #68409 - sinkuu:temp_path, r=Mark-Simulacrum
[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_errors::{emitter::SilentEmitter, ColorConfig, Handler};
10 use rustc_errors::{error_code, Applicability, DiagnosticBuilder};
11 use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures};
12 use rustc_span::edition::Edition;
13 use rustc_span::hygiene::ExpnId;
14 use rustc_span::source_map::{FilePathMapping, SourceMap};
15 use rustc_span::{MultiSpan, Span, Symbol};
16
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 /// Construct a diagnostic for a language feature error due to the given `span`.
65 /// The `feature`'s `Symbol` is the one you used in `active.rs` and `rustc_span::symbols`.
66 pub fn feature_err<'a>(
67     sess: &'a ParseSess,
68     feature: Symbol,
69     span: impl Into<MultiSpan>,
70     explain: &str,
71 ) -> DiagnosticBuilder<'a> {
72     feature_err_issue(sess, feature, span, GateIssue::Language, explain)
73 }
74
75 /// Construct a diagnostic for a feature gate error.
76 ///
77 /// This variant allows you to control whether it is a library or language feature.
78 /// Almost always, you want to use this for a language feature. If so, prefer `feature_err`.
79 pub fn feature_err_issue<'a>(
80     sess: &'a ParseSess,
81     feature: Symbol,
82     span: impl Into<MultiSpan>,
83     issue: GateIssue,
84     explain: &str,
85 ) -> DiagnosticBuilder<'a> {
86     let mut err = sess.span_diagnostic.struct_span_err_with_code(span, explain, error_code!(E0658));
87
88     if let Some(n) = find_feature_issue(feature, issue) {
89         err.note(&format!(
90             "for more information, see https://github.com/rust-lang/rust/issues/{}",
91             n,
92         ));
93     }
94
95     // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
96     if sess.unstable_features.is_nightly_build() {
97         err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature));
98     }
99
100     err
101 }
102
103 /// Info about a parsing session.
104 pub struct ParseSess {
105     pub span_diagnostic: Handler,
106     pub unstable_features: UnstableFeatures,
107     pub config: CrateConfig,
108     pub edition: Edition,
109     pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
110     /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
111     pub raw_identifier_spans: Lock<Vec<Span>>,
112     /// Used to determine and report recursive module inclusions.
113     pub included_mod_stack: Lock<Vec<PathBuf>>,
114     source_map: Lrc<SourceMap>,
115     pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
116     /// Contains the spans of block expressions that could have been incomplete based on the
117     /// operation token that followed it, but that the parser cannot identify without further
118     /// analysis.
119     pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
120     pub injected_crate_name: Once<Symbol>,
121     pub gated_spans: GatedSpans,
122     /// The parser has reached `Eof` due to an unclosed brace. Used to silence unnecessary errors.
123     pub reached_eof: Lock<bool>,
124 }
125
126 impl ParseSess {
127     pub fn new(file_path_mapping: FilePathMapping) -> Self {
128         let cm = Lrc::new(SourceMap::new(file_path_mapping));
129         let handler = Handler::with_tty_emitter(ColorConfig::Auto, true, None, Some(cm.clone()));
130         ParseSess::with_span_handler(handler, cm)
131     }
132
133     pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self {
134         Self {
135             span_diagnostic: handler,
136             unstable_features: UnstableFeatures::from_environment(),
137             config: FxHashSet::default(),
138             edition: ExpnId::root().expn_data().edition,
139             missing_fragment_specifiers: Lock::new(FxHashSet::default()),
140             raw_identifier_spans: Lock::new(Vec::new()),
141             included_mod_stack: Lock::new(vec![]),
142             source_map,
143             buffered_lints: Lock::new(vec![]),
144             ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
145             injected_crate_name: Once::new(),
146             gated_spans: GatedSpans::default(),
147             reached_eof: Lock::new(false),
148         }
149     }
150
151     pub fn with_silent_emitter() -> Self {
152         let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
153         let handler = Handler::with_emitter(false, None, Box::new(SilentEmitter));
154         ParseSess::with_span_handler(handler, cm)
155     }
156
157     #[inline]
158     pub fn source_map(&self) -> &SourceMap {
159         &self.source_map
160     }
161
162     pub fn buffer_lint(
163         &self,
164         lint: &'static Lint,
165         span: impl Into<MultiSpan>,
166         node_id: NodeId,
167         msg: &str,
168     ) {
169         self.buffered_lints.with_lock(|buffered_lints| {
170             buffered_lints.push(BufferedEarlyLint {
171                 span: span.into(),
172                 node_id,
173                 msg: msg.into(),
174                 lint_id: LintId::of(lint),
175                 diagnostic: BuiltinLintDiagnostics::Normal,
176             });
177         });
178     }
179
180     /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
181     /// parser to continue parsing the following operation as part of the same expression.
182     pub fn expr_parentheses_needed(
183         &self,
184         err: &mut DiagnosticBuilder<'_>,
185         span: Span,
186         alt_snippet: Option<String>,
187     ) {
188         if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
189             err.span_suggestion(
190                 span,
191                 "parentheses are required to parse this as an expression",
192                 format!("({})", snippet),
193                 Applicability::MachineApplicable,
194             );
195         }
196     }
197 }