Skip to content

Commit 4db0b32

Browse files
committed
Auto merge of #22796 - Manishearth:rollup, r=Manishearth
2 parents 880fb89 + 357b41b commit 4db0b32

File tree

139 files changed

+1698
-1093
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

139 files changed

+1698
-1093
lines changed

src/doc/index.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ There are questions that are asked quite often, and so we've made FAQs for them:
6868
* [Language Design FAQ](complement-design-faq.html)
6969
* [Language FAQ](complement-lang-faq.html)
7070
* [Project FAQ](complement-project-faq.html)
71-
* [How to submit a bug report](complement-bugreport.html)
71+
* [How to submit a bug report](https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.md#bug-reports)
7272

7373
# The standard library
7474

src/doc/reference.md

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -731,15 +731,20 @@ Rust syntax is restricted in two ways:
731731
pairs when they occur at the beginning of, or immediately after, a `$(...)*`;
732732
requiring a distinctive token in front can solve the problem.
733733

734-
## Syntax extensions useful for the macro author
734+
## Syntax extensions useful in macros
735735

736-
* `log_syntax!` : print out the arguments at compile time
737-
* `trace_macros!` : supply `true` or `false` to enable or disable macro expansion logging
738736
* `stringify!` : turn the identifier argument into a string literal
739737
* `concat!` : concatenates a comma-separated list of literals
740-
* `concat_idents!` : create a new identifier by concatenating the arguments
741738

742-
The following attributes are used for quasiquoting in procedural macros:
739+
## Syntax extensions for macro debugging
740+
741+
* `log_syntax!` : print out the arguments at compile time
742+
* `trace_macros!` : supply `true` or `false` to enable or disable macro expansion logging
743+
744+
## Quasiquoting
745+
746+
The following syntax extensions are used for quasiquoting Rust syntax trees,
747+
usually in [procedural macros](book/plugins.html#syntax-extensions):
743748

744749
* `quote_expr!`
745750
* `quote_item!`
@@ -748,6 +753,8 @@ The following attributes are used for quasiquoting in procedural macros:
748753
* `quote_tokens!`
749754
* `quote_ty!`
750755

756+
Documentation is very limited at the moment.
757+
751758
# Crates and source files
752759

753760
Rust is a *compiled* language. Its semantics obey a *phase distinction*

src/doc/trpl/advanced-macros.md

Lines changed: 48 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -192,19 +192,58 @@ To keep this system simple and correct, `#[macro_use] extern crate ...` may
192192
only appear at the root of your crate, not inside `mod`. This ensures that
193193
`$crate` is a single identifier.
194194

195-
# A final note
195+
# The deep end
196196

197-
Macros, as currently implemented, are not for the faint of heart. Even
198-
ordinary syntax errors can be more difficult to debug when they occur inside a
199-
macro, and errors caused by parse problems in generated code can be very
200-
tricky. Invoking the `log_syntax!` macro can help elucidate intermediate
201-
states, invoking `trace_macros!(true)` will automatically print those
202-
intermediate states out, and passing the flag `--pretty expanded` as a
203-
command-line argument to the compiler will show the result of expansion.
197+
The introductory chapter mentioned recursive macros, but it did not give the
198+
full story. Recursive macros are useful for another reason: Each recursive
199+
invocation gives you another opportunity to pattern-match the macro's
200+
arguments.
201+
202+
As an extreme example, it is possible, though hardly advisable, to implement
203+
the [Bitwise Cyclic Tag](http://esolangs.org/wiki/Bitwise_Cyclic_Tag) automaton
204+
within Rust's macro system.
205+
206+
```rust
207+
#![feature(trace_macros)]
208+
209+
macro_rules! bct {
210+
// cmd 0: d ... => ...
211+
(0, $($ps:tt),* ; $_d:tt)
212+
=> (bct!($($ps),*, 0 ; ));
213+
(0, $($ps:tt),* ; $_d:tt, $($ds:tt),*)
214+
=> (bct!($($ps),*, 0 ; $($ds),*));
215+
216+
// cmd 1p: 1 ... => 1 ... p
217+
(1, $p:tt, $($ps:tt),* ; 1)
218+
=> (bct!($($ps),*, 1, $p ; 1, $p));
219+
(1, $p:tt, $($ps:tt),* ; 1, $($ds:tt),*)
220+
=> (bct!($($ps),*, 1, $p ; 1, $($ds),*, $p));
221+
222+
// cmd 1p: 0 ... => 0 ...
223+
(1, $p:tt, $($ps:tt),* ; $($ds:tt),*)
224+
=> (bct!($($ps),*, 1, $p ; $($ds),*));
225+
226+
// halt on empty data string
227+
( $($ps:tt),* ; )
228+
=> (());
229+
}
230+
231+
fn main() {
232+
trace_macros!(true);
233+
# /* just check the definition
234+
bct!(0, 0, 1, 1, 1 ; 1, 0, 1);
235+
# */
236+
}
237+
```
238+
239+
Exercise: use macros to reduce duplication in the above definition of the
240+
`bct!` macro.
241+
242+
# Procedural macros
204243

205244
If Rust's macro system can't do what you need, you may want to write a
206245
[compiler plugin](plugins.html) instead. Compared to `macro_rules!`
207246
macros, this is significantly more work, the interfaces are much less stable,
208-
and the warnings about debugging apply ten-fold. In exchange you get the
247+
and bugs can be much harder to track down. In exchange you get the
209248
flexibility of running arbitrary Rust code within the compiler. Syntax
210249
extension plugins are sometimes called *procedural macros* for this reason.

src/doc/trpl/error-handling.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,78 @@ let input = io::stdin().read_line()
223223
.ok()
224224
.expect("Failed to read line");
225225
```
226+
226227
`ok()` converts the `IoResult` into an `Option`, and `expect()` does the same
227228
thing as `unwrap()`, but takes a message. This message is passed along to the
228229
underlying `panic!`, providing a better error message if the code errors.
230+
231+
# Using `try!`
232+
233+
When writing code that calls many functions that return the `Result` type, the
234+
error handling can be tedious. The `try!` macro hides some of the boilerplate
235+
of propagating errors up the call stack.
236+
237+
It replaces this:
238+
239+
```rust
240+
use std::fs::File;
241+
use std::io;
242+
use std::io::prelude::*;
243+
244+
struct Info {
245+
name: String,
246+
age: i32,
247+
rating: i32,
248+
}
249+
250+
fn write_info(info: &Info) -> io::Result<()> {
251+
let mut file = File::open("my_best_friends.txt").unwrap();
252+
253+
if let Err(e) = writeln!(&mut file, "name: {}", info.name) {
254+
return Err(e)
255+
}
256+
if let Err(e) = writeln!(&mut file, "age: {}", info.age) {
257+
return Err(e)
258+
}
259+
if let Err(e) = writeln!(&mut file, "rating: {}", info.rating) {
260+
return Err(e)
261+
}
262+
263+
return Ok(());
264+
}
265+
```
266+
267+
With this:
268+
269+
```rust
270+
use std::fs::File;
271+
use std::io;
272+
use std::io::prelude::*;
273+
274+
struct Info {
275+
name: String,
276+
age: i32,
277+
rating: i32,
278+
}
279+
280+
fn write_info(info: &Info) -> io::Result<()> {
281+
let mut file = try!(File::open("my_best_friends.txt"));
282+
283+
try!(writeln!(&mut file, "name: {}", info.name));
284+
try!(writeln!(&mut file, "age: {}", info.age));
285+
try!(writeln!(&mut file, "rating: {}", info.rating));
286+
287+
return Ok(());
288+
}
289+
```
290+
291+
Wrapping an expression in `try!` will result in the unwrapped success (`Ok`)
292+
value, unless the result is `Err`, in which case `Err` is returned early from
293+
the enclosing function.
294+
295+
It's worth noting that you can only use `try!` from a function that returns a
296+
`Result`, which means that you cannot use `try!` inside of `main()`, because
297+
`main()` doesn't return anything.
298+
299+
`try!` makes use of [`FromError`](../std/error/#the-fromerror-trait) to determine
300+
what to return in the error case.

src/doc/trpl/macros.md

Lines changed: 78 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ macro_rules! vec {
7373
};
7474
}
7575
# fn main() {
76-
# assert_eq!(&[1,2,3], &vec![1,2,3]);
76+
# assert_eq!([1,2,3], vec![1,2,3]);
7777
# }
7878
```
7979

@@ -189,14 +189,12 @@ shorthand for a data type could be valid as either an expression or a pattern.
189189

190190
## Repetition
191191

192-
The repetition behavior can seem somewhat magical, especially when multiple
193-
names are bound at multiple nested levels of repetition. The two rules to keep
194-
in mind are:
192+
The repetition operator follows two principal rules:
195193

196-
1. the behavior of `$(...)*` is to walk through one "layer" of repetitions, for
197-
all of the `$name`s it contains, in lockstep, and
194+
1. `$(...)*` walks through one "layer" of repetitions, for all of the `$name`s
195+
it contains, in lockstep, and
198196
2. each `$name` must be under at least as many `$(...)*`s as it was matched
199-
against. If it is under more, it'll be duplicated, as appropriate.
197+
against. If it is under more, it'll be duplicated, as appropriate.
200198

201199
This baroque macro illustrates the duplication of variables from outer
202200
repetition levels.
@@ -226,6 +224,10 @@ That's most of the matcher syntax. These examples use `$(...)*`, which is a
226224
more" match. Both forms optionally include a separator, which can be any token
227225
except `+` or `*`.
228226

227+
This system is based on
228+
"[Macro-by-Example](http://www.cs.indiana.edu/ftp/techreports/TR206.pdf)"
229+
(PDF link).
230+
229231
# Hygiene
230232

231233
Some languages implement macros using simple text substitution, which leads to
@@ -273,19 +275,26 @@ macro, using [a GNU C extension] to emulate Rust's expression blocks.
273275
})
274276
```
275277

276-
This looks reasonable, but watch what happens in this example:
278+
Here's a simple use case that goes terribly wrong:
277279

278280
```text
279281
const char *state = "reticulating splines";
280-
LOG(state);
282+
LOG(state)
281283
```
282284

283-
The program will likely segfault, after it tries to execute
285+
This expands to
284286

285287
```text
286-
printf("log(%d): %s\n", state, state);
288+
const char *state = "reticulating splines";
289+
int state = get_log_state();
290+
if (state > 0) {
291+
printf("log(%d): %s\n", state, state);
292+
}
287293
```
288294

295+
The second variable named `state` shadows the first one. This is a problem
296+
because the print statement should refer to both of them.
297+
289298
The equivalent Rust macro has the desired behavior.
290299

291300
```rust
@@ -357,6 +366,64 @@ fn main() {
357366

358367
[items]: ../reference.html#items
359368

369+
# Recursive macros
370+
371+
A macro's expansion can include more macro invocations, including invocations
372+
of the very same macro being expanded. These recursive macros are useful for
373+
processing tree-structured input, as illustrated by this (simplistic) HTML
374+
shorthand:
375+
376+
```rust
377+
# #![allow(unused_must_use)]
378+
macro_rules! write_html {
379+
($w:expr, ) => (());
380+
381+
($w:expr, $e:tt) => (write!($w, "{}", $e));
382+
383+
($w:expr, $tag:ident [ $($inner:tt)* ] $($rest:tt)*) => {{
384+
write!($w, "<{}>", stringify!($tag));
385+
write_html!($w, $($inner)*);
386+
write!($w, "</{}>", stringify!($tag));
387+
write_html!($w, $($rest)*);
388+
}};
389+
}
390+
391+
fn main() {
392+
# // FIXME(#21826)
393+
use std::fmt::Write;
394+
let mut out = String::new();
395+
396+
write_html!(&mut out,
397+
html[
398+
head[title["Macros guide"]]
399+
body[h1["Macros are the best!"]]
400+
]);
401+
402+
assert_eq!(out,
403+
"<html><head><title>Macros guide</title></head>\
404+
<body><h1>Macros are the best!</h1></body></html>");
405+
}
406+
```
407+
408+
# Debugging macro code
409+
410+
To see the results of expanding macros, run `rustc --pretty expanded`. The
411+
output represents a whole crate, so you can also feed it back in to `rustc`,
412+
which will sometimes produce better error messages than the original
413+
compilation. Note that the `--pretty expanded` output may have a different
414+
meaning if multiple variables of the same name (but different syntax contexts)
415+
are in play in the same scope. In this case `--pretty expanded,hygiene` will
416+
tell you about the syntax contexts.
417+
418+
`rustc` provides two syntax extensions that help with macro debugging. For now,
419+
they are unstable and require feature gates.
420+
421+
* `log_syntax!(...)` will print its arguments to standard output, at compile
422+
time, and "expand" to nothing.
423+
424+
* `trace_macros!(true)` will enable a compiler message every time a macro is
425+
expanded. Use `trace_macros!(false)` later in expansion to turn it off.
426+
360427
# Further reading
361428

362429
The [advanced macros chapter][] goes into more detail about macro syntax. It

src/doc/trpl/plugins.md

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -146,14 +146,7 @@ a more involved macro example, see
146146

147147
## Tips and tricks
148148

149-
To see the results of expanding syntax extensions, run
150-
`rustc --pretty expanded`. The output represents a whole crate, so you
151-
can also feed it back in to `rustc`, which will sometimes produce better
152-
error messages than the original compilation. Note that the
153-
`--pretty expanded` output may have a different meaning if multiple
154-
variables of the same name (but different syntax contexts) are in play
155-
in the same scope. In this case `--pretty expanded,hygiene` will tell
156-
you about the syntax contexts.
149+
Some of the [macro debugging tips](macros.html#debugging-macro-code) are applicable.
157150

158151
You can use [`syntax::parse`](../syntax/parse/index.html) to turn token trees into
159152
higher-level syntax elements like expressions:
@@ -184,6 +177,11 @@ and return
184177
[`DummyResult`](../syntax/ext/base/struct.DummyResult.html),
185178
so that the compiler can continue and find further errors.
186179

180+
To print syntax fragments for debugging, you can use
181+
[`span_note`](../syntax/ext/base/struct.ExtCtxt.html#method.span_note) together
182+
with
183+
[`syntax::print::pprust::*_to_string`](http://doc.rust-lang.org/syntax/print/pprust/index.html#functions).
184+
187185
The example above produced an integer literal using
188186
[`AstBuilder::expr_uint`](../syntax/ext/build/trait.AstBuilder.html#tymethod.expr_uint).
189187
As an alternative to the `AstBuilder` trait, `libsyntax` provides a set of

src/liballoc/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@
7373
#![feature(unboxed_closures)]
7474
#![feature(unsafe_no_drop_flag)]
7575
#![feature(core)]
76+
#![feature(unique)]
7677
#![cfg_attr(test, feature(test, alloc, rustc_private))]
7778
#![cfg_attr(all(not(feature = "external_funcs"), not(feature = "external_crate")),
7879
feature(libc))]

src/libcollections/binary_heap.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -480,7 +480,7 @@ impl<T: Ord> BinaryHeap<T> {
480480
/// heap.push(3);
481481
///
482482
/// let vec = heap.into_sorted_vec();
483-
/// assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7]);
483+
/// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
484484
/// ```
485485
pub fn into_sorted_vec(mut self) -> Vec<T> {
486486
let mut end = self.len();

0 commit comments

Comments
 (0)