jiebi/CodeConvo huggingface dataset:
Change:
I think this is an omission from TRPL, in the description of either Lifetimes or impl - requesting because I think any new user would benefit from it. Having got a limited understanding of , lifetime and I wanted to write thinking that the on defines it for... whatever is using it later. I got the answer ( / made mcast/markdown-chapterise and concluded that in I am defining for the impl block, then using that definition at (which must be here, to compile) to describe the . The sort of explanatory example that would make sense to me would be like in which I avoid repeating a lifetime label so it's easier to describe which define and which consume which could be elided & when, and what that means what the described lifetime constraints will mean when we set e.g. and so on, to make it compile relationships to lifetimes in enclosing blocks, if there could be any

Discussion:
i32` as ‘a mutable reference to an i32’ and `&'a mut i32` as ‘a mutable reference to an `i32` with the lifetime `'a`’. <ins> # In `struct`s </ins> You’ll also need explicit lifetimes when working with [`struct`][structs]s: ```rust

uses it. So why do we need a lifetime here? We need to ensure that any reference to a `Foo` cannot outlive the reference to an `i32` it contains. <ins> ## `impl` blocks Let’s implement a method on `Foo`: ```rust struct Foo<'a> { x: &'a i32, } impl<'a> Foo<'a> { fn x(&self) -> &'a i32 { self.x } } fn main() { let y = &5; // this is the same as `let _y = 5; let y = &_y;` let f = Foo { x: y }; println!("x is: {}", f.x()); } ``` As you can see, we need to declare a lifetime for `Foo` in the `impl` line. We repeat `'a` twice, just like on functions: `impl<'a>` defines a lifetime `'a`, and `Foo<'a>` uses it. ## Multiple lifetimes </ins> If you have multiple references, you can use the same lifetime multiple times: ```rust
Change:
If C calls into a Rust function that panics it's Undefined Behaviour if it's not caught before the FFI boundary. You need to spawn a thread (stable) or catch_panic (unstable) if you can panic. Similarly if e.g. C++ unwinds into Rust this is also Undefined Behaviour, though this is perhaps out of scope as a "Rust" problem.
It looks like panics are turned into aborts on the boundaries of functions with non-Rust ABI. But it should probably be documented anyway.
yeah, it's in the reference, but not in the book

Discussion:
discussed above in "[Foreign Calling Conventions](ffi.html#foreign-calling-conventions)". The `no_mangle` attribute turns off Rust's name mangling, so that it is easier to link to. <ins> # FFI and panics It’s important to be mindful of `panic!`s when working with FFI. This code, when called from C, will `abort`: ```rust #[no_mangle] pub extern fn oh_no() -> ! { panic!("Oops!"); } # fn main() {} ``` If you’re writing code that may panic, you should run it in another thread, so that the panic doesn’t bubble up to C: ```rust use std::thread; #[no_mangle] pub extern fn oh_no() -> i32 { let h = thread::spawn(|| { panic!("Oops!"); }); match h.join() { Ok(_) => 1, Err(_) => 0, } } # fn main() {} ``` </ins>
Change:
This test program should exit quietly, but with , it instead fails the assertion: I also tested a really old 32-bit compiler, and it also failed: This test case is reduced from .
Probably a dup of (and )
Perhaps it's a dup. The other two issues are broken with and without optimizations, though. This issue only fails with optimizations.
Also: the expression in this issue doesn't actually require any overlap of the match patterns. (I'll update the test case.)
The bug also happens without a expression:
Good point. Also, this only happens with opt-level=2 (not 0 or 3).
cc Further refinement of the test case: Changing from to a large enough value avoids the bug. Apparently, the value needs to be large enough that, when rounded to the next highest power-of-two-minus-one, it is at least as large as . I think this is an LLVM bug. It involves the metadata. It's as if the compiler is reusing the range information from the check to elide the check (which is missing from the x64 assembly). Relevant unoptimized LLVM IR: isn't used in the test program. When I change its value, the only difference I notice in the unoptimized LLVM IR is in the range metadata (i.e. ).
Thanks Ryan! Indeed LLVM replaces the load with another disregarding the range information.
Patch is at
Patch landed upstream.
Using yesterday's nightly, fails on at this single test. The problem seems to be local llvm 3.6 is still allowed by the build system.

