jiebi/CodeConvo huggingface dataset:
} }) }; <del> let mut diff = Command::new("diff"); // diff recursively, showing context, and excluding .css files diff.args(&["-u", "-r", "-x", "*.css"]).args(&[&compare_dir, out_dir]); let output = if let Some(pager) = pager { let diff_pid = diff.stdout(Stdio::piped()).spawn().expect("failed to run `diff`"); </del> <ins> let diff_filename = format!("build/tmp/rustdoc-compare-{}.diff", std::process::id()); { let mut diff_output = File::create(&diff_filename).unwrap(); for entry in walkdir::WalkDir::new(out_dir) { let entry = entry.expect("failed to read file"); let extension = entry.path().extension().and_then(|p| p.to_str()); if entry.file_type().is_file() && (extension == Some("html".into()) || extension == Some("js".into())) { let expected_path = compare_dir.join(entry.path().strip_prefix(&out_dir).unwrap()); let expected = if let Ok(s) = std::fs::read(&expected_path) { s } else { continue }; let actual_path = entry.path(); let actual = std::fs::read(&actual_path).unwrap(); diff_output .write_all(&unified_diff::diff( &expected, &expected_path.to_string_lossy(), &actual, &actual_path.to_string_lossy(), 3, )) .unwrap(); } } } match self.config.color { ColorConfig::AlwaysColor => colored::control::set_override(true), ColorConfig::NeverColor => colored::control::set_override(false), _ => {} } if let Some(pager) = pager { </ins> let pager = pager.trim(); if self.config.verbose { eprintln!("using pager {}", pager);
let output = Command::new(pager) // disable paging; we want this to be non-interactive .env("PAGER", "") <del> .stdin(diff_pid.stdout.unwrap()) </del> <ins> .stdin(File::open(&diff_filename).unwrap()) </ins> // Capture output and print it explicitly so it will in turn be // captured by libtest. .output() .unwrap(); assert!(output.status.success()); <del> output </del> <ins> println!("{}", String::from_utf8_lossy(&output.stdout)); eprintln!("{}", String::from_utf8_lossy(&output.stderr)); </ins> } else { <del> eprintln!("warning: no pager configured, falling back to `diff --color`"); </del> <ins> use colored::Colorize; eprintln!("warning: no pager configured, falling back to unified diff"); </ins> eprintln!( "help: try configuring a git pager (e.g. `delta`) with `git config --global core.pager delta`" ); <del> let output = diff.arg("--color").output().unwrap(); assert!(output.status.success() || output.status.code() == Some(1)); output </del> <ins> let mut out = io::stdout(); let mut diff = BufReader::new(File::open(&diff_filename).unwrap()); let mut line = Vec::new(); loop { line.truncate(0); match diff.read_until(b'n', &mut line) { Ok(0) => break, Ok(_) => {} Err(e) => eprintln!("ERROR: {:?}", e), } match String::from_utf8(line.clone()) { Ok(line) => { if line.starts_with("+") { write!(&mut out, "{}", line.green()).unwrap(); } else if line.starts_with("-") { write!(&mut out, "{}", line.red()).unwrap(); } else if line.starts_with("@") { write!(&mut out, "{}", line.blue()).unwrap(); } else { out.write_all(line.as_bytes()).unwrap(); } } Err(_) => { write!(&mut out, "{}", String::from_utf8_lossy(&line).reversed()).unwrap(); } } } </ins> }; <del> println!("{}", String::from_utf8_lossy(&output.stdout)); eprintln!("{}", String::from_utf8_lossy(&output.stderr)); </del> } fn run_rustdoc_json_test(&self) {
let id = id.expect_local(); let tables = tcx.typeck(id); let hir_id = tcx.hir().local_def_id_to_hir_id(id); <del> let (span, place) = &tables.closure_kind_origins()[hir_id]; let reason = if let PlaceBase::Upvar(upvar_id) = place.base { let upvar = ty::place_to_string_for_capture(tcx, place); match tables.upvar_capture(upvar_id) { ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind: ty::BorrowKind::MutBorrow | ty::BorrowKind::UniqueImmBorrow, .. }) => { format!("mutable borrow of `{}`", upvar) } ty::UpvarCapture::ByValue(_) => { format!("possible mutation of `{}`", upvar) </del> <ins> if let Some((span, place)) = tables.closure_kind_origins().get(hir_id) { let reason = if let PlaceBase::Upvar(upvar_id) = place.base { let upvar = ty::place_to_string_for_capture(tcx, place); match tables.upvar_capture(upvar_id) { ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind: ty::BorrowKind::MutBorrow | ty::BorrowKind::UniqueImmBorrow, .. }) => { format!("mutable borrow of `{}`", upvar) } ty::UpvarCapture::ByValue(_) => { format!("possible mutation of `{}`", upvar) } val => bug!("upvar `{}` borrowed, but not mutably: {:?}", upvar, val), </ins> } <del> val => bug!("upvar `{}` borrowed, but not mutably: {:?}", upvar, val), } } else { bug!("not an upvar") }; err.span_label( *span, format!( "calling `{}` requires mutable binding due to {}", self.describe_place(the_place_err).unwrap(), reason ), ); </del> <ins> } else { bug!("not an upvar") }; err.span_label( *span, format!( "calling `{}` requires mutable binding due to {}", self.describe_place(the_place_err).unwrap(), reason ), ); } </ins> } // Attempt to search similar mutable associated items for suggestion.
<ins> use std::error::Error; struct A { } impl A { pub fn new() -> A { A { } } pub fn f<'a>( &'a self, team_name: &'a str, c: &'a mut dyn FnMut(String, String, u64, u64) ) -> Result<(), Box<dyn Error>> { Ok(()) } } fn main() { let A = A::new(); let participant_name = "A"; let c = |a, b, c, d| {}; A.f(participant_name, &mut c); //~ ERROR cannot borrow } </ins>
<ins> error[E0596]: cannot borrow `c` as mutable, as it is not declared as mutable --> $DIR/issue-82438-mut-without-upvar.rs:27:27 | LL |     let c = |a, b, c, d| {}; |         - help: consider changing this to be mutable: `mut c` LL | LL |     A.f(participant_name, &mut c); |                           ^^^^^^ cannot borrow as mutable error: aborting due to previous error For more information about this error, try `rustc --explain E0596`. </ins>
span: Span, ) -> &'tcx Const<'tcx> { bad_placeholder_type(self.tcx(), vec![span]).emit(); <ins> // Typeck doesn't expect erased regions to be returned from `type_of`. let ty = self.tcx.fold_regions(ty, &mut false, |r, _| match r { ty::ReErased => self.tcx.lifetimes.re_static, _ => r, }); </ins> self.tcx().const_error(ty) }
match get_infer_ret_ty(&sig.decl.output) { Some(ty) => { let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id]; <ins> // Typeck doesn't expect erased regions to be returned from `type_of`. let fn_sig = tcx.fold_regions(fn_sig, &mut false, |r, _| match r { ty::ReErased => tcx.lifetimes.re_static, _ => r, }); </ins> let mut visitor = PlaceholderHirTyCollector::default(); visitor.visit_ty(ty); let mut diag = bad_placeholder_type(tcx, visitor.0);
const D: _ = 42; //~^ ERROR the type placeholder `_` is not allowed within types on item signatures } <ins> fn map<T>(_: fn() -> Option<&'static T>) -> Option<T> { None } fn value() -> Option<&'static _> { //~^ ERROR the type placeholder `_` is not allowed within types on item signatures Option::<&'static u8>::None } const _: Option<_> = map(value); //~^ ERROR the type placeholder `_` is not allowed within types on item signatures </ins>
|                         -^ |                         || |                         |not allowed in type signatures <del> |                         help: replace with the correct return type: `&&usize` </del> <ins> |                         help: replace with the correct return type: `&'static &'static usize` </ins> error[E0121]: the type placeholder `_` is not allowed within types on item signatures --> $DIR/typeck_type_placeholder_item.rs:52:52
|                     ^ not allowed in type signatures error[E0121]: the type placeholder `_` is not allowed within types on item signatures <ins> --> $DIR/typeck_type_placeholder_item.rs:216:31 | LL | fn value() -> Option<&'static _> { |               ----------------^- |               |               | |               |               not allowed in type signatures |               help: replace with the correct return type: `Option<&'static u8>` error[E0121]: the type placeholder `_` is not allowed within types on item signatures --> $DIR/typeck_type_placeholder_item.rs:221:10 | LL | const _: Option<_> = map(value); |          ^^^^^^^^^ |          | |          not allowed in type signatures |          help: replace `_` with the correct type: `Option<u8>` error[E0121]: the type placeholder `_` is not allowed within types on item signatures </ins> --> $DIR/typeck_type_placeholder_item.rs:140:31 | LL |     fn method_test1(&self, x: _);
/// destination value, then forgets the original. It's equivalent to C's /// `memcpy` under the hood, just like `transmute_copy`. /// <ins> /// Because `transmute` is a by-value operation, alignment of the *transmuted values /// themselves* is not a concern. As with any other function, the compiler already ensures /// both `T` and `U` are properly aligned. However, when transmuting values that *point /// elsewhere* (such as pointers, references, boxes…), the caller has to ensure proper /// alignment of the pointed-to values. /// </ins> /// `transmute` is **incredibly** unsafe. There are a vast number of ways to /// cause [undefined behavior][ub] with this function. `transmute` should be /// the absolute last resort.
/// assert_eq!(b"Rust", &[82, 117, 115, 116]); /// ``` /// <del> /// Turning a `Vec<&T>` into a `Vec<Option<&T>>`: </del> <ins> /// Turning a `Vec<&T>` into a `Vec<Option<&T>>`. /// /// To transmute the inner type of the contents of a container, you must make sure to not /// violate any of the container's invariants. For `Vec`, this means that both the size /// *and alignment* of the inner types have to match. Other containers might rely on the /// size of the type, alignment, or even the `TypeId`, in which case transmuting wouldn't /// be possible at all without violating the container invariants. </ins> /// /// ``` /// let store = [0, 1, 2, 3];
/// /// let v_clone = v_orig.clone(); /// <del> /// // The no-copy, unsafe way, still using transmute, but not relying on the data layout. /// // Like the first approach, this reuses the `Vec` internals. /// // Therefore, the new inner type must have the /// // exact same size, *and the same alignment*, as the old type. /// // The same caveats exist for this method as transmute, for /// // the original inner type (`&i32`) to the converted inner type /// // (`Option<&i32>`), so read the nomicon pages linked above and also /// // consult the [`from_raw_parts`] documentation. </del> <ins> /// // This is the proper no-copy, unsafe way of "transmuting" a `Vec`, without relying on the /// // data layout. Instead of literally calling `transmute`, we perform a pointer cast, but /// // in terms of converting the original inner type (`&i32`) to the new one (`Option<&i32>`), /// // this has all the same caveats. Besides the information provided above, also consult the /// // [`from_raw_parts`] documentation. </ins> /// let v_from_raw = unsafe { // FIXME Update this when vec_into_raw_parts is stabilized ///     // Ensure the original vector is not dropped.
<ins> // run-rustfix #![allow(dead_code, unused_variables)] fn foo1(bar: &str) {} //~^ ERROR the size for values of type `str` cannot be known at compilation time //~| HELP the trait `Sized` is not implemented for `str` //~| HELP unsized fn params are gated as an unstable feature //~| HELP function arguments must have a statically known size, borrowed types always have a known size fn foo2(_bar: &str) {} //~^ ERROR the size for values of type `str` cannot be known at compilation time //~| HELP the trait `Sized` is not implemented for `str` //~| HELP unsized fn params are gated as an unstable feature //~| HELP function arguments must have a statically known size, borrowed types always have a known size fn foo3(_: &str) {} //~^ ERROR the size for values of type `str` cannot be known at compilation time //~| HELP the trait `Sized` is not implemented for `str` //~| HELP unsized fn params are gated as an unstable feature //~| HELP function arguments must have a statically known size, borrowed types always have a known size fn main() {} </ins>
<ins> // run-rustfix #![allow(dead_code, unused_variables)] fn foo1(bar: str) {} //~^ ERROR the size for values of type `str` cannot be known at compilation time //~| HELP the trait `Sized` is not implemented for `str` //~| HELP unsized fn params are gated as an unstable feature //~| HELP function arguments must have a statically known size, borrowed types always have a known size fn foo2(_bar: str) {} //~^ ERROR the size for values of type `str` cannot be known at compilation time //~| HELP the trait `Sized` is not implemented for `str` //~| HELP unsized fn params are gated as an unstable feature //~| HELP function arguments must have a statically known size, borrowed types always have a known size fn foo3(_: str) {} //~^ ERROR the size for values of type `str` cannot be known at compilation time //~| HELP the trait `Sized` is not implemented for `str` //~| HELP unsized fn params are gated as an unstable feature //~| HELP function arguments must have a statically known size, borrowed types always have a known size fn main() {} </ins>
<ins> error[E0277]: the size for values of type `str` cannot be known at compilation time --> $DIR/unsized-function-parameter.rs:5:9 | LL | fn foo1(bar: str) {} |         ^^^ doesn't have a size known at compile-time | = help: the trait `Sized` is not implemented for `str` = help: unsized fn params are gated as an unstable feature help: function arguments must have a statically known size, borrowed types always have a known size | LL | fn foo1(bar: &str) {} |              ^ error[E0277]: the size for values of type `str` cannot be known at compilation time --> $DIR/unsized-function-parameter.rs:11:9 | LL | fn foo2(_bar: str) {} |         ^^^^ doesn't have a size known at compile-time | = help: the trait `Sized` is not implemented for `str` = help: unsized fn params are gated as an unstable feature help: function arguments must have a statically known size, borrowed types always have a known size | LL | fn foo2(_bar: &str) {} |               ^ error[E0277]: the size for values of type `str` cannot be known at compilation time --> $DIR/unsized-function-parameter.rs:17:9 | LL | fn foo3(_: str) {} |         ^ doesn't have a size known at compile-time | = help: the trait `Sized` is not implemented for `str` = help: unsized fn params are gated as an unstable feature help: function arguments must have a statically known size, borrowed types always have a known size | LL | fn foo3(_: &str) {} |            ^ error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0277`. </ins>
let dl = self.data_layout(); let pack = repr.pack; if pack.is_some() && repr.align.is_some() { <del> bug!("struct cannot be packed and aligned"); </del> <ins> self.tcx.sess.delay_span_bug(DUMMY_SP, "struct cannot be packed and aligned"); return Err(LayoutError::Unknown(ty)); </ins> } let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align };
if def.is_union() { if def.repr.pack.is_some() && def.repr.align.is_some() { <del> bug!("union cannot be packed and aligned"); </del> <ins> self.tcx.sess.delay_span_bug( tcx.def_span(def.did), "union cannot be packed and aligned", ); return Err(LayoutError::Unknown(ty)); </ins> } let mut align =
i: i32, } <ins> #[repr(packed, align(0x100))] pub struct S(u16); //~ ERROR type has conflicting packed and align representation hints #[repr(packed, align(0x100))] pub union U { //~ ERROR type has conflicting packed and align representation hints u: u16 } static B: U = U { u: 0 }; static A: S = S(0); </ins> fn main() {}
LL | | } | |_^ <del> error: aborting due to 10 previous errors </del> <ins> error[E0587]: type has conflicting packed and align representation hints --> $DIR/conflicting-repr-hints.rs:70:1 | LL | pub struct S(u16); | ^^^^^^^^^^^^^^^^^^ error[E0587]: type has conflicting packed and align representation hints --> $DIR/conflicting-repr-hints.rs:73:1 | LL | / pub union U { LL | |     u: u16 LL | | } | |_^ error: aborting due to 12 previous errors </ins> Some errors have detailed explanations: E0566, E0587, E0634. For more information about an error, try `rustc --explain E0566`.
#[unstable(feature = "str_internals", issue = "none")] pub use validations::next_code_point; <ins> #[unstable(feature = "str_internals", issue = "none")] pub use validations::utf8_char_width; </ins> use iter::MatchIndicesInternal; use iter::SplitInternal; use iter::{MatchesInternal, SplitNInternal};
use crate::sys::c; use crate::sys::cvt; use crate::sys::handle::Handle; <ins> use core::str::utf8_char_width; </ins> // Don't cache handles but get them fresh for every read/write. This allows us to track changes to // the value over time (such as if a process calls `SetStdHandle` while it's running). See #40490. pub struct Stdin { surrogate: u16, } <del> pub struct Stdout; pub struct Stderr; </del> <ins> pub struct Stdout { incomplete_utf8: IncompleteUtf8, } pub struct Stderr { incomplete_utf8: IncompleteUtf8, } struct IncompleteUtf8 { bytes: [u8; 4], len: u8, } </ins> // Apparently Windows doesn't handle large reads on stdin or writes to stdout/stderr well (see // #13304 for details).
unsafe { c::GetConsoleMode(handle, &mut mode) != 0 } } <del> fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result<usize> { </del> <ins> fn write( handle_id: c::DWORD, data: &[u8], incomplete_utf8: &mut IncompleteUtf8, ) -> io::Result<usize> { if data.is_empty() { return Ok(0); } </ins> let handle = get_handle(handle_id)?; if !is_console(handle) { let handle = Handle::new(handle);
return ret; } <del> // As the console is meant for presenting text, we assume bytes of `data` come from a string // and are encoded as UTF-8, which needs to be encoded as UTF-16. </del> <ins> if incomplete_utf8.len > 0 { assert!( incomplete_utf8.len < 4, "Unexpected number of bytes for incomplete UTF-8 codepoint." ); if data[0] >> 6 != 0b10 { incomplete_utf8.len = 0; // not a continuation byte - reject return Err(io::Error::new_const( io::ErrorKind::InvalidData, &"Windows stdio in console mode does not support writing non-UTF-8 byte sequences", )); } incomplete_utf8.bytes[incomplete_utf8.len as usize] = data[0]; incomplete_utf8.len += 1; let char_width = utf8_char_width(incomplete_utf8.bytes[0]); if (incomplete_utf8.len as usize) < char_width { // more bytes needed return Ok(1); } let s = str::from_utf8(&incomplete_utf8.bytes[0..incomplete_utf8.len as usize]); incomplete_utf8.len = 0; match s { Ok(s) => { assert_eq!(char_width, s.len()); let written = write_valid_utf8_to_console(handle, s)?; assert_eq!(written, s.len()); // guaranteed by write_valid_utf8_to_console() for single codepoint writes return Ok(1); } Err(_) => { return Err(io::Error::new_const( io::ErrorKind::InvalidData, &"Windows stdio in console mode does not support writing non-UTF-8 byte sequences", )); } } } // As the console is meant for presenting text, we assume bytes of `data` are encoded as UTF-8, // which needs to be encoded as UTF-16. </ins> // // If the data is not valid UTF-8 we write out as many bytes as are valid. <del> // Only when there are no valid bytes (which will happen on the next call), return an error. </del> <ins> // If the first byte is invalid it is either first byte of a multi-byte sequence but the // provided byte slice is too short or it is the first byte of an invalide multi-byte sequence. </ins> let len = cmp::min(data.len(), MAX_BUFFER_SIZE / 2); let utf8 = match str::from_utf8(&data[..len]) { Ok(s) => s, Err(ref e) if e.valid_up_to() == 0 => { <del> return Err(io::Error::new_const( io::ErrorKind::InvalidData, &"Windows stdio in console mode does not support writing non-UTF-8 byte sequences", )); </del> <ins> let first_byte_char_width = utf8_char_width(data[0]); if first_byte_char_width > 1 && data.len() < first_byte_char_width { incomplete_utf8.bytes[0] = data[0]; incomplete_utf8.len = 1; return Ok(1); } else { return Err(io::Error::new_const( io::ErrorKind::InvalidData, &"Windows stdio in console mode does not support writing non-UTF-8 byte sequences", )); } </ins> } Err(e) => str::from_utf8(&data[..e.valid_up_to()]).unwrap(), }; <ins> write_valid_utf8_to_console(handle, utf8) } fn write_valid_utf8_to_console(handle: c::HANDLE, utf8: &str) -> io::Result<usize> { </ins> let mut utf16 = [0u16; MAX_BUFFER_SIZE / 2]; let mut len_utf16 = 0; for (chr, dest) in utf8.encode_utf16().zip(utf16.iter_mut()) {
Ok(written) } <ins> impl IncompleteUtf8 { pub const fn new() -> IncompleteUtf8 { IncompleteUtf8 { bytes: [0; 4], len: 0 } } } </ins> impl Stdout { pub const fn new() -> Stdout { <del> Stdout </del> <ins> Stdout { incomplete_utf8: IncompleteUtf8::new() } </ins> } } impl io::Write for Stdout { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { <del> write(c::STD_OUTPUT_HANDLE, buf) </del> <ins> write(c::STD_OUTPUT_HANDLE, buf, &mut self.incomplete_utf8) </ins> } fn flush(&mut self) -> io::Result<()> {
impl Stderr { pub const fn new() -> Stderr { <del> Stderr </del> <ins> Stderr { incomplete_utf8: IncompleteUtf8::new() } </ins> } } impl io::Write for Stderr { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { <del> write(c::STD_ERROR_HANDLE, buf) </del> <ins> write(c::STD_ERROR_HANDLE, buf, &mut self.incomplete_utf8) </ins> } fn flush(&mut self) -> io::Result<()> {
let mut inserted = FxHashSet::default(); items.extend(doc.foreigns.iter().map(|(item, renamed)| { let item = clean_maybe_renamed_foreign_item(cx, item, *renamed); <del> if let Some(name) = item.name { </del> <ins> if let Some(name) = item.name && !item.attrs.lists(sym::doc).has_word(sym::hidden) { </ins> inserted.insert((item.type_(), name)); } item })); <del> items.extend(doc.mods.iter().map(|x| { inserted.insert((ItemType::Module, x.name)); clean_doc_module(x, cx) </del> <ins> items.extend(doc.mods.iter().filter_map(|x| { if !inserted.insert((ItemType::Module, x.name)) { return None; } let item = clean_doc_module(x, cx); if item.attrs.lists(sym::doc).has_word(sym::hidden) { // Hidden modules are stripped at a later stage. // If a hidden module has the same name as a visible one, we want // to keep both of them around. inserted.remove(&(ItemType::Module, x.name)); } Some(item) </ins> })); // Split up imports from all other items.
self.inside_public_path &= self.cx.tcx.visibility(def_id).is_public(); for &i in m.item_ids { let item = self.cx.tcx.hir().item(i); <ins> if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) { continue; } </ins> self.visit_item(item, None, &mut om); } <ins> for &i in m.item_ids { let item = self.cx.tcx.hir().item(i); // To match the way import precedence works, visit glob imports last. // Later passes in rustdoc will de-duplicate by name and kind, so if glob- // imported items appear last, then they'll be the ones that get discarded. if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) { self.visit_item(item, None, &mut om); } } </ins> self.inside_public_path = orig_inside_public_path; om }
<ins> // https://github.com/rust-lang/rust/pull/83872#issuecomment-820101008 #![crate_name="foo"] mod sub4 { /// 0 pub const X: usize = 0; pub mod inner { pub use super::*; /// 1 pub const X: usize = 1; } } #[doc(inline)] pub use sub4::inner::*; // @has 'foo/index.html' // @has - '//div[@class="item-right docblock-short"]' '1' // @!has - '//div[@class="item-right docblock-short"]' '0' fn main() { assert_eq!(X, 1); } </ins>