From 09856c85b73feff1db93990cd3d80f2c585b40c4 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sun, 24 Jun 2018 19:24:51 +0300 Subject: expansion: Give names to some fields of `SyntaxExtension` --- src/libsyntax/ext/base.rs | 30 ++++++++++++++++-------------- src/libsyntax/ext/expand.rs | 10 +++++----- src/libsyntax/ext/tt/macro_rules.rs | 6 +++++- 3 files changed, 26 insertions(+), 20 deletions(-) (limited to 'src/libsyntax') diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 9afce74f53c..78fa3f326d6 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -597,11 +597,11 @@ pub enum SyntaxExtension { MultiModifier(Box), /// A function-like procedural macro. TokenStream -> TokenStream. - ProcMacro( - /* expander: */ Box, - /* allow_internal_unstable: */ bool, - /* edition: */ Edition, - ), + ProcMacro { + expander: Box, + allow_internal_unstable: bool, + edition: Edition, + }, /// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream. /// The first TokenSteam is the attribute, the second is the annotated item. @@ -646,19 +646,21 @@ pub enum SyntaxExtension { BuiltinDerive(BuiltinDeriveFn), /// A declarative macro, e.g. `macro m() {}`. - /// - /// The second element is the definition site span. - DeclMacro(Box, Option<(ast::NodeId, Span)>, Edition), + DeclMacro { + expander: Box, + def_info: Option<(ast::NodeId, Span)>, + edition: Edition, + } } impl SyntaxExtension { /// Return which kind of macro calls this syntax extension. pub fn kind(&self) -> MacroKind { match *self { - SyntaxExtension::DeclMacro(..) | + SyntaxExtension::DeclMacro { .. } | SyntaxExtension::NormalTT { .. } | SyntaxExtension::IdentTT(..) | - SyntaxExtension::ProcMacro(..) => + SyntaxExtension::ProcMacro { .. } => MacroKind::Bang, SyntaxExtension::MultiDecorator(..) | SyntaxExtension::MultiModifier(..) | @@ -672,8 +674,8 @@ impl SyntaxExtension { pub fn is_modern(&self) -> bool { match *self { - SyntaxExtension::DeclMacro(..) | - SyntaxExtension::ProcMacro(..) | + SyntaxExtension::DeclMacro { .. } | + SyntaxExtension::ProcMacro { .. } | SyntaxExtension::AttrProcMacro(..) | SyntaxExtension::ProcMacroDerive(..) => true, _ => false, @@ -683,8 +685,8 @@ impl SyntaxExtension { pub fn edition(&self) -> Edition { match *self { SyntaxExtension::NormalTT { edition, .. } | - SyntaxExtension::DeclMacro(.., edition) | - SyntaxExtension::ProcMacro(.., edition) | + SyntaxExtension::DeclMacro { edition, .. } | + SyntaxExtension::ProcMacro { edition, .. } | SyntaxExtension::AttrProcMacro(.., edition) | SyntaxExtension::ProcMacroDerive(.., edition) => edition, // Unstable legacy stuff diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 9cd410d4243..38fa92f2c93 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -738,13 +738,13 @@ impl<'a, 'b> MacroExpander<'a, 'b> { }; let opt_expanded = match *ext { - DeclMacro(ref expand, def_span, edition) => { - if let Err(dummy_span) = validate_and_set_expn_info(self, def_span.map(|(_, s)| s), + DeclMacro { ref expander, def_info, edition } => { + if let Err(dummy_span) = validate_and_set_expn_info(self, def_info.map(|(_, s)| s), false, false, false, None, edition) { dummy_span } else { - kind.make_from(expand.expand(self.cx, span, mac.node.stream())) + kind.make_from(expander.expand(self.cx, span, mac.node.stream())) } } @@ -804,7 +804,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { kind.dummy(span) } - ProcMacro(ref expandfun, allow_internal_unstable, edition) => { + SyntaxExtension::ProcMacro { ref expander, allow_internal_unstable, edition } => { if ident.name != keywords::Invalid.name() { let msg = format!("macro {}! expects no ident argument, given '{}'", path, ident); @@ -826,7 +826,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { edition, }); - let tok_result = expandfun.expand(self.cx, span, mac.node.stream()); + let tok_result = expander.expand(self.cx, span, mac.node.stream()); let result = self.parse_ast_fragment(tok_result, kind, path, span); self.gate_proc_macro_expansion(span, &result); result diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 3b3892729d9..0c81a68e999 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -312,7 +312,11 @@ pub fn compile(sess: &ParseSess, features: &Features, def: &ast::Item, edition: edition, } } else { - SyntaxExtension::DeclMacro(expander, Some((def.id, def.span)), edition) + SyntaxExtension::DeclMacro { + expander, + def_info: Some((def.id, def.span)), + edition, + } } } -- cgit 1.4.1-3-g733a5 From 99ecdb3f5fc49efb3eccdd10fbe12dc98623a938 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sun, 24 Jun 2018 19:54:23 +0300 Subject: hygiene: Implement transparent marks --- src/librustc_resolve/lib.rs | 13 ++- src/librustc_resolve/macros.rs | 4 +- src/libsyntax/ext/base.rs | 8 ++ src/libsyntax/ext/expand.rs | 2 +- src/libsyntax/ext/tt/macro_rules.rs | 3 + src/libsyntax_pos/hygiene.rs | 97 +++++++++++++++++----- src/libsyntax_pos/lib.rs | 6 ++ src/libsyntax_pos/symbol.rs | 9 ++ src/test/ui/hygiene/auxiliary/intercrate.rs | 6 ++ src/test/ui/hygiene/auxiliary/transparent-basic.rs | 16 ++++ src/test/ui/hygiene/dollar-crate-modern.rs | 22 +++++ src/test/ui/hygiene/generate-mod.rs | 24 ++++++ src/test/ui/hygiene/generate-mod.stderr | 17 ++++ src/test/ui/hygiene/transparent-basic.rs | 53 ++++++++++++ 14 files changed, 253 insertions(+), 27 deletions(-) create mode 100644 src/test/ui/hygiene/auxiliary/transparent-basic.rs create mode 100644 src/test/ui/hygiene/dollar-crate-modern.rs create mode 100644 src/test/ui/hygiene/generate-mod.rs create mode 100644 src/test/ui/hygiene/generate-mod.stderr create mode 100644 src/test/ui/hygiene/transparent-basic.rs (limited to 'src/libsyntax') diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 7771bc9b1cb..640e650207e 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -1850,6 +1850,8 @@ impl<'a> Resolver<'a> { } else { ident.span.modern() } + } else { + ident = ident.modern_and_legacy(); } // Walk backwards up the ribs in scope. @@ -1987,7 +1989,7 @@ impl<'a> Resolver<'a> { // When resolving `$crate` from a `macro_rules!` invoked in a `macro`, // we don't want to pretend that the `macro_rules!` definition is in the `macro` // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks. - ctxt.marks().into_iter().find(|&mark| mark.transparency() != Transparency::Opaque) + ctxt.marks().into_iter().rev().find(|m| m.transparency() != Transparency::Transparent) } else { ctxt = ctxt.modern(); ctxt.adjust(Mark::root()) @@ -2628,6 +2630,7 @@ impl<'a> Resolver<'a> { // must not add it if it's in the bindings map // because that breaks the assumptions later // passes make about or-patterns.) + let ident = ident.modern_and_legacy(); let mut def = Def::Local(pat_id); match bindings.get(&ident).cloned() { Some(id) if id == outer_pat_id => { @@ -3782,7 +3785,8 @@ impl<'a> Resolver<'a> { self.unused_labels.insert(id, label.ident.span); let def = Def::Label(id); self.with_label_rib(|this| { - this.label_ribs.last_mut().unwrap().bindings.insert(label.ident, def); + let ident = label.ident.modern_and_legacy(); + this.label_ribs.last_mut().unwrap().bindings.insert(ident, def); f(this); }); } else { @@ -3813,7 +3817,10 @@ impl<'a> Resolver<'a> { } ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => { - match self.search_label(label.ident, |rib, id| rib.bindings.get(&id).cloned()) { + let def = self.search_label(label.ident, |rib, ident| { + rib.bindings.get(&ident.modern_and_legacy()).cloned() + }); + match def { None => { // Search again for close matches... // Picks the first label that is "close enough", which is not necessarily diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index c4a20bea685..0523765ea18 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -332,7 +332,9 @@ impl<'a> base::Resolver for Resolver<'a> { self.unused_macros.remove(&def_id); let ext = self.get_macro(def); if ext.is_modern() { - invoc.expansion_data.mark.set_transparency(Transparency::Opaque); + let transparency = + if ext.is_transparent() { Transparency::Transparent } else { Transparency::Opaque }; + invoc.expansion_data.mark.set_transparency(transparency); } else if def_id.krate == BUILTIN_MACROS_CRATE { invoc.expansion_data.mark.set_is_builtin(true); } diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 78fa3f326d6..e2424de4d14 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -649,6 +649,7 @@ pub enum SyntaxExtension { DeclMacro { expander: Box, def_info: Option<(ast::NodeId, Span)>, + is_transparent: bool, edition: Edition, } } @@ -682,6 +683,13 @@ impl SyntaxExtension { } } + pub fn is_transparent(&self) -> bool { + match *self { + SyntaxExtension::DeclMacro { is_transparent, .. } => is_transparent, + _ => false, + } + } + pub fn edition(&self) -> Edition { match *self { SyntaxExtension::NormalTT { edition, .. } | diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 38fa92f2c93..e364e145593 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -738,7 +738,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { }; let opt_expanded = match *ext { - DeclMacro { ref expander, def_info, edition } => { + DeclMacro { ref expander, def_info, edition, .. } => { if let Err(dummy_span) = validate_and_set_expn_info(self, def_info.map(|(_, s)| s), false, false, false, None, edition) { diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 0c81a68e999..70fc9dada42 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -312,9 +312,12 @@ pub fn compile(sess: &ParseSess, features: &Features, def: &ast::Item, edition: edition, } } else { + let is_transparent = attr::contains_name(&def.attrs, "rustc_transparent_macro"); + SyntaxExtension::DeclMacro { expander, def_info: Some((def.id, def.span)), + is_transparent, edition, } } diff --git a/src/libsyntax_pos/hygiene.rs b/src/libsyntax_pos/hygiene.rs index 99d8b1b172d..e7f1f31084a 100644 --- a/src/libsyntax_pos/hygiene.rs +++ b/src/libsyntax_pos/hygiene.rs @@ -33,14 +33,17 @@ pub struct SyntaxContext(pub(super) u32); pub struct SyntaxContextData { pub outer_mark: Mark, pub prev_ctxt: SyntaxContext, - pub modern: SyntaxContext, + // This context, but with all transparent and semi-transparent marks filtered away. + pub opaque: SyntaxContext, + // This context, but with all transparent marks filtered away. + pub opaque_and_semitransparent: SyntaxContext, } /// A mark is a unique id associated with a macro expansion. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)] pub struct Mark(u32); -#[derive(Debug)] +#[derive(Clone, Debug)] struct MarkData { parent: Mark, transparency: Transparency, @@ -50,7 +53,7 @@ struct MarkData { /// A property of a macro expansion that determines how identifiers /// produced by that expansion are resolved. -#[derive(Copy, Clone, PartialEq, Eq, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Debug)] pub enum Transparency { /// Identifier produced by a transparent expansion is always resolved at call-site. /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this. @@ -69,16 +72,26 @@ pub enum Transparency { } impl Mark { + fn fresh_with_data(mark_data: MarkData, data: &mut HygieneData) -> Self { + data.marks.push(mark_data); + Mark(data.marks.len() as u32 - 1) + } + pub fn fresh(parent: Mark) -> Self { HygieneData::with(|data| { - data.marks.push(MarkData { + Mark::fresh_with_data(MarkData { parent, // By default expansions behave like `macro_rules`. transparency: Transparency::SemiTransparent, is_builtin: false, expn_info: None, - }); - Mark(data.marks.len() as u32 - 1) + }, data) + }) + } + + pub fn fresh_cloned(clone_from: Mark) -> Self { + HygieneData::with(|data| { + Mark::fresh_with_data(data.marks[clone_from.0 as usize].clone(), data) }) } @@ -207,7 +220,8 @@ impl HygieneData { syntax_contexts: vec![SyntaxContextData { outer_mark: Mark::root(), prev_ctxt: SyntaxContext(0), - modern: SyntaxContext(0), + opaque: SyntaxContext(0), + opaque_and_semitransparent: SyntaxContext(0), }], markings: HashMap::new(), default_edition: Edition::Edition2015, @@ -239,7 +253,7 @@ impl SyntaxContext { // Allocate a new SyntaxContext with the given ExpnInfo. This is used when // deserializing Spans from the incr. comp. cache. // FIXME(mw): This method does not restore MarkData::parent or - // SyntaxContextData::prev_ctxt or SyntaxContextData::modern. These things + // SyntaxContextData::prev_ctxt or SyntaxContextData::opaque. These things // don't seem to be used after HIR lowering, so everything should be fine // as long as incremental compilation does not kick in before that. pub fn allocate_directly(expansion_info: ExpnInfo) -> Self { @@ -256,7 +270,8 @@ impl SyntaxContext { data.syntax_contexts.push(SyntaxContextData { outer_mark: mark, prev_ctxt: SyntaxContext::empty(), - modern: SyntaxContext::empty(), + opaque: SyntaxContext::empty(), + opaque_and_semitransparent: SyntaxContext::empty(), }); SyntaxContext(data.syntax_contexts.len() as u32 - 1) }) @@ -269,7 +284,13 @@ impl SyntaxContext { } let call_site_ctxt = - mark.expn_info().map_or(SyntaxContext::empty(), |info| info.call_site.ctxt()).modern(); + mark.expn_info().map_or(SyntaxContext::empty(), |info| info.call_site.ctxt()); + let call_site_ctxt = if mark.transparency() == Transparency::SemiTransparent { + call_site_ctxt.modern() + } else { + call_site_ctxt.modern_and_legacy() + }; + if call_site_ctxt == SyntaxContext::empty() { return self.apply_mark_internal(mark); } @@ -293,26 +314,53 @@ impl SyntaxContext { fn apply_mark_internal(self, mark: Mark) -> SyntaxContext { HygieneData::with(|data| { let syntax_contexts = &mut data.syntax_contexts; - let mut modern = syntax_contexts[self.0 as usize].modern; - if data.marks[mark.0 as usize].transparency == Transparency::Opaque { - modern = *data.markings.entry((modern, mark)).or_insert_with(|| { - let len = syntax_contexts.len() as u32; + let transparency = data.marks[mark.0 as usize].transparency; + + let mut opaque = syntax_contexts[self.0 as usize].opaque; + let mut opaque_and_semitransparent = + syntax_contexts[self.0 as usize].opaque_and_semitransparent; + + if transparency >= Transparency::Opaque { + let prev_ctxt = opaque; + opaque = *data.markings.entry((prev_ctxt, mark)).or_insert_with(|| { + let new_opaque = SyntaxContext(syntax_contexts.len() as u32); + syntax_contexts.push(SyntaxContextData { + outer_mark: mark, + prev_ctxt, + opaque: new_opaque, + opaque_and_semitransparent: new_opaque, + }); + new_opaque + }); + } + + if transparency >= Transparency::SemiTransparent { + let prev_ctxt = opaque_and_semitransparent; + opaque_and_semitransparent = + *data.markings.entry((prev_ctxt, mark)).or_insert_with(|| { + let new_opaque_and_semitransparent = + SyntaxContext(syntax_contexts.len() as u32); syntax_contexts.push(SyntaxContextData { outer_mark: mark, - prev_ctxt: modern, - modern: SyntaxContext(len), + prev_ctxt, + opaque, + opaque_and_semitransparent: new_opaque_and_semitransparent, }); - SyntaxContext(len) + new_opaque_and_semitransparent }); } - *data.markings.entry((self, mark)).or_insert_with(|| { + let prev_ctxt = self; + *data.markings.entry((prev_ctxt, mark)).or_insert_with(|| { + let new_opaque_and_semitransparent_and_transparent = + SyntaxContext(syntax_contexts.len() as u32); syntax_contexts.push(SyntaxContextData { outer_mark: mark, - prev_ctxt: self, - modern, + prev_ctxt, + opaque, + opaque_and_semitransparent, }); - SyntaxContext(syntax_contexts.len() as u32 - 1) + new_opaque_and_semitransparent_and_transparent }) }) } @@ -452,7 +500,12 @@ impl SyntaxContext { #[inline] pub fn modern(self) -> SyntaxContext { - HygieneData::with(|data| data.syntax_contexts[self.0 as usize].modern) + HygieneData::with(|data| data.syntax_contexts[self.0 as usize].opaque) + } + + #[inline] + pub fn modern_and_legacy(self) -> SyntaxContext { + HygieneData::with(|data| data.syntax_contexts[self.0 as usize].opaque_and_semitransparent) } #[inline] diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs index 55dec31511c..308fb118f07 100644 --- a/src/libsyntax_pos/lib.rs +++ b/src/libsyntax_pos/lib.rs @@ -491,6 +491,12 @@ impl Span { let span = self.data(); span.with_ctxt(span.ctxt.modern()) } + + #[inline] + pub fn modern_and_legacy(self) -> Span { + let span = self.data(); + span.with_ctxt(span.ctxt.modern_and_legacy()) + } } #[derive(Clone, Debug)] diff --git a/src/libsyntax_pos/symbol.rs b/src/libsyntax_pos/symbol.rs index bb64dad1208..fe0b479d161 100644 --- a/src/libsyntax_pos/symbol.rs +++ b/src/libsyntax_pos/symbol.rs @@ -68,6 +68,15 @@ impl Ident { Ident::new(self.name, self.span.modern()) } + // "Normalize" ident for use in comparisons using "local variable hygiene". + // Identifiers with same string value become same if they came from the same non-transparent + // macro (e.g. `macro` or `macro_rules!` items) and stay different if they came from different + // non-transparent macros. + // Technically, this operation strips all transparent marks from ident's syntactic context. + pub fn modern_and_legacy(self) -> Ident { + Ident::new(self.name, self.span.modern_and_legacy()) + } + pub fn gensym(self) -> Ident { Ident::new(self.name.gensymed(), self.span) } diff --git a/src/test/ui/hygiene/auxiliary/intercrate.rs b/src/test/ui/hygiene/auxiliary/intercrate.rs index aa67e5c5f4d..244a9903e31 100644 --- a/src/test/ui/hygiene/auxiliary/intercrate.rs +++ b/src/test/ui/hygiene/auxiliary/intercrate.rs @@ -19,3 +19,9 @@ pub mod foo { } } } + +pub struct SomeType; + +pub macro uses_dollar_crate() { + type Alias = $crate::SomeType; +} diff --git a/src/test/ui/hygiene/auxiliary/transparent-basic.rs b/src/test/ui/hygiene/auxiliary/transparent-basic.rs new file mode 100644 index 00000000000..ba65c5f4da8 --- /dev/null +++ b/src/test/ui/hygiene/auxiliary/transparent-basic.rs @@ -0,0 +1,16 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(decl_macro, rustc_attrs)] + +#[rustc_transparent_macro] +pub macro dollar_crate() { + let s = $crate::S; +} diff --git a/src/test/ui/hygiene/dollar-crate-modern.rs b/src/test/ui/hygiene/dollar-crate-modern.rs new file mode 100644 index 00000000000..f4b24d0c5b4 --- /dev/null +++ b/src/test/ui/hygiene/dollar-crate-modern.rs @@ -0,0 +1,22 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Make sure `$crate` works in `macro` macros. + +// compile-pass +// aux-build:intercrate.rs + +#![feature(use_extern_macros)] + +extern crate intercrate; + +intercrate::uses_dollar_crate!(); + +fn main() {} diff --git a/src/test/ui/hygiene/generate-mod.rs b/src/test/ui/hygiene/generate-mod.rs new file mode 100644 index 00000000000..90409857dea --- /dev/null +++ b/src/test/ui/hygiene/generate-mod.rs @@ -0,0 +1,24 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// This is an equivalent of issue #50504, but for declarative macros. + +#![feature(decl_macro, rustc_attrs)] + +#[rustc_transparent_macro] +macro genmod() { + mod m { + type A = S; //~ ERROR cannot find type `S` in this scope + } +} + +struct S; + +genmod!(); diff --git a/src/test/ui/hygiene/generate-mod.stderr b/src/test/ui/hygiene/generate-mod.stderr new file mode 100644 index 00000000000..e79f8528c2c --- /dev/null +++ b/src/test/ui/hygiene/generate-mod.stderr @@ -0,0 +1,17 @@ +error[E0412]: cannot find type `S` in this scope + --> $DIR/generate-mod.rs:18:18 + | +LL | type A = S; //~ ERROR cannot find type `S` in this scope + | ^ did you mean `A`? +... +LL | genmod!(); + | ---------- in this macro invocation + +error[E0601]: `main` function not found in crate `generate_mod` + | + = note: consider adding a `main` function to `$DIR/generate-mod.rs` + +error: aborting due to 2 previous errors + +Some errors occurred: E0412, E0601. +For more information about an error, try `rustc --explain E0412`. diff --git a/src/test/ui/hygiene/transparent-basic.rs b/src/test/ui/hygiene/transparent-basic.rs new file mode 100644 index 00000000000..81ece1f11bc --- /dev/null +++ b/src/test/ui/hygiene/transparent-basic.rs @@ -0,0 +1,53 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// compile-pass +// aux-build:transparent-basic.rs + +#![feature(decl_macro, rustc_attrs)] + +extern crate transparent_basic; + +#[rustc_transparent_macro] +macro binding() { + let x = 10; +} + +#[rustc_transparent_macro] +macro label() { + break 'label +} + +macro_rules! legacy { + () => { + binding!(); + let y = x; + } +} + +fn legacy_interaction1() { + legacy!(); +} + +struct S; + +fn check_dollar_crate() { + // `$crate::S` inside the macro resolves to `S` from this crate. + transparent_basic::dollar_crate!(); +} + +fn main() { + binding!(); + let y = x; + + 'label: loop { + label!(); + } +} -- cgit 1.4.1-3-g733a5 From 9f92fce77c74cf3c47035e9ff69c29daee0517b3 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Mon, 25 Jun 2018 01:00:21 +0300 Subject: Fortify dummy span checking --- src/libproc_macro/lib.rs | 4 +--- src/librustc/hir/map/definitions.rs | 11 +++-------- src/librustc/middle/stability.rs | 6 +++--- src/librustc/ty/query/plumbing.rs | 2 +- src/librustc_codegen_llvm/debuginfo/metadata.rs | 2 +- src/librustc_codegen_llvm/debuginfo/mod.rs | 2 +- src/librustc_errors/emitter.rs | 16 ++++++++-------- src/librustc_metadata/encoder.rs | 4 ++-- src/librustc_mir/borrow_check/nll/type_check/mod.rs | 4 ++-- src/librustc_resolve/check_unused.rs | 4 ++-- src/librustc_resolve/lib.rs | 8 ++++---- src/librustc_save_analysis/lib.rs | 2 +- src/librustc_typeck/check_unused.rs | 4 ++-- src/librustdoc/clean/mod.rs | 2 +- src/libsyntax/codemap.rs | 2 +- src/libsyntax/ext/expand.rs | 2 +- src/libsyntax/ext/tt/quoted.rs | 10 +++++----- src/libsyntax/parse/mod.rs | 6 +++--- src/libsyntax/parse/parser.rs | 10 +++++----- src/libsyntax/tokenstream.rs | 8 ++++---- src/libsyntax_pos/lib.rs | 9 ++++++++- 21 files changed, 59 insertions(+), 59 deletions(-) (limited to 'src/libsyntax') diff --git a/src/libproc_macro/lib.rs b/src/libproc_macro/lib.rs index e580b459196..820b0906a75 100644 --- a/src/libproc_macro/lib.rs +++ b/src/libproc_macro/lib.rs @@ -177,8 +177,6 @@ impl iter::FromIterator for TokenStream { #[unstable(feature = "proc_macro", issue = "38356")] pub mod token_stream { use syntax::tokenstream; - use syntax_pos::DUMMY_SP; - use {TokenTree, TokenStream, Delimiter}; /// An iterator over `TokenStream`'s `TokenTree`s. @@ -207,7 +205,7 @@ pub mod token_stream { // need to flattened during iteration over stream's token trees. // Eventually this needs to be removed in favor of keeping original token trees // and not doing the roundtrip through AST. - if tree.span().0 == DUMMY_SP { + if tree.span().0.is_dummy() { if let TokenTree::Group(ref group) = tree { if group.delimiter() == Delimiter::None { self.cursor.insert(group.stream.clone().0); diff --git a/src/librustc/hir/map/definitions.rs b/src/librustc/hir/map/definitions.rs index b2365e22cc6..e262c951e39 100644 --- a/src/librustc/hir/map/definitions.rs +++ b/src/librustc/hir/map/definitions.rs @@ -486,12 +486,7 @@ impl Definitions { #[inline] pub fn opt_span(&self, def_id: DefId) -> Option { if def_id.krate == LOCAL_CRATE { - let span = self.def_index_to_span.get(&def_id.index).cloned().unwrap_or(DUMMY_SP); - if span != DUMMY_SP { - Some(span) - } else { - None - } + self.def_index_to_span.get(&def_id.index).cloned() } else { None } @@ -588,8 +583,8 @@ impl Definitions { self.opaque_expansions_that_defined.insert(index, expansion); } - // The span is added if it isn't DUMMY_SP - if span != DUMMY_SP { + // The span is added if it isn't dummy + if !span.is_dummy() { self.def_index_to_span.insert(index, span); } diff --git a/src/librustc/middle/stability.rs b/src/librustc/middle/stability.rs index a289a2c21ce..9bf5c4d72b7 100644 --- a/src/librustc/middle/stability.rs +++ b/src/librustc/middle/stability.rs @@ -20,7 +20,7 @@ use ty::{self, TyCtxt}; use middle::privacy::AccessLevels; use session::DiagnosticMessageId; use syntax::symbol::Symbol; -use syntax_pos::{Span, MultiSpan, DUMMY_SP}; +use syntax_pos::{Span, MultiSpan}; use syntax::ast; use syntax::ast::{NodeId, Attribute}; use syntax::feature_gate::{GateIssue, emit_feature_err, find_lang_feature_accepted_version}; @@ -687,7 +687,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { let msp: MultiSpan = span.into(); let cm = &self.sess.parse_sess.codemap(); let span_key = msp.primary_span().and_then(|sp: Span| - if sp != DUMMY_SP { + if !sp.is_dummy() { let file = cm.lookup_char_pos(sp.lo()).file; if file.name.is_macros() { None @@ -725,7 +725,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Checker<'a, 'tcx> { match item.node { hir::ItemExternCrate(_) => { // compiler-generated `extern crate` items have a dummy span. - if item.span == DUMMY_SP { return } + if item.span.is_dummy() { return } let def_id = self.tcx.hir.local_def_id(item.id); let cnum = match self.tcx.extern_mod_stmt_cnum(def_id) { diff --git a/src/librustc/ty/query/plumbing.rs b/src/librustc/ty/query/plumbing.rs index e17c6fba74c..d783b9574ef 100644 --- a/src/librustc/ty/query/plumbing.rs +++ b/src/librustc/ty/query/plumbing.rs @@ -708,7 +708,7 @@ macro_rules! define_queries { // FIXME(eddyb) Get more valid Span's on queries. pub fn default_span(&self, tcx: TyCtxt<'_, $tcx, '_>, span: Span) -> Span { - if span != DUMMY_SP { + if !span.is_dummy() { return span; } // The def_span query is used to calculate default_span, diff --git a/src/librustc_codegen_llvm/debuginfo/metadata.rs b/src/librustc_codegen_llvm/debuginfo/metadata.rs index 1eec57c9c87..6d727f7b048 100644 --- a/src/librustc_codegen_llvm/debuginfo/metadata.rs +++ b/src/librustc_codegen_llvm/debuginfo/metadata.rs @@ -1662,7 +1662,7 @@ pub fn create_global_var_metadata(cx: &CodegenCx, let var_scope = get_namespace_for_item(cx, def_id); let span = tcx.def_span(def_id); - let (file_metadata, line_number) = if span != syntax_pos::DUMMY_SP { + let (file_metadata, line_number) = if !span.is_dummy() { let loc = span_start(cx, span); (file_metadata(cx, &loc.file.name, LOCAL_CRATE), loc.line as c_uint) } else { diff --git a/src/librustc_codegen_llvm/debuginfo/mod.rs b/src/librustc_codegen_llvm/debuginfo/mod.rs index 803966145f7..068dd9821ac 100644 --- a/src/librustc_codegen_llvm/debuginfo/mod.rs +++ b/src/librustc_codegen_llvm/debuginfo/mod.rs @@ -219,7 +219,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, let span = mir.span; // This can be the case for functions inlined from another crate - if span == syntax_pos::DUMMY_SP { + if span.is_dummy() { // FIXME(simulacrum): Probably can't happen; remove. return FunctionDebugContext::FunctionWithoutDebugInfo; } diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs index 92e72fe91d3..e79a3a87738 100644 --- a/src/librustc_errors/emitter.rs +++ b/src/librustc_errors/emitter.rs @@ -10,7 +10,7 @@ use self::Destination::*; -use syntax_pos::{DUMMY_SP, FileMap, Span, MultiSpan}; +use syntax_pos::{FileMap, Span, MultiSpan}; use {Level, CodeSuggestion, DiagnosticBuilder, SubDiagnostic, CodeMapperDyn, DiagnosticId}; use snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, StyledString, Style}; @@ -216,7 +216,7 @@ impl EmitterWriter { if let Some(ref cm) = self.cm { for span_label in msp.span_labels() { - if span_label.span == DUMMY_SP { + if span_label.span.is_dummy() { continue; } @@ -730,7 +730,7 @@ impl EmitterWriter { let mut max = 0; if let Some(ref cm) = self.cm { for primary_span in msp.primary_spans() { - if primary_span != &DUMMY_SP { + if !primary_span.is_dummy() { let hi = cm.lookup_char_pos(primary_span.hi()); if hi.line > max { max = hi.line; @@ -739,7 +739,7 @@ impl EmitterWriter { } if !self.short_message { for span_label in msp.span_labels() { - if span_label.span != DUMMY_SP { + if !span_label.span.is_dummy() { let hi = cm.lookup_char_pos(span_label.span.hi()); if hi.line > max { max = hi.line; @@ -778,7 +778,7 @@ impl EmitterWriter { // First, find all the spans in <*macros> and point instead at their use site for sp in span.primary_spans() { - if *sp == DUMMY_SP { + if sp.is_dummy() { continue; } let call_sp = cm.call_span_if_macro(*sp); @@ -790,7 +790,7 @@ impl EmitterWriter { // Only show macro locations that are local // and display them like a span_note if let Some(def_site) = trace.def_site_span { - if def_site == DUMMY_SP { + if def_site.is_dummy() { continue; } if always_backtrace { @@ -830,7 +830,7 @@ impl EmitterWriter { span.push_span_label(label_span, label_text); } for sp_label in span.span_labels() { - if sp_label.span == DUMMY_SP { + if sp_label.span.is_dummy() { continue; } if cm.span_to_filename(sp_label.span.clone()).is_macros() && @@ -1003,7 +1003,7 @@ impl EmitterWriter { // Make sure our primary file comes first let (primary_lo, cm) = if let (Some(cm), Some(ref primary_span)) = (self.cm.as_ref(), msp.primary_span().as_ref()) { - if primary_span != &&DUMMY_SP { + if !primary_span.is_dummy() { (cm.lookup_char_pos(primary_span.lo()), cm) } else { emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?; diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index d8a224d3bad..93294075272 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -41,7 +41,7 @@ use std::u32; use syntax::ast::{self, CRATE_NODE_ID}; use syntax::attr; use syntax::symbol::keywords; -use syntax_pos::{self, hygiene, FileName, FileMap, Span, DUMMY_SP}; +use syntax_pos::{self, hygiene, FileName, FileMap, Span}; use rustc::hir::{self, PatKind}; use rustc::hir::itemlikevisit::ItemLikeVisitor; @@ -147,7 +147,7 @@ impl<'a, 'tcx> SpecializedEncoder for EncodeContext<'a, 'tcx> { impl<'a, 'tcx> SpecializedEncoder for EncodeContext<'a, 'tcx> { fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> { - if *span == DUMMY_SP { + if span.is_dummy() { return TAG_INVALID_SPAN.encode(self) } diff --git a/src/librustc_mir/borrow_check/nll/type_check/mod.rs b/src/librustc_mir/borrow_check/nll/type_check/mod.rs index 2da2b10edb8..9b6e3e0cab6 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/mod.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/mod.rs @@ -190,7 +190,7 @@ struct TypeVerifier<'a, 'b: 'a, 'gcx: 'b + 'tcx, 'tcx: 'b> { impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> { fn visit_span(&mut self, span: &Span) { - if *span != DUMMY_SP { + if !span.is_dummy() { self.last_span = *span; } } @@ -1601,7 +1601,7 @@ impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> { statement_index: 0, }; for stmt in &block_data.statements { - if stmt.source_info.span != DUMMY_SP { + if !stmt.source_info.span.is_dummy() { self.last_span = stmt.source_info.span; } self.check_stmt(mir, stmt, location); diff --git a/src/librustc_resolve/check_unused.rs b/src/librustc_resolve/check_unused.rs index 590ce168d5d..0c4b9a546cb 100644 --- a/src/librustc_resolve/check_unused.rs +++ b/src/librustc_resolve/check_unused.rs @@ -86,7 +86,7 @@ impl<'a, 'b> Visitor<'a> for UnusedImportCheckVisitor<'a, 'b> { // because this means that they were generated in some fashion by the // compiler and we don't need to consider them. if let ast::ItemKind::Use(..) = item.node { - if item.vis.node == ast::VisibilityKind::Public || item.span.source_equal(&DUMMY_SP) { + if item.vis.node == ast::VisibilityKind::Public || item.span.is_dummy() { return; } } @@ -129,7 +129,7 @@ pub fn check_crate(resolver: &mut Resolver, krate: &ast::Crate) { match directive.subclass { _ if directive.used.get() || directive.vis.get() == ty::Visibility::Public || - directive.span.source_equal(&DUMMY_SP) => {} + directive.span.is_dummy() => {} ImportDirectiveSubclass::ExternCrate(_) => { resolver.maybe_unused_extern_crates.push((directive.id, directive.span)); } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 640e650207e..9887abd60bf 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -2861,7 +2861,7 @@ impl<'a> Resolver<'a> { .map(|suggestion| import_candidate_to_paths(&suggestion)).collect::>(); enum_candidates.sort(); for (sp, variant_path, enum_path) in enum_candidates { - if sp == DUMMY_SP { + if sp.is_dummy() { let msg = format!("there is an enum variant `{}`, \ try using `{}`?", variant_path, @@ -4285,7 +4285,7 @@ impl<'a> Resolver<'a> { let mut err = struct_span_err!(self.session, span, E0659, "`{}` is ambiguous", name); err.span_note(b1.span, &msg1); match b2.def() { - Def::Macro(..) if b2.span == DUMMY_SP => + Def::Macro(..) if b2.span.is_dummy() => err.note(&format!("`{}` is also a builtin macro", name)), _ => err.span_note(b2.span, &msg2), }; @@ -4398,14 +4398,14 @@ impl<'a> Resolver<'a> { container)); err.span_label(span, format!("`{}` re{} here", name, new_participle)); - if old_binding.span != DUMMY_SP { + if !old_binding.span.is_dummy() { err.span_label(self.session.codemap().def_span(old_binding.span), format!("previous {} of the {} `{}` here", old_noun, old_kind, name)); } // See https://github.com/rust-lang/rust/issues/32354 if old_binding.is_import() || new_binding.is_import() { - let binding = if new_binding.is_import() && new_binding.span != DUMMY_SP { + let binding = if new_binding.is_import() && !new_binding.span.is_dummy() { new_binding } else { old_binding diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index 89d30fd666a..c07db44b36c 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -1157,7 +1157,7 @@ fn escape(s: String) -> String { // Helper function to determine if a span came from a // macro expansion or syntax extension. fn generated_code(span: Span) -> bool { - span.ctxt() != NO_EXPANSION || span == DUMMY_SP + span.ctxt() != NO_EXPANSION || span.is_dummy() } // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore diff --git a/src/librustc_typeck/check_unused.rs b/src/librustc_typeck/check_unused.rs index 41adde0d4a1..ae5ca5441ad 100644 --- a/src/librustc_typeck/check_unused.rs +++ b/src/librustc_typeck/check_unused.rs @@ -12,7 +12,7 @@ use lint; use rustc::ty::TyCtxt; use syntax::ast; -use syntax_pos::{Span, DUMMY_SP}; +use syntax_pos::Span; use rustc::hir::def_id::{DefId, LOCAL_CRATE}; use rustc::hir::itemlikevisit::ItemLikeVisitor; @@ -39,7 +39,7 @@ pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for CheckVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &hir::Item) { - if item.vis == hir::Public || item.span == DUMMY_SP { + if item.vis == hir::Public || item.span.is_dummy() { return; } if let hir::ItemUse(ref path, _) = item.node { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 23c367da48d..65babbffffe 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -3464,7 +3464,7 @@ impl Span { impl Clean for syntax_pos::Span { fn clean(&self, cx: &DocContext) -> Span { - if *self == DUMMY_SP { + if self.is_dummy() { return Span::empty(); } diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 1d5429bdf8f..ea6b39504e8 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -443,7 +443,7 @@ impl CodeMap { } pub fn span_to_string(&self, sp: Span) -> String { - if self.files.borrow().file_maps.is_empty() && sp.source_equal(&DUMMY_SP) { + if self.files.borrow().file_maps.is_empty() && sp.is_dummy() { return "no-location".to_string(); } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index e364e145593..f29bff20f3d 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -1297,7 +1297,7 @@ impl<'a, 'b> Folder for InvocationCollector<'a, 'b> { // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`). // In the non-inline case, `inner` is never the dummy span (c.f. `parse_item_mod`). // Thus, if `inner` is the dummy span, we know the module is inline. - let inline_module = item.span.contains(inner) || inner == DUMMY_SP; + let inline_module = item.span.contains(inner) || inner.is_dummy(); if inline_module { if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, "path") { diff --git a/src/libsyntax/ext/tt/quoted.rs b/src/libsyntax/ext/tt/quoted.rs index 01b971976a7..82b0fae3e9c 100644 --- a/src/libsyntax/ext/tt/quoted.rs +++ b/src/libsyntax/ext/tt/quoted.rs @@ -14,7 +14,7 @@ use feature_gate::{self, emit_feature_err, Features, GateIssue}; use parse::{token, ParseSess}; use print::pprust; use symbol::keywords; -use syntax_pos::{BytePos, Span, DUMMY_SP}; +use syntax_pos::{BytePos, Span}; use tokenstream; use std::iter::Peekable; @@ -41,8 +41,8 @@ impl Delimited { /// Return a `self::TokenTree` with a `Span` corresponding to the opening delimiter. pub fn open_tt(&self, span: Span) -> TokenTree { - let open_span = if span == DUMMY_SP { - DUMMY_SP + let open_span = if span.is_dummy() { + span } else { span.with_lo(span.lo() + BytePos(self.delim.len() as u32)) }; @@ -51,8 +51,8 @@ impl Delimited { /// Return a `self::TokenTree` with a `Span` corresponding to the closing delimiter. pub fn close_tt(&self, span: Span) -> TokenTree { - let close_span = if span == DUMMY_SP { - DUMMY_SP + let close_span = if span.is_dummy() { + span } else { span.with_lo(span.hi() - BytePos(self.delim.len() as u32)) }; diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index cce8da1dcbd..c443f240780 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -13,7 +13,7 @@ use rustc_data_structures::sync::{Lrc, Lock}; use ast::{self, CrateConfig}; use codemap::{CodeMap, FilePathMapping}; -use syntax_pos::{self, Span, FileMap, NO_EXPANSION, FileName}; +use syntax_pos::{Span, FileMap, FileName}; use errors::{Handler, ColorConfig, DiagnosticBuilder}; use feature_gate::UnstableFeatures; use parse::parser::Parser; @@ -188,8 +188,8 @@ fn filemap_to_parser(sess: & ParseSess, filemap: Lrc) -> Parser { let end_pos = filemap.end_pos; let mut parser = stream_to_parser(sess, filemap_to_stream(sess, filemap, None)); - if parser.token == token::Eof && parser.span == syntax_pos::DUMMY_SP { - parser.span = Span::new(end_pos, end_pos, NO_EXPANSION); + if parser.token == token::Eof && parser.span.is_dummy() { + parser.span = Span::new(end_pos, end_pos, parser.span.ctxt()); } parser diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index faf2cf64e1d..96053f988fa 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -43,7 +43,7 @@ use ast::{BinOpKind, UnOp}; use ast::{RangeEnd, RangeSyntax}; use {ast, attr}; use codemap::{self, CodeMap, Spanned, respan}; -use syntax_pos::{self, Span, MultiSpan, BytePos, FileName, DUMMY_SP, edition::Edition}; +use syntax_pos::{self, Span, MultiSpan, BytePos, FileName, edition::Edition}; use errors::{self, Applicability, DiagnosticBuilder}; use parse::{self, SeqSep, classify, token}; use parse::lexer::TokenAndSpan; @@ -567,7 +567,7 @@ impl<'a> Parser<'a> { if let Some(directory) = directory { parser.directory = directory; - } else if !parser.span.source_equal(&DUMMY_SP) { + } else if !parser.span.is_dummy() { if let FileName::Real(mut path) = sess.codemap().span_to_unmapped_path(parser.span) { path.pop(); parser.directory.path = Cow::from(path); @@ -584,7 +584,7 @@ impl<'a> Parser<'a> { } else { self.token_cursor.next() }; - if next.sp == syntax_pos::DUMMY_SP { + if next.sp.is_dummy() { // Tweak the location for better diagnostics, but keep syntactic context intact. next.sp = self.prev_span.with_ctxt(next.sp.ctxt()); } @@ -6137,7 +6137,7 @@ impl<'a> Parser<'a> { return Err(err); } - let hi = if self.span == syntax_pos::DUMMY_SP { + let hi = if self.span.is_dummy() { inner_lo } else { self.prev_span @@ -6368,7 +6368,7 @@ impl<'a> Parser<'a> { } let mut err = self.diagnostic().struct_span_err(id_sp, "cannot declare a new module at this location"); - if id_sp != syntax_pos::DUMMY_SP { + if !id_sp.is_dummy() { let src_path = self.sess.codemap().span_to_filename(id_sp); if let FileName::Real(src_path) = src_path { if let Some(stem) = src_path.file_stem() { diff --git a/src/libsyntax/tokenstream.rs b/src/libsyntax/tokenstream.rs index 455cc4391dd..8736fcf9729 100644 --- a/src/libsyntax/tokenstream.rs +++ b/src/libsyntax/tokenstream.rs @@ -57,8 +57,8 @@ impl Delimited { /// Returns the opening delimiter as a token tree. pub fn open_tt(&self, span: Span) -> TokenTree { - let open_span = if span == DUMMY_SP { - DUMMY_SP + let open_span = if span.is_dummy() { + span } else { span.with_hi(span.lo() + BytePos(self.delim.len() as u32)) }; @@ -67,8 +67,8 @@ impl Delimited { /// Returns the closing delimiter as a token tree. pub fn close_tt(&self, span: Span) -> TokenTree { - let close_span = if span == DUMMY_SP { - DUMMY_SP + let close_span = if span.is_dummy() { + span } else { span.with_lo(span.hi() - BytePos(self.delim.len() as u32)) }; diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs index 308fb118f07..491ce720f36 100644 --- a/src/libsyntax_pos/lib.rs +++ b/src/libsyntax_pos/lib.rs @@ -248,6 +248,13 @@ impl Span { self.data().with_ctxt(ctxt) } + /// Returns `true` if this is a dummy span with any hygienic context. + #[inline] + pub fn is_dummy(self) -> bool { + let span = self.data(); + span.lo.0 == 0 && span.hi.0 == 0 + } + /// Returns a new span representing an empty span at the beginning of this span #[inline] pub fn shrink_to_lo(self) -> Span { @@ -263,7 +270,7 @@ impl Span { /// Returns `self` if `self` is not the dummy span, and `other` otherwise. pub fn substitute_dummy(self, other: Span) -> Span { - if self.source_equal(&DUMMY_SP) { other } else { self } + if self.is_dummy() { other } else { self } } /// Return true if `self` fully encloses `other`. -- cgit 1.4.1-3-g733a5