Discussion:
<ins> // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(dead_code)] enum FooMode { Check = 0x1001, } enum BarMode { Check = 0x2001, } enum Mode { Foo(FooMode), Bar(BarMode), } #[inline(never)] fn broken(mode: &Mode) -> u32 { for _ in 0..1 { if let Mode::Foo(FooMode::Check) = *mode { return 17 } if let Mode::Bar(BarMode::Check) = *mode { return 19 } } return 42; } fn main() { let mode = Mode::Bar(BarMode::Check); assert_eq!(broken(&mode), 19); } </ins>
Change:
If you go to a place in the libstd docs that references the rand crate, such as , all the links (, , ) are broken. Looks like they need an extra "/rand/" in the URL. The same problem occurs in the nightly docs (not sure what the correct URL is for those, though). Since these links to trait impls are auto-generated by rustdoc, I'm assuming this is a bug in rustdoc, not just a typo in the documentation. Or it has something to do with the rand code existing in libstd but also librand.
I believe this is the cause. any ideas?
Ah yes this is just a private trait in the distribution, so it just needs to be marked .

Discussion:
mod rand_impls; /// A type that can be randomly generated using an `Rng`. <ins> #[doc(hidden)] </ins> pub trait Rand : Sized { /// Generates a random instance of this type using the specified source of /// randomness.
Change:
I just started reading about the guessing game in the rust book and thought I should share my experiences. When being introduced to dependencies in cargo the version specification given is: Followed by this text: This was very confusing for me coming from using semver with npm, I expected to match exactly and it took me a while to understand why that was not the case. Apparently npm's default behaviour is to match an exact version while cargo's is to use a careted version. It is documented on that cargo defaults to use careted versions: Which differs from npm, from : I would like to offer two suggestions: Explain in the guessing game how we told Cargo we wanted a version, currently this is just a statement () without explanation. Make it more clear how cargo and npm differ with regards to semver, especially considering npm is linked to directly in the documentation.

Discussion:
The `[dependencies]` section of `Cargo.toml` is like the `[package]` section: everything that follows it is part of it, until the next section starts. Cargo uses the dependencies section to know what dependencies on external <del> crates you have, and what versions you require. In this case, we’ve used version `0.3.0`. </del> <ins> crates you have, and what versions you require. In this case, we’ve specified version `0.3.0`, which Cargo understands to be any release that’s compatible with this specific version. </ins> Cargo understands [Semantic Versioning][semver], which is a standard for writing version <del> numbers. If we wanted to use the latest version we could use `*` or we could use a range of versions. [Cargo’s documentation][cargodoc] contains more details. </del> <ins> numbers. If we wanted to use only `0.3.0` exactly, we could use `=0.3.0`. If we wanted to use the latest version we could use `*`; We could use a range of versions. [Cargo’s documentation][cargodoc] contains more details. </ins> [semver]: http://semver.org [cargodoc]: http://doc.crates.io/crates-io.html
Change:
The message "expected constant integer for repeat count, but unsupported constant expr" is a bit weird (ungrammatical?).

Discussion:
use middle; use middle::cast; use middle::check_const; <del> use middle::const_eval::{self, ConstVal}; </del> <ins> use middle::const_eval::{self, ConstVal, ErrKind}; </ins> use middle::const_eval::EvalHint::UncheckedExprHint; use middle::def::{self, DefMap, ExportMap}; use middle::dependency_format;

found); } Err(err) => { <del> let err_description = err.description(); let found = match count_expr.node { </del> <ins> let err_msg = match count_expr.node { </ins> ast::ExprPath(None, ast::Path { global: false, ref segments, .. }) if segments.len() == 1 => <del> format!("{}", "found variable"), _ => format!("but {}", err_description), </del> <ins> format!("found variable"), _ => match err.kind { ErrKind::MiscCatchAll => format!("but found {}", err.description()), _ => format!("but {}", err.description()) } </ins> }; span_err!(self.sess, count_expr.span, E0307, <del> "expected constant integer for repeat count, {}", found); </del> <ins> "expected constant integer for repeat count, {}", err_msg); </ins> } } 0
Change:
Link to the docs in question:
Is there any API that accepts a null raw pointer?
What about ptr::copy if the count is zero?
transmute does :)
I suppose I implicitly meant "explicitly accepts a pointer, and not some opaque T"

