1 //! Contains `ParseSess` which holds state living beyond what one `Parser` might.
2 //! It also serves as an input to the parser itself.
4 use crate::lint::BufferedEarlyLint;
5 use crate::node_id::NodeId;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_data_structures::sync::{Lock, Lrc, Once};
10 emitter::SilentEmitter, Applicability, ColorConfig, DiagnosticBuilder, Handler,
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};
18 use std::path::PathBuf;
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>)>;
25 /// Collected spans during parsing for places where a certain feature was
26 /// used and should be feature gated accordingly in `check_crate`.
28 pub struct GatedSpans {
29 pub spans: Lock<FxHashMap<Symbol, Vec<Span>>>,
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);
39 /// Ungate the last span under the given `feature`.
40 /// Panics if the given `span` wasn't the last one.
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);
48 /// Is the provided `feature` gate ungated currently?
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())
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);
65 /// Info about a parsing session.
66 pub struct ParseSess {
67 pub span_diagnostic: Handler,
68 pub unstable_features: UnstableFeatures,
69 pub config: CrateConfig,
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
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>,
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)
95 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> 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![]),
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),
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)
120 pub fn source_map(&self) -> &SourceMap {
126 lint_id: &'static crate::lint::Lint,
127 span: impl Into<MultiSpan>,
131 self.buffered_lints.with_lock(|buffered_lints| {
132 buffered_lints.push(BufferedEarlyLint {
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(
145 err: &mut DiagnosticBuilder<'_>,
147 alt_snippet: Option<String>,
149 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
152 "parentheses are required to parse this as an expression",
153 format!("({})", snippet),
154 Applicability::MachineApplicable,