Skip to content

Commit

Permalink
Keep a parent LocalDefId in SpanData.
Browse files Browse the repository at this point in the history
  • Loading branch information
cjgillot committed Sep 10, 2021
1 parent 06f7ca3 commit 00485e0
Show file tree
Hide file tree
Showing 22 changed files with 88 additions and 40 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_ast/src/attr/mod.rs
Expand Up @@ -367,7 +367,7 @@ impl MetaItem {
let is_first = i == 0;
if !is_first {
let mod_sep_span =
Span::new(last_pos, segment.ident.span.lo(), segment.ident.span.ctxt());
Span::new(last_pos, segment.ident.span.lo(), segment.ident.span.ctxt(), None);
idents.push(TokenTree::token(token::ModSep, mod_sep_span).into());
}
idents.push(TokenTree::Token(Token::from_ast_ident(segment.ident)).into());
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_expand/src/proc_macro_server.rs
Expand Up @@ -745,7 +745,7 @@ impl server::Span for Rustc<'_> {
self.sess.source_map().lookup_char_pos(span.lo()).file
}
fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
span.parent()
span.parent_callsite()
}
fn source(&mut self, span: Self::Span) -> Self::Span {
span.source_callsite()
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_metadata/src/rmeta/decoder.rs
Expand Up @@ -536,7 +536,8 @@ impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for Span {
let hi =
(hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos;

Ok(Span::new(lo, hi, ctxt))
// Do not try to decode parent for foreign spans.
Ok(Span::new(lo, hi, ctxt, None))
}
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/error.rs
Expand Up @@ -964,7 +964,7 @@ fn foo(&self) -> Self::T { String::new() }
{
let (span, sugg) = if has_params {
let pos = span.hi() - BytePos(1);
let span = Span::new(pos, pos, span.ctxt());
let span = Span::new(pos, pos, span.ctxt(), span.parent());
(span, format!(", {} = {}", assoc.ident, ty))
} else {
let item_args = self.format_generic_args(assoc_substs);
Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_mir_transform/src/coverage/spans.rs
Expand Up @@ -196,7 +196,11 @@ impl CoverageSpan {
/// body_span), returns the macro name symbol.
pub fn visible_macro(&self, body_span: Span) -> Option<Symbol> {
if let Some(current_macro) = self.current_macro() {
if self.expn_span.parent().unwrap_or_else(|| bug!("macro must have a parent")).ctxt()
if self
.expn_span
.parent_callsite()
.unwrap_or_else(|| bug!("macro must have a parent"))
.ctxt()
== body_span.ctxt()
{
return Some(current_macro);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_parse/src/lib.rs
Expand Up @@ -131,7 +131,7 @@ fn maybe_source_file_to_parser(
let mut parser = stream_to_parser(sess, stream, None);
parser.unclosed_delims = unclosed_delims;
if parser.token == token::Eof {
parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt());
parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt(), None);
}

Ok(parser)
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_query_impl/src/on_disk_cache.rs
Expand Up @@ -848,7 +848,7 @@ impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Span {
let lo = file_lo.lines[line_lo - 1] + col_lo;
let hi = lo + len;

Ok(Span::new(lo, hi, ctxt))
Ok(Span::new(lo, hi, ctxt, None))
}
}

Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_resolve/src/late/diagnostics.rs
Expand Up @@ -768,6 +768,7 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
args[1].span.lo(),
args.last().unwrap().span.hi(),
call_span.ctxt(),
None,
))
} else {
None
Expand Down
61 changes: 43 additions & 18 deletions compiler/rustc_span/src/lib.rs
Expand Up @@ -41,7 +41,7 @@ use hygiene::Transparency;
pub use hygiene::{DesugaringKind, ExpnKind, ForLoopLoc, MacroKind};
pub use hygiene::{ExpnData, ExpnHash, ExpnId, LocalExpnId, SyntaxContext};
pub mod def_id;
use def_id::{CrateNum, DefId, DefPathHash, LOCAL_CRATE};
use def_id::{CrateNum, DefId, DefPathHash, LocalDefId, LOCAL_CRATE};
pub mod lev_distance;
mod span_encoding;
pub use span_encoding::{Span, DUMMY_SP};
Expand Down Expand Up @@ -434,24 +434,38 @@ pub struct SpanData {
/// Information about where the macro came from, if this piece of
/// code was created by a macro expansion.
pub ctxt: SyntaxContext,
pub parent: Option<LocalDefId>,
}

impl SpanData {
#[inline]
pub fn span(&self) -> Span {
Span::new(self.lo, self.hi, self.ctxt)
Span::new(self.lo, self.hi, self.ctxt, self.parent)
}
#[inline]
pub fn with_lo(&self, lo: BytePos) -> Span {
Span::new(lo, self.hi, self.ctxt)
Span::new(lo, self.hi, self.ctxt, self.parent)
}
#[inline]
pub fn with_hi(&self, hi: BytePos) -> Span {
Span::new(self.lo, hi, self.ctxt)
Span::new(self.lo, hi, self.ctxt, self.parent)
}
#[inline]
pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
Span::new(self.lo, self.hi, ctxt)
Span::new(self.lo, self.hi, ctxt, self.parent)
}
#[inline]
pub fn with_parent(&self, parent: Option<LocalDefId>) -> Span {
Span::new(self.lo, self.hi, self.ctxt, parent)
}
/// Returns `true` if this is a dummy span with any hygienic context.
#[inline]
pub fn is_dummy(self) -> bool {
self.lo.0 == 0 && self.hi.0 == 0
}
/// Returns `true` if `self` fully encloses `other`.
pub fn contains(self, other: Self) -> bool {
self.lo <= other.lo && other.hi <= self.hi
}
}

Expand Down Expand Up @@ -513,12 +527,19 @@ impl Span {
pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
self.data().with_ctxt(ctxt)
}
#[inline]
pub fn parent(self) -> Option<LocalDefId> {
self.data().parent
}
#[inline]
pub fn with_parent(self, ctxt: Option<LocalDefId>) -> Span {
self.data().with_parent(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
self.data().is_dummy()
}

/// Returns `true` if this span comes from a macro or desugaring.
Expand All @@ -534,7 +555,7 @@ impl Span {

#[inline]
pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
Span::new(lo, hi, SyntaxContext::root())
Span::new(lo, hi, SyntaxContext::root(), None)
}

/// Returns a new span representing an empty span at the beginning of this span.
Expand Down Expand Up @@ -566,7 +587,7 @@ impl Span {
pub fn contains(self, other: Span) -> bool {
let span = self.data();
let other = other.data();
span.lo <= other.lo && other.hi <= span.hi
span.contains(other)
}

/// Returns `true` if `self` touches `other`.
Expand Down Expand Up @@ -602,15 +623,15 @@ impl Span {

/// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
/// if any.
pub fn parent(self) -> Option<Span> {
pub fn parent_callsite(self) -> Option<Span> {
let expn_data = self.ctxt().outer_expn_data();
if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
}

/// Walk down the expansion ancestors to find a span that's contained within `outer`.
pub fn find_ancestor_inside(mut self, outer: Span) -> Option<Span> {
while !outer.contains(self) {
self = self.parent()?;
self = self.parent_callsite()?;
}
Some(self)
}
Expand Down Expand Up @@ -731,6 +752,7 @@ impl Span {
cmp::min(span_data.lo, end_data.lo),
cmp::max(span_data.hi, end_data.hi),
if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
if span_data.parent == end_data.parent { span_data.parent } else { None },
)
}

Expand All @@ -748,6 +770,7 @@ impl Span {
span.hi,
end.lo,
if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
if span.parent == end.parent { span.parent } else { None },
)
}

Expand All @@ -765,6 +788,7 @@ impl Span {
span.lo,
end.lo,
if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
if span.parent == end.parent { span.parent } else { None },
)
}

Expand All @@ -774,6 +798,7 @@ impl Span {
span.lo + BytePos::from_usize(inner.start),
span.lo + BytePos::from_usize(inner.end),
span.ctxt,
span.parent,
)
}

Expand Down Expand Up @@ -812,31 +837,31 @@ impl Span {
pub fn remove_mark(&mut self) -> ExpnId {
let mut span = self.data();
let mark = span.ctxt.remove_mark();
*self = Span::new(span.lo, span.hi, span.ctxt);
*self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
mark
}

#[inline]
pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
let mut span = self.data();
let mark = span.ctxt.adjust(expn_id);
*self = Span::new(span.lo, span.hi, span.ctxt);
*self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
mark
}

#[inline]
pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
let mut span = self.data();
let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
*self = Span::new(span.lo, span.hi, span.ctxt);
*self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
mark
}

#[inline]
pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
let mut span = self.data();
let mark = span.ctxt.glob_adjust(expn_id, glob_span);
*self = Span::new(span.lo, span.hi, span.ctxt);
*self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
mark
}

Expand All @@ -848,7 +873,7 @@ impl Span {
) -> Option<Option<ExpnId>> {
let mut span = self.data();
let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
*self = Span::new(span.lo, span.hi, span.ctxt);
*self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
mark
}

Expand Down Expand Up @@ -900,7 +925,7 @@ impl<D: Decoder> Decodable<D> for Span {
let lo = d.read_struct_field("lo", Decodable::decode)?;
let hi = d.read_struct_field("hi", Decodable::decode)?;

Ok(Span::new(lo, hi, SyntaxContext::root()))
Ok(Span::new(lo, hi, SyntaxContext::root(), None))
})
}
}
Expand Down Expand Up @@ -961,7 +986,7 @@ impl fmt::Debug for Span {

impl fmt::Debug for SpanData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
(*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt, self.parent), f)
}
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_span/src/source_map.rs
Expand Up @@ -794,7 +794,7 @@ impl SourceMap {
start_of_next_point.checked_add(width - 1).unwrap_or(start_of_next_point);

let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt(), None)
}

