Auto merge of #30782 - steveklabnik:rollup, r=steveklabnik

- Successful merges: #30584, #30747, #30755, #30758, #30760, #30769
- Failed merges: #30766
This commit is contained in:
bors 2016-01-08 22:42:10 +00:00
commit d70ab2bdf1
16 changed files with 92 additions and 69 deletions

View File

@ -14,7 +14,7 @@ Even then, Rust still allows precise control like a low-level language would.
[rust]: https://www.rust-lang.org [rust]: https://www.rust-lang.org
“The Rust Programming Language” is split into sections. This introduction “The Rust Programming Language” is split into chapters. This introduction
is the first. After this: is the first. After this:
* [Getting started][gs] - Set up your computer for Rust development. * [Getting started][gs] - Set up your computer for Rust development.

View File

@ -208,7 +208,7 @@ different.
Rusts implementation of closures is a bit different than other languages. They Rusts implementation of closures is a bit different than other languages. They
are effectively syntax sugar for traits. Youll want to make sure to have read are effectively syntax sugar for traits. Youll want to make sure to have read
the [traits chapter][traits] before this one, as well as the chapter on [trait the [traits][traits] section before this one, as well as the section on [trait
objects][trait-objects]. objects][trait-objects].
[traits]: traits.html [traits]: traits.html

View File

@ -3,6 +3,6 @@
So youve learned how to write some Rust code. But theres a difference between So youve learned how to write some Rust code. But theres a difference between
writing *any* Rust code and writing *good* Rust code. writing *any* Rust code and writing *good* Rust code.
This section consists of relatively independent tutorials which show you how to This chapter consists of relatively independent tutorials which show you how to
take your Rust to the next level. Common patterns and standard library features take your Rust to the next level. Common patterns and standard library features
will be introduced. Read these sections in any order of your choosing. will be introduced. Read these sections in any order of your choosing.

View File

