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