]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/sess.rs
Auto merge of #64878 - XAMPPRocky:relnotes-1.39.0, r=XAMPPRocky
[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, 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 crate struct GatedSpans {
23     /// Spans collected for gating `let_chains`, e.g. `if a && let b = c {}`.
24     crate let_chains: Lock<Vec<Span>>,
25     /// Spans collected for gating `async_closure`, e.g. `async || ..`.
26     crate async_closure: Lock<Vec<Span>>,
27     /// Spans collected for gating `yield e?` expressions (`generators` gate).
28     crate yields: Lock<Vec<Span>>,
29     /// Spans collected for gating `or_patterns`, e.g. `Some(Foo | Bar)`.
30     crate or_patterns: Lock<Vec<Span>>,
31     /// Spans collected for gating `const_extern_fn`, e.g. `const extern fn foo`.
32     crate const_extern_fn: Lock<Vec<Span>>,
33     /// Spans collected for gating `trait_alias`, e.g. `trait Foo = Ord + Eq;`.
34     pub trait_alias: Lock<Vec<Span>>,
35     /// Spans collected for gating `associated_type_bounds`, e.g. `Iterator<Item: Ord>`.
36     pub associated_type_bounds: Lock<Vec<Span>>,
37     /// Spans collected for gating `crate_visibility_modifier`, e.g. `crate fn`.
38     pub crate_visibility_modifier: Lock<Vec<Span>>,
39     /// Spans collected for gating `const_generics`, e.g. `const N: usize`.
40     pub const_generics: Lock<Vec<Span>>,
41     /// Spans collected for gating `decl_macro`, e.g. `macro m() {}`.
42     pub decl_macro: Lock<Vec<Span>>,
43     /// Spans collected for gating `box_patterns`, e.g. `box 0`.
44     pub box_patterns: Lock<Vec<Span>>,
45     /// Spans collected for gating `exclusive_range_pattern`, e.g. `0..2`.
46     pub exclusive_range_pattern: Lock<Vec<Span>>,
47     /// Spans collected for gating `try_blocks`, e.g. `try { a? + b? }`.
48     pub try_blocks: Lock<Vec<Span>>,
49     /// Spans collected for gating `label_break_value`, e.g. `'label: { ... }`.
50     pub label_break_value: Lock<Vec<Span>>,
51     /// Spans collected for gating `box_syntax`, e.g. `box $expr`.
52     pub box_syntax: Lock<Vec<Span>>,
53     /// Spans collected for gating `type_ascription`, e.g. `42: usize`.
54     pub type_ascription: Lock<Vec<Span>>,
55 }
56
57 /// Info about a parsing session.
58 pub struct ParseSess {
59     pub span_diagnostic: Handler,
60     crate unstable_features: UnstableFeatures,
61     pub config: CrateConfig,
62     pub edition: Edition,
63     pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
64     /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
65     pub raw_identifier_spans: Lock<Vec<Span>>,
66     /// Used to determine and report recursive module inclusions.
67     pub(super) included_mod_stack: Lock<Vec<PathBuf>>,
68     source_map: Lrc<SourceMap>,
69     pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
70     /// Contains the spans of block expressions that could have been incomplete based on the
71     /// operation token that followed it, but that the parser cannot identify without further
72     /// analysis.
73     pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
74     pub injected_crate_name: Once<Symbol>,
75     crate gated_spans: GatedSpans,
76     /// The parser has reached `Eof` due to an unclosed brace. Used to silence unnecessary errors.
77     pub reached_eof: Lock<bool>,
78 }
79
80 impl ParseSess {
81     pub fn new(file_path_mapping: FilePathMapping) -> Self {
82         let cm = Lrc::new(SourceMap::new(file_path_mapping));
83         let handler = Handler::with_tty_emitter(
84             ColorConfig::Auto,
85             true,
86             None,
87             Some(cm.clone()),
88         );
89         ParseSess::with_span_handler(handler, cm)
90     }
91
92     pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self {
93         Self {
94             span_diagnostic: handler,
95             unstable_features: UnstableFeatures::from_environment(),
96             config: FxHashSet::default(),
97             edition: ExpnId::root().expn_data().edition,
98             missing_fragment_specifiers: Lock::new(FxHashSet::default()),
99             raw_identifier_spans: Lock::new(Vec::new()),
100             included_mod_stack: Lock::new(vec![]),
101             source_map,
102             buffered_lints: Lock::new(vec![]),
103             ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
104             injected_crate_name: Once::new(),
105             gated_spans: GatedSpans::default(),
106             reached_eof: Lock::new(false),
107         }
108     }
109
110     #[inline]
111     pub fn source_map(&self) -> &SourceMap {
112         &self.source_map
113     }
114
115     pub fn buffer_lint(
116         &self,
117         lint_id: BufferedEarlyLintId,
118         span: impl Into<MultiSpan>,
119         id: NodeId,
120         msg: &str,
121     ) {
122         self.buffered_lints.with_lock(|buffered_lints| {
123             buffered_lints.push(BufferedEarlyLint{
124                 span: span.into(),
125                 id,
126                 msg: msg.into(),
127                 lint_id,
128             });
129         });
130     }
131
132     /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
133     /// parser to continue parsing the following operation as part of the same expression.
134     pub fn expr_parentheses_needed(
135         &self,
136         err: &mut DiagnosticBuilder<'_>,
137         span: Span,
138         alt_snippet: Option<String>,
139     ) {
140         if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
141             err.span_suggestion(
142                 span,
143                 "parentheses are required to parse this as an expression",
144                 format!("({})", snippet),
145                 Applicability::MachineApplicable,
146             );
147         }
148     }
149 }