Discussion:
/// /// The `len` argument is the number of **elements**, not the number of bytes. /// <ins> /// # Unsafety /// </ins> /// This function is unsafe as there is no guarantee that the given pointer is /// valid for `len` elements, nor whether the lifetime inferred is a suitable /// lifetime for the returned slice. /// <ins> /// `p` must be non-null, even for zero-length slices. /// </ins> /// # Caveat /// /// The lifetime for the returned slice is inferred from its usage. To
Change:
uses , which implies that relinquishes the borrow, which won't work for anything but .

Discussion:
/// Disposes of a value. /// <del> /// This function can be used to destroy any value by allowing `drop` to take ownership of its /// argument. </del> <ins> /// While this does call the argument's implementation of `Drop`, it will not /// release any borrows, as borrows are based on lexical scope. </ins> /// /// # Examples /// <ins> /// Basic usage: /// /// ``` /// let v = vec![1, 2, 3]; /// /// drop(v); // explicitly drop the vector /// ``` /// /// Borrows are based on lexical scope, so this produces an error: /// /// ```ignore /// let mut v = vec![1, 2, 3]; /// let x = &v[0]; /// /// drop(x); // explicitly drop the reference, but the borrow still exists /// /// v.push(4); // error: cannot borrow `v` as mutable because it is also ///            // borrowed as immutable /// ``` /// /// An inner scope is needed to fix this: /// /// ``` /// let mut v = vec![1, 2, 3]; /// /// { ///     let x = &v[0]; /// ///     drop(x); // this is now redundant, as `x` is going out of scope anyway /// } /// /// v.push(4); // no problems /// ``` /// /// Since `RefCell` enforces the borrow rules at runtime, `drop()` can /// seemingly release a borrow of one: /// </ins> /// ``` /// use std::cell::RefCell; ///
Change:
The "src" link at the top goes to the incorrect URL:
Can you please file this against instead? This tracker is just for Rust itself. Thanks!
This is a bug in rustdoc afaict.
Ah! Sorry about that
Might be related to

Discussion:
true, |component| { path.push(component.to_string()); }); <del> Some(format!("{root}src/{krate}/{path}.html#{href}", root = self.cx.root_path, krate = self.cx.layout.krate, path = path.join("/"), href = href)) </del> <ins> // If the span points into an external macro the // source-file will be bogus, i.e `<foo macros>` if Path::new(&self.item.source.filename).is_file() { Some(format!("{root}src/{krate}/{path}.html#{href}", root = self.cx.root_path, krate = self.cx.layout.krate, path = path.join("/"), href = href)) } else { None } </ins> // If this item is not part of the local crate, then things get a little // trickier. We don't actually know the span of the external item, but

<ins> // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[macro_export] macro_rules! make_item ( ($name: ident) => (pub const $name: usize = 42;) ); </ins>

<ins> // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:issue-26606-macro.rs // ignore-cross-compile // build-aux-docs // @has issue_26606_macro/macro.make_item!.html #[macro_use] extern crate issue_26606_macro; // @has issue_26606/constant.FOO.html // @!has - '//a/@href' '../src/' make_item!(FOO); </ins>
Change:
Converting my type to handle unsized types has exposed an ICE (assertion failure) in when handling 's destructor. Reproduction code (triggers assertion on playpen, and current nightly )
Reduced test case: The assert seems to be tripped by , wants a single argument for a call, but it's seeing two (because a fat pointer is now passed in two immediate arguments). cc

Discussion:
let ty = Type::from_ref(llvm::LLVMTypeOf(dtor_addr)); ty.element_type().func_params() }; <del> assert_eq!(params.len(), 1); </del> <ins> assert_eq!(params.len(), if type_is_sized(bcx.tcx(), t) { 1 } else { 2 }); </ins> // Be sure to put the contents into a scope so we can use an invoke // instruction to call the user destructor but still call the field

