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