@ -5,18 +5,18 @@ errors in a particular way. Generally speaking, error handling is divided into
two broad categories: exceptions and return values. Rust opts for return two broad categories: exceptions and return values. Rust opts for return
values. values.
In this chapter, we intend to provide a comprehensive treatment of how to deal In this section, we intend to provide a comprehensive treatment of how to deal
with errors in Rust. More than that, we will attempt to introduce error handling with errors in Rust. More than that, we will attempt to introduce error handling
one piece at a time so that you'll come away with a solid working knowledge of one piece at a time so that you'll come away with a solid working knowledge of
how everything fits together. how everything fits together.
When done naïvely, error handling in Rust can be verbose and annoying. This When done naïvely, error handling in Rust can be verbose and annoying. This
chapter will explore those stumbling blocks and demonstrate how to use the section will explore those stumbling blocks and demonstrate how to use the
standard library to make error handling concise and ergonomic. standard library to make error handling concise and ergonomic.
# Table of Contents # Table of Contents
This chapter is very long, mostly because we start at the very beginning with This section is very long, mostly because we start at the very beginning with
sum types and combinators, and try to motivate the way Rust does error handling sum types and combinators, and try to motivate the way Rust does error handling
incrementally. As such, programmers with experience in other expressive type incrementally. As such, programmers with experience in other expressive type
systems may want to jump around. systems may want to jump around.
@ -636,7 +636,7 @@ Thus far, we've looked at error handling where everything was either an
`Option` and a `Result`? Or what if you have a `Result<T, Error1>` and a `Option` and a `Result`? Or what if you have a `Result<T, Error1>` and a
`Result<T, Error2>`? Handling *composition of distinct error types* is the next `Result<T, Error2>`? Handling *composition of distinct error types* is the next
challenge in front of us, and it will be the major theme throughout the rest of challenge in front of us, and it will be the major theme throughout the rest of
this chapter. this section.
## Composing `Option` and `Result` ## Composing `Option` and `Result`
@ -648,7 +648,7 @@ Of course, in real code, things aren't always as clean. Sometimes you have a
mix of `Option` and `Result` types. Must we resort to explicit case analysis, mix of `Option` and `Result` types. Must we resort to explicit case analysis,
or can we continue using combinators? or can we continue using combinators?
For now, let's revisit one of the first examples in this chapter: For now, let's revisit one of the first examples in this section:
```rust,should_panic ```rust,should_panic
use std::env; use std::env;
@ -1319,7 +1319,7 @@ and [`cause`](../std/error/trait.Error.html#method.cause), but the
limitation remains: `Box<Error>` is opaque. (N.B. This isn't entirely limitation remains: `Box<Error>` is opaque. (N.B. This isn't entirely
true because Rust does have runtime reflection, which is useful in true because Rust does have runtime reflection, which is useful in
some scenarios that are [beyond the scope of this some scenarios that are [beyond the scope of this
chapter](https://crates.io/crates/error).) section](https://crates.io/crates/error).)
It's time to revisit our custom `CliError` type and tie everything together. It's time to revisit our custom `CliError` type and tie everything together.
@ -1486,7 +1486,7 @@ and [`fmt::Result`](../std/fmt/type.Result.html).
# Case study: A program to read population data # Case study: A program to read population data
This chapter was long, and depending on your background, it might be This section was long, and depending on your background, it might be
rather dense. While there is plenty of example code to go along with rather dense. While there is plenty of example code to go along with
the prose, most of it was specifically designed to be pedagogical. So, the prose, most of it was specifically designed to be pedagogical. So,
we're going to do something new: a case study. we're going to do something new: a case study.
@ -1512,7 +1512,7 @@ and [`rustc-serialize`](https://crates.io/crates/rustc-serialize) crates.
We're not going to spend a lot of time on setting up a project with We're not going to spend a lot of time on setting up a project with
Cargo because it is already covered well in [the Cargo Cargo because it is already covered well in [the Cargo
chapter](../book/hello-cargo.html) and [Cargo's documentation][14]. section](../book/hello-cargo.html) and [Cargo's documentation][14].
To get started from scratch, run `cargo new --bin city-pop` and make sure your To get started from scratch, run `cargo new --bin city-pop` and make sure your
`Cargo.toml` looks something like this: `Cargo.toml` looks something like this:
@ -2108,7 +2108,7 @@ handling.
# The Short Story # The Short Story
Since this chapter is long, it is useful to have a quick summary for error Since this section is long, it is useful to have a quick summary for error
handling in Rust. These are some good “rules of thumb." They are emphatically handling in Rust. These are some good “rules of thumb." They are emphatically
*not* commandments. There are probably good reasons to break every one of these *not* commandments. There are probably good reasons to break every one of these
heuristics! heuristics!

View File

@ -1,13 +1,13 @@
% Getting Started % Getting Started
This first section of the book will get us going with Rust and its tooling. This first chapter of the book will get us going with Rust and its tooling.
First, well install Rust. Then, the classic Hello World program. Finally, First, well install Rust. Then, the classic Hello World program. Finally,
well talk about Cargo, Rusts build system and package manager. well talk about Cargo, Rusts build system and package manager.
# Installing Rust # Installing Rust
The first step to using Rust is to install it. Generally speaking, youll need The first step to using Rust is to install it. Generally speaking, youll need
an Internet connection to run the commands in this chapter, as well be an Internet connection to run the commands in this section, as well be
downloading Rust from the internet. downloading Rust from the internet.
Well be showing off a number of commands using a terminal, and those lines all Well be showing off a number of commands using a terminal, and those lines all

View File

@ -7,7 +7,7 @@ prompt us to enter a guess. Upon entering our guess, it will tell us if were
too low or too high. Once we guess correctly, it will congratulate us. Sounds too low or too high. Once we guess correctly, it will congratulate us. Sounds
good? good?
Along the way, well learn a little bit about Rust. The next section, Syntax Along the way, well learn a little bit about Rust. The next chapter, Syntax
and Semantics, will dive deeper into each part. and Semantics, will dive deeper into each part.
# Set up # Set up

View File

@ -1,6 +1,6 @@
% Learn Rust % Learn Rust
Welcome! This section has a few tutorials that teach you Rust through building Welcome! This chapter has a few tutorials that teach you Rust through building
projects. Youll get a high-level overview, but well skim over the details. projects. Youll get a high-level overview, but well skim over the details.
If youd prefer a more from the ground up-style experience, check If youd prefer a more from the ground up-style experience, check

View File

@ -51,15 +51,24 @@ fn foo() {
} }
``` ```
When `v` comes into scope, a new [`Vec<T>`][vect] is created. In this case, the When `v` comes into scope, a new [vector] is created, and it allocates space on
vector also allocates space on [the heap][heap], for the three elements. When [the heap][heap] for each of its elements. When `v` goes out of scope at the
`v` goes out of scope at the end of `foo()`, Rust will clean up everything end of `foo()`, Rust will clean up everything related to the vector, even the
related to the vector, even the heap-allocated memory. This happens heap-allocated memory. This happens deterministically, at the end of the scope.
deterministically, at the end of the scope.
[vect]: ../std/vec/struct.Vec.html We'll cover [vectors] in detail later in this chapter; we only use them
here as an example of a type that allocates space on the heap at runtime. They
behave like [arrays], except their size may change by `push()`ing more
elements onto them.
Vectors have a [generic type][generics] `Vec<T>`, so in this example `v` will have type
`Vec<i32>`. We'll cover generics in detail later in this chapter.
[arrays]: primitive-types.html#arrays
[vectors]: vectors.html
[heap]: the-stack-and-the-heap.html [heap]: the-stack-and-the-heap.html
[bindings]: variable-bindings.html [bindings]: variable-bindings.html
[generics]: generics.html
# Move semantics # Move semantics

View File

@ -167,8 +167,11 @@ variable binding. Slices have a defined length, can be mutable or immutable.
## Slicing syntax ## Slicing syntax
You can use a combo of `&` and `[]` to create a slice from various things. The You can use a combo of `&` and `[]` to create a slice from various things. The
`&` indicates that slices are similar to references, and the `[]`s, with a `&` indicates that slices are similar to [references], which we will cover in
range, let you define the length of the slice: detail later in this section. The `[]`s, with a range, let you define the
length of the slice:
[references]: references-and-borrowing.html
```rust ```rust
let a = [0, 1, 2, 3, 4]; let a = [0, 1, 2, 3, 4];
@ -189,11 +192,13 @@ documentation][slice].
# `str` # `str`
Rusts `str` type is the most primitive string type. As an [unsized type][dst], Rusts `str` type is the most primitive string type. As an [unsized type][dst],
its not very useful by itself, but becomes useful when placed behind a reference, its not very useful by itself, but becomes useful when placed behind a
like [`&str`][strings]. As such, well just leave it at that. reference, like `&str`. We'll elaborate further when we cover
[Strings][strings] and [references].
[dst]: unsized-types.html [dst]: unsized-types.html
[strings]: strings.html [strings]: strings.html
[references]: references-and-borrowing.html
You can find more documentation for `str` [in the standard library You can find more documentation for `str` [in the standard library
documentation][str]. documentation][str].

View File

@ -1,6 +1,6 @@
% Syntax and Semantics % Syntax and Semantics
This section breaks Rust down into small chunks, one for each concept. This chapter breaks Rust down into small chunks, one for each concept.
If youd like to learn Rust from the bottom up, reading this in order is a If youd like to learn Rust from the bottom up, reading this in order is a
great way to do that. great way to do that.

View File

@ -24,7 +24,7 @@ pub fn insert(&mut self, index: usize, elem: T) {
// ptr::copy(src, dest, len): "copy from source to dest len elems" // ptr::copy(src, dest, len): "copy from source to dest len elems"
ptr::copy(self.ptr.offset(index as isize), ptr::copy(self.ptr.offset(index as isize),
self.ptr.offset(index as isize + 1), self.ptr.offset(index as isize + 1),
len - index); self.len - index);
} }
ptr::write(self.ptr.offset(index as isize), elem); ptr::write(self.ptr.offset(index as isize), elem);
self.len += 1; self.len += 1;
@ -44,7 +44,7 @@ pub fn remove(&mut self, index: usize) -> T {
let result = ptr::read(self.ptr.offset(index as isize)); let result = ptr::read(self.ptr.offset(index as isize));
ptr::copy(self.ptr.offset(index as isize + 1), ptr::copy(self.ptr.offset(index as isize + 1),
self.ptr.offset(index as isize), self.ptr.offset(index as isize),
len - index); self.len - index);
result result
} }
} }

