Skip to content

Commit 1839c14

Browse files
committed
Auto merge of #54517 - mcr431:53956-panic-on-include_bytes-of-own-file, r=michaelwoerister
53956 panic on include bytes of own file fix #53956 When using `include_bytes!` on a source file in the project, compiler would panic on subsequent compilations because `expand_include_bytes` would overwrite files in the source_map with no source. This PR changes `expand_include_bytes` to check source_map and use the already existing src, if any.
2 parents 4988b09 + f0f8aa9 commit 1839c14

File tree

21 files changed

+180
-119
lines changed

21 files changed

+180
-119
lines changed

src/librustc/ich/impls_syntax.rs

+8-7
Original file line numberDiff line numberDiff line change
@@ -417,13 +417,14 @@ impl_stable_hash_for!(enum ::syntax_pos::hygiene::CompilerDesugaringKind {
417417
impl_stable_hash_for!(enum ::syntax_pos::FileName {
418418
Real(pb),
419419
Macros(s),
420-
QuoteExpansion,
421-
Anon,
422-
MacroExpansion,
423-
ProcMacroSourceCode,
424-
CliCrateAttr,
425-
CfgSpec,
426-
Custom(s)
420+
QuoteExpansion(s),
421+
Anon(s),
422+
MacroExpansion(s),
423+
ProcMacroSourceCode(s),
424+
CliCrateAttr(s),
425+
CfgSpec(s),
426+
Custom(s),
427+
DocTest(pb, line),
427428
});
428429

429430
impl<'a> HashStable<StableHashingContext<'a>> for SourceFile {

src/librustc/session/config.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1756,8 +1756,8 @@ pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> ast::CrateConfig {
17561756
.into_iter()
17571757
.map(|s| {
17581758
let sess = parse::ParseSess::new(FilePathMapping::empty());
1759-
let mut parser =
1760-
parse::new_parser_from_source_str(&sess, FileName::CfgSpec, s.to_string());
1759+
let filename = FileName::cfg_spec_source_code(&s);
1760+
let mut parser = parse::new_parser_from_source_str(&sess, filename, s.to_string());
17611761

17621762
macro_rules! error {($reason: expr) => {
17631763
early_error(ErrorOutputType::default(),

src/librustc_driver/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -594,7 +594,7 @@ fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option
594594
} else {
595595
None
596596
};
597-
Some((Input::Str { name: FileName::Anon, input: src },
597+
Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
598598
None, err))
599599
} else {
600600
Some((Input::File(PathBuf::from(ifile)),

src/librustc_driver/test.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ fn test_env_with_pool<F>(
129129
let cstore = CStore::new(::get_codegen_backend(&sess).metadata_loader());
130130
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
131131
let input = config::Input::Str {
132-
name: FileName::Anon,
132+
name: FileName::anon_source_code(&source_string),
133133
input: source_string.to_string(),
134134
};
135135
let krate =

src/librustc_errors/emitter.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -1044,7 +1044,7 @@ impl EmitterWriter {
10441044
buffer.append(buffer_msg_line_offset,
10451045
&format!("{}:{}:{}",
10461046
loc.file.name,
1047-
sm.doctest_offset_line(loc.line),
1047+
sm.doctest_offset_line(&loc.file.name, loc.line),
10481048
loc.col.0 + 1),
10491049
Style::LineAndColumn);
10501050
for _ in 0..max_line_num_len {
@@ -1054,7 +1054,7 @@ impl EmitterWriter {
10541054
buffer.prepend(0,
10551055
&format!("{}:{}:{}: ",
10561056
loc.file.name,
1057-
sm.doctest_offset_line(loc.line),
1057+
sm.doctest_offset_line(&loc.file.name, loc.line),
10581058
loc.col.0 + 1),
10591059
Style::LineAndColumn);
10601060
}
@@ -1075,7 +1075,8 @@ impl EmitterWriter {
10751075
};
10761076
format!("{}:{}{}",
10771077
annotated_file.file.name,
1078-
sm.doctest_offset_line(first_line.line_index),
1078+
sm.doctest_offset_line(
1079+
&annotated_file.file.name, first_line.line_index),
10791080
col)
10801081
} else {
10811082
annotated_file.file.name.to_string()

src/librustc_errors/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ pub trait SourceMapper {
130130
fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
131131
fn call_span_if_macro(&self, sp: Span) -> Span;
132132
fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool;
133-
fn doctest_offset_line(&self, line: usize) -> usize;
133+
fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize;
134134
}
135135

136136
impl CodeSuggestion {

src/librustdoc/clean/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3008,7 +3008,7 @@ pub struct Span {
30083008
impl Span {
30093009
pub fn empty() -> Span {
30103010
Span {
3011-
filename: FileName::Anon,
3011+
filename: FileName::Anon(0),
30123012
loline: 0, locol: 0,
30133013
hiline: 0, hicol: 0,
30143014
}

src/librustdoc/test.rs

+9-9
Original file line numberDiff line numberDiff line change
@@ -197,8 +197,14 @@ fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
197197
let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts);
198198
// FIXME(#44940): if doctests ever support path remapping, then this filename
199199
// needs to be the result of SourceMap::span_to_unmapped_path
200+
201+
let path = match filename {
202+
FileName::Real(path) => path.clone(),
203+
_ => PathBuf::from(r"doctest.rs"),
204+
};
205+
200206
let input = config::Input::Str {
201-
name: filename.to_owned(),
207+
name: FileName::DocTest(path, line as isize - line_offset as isize),
202208
input: test,
203209
};
204210
let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
@@ -252,9 +258,7 @@ fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
252258
let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
253259

254260
let (libdir, outdir, compile_result) = driver::spawn_thread_pool(sessopts, |sessopts| {
255-
let source_map = Lrc::new(SourceMap::new_doctest(
256-
sessopts.file_path_mapping(), filename.clone(), line as isize - line_offset as isize
257-
));
261+
let source_map = Lrc::new(SourceMap::new(sessopts.file_path_mapping()));
258262
let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
259263
Some(source_map.clone()),
260264
false,
@@ -401,7 +405,7 @@ pub fn make_test(s: &str,
401405
use errors::emitter::EmitterWriter;
402406
use errors::Handler;
403407

404-
let filename = FileName::Anon;
408+
let filename = FileName::anon_source_code(s);
405409
let source = crates + &everything_else;
406410

407411
// any errors in parsing should also appear when the doctest is compiled for real, so just
@@ -411,8 +415,6 @@ pub fn make_test(s: &str,
411415
let handler = Handler::with_emitter(false, false, box emitter);
412416
let sess = ParseSess::with_span_handler(handler, cm);
413417

414-
debug!("about to parse: \n{}", source);
415-
416418
let mut found_main = false;
417419
let mut found_extern_crate = cratename.is_none();
418420

@@ -487,8 +489,6 @@ pub fn make_test(s: &str,
487489
prog.push_str("\n}");
488490
}
489491

490-
info!("final test program: {}", prog);
491-
492492
(prog, line_offset)
493493
}
494494

src/libsyntax/attr/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -803,7 +803,7 @@ pub fn inject(mut krate: ast::Crate, parse_sess: &ParseSess, attrs: &[String]) -
803803
for raw_attr in attrs {
804804
let mut parser = parse::new_parser_from_source_str(
805805
parse_sess,
806-
FileName::CliCrateAttr,
806+
FileName::cli_crate_attr_source_code(&raw_attr),
807807
raw_attr.clone(),
808808
);
809809

src/libsyntax/ext/quote.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -353,27 +353,27 @@ pub mod rt {
353353
impl<'a> ExtParseUtils for ExtCtxt<'a> {
354354
fn parse_item(&self, s: String) -> P<ast::Item> {
355355
panictry!(parse::parse_item_from_source_str(
356-
FileName::QuoteExpansion,
356+
FileName::quote_expansion_source_code(&s),
357357
s,
358358
self.parse_sess())).expect("parse error")
359359
}
360360

361361
fn parse_stmt(&self, s: String) -> ast::Stmt {
362362
panictry!(parse::parse_stmt_from_source_str(
363-
FileName::QuoteExpansion,
363+
FileName::quote_expansion_source_code(&s),
364364
s,
365365
self.parse_sess())).expect("parse error")
366366
}
367367

368368
fn parse_expr(&self, s: String) -> P<ast::Expr> {
369369
panictry!(parse::parse_expr_from_source_str(
370-
FileName::QuoteExpansion,
370+
FileName::quote_expansion_source_code(&s),
371371
s,
372372
self.parse_sess()))
373373
}
374374

375375
fn parse_tts(&self, s: String) -> Vec<TokenTree> {
376-
let source_name = FileName::QuoteExpansion;
376+
let source_name = FileName::quote_expansion_source_code(&s);
377377
parse::parse_stream_from_source_str(source_name, s, self.parse_sess(), None)
378378
.into_trees().collect()
379379
}

src/libsyntax/ext/source_util.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -182,9 +182,12 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::Toke
182182
DummyResult::expr(sp)
183183
}
184184
Ok(..) => {
185-
// Add this input file to the code map to make it available as
186-
// dependency information, but don't enter it's contents
187-
cx.source_map().new_source_file(file.into(), String::new());
185+
let src = match String::from_utf8(bytes.clone()) {
186+
Ok(contents) => contents,
187+
Err(..) => "".to_string()
188+
};
189+
190+
cx.source_map().new_source_file(file.into(), src);
188191

189192
base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes))))
190193
}
@@ -201,6 +204,7 @@ fn res_rel_file(cx: &mut ExtCtxt, sp: syntax_pos::Span, arg: String) -> PathBuf
201204
let callsite = sp.source_callsite();
202205
let mut path = match cx.source_map().span_to_unmapped_path(callsite) {
203206
FileName::Real(path) => path,
207+
FileName::DocTest(path, _) => path,
204208
other => panic!("cannot resolve relative path in non-file source `{}`", other),
205209
};
206210
path.pop();

src/libsyntax/parse/lexer/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1900,7 +1900,7 @@ mod tests {
19001900
sess: &'a ParseSess,
19011901
teststr: String)
19021902
-> StringReader<'a> {
1903-
let sf = sm.new_source_file(PathBuf::from("zebra.rs").into(), teststr);
1903+
let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr);
19041904
StringReader::new(sess, sf, None)
19051905
}
19061906

src/libsyntax/parse/mod.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -974,23 +974,25 @@ mod tests {
974974
with_globals(|| {
975975
let sess = ParseSess::new(FilePathMapping::empty());
976976

977-
let name = FileName::Custom("source".to_string());
977+
let name_1 = FileName::Custom("crlf_source_1".to_string());
978978
let source = "/// doc comment\r\nfn foo() {}".to_string();
979-
let item = parse_item_from_source_str(name.clone(), source, &sess)
979+
let item = parse_item_from_source_str(name_1, source, &sess)
980980
.unwrap().unwrap();
981981
let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
982982
assert_eq!(doc, "/// doc comment");
983983

984+
let name_2 = FileName::Custom("crlf_source_2".to_string());
984985
let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
985-
let item = parse_item_from_source_str(name.clone(), source, &sess)
986+
let item = parse_item_from_source_str(name_2, source, &sess)
986987
.unwrap().unwrap();
987988
let docs = item.attrs.iter().filter(|a| a.path == "doc")
988989
.map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
989990
let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
990991
assert_eq!(&docs[..], b);
991992

993+
let name_3 = FileName::Custom("clrf_source_3".to_string());
992994
let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
993-
let item = parse_item_from_source_str(name, source, &sess).unwrap().unwrap();
995+
let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
994996
let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
995997
assert_eq!(doc, "/** doc comment\n * with CRLF */");
996998
});

src/libsyntax/parse/token.rs

+8-5
Original file line numberDiff line numberDiff line change
@@ -545,7 +545,8 @@ impl Token {
545545
let tokens_for_real = nt.1.force(|| {
546546
// FIXME(#43081): Avoid this pretty-print + reparse hack
547547
let source = pprust::token_to_string(self);
548-
parse_stream_from_source_str(FileName::MacroExpansion, source, sess, Some(span))
548+
let filename = FileName::macro_expansion_source_code(&source);
549+
parse_stream_from_source_str(filename, source, sess, Some(span))
549550
});
550551

551552
// During early phases of the compiler the AST could get modified
@@ -781,10 +782,12 @@ fn prepend_attrs(sess: &ParseSess,
781782
assert_eq!(attr.style, ast::AttrStyle::Outer,
782783
"inner attributes should prevent cached tokens from existing");
783784

785+
let source = pprust::attr_to_string(attr);
786+
let macro_filename = FileName::macro_expansion_source_code(&source);
784787
if attr.is_sugared_doc {
785788
let stream = parse_stream_from_source_str(
786-
FileName::MacroExpansion,
787-
pprust::attr_to_string(attr),
789+
macro_filename,
790+
source,
788791
sess,
789792
Some(span),
790793
);
@@ -805,8 +808,8 @@ fn prepend_attrs(sess: &ParseSess,
805808
// should eventually be removed.
806809
} else {
807810
let stream = parse_stream_from_source_str(
808-
FileName::MacroExpansion,
809-
pprust::path_to_string(&attr.path),
811+
macro_filename,
812+
source,
810813
sess,
811814
Some(span),
812815
);

0 commit comments

Comments
 (0)