1
Fork 0

Move edition outside the hygiene lock and avoid accessing it

This commit is contained in:
John Kåre Alsaker 2019-04-06 00:15:49 +02:00
parent 50a0defd5a
commit a1f2dceaeb
39 changed files with 155 additions and 139 deletions

View file

@ -1853,7 +1853,7 @@ pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
// Convert strings provided as --cfg [cfgspec] into a crate_cfg // Convert strings provided as --cfg [cfgspec] into a crate_cfg
pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> { pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
syntax::with_globals(move || { syntax::with_default_globals(move || {
let cfg = cfgspecs.into_iter().map(|s| { let cfg = cfgspecs.into_iter().map(|s| {
let sess = parse::ParseSess::new(FilePathMapping::empty()); let sess = parse::ParseSess::new(FilePathMapping::empty());
let filename = FileName::cfg_spec_source_code(&s); let filename = FileName::cfg_spec_source_code(&s);
@ -2735,7 +2735,7 @@ mod tests {
// When the user supplies --test we should implicitly supply --cfg test // When the user supplies --test we should implicitly supply --cfg test
#[test] #[test]
fn test_switch_implies_cfg_test() { fn test_switch_implies_cfg_test() {
syntax::with_globals(|| { syntax::with_default_globals(|| {
let matches = &match optgroups().parse(&["--test".to_string()]) { let matches = &match optgroups().parse(&["--test".to_string()]) {
Ok(m) => m, Ok(m) => m,
Err(f) => panic!("test_switch_implies_cfg_test: {}", f), Err(f) => panic!("test_switch_implies_cfg_test: {}", f),
@ -2753,7 +2753,7 @@ mod tests {
#[test] #[test]
fn test_switch_implies_cfg_test_unless_cfg_test() { fn test_switch_implies_cfg_test_unless_cfg_test() {
use syntax::symbol::sym; use syntax::symbol::sym;
syntax::with_globals(|| { syntax::with_default_globals(|| {
let matches = &match optgroups().parse(&["--test".to_string(), let matches = &match optgroups().parse(&["--test".to_string(),
"--cfg=test".to_string()]) { "--cfg=test".to_string()]) {
Ok(m) => m, Ok(m) => m,
@ -2771,7 +2771,7 @@ mod tests {
#[test] #[test]
fn test_can_print_warnings() { fn test_can_print_warnings() {
syntax::with_globals(|| { syntax::with_default_globals(|| {
let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap(); let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
let registry = errors::registry::Registry::new(&[]); let registry = errors::registry::Registry::new(&[]);
let (sessopts, _) = build_session_options_and_crate_config(&matches); let (sessopts, _) = build_session_options_and_crate_config(&matches);
@ -2779,7 +2779,7 @@ mod tests {
assert!(!sess.diagnostic().flags.can_emit_warnings); assert!(!sess.diagnostic().flags.can_emit_warnings);
}); });
syntax::with_globals(|| { syntax::with_default_globals(|| {
let matches = optgroups() let matches = optgroups()
.parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()]) .parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()])
.unwrap(); .unwrap();
@ -2789,7 +2789,7 @@ mod tests {
assert!(sess.diagnostic().flags.can_emit_warnings); assert!(sess.diagnostic().flags.can_emit_warnings);
}); });
syntax::with_globals(|| { syntax::with_default_globals(|| {
let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap(); let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
let registry = errors::registry::Registry::new(&[]); let registry = errors::registry::Registry::new(&[]);
let (sessopts, _) = build_session_options_and_crate_config(&matches); let (sessopts, _) = build_session_options_and_crate_config(&matches);

View file

@ -14,7 +14,7 @@ use syntax::{
base::{ExtCtxt, Resolver}, base::{ExtCtxt, Resolver},
build::AstBuilder, build::AstBuilder,
expand::ExpansionConfig, expand::ExpansionConfig,
hygiene::{self, Mark, SyntaxContext}, hygiene::{Mark, SyntaxContext},
}, },
mut_visit::{self, MutVisitor}, mut_visit::{self, MutVisitor},
parse::ParseSess, parse::ParseSess,
@ -96,7 +96,7 @@ impl MutVisitor for ExpandAllocatorDirectives<'_> {
].into()), ].into()),
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
edition: hygiene::default_edition(), edition: self.sess.edition,
}); });
// Tie the span to the macro expansion info we just created // Tie the span to the macro expansion info we just created

View file

@ -18,6 +18,7 @@ use std::result;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use syntax; use syntax;
use syntax::source_map::{FileLoader, SourceMap}; use syntax::source_map::{FileLoader, SourceMap};
use syntax_pos::edition;
pub type Result<T> = result::Result<T, ErrorReported>; pub type Result<T> = result::Result<T, ErrorReported>;
@ -135,6 +136,7 @@ where
{ {
let stderr = config.stderr.take(); let stderr = config.stderr.take();
util::spawn_thread_pool( util::spawn_thread_pool(
config.opts.edition,
config.opts.debugging_opts.threads, config.opts.debugging_opts.threads,
&stderr, &stderr,
|| run_compiler_in_existing_thread_pool(config, f), || run_compiler_in_existing_thread_pool(config, f),
@ -146,5 +148,5 @@ where
F: FnOnce() -> R + Send, F: FnOnce() -> R + Send,
R: Send, R: Send,
{ {
util::spawn_thread_pool(None, &None, f) util::spawn_thread_pool(edition::DEFAULT_EDITION, None, &None, f)
} }

View file

@ -48,7 +48,7 @@ use syntax::util::node_count::NodeCounter;
use syntax::util::lev_distance::find_best_match_for_name; use syntax::util::lev_distance::find_best_match_for_name;
use syntax::symbol::Symbol; use syntax::symbol::Symbol;
use syntax::feature_gate::AttributeType; use syntax::feature_gate::AttributeType;
use syntax_pos::{FileName, hygiene}; use syntax_pos::{FileName, edition::Edition, hygiene};
use syntax_ext; use syntax_ext;
use serialize::json; use serialize::json;
@ -70,8 +70,6 @@ use std::ops::Generator;
pub fn parse<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> { pub fn parse<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
sess.diagnostic() sess.diagnostic()
.set_continue_after_error(sess.opts.debugging_opts.continue_parse_after_error); .set_continue_after_error(sess.opts.debugging_opts.continue_parse_after_error);
hygiene::set_default_edition(sess.edition());
sess.profiler(|p| p.start_activity("parsing")); sess.profiler(|p| p.start_activity("parsing"));
let krate = time(sess, "parsing", || match *input { let krate = time(sess, "parsing", || match *input {
Input::File(ref file) => parse::parse_crate_from_file(file, &sess.parse_sess), Input::File(ref file) => parse::parse_crate_from_file(file, &sess.parse_sess),
@ -375,7 +373,7 @@ fn configure_and_expand_inner<'a>(
crate_loader, crate_loader,
&resolver_arenas, &resolver_arenas,
); );
syntax_ext::register_builtins(&mut resolver, plugin_info.syntax_exts); syntax_ext::register_builtins(&mut resolver, plugin_info.syntax_exts, sess.edition());
// Expand all macros // Expand all macros
sess.profiler(|p| p.start_activity("macro expansion")); sess.profiler(|p| p.start_activity("macro expansion"));

View file

@ -37,6 +37,7 @@ use syntax::util::lev_distance::find_best_match_for_name;
use syntax::source_map::{FileLoader, RealFileLoader, SourceMap}; use syntax::source_map::{FileLoader, RealFileLoader, SourceMap};
use syntax::symbol::{Symbol, sym}; use syntax::symbol::{Symbol, sym};
use syntax::{self, ast, attr}; use syntax::{self, ast, attr};
use syntax_pos::edition::Edition;
#[cfg(not(parallel_compiler))] #[cfg(not(parallel_compiler))]
use std::{thread, panic}; use std::{thread, panic};
@ -167,6 +168,7 @@ pub fn scoped_thread<F: FnOnce() -> R + Send, R: Send>(cfg: thread::Builder, f:
#[cfg(not(parallel_compiler))] #[cfg(not(parallel_compiler))]
pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>( pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
edition: Edition,
_threads: Option<usize>, _threads: Option<usize>,
stderr: &Option<Arc<Mutex<Vec<u8>>>>, stderr: &Option<Arc<Mutex<Vec<u8>>>>,
f: F, f: F,
@ -178,7 +180,7 @@ pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
} }
scoped_thread(cfg, || { scoped_thread(cfg, || {
syntax::with_globals( || { syntax::with_globals(edition, || {
ty::tls::GCX_PTR.set(&Lock::new(0), || { ty::tls::GCX_PTR.set(&Lock::new(0), || {
if let Some(stderr) = stderr { if let Some(stderr) = stderr {
io::set_panic(Some(box Sink(stderr.clone()))); io::set_panic(Some(box Sink(stderr.clone())));
@ -191,6 +193,7 @@ pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
#[cfg(parallel_compiler)] #[cfg(parallel_compiler)]
pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>( pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
edition: Edition,
threads: Option<usize>, threads: Option<usize>,
stderr: &Option<Arc<Mutex<Vec<u8>>>>, stderr: &Option<Arc<Mutex<Vec<u8>>>>,
f: F, f: F,
@ -213,7 +216,7 @@ pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
let with_pool = move |pool: &ThreadPool| pool.install(move || f()); let with_pool = move |pool: &ThreadPool| pool.install(move || f());
syntax::with_globals(|| { syntax::with_globals(edition, || {
syntax::GLOBALS.with(|syntax_globals| { syntax::GLOBALS.with(|syntax_globals| {
syntax_pos::GLOBALS.with(|syntax_pos_globals| { syntax_pos::GLOBALS.with(|syntax_pos_globals| {
// The main handler runs for each Rayon worker thread and sets up // The main handler runs for each Rayon worker thread and sets up

View file

@ -34,7 +34,7 @@ use syntax::ast;
use syntax::attr; use syntax::attr;
use syntax::source_map::Spanned; use syntax::source_map::Spanned;
use syntax::symbol::{keywords, sym}; use syntax::symbol::{keywords, sym};
use syntax_pos::{self, hygiene, FileName, SourceFile, Span}; use syntax_pos::{self, FileName, SourceFile, Span};
use log::{debug, trace}; use log::{debug, trace};
use rustc::hir::{self, PatKind}; use rustc::hir::{self, PatKind};
@ -480,7 +480,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
hash: tcx.crate_hash(LOCAL_CRATE), hash: tcx.crate_hash(LOCAL_CRATE),
disambiguator: tcx.sess.local_crate_disambiguator(), disambiguator: tcx.sess.local_crate_disambiguator(),
panic_strategy: tcx.sess.panic_strategy(), panic_strategy: tcx.sess.panic_strategy(),
edition: hygiene::default_edition(), edition: tcx.sess.edition(),
has_global_allocator: has_global_allocator, has_global_allocator: has_global_allocator,
has_panic_handler: has_panic_handler, has_panic_handler: has_panic_handler,
has_default_lib_allocator: has_default_lib_allocator, has_default_lib_allocator: has_default_lib_allocator,

View file

@ -6,7 +6,6 @@ use rustc::util::nodemap::FxHashMap;
use syntax::ext::base::{SyntaxExtension, NamedSyntaxExtension, NormalTT, IdentTT}; use syntax::ext::base::{SyntaxExtension, NamedSyntaxExtension, NormalTT, IdentTT};
use syntax::ext::base::MacroExpanderFn; use syntax::ext::base::MacroExpanderFn;
use syntax::ext::hygiene;
use syntax::symbol::{Symbol, sym}; use syntax::symbol::{Symbol, sym};
use syntax::ast; use syntax::ast;
use syntax::feature_gate::AttributeType; use syntax::feature_gate::AttributeType;
@ -130,7 +129,7 @@ impl<'a> Registry<'a> {
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
unstable_feature: None, unstable_feature: None,
edition: hygiene::default_edition(), edition: self.sess.edition(),
}); });
} }

View file

@ -17,7 +17,7 @@ use syntax::errors::DiagnosticBuilder;
use syntax::ext::base::{self, Determinacy}; use syntax::ext::base::{self, Determinacy};
use syntax::ext::base::{MacroKind, SyntaxExtension}; use syntax::ext::base::{MacroKind, SyntaxExtension};
use syntax::ext::expand::{AstFragment, Invocation, InvocationKind}; use syntax::ext::expand::{AstFragment, Invocation, InvocationKind};
use syntax::ext::hygiene::{self, Mark}; use syntax::ext::hygiene::Mark;
use syntax::ext::tt::macro_rules; use syntax::ext::tt::macro_rules;
use syntax::feature_gate::{ use syntax::feature_gate::{
feature_err, is_builtin_attr_name, AttributeGate, GateIssue, Stability, BUILTIN_ATTRIBUTES, feature_err, is_builtin_attr_name, AttributeGate, GateIssue, Stability, BUILTIN_ATTRIBUTES,
@ -1100,7 +1100,7 @@ impl<'a> Resolver<'a> {
let def_id = self.definitions.local_def_id(item.id); let def_id = self.definitions.local_def_id(item.id);
let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess, let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
&self.session.features_untracked(), &self.session.features_untracked(),
item, hygiene::default_edition())); item, self.session.edition()));
self.macro_map.insert(def_id, ext); self.macro_map.insert(def_id, ext);
let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() }; let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };

View file

@ -418,7 +418,7 @@ mod test {
use syntax::attr; use syntax::attr;
use syntax::source_map::dummy_spanned; use syntax::source_map::dummy_spanned;
use syntax::symbol::Symbol; use syntax::symbol::Symbol;
use syntax::with_globals; use syntax::with_default_globals;
fn word_cfg(s: &str) -> Cfg { fn word_cfg(s: &str) -> Cfg {
Cfg::Cfg(Symbol::intern(s), None) Cfg::Cfg(Symbol::intern(s), None)
@ -466,7 +466,7 @@ mod test {
#[test] #[test]
fn test_cfg_not() { fn test_cfg_not() {
with_globals(|| { with_default_globals(|| {
assert_eq!(!Cfg::False, Cfg::True); assert_eq!(!Cfg::False, Cfg::True);
assert_eq!(!Cfg::True, Cfg::False); assert_eq!(!Cfg::True, Cfg::False);
assert_eq!(!word_cfg("test"), Cfg::Not(Box::new(word_cfg("test")))); assert_eq!(!word_cfg("test"), Cfg::Not(Box::new(word_cfg("test"))));
@ -484,7 +484,7 @@ mod test {
#[test] #[test]
fn test_cfg_and() { fn test_cfg_and() {
with_globals(|| { with_default_globals(|| {
let mut x = Cfg::False; let mut x = Cfg::False;
x &= Cfg::True; x &= Cfg::True;
assert_eq!(x, Cfg::False); assert_eq!(x, Cfg::False);
@ -536,7 +536,7 @@ mod test {
#[test] #[test]
fn test_cfg_or() { fn test_cfg_or() {
with_globals(|| { with_default_globals(|| {
let mut x = Cfg::True; let mut x = Cfg::True;
x |= Cfg::False; x |= Cfg::False;
assert_eq!(x, Cfg::True); assert_eq!(x, Cfg::True);
@ -588,7 +588,7 @@ mod test {
#[test] #[test]
fn test_parse_ok() { fn test_parse_ok() {
with_globals(|| { with_default_globals(|| {
let mi = dummy_meta_item_word("all"); let mi = dummy_meta_item_word("all");
assert_eq!(Cfg::parse(&mi), Ok(word_cfg("all"))); assert_eq!(Cfg::parse(&mi), Ok(word_cfg("all")));
@ -622,7 +622,7 @@ mod test {
#[test] #[test]
fn test_parse_err() { fn test_parse_err() {
with_globals(|| { with_default_globals(|| {
let mi = attr::mk_name_value_item( let mi = attr::mk_name_value_item(
DUMMY_SP, DUMMY_SP,
Ident::from_str("foo"), Ident::from_str("foo"),
@ -661,7 +661,7 @@ mod test {
#[test] #[test]
fn test_render_short_html() { fn test_render_short_html() {
with_globals(|| { with_default_globals(|| {
assert_eq!( assert_eq!(
word_cfg("unix").render_short_html(), word_cfg("unix").render_short_html(),
"Unix" "Unix"
@ -741,7 +741,7 @@ mod test {
#[test] #[test]
fn test_render_long_html() { fn test_render_long_html() {
with_globals(|| { with_default_globals(|| {
assert_eq!( assert_eq!(
word_cfg("unix").render_long_html(), word_cfg("unix").render_long_html(),
"This is supported on <strong>Unix</strong> only." "This is supported on <strong>Unix</strong> only."

View file

@ -8,6 +8,7 @@ use rustc::session::config::{OutputType, OutputTypes, Externs, CodegenOptions};
use rustc::session::search_paths::SearchPath; use rustc::session::search_paths::SearchPath;
use rustc::util::common::ErrorReported; use rustc::util::common::ErrorReported;
use syntax::ast; use syntax::ast;
use syntax::with_globals;
use syntax::source_map::SourceMap; use syntax::source_map::SourceMap;
use syntax::edition::Edition; use syntax::edition::Edition;
use syntax::feature_gate::UnstableFeatures; use syntax::feature_gate::UnstableFeatures;
@ -386,13 +387,11 @@ pub fn make_test(s: &str,
// Uses libsyntax to parse the doctest and find if there's a main fn and the extern // Uses libsyntax to parse the doctest and find if there's a main fn and the extern
// crate already is included. // crate already is included.
let (already_has_main, already_has_extern_crate, found_macro) = crate::syntax::with_globals(|| { let (already_has_main, already_has_extern_crate, found_macro) = with_globals(edition, || {
use crate::syntax::{parse::{self, ParseSess}, source_map::FilePathMapping}; use crate::syntax::{parse::{self, ParseSess}, source_map::FilePathMapping};
use errors::emitter::EmitterWriter; use errors::emitter::EmitterWriter;
use errors::Handler; use errors::Handler;
syntax::ext::hygiene::set_default_edition(edition);
let filename = FileName::anon_source_code(s); let filename = FileName::anon_source_code(s);
let source = crates + &everything_else; let source = crates + &everything_else;

View file

@ -5,7 +5,7 @@ use crate::attr::HasAttrs;
use crate::source_map::{SourceMap, Spanned, respan}; use crate::source_map::{SourceMap, Spanned, respan};
use crate::edition::Edition; use crate::edition::Edition;
use crate::ext::expand::{self, AstFragment, Invocation}; use crate::ext::expand::{self, AstFragment, Invocation};
use crate::ext::hygiene::{self, Mark, SyntaxContext, Transparency}; use crate::ext::hygiene::{Mark, SyntaxContext, Transparency};
use crate::mut_visit::{self, MutVisitor}; use crate::mut_visit::{self, MutVisitor};
use crate::parse::{self, parser, DirectoryOwnership}; use crate::parse::{self, parser, DirectoryOwnership};
use crate::parse::token; use crate::parse::token;
@ -713,7 +713,7 @@ impl SyntaxExtension {
} }
} }
pub fn edition(&self) -> Edition { pub fn edition(&self, default_edition: Edition) -> Edition {
match *self { match *self {
SyntaxExtension::NormalTT { edition, .. } | SyntaxExtension::NormalTT { edition, .. } |
SyntaxExtension::DeclMacro { edition, .. } | SyntaxExtension::DeclMacro { edition, .. } |
@ -725,7 +725,7 @@ impl SyntaxExtension {
SyntaxExtension::IdentTT { .. } | SyntaxExtension::IdentTT { .. } |
SyntaxExtension::MultiDecorator(..) | SyntaxExtension::MultiDecorator(..) |
SyntaxExtension::MultiModifier(..) | SyntaxExtension::MultiModifier(..) |
SyntaxExtension::BuiltinDerive(..) => hygiene::default_edition(), SyntaxExtension::BuiltinDerive(..) => default_edition,
} }
} }
} }
@ -734,6 +734,7 @@ pub type NamedSyntaxExtension = (Name, SyntaxExtension);
pub trait Resolver { pub trait Resolver {
fn next_node_id(&mut self) -> ast::NodeId; fn next_node_id(&mut self) -> ast::NodeId;
fn get_module_scope(&mut self, id: ast::NodeId) -> Mark; fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
fn resolve_dollar_crates(&mut self, fragment: &AstFragment); fn resolve_dollar_crates(&mut self, fragment: &AstFragment);
@ -768,6 +769,7 @@ pub struct DummyResolver;
impl Resolver for DummyResolver { impl Resolver for DummyResolver {
fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID } fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() } fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
fn resolve_dollar_crates(&mut self, _fragment: &AstFragment) {} fn resolve_dollar_crates(&mut self, _fragment: &AstFragment) {}

View file

@ -1,6 +1,6 @@
use crate::attr::HasAttrs; use crate::attr::HasAttrs;
use crate::ast; use crate::ast;
use crate::source_map::{hygiene, ExpnInfo, ExpnFormat}; use crate::source_map::{ExpnInfo, ExpnFormat};
use crate::ext::base::ExtCtxt; use crate::ext::base::ExtCtxt;
use crate::ext::build::AstBuilder; use crate::ext::build::AstBuilder;
use crate::parse::parser::PathStyle; use crate::parse::parser::PathStyle;
@ -64,7 +64,7 @@ pub fn add_derived_markers<T>(cx: &mut ExtCtxt<'_>, span: Span, traits: &[ast::P
].into()), ].into()),
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
edition: hygiene::default_edition(), edition: cx.parse_sess.edition,
}); });
let span = span.with_ctxt(cx.backtrace()); let span = span.with_ctxt(cx.backtrace());

View file

@ -5,7 +5,7 @@ use crate::source_map::{ExpnInfo, MacroBang, MacroAttribute, dummy_spanned, resp
use crate::config::StripUnconfigured; use crate::config::StripUnconfigured;
use crate::ext::base::*; use crate::ext::base::*;
use crate::ext::derive::{add_derived_markers, collect_derives}; use crate::ext::derive::{add_derived_markers, collect_derives};
use crate::ext::hygiene::{self, Mark, SyntaxContext}; use crate::ext::hygiene::{Mark, SyntaxContext};
use crate::ext::placeholders::{placeholder, PlaceholderExpander}; use crate::ext::placeholders::{placeholder, PlaceholderExpander};
use crate::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err}; use crate::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
use crate::mut_visit::*; use crate::mut_visit::*;
@ -560,7 +560,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
allow_internal_unstable: None, allow_internal_unstable: None,
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
edition: ext.edition(), edition: ext.edition(self.cx.parse_sess.edition),
}); });
match *ext { match *ext {
@ -805,7 +805,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
allow_internal_unstable: allow_internal_unstable.clone(), allow_internal_unstable: allow_internal_unstable.clone(),
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
edition: hygiene::default_edition(), edition: self.cx.parse_sess.edition,
}); });
let input: Vec<_> = mac.node.stream().into_trees().collect(); let input: Vec<_> = mac.node.stream().into_trees().collect();
@ -921,7 +921,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
allow_internal_unstable: None, allow_internal_unstable: None,
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
edition: ext.edition(), edition: ext.edition(self.cx.parse_sess.edition),
}; };
match *ext { match *ext {

View file

@ -29,6 +29,7 @@ use rustc_data_structures::sync::Lock;
use rustc_data_structures::bit_set::GrowableBitSet; use rustc_data_structures::bit_set::GrowableBitSet;
pub use rustc_data_structures::thin_vec::ThinVec; pub use rustc_data_structures::thin_vec::ThinVec;
use ast::AttrId; use ast::AttrId;
use syntax_pos::edition::Edition;
// A variant of 'try!' that panics on an Err. This is used as a crutch on the // A variant of 'try!' that panics on an Err. This is used as a crutch on the
// way towards a non-panic!-prone parser. It should be used for fatal parsing // way towards a non-panic!-prone parser. It should be used for fatal parsing
@ -82,26 +83,32 @@ pub struct Globals {
} }
impl Globals { impl Globals {
fn new() -> Globals { fn new(edition: Edition) -> Globals {
Globals { Globals {
// We have no idea how many attributes their will be, so just // We have no idea how many attributes their will be, so just
// initiate the vectors with 0 bits. We'll grow them as necessary. // initiate the vectors with 0 bits. We'll grow them as necessary.
used_attrs: Lock::new(GrowableBitSet::new_empty()), used_attrs: Lock::new(GrowableBitSet::new_empty()),
known_attrs: Lock::new(GrowableBitSet::new_empty()), known_attrs: Lock::new(GrowableBitSet::new_empty()),
syntax_pos_globals: syntax_pos::Globals::new(), syntax_pos_globals: syntax_pos::Globals::new(edition),
} }
} }
} }
pub fn with_globals<F, R>(f: F) -> R pub fn with_globals<F, R>(edition: Edition, f: F) -> R
where F: FnOnce() -> R where F: FnOnce() -> R
{ {
let globals = Globals::new(); let globals = Globals::new(edition);
GLOBALS.set(&globals, || { GLOBALS.set(&globals, || {
syntax_pos::GLOBALS.set(&globals.syntax_pos_globals, f) syntax_pos::GLOBALS.set(&globals.syntax_pos_globals, f)
}) })
} }
pub fn with_default_globals<F, R>(f: F) -> R
where F: FnOnce() -> R
{
with_globals(edition::DEFAULT_EDITION, f)
}
scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals); scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
#[macro_use] #[macro_use]

View file

@ -1305,7 +1305,7 @@ mod tests {
use crate::util::parser_testing::{string_to_crate, matches_codepattern}; use crate::util::parser_testing::{string_to_crate, matches_codepattern};
use crate::print::pprust; use crate::print::pprust;
use crate::mut_visit; use crate::mut_visit;
use crate::with_globals; use crate::with_default_globals;
use super::*; use super::*;
// this version doesn't care about getting comments or docstrings in. // this version doesn't care about getting comments or docstrings in.
@ -1343,7 +1343,7 @@ mod tests {
// make sure idents get transformed everywhere // make sure idents get transformed everywhere
#[test] fn ident_transformation () { #[test] fn ident_transformation () {
with_globals(|| { with_default_globals(|| {
let mut zz_visitor = ToZzIdentMutVisitor; let mut zz_visitor = ToZzIdentMutVisitor;
let mut krate = string_to_crate( let mut krate = string_to_crate(
"#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string()); "#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string());
@ -1358,7 +1358,7 @@ mod tests {
// even inside macro defs.... // even inside macro defs....
#[test] fn ident_transformation_in_defs () { #[test] fn ident_transformation_in_defs () {
with_globals(|| { with_default_globals(|| {
let mut zz_visitor = ToZzIdentMutVisitor; let mut zz_visitor = ToZzIdentMutVisitor;
let mut krate = string_to_crate( let mut krate = string_to_crate(
"macro_rules! a {(b $c:expr $(d $e:token)f+ => \ "macro_rules! a {(b $c:expr $(d $e:token)f+ => \

View file

@ -1558,10 +1558,10 @@ mod tests {
use crate::feature_gate::UnstableFeatures; use crate::feature_gate::UnstableFeatures;
use crate::parse::token; use crate::parse::token;
use crate::diagnostics::plugin::ErrorMap; use crate::diagnostics::plugin::ErrorMap;
use crate::with_globals; use crate::with_default_globals;
use std::io; use std::io;
use std::path::PathBuf; use std::path::PathBuf;
use syntax_pos::{BytePos, Span, NO_EXPANSION}; use syntax_pos::{BytePos, Span, NO_EXPANSION, edition::Edition};
use rustc_data_structures::fx::{FxHashSet, FxHashMap}; use rustc_data_structures::fx::{FxHashSet, FxHashMap};
use rustc_data_structures::sync::Lock; use rustc_data_structures::sync::Lock;
@ -1581,6 +1581,7 @@ mod tests {
raw_identifier_spans: Lock::new(Vec::new()), raw_identifier_spans: Lock::new(Vec::new()),
registered_diagnostics: Lock::new(ErrorMap::new()), registered_diagnostics: Lock::new(ErrorMap::new()),
buffered_lints: Lock::new(vec![]), buffered_lints: Lock::new(vec![]),
edition: Edition::from_session(),
ambiguous_block_expr_parse: Lock::new(FxHashMap::default()), ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
} }
} }
@ -1601,7 +1602,7 @@ mod tests {
#[test] #[test]
fn t1() { fn t1() {
with_globals(|| { with_default_globals(|| {
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sh = mk_sess(sm.clone()); let sh = mk_sess(sm.clone());
let mut string_reader = setup(&sm, let mut string_reader = setup(&sm,
@ -1649,7 +1650,7 @@ mod tests {
#[test] #[test]
fn doublecolonparsing() { fn doublecolonparsing() {
with_globals(|| { with_default_globals(|| {
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sh = mk_sess(sm.clone()); let sh = mk_sess(sm.clone());
check_tokenization(setup(&sm, &sh, "a b".to_string()), check_tokenization(setup(&sm, &sh, "a b".to_string()),
@ -1659,7 +1660,7 @@ mod tests {
#[test] #[test]
fn dcparsing_2() { fn dcparsing_2() {
with_globals(|| { with_default_globals(|| {
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sh = mk_sess(sm.clone()); let sh = mk_sess(sm.clone());
check_tokenization(setup(&sm, &sh, "a::b".to_string()), check_tokenization(setup(&sm, &sh, "a::b".to_string()),
@ -1669,7 +1670,7 @@ mod tests {
#[test] #[test]
fn dcparsing_3() { fn dcparsing_3() {
with_globals(|| { with_default_globals(|| {
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sh = mk_sess(sm.clone()); let sh = mk_sess(sm.clone());
check_tokenization(setup(&sm, &sh, "a ::b".to_string()), check_tokenization(setup(&sm, &sh, "a ::b".to_string()),
@ -1679,7 +1680,7 @@ mod tests {
#[test] #[test]
fn dcparsing_4() { fn dcparsing_4() {
with_globals(|| { with_default_globals(|| {
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sh = mk_sess(sm.clone()); let sh = mk_sess(sm.clone());
check_tokenization(setup(&sm, &sh, "a:: b".to_string()), check_tokenization(setup(&sm, &sh, "a:: b".to_string()),
@ -1689,7 +1690,7 @@ mod tests {
#[test] #[test]
fn character_a() { fn character_a() {
with_globals(|| { with_default_globals(|| {
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sh = mk_sess(sm.clone()); let sh = mk_sess(sm.clone());
assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token().tok, assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token().tok,
@ -1699,7 +1700,7 @@ mod tests {
#[test] #[test]
fn character_space() { fn character_space() {
with_globals(|| { with_default_globals(|| {
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sh = mk_sess(sm.clone()); let sh = mk_sess(sm.clone());
assert_eq!(setup(&sm, &sh, "' '".to_string()).next_token().tok, assert_eq!(setup(&sm, &sh, "' '".to_string()).next_token().tok,
@ -1709,7 +1710,7 @@ mod tests {
#[test] #[test]
fn character_escaped() { fn character_escaped() {
with_globals(|| { with_default_globals(|| {
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sh = mk_sess(sm.clone()); let sh = mk_sess(sm.clone());
assert_eq!(setup(&sm, &sh, "'\\n'".to_string()).next_token().tok, assert_eq!(setup(&sm, &sh, "'\\n'".to_string()).next_token().tok,
@ -1719,7 +1720,7 @@ mod tests {
#[test] #[test]
fn lifetime_name() { fn lifetime_name() {
with_globals(|| { with_default_globals(|| {
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sh = mk_sess(sm.clone()); let sh = mk_sess(sm.clone());
assert_eq!(setup(&sm, &sh, "'abc".to_string()).next_token().tok, assert_eq!(setup(&sm, &sh, "'abc".to_string()).next_token().tok,
@ -1729,7 +1730,7 @@ mod tests {
#[test] #[test]
fn raw_string() { fn raw_string() {
with_globals(|| { with_default_globals(|| {
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sh = mk_sess(sm.clone()); let sh = mk_sess(sm.clone());
assert_eq!(setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string()) assert_eq!(setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
@ -1741,7 +1742,7 @@ mod tests {
#[test] #[test]
fn literal_suffixes() { fn literal_suffixes() {
with_globals(|| { with_default_globals(|| {
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sh = mk_sess(sm.clone()); let sh = mk_sess(sm.clone());
macro_rules! test { macro_rules! test {
@ -1787,7 +1788,7 @@ mod tests {
#[test] #[test]
fn nested_block_comments() { fn nested_block_comments() {
with_globals(|| { with_default_globals(|| {
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sh = mk_sess(sm.clone()); let sh = mk_sess(sm.clone());
let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string()); let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string());
@ -1802,7 +1803,7 @@ mod tests {
#[test] #[test]
fn crlf_comments() { fn crlf_comments() {
with_globals(|| { with_default_globals(|| {
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sh = mk_sess(sm.clone()); let sh = mk_sess(sm.clone());
let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string()); let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string());

View file

@ -13,6 +13,7 @@ use crate::print::pprust::token_to_string;
use errors::{Applicability, FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder}; use errors::{Applicability, FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
use rustc_data_structures::sync::{Lrc, Lock}; use rustc_data_structures::sync::{Lrc, Lock};
use syntax_pos::{Span, SourceFile, FileName, MultiSpan}; use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
use syntax_pos::edition::Edition;
use rustc_data_structures::fx::{FxHashSet, FxHashMap}; use rustc_data_structures::fx::{FxHashSet, FxHashMap};
use std::borrow::Cow; use std::borrow::Cow;
@ -38,6 +39,7 @@ pub struct ParseSess {
pub span_diagnostic: Handler, pub span_diagnostic: Handler,
pub unstable_features: UnstableFeatures, pub unstable_features: UnstableFeatures,
pub config: CrateConfig, pub config: CrateConfig,
pub edition: Edition,
pub missing_fragment_specifiers: Lock<FxHashSet<Span>>, pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
/// Places where raw identifiers were used. This is used for feature-gating raw identifiers. /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
pub raw_identifier_spans: Lock<Vec<Span>>, pub raw_identifier_spans: Lock<Vec<Span>>,
@ -74,6 +76,7 @@ impl ParseSess {
included_mod_stack: Lock::new(vec![]), included_mod_stack: Lock::new(vec![]),
source_map, source_map,
buffered_lints: Lock::new(vec![]), buffered_lints: Lock::new(vec![]),
edition: Edition::from_session(),
ambiguous_block_expr_parse: Lock::new(FxHashMap::default()), ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
} }
} }
@ -363,7 +366,7 @@ mod tests {
use crate::tokenstream::{DelimSpan, TokenTree}; use crate::tokenstream::{DelimSpan, TokenTree};
use crate::util::parser_testing::string_to_stream; use crate::util::parser_testing::string_to_stream;
use crate::util::parser_testing::{string_to_expr, string_to_item}; use crate::util::parser_testing::{string_to_expr, string_to_item};
use crate::with_globals; use crate::with_default_globals;
use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION}; use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
/// Parses an item. /// Parses an item.
@ -382,7 +385,7 @@ mod tests {
#[should_panic] #[should_panic]
#[test] fn bad_path_expr_1() { #[test] fn bad_path_expr_1() {
with_globals(|| { with_default_globals(|| {
string_to_expr("::abc::def::return".to_string()); string_to_expr("::abc::def::return".to_string());
}) })
} }
@ -390,7 +393,7 @@ mod tests {
// check the token-tree-ization of macros // check the token-tree-ization of macros
#[test] #[test]
fn string_to_tts_macro () { fn string_to_tts_macro () {
with_globals(|| { with_default_globals(|| {
use crate::symbol::sym; use crate::symbol::sym;
let tts: Vec<_> = let tts: Vec<_> =
@ -447,7 +450,7 @@ mod tests {
#[test] #[test]
fn string_to_tts_1() { fn string_to_tts_1() {
with_globals(|| { with_default_globals(|| {
let tts = string_to_stream("fn a (b : i32) { b; }".to_string()); let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
let expected = TokenStream::new(vec![ let expected = TokenStream::new(vec![
@ -480,7 +483,7 @@ mod tests {
} }
#[test] fn parse_use() { #[test] fn parse_use() {
with_globals(|| { with_default_globals(|| {
let use_s = "use foo::bar::baz;"; let use_s = "use foo::bar::baz;";
let vitem = string_to_item(use_s.to_string()).unwrap(); let vitem = string_to_item(use_s.to_string()).unwrap();
let vitem_s = item_to_string(&vitem); let vitem_s = item_to_string(&vitem);
@ -494,7 +497,7 @@ mod tests {
} }
#[test] fn parse_extern_crate() { #[test] fn parse_extern_crate() {
with_globals(|| { with_default_globals(|| {
let ex_s = "extern crate foo;"; let ex_s = "extern crate foo;";
let vitem = string_to_item(ex_s.to_string()).unwrap(); let vitem = string_to_item(ex_s.to_string()).unwrap();
let vitem_s = item_to_string(&vitem); let vitem_s = item_to_string(&vitem);
@ -531,7 +534,7 @@ mod tests {
} }
#[test] fn span_of_self_arg_pat_idents_are_correct() { #[test] fn span_of_self_arg_pat_idents_are_correct() {
with_globals(|| { with_default_globals(|| {
let srcs = ["impl z { fn a (&self, &myarg: i32) {} }", let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
"impl z { fn a (&mut self, &myarg: i32) {} }", "impl z { fn a (&mut self, &myarg: i32) {} }",
@ -551,7 +554,7 @@ mod tests {
} }
#[test] fn parse_exprs () { #[test] fn parse_exprs () {
with_globals(|| { with_default_globals(|| {
// just make sure that they parse.... // just make sure that they parse....
string_to_expr("3 + 4".to_string()); string_to_expr("3 + 4".to_string());
string_to_expr("a::z.froob(b,&(987+3))".to_string()); string_to_expr("a::z.froob(b,&(987+3))".to_string());
@ -559,7 +562,7 @@ mod tests {
} }
#[test] fn attrs_fix_bug () { #[test] fn attrs_fix_bug () {
with_globals(|| { with_default_globals(|| {
string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag]) string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
-> Result<Box<Writer>, String> { -> Result<Box<Writer>, String> {
#[cfg(windows)] #[cfg(windows)]
@ -576,7 +579,7 @@ mod tests {
} }
#[test] fn crlf_doc_comments() { #[test] fn crlf_doc_comments() {
with_globals(|| { with_default_globals(|| {
use crate::symbol::sym; use crate::symbol::sym;
let sess = ParseSess::new(FilePathMapping::empty()); let sess = ParseSess::new(FilePathMapping::empty());
@ -613,7 +616,7 @@ mod tests {
new_parser_from_source_str(sess, name, source).parse_expr() new_parser_from_source_str(sess, name, source).parse_expr()
} }
with_globals(|| { with_default_globals(|| {
let sess = ParseSess::new(FilePathMapping::empty()); let sess = ParseSess::new(FilePathMapping::empty());
let expr = parse_expr_from_source_str(PathBuf::from("foo").into(), let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
"foo!( fn main() { body } )".to_string(), &sess).unwrap(); "foo!( fn main() { body } )".to_string(), &sess).unwrap();
@ -637,7 +640,7 @@ mod tests {
// See `recurse_into_file_modules` in the parser. // See `recurse_into_file_modules` in the parser.
#[test] #[test]
fn out_of_line_mod() { fn out_of_line_mod() {
with_globals(|| { with_default_globals(|| {
let sess = ParseSess::new(FilePathMapping::empty()); let sess = ParseSess::new(FilePathMapping::empty());
let item = parse_item_from_source_str( let item = parse_item_from_source_str(
PathBuf::from("foo").into(), PathBuf::from("foo").into(),

View file

@ -3147,12 +3147,12 @@ mod tests {
use crate::ast; use crate::ast;
use crate::source_map; use crate::source_map;
use crate::with_globals; use crate::with_default_globals;
use syntax_pos; use syntax_pos;
#[test] #[test]
fn test_fun_to_string() { fn test_fun_to_string() {
with_globals(|| { with_default_globals(|| {
let abba_ident = ast::Ident::from_str("abba"); let abba_ident = ast::Ident::from_str("abba");
let decl = ast::FnDecl { let decl = ast::FnDecl {
@ -3180,7 +3180,7 @@ mod tests {
#[test] #[test]
fn test_variant_to_string() { fn test_variant_to_string() {
with_globals(|| { with_default_globals(|| {
let ident = ast::Ident::from_str("principal_skinner"); let ident = ast::Ident::from_str("principal_skinner");
let var = source_map::respan(syntax_pos::DUMMY_SP, ast::Variant_ { let var = source_map::respan(syntax_pos::DUMMY_SP, ast::Variant_ {

View file

@ -947,7 +947,7 @@ impl SourceMap {
allow_internal_unstable, allow_internal_unstable,
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
edition: hygiene::default_edition(), edition: edition::Edition::from_session(),
}); });
span.with_ctxt(SyntaxContext::empty().apply_mark(mark)) span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
} }

View file

@ -3,7 +3,7 @@ use crate::attr;
use crate::edition::Edition; use crate::edition::Edition;
use crate::ext::hygiene::{Mark, SyntaxContext}; use crate::ext::hygiene::{Mark, SyntaxContext};
use crate::symbol::{Ident, Symbol, keywords, sym}; use crate::symbol::{Ident, Symbol, keywords, sym};
use crate::source_map::{ExpnInfo, MacroAttribute, dummy_spanned, hygiene, respan}; use crate::source_map::{ExpnInfo, MacroAttribute, dummy_spanned, respan};
use crate::ptr::P; use crate::ptr::P;
use crate::tokenstream::TokenStream; use crate::tokenstream::TokenStream;
@ -14,7 +14,7 @@ use syntax_pos::{DUMMY_SP, Span};
/// Craft a span that will be ignored by the stability lint's /// Craft a span that will be ignored by the stability lint's
/// call to source_map's `is_internal` check. /// call to source_map's `is_internal` check.
/// The expanded code uses the unstable `#[prelude_import]` attribute. /// The expanded code uses the unstable `#[prelude_import]` attribute.
fn ignored_span(sp: Span) -> Span { fn ignored_span(sp: Span, edition: Edition) -> Span {
let mark = Mark::fresh(Mark::root()); let mark = Mark::fresh(Mark::root());
mark.set_expn_info(ExpnInfo { mark.set_expn_info(ExpnInfo {
call_site: DUMMY_SP, call_site: DUMMY_SP,
@ -25,7 +25,7 @@ fn ignored_span(sp: Span) -> Span {
].into()), ].into()),
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
edition: hygiene::default_edition(), edition,
}); });
sp.with_ctxt(SyntaxContext::empty().apply_mark(mark)) sp.with_ctxt(SyntaxContext::empty().apply_mark(mark))
} }
@ -94,7 +94,7 @@ pub fn maybe_inject_crates_ref(
INJECTED_CRATE_NAME.with(|opt_name| opt_name.set(Some(name))); INJECTED_CRATE_NAME.with(|opt_name| opt_name.set(Some(name)));
let span = ignored_span(DUMMY_SP); let span = ignored_span(DUMMY_SP, edition);
krate.module.items.insert(0, P(ast::Item { krate.module.items.insert(0, P(ast::Item {
attrs: vec![ast::Attribute { attrs: vec![ast::Attribute {
style: ast::AttrStyle::Outer, style: ast::AttrStyle::Outer,

View file

@ -291,7 +291,7 @@ fn generate_test_harness(sess: &ParseSess,
].into()), ].into()),
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
edition: hygiene::default_edition(), edition: sess.edition,
}); });
TestHarnessGenerator { TestHarnessGenerator {

View file

@ -1,5 +1,5 @@
use crate::source_map::{SourceMap, FilePathMapping}; use crate::source_map::{SourceMap, FilePathMapping};
use crate::with_globals; use crate::with_default_globals;
use errors::Handler; use errors::Handler;
use errors::emitter::EmitterWriter; use errors::emitter::EmitterWriter;
@ -39,7 +39,7 @@ impl<T: Write> Write for Shared<T> {
} }
fn test_harness(file_text: &str, span_labels: Vec<SpanLabel>, expected_output: &str) { fn test_harness(file_text: &str, span_labels: Vec<SpanLabel>, expected_output: &str) {
with_globals(|| { with_default_globals(|| {
let output = Arc::new(Mutex::new(Vec::new())); let output = Arc::new(Mutex::new(Vec::new()));
let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty())); let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));

View file

@ -557,7 +557,7 @@ impl DelimSpan {
mod tests { mod tests {
use super::*; use super::*;
use crate::syntax::ast::Ident; use crate::syntax::ast::Ident;
use crate::with_globals; use crate::with_default_globals;
use crate::parse::token::Token; use crate::parse::token::Token;
use crate::util::parser_testing::string_to_stream; use crate::util::parser_testing::string_to_stream;
use syntax_pos::{Span, BytePos, NO_EXPANSION}; use syntax_pos::{Span, BytePos, NO_EXPANSION};
@ -572,7 +572,7 @@ mod tests {
#[test] #[test]
fn test_concat() { fn test_concat() {
with_globals(|| { with_default_globals(|| {
let test_res = string_to_ts("foo::bar::baz"); let test_res = string_to_ts("foo::bar::baz");
let test_fst = string_to_ts("foo::bar"); let test_fst = string_to_ts("foo::bar");
let test_snd = string_to_ts("::baz"); let test_snd = string_to_ts("::baz");
@ -585,7 +585,7 @@ mod tests {
#[test] #[test]
fn test_to_from_bijection() { fn test_to_from_bijection() {
with_globals(|| { with_default_globals(|| {
let test_start = string_to_ts("foo::bar(baz)"); let test_start = string_to_ts("foo::bar(baz)");
let test_end = test_start.trees().collect(); let test_end = test_start.trees().collect();
assert_eq!(test_start, test_end) assert_eq!(test_start, test_end)
@ -594,7 +594,7 @@ mod tests {
#[test] #[test]
fn test_eq_0() { fn test_eq_0() {
with_globals(|| { with_default_globals(|| {
let test_res = string_to_ts("foo"); let test_res = string_to_ts("foo");
let test_eqs = string_to_ts("foo"); let test_eqs = string_to_ts("foo");
assert_eq!(test_res, test_eqs) assert_eq!(test_res, test_eqs)
@ -603,7 +603,7 @@ mod tests {
#[test] #[test]
fn test_eq_1() { fn test_eq_1() {
with_globals(|| { with_default_globals(|| {
let test_res = string_to_ts("::bar::baz"); let test_res = string_to_ts("::bar::baz");
let test_eqs = string_to_ts("::bar::baz"); let test_eqs = string_to_ts("::bar::baz");
assert_eq!(test_res, test_eqs) assert_eq!(test_res, test_eqs)
@ -612,7 +612,7 @@ mod tests {
#[test] #[test]
fn test_eq_3() { fn test_eq_3() {
with_globals(|| { with_default_globals(|| {
let test_res = string_to_ts(""); let test_res = string_to_ts("");
let test_eqs = string_to_ts(""); let test_eqs = string_to_ts("");
assert_eq!(test_res, test_eqs) assert_eq!(test_res, test_eqs)
@ -621,7 +621,7 @@ mod tests {
#[test] #[test]
fn test_diseq_0() { fn test_diseq_0() {
with_globals(|| { with_default_globals(|| {
let test_res = string_to_ts("::bar::baz"); let test_res = string_to_ts("::bar::baz");
let test_eqs = string_to_ts("bar::baz"); let test_eqs = string_to_ts("bar::baz");
assert_eq!(test_res == test_eqs, false) assert_eq!(test_res == test_eqs, false)
@ -630,7 +630,7 @@ mod tests {
#[test] #[test]
fn test_diseq_1() { fn test_diseq_1() {
with_globals(|| { with_default_globals(|| {
let test_res = string_to_ts("(bar,baz)"); let test_res = string_to_ts("(bar,baz)");
let test_eqs = string_to_ts("bar,baz"); let test_eqs = string_to_ts("bar,baz");
assert_eq!(test_res == test_eqs, false) assert_eq!(test_res == test_eqs, false)
@ -639,7 +639,7 @@ mod tests {
#[test] #[test]
fn test_is_empty() { fn test_is_empty() {
with_globals(|| { with_default_globals(|| {
let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect(); let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
let test1: TokenStream = let test1: TokenStream =
TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into(); TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into();
@ -653,6 +653,7 @@ mod tests {
#[test] #[test]
fn test_dotdotdot() { fn test_dotdotdot() {
with_default_globals(|| {
let mut builder = TokenStreamBuilder::new(); let mut builder = TokenStreamBuilder::new();
builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint()); builder.push(TokenTree::Token(sp(0, 1), Token::Dot).joint());
builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint()); builder.push(TokenTree::Token(sp(1, 2), Token::Dot).joint());
@ -660,5 +661,6 @@ mod tests {
let stream = builder.build(); let stream = builder.build();
assert!(stream.eq_unspanned(&string_to_ts("..."))); assert!(stream.eq_unspanned(&string_to_ts("...")));
assert_eq!(stream.trees().count(), 1); assert_eq!(stream.trees().count(), 1);
})
} }
} }

View file

@ -101,8 +101,8 @@ fn test_lev_distance() {
#[test] #[test]
fn test_find_best_match_for_name() { fn test_find_best_match_for_name() {
use crate::with_globals; use crate::with_default_globals;
with_globals(|| { with_default_globals(|| {
let input = vec![Symbol::intern("aaab"), Symbol::intern("aaabc")]; let input = vec![Symbol::intern("aaab"), Symbol::intern("aaabc")];
assert_eq!( assert_eq!(
find_best_match_for_name(input.iter(), "aaaa", None), find_best_match_for_name(input.iter(), "aaaa", None),

View file

@ -42,17 +42,17 @@ pub mod proc_macro_impl;
use rustc_data_structures::sync::Lrc; use rustc_data_structures::sync::Lrc;
use syntax::ast; use syntax::ast;
use syntax::ext::base::{MacroExpanderFn, NormalTT, NamedSyntaxExtension, MultiModifier}; use syntax::ext::base::{MacroExpanderFn, NormalTT, NamedSyntaxExtension, MultiModifier};
use syntax::ext::hygiene;
use syntax::symbol::Symbol; use syntax::symbol::Symbol;
use syntax::edition::Edition;
pub fn register_builtins(resolver: &mut dyn syntax::ext::base::Resolver, pub fn register_builtins(resolver: &mut dyn syntax::ext::base::Resolver,
user_exts: Vec<NamedSyntaxExtension>) { user_exts: Vec<NamedSyntaxExtension>,
edition: Edition) {
deriving::register_builtin_derives(resolver); deriving::register_builtin_derives(resolver);
let mut register = |name, ext| { let mut register = |name, ext| {
resolver.add_builtin(ast::Ident::with_empty_ctxt(name), Lrc::new(ext)); resolver.add_builtin(ast::Ident::with_empty_ctxt(name), Lrc::new(ext));
}; };
macro_rules! register { macro_rules! register {
($( $name:ident: $f:expr, )*) => { $( ($( $name:ident: $f:expr, )*) => { $(
register(Symbol::intern(stringify!($name)), register(Symbol::intern(stringify!($name)),
@ -63,7 +63,7 @@ pub fn register_builtins(resolver: &mut dyn syntax::ext::base::Resolver,
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
unstable_feature: None, unstable_feature: None,
edition: hygiene::default_edition(), edition,
}); });
)* } )* }
} }
@ -108,7 +108,7 @@ pub fn register_builtins(resolver: &mut dyn syntax::ext::base::Resolver,
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
unstable_feature: None, unstable_feature: None,
edition: hygiene::default_edition(), edition,
}); });
register(Symbol::intern("format_args_nl"), register(Symbol::intern("format_args_nl"),
NormalTT { NormalTT {
@ -120,7 +120,7 @@ pub fn register_builtins(resolver: &mut dyn syntax::ext::base::Resolver,
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
unstable_feature: None, unstable_feature: None,
edition: hygiene::default_edition(), edition,
}); });
for (name, ext) in user_exts { for (name, ext) in user_exts {

View file

@ -4,7 +4,7 @@ use crate::deriving;
use syntax::ast::{self, Ident}; use syntax::ast::{self, Ident};
use syntax::attr; use syntax::attr;
use syntax::source_map::{ExpnInfo, MacroAttribute, hygiene, respan}; use syntax::source_map::{ExpnInfo, MacroAttribute, respan};
use syntax::ext::base::ExtCtxt; use syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder; use syntax::ext::build::AstBuilder;
use syntax::ext::expand::ExpansionConfig; use syntax::ext::expand::ExpansionConfig;
@ -358,7 +358,7 @@ fn mk_decls(
].into()), ].into()),
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
edition: hygiene::default_edition(), edition: cx.parse_sess.edition,
}); });
let span = DUMMY_SP.apply_mark(mark); let span = DUMMY_SP.apply_mark(mark);

View file

@ -3,7 +3,7 @@
use syntax::ext::base::*; use syntax::ext::base::*;
use syntax::ext::build::AstBuilder; use syntax::ext::build::AstBuilder;
use syntax::ext::hygiene::{self, Mark, SyntaxContext}; use syntax::ext::hygiene::{Mark, SyntaxContext};
use syntax::attr; use syntax::attr;
use syntax::ast; use syntax::ast;
use syntax::print::pprust; use syntax::print::pprust;
@ -72,7 +72,7 @@ pub fn expand_test_or_bench(
].into()), ].into()),
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
edition: hygiene::default_edition(), edition: cx.parse_sess.edition,
}); });
(item.span.with_ctxt(SyntaxContext::empty().apply_mark(mark)), (item.span.with_ctxt(SyntaxContext::empty().apply_mark(mark)),
attr_sp.with_ctxt(SyntaxContext::empty().apply_mark(mark))) attr_sp.with_ctxt(SyntaxContext::empty().apply_mark(mark)))

View file

@ -11,7 +11,7 @@
use syntax::ext::base::*; use syntax::ext::base::*;
use syntax::ext::build::AstBuilder; use syntax::ext::build::AstBuilder;
use syntax::ext::hygiene::{self, Mark, SyntaxContext}; use syntax::ext::hygiene::{Mark, SyntaxContext};
use syntax::ast; use syntax::ast;
use syntax::source_map::respan; use syntax::source_map::respan;
use syntax::symbol::{Symbol, sym}; use syntax::symbol::{Symbol, sym};
@ -47,7 +47,7 @@ pub fn expand(
].into()), ].into()),
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
edition: hygiene::default_edition(), edition: ecx.parse_sess.edition,
}); });
attr_sp.with_ctxt(SyntaxContext::empty().apply_mark(mark)) attr_sp.with_ctxt(SyntaxContext::empty().apply_mark(mark))
}; };

View file

@ -1,6 +1,7 @@
use crate::symbol::{Symbol, sym}; use crate::symbol::{Symbol, sym};
use std::fmt; use std::fmt;
use std::str::FromStr; use std::str::FromStr;
use crate::GLOBALS;
/// The edition of the compiler (RFC 2052) /// The edition of the compiler (RFC 2052)
#[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Debug, RustcEncodable, RustcDecodable, Eq)] #[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Debug, RustcEncodable, RustcDecodable, Eq)]
@ -38,6 +39,10 @@ impl fmt::Display for Edition {
} }
impl Edition { impl Edition {
pub fn from_session() -> Edition {
GLOBALS.with(|globals| globals.edition)
}
pub fn lint_name(&self) -> &'static str { pub fn lint_name(&self) -> &'static str {
match *self { match *self {
Edition::Edition2015 => "rust_2015_compatibility", Edition::Edition2015 => "rust_2015_compatibility",

View file

@ -7,7 +7,7 @@
use crate::GLOBALS; use crate::GLOBALS;
use crate::Span; use crate::Span;
use crate::edition::{Edition, DEFAULT_EDITION}; use crate::edition::Edition;
use crate::symbol::{keywords, Symbol}; use crate::symbol::{keywords, Symbol};
use serialize::{Encodable, Decodable, Encoder, Decoder}; use serialize::{Encodable, Decodable, Encoder, Decoder};
@ -174,7 +174,6 @@ crate struct HygieneData {
marks: Vec<MarkData>, marks: Vec<MarkData>,
syntax_contexts: Vec<SyntaxContextData>, syntax_contexts: Vec<SyntaxContextData>,
markings: FxHashMap<(SyntaxContext, Mark, Transparency), SyntaxContext>, markings: FxHashMap<(SyntaxContext, Mark, Transparency), SyntaxContext>,
default_edition: Edition,
} }
impl HygieneData { impl HygieneData {
@ -196,7 +195,6 @@ impl HygieneData {
dollar_crate_name: keywords::DollarCrate.name(), dollar_crate_name: keywords::DollarCrate.name(),
}], }],
markings: FxHashMap::default(), markings: FxHashMap::default(),
default_edition: DEFAULT_EDITION,
} }
} }
@ -205,14 +203,6 @@ impl HygieneData {
} }
} }
pub fn default_edition() -> Edition {
HygieneData::with(|data| data.default_edition)
}
pub fn set_default_edition(edition: Edition) {
HygieneData::with(|data| data.default_edition = edition);
}
pub fn clear_markings() { pub fn clear_markings() {
HygieneData::with(|data| data.markings = FxHashMap::default()); HygieneData::with(|data| data.markings = FxHashMap::default());
} }

View file

@ -26,6 +26,7 @@ use serialize::{Encodable, Decodable, Encoder, Decoder};
extern crate serialize as rustc_serialize; // used by deriving extern crate serialize as rustc_serialize; // used by deriving
pub mod edition; pub mod edition;
use edition::Edition;
pub mod hygiene; pub mod hygiene;
pub use hygiene::{Mark, SyntaxContext, ExpnInfo, ExpnFormat, CompilerDesugaringKind}; pub use hygiene::{Mark, SyntaxContext, ExpnInfo, ExpnFormat, CompilerDesugaringKind};
@ -52,14 +53,16 @@ pub struct Globals {
symbol_interner: Lock<symbol::Interner>, symbol_interner: Lock<symbol::Interner>,
span_interner: Lock<span_encoding::SpanInterner>, span_interner: Lock<span_encoding::SpanInterner>,
hygiene_data: Lock<hygiene::HygieneData>, hygiene_data: Lock<hygiene::HygieneData>,
edition: Edition,
} }
impl Globals { impl Globals {
pub fn new() -> Globals { pub fn new(edition: Edition) -> Globals {
Globals { Globals {
symbol_interner: Lock::new(symbol::Interner::fresh()), symbol_interner: Lock::new(symbol::Interner::fresh()),
span_interner: Lock::new(span_encoding::SpanInterner::default()), span_interner: Lock::new(span_encoding::SpanInterner::default()),
hygiene_data: Lock::new(hygiene::HygieneData::new()), hygiene_data: Lock::new(hygiene::HygieneData::new()),
edition,
} }
} }
} }
@ -356,8 +359,9 @@ impl Span {
/// Edition of the crate from which this span came. /// Edition of the crate from which this span came.
pub fn edition(self) -> edition::Edition { pub fn edition(self) -> edition::Edition {
self.ctxt().outer().expn_info().map_or_else(|| hygiene::default_edition(), self.ctxt().outer().expn_info().map_or_else(|| {
|einfo| einfo.edition) Edition::from_session()
}, |einfo| einfo.edition)
} }
#[inline] #[inline]

View file

@ -1276,6 +1276,7 @@ impl Encodable for InternedString {
mod tests { mod tests {
use super::*; use super::*;
use crate::Globals; use crate::Globals;
use crate::edition;
#[test] #[test]
fn interner_tests() { fn interner_tests() {
@ -1300,7 +1301,7 @@ mod tests {
#[test] #[test]
fn without_first_quote_test() { fn without_first_quote_test() {
GLOBALS.set(&Globals::new(), || { GLOBALS.set(&Globals::new(edition::DEFAULT_EDITION), || {
let i = Ident::from_str("'break"); let i = Ident::from_str("'break");
assert_eq!(i.without_first_quote().name, keywords::Break.name()); assert_eq!(i.without_first_quote().name, keywords::Break.name());
}); });

View file

@ -105,7 +105,7 @@ fn reject_stmt_parse(es: &str) {
} }
fn main() { fn main() {
syntax::with_globals(|| run()); syntax::with_default_globals(|| run());
} }
fn run() { fn run() {

View file

@ -47,6 +47,6 @@ pub fn plugin_registrar(reg: &mut Registry) {
allow_internal_unsafe: false, allow_internal_unsafe: false,
local_inner_macros: false, local_inner_macros: false,
unstable_feature: None, unstable_feature: None,
edition: hygiene::default_edition(), edition: reg.sess.edition(),
}); });
} }

View file

@ -13,7 +13,7 @@ use syntax::parse::{self, ParseSess};
mod gravy; mod gravy;
pub fn main() { pub fn main() {
syntax::with_globals(|| parse()); syntax::with_default_globals(|| parse());
assert_eq!(gravy::foo(), 10); assert_eq!(gravy::foo(), 10);
} }

View file

@ -189,7 +189,7 @@ impl MutVisitor for AddParens {
} }
fn main() { fn main() {
syntax::with_globals(|| run()); syntax::with_default_globals(|| run());
} }
fn run() { fn run() {

View file

@ -15,7 +15,7 @@ error[E0425]: cannot find value `no` in this scope
error: aborting due to previous error error: aborting due to previous error
For more information about this error, try `rustc --explain E0425`. For more information about this error, try `rustc --explain E0425`.
thread '$DIR/failed-doctest-output.rs - OtherStruct (line 17)' panicked at 'couldn't compile the test', src/librustdoc/test.rs:319:13 thread '$DIR/failed-doctest-output.rs - OtherStruct (line 17)' panicked at 'couldn't compile the test', src/librustdoc/test.rs:320:13
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace. note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
---- $DIR/failed-doctest-output.rs - SomeStruct (line 11) stdout ---- ---- $DIR/failed-doctest-output.rs - SomeStruct (line 11) stdout ----
@ -24,7 +24,7 @@ thread '$DIR/failed-doctest-output.rs - SomeStruct (line 11)' panicked at 'test
thread 'main' panicked at 'oh no', $DIR/failed-doctest-output.rs:3:1 thread 'main' panicked at 'oh no', $DIR/failed-doctest-output.rs:3:1
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace. note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
', src/librustdoc/test.rs:341:17 ', src/librustdoc/test.rs:342:17
failures: failures:

View file

@ -13,7 +13,7 @@ error: unterminated double quote string
error: aborting due to previous error error: aborting due to previous error
thread '$DIR/unparseable-doc-test.rs - foo (line 6)' panicked at 'couldn't compile the test', src/librustdoc/test.rs:319:13 thread '$DIR/unparseable-doc-test.rs - foo (line 6)' panicked at 'couldn't compile the test', src/librustdoc/test.rs:320:13
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace. note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

View file

@ -266,7 +266,7 @@ fn main() {
*slot.borrow_mut() = Some((None, String::from("https://play.rust-lang.org/"))); *slot.borrow_mut() = Some((None, String::from("https://play.rust-lang.org/")));
}); });
let (format, dst) = parse_args(); let (format, dst) = parse_args();
let result = syntax::with_globals(move || { let result = syntax::with_default_globals(move || {
main_with_result(format, &dst) main_with_result(format, &dst)
}); });
if let Err(e) = result { if let Err(e) = result {