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