/// Finds the width of the character, either before or after the end of provided span,
Expand Down
14 changes: 11 additions & 3 deletions compiler/rustc_span/src/span_encoding.rs
Expand Up @@ -4,6 +4,7 @@
// The encoding format for inline spans were obtained by optimizing over crates in rustc/libstd.
// See https://internals.rust-lang.org/t/rfc-compiler-refactoring-spans/1357/28

use crate::def_id::LocalDefId;
use crate::hygiene::SyntaxContext;
use crate::{BytePos, SpanData};

Expand Down Expand Up @@ -70,19 +71,25 @@ pub const DUMMY_SP: Span = Span { base_or_index: 0, len_or_tag: 0, ctxt_or_zero:

impl Span {
#[inline]
pub fn new(mut lo: BytePos, mut hi: BytePos, ctxt: SyntaxContext) -> Self {
pub fn new(
mut lo: BytePos,
mut hi: BytePos,
ctxt: SyntaxContext,
parent: Option<LocalDefId>,
) -> Self {
if lo > hi {
std::mem::swap(&mut lo, &mut hi);
}

let (base, len, ctxt2) = (lo.0, hi.0 - lo.0, ctxt.as_u32());

if len <= MAX_LEN && ctxt2 <= MAX_CTXT {
if len <= MAX_LEN && ctxt2 <= MAX_CTXT && parent.is_none() {
// Inline format.
Span { base_or_index: base, len_or_tag: len as u16, ctxt_or_zero: ctxt2 as u16 }
} else {
// Interned format.
let index = with_span_interner(|interner| interner.intern(&SpanData { lo, hi, ctxt }));
let index =
with_span_interner(|interner| interner.intern(&SpanData { lo, hi, ctxt, parent }));
Span { base_or_index: index, len_or_tag: LEN_TAG, ctxt_or_zero: 0 }
}
}
Expand All @@ -96,6 +103,7 @@ impl Span {
lo: BytePos(self.base_or_index),
hi: BytePos(self.base_or_index + self.len_or_tag as u32),
ctxt: SyntaxContext::from_u32(self.ctxt_or_zero as u32),
parent: None,
}
} else {
// Interned format.
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_typeck/src/check/demand.rs
Expand Up @@ -589,7 +589,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// E.g. for `&format!("")`, where we want the span to the
// `format!()` invocation instead of its expansion.
if let Some(call_span) =
iter::successors(Some(expr.span), |s| s.parent()).find(|&s| sp.contains(s))
iter::successors(Some(expr.span), |s| s.parent_callsite())
.find(|&s| sp.contains(s))
{
if sm.span_to_snippet(call_span).is_ok() {
return Some((
Expand Down
4 changes: 2 additions & 2 deletions src/tools/clippy/clippy_lints/src/attrs.rs
Expand Up @@ -527,8 +527,8 @@ fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::It
return;
}

let begin_of_attr_to_item = Span::new(attr.span.lo(), item.span.lo(), item.span.ctxt());
let end_of_attr_to_item = Span::new(attr.span.hi(), item.span.lo(), item.span.ctxt());
let begin_of_attr_to_item = Span::new(attr.span.lo(), item.span.lo(), item.span.ctxt(), item.span.parent());
let end_of_attr_to_item = Span::new(attr.span.hi(), item.span.lo(), item.span.ctxt(), item.span.parent());

if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
let lines = snippet.split('\n').collect::<Vec<_>>();
Expand Down
2 changes: 1 addition & 1 deletion src/tools/clippy/clippy_lints/src/cognitive_complexity.rs
Expand Up @@ -95,7 +95,7 @@ impl CognitiveComplexity {
});

if let Some((low, high)) = pos {
Span::new(low, high, header_span.ctxt())
Span::new(low, high, header_span.ctxt(), header_span.parent())
} else {
return;
}
Expand Down
2 changes: 1 addition & 1 deletion src/tools/clippy/clippy_lints/src/copies.rs
Expand Up @@ -472,7 +472,7 @@ fn emit_branches_sharing_code_lint(

let mut span = moved_start.to(span_end);
// Improve formatting if the inner block has indention (i.e. normal Rust formatting)
let test_span = Span::new(span.lo() - BytePos(4), span.lo(), span.ctxt());
let test_span = Span::new(span.lo() - BytePos(4), span.lo(), span.ctxt(), span.parent());
if snippet_opt(cx, test_span)
.map(|snip| snip == " ")
.unwrap_or_default()
Expand Down
1 change: 1 addition & 0 deletions src/tools/clippy/clippy_lints/src/doc.rs
Expand Up @@ -665,6 +665,7 @@ fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str
span.lo() + BytePos::from_usize(offset),
span.lo() + BytePos::from_usize(offset + word.len()),
span.ctxt(),
span.parent(),
);

check_word(cx, word, span);
Expand Down
4 changes: 2 additions & 2 deletions src/tools/clippy/clippy_lints/src/implicit_hasher.rs
Expand Up @@ -130,7 +130,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitHasher {
let pos = snippet_opt(cx, item.span.until(target.span()))
.and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
if let Some(pos) = pos {
Span::new(pos, pos, item.span.data().ctxt)
Span::new(pos, pos, item.span.ctxt(), item.span.parent())
} else {
return;
}
Expand Down Expand Up @@ -173,7 +173,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitHasher {
Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
})
.expect("failed to create span for type parameters");
Span::new(pos, pos, item.span.data().ctxt)
Span::new(pos, pos, item.span.ctxt(), item.span.parent())
});

let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
Expand Down

0 comments on commit 00485e0

Please sign in to comment.