Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
syntax: extract sess.rs for ParseSess
  • Loading branch information
Centril committed Oct 15, 2019
commit 52d0e86b9a46ab74f76c0bc7b2b9df3d32fcfbc1
125 changes: 7 additions & 118 deletions src/libsyntax/parse/mod.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,19 @@
//! The main parser interface.

use crate::ast::{self, CrateConfig, NodeId};
use crate::early_buffered_lints::{BufferedEarlyLint, BufferedEarlyLintId};
use crate::source_map::{SourceMap, FilePathMapping};
use crate::feature_gate::UnstableFeatures;
use crate::ast;
use crate::parse::parser::{Parser, emit_unclosed_delims};
use crate::parse::token::{Nonterminal, TokenKind};
use crate::tokenstream::{self, TokenStream, TokenTree};
use crate::print::pprust;
use crate::symbol::Symbol;

use errors::{Applicability, FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
use rustc_data_structures::fx::{FxHashSet, FxHashMap};
use errors::{FatalError, Level, Diagnostic, DiagnosticBuilder};
#[cfg(target_arch = "x86_64")]
use rustc_data_structures::static_assert_size;
use rustc_data_structures::sync::{Lrc, Lock, Once};
use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
use syntax_pos::edition::Edition;
use syntax_pos::hygiene::ExpnId;
use rustc_data_structures::sync::Lrc;
use syntax_pos::{Span, SourceFile, FileName};

use std::borrow::Cow;
use std::path::{Path, PathBuf};
use std::path::Path;
use std::str;

use log::info;
Expand All @@ -33,6 +26,8 @@ pub mod parser;
pub mod attr;
pub mod lexer;
pub mod token;
mod sess;
pub use sess::ParseSess;

crate mod classify;
crate mod diagnostics;
Expand All @@ -46,112 +41,6 @@ pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
#[cfg(target_arch = "x86_64")]
static_assert_size!(PResult<'_, bool>, 16);

/// Collected spans during parsing for places where a certain feature was
/// used and should be feature gated accordingly in `check_crate`.
#[derive(Default)]
pub struct GatedSpans {
/// Spans collected for gating `let_chains`, e.g. `if a && let b = c {}`.
pub let_chains: Lock<Vec<Span>>,
/// Spans collected for gating `async_closure`, e.g. `async || ..`.
pub async_closure: Lock<Vec<Span>>,
/// Spans collected for gating `yield e?` expressions (`generators` gate).
pub yields: Lock<Vec<Span>>,
/// Spans collected for gating `or_patterns`, e.g. `Some(Foo | Bar)`.
pub or_patterns: Lock<Vec<Span>>,
/// Spans collected for gating `const_extern_fn`, e.g. `const extern fn foo`.
pub const_extern_fn: Lock<Vec<Span>>,
}

/// Info about a parsing session.
pub struct ParseSess {
pub span_diagnostic: Handler,
pub unstable_features: UnstableFeatures,
pub config: CrateConfig,
pub edition: Edition,
pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
/// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
pub raw_identifier_spans: Lock<Vec<Span>>,
/// Used to determine and report recursive module inclusions.
included_mod_stack: Lock<Vec<PathBuf>>,
source_map: Lrc<SourceMap>,
pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
/// Contains the spans of block expressions that could have been incomplete based on the
/// operation token that followed it, but that the parser cannot identify without further
/// analysis.
pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
pub injected_crate_name: Once<Symbol>,
pub gated_spans: GatedSpans,
}

impl ParseSess {
pub fn new(file_path_mapping: FilePathMapping) -> Self {
let cm = Lrc::new(SourceMap::new(file_path_mapping));
let handler = Handler::with_tty_emitter(
ColorConfig::Auto,
true,
None,
Some(cm.clone()),
);
ParseSess::with_span_handler(handler, cm)
}

pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self {
Self {
span_diagnostic: handler,
unstable_features: UnstableFeatures::from_environment(),
config: FxHashSet::default(),
edition: ExpnId::root().expn_data().edition,
missing_fragment_specifiers: Lock::new(FxHashSet::default()),
raw_identifier_spans: Lock::new(Vec::new()),
included_mod_stack: Lock::new(vec![]),
source_map,
buffered_lints: Lock::new(vec![]),
ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
injected_crate_name: Once::new(),
gated_spans: GatedSpans::default(),
}
}

#[inline]
pub fn source_map(&self) -> &SourceMap {
&self.source_map
}

pub fn buffer_lint<S: Into<MultiSpan>>(&self,
lint_id: BufferedEarlyLintId,
span: S,
id: NodeId,
msg: &str,
) {
self.buffered_lints.with_lock(|buffered_lints| {
buffered_lints.push(BufferedEarlyLint{
span: span.into(),
id,
msg: msg.into(),
lint_id,
});
});
}

/// Extend an error with a suggestion to wrap an expression with parentheses to allow the
/// parser to continue parsing the following operation as part of the same expression.
pub fn expr_parentheses_needed(
&self,
err: &mut DiagnosticBuilder<'_>,
span: Span,
alt_snippet: Option<String>,
) {
if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
err.span_suggestion(
span,
"parentheses are required to parse this as an expression",
format!("({})", snippet),
Applicability::MachineApplicable,
);
}
}
}

#[derive(Clone)]
pub struct Directory<'a> {
pub path: Cow<'a, Path>,
Expand Down
2 changes: 1 addition & 1 deletion src/libsyntax/parse/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1366,7 +1366,7 @@ impl<'a> Parser<'a> {
],
Applicability::MaybeIncorrect,
).span_suggestion(
self.sess.source_map.next_point(self.prev_span),
self.sess.source_map().next_point(self.prev_span),
"add a semicolon",
';'.to_string(),
Applicability::MaybeIncorrect,
Expand Down
124 changes: 124 additions & 0 deletions src/libsyntax/parse/sess.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
//! Contains `ParseSess` which holds state living beyond what one `Parser` might.
//! It also serves as an input to the parser itself.

use crate::ast::{CrateConfig, NodeId};
use crate::early_buffered_lints::{BufferedEarlyLint, BufferedEarlyLintId};
use crate::source_map::{SourceMap, FilePathMapping};
use crate::feature_gate::UnstableFeatures;

use errors::{Applicability, Handler, ColorConfig, DiagnosticBuilder};
use rustc_data_structures::fx::{FxHashSet, FxHashMap};
use rustc_data_structures::sync::{Lrc, Lock, Once};
use syntax_pos::{Symbol, Span, MultiSpan};
use syntax_pos::edition::Edition;
use syntax_pos::hygiene::ExpnId;

use std::path::PathBuf;
use std::str;

/// Collected spans during parsing for places where a certain feature was
/// used and should be feature gated accordingly in `check_crate`.
#[derive(Default)]
crate struct GatedSpans {
/// Spans collected for gating `let_chains`, e.g. `if a && let b = c {}`.
crate let_chains: Lock<Vec<Span>>,
/// Spans collected for gating `async_closure`, e.g. `async || ..`.
crate async_closure: Lock<Vec<Span>>,
/// Spans collected for gating `yield e?` expressions (`generators` gate).
crate yields: Lock<Vec<Span>>,
/// Spans collected for gating `or_patterns`, e.g. `Some(Foo | Bar)`.
crate or_patterns: Lock<Vec<Span>>,
/// Spans collected for gating `const_extern_fn`, e.g. `const extern fn foo`.
crate const_extern_fn: Lock<Vec<Span>>,
}

/// Info about a parsing session.
pub struct ParseSess {
pub span_diagnostic: Handler,
crate unstable_features: UnstableFeatures,
pub config: CrateConfig,
pub edition: Edition,
pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
/// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
pub raw_identifier_spans: Lock<Vec<Span>>,
/// Used to determine and report recursive module inclusions.
pub(super) included_mod_stack: Lock<Vec<PathBuf>>,
source_map: Lrc<SourceMap>,
pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
/// Contains the spans of block expressions that could have been incomplete based on the
/// operation token that followed it, but that the parser cannot identify without further
/// analysis.
pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
pub injected_crate_name: Once<Symbol>,
crate gated_spans: GatedSpans,
}

impl ParseSess {
pub fn new(file_path_mapping: FilePathMapping) -> Self {
let cm = Lrc::new(SourceMap::new(file_path_mapping));
let handler = Handler::with_tty_emitter(
ColorConfig::Auto,
true,
None,
Some(cm.clone()),
);
ParseSess::with_span_handler(handler, cm)
}

pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self {
Self {
span_diagnostic: handler,
unstable_features: UnstableFeatures::from_environment(),
config: FxHashSet::default(),
edition: ExpnId::root().expn_data().edition,
missing_fragment_specifiers: Lock::new(FxHashSet::default()),
raw_identifier_spans: Lock::new(Vec::new()),
included_mod_stack: Lock::new(vec![]),
source_map,
buffered_lints: Lock::new(vec![]),
ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
injected_crate_name: Once::new(),
gated_spans: GatedSpans::default(),
}
}

#[inline]
pub fn source_map(&self) -> &SourceMap {
&self.source_map
}

pub fn buffer_lint(
&self,
lint_id: BufferedEarlyLintId,
span: impl Into<MultiSpan>,
id: NodeId,
msg: &str,
) {
self.buffered_lints.with_lock(|buffered_lints| {
buffered_lints.push(BufferedEarlyLint{
span: span.into(),
id,
msg: msg.into(),
lint_id,
});
});
}

/// Extend an error with a suggestion to wrap an expression with parentheses to allow the
/// parser to continue parsing the following operation as part of the same expression.
pub fn expr_parentheses_needed(
&self,
err: &mut DiagnosticBuilder<'_>,
span: Span,
alt_snippet: Option<String>,
) {
if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
err.span_suggestion(
span,
"parentheses are required to parse this as an expression",
format!("({})", snippet),
Applicability::MachineApplicable,
);
}
}
}