View File

@ -295,6 +295,10 @@ macro_rules! impls{
/// even though it does not. This allows you to inform the compiler about certain safety properties /// even though it does not. This allows you to inform the compiler about certain safety properties
/// of your code. /// of your code.
/// ///
/// For a more in-depth explanation of how to use `PhantomData<T>`, please see [the Nomicon].
///
/// [the Nomicon]: ../../nomicon/phantom-data.html
///
/// # A ghastly note 👻👻👻 /// # A ghastly note 👻👻👻
/// ///
/// Though they both have scary names, `PhantomData<T>` and 'phantom types' are related, but not /// Though they both have scary names, `PhantomData<T>` and 'phantom types' are related, but not

View File

@ -72,7 +72,7 @@ use rustc_front::intravisit::{self, FnKind, Visitor};
use rustc_front::hir; use rustc_front::hir;
use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block}; use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
use rustc_front::hir::Crate; use rustc_front::hir::Crate;
use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprField}; use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprCall, ExprField};
use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall}; use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
use rustc_front::hir::{ExprPath, ExprStruct, FnDecl}; use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics}; use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
@ -433,7 +433,7 @@ fn resolve_struct_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
msg); msg);
match context { match context {
UnresolvedNameContext::Other => {} // no help available UnresolvedNameContext::Other => { } // no help available
UnresolvedNameContext::PathIsMod(id) => { UnresolvedNameContext::PathIsMod(id) => {
let mut help_msg = String::new(); let mut help_msg = String::new();
let parent_id = resolver.ast_map.get_parent_node(id); let parent_id = resolver.ast_map.get_parent_node(id);
@ -446,7 +446,6 @@ fn resolve_struct_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
module = &*path, module = &*path,
ident = ident.node); ident = ident.node);
} }
ExprMethodCall(ident, _, _) => { ExprMethodCall(ident, _, _) => {
help_msg = format!("To call a function from the \ help_msg = format!("To call a function from the \
`{module}` module, use \ `{module}` module, use \
@ -454,9 +453,15 @@ fn resolve_struct_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
module = &*path, module = &*path,
ident = ident.node); ident = ident.node);
} }
ExprCall(_, _) => {
_ => {} // no help available help_msg = format!("No function corresponds to `{module}(..)`",
module = &*path);
}
_ => { } // no help available
} }
} else {
help_msg = format!("Module `{module}` cannot be the value of an expression",
module = &*path);
} }
if !help_msg.is_empty() { if !help_msg.is_empty() {

View File

@ -8,27 +8,6 @@
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // except according to those terms.
//! A type that can represent all platform-native strings, but is cheaply
//! interconvertable with Rust strings.
//!
//! The need for this type arises from the fact that:
//!
//! * On Unix systems, strings are often arbitrary sequences of non-zero
//! bytes, in many cases interpreted as UTF-8.
//!
//! * On Windows, strings are often arbitrary sequences of non-zero 16-bit
//! values, interpreted as UTF-16 when it is valid to do so.
//!
//! * In Rust, strings are always valid UTF-8, but may contain zeros.
//!
//! The types in this module bridge this gap by simultaneously representing Rust
//! and platform-native string values, and in particular allowing a Rust string
//! to be converted into an "OS" string with no cost.
//!
//! **Note**: At the moment, these types are extremely bare-bones, usable only
//! for conversion to/from various other string types. Eventually these types
//! will offer a full-fledged string API.
use borrow::{Borrow, Cow, ToOwned}; use borrow::{Borrow, Cow, ToOwned};
use ffi::CString; use ffi::CString;
use fmt::{self, Debug}; use fmt::{self, Debug};
@ -42,14 +21,29 @@ use vec::Vec;
use sys::os_str::{Buf, Slice}; use sys::os_str::{Buf, Slice};
use sys_common::{AsInner, IntoInner, FromInner}; use sys_common::{AsInner, IntoInner, FromInner};
/// Owned, mutable OS strings. /// A type that can represent owned, mutable platform-native strings, but is
/// cheaply interconvertable with Rust strings.
///
/// The need for this type arises from the fact that:
///
/// * On Unix systems, strings are often arbitrary sequences of non-zero
/// bytes, in many cases interpreted as UTF-8.
///
/// * On Windows, strings are often arbitrary sequences of non-zero 16-bit
/// values, interpreted as UTF-16 when it is valid to do so.
///
/// * In Rust, strings are always valid UTF-8, but may contain zeros.
///
/// `OsString` and `OsStr` bridge this gap by simultaneously representing Rust
/// and platform-native string values, and in particular allowing a Rust string
/// to be converted into an "OS" string with no cost.
#[derive(Clone)] #[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub struct OsString { pub struct OsString {
inner: Buf inner: Buf
} }
/// Slices into OS strings. /// Slices into OS strings (see `OsString`).
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub struct OsStr { pub struct OsStr {
inner: Slice inner: Slice

View File

@ -58,3 +58,15 @@ fn h6() -> i32 {
//~^ ERROR E0425 //~^ ERROR E0425
//~| HELP To call a function from the `a::b` module, use `a::b::f(..)` //~| HELP To call a function from the `a::b` module, use `a::b::f(..)`
} }
fn h7() {
a::b
//~^ ERROR E0425
//~| HELP Module `a::b` cannot be the value of an expression
}
fn h8() -> i32 {
a::b()
//~^ ERROR E0425
//~| HELP No function corresponds to `a::b(..)`
}

View File

@ -58,16 +58,11 @@ fn test5(x: &Bar, a: isize) -> isize {
x.extension_method(a) x.extension_method(a)
} }
// FIXME #30661: Although this function has the #[rustc_mir] attribute it never #[rustc_mir]
// was translated via the MIR implementation because attributes fn test6<T: Bar>(x: &T, a: isize) -> isize {
// where not passed along to trans::base::trans_fn() for generic // Test calling extension method on generic callee
// functions. x.extension_method(a)
// Uncomment this test once the thing it tests is fixed. }
// #[rustc_mir]
// fn test6<T: Bar>(x: &T, a: isize) -> isize {
// // Test calling extension method on generic callee
// x.extension_method(a)
// }
trait One<T = Self> { trait One<T = Self> {
fn one() -> T; fn one() -> T;
@ -119,8 +114,7 @@ fn main() {
assert_eq!(test3(&Foo, 42), 42); assert_eq!(test3(&Foo, 42), 42);
assert_eq!(test4(&Foo, 970), 970); assert_eq!(test4(&Foo, 970), 970);
assert_eq!(test5(&Foo, 8576), 8576); assert_eq!(test5(&Foo, 8576), 8576);
// see definition of test6() above assert_eq!(test6(&Foo, 12367), 12367);
// assert_eq!(test6(&Foo, 12367), 12367);
assert_eq!(test7(), 1); assert_eq!(test7(), 1);
assert_eq!(test8(), 2); assert_eq!(test8(), 2);