Skip to content

Commit 1025db8

Browse files
committed
Auto merge of #85211 - Aaron1011:metadata-invalid-span, r=michaelwoerister
Preserve `SyntaxContext` for invalid/dummy spans in crate metadata Fixes #85197 We already preserved the `SyntaxContext` for invalid/dummy spans in the incremental cache, but we weren't doing the same for crate metadata. If an invalid (lo/hi from different files) span is written to the incremental cache, we will decode it with a 'dummy' location, but keep the original `SyntaxContext`. Since the crate metadata encoder was only checking for `DUMMY_SP` (dummy location + root `SyntaxContext`), the metadata encoder would treat it as a normal span, encoding the `SyntaxContext`. As a result, the final span encoded to the metadata would change across sessions, even if the crate itself was unchanged. This could lead to an 'unstable fingerprint' ICE under the following conditions: 1. We compile a crate with an invalid span using incremental compilation. The metadata encoder discards the `SyntaxContext` since the span is invalid, while the incremental cache encoder preserves the `SyntaxContext` 2. From another crate, we execute a foreign query, decoding the invalid span from the metadata as `DUMMY_SP` (e.g. with `SyntaxContext::root()`). This span gets hashed into the query fingerprint. So far, this has always happened through the `optimized_mir` query. 3. We recompile the first crate using our populated incremental cache, without changing anything. We load the (previously) invalid span from our incremental cache - it gets converted to a span with a dummy (but valid) location, along with the original `SyntaxContext`. This span gets written out to the crate metadata - since it now has a valid location, we preserve its `SyntaxContext`. 4. We recompile the second crate, again using a populated incremental cache. We now re-run the foreign query `optimized_mir` - the foreign crate hash is unchanged, but we end up decoding a different span (it now ha a non-root `SyntaxContext`). This results in the fingerprint changing, resulting in an ICE. This PR updates our encoding of spans in the crate metadata to mirror the encoding of spans into the incremental cache. We now always encode a `SyntaxContext`, and encode location information for spans with a non-dummy location.
2 parents 75da570 + cdca3c8 commit 1025db8

File tree

7 files changed

+113
-45
lines changed

7 files changed

+113
-45
lines changed

