From 6ee4d3cafce0d46b2d76a3f96aa62ca985a3ab6c Mon Sep 17 00:00:00 2001 From: Matthew Russo Date: Tue, 30 Oct 2018 10:10:42 -0400 Subject: new_source_file no longer enters duplicate files, expand_include_bytes includes the source if it can convert bytes to string --- src/libsyntax/source_map.rs | 50 ++++++++++++++++++++++++++++++--------------- 1 file changed, 34 insertions(+), 16 deletions(-) (limited to 'src/libsyntax/source_map.rs') diff --git a/src/libsyntax/source_map.rs b/src/libsyntax/source_map.rs index e8cacc3b5af..b027e7d5778 100644 --- a/src/libsyntax/source_map.rs +++ b/src/libsyntax/source_map.rs @@ -110,11 +110,19 @@ pub struct StableSourceFileId(u128); impl StableSourceFileId { pub fn new(source_file: &SourceFile) -> StableSourceFileId { + StableFilemapId::new_from_pieces(&source_file.name, + source_file.name_was_remapped, + source_file.unmapped_path.as_ref()) + } + + pub fn new_from_pieces(name: &FileName, + name_was_remapped: bool, + unmapped_path: Option<&FileName>) -> StableFilemapId { let mut hasher = StableHasher::new(); - source_file.name.hash(&mut hasher); - source_file.name_was_remapped.hash(&mut hasher); - source_file.unmapped_path.hash(&mut hasher); + name.hash(&mut hasher); + name_was_remapped.hash(&mut hasher); + unmapped_path.hash(&mut hasher); StableSourceFileId(hasher.finish()) } @@ -208,7 +216,8 @@ impl SourceMap { } /// Creates a new source_file. - /// This does not ensure that only one SourceFile exists per file name. + /// If a file already exists in the source_map with the same id, that file is returned + /// unmodified pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc { let start_pos = self.next_start_pos(); @@ -226,21 +235,30 @@ impl SourceMap { }, other => (other, false), }; - let source_file = Lrc::new(SourceFile::new( - filename, - was_remapped, - unmapped_path, - src, - Pos::from_usize(start_pos), - )); - let mut files = self.files.borrow_mut(); + let file_id = StableFilemapId::new_from_pieces(&filename, + was_remapped, + Some(&unmapped_path)); - files.source_files.push(source_file.clone()); - files.stable_id_to_source_file.insert(StableSourceFileId::new(&source_file), - source_file.clone()); + return match self.source_file_by_stable_id(file_id) { + Some(lrc_sf) => lrc_sf, + None => { + let source_file = Lrc::new(SourceFile::new( + filename, + was_remapped, + unmapped_path, + src, + Pos::from_usize(start_pos), + )); - source_file + let mut files = self.files.borrow_mut(); + + files.source_files.push(source_file.clone()); + files.stable_id_to_source_file.insert(file_id, source_file.clone()); + + source_file + } + } } /// Allocates a new SourceFile representing a source file from an external -- cgit 1.4.1-3-g733a5 From 88130f1796e98837dc6f58aea9b9a0f49b85f426 Mon Sep 17 00:00:00 2001 From: Matthew Russo Date: Tue, 30 Oct 2018 10:11:24 -0400 Subject: updates all Filename variants to take a fingerprint --- src/librustc/ich/impls_syntax.rs | 12 +-- src/librustc/session/config.rs | 4 +- src/librustc_driver/lib.rs | 2 +- src/librustc_driver/test.rs | 2 +- src/librustdoc/clean/mod.rs | 2 +- src/libsyntax/attr/mod.rs | 2 +- src/libsyntax/ext/quote.rs | 8 +- src/libsyntax/parse/token.rs | 13 ++-- src/libsyntax/source_map.rs | 6 +- src/libsyntax_pos/lib.rs | 85 ++++++++++++++++------ src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs | 2 +- .../run-pass-fulldeps/pprust-expr-roundtrip.rs | 6 +- 12 files changed, 93 insertions(+), 51 deletions(-) (limited to 'src/libsyntax/source_map.rs') diff --git a/src/librustc/ich/impls_syntax.rs b/src/librustc/ich/impls_syntax.rs index b629fb820b3..dbf0147928a 100644 --- a/src/librustc/ich/impls_syntax.rs +++ b/src/librustc/ich/impls_syntax.rs @@ -417,12 +417,12 @@ 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, + QuoteExpansion(s), + Anon(s), + MacroExpansion(s), + ProcMacroSourceCode(s), + CliCrateAttr(s), + CfgSpec(s), Custom(s) }); diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index 480d4a8e48f..c9866230cdd 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -1756,8 +1756,8 @@ pub fn parse_cfgspecs(cfgspecs: Vec) -> 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(), diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 061c19eca36..45d107f13a0 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -594,7 +594,7 @@ fn make_input(free_matches: &[String]) -> Option<(Input, Option, 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)), diff --git a/src/librustc_driver/test.rs b/src/librustc_driver/test.rs index 8865c7e438e..b8cd9bda7f0 100644 --- a/src/librustc_driver/test.rs +++ b/src/librustc_driver/test.rs @@ -129,7 +129,7 @@ fn test_env_with_pool( 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 = diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index fd8f70b19e7..85ade8ffe75 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -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, } diff --git a/src/libsyntax/attr/mod.rs b/src/libsyntax/attr/mod.rs index 64876659477..518b34eefa8 100644 --- a/src/libsyntax/attr/mod.rs +++ b/src/libsyntax/attr/mod.rs @@ -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(), ); diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index 69ed318b049..91818992fe1 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -353,27 +353,27 @@ pub mod rt { impl<'a> ExtParseUtils for ExtCtxt<'a> { fn parse_item(&self, s: String) -> P { 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 { 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 { - 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() } diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 4a5f3e240da..04a791fbcb9 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -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 @@ -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), ); @@ -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), ); diff --git a/src/libsyntax/source_map.rs b/src/libsyntax/source_map.rs index b027e7d5778..e22d4f8f133 100644 --- a/src/libsyntax/source_map.rs +++ b/src/libsyntax/source_map.rs @@ -110,14 +110,14 @@ pub struct StableSourceFileId(u128); impl StableSourceFileId { pub fn new(source_file: &SourceFile) -> StableSourceFileId { - StableFilemapId::new_from_pieces(&source_file.name, + StableSourceFileId::new_from_pieces(&source_file.name, source_file.name_was_remapped, source_file.unmapped_path.as_ref()) } pub fn new_from_pieces(name: &FileName, name_was_remapped: bool, - unmapped_path: Option<&FileName>) -> StableFilemapId { + unmapped_path: Option<&FileName>) -> StableSourceFileId { let mut hasher = StableHasher::new(); name.hash(&mut hasher); @@ -236,7 +236,7 @@ impl SourceMap { other => (other, false), }; - let file_id = StableFilemapId::new_from_pieces(&filename, + let file_id = StableSourceFileId::new_from_pieces(&filename, was_remapped, Some(&unmapped_path)); diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs index 34fb71e4ddf..ff3c1cf9f47 100644 --- a/src/libsyntax_pos/lib.rs +++ b/src/libsyntax_pos/lib.rs @@ -90,17 +90,17 @@ pub enum FileName { /// A macro. This includes the full name of the macro, so that there are no clashes. Macros(String), /// call to `quote!` - QuoteExpansion, + QuoteExpansion(u64), /// Command line - Anon, + Anon(u64), /// Hack in src/libsyntax/parse.rs /// FIXME(jseyfried) - MacroExpansion, - ProcMacroSourceCode, + MacroExpansion(u64), + ProcMacroSourceCode(u64), /// Strings provided as --cfg [cfgspec] stored in a crate_cfg - CfgSpec, + CfgSpec(u64), /// Strings provided as crate attributes in the CLI - CliCrateAttr, + CliCrateAttr(u64), /// Custom sources for explicit parser calls from plugins and drivers Custom(String), } @@ -111,12 +111,13 @@ impl std::fmt::Display for FileName { match *self { Real(ref path) => write!(fmt, "{}", path.display()), Macros(ref name) => write!(fmt, "<{} macros>", name), - QuoteExpansion => write!(fmt, ""), - MacroExpansion => write!(fmt, ""), - Anon => write!(fmt, ""), - ProcMacroSourceCode => write!(fmt, ""), - CfgSpec => write!(fmt, "cfgspec"), - CliCrateAttr => write!(fmt, ""), + QuoteExpansion(_) => write!(fmt, ""), + MacroExpansion(_) => write!(fmt, ""), + Anon(_) => write!(fmt, ""), + ProcMacroSourceCode(_) => + write!(fmt, ""), + CfgSpec(_) => write!(fmt, ""), + CliCrateAttr(_) => write!(fmt, ""), Custom(ref s) => write!(fmt, "<{}>", s), } } @@ -135,13 +136,13 @@ impl FileName { match *self { Real(_) => true, Macros(_) | - Anon | - MacroExpansion | - ProcMacroSourceCode | - CfgSpec | - CliCrateAttr | + Anon(_) | + MacroExpansion(_) | + ProcMacroSourceCode(_) | + CfgSpec(_) | + CliCrateAttr(_) | Custom(_) | - QuoteExpansion => false, + QuoteExpansion(_) => false, } } @@ -149,16 +150,52 @@ impl FileName { use self::FileName::*; match *self { Real(_) | - Anon | - MacroExpansion | - ProcMacroSourceCode | - CfgSpec | - CliCrateAttr | + Anon(_) | + MacroExpansion(_) | + ProcMacroSourceCode(_) | + CfgSpec(_) | + CliCrateAttr(_) | Custom(_) | - QuoteExpansion => false, + QuoteExpansion(_) => false, Macros(_) => true, } } + + pub fn quote_expansion_source_code(src: &str) -> FileName { + let mut hasher = StableHasher::new(); + src.hash(&mut hasher); + FileName::QuoteExpansion(hasher.finish()) + } + + pub fn macro_expansion_source_code(src: &str) -> FileName { + let mut hasher = StableHasher::new(); + src.hash(&mut hasher); + FileName::MacroExpansion(hasher.finish()) + } + + pub fn anon_source_code(src: &str) -> FileName { + let mut hasher = StableHasher::new(); + src.hash(&mut hasher); + FileName::Anon(hasher.finish()) + } + + pub fn proc_macro_source_code(src: &str) -> FileName { + let mut hasher = StableHasher::new(); + src.hash(&mut hasher); + FileName::ProcMacroSourceCode(hasher.finish()) + } + + pub fn cfg_spec_source_code(src: &str) -> FileName { + let mut hasher = StableHasher::new(); + src.hash(&mut hasher); + FileName::QuoteExpansion(hasher.finish()) + } + + pub fn cli_crate_attr_source_code(src: &str) -> FileName { + let mut hasher = StableHasher::new(); + src.hash(&mut hasher); + FileName::CliCrateAttr(hasher.finish()) + } } /// Spans represent a region of code, used for error reporting. Positions in spans diff --git a/src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs b/src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs index 8f54f2e2dc3..97d5fab569d 100644 --- a/src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs +++ b/src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs @@ -33,7 +33,7 @@ use std::fmt; // Copied out of syntax::util::parser_testing pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> { - new_parser_from_source_str(ps, FileName::Custom("bogofile".to_owned()), source_str) + new_parser_from_source_str(ps, FileName::Custom(source_str.clone()), source_str) } fn with_error_checking_parse<'a, T, F>(s: String, ps: &'a ParseSess, f: F) -> PResult<'a, T> where diff --git a/src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs b/src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs index e944ef2b620..854063a2984 100644 --- a/src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs +++ b/src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs @@ -44,9 +44,11 @@ use syntax::ptr::P; fn parse_expr(ps: &ParseSess, src: &str) -> P { + let src_as_string = src.to_string(); + let mut p = parse::new_parser_from_source_str(ps, - FileName::Custom("expr".to_owned()), - src.to_owned()); + FileName::Custom(src_as_string.clone()), + src_as_string); p.parse_expr().unwrap() } -- cgit 1.4.1-3-g733a5 From f0f8aa9e05726bfbc065fa2504daf3232f29bc03 Mon Sep 17 00:00:00 2001 From: Matthew Russo Date: Tue, 4 Dec 2018 15:18:03 -0500 Subject: adds DocTest filename variant, refactors doctest_offset out of source_map, fixes remaining test failures --- src/librustc/ich/impls_syntax.rs | 3 +- src/librustc_errors/emitter.rs | 7 ++-- src/librustc_errors/lib.rs | 2 +- src/librustdoc/test.rs | 18 +++++----- src/libsyntax/ext/source_util.rs | 1 + src/libsyntax/parse/lexer/mod.rs | 2 +- src/libsyntax/parse/mod.rs | 10 +++--- src/libsyntax/source_map.rs | 42 ++++++++---------------- src/libsyntax_ext/proc_macro_server.rs | 2 +- src/libsyntax_pos/lib.rs | 12 +++++-- src/test/run-make-fulldeps/issue-19371/foo.rs | 3 +- src/test/rustdoc-ui/failed-doctest-output.stdout | 4 +-- 12 files changed, 52 insertions(+), 54 deletions(-) (limited to 'src/libsyntax/source_map.rs') diff --git a/src/librustc/ich/impls_syntax.rs b/src/librustc/ich/impls_syntax.rs index dbf0147928a..439c6e42e1a 100644 --- a/src/librustc/ich/impls_syntax.rs +++ b/src/librustc/ich/impls_syntax.rs @@ -423,7 +423,8 @@ impl_stable_hash_for!(enum ::syntax_pos::FileName { ProcMacroSourceCode(s), CliCrateAttr(s), CfgSpec(s), - Custom(s) + Custom(s), + DocTest(pb, line), }); impl<'a> HashStable> for SourceFile { diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs index 7e69e98071d..ab2ab25c91a 100644 --- a/src/librustc_errors/emitter.rs +++ b/src/librustc_errors/emitter.rs @@ -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 { @@ -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); } @@ -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() diff --git a/src/librustc_errors/lib.rs b/src/librustc_errors/lib.rs index 0fb77a7a3ab..b6528cbe2c8 100644 --- a/src/librustc_errors/lib.rs +++ b/src/librustc_errors/lib.rs @@ -130,7 +130,7 @@ pub trait SourceMapper { fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option; fn call_span_if_macro(&self, sp: Span) -> Span; fn ensure_source_file_source_present(&self, source_file: Lrc) -> bool; - fn doctest_offset_line(&self, line: usize) -> usize; + fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize; } impl CodeSuggestion { diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index d9bab91fd0c..74583196818 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -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)]); @@ -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, @@ -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 @@ -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(); @@ -487,8 +489,6 @@ pub fn make_test(s: &str, prog.push_str("\n}"); } - info!("final test program: {}", prog); - (prog, line_offset) } diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 654be85862f..75e25083d03 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -204,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(); diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index c90c62c13f9..5c3e11c8c19 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -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) } diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index ac972f20f94..a229ccfa265 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -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::>(); 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 */"); }); diff --git a/src/libsyntax/source_map.rs b/src/libsyntax/source_map.rs index e22d4f8f133..ee60d2dd615 100644 --- a/src/libsyntax/source_map.rs +++ b/src/libsyntax/source_map.rs @@ -144,9 +144,6 @@ pub struct SourceMap { // This is used to apply the file path remapping as specified via // --remap-path-prefix to all SourceFiles allocated within this SourceMap. path_mapping: FilePathMapping, - /// In case we are in a doctest, replace all file names with the PathBuf, - /// and add the given offsets to the line info - doctest_offset: Option<(FileName, isize)>, } impl SourceMap { @@ -155,19 +152,9 @@ impl SourceMap { files: Default::default(), file_loader: Box::new(RealFileLoader), path_mapping, - doctest_offset: None, } } - pub fn new_doctest(path_mapping: FilePathMapping, - file: FileName, line: isize) -> SourceMap { - SourceMap { - doctest_offset: Some((file, line)), - ..SourceMap::new(path_mapping) - } - - } - pub fn with_file_loader(file_loader: Box, path_mapping: FilePathMapping) -> SourceMap { @@ -175,7 +162,6 @@ impl SourceMap { files: Default::default(), file_loader: file_loader, path_mapping, - doctest_offset: None, } } @@ -189,11 +175,7 @@ impl SourceMap { pub fn load_file(&self, path: &Path) -> io::Result> { let src = self.file_loader.read_file(path)?; - let filename = if let Some((ref name, _)) = self.doctest_offset { - name.clone() - } else { - path.to_owned().into() - }; + let filename = path.to_owned().into(); Ok(self.new_source_file(filename, src)) } @@ -328,15 +310,17 @@ impl SourceMap { } // If there is a doctest_offset, apply it to the line - pub fn doctest_offset_line(&self, mut orig: usize) -> usize { - if let Some((_, line)) = self.doctest_offset { - if line >= 0 { - orig = orig + line as usize; - } else { - orig = orig - (-line) as usize; - } + pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize { + return match file { + FileName::DocTest(_, offset) => { + return if *offset >= 0 { + orig + *offset as usize + } else { + orig - (-(*offset)) as usize + } + }, + _ => orig } - orig } /// Lookup source information about a BytePos @@ -1001,8 +985,8 @@ impl SourceMapper for SourceMap { } ) } - fn doctest_offset_line(&self, line: usize) -> usize { - self.doctest_offset_line(line) + fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize { + self.doctest_offset_line(file, line) } } diff --git a/src/libsyntax_ext/proc_macro_server.rs b/src/libsyntax_ext/proc_macro_server.rs index 4babc2e612f..6c7da589a42 100644 --- a/src/libsyntax_ext/proc_macro_server.rs +++ b/src/libsyntax_ext/proc_macro_server.rs @@ -402,7 +402,7 @@ impl server::TokenStream for Rustc<'_> { } fn from_str(&mut self, src: &str) -> Self::TokenStream { parse::parse_stream_from_source_str( - FileName::ProcMacroSourceCode, + FileName::proc_macro_source_code(src.clone()), src.to_string(), self.sess, Some(self.call_site), diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs index ff3c1cf9f47..4d42b85ea75 100644 --- a/src/libsyntax_pos/lib.rs +++ b/src/libsyntax_pos/lib.rs @@ -103,6 +103,7 @@ pub enum FileName { CliCrateAttr(u64), /// Custom sources for explicit parser calls from plugins and drivers Custom(String), + DocTest(PathBuf, isize), } impl std::fmt::Display for FileName { @@ -119,6 +120,7 @@ impl std::fmt::Display for FileName { CfgSpec(_) => write!(fmt, ""), CliCrateAttr(_) => write!(fmt, ""), Custom(ref s) => write!(fmt, "<{}>", s), + DocTest(ref path, _) => write!(fmt, "{}", path.display()), } } } @@ -142,7 +144,8 @@ impl FileName { CfgSpec(_) | CliCrateAttr(_) | Custom(_) | - QuoteExpansion(_) => false, + QuoteExpansion(_) | + DocTest(_, _) => false, } } @@ -156,7 +159,8 @@ impl FileName { CfgSpec(_) | CliCrateAttr(_) | Custom(_) | - QuoteExpansion(_) => false, + QuoteExpansion(_) | + DocTest(_, _) => false, Macros(_) => true, } } @@ -196,6 +200,10 @@ impl FileName { src.hash(&mut hasher); FileName::CliCrateAttr(hasher.finish()) } + + pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName{ + FileName::DocTest(path, line) + } } /// Spans represent a region of code, used for error reporting. Positions in spans diff --git a/src/test/run-make-fulldeps/issue-19371/foo.rs b/src/test/run-make-fulldeps/issue-19371/foo.rs index 4dfecb33c14..c342e1c4835 100644 --- a/src/test/run-make-fulldeps/issue-19371/foo.rs +++ b/src/test/run-make-fulldeps/issue-19371/foo.rs @@ -72,7 +72,8 @@ fn compile(code: String, output: PathBuf, sysroot: PathBuf) { driver::spawn_thread_pool(opts, |opts| { let (sess, cstore, codegen_backend) = basic_sess(opts); let control = CompileController::basic(); - let input = Input::Str { name: FileName::Anon, input: code }; + let name = FileName::anon_source_code(&code); + let input = Input::Str { name, input: code }; let _ = compile_input( codegen_backend, &sess, diff --git a/src/test/rustdoc-ui/failed-doctest-output.stdout b/src/test/rustdoc-ui/failed-doctest-output.stdout index cab7bda6c67..52e0cdca950 100644 --- a/src/test/rustdoc-ui/failed-doctest-output.stdout +++ b/src/test/rustdoc-ui/failed-doctest-output.stdout @@ -12,7 +12,7 @@ error[E0425]: cannot find value `no` in this scope 3 | no | ^^ not found in this scope -thread '$DIR/failed-doctest-output.rs - OtherStruct (line 27)' panicked at 'couldn't compile the test', src/librustdoc/test.rs:323:13 +thread '$DIR/failed-doctest-output.rs - OtherStruct (line 27)' panicked at 'couldn't compile the test', src/librustdoc/test.rs:327:13 note: Run with `RUST_BACKTRACE=1` for a backtrace. ---- $DIR/failed-doctest-output.rs - SomeStruct (line 21) stdout ---- @@ -21,7 +21,7 @@ thread '$DIR/failed-doctest-output.rs - SomeStruct (line 21)' panicked at 'test thread 'main' panicked at 'oh no', $DIR/failed-doctest-output.rs:3:1 note: Run with `RUST_BACKTRACE=1` for a backtrace. -', src/librustdoc/test.rs:358:17 +', src/librustdoc/test.rs:362:17 failures: -- cgit 1.4.1-3-g733a5 From 2f6226518bd5085896a0f27cfd3ea396367ecd50 Mon Sep 17 00:00:00 2001 From: Andy Russell Date: Fri, 16 Nov 2018 16:22:06 -0500 Subject: use top level `fs` functions where appropriate This commit replaces many usages of `File::open` and reading or writing with `fs::read_to_string`, `fs::read` and `fs::write`. This reduces code complexity, and will improve performance for most reads, since the functions allocate the buffer to be the size of the file. I believe that this commit will not impact behavior in any way, so some matches will check the error kind in case the file was not valid UTF-8. Some of these cases may not actually care about the error. --- src/bootstrap/compile.rs | 19 +++--- src/bootstrap/config.rs | 7 +-- src/bootstrap/dist.rs | 14 ++--- src/bootstrap/doc.rs | 14 ++--- src/bootstrap/lib.rs | 6 +- src/bootstrap/native.rs | 9 +-- src/bootstrap/sanity.rs | 7 +-- src/bootstrap/test.rs | 9 +-- src/libcore/convert.rs | 7 +-- .../infer/lexical_region_resolve/graphviz.rs | 5 +- src/librustc_codegen_utils/codegen_backend.rs | 13 ++-- src/librustdoc/html/render.rs | 16 ++--- src/librustdoc/theme.rs | 10 +--- src/libsyntax/ext/expand.rs | 47 ++++++++------- src/libsyntax/ext/source_util.rs | 54 +++++++---------- src/libsyntax/source_map.rs | 6 +- src/tools/build-manifest/src/main.rs | 4 +- src/tools/cargotest/main.rs | 8 +-- src/tools/compiletest/src/main.rs | 8 +-- src/tools/compiletest/src/runtest.rs | 70 ++++++---------------- src/tools/error_index_generator/main.rs | 7 +-- src/tools/tidy/src/bins.rs | 5 +- src/tools/tidy/src/cargo.rs | 9 +-- src/tools/tidy/src/deps.rs | 6 +- src/tools/tidy/src/extdeps.rs | 6 +- src/tools/tidy/src/features.rs | 6 +- 26 files changed, 137 insertions(+), 235 deletions(-) (limited to 'src/libsyntax/source_map.rs') diff --git a/src/bootstrap/compile.rs b/src/bootstrap/compile.rs index b6bb11d07ef..2e792b6053e 100644 --- a/src/bootstrap/compile.rs +++ b/src/bootstrap/compile.rs @@ -18,7 +18,7 @@ use std::borrow::Cow; use std::env; -use std::fs::{self, File}; +use std::fs; use std::io::BufReader; use std::io::prelude::*; use std::path::{Path, PathBuf}; @@ -707,7 +707,7 @@ impl Step for CodegenBackend { } let stamp = codegen_backend_stamp(builder, compiler, target, backend); let codegen_backend = codegen_backend.to_str().unwrap(); - t!(t!(File::create(&stamp)).write_all(codegen_backend.as_bytes())); + t!(fs::write(&stamp, &codegen_backend)); } } @@ -796,8 +796,7 @@ fn copy_codegen_backends_to_sysroot(builder: &Builder, for backend in builder.config.rust_codegen_backends.iter() { let stamp = codegen_backend_stamp(builder, compiler, target, *backend); - let mut dylib = String::new(); - t!(t!(File::open(&stamp)).read_to_string(&mut dylib)); + let dylib = t!(fs::read_to_string(&stamp)); let file = Path::new(&dylib); let filename = file.file_name().unwrap().to_str().unwrap(); // change `librustc_codegen_llvm-xxxxxx.so` to `librustc_codegen_llvm-llvm.so` @@ -1137,10 +1136,7 @@ pub fn run_cargo(builder: &Builder, // contents (the list of files to copy) is different or if any dep's mtime // is newer then we rewrite the stamp file. deps.sort(); - let mut stamp_contents = Vec::new(); - if let Ok(mut f) = File::open(stamp) { - t!(f.read_to_end(&mut stamp_contents)); - } + let stamp_contents = fs::read(stamp); let stamp_mtime = mtime(&stamp); let mut new_contents = Vec::new(); let mut max = None; @@ -1156,7 +1152,10 @@ pub fn run_cargo(builder: &Builder, } let max = max.unwrap(); let max_path = max_path.unwrap(); - if stamp_contents == new_contents && max <= stamp_mtime { + let contents_equal = stamp_contents + .map(|contents| contents == new_contents) + .unwrap_or_default(); + if contents_equal && max <= stamp_mtime { builder.verbose(&format!("not updating {:?}; contents equal and {:?} <= {:?}", stamp, max, stamp_mtime)); return deps @@ -1166,7 +1165,7 @@ pub fn run_cargo(builder: &Builder, } else { builder.verbose(&format!("updating {:?} as deps changed", stamp)); } - t!(t!(File::create(stamp)).write_all(&new_contents)); + t!(fs::write(&stamp, &new_contents)); deps } diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 8fc2d5787cb..1dafbe148af 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -15,8 +15,7 @@ use std::collections::{HashMap, HashSet}; use std::env; -use std::fs::{self, File}; -use std::io::prelude::*; +use std::fs; use std::path::{Path, PathBuf}; use std::process; use std::cmp; @@ -416,9 +415,7 @@ impl Config { config.run_host_only = !(flags.host.is_empty() && !flags.target.is_empty()); let toml = file.map(|file| { - let mut f = t!(File::open(&file)); - let mut contents = String::new(); - t!(f.read_to_string(&mut contents)); + let contents = t!(fs::read_to_string(&file)); match toml::from_str(&contents) { Ok(table) => table, Err(err) => { diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 6108692e43c..d9ff6276d52 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -19,8 +19,8 @@ //! pieces of `rustup.rs`! use std::env; -use std::fs::{self, File}; -use std::io::{Read, Write}; +use std::fs; +use std::io::Write; use std::path::{PathBuf, Path}; use std::process::{Command, Stdio}; @@ -1511,8 +1511,7 @@ impl Step for Extended { } let xform = |p: &Path| { - let mut contents = String::new(); - t!(t!(File::open(p)).read_to_string(&mut contents)); + let mut contents = t!(fs::read_to_string(p)); if rls_installer.is_none() { contents = filter(&contents, "rls"); } @@ -1523,8 +1522,8 @@ impl Step for Extended { contents = filter(&contents, "rustfmt"); } let ret = tmp.join(p.file_name().unwrap()); - t!(t!(File::create(&ret)).write_all(contents.as_bytes())); - return ret + t!(fs::write(&ret, &contents)); + ret }; if target.contains("apple-darwin") { @@ -1869,8 +1868,7 @@ impl Step for HashSign { let file = builder.config.dist_gpg_password_file.as_ref().unwrap_or_else(|| { panic!("\n\nfailed to specify `dist.gpg-password-file` in `config.toml`\n\n") }); - let mut pass = String::new(); - t!(t!(File::open(&file)).read_to_string(&mut pass)); + let pass = t!(fs::read_to_string(&file)); let today = output(Command::new("date").arg("+%Y-%m-%d")); diff --git a/src/bootstrap/doc.rs b/src/bootstrap/doc.rs index e9c27a3f3cf..2d0625b26db 100644 --- a/src/bootstrap/doc.rs +++ b/src/bootstrap/doc.rs @@ -18,8 +18,7 @@ //! `rustdoc`. use std::collections::HashSet; -use std::fs::{self, File}; -use std::io::prelude::*; +use std::fs; use std::io; use std::path::{PathBuf, Path}; @@ -379,12 +378,11 @@ impl Step for Standalone { let version_info = out.join("version_info.html"); if !builder.config.dry_run && !up_to_date(&version_input, &version_info) { - let mut info = String::new(); - t!(t!(File::open(&version_input)).read_to_string(&mut info)); - let info = info.replace("VERSION", &builder.rust_release()) - .replace("SHORT_HASH", builder.rust_info.sha_short().unwrap_or("")) - .replace("STAMP", builder.rust_info.sha().unwrap_or("")); - t!(t!(File::create(&version_info)).write_all(info.as_bytes())); + let info = t!(fs::read_to_string(&version_input)) + .replace("VERSION", &builder.rust_release()) + .replace("SHORT_HASH", builder.rust_info.sha_short().unwrap_or("")) + .replace("STAMP", builder.rust_info.sha().unwrap_or("")); + t!(fs::write(&version_info, &info)); } for file in t!(fs::read_dir(builder.src.join("src/doc"))) { diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index 2832f5bebdd..a62830da4bb 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -1067,9 +1067,8 @@ impl Build { /// Returns the `a.b.c` version that the given package is at. fn release_num(&self, package: &str) -> String { - let mut toml = String::new(); let toml_file_name = self.src.join(&format!("src/tools/{}/Cargo.toml", package)); - t!(t!(File::open(toml_file_name)).read_to_string(&mut toml)); + let toml = t!(fs::read_to_string(&toml_file_name)); for line in toml.lines() { let prefix = "version = \""; let suffix = "\""; @@ -1151,8 +1150,7 @@ impl Build { } let mut paths = Vec::new(); - let mut contents = Vec::new(); - t!(t!(File::open(stamp)).read_to_end(&mut contents)); + let contents = t!(fs::read(stamp)); // This is the method we use for extracting paths from the stamp file passed to us. See // run_cargo for more information (in compile.rs). for part in contents.split(|b| *b == 0) { diff --git a/src/bootstrap/native.rs b/src/bootstrap/native.rs index 448967ef0c2..150b6bea180 100644 --- a/src/bootstrap/native.rs +++ b/src/bootstrap/native.rs @@ -21,7 +21,6 @@ use std::env; use std::ffi::OsString; use std::fs::{self, File}; -use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::process::Command; @@ -75,8 +74,7 @@ impl Step for Llvm { } let rebuild_trigger = builder.src.join("src/rustllvm/llvm-rebuild-trigger"); - let mut rebuild_trigger_contents = String::new(); - t!(t!(File::open(&rebuild_trigger)).read_to_string(&mut rebuild_trigger_contents)); + let rebuild_trigger_contents = t!(fs::read_to_string(&rebuild_trigger)); let (out_dir, llvm_config_ret_dir) = if emscripten { let dir = builder.emscripten_llvm_out(target); @@ -93,8 +91,7 @@ impl Step for Llvm { let build_llvm_config = llvm_config_ret_dir .join(exe("llvm-config", &*builder.config.build)); if done_stamp.exists() { - let mut done_contents = String::new(); - t!(t!(File::open(&done_stamp)).read_to_string(&mut done_contents)); + let done_contents = t!(fs::read_to_string(&done_stamp)); // If LLVM was already built previously and contents of the rebuild-trigger file // didn't change from the previous build, then no action is required. @@ -261,7 +258,7 @@ impl Step for Llvm { cfg.build(); - t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes())); + t!(fs::write(&done_stamp, &rebuild_trigger_contents)); build_llvm_config } diff --git a/src/bootstrap/sanity.rs b/src/bootstrap/sanity.rs index 15d3bccba09..7a9e6d4fd38 100644 --- a/src/bootstrap/sanity.rs +++ b/src/bootstrap/sanity.rs @@ -21,8 +21,7 @@ use std::collections::HashMap; use std::env; use std::ffi::{OsString, OsStr}; -use std::fs::{self, File}; -use std::io::Read; +use std::fs; use std::path::PathBuf; use std::process::Command; @@ -235,9 +234,7 @@ $ pacman -R cmake && pacman -S mingw-w64-x86_64-cmake } if build.config.channel == "stable" { - let mut stage0 = String::new(); - t!(t!(File::open(build.src.join("src/stage0.txt"))) - .read_to_string(&mut stage0)); + let stage0 = t!(fs::read_to_string(build.src.join("src/stage0.txt"))); if stage0.contains("\ndev:") { panic!("bootstrapping from a dev compiler in a stable release, but \ should only be bootstrapping from a released compiler!"); diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index da827356800..4ece3435e92 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -16,8 +16,7 @@ use std::env; use std::ffi::OsString; use std::fmt; -use std::fs::{self, File}; -use std::io::Read; +use std::fs; use std::iter; use std::path::{Path, PathBuf}; use std::process::Command; @@ -1427,10 +1426,8 @@ impl Step for ErrorIndex { } fn markdown_test(builder: &Builder, compiler: Compiler, markdown: &Path) -> bool { - match File::open(markdown) { - Ok(mut file) => { - let mut contents = String::new(); - t!(file.read_to_string(&mut contents)); + match fs::read_to_string(markdown) { + Ok(contents) => { if !contents.contains("```") { return true; } diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs index dbc28ef7cf6..2d4813718f4 100644 --- a/src/libcore/convert.rs +++ b/src/libcore/convert.rs @@ -327,7 +327,8 @@ pub trait Into: Sized { /// An example usage for error handling: /// /// ``` -/// use std::io::{self, Read}; +/// use std::fs; +/// use std::io; /// use std::num; /// /// enum CliError { @@ -348,9 +349,7 @@ pub trait Into: Sized { /// } /// /// fn open_and_parse_file(file_name: &str) -> Result { -/// let mut file = std::fs::File::open("test")?; -/// let mut contents = String::new(); -/// file.read_to_string(&mut contents)?; +/// let mut contents = fs::read_to_string(&file_name)?; /// let num: i32 = contents.trim().parse()?; /// Ok(num) /// } diff --git a/src/librustc/infer/lexical_region_resolve/graphviz.rs b/src/librustc/infer/lexical_region_resolve/graphviz.rs index a210d63f129..512e57d810a 100644 --- a/src/librustc/infer/lexical_region_resolve/graphviz.rs +++ b/src/librustc/infer/lexical_region_resolve/graphviz.rs @@ -31,9 +31,8 @@ use std::borrow::Cow; use std::collections::hash_map::Entry::Vacant; use std::collections::btree_map::BTreeMap; use std::env; -use std::fs::File; +use std::fs; use std::io; -use std::io::prelude::*; use std::sync::atomic::{AtomicBool, Ordering}; fn print_help_message() { @@ -268,5 +267,5 @@ fn dump_region_data_to<'a, 'gcx, 'tcx>(region_rels: &RegionRelations<'a, 'gcx, ' debug!("dump_region_data calling render"); let mut v = Vec::new(); dot::render(&g, &mut v).unwrap(); - File::create(path).and_then(|mut f| f.write_all(&v)) + fs::write(path, &v) } diff --git a/src/librustc_codegen_utils/codegen_backend.rs b/src/librustc_codegen_utils/codegen_backend.rs index b328873800e..74718460f56 100644 --- a/src/librustc_codegen_utils/codegen_backend.rs +++ b/src/librustc_codegen_utils/codegen_backend.rs @@ -22,8 +22,8 @@ #![feature(box_syntax)] use std::any::Any; -use std::io::{self, Write}; -use std::fs::File; +use std::io::Write; +use std::fs; use std::path::Path; use std::sync::{mpsc, Arc}; @@ -81,11 +81,7 @@ pub struct NoLlvmMetadataLoader; impl MetadataLoader for NoLlvmMetadataLoader { fn get_rlib_metadata(&self, _: &Target, filename: &Path) -> Result { - let mut file = File::open(filename) - .map_err(|e| format!("metadata file open err: {:?}", e))?; - - let mut buf = Vec::new(); - io::copy(&mut file, &mut buf).unwrap(); + let buf = fs::read(filename).map_err(|e| format!("metadata file open err: {:?}", e))?; let buf: OwningRef, [u8]> = OwningRef::new(buf); Ok(rustc_erase_owner!(buf.map_owner_box())) } @@ -209,8 +205,7 @@ impl CodegenBackend for MetadataOnlyCodegenBackend { } else { &ongoing_codegen.metadata.raw_data }; - let mut file = File::create(&output_name).unwrap(); - file.write_all(metadata).unwrap(); + fs::write(&output_name, metadata).unwrap(); } sess.abort_if_errors(); diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 30054f66e2f..b316cddf0c8 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -778,10 +778,7 @@ fn write_shared( let mut themes: FxHashSet = FxHashSet::default(); for entry in &cx.shared.themes { - let mut content = Vec::with_capacity(100000); - - let mut f = try_err!(File::open(&entry), &entry); - try_err!(f.read_to_end(&mut content), &entry); + let content = try_err!(fs::read(&entry), &entry); let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry); let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry); write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)), @@ -881,10 +878,7 @@ themePicker.onblur = handleThemeButtonsBlur; if !options.enable_minification { try_err!(fs::copy(css, out), css); } else { - let mut f = try_err!(File::open(css), css); - let mut buffer = String::with_capacity(1000); - - try_err!(f.read_to_string(&mut buffer), css); + let buffer = try_err!(fs::read_to_string(css), css); write_minify(out, &buffer, options.enable_minification)?; } } @@ -2102,8 +2096,7 @@ impl Context { if !buf.is_empty() { try_err!(this.shared.ensure_dir(&this.dst), &this.dst); let joint_dst = this.dst.join("index.html"); - let mut dst = try_err!(File::create(&joint_dst), &joint_dst); - try_err!(dst.write_all(&buf), &joint_dst); + try_err!(fs::write(&joint_dst, buf), &joint_dst); } let m = match item.inner { @@ -2137,8 +2130,7 @@ impl Context { let file_name = &item_path(item_type, name); try_err!(self.shared.ensure_dir(&self.dst), &self.dst); let joint_dst = self.dst.join(file_name); - let mut dst = try_err!(File::create(&joint_dst), &joint_dst); - try_err!(dst.write_all(&buf), &joint_dst); + try_err!(fs::write(&joint_dst, buf), &joint_dst); if !self.render_redirect_pages { all.append(full_path(self, &item), &item_type); diff --git a/src/librustdoc/theme.rs b/src/librustdoc/theme.rs index 55a11d19765..206a72cebfe 100644 --- a/src/librustdoc/theme.rs +++ b/src/librustdoc/theme.rs @@ -9,9 +9,8 @@ // except according to those terms. use rustc_data_structures::fx::FxHashSet; -use std::fs::File; +use std::fs; use std::hash::{Hash, Hasher}; -use std::io::Read; use std::path::Path; use errors::Handler; @@ -278,12 +277,9 @@ pub fn get_differences(against: &CssPath, other: &CssPath, v: &mut Vec) pub fn test_theme_against>(f: &P, against: &CssPath, diag: &Handler) -> (bool, Vec) { - let mut file = try_something!(File::open(f), diag, (false, Vec::new())); - let mut data = Vec::with_capacity(1000); - - try_something!(file.read_to_end(&mut data), diag, (false, Vec::new())); + let data = try_something!(fs::read(f), diag, (false, vec![])); let paths = load_css_paths(&data); - let mut ret = Vec::new(); + let mut ret = vec![]; get_differences(against, &paths, &mut ret); (true, ret) } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 14f19c493b3..bb5be7f5394 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -34,8 +34,8 @@ use tokenstream::{TokenStream, TokenTree}; use visit::{self, Visitor}; use rustc_data_structures::fx::FxHashMap; -use std::fs::File; -use std::io::Read; +use std::fs; +use std::io::ErrorKind; use std::{iter, mem}; use std::rc::Rc; use std::path::PathBuf; @@ -1507,20 +1507,8 @@ impl<'a, 'b> Folder for InvocationCollector<'a, 'b> { return noop_fold_attribute(at, self); } - let mut buf = vec![]; let filename = self.cx.root_path.join(file.to_string()); - - match File::open(&filename).and_then(|mut f| f.read_to_end(&mut buf)) { - Ok(..) => {} - Err(e) => { - self.cx.span_err(at.span, - &format!("couldn't read {}: {}", - filename.display(), - e)); - } - } - - match String::from_utf8(buf) { + match fs::read_to_string(&filename) { Ok(src) => { let src_interned = Symbol::intern(&src); @@ -1530,21 +1518,34 @@ impl<'a, 'b> Folder for InvocationCollector<'a, 'b> { let include_info = vec![ dummy_spanned(ast::NestedMetaItemKind::MetaItem( - attr::mk_name_value_item_str(Ident::from_str("file"), - dummy_spanned(file)))), + attr::mk_name_value_item_str( + Ident::from_str("file"), + dummy_spanned(file), + ), + )), dummy_spanned(ast::NestedMetaItemKind::MetaItem( - attr::mk_name_value_item_str(Ident::from_str("contents"), - dummy_spanned(src_interned)))), + attr::mk_name_value_item_str( + Ident::from_str("contents"), + dummy_spanned(src_interned), + ), + )), ]; let include_ident = Ident::from_str("include"); let item = attr::mk_list_item(DUMMY_SP, include_ident, include_info); items.push(dummy_spanned(ast::NestedMetaItemKind::MetaItem(item))); } - Err(_) => { - self.cx.span_err(at.span, - &format!("{} wasn't a utf-8 file", - filename.display())); + Err(ref e) if e.kind() == ErrorKind::InvalidData => { + self.cx.span_err( + at.span, + &format!("{} wasn't a utf-8 file", filename.display()), + ); + } + Err(e) => { + self.cx.span_err( + at.span, + &format!("couldn't read {}: {}", filename.display(), e), + ); } } } else { diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 75e25083d03..ec27ceeb74c 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -21,8 +21,8 @@ use smallvec::SmallVec; use symbol::Symbol; use tokenstream; -use std::fs::File; -use std::io::prelude::*; +use std::fs; +use std::io::ErrorKind; use std::path::PathBuf; use rustc_data_structures::sync::Lrc; @@ -137,18 +137,7 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenT None => return DummyResult::expr(sp) }; let file = res_rel_file(cx, sp, file); - let mut bytes = Vec::new(); - match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) { - Ok(..) => {} - Err(e) => { - cx.span_err(sp, - &format!("couldn't read {}: {}", - file.display(), - e)); - return DummyResult::expr(sp); - } - }; - match String::from_utf8(bytes) { + match fs::read_to_string(&file) { Ok(src) => { let interned_src = Symbol::intern(&src); @@ -157,11 +146,13 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenT cx.source_map().new_source_file(file.into(), src); base::MacEager::expr(cx.expr_str(sp, interned_src)) + }, + Err(ref e) if e.kind() == ErrorKind::InvalidData => { + cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display())); + DummyResult::expr(sp) } - Err(_) => { - cx.span_err(sp, - &format!("{} wasn't a utf-8 file", - file.display())); + Err(e) => { + cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e)); DummyResult::expr(sp) } } @@ -174,22 +165,23 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::Toke None => return DummyResult::expr(sp) }; let file = res_rel_file(cx, sp, file); - let mut bytes = Vec::new(); - match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) { - Err(e) => { - cx.span_err(sp, - &format!("couldn't read {}: {}", file.display(), e)); - DummyResult::expr(sp) - } - Ok(..) => { - let src = match String::from_utf8(bytes.clone()) { - Ok(contents) => contents, - Err(..) => "".to_string() + match fs::read(&file) { + Ok(bytes) => { + // Add the contents to the source map if it contains UTF-8. + let (contents, bytes) = match String::from_utf8(bytes) { + Ok(s) => { + let bytes = s.as_bytes().to_owned(); + (s, bytes) + }, + Err(e) => (String::new(), e.into_bytes()), }; - - cx.source_map().new_source_file(file.into(), src); + cx.source_map().new_source_file(file.into(), contents); base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes)))) + }, + Err(e) => { + cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e)); + DummyResult::expr(sp) } } } diff --git a/src/libsyntax/source_map.rs b/src/libsyntax/source_map.rs index ee60d2dd615..45008129e83 100644 --- a/src/libsyntax/source_map.rs +++ b/src/libsyntax/source_map.rs @@ -31,7 +31,7 @@ use std::path::{Path, PathBuf}; use std::env; use std::fs; -use std::io::{self, Read}; +use std::io; use errors::SourceMapper; /// Return the span itself if it doesn't come from a macro expansion, @@ -96,9 +96,7 @@ impl FileLoader for RealFileLoader { } fn read_file(&self, path: &Path) -> io::Result { - let mut src = String::new(); - fs::File::open(path)?.read_to_string(&mut src)?; - Ok(src) + fs::read_to_string(path) } } diff --git a/src/tools/build-manifest/src/main.rs b/src/tools/build-manifest/src/main.rs index bf95b31ae3c..d9834f9f0a0 100644 --- a/src/tools/build-manifest/src/main.rs +++ b/src/tools/build-manifest/src/main.rs @@ -606,7 +606,7 @@ impl Builder { let filename = path.file_name().unwrap().to_str().unwrap(); let sha256 = self.output.join(format!("{}.sha256", filename)); - t!(t!(File::create(&sha256)).write_all(&sha.stdout)); + t!(fs::write(&sha256, &sha.stdout)); let stdout = String::from_utf8_lossy(&sha.stdout); stdout.split_whitespace().next().unwrap().to_string() @@ -643,7 +643,7 @@ impl Builder { fn write(&self, contents: &str, channel_name: &str, suffix: &str) { let dst = self.output.join(format!("channel-rust-{}{}", channel_name, suffix)); - t!(t!(File::create(&dst)).write_all(contents.as_bytes())); + t!(fs::write(&dst, contents)); self.hash(&dst); self.sign(&dst); } diff --git a/src/tools/cargotest/main.rs b/src/tools/cargotest/main.rs index 5b717c45254..ab74e7b7a7f 100644 --- a/src/tools/cargotest/main.rs +++ b/src/tools/cargotest/main.rs @@ -11,8 +11,7 @@ use std::env; use std::process::Command; use std::path::{Path, PathBuf}; -use std::fs::File; -use std::io::Write; +use std::fs; struct Test { repo: &'static str, @@ -91,10 +90,7 @@ fn test_repo(cargo: &Path, out_dir: &Path, test: &Test) { println!("testing {}", test.repo); let dir = clone_repo(test, out_dir); if let Some(lockfile) = test.lock { - File::create(&dir.join("Cargo.lock")) - .expect("") - .write_all(lockfile.as_bytes()) - .expect(""); + fs::write(&dir.join("Cargo.lock"), lockfile).unwrap(); } if !run_cargo_test(cargo, &dir, test.packages) { panic!("tests failed for {}", test.repo); diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs index f63950b448a..65f6bff7eaf 100644 --- a/src/tools/compiletest/src/main.rs +++ b/src/tools/compiletest/src/main.rs @@ -38,7 +38,7 @@ use getopts::Options; use std::env; use std::ffi::OsString; use std::fs; -use std::io::{self, Read}; +use std::io::{self, ErrorKind}; use std::path::{Path, PathBuf}; use std::process::Command; use test::ColorConfig; @@ -686,13 +686,11 @@ fn up_to_date( ) -> bool { let stamp_name = stamp(config, testpaths, revision); // Check hash. - let mut f = match fs::File::open(&stamp_name) { + let contents = match fs::read_to_string(&stamp_name) { Ok(f) => f, + Err(ref e) if e.kind() == ErrorKind::InvalidData => panic!("Can't read stamp contents"), Err(_) => return true, }; - let mut contents = String::new(); - f.read_to_string(&mut contents) - .expect("Can't read stamp contents"); let expected_hash = runtest::compute_stamp_hash(config); if contents != expected_hash { return true; diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index c654230e203..45527a7cce5 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -458,11 +458,7 @@ impl<'test> TestCx<'test> { None => 2, }; - let mut src = String::new(); - File::open(&self.testpaths.file) - .unwrap() - .read_to_string(&mut src) - .unwrap(); + let src = fs::read_to_string(&self.testpaths.file).unwrap(); let mut srcs = vec![src]; let mut round = 0; @@ -500,12 +496,7 @@ impl<'test> TestCx<'test> { let mut expected = match self.props.pp_exact { Some(ref file) => { let filepath = self.testpaths.file.parent().unwrap().join(file); - let mut s = String::new(); - File::open(&filepath) - .unwrap() - .read_to_string(&mut s) - .unwrap(); - s + fs::read_to_string(&filepath).unwrap() } None => srcs[srcs.len() - 2].clone(), }; @@ -1949,10 +1940,7 @@ impl<'test> TestCx<'test> { fn dump_output_file(&self, out: &str, extension: &str) { let outfile = self.make_out_name(extension); - File::create(&outfile) - .unwrap() - .write_all(out.as_bytes()) - .unwrap(); + fs::write(&outfile, out).unwrap(); } /// Create a filename for output with the given extension. Example: @@ -2149,11 +2137,7 @@ impl<'test> TestCx<'test> { path: &P, mut other_files: Option<&mut Vec>, ) -> Vec { - let mut file = - fs::File::open(path).expect("markdown_test_output_check_entry File::open failed"); - let mut content = String::new(); - file.read_to_string(&mut content) - .expect("markdown_test_output_check_entry read_to_string failed"); + let content = fs::read_to_string(&path).unwrap(); let mut ignore = false; content .lines() @@ -2826,11 +2810,7 @@ impl<'test> TestCx<'test> { } fn check_mir_dump(&self) { - let mut test_file_contents = String::new(); - fs::File::open(self.testpaths.file.clone()) - .unwrap() - .read_to_string(&mut test_file_contents) - .unwrap(); + let test_file_contents = fs::read_to_string(&self.testpaths.file).unwrap(); if let Some(idx) = test_file_contents.find("// END RUST SOURCE") { let (_, tests_text) = test_file_contents.split_at(idx + "// END_RUST SOURCE".len()); let tests_text_str = String::from(tests_text); @@ -2894,9 +2874,7 @@ impl<'test> TestCx<'test> { } self.check_mir_test_timestamp(test_name, &output_file); - let mut dumped_file = fs::File::open(output_file.clone()).unwrap(); - let mut dumped_string = String::new(); - dumped_file.read_to_string(&mut dumped_string).unwrap(); + let dumped_string = fs::read_to_string(&output_file).unwrap(); let mut dumped_lines = dumped_string .lines() .map(|l| nocomment_mir_line(l)) @@ -3108,19 +3086,13 @@ impl<'test> TestCx<'test> { } fn load_expected_output_from_path(&self, path: &Path) -> Result { - let mut result = String::new(); - match File::open(path).and_then(|mut f| f.read_to_string(&mut result)) { - Ok(_) => Ok(result), - Err(e) => Err(format!( - "failed to load expected output from `{}`: {}", - path.display(), - e - )), - } + fs::read_to_string(path).map_err(|err| { + format!("failed to load expected output from `{}`: {}", path.display(), err) + }) } fn delete_file(&self, file: &PathBuf) { - if let Err(e) = ::std::fs::remove_file(file) { + if let Err(e) = fs::remove_file(file) { self.fatal(&format!( "failed to delete `{}`: {}", file.display(), @@ -3182,16 +3154,13 @@ impl<'test> TestCx<'test> { for output_file in &files { if actual.is_empty() { self.delete_file(output_file); - } else { - match File::create(&output_file).and_then(|mut f| f.write_all(actual.as_bytes())) { - Ok(()) => {} - Err(e) => self.fatal(&format!( - "failed to write {} to `{}`: {}", - kind, - output_file.display(), - e - )), - } + } else if let Err(err) = fs::write(&output_file, &actual) { + self.fatal(&format!( + "failed to write {} to `{}`: {}", + kind, + output_file.display(), + err, + )); } } @@ -3243,9 +3212,8 @@ impl<'test> TestCx<'test> { } fn create_stamp(&self) { - let mut f = File::create(::stamp(&self.config, self.testpaths, self.revision)).unwrap(); - f.write_all(compute_stamp_hash(&self.config).as_bytes()) - .unwrap(); + let stamp = ::stamp(&self.config, self.testpaths, self.revision); + fs::write(&stamp, compute_stamp_hash(&self.config)).unwrap(); } } diff --git a/src/tools/error_index_generator/main.rs b/src/tools/error_index_generator/main.rs index a5556e1d570..03add412b64 100644 --- a/src/tools/error_index_generator/main.rs +++ b/src/tools/error_index_generator/main.rs @@ -18,8 +18,8 @@ extern crate serialize as rustc_serialize; use std::collections::BTreeMap; use std::env; use std::error::Error; -use std::fs::{read_dir, File}; -use std::io::{Read, Write}; +use std::fs::{self, read_dir, File}; +use std::io::Write; use std::path::Path; use std::path::PathBuf; use std::cell::RefCell; @@ -210,8 +210,7 @@ fn load_all_errors(metadata_dir: &Path) -> Result bool { if !path.exists() { panic!("{} does not exist", path.display()); } - let mut contents = String::new(); - t!(t!(File::open(path)).read_to_string(&mut contents)); + let contents = t!(fs::read_to_string(&path)); let mut found_license = false; for line in contents.lines() { diff --git a/src/tools/tidy/src/extdeps.rs b/src/tools/tidy/src/extdeps.rs index a78d2d4ee4e..377a7c33d75 100644 --- a/src/tools/tidy/src/extdeps.rs +++ b/src/tools/tidy/src/extdeps.rs @@ -10,8 +10,7 @@ // ! Check for external package sources. Allow only vendorable packages. -use std::fs::File; -use std::io::Read; +use std::fs; use std::path::Path; /// List of whitelisted sources for packages @@ -25,8 +24,7 @@ pub fn check(path: &Path, bad: &mut bool) { let path = path.join("../Cargo.lock"); // open and read the whole file - let mut cargo_lock = String::new(); - t!(t!(File::open(path)).read_to_string(&mut cargo_lock)); + let cargo_lock = t!(fs::read_to_string(&path)); // process each line for line in cargo_lock.lines() { diff --git a/src/tools/tidy/src/features.rs b/src/tools/tidy/src/features.rs index 85b123e4af5..b0bd5ba8dbd 100644 --- a/src/tools/tidy/src/features.rs +++ b/src/tools/tidy/src/features.rs @@ -20,7 +20,7 @@ use std::collections::HashMap; use std::fmt; -use std::fs::File; +use std::fs::{self, File}; use std::io::prelude::*; use std::path::Path; @@ -183,9 +183,7 @@ fn test_filen_gate(filen_underscore: &str, features: &mut Features) -> bool { } pub fn collect_lang_features(base_src_path: &Path, bad: &mut bool) -> Features { - let mut contents = String::new(); - let path = base_src_path.join("libsyntax/feature_gate.rs"); - t!(t!(File::open(path)).read_to_string(&mut contents)); + let contents = t!(fs::read_to_string(base_src_path.join("libsyntax/feature_gate.rs"))); // we allow rustc-internal features to omit a tracking issue. // these features must be marked with `// rustc internal` in its own group. -- cgit 1.4.1-3-g733a5 From cf47a19305d929d1870414dd6911ca3191597668 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 5 Dec 2018 06:42:56 -0800 Subject: Bump to 1.33.0 * Update bootstrap compiler * Update version to 1.33.0 * Remove some `#[cfg(stage0)]` annotations Actually updating the version number is blocked on updating Cargo --- src/bootstrap/channel.rs | 2 +- src/liballoc/tests/str.rs | 8 ++++---- src/libcore/ffi.rs | 4 ---- src/libcore/intrinsics.rs | 3 --- src/libcore/mem.rs | 1 - src/libcore/num/mod.rs | 14 ++------------ src/libcore/ops/unsize.rs | 2 +- src/libcore/sync/atomic.rs | 4 ++-- src/librustc/lint/builtin.rs | 2 +- src/librustc_errors/emitter.rs | 2 +- src/librustc_lint/nonstandard_style.rs | 4 ++-- src/librustc_llvm/build.rs | 4 ++-- src/librustc_mir/borrow_check/move_errors.rs | 4 ++-- src/librustc_mir/interpret/intrinsics.rs | 2 +- src/librustc_typeck/check/demand.rs | 4 ++-- src/librustdoc/markdown.rs | 2 +- src/librustdoc/passes/collect_intra_doc_links.rs | 10 +++++----- src/librustdoc/passes/unindent_comments.rs | 2 +- src/libserialize/json.rs | 2 +- src/libstd/error.rs | 1 + src/libstd/ffi/mod.rs | 1 - src/libstd/io/error.rs | 1 + src/libstd/lib.rs | 4 ---- src/libstd/panic.rs | 4 ++-- src/libstd/sys/windows/os.rs | 2 +- src/libsyntax/diagnostics/plugin.rs | 1 + src/libsyntax/source_map.rs | 8 ++++---- src/libsyntax_pos/symbol.rs | 2 +- src/stage0.txt | 2 +- src/tools/cargo | 2 +- src/tools/compiletest/src/main.rs | 6 +++++- 31 files changed, 47 insertions(+), 63 deletions(-) (limited to 'src/libsyntax/source_map.rs') diff --git a/src/bootstrap/channel.rs b/src/bootstrap/channel.rs index 88b6925b2b1..878b6ed73a3 100644 --- a/src/bootstrap/channel.rs +++ b/src/bootstrap/channel.rs @@ -24,7 +24,7 @@ use Build; use config::Config; // The version number -pub const CFG_RELEASE_NUM: &str = "1.32.0"; +pub const CFG_RELEASE_NUM: &str = "1.33.0"; pub struct GitInfo { inner: Option, diff --git a/src/liballoc/tests/str.rs b/src/liballoc/tests/str.rs index 683ce2bf112..9ad8ad1fc07 100644 --- a/src/liballoc/tests/str.rs +++ b/src/liballoc/tests/str.rs @@ -1514,9 +1514,9 @@ fn contains_weird_cases() { #[test] fn trim_ws() { - assert_eq!(" \t a \t ".trim_left_matches(|c: char| c.is_whitespace()), + assert_eq!(" \t a \t ".trim_start_matches(|c: char| c.is_whitespace()), "a \t "); - assert_eq!(" \t a \t ".trim_right_matches(|c: char| c.is_whitespace()), + assert_eq!(" \t a \t ".trim_end_matches(|c: char| c.is_whitespace()), " \t a"); assert_eq!(" \t a \t ".trim_start_matches(|c: char| c.is_whitespace()), "a \t "); @@ -1524,9 +1524,9 @@ fn trim_ws() { " \t a"); assert_eq!(" \t a \t ".trim_matches(|c: char| c.is_whitespace()), "a"); - assert_eq!(" \t \t ".trim_left_matches(|c: char| c.is_whitespace()), + assert_eq!(" \t \t ".trim_start_matches(|c: char| c.is_whitespace()), ""); - assert_eq!(" \t \t ".trim_right_matches(|c: char| c.is_whitespace()), + assert_eq!(" \t \t ".trim_end_matches(|c: char| c.is_whitespace()), ""); assert_eq!(" \t \t ".trim_start_matches(|c: char| c.is_whitespace()), ""); diff --git a/src/libcore/ffi.rs b/src/libcore/ffi.rs index d7a112eb90d..899fae90946 100644 --- a/src/libcore/ffi.rs +++ b/src/libcore/ffi.rs @@ -1,7 +1,6 @@ #![stable(feature = "", since = "1.30.0")] #![allow(non_camel_case_types)] -#![cfg_attr(stage0, allow(dead_code))] //! Utilities related to FFI bindings. @@ -123,7 +122,6 @@ struct VaListImpl { all supported platforms", issue = "27745")] #[repr(transparent)] -#[cfg(not(stage0))] pub struct VaList<'a>(&'a mut VaListImpl); // The VaArgSafe trait needs to be used in public interfaces, however, the trait @@ -173,7 +171,6 @@ impl sealed_trait::VaArgSafe for *mut T {} issue = "27745")] impl sealed_trait::VaArgSafe for *const T {} -#[cfg(not(stage0))] impl<'a> VaList<'a> { /// Advance to the next arg. #[unstable(feature = "c_variadic", @@ -208,7 +205,6 @@ impl<'a> VaList<'a> { } } -#[cfg(not(stage0))] extern "rust-intrinsic" { /// Destroy the arglist `ap` after initialization with `va_start` or /// `va_copy`. diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs index eebb98b5e6d..b94d5b4adcf 100644 --- a/src/libcore/intrinsics.rs +++ b/src/libcore/intrinsics.rs @@ -718,7 +718,6 @@ extern "rust-intrinsic" { pub fn uninit() -> T; /// Moves a value out of scope without running drop glue. - #[cfg(not(stage0))] pub fn forget(_: T); /// Reinterprets the bits of a value of one type as another type. @@ -1476,14 +1475,12 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `rotate_left` method. For example, /// [`std::u32::rotate_left`](../../std/primitive.u32.html#method.rotate_left) - #[cfg(not(stage0))] pub fn rotate_left(x: T, y: T) -> T; /// Performs rotate right. /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `rotate_right` method. For example, /// [`std::u32::rotate_right`](../../std/primitive.u32.html#method.rotate_right) - #[cfg(not(stage0))] pub fn rotate_right(x: T, y: T) -> T; /// Returns (a + b) mod 2N, where N is the width of T in bits. diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index 06754f17a6f..afd9fcb1fba 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -149,7 +149,6 @@ pub fn forget(t: T) { /// /// [`forget`]: fn.forget.html #[inline] -#[cfg(not(stage0))] #[unstable(feature = "forget_unsized", issue = "0")] pub fn forget_unsized(t: T) { unsafe { intrinsics::forget(t) } diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 13b422162f3..4acf3a15ebf 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -2330,12 +2330,7 @@ assert_eq!(n.rotate_left(", $rot, "), m); #[rustc_const_unstable(feature = "const_int_rotate")] #[inline] pub const fn rotate_left(self, n: u32) -> Self { - #[cfg(not(stage0))] { - unsafe { intrinsics::rotate_left(self, n as $SelfT) } - } - #[cfg(stage0)] { - (self << (n % $BITS)) | (self >> (($BITS - (n % $BITS)) % $BITS)) - } + unsafe { intrinsics::rotate_left(self, n as $SelfT) } } } @@ -2360,12 +2355,7 @@ assert_eq!(n.rotate_right(", $rot, "), m); #[rustc_const_unstable(feature = "const_int_rotate")] #[inline] pub const fn rotate_right(self, n: u32) -> Self { - #[cfg(not(stage0))] { - unsafe { intrinsics::rotate_right(self, n as $SelfT) } - } - #[cfg(stage0)] { - (self >> (n % $BITS)) | (self << (($BITS - (n % $BITS)) % $BITS)) - } + unsafe { intrinsics::rotate_right(self, n as $SelfT) } } } diff --git a/src/libcore/ops/unsize.rs b/src/libcore/ops/unsize.rs index 4d9a40a1b90..e86a392a2c8 100644 --- a/src/libcore/ops/unsize.rs +++ b/src/libcore/ops/unsize.rs @@ -93,7 +93,7 @@ impl, U: ?Sized> CoerceUnsized<*const U> for *const T {} /// {} /// ``` #[unstable(feature = "dispatch_from_dyn", issue = "0")] -#[cfg_attr(not(stage0), lang = "dispatch_from_dyn")] +#[lang = "dispatch_from_dyn"] pub trait DispatchFromDyn { // Empty. } diff --git a/src/libcore/sync/atomic.rs b/src/libcore/sync/atomic.rs index 27eeb045bb1..060983a702f 100644 --- a/src/libcore/sync/atomic.rs +++ b/src/libcore/sync/atomic.rs @@ -1940,7 +1940,7 @@ atomic_int! { 8, u64 AtomicU64 ATOMIC_U64_INIT } -#[cfg(all(not(stage0), target_has_atomic = "128"))] +#[cfg(target_has_atomic = "128")] atomic_int! { unstable(feature = "integer_atomics", issue = "32976"), unstable(feature = "integer_atomics", issue = "32976"), @@ -1954,7 +1954,7 @@ atomic_int! { 16, i128 AtomicI128 ATOMIC_I128_INIT } -#[cfg(all(not(stage0), target_has_atomic = "128"))] +#[cfg(target_has_atomic = "128")] atomic_int! { unstable(feature = "integer_atomics", issue = "32976"), unstable(feature = "integer_atomics", issue = "32976"), diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index a09d167f217..b7759a8c92b 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -463,7 +463,7 @@ impl BuiltinLintDiagnostics { Ok(ref s) => { // FIXME(Manishearth) ideally the emitting code // can tell us whether or not this is global - let opt_colon = if s.trim_left().starts_with("::") { + let opt_colon = if s.trim_start().starts_with("::") { "" } else { "::" diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs index ae9f6a5e140..7bd0f0f8fc4 100644 --- a/src/librustc_errors/emitter.rs +++ b/src/librustc_errors/emitter.rs @@ -1262,7 +1262,7 @@ impl EmitterWriter { // Do not underline the leading... let start = part.snippet.len() - .saturating_sub(part.snippet.trim_left().len()); + .saturating_sub(part.snippet.trim_start().len()); // ...or trailing spaces. Account for substitutions containing unicode // characters. let sub_len = part.snippet.trim().chars().fold(0, |acc, ch| { diff --git a/src/librustc_lint/nonstandard_style.rs b/src/librustc_lint/nonstandard_style.rs index 13be50ef01f..e071c34ff7f 100644 --- a/src/librustc_lint/nonstandard_style.rs +++ b/src/librustc_lint/nonstandard_style.rs @@ -167,7 +167,7 @@ impl NonSnakeCase { fn to_snake_case(mut str: &str) -> String { let mut words = vec![]; // Preserve leading underscores - str = str.trim_left_matches(|c: char| { + str = str.trim_start_matches(|c: char| { if c == '_' { words.push(String::new()); true @@ -199,7 +199,7 @@ impl NonSnakeCase { if ident.is_empty() { return true; } - let ident = ident.trim_left_matches('\''); + let ident = ident.trim_start_matches('\''); let ident = ident.trim_matches('_'); let mut allow_underscore = true; diff --git a/src/librustc_llvm/build.rs b/src/librustc_llvm/build.rs index 7d01ed556c8..ce482087bba 100644 --- a/src/librustc_llvm/build.rs +++ b/src/librustc_llvm/build.rs @@ -192,11 +192,11 @@ fn main() { // On MSVC llvm-config will print the full name to libraries, but // we're only interested in the name part let name = Path::new(lib).file_name().unwrap().to_str().unwrap(); - name.trim_right_matches(".lib") + name.trim_end_matches(".lib") } else if lib.ends_with(".lib") { // Some MSVC libraries just come up with `.lib` tacked on, so chop // that off - lib.trim_right_matches(".lib") + lib.trim_end_matches(".lib") } else { continue; }; diff --git a/src/librustc_mir/borrow_check/move_errors.rs b/src/librustc_mir/borrow_check/move_errors.rs index db60017185a..fb93c41ce4f 100644 --- a/src/librustc_mir/borrow_check/move_errors.rs +++ b/src/librustc_mir/borrow_check/move_errors.rs @@ -426,13 +426,13 @@ impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> { .span_to_snippet(pat_span) .unwrap(); if pat_snippet.starts_with('&') { - let pat_snippet = pat_snippet[1..].trim_left(); + let pat_snippet = pat_snippet[1..].trim_start(); let suggestion; let to_remove; if pat_snippet.starts_with("mut") && pat_snippet["mut".len()..].starts_with(Pattern_White_Space) { - suggestion = pat_snippet["mut".len()..].trim_left(); + suggestion = pat_snippet["mut".len()..].trim_start(); to_remove = "&mut"; } else { suggestion = pat_snippet; diff --git a/src/librustc_mir/interpret/intrinsics.rs b/src/librustc_mir/interpret/intrinsics.rs index bbee6e0b49a..cbe2e25b4fc 100644 --- a/src/librustc_mir/interpret/intrinsics.rs +++ b/src/librustc_mir/interpret/intrinsics.rs @@ -103,7 +103,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> if bits == 0 { return err!(Intrinsic(format!("{} called on 0", intrinsic_name))); } - numeric_intrinsic(intrinsic_name.trim_right_matches("_nonzero"), bits, kind)? + numeric_intrinsic(intrinsic_name.trim_end_matches("_nonzero"), bits, kind)? } else { numeric_intrinsic(intrinsic_name, bits, kind)? }; diff --git a/src/librustc_typeck/check/demand.rs b/src/librustc_typeck/check/demand.rs index f4f6b3d6616..db4b68611c5 100644 --- a/src/librustc_typeck/check/demand.rs +++ b/src/librustc_typeck/check/demand.rs @@ -123,7 +123,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let sole_field_ty = sole_field.ty(self.tcx, substs); if self.can_coerce(expr_ty, sole_field_ty) { let variant_path = self.tcx.item_path_str(variant.did); - Some(variant_path.trim_left_matches("std::prelude::v1::").to_string()) + Some(variant_path.trim_start_matches("std::prelude::v1::").to_string()) } else { None } @@ -519,7 +519,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let suffix_suggestion = format!( "{}{}{}{}", if needs_paren { "(" } else { "" }, - src.trim_right_matches(&checked_ty.to_string()), + src.trim_end_matches(&checked_ty.to_string()), expected_ty, if needs_paren { ")" } else { "" }, ); diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index e0e0be717b2..504567e96e7 100644 --- a/src/librustdoc/markdown.rs +++ b/src/librustdoc/markdown.rs @@ -35,7 +35,7 @@ fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) { for line in s.lines() { if line.starts_with("# ") || line.starts_with("%") { // trim the whitespace after the symbol - metadata.push(line[1..].trim_left()); + metadata.push(line[1..].trim_start()); count += line.len() + 1; } else { return (metadata, &s[count..]); diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 29062ba58c2..2e8bfd8f07f 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -294,23 +294,23 @@ impl<'a, 'tcx, 'rcx, 'cstore> DocFolder for LinkCollector<'a, 'tcx, 'rcx, 'cstor "trait@", "union@"].iter() .find(|p| link.starts_with(**p)) { kind = PathKind::Type; - link.trim_left_matches(prefix) + link.trim_start_matches(prefix) } else if let Some(prefix) = ["const@", "static@", "value@", "function@", "mod@", "fn@", "module@", "method@"] .iter().find(|p| link.starts_with(**p)) { kind = PathKind::Value; - link.trim_left_matches(prefix) + link.trim_start_matches(prefix) } else if link.ends_with("()") { kind = PathKind::Value; - link.trim_right_matches("()") + link.trim_end_matches("()") } else if link.starts_with("macro@") { kind = PathKind::Macro; - link.trim_left_matches("macro@") + link.trim_start_matches("macro@") } else if link.ends_with('!') { kind = PathKind::Macro; - link.trim_right_matches('!') + link.trim_end_matches('!') } else { &link[..] }.trim(); diff --git a/src/librustdoc/passes/unindent_comments.rs b/src/librustdoc/passes/unindent_comments.rs index 6d875c107c8..5c565bf8181 100644 --- a/src/librustdoc/passes/unindent_comments.rs +++ b/src/librustdoc/passes/unindent_comments.rs @@ -95,7 +95,7 @@ fn unindent(s: &str) -> String { }); if !lines.is_empty() { - let mut unindented = vec![ lines[0].trim_left().to_string() ]; + let mut unindented = vec![ lines[0].trim_start().to_string() ]; unindented.extend_from_slice(&lines[1..].iter().map(|&line| { if line.chars().all(|c| c.is_whitespace()) { line.to_string() diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 9439dc78d3c..b0884e1fbd1 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -3493,7 +3493,7 @@ mod tests { // Helper function for counting indents fn indents(source: &str) -> usize { - let trimmed = source.trim_left_matches(' '); + let trimmed = source.trim_start_matches(' '); source.len() - trimmed.len() } diff --git a/src/libstd/error.rs b/src/libstd/error.rs index a9b27115261..e5c5ab83cbc 100644 --- a/src/libstd/error.rs +++ b/src/libstd/error.rs @@ -533,6 +533,7 @@ impl Error for Box { Error::description(&**self) } + #[allow(deprecated)] fn cause(&self) -> Option<&dyn Error> { Error::cause(&**self) } diff --git a/src/libstd/ffi/mod.rs b/src/libstd/ffi/mod.rs index 99da73adc63..f46c4f2938b 100644 --- a/src/libstd/ffi/mod.rs +++ b/src/libstd/ffi/mod.rs @@ -174,7 +174,6 @@ pub use self::os_str::{OsString, OsStr}; #[stable(feature = "raw_os", since = "1.1.0")] pub use core::ffi::c_void; -#[cfg(not(stage0))] #[unstable(feature = "c_variadic", reason = "the `c_variadic` feature has not been properly tested on \ all supported platforms", diff --git a/src/libstd/io/error.rs b/src/libstd/io/error.rs index 32e29962760..d3844ebe19e 100644 --- a/src/libstd/io/error.rs +++ b/src/libstd/io/error.rs @@ -555,6 +555,7 @@ impl error::Error for Error { } } + #[allow(deprecated)] fn cause(&self) -> Option<&dyn error::Error> { match self.repr { Repr::Os(..) => None, diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 90c8eaf0f7c..7c43ba5afa7 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -317,10 +317,6 @@ #![default_lib_allocator] -#[cfg(stage0)] -#[global_allocator] -static ALLOC: alloc::System = alloc::System; - // Explicitly import the prelude. The compiler uses this same unstable attribute // to import the prelude implicitly when building crates that depend on std. #[prelude_import] diff --git a/src/libstd/panic.rs b/src/libstd/panic.rs index 099b4d6f577..3eacc7afc41 100644 --- a/src/libstd/panic.rs +++ b/src/libstd/panic.rs @@ -264,7 +264,7 @@ impl RefUnwindSafe for atomic::AtomicI32 {} #[cfg(target_has_atomic = "64")] #[unstable(feature = "integer_atomics", issue = "32976")] impl RefUnwindSafe for atomic::AtomicI64 {} -#[cfg(all(not(stage0), target_has_atomic = "128"))] +#[cfg(target_has_atomic = "128")] #[unstable(feature = "integer_atomics", issue = "32976")] impl RefUnwindSafe for atomic::AtomicI128 {} @@ -283,7 +283,7 @@ impl RefUnwindSafe for atomic::AtomicU32 {} #[cfg(target_has_atomic = "64")] #[unstable(feature = "integer_atomics", issue = "32976")] impl RefUnwindSafe for atomic::AtomicU64 {} -#[cfg(all(not(stage0), target_has_atomic = "128"))] +#[cfg(target_has_atomic = "128")] #[unstable(feature = "integer_atomics", issue = "32976")] impl RefUnwindSafe for atomic::AtomicU128 {} diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index 2be30e68d24..84ef62e5fe9 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -76,7 +76,7 @@ pub fn error_string(mut errnum: i32) -> String { match String::from_utf16(&buf[..res]) { Ok(mut msg) => { // Trim trailing CRLF inserted by FormatMessageW - let len = msg.trim_right().len(); + let len = msg.trim_end().len(); msg.truncate(len); msg }, diff --git a/src/libsyntax/diagnostics/plugin.rs b/src/libsyntax/diagnostics/plugin.rs index 1229db9b0e0..3b88767f0e8 100644 --- a/src/libsyntax/diagnostics/plugin.rs +++ b/src/libsyntax/diagnostics/plugin.rs @@ -141,6 +141,7 @@ pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt, ]) } +#[allow(deprecated)] pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt, span: Span, token_tree: &[TokenTree]) diff --git a/src/libsyntax/source_map.rs b/src/libsyntax/source_map.rs index 45008129e83..9a343123f61 100644 --- a/src/libsyntax/source_map.rs +++ b/src/libsyntax/source_map.rs @@ -579,7 +579,7 @@ impl SourceMap { match self.span_to_prev_source(sp) { Err(_) => None, Ok(source) => source.split('\n').last().map(|last_line| { - last_line.len() - last_line.trim_left().len() + last_line.len() - last_line.trim_start().len() }) } } @@ -593,7 +593,7 @@ impl SourceMap { /// if no character could be found or if an error occurred while retrieving the code snippet. pub fn span_extend_to_prev_char(&self, sp: Span, c: char) -> Span { if let Ok(prev_source) = self.span_to_prev_source(sp) { - let prev_source = prev_source.rsplit(c).nth(0).unwrap_or("").trim_left(); + let prev_source = prev_source.rsplit(c).nth(0).unwrap_or("").trim_start(); if !prev_source.is_empty() && !prev_source.contains('\n') { return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32)); } @@ -613,7 +613,7 @@ impl SourceMap { for ws in &[" ", "\t", "\n"] { let pat = pat.to_owned() + ws; if let Ok(prev_source) = self.span_to_prev_source(sp) { - let prev_source = prev_source.rsplit(&pat).nth(0).unwrap_or("").trim_left(); + let prev_source = prev_source.rsplit(&pat).nth(0).unwrap_or("").trim_start(); if !prev_source.is_empty() && (!prev_source.contains('\n') || accept_newlines) { return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32)); } @@ -627,7 +627,7 @@ impl SourceMap { pub fn span_until_char(&self, sp: Span, c: char) -> Span { match self.span_to_snippet(sp) { Ok(snippet) => { - let snippet = snippet.split(c).nth(0).unwrap_or("").trim_right(); + let snippet = snippet.split(c).nth(0).unwrap_or("").trim_end(); if !snippet.is_empty() && !snippet.contains('\n') { sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32)) } else { diff --git a/src/libsyntax_pos/symbol.rs b/src/libsyntax_pos/symbol.rs index 05c53878e70..f1adb9d64da 100644 --- a/src/libsyntax_pos/symbol.rs +++ b/src/libsyntax_pos/symbol.rs @@ -57,7 +57,7 @@ impl Ident { } pub fn without_first_quote(self) -> Ident { - Ident::new(Symbol::intern(self.as_str().trim_left_matches('\'')), self.span) + Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span) } /// "Normalize" ident for use in comparisons using "item hygiene". diff --git a/src/stage0.txt b/src/stage0.txt index 83694137775..843ecae1ce3 100644 --- a/src/stage0.txt +++ b/src/stage0.txt @@ -12,7 +12,7 @@ # source tarball for a stable release you'll likely see `1.x.0` for rustc and # `0.x.0` for Cargo where they were released on `date`. -date: 2018-11-21 +date: 2018-12-09 rustc: beta cargo: beta diff --git a/src/tools/cargo b/src/tools/cargo index 28fb20034a5..2cf1f5dda2f 160000 --- a/src/tools/cargo +++ b/src/tools/cargo @@ -1 +1 @@ -Subproject commit 28fb20034a5bb42ea589664de2617dd1840506d3 +Subproject commit 2cf1f5dda2f7ed84e94c4d32f643e0f1f15352f0 diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs index 65f6bff7eaf..9aefd15765d 100644 --- a/src/tools/compiletest/src/main.rs +++ b/src/tools/compiletest/src/main.rs @@ -511,7 +511,11 @@ pub fn test_opts(config: &Config) -> test::TestOpts { test::TestOpts { filter: config.filter.clone(), filter_exact: config.filter_exact, - run_ignored: config.run_ignored, + run_ignored: if config.run_ignored { + test::RunIgnored::Yes + } else { + test::RunIgnored::No + }, format: if config.quiet { test::OutputFormat::Terse } else { -- cgit 1.4.1-3-g733a5