Skip to content

53956 panic on include bytes of own file #54517

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions src/librustc/ich/impls_syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -417,13 +417,14 @@ impl_stable_hash_for!(enum ::syntax_pos::hygiene::CompilerDesugaringKind {
impl_stable_hash_for!(enum ::syntax_pos::FileName {
Real(pb),
Macros(s),
QuoteExpansion,
Anon,
MacroExpansion,
ProcMacroSourceCode,
CliCrateAttr,
CfgSpec,
Custom(s)
QuoteExpansion(s),
Anon(s),
MacroExpansion(s),
ProcMacroSourceCode(s),
CliCrateAttr(s),
CfgSpec(s),
Custom(s),
DocTest(pb, line),
});

impl<'a> HashStable<StableHashingContext<'a>> for SourceFile {
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/session/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1756,8 +1756,8 @@ pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> ast::CrateConfig {
.into_iter()
.map(|s| {
let sess = parse::ParseSess::new(FilePathMapping::empty());
let mut parser =
parse::new_parser_from_source_str(&sess, FileName::CfgSpec, s.to_string());
let filename = FileName::cfg_spec_source_code(&s);
let mut parser = parse::new_parser_from_source_str(&sess, filename, s.to_string());

macro_rules! error {($reason: expr) => {
early_error(ErrorOutputType::default(),
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_driver/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option
} else {
None
};
Some((Input::Str { name: FileName::Anon, input: src },
Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
None, err))
} else {
Some((Input::File(PathBuf::from(ifile)),
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_driver/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ fn test_env_with_pool<F>(
let cstore = CStore::new(::get_codegen_backend(&sess).metadata_loader());
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
let input = config::Input::Str {
name: FileName::Anon,
name: FileName::anon_source_code(&source_string),
input: source_string.to_string(),
};
let krate =
Expand Down
7 changes: 4 additions & 3 deletions src/librustc_errors/emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1044,7 +1044,7 @@ impl EmitterWriter {
buffer.append(buffer_msg_line_offset,
&format!("{}:{}:{}",
loc.file.name,
sm.doctest_offset_line(loc.line),
sm.doctest_offset_line(&loc.file.name, loc.line),
loc.col.0 + 1),
Style::LineAndColumn);
for _ in 0..max_line_num_len {
Expand All @@ -1054,7 +1054,7 @@ impl EmitterWriter {
buffer.prepend(0,
&format!("{}:{}:{}: ",
loc.file.name,
sm.doctest_offset_line(loc.line),
sm.doctest_offset_line(&loc.file.name, loc.line),
loc.col.0 + 1),
Style::LineAndColumn);
}
Expand All @@ -1075,7 +1075,8 @@ impl EmitterWriter {
};
format!("{}:{}{}",
annotated_file.file.name,
sm.doctest_offset_line(first_line.line_index),
sm.doctest_offset_line(
&annotated_file.file.name, first_line.line_index),
col)
} else {
annotated_file.file.name.to_string()
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_errors/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ pub trait SourceMapper {
fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
fn call_span_if_macro(&self, sp: Span) -> Span;
fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool;
fn doctest_offset_line(&self, line: usize) -> usize;
fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize;
}

impl CodeSuggestion {
Expand Down
2 changes: 1 addition & 1 deletion src/librustdoc/clean/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3008,7 +3008,7 @@ pub struct Span {
impl Span {
pub fn empty() -> Span {
Span {
filename: FileName::Anon,
filename: FileName::Anon(0),
loline: 0, locol: 0,
hiline: 0, hicol: 0,
}
Expand Down
18 changes: 9 additions & 9 deletions src/librustdoc/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,14 @@ fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts);
// FIXME(#44940): if doctests ever support path remapping, then this filename
// needs to be the result of SourceMap::span_to_unmapped_path

let path = match filename {
FileName::Real(path) => path.clone(),
_ => PathBuf::from(r"doctest.rs"),
};

let input = config::Input::Str {
name: filename.to_owned(),
name: FileName::DocTest(path, line as isize - line_offset as isize),
input: test,
};
let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
Expand Down Expand Up @@ -252,9 +258,7 @@ fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));

let (libdir, outdir, compile_result) = driver::spawn_thread_pool(sessopts, |sessopts| {
let source_map = Lrc::new(SourceMap::new_doctest(
sessopts.file_path_mapping(), filename.clone(), line as isize - line_offset as isize
));
let source_map = Lrc::new(SourceMap::new(sessopts.file_path_mapping()));
let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
Some(source_map.clone()),
false,
Expand Down Expand Up @@ -401,7 +405,7 @@ pub fn make_test(s: &str,
use errors::emitter::EmitterWriter;
use errors::Handler;

let filename = FileName::Anon;
let filename = FileName::anon_source_code(s);
let source = crates + &everything_else;

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

debug!("about to parse: \n{}", source);

let mut found_main = false;
let mut found_extern_crate = cratename.is_none();

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

info!("final test program: {}", prog);

(prog, line_offset)
}

Expand Down
2 changes: 1 addition & 1 deletion src/libsyntax/attr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -803,7 +803,7 @@ pub fn inject(mut krate: ast::Crate, parse_sess: &ParseSess, attrs: &[String]) -
for raw_attr in attrs {
let mut parser = parse::new_parser_from_source_str(
parse_sess,
FileName::CliCrateAttr,
FileName::cli_crate_attr_source_code(&raw_attr),
raw_attr.clone(),
);

Expand Down
8 changes: 4 additions & 4 deletions src/libsyntax/ext/quote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,27 +353,27 @@ pub mod rt {
impl<'a> ExtParseUtils for ExtCtxt<'a> {
fn parse_item(&self, s: String) -> P<ast::Item> {
panictry!(parse::parse_item_from_source_str(
FileName::QuoteExpansion,
FileName::quote_expansion_source_code(&s),
s,
self.parse_sess())).expect("parse error")
}

fn parse_stmt(&self, s: String) -> ast::Stmt {
panictry!(parse::parse_stmt_from_source_str(
FileName::QuoteExpansion,
FileName::quote_expansion_source_code(&s),
s,
self.parse_sess())).expect("parse error")
}

fn parse_expr(&self, s: String) -> P<ast::Expr> {
panictry!(parse::parse_expr_from_source_str(
FileName::QuoteExpansion,
FileName::quote_expansion_source_code(&s),
s,
self.parse_sess()))
}

fn parse_tts(&self, s: String) -> Vec<TokenTree> {
let source_name = FileName::QuoteExpansion;
let source_name = FileName::quote_expansion_source_code(&s);
parse::parse_stream_from_source_str(source_name, s, self.parse_sess(), None)
.into_trees().collect()
}
Expand Down
10 changes: 7 additions & 3 deletions src/libsyntax/ext/source_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,12 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::Toke
DummyResult::expr(sp)
}
Ok(..) => {
// Add this input file to the code map to make it available as
// dependency information, but don't enter it's contents
cx.source_map().new_source_file(file.into(), String::new());
let src = match String::from_utf8(bytes.clone()) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You shouldn't need to clone the bytes vec.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is cloned because bytes is also used to make both the src string and the LitKind::ByteStr ast node at the end of the method.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh right, I didn't see that. Nevermind then.

Ok(contents) => contents,
Err(..) => "".to_string()
};

cx.source_map().new_source_file(file.into(), src);

base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes))))
}
Expand All @@ -201,6 +204,7 @@ fn res_rel_file(cx: &mut ExtCtxt, sp: syntax_pos::Span, arg: String) -> PathBuf
let callsite = sp.source_callsite();
let mut path = match cx.source_map().span_to_unmapped_path(callsite) {
FileName::Real(path) => path,
FileName::DocTest(path, _) => path,
other => panic!("cannot resolve relative path in non-file source `{}`", other),
};
path.pop();
Expand Down
2 changes: 1 addition & 1 deletion src/libsyntax/parse/lexer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1898,7 +1898,7 @@ mod tests {
sess: &'a ParseSess,
teststr: String)
-> StringReader<'a> {
let sf = sm.new_source_file(PathBuf::from("zebra.rs").into(), teststr);
let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr);
StringReader::new(sess, sf, None)
}

Expand Down
10 changes: 6 additions & 4 deletions src/libsyntax/parse/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -977,23 +977,25 @@ mod tests {
with_globals(|| {
let sess = ParseSess::new(FilePathMapping::empty());

let name = FileName::Custom("source".to_string());
let name_1 = FileName::Custom("crlf_source_1".to_string());
let source = "/// doc comment\r\nfn foo() {}".to_string();
let item = parse_item_from_source_str(name.clone(), source, &sess)
let item = parse_item_from_source_str(name_1, source, &sess)
.unwrap().unwrap();
let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
assert_eq!(doc, "/// doc comment");

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

let name_3 = FileName::Custom("clrf_source_3".to_string());
let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
let item = parse_item_from_source_str(name, source, &sess).unwrap().unwrap();
let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
assert_eq!(doc, "/** doc comment\n * with CRLF */");
});
Expand Down
13 changes: 8 additions & 5 deletions src/libsyntax/parse/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -545,7 +545,8 @@ impl Token {
let tokens_for_real = nt.1.force(|| {
// FIXME(#43081): Avoid this pretty-print + reparse hack
let source = pprust::token_to_string(self);
parse_stream_from_source_str(FileName::MacroExpansion, source, sess, Some(span))
let filename = FileName::macro_expansion_source_code(&source);
parse_stream_from_source_str(filename, source, sess, Some(span))
});

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

let source = pprust::attr_to_string(attr);
let macro_filename = FileName::macro_expansion_source_code(&source);
if attr.is_sugared_doc {
let stream = parse_stream_from_source_str(
FileName::MacroExpansion,
pprust::attr_to_string(attr),
macro_filename,
source,
sess,
Some(span),
);
Expand All @@ -805,8 +808,8 @@ fn prepend_attrs(sess: &ParseSess,
// should eventually be removed.
} else {
let stream = parse_stream_from_source_str(
FileName::MacroExpansion,
pprust::path_to_string(&attr.path),
macro_filename,
source,
sess,
Some(span),
);
Expand Down
Loading