compiler/rustc_metadata/src/rmeta/decoder.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -406,17 +406,17 @@ impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for ExpnId {
406406

407407
impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for Span {
408408
fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Result<Span, String> {
409+
let ctxt = SyntaxContext::decode(decoder)?;
409410
let tag = u8::decode(decoder)?;
410411

411-
if tag == TAG_INVALID_SPAN {
412-
return Ok(DUMMY_SP);
412+
if tag == TAG_PARTIAL_SPAN {
413+
return Ok(DUMMY_SP.with_ctxt(ctxt));
413414
}
414415

415416
debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN);
416417

417418
let lo = BytePos::decode(decoder)?;
418419
let len = BytePos::decode(decoder)?;
419-
let ctxt = SyntaxContext::decode(decoder)?;
420420
let hi = lo + len;
421421

422422
let sess = if let Some(sess) = decoder.sess {

compiler/rustc_metadata/src/rmeta/encoder.rs

+41-41
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,48 @@ impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
187187

188188
impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
189189
fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
190-
if *self == rustc_span::DUMMY_SP {
191-
return TAG_INVALID_SPAN.encode(s);
190+
let span = self.data();
191+
192+
// Don't serialize any `SyntaxContext`s from a proc-macro crate,
193+
// since we don't load proc-macro dependencies during serialization.
194+
// This means that any hygiene information from macros used *within*
195+
// a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
196+
// definition) will be lost.
197+
//
198+
// This can show up in two ways:
199+
//
200+
// 1. Any hygiene information associated with identifier of
201+
// a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
202+
// Since proc-macros can only be invoked from a different crate,
203+
// real code should never need to care about this.
204+
//
205+
// 2. Using `Span::def_site` or `Span::mixed_site` will not
206+
// include any hygiene information associated with the definition
207+
// site. This means that a proc-macro cannot emit a `$crate`
208+
// identifier which resolves to one of its dependencies,
209+
// which also should never come up in practice.
210+
//
211+
// Additionally, this affects `Span::parent`, and any other
212+
// span inspection APIs that would otherwise allow traversing
213+
// the `SyntaxContexts` associated with a span.
214+
//
215+
// None of these user-visible effects should result in any
216+
// cross-crate inconsistencies (getting one behavior in the same
217+
// crate, and a different behavior in another crate) due to the
218+
// limited surface that proc-macros can expose.
219+
//
220+
// IMPORTANT: If this is ever changed, be sure to update
221+
// `rustc_span::hygiene::raw_encode_expn_id` to handle
222+
// encoding `ExpnData` for proc-macro crates.
223+
if s.is_proc_macro {
224+
SyntaxContext::root().encode(s)?;
225+
} else {
226+
span.ctxt.encode(s)?;
192227
}
193228

194-
let span = self.data();
229+
if self.is_dummy() {
230+
return TAG_PARTIAL_SPAN.encode(s);
231+
}
195232

196233
// The Span infrastructure should make sure that this invariant holds:
197234
debug_assert!(span.lo <= span.hi);
@@ -206,7 +243,7 @@ impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
206243
if !s.source_file_cache.0.contains(span.hi) {
207244
// Unfortunately, macro expansion still sometimes generates Spans
208245
// that malformed in this way.
209-
return TAG_INVALID_SPAN.encode(s);
246+
return TAG_PARTIAL_SPAN.encode(s);
210247
}
211248

212249
let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!");
@@ -262,43 +299,6 @@ impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
262299
let len = hi - lo;
263300
len.encode(s)?;
264301

265-
// Don't serialize any `SyntaxContext`s from a proc-macro crate,
266-
// since we don't load proc-macro dependencies during serialization.
267-
// This means that any hygiene information from macros used *within*
268-
// a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
269-
// definition) will be lost.
270-
//
271-
// This can show up in two ways:
272-
//
273-
// 1. Any hygiene information associated with identifier of
274-
// a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
275-
// Since proc-macros can only be invoked from a different crate,
276-
// real code should never need to care about this.
277-
//
278-
// 2. Using `Span::def_site` or `Span::mixed_site` will not
279-
// include any hygiene information associated with the definition
280-
// site. This means that a proc-macro cannot emit a `$crate`
281-
// identifier which resolves to one of its dependencies,
282-
// which also should never come up in practice.
283-
//
284-
// Additionally, this affects `Span::parent`, and any other
285-
// span inspection APIs that would otherwise allow traversing
286-
// the `SyntaxContexts` associated with a span.
287-
//
288-
// None of these user-visible effects should result in any
289-
// cross-crate inconsistencies (getting one behavior in the same
290-
// crate, and a different behavior in another crate) due to the
291-
// limited surface that proc-macros can expose.
292-
//
293-
// IMPORTANT: If this is ever changed, be sure to update
294-
// `rustc_span::hygiene::raw_encode_expn_id` to handle
295-
// encoding `ExpnData` for proc-macro crates.
296-
if s.is_proc_macro {
297-
SyntaxContext::root().encode(s)?;
298-
} else {
299-
span.ctxt.encode(s)?;
300-
}
301-
302302
if tag == TAG_VALID_SPAN_FOREIGN {
303303
// This needs to be two lines to avoid holding the `s.source_file_cache`
304304
// while calling `cnum.encode(s)`

compiler/rustc_metadata/src/rmeta/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -451,4 +451,4 @@ struct GeneratorData<'tcx> {
451451
// Tags used for encoding Spans:
452452
const TAG_VALID_SPAN_LOCAL: u8 = 0;
453453
const TAG_VALID_SPAN_FOREIGN: u8 = 1;
454-
const TAG_INVALID_SPAN: u8 = 2;
454+
const TAG_PARTIAL_SPAN: u8 = 2;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// revisions: rpass1 rpass2
2+
3+
extern crate respan;
4+
5+
#[macro_use]
6+
#[path = "invalid-span-helper-mod.rs"]
7+
mod invalid_span_helper_mod;
8+
9+
// Invoke a macro from a different file - this
10+
// allows us to get tokens with spans from different files
11+
helper!(1);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#[macro_export]
2+
macro_rules! helper {
3+
// Use `:tt` instead of `:ident` so that we don't get a `None`-delimited group
4+
($first:tt) => {
5+
pub fn foo<T>() {
6+
// The span of `$first` comes from another file,
7+
// so the expression `1 + $first` ends up with an
8+
// 'invalid' span that starts and ends in different files.
9+
// We use the `respan!` macro to give all tokens the same
10+
// `SyntaxContext`, so that the parser will try to merge the spans.
11+
respan::respan!(let a = 1 + $first;);
12+
}
13+
}
14+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// force-host
2+
// no-prefer-dynamic
3+
4+
#![crate_type = "proc-macro"]
5+
6+
extern crate proc_macro;
7+
use proc_macro::TokenStream;
8+
9+
10+
/// Copies the resolution information (the `SyntaxContext`) of the first
11+
/// token to all other tokens in the stream. Does not recurse into groups.
12+
#[proc_macro]
13+
pub fn respan(input: TokenStream) -> TokenStream {
14+
let first_span = input.clone().into_iter().next().unwrap().span();
15+
input.into_iter().map(|mut tree| {
16+
tree.set_span(tree.span().resolved_at(first_span));
17+
tree
18+
}).collect()
19+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// revisions: rpass1 rpass2
2+
// aux-build:respan.rs
3+
// aux-build:invalid-span-helper-lib.rs
4+
5+
// This issue has several different parts. The high level idea is:
6+
// 1. We create an 'invalid' span with the help of the `respan` proc-macro,
7+
// The compiler attempts to prevent the creation of invalid spans by
8+
// refusing to join spans with different `SyntaxContext`s. We work around
9+
// this by applying the same `SyntaxContext` to the span of every token,
10+
// using `Span::resolved_at`
11+
// 2. We using this invalid span in the body of a function, causing it to get
12+
// encoded into the `optimized_mir`
13+
// 3. We call the function from a different crate - since the function is generic,
14+
// monomorphization runs, causing `optimized_mir` to get called.
15+
// 4. We re-run compilation using our populated incremental cache, but without
16+
// making any changes. When we recompile the crate containing our generic function
17+
// (`invalid_span_helper_lib`), we load the span from the incremental cache, and
18+
// write it into the crate metadata.
19+
20+
extern crate invalid_span_helper_lib;
21+
22+
fn main() {
23+
invalid_span_helper_lib::foo::<u8>();
24+
}

0 commit comments

Comments
 (0)