From 88fa5c6a45a533a78c698a22f4b16002a3bc9fc3 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sun, 19 May 2019 13:59:44 +0300 Subject: Improve type size assertions Now they - Tell what the new size is, when it changes - Do not require passing an identifier --- src/libsyntax/parse/token.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/libsyntax/parse') diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 049fb6cb78b..068fc41c87a 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -19,7 +19,7 @@ use log::info; use std::fmt; use std::mem; #[cfg(target_arch = "x86_64")] -use rustc_data_structures::static_assert; +use rustc_data_structures::static_assert_size; use rustc_data_structures::sync::Lrc; #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] @@ -74,7 +74,7 @@ pub enum Lit { } #[cfg(target_arch = "x86_64")] -static_assert!(MEM_SIZE_OF_LIT: mem::size_of::() == 8); +static_assert_size!(Lit, 8); impl Lit { crate fn literal_name(&self) -> &'static str { @@ -220,7 +220,7 @@ pub enum Token { // `Token` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(target_arch = "x86_64")] -static_assert!(MEM_SIZE_OF_STATEMENT: mem::size_of::() == 16); +static_assert_size!(Token, 16); impl Token { /// Recovers a `Token` from an `ast::Ident`. This creates a raw identifier if necessary. -- cgit 1.4.1-3-g733a5 From e186d3f3e057eef69c60c7d34e474461432ee544 Mon Sep 17 00:00:00 2001 From: topecongiro Date: Tue, 21 May 2019 13:18:20 +0900 Subject: Add stream_to_parser_with_base_dir --- src/libsyntax/parse/mod.rs | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'src/libsyntax/parse') diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 0611c1d9b42..53d6838939d 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -329,6 +329,13 @@ pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> { Parser::new(sess, stream, None, true, false) } +/// Given stream, the `ParseSess` and the base directory, produces a parser. +pub fn stream_to_parser_with_base_dir<'a>(sess: &'a ParseSess, + stream: TokenStream, + base_dir: Directory<'a>) -> Parser<'a> { + Parser::new(sess, stream, Some(base_dir), true, false) +} + /// A sequence separator. pub struct SeqSep { /// The seperator token. -- cgit 1.4.1-3-g733a5 From b07dbe1d44038b84e722cbe1efe3201e8fa934d8 Mon Sep 17 00:00:00 2001 From: topecongiro Date: Tue, 21 May 2019 22:57:34 +0900 Subject: Add doc comment --- src/libsyntax/parse/mod.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src/libsyntax/parse') diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 53d6838939d..8c1810e3efa 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -330,6 +330,16 @@ pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> { } /// Given stream, the `ParseSess` and the base directory, produces a parser. +/// +/// Use this function when you are creating a parser from the token stream +/// and also care about the current working directory of the parser (e.g., +/// you are trying to resolve modules defined inside a macro invocation). +/// +/// # Note +/// +/// The main usage of this function is outside of rustc, for those who uses +/// libsyntax as a library. Please do not remove this function while refactoring +/// just because it is not used in rustc codebase! pub fn stream_to_parser_with_base_dir<'a>(sess: &'a ParseSess, stream: TokenStream, base_dir: Directory<'a>) -> Parser<'a> { -- cgit 1.4.1-3-g733a5 From 1f1a9176e7963b43155ce56d2a4cea3bee4a4f7e Mon Sep 17 00:00:00 2001 From: topecongiro Date: Tue, 21 May 2019 23:17:59 +0900 Subject: Fix tidy: remove a trailing whitespace --- src/libsyntax/parse/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/libsyntax/parse') diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 8c1810e3efa..d0af1afd8fd 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -334,7 +334,7 @@ pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> { /// Use this function when you are creating a parser from the token stream /// and also care about the current working directory of the parser (e.g., /// you are trying to resolve modules defined inside a macro invocation). -/// +/// /// # Note /// /// The main usage of this function is outside of rustc, for those who uses -- cgit 1.4.1-3-g733a5 From a1f2dceaebd21a6f8a5f9341bf41724bb20e2a7d Mon Sep 17 00:00:00 2001 From: John Kåre Alsaker Date: Sat, 6 Apr 2019 00:15:49 +0200 Subject: Move `edition` outside the hygiene lock and avoid accessing it --- src/librustc/session/config.rs | 12 ++++---- src/librustc_allocator/expand.rs | 4 +-- src/librustc_interface/interface.rs | 4 ++- src/librustc_interface/passes.rs | 6 ++-- src/librustc_interface/util.rs | 7 +++-- src/librustc_metadata/encoder.rs | 4 +-- src/librustc_plugin/registry.rs | 3 +- src/librustc_resolve/macros.rs | 4 +-- src/librustdoc/clean/cfg.rs | 16 +++++----- src/librustdoc/test.rs | 5 ++-- src/libsyntax/ext/base.rs | 8 +++-- src/libsyntax/ext/derive.rs | 4 +-- src/libsyntax/ext/expand.rs | 8 ++--- src/libsyntax/lib.rs | 15 +++++++--- src/libsyntax/mut_visit.rs | 6 ++-- src/libsyntax/parse/lexer/mod.rs | 31 ++++++++++---------- src/libsyntax/parse/mod.rs | 27 +++++++++-------- src/libsyntax/print/pprust.rs | 6 ++-- src/libsyntax/source_map.rs | 2 +- src/libsyntax/std_inject.rs | 8 ++--- src/libsyntax/test.rs | 2 +- src/libsyntax/test_snippet.rs | 4 +-- src/libsyntax/tokenstream.rs | 34 ++++++++++++---------- src/libsyntax/util/lev_distance.rs | 4 +-- src/libsyntax_ext/lib.rs | 12 ++++---- src/libsyntax_ext/proc_macro_decls.rs | 4 +-- src/libsyntax_ext/test.rs | 4 +-- src/libsyntax_ext/test_case.rs | 4 +-- src/libsyntax_pos/edition.rs | 5 ++++ src/libsyntax_pos/hygiene.rs | 12 +------- src/libsyntax_pos/lib.rs | 10 +++++-- src/libsyntax_pos/symbol.rs | 3 +- src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs | 2 +- .../run-pass-fulldeps/auxiliary/plugin-args.rs | 2 +- .../mod_dir_path_canonicalized.rs | 2 +- .../run-pass-fulldeps/pprust-expr-roundtrip.rs | 2 +- src/test/rustdoc-ui/failed-doctest-output.stdout | 4 +-- src/test/rustdoc-ui/unparseable-doc-test.stdout | 2 +- src/tools/error_index_generator/main.rs | 2 +- 39 files changed, 155 insertions(+), 139 deletions(-) (limited to 'src/libsyntax/parse') diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index b5e3c4cda0a..f16137bd2c2 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -1853,7 +1853,7 @@ pub fn rustc_optgroups() -> Vec { // Convert strings provided as --cfg [cfgspec] into a crate_cfg pub fn parse_cfgspecs(cfgspecs: Vec) -> FxHashSet<(String, Option)> { - syntax::with_globals(move || { + syntax::with_default_globals(move || { let cfg = cfgspecs.into_iter().map(|s| { let sess = parse::ParseSess::new(FilePathMapping::empty()); 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 #[test] fn test_switch_implies_cfg_test() { - syntax::with_globals(|| { + syntax::with_default_globals(|| { let matches = &match optgroups().parse(&["--test".to_string()]) { Ok(m) => m, Err(f) => panic!("test_switch_implies_cfg_test: {}", f), @@ -2753,7 +2753,7 @@ mod tests { #[test] fn test_switch_implies_cfg_test_unless_cfg_test() { use syntax::symbol::sym; - syntax::with_globals(|| { + syntax::with_default_globals(|| { let matches = &match optgroups().parse(&["--test".to_string(), "--cfg=test".to_string()]) { Ok(m) => m, @@ -2771,7 +2771,7 @@ mod tests { #[test] fn test_can_print_warnings() { - syntax::with_globals(|| { + syntax::with_default_globals(|| { let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap(); let registry = errors::registry::Registry::new(&[]); let (sessopts, _) = build_session_options_and_crate_config(&matches); @@ -2779,7 +2779,7 @@ mod tests { assert!(!sess.diagnostic().flags.can_emit_warnings); }); - syntax::with_globals(|| { + syntax::with_default_globals(|| { let matches = optgroups() .parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()]) .unwrap(); @@ -2789,7 +2789,7 @@ mod tests { assert!(sess.diagnostic().flags.can_emit_warnings); }); - syntax::with_globals(|| { + syntax::with_default_globals(|| { let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap(); let registry = errors::registry::Registry::new(&[]); let (sessopts, _) = build_session_options_and_crate_config(&matches); diff --git a/src/librustc_allocator/expand.rs b/src/librustc_allocator/expand.rs index 6931b3542f7..0c19d770194 100644 --- a/src/librustc_allocator/expand.rs +++ b/src/librustc_allocator/expand.rs @@ -14,7 +14,7 @@ use syntax::{ base::{ExtCtxt, Resolver}, build::AstBuilder, expand::ExpansionConfig, - hygiene::{self, Mark, SyntaxContext}, + hygiene::{Mark, SyntaxContext}, }, mut_visit::{self, MutVisitor}, parse::ParseSess, @@ -96,7 +96,7 @@ impl MutVisitor for ExpandAllocatorDirectives<'_> { ].into()), allow_internal_unsafe: false, local_inner_macros: false, - edition: hygiene::default_edition(), + edition: self.sess.edition, }); // Tie the span to the macro expansion info we just created diff --git a/src/librustc_interface/interface.rs b/src/librustc_interface/interface.rs index f2a21d61aed..d598a48649e 100644 --- a/src/librustc_interface/interface.rs +++ b/src/librustc_interface/interface.rs @@ -18,6 +18,7 @@ use std::result; use std::sync::{Arc, Mutex}; use syntax; use syntax::source_map::{FileLoader, SourceMap}; +use syntax_pos::edition; pub type Result = result::Result; @@ -135,6 +136,7 @@ where { let stderr = config.stderr.take(); util::spawn_thread_pool( + config.opts.edition, config.opts.debugging_opts.threads, &stderr, || run_compiler_in_existing_thread_pool(config, f), @@ -146,5 +148,5 @@ where F: FnOnce() -> R + Send, R: Send, { - util::spawn_thread_pool(None, &None, f) + util::spawn_thread_pool(edition::DEFAULT_EDITION, None, &None, f) } diff --git a/src/librustc_interface/passes.rs b/src/librustc_interface/passes.rs index c5ac8860ccd..04041f88344 100644 --- a/src/librustc_interface/passes.rs +++ b/src/librustc_interface/passes.rs @@ -48,7 +48,7 @@ use syntax::util::node_count::NodeCounter; use syntax::util::lev_distance::find_best_match_for_name; use syntax::symbol::Symbol; use syntax::feature_gate::AttributeType; -use syntax_pos::{FileName, hygiene}; +use syntax_pos::{FileName, edition::Edition, hygiene}; use syntax_ext; use serialize::json; @@ -70,8 +70,6 @@ use std::ops::Generator; pub fn parse<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> { sess.diagnostic() .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")); let krate = time(sess, "parsing", || match *input { 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, &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 sess.profiler(|p| p.start_activity("macro expansion")); diff --git a/src/librustc_interface/util.rs b/src/librustc_interface/util.rs index d2d0d191807..09bb547191f 100644 --- a/src/librustc_interface/util.rs +++ b/src/librustc_interface/util.rs @@ -37,6 +37,7 @@ use syntax::util::lev_distance::find_best_match_for_name; use syntax::source_map::{FileLoader, RealFileLoader, SourceMap}; use syntax::symbol::{Symbol, sym}; use syntax::{self, ast, attr}; +use syntax_pos::edition::Edition; #[cfg(not(parallel_compiler))] use std::{thread, panic}; @@ -167,6 +168,7 @@ pub fn scoped_thread R + Send, R: Send>(cfg: thread::Builder, f: #[cfg(not(parallel_compiler))] pub fn spawn_thread_pool R + Send, R: Send>( + edition: Edition, _threads: Option, stderr: &Option>>>, f: F, @@ -178,7 +180,7 @@ pub fn spawn_thread_pool R + Send, R: Send>( } scoped_thread(cfg, || { - syntax::with_globals( || { + syntax::with_globals(edition, || { ty::tls::GCX_PTR.set(&Lock::new(0), || { if let Some(stderr) = stderr { io::set_panic(Some(box Sink(stderr.clone()))); @@ -191,6 +193,7 @@ pub fn spawn_thread_pool R + Send, R: Send>( #[cfg(parallel_compiler)] pub fn spawn_thread_pool R + Send, R: Send>( + edition: Edition, threads: Option, stderr: &Option>>>, f: F, @@ -213,7 +216,7 @@ pub fn spawn_thread_pool R + Send, R: Send>( let with_pool = move |pool: &ThreadPool| pool.install(move || f()); - syntax::with_globals(|| { + syntax::with_globals(edition, || { syntax::GLOBALS.with(|syntax_globals| { syntax_pos::GLOBALS.with(|syntax_pos_globals| { // The main handler runs for each Rayon worker thread and sets up diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index 939aadcc9ec..7f0993e799f 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -34,7 +34,7 @@ use syntax::ast; use syntax::attr; use syntax::source_map::Spanned; 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 rustc::hir::{self, PatKind}; @@ -480,7 +480,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { hash: tcx.crate_hash(LOCAL_CRATE), disambiguator: tcx.sess.local_crate_disambiguator(), panic_strategy: tcx.sess.panic_strategy(), - edition: hygiene::default_edition(), + edition: tcx.sess.edition(), has_global_allocator: has_global_allocator, has_panic_handler: has_panic_handler, has_default_lib_allocator: has_default_lib_allocator, diff --git a/src/librustc_plugin/registry.rs b/src/librustc_plugin/registry.rs index c2d1d5fa65a..2ed6f868fa1 100644 --- a/src/librustc_plugin/registry.rs +++ b/src/librustc_plugin/registry.rs @@ -6,7 +6,6 @@ use rustc::util::nodemap::FxHashMap; use syntax::ext::base::{SyntaxExtension, NamedSyntaxExtension, NormalTT, IdentTT}; use syntax::ext::base::MacroExpanderFn; -use syntax::ext::hygiene; use syntax::symbol::{Symbol, sym}; use syntax::ast; use syntax::feature_gate::AttributeType; @@ -130,7 +129,7 @@ impl<'a> Registry<'a> { allow_internal_unsafe: false, local_inner_macros: false, unstable_feature: None, - edition: hygiene::default_edition(), + edition: self.sess.edition(), }); } diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index e34a33ef8fa..d07f7b65275 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -17,7 +17,7 @@ use syntax::errors::DiagnosticBuilder; use syntax::ext::base::{self, Determinacy}; use syntax::ext::base::{MacroKind, SyntaxExtension}; 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::feature_gate::{ 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 ext = Lrc::new(macro_rules::compile(&self.session.parse_sess, &self.session.features_untracked(), - item, hygiene::default_edition())); + item, self.session.edition())); self.macro_map.insert(def_id, ext); let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() }; diff --git a/src/librustdoc/clean/cfg.rs b/src/librustdoc/clean/cfg.rs index 61399e0568c..67113787915 100644 --- a/src/librustdoc/clean/cfg.rs +++ b/src/librustdoc/clean/cfg.rs @@ -418,7 +418,7 @@ mod test { use syntax::attr; use syntax::source_map::dummy_spanned; use syntax::symbol::Symbol; - use syntax::with_globals; + use syntax::with_default_globals; fn word_cfg(s: &str) -> Cfg { Cfg::Cfg(Symbol::intern(s), None) @@ -466,7 +466,7 @@ mod test { #[test] fn test_cfg_not() { - with_globals(|| { + with_default_globals(|| { assert_eq!(!Cfg::False, Cfg::True); assert_eq!(!Cfg::True, Cfg::False); assert_eq!(!word_cfg("test"), Cfg::Not(Box::new(word_cfg("test")))); @@ -484,7 +484,7 @@ mod test { #[test] fn test_cfg_and() { - with_globals(|| { + with_default_globals(|| { let mut x = Cfg::False; x &= Cfg::True; assert_eq!(x, Cfg::False); @@ -536,7 +536,7 @@ mod test { #[test] fn test_cfg_or() { - with_globals(|| { + with_default_globals(|| { let mut x = Cfg::True; x |= Cfg::False; assert_eq!(x, Cfg::True); @@ -588,7 +588,7 @@ mod test { #[test] fn test_parse_ok() { - with_globals(|| { + with_default_globals(|| { let mi = dummy_meta_item_word("all"); assert_eq!(Cfg::parse(&mi), Ok(word_cfg("all"))); @@ -622,7 +622,7 @@ mod test { #[test] fn test_parse_err() { - with_globals(|| { + with_default_globals(|| { let mi = attr::mk_name_value_item( DUMMY_SP, Ident::from_str("foo"), @@ -661,7 +661,7 @@ mod test { #[test] fn test_render_short_html() { - with_globals(|| { + with_default_globals(|| { assert_eq!( word_cfg("unix").render_short_html(), "Unix" @@ -741,7 +741,7 @@ mod test { #[test] fn test_render_long_html() { - with_globals(|| { + with_default_globals(|| { assert_eq!( word_cfg("unix").render_long_html(), "This is supported on Unix only." diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 0cc99da6407..d76d4380755 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -8,6 +8,7 @@ use rustc::session::config::{OutputType, OutputTypes, Externs, CodegenOptions}; use rustc::session::search_paths::SearchPath; use rustc::util::common::ErrorReported; use syntax::ast; +use syntax::with_globals; use syntax::source_map::SourceMap; use syntax::edition::Edition; 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 // 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 errors::emitter::EmitterWriter; use errors::Handler; - syntax::ext::hygiene::set_default_edition(edition); - let filename = FileName::anon_source_code(s); let source = crates + &everything_else; diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 0a88d2f8824..489fac4f1ca 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -5,7 +5,7 @@ use crate::attr::HasAttrs; use crate::source_map::{SourceMap, Spanned, respan}; use crate::edition::Edition; 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::parse::{self, parser, DirectoryOwnership}; 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 { SyntaxExtension::NormalTT { edition, .. } | SyntaxExtension::DeclMacro { edition, .. } | @@ -725,7 +725,7 @@ impl SyntaxExtension { SyntaxExtension::IdentTT { .. } | SyntaxExtension::MultiDecorator(..) | SyntaxExtension::MultiModifier(..) | - SyntaxExtension::BuiltinDerive(..) => hygiene::default_edition(), + SyntaxExtension::BuiltinDerive(..) => default_edition, } } } @@ -734,6 +734,7 @@ pub type NamedSyntaxExtension = (Name, SyntaxExtension); pub trait Resolver { fn next_node_id(&mut self) -> ast::NodeId; + fn get_module_scope(&mut self, id: ast::NodeId) -> Mark; fn resolve_dollar_crates(&mut self, fragment: &AstFragment); @@ -768,6 +769,7 @@ pub struct DummyResolver; impl Resolver for DummyResolver { 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 resolve_dollar_crates(&mut self, _fragment: &AstFragment) {} diff --git a/src/libsyntax/ext/derive.rs b/src/libsyntax/ext/derive.rs index a24e09f127e..6e789c4c708 100644 --- a/src/libsyntax/ext/derive.rs +++ b/src/libsyntax/ext/derive.rs @@ -1,6 +1,6 @@ use crate::attr::HasAttrs; use crate::ast; -use crate::source_map::{hygiene, ExpnInfo, ExpnFormat}; +use crate::source_map::{ExpnInfo, ExpnFormat}; use crate::ext::base::ExtCtxt; use crate::ext::build::AstBuilder; use crate::parse::parser::PathStyle; @@ -64,7 +64,7 @@ pub fn add_derived_markers(cx: &mut ExtCtxt<'_>, span: Span, traits: &[ast::P ].into()), allow_internal_unsafe: false, local_inner_macros: false, - edition: hygiene::default_edition(), + edition: cx.parse_sess.edition, }); let span = span.with_ctxt(cx.backtrace()); diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 019ebc8566f..478ae4de82b 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -5,7 +5,7 @@ use crate::source_map::{ExpnInfo, MacroBang, MacroAttribute, dummy_spanned, resp use crate::config::StripUnconfigured; use crate::ext::base::*; 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::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err}; use crate::mut_visit::*; @@ -560,7 +560,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { allow_internal_unstable: None, allow_internal_unsafe: false, local_inner_macros: false, - edition: ext.edition(), + edition: ext.edition(self.cx.parse_sess.edition), }); match *ext { @@ -805,7 +805,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { allow_internal_unstable: allow_internal_unstable.clone(), allow_internal_unsafe: false, local_inner_macros: false, - edition: hygiene::default_edition(), + edition: self.cx.parse_sess.edition, }); 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_unsafe: false, local_inner_macros: false, - edition: ext.edition(), + edition: ext.edition(self.cx.parse_sess.edition), }; match *ext { diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index db10ab7af5a..5eda975bc9e 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -29,6 +29,7 @@ use rustc_data_structures::sync::Lock; use rustc_data_structures::bit_set::GrowableBitSet; pub use rustc_data_structures::thin_vec::ThinVec; 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 // way towards a non-panic!-prone parser. It should be used for fatal parsing @@ -82,26 +83,32 @@ pub struct Globals { } impl Globals { - fn new() -> Globals { + fn new(edition: Edition) -> Globals { Globals { // We have no idea how many attributes their will be, so just // initiate the vectors with 0 bits. We'll grow them as necessary. used_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: F) -> R +pub fn with_globals(edition: Edition, f: F) -> R where F: FnOnce() -> R { - let globals = Globals::new(); + let globals = Globals::new(edition); GLOBALS.set(&globals, || { syntax_pos::GLOBALS.set(&globals.syntax_pos_globals, f) }) } +pub fn with_default_globals(f: F) -> R + where F: FnOnce() -> R +{ + with_globals(edition::DEFAULT_EDITION, f) +} + scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals); #[macro_use] diff --git a/src/libsyntax/mut_visit.rs b/src/libsyntax/mut_visit.rs index f587e63e12b..8fdd15a029f 100644 --- a/src/libsyntax/mut_visit.rs +++ b/src/libsyntax/mut_visit.rs @@ -1305,7 +1305,7 @@ mod tests { use crate::util::parser_testing::{string_to_crate, matches_codepattern}; use crate::print::pprust; use crate::mut_visit; - use crate::with_globals; + use crate::with_default_globals; use super::*; // this version doesn't care about getting comments or docstrings in. @@ -1343,7 +1343,7 @@ mod tests { // make sure idents get transformed everywhere #[test] fn ident_transformation () { - with_globals(|| { + with_default_globals(|| { let mut zz_visitor = ToZzIdentMutVisitor; let mut krate = string_to_crate( "#[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.... #[test] fn ident_transformation_in_defs () { - with_globals(|| { + with_default_globals(|| { let mut zz_visitor = ToZzIdentMutVisitor; let mut krate = string_to_crate( "macro_rules! a {(b $c:expr $(d $e:token)f+ => \ diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 47da3ee6a6c..c97d8040761 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -1558,10 +1558,10 @@ mod tests { use crate::feature_gate::UnstableFeatures; use crate::parse::token; use crate::diagnostics::plugin::ErrorMap; - use crate::with_globals; + use crate::with_default_globals; use std::io; 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::sync::Lock; @@ -1581,6 +1581,7 @@ mod tests { raw_identifier_spans: Lock::new(Vec::new()), registered_diagnostics: Lock::new(ErrorMap::new()), buffered_lints: Lock::new(vec![]), + edition: Edition::from_session(), ambiguous_block_expr_parse: Lock::new(FxHashMap::default()), } } @@ -1601,7 +1602,7 @@ mod tests { #[test] fn t1() { - with_globals(|| { + with_default_globals(|| { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sh = mk_sess(sm.clone()); let mut string_reader = setup(&sm, @@ -1649,7 +1650,7 @@ mod tests { #[test] fn doublecolonparsing() { - with_globals(|| { + with_default_globals(|| { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sh = mk_sess(sm.clone()); check_tokenization(setup(&sm, &sh, "a b".to_string()), @@ -1659,7 +1660,7 @@ mod tests { #[test] fn dcparsing_2() { - with_globals(|| { + with_default_globals(|| { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sh = mk_sess(sm.clone()); check_tokenization(setup(&sm, &sh, "a::b".to_string()), @@ -1669,7 +1670,7 @@ mod tests { #[test] fn dcparsing_3() { - with_globals(|| { + with_default_globals(|| { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sh = mk_sess(sm.clone()); check_tokenization(setup(&sm, &sh, "a ::b".to_string()), @@ -1679,7 +1680,7 @@ mod tests { #[test] fn dcparsing_4() { - with_globals(|| { + with_default_globals(|| { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sh = mk_sess(sm.clone()); check_tokenization(setup(&sm, &sh, "a:: b".to_string()), @@ -1689,7 +1690,7 @@ mod tests { #[test] fn character_a() { - with_globals(|| { + with_default_globals(|| { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sh = mk_sess(sm.clone()); assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token().tok, @@ -1699,7 +1700,7 @@ mod tests { #[test] fn character_space() { - with_globals(|| { + with_default_globals(|| { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sh = mk_sess(sm.clone()); assert_eq!(setup(&sm, &sh, "' '".to_string()).next_token().tok, @@ -1709,7 +1710,7 @@ mod tests { #[test] fn character_escaped() { - with_globals(|| { + with_default_globals(|| { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sh = mk_sess(sm.clone()); assert_eq!(setup(&sm, &sh, "'\\n'".to_string()).next_token().tok, @@ -1719,7 +1720,7 @@ mod tests { #[test] fn lifetime_name() { - with_globals(|| { + with_default_globals(|| { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sh = mk_sess(sm.clone()); assert_eq!(setup(&sm, &sh, "'abc".to_string()).next_token().tok, @@ -1729,7 +1730,7 @@ mod tests { #[test] fn raw_string() { - with_globals(|| { + with_default_globals(|| { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sh = mk_sess(sm.clone()); assert_eq!(setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string()) @@ -1741,7 +1742,7 @@ mod tests { #[test] fn literal_suffixes() { - with_globals(|| { + with_default_globals(|| { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sh = mk_sess(sm.clone()); macro_rules! test { @@ -1787,7 +1788,7 @@ mod tests { #[test] fn nested_block_comments() { - with_globals(|| { + with_default_globals(|| { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sh = mk_sess(sm.clone()); let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string()); @@ -1802,7 +1803,7 @@ mod tests { #[test] fn crlf_comments() { - with_globals(|| { + with_default_globals(|| { let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sh = mk_sess(sm.clone()); let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string()); diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 0611c1d9b42..d574626e6db 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -13,6 +13,7 @@ use crate::print::pprust::token_to_string; use errors::{Applicability, FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder}; use rustc_data_structures::sync::{Lrc, Lock}; use syntax_pos::{Span, SourceFile, FileName, MultiSpan}; +use syntax_pos::edition::Edition; use rustc_data_structures::fx::{FxHashSet, FxHashMap}; use std::borrow::Cow; @@ -38,6 +39,7 @@ pub struct ParseSess { pub span_diagnostic: Handler, pub unstable_features: UnstableFeatures, pub config: CrateConfig, + pub edition: Edition, pub missing_fragment_specifiers: Lock>, /// Places where raw identifiers were used. This is used for feature-gating raw identifiers. pub raw_identifier_spans: Lock>, @@ -74,6 +76,7 @@ impl ParseSess { included_mod_stack: Lock::new(vec![]), source_map, buffered_lints: Lock::new(vec![]), + edition: Edition::from_session(), ambiguous_block_expr_parse: Lock::new(FxHashMap::default()), } } @@ -363,7 +366,7 @@ mod tests { use crate::tokenstream::{DelimSpan, TokenTree}; use crate::util::parser_testing::string_to_stream; 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}; /// Parses an item. @@ -382,7 +385,7 @@ mod tests { #[should_panic] #[test] fn bad_path_expr_1() { - with_globals(|| { + with_default_globals(|| { string_to_expr("::abc::def::return".to_string()); }) } @@ -390,7 +393,7 @@ mod tests { // check the token-tree-ization of macros #[test] fn string_to_tts_macro () { - with_globals(|| { + with_default_globals(|| { use crate::symbol::sym; let tts: Vec<_> = @@ -447,7 +450,7 @@ mod tests { #[test] fn string_to_tts_1() { - with_globals(|| { + with_default_globals(|| { let tts = string_to_stream("fn a (b : i32) { b; }".to_string()); let expected = TokenStream::new(vec![ @@ -480,7 +483,7 @@ mod tests { } #[test] fn parse_use() { - with_globals(|| { + with_default_globals(|| { let use_s = "use foo::bar::baz;"; let vitem = string_to_item(use_s.to_string()).unwrap(); let vitem_s = item_to_string(&vitem); @@ -494,7 +497,7 @@ mod tests { } #[test] fn parse_extern_crate() { - with_globals(|| { + with_default_globals(|| { let ex_s = "extern crate foo;"; let vitem = string_to_item(ex_s.to_string()).unwrap(); let vitem_s = item_to_string(&vitem); @@ -531,7 +534,7 @@ mod tests { } #[test] fn span_of_self_arg_pat_idents_are_correct() { - with_globals(|| { + with_default_globals(|| { let srcs = ["impl z { fn a (&self, &myarg: i32) {} }", "impl z { fn a (&mut self, &myarg: i32) {} }", @@ -551,7 +554,7 @@ mod tests { } #[test] fn parse_exprs () { - with_globals(|| { + with_default_globals(|| { // just make sure that they parse.... string_to_expr("3 + 4".to_string()); string_to_expr("a::z.froob(b,&(987+3))".to_string()); @@ -559,7 +562,7 @@ mod tests { } #[test] fn attrs_fix_bug () { - with_globals(|| { + with_default_globals(|| { string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag]) -> Result, String> { #[cfg(windows)] @@ -576,7 +579,7 @@ mod tests { } #[test] fn crlf_doc_comments() { - with_globals(|| { + with_default_globals(|| { use crate::symbol::sym; let sess = ParseSess::new(FilePathMapping::empty()); @@ -613,7 +616,7 @@ mod tests { new_parser_from_source_str(sess, name, source).parse_expr() } - with_globals(|| { + with_default_globals(|| { let sess = ParseSess::new(FilePathMapping::empty()); let expr = parse_expr_from_source_str(PathBuf::from("foo").into(), "foo!( fn main() { body } )".to_string(), &sess).unwrap(); @@ -637,7 +640,7 @@ mod tests { // See `recurse_into_file_modules` in the parser. #[test] fn out_of_line_mod() { - with_globals(|| { + with_default_globals(|| { let sess = ParseSess::new(FilePathMapping::empty()); let item = parse_item_from_source_str( PathBuf::from("foo").into(), diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index cd86d94f4b8..ac240359b56 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -3147,12 +3147,12 @@ mod tests { use crate::ast; use crate::source_map; - use crate::with_globals; + use crate::with_default_globals; use syntax_pos; #[test] fn test_fun_to_string() { - with_globals(|| { + with_default_globals(|| { let abba_ident = ast::Ident::from_str("abba"); let decl = ast::FnDecl { @@ -3180,7 +3180,7 @@ mod tests { #[test] fn test_variant_to_string() { - with_globals(|| { + with_default_globals(|| { let ident = ast::Ident::from_str("principal_skinner"); let var = source_map::respan(syntax_pos::DUMMY_SP, ast::Variant_ { diff --git a/src/libsyntax/source_map.rs b/src/libsyntax/source_map.rs index 215618bd09c..8a210db9185 100644 --- a/src/libsyntax/source_map.rs +++ b/src/libsyntax/source_map.rs @@ -947,7 +947,7 @@ impl SourceMap { allow_internal_unstable, allow_internal_unsafe: false, local_inner_macros: false, - edition: hygiene::default_edition(), + edition: edition::Edition::from_session(), }); span.with_ctxt(SyntaxContext::empty().apply_mark(mark)) } diff --git a/src/libsyntax/std_inject.rs b/src/libsyntax/std_inject.rs index 1be7986ad53..e01a3260d49 100644 --- a/src/libsyntax/std_inject.rs +++ b/src/libsyntax/std_inject.rs @@ -3,7 +3,7 @@ use crate::attr; use crate::edition::Edition; use crate::ext::hygiene::{Mark, SyntaxContext}; 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::tokenstream::TokenStream; @@ -14,7 +14,7 @@ use syntax_pos::{DUMMY_SP, Span}; /// Craft a span that will be ignored by the stability lint's /// call to source_map's `is_internal` check. /// 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()); mark.set_expn_info(ExpnInfo { call_site: DUMMY_SP, @@ -25,7 +25,7 @@ fn ignored_span(sp: Span) -> Span { ].into()), allow_internal_unsafe: false, local_inner_macros: false, - edition: hygiene::default_edition(), + edition, }); 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))); - let span = ignored_span(DUMMY_SP); + let span = ignored_span(DUMMY_SP, edition); krate.module.items.insert(0, P(ast::Item { attrs: vec![ast::Attribute { style: ast::AttrStyle::Outer, diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index 3dc7aad9459..7cd83f3e495 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -291,7 +291,7 @@ fn generate_test_harness(sess: &ParseSess, ].into()), allow_internal_unsafe: false, local_inner_macros: false, - edition: hygiene::default_edition(), + edition: sess.edition, }); TestHarnessGenerator { diff --git a/src/libsyntax/test_snippet.rs b/src/libsyntax/test_snippet.rs index 3cf6699538d..107cbe70a23 100644 --- a/src/libsyntax/test_snippet.rs +++ b/src/libsyntax/test_snippet.rs @@ -1,5 +1,5 @@ use crate::source_map::{SourceMap, FilePathMapping}; -use crate::with_globals; +use crate::with_default_globals; use errors::Handler; use errors::emitter::EmitterWriter; @@ -39,7 +39,7 @@ impl Write for Shared { } fn test_harness(file_text: &str, span_labels: Vec, expected_output: &str) { - with_globals(|| { + with_default_globals(|| { let output = Arc::new(Mutex::new(Vec::new())); let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty())); diff --git a/src/libsyntax/tokenstream.rs b/src/libsyntax/tokenstream.rs index 3cb16c30a50..79efc6bf689 100644 --- a/src/libsyntax/tokenstream.rs +++ b/src/libsyntax/tokenstream.rs @@ -557,7 +557,7 @@ impl DelimSpan { mod tests { use super::*; use crate::syntax::ast::Ident; - use crate::with_globals; + use crate::with_default_globals; use crate::parse::token::Token; use crate::util::parser_testing::string_to_stream; use syntax_pos::{Span, BytePos, NO_EXPANSION}; @@ -572,7 +572,7 @@ mod tests { #[test] fn test_concat() { - with_globals(|| { + with_default_globals(|| { let test_res = string_to_ts("foo::bar::baz"); let test_fst = string_to_ts("foo::bar"); let test_snd = string_to_ts("::baz"); @@ -585,7 +585,7 @@ mod tests { #[test] fn test_to_from_bijection() { - with_globals(|| { + with_default_globals(|| { let test_start = string_to_ts("foo::bar(baz)"); let test_end = test_start.trees().collect(); assert_eq!(test_start, test_end) @@ -594,7 +594,7 @@ mod tests { #[test] fn test_eq_0() { - with_globals(|| { + with_default_globals(|| { let test_res = string_to_ts("foo"); let test_eqs = string_to_ts("foo"); assert_eq!(test_res, test_eqs) @@ -603,7 +603,7 @@ mod tests { #[test] fn test_eq_1() { - with_globals(|| { + with_default_globals(|| { let test_res = string_to_ts("::bar::baz"); let test_eqs = string_to_ts("::bar::baz"); assert_eq!(test_res, test_eqs) @@ -612,7 +612,7 @@ mod tests { #[test] fn test_eq_3() { - with_globals(|| { + with_default_globals(|| { let test_res = string_to_ts(""); let test_eqs = string_to_ts(""); assert_eq!(test_res, test_eqs) @@ -621,7 +621,7 @@ mod tests { #[test] fn test_diseq_0() { - with_globals(|| { + with_default_globals(|| { let test_res = string_to_ts("::bar::baz"); let test_eqs = string_to_ts("bar::baz"); assert_eq!(test_res == test_eqs, false) @@ -630,7 +630,7 @@ mod tests { #[test] fn test_diseq_1() { - with_globals(|| { + with_default_globals(|| { let test_res = string_to_ts("(bar,baz)"); let test_eqs = string_to_ts("bar,baz"); assert_eq!(test_res == test_eqs, false) @@ -639,7 +639,7 @@ mod tests { #[test] fn test_is_empty() { - with_globals(|| { + with_default_globals(|| { let test0: TokenStream = Vec::::new().into_iter().collect(); let test1: TokenStream = TokenTree::Token(sp(0, 1), Token::Ident(Ident::from_str("a"), false)).into(); @@ -653,12 +653,14 @@ mod tests { #[test] fn test_dotdotdot() { - let mut builder = TokenStreamBuilder::new(); - 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(2, 3), Token::Dot)); - let stream = builder.build(); - assert!(stream.eq_unspanned(&string_to_ts("..."))); - assert_eq!(stream.trees().count(), 1); + with_default_globals(|| { + let mut builder = TokenStreamBuilder::new(); + 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(2, 3), Token::Dot)); + let stream = builder.build(); + assert!(stream.eq_unspanned(&string_to_ts("..."))); + assert_eq!(stream.trees().count(), 1); + }) } } diff --git a/src/libsyntax/util/lev_distance.rs b/src/libsyntax/util/lev_distance.rs index 2f150d22159..885b5a4f333 100644 --- a/src/libsyntax/util/lev_distance.rs +++ b/src/libsyntax/util/lev_distance.rs @@ -101,8 +101,8 @@ fn test_lev_distance() { #[test] fn test_find_best_match_for_name() { - use crate::with_globals; - with_globals(|| { + use crate::with_default_globals; + with_default_globals(|| { let input = vec![Symbol::intern("aaab"), Symbol::intern("aaabc")]; assert_eq!( find_best_match_for_name(input.iter(), "aaaa", None), diff --git a/src/libsyntax_ext/lib.rs b/src/libsyntax_ext/lib.rs index 508f740cac9..e5fc7aab61d 100644 --- a/src/libsyntax_ext/lib.rs +++ b/src/libsyntax_ext/lib.rs @@ -42,17 +42,17 @@ pub mod proc_macro_impl; use rustc_data_structures::sync::Lrc; use syntax::ast; use syntax::ext::base::{MacroExpanderFn, NormalTT, NamedSyntaxExtension, MultiModifier}; -use syntax::ext::hygiene; use syntax::symbol::Symbol; +use syntax::edition::Edition; pub fn register_builtins(resolver: &mut dyn syntax::ext::base::Resolver, - user_exts: Vec) { + user_exts: Vec, + edition: Edition) { deriving::register_builtin_derives(resolver); let mut register = |name, ext| { resolver.add_builtin(ast::Ident::with_empty_ctxt(name), Lrc::new(ext)); }; - macro_rules! register { ($( $name:ident: $f:expr, )*) => { $( register(Symbol::intern(stringify!($name)), @@ -63,7 +63,7 @@ pub fn register_builtins(resolver: &mut dyn syntax::ext::base::Resolver, allow_internal_unsafe: false, local_inner_macros: false, 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, local_inner_macros: false, unstable_feature: None, - edition: hygiene::default_edition(), + edition, }); register(Symbol::intern("format_args_nl"), NormalTT { @@ -120,7 +120,7 @@ pub fn register_builtins(resolver: &mut dyn syntax::ext::base::Resolver, allow_internal_unsafe: false, local_inner_macros: false, unstable_feature: None, - edition: hygiene::default_edition(), + edition, }); for (name, ext) in user_exts { diff --git a/src/libsyntax_ext/proc_macro_decls.rs b/src/libsyntax_ext/proc_macro_decls.rs index 200445d1248..a13fe65ca0d 100644 --- a/src/libsyntax_ext/proc_macro_decls.rs +++ b/src/libsyntax_ext/proc_macro_decls.rs @@ -4,7 +4,7 @@ use crate::deriving; use syntax::ast::{self, Ident}; 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::build::AstBuilder; use syntax::ext::expand::ExpansionConfig; @@ -358,7 +358,7 @@ fn mk_decls( ].into()), allow_internal_unsafe: false, local_inner_macros: false, - edition: hygiene::default_edition(), + edition: cx.parse_sess.edition, }); let span = DUMMY_SP.apply_mark(mark); diff --git a/src/libsyntax_ext/test.rs b/src/libsyntax_ext/test.rs index 211a098022f..8ee61a3f67f 100644 --- a/src/libsyntax_ext/test.rs +++ b/src/libsyntax_ext/test.rs @@ -3,7 +3,7 @@ use syntax::ext::base::*; use syntax::ext::build::AstBuilder; -use syntax::ext::hygiene::{self, Mark, SyntaxContext}; +use syntax::ext::hygiene::{Mark, SyntaxContext}; use syntax::attr; use syntax::ast; use syntax::print::pprust; @@ -72,7 +72,7 @@ pub fn expand_test_or_bench( ].into()), allow_internal_unsafe: false, local_inner_macros: false, - edition: hygiene::default_edition(), + edition: cx.parse_sess.edition, }); (item.span.with_ctxt(SyntaxContext::empty().apply_mark(mark)), attr_sp.with_ctxt(SyntaxContext::empty().apply_mark(mark))) diff --git a/src/libsyntax_ext/test_case.rs b/src/libsyntax_ext/test_case.rs index 802037f6d22..5b1ae167ce3 100644 --- a/src/libsyntax_ext/test_case.rs +++ b/src/libsyntax_ext/test_case.rs @@ -11,7 +11,7 @@ use syntax::ext::base::*; use syntax::ext::build::AstBuilder; -use syntax::ext::hygiene::{self, Mark, SyntaxContext}; +use syntax::ext::hygiene::{Mark, SyntaxContext}; use syntax::ast; use syntax::source_map::respan; use syntax::symbol::{Symbol, sym}; @@ -47,7 +47,7 @@ pub fn expand( ].into()), allow_internal_unsafe: false, local_inner_macros: false, - edition: hygiene::default_edition(), + edition: ecx.parse_sess.edition, }); attr_sp.with_ctxt(SyntaxContext::empty().apply_mark(mark)) }; diff --git a/src/libsyntax_pos/edition.rs b/src/libsyntax_pos/edition.rs index 00cd00f2837..20216568426 100644 --- a/src/libsyntax_pos/edition.rs +++ b/src/libsyntax_pos/edition.rs @@ -1,6 +1,7 @@ use crate::symbol::{Symbol, sym}; use std::fmt; use std::str::FromStr; +use crate::GLOBALS; /// The edition of the compiler (RFC 2052) #[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Debug, RustcEncodable, RustcDecodable, Eq)] @@ -38,6 +39,10 @@ impl fmt::Display for Edition { } impl Edition { + pub fn from_session() -> Edition { + GLOBALS.with(|globals| globals.edition) + } + pub fn lint_name(&self) -> &'static str { match *self { Edition::Edition2015 => "rust_2015_compatibility", diff --git a/src/libsyntax_pos/hygiene.rs b/src/libsyntax_pos/hygiene.rs index 1d9dc26bf60..6e787c08504 100644 --- a/src/libsyntax_pos/hygiene.rs +++ b/src/libsyntax_pos/hygiene.rs @@ -7,7 +7,7 @@ use crate::GLOBALS; use crate::Span; -use crate::edition::{Edition, DEFAULT_EDITION}; +use crate::edition::Edition; use crate::symbol::{keywords, Symbol}; use serialize::{Encodable, Decodable, Encoder, Decoder}; @@ -174,7 +174,6 @@ crate struct HygieneData { marks: Vec, syntax_contexts: Vec, markings: FxHashMap<(SyntaxContext, Mark, Transparency), SyntaxContext>, - default_edition: Edition, } impl HygieneData { @@ -196,7 +195,6 @@ impl HygieneData { dollar_crate_name: keywords::DollarCrate.name(), }], 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() { HygieneData::with(|data| data.markings = FxHashMap::default()); } diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs index 39859f25f97..cb5aaf7eb88 100644 --- a/src/libsyntax_pos/lib.rs +++ b/src/libsyntax_pos/lib.rs @@ -26,6 +26,7 @@ use serialize::{Encodable, Decodable, Encoder, Decoder}; extern crate serialize as rustc_serialize; // used by deriving pub mod edition; +use edition::Edition; pub mod hygiene; pub use hygiene::{Mark, SyntaxContext, ExpnInfo, ExpnFormat, CompilerDesugaringKind}; @@ -52,14 +53,16 @@ pub struct Globals { symbol_interner: Lock, span_interner: Lock, hygiene_data: Lock, + edition: Edition, } impl Globals { - pub fn new() -> Globals { + pub fn new(edition: Edition) -> Globals { Globals { symbol_interner: Lock::new(symbol::Interner::fresh()), span_interner: Lock::new(span_encoding::SpanInterner::default()), hygiene_data: Lock::new(hygiene::HygieneData::new()), + edition, } } } @@ -356,8 +359,9 @@ impl Span { /// Edition of the crate from which this span came. pub fn edition(self) -> edition::Edition { - self.ctxt().outer().expn_info().map_or_else(|| hygiene::default_edition(), - |einfo| einfo.edition) + self.ctxt().outer().expn_info().map_or_else(|| { + Edition::from_session() + }, |einfo| einfo.edition) } #[inline] diff --git a/src/libsyntax_pos/symbol.rs b/src/libsyntax_pos/symbol.rs index a07c7eb897e..e69a9a1c5cf 100644 --- a/src/libsyntax_pos/symbol.rs +++ b/src/libsyntax_pos/symbol.rs @@ -1276,6 +1276,7 @@ impl Encodable for InternedString { mod tests { use super::*; use crate::Globals; + use crate::edition; #[test] fn interner_tests() { @@ -1300,7 +1301,7 @@ mod tests { #[test] fn without_first_quote_test() { - GLOBALS.set(&Globals::new(), || { + GLOBALS.set(&Globals::new(edition::DEFAULT_EDITION), || { let i = Ident::from_str("'break"); assert_eq!(i.without_first_quote().name, keywords::Break.name()); }); diff --git a/src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs b/src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs index d32fafd215c..49e137549c0 100644 --- a/src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs +++ b/src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs @@ -105,7 +105,7 @@ fn reject_stmt_parse(es: &str) { } fn main() { - syntax::with_globals(|| run()); + syntax::with_default_globals(|| run()); } fn run() { diff --git a/src/test/run-pass-fulldeps/auxiliary/plugin-args.rs b/src/test/run-pass-fulldeps/auxiliary/plugin-args.rs index 309acb25184..096701bd9b3 100644 --- a/src/test/run-pass-fulldeps/auxiliary/plugin-args.rs +++ b/src/test/run-pass-fulldeps/auxiliary/plugin-args.rs @@ -47,6 +47,6 @@ pub fn plugin_registrar(reg: &mut Registry) { allow_internal_unsafe: false, local_inner_macros: false, unstable_feature: None, - edition: hygiene::default_edition(), + edition: reg.sess.edition(), }); } diff --git a/src/test/run-pass-fulldeps/mod_dir_path_canonicalized.rs b/src/test/run-pass-fulldeps/mod_dir_path_canonicalized.rs index 22a76a3d968..a0dca9b1da4 100644 --- a/src/test/run-pass-fulldeps/mod_dir_path_canonicalized.rs +++ b/src/test/run-pass-fulldeps/mod_dir_path_canonicalized.rs @@ -13,7 +13,7 @@ use syntax::parse::{self, ParseSess}; mod gravy; pub fn main() { - syntax::with_globals(|| parse()); + syntax::with_default_globals(|| parse()); assert_eq!(gravy::foo(), 10); } diff --git a/src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs b/src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs index 80e0b0102af..659de9cf6d5 100644 --- a/src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs +++ b/src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs @@ -189,7 +189,7 @@ impl MutVisitor for AddParens { } fn main() { - syntax::with_globals(|| run()); + syntax::with_default_globals(|| run()); } fn run() { diff --git a/src/test/rustdoc-ui/failed-doctest-output.stdout b/src/test/rustdoc-ui/failed-doctest-output.stdout index 7b1cd702731..45efa30d991 100644 --- a/src/test/rustdoc-ui/failed-doctest-output.stdout +++ b/src/test/rustdoc-ui/failed-doctest-output.stdout @@ -15,7 +15,7 @@ error[E0425]: cannot find value `no` in this scope error: aborting due to previous error 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. ---- $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 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: diff --git a/src/test/rustdoc-ui/unparseable-doc-test.stdout b/src/test/rustdoc-ui/unparseable-doc-test.stdout index 7048ef2c589..f31b64fbce3 100644 --- a/src/test/rustdoc-ui/unparseable-doc-test.stdout +++ b/src/test/rustdoc-ui/unparseable-doc-test.stdout @@ -13,7 +13,7 @@ error: unterminated double quote string 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. diff --git a/src/tools/error_index_generator/main.rs b/src/tools/error_index_generator/main.rs index 38bd3fc006d..3e7c7ab6379 100644 --- a/src/tools/error_index_generator/main.rs +++ b/src/tools/error_index_generator/main.rs @@ -266,7 +266,7 @@ fn main() { *slot.borrow_mut() = Some((None, String::from("https://play.rust-lang.org/"))); }); let (format, dst) = parse_args(); - let result = syntax::with_globals(move || { + let result = syntax::with_default_globals(move || { main_with_result(format, &dst) }); if let Err(e) = result { -- cgit 1.4.1-3-g733a5 From 4bfb0453f537b2927574f29bdf90c9a22ea98add Mon Sep 17 00:00:00 2001 From: Matthew Jasper Date: Sat, 30 Mar 2019 22:54:29 +0000 Subject: Give match arms an HirId and a Span --- src/librustc/hir/intravisit.rs | 1 + src/librustc/hir/lowering.rs | 8 ++++++++ src/librustc/hir/map/collector.rs | 10 ++++++++++ src/librustc/hir/map/mod.rs | 7 +++++++ src/librustc/hir/mod.rs | 4 ++++ src/librustc/hir/print.rs | 2 +- src/librustc_passes/hir_stats.rs | 2 +- src/librustc_typeck/check/_match.rs | 15 +++++++++------ src/libsyntax/ast.rs | 1 + src/libsyntax/ext/build.rs | 3 ++- src/libsyntax/mut_visit.rs | 6 +++++- src/libsyntax/parse/parser.rs | 4 ++++ 12 files changed, 53 insertions(+), 10 deletions(-) (limited to 'src/libsyntax/parse') diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index 38d6d710868..517c99f99ef 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -1102,6 +1102,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) { } pub fn walk_arm<'v, V: Visitor<'v>>(visitor: &mut V, arm: &'v Arm) { + visitor.visit_id(arm.hir_id); walk_list!(visitor, visit_pat, &arm.pats); if let Some(ref g) = arm.guard { match g { diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 3ec4d4e8cc8..8dba7491bf5 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1313,7 +1313,10 @@ impl<'a> LoweringContext<'a> { } fn lower_arm(&mut self, arm: &Arm) -> hir::Arm { + let LoweredNodeId { node_id: _, hir_id } = self.next_id(); + hir::Arm { + hir_id, attrs: self.lower_attrs(&arm.attrs), pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(), guard: match arm.guard { @@ -1321,6 +1324,7 @@ impl<'a> LoweringContext<'a> { _ => None, }, body: P(self.lower_expr(&arm.body)), + span: arm.span, } } @@ -5023,10 +5027,14 @@ impl<'a> LoweringContext<'a> { // Helper methods for building HIR. fn arm(&mut self, pats: hir::HirVec>, expr: P) -> hir::Arm { + let LoweredNodeId { node_id: _, hir_id } = self.next_id(); + hir::Arm { + hir_id, attrs: hir_vec![], pats, guard: None, + span: expr.span, body: expr, } } diff --git a/src/librustc/hir/map/collector.rs b/src/librustc/hir/map/collector.rs index eeba628b3bf..b5203f9ec1f 100644 --- a/src/librustc/hir/map/collector.rs +++ b/src/librustc/hir/map/collector.rs @@ -430,6 +430,16 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { }); } + fn visit_arm(&mut self, arm: &'hir Arm) { + let node = Node::Arm(arm); + + self.insert(arm.span, arm.hir_id, node); + + self.with_parent(arm.hir_id, |this| { + intravisit::walk_arm(this, arm); + }); + } + fn visit_anon_const(&mut self, constant: &'hir AnonConst) { self.insert(DUMMY_SP, constant.hir_id, Node::AnonConst(constant)); diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index 4b94f772554..d8fe90d4048 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -373,6 +373,7 @@ impl<'hir> Map<'hir> { Node::Pat(_) | Node::Binding(_) | Node::Local(_) | + Node::Arm(_) | Node::Lifetime(_) | Node::Visibility(_) | Node::Block(_) | @@ -1000,6 +1001,7 @@ impl<'hir> Map<'hir> { Some(Node::Field(ref f)) => Some(&f.attrs[..]), Some(Node::Expr(ref e)) => Some(&*e.attrs), Some(Node::Stmt(ref s)) => Some(s.node.attrs()), + Some(Node::Arm(ref a)) => Some(&*a.attrs), Some(Node::GenericParam(param)) => Some(¶m.attrs[..]), // Unit/tuple structs/variants take the attributes straight from // the struct/variant definition. @@ -1073,6 +1075,7 @@ impl<'hir> Map<'hir> { Some(Node::TraitRef(tr)) => tr.path.span, Some(Node::Binding(pat)) => pat.span, Some(Node::Pat(pat)) => pat.span, + Some(Node::Arm(arm)) => arm.span, Some(Node::Block(block)) => block.span, Some(Node::Ctor(..)) => match self.find_by_hir_id( self.get_parent_node_by_hir_id(hir_id)) @@ -1288,6 +1291,7 @@ impl<'a> print::State<'a> { Node::TraitRef(a) => self.print_trait_ref(&a), Node::Binding(a) | Node::Pat(a) => self.print_pat(&a), + Node::Arm(a) => self.print_arm(&a), Node::Block(a) => { use syntax::print::pprust::PrintState; @@ -1417,6 +1421,9 @@ fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String { Some(Node::Pat(_)) => { format!("pat {}{}", map.hir_to_pretty_string(id), id_str) } + Some(Node::Arm(_)) => { + format!("arm {}{}", map.hir_to_pretty_string(id), id_str) + } Some(Node::Block(_)) => { format!("block {}{}", map.hir_to_pretty_string(id), id_str) } diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 57304c5ed37..08feea3ccce 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -1228,6 +1228,9 @@ pub struct Local { /// ` (if ) => `. #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] pub struct Arm { + #[stable_hasher(ignore)] + pub hir_id: HirId, + pub span: Span, pub attrs: HirVec, /// Multiple patterns can be combined with `|` pub pats: HirVec>, @@ -2656,6 +2659,7 @@ pub enum Node<'hir> { TraitRef(&'hir TraitRef), Binding(&'hir Pat), Pat(&'hir Pat), + Arm(&'hir Arm), Block(&'hir Block), Local(&'hir Local), MacroDef(&'hir MacroDef), diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index 8a9028e5443..ef9fee5cab6 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -1862,7 +1862,7 @@ impl<'a> State<'a> { self.ann.post(self, AnnNode::Pat(pat)) } - fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> { + pub fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> { // I have no idea why this check is necessary, but here it // is :( if arm.attrs.is_empty() { diff --git a/src/librustc_passes/hir_stats.rs b/src/librustc_passes/hir_stats.rs index c74314ce0c4..0088c97679c 100644 --- a/src/librustc_passes/hir_stats.rs +++ b/src/librustc_passes/hir_stats.rs @@ -149,7 +149,7 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_arm(&mut self, a: &'v hir::Arm) { - self.record("Arm", Id::None, a); + self.record("Arm", Id::Node(a.hir_id), a); hir_visit::walk_arm(self, a) } diff --git a/src/librustc_typeck/check/_match.rs b/src/librustc_typeck/check/_match.rs index a69f639e894..99b350b8332 100644 --- a/src/librustc_typeck/check/_match.rs +++ b/src/librustc_typeck/check/_match.rs @@ -781,14 +781,17 @@ https://doc.rust-lang.org/reference/types.html#trait-objects"); fn maybe_get_coercion_reason(&self, hir_id: hir::HirId, span: Span) -> Option<(Span, String)> { use hir::Node::{Block, Item, Local}; - let node = self.tcx.hir().get_by_hir_id(self.tcx.hir().get_parent_node_by_hir_id( - self.tcx.hir().get_parent_node_by_hir_id(hir_id), - )); + let hir = self.tcx.hir(); + let arm_id = hir.get_parent_node_by_hir_id(hir_id); + let match_id = hir.get_parent_node_by_hir_id(arm_id); + let containing_id = hir.get_parent_node_by_hir_id(match_id); + + let node = hir.get_by_hir_id(containing_id); if let Block(block) = node { // check that the body's parent is an fn - let parent = self.tcx.hir().get_by_hir_id( - self.tcx.hir().get_parent_node_by_hir_id( - self.tcx.hir().get_parent_node_by_hir_id(block.hir_id), + let parent = hir.get_by_hir_id( + hir.get_parent_node_by_hir_id( + hir.get_parent_node_by_hir_id(block.hir_id), ), ); if let (Some(expr), Item(hir::Item { diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index a6bb47bef87..e2c2c46abf6 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -908,6 +908,7 @@ pub struct Arm { pub pats: Vec>, pub guard: Option, pub body: P, + pub span: Span, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index d24106f697e..cb967a76822 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -890,12 +890,13 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self.pat_tuple_struct(span, path, vec![pat]) } - fn arm(&self, _span: Span, pats: Vec>, expr: P) -> ast::Arm { + fn arm(&self, span: Span, pats: Vec>, expr: P) -> ast::Arm { ast::Arm { attrs: vec![], pats, guard: None, body: expr, + span, } } diff --git a/src/libsyntax/mut_visit.rs b/src/libsyntax/mut_visit.rs index f587e63e12b..cb21014ec76 100644 --- a/src/libsyntax/mut_visit.rs +++ b/src/libsyntax/mut_visit.rs @@ -392,11 +392,15 @@ pub fn noop_visit_use_tree(use_tree: &mut UseTree, vis: &mut T) { vis.visit_span(span); } -pub fn noop_visit_arm(Arm { attrs, pats, guard, body }: &mut Arm, vis: &mut T) { +pub fn noop_visit_arm( + Arm { attrs, pats, guard, body, span }: &mut Arm, + vis: &mut T, +) { visit_attrs(attrs, vis); visit_vec(pats, |pat| vis.visit_pat(pat)); visit_opt(guard, |guard| vis.visit_guard(guard)); vis.visit_expr(body); + vis.visit_span(span); } pub fn noop_visit_guard(g: &mut Guard, vis: &mut T) { diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 24d120376de..ba36783e11e 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -3946,6 +3946,7 @@ impl<'a> Parser<'a> { crate fn parse_arm(&mut self) -> PResult<'a, Arm> { let attrs = self.parse_outer_attributes()?; + let lo = self.span; let pats = self.parse_pats()?; let guard = if self.eat_keyword(keywords::If) { Some(Guard::If(self.parse_expr()?)) @@ -3965,6 +3966,8 @@ impl<'a> Parser<'a> { let require_comma = classify::expr_requires_semi_to_be_stmt(&expr) && self.token != token::CloseDelim(token::Brace); + let hi = self.span; + if require_comma { let cm = self.sess.source_map(); self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) @@ -4008,6 +4011,7 @@ impl<'a> Parser<'a> { pats, guard, body: expr, + span: lo.to(hi), }) } -- cgit 1.4.1-3-g733a5 From ebd6c7164ee7d8f85a640858f1cad1f56cc11a35 Mon Sep 17 00:00:00 2001 From: Matthew Jasper Date: Fri, 3 May 2019 22:24:52 +0100 Subject: Dont show variables from desugarings in borrowck errors --- src/librustc/mir/mod.rs | 7 ++++ src/librustc_mir/borrow_check/error_reporting.rs | 8 ++-- src/librustc_mir/borrow_check/mutability_errors.rs | 47 ++++++++++++---------- .../borrow_check/nll/explain_borrow/mod.rs | 4 +- src/libsyntax/parse/parser.rs | 9 +++-- src/test/ui/nll/dont-print-desugared-async.rs | 9 +++++ src/test/ui/nll/dont-print-desugared-async.stderr | 12 ++++++ src/test/ui/nll/dont-print-desugared.rs | 21 ++++++++++ src/test/ui/nll/dont-print-desugared.stderr | 27 +++++++++++++ 9 files changed, 112 insertions(+), 32 deletions(-) create mode 100644 src/test/ui/nll/dont-print-desugared-async.rs create mode 100644 src/test/ui/nll/dont-print-desugared-async.stderr create mode 100644 src/test/ui/nll/dont-print-desugared.rs create mode 100644 src/test/ui/nll/dont-print-desugared.stderr (limited to 'src/libsyntax/parse') diff --git a/src/librustc/mir/mod.rs b/src/librustc/mir/mod.rs index dd43cb2f18e..aab9d5e3a02 100644 --- a/src/librustc/mir/mod.rs +++ b/src/librustc/mir/mod.rs @@ -915,6 +915,13 @@ impl<'tcx> LocalDecl<'tcx> { } } + /// Returns `true` is the local is from a compiler desugaring, e.g., + /// `__next` from a `for` loop. + #[inline] + pub fn from_compiler_desugaring(&self) -> bool { + self.source_info.span.compiler_desugaring_kind().is_some() + } + /// Creates a new `LocalDecl` for a temporary. #[inline] pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self { diff --git a/src/librustc_mir/borrow_check/error_reporting.rs b/src/librustc_mir/borrow_check/error_reporting.rs index 1a1000f0bb4..d7841807624 100644 --- a/src/librustc_mir/borrow_check/error_reporting.rs +++ b/src/librustc_mir/borrow_check/error_reporting.rs @@ -1760,15 +1760,15 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { } /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have - /// a name, then `Err` is returned + /// a name, or its name was generated by the compiler, then `Err` is returned fn append_local_to_string(&self, local_index: Local, buf: &mut String) -> Result<(), ()> { let local = &self.mir.local_decls[local_index]; match local.name { - Some(name) => { - buf.push_str(&name.to_string()); + Some(name) if !local.from_compiler_desugaring() => { + buf.push_str(name.as_str().get()); Ok(()) } - None => Err(()), + _ => Err(()), } } diff --git a/src/librustc_mir/borrow_check/mutability_errors.rs b/src/librustc_mir/borrow_check/mutability_errors.rs index 32088ff9f61..f0b4efe2630 100644 --- a/src/librustc_mir/borrow_check/mutability_errors.rs +++ b/src/librustc_mir/borrow_check/mutability_errors.rs @@ -420,28 +420,31 @@ impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> { ); } - if let Some(name) = local_decl.name { - err.span_label( - span, - format!( - "`{NAME}` is a `{SIGIL}` {DESC}, \ - so the data it refers to cannot be {ACTED_ON}", - NAME = name, - SIGIL = pointer_sigil, - DESC = pointer_desc, - ACTED_ON = acted_on - ), - ); - } else { - err.span_label( - span, - format!( - "cannot {ACT} through `{SIGIL}` {DESC}", - ACT = act, - SIGIL = pointer_sigil, - DESC = pointer_desc - ), - ); + match local_decl.name { + Some(name) if !local_decl.from_compiler_desugaring() => { + err.span_label( + span, + format!( + "`{NAME}` is a `{SIGIL}` {DESC}, \ + so the data it refers to cannot be {ACTED_ON}", + NAME = name, + SIGIL = pointer_sigil, + DESC = pointer_desc, + ACTED_ON = acted_on + ), + ); + } + _ => { + err.span_label( + span, + format!( + "cannot {ACT} through `{SIGIL}` {DESC}", + ACT = act, + SIGIL = pointer_sigil, + DESC = pointer_desc + ), + ); + } } } diff --git a/src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs b/src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs index 35efc6195be..6bca470bf3e 100644 --- a/src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs +++ b/src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs @@ -112,7 +112,7 @@ impl BorrowExplanation { }; match local_decl.name { - Some(local_name) => { + Some(local_name) if !local_decl.from_compiler_desugaring() => { let message = format!( "{B}borrow might be used here, when `{LOC}` is dropped \ and runs the {DTOR} for {TYPE}", @@ -130,7 +130,7 @@ impl BorrowExplanation { ); } } - None => { + _ => { err.span_label( local_decl.source_info.span, format!( diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 24d120376de..8083e00f607 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -8423,6 +8423,8 @@ impl<'a> Parser<'a> { for (index, input) in decl.inputs.iter_mut().enumerate() { let id = ast::DUMMY_NODE_ID; let span = input.pat.span; + let desugared_span = self.sess.source_map() + .mark_span_with_reason(CompilerDesugaringKind::Async, span, None); // Construct a name for our temporary argument. let name = format!("__arg{}", index); @@ -8439,8 +8441,7 @@ impl<'a> Parser<'a> { // this would affect the input to procedural macros, but they can have // their span marked as being the result of a compiler desugaring so // that they aren't linted against. - input.pat.span = self.sess.source_map().mark_span_with_reason( - CompilerDesugaringKind::Async, span, None); + input.pat.span = desugared_span; (binding_mode, ident, true) } @@ -8460,7 +8461,7 @@ impl<'a> Parser<'a> { node: PatKind::Ident( BindingMode::ByValue(Mutability::Immutable), ident, None, ), - span, + span: desugared_span, }), source: ArgSource::AsyncFn(input.pat.clone()), }) @@ -8473,7 +8474,7 @@ impl<'a> Parser<'a> { pat: P(Pat { id, node: PatKind::Ident(binding_mode, ident, None), - span, + span: desugared_span, }), // We explicitly do not specify the type for this statement. When the user's // argument type is `impl Trait` then this would require the diff --git a/src/test/ui/nll/dont-print-desugared-async.rs b/src/test/ui/nll/dont-print-desugared-async.rs new file mode 100644 index 00000000000..8150a260866 --- /dev/null +++ b/src/test/ui/nll/dont-print-desugared-async.rs @@ -0,0 +1,9 @@ +// Test that we don't show variables with from async fn desugaring + +// edition:2018 +#![feature(async_await)] + +async fn async_fn(&ref mut s: &[i32]) {} +//~^ ERROR cannot borrow data in a `&` reference as mutable [E0596] + +fn main() {} diff --git a/src/test/ui/nll/dont-print-desugared-async.stderr b/src/test/ui/nll/dont-print-desugared-async.stderr new file mode 100644 index 00000000000..47726ba65df --- /dev/null +++ b/src/test/ui/nll/dont-print-desugared-async.stderr @@ -0,0 +1,12 @@ +error[E0596]: cannot borrow data in a `&` reference as mutable + --> $DIR/dont-print-desugared-async.rs:6:20 + | +LL | async fn async_fn(&ref mut s: &[i32]) {} + | -^^^^^^^^^ + | || + | |cannot borrow as mutable through `&` reference + | help: consider changing this to be a mutable reference: `&mut ref mut s` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0596`. diff --git a/src/test/ui/nll/dont-print-desugared.rs b/src/test/ui/nll/dont-print-desugared.rs new file mode 100644 index 00000000000..829d78ed4c3 --- /dev/null +++ b/src/test/ui/nll/dont-print-desugared.rs @@ -0,0 +1,21 @@ +// Test that we don't show variables with from for loop desugaring + +fn for_loop(s: &[i32]) { + for &ref mut x in s {} + //~^ ERROR cannot borrow data in a `&` reference as mutable [E0596] +} + +struct D<'a>(&'a ()); + +impl Drop for D<'_> { + fn drop(&mut self) {} +} + +fn for_loop_dropck(v: Vec>) { + for ref mut d in v { + let y = (); + *d = D(&y); //~ ERROR `y` does not live long enough + } +} + +fn main() {} diff --git a/src/test/ui/nll/dont-print-desugared.stderr b/src/test/ui/nll/dont-print-desugared.stderr new file mode 100644 index 00000000000..45d7cbcdfbe --- /dev/null +++ b/src/test/ui/nll/dont-print-desugared.stderr @@ -0,0 +1,27 @@ +error[E0596]: cannot borrow data in a `&` reference as mutable + --> $DIR/dont-print-desugared.rs:4:10 + | +LL | for &ref mut x in s {} + | -^^^^^^^^^ + | || + | |cannot borrow as mutable through `&` reference + | help: consider changing this to be a mutable reference: `&mut ref mut x` + +error[E0597]: `y` does not live long enough + --> $DIR/dont-print-desugared.rs:17:16 + | +LL | for ref mut d in v { + | - a temporary with access to the borrow is created here ... +LL | let y = (); +LL | *d = D(&y); + | ^^ borrowed value does not live long enough +LL | } + | - + | | + | `y` dropped here while still borrowed + | ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D` + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0596, E0597. +For more information about an error, try `rustc --explain E0596`. -- cgit 1.4.1-3-g733a5 From 59a382122fb09e2a9b4629e36efbc63a321eab6a Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sat, 11 May 2019 17:41:37 +0300 Subject: Simplify use of keyword symbols --- src/librustc/hir/lowering.rs | 22 +- src/librustc/hir/map/def_collector.rs | 4 +- src/librustc/hir/map/mod.rs | 2 +- src/librustc/hir/mod.rs | 17 +- src/librustc/hir/print.rs | 10 +- src/librustc/middle/liveness.rs | 4 +- src/librustc/middle/resolve_lifetime.rs | 10 +- src/librustc/ty/context.rs | 4 +- src/librustc/ty/mod.rs | 4 +- src/librustc/ty/print/pretty.rs | 2 +- src/librustc/ty/sty.rs | 6 +- src/librustc_codegen_ssa/mir/mod.rs | 6 +- src/librustc_lint/builtin.rs | 4 +- src/librustc_lint/unused.rs | 4 +- src/librustc_macros/src/symbols.rs | 19 +- src/librustc_metadata/encoder.rs | 4 +- src/librustc_mir/borrow_check/mutability_errors.rs | 4 +- .../nll/region_infer/error_reporting/mod.rs | 4 +- .../region_infer/error_reporting/region_name.rs | 4 +- src/librustc_mir/build/mod.rs | 4 +- src/librustc_passes/ast_validation.rs | 8 +- src/librustc_privacy/lib.rs | 4 +- src/librustc_resolve/build_reduced_graph.rs | 30 +- src/librustc_resolve/diagnostics.rs | 14 +- src/librustc_resolve/lib.rs | 74 ++-- src/librustc_resolve/macros.rs | 12 +- src/librustc_resolve/resolve_imports.rs | 16 +- src/librustc_typeck/check/mod.rs | 8 +- src/librustc_typeck/collect.rs | 8 +- src/librustdoc/clean/mod.rs | 17 +- src/librustdoc/html/layout.rs | 2 +- src/libsyntax/ast.rs | 12 +- src/libsyntax/attr/mod.rs | 8 +- src/libsyntax/diagnostics/plugin.rs | 4 +- src/libsyntax/ext/base.rs | 4 +- src/libsyntax/ext/build.rs | 6 +- src/libsyntax/ext/expand.rs | 18 +- src/libsyntax/ext/placeholders.rs | 4 +- src/libsyntax/ext/tt/macro_parser.rs | 8 +- src/libsyntax/ext/tt/macro_rules.rs | 2 +- src/libsyntax/ext/tt/quoted.rs | 10 +- src/libsyntax/mut_visit.rs | 4 +- src/libsyntax/parse/literal.rs | 2 +- src/libsyntax/parse/parser.rs | 415 +++++++++++---------- src/libsyntax/parse/token.rs | 74 ++-- src/libsyntax/print/pprust.rs | 14 +- src/libsyntax/std_inject.rs | 6 +- src/libsyntax/test.rs | 6 +- src/libsyntax/util/parser.rs | 4 +- src/libsyntax_ext/deriving/clone.rs | 5 +- src/libsyntax_ext/deriving/generic/mod.rs | 8 +- src/libsyntax_ext/deriving/generic/ty.rs | 4 +- src/libsyntax_ext/env.rs | 4 +- src/libsyntax_ext/proc_macro_decls.rs | 4 +- src/libsyntax_ext/proc_macro_server.rs | 6 +- src/libsyntax_ext/trace_macros.rs | 6 +- src/libsyntax_pos/hygiene.rs | 14 +- src/libsyntax_pos/symbol.rs | 55 +-- 58 files changed, 503 insertions(+), 535 deletions(-) (limited to 'src/libsyntax/parse') diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 3ec4d4e8cc8..7cf5b4a9021 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -64,7 +64,7 @@ use syntax::ptr::P; use syntax::source_map::{respan, CompilerDesugaringKind, Spanned}; use syntax::source_map::CompilerDesugaringKind::IfTemporary; use syntax::std_inject; -use syntax::symbol::{keywords, Symbol, sym}; +use syntax::symbol::{kw, sym, Symbol}; use syntax::tokenstream::{TokenStream, TokenTree}; use syntax::parse::token::Token; use syntax::visit::{self, Visitor}; @@ -927,11 +927,11 @@ impl<'a> LoweringContext<'a> { hir::LifetimeParamKind::InBand, ), ParamName::Fresh(_) => ( - keywords::UnderscoreLifetime.name().as_interned_str(), + kw::UnderscoreLifetime.as_interned_str(), hir::LifetimeParamKind::Elided, ), ParamName::Error => ( - keywords::UnderscoreLifetime.name().as_interned_str(), + kw::UnderscoreLifetime.as_interned_str(), hir::LifetimeParamKind::Error, ), }; @@ -1415,7 +1415,7 @@ impl<'a> LoweringContext<'a> { P(hir::Path { res, segments: hir_vec![hir::PathSegment::from_ident( - keywords::SelfUpper.ident() + Ident::with_empty_ctxt(kw::SelfUpper) )], span: t.span, }), @@ -1614,7 +1614,7 @@ impl<'a> LoweringContext<'a> { trace!("registering existential type with id {:#?}", exist_ty_id); let exist_ty_item = hir::Item { hir_id: exist_ty_id, - ident: keywords::Invalid.ident(), + ident: Ident::with_empty_ctxt(kw::Invalid), attrs: Default::default(), node: exist_ty_item_kind, vis: respan(span.shrink_to_lo(), hir::VisibilityKind::Inherited), @@ -1747,7 +1747,7 @@ impl<'a> LoweringContext<'a> { let (name, kind) = match name { hir::LifetimeName::Underscore => ( - hir::ParamName::Plain(keywords::UnderscoreLifetime.ident()), + hir::ParamName::Plain(Ident::with_empty_ctxt(kw::UnderscoreLifetime)), hir::LifetimeParamKind::Elided, ), hir::LifetimeName::Param(param_name) => ( @@ -2296,7 +2296,7 @@ impl<'a> LoweringContext<'a> { .iter() .map(|arg| match arg.pat.node { PatKind::Ident(_, ident, _) => ident, - _ => Ident::new(keywords::Invalid.name(), arg.pat.span), + _ => Ident::new(kw::Invalid, arg.pat.span), }) .collect() } @@ -2585,9 +2585,9 @@ impl<'a> LoweringContext<'a> { fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime { let span = l.ident.span; match l.ident { - ident if ident.name == keywords::StaticLifetime.name() => + ident if ident.name == kw::StaticLifetime => self.new_named_lifetime(l.id, span, hir::LifetimeName::Static), - ident if ident.name == keywords::UnderscoreLifetime.name() => + ident if ident.name == kw::UnderscoreLifetime => match self.anonymous_lifetime_mode { AnonymousLifetimeMode::CreateParameter => { let fresh_name = self.collect_fresh_in_band_lifetime(span); @@ -2709,7 +2709,7 @@ impl<'a> LoweringContext<'a> { // Don't expose `Self` (recovered "keyword used as ident" parse error). // `rustc::ty` expects `Self` to be only used for a trait's `Self`. // Instead, use `gensym("Self")` to create a distinct name that looks the same. - let ident = if param.ident.name == keywords::SelfUpper.name() { + let ident = if param.ident.name == kw::SelfUpper { param.ident.gensym() } else { param.ident @@ -3325,7 +3325,7 @@ impl<'a> LoweringContext<'a> { // Correctly resolve `self` imports. if path.segments.len() > 1 - && path.segments.last().unwrap().ident.name == keywords::SelfLower.name() + && path.segments.last().unwrap().ident.name == kw::SelfLower { let _ = path.segments.pop(); if rename.is_none() { diff --git a/src/librustc/hir/map/def_collector.rs b/src/librustc/hir/map/def_collector.rs index 6e7a8f5bc23..77fd8cc062f 100644 --- a/src/librustc/hir/map/def_collector.rs +++ b/src/librustc/hir/map/def_collector.rs @@ -5,7 +5,7 @@ use crate::session::CrateDisambiguator; use syntax::ast::*; use syntax::ext::hygiene::Mark; use syntax::visit; -use syntax::symbol::keywords; +use syntax::symbol::kw; use syntax::symbol::Symbol; use syntax::parse::token::{self, Token}; use syntax_pos::Span; @@ -138,7 +138,7 @@ impl<'a> visit::Visitor<'a> for DefCollector<'a> { // information we encapsulate into, the better let def_data = match i.node { ItemKind::Impl(..) => DefPathData::Impl, - ItemKind::Mod(..) if i.ident == keywords::Invalid.ident() => { + ItemKind::Mod(..) if i.ident == Ident::with_empty_ctxt(kw::Invalid) => { return visit::walk_item(self, i); } ItemKind::Mod(..) | ItemKind::Trait(..) | ItemKind::TraitAlias(..) | diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index 23f4d208571..e5ca97b82ab 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -519,7 +519,7 @@ impl<'hir> Map<'hir> { pub fn ty_param_name(&self, id: HirId) -> Name { match self.get_by_hir_id(id) { Node::Item(&Item { node: ItemKind::Trait(..), .. }) | - Node::Item(&Item { node: ItemKind::TraitAlias(..), .. }) => keywords::SelfUpper.name(), + Node::Item(&Item { node: ItemKind::TraitAlias(..), .. }) => kw::SelfUpper, Node::GenericParam(param) => param.name.ident().name, _ => bug!("ty_param_name: {} not a type parameter", self.hir_to_string(id)), } diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index d2b926d1886..e5e6c408a06 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -24,7 +24,7 @@ use syntax::ast::{Attribute, Label, LitKind, StrStyle, FloatTy, IntTy, UintTy}; use syntax::attr::{InlineAttr, OptimizeAttr}; use syntax::ext::hygiene::SyntaxContext; use syntax::ptr::P; -use syntax::symbol::{Symbol, keywords}; +use syntax::symbol::{Symbol, kw}; use syntax::tokenstream::TokenStream; use syntax::util::parser::ExprPrecedence; use crate::ty::AdtKind; @@ -160,7 +160,7 @@ pub struct Lifetime { pub span: Span, /// Either "`'a`", referring to a named lifetime definition, - /// or "``" (i.e., `keywords::Invalid`), for elision placeholders. + /// or "``" (i.e., `kw::Invalid`), for elision placeholders. /// /// HIR lowering inserts these placeholders in type paths that /// refer to type definitions needing lifetime parameters, @@ -199,7 +199,8 @@ impl ParamName { pub fn ident(&self) -> Ident { match *self { ParamName::Plain(ident) => ident, - ParamName::Error | ParamName::Fresh(_) => keywords::UnderscoreLifetime.ident(), + ParamName::Fresh(_) | + ParamName::Error => Ident::with_empty_ctxt(kw::UnderscoreLifetime), } } @@ -233,10 +234,10 @@ pub enum LifetimeName { impl LifetimeName { pub fn ident(&self) -> Ident { match *self { - LifetimeName::Implicit => keywords::Invalid.ident(), - LifetimeName::Error => keywords::Invalid.ident(), - LifetimeName::Underscore => keywords::UnderscoreLifetime.ident(), - LifetimeName::Static => keywords::StaticLifetime.ident(), + LifetimeName::Implicit => Ident::with_empty_ctxt(kw::Invalid), + LifetimeName::Error => Ident::with_empty_ctxt(kw::Invalid), + LifetimeName::Underscore => Ident::with_empty_ctxt(kw::UnderscoreLifetime), + LifetimeName::Static => Ident::with_empty_ctxt(kw::StaticLifetime), LifetimeName::Param(param_name) => param_name.ident(), } } @@ -305,7 +306,7 @@ pub struct Path { impl Path { pub fn is_global(&self) -> bool { - !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name() + !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot } } diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index 8a9028e5443..60511ecc883 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -7,7 +7,7 @@ use syntax::print::pp::{self, Breaks}; use syntax::print::pp::Breaks::{Consistent, Inconsistent}; use syntax::print::pprust::{self, PrintState}; use syntax::ptr::P; -use syntax::symbol::keywords; +use syntax::symbol::kw; use syntax::util::parser::{self, AssocOp, Fixity}; use syntax_pos::{self, BytePos, FileName}; @@ -798,7 +798,7 @@ impl<'a> State<'a> { hir::VisibilityKind::Restricted { ref path, .. } => { self.s.word("pub(")?; if path.segments.len() == 1 && - path.segments[0].ident.name == keywords::Super.name() { + path.segments[0].ident.name == kw::Super { // Special case: `super` can print like `pub(super)`. self.s.word("super")?; } else { @@ -1559,7 +1559,7 @@ impl<'a> State<'a> { if i > 0 { self.s.word("::")? } - if segment.ident.name != keywords::PathRoot.name() { + if segment.ident.name != kw::PathRoot { self.print_ident(segment.ident)?; segment.with_generic_args(|generic_args| { self.print_generic_args(generic_args, segment.infer_types, @@ -1572,7 +1572,7 @@ impl<'a> State<'a> { } pub fn print_path_segment(&mut self, segment: &hir::PathSegment) -> io::Result<()> { - if segment.ident.name != keywords::PathRoot.name() { + if segment.ident.name != kw::PathRoot { self.print_ident(segment.ident)?; segment.with_generic_args(|generic_args| { self.print_generic_args(generic_args, segment.infer_types, false) @@ -1599,7 +1599,7 @@ impl<'a> State<'a> { if i > 0 { self.s.word("::")? } - if segment.ident.name != keywords::PathRoot.name() { + if segment.ident.name != kw::PathRoot { self.print_ident(segment.ident)?; segment.with_generic_args(|generic_args| { self.print_generic_args(generic_args, diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index cb333b5b0cb..91a19852c6c 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -112,7 +112,7 @@ use std::io; use std::rc::Rc; use syntax::ast::{self, NodeId}; use syntax::ptr::P; -use syntax::symbol::{keywords, sym}; +use syntax::symbol::{kw, sym}; use syntax_pos::Span; use crate::hir; @@ -1552,7 +1552,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { let sp = ident.span; let var = self.variable(hir_id, sp); // Ignore unused self. - if ident.name != keywords::SelfLower.name() { + if ident.name != kw::SelfLower { if !self.warn_about_unused(vec![sp], hir_id, entry_ln, var) { if self.live_on_entry(entry_ln, var).is_none() { self.report_dead_assign(hir_id, sp, var, true); diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 2402d0eefde..6a4d2e0966b 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -23,7 +23,7 @@ use std::mem::replace; use syntax::ast; use syntax::attr; use syntax::ptr::P; -use syntax::symbol::{keywords, sym}; +use syntax::symbol::{kw, sym}; use syntax_pos::Span; use crate::hir::intravisit::{self, NestedVisitorMap, Visitor}; @@ -711,7 +711,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { GenericParamKind::Lifetime { .. } => { let (name, reg) = Region::early(&self.tcx.hir(), &mut index, ¶m); if let hir::ParamName::Plain(param_name) = name { - if param_name.name == keywords::UnderscoreLifetime.name() { + if param_name.name == kw::UnderscoreLifetime { // Pick the elided lifetime "definition" if one exists // and use it to make an elision scope. elision = Some(reg); @@ -1602,7 +1602,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } { debug!("id = {:?} span = {:?} name = {:?}", id, span, name); - if name == keywords::UnderscoreLifetime.ident() { + if name == ast::Ident::with_empty_ctxt(kw::UnderscoreLifetime) { continue; } @@ -2525,8 +2525,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() { if let hir::ParamName::Plain(_) = lifetime_i_name { let name = lifetime_i_name.ident().name; - if name == keywords::UnderscoreLifetime.name() - || name == keywords::StaticLifetime.name() + if name == kw::UnderscoreLifetime + || name == kw::StaticLifetime { let mut err = struct_span_err!( self.tcx.sess, diff --git a/src/librustc/ty/context.rs b/src/librustc/ty/context.rs index c9fee02f66b..b5a17684c0f 100644 --- a/src/librustc/ty/context.rs +++ b/src/librustc/ty/context.rs @@ -74,7 +74,7 @@ use syntax::ast; use syntax::attr; use syntax::source_map::MultiSpan; use syntax::feature_gate; -use syntax::symbol::{Symbol, keywords, InternedString, sym}; +use syntax::symbol::{Symbol, InternedString, kw, sym}; use syntax_pos::Span; use crate::hir; @@ -2735,7 +2735,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { #[inline] pub fn mk_self_type(self) -> Ty<'tcx> { - self.mk_ty_param(0, keywords::SelfUpper.name().as_interned_str()) + self.mk_ty_param(0, kw::SelfUpper.as_interned_str()) } pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> Kind<'tcx> { diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs index 4d242265e61..a2c89489b95 100644 --- a/src/librustc/ty/mod.rs +++ b/src/librustc/ty/mod.rs @@ -47,7 +47,7 @@ use std::ops::Range; use syntax::ast::{self, Name, Ident, NodeId}; use syntax::attr; use syntax::ext::hygiene::Mark; -use syntax::symbol::{keywords, sym, Symbol, LocalInternedString, InternedString}; +use syntax::symbol::{kw, sym, Symbol, LocalInternedString, InternedString}; use syntax_pos::Span; use smallvec; @@ -835,7 +835,7 @@ impl ty::EarlyBoundRegion { /// Does this early bound region have a name? Early bound regions normally /// always have names except when using anonymous lifetimes (`'_`). pub fn has_name(&self) -> bool { - self.name != keywords::UnderscoreLifetime.name().as_interned_str() + self.name != kw::UnderscoreLifetime.as_interned_str() } } diff --git a/src/librustc/ty/print/pretty.rs b/src/librustc/ty/print/pretty.rs index c18852a832f..5199da8fbbc 100644 --- a/src/librustc/ty/print/pretty.rs +++ b/src/librustc/ty/print/pretty.rs @@ -980,7 +980,7 @@ impl Printer<'gcx, 'tcx> for FmtPrinter<'_, 'gcx, 'tcx, F> { if self.tcx.sess.rust_2018() { // We add the `crate::` keyword on Rust 2018, only when desired. if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) { - write!(self, "{}", keywords::Crate.name())?; + write!(self, "{}", kw::Crate)?; self.empty_path = false; } } diff --git a/src/librustc/ty/sty.rs b/src/librustc/ty/sty.rs index e8f3bad4d3e..0b5a6fce5cb 100644 --- a/src/librustc/ty/sty.rs +++ b/src/librustc/ty/sty.rs @@ -22,7 +22,7 @@ use std::marker::PhantomData; use std::ops::Range; use rustc_target::spec::abi; use syntax::ast::{self, Ident}; -use syntax::symbol::{keywords, InternedString}; +use syntax::symbol::{kw, InternedString}; use serialize; use self::InferTy::*; @@ -1121,7 +1121,7 @@ impl<'a, 'gcx, 'tcx> ParamTy { } pub fn for_self() -> ParamTy { - ParamTy::new(0, keywords::SelfUpper.name().as_interned_str()) + ParamTy::new(0, kw::SelfUpper.as_interned_str()) } pub fn for_def(def: &ty::GenericParamDef) -> ParamTy { @@ -1136,7 +1136,7 @@ impl<'a, 'gcx, 'tcx> ParamTy { // FIXME(#50125): Ignoring `Self` with `index != 0` might lead to weird behavior elsewhere, // but this should only be possible when using `-Z continue-parse-after-error` like // `compile-fail/issue-36638.rs`. - self.name.as_symbol() == keywords::SelfUpper.name() && self.index == 0 + self.name.as_symbol() == kw::SelfUpper && self.index == 0 } } diff --git a/src/librustc_codegen_ssa/mir/mod.rs b/src/librustc_codegen_ssa/mir/mod.rs index 060d7d18625..fed12c9a29f 100644 --- a/src/librustc_codegen_ssa/mir/mod.rs +++ b/src/librustc_codegen_ssa/mir/mod.rs @@ -10,7 +10,7 @@ use crate::debuginfo::{self, VariableAccess, VariableKind, FunctionDebugContext} use crate::traits::*; use syntax_pos::{DUMMY_SP, NO_EXPANSION, BytePos, Span}; -use syntax::symbol::keywords; +use syntax::symbol::kw; use std::iter; @@ -496,7 +496,7 @@ fn arg_local_refs<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>( }; bx.declare_local( &fx.debug_context, - arg_decl.name.unwrap_or(keywords::Invalid.name()), + arg_decl.name.unwrap_or(kw::Invalid), arg_ty, scope, variable_access, VariableKind::ArgumentVariable(arg_index + 1), @@ -613,7 +613,7 @@ fn arg_local_refs<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>( bx.declare_local( &fx.debug_context, - arg_decl.name.unwrap_or(keywords::Invalid.name()), + arg_decl.name.unwrap_or(kw::Invalid), arg.layout.ty, scope, variable_access, diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index d17a92efb06..d52e497cf63 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -42,7 +42,7 @@ use syntax::edition::Edition; use syntax::feature_gate::{AttributeGate, AttributeTemplate, AttributeType}; use syntax::feature_gate::{Stability, deprecated_attributes}; use syntax_pos::{BytePos, Span, SyntaxContext}; -use syntax::symbol::{Symbol, keywords, sym}; +use syntax::symbol::{Symbol, kw, sym}; use syntax::errors::{Applicability, DiagnosticBuilder}; use syntax::print::pprust::expr_to_string; use syntax::visit::FnKind; @@ -607,7 +607,7 @@ impl EarlyLintPass for AnonymousParameters { for arg in sig.decl.inputs.iter() { match arg.pat.node { ast::PatKind::Ident(_, ident, None) => { - if ident.name == keywords::Invalid.name() { + if ident.name == kw::Invalid { let ty_snip = cx .sess .source_map() diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index c3dfd44ad85..34f7e04c164 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -12,7 +12,7 @@ use syntax::attr; use syntax::errors::Applicability; use syntax::feature_gate::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP}; use syntax::print::pprust; -use syntax::symbol::{keywords, sym}; +use syntax::symbol::{kw, sym}; use syntax::symbol::Symbol; use syntax::util::parser; use syntax_pos::Span; @@ -455,7 +455,7 @@ impl UnusedImportBraces { match items[0].0.kind { ast::UseTreeKind::Simple(rename, ..) => { let orig_ident = items[0].0.prefix.segments.last().unwrap().ident; - if orig_ident.name == keywords::SelfLower.name() { + if orig_ident.name == kw::SelfLower { return; } node_ident = rename.unwrap_or(orig_ident); diff --git a/src/librustc_macros/src/symbols.rs b/src/librustc_macros/src/symbols.rs index a4c7daf088f..3883682fa9d 100644 --- a/src/librustc_macros/src/symbols.rs +++ b/src/librustc_macros/src/symbols.rs @@ -97,7 +97,6 @@ pub fn symbols(input: TokenStream) -> TokenStream { let mut keyword_stream = quote! {}; let mut symbols_stream = quote! {}; let mut prefill_stream = quote! {}; - let mut from_str_stream = quote! {}; let mut counter = 0u32; let mut keys = HashSet::::new(); @@ -115,12 +114,7 @@ pub fn symbols(input: TokenStream) -> TokenStream { #value, }); keyword_stream.extend(quote! { - pub const #name: Keyword = Keyword { - ident: Ident::with_empty_ctxt(super::Symbol::new(#counter)) - }; - }); - from_str_stream.extend(quote! { - #value => Ok(#name), + pub const #name: Symbol = Symbol::new(#counter); }); counter += 1; } @@ -145,17 +139,6 @@ pub fn symbols(input: TokenStream) -> TokenStream { macro_rules! keywords { () => { #keyword_stream - - impl std::str::FromStr for Keyword { - type Err = (); - - fn from_str(s: &str) -> Result { - match s { - #from_str_stream - _ => Err(()), - } - } - } } } diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index 7f0993e799f..dfc3439fc55 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -33,7 +33,7 @@ use std::u32; use syntax::ast; use syntax::attr; use syntax::source_map::Spanned; -use syntax::symbol::{keywords, sym}; +use syntax::symbol::{kw, sym}; use syntax_pos::{self, FileName, SourceFile, Span}; use log::{debug, trace}; @@ -1042,7 +1042,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> { self.lazy_seq(body.arguments.iter().map(|arg| { match arg.pat.node { PatKind::Binding(_, _, ident, _) => ident.name, - _ => keywords::Invalid.name(), + _ => kw::Invalid, } })) }) diff --git a/src/librustc_mir/borrow_check/mutability_errors.rs b/src/librustc_mir/borrow_check/mutability_errors.rs index 32088ff9f61..4bee7f9c4bf 100644 --- a/src/librustc_mir/borrow_check/mutability_errors.rs +++ b/src/librustc_mir/borrow_check/mutability_errors.rs @@ -8,7 +8,7 @@ use rustc::mir::{Terminator, TerminatorKind}; use rustc::ty::{self, Const, DefIdTree, Ty, TyS, TyCtxt}; use rustc_data_structures::indexed_vec::Idx; use syntax_pos::Span; -use syntax_pos::symbol::keywords; +use syntax_pos::symbol::kw; use crate::dataflow::move_paths::InitLocation; use crate::borrow_check::MirBorrowckCtxt; @@ -256,7 +256,7 @@ impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> { // Deliberately fall into this case for all implicit self types, // so that we don't fall in to the next case with them. *kind == mir::ImplicitSelfKind::MutRef - } else if Some(keywords::SelfLower.name()) == local_decl.name { + } else if Some(kw::SelfLower) == local_decl.name { // Otherwise, check if the name is the self kewyord - in which case // we have an explicit self. Do the same thing in this case and check // for a `self: &mut Self` to suggest removing the `&mut`. diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs index 00e81ee0491..18ca105070e 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs @@ -15,7 +15,7 @@ use rustc_data_structures::indexed_vec::IndexVec; use rustc_errors::{Diagnostic, DiagnosticBuilder}; use std::collections::VecDeque; use syntax::errors::Applicability; -use syntax::symbol::keywords; +use syntax::symbol::kw; use syntax_pos::Span; mod region_name; @@ -631,7 +631,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { "add_static_impl_trait_suggestion: has_static_predicate={:?}", has_static_predicate ); - let static_str = keywords::StaticLifetime.name(); + let static_str = kw::StaticLifetime; // If there is a static predicate, then the only sensible suggestion is to replace // fr with `'static`. if has_static_predicate { diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs index 4d8acd241ac..f3cfc1a59a9 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs @@ -12,7 +12,7 @@ use rustc::ty::subst::{SubstsRef, UnpackedKind}; use rustc::ty::{self, RegionKind, RegionVid, Ty, TyCtxt}; use rustc::ty::print::RegionHighlightMode; use rustc_errors::DiagnosticBuilder; -use syntax::symbol::keywords; +use syntax::symbol::kw; use syntax_pos::Span; use syntax_pos::symbol::InternedString; @@ -216,7 +216,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { } ty::ReStatic => Some(RegionName { - name: keywords::StaticLifetime.name().as_interned_str(), + name: kw::StaticLifetime.as_interned_str(), source: RegionNameSource::Static }), diff --git a/src/librustc_mir/build/mod.rs b/src/librustc_mir/build/mod.rs index e46c5153555..199b0176601 100644 --- a/src/librustc_mir/build/mod.rs +++ b/src/librustc_mir/build/mod.rs @@ -20,7 +20,7 @@ use std::mem; use std::u32; use rustc_target::spec::abi::Abi; use syntax::attr::{self, UnwindAttr}; -use syntax::symbol::keywords; +use syntax::symbol::kw; use syntax_pos::Span; use super::lints; @@ -660,7 +660,7 @@ fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>, ty::UpvarCapture::ByRef(..) => true, }; let mut debuginfo = UpvarDebuginfo { - debug_name: keywords::Invalid.name(), + debug_name: kw::Invalid, by_ref, }; let mut mutability = Mutability::Not; diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index 2bea1db841a..3091570d148 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -15,7 +15,7 @@ use rustc_data_structures::fx::FxHashMap; use syntax::ast::*; use syntax::attr; use syntax::source_map::Spanned; -use syntax::symbol::{keywords, sym}; +use syntax::symbol::{kw, sym}; use syntax::ptr::P; use syntax::visit::{self, Visitor}; use syntax::{span_err, struct_span_err, walk_list}; @@ -177,9 +177,9 @@ impl<'a> AstValidator<'a> { } fn check_lifetime(&self, ident: Ident) { - let valid_names = [keywords::UnderscoreLifetime.name(), - keywords::StaticLifetime.name(), - keywords::Invalid.name()]; + let valid_names = [kw::UnderscoreLifetime, + kw::StaticLifetime, + kw::Invalid]; if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() { self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names"); } diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index cd21713cddf..1df42a95042 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -27,7 +27,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::sync::Lrc; use syntax::ast::Ident; use syntax::attr; -use syntax::symbol::{keywords, sym}; +use syntax::symbol::{kw, sym}; use syntax_pos::Span; use std::{cmp, fmt, mem}; @@ -844,7 +844,7 @@ impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> { span: Span, // span of the field pattern, e.g., `x: 0` def: &'tcx ty::AdtDef, // definition of the struct or enum field: &'tcx ty::FieldDef) { // definition of the field - let ident = Ident::new(keywords::Invalid.name(), use_ctxt); + let ident = Ident::new(kw::Invalid, use_ctxt); let current_hir = self.current_item; let def_id = self.tcx.adjust_ident(ident, def.did, current_hir).1; if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) { diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index 3b58a99d19f..782f36a77da 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -37,7 +37,7 @@ use syntax::feature_gate::is_builtin_attr; use syntax::parse::token::{self, Token}; use syntax::span_err; use syntax::std_inject::injected_crate_name; -use syntax::symbol::{keywords, sym}; +use syntax::symbol::{kw, sym}; use syntax::visit::{self, Visitor}; use syntax_pos::{Span, DUMMY_SP}; @@ -143,7 +143,7 @@ impl<'a> Resolver<'a> { } _ => None, }.map(|ctxt| Segment::from_ident(Ident::new( - keywords::PathRoot.name(), use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt) + kw::PathRoot, use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt) ))); let prefix = crate_root.into_iter().chain(prefix_iter).collect::>(); @@ -151,7 +151,7 @@ impl<'a> Resolver<'a> { let empty_for_self = |prefix: &[Segment]| { prefix.is_empty() || - prefix.len() == 1 && prefix[0].ident.name == keywords::PathRoot.name() + prefix.len() == 1 && prefix[0].ident.name == kw::PathRoot }; match use_tree.kind { ast::UseTreeKind::Simple(rename, ..) => { @@ -162,7 +162,7 @@ impl<'a> Resolver<'a> { if nested { // Correctly handle `self` - if source.ident.name == keywords::SelfLower.name() { + if source.ident.name == kw::SelfLower { type_ns_only = true; if empty_for_self(&module_path) { @@ -183,14 +183,14 @@ impl<'a> Resolver<'a> { } } else { // Disallow `self` - if source.ident.name == keywords::SelfLower.name() { + if source.ident.name == kw::SelfLower { resolve_error(self, use_tree.span, ResolutionError::SelfImportsOnlyAllowedWithin); } // Disallow `use $crate;` - if source.ident.name == keywords::DollarCrate.name() && module_path.is_empty() { + if source.ident.name == kw::DollarCrate && module_path.is_empty() { let crate_root = self.resolve_crate_root(source.ident); let crate_name = match crate_root.kind { ModuleKind::Def(.., name) => name, @@ -199,11 +199,11 @@ impl<'a> Resolver<'a> { // HACK(eddyb) unclear how good this is, but keeping `$crate` // in `source` breaks `src/test/compile-fail/import-crate-var.rs`, // while the current crate doesn't have a valid `crate_name`. - if crate_name != keywords::Invalid.name() { + if crate_name != kw::Invalid { // `crate_name` should not be interpreted as relative. module_path.push(Segment { ident: Ident { - name: keywords::PathRoot.name(), + name: kw::PathRoot, span: source.ident.span, }, id: Some(self.session.next_node_id()), @@ -221,7 +221,7 @@ impl<'a> Resolver<'a> { } } - if ident.name == keywords::Crate.name() { + if ident.name == kw::Crate { self.session.span_err(ident.span, "crate root imports need to be explicitly named: \ `use crate as name;`"); @@ -276,7 +276,7 @@ impl<'a> Resolver<'a> { // Ensure there is at most one `self` in the list let self_spans = items.iter().filter_map(|&(ref use_tree, _)| { if let ast::UseTreeKind::Simple(..) = use_tree.kind { - if use_tree.ident().name == keywords::SelfLower.name() { + if use_tree.ident().name == kw::SelfLower { return Some(use_tree.span); } } @@ -311,7 +311,7 @@ impl<'a> Resolver<'a> { let new_span = prefix[prefix.len() - 1].ident.span; let tree = ast::UseTree { prefix: ast::Path::from_ident( - Ident::new(keywords::SelfLower.name(), new_span) + Ident::new(kw::SelfLower, new_span) ), kind: ast::UseTreeKind::Simple( Some(Ident::from_str_and_span("__dummy", new_span).gensym()), @@ -350,7 +350,7 @@ impl<'a> Resolver<'a> { } ItemKind::ExternCrate(orig_name) => { - let module = if orig_name.is_none() && ident.name == keywords::SelfLower.name() { + let module = if orig_name.is_none() && ident.name == kw::SelfLower { self.session .struct_span_err(item.span, "`extern crate self;` requires renaming") .span_suggestion( @@ -361,7 +361,7 @@ impl<'a> Resolver<'a> { ) .emit(); return; - } else if orig_name == Some(keywords::SelfLower.name()) { + } else if orig_name == Some(kw::SelfLower) { self.graph_root } else { let crate_id = self.crate_loader.process_extern_crate(item, &self.definitions); @@ -420,7 +420,7 @@ impl<'a> Resolver<'a> { ItemKind::GlobalAsm(..) => {} - ItemKind::Mod(..) if ident == keywords::Invalid.ident() => {} // Crate root + ItemKind::Mod(..) if ident == Ident::with_empty_ctxt(kw::Invalid) => {} // Crate root ItemKind::Mod(..) => { let def_id = self.definitions.local_def_id(item.id); @@ -831,7 +831,7 @@ impl<'a> Resolver<'a> { "an `extern crate` loading macros must be at the crate root"); } if let ItemKind::ExternCrate(Some(orig_name)) = item.node { - if orig_name == keywords::SelfLower.name() { + if orig_name == kw::SelfLower { self.session.span_err(attr.span, "`macro_use` is not supported on `extern crate self`"); } diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index 509aa95bb61..730927d2bb5 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -7,7 +7,7 @@ use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId}; use rustc::session::{Session, config::nightly_options}; use syntax::ast::{self, Expr, ExprKind, Ident}; use syntax::ext::base::MacroKind; -use syntax::symbol::{Symbol, keywords}; +use syntax::symbol::{Symbol, kw}; use syntax_pos::{BytePos, Span}; type Res = def::Res; @@ -48,7 +48,7 @@ impl<'a> Resolver<'a> { let item_span = path.last().unwrap().ident.span; let (mod_prefix, mod_str) = if path.len() == 1 { (String::new(), "this scope".to_string()) - } else if path.len() == 2 && path[0].ident.name == keywords::PathRoot.name() { + } else if path.len() == 2 && path[0].ident.name == kw::PathRoot { (String::new(), "the crate root".to_string()) } else { let mod_path = &path[..path.len() - 1]; @@ -454,13 +454,13 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { match (path.get(0), path.get(1)) { // `{{root}}::ident::...` on both editions. // On 2015 `{{root}}` is usually added implicitly. - (Some(fst), Some(snd)) if fst.ident.name == keywords::PathRoot.name() && + (Some(fst), Some(snd)) if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {} // `ident::...` on 2018. (Some(fst), _) if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() => { // Insert a placeholder that's later replaced by `self`/`super`/etc. - path.insert(0, Segment::from_ident(keywords::Invalid.ident())); + path.insert(0, Segment::from_ident(Ident::with_empty_ctxt(kw::Invalid))); } _ => return None, } @@ -485,7 +485,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { parent_scope: &ParentScope<'b>, ) -> Option<(Vec, Vec)> { // Replace first ident with `self` and check if that is valid. - path[0].ident.name = keywords::SelfLower.name(); + path[0].ident.name = kw::SelfLower; let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No); debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result); if let PathResult::Module(..) = result { @@ -509,7 +509,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { parent_scope: &ParentScope<'b>, ) -> Option<(Vec, Vec)> { // Replace first ident with `crate` and check if that is valid. - path[0].ident.name = keywords::Crate.name(); + path[0].ident.name = kw::Crate; let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No); debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result); if let PathResult::Module(..) = result { @@ -540,7 +540,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { parent_scope: &ParentScope<'b>, ) -> Option<(Vec, Vec)> { // Replace first ident with `crate` and check if that is valid. - path[0].ident.name = keywords::Super.name(); + path[0].ident.name = kw::Super; let result = self.resolve_path(&path, None, parent_scope, false, span, CrateLint::No); debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result); if let PathResult::Module(..) = result { diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index c4a4dd30605..748cf691f8d 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -43,7 +43,7 @@ use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy}; use syntax::ext::base::SyntaxExtension; use syntax::ext::base::Determinacy::{self, Determined, Undetermined}; use syntax::ext::base::MacroKind; -use syntax::symbol::{Symbol, keywords, sym}; +use syntax::symbol::{Symbol, kw, sym}; use syntax::util::lev_distance::find_best_match_for_name; use syntax::visit::{self, FnKind, Visitor}; @@ -820,7 +820,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> { self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type); } TyKind::ImplicitSelf => { - let self_ty = keywords::SelfUpper.ident(); + let self_ty = Ident::with_empty_ctxt(kw::SelfUpper); let res = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span) .map_or(Res::Err, |d| d.res()); self.record_partial_res(ty.id, PartialRes::new(res)); @@ -1817,18 +1817,17 @@ impl<'a> hir::lowering::Resolver for Resolver<'a> { is_value: bool ) -> hir::Path { let root = if crate_root.is_some() { - keywords::PathRoot + kw::PathRoot } else { - keywords::Crate + kw::Crate }; - let segments = iter::once(root.ident()) + let segments = iter::once(Ident::with_empty_ctxt(root)) .chain( crate_root.into_iter() .chain(components.iter().cloned()) .map(Ident::with_empty_ctxt) ).map(|i| self.new_ast_path_segment(i)).collect::>(); - let path = ast::Path { span, segments, @@ -1866,7 +1865,7 @@ impl<'a> Resolver<'a> { let path = if path_str.starts_with("::") { ast::Path { span, - segments: iter::once(keywords::PathRoot.ident()) + segments: iter::once(Ident::with_empty_ctxt(kw::PathRoot)) .chain({ path_str.split("::").skip(1).map(Ident::from_str) }) @@ -1961,7 +1960,7 @@ impl<'a> Resolver<'a> { let root_module_kind = ModuleKind::Def( DefKind::Mod, root_def_id, - keywords::Invalid.name(), + kw::Invalid, ); let graph_root = arenas.alloc_module(ModuleData { no_implicit_prelude: attr::contains_name(&krate.attrs, sym::no_implicit_prelude), @@ -2187,10 +2186,10 @@ impl<'a> Resolver<'a> { path_span: Span) -> Option> { assert!(ns == TypeNS || ns == ValueNS); - if ident.name == keywords::Invalid.name() { + if ident.name == kw::Invalid { return Some(LexicalScopeBinding::Res(Res::Err)); } - ident.span = if ident.name == keywords::SelfUpper.name() { + ident.span = if ident.name == kw::SelfUpper { // FIXME(jseyfried) improve `Self` hygiene ident.span.with_ctxt(SyntaxContext::empty()) } else if ns == TypeNS { @@ -2405,7 +2404,7 @@ impl<'a> Resolver<'a> { fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> { let mut ctxt = ident.span.ctxt(); - let mark = if ident.name == keywords::DollarCrate.name() { + let mark = if ident.name == kw::DollarCrate { // When resolving `$crate` from a `macro_rules!` invoked in a `macro`, // we don't want to pretend that the `macro_rules!` definition is in the `macro` // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks. @@ -2851,7 +2850,7 @@ impl<'a> Resolver<'a> { let mut self_type_rib = Rib::new(NormalRibKind); // Plain insert (no renaming, since types are not currently hygienic) - self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_res); + self_type_rib.bindings.insert(Ident::with_empty_ctxt(kw::SelfUpper), self_res); self.ribs[TypeNS].push(self_type_rib); f(self); self.ribs[TypeNS].pop(); @@ -2862,7 +2861,7 @@ impl<'a> Resolver<'a> { { let self_res = Res::SelfCtor(impl_id); let mut self_type_rib = Rib::new(NormalRibKind); - self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_res); + self_type_rib.bindings.insert(Ident::with_empty_ctxt(kw::SelfUpper), self_res); self.ribs[ValueNS].push(self_type_rib); f(self); self.ribs[ValueNS].pop(); @@ -3199,7 +3198,7 @@ impl<'a> Resolver<'a> { } None => { // A completely fresh binding, add to the lists if it's valid. - if ident.name != keywords::Invalid.name() { + if ident.name != kw::Invalid { bindings.insert(ident, outer_pat_id); self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, res); } @@ -3494,13 +3493,13 @@ impl<'a> Resolver<'a> { } fn self_type_is_available(&mut self, span: Span) -> bool { - let binding = self.resolve_ident_in_lexical_scope(keywords::SelfUpper.ident(), + let binding = self.resolve_ident_in_lexical_scope(Ident::with_empty_ctxt(kw::SelfUpper), TypeNS, None, span); if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false } } fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool { - let ident = Ident::new(keywords::SelfLower.name(), self_span); + let ident = Ident::new(kw::SelfLower, self_span); let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span); if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false } } @@ -3657,8 +3656,8 @@ impl<'a> Resolver<'a> { }; if path.len() > 1 && !global_by_default && result.base_res() != Res::Err && - path[0].ident.name != keywords::PathRoot.name() && - path[0].ident.name != keywords::DollarCrate.name() { + path[0].ident.name != kw::PathRoot && + path[0].ident.name != kw::DollarCrate { let unqualified_result = { match self.resolve_path_without_parent_scope( &[*path.last().unwrap()], @@ -3739,11 +3738,11 @@ impl<'a> Resolver<'a> { let name = ident.name; allow_super &= ns == TypeNS && - (name == keywords::SelfLower.name() || - name == keywords::Super.name()); + (name == kw::SelfLower || + name == kw::Super); if ns == TypeNS { - if allow_super && name == keywords::Super.name() { + if allow_super && name == kw::Super { let mut ctxt = ident.span.ctxt().modern(); let self_module = match i { 0 => Some(self.resolve_self(&mut ctxt, self.current_module)), @@ -3768,25 +3767,25 @@ impl<'a> Resolver<'a> { }; } if i == 0 { - if name == keywords::SelfLower.name() { + if name == kw::SelfLower { let mut ctxt = ident.span.ctxt().modern(); module = Some(ModuleOrUniformRoot::Module( self.resolve_self(&mut ctxt, self.current_module))); continue; } - if name == keywords::PathRoot.name() && ident.span.rust_2018() { + if name == kw::PathRoot && ident.span.rust_2018() { module = Some(ModuleOrUniformRoot::ExternPrelude); continue; } - if name == keywords::PathRoot.name() && + if name == kw::PathRoot && ident.span.rust_2015() && self.session.rust_2018() { // `::a::b` from 2015 macro on 2018 global edition module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude); continue; } - if name == keywords::PathRoot.name() || - name == keywords::Crate.name() || - name == keywords::DollarCrate.name() { + if name == kw::PathRoot || + name == kw::Crate || + name == kw::DollarCrate { // `::a::b`, `crate::a::b` or `$crate::a::b` module = Some(ModuleOrUniformRoot::Module( self.resolve_crate_root(ident))); @@ -3797,12 +3796,12 @@ impl<'a> Resolver<'a> { // Report special messages for path segment keywords in wrong positions. if ident.is_path_segment_keyword() && i != 0 { - let name_str = if name == keywords::PathRoot.name() { + let name_str = if name == kw::PathRoot { "crate root".to_string() } else { format!("`{}`", name) }; - let label = if i == 1 && path[0].ident.name == keywords::PathRoot.name() { + let label = if i == 1 && path[0].ident.name == kw::PathRoot { format!("global paths cannot start with {}", name_str) } else { format!("{} in paths can only be used in start position", name_str) @@ -3971,13 +3970,13 @@ impl<'a> Resolver<'a> { // We're only interested in `use` paths which should start with // `{{root}}` currently. - if first_name != keywords::PathRoot.name() { + if first_name != kw::PathRoot { return } match path.get(1) { // If this import looks like `crate::...` it's already good - Some(Segment { ident, .. }) if ident.name == keywords::Crate.name() => return, + Some(Segment { ident, .. }) if ident.name == kw::Crate => return, // Otherwise go below to see if it's an extern crate Some(_) => {} // If the path has length one (and it's `PathRoot` most likely) @@ -4670,7 +4669,7 @@ impl<'a> Resolver<'a> { { let mut candidates = Vec::new(); let mut seen_modules = FxHashSet::default(); - let not_local_module = crate_name != keywords::Crate.ident(); + let not_local_module = crate_name != Ident::with_empty_ctxt(kw::Crate); let mut worklist = vec![(start_module, Vec::::new(), not_local_module)]; while let Some((in_module, @@ -4764,7 +4763,8 @@ impl<'a> Resolver<'a> { where FilterFn: Fn(Res) -> bool { let mut suggestions = self.lookup_import_candidates_from_module( - lookup_ident, namespace, self.graph_root, keywords::Crate.ident(), &filter_fn); + lookup_ident, namespace, self.graph_root, Ident::with_empty_ctxt(kw::Crate), &filter_fn + ); if lookup_ident.span.rust_2018() { let extern_prelude_names = self.extern_prelude.clone(); @@ -4883,7 +4883,7 @@ impl<'a> Resolver<'a> { } else { let ctxt = ident.span.ctxt(); Some(Segment::from_ident(Ident::new( - keywords::PathRoot.name(), path.span.shrink_to_lo().with_ctxt(ctxt) + kw::PathRoot, path.span.shrink_to_lo().with_ctxt(ctxt) ))) }; @@ -5352,17 +5352,17 @@ impl<'a> Resolver<'a> { } fn is_self_type(path: &[Segment], namespace: Namespace) -> bool { - namespace == TypeNS && path.len() == 1 && path[0].ident.name == keywords::SelfUpper.name() + namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper } fn is_self_value(path: &[Segment], namespace: Namespace) -> bool { - namespace == ValueNS && path.len() == 1 && path[0].ident.name == keywords::SelfLower.name() + namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower } fn names_to_string(idents: &[Ident]) -> String { let mut result = String::new(); for (i, ident) in idents.iter() - .filter(|ident| ident.name != keywords::PathRoot.name()) + .filter(|ident| ident.name != kw::PathRoot) .enumerate() { if i > 0 { result.push_str("::"); diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index d07f7b65275..9bb607a2cc2 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -22,7 +22,7 @@ use syntax::ext::tt::macro_rules; use syntax::feature_gate::{ feature_err, is_builtin_attr_name, AttributeGate, GateIssue, Stability, BUILTIN_ATTRIBUTES, }; -use syntax::symbol::{Symbol, keywords, sym}; +use syntax::symbol::{Symbol, kw, sym}; use syntax::visit::Visitor; use syntax::util::lev_distance::find_best_match_for_name; use syntax_pos::{Span, DUMMY_SP}; @@ -137,10 +137,10 @@ impl<'a> base::Resolver for Resolver<'a> { } impl<'a> Visitor<'a> for ResolveDollarCrates<'a, '_> { fn visit_ident(&mut self, ident: Ident) { - if ident.name == keywords::DollarCrate.name() { + if ident.name == kw::DollarCrate { let name = match self.resolver.resolve_crate_root(ident).kind { - ModuleKind::Def(.., name) if name != keywords::Invalid.name() => name, - _ => keywords::Crate.name(), + ModuleKind::Def(.., name) if name != kw::Invalid => name, + _ => kw::Crate, }; ident.span.ctxt().set_dollar_crate_name(name); } @@ -415,7 +415,7 @@ impl<'a> Resolver<'a> { if kind == MacroKind::Bang && path.len() == 1 && path[0].ident.span.ctxt().outer().expn_info() .map_or(false, |info| info.local_inner_macros) { - let root = Ident::new(keywords::DollarCrate.name(), path[0].ident.span); + let root = Ident::new(kw::DollarCrate, path[0].ident.span); path.insert(0, Segment::from_ident(root)); } @@ -613,7 +613,7 @@ impl<'a> Resolver<'a> { _ => Err(Determinacy::Determined), } WhereToResolve::CrateRoot => { - let root_ident = Ident::new(keywords::PathRoot.name(), orig_ident.span); + let root_ident = Ident::new(kw::PathRoot, orig_ident.span); let root_module = self.resolve_crate_root(root_ident); let binding = self.resolve_ident_in_module_ext( ModuleOrUniformRoot::Module(root_module), diff --git a/src/librustc_resolve/resolve_imports.rs b/src/librustc_resolve/resolve_imports.rs index 3a6a8b56ff3..ab873ea2701 100644 --- a/src/librustc_resolve/resolve_imports.rs +++ b/src/librustc_resolve/resolve_imports.rs @@ -29,7 +29,7 @@ use rustc::{bug, span_bug}; use syntax::ast::{self, Ident, Name, NodeId, CRATE_NODE_ID}; use syntax::ext::base::Determinacy::{self, Determined, Undetermined}; use syntax::ext::hygiene::Mark; -use syntax::symbol::{keywords, sym}; +use syntax::symbol::{kw, sym}; use syntax::util::lev_distance::find_best_match_for_name; use syntax::{struct_span_err, unwrap_or}; use syntax_pos::{MultiSpan, Span}; @@ -217,15 +217,15 @@ impl<'a> Resolver<'a> { parent_scope.expect("no parent scope for a single-segment import"); if ns == TypeNS { - if ident.name == keywords::Crate.name() || - ident.name == keywords::DollarCrate.name() { + if ident.name == kw::Crate || + ident.name == kw::DollarCrate { let module = self.resolve_crate_root(ident); let binding = (module, ty::Visibility::Public, module.span, Mark::root()) .to_name_binding(self.arenas); return Ok(binding); - } else if ident.name == keywords::Super.name() || - ident.name == keywords::SelfLower.name() { + } else if ident.name == kw::Super || + ident.name == kw::SelfLower { // FIXME: Implement these with renaming requirements so that e.g. // `use super;` doesn't work, but `use super as name;` does. // Fall through here to get an error from `early_resolve_...`. @@ -992,7 +992,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { // HACK(eddyb) `lint_if_path_starts_with_module` needs at least // 2 segments, so the `resolve_path` above won't trigger it. let mut full_path = directive.module_path.clone(); - full_path.push(Segment::from_ident(keywords::Invalid.ident())); + full_path.push(Segment::from_ident(Ident::with_empty_ctxt(kw::Invalid))); self.lint_if_path_starts_with_module( directive.crate_lint(), &full_path, @@ -1484,8 +1484,8 @@ fn import_path_to_string(names: &[Ident], subclass: &ImportDirectiveSubclass<'_>, span: Span) -> String { let pos = names.iter() - .position(|p| span == p.span && p.name != keywords::PathRoot.name()); - let global = !names.is_empty() && names[0].name == keywords::PathRoot.name(); + .position(|p| span == p.span && p.name != kw::PathRoot); + let global = !names.is_empty() && names[0].name == kw::PathRoot; if let Some(pos) = pos { let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] }; names_to_string(names) diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 362b6f0504d..a20a91b3e6f 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -123,7 +123,7 @@ use syntax::attr; use syntax::feature_gate::{GateIssue, emit_feature_err}; use syntax::ptr::P; use syntax::source_map::{DUMMY_SP, original_sp}; -use syntax::symbol::{Symbol, LocalInternedString, keywords, sym}; +use syntax::symbol::{Symbol, LocalInternedString, kw, sym}; use syntax::util::lev_distance::find_best_match_for_name; use std::cell::{Cell, RefCell, Ref, RefMut}; @@ -3290,7 +3290,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { Ok(method) } Err(error) => { - if segment.ident.name != keywords::Invalid.name() { + if segment.ident.name != kw::Invalid { self.report_method_error(span, rcvr_t, segment.ident, @@ -3402,7 +3402,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } err.emit(); field_ty - } else if field.name == keywords::Invalid.name() { + } else if field.name == kw::Invalid { self.tcx().types.err } else if self.method_exists(field, expr_t, expr.hir_id, true) { let mut err = type_error_struct!(self.tcx().sess, field.span, expr_t, E0615, @@ -4672,7 +4672,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { method::MethodError::PrivateMatch(kind, def_id, _) => Ok((kind, def_id)), _ => Err(ErrorReported), }; - if item_name.name != keywords::Invalid.name() { + if item_name.name != kw::Invalid { self.report_method_error( span, ty, diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 7adf86a99bd..2a4d8f304b5 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -39,7 +39,7 @@ use syntax::ast::{Ident, MetaItemKind}; use syntax::attr::{InlineAttr, OptimizeAttr, list_contains_name, mark_used}; use syntax::source_map::Spanned; use syntax::feature_gate; -use syntax::symbol::{InternedString, keywords, Symbol, sym}; +use syntax::symbol::{InternedString, kw, Symbol, sym}; use syntax_pos::{Span, DUMMY_SP}; use rustc::hir::def::{CtorKind, Res, DefKind}; @@ -939,7 +939,7 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty opt_self = Some(ty::GenericParamDef { index: 0, - name: keywords::SelfUpper.name().as_interned_str(), + name: kw::SelfUpper.as_interned_str(), def_id: tcx.hir().local_def_id_from_hir_id(param_id), pure_wrt_drop: false, kind: ty::GenericParamDefKind::Type { @@ -1008,7 +1008,7 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty synthetic, .. } => { - if param.name.ident().name == keywords::SelfUpper.name() { + if param.name.ident().name == kw::SelfUpper { span_bug!( param.span, "`Self` should not be the name of a regular parameter" @@ -1038,7 +1038,7 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty } } GenericParamKind::Const { .. } => { - if param.name.ident().name == keywords::SelfUpper.name() { + if param.name.ident().name == kw::SelfUpper { span_bug!( param.span, "`Self` should not be the name of a regular parameter", diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 6d03a5ad63b..1bbbe581c3c 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -31,8 +31,7 @@ use syntax::attr; use syntax::ext::base::MacroKind; use syntax::source_map::{dummy_spanned, Spanned}; use syntax::ptr::P; -use syntax::symbol::keywords::{self, Keyword}; -use syntax::symbol::{Symbol, sym}; +use syntax::symbol::{Symbol, kw, sym}; use syntax::symbol::InternedString; use syntax_pos::{self, Pos, FileName}; @@ -43,7 +42,6 @@ use std::default::Default; use std::{mem, slice, vec}; use std::iter::{FromIterator, once}; use std::rc::Rc; -use std::str::FromStr; use std::cell::RefCell; use std::sync::Arc; use std::u32; @@ -309,10 +307,9 @@ impl Clean for CrateNum { for attr in attrs.lists(sym::doc) { if let Some(v) = attr.value_str() { if attr.check_name(sym::keyword) { - keyword = Keyword::from_str(&v.as_str()).ok() - .map(|x| x.name().to_string()); - if keyword.is_some() { - break + if v.is_doc_keyword() { + keyword = Some(v.to_string()); + break; } // FIXME: should warn on unknown keywords? } @@ -1702,7 +1699,7 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, let stripped_typarams = gens.params.iter().filter_map(|param| match param.kind { ty::GenericParamDefKind::Lifetime => None, ty::GenericParamDefKind::Type { .. } => { - if param.name.as_symbol() == keywords::SelfUpper.name() { + if param.name.as_symbol() == kw::SelfUpper { assert_eq!(param.index, 0); return None; } @@ -3596,7 +3593,7 @@ fn qpath_to_string(p: &hir::QPath) -> String { if i > 0 { s.push_str("::"); } - if seg.ident.name != keywords::PathRoot.name() { + if seg.ident.name != kw::PathRoot { s.push_str(&*seg.ident.as_str()); } } @@ -4176,7 +4173,7 @@ fn resolve_type(cx: &DocContext<'_>, hir::Float(float_ty) => return Primitive(float_ty.into()), }, Res::SelfTy(..) if path.segments.len() == 1 => { - return Generic(keywords::SelfUpper.name().to_string()); + return Generic(kw::SelfUpper.to_string()); } Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => { return Generic(format!("{:#}", path)); diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs index ae0bd1aafa8..71d8665f3b3 100644 --- a/src/librustdoc/html/layout.rs +++ b/src/librustdoc/html/layout.rs @@ -44,7 +44,7 @@ pub fn render( \ \ \ - \ + \ {title}\ \ , } @@ -100,7 +100,7 @@ impl Path { } pub fn is_global(&self) -> bool { - !self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name() + !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot } } @@ -128,7 +128,7 @@ impl PathSegment { PathSegment { ident, id: DUMMY_NODE_ID, args: None } } pub fn path_root(span: Span) -> Self { - PathSegment::from_ident(Ident::new(keywords::PathRoot.name(), span)) + PathSegment::from_ident(Ident::new(kw::PathRoot, span)) } } @@ -1782,7 +1782,7 @@ pub type ExplicitSelf = Spanned; impl Arg { pub fn to_self(&self) -> Option { if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node { - if ident.name == keywords::SelfLower.name() { + if ident.name == kw::SelfLower { return match self.ty.node { TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))), TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => { @@ -1800,7 +1800,7 @@ impl Arg { pub fn is_self(&self) -> bool { if let PatKind::Ident(_, ident, _) = self.pat.node { - ident.name == keywords::SelfLower.name() + ident.name == kw::SelfLower } else { false } diff --git a/src/libsyntax/attr/mod.rs b/src/libsyntax/attr/mod.rs index 592b40df176..3e93ac23a53 100644 --- a/src/libsyntax/attr/mod.rs +++ b/src/libsyntax/attr/mod.rs @@ -22,7 +22,7 @@ use crate::parse::parser::Parser; use crate::parse::{self, ParseSess, PResult}; use crate::parse::token::{self, Token}; use crate::ptr::P; -use crate::symbol::{keywords, Symbol, sym}; +use crate::symbol::{kw, sym, Symbol}; use crate::ThinVec; use crate::tokenstream::{TokenStream, TokenTree, DelimSpan}; use crate::GLOBALS; @@ -90,7 +90,7 @@ impl NestedMetaItem { self.meta_item().and_then(|meta_item| meta_item.ident()) } pub fn name_or_empty(&self) -> Symbol { - self.ident().unwrap_or(keywords::Invalid.ident()).name + self.ident().unwrap_or(Ident::invalid()).name } /// Gets the string value if self is a MetaItem and the MetaItem is a @@ -168,7 +168,7 @@ impl Attribute { } } pub fn name_or_empty(&self) -> Symbol { - self.ident().unwrap_or(keywords::Invalid.ident()).name + self.ident().unwrap_or(Ident::invalid()).name } pub fn value_str(&self) -> Option { @@ -206,7 +206,7 @@ impl MetaItem { } } pub fn name_or_empty(&self) -> Symbol { - self.ident().unwrap_or(keywords::Invalid.ident()).name + self.ident().unwrap_or(Ident.invalid()).name } // #[attribute(name = "value")] diff --git a/src/libsyntax/diagnostics/plugin.rs b/src/libsyntax/diagnostics/plugin.rs index c988dc61bec..e9476e2fdfd 100644 --- a/src/libsyntax/diagnostics/plugin.rs +++ b/src/libsyntax/diagnostics/plugin.rs @@ -7,7 +7,7 @@ use crate::ext::base::{ExtCtxt, MacEager, MacResult}; use crate::ext::build::AstBuilder; use crate::parse::token; use crate::ptr::P; -use crate::symbol::keywords; +use crate::symbol::kw; use crate::tokenstream::{TokenTree}; use smallvec::smallvec; @@ -185,7 +185,7 @@ pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt<'_>, (descriptions.len(), ecx.expr_vec(span, descriptions)) }); - let static_ = ecx.lifetime(span, keywords::StaticLifetime.ident()); + let static_ = ecx.lifetime(span, Ident::with_empty_ctxt(kw::StaticLifetime)); let ty_str = ecx.ty_rptr( span, ecx.ty_ident(span, ecx.ident_of("str")), diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 489fac4f1ca..f1a20d54065 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -10,7 +10,7 @@ use crate::mut_visit::{self, MutVisitor}; use crate::parse::{self, parser, DirectoryOwnership}; use crate::parse::token; use crate::ptr::P; -use crate::symbol::{keywords, Ident, Symbol, sym}; +use crate::symbol::{kw, sym, Ident, Symbol}; use crate::ThinVec; use crate::tokenstream::{self, TokenStream}; @@ -971,7 +971,7 @@ impl<'a> ExtCtxt<'a> { } pub fn std_path(&self, components: &[&str]) -> Vec { let def_site = DUMMY_SP.apply_mark(self.current_expansion.mark); - iter::once(Ident::new(keywords::DollarCrate.name(), def_site)) + iter::once(Ident::new(kw::DollarCrate, def_site)) .chain(components.iter().map(|s| self.ident_of(s))) .collect() } diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index d24106f697e..77d5fa238f2 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -3,7 +3,7 @@ use crate::attr; use crate::source_map::{dummy_spanned, respan, Spanned}; use crate::ext::base::ExtCtxt; use crate::ptr::P; -use crate::symbol::{Symbol, keywords}; +use crate::symbol::{Symbol, kw}; use crate::ThinVec; use rustc_target::spec::abi::Abi; @@ -628,7 +628,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self.expr_path(self.path_ident(span, id)) } fn expr_self(&self, span: Span) -> P { - self.expr_ident(span, keywords::SelfLower.ident()) + self.expr_ident(span, Ident::with_empty_ctxt(kw::SelfLower)) } fn expr_binary(&self, sp: Span, op: ast::BinOpKind, @@ -1175,7 +1175,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { vis: ast::Visibility, vp: P) -> P { P(ast::Item { id: ast::DUMMY_NODE_ID, - ident: keywords::Invalid.ident(), + ident: Ident::with_empty_ctxt(kw::Invalid), attrs: vec![], node: ast::ItemKind::Use(vp), vis, diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 478ae4de82b..5f9c84c6126 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -14,7 +14,7 @@ use crate::parse::token::{self, Token}; use crate::parse::parser::Parser; use crate::ptr::P; use crate::symbol::Symbol; -use crate::symbol::{keywords, sym}; +use crate::symbol::{kw, sym}; use crate::tokenstream::{TokenStream, TokenTree}; use crate::visit::{self, Visitor}; use crate::util::map_in_place::MapInPlace; @@ -198,7 +198,7 @@ fn macro_bang_format(path: &ast::Path) -> ExpnFormat { if i != 0 { path_str.push_str("::"); } - if segment.ident.name != keywords::PathRoot.name() { + if segment.ident.name != kw::PathRoot { path_str.push_str(&segment.ident.as_str()) } } @@ -271,7 +271,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { attrs: krate.attrs, span: krate.span, node: ast::ItemKind::Mod(krate.module), - ident: keywords::Invalid.ident(), + ident: Ident::with_empty_ctxt(kw::Invalid), id: ast::DUMMY_NODE_ID, vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public), tokens: None, @@ -708,7 +708,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { }; let path = &mac.node.path; - let ident = ident.unwrap_or_else(|| keywords::Invalid.ident()); + let ident = ident.unwrap_or_else(|| Ident::with_empty_ctxt(kw::Invalid)); let validate_and_set_expn_info = |this: &mut Self, // arg instead of capture def_site_span: Option, allow_internal_unstable, @@ -736,7 +736,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } } - if ident.name != keywords::Invalid.name() { + if ident.name != kw::Invalid { let msg = format!("macro {}! expects no ident argument, given '{}'", path, ident); this.cx.span_err(path.span, &msg); this.cx.trace_macros_diag(); @@ -792,7 +792,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } IdentTT { ref expander, span: tt_span, ref allow_internal_unstable } => { - if ident.name == keywords::Invalid.name() { + if ident.name == kw::Invalid { self.cx.span_err(path.span, &format!("macro {}! expects an ident argument", path)); self.cx.trace_macros_diag(); @@ -828,7 +828,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } SyntaxExtension::ProcMacro { ref expander, ref allow_internal_unstable, edition } => { - if ident.name != keywords::Invalid.name() { + if ident.name != kw::Invalid { let msg = format!("macro {}! expects no ident argument, given '{}'", path, ident); self.cx.span_err(path.span, &msg); @@ -929,7 +929,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { invoc.expansion_data.mark.set_expn_info(expn_info); let span = span.with_ctxt(self.cx.backtrace()); let dummy = ast::MetaItem { // FIXME(jseyfried) avoid this - path: Path::from_ident(keywords::Invalid.ident()), + path: Path::from_ident(Ident::with_empty_ctxt(kw::Invalid)), span: DUMMY_SP, node: ast::MetaItemKind::Word, }; @@ -1338,7 +1338,7 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { }) } ast::ItemKind::Mod(ast::Mod { inner, .. }) => { - if item.ident == keywords::Invalid.ident() { + if item.ident == Ident::with_empty_ctxt(kw::Invalid) { return noop_flat_map_item(item, self); } diff --git a/src/libsyntax/ext/placeholders.rs b/src/libsyntax/ext/placeholders.rs index f5e18e98436..9ba1ff0ec7e 100644 --- a/src/libsyntax/ext/placeholders.rs +++ b/src/libsyntax/ext/placeholders.rs @@ -6,7 +6,7 @@ use crate::ext::hygiene::Mark; use crate::tokenstream::TokenStream; use crate::mut_visit::*; use crate::ptr::P; -use crate::symbol::keywords; +use crate::symbol::kw; use crate::ThinVec; use smallvec::{smallvec, SmallVec}; @@ -22,7 +22,7 @@ pub fn placeholder(kind: AstFragmentKind, id: ast::NodeId) -> AstFragment { }) } - let ident = keywords::Invalid.ident(); + let ident = ast::Ident::with_empty_ctxt(kw::Invalid); let attrs = Vec::new(); let generics = ast::Generics::default(); let vis = dummy_spanned(ast::VisibilityKind::Inherited); diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 084a69f4cda..fa1f85c0e7b 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -80,7 +80,7 @@ use crate::parse::{Directory, ParseSess}; use crate::parse::parser::{Parser, PathStyle}; use crate::parse::token::{self, DocComment, Nonterminal, Token}; use crate::print::pprust; -use crate::symbol::keywords; +use crate::symbol::kw; use crate::tokenstream::{DelimSpan, TokenStream}; use errors::FatalError; @@ -382,7 +382,7 @@ fn nameize>( TokenTree::Delimited(_, ref delim) => for next_m in &delim.tts { n_rec(sess, next_m, res.by_ref(), ret_val)?; }, - TokenTree::MetaVarDecl(span, _, id) if id.name == keywords::Invalid.name() => { + TokenTree::MetaVarDecl(span, _, id) if id.name == kw::Invalid => { if sess.missing_fragment_specifiers.borrow_mut().remove(&span) { return Err((span, "missing fragment specifier".to_string())); } @@ -587,7 +587,7 @@ fn inner_parse_loop<'root, 'tt>( } // We need to match a metavar (but the identifier is invalid)... this is an error - TokenTree::MetaVarDecl(span, _, id) if id.name == keywords::Invalid.name() => { + TokenTree::MetaVarDecl(span, _, id) if id.name == kw::Invalid => { if sess.missing_fragment_specifiers.borrow_mut().remove(&span) { return Error(span, "missing fragment specifier".to_string()); } @@ -802,7 +802,7 @@ pub fn parse( /// We prohibit passing `_` to macros expecting `ident` for now. fn get_macro_ident(token: &Token) -> Option<(Ident, bool)> { match *token { - token::Ident(ident, is_raw) if ident.name != keywords::Underscore.name() => + token::Ident(ident, is_raw) if ident.name != kw::Underscore => Some((ident, is_raw)), _ => None, } diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 672b7b42855..8adee4be75f 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -1107,7 +1107,7 @@ fn is_in_follow(tok: "ed::TokenTree, frag: &str) -> IsInFollow { _ => IsInFollow::No(tokens), } }, - "" => IsInFollow::Yes, // keywords::Invalid + "" => IsInFollow::Yes, // kw::Invalid _ => IsInFollow::Invalid(format!("invalid fragment specifier `{}`", frag), VALID_FRAGMENT_NAMES_MSG), } diff --git a/src/libsyntax/ext/tt/quoted.rs b/src/libsyntax/ext/tt/quoted.rs index ed8395f11ad..2f1a9834674 100644 --- a/src/libsyntax/ext/tt/quoted.rs +++ b/src/libsyntax/ext/tt/quoted.rs @@ -6,7 +6,7 @@ use crate::parse::{token, ParseSess}; use crate::print::pprust; use crate::tokenstream::{self, DelimSpan}; use crate::ast; -use crate::symbol::keywords; +use crate::symbol::kw; use syntax_pos::{edition::Edition, BytePos, Span}; @@ -228,7 +228,7 @@ pub fn parse( result.push(TokenTree::MetaVarDecl( span, ident, - keywords::Invalid.ident(), + ast::Ident::with_empty_ctxt(kw::Invalid), )); } @@ -319,8 +319,8 @@ where Some(tokenstream::TokenTree::Token(ident_span, ref token)) if token.is_ident() => { let (ident, is_raw) = token.ident().unwrap(); let span = ident_span.with_lo(span.lo()); - if ident.name == keywords::Crate.name() && !is_raw { - let ident = ast::Ident::new(keywords::DollarCrate.name(), ident.span); + if ident.name == kw::Crate && !is_raw { + let ident = ast::Ident::new(kw::DollarCrate, ident.span); TokenTree::Token(span, token::Ident(ident, is_raw)) } else { TokenTree::MetaVar(span, ident) @@ -334,7 +334,7 @@ where pprust::token_to_string(&tok) ); sess.span_diagnostic.span_err(span, &msg); - TokenTree::MetaVar(span, keywords::Invalid.ident()) + TokenTree::MetaVar(span, ast::Ident::with_empty_ctxt(kw::Invalid)) } // There are no more tokens. Just return the `$` we already have. diff --git a/src/libsyntax/mut_visit.rs b/src/libsyntax/mut_visit.rs index 8fdd15a029f..8dae4756c82 100644 --- a/src/libsyntax/mut_visit.rs +++ b/src/libsyntax/mut_visit.rs @@ -11,7 +11,7 @@ use crate::ast::*; use crate::source_map::{Spanned, respan}; use crate::parse::token::{self, Token}; use crate::ptr::P; -use crate::symbol::keywords; +use crate::symbol::kw; use crate::ThinVec; use crate::tokenstream::*; use crate::util::map_in_place::MapInPlace; @@ -977,7 +977,7 @@ pub fn noop_visit_mod(Mod { inner, items, inline: _ }: &mut Mod, pub fn noop_visit_crate(krate: &mut Crate, vis: &mut T) { visit_clobber(krate, |Crate { module, attrs, span }| { let item = P(Item { - ident: keywords::Invalid.ident(), + ident: Ident::with_empty_ctxt(kw::Invalid), attrs, id: DUMMY_NODE_ID, vis: respan(span.shrink_to_lo(), VisibilityKind::Public), diff --git a/src/libsyntax/parse/literal.rs b/src/libsyntax/parse/literal.rs index 53195421ddc..6db1a669493 100644 --- a/src/libsyntax/parse/literal.rs +++ b/src/libsyntax/parse/literal.rs @@ -6,7 +6,7 @@ use crate::parse::PResult; use crate::parse::token::{self, Token}; use crate::parse::unescape::{unescape_str, unescape_char, unescape_byte_str, unescape_byte}; use crate::print::pprust; -use crate::symbol::{keywords, Symbol}; +use crate::symbol::{kw, Symbol}; use crate::tokenstream::{TokenStream, TokenTree}; use errors::{Applicability, Handler}; diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 24d120376de..0099dd3d3c8 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -46,7 +46,7 @@ use crate::ptr::P; use crate::parse::PResult; use crate::ThinVec; use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint}; -use crate::symbol::{keywords, sym, Symbol}; +use crate::symbol::{kw, sym, Symbol}; use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError}; use rustc_target::spec::abi::{self, Abi}; @@ -379,7 +379,7 @@ impl TokenCursor { #[derive(Clone, PartialEq)] crate enum TokenType { Token(token::Token), - Keyword(keywords::Keyword), + Keyword(Symbol), Operator, Lifetime, Ident, @@ -392,7 +392,7 @@ impl TokenType { crate fn to_string(&self) -> String { match *self { TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)), - TokenType::Keyword(kw) => format!("`{}`", kw.name()), + TokenType::Keyword(kw) => format!("`{}`", kw), TokenType::Operator => "an operator".to_string(), TokenType::Lifetime => "lifetime".to_string(), TokenType::Ident => "identifier".to_string(), @@ -510,7 +510,7 @@ impl From> for LhsExpr { /// Creates a placeholder argument. fn dummy_arg(span: Span) -> Arg { - let ident = Ident::new(keywords::Invalid.name(), span); + let ident = Ident::new(kw::Invalid, span); let pat = P(Pat { id: ast::DUMMY_NODE_ID, node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None), @@ -771,15 +771,15 @@ impl<'a> Parser<'a> { TokenType::Token(token::Semi) => true, // we expect a `;` here _ => false, }) && ( // a `;` would be expected before the current keyword - self.token.is_keyword(keywords::Break) || - self.token.is_keyword(keywords::Continue) || - self.token.is_keyword(keywords::For) || - self.token.is_keyword(keywords::If) || - self.token.is_keyword(keywords::Let) || - self.token.is_keyword(keywords::Loop) || - self.token.is_keyword(keywords::Match) || - self.token.is_keyword(keywords::Return) || - self.token.is_keyword(keywords::While) + self.token.is_keyword(kw::Break) || + self.token.is_keyword(kw::Continue) || + self.token.is_keyword(kw::For) || + self.token.is_keyword(kw::If) || + self.token.is_keyword(kw::Let) || + self.token.is_keyword(kw::Loop) || + self.token.is_keyword(kw::Match) || + self.token.is_keyword(kw::Return) || + self.token.is_keyword(kw::While) ); let cm = self.sess.source_map(); match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) { @@ -913,14 +913,14 @@ impl<'a> Parser<'a> { is_present } - fn check_keyword(&mut self, kw: keywords::Keyword) -> bool { + fn check_keyword(&mut self, kw: Symbol) -> bool { self.expected_tokens.push(TokenType::Keyword(kw)); self.token.is_keyword(kw) } /// If the next token is the given keyword, eats it and returns /// `true`. Otherwise, returns `false`. - pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool { + pub fn eat_keyword(&mut self, kw: Symbol) -> bool { if self.check_keyword(kw) { self.bump(); true @@ -929,7 +929,7 @@ impl<'a> Parser<'a> { } } - fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool { + fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { if self.token.is_keyword(kw) { self.bump(); true @@ -941,7 +941,7 @@ impl<'a> Parser<'a> { /// If the given word is not a keyword, signals an error. /// If the next token is not the given word, signals an error. /// Otherwise, eats it. - fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> { + fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { if !self.eat_keyword(kw) { self.unexpected() } else { @@ -1375,9 +1375,9 @@ impl<'a> Parser<'a> { /// Is the current token one of the keywords that signals a bare function type? fn token_is_bare_fn_keyword(&mut self) -> bool { - self.check_keyword(keywords::Fn) || - self.check_keyword(keywords::Unsafe) || - self.check_keyword(keywords::Extern) + self.check_keyword(kw::Fn) || + self.check_keyword(kw::Unsafe) || + self.check_keyword(kw::Extern) } /// Parses a `TyKind::BareFn` type. @@ -1395,13 +1395,13 @@ impl<'a> Parser<'a> { */ let unsafety = self.parse_unsafety(); - let abi = if self.eat_keyword(keywords::Extern) { + let abi = if self.eat_keyword(kw::Extern) { self.parse_opt_abi()?.unwrap_or(Abi::C) } else { Abi::Rust }; - self.expect_keyword(keywords::Fn)?; + self.expect_keyword(kw::Fn)?; let (inputs, c_variadic) = self.parse_fn_args(false, true)?; let ret_ty = self.parse_ret_ty(false)?; let decl = P(FnDecl { @@ -1419,7 +1419,7 @@ impl<'a> Parser<'a> { /// Parses asyncness: `async` or nothing. fn parse_asyncness(&mut self) -> IsAsync { - if self.eat_keyword(keywords::Async) { + if self.eat_keyword(kw::Async) { IsAsync::Async { closure_id: ast::DUMMY_NODE_ID, return_impl_trait_id: ast::DUMMY_NODE_ID, @@ -1432,7 +1432,7 @@ impl<'a> Parser<'a> { /// Parses unsafety: `unsafe` or nothing. fn parse_unsafety(&mut self) -> Unsafety { - if self.eat_keyword(keywords::Unsafe) { + if self.eat_keyword(kw::Unsafe) { Unsafety::Unsafe } else { Unsafety::Normal @@ -1462,10 +1462,10 @@ impl<'a> Parser<'a> { mut attrs: Vec) -> PResult<'a, TraitItem> { let lo = self.span; self.eat_bad_pub(); - let (name, node, generics) = if self.eat_keyword(keywords::Type) { + let (name, node, generics) = if self.eat_keyword(kw::Type) { self.parse_trait_item_assoc_ty()? } else if self.is_const_item() { - self.expect_keyword(keywords::Const)?; + self.expect_keyword(kw::Const)?; let ident = self.parse_ident()?; self.expect(&token::Colon)?; let ty = self.parse_ty()?; @@ -1480,7 +1480,9 @@ impl<'a> Parser<'a> { (ident, TraitItemKind::Const(ty, default), ast::Generics::default()) } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? { // trait item macro. - (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default()) + (Ident::with_empty_ctxt(kw::Invalid), + ast::TraitItemKind::Macro(mac), + ast::Generics::default()) } else { let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?; @@ -1654,7 +1656,7 @@ impl<'a> Parser<'a> { // Reference self.expect_and()?; self.parse_borrowed_pointee()? - } else if self.eat_keyword_noexpect(keywords::Typeof) { + } else if self.eat_keyword_noexpect(kw::Typeof) { // `typeof(EXPR)` // In order to not be ambiguous, the type must be surrounded by parens. self.expect(&token::OpenDelim(token::Paren))?; @@ -1664,13 +1666,13 @@ impl<'a> Parser<'a> { }; self.expect(&token::CloseDelim(token::Paren))?; TyKind::Typeof(e) - } else if self.eat_keyword(keywords::Underscore) { + } else if self.eat_keyword(kw::Underscore) { // A type to be inferred `_` TyKind::Infer } else if self.token_is_bare_fn_keyword() { // Function pointer type self.parse_ty_bare_fn(Vec::new())? - } else if self.check_keyword(keywords::For) { + } else if self.check_keyword(kw::For) { // Function pointer type or bound list (trait object type) starting with a poly-trait. // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T` // `for<'lt> Trait1<'lt> + Trait2 + 'a` @@ -1683,12 +1685,12 @@ impl<'a> Parser<'a> { let parse_plus = allow_plus && self.check_plus(); self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)? } - } else if self.eat_keyword(keywords::Impl) { + } else if self.eat_keyword(kw::Impl) { // Always parse bounds greedily for better error recovery. let bounds = self.parse_generic_bounds(None)?; impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus; TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds) - } else if self.check_keyword(keywords::Dyn) && + } else if self.check_keyword(kw::Dyn) && (self.span.rust_2018() || self.look_ahead(1, |t| t.can_begin_bound() && !can_continue_type_after_non_fn_ident(t))) { @@ -1766,9 +1768,9 @@ impl<'a> Parser<'a> { } fn parse_ptr(&mut self) -> PResult<'a, MutTy> { - let mutbl = if self.eat_keyword(keywords::Mut) { + let mutbl = if self.eat_keyword(kw::Mut) { Mutability::Mutable - } else if self.eat_keyword(keywords::Const) { + } else if self.eat_keyword(kw::Const) { Mutability::Immutable } else { let span = self.prev_span; @@ -1790,7 +1792,7 @@ impl<'a> Parser<'a> { _ => 0, } token::BinOp(token::And) | token::AndAnd => 1, - _ if self.token.is_keyword(keywords::Mut) => 1, + _ if self.token.is_keyword(kw::Mut) => 1, _ => 0, }; @@ -1891,7 +1893,7 @@ impl<'a> Parser<'a> { } match ty { Ok(ty) => { - let ident = Ident::new(keywords::Invalid.name(), self.prev_span); + let ident = Ident::new(kw::Invalid, self.prev_span); let pat = P(Pat { id: ast::DUMMY_NODE_ID, node: PatKind::Ident( @@ -2006,7 +2008,7 @@ impl<'a> Parser<'a> { fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> { match self.token { - token::Ident(ident, false) if ident.name == keywords::Underscore.name() => { + token::Ident(ident, false) if ident.name == kw::Underscore => { let span = self.span; self.bump(); Ok(Ident::new(ident.name, span)) @@ -2034,7 +2036,7 @@ impl<'a> Parser<'a> { // above). `path_span` has the span of that path, or an empty // span in the case of something like `::Bar`. let (mut path, path_span); - if self.eat_keyword(keywords::As) { + if self.eat_keyword(kw::As) { let path_lo = self.span; path = self.parse_path(PathStyle::Type)?; path_span = path_lo.to(self.prev_span); @@ -2233,7 +2235,7 @@ impl<'a> Parser<'a> { /// Parses mutability (`mut` or nothing). fn parse_mutability(&mut self) -> Mutability { - if self.eat_keyword(keywords::Mut) { + if self.eat_keyword(kw::Mut) { Mutability::Mutable } else { Mutability::Immutable @@ -2465,37 +2467,37 @@ impl<'a> Parser<'a> { hi = path.span; return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs)); } - if self.span.rust_2018() && self.check_keyword(keywords::Async) { + if self.span.rust_2018() && self.check_keyword(kw::Async) { return if self.is_async_block() { // check for `async {` and `async move {` self.parse_async_block(attrs) } else { self.parse_lambda_expr(attrs) }; } - if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) { + if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) { return self.parse_lambda_expr(attrs); } - if self.eat_keyword(keywords::If) { + if self.eat_keyword(kw::If) { return self.parse_if_expr(attrs); } - if self.eat_keyword(keywords::For) { + if self.eat_keyword(kw::For) { let lo = self.prev_span; return self.parse_for_expr(None, lo, attrs); } - if self.eat_keyword(keywords::While) { + if self.eat_keyword(kw::While) { let lo = self.prev_span; return self.parse_while_expr(None, lo, attrs); } if let Some(label) = self.eat_label() { let lo = label.ident.span; self.expect(&token::Colon)?; - if self.eat_keyword(keywords::While) { + if self.eat_keyword(kw::While) { return self.parse_while_expr(Some(label), lo, attrs) } - if self.eat_keyword(keywords::For) { + if self.eat_keyword(kw::For) { return self.parse_for_expr(Some(label), lo, attrs) } - if self.eat_keyword(keywords::Loop) { + if self.eat_keyword(kw::Loop) { return self.parse_loop_expr(Some(label), lo, attrs) } if self.token == token::OpenDelim(token::Brace) { @@ -2509,24 +2511,24 @@ impl<'a> Parser<'a> { err.span_label(self.span, msg); return Err(err); } - if self.eat_keyword(keywords::Loop) { + if self.eat_keyword(kw::Loop) { let lo = self.prev_span; return self.parse_loop_expr(None, lo, attrs); } - if self.eat_keyword(keywords::Continue) { + if self.eat_keyword(kw::Continue) { let label = self.eat_label(); let ex = ExprKind::Continue(label); let hi = self.prev_span; return Ok(self.mk_expr(lo.to(hi), ex, attrs)); } - if self.eat_keyword(keywords::Match) { + if self.eat_keyword(kw::Match) { let match_sp = self.prev_span; return self.parse_match_expr(attrs).map_err(|mut err| { err.span_label(match_sp, "while parsing this match expression"); err }); } - if self.eat_keyword(keywords::Unsafe) { + if self.eat_keyword(kw::Unsafe) { return self.parse_block_expr( None, lo, @@ -2540,10 +2542,10 @@ impl<'a> Parser<'a> { } if self.is_try_block() { let lo = self.span; - assert!(self.eat_keyword(keywords::Try)); + assert!(self.eat_keyword(kw::Try)); return self.parse_try_block(lo, attrs); } - if self.eat_keyword(keywords::Return) { + if self.eat_keyword(kw::Return) { if self.token.can_begin_expr() { let e = self.parse_expr()?; hi = e.span; @@ -2551,7 +2553,7 @@ impl<'a> Parser<'a> { } else { ex = ExprKind::Ret(None); } - } else if self.eat_keyword(keywords::Break) { + } else if self.eat_keyword(kw::Break) { let label = self.eat_label(); let e = if self.token.can_begin_expr() && !(self.token == token::OpenDelim(token::Brace) @@ -2563,7 +2565,7 @@ impl<'a> Parser<'a> { }; ex = ExprKind::Break(label, e); hi = self.prev_span; - } else if self.eat_keyword(keywords::Yield) { + } else if self.eat_keyword(kw::Yield) { if self.token.can_begin_expr() { let e = self.parse_expr()?; hi = e.span; @@ -2571,14 +2573,14 @@ impl<'a> Parser<'a> { } else { ex = ExprKind::Yield(None); } - } else if self.token.is_keyword(keywords::Let) { + } else if self.token.is_keyword(kw::Let) { // Catch this syntax error here, instead of in `parse_ident`, so // that we can explicitly mention that let is not to be used as an expression let mut db = self.fatal("expected expression, found statement (`let`)"); db.span_label(self.span, "expected expression"); db.note("variable declaration using `let` is a statement"); return Err(db); - } else if self.span.rust_2018() && self.eat_keyword(keywords::Await) { + } else if self.span.rust_2018() && self.eat_keyword(kw::Await) { let (await_hi, e_kind) = self.parse_await_macro_or_alt(lo, self.prev_span)?; hi = await_hi; ex = e_kind; @@ -2879,7 +2881,7 @@ impl<'a> Parser<'a> { // Assuming we have just parsed `.`, continue parsing into an expression. fn parse_dot_suffix(&mut self, self_arg: P, lo: Span) -> PResult<'a, P> { - if self.span.rust_2018() && self.eat_keyword(keywords::Await) { + if self.span.rust_2018() && self.eat_keyword(kw::Await) { let span = lo.to(self.prev_span); let await_expr = self.mk_expr( span, @@ -3250,7 +3252,7 @@ impl<'a> Parser<'a> { let (span, e) = self.interpolated_or_expr_span(e)?; (lo.to(span), ExprKind::AddrOf(m, e)) } - token::Ident(..) if self.token.is_keyword(keywords::In) => { + token::Ident(..) if self.token.is_keyword(kw::In) => { self.bump(); let place = self.parse_expr_res( Restrictions::NO_STRUCT_LITERAL, @@ -3261,7 +3263,7 @@ impl<'a> Parser<'a> { let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new()); (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr)) } - token::Ident(..) if self.token.is_keyword(keywords::Box) => { + token::Ident(..) if self.token.is_keyword(kw::Box) => { self.bump(); let e = self.parse_prefix_expr(None); let (span, e) = self.interpolated_or_expr_span(e)?; @@ -3683,7 +3685,7 @@ impl<'a> Parser<'a> { /// Parses an `if` or `if let` expression (`if` token already eaten). fn parse_if_expr(&mut self, attrs: ThinVec) -> PResult<'a, P> { - if self.check_keyword(keywords::Let) { + if self.check_keyword(kw::Let) { return self.parse_if_let_expr(attrs); } let lo = self.prev_span; @@ -3693,7 +3695,7 @@ impl<'a> Parser<'a> { // verify that the last statement is either an implicit return (no `;`) or an explicit // return. This won't catch blocks with an explicit `return`, but that would be caught by // the dead code lint. - if self.eat_keyword(keywords::Else) || !cond.returns() { + if self.eat_keyword(kw::Else) || !cond.returns() { let sp = self.sess.source_map().next_point(lo); let mut err = self.diagnostic() .struct_span_err(sp, "missing condition for `if` statemement"); @@ -3709,7 +3711,7 @@ impl<'a> Parser<'a> { })?; let mut els: Option> = None; let mut hi = thn.span; - if self.eat_keyword(keywords::Else) { + if self.eat_keyword(kw::Else) { let elexpr = self.parse_else_expr()?; hi = elexpr.span; els = Some(elexpr); @@ -3721,12 +3723,12 @@ impl<'a> Parser<'a> { fn parse_if_let_expr(&mut self, attrs: ThinVec) -> PResult<'a, P> { let lo = self.prev_span; - self.expect_keyword(keywords::Let)?; + self.expect_keyword(kw::Let)?; let pats = self.parse_pats()?; self.expect(&token::Eq)?; let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?; let thn = self.parse_block()?; - let (hi, els) = if self.eat_keyword(keywords::Else) { + let (hi, els) = if self.eat_keyword(kw::Else) { let expr = self.parse_else_expr()?; (expr.span, Some(expr)) } else { @@ -3741,7 +3743,7 @@ impl<'a> Parser<'a> { -> PResult<'a, P> { let lo = self.span; - let movability = if self.eat_keyword(keywords::Static) { + let movability = if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable @@ -3751,7 +3753,7 @@ impl<'a> Parser<'a> { } else { IsAsync::NotAsync }; - let capture_clause = if self.eat_keyword(keywords::Move) { + let capture_clause = if self.eat_keyword(kw::Move) { CaptureBy::Value } else { CaptureBy::Ref @@ -3779,7 +3781,7 @@ impl<'a> Parser<'a> { // `else` token already eaten fn parse_else_expr(&mut self) -> PResult<'a, P> { - if self.eat_keyword(keywords::If) { + if self.eat_keyword(kw::If) { return self.parse_if_expr(ThinVec::new()); } else { let blk = self.parse_block()?; @@ -3794,7 +3796,7 @@ impl<'a> Parser<'a> { // Parse: `for in ` let pat = self.parse_top_level_pat()?; - if !self.eat_keyword(keywords::In) { + if !self.eat_keyword(kw::In) { let in_span = self.prev_span.between(self.span); let mut err = self.sess.span_diagnostic .struct_span_err(in_span, "missing `in` in `for` loop"); @@ -3806,7 +3808,7 @@ impl<'a> Parser<'a> { err.emit(); } let in_span = self.prev_span; - if self.eat_keyword(keywords::In) { + if self.eat_keyword(kw::In) { // a common typo: `for _ in in bar {}` let mut err = self.sess.span_diagnostic.struct_span_err( self.prev_span, @@ -3835,7 +3837,7 @@ impl<'a> Parser<'a> { fn parse_while_expr(&mut self, opt_label: Option