]> git.lizzy.rs Git - rust.git/blob - src/librustc_session/parse.rs
Rollup merge of #66878 - Mark-Simulacrum:sess-decouple, 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::node_id::NodeId;
5 use crate::lint::BufferedEarlyLint;
6
7 use rustc_errors::{Applicability, emitter::SilentEmitter, Handler, ColorConfig, DiagnosticBuilder};
8 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
9 use rustc_data_structures::sync::{Lrc, Lock, Once};
10 use rustc_feature::UnstableFeatures;
11 use syntax_pos::{Symbol, Span, MultiSpan};
12 use syntax_pos::edition::Edition;
13 use syntax_pos::hygiene::ExpnId;
14 use syntax_pos::source_map::{SourceMap, FilePathMapping};
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
35             .borrow_mut()
36             .entry(feature)
37             .or_default()
38             .push(span);
39     }
40
41     /// Ungate the last span under the given `feature`.
42     /// Panics if the given `span` wasn't the last one.
43     ///
44     /// Using this is discouraged unless you have a really good reason to.
45     pub fn ungate_last(&self, feature: Symbol, span: Span) {
46         let removed_span = self.spans
47             .borrow_mut()
48             .entry(feature)
49             .or_default()
50             .pop()
51             .unwrap();
52         debug_assert_eq!(span, removed_span);
53     }
54
55     /// Is the provided `feature` gate ungated currently?
56     ///
57     /// Using this is discouraged unless you have a really good reason to.
58     pub fn is_ungated(&self, feature: Symbol) -> bool {
59         self.spans
60             .borrow()
61             .get(&feature)
62             .map_or(true, |spans| spans.is_empty())
63     }
64
65     /// Prepend the given set of `spans` onto the set in `self`.
66     pub fn merge(&self, mut spans: FxHashMap<Symbol, Vec<Span>>) {
67         let mut inner = self.spans.borrow_mut();
68         for (gate, mut gate_spans) in inner.drain() {
69             spans.entry(gate).or_default().append(&mut gate_spans);
70         }
71         *inner = spans;
72     }
73 }
74
75 /// Info about a parsing session.
76 pub struct ParseSess {
77     pub span_diagnostic: Handler,
78     pub unstable_features: UnstableFeatures,
79     pub config: CrateConfig,
80     pub edition: Edition,
81     pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
82     /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
83     pub raw_identifier_spans: Lock<Vec<Span>>,
84     /// Used to determine and report recursive module inclusions.
85     pub included_mod_stack: Lock<Vec<PathBuf>>,
86     source_map: Lrc<SourceMap>,
87     pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
88     /// Contains the spans of block expressions that could have been incomplete based on the
89     /// operation token that followed it, but that the parser cannot identify without further
90     /// analysis.
91     pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
92     pub injected_crate_name: Once<Symbol>,
93     pub gated_spans: GatedSpans,
94     /// The parser has reached `Eof` due to an unclosed brace. Used to silence unnecessary errors.
95     pub reached_eof: Lock<bool>,
96 }
97
98 impl ParseSess {
99     pub fn new(file_path_mapping: FilePathMapping) -> Self {
100         let cm = Lrc::new(SourceMap::new(file_path_mapping));
101         let handler = Handler::with_tty_emitter(
102             ColorConfig::Auto,
103             true,
104             None,
105             Some(cm.clone()),
106         );
107         ParseSess::with_span_handler(handler, cm)
108     }
109
110     pub fn with_span_handler(
111         handler: Handler,
112         source_map: Lrc<SourceMap>,
113     ) -> Self {
114         Self {
115             span_diagnostic: handler,
116             unstable_features: UnstableFeatures::from_environment(),
117             config: FxHashSet::default(),
118             edition: ExpnId::root().expn_data().edition,
119             missing_fragment_specifiers: Lock::new(FxHashSet::default()),
120             raw_identifier_spans: Lock::new(Vec::new()),
121             included_mod_stack: Lock::new(vec![]),
122             source_map,
123             buffered_lints: Lock::new(vec![]),
124             ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
125             injected_crate_name: Once::new(),
126             gated_spans: GatedSpans::default(),
127             reached_eof: Lock::new(false),
128         }
129     }
130
131     pub fn with_silent_emitter() -> Self {
132         let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
133         let handler = Handler::with_emitter(false, None, Box::new(SilentEmitter));
134         ParseSess::with_span_handler(handler, cm)
135     }
136
137     #[inline]
138     pub fn source_map(&self) -> &SourceMap {
139         &self.source_map
140     }
141
142     pub fn buffer_lint(
143         &self,
144         lint_id: &'static crate::lint::Lint,
145         span: impl Into<MultiSpan>,
146         id: NodeId,
147         msg: &str,
148     ) {
149         self.buffered_lints.with_lock(|buffered_lints| {
150             buffered_lints.push(BufferedEarlyLint{
151                 span: span.into(),
152                 id,
153                 msg: msg.into(),
154                 lint_id,
155             });
156         });
157     }
158
159     /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
160     /// parser to continue parsing the following operation as part of the same expression.
161     pub fn expr_parentheses_needed(
162         &self,
163         err: &mut DiagnosticBuilder<'_>,
164         span: Span,
165         alt_snippet: Option<String>,
166     ) {
167         if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
168             err.span_suggestion(
169                 span,
170                 "parentheses are required to parse this as an expression",
171                 format!("({})", snippet),
172                 Applicability::MachineApplicable,
173             );
174         }
175     }
176 }