From baae274fb72c91dbee441e20622cffdc218bdcb5 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sun, 18 Mar 2018 02:57:23 +0300 Subject: [PATCH 01/10] Use `Span` instead of `SyntaxContext` in `Ident` --- src/libproc_macro/lib.rs | 2 +- src/librustc/hir/lowering.rs | 7 +-- src/librustc/ich/impls_hir.rs | 2 +- src/librustc/ty/mod.rs | 6 +-- src/librustc_driver/pretty.rs | 4 +- src/librustc_privacy/lib.rs | 13 +++-- src/librustc_resolve/build_reduced_graph.rs | 2 +- src/librustc_resolve/lib.rs | 53 +++++++++++---------- src/librustc_resolve/macros.rs | 4 +- src/librustc_resolve/resolve_imports.rs | 8 ++-- src/librustc_typeck/check/mod.rs | 6 +-- src/libsyntax/ast.rs | 2 +- src/libsyntax/ext/base.rs | 4 +- src/libsyntax/ext/expand.rs | 2 +- src/libsyntax/ext/tt/quoted.rs | 11 ++--- src/libsyntax/ext/tt/transcribe.rs | 2 +- src/libsyntax/parse/lexer/mod.rs | 2 +- src/libsyntax/print/pprust.rs | 4 +- src/libsyntax_ext/concat_idents.rs | 9 ++-- src/libsyntax_ext/deriving/generic/ty.rs | 7 ++- src/libsyntax_pos/hygiene.rs | 6 +-- src/libsyntax_pos/lib.rs | 48 ++++++++++++++++++- src/libsyntax_pos/symbol.rs | 35 ++++++++++---- 23 files changed, 146 insertions(+), 93 deletions(-) diff --git a/src/libproc_macro/lib.rs b/src/libproc_macro/lib.rs index ebd5c834fd036..124815a884931 100644 --- a/src/libproc_macro/lib.rs +++ b/src/libproc_macro/lib.rs @@ -1097,7 +1097,7 @@ impl TokenTree { }).into(); }, self::TokenTree::Term(tt) => { - let ident = ast::Ident { name: tt.sym, ctxt: tt.span.0.ctxt() }; + let ident = ast::Ident::new(tt.sym, tt.span.0); let sym_str = tt.sym.as_str(); let token = if sym_str.starts_with("'") { Lifetime(ident) } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index b767ede5faa70..c47f67ec74093 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -909,7 +909,7 @@ impl<'a> LoweringContext<'a> { fn lower_ident(&mut self, ident: Ident) -> Name { let ident = ident.modern(); - if ident.ctxt == SyntaxContext::empty() { + if ident.span.ctxt() == SyntaxContext::empty() { return ident.name; } *self.name_map @@ -2089,10 +2089,7 @@ impl<'a> LoweringContext<'a> { name: self.lower_ident(match f.ident { Some(ident) => ident, // FIXME(jseyfried) positional field hygiene - None => Ident { - name: Symbol::intern(&index.to_string()), - ctxt: f.span.ctxt(), - }, + None => Ident::new(Symbol::intern(&index.to_string()), f.span), }), vis: self.lower_visibility(&f.vis, None), ty: self.lower_ty(&f.ty, ImplTraitContext::Disallowed), diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index c3b3e10201f99..7335511a5a051 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -655,7 +655,7 @@ impl<'a> HashStable> for ast::Ident { hasher: &mut StableHasher) { let ast::Ident { ref name, - ctxt: _ // Ignore this + span: _ // Ignore this } = *self; name.hash_stable(hcx, hasher); diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs index 72ba199eb2412..b920553ec3698 100644 --- a/src/librustc/ty/mod.rs +++ b/src/librustc/ty/mod.rs @@ -2088,8 +2088,8 @@ impl<'a, 'gcx, 'tcx> VariantDef { return Some(index); } let mut ident = name.to_ident(); - while ident.ctxt != SyntaxContext::empty() { - ident.ctxt.remove_mark(); + while ident.span.ctxt() != SyntaxContext::empty() { + ident.span.remove_mark(); if let Some(field) = self.fields.iter().position(|f| f.name.to_ident() == ident) { return Some(field); } @@ -2558,7 +2558,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { LOCAL_CRATE => self.hir.definitions().expansion(scope.index), _ => Mark::root(), }; - let scope = match ident.ctxt.adjust(expansion) { + let scope = match ident.span.adjust(expansion) { Some(macro_def) => self.hir.definitions().macro_def_scope(macro_def), None if block == DUMMY_NODE_ID => DefId::local(CRATE_DEF_INDEX), // Dummy DefId None => self.hir.get_module_parent(block), diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index c5e7fdb30d36a..70b73ebb8cdeb 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -466,11 +466,11 @@ impl<'a> PrinterSupport for HygieneAnnotation<'a> { impl<'a> pprust::PpAnn for HygieneAnnotation<'a> { fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> { match node { - pprust::NodeIdent(&ast::Ident { name, ctxt }) => { + pprust::NodeIdent(&ast::Ident { name, span }) => { s.s.space()?; // FIXME #16420: this doesn't display the connections // between syntax contexts - s.synth_comment(format!("{}{:?}", name.as_u32(), ctxt)) + s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt())) } pprust::NodeName(&name) => { s.s.space()?; diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 95be691b30c79..d951a7f1cc1cd 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -35,7 +35,6 @@ use rustc::util::nodemap::NodeSet; use syntax::ast::{self, CRATE_NODE_ID, Ident}; use syntax::symbol::keywords; use syntax_pos::Span; -use syntax_pos::hygiene::SyntaxContext; use std::cmp; use std::mem::replace; @@ -495,11 +494,11 @@ struct NamePrivacyVisitor<'a, 'tcx: 'a> { impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> { // Checks that a field in a struct constructor (expression or pattern) is accessible. fn check_field(&mut self, - use_ctxt: SyntaxContext, // Syntax context of the field name at the use site + use_ctxt: Span, // Syntax context of the field name at the use site 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 { ctxt: use_ctxt.modern(), ..keywords::Invalid.ident() }; + let ident = Ident::new(keywords::Invalid.name(), use_ctxt.modern()); let def_id = self.tcx.adjust_ident(ident, def.did, self.current_item).1; if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) { struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private", @@ -573,14 +572,14 @@ impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> { for variant_field in &variant.fields { let field = fields.iter().find(|f| f.name.node == variant_field.name); let (use_ctxt, span) = match field { - Some(field) => (field.name.node.to_ident().ctxt, field.span), - None => (base.span.ctxt(), base.span), + Some(field) => (field.name.node.to_ident().span, field.span), + None => (base.span, base.span), }; self.check_field(use_ctxt, span, adt, variant_field); } } else { for field in fields { - let use_ctxt = field.name.node.to_ident().ctxt; + let use_ctxt = field.name.node.to_ident().span; let field_def = variant.field_named(field.name.node); self.check_field(use_ctxt, field.span, adt, field_def); } @@ -599,7 +598,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> { let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap(); let variant = adt.variant_of_def(def); for field in fields { - let use_ctxt = field.node.name.to_ident().ctxt; + let use_ctxt = field.node.name.to_ident().span; let field_def = variant.field_named(field.node.name); self.check_field(use_ctxt, field.span, adt, field_def); } diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index 397590012fd73..f7fd190af0c29 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -157,7 +157,7 @@ impl<'a> Resolver<'a> { // Disallow `use $crate;` if source.name == keywords::DollarCrate.name() && path.segments.len() == 1 { - let crate_root = self.resolve_crate_root(source.ctxt, true); + let crate_root = self.resolve_crate_root(source.span.ctxt(), true); let crate_name = match crate_root.kind { ModuleKind::Def(_, name) => name, ModuleKind::Block(..) => unreachable!(), diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 64d57ea34c229..cb5c6f8ec5f87 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -1912,10 +1912,11 @@ impl<'a> Resolver<'a> { path_span: Span) -> Option> { if ns == TypeNS { - ident.ctxt = if ident.name == keywords::SelfType.name() { - SyntaxContext::empty() // FIXME(jseyfried) improve `Self` hygiene + ident.span = if ident.name == keywords::SelfType.name() { + // FIXME(jseyfried) improve `Self` hygiene + ident.span.with_ctxt(SyntaxContext::empty()) } else { - ident.ctxt.modern() + ident.span.modern() } } @@ -1931,10 +1932,10 @@ impl<'a> Resolver<'a> { module = match self.ribs[ns][i].kind { ModuleRibKind(module) => module, - MacroDefinition(def) if def == self.macro_def(ident.ctxt) => { + MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => { // If an invocation of this macro created `ident`, give up on `ident` // and switch to `ident`'s source from the macro definition. - ident.ctxt.remove_mark(); + ident.span.remove_mark(); continue } _ => continue, @@ -1954,9 +1955,9 @@ impl<'a> Resolver<'a> { } } - ident.ctxt = ident.ctxt.modern(); + ident.span = ident.span.modern(); loop { - module = unwrap_or!(self.hygienic_lexical_parent(module, &mut ident.ctxt), break); + module = unwrap_or!(self.hygienic_lexical_parent(module, &mut ident.span), break); let orig_current_module = self.current_module; self.current_module = module; // Lexical resolutions can never be a privacy error. let result = self.resolve_ident_in_module_unadjusted( @@ -1980,10 +1981,10 @@ impl<'a> Resolver<'a> { } } - fn hygienic_lexical_parent(&mut self, mut module: Module<'a>, ctxt: &mut SyntaxContext) + fn hygienic_lexical_parent(&mut self, mut module: Module<'a>, span: &mut Span) -> Option> { - if !module.expansion.is_descendant_of(ctxt.outer()) { - return Some(self.macro_def_scope(ctxt.remove_mark())); + if !module.expansion.is_descendant_of(span.ctxt().outer()) { + return Some(self.macro_def_scope(span.remove_mark())); } if let ModuleKind::Block(..) = module.kind { @@ -1995,7 +1996,7 @@ impl<'a> Resolver<'a> { let parent_expansion = parent.expansion.modern(); if module_expansion.is_descendant_of(parent_expansion) && parent_expansion != module_expansion { - return if parent_expansion.is_descendant_of(ctxt.outer()) { + return if parent_expansion.is_descendant_of(span.ctxt().outer()) { Some(parent) } else { None @@ -2016,9 +2017,9 @@ impl<'a> Resolver<'a> { record_used: bool, span: Span) -> Result<&'a NameBinding<'a>, Determinacy> { - ident.ctxt = ident.ctxt.modern(); + ident.span = ident.span.modern(); let orig_current_module = self.current_module; - if let Some(def) = ident.ctxt.adjust(module.expansion) { + if let Some(def) = ident.span.adjust(module.expansion) { self.current_module = self.macro_def_scope(def); } let result = self.resolve_ident_in_module_unadjusted( @@ -2108,8 +2109,8 @@ impl<'a> Resolver<'a> { // If an invocation of this macro created `ident`, give up on `ident` // and switch to `ident`'s source from the macro definition. MacroDefinition(def) => { - if def == self.macro_def(ident.ctxt) { - ident.ctxt.remove_mark(); + if def == self.macro_def(ident.span.ctxt()) { + ident.span.remove_mark(); } } _ => { @@ -2873,7 +2874,7 @@ impl<'a> Resolver<'a> { } if path.len() == 1 && this.self_type_is_available(span) { if let Some(candidate) = this.lookup_assoc_candidate(ident.node, ns, is_expected) { - let self_is_available = this.self_value_is_available(path[0].node.ctxt, span); + let self_is_available = this.self_value_is_available(path[0].node.span, span); match candidate { AssocSuggestion::Field => { err.span_suggestion(span, "try", @@ -3084,9 +3085,9 @@ impl<'a> Resolver<'a> { if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false } } - fn self_value_is_available(&mut self, ctxt: SyntaxContext, span: Span) -> bool { - let ident = Ident { name: keywords::SelfValue.name(), ctxt: ctxt }; - let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, false, span); + fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool { + let ident = Ident::new(keywords::SelfValue.name(), self_span); + let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, false, path_span); if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false } } @@ -3219,11 +3220,11 @@ impl<'a> Resolver<'a> { let name = ident.node.name; if i == 0 && ns == TypeNS && name == keywords::SelfValue.name() { - let mut ctxt = ident.node.ctxt.modern(); + let mut ctxt = ident.node.span.ctxt().modern(); module = Some(self.resolve_self(&mut ctxt, self.current_module)); continue } else if allow_super && ns == TypeNS && name == keywords::Super.name() { - let mut ctxt = ident.node.ctxt.modern(); + let mut ctxt = ident.node.span.ctxt().modern(); let self_module = match i { 0 => self.resolve_self(&mut ctxt, self.current_module), _ => module.unwrap(), @@ -3245,11 +3246,11 @@ impl<'a> Resolver<'a> { (i == 1 && name == keywords::Crate.name() && path[0].node.name == keywords::CrateRoot.name()) { // `::a::b` or `::crate::a::b` - module = Some(self.resolve_crate_root(ident.node.ctxt, false)); + module = Some(self.resolve_crate_root(ident.node.span.ctxt(), false)); continue } else if i == 0 && name == keywords::DollarCrate.name() { // `$crate::a::b` - module = Some(self.resolve_crate_root(ident.node.ctxt, true)); + module = Some(self.resolve_crate_root(ident.node.span.ctxt(), true)); continue } else if i == 1 && !token::is_path_segment_keyword(ident.node) { let prev_name = path[0].node.name; @@ -3771,12 +3772,12 @@ impl<'a> Resolver<'a> { } } - ident.ctxt = ident.ctxt.modern(); + ident.span = ident.span.modern(); let mut search_module = self.current_module; loop { self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits); search_module = - unwrap_or!(self.hygienic_lexical_parent(search_module, &mut ident.ctxt), break); + unwrap_or!(self.hygienic_lexical_parent(search_module, &mut ident.span), break); } if let Some(prelude) = self.prelude { @@ -3808,7 +3809,7 @@ impl<'a> Resolver<'a> { for &(trait_name, binding) in traits.as_ref().unwrap().iter() { let module = binding.module().unwrap(); let mut ident = ident; - if ident.ctxt.glob_adjust(module.expansion, binding.span.ctxt().modern()).is_none() { + if ident.span.glob_adjust(module.expansion, binding.span.ctxt().modern()).is_none() { continue } if self.resolve_ident_in_module_unadjusted(module, ident, ns, false, false, module.span) diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index 0692a1e0d7f8a..289556cd45e0f 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -140,7 +140,7 @@ impl<'a> base::Resolver for Resolver<'a> { let ident = path.segments[0].identifier; if ident.name == keywords::DollarCrate.name() { path.segments[0].identifier.name = keywords::CrateRoot.name(); - let module = self.0.resolve_crate_root(ident.ctxt, true); + let module = self.0.resolve_crate_root(ident.span.ctxt(), true); if !module.is_local() { let span = path.segments[0].span; path.segments.insert(1, match module.kind { @@ -534,7 +534,7 @@ impl<'a> Resolver<'a> { } module = match module { - Some(module) => self.hygienic_lexical_parent(module, &mut ident.ctxt), + Some(module) => self.hygienic_lexical_parent(module, &mut ident.span), None => return potential_illegal_shadower, } } diff --git a/src/librustc_resolve/resolve_imports.rs b/src/librustc_resolve/resolve_imports.rs index 7036bdd0e2b07..90a90d731534b 100644 --- a/src/librustc_resolve/resolve_imports.rs +++ b/src/librustc_resolve/resolve_imports.rs @@ -238,7 +238,7 @@ impl<'a> Resolver<'a> { } let module = unwrap_or!(directive.imported_module.get(), return Err(Undetermined)); let (orig_current_module, mut ident) = (self.current_module, ident.modern()); - match ident.ctxt.glob_adjust(module.expansion, directive.span.ctxt().modern()) { + match ident.span.glob_adjust(module.expansion, directive.span.ctxt().modern()) { Some(Some(def)) => self.current_module = self.macro_def_scope(def), Some(None) => {} None => continue, @@ -398,7 +398,7 @@ impl<'a> Resolver<'a> { // Define `binding` in `module`s glob importers. for directive in module.glob_importers.borrow_mut().iter() { let mut ident = ident.modern(); - let scope = match ident.ctxt.reverse_glob_adjust(module.expansion, + let scope = match ident.span.reverse_glob_adjust(module.expansion, directive.span.ctxt().modern()) { Some(Some(def)) => self.macro_def_scope(def), Some(None) => directive.parent, @@ -623,7 +623,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { "crate root imports need to be explicitly named: \ `use crate as name;`".to_string())); } else { - Some(self.resolve_crate_root(source.ctxt.modern(), false)) + Some(self.resolve_crate_root(source.span.ctxt().modern(), false)) } } else if is_extern && !token::is_path_segment_keyword(source) { let crate_id = @@ -860,7 +860,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { resolution.borrow().binding().map(|binding| (ident, binding)) }).collect::>(); for ((mut ident, ns), binding) in bindings { - let scope = match ident.ctxt.reverse_glob_adjust(module.expansion, + let scope = match ident.span.reverse_glob_adjust(module.expansion, directive.span.ctxt().modern()) { Some(Some(def)) => self.macro_def_scope(def), Some(None) => self.current_module, diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 27e0f6ad6ddd9..6d85e949d6bd8 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -3213,10 +3213,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { if !tuple_like { continue } debug!("tuple struct named {:?}", base_t); - let ident = ast::Ident { - name: Symbol::intern(&idx.node.to_string()), - ctxt: idx.span.ctxt().modern(), - }; + let ident = + ast::Ident::new(Symbol::intern(&idx.node.to_string()), idx.span.modern()); let (ident, def_scope) = self.tcx.adjust_ident(ident, base_def.did, self.body_id); let fields = &base_def.non_enum_variant().fields; diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 9d0c85a34f935..ec5dd7dfd179a 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -150,7 +150,7 @@ impl PathSegment { } pub fn crate_root(span: Span) -> Self { PathSegment { - identifier: Ident { ctxt: span.ctxt(), ..keywords::CrateRoot.ident() }, + identifier: Ident::new(keywords::CrateRoot.name(), span), span, parameters: None, } diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 5a735be55c0e6..1e264369f918d 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -876,8 +876,8 @@ impl<'a> ExtCtxt<'a> { ast::Ident::from_str(st) } pub fn std_path(&self, components: &[&str]) -> Vec { - let def_site = SyntaxContext::empty().apply_mark(self.current_expansion.mark); - iter::once(Ident { ctxt: def_site, ..keywords::DollarCrate.ident() }) + let def_site = DUMMY_SP.apply_mark(self.current_expansion.mark); + iter::once(Ident::new(keywords::DollarCrate.name(), def_site)) .chain(components.iter().map(|s| self.ident_of(s))) .collect() } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 105de13b976a1..31072159ab3f8 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -1378,7 +1378,7 @@ pub struct Marker(pub Mark); impl Folder for Marker { fn fold_ident(&mut self, mut ident: Ident) -> Ident { - ident.ctxt = ident.ctxt.apply_mark(self.0); + ident.span = ident.span.apply_mark(self.0); ident } diff --git a/src/libsyntax/ext/tt/quoted.rs b/src/libsyntax/ext/tt/quoted.rs index f324edeb1178a..01b971976a763 100644 --- a/src/libsyntax/ext/tt/quoted.rs +++ b/src/libsyntax/ext/tt/quoted.rs @@ -289,14 +289,11 @@ where // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special // metavariable that names the crate of the invokation. Some(tokenstream::TokenTree::Token(ident_span, ref token)) if token.is_ident() => { - let (ident, _) = token.ident().unwrap(); + let (ident, is_raw) = token.ident().unwrap(); let span = ident_span.with_lo(span.lo()); - if ident.name == keywords::Crate.name() { - let ident = ast::Ident { - name: keywords::DollarCrate.name(), - ..ident - }; - TokenTree::Token(span, token::Ident(ident, false)) + if ident.name == keywords::Crate.name() && !is_raw { + let ident = ast::Ident::new(keywords::DollarCrate.name(), ident.span); + TokenTree::Token(span, token::Ident(ident, is_raw)) } else { TokenTree::MetaVar(span, ident) } diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index 3f01d5ec6dd87..12ada3bdbc0b9 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -166,7 +166,7 @@ pub fn transcribe(cx: &ExtCtxt, } } else { let ident = - Ident { ctxt: ident.ctxt.apply_mark(cx.current_expansion.mark), ..ident }; + Ident::new(ident.name, ident.span.apply_mark(cx.current_expansion.mark)); sp = sp.with_ctxt(sp.ctxt().apply_mark(cx.current_expansion.mark)); result.push(TokenTree::Token(sp, token::Dollar).into()); result.push(TokenTree::Token(sp, token::Token::from_ast_ident(ident)).into()); diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 068929c8948df..152c4c31eb3e3 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -76,7 +76,7 @@ impl<'a> StringReader<'a> { fn mk_ident(&self, string: &str) -> Ident { let mut ident = Ident::from_str(string); if let Some(span) = self.override_span { - ident.ctxt = span.ctxt(); + ident.span = span; } ident } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 1bed6109dd26e..30be2389e7e3f 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -743,7 +743,7 @@ pub trait PrintState<'a> { segment.identifier.name != keywords::DollarCrate.name() { self.writer().word(&segment.identifier.name.as_str())?; } else if segment.identifier.name == keywords::DollarCrate.name() { - self.print_dollar_crate(segment.identifier.ctxt)?; + self.print_dollar_crate(segment.identifier.span.ctxt())?; } } self.writer().space()?; @@ -2424,7 +2424,7 @@ impl<'a> State<'a> { self.print_path_parameters(parameters, colons_before_params)?; } } else if segment.identifier.name == keywords::DollarCrate.name() { - self.print_dollar_crate(segment.identifier.ctxt)?; + self.print_dollar_crate(segment.identifier.span.ctxt())?; } Ok(()) } diff --git a/src/libsyntax_ext/concat_idents.rs b/src/libsyntax_ext/concat_idents.rs index d513008f0e2d3..2b80d69876423 100644 --- a/src/libsyntax_ext/concat_idents.rs +++ b/src/libsyntax_ext/concat_idents.rs @@ -9,6 +9,7 @@ // except according to those terms. use syntax::ast; +use syntax::codemap::DUMMY_SP; use syntax::ext::base::*; use syntax::ext::base; use syntax::feature_gate; @@ -16,7 +17,6 @@ use syntax::parse::token; use syntax::ptr::P; use syntax_pos::Span; use syntax_pos::symbol::Symbol; -use syntax_pos::hygiene::SyntaxContext; use syntax::tokenstream::TokenTree; pub fn expand_syntax_ext<'cx>(cx: &'cx mut ExtCtxt, @@ -53,11 +53,8 @@ pub fn expand_syntax_ext<'cx>(cx: &'cx mut ExtCtxt, } } } - let res = ast::Ident { - name: Symbol::intern(&res_str), - ctxt: SyntaxContext::empty().apply_mark(cx.current_expansion.mark), - }; - + let res = ast::Ident::new(Symbol::intern(&res_str), + DUMMY_SP.apply_mark(cx.current_expansion.mark)); struct Result { ident: ast::Ident, span: Span, diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index cc3e8b6e6b7c0..25a2969448835 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -18,10 +18,9 @@ use syntax::ast; use syntax::ast::{Expr, GenericParam, Generics, Ident, SelfKind}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; -use syntax::codemap::respan; +use syntax::codemap::{respan, DUMMY_SP}; use syntax::ptr::P; use syntax_pos::Span; -use syntax_pos::hygiene::SyntaxContext; use syntax_pos::symbol::keywords; /// The types of pointers @@ -93,8 +92,8 @@ impl<'a> Path<'a> { PathKind::Global => cx.path_all(span, true, idents, lt, tys, Vec::new()), PathKind::Local => cx.path_all(span, false, idents, lt, tys, Vec::new()), PathKind::Std => { - let def_site = SyntaxContext::empty().apply_mark(cx.current_expansion.mark); - idents.insert(0, Ident { ctxt: def_site, ..keywords::DollarCrate.ident() }); + let def_site = DUMMY_SP.apply_mark(cx.current_expansion.mark); + idents.insert(0, Ident::new(keywords::DollarCrate.name(), def_site)); cx.path_all(span, false, idents, lt, tys, Vec::new()) } } diff --git a/src/libsyntax_pos/hygiene.rs b/src/libsyntax_pos/hygiene.rs index aba71bd046831..c180563450f83 100644 --- a/src/libsyntax_pos/hygiene.rs +++ b/src/libsyntax_pos/hygiene.rs @@ -123,7 +123,7 @@ pub struct HygieneData { marks: Vec, syntax_contexts: Vec, markings: HashMap<(SyntaxContext, Mark), SyntaxContext>, - gensym_to_ctxt: HashMap, + gensym_to_ctxt: HashMap, } impl HygieneData { @@ -461,7 +461,7 @@ impl Symbol { pub fn from_ident(ident: Ident) -> Symbol { HygieneData::with(|data| { let gensym = ident.name.gensymed(); - data.gensym_to_ctxt.insert(gensym, ident.ctxt); + data.gensym_to_ctxt.insert(gensym, ident.span); gensym }) } @@ -469,7 +469,7 @@ impl Symbol { pub fn to_ident(self) -> Ident { HygieneData::with(|data| { match data.gensym_to_ctxt.get(&self) { - Some(&ctxt) => Ident { name: self.interned(), ctxt: ctxt }, + Some(&span) => Ident::new(self.interned(), span), None => Ident::with_empty_ctxt(self), } }) diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs index eb345200f413d..8b2ebfef2504e 100644 --- a/src/libsyntax_pos/lib.rs +++ b/src/libsyntax_pos/lib.rs @@ -50,7 +50,7 @@ extern crate serialize as rustc_serialize; // used by deriving extern crate unicode_width; pub mod hygiene; -pub use hygiene::{SyntaxContext, ExpnInfo, ExpnFormat, NameAndSpan, CompilerDesugaringKind}; +pub use hygiene::{Mark, SyntaxContext, ExpnInfo, ExpnFormat, NameAndSpan, CompilerDesugaringKind}; mod span_encoding; pub use span_encoding::{Span, DUMMY_SP}; @@ -422,6 +422,52 @@ impl Span { if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt }, ) } + + #[inline] + pub fn apply_mark(self, mark: Mark) -> Span { + let span = self.data(); + span.with_ctxt(span.ctxt.apply_mark(mark)) + } + + #[inline] + pub fn remove_mark(&mut self) -> Mark { + let mut span = self.data(); + let mark = span.ctxt.remove_mark(); + *self = Span::new(span.lo, span.hi, span.ctxt); + mark + } + + #[inline] + pub fn adjust(&mut self, expansion: Mark) -> Option { + let mut span = self.data(); + let mark = span.ctxt.adjust(expansion); + *self = Span::new(span.lo, span.hi, span.ctxt); + mark + } + + #[inline] + pub fn glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext) + -> Option> { + let mut span = self.data(); + let mark = span.ctxt.glob_adjust(expansion, glob_ctxt); + *self = Span::new(span.lo, span.hi, span.ctxt); + mark + } + + #[inline] + pub fn reverse_glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext) + -> Option> { + let mut span = self.data(); + let mark = span.ctxt.reverse_glob_adjust(expansion, glob_ctxt); + *self = Span::new(span.lo, span.hi, span.ctxt); + mark + } + + #[inline] + pub fn modern(self) -> Span { + let span = self.data(); + span.with_ctxt(span.ctxt.modern()) + } } #[derive(Clone, Debug)] diff --git a/src/libsyntax_pos/symbol.rs b/src/libsyntax_pos/symbol.rs index 098eafef2585c..661a28d837535 100644 --- a/src/libsyntax_pos/symbol.rs +++ b/src/libsyntax_pos/symbol.rs @@ -13,21 +13,27 @@ //! type, and vice versa. use hygiene::SyntaxContext; -use GLOBALS; +use {Span, DUMMY_SP, GLOBALS}; use serialize::{Decodable, Decoder, Encodable, Encoder}; use std::collections::HashMap; use std::fmt; +use std::hash::{Hash, Hasher}; -#[derive(Copy, Clone, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Eq)] pub struct Ident { pub name: Symbol, - pub ctxt: SyntaxContext, + pub span: Span, } impl Ident { + #[inline] + pub const fn new(name: Symbol, span: Span) -> Ident { + Ident { name, span } + } + #[inline] pub const fn with_empty_ctxt(name: Symbol) -> Ident { - Ident { name: name, ctxt: SyntaxContext::empty() } + Ident::new(name, DUMMY_SP) } /// Maps a string to an identifier with an empty syntax context. @@ -36,17 +42,30 @@ impl Ident { } pub fn without_first_quote(&self) -> Ident { - Ident { name: Symbol::from(self.name.as_str().trim_left_matches('\'')), ctxt: self.ctxt } + Ident::new(Symbol::from(self.name.as_str().trim_left_matches('\'')), self.span) } pub fn modern(self) -> Ident { - Ident { name: self.name, ctxt: self.ctxt.modern() } + Ident::new(self.name, self.span.modern()) + } +} + +impl PartialEq for Ident { + fn eq(&self, rhs: &Self) -> bool { + self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt() + } +} + +impl Hash for Ident { + fn hash(&self, state: &mut H) { + self.name.hash(state); + self.span.ctxt().hash(state); } } impl fmt::Debug for Ident { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}{:?}", self.name, self.ctxt) + write!(f, "{}{:?}", self.name, self.span.ctxt()) } } @@ -58,7 +77,7 @@ impl fmt::Display for Ident { impl Encodable for Ident { fn encode(&self, s: &mut S) -> Result<(), S::Error> { - if self.ctxt.modern() == SyntaxContext::empty() { + if self.span.ctxt().modern() == SyntaxContext::empty() { s.emit_str(&self.name.as_str()) } else { // FIXME(jseyfried) intercrate hygiene let mut string = "#".to_owned(); From 8719d1ed05761b344d611ae0893b1d994b6ebe6f Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sun, 18 Mar 2018 03:53:41 +0300 Subject: [PATCH 02/10] Rename `PathSegment::identifier` to `ident` --- src/librustc/hir/lowering.rs | 6 ++-- src/librustc/ich/impls_syntax.rs | 2 +- src/librustc_resolve/build_reduced_graph.rs | 8 ++--- src/librustc_resolve/lib.rs | 12 ++++---- src/librustc_resolve/macros.rs | 12 ++++---- src/librustdoc/clean/mod.rs | 12 ++------ src/libsyntax/ast.rs | 20 +++++-------- src/libsyntax/attr.rs | 6 ++-- src/libsyntax/ext/build.rs | 6 ++-- src/libsyntax/ext/derive.rs | 2 +- src/libsyntax/ext/expand.rs | 8 ++--- src/libsyntax/ext/quote.rs | 2 +- src/libsyntax/feature_gate.rs | 4 +-- src/libsyntax/fold.rs | 6 ++-- src/libsyntax/parse/parser.rs | 4 +-- src/libsyntax/print/pprust.rs | 24 +++++++-------- src/libsyntax/visit.rs | 2 +- src/libsyntax_ext/deriving/generic/mod.rs | 4 +-- .../pprust-expr-roundtrip.rs | 29 ++++--------------- 19 files changed, 67 insertions(+), 102 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index c47f67ec74093..2ca386e287d83 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1607,7 +1607,7 @@ impl<'a> LoweringContext<'a> { } hir::PathSegment::new( - self.lower_ident(segment.identifier), + self.lower_ident(segment.ident), parameters, infer_types, ) @@ -2356,11 +2356,11 @@ impl<'a> LoweringContext<'a> { // Correctly resolve `self` imports if path.segments.len() > 1 - && path.segments.last().unwrap().identifier.name == keywords::SelfValue.name() + && path.segments.last().unwrap().ident.name == keywords::SelfValue.name() { let _ = path.segments.pop(); if rename.is_none() { - *name = path.segments.last().unwrap().identifier.name; + *name = path.segments.last().unwrap().ident.name; } } diff --git a/src/librustc/ich/impls_syntax.rs b/src/librustc/ich/impls_syntax.rs index 425459f448fad..e3b0d2c9d2cc5 100644 --- a/src/librustc/ich/impls_syntax.rs +++ b/src/librustc/ich/impls_syntax.rs @@ -211,7 +211,7 @@ impl<'a> HashStable> for ast::Attribute { style.hash_stable(hcx, hasher); path.segments.len().hash_stable(hcx, hasher); for segment in &path.segments { - segment.identifier.name.hash_stable(hcx, hasher); + segment.ident.name.hash_stable(hcx, hasher); } for tt in tokens.trees() { tt.hash_stable(hcx, hasher); diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index f7fd190af0c29..3598fe1d66cc4 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -115,7 +115,7 @@ impl<'a> Resolver<'a> { let mut module_path: Vec<_> = prefix.segments.iter() .chain(path.segments.iter()) - .map(|seg| respan(seg.span, seg.identifier)) + .map(|seg| respan(seg.span, seg.ident)) .collect(); match use_tree.kind { @@ -196,11 +196,7 @@ impl<'a> Resolver<'a> { ast::UseTreeKind::Nested(ref items) => { let prefix = ast::Path { segments: module_path.iter() - .map(|s| ast::PathSegment { - identifier: s.node, - span: s.span, - parameters: None, - }) + .map(|s| ast::PathSegment::from_ident(s.node, s.span)) .collect(), span: path.span, }; diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index cb5c6f8ec5f87..b6a43949ca3d0 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -2351,7 +2351,7 @@ impl<'a> Resolver<'a> { let mut new_id = None; if let Some(trait_ref) = opt_trait_ref { let path: Vec<_> = trait_ref.path.segments.iter() - .map(|seg| respan(seg.span, seg.identifier)) + .map(|seg| respan(seg.span, seg.ident)) .collect(); let def = self.smart_resolve_path_fragment( trait_ref.ref_id, @@ -2786,7 +2786,7 @@ impl<'a> Resolver<'a> { source: PathSource) -> PathResolution { let segments = &path.segments.iter() - .map(|seg| respan(seg.span, seg.identifier)) + .map(|seg| respan(seg.span, seg.ident)) .collect::>(); self.smart_resolve_path_fragment(id, qself, segments, path.span, source) } @@ -2924,7 +2924,7 @@ impl<'a> Resolver<'a> { } ExprKind::MethodCall(ref segment, ..) => { err.span_label(parent.span, format!("did you mean `{}::{}(...)`?", - path_str, segment.identifier)); + path_str, segment.ident)); return (err, candidates); } _ => {} @@ -3750,7 +3750,7 @@ impl<'a> Resolver<'a> { ExprKind::MethodCall(ref segment, ..) => { debug!("(recording candidate traits for expr) recording traits for {}", expr.id); - let traits = self.get_traits_containing_item(segment.identifier, ValueNS); + let traits = self.get_traits_containing_item(segment.ident, ValueNS); self.trait_map.insert(expr.id, traits); } _ => { @@ -4222,7 +4222,7 @@ impl<'a> Resolver<'a> { if attr.path.segments.len() > 1 { continue } - let ident = attr.path.segments[0].identifier; + let ident = attr.path.segments[0].ident; let result = self.resolve_lexical_macro_path_segment(ident, MacroNS, false, @@ -4267,7 +4267,7 @@ fn names_to_string(idents: &[SpannedIdent]) -> String { fn path_names_to_string(path: &Path) -> String { names_to_string(&path.segments.iter() - .map(|seg| respan(seg.span, seg.identifier)) + .map(|seg| respan(seg.span, seg.ident)) .collect::>()) } diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index 289556cd45e0f..c65ee11e427fa 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -137,9 +137,9 @@ impl<'a> base::Resolver for Resolver<'a> { impl<'a, 'b> Folder for EliminateCrateVar<'a, 'b> { fn fold_path(&mut self, mut path: ast::Path) -> ast::Path { - let ident = path.segments[0].identifier; + let ident = path.segments[0].ident; if ident.name == keywords::DollarCrate.name() { - path.segments[0].identifier.name = keywords::CrateRoot.name(); + path.segments[0].ident.name = keywords::CrateRoot.name(); let module = self.0.resolve_crate_root(ident.span.ctxt(), true); if !module.is_local() { let span = path.segments[0].span; @@ -249,7 +249,7 @@ impl<'a> base::Resolver for Resolver<'a> { if traits[j].segments.len() > 1 { continue } - let trait_name = traits[j].segments[0].identifier.name; + let trait_name = traits[j].segments[0].ident.name; let legacy_name = Symbol::intern(&format!("derive_{}", trait_name)); if !self.global_macros.contains_key(&legacy_name) { continue @@ -268,7 +268,7 @@ impl<'a> base::Resolver for Resolver<'a> { if k > 0 { tokens.push(TokenTree::Token(path.span, Token::ModSep).into()); } - let tok = Token::from_ast_ident(segment.identifier); + let tok = Token::from_ast_ident(segment.ident); tokens.push(TokenTree::Token(path.span, tok).into()); } } @@ -365,7 +365,7 @@ impl<'a> Resolver<'a> { } let attr_name = match path.segments.len() { - 1 => path.segments[0].identifier.name, + 1 => path.segments[0].ident.name, _ => return Err(determinacy), }; for path in traits { @@ -413,7 +413,7 @@ impl<'a> Resolver<'a> { kind: MacroKind, force: bool) -> Result { let ast::Path { ref segments, span } = *path; - let path: Vec<_> = segments.iter().map(|seg| respan(seg.span, seg.identifier)).collect(); + let path: Vec<_> = segments.iter().map(|seg| respan(seg.span, seg.ident)).collect(); let invocation = self.invocations[&scope]; let module = invocation.module.get(); self.current_module = if module.is_trait() { module.parent.unwrap() } else { module }; diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 6ada4ccfbddc2..32b80924e568d 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1146,16 +1146,8 @@ fn resolve(cx: &DocContext, path_str: &str, is_val: bool) -> Result<(Def, Option fn macro_resolve(cx: &DocContext, path_str: &str) -> Option { use syntax::ext::base::{MacroKind, SyntaxExtension}; use syntax::ext::hygiene::Mark; - let segment = ast::PathSegment { - identifier: ast::Ident::from_str(path_str), - span: DUMMY_SP, - parameters: None, - }; - let path = ast::Path { - span: DUMMY_SP, - segments: vec![segment], - }; - + let segment = ast::PathSegment::from_ident(ast::Ident::from_str(path_str), DUMMY_SP); + let path = ast::Path { segments: vec![segment], span: DUMMY_SP }; let mut resolver = cx.resolver.borrow_mut(); let mark = Mark::root(); let res = resolver diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index ec5dd7dfd179a..a3839a861c6c7 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -82,7 +82,7 @@ pub struct Path { impl<'a> PartialEq<&'a str> for Path { fn eq(&self, string: &&'a str) -> bool { - self.segments.len() == 1 && self.segments[0].identifier.name == *string + self.segments.len() == 1 && self.segments[0].ident.name == *string } } @@ -101,17 +101,17 @@ impl fmt::Display for Path { impl Path { // convert a span and an identifier to the corresponding // 1-segment path - pub fn from_ident(s: Span, identifier: Ident) -> Path { + pub fn from_ident(s: Span, ident: Ident) -> Path { Path { span: s, - segments: vec![PathSegment::from_ident(identifier, s)], + segments: vec![PathSegment::from_ident(ident, s)], } } // Make a "crate root" segment for this path unless it already has it // or starts with something like `self`/`super`/`$crate`/etc. pub fn make_root(&self) -> Option { - if let Some(ident) = self.segments.get(0).map(|seg| seg.identifier) { + if let Some(ident) = self.segments.get(0).map(|seg| seg.ident) { if ::parse::token::is_path_segment_keyword(ident) && ident.name != keywords::Crate.name() { return None; @@ -121,7 +121,7 @@ impl Path { } pub fn is_global(&self) -> bool { - !self.segments.is_empty() && self.segments[0].identifier.name == keywords::CrateRoot.name() + !self.segments.is_empty() && self.segments[0].ident.name == keywords::CrateRoot.name() } } @@ -131,7 +131,7 @@ impl Path { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct PathSegment { /// The identifier portion of this path segment. - pub identifier: Ident, + pub ident: Ident, /// Span of the segment identifier. pub span: Span, @@ -146,14 +146,10 @@ pub struct PathSegment { impl PathSegment { pub fn from_ident(ident: Ident, span: Span) -> Self { - PathSegment { identifier: ident, span: span, parameters: None } + PathSegment { ident, span, parameters: None } } pub fn crate_root(span: Span) -> Self { - PathSegment { - identifier: Ident::new(keywords::CrateRoot.name(), span), - span, - parameters: None, - } + PathSegment::from_ident(Ident::new(keywords::CrateRoot.name(), span), span) } } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 5954b9eb27475..739679b71d5b1 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -215,7 +215,7 @@ impl Attribute { pub fn name(&self) -> Option { match self.path.segments.len() { - 1 => Some(self.path.segments[0].identifier.name), + 1 => Some(self.path.segments[0].ident.name), _ => None, } } @@ -301,7 +301,7 @@ impl Attribute { let mut tokens = self.tokens.trees().peekable(); Some(MetaItem { name: match self.path.segments.len() { - 1 => self.path.segments[0].identifier.name, + 1 => self.path.segments[0].ident.name, _ => return None, }, node: if let Some(node) = MetaItemKind::from_tokens(&mut tokens) { @@ -353,7 +353,7 @@ impl Attribute { } Ok(MetaItem { - name: self.path.segments.last().unwrap().identifier.name, + name: self.path.segments.last().unwrap().ident.name, node: self.parse(sess, |parser| parser.parse_meta_item_kind())?, span: self.span, }) diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 269517e998f5b..8dabc03c2f95b 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -319,7 +319,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { types: Vec>, bindings: Vec ) -> ast::Path { - let last_identifier = idents.pop().unwrap(); + let last_ident = idents.pop().unwrap(); let mut segments: Vec = Vec::new(); segments.extend(idents.into_iter().map(|i| ast::PathSegment::from_ident(i, span))); @@ -328,7 +328,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } else { None }; - segments.push(ast::PathSegment { identifier: last_identifier, span, parameters }); + segments.push(ast::PathSegment { ident: last_ident, span, parameters }); let mut path = ast::Path { span, segments }; if global { if let Some(seg) = path.make_root() { @@ -367,7 +367,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { None }; path.segments.push(ast::PathSegment { - identifier: ident.node, + ident: ident.node, span: ident.span, parameters, }); diff --git a/src/libsyntax/ext/derive.rs b/src/libsyntax/ext/derive.rs index c7fa0331c1bd5..6bf166dfe950a 100644 --- a/src/libsyntax/ext/derive.rs +++ b/src/libsyntax/ext/derive.rs @@ -54,7 +54,7 @@ pub fn add_derived_markers(cx: &mut ExtCtxt, span: Span, traits: &[ast::Path] pretty_name.push_str(", "); } pretty_name.push_str(&path.to_string()); - names.insert(unwrap_or!(path.segments.get(0), continue).identifier.name); + names.insert(unwrap_or!(path.segments.get(0), continue).ident.name); } pretty_name.push(')'); diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 31072159ab3f8..f9a6ab49039dd 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -168,10 +168,10 @@ fn macro_bang_format(path: &ast::Path) -> ExpnFormat { path_str.push_str("::"); } - if segment.identifier.name != keywords::CrateRoot.name() && - segment.identifier.name != keywords::DollarCrate.name() + if segment.ident.name != keywords::CrateRoot.name() && + segment.ident.name != keywords::DollarCrate.name() { - path_str.push_str(&segment.identifier.name.as_str()) + path_str.push_str(&segment.ident.name.as_str()) } } @@ -688,7 +688,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { opt_expanded } else { let msg = format!("non-{kind} macro in {kind} position: {name}", - name = path.segments[0].identifier.name, kind = kind.name()); + name = path.segments[0].ident.name, kind = kind.name()); self.cx.span_err(path.span, &msg); self.cx.trace_macros_diag(); kind.dummy(span) diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index 540a03ff032ff..b412c2fbc7f7c 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -239,7 +239,7 @@ pub mod rt { inner.push(TokenTree::Token(self.span, token::Colon).into()); } inner.push(TokenTree::Token( - self.span, token::Token::from_ast_ident(segment.identifier) + self.span, token::Token::from_ast_ident(segment.ident) ).into()); } inner.push(self.tokens.clone()); diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index 9d1f4ccf8a3d2..c2a0fcc9d2f7a 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -1766,10 +1766,10 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { fn visit_path(&mut self, path: &'a ast::Path, _id: NodeId) { for segment in &path.segments { - if segment.identifier.name == keywords::Crate.name() { + if segment.ident.name == keywords::Crate.name() { gate_feature_post!(&self, crate_in_paths, segment.span, "`crate` in paths is experimental"); - } else if segment.identifier.name == keywords::Extern.name() { + } else if segment.ident.name == keywords::Extern.name() { gate_feature_post!(&self, extern_in_paths, segment.span, "`extern` in paths is experimental"); } diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 1bee67bf3604a..2c757a0a88738 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -449,8 +449,8 @@ pub fn noop_fold_usize(i: usize, _: &mut T) -> usize { pub fn noop_fold_path(Path { segments, span }: Path, fld: &mut T) -> Path { Path { - segments: segments.move_map(|PathSegment {identifier, span, parameters}| PathSegment { - identifier: fld.fold_ident(identifier), + segments: segments.move_map(|PathSegment {ident, span, parameters}| PathSegment { + ident: fld.fold_ident(ident), span: fld.new_span(span), parameters: parameters.map(|ps| ps.map(|ps| fld.fold_path_parameters(ps))), }), @@ -1195,7 +1195,7 @@ pub fn noop_fold_expr(Expr {id, node, span, attrs}: Expr, folder: &mu ExprKind::MethodCall(seg, args) => { ExprKind::MethodCall( PathSegment { - identifier: folder.fold_ident(seg.identifier), + ident: folder.fold_ident(seg.ident), span: folder.new_span(seg.span), parameters: seg.parameters.map(|ps| { ps.map(|ps| folder.fold_path_parameters(ps)) diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 9936eea935684..81f8428c2c77a 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -2051,7 +2051,7 @@ impl<'a> Parser<'a> { ParenthesizedParameterData { inputs, output, span }.into() }; - PathSegment { identifier: ident, span: ident_span, parameters } + PathSegment { ident, span: ident_span, parameters } } else { // Generic arguments are not found. PathSegment::from_ident(ident, ident_span) @@ -2592,7 +2592,7 @@ impl<'a> Parser<'a> { } let span = lo.to(self.prev_span); - let ident = respan(segment.span, segment.identifier); + let ident = respan(segment.span, segment.ident); self.mk_expr(span, ExprKind::Field(self_arg, ident), ThinVec::new()) } }) diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 30be2389e7e3f..b7026529a5ee5 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -739,11 +739,11 @@ pub trait PrintState<'a> { if i > 0 { self.writer().word("::")? } - if segment.identifier.name != keywords::CrateRoot.name() && - segment.identifier.name != keywords::DollarCrate.name() { - self.writer().word(&segment.identifier.name.as_str())?; - } else if segment.identifier.name == keywords::DollarCrate.name() { - self.print_dollar_crate(segment.identifier.span.ctxt())?; + if segment.ident.name != keywords::CrateRoot.name() && + segment.ident.name != keywords::DollarCrate.name() { + self.writer().word(&segment.ident.name.as_str())?; + } else if segment.ident.name == keywords::DollarCrate.name() { + self.print_dollar_crate(segment.ident.span.ctxt())?; } } self.writer().space()?; @@ -1981,7 +1981,7 @@ impl<'a> State<'a> { let base_args = &args[1..]; self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?; self.s.word(".")?; - self.print_ident(segment.identifier)?; + self.print_ident(segment.ident)?; if let Some(ref parameters) = segment.parameters { self.print_path_parameters(parameters, true)?; } @@ -2417,14 +2417,14 @@ impl<'a> State<'a> { colons_before_params: bool) -> io::Result<()> { - if segment.identifier.name != keywords::CrateRoot.name() && - segment.identifier.name != keywords::DollarCrate.name() { - self.print_ident(segment.identifier)?; + if segment.ident.name != keywords::CrateRoot.name() && + segment.ident.name != keywords::DollarCrate.name() { + self.print_ident(segment.ident)?; if let Some(ref parameters) = segment.parameters { self.print_path_parameters(parameters, colons_before_params)?; } - } else if segment.identifier.name == keywords::DollarCrate.name() { - self.print_dollar_crate(segment.identifier.span.ctxt())?; + } else if segment.ident.name == keywords::DollarCrate.name() { + self.print_dollar_crate(segment.ident.span.ctxt())?; } Ok(()) } @@ -2446,7 +2446,7 @@ impl<'a> State<'a> { self.s.word(">")?; self.s.word("::")?; let item_segment = path.segments.last().unwrap(); - self.print_ident(item_segment.identifier)?; + self.print_ident(item_segment.ident)?; match item_segment.parameters { Some(ref parameters) => self.print_path_parameters(parameters, colons_before_params), None => Ok(()), diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 3a2069efd89e7..88fddb1368689 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -372,7 +372,7 @@ pub fn walk_use_tree<'a, V: Visitor<'a>>( pub fn walk_path_segment<'a, V: Visitor<'a>>(visitor: &mut V, path_span: Span, segment: &'a PathSegment) { - visitor.visit_ident(path_span, segment.identifier); + visitor.visit_ident(path_span, segment.ident); if let Some(ref parameters) = segment.parameters { visitor.visit_path_parameters(path_span, parameters); } diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 3935f1722b615..c51f44cdeced2 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -367,7 +367,7 @@ fn find_type_parameters(ty: &ast::Ty, fn visit_ty(&mut self, ty: &'a ast::Ty) { if let ast::TyKind::Path(_, ref path) = ty.node { if let Some(segment) = path.segments.first() { - if self.ty_param_names.contains(&segment.identifier.name) { + if self.ty_param_names.contains(&segment.ident.name) { self.types.push(P(ty.clone())); } } @@ -622,7 +622,7 @@ impl<'a> TraitDef<'a> { // if we have already handled this type, skip it if let ast::TyKind::Path(_, ref p) = ty.node { if p.segments.len() == 1 && - ty_param_names.contains(&p.segments[0].identifier.name) || + ty_param_names.contains(&p.segments[0].ident.name) || processed_field_types.contains(&p.segments) { continue; }; diff --git a/src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs b/src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs index 920760cd34ac8..0406d2d22f435 100644 --- a/src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs +++ b/src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs @@ -61,15 +61,8 @@ fn expr(kind: ExprKind) -> P { } fn make_x() -> P { - let seg = PathSegment { - identifier: Ident::from_str("x"), - span: DUMMY_SP, - parameters: None, - }; - let path = Path { - span: DUMMY_SP, - segments: vec![seg], - }; + let seg = PathSegment::from_ident(Ident::from_str("x"), DUMMY_SP); + let path = Path { segments: vec![seg], span: DUMMY_SP }; expr(ExprKind::Path(None, path)) } @@ -89,12 +82,7 @@ fn iter_exprs(depth: usize, f: &mut FnMut(P)) { 0 => iter_exprs(depth - 1, &mut |e| g(ExprKind::Box(e))), 1 => iter_exprs(depth - 1, &mut |e| g(ExprKind::Call(e, vec![]))), 2 => { - let seg = PathSegment { - identifier: Ident::from_str("x"), - span: DUMMY_SP, - parameters: None, - }; - + let seg = PathSegment::from_ident(Ident::from_str("x"), DUMMY_SP); iter_exprs(depth - 1, &mut |e| g(ExprKind::MethodCall( seg.clone(), vec![e, make_x()]))); iter_exprs(depth - 1, &mut |e| g(ExprKind::MethodCall( @@ -163,15 +151,8 @@ fn iter_exprs(depth: usize, f: &mut FnMut(P)) { iter_exprs(depth - 1, &mut |e| g(ExprKind::Ret(Some(e)))); }, 14 => { - let seg = PathSegment { - identifier: Ident::from_str("S"), - span: DUMMY_SP, - parameters: None, - }; - let path = Path { - span: DUMMY_SP, - segments: vec![seg], - }; + let seg = PathSegment::new(Ident::from_str("S"), DUMMY_SP); + let path = Path { segments: vec![seg], span: DUMMY_SP }; g(ExprKind::Struct(path, vec![], Some(make_x()))); }, 15 => { From e2afefd80bf779bc3c6f697a3c6cc3a476993602 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sun, 18 Mar 2018 16:47:09 +0300 Subject: [PATCH 03/10] Get rid of `SpannedIdent` --- src/librustc/hir/lowering.rs | 14 +-- src/librustc_lint/builtin.rs | 10 +- src/librustc_mir/build/mod.rs | 4 +- src/librustc_mir/hair/pattern/mod.rs | 6 +- src/librustc_resolve/build_reduced_graph.rs | 15 ++- src/librustc_resolve/lib.rs | 133 ++++++++++---------- src/librustc_resolve/macros.rs | 17 +-- src/librustc_resolve/resolve_imports.rs | 28 ++--- src/librustc_save_analysis/lib.rs | 12 +- src/librustc_save_analysis/sig.rs | 2 +- src/libsyntax/ast.rs | 16 ++- src/libsyntax/attr.rs | 2 +- src/libsyntax/ext/base.rs | 2 +- src/libsyntax/ext/build.rs | 23 ++-- src/libsyntax/ext/quote.rs | 2 +- src/libsyntax/ext/tt/macro_parser.rs | 6 +- src/libsyntax/fold.rs | 26 ++-- src/libsyntax/parse/parser.rs | 67 +++++----- src/libsyntax/parse/token.rs | 6 +- src/libsyntax/print/pprust.rs | 52 ++++---- src/libsyntax/visit.rs | 10 +- src/libsyntax_ext/concat_idents.rs | 33 ++--- src/libsyntax_ext/deriving/generic/mod.rs | 10 +- src/libsyntax_pos/symbol.rs | 7 +- 24 files changed, 231 insertions(+), 272 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 2ca386e287d83..08b0def03b9ea 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1720,7 +1720,7 @@ impl<'a> LoweringContext<'a> { decl.inputs .iter() .map(|arg| match arg.pat.node { - PatKind::Ident(_, ident, None) => respan(ident.span, ident.node.name), + PatKind::Ident(_, ident, None) => respan(ident.span, ident.name), _ => respan(arg.pat.span, keywords::Invalid.name()), }) .collect() @@ -2099,7 +2099,7 @@ impl<'a> LoweringContext<'a> { fn lower_field(&mut self, f: &Field) -> hir::Field { hir::Field { - name: respan(f.ident.span, self.lower_ident(f.ident.node)), + name: respan(f.ident.span, self.lower_ident(f.ident)), expr: P(self.lower_expr(&f.expr)), span: f.span, is_shorthand: f.is_shorthand, @@ -2801,7 +2801,7 @@ impl<'a> LoweringContext<'a> { fn lower_pat(&mut self, p: &Pat) -> P { let node = match p.node { PatKind::Wild => hir::PatKind::Wild, - PatKind::Ident(ref binding_mode, pth1, ref sub) => { + PatKind::Ident(ref binding_mode, ident, ref sub) => { match self.resolver.get_resolution(p.id).map(|d| d.base_def()) { // `None` can occur in body-less function signatures def @ None | def @ Some(Def::Local(_)) => { @@ -2812,16 +2812,16 @@ impl<'a> LoweringContext<'a> { hir::PatKind::Binding( self.lower_binding_mode(binding_mode), canonical_id, - respan(pth1.span, pth1.node.name), + respan(ident.span, ident.name), sub.as_ref().map(|x| self.lower_pat(x)), ) } Some(def) => hir::PatKind::Path(hir::QPath::Resolved( None, P(hir::Path { - span: pth1.span, + span: ident.span, def, - segments: hir_vec![hir::PathSegment::from_name(pth1.node.name)], + segments: hir_vec![hir::PathSegment::from_name(ident.name)], }), )), } @@ -3071,7 +3071,7 @@ impl<'a> LoweringContext<'a> { ), ExprKind::Field(ref el, ident) => hir::ExprField( P(self.lower_expr(el)), - respan(ident.span, self.lower_ident(ident.node)), + respan(ident.span, self.lower_ident(ident)), ), ExprKind::TupField(ref el, ident) => hir::ExprTupField(P(self.lower_expr(el)), ident), ExprKind::Index(ref el, ref er) => { diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index c0728cb2b6669..2cc6708bc034e 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -171,16 +171,16 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns { if fieldpat.node.is_shorthand { continue; } - if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node { - if ident.node == fieldpat.node.name { + if let PatKind::Binding(_, _, name, None) = fieldpat.node.pat.node { + if name.node == fieldpat.node.name { let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span, &format!("the `{}:` in this pattern is redundant", - ident.node)); + name.node)); let subspan = cx.tcx.sess.codemap().span_through_char(fieldpat.span, ':'); err.span_suggestion_short(subspan, "remove this", - format!("{}", ident.node)); + format!("{}", name.node)); err.emit(); } } @@ -625,7 +625,7 @@ impl EarlyLintPass for AnonymousParameters { for arg in sig.decl.inputs.iter() { match arg.pat.node { ast::PatKind::Ident(_, ident, None) => { - if ident.node.name == keywords::Invalid.name() { + if ident.name == keywords::Invalid.name() { cx.span_lint(ANONYMOUS_PARAMETERS, arg.pat.span, "use of deprecated anonymous parameter"); diff --git a/src/librustc_mir/build/mod.rs b/src/librustc_mir/build/mod.rs index 6f5fcc9e421cc..9b0e4c64171ca 100644 --- a/src/librustc_mir/build/mod.rs +++ b/src/librustc_mir/build/mod.rs @@ -467,8 +467,8 @@ fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>, mutability: Mutability::Not, }; if let Some(hir::map::NodeBinding(pat)) = tcx.hir.find(var_id) { - if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node { - decl.debug_name = ident.node; + if let hir::PatKind::Binding(_, _, ref name, _) = pat.node { + decl.debug_name = name.node; let bm = *hir.tables.pat_binding_modes() .get(pat.hir_id) diff --git a/src/librustc_mir/hair/pattern/mod.rs b/src/librustc_mir/hair/pattern/mod.rs index 798d635318180..c3f41e8ac4827 100644 --- a/src/librustc_mir/hair/pattern/mod.rs +++ b/src/librustc_mir/hair/pattern/mod.rs @@ -466,7 +466,7 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { } } - PatKind::Binding(_, id, ref ident, ref sub) => { + PatKind::Binding(_, id, ref name, ref sub) => { let var_ty = self.tables.node_id_to_type(pat.hir_id); let region = match var_ty.sty { ty::TyRef(r, _) => Some(r), @@ -493,14 +493,14 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { if let ty::TyRef(_, mt) = ty.sty { ty = mt.ty; } else { - bug!("`ref {}` has wrong type {}", ident.node, ty); + bug!("`ref {}` has wrong type {}", name.node, ty); } } PatternKind::Binding { mutability, mode, - name: ident.node, + name: name.node, var: id, ty: var_ty, subpattern: self.lower_opt_pattern(sub), diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index 3598fe1d66cc4..45ecf665ef10b 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -34,7 +34,6 @@ use syntax::attr; use syntax::ast::{self, Block, ForeignItem, ForeignItemKind, Item, ItemKind, NodeId}; use syntax::ast::{Mutability, StmtKind, TraitItem, TraitItemKind, Variant}; -use syntax::codemap::respan; use syntax::ext::base::SyntaxExtension; use syntax::ext::base::Determinacy::Undetermined; use syntax::ext::hygiene::Mark; @@ -115,13 +114,13 @@ impl<'a> Resolver<'a> { let mut module_path: Vec<_> = prefix.segments.iter() .chain(path.segments.iter()) - .map(|seg| respan(seg.span, seg.ident)) + .map(|seg| seg.ident) .collect(); match use_tree.kind { ast::UseTreeKind::Simple(rename) => { let mut ident = use_tree.ident(); - let mut source = module_path.pop().unwrap().node; + let mut source = module_path.pop().unwrap(); let mut type_ns_only = false; if nested { @@ -130,7 +129,7 @@ impl<'a> Resolver<'a> { type_ns_only = true; let last_segment = *module_path.last().unwrap(); - if last_segment.node.name == keywords::CrateRoot.name() { + if last_segment.name == keywords::CrateRoot.name() { resolve_error( self, use_tree.span, @@ -142,9 +141,9 @@ impl<'a> Resolver<'a> { // Replace `use foo::self;` with `use foo;` let _ = module_path.pop(); - source = last_segment.node; + source = last_segment; if rename.is_none() { - ident = last_segment.node; + ident = last_segment; } } } else { @@ -195,8 +194,8 @@ impl<'a> Resolver<'a> { } ast::UseTreeKind::Nested(ref items) => { let prefix = ast::Path { - segments: module_path.iter() - .map(|s| ast::PathSegment::from_ident(s.node, s.span)) + segments: module_path.into_iter() + .map(|ident| ast::PathSegment::from_ident(ident, ident.span)) .collect(), span: path.span, }; diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index b6a43949ca3d0..41abb794f22d0 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -41,9 +41,9 @@ use rustc::ty; use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap}; use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap}; -use syntax::codemap::{dummy_spanned, respan, BytePos, CodeMap}; +use syntax::codemap::{BytePos, CodeMap}; use syntax::ext::hygiene::{Mark, MarkKind, SyntaxContext}; -use syntax::ast::{self, Name, NodeId, Ident, SpannedIdent, FloatTy, IntTy, UintTy}; +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; @@ -1654,8 +1654,8 @@ impl<'a> Resolver<'a> { { let namespace = if is_value { ValueNS } else { TypeNS }; let hir::Path { ref segments, span, ref mut def } = *path; - let path: Vec = segments.iter() - .map(|seg| respan(span, Ident::with_empty_ctxt(seg.name))) + let path: Vec = segments.iter() + .map(|seg| Ident::new(seg.name, span)) .collect(); match self.resolve_path(&path, Some(namespace), true, span) { PathResult::Module(module) => *def = module.def().unwrap(), @@ -2351,7 +2351,7 @@ impl<'a> Resolver<'a> { let mut new_id = None; if let Some(trait_ref) = opt_trait_ref { let path: Vec<_> = trait_ref.path.segments.iter() - .map(|seg| respan(seg.span, seg.ident)) + .map(|seg| seg.ident) .collect(); let def = self.smart_resolve_path_fragment( trait_ref.ref_id, @@ -2500,7 +2500,7 @@ impl<'a> Resolver<'a> { _ => false, } { let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode }; - binding_map.insert(ident.node, binding_info); + binding_map.insert(ident, binding_info); } } true @@ -2640,7 +2640,7 @@ impl<'a> Resolver<'a> { } fn fresh_binding(&mut self, - ident: &SpannedIdent, + ident: Ident, pat_id: NodeId, outer_pat_id: NodeId, pat_src: PatternSource, @@ -2652,14 +2652,14 @@ impl<'a> Resolver<'a> { // because that breaks the assumptions later // passes make about or-patterns.) let mut def = Def::Local(pat_id); - match bindings.get(&ident.node).cloned() { + match bindings.get(&ident).cloned() { Some(id) if id == outer_pat_id => { // `Variant(a, a)`, error resolve_error( self, ident.span, ResolutionError::IdentifierBoundMoreThanOnceInSamePattern( - &ident.node.name.as_str()) + &ident.name.as_str()) ); } Some(..) if pat_src == PatternSource::FnParam => { @@ -2668,7 +2668,7 @@ impl<'a> Resolver<'a> { self, ident.span, ResolutionError::IdentifierBoundMoreThanOnceInParameterList( - &ident.node.name.as_str()) + &ident.name.as_str()) ); } Some(..) if pat_src == PatternSource::Match || @@ -2676,7 +2676,7 @@ impl<'a> Resolver<'a> { pat_src == PatternSource::WhileLet => { // `Variant1(a) | Variant2(a)`, ok // Reuse definition from the first `a`. - def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident.node]; + def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident]; } Some(..) => { span_bug!(ident.span, "two bindings with the same name from \ @@ -2684,9 +2684,9 @@ impl<'a> Resolver<'a> { } None => { // A completely fresh binding, add to the lists if it's valid. - if ident.node.name != keywords::Invalid.name() { - bindings.insert(ident.node, outer_pat_id); - self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident.node, def); + if ident.name != keywords::Invalid.name() { + bindings.insert(ident, outer_pat_id); + self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, def); } } } @@ -2704,10 +2704,10 @@ impl<'a> Resolver<'a> { let outer_pat_id = pat.id; pat.walk(&mut |pat| { match pat.node { - PatKind::Ident(bmode, ref ident, ref opt_pat) => { + PatKind::Ident(bmode, ident, ref opt_pat) => { // First try to resolve the identifier as some existing // entity, then fall back to a fresh binding. - let binding = self.resolve_ident_in_lexical_scope(ident.node, ValueNS, + let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, false, pat.span) .and_then(LexicalScopeBinding::item); let resolution = binding.map(NameBinding::def).and_then(|def| { @@ -2719,7 +2719,7 @@ impl<'a> Resolver<'a> { Def::Const(..) if is_syntactic_ambiguity => { // Disambiguate in favor of a unit struct/variant // or constant pattern. - self.record_use(ident.node, ValueNS, binding.unwrap(), ident.span); + self.record_use(ident, ValueNS, binding.unwrap(), ident.span); Some(PathResolution::new(def)) } Def::StructCtor(..) | Def::VariantCtor(..) | @@ -2733,7 +2733,7 @@ impl<'a> Resolver<'a> { self, ident.span, ResolutionError::BindingShadowsSomethingUnacceptable( - pat_src.descr(), ident.node.name, binding.unwrap()) + pat_src.descr(), ident.name, binding.unwrap()) ); None } @@ -2786,7 +2786,7 @@ impl<'a> Resolver<'a> { source: PathSource) -> PathResolution { let segments = &path.segments.iter() - .map(|seg| respan(seg.span, seg.ident)) + .map(|seg| seg.ident) .collect::>(); self.smart_resolve_path_fragment(id, qself, segments, path.span, source) } @@ -2794,7 +2794,7 @@ impl<'a> Resolver<'a> { fn smart_resolve_path_fragment(&mut self, id: NodeId, qself: Option<&QSelf>, - path: &[SpannedIdent], + path: &[Ident], span: Span, source: PathSource) -> PathResolution { @@ -2814,11 +2814,11 @@ impl<'a> Resolver<'a> { format!("not a {}", expected), span) } else { - let item_str = path[path.len() - 1].node; + let item_str = path[path.len() - 1]; let item_span = path[path.len() - 1].span; let (mod_prefix, mod_str) = if path.len() == 1 { (format!(""), format!("this scope")) - } else if path.len() == 2 && path[0].node.name == keywords::CrateRoot.name() { + } else if path.len() == 2 && path[0].name == keywords::CrateRoot.name() { (format!(""), format!("the crate root")) } else { let mod_path = &path[..path.len() - 1]; @@ -2852,10 +2852,10 @@ impl<'a> Resolver<'a> { // Try to lookup the name in more relaxed fashion for better error reporting. let ident = *path.last().unwrap(); - let candidates = this.lookup_import_candidates(ident.node.name, ns, is_expected); + let candidates = this.lookup_import_candidates(ident.name, ns, is_expected); if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) { let enum_candidates = - this.lookup_import_candidates(ident.node.name, ns, is_enum_variant); + this.lookup_import_candidates(ident.name, ns, is_enum_variant); let mut enum_candidates = enum_candidates.iter() .map(|suggestion| import_candidate_to_paths(&suggestion)).collect::>(); enum_candidates.sort(); @@ -2873,8 +2873,8 @@ impl<'a> Resolver<'a> { } } if path.len() == 1 && this.self_type_is_available(span) { - if let Some(candidate) = this.lookup_assoc_candidate(ident.node, ns, is_expected) { - let self_is_available = this.self_value_is_available(path[0].node.span, span); + if let Some(candidate) = this.lookup_assoc_candidate(ident, ns, is_expected) { + let self_is_available = this.self_value_is_available(path[0].span, span); match candidate { AssocSuggestion::Field => { err.span_suggestion(span, "try", @@ -2919,7 +2919,7 @@ impl<'a> Resolver<'a> { (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node { ExprKind::Field(_, ident) => { err.span_label(parent.span, format!("did you mean `{}::{}`?", - path_str, ident.node)); + path_str, ident)); return (err, candidates); } ExprKind::MethodCall(ref segment, ..) => { @@ -3028,7 +3028,7 @@ impl<'a> Resolver<'a> { // or `::A::B`. If `B` should be resolved in value namespace then // it needs to be added to the trait map. if ns == ValueNS { - let item_name = path.last().unwrap().node; + let item_name = *path.last().unwrap(); let traits = self.get_traits_containing_item(item_name, ns); self.trait_map.insert(id, traits); } @@ -3095,7 +3095,7 @@ impl<'a> Resolver<'a> { fn resolve_qpath_anywhere(&mut self, id: NodeId, qself: Option<&QSelf>, - path: &[SpannedIdent], + path: &[Ident], primary_ns: Namespace, span: Span, defer_to_typeck: bool, @@ -3115,10 +3115,10 @@ impl<'a> Resolver<'a> { }; } } - let is_global = self.global_macros.get(&path[0].node.name).cloned() + let is_global = self.global_macros.get(&path[0].name).cloned() .map(|binding| binding.get_macro(self).kind() == MacroKind::Bang).unwrap_or(false); if primary_ns != MacroNS && (is_global || - self.macro_names.contains(&path[0].node.modern())) { + self.macro_names.contains(&path[0].modern())) { // Return some dummy definition, it's enough for error reporting. return Some( PathResolution::new(Def::Macro(DefId::local(CRATE_DEF_INDEX), MacroKind::Bang)) @@ -3131,7 +3131,7 @@ impl<'a> Resolver<'a> { fn resolve_qpath(&mut self, id: NodeId, qself: Option<&QSelf>, - path: &[SpannedIdent], + path: &[Ident], ns: Namespace, span: Span, global_by_default: bool) @@ -3172,8 +3172,8 @@ impl<'a> Resolver<'a> { PathResult::Module(..) | PathResult::Failed(..) if (ns == TypeNS || path.len() > 1) && self.primitive_type_table.primitive_types - .contains_key(&path[0].node.name) => { - let prim = self.primitive_type_table.primitive_types[&path[0].node.name]; + .contains_key(&path[0].name) => { + let prim = self.primitive_type_table.primitive_types[&path[0].name]; PathResolution::with_unresolved_segments(Def::PrimTy(prim), path.len() - 1) } PathResult::Module(module) => PathResolution::new(module.def().unwrap()), @@ -3186,8 +3186,8 @@ impl<'a> Resolver<'a> { }; if path.len() > 1 && !global_by_default && result.base_def() != Def::Err && - path[0].node.name != keywords::CrateRoot.name() && - path[0].node.name != keywords::DollarCrate.name() { + path[0].name != keywords::CrateRoot.name() && + path[0].name != keywords::DollarCrate.name() { let unqualified_result = { match self.resolve_path(&[*path.last().unwrap()], Some(ns), false, span) { PathResult::NonModule(path_res) => path_res.base_def(), @@ -3205,7 +3205,7 @@ impl<'a> Resolver<'a> { } fn resolve_path(&mut self, - path: &[SpannedIdent], + path: &[Ident], opt_ns: Option, // `None` indicates a module path record_used: bool, path_span: Span) @@ -3217,14 +3217,14 @@ impl<'a> Resolver<'a> { debug!("resolve_path ident {} {:?}", i, ident); let is_last = i == path.len() - 1; let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS }; - let name = ident.node.name; + let name = ident.name; if i == 0 && ns == TypeNS && name == keywords::SelfValue.name() { - let mut ctxt = ident.node.span.ctxt().modern(); + let mut ctxt = ident.span.ctxt().modern(); module = Some(self.resolve_self(&mut ctxt, self.current_module)); continue } else if allow_super && ns == TypeNS && name == keywords::Super.name() { - let mut ctxt = ident.node.span.ctxt().modern(); + let mut ctxt = ident.span.ctxt().modern(); let self_module = match i { 0 => self.resolve_self(&mut ctxt, self.current_module), _ => module.unwrap(), @@ -3244,16 +3244,16 @@ impl<'a> Resolver<'a> { if ns == TypeNS { if (i == 0 && name == keywords::CrateRoot.name()) || (i == 1 && name == keywords::Crate.name() && - path[0].node.name == keywords::CrateRoot.name()) { + path[0].name == keywords::CrateRoot.name()) { // `::a::b` or `::crate::a::b` - module = Some(self.resolve_crate_root(ident.node.span.ctxt(), false)); + module = Some(self.resolve_crate_root(ident.span.ctxt(), false)); continue } else if i == 0 && name == keywords::DollarCrate.name() { // `$crate::a::b` - module = Some(self.resolve_crate_root(ident.node.span.ctxt(), true)); + module = Some(self.resolve_crate_root(ident.span.ctxt(), true)); continue - } else if i == 1 && !token::is_path_segment_keyword(ident.node) { - let prev_name = path[0].node.name; + } else if i == 1 && !token::is_path_segment_keyword(ident) { + let prev_name = path[0].name; if prev_name == keywords::Extern.name() || prev_name == keywords::CrateRoot.name() && self.session.features_untracked().extern_absolute_paths { @@ -3276,13 +3276,13 @@ impl<'a> Resolver<'a> { name == keywords::Super.name() && i != 0 || name == keywords::Extern.name() && i != 0 || name == keywords::Crate.name() && i != 1 && - path[0].node.name != keywords::CrateRoot.name() { + path[0].name != keywords::CrateRoot.name() { let name_str = if name == keywords::CrateRoot.name() { format!("crate root") } else { format!("`{}`", name) }; - let msg = if i == 1 && path[0].node.name == keywords::CrateRoot.name() { + let msg = if i == 1 && path[0].name == keywords::CrateRoot.name() { format!("global paths cannot start with {}", name_str) } else if i == 0 && name == keywords::Crate.name() { format!("{} can only be used in absolute paths", name_str) @@ -3293,12 +3293,12 @@ impl<'a> Resolver<'a> { } let binding = if let Some(module) = module { - self.resolve_ident_in_module(module, ident.node, ns, false, record_used, path_span) + self.resolve_ident_in_module(module, ident, ns, false, record_used, path_span) } else if opt_ns == Some(MacroNS) { - self.resolve_lexical_macro_path_segment(ident.node, ns, record_used, path_span) + self.resolve_lexical_macro_path_segment(ident, ns, record_used, path_span) .map(MacroBinding::binding) } else { - match self.resolve_ident_in_lexical_scope(ident.node, ns, record_used, path_span) { + match self.resolve_ident_in_lexical_scope(ident, ns, record_used, path_span) { Some(LexicalScopeBinding::Item(binding)) => Ok(binding), Some(LexicalScopeBinding::Def(def)) if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => { @@ -3324,7 +3324,7 @@ impl<'a> Resolver<'a> { )); } else { return PathResult::Failed(ident.span, - format!("Not a module `{}`", ident.node), + format!("Not a module `{}`", ident), is_last); } } @@ -3345,12 +3345,12 @@ impl<'a> Resolver<'a> { if let Some(candidate) = candidates.get(0) { format!("Did you mean `{}`?", candidate.path) } else { - format!("Maybe a missing `extern crate {};`?", ident.node) + format!("Maybe a missing `extern crate {};`?", ident) } } else if i == 0 { - format!("Use of undeclared type or module `{}`", ident.node) + format!("Use of undeclared type or module `{}`", ident) } else { - format!("Could not find `{}` in `{}`", ident.node, path[i - 1].node) + format!("Could not find `{}` in `{}`", ident, path[i - 1]) }; return PathResult::Failed(ident.span, msg, is_last); } @@ -3516,7 +3516,7 @@ impl<'a> Resolver<'a> { } fn lookup_typo_candidate(&mut self, - path: &[SpannedIdent], + path: &[Ident], ns: Namespace, filter_fn: FilterFn, span: Span) @@ -3577,7 +3577,7 @@ impl<'a> Resolver<'a> { } } - let name = path[path.len() - 1].node.name; + let name = path[path.len() - 1].name; // Make sure error reporting is deterministic. names.sort_by_key(|name| name.as_str()); match find_best_match_for_name(names.iter(), &name.as_str(), None) { @@ -3739,12 +3739,12 @@ impl<'a> Resolver<'a> { fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) { match expr.node { - ExprKind::Field(_, name) => { + ExprKind::Field(_, ident) => { // FIXME(#6890): Even though you can't treat a method like a // field, we need to add any trait methods we find that match // the field name so that we can do some nice error reporting // later on in typeck. - let traits = self.get_traits_containing_item(name.node, ValueNS); + let traits = self.get_traits_containing_item(ident, ValueNS); self.trait_map.insert(expr.id, traits); } ExprKind::MethodCall(ref segment, ..) => { @@ -4244,30 +4244,30 @@ impl<'a> Resolver<'a> { } } -fn is_self_type(path: &[SpannedIdent], namespace: Namespace) -> bool { - namespace == TypeNS && path.len() == 1 && path[0].node.name == keywords::SelfType.name() +fn is_self_type(path: &[Ident], namespace: Namespace) -> bool { + namespace == TypeNS && path.len() == 1 && path[0].name == keywords::SelfType.name() } -fn is_self_value(path: &[SpannedIdent], namespace: Namespace) -> bool { - namespace == ValueNS && path.len() == 1 && path[0].node.name == keywords::SelfValue.name() +fn is_self_value(path: &[Ident], namespace: Namespace) -> bool { + namespace == ValueNS && path.len() == 1 && path[0].name == keywords::SelfValue.name() } -fn names_to_string(idents: &[SpannedIdent]) -> String { +fn names_to_string(idents: &[Ident]) -> String { let mut result = String::new(); for (i, ident) in idents.iter() - .filter(|i| i.node.name != keywords::CrateRoot.name()) + .filter(|ident| ident.name != keywords::CrateRoot.name()) .enumerate() { if i > 0 { result.push_str("::"); } - result.push_str(&ident.node.name.as_str()); + result.push_str(&ident.name.as_str()); } result } fn path_names_to_string(path: &Path) -> String { names_to_string(&path.segments.iter() - .map(|seg| respan(seg.span, seg.ident)) + .map(|seg| seg.ident) .collect::>()) } @@ -4356,7 +4356,6 @@ fn module_to_string(module: Module) -> Option { } Some(names_to_string(&names.into_iter() .rev() - .map(|n| dummy_spanned(n)) .collect::>())) } diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index c65ee11e427fa..3b3bdfdba9ce2 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -20,7 +20,6 @@ use rustc::hir::map::{self, DefCollector}; use rustc::{ty, lint}; use syntax::ast::{self, Name, Ident}; use syntax::attr::{self, HasAttrs}; -use syntax::codemap::respan; use syntax::errors::DiagnosticBuilder; use syntax::ext::base::{self, Annotatable, Determinacy, MultiModifier, MultiDecorator}; use syntax::ext::base::{MacroKind, SyntaxExtension, Resolver as SyntaxResolver}; @@ -413,7 +412,7 @@ impl<'a> Resolver<'a> { kind: MacroKind, force: bool) -> Result { let ast::Path { ref segments, span } = *path; - let path: Vec<_> = segments.iter().map(|seg| respan(seg.span, seg.ident)).collect(); + let path: Vec<_> = segments.iter().map(|seg| seg.ident).collect(); let invocation = self.invocations[&scope]; let module = invocation.module.get(); self.current_module = if module.is_trait() { module.parent.unwrap() } else { module }; @@ -447,19 +446,16 @@ impl<'a> Resolver<'a> { Err(Determinacy::Determined) }, }; - let path = path.iter().map(|p| p.node).collect::>(); self.current_module.nearest_item_scope().macro_resolutions.borrow_mut() .push((path.into_boxed_slice(), span)); return def; } - let legacy_resolution = self.resolve_legacy_scope(&invocation.legacy_scope, - path[0].node, - false); + let legacy_resolution = self.resolve_legacy_scope(&invocation.legacy_scope, path[0], false); let result = if let Some(MacroBinding::Legacy(binding)) = legacy_resolution { Ok(Def::Macro(binding.def_id, MacroKind::Bang)) } else { - match self.resolve_lexical_macro_path_segment(path[0].node, MacroNS, false, span) { + match self.resolve_lexical_macro_path_segment(path[0], MacroNS, false, span) { Ok(binding) => Ok(binding.binding().def_ignoring_ambiguity()), Err(Determinacy::Undetermined) if !force => return Err(Determinacy::Undetermined), Err(_) => { @@ -470,7 +466,7 @@ impl<'a> Resolver<'a> { }; self.current_module.nearest_item_scope().legacy_macro_resolutions.borrow_mut() - .push((scope, path[0].node, span, kind)); + .push((scope, path[0], span, kind)); result } @@ -608,7 +604,6 @@ impl<'a> Resolver<'a> { pub fn finalize_current_module_macro_resolutions(&mut self) { let module = self.current_module; for &(ref path, span) in module.macro_resolutions.borrow().iter() { - let path = path.iter().map(|p| respan(span, *p)).collect::>(); match self.resolve_path(&path, Some(MacroNS), true, span) { PathResult::NonModule(_) => {}, PathResult::Failed(span, msg, _) => { @@ -684,8 +679,8 @@ impl<'a> Resolver<'a> { false } }; - let ident = Ident::from_str(name); - self.lookup_typo_candidate(&vec![respan(span, ident)], MacroNS, is_macro, span) + let ident = Ident::new(Symbol::intern(name), span); + self.lookup_typo_candidate(&vec![ident], MacroNS, is_macro, span) }); if let Some(suggestion) = suggestion { diff --git a/src/librustc_resolve/resolve_imports.rs b/src/librustc_resolve/resolve_imports.rs index 90a90d731534b..87738f7b79be5 100644 --- a/src/librustc_resolve/resolve_imports.rs +++ b/src/librustc_resolve/resolve_imports.rs @@ -24,7 +24,7 @@ use rustc::hir::def::*; use rustc::session::DiagnosticMessageId; use rustc::util::nodemap::{FxHashMap, FxHashSet}; -use syntax::ast::{Ident, Name, SpannedIdent, NodeId}; +use syntax::ast::{Ident, Name, NodeId}; use syntax::ext::base::Determinacy::{self, Determined, Undetermined}; use syntax::ext::hygiene::Mark; use syntax::parse::token; @@ -58,7 +58,7 @@ pub enum ImportDirectiveSubclass<'a> { pub struct ImportDirective<'a> { pub id: NodeId, pub parent: Module<'a>, - pub module_path: Vec, + pub module_path: Vec, pub imported_module: Cell>>, // the resolution of `module_path` pub subclass: ImportDirectiveSubclass<'a>, pub span: Span, @@ -257,7 +257,7 @@ impl<'a> Resolver<'a> { // Add an import directive to the current module. pub fn add_import_directive(&mut self, - module_path: Vec, + module_path: Vec, subclass: ImportDirectiveSubclass<'a>, span: Span, id: NodeId, @@ -606,9 +606,9 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { // FIXME: Last path segment is treated specially in import resolution, so extern crate // mode for absolute paths needs some special support for single-segment imports. - if module_path.len() == 1 && (module_path[0].node.name == keywords::CrateRoot.name() || - module_path[0].node.name == keywords::Extern.name()) { - let is_extern = module_path[0].node.name == keywords::Extern.name() || + if module_path.len() == 1 && (module_path[0].name == keywords::CrateRoot.name() || + module_path[0].name == keywords::Extern.name()) { + let is_extern = module_path[0].name == keywords::Extern.name() || self.session.features_untracked().extern_absolute_paths; match directive.subclass { GlobImport { .. } if is_extern => { @@ -617,7 +617,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { } SingleImport { source, target, .. } => { let crate_root = if source.name == keywords::Crate.name() && - module_path[0].node.name != keywords::Extern.name() { + module_path[0].name != keywords::Extern.name() { if target.name == keywords::Crate.name() { return Some((directive.span, "crate root imports need to be explicitly named: \ @@ -669,9 +669,9 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { let (mut self_path, mut self_result) = (module_path.clone(), None); let is_special = |ident| token::is_path_segment_keyword(ident) && ident.name != keywords::CrateRoot.name(); - if !self_path.is_empty() && !is_special(self_path[0].node) && - !(self_path.len() > 1 && is_special(self_path[1].node)) { - self_path[0].node.name = keywords::SelfValue.name(); + if !self_path.is_empty() && !is_special(self_path[0]) && + !(self_path.len() > 1 && is_special(self_path[1])) { + self_path[0].name = keywords::SelfValue.name(); self_result = Some(self.resolve_path(&self_path, None, false, span)); } return if let Some(PathResult::Module(..)) = self_result { @@ -957,7 +957,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { let resolutions = imported_module.parent.expect("parent should exist") .resolutions.borrow(); let enum_path_segment_index = directive.module_path.len() - 1; - let enum_ident = directive.module_path[enum_path_segment_index].node; + let enum_ident = directive.module_path[enum_path_segment_index]; let enum_resolution = resolutions.get(&(enum_ident, TypeNS)) .expect("resolution should exist"); @@ -1011,12 +1011,12 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { } } -fn import_path_to_string(names: &[SpannedIdent], +fn import_path_to_string(names: &[Ident], subclass: &ImportDirectiveSubclass, span: Span) -> String { let pos = names.iter() - .position(|p| span == p.span && p.node.name != keywords::CrateRoot.name()); - let global = !names.is_empty() && names[0].node.name == keywords::CrateRoot.name(); + .position(|p| span == p.span && p.name != keywords::CrateRoot.name()); + let global = !names.is_empty() && names[0].name == keywords::CrateRoot.name(); 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_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index fb4cb2afe5a66..74c2597fa99e9 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -554,7 +554,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { }; match self.tables.expr_ty_adjusted(&hir_node).sty { ty::TyAdt(def, _) if !def.is_enum() => { - let f = def.non_enum_variant().field_named(ident.node.name); + let f = def.non_enum_variant().field_named(ident.name); let sub_span = self.span_utils.span_for_last_ident(expr.span); filter!(self.span_utils, sub_span, expr.span, None); let span = self.span_from_span(sub_span.unwrap()); @@ -817,7 +817,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { field_ref: &ast::Field, variant: &ty::VariantDef, ) -> Option { - let f = variant.find_field_named(field_ref.ident.node.name)?; + let f = variant.find_field_named(field_ref.ident.name)?; // We don't really need a sub-span here, but no harm done let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span); filter!(self.span_utils, sub_span, field_ref.ident.span, None); @@ -982,12 +982,12 @@ impl<'l, 'a: 'l> Visitor<'a> for PathCollector<'l> { PatKind::TupleStruct(ref path, ..) | PatKind::Path(_, ref path) => { self.collected_paths.push((p.id, path)); } - PatKind::Ident(bm, ref path1, _) => { + PatKind::Ident(bm, ident, _) => { debug!( "PathCollector, visit ident in pat {}: {:?} {:?}", - path1.node, + ident, p.span, - path1.span + ident.span ); let immut = match bm { // Even if the ref is mut, you can't change the ref, only @@ -997,7 +997,7 @@ impl<'l, 'a: 'l> Visitor<'a> for PathCollector<'l> { ast::BindingMode::ByValue(mt) => mt, }; self.collected_idents - .push((p.id, path1.node, path1.span, immut)); + .push((p.id, ident, ident.span, immut)); } _ => {} } diff --git a/src/librustc_save_analysis/sig.rs b/src/librustc_save_analysis/sig.rs index fd4d3e7638642..23845c94aa42f 100644 --- a/src/librustc_save_analysis/sig.rs +++ b/src/librustc_save_analysis/sig.rs @@ -671,7 +671,7 @@ impl Sig for ast::StructField { fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> Result { let mut text = String::new(); let mut defs = None; - if let Some(ref ident) = self.ident { + if let Some(ident) = self.ident { text.push_str(&ident.to_string()); defs = Some(SigElement { id: id_from_node_id(self.id, scx), diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index a3839a861c6c7..652aaa795c331 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -541,7 +541,7 @@ impl Pat { let node = match &self.node { PatKind::Wild => TyKind::Infer, PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => - TyKind::Path(None, Path::from_ident(ident.span, ident.node)), + TyKind::Path(None, Path::from_ident(ident.span, *ident)), PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()), PatKind::Mac(mac) => TyKind::Mac(mac.clone()), PatKind::Ref(pat, mutbl) => @@ -638,7 +638,7 @@ pub enum PatKind { /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens /// during name resolution. - Ident(BindingMode, SpannedIdent, Option>), + Ident(BindingMode, Ident, Option>), /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`. /// The `bool` is `true` in the presence of a `..`. @@ -910,15 +910,13 @@ pub struct Arm { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct Field { - pub ident: SpannedIdent, + pub ident: Ident, pub expr: P, pub span: Span, pub is_shorthand: bool, pub attrs: ThinVec, } -pub type SpannedIdent = Spanned; - #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] pub enum BlockCheckMode { Default, @@ -1144,7 +1142,7 @@ pub enum ExprKind { /// For example, `a += 1`. AssignOp(BinOp, P, P), /// Access of a named struct field (`obj.foo`) - Field(P, SpannedIdent), + Field(P, Ident), /// Access of an unnamed field of a struct or tuple-struct /// /// For example, `foo.0`. @@ -1689,7 +1687,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.node.name == keywords::SelfValue.name() { + if ident.name == keywords::SelfValue.name() { 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 == TyKind::ImplicitSelf => { @@ -1705,13 +1703,13 @@ impl Arg { pub fn is_self(&self) -> bool { if let PatKind::Ident(_, ident, _) = self.pat.node { - ident.node.name == keywords::SelfValue.name() + ident.name == keywords::SelfValue.name() } else { false } } - pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg { + pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg { let span = eself.span.to(eself_ident.span); let infer_ty = P(Ty { id: DUMMY_NODE_ID, diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 739679b71d5b1..541517b2bcbf3 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -1117,7 +1117,7 @@ impl MetaItem { let (span, name) = match tokens.next() { Some(TokenTree::Token(span, Token::Ident(ident, _))) => (span, ident.name), Some(TokenTree::Token(_, Token::Interpolated(ref nt))) => match nt.0 { - token::Nonterminal::NtIdent(ident, _) => (ident.span, ident.node.name), + token::Nonterminal::NtIdent(ident, _) => (ident.span, ident.name), token::Nonterminal::NtMeta(ref meta) => return Some(meta.clone()), _ => return None, }, diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 1e264369f918d..75b1366d3cdb3 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -251,7 +251,7 @@ impl TTMacroExpander for F if let tokenstream::TokenTree::Token(_, token::Interpolated(ref nt)) = tt { if let token::NtIdent(ident, is_raw) = nt.0 { return tokenstream::TokenTree::Token(ident.span, - token::Ident(ident.node, is_raw)); + token::Ident(ident, is_raw)); } } fold::noop_fold_tt(tt, self) diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 8dabc03c2f95b..fc3000ea0b5f6 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -38,11 +38,11 @@ pub trait AstBuilder { fn qpath(&self, self_type: P, trait_path: ast::Path, - ident: ast::SpannedIdent) + ident: ast::Ident) -> (ast::QSelf, ast::Path); fn qpath_all(&self, self_type: P, trait_path: ast::Path, - ident: ast::SpannedIdent, + ident: ast::Ident, lifetimes: Vec, types: Vec>, bindings: Vec) @@ -344,7 +344,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn qpath(&self, self_type: P, trait_path: ast::Path, - ident: ast::SpannedIdent) + ident: ast::Ident) -> (ast::QSelf, ast::Path) { self.qpath_all(self_type, trait_path, ident, vec![], vec![], vec![]) } @@ -355,7 +355,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn qpath_all(&self, self_type: P, trait_path: ast::Path, - ident: ast::SpannedIdent, + ident: ast::Ident, lifetimes: Vec, types: Vec>, bindings: Vec) @@ -366,11 +366,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } else { None }; - path.segments.push(ast::PathSegment { - ident: ident.node, - span: ident.span, - parameters, - }); + path.segments.push(ast::PathSegment { ident, span: ident.span, parameters }); (ast::QSelf { ty: self_type, @@ -636,8 +632,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } fn expr_field_access(&self, sp: Span, expr: P, ident: ast::Ident) -> P { - let id = Spanned { node: ident, span: sp }; - self.expr(sp, ast::ExprKind::Field(expr, id)) + self.expr(sp, ast::ExprKind::Field(expr, ident.with_span_pos(sp))) } fn expr_tup_field_access(&self, sp: Span, expr: P, idx: usize) -> P { let id = Spanned { node: idx, span: sp }; @@ -672,9 +667,9 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn expr_block(&self, b: P) -> P { self.expr(b.span, ast::ExprKind::Block(b)) } - fn field_imm(&self, span: Span, name: Ident, e: P) -> ast::Field { + fn field_imm(&self, span: Span, ident: Ident, e: P) -> ast::Field { ast::Field { - ident: respan(span, name), + ident: ident.with_span_pos(span), expr: e, span, is_shorthand: false, @@ -835,7 +830,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { span: Span, ident: ast::Ident, bm: ast::BindingMode) -> P { - let pat = PatKind::Ident(bm, Spanned{span: span, node: ident}, None); + let pat = PatKind::Ident(bm, ident.with_span_pos(span), None); self.pat(span, pat) } fn pat_path(&self, span: Span, path: ast::Path) -> P { diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index b412c2fbc7f7c..10dc17beb96ea 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -75,7 +75,7 @@ pub mod rt { impl ToTokens for ast::Ident { fn to_tokens(&self, _cx: &ExtCtxt) -> Vec { - vec![TokenTree::Token(DUMMY_SP, Token::from_ast_ident(*self))] + vec![TokenTree::Token(self.span, Token::from_ast_ident(*self))] } } diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 8cb331c65da28..fdff17b13ed40 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -86,7 +86,6 @@ use self::TokenTreeOrTokenTreeVec::*; use ast::Ident; use syntax_pos::{self, BytePos, Span}; -use codemap::respan; use errors::FatalError; use ext::tt::quoted::{self, TokenTree}; use parse::{Directory, ParseSess}; @@ -824,9 +823,10 @@ fn parse_nt<'a>(p: &mut Parser<'a>, sp: Span, name: &str) -> Nonterminal { "expr" => token::NtExpr(panictry!(p.parse_expr())), "ty" => token::NtTy(panictry!(p.parse_ty())), // this could be handled like a token, since it is one - "ident" => if let Some((ident, is_raw)) = get_macro_ident(&p.token) { + "ident" => if let Some((ident, is_raw))) = get_macro_ident(&p.token) { + let span = p.span; p.bump(); - token::NtIdent(respan(p.prev_span, ident), is_raw) + token::NtIdent(Ident::new(ident.name, span), is_raw) } else { let token_str = pprust::token_to_string(&p.token); p.fatal(&format!("expected ident, found {}", &token_str)).emit(); diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 2c757a0a88738..9ffa91c431c82 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -439,8 +439,8 @@ pub fn noop_fold_variant(v: Variant, fld: &mut T) -> Variant { } } -pub fn noop_fold_ident(i: Ident, _: &mut T) -> Ident { - i +pub fn noop_fold_ident(ident: Ident, fld: &mut T) -> Ident { + Ident::new(ident.name, fld.new_span(ident.span)) } pub fn noop_fold_usize(i: usize, _: &mut T) -> usize { @@ -634,8 +634,7 @@ pub fn noop_fold_interpolated(nt: token::Nonterminal, fld: &mut T) token::NtPat(pat) => token::NtPat(fld.fold_pat(pat)), token::NtExpr(expr) => token::NtExpr(fld.fold_expr(expr)), token::NtTy(ty) => token::NtTy(fld.fold_ty(ty)), - token::NtIdent(id, is_raw) => - token::NtIdent(Spanned::{node: fld.fold_ident(id.node), ..id}, is_raw), + token::NtIdent(id, is_raw) => token::NtIdent(fld.fold_ident(id), is_raw), token::NtMeta(meta) => token::NtMeta(fld.fold_meta_item(meta)), token::NtPath(path) => token::NtPath(fld.fold_path(path)), token::NtTT(tt) => token::NtTT(fld.fold_tt(tt)), @@ -859,7 +858,7 @@ pub fn noop_fold_struct_field(f: StructField, fld: &mut T) -> StructF pub fn noop_fold_field(f: Field, folder: &mut T) -> Field { Field { - ident: respan(f.ident.span, folder.fold_ident(f.ident.node)), + ident: folder.fold_ident(f.ident), expr: folder.fold_expr(f.expr), span: folder.new_span(f.span), is_shorthand: f.is_shorthand, @@ -1119,11 +1118,10 @@ pub fn noop_fold_pat(p: P, folder: &mut T) -> P { id: folder.new_id(id), node: match node { PatKind::Wild => PatKind::Wild, - PatKind::Ident(binding_mode, pth1, sub) => { + PatKind::Ident(binding_mode, ident, sub) => { PatKind::Ident(binding_mode, - Spanned{span: folder.new_span(pth1.span), - node: folder.fold_ident(pth1.node)}, - sub.map(|x| folder.fold_pat(x))) + folder.fold_ident(ident), + sub.map(|x| folder.fold_pat(x))) } PatKind::Lit(e) => PatKind::Lit(folder.fold_expr(e)), PatKind::TupleStruct(pth, pats, ddpos) => { @@ -1272,14 +1270,12 @@ pub fn noop_fold_expr(Expr {id, node, span, attrs}: Expr, folder: &mu folder.fold_expr(er)) } ExprKind::Field(el, ident) => { - ExprKind::Field(folder.fold_expr(el), - respan(folder.new_span(ident.span), - folder.fold_ident(ident.node))) + ExprKind::Field(folder.fold_expr(el), folder.fold_ident(ident)) } - ExprKind::TupField(el, ident) => { + ExprKind::TupField(el, index) => { ExprKind::TupField(folder.fold_expr(el), - respan(folder.new_span(ident.span), - folder.fold_usize(ident.node))) + respan(folder.new_span(index.span), + folder.fold_usize(index.node))) } ExprKind::Index(el, er) => { ExprKind::Index(folder.fold_expr(el), folder.fold_expr(er)) diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 81f8428c2c77a..0c8ffa2ebde65 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -512,13 +512,10 @@ impl From> for LhsExpr { /// Create a placeholder argument. fn dummy_arg(span: Span) -> Arg { - let spanned = Spanned { - span, - node: keywords::Invalid.ident() - }; + let ident = Ident::new(keywords::Invalid.name(), span); let pat = P(Pat { id: ast::DUMMY_NODE_ID, - node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None), + node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None), span, }); let ty = Ty { @@ -778,7 +775,7 @@ impl<'a> Parser<'a> { fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> { match self.token { - token::Ident(i, _) => { + token::Ident(ident, _) => { if self.token.is_reserved_ident() { let mut err = self.expected_ident_found(); if recover { @@ -787,8 +784,9 @@ impl<'a> Parser<'a> { return Err(err); } } + let span = self.span; self.bump(); - Ok(i) + Ok(Ident::new(ident.name, span)) } _ => { Err(if self.prev_token_kind == PrevTokenKind::DocComment { @@ -1321,7 +1319,7 @@ impl<'a> Parser<'a> { fn eat_label(&mut self) -> Option