Skip to main content

rustc_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
4use std::sync::Arc;
5
6use rustc_ast::ast;
7use rustc_ast::attr::AttrIdGenerator;
8use rustc_ast::node_id::NodeId;
9use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
10use rustc_data_structures::sync::{AppendOnlyVec, DynSend, DynSync, Lock};
11use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
12use rustc_errors::emitter::{EmitterWithNote, stderr_destination};
13use rustc_errors::{
14    BufferedEarlyLint, ColorConfig, DecorateDiagCompat, Diag, DiagCtxt, DiagCtxtHandle, Level,
15    MultiSpan,
16};
17use rustc_span::edition::Edition;
18use rustc_span::hygiene::ExpnId;
19use rustc_span::source_map::{FilePathMapping, SourceMap};
20use rustc_span::{Span, Symbol};
21
22use crate::Session;
23use crate::lint::{Lint, LintId};
24
25/// Collected spans during parsing for places where a certain feature was
26/// used and should be feature gated accordingly in `check_crate` in `rustc_ast_passes`.
27#[derive(#[automatically_derived]impl ::core::default::Default for GatedSpans {
    #[inline]
    fn default() -> Self {
        GatedSpans { spans: ::core::default::Default::default() }
    }
}Default)]
28pub struct GatedSpans {
29    pub spans: Lock<FxHashMap<Symbol, Vec<Span>>>,
30}
31
32impl GatedSpans {
33    /// Feature gate the given `span` under the given `feature`
34    /// which is same `Symbol` used in `unstable.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        if true {
    {
        match (&span, &removed_span) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(span, removed_span);
46    }
47
48    /// Prepend the given set of `spans` onto the set in `self`.
49    pub fn merge(&self, mut spans: FxHashMap<Symbol, Vec<Span>>) {
50        let mut inner = self.spans.borrow_mut();
51        // The entries will be moved to another map so the drain order does not
52        // matter.
53        #[allow(rustc::potential_query_instability)]
54        for (gate, mut gate_spans) in inner.drain() {
55            spans.entry(gate).or_default().append(&mut gate_spans);
56        }
57        *inner = spans;
58    }
59}
60
61#[derive(#[automatically_derived]impl ::core::default::Default for SymbolGallery {
    #[inline]
    fn default() -> Self {
        SymbolGallery { symbols: ::core::default::Default::default() }
    }
}Default)]
62pub struct SymbolGallery {
63    /// All symbols occurred and their first occurrence span.
64    pub symbols: Lock<FxIndexMap<Symbol, Span>>,
65}
66
67impl SymbolGallery {
68    /// Insert a symbol and its span into symbol gallery.
69    /// If the symbol has occurred before, ignore the new occurrence.
70    pub fn insert(&self, symbol: Symbol, span: Span) {
71        self.symbols.lock().entry(symbol).or_insert(span);
72    }
73}
74
75/// Info about a parsing session.
76pub struct ParseSess {
77    dcx: DiagCtxt,
78    pub edition: Edition,
79    /// Places where raw identifiers were used. This is used to avoid complaining about idents
80    /// clashing with keywords in new editions.
81    pub raw_identifier_spans: AppendOnlyVec<Span>,
82    /// Places where identifiers that contain invalid Unicode codepoints but that look like they
83    /// should be. Useful to avoid bad tokenization when encountering emoji. We group them to
84    /// provide a single error per unique incorrect identifier.
85    pub bad_unicode_identifiers: Lock<FxIndexMap<Symbol, Vec<Span>>>,
86    source_map: Arc<SourceMap>,
87    /// Lints that are emitted before the lint infrastructure is working, these will be taken
88    /// during early linting.
89    /// This is an `Option` because it will be `None` after the buffered lints are emptied, to ensure that
90    /// nothing uses `buffered_lints` after.
91    pub buffered_lints: Lock<Option<Vec<BufferedEarlyLint>>>,
92    /// Places where *complete* stmt exprs are followed by a token that would've been interpreted as
93    /// a binary operator instead of the start of a following stmt or pat *if we weren't in a stmt
94    /// expr context*.
95    ///
96    /// **For error recovery and diagnostic purposes only!**
97    ///
98    /// Maps from the [`start_point`] of the bin op lookalike to the span of the complete stmt expr
99    /// (e.g., block) that could be interpreted as its left operand.
100    ///
101    /// Examples: Given `fn f() { { dbg!(); } *ptr = 0; }` it maps the span of `*` to the span of
102    /// `{ dbg!(); }`; given `fn f() { { true } && panic!(); }` it maps the span of the first `&` to
103    /// the span of `{ true }`.
104    ///
105    /// [`start_point`]: SourceMap::start_point
106    pub complete_stmt_exprs_before_bin_op_lookalike: Lock<FxIndexMap<Span, Span>>,
107    pub gated_spans: GatedSpans,
108    pub symbol_gallery: SymbolGallery,
109    /// Used to generate new `AttrId`s. Every `AttrId` is unique.
110    pub attr_id_generator: AttrIdGenerator,
111}
112
113impl ParseSess {
114    /// Used for testing.
115    pub fn new() -> Self {
116        let sm = Arc::new(SourceMap::new(FilePathMapping::empty()));
117        let emitter = Box::new(
118            AnnotateSnippetEmitter::new(stderr_destination(ColorConfig::Auto))
119                .sm(Some(Arc::clone(&sm))),
120        );
121        let dcx = DiagCtxt::new(emitter);
122        ParseSess::with_dcx(dcx, sm)
123    }
124
125    pub fn with_dcx(dcx: DiagCtxt, source_map: Arc<SourceMap>) -> Self {
126        Self {
127            dcx,
128            edition: ExpnId::root().expn_data().edition,
129            raw_identifier_spans: Default::default(),
130            bad_unicode_identifiers: Lock::new(Default::default()),
131            source_map,
132            buffered_lints: Lock::new(Some(::alloc::vec::Vec::new()vec![])),
133            complete_stmt_exprs_before_bin_op_lookalike: Lock::new(Default::default()),
134            gated_spans: GatedSpans::default(),
135            symbol_gallery: SymbolGallery::default(),
136            attr_id_generator: AttrIdGenerator::new(),
137        }
138    }
139
140    pub fn emitter_with_note(note: String) -> Self {
141        let sm = Arc::new(SourceMap::new(FilePathMapping::empty()));
142        let emitter = Box::new(AnnotateSnippetEmitter::new(stderr_destination(ColorConfig::Auto)));
143        let dcx = DiagCtxt::new(Box::new(EmitterWithNote { emitter, note }));
144        ParseSess::with_dcx(dcx, sm)
145    }
146
147    #[inline]
148    pub fn source_map(&self) -> &SourceMap {
149        &self.source_map
150    }
151
152    pub fn clone_source_map(&self) -> Arc<SourceMap> {
153        Arc::clone(&self.source_map)
154    }
155
156    pub fn buffer_lint(
157        &self,
158        lint: &'static Lint,
159        span: impl Into<MultiSpan>,
160        node_id: NodeId,
161        diagnostic: impl Into<DecorateDiagCompat>,
162    ) {
163        self.opt_span_buffer_lint(lint, Some(span.into()), node_id, diagnostic.into())
164    }
165
166    /// Buffer a crate-level lint. This is used for lints that are associated with command-line
167    /// arguments and dependency structure.
168    pub fn buffer_crate_lint(
169        &self,
170        lint: &'static Lint,
171        diagnostic: impl Into<DecorateDiagCompat>,
172    ) {
173        self.opt_span_buffer_lint(lint, None, ast::CRATE_NODE_ID, diagnostic.into())
174    }
175
176    pub fn dyn_buffer_lint<
177        F: for<'a> FnOnce(DiagCtxtHandle<'a>, Level) -> Diag<'a> + DynSync + DynSend + 'static,
178    >(
179        &self,
180        lint: &'static Lint,
181        span: impl Into<MultiSpan>,
182        node_id: NodeId,
183        callback: F,
184    ) {
185        self.opt_span_buffer_lint(
186            lint,
187            Some(span.into()),
188            node_id,
189            DecorateDiagCompat(Box::new(|dcx, level, _| callback(dcx, level))),
190        )
191    }
192
193    pub fn dyn_buffer_lint_sess<
194        F: for<'a> FnOnce(DiagCtxtHandle<'a>, Level, &Session) -> Diag<'a>
195            + DynSync
196            + DynSend
197            + 'static,
198    >(
199        &self,
200        lint: &'static Lint,
201        span: impl Into<MultiSpan>,
202        node_id: NodeId,
203        callback: F,
204    ) {
205        self.opt_span_buffer_lint(
206            lint,
207            Some(span.into()),
208            node_id,
209            DecorateDiagCompat(Box::new(|dcx, level, sess| {
210                let sess = sess.downcast_ref::<Session>().expect("expected a `Session`");
211                callback(dcx, level, sess)
212            })),
213        )
214    }
215
216    pub(crate) fn opt_span_buffer_lint(
217        &self,
218        lint: &'static Lint,
219        span: Option<MultiSpan>,
220        node_id: NodeId,
221        diagnostic: DecorateDiagCompat,
222    ) {
223        self.buffered_lints.with_lock(|buffered_lints| {
224            buffered_lints
225                .as_mut()
226                .expect("Buffered lints are not stolen yet")
227                .push(BufferedEarlyLint { span, node_id, lint_id: LintId::of(lint), diagnostic });
228        });
229    }
230
231    pub fn dcx(&self) -> DiagCtxtHandle<'_> {
232        self.dcx.handle()
233    }
234}