Keep a parent LocalDefId in SpanData.

This commit is contained in:
Camille GILLOT 2021-04-18 14:27:04 +02:00
parent 06f7ca307d
commit 00485e0c0e
22 changed files with 88 additions and 40 deletions

View File

@ -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());

View File

@ -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()

View File

@ -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))
}
}

View File

@ -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);

View File

@ -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);

View File

@ -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)

View File

@ -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))
}
}

View File

@ -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

View File

@ -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};
@ -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
}
}
@ -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.
@ -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.
@ -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`.
@ -602,7 +623,7 @@ 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 }
}
@ -610,7 +631,7 @@ impl Span {
/// 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)
}
@ -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 },
)
}
@ -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 },
)
}
@ -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 },
)
}
@ -774,6 +798,7 @@ impl Span {
span.lo + BytePos::from_usize(inner.start),
span.lo + BytePos::from_usize(inner.end),
span.ctxt,
span.parent,
)
}
@ -812,7 +837,7 @@ 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
}
@ -820,7 +845,7 @@ impl Span {
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
}
@ -828,7 +853,7 @@ impl Span {
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
}
@ -836,7 +861,7 @@ impl Span {
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
}
@ -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
}
@ -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))
})
}
}
@ -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)
}
}

View File

@ -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,

View File

@ -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};
@ -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 }
}
}
@ -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.

View File

@ -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((

View File

@ -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<_>>();

View File

@ -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;
}

View File

@ -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()

View File

@ -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);

View File

@ -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;
}
@ -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);

View File

@ -63,6 +63,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeConstArrays {
hi_pos - BytePos::from_usize("const".len()),
hi_pos,
item.span.ctxt(),
item.span.parent(),
);
span_lint_and_then(
cx,

View File

@ -91,7 +91,7 @@ fn str_span(base: Span, c: regex_syntax::ast::Span, offset: u16) -> Span {
let end = base.lo() + BytePos(u32::try_from(c.end.offset).expect("offset too large") + offset);
let start = base.lo() + BytePos(u32::try_from(c.start.offset).expect("offset too large") + offset);
assert!(start <= end);
Span::new(start, end, base.ctxt())
Span::new(start, end, base.ctxt(), base.parent())
}
fn const_str<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> Option<String> {

View File

@ -69,6 +69,7 @@ impl TabsInDocComments {
attr.span.lo() + BytePos(3 + lo),
attr.span.lo() + BytePos(3 + hi),
attr.span.ctxt(),
attr.span.parent(),
);
span_lint_and_sugg(
cx,

View File

@ -1270,7 +1270,12 @@ impl MacroParser {
let data = delimited_span.entire().data();
(
data.hi,
Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
Span::new(
data.lo + BytePos(1),
data.hi - BytePos(1),
data.ctxt,
data.parent,
),
delimited_span.entire(),
)
}

View File

@ -356,11 +356,11 @@ macro_rules! source {
}
pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
Span::new(lo, hi, SyntaxContext::root())
Span::new(lo, hi, SyntaxContext::root(), None)
}
pub(crate) fn mk_sp_lo_plus_one(lo: BytePos) -> Span {
Span::new(lo, lo + BytePos(1), SyntaxContext::root())
Span::new(lo, lo + BytePos(1), SyntaxContext::root(), None)
}
// Returns `true` if the given span does not intersect with file lines.