let glue_type = get_drop_glue_type(bcx.ccx(), t); let dtor_ty = bcx.tcx().mk_ctor_fn(class_did, &[glue_type], bcx.tcx().mk_nil()); <del> let (_, bcx) = invoke(bcx, dtor_addr, &[v0], dtor_ty, DebugLoc::None); </del> <ins> let (_, bcx) = if type_is_sized(bcx.tcx(), t) { invoke(bcx, dtor_addr, &[v0], dtor_ty, DebugLoc::None) } else { let args = [Load(bcx, expr::get_dataptr(bcx, v0)), Load(bcx, expr::get_len(bcx, v0))]; invoke(bcx, dtor_addr, &args, dtor_ty, DebugLoc::None) }; </ins> bcx.fcx.pop_and_trans_custom_cleanup_scope(bcx, contents_scope) }

<ins> // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct Wrapper<'a, T: ?Sized>(&'a mut i32, T); impl<'a, T: ?Sized> Drop for Wrapper<'a, T> { fn drop(&mut self) { *self.0 = 432; } } fn main() { let mut x = 0; { let wrapper = Box::new(Wrapper(&mut x, 123)); let _: Box<Wrapper<Send>> = wrapper; } assert_eq!(432, x) } </ins>
Change:
The docs for these are currently fairly meagre: They need to be more specific about the details, e.g.: needs to have been previously allocated via / (at least, it's highly likely to be incorrect if it wasn't) needs to be the capacity that the pointer was allocated with. Violating these may cause problems like corrupting the allocators internal datastructures.

Discussion:
/// Creates a new `String` from a length, capacity, and pointer. /// <del> /// This is unsafe because: </del> <ins> /// # Unsafety </ins> /// <del> /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`; </del> <ins> /// This is _very_ unsafe because: /// /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`. Therefore, this ///   function inherits all of its unsafety, see [its ///   documentation](../vec/struct.Vec.html#method.from_raw_parts) ///   for the invariants it expects, they also apply to this function. </ins> /// * We assume that the `Vec` contains valid UTF-8. #[inline] #[stable(feature = "rust1", since = "1.0.0")]

/// Creates a `Vec<T>` directly from the raw components of another vector. /// <del> /// This is highly unsafe, due to the number of invariants that aren't checked. </del> <ins> /// # Unsafety /// /// This is highly unsafe, due to the number of invariants that aren't /// checked: /// /// * `ptr` needs to have been previously allocated via `String`/`Vec<T>` ///   (at least, it's highly likely to be incorrect if it wasn't). /// * `capacity` needs to be the capacity that the pointer was allocated with. /// /// Violating these may cause problems like corrupting the allocator's /// internal datastructures. </ins> /// /// # Examples ///
Change:
The fact that function pointers implement the closure traits // also doesn't seem to be mentioned in either the book or the reference.
We do mention the type, but not that they implement Fn:
Note that items are not actually function pointers, they share the same mechanism as closures of being anonymous types with impls of ; they are only coercible to pointers ().

Discussion:
Now we take a trait object, a `&Fn`. And we have to make a reference to our closure when we pass it to `call_with_one`, so we use `&||`. <ins> # Function pointers and closures A function pointer is kind of like a closure that has no environment. As such, you can pass a function pointer to any function expecting a closure argument, and it will work: ```rust fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 { some_closure(1) } fn add_one(i: i32) -> i32 { i + 1 } let f = add_one; let answer = call_with_one(&f); assert_eq!(2, answer); ``` In this example, we don’t strictly need the intermediate variable `f`, the name of the function works just fine too: ```ignore let answer = call_with_one(&add_one); ``` </ins> # Returning closures It’s very common for functional-style code to return closures in various

let x: i32 = diverges(); let x: String = diverges(); ``` <ins> ## Function pointers We can also create variable bindings which point to functions: ```rust let f: fn(i32) -> i32; ``` `f` is a variable binding which points to a function that takes an `i32` as an argument and returns an `i32`. For example: ```rust fn plus_one(i: i32) -> i32 { i + 1 } // without type inference let f: fn(i32) -> i32 = plus_one; // with type inference let f = plus_one; ``` We can then use `f` to call the function: ```rust # fn plus_one(i: i32) -> i32 { i + 1 } # let f = plus_one; let six = f(5); ``` </ins>
Change:
discusses two types of comments: comments and doc comments. mentions a third type: module doc comments. Should be updated to include , or have I misunderstood something? I'd be happy to help update the docs, but I thought I should make sure I know what's going on before I start telling everyone else :)
The reference for doc comments. Maybe mentioning is a good idea for the book though.
Yeah, I would not be opposed to describing in the comments section as well.
Thanks y'all! :)

Discussion:
} ``` <ins> There is another style of doc comment, `//!`, to comment containing items (e.g. crates, modules or functions), instead of the items following it. Commonly used inside crates root (lib.rs) or modules root (mod.rs): ``` //! # The Rust Standard Library //! //! The Rust Standard Library provides the essential runtime //! functionality for building portable Rust software. ``` </ins> When writing doc comments, providing some examples of usage is very, very helpful. You’ll notice we’ve used a new macro here: `assert_eq!`. This compares two values, and `panic!`s if they’re not equal to each other. It’s very helpful
Change:
We're not shipping all the dependencies anyway right now and should just stop shipping everything related to this (cc )

Discussion:
elif key == "libraries": lib_path.extend(val.lstrip(' =').split(';')) <del> target_tools = ["gcc.exe", "ld.exe", "ar.exe", "dlltool.exe", "windres.exe"] </del> <ins> target_tools = ["gcc.exe", "ld.exe", "ar.exe", "dlltool.exe"] </ins> rustc_dlls = ["libstdc++-6.dll"] if target_triple.startswith("i686-"):
Change:
I tried this code: I expected to see this happen: code should compile or the compiler should report an error. Instead, this happened: the compiler panicked. : Backtrace:
Reduced test case:

Discussion:
// any ambiguity. fn find_bound_for_assoc_item<'tcx>(this: &AstConv<'tcx>, ty_param_node_id: ast::NodeId, <ins> ty_param_name: Option<ast::Name>, </ins> assoc_name: ast::Name, span: Span) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>

.filter(|b| this.trait_defines_associated_type_named(b.def_id(), assoc_name)) .collect(); <del> let ty_param_name = tcx.type_parameter_def(ty_param_node_id).name; one_bound_for_assoc_type(tcx, suitable_bounds, &token::get_name(ty_param_name), &token::get_name(assoc_name), span) </del> <ins> if let Some(s) = ty_param_name { // borrowck doesn't like this any other way one_bound_for_assoc_type(tcx, suitable_bounds, &token::get_name(s), &token::get_name(assoc_name), span) } else { one_bound_for_assoc_type(tcx, suitable_bounds, "Self", &token::get_name(assoc_name), span) } </ins> }

_ => unreachable!() } } <del> (&ty::TyParam(_), def::DefTyParam(..)) | (&ty::TyParam(_), def::DefSelfTy(Some(_), None)) => { // A type parameter or Self, we need to find the associated item from // a bound. let ty_param_node_id = ty_path_def.local_node_id(); match find_bound_for_assoc_item(this, ty_param_node_id, assoc_name, span) { </del> <ins> (&ty::TyParam(_), def::DefSelfTy(Some(trait_did),  None)) => { assert_eq!(trait_did.krate, ast::LOCAL_CRATE); match find_bound_for_assoc_item(this, trait_did.node, None, assoc_name, span) { Ok(bound) => bound, Err(ErrorReported) => return (tcx.types.err, ty_path_def), } } (&ty::TyParam(_), def::DefTyParam(_, _, param_did, param_name)) => { assert_eq!(param_did.krate, ast::LOCAL_CRATE); match find_bound_for_assoc_item(this, param_did.node, Some(param_name), assoc_name, span) { </ins> Ok(bound) => bound, Err(ErrorReported) => return (tcx.types.err, ty_path_def), }

<ins> // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn avg<T=T::Item>(_: T) {} //~ ERROR associated type `Item` not found for `T` fn main() {} </ins>