]> git.lizzy.rs Git - rust.git/commitdiff
auto merge of #17175 : pcwalton/rust/region-bounds-on-closures, r=huonw
authorbors <bors@rust-lang.org>
Sat, 13 Sep 2014 08:06:00 +0000 (08:06 +0000)
committerbors <bors@rust-lang.org>
Sat, 13 Sep 2014 08:06:00 +0000 (08:06 +0000)
This can break code like:

    fn call_rec(f: |uint| -> uint) -> uint {
        (|x| f(x))(call_rec(f))
    }

Change this code to use a temporary instead of violating the borrow
rules:

    fn call_rec(f: |uint| -> uint) -> uint {
        let tmp = call_rec(|x| f(x)); f(tmp)
    }

Closes #17144.

[breaking-change]

r? @huonw

78 files changed:
README.md
mk/dist.mk
mk/docs.mk
src/doc/guide.md
src/doc/index.md
src/doc/intro.md
src/doc/po4a.conf
src/doc/rust.md
src/doc/tutorial.md
src/etc/copy-runtime-deps.py [deleted file]
src/etc/get-snapshot.py
src/etc/make-win-dist.py [new file with mode: 0644]
src/etc/snapshot.py
src/etc/third-party/README.txt
src/libcore/fmt/mod.rs
src/librustc/back/link.rs
src/librustc/driver/driver.rs
src/librustc/front/feature_gate.rs
src/librustc/front/show_span.rs
src/librustc/lint/builtin.rs
src/librustc/lint/context.rs
src/librustc/lint/mod.rs
src/librustc/metadata/creader.rs
src/librustc/metadata/encoder.rs
src/librustc/metadata/filesearch.rs
src/librustc/middle/borrowck/gather_loans/mod.rs
src/librustc/middle/borrowck/mod.rs
src/librustc/middle/check_const.rs
src/librustc/middle/check_loop.rs
src/librustc/middle/check_match.rs
src/librustc/middle/check_rvalues.rs
src/librustc/middle/check_static.rs
src/librustc/middle/const_eval.rs
src/librustc/middle/dataflow.rs
src/librustc/middle/dead.rs
src/librustc/middle/effect.rs
src/librustc/middle/entry.rs
src/librustc/middle/freevars.rs
src/librustc/middle/intrinsicck.rs
src/librustc/middle/kind.rs
src/librustc/middle/lang_items.rs
src/librustc/middle/liveness.rs
src/librustc/middle/privacy.rs
src/librustc/middle/reachable.rs
src/librustc/middle/region.rs
src/librustc/middle/resolve.rs
src/librustc/middle/resolve_lifetime.rs
src/librustc/middle/save/mod.rs
src/librustc/middle/stability.rs
src/librustc/middle/trans/base.rs
src/librustc/middle/trans/controlflow.rs
src/librustc/middle/trans/meth.rs
src/librustc/middle/ty.rs
src/librustc/middle/typeck/check/mod.rs
src/librustc/middle/typeck/check/regionck.rs
src/librustc/middle/typeck/check/vtable.rs
src/librustc/middle/typeck/check/writeback.rs
src/librustc/middle/typeck/coherence.rs
src/librustc/middle/typeck/collect.rs
src/librustc/middle/typeck/variance.rs
src/librustc/middle/weak_lang_items.rs
src/librustc/plugin/build.rs
src/librustc/plugin/load.rs
src/librustc/plugin/registry.rs
src/librustc/util/common.rs
src/librustc_back/lib.rs
src/librustc_back/svh.rs
src/libsyntax/ast_util.rs
src/libsyntax/diagnostic.rs
src/libsyntax/ext/base.rs
src/libsyntax/ext/expand.rs
src/libsyntax/visit.rs
src/snapshots.txt
src/test/auxiliary/macro_crate_test.rs
src/test/compile-fail/lint-unused-extern-crate.rs [new file with mode: 0644]
src/test/compile-fail/unsized5.rs
src/test/run-pass/ifmt.rs
src/test/run-pass/unsized3.rs [new file with mode: 0644]

index 097a2aeb6e49077f5b2e2cbc09e5840623b79b7c..9def5e305db090900cb5efe26ece0ebb99e8780a 100644 (file)
--- a/README.md
+++ b/README.md
@@ -6,14 +6,14 @@ documentation.
 ## Quick Start
 
 1. Download a [binary installer][installer] for your platform.
-2. Read the [tutorial].
+2. Read the [guide].
 3. Enjoy!
 
 > ***Note:*** Windows users can read the detailed
 > [getting started][wiki-start] notes on the wiki.
 
 [installer]: http://www.rust-lang.org/install.html
-[tutorial]: http://doc.rust-lang.org/tutorial.html
+[guide]: http://doc.rust-lang.org/guide.html
 [wiki-start]: https://github.com/rust-lang/rust/wiki/Note-getting-started-developing-Rust
 [win-wiki]: https://github.com/rust-lang/rust/wiki/Using-Rust-on-Windows
 
@@ -54,7 +54,7 @@ documentation.
     When complete, `make install` will place several programs into
     `/usr/local/bin`: `rustc`, the Rust compiler, and `rustdoc`, the
     API-documentation tool.
-3. Read the [tutorial].
+3. Read the [guide].
 4. Enjoy!
 
 ### Building on Windows
@@ -76,7 +76,7 @@ To easily build on windows we can use [MSYS2](http://sourceforge.net/projects/ms
 
 [repo]: https://github.com/rust-lang/rust
 [tarball]: https://static.rust-lang.org/dist/rust-nightly.tar.gz
-[tutorial]: http://doc.rust-lang.org/tutorial.html
+[guide]: http://doc.rust-lang.org/guide.html
 
 ## Notes
 
index 4d86af37171b41561ff9e7ecfcb41afcf26ce701..26169f3a13bd0f4c6884ddaf05feb8495d2d8072 100644 (file)
@@ -123,7 +123,7 @@ PKG_EXE = dist/$(PKG_NAME)-$(CFG_BUILD).exe
 $(PKG_EXE): rust.iss modpath.iss upgrade.iss LICENSE.txt rust-logo.ico \
             $(CSREQ3_T_$(CFG_BUILD)_H_$(CFG_BUILD)) \
             dist-prepare-win
-       $(CFG_PYTHON) $(S)src/etc/copy-runtime-deps.py tmp/dist/win/bin $(CFG_BUILD)
+       $(CFG_PYTHON) $(S)src/etc/make-win-dist.py tmp/dist/win $(CFG_BUILD)
        @$(call E, ISCC: $@)
        $(Q)"$(CFG_ISCC)" $<
 
index db0de4bde5b8a20df66618aaa4c3ca3435cf2dfb..34031aded5a4a2e04e1b1d1ed2ceade2b1ae3691 100644 (file)
@@ -9,8 +9,7 @@
 # except according to those terms.
 
 ######################################################################
-# The various pieces of standalone documentation: guides, tutorial,
-# manual etc.
+# The various pieces of standalone documentation: guides, manual, etc
 #
 # The DOCS variable is their names (with no file extension).
 #
@@ -32,7 +31,7 @@ DOCS := index intro tutorial guide guide-ffi guide-macros guide-lifetimes \
        complement-lang-faq complement-design-faq complement-project-faq rust \
     rustdoc guide-unsafe guide-strings
 
-PDF_DOCS := tutorial rust
+PDF_DOCS := guide rust
 
 RUSTDOC_DEPS_rust := doc/full-toc.inc
 RUSTDOC_FLAGS_rust := --html-in-header=doc/full-toc.inc
@@ -226,7 +225,7 @@ $(foreach docname,$(DOCS),$(eval $(call DEF_DOC,$(docname))))
 #
 # As such, I've attempted to get it working as much as possible (and
 # switching from pandoc to rustdoc), but preserving the old behaviour
-# (e.g. only running on the tutorial)
+# (e.g. only running on the guide)
 .PHONY: l10n-mds
 l10n-mds: $(D)/po4a.conf \
                $(foreach lang,$(L10N_LANG),$(D)/po/$(lang)/*.md.po)
@@ -244,7 +243,7 @@ doc/l10n/$(1)/$(2).html: l10n-mds $$(HTML_DEPS) $$(RUSTDOC_DEPS_$(2))
        $$(RUSTDOC) $$(RUSTDOC_HTML_OPTS) $$(RUSTDOC_FLAGS_$(1)) doc/l10n/$(1)/$(2).md
 endef
 
-$(foreach lang,$(L10N_LANGS),$(eval $(call DEF_L10N_DOC,$(lang),tutorial)))
+$(foreach lang,$(L10N_LANGS),$(eval $(call DEF_L10N_DOC,$(lang),guide)))
 
 
 ######################################################################
index ec5e544fa75298a6845e5ec9c185781e4dae965e..140536543d93dcbfd662666eac6b205216a19cf5 100644 (file)
@@ -1,14 +1,5 @@
 % The Rust Guide
 
-<div style="border: 2px solid red; padding:5px;">
-This guide is a work in progress. Until it is ready, we highly recommend that
-you read the <a href="tutorial.html">Tutorial</a> instead. This work-in-progress Guide is being
-displayed here in line with Rust's open development policy. Please open any
-issues you find as usual.
-</div>
-
-# Welcome!
-
 Hey there! Welcome to the Rust guide. This is the place to be if you'd like to
 learn how to program in Rust. Rust is a systems programming language with a
 focus on "high-level, bare-metal programming": the lowest level control a
@@ -119,7 +110,7 @@ The first thing that we need to do is make a file to put our code in. I like
 to make a `projects` directory in my home directory, and keep all my projects
 there. Rust does not care where your code lives.
 
-This actually leads to one other concern we should address: this tutorial will
+This actually leads to one other concern we should address: this guide will
 assume that you have basic familiarity with the command line. Rust does not
 require that you know a whole ton about the command line, but until the
 language is in a more finished state, IDE support is spotty. Rust makes no
@@ -139,14 +130,15 @@ the documentation for your shell for more details.
 
 Let's make a new source file next. I'm going to use the syntax `editor
 filename` to represent editing a file in these examples, but you should use
-whatever method you want. We'll call our file `hello_world.rs`:
+whatever method you want. We'll call our file `main.rs`:
 
 ```{bash}
-$ editor hello_world.rs
+$ editor main.rs
 ```
 
 Rust files always end in a `.rs` extension. If you're using more than one word
-in your file name, use an underscore. `hello_world.rs` versus `goodbye.rs`.
+in your file name, use an underscore. `hello_world.rs` rather than
+`helloworld.rs`.
 
 Now that you've got your file open, type this in:
 
@@ -159,7 +151,7 @@ fn main() {
 Save the file, and then type this into your terminal window:
 
 ```{bash}
-$ rustc hello_world.rs
+$ rustc main.rs
 $ ./hello_world # or hello_world.exe on Windows
 Hello, world!
 ```
@@ -215,13 +207,13 @@ Finally, the line ends with a semicolon (`;`). Rust is an **expression
 oriented** language, which means that most things are expressions. The `;` is
 used to indicate that this expression is over, and the next one is ready to
 begin. Most lines of Rust code end with a `;`. We will cover this in-depth
-later in the tutorial.
+later in the guide.
 
 Finally, actually **compiling** and **running** our program. We can compile
 with our compiler, `rustc`, by passing it the name of our source file:
 
 ```{bash}
-$ rustc hello_world.rs
+$ rustc main.rs
 ```
 
 This is similar to `gcc` or `clang`, if you come from a C or C++ background. Rust
@@ -229,14 +221,14 @@ will output a binary executable. You can see it with `ls`:
 
 ```{bash}
 $ ls
-hello_world  hello_world.rs
+main  main.rs
 ```
 
 Or on Windows:
 
 ```{bash}
 $ dir
-hello_world.exe  hello_world.rs
+main.exe  main.rs
 ```
 
 There are now two files: our source code, with the `.rs` extension, and the
@@ -293,7 +285,7 @@ do that part first:
 
 ```{bash}
 $ mkdir src
-$ mv hello_world.rs src/hello_world.rs
+$ mv main.rs src/main.rs
 ```
 
 Cargo expects your source files to live inside a `src` directory. That leaves
@@ -461,9 +453,9 @@ let x;
 ...we'll get an error:
 
 ```{ignore}
-src/hello_world.rs:2:9: 2:10 error: cannot determine a type for this local variable: unconstrained type
-src/hello_world.rs:2     let x;
-                             ^
+src/main.rs:2:9: 2:10 error: cannot determine a type for this local variable: unconstrained type
+src/main.rs:2     let x;
+                      ^
 ```
 
 Giving it a type will compile, though:
@@ -472,7 +464,7 @@ Giving it a type will compile, though:
 let x: int;
 ```
 
-Let's try it out. Change your `src/hello_world.rs` file to look like this:
+Let's try it out. Change your `src/main.rs` file to look like this:
 
 ```{rust}
 fn main() {
@@ -487,8 +479,8 @@ but it will still print "Hello, world!":
 
 ```{ignore,notrust}
    Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
-src/hello_world.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)] on by default
-src/hello_world.rs:2     let x: int;
+src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)] on by default
+src/main.rs:2     let x: int;
                              ^
 ```
 
@@ -509,13 +501,13 @@ And try to build it. You'll get an error:
 ```{bash}
 $ cargo build
    Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
-src/hello_world.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x`
-src/hello_world.rs:4     println!("The value of x is: {}", x);
-                                                           ^
+src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x`
+src/main.rs:4     println!("The value of x is: {}", x);
+                                                    ^
 note: in expansion of format_args!
 <std macros>:2:23: 2:77 note: expansion site
 <std macros>:1:1: 3:2 note: in expansion of println!
-src/hello_world.rs:4:5: 4:42 note: expansion site
+src/main.rs:4:5: 4:42 note: expansion site
 error: aborting due to previous error
 Could not compile `hello_world`.
 ```
@@ -1327,10 +1319,7 @@ upper bound is exclusive, though, so our loop will print `0` through `9`, not
 
 Rust does not have the "C style" `for` loop on purpose. Manually controlling
 each element of the loop is complicated and error prone, even for experienced C
-developers. There's an old joke that goes, "There are two hard problems in
-computer science: naming things, cache invalidation, and off-by-one errors."
-The joke, of course, being that the setup says "two hard problems" but then
-lists three things. This happens quite a bit with "C style" `for` loops.
+developers. 
 
 We'll talk more about `for` when we cover **iterator**s, later in the Guide.
 
@@ -2017,7 +2006,7 @@ Great! Next up: let's compare our guess to the secret guess.
 
 ## Comparing guesses
 
-If you remember, earlier in the tutorial, we made a `cmp` function that compared
+If you remember, earlier in the guide, we made a `cmp` function that compared
 two numbers. Let's add that in, along with a `match` statement to compare the
 guess to the secret guess:
 
@@ -2754,197 +2743,8 @@ $ cargo run
 Hello, world!
 ```
 
-Nice!
-
-There's a common pattern when you're building an executable: you build both an
-executable and a library, and put most of your logic in the library. That way,
-other programs can use that library to build their own functionality.
-
-Let's do that with our project. If you remember, libraries and executables
-are both crates, so while our project has one crate now, let's make a second:
-one for the library, and one for the executable.
-
-To make the second crate, open up `src/lib.rs` and put this code in it:
-
-```{rust}
-mod hello {
-    pub fn print_hello() {
-        println!("Hello, world!");
-    }
-}
-```
-
-And change your `src/main.rs` to look like this:
-
-```{rust,ignore}
-extern crate modules;
-
-fn main() {
-    modules::hello::print_hello();
-}
-```
-
-There's been a few changes. First, we moved our `hello` module into its own
-file, `src/lib.rs`. This is the file that Cargo expects a library crate to
-be named, by convention.
-
-Next, we added an `extern crate modules` to the top of our `src/main.rs`. This,
-as you can guess, lets Rust know that our crate relies on another, external
-crate. We also had to modify our call to `print_hello`: now that it's in
-another crate, we need to specify that crate first.
-
-This doesn't _quite_ work yet. Try it:
-
-```{notrust,ignore}
-$ cargo build
-   Compiling modules v0.0.1 (file:///home/you/projects/modules)
-/home/you/projects/modules/src/lib.rs:2:5: 4:6 warning: code is never used: `print_hello`, #[warn(dead_code)] on by default
-/home/you/projects/modules/src/lib.rs:2     pub fn print_hello() {
-/home/you/projects/modules/src/lib.rs:3         println!("Hello, world!");
-/home/you/projects/modules/src/lib.rs:4     }
-/home/you/projects/modules/src/main.rs:4:5: 4:32 error: function `print_hello` is private
-/home/you/projects/modules/src/main.rs:4     modules::hello::print_hello();
-                                          ^~~~~~~~~~~~~~~~~~~~~~~~~~~
-error: aborting due to previous error
-Could not compile `modules`.
-```
-
-First, we get a warning that some code is never used. Odd. Next, we get an error:
-`print_hello` is private, so we can't call it. Notice that the first error came
-from `src/lib.rs`, and the second came from `src/main.rs`: cargo is smart enough
-to build it all with one command. Also, after seeing the second error, the warning
-makes sense: we never actually call `hello_world`, because we're not allowed to!
-
-Just like modules, crates also have private visibility by default. Any modules
-inside of a crate can only be used by other modules in the crate, unless they
-use `pub`. In `src/lib.rs`, change this line:
-
-```{rust,ignore}
-mod hello {
-```
-
-To this:
-
-```{rust,ignore}
-pub mod hello {
-```
-
-And everything should work:
-
-```{notrust,ignore}
-$ cargo run
-   Compiling modules v0.0.1 (file:///home/you/projects/modules)
-     Running `target/modules`
-Hello, world!
-```
-
-Let's do one more thing: add a `goodbye` module as well. Imagine a `src/lib.rs`
-that looks like this:
-
-```{rust,ignore}
-pub mod hello {
-    pub fn print_hello() {
-        println!("Hello, world!");
-    }
-}
-
-pub mod goodbye {
-    pub fn print_goodbye() {
-        println!("Goodbye for now!");
-    }
-}
-```
-
-Now, these two modules are pretty small, but imagine we've written a real, large
-program: they could both be huge. So maybe we want to move them into their own
-files. We can do that pretty easily, and there are two different conventions
-for doing it. Let's give each a try. First, make `src/lib.rs` look like this:
-
-```{rust,ignore}
-pub mod hello;
-pub mod goodbye;
-```
-
-This tells Rust that this crate has two public modules: `hello` and `goodbye`.
-
-Next, make a `src/hello.rs` that contains this:
-
-```{rust,ignore}
-pub fn print_hello() {
-    println!("Hello, world!");
-}
-```
-
-When we include a module like this, we don't need to make the `mod` declaration
-in `hello.rs`, because it's already been declared in `lib.rs`. `hello.rs` just
-contains the body of the module which is defined (by the `pub mod hello`) in
-`lib.rs`.  This helps prevent 'rightward drift': when you end up indenting so
-many times that your code is hard to read.
-
-Finally, make a new directory, `src/goodbye`, and make a new file in it,
-`src/goodbye/mod.rs`:
-
-```{rust,ignore}
-pub fn print_goodbye() {
-    println!("Bye for now!");
-}
-```
-
-Same deal, but we can make a folder with a `mod.rs` instead of `mod_name.rs` in
-the same directory. If you have a lot of modules, nested folders can make
-sense.  For example, if the `goodbye` module had its _own_ modules inside of
-it, putting all of that in a folder helps keep our directory structure tidy.
-And in fact, if you place the modules in separate files, they're required to be
-in separate folders.
-
-This should all compile as usual:
-
-```{notrust,ignore}
-$ cargo build
-   Compiling modules v0.0.1 (file:///home/you/projects/modules)
-```
-
-We've seen how the `::` operator can be used to call into modules, but when
-we have deep nesting like `modules::hello::say_hello`, it can get tedious.
-That's why we have the `use` keyword.
-
-`use` allows us to bring certain names into another scope. For example, here's
-our main program:
-
-```{rust,ignore}
-extern crate modules;
-
-fn main() {
-    modules::hello::print_hello();
-}
-```
-
-We could instead write this:
-
-```{rust,ignore}
-extern crate modules;
-
-use modules::hello::print_hello;
-
-fn main() {
-    print_hello();
-}
-```
-
-By bringing `print_hello` into scope, we don't need to qualify it anymore. However,
-it's considered proper style to do write this code like like this:
-
-```{rust,ignore}
-extern crate modules;
-
-use modules::hello;
-
-fn main() {
-    hello::print_hello();
-}
-```
-
-By just bringing the module into scope, we can keep one level of namespacing.
+Nice! There are more things we can do with modules, including moving them into
+their own files. This is enough detail for now.
 
 # Testing
 
@@ -3810,9 +3610,9 @@ Here's the second note, which lets us know where the first borrow would be over.
 This is useful, because if we wait to try to borrow `x` after this borrow is
 over, then everything will work.
 
-These rules are very simple, but that doesn't mean that they're easy. For more
-advanced patterns, please consult the [Lifetime Guide](guide-lifetimes.html).
-You'll also learn what this type signature with the `'a` syntax is:
+For more advanced patterns, please consult the [Lifetime
+Guide](guide-lifetimes.html).  You'll also learn what this type signature with
+the `'a` syntax is:
 
 ```{rust,ignore}
 pub fn as_maybe_owned(&self) -> MaybeOwned<'a> { ... }
@@ -4463,14 +4263,14 @@ for num in nums.iter() {
 }
 ```
 
-There are two reasons for this. First, this is more semantic. We iterate
-through the entire vector, rather than iterating through indexes, and then
-indexing the vector. Second, this version is more efficient: the first version
-will have extra bounds checking because it used indexing, `nums[i]`. But since
-we yield a reference to each element of the vector in turn with the iterator,
-there's no bounds checking in the second example. This is very common with
-iterators: we can ignore unnecessary bounds checks, but still know that we're
-safe.
+There are two reasons for this. First, this more directly expresses what we
+mean. We iterate through the entire vector, rather than iterating through
+indexes, and then indexing the vector. Second, this version is more efficient:
+the first version will have extra bounds checking because it used indexing,
+`nums[i]`. But since we yield a reference to each element of the vector in turn
+with the iterator, there's no bounds checking in the second example. This is
+very common with iterators: we can ignore unnecessary bounds checks, but still
+know that we're safe.
 
 There's another detail here that's not 100% clear because of how `println!`
 works. `num` is actually of type `&int`, that is, it's a reference to an `int`,
index a479164c505029f105992f514bed13b2490a3847..66f69d62e788f2043d6a9c0ab3fe989920903a56 100644 (file)
@@ -43,6 +43,10 @@ discussion about Rust.
 There is also a [developer forum](http://discuss.rust-lang.org/), where the
 development of Rust itself is discussed.
 
+# Specification
+
+Rust does not have an exact specification, but an effort to describe as much of
+the language in as much detail as possible is in [the manual](rust.html).
 
 # Guides
 
index 6deaa50867b0d8d6dc1676f98353f61bcce8e982..503ea2b1bbee69eec6da135e496f0d1b9777afa0 100644 (file)
@@ -4,12 +4,12 @@ Rust is a systems programming language that combines strong compile-time correct
 It improves upon the ideas of other systems languages like C++
 by providing guaranteed memory safety (no crashes, no data races) and complete control over the lifecycle of memory.
 Strong memory guarantees make writing correct concurrent Rust code easier than in other languages.
-This tutorial will give you an idea of what Rust is like in about thirty minutes.
+This introduction will give you an idea of what Rust is like in about thirty minutes.
 It expects that you're at least vaguely familiar with a previous 'curly brace' language,
 but does not require prior experience with systems programming.
 The concepts are more important than the syntax,
 so don't worry if you don't get every last detail:
-the [tutorial](tutorial.html) can help you out with that later.
+the [guide](guide.html) can help you out with that later.
 
 Let's talk about the most important concept in Rust, "ownership,"
 and its implications on a task that programmers usually find very difficult: concurrency.
@@ -433,5 +433,5 @@ yet get the efficiency of languages such as C++.
 
 I hope that this taste of Rust has given you an idea if Rust is the right language for you.
 If that's true,
-I encourage you to check out [the tutorial](tutorial.html) for a full,
+I encourage you to check out [the guide](guide.html) for a full,
 in-depth exploration of Rust's syntax and concepts.
index 4069e630a8453443732790c3cd75eef04d1fef08..d5e386325cbcaa5b95b68f085a58ea16be04ac3c 100644 (file)
@@ -24,4 +24,4 @@
 [type: text] src/doc/intro.md $lang:doc/l10n/$lang/intro.md
 [type: text] src/doc/rust.md $lang:doc/l10n/$lang/rust.md
 [type: text] src/doc/rustdoc.md $lang:doc/l10n/$lang/rustdoc.md
-[type: text] src/doc/tutorial.md $lang:doc/l10n/$lang/tutorial.md
+[type: text] src/doc/guide.md $lang:doc/l10n/$lang/guide.md
index fb2407e5163818560aa1bb7d0afc0101da42ebf0..0d1331e6077cd9d2270c0872f14658f700a6bff0 100644 (file)
@@ -13,16 +13,16 @@ provides three kinds of material:
   - Appendix chapters providing rationale and references to languages that
     influenced the design.
 
-This document does not serve as a tutorial introduction to the
+This document does not serve as an introduction to the
 language. Background familiarity with the language is assumed. A separate
-[tutorial] document is available to help acquire such background familiarity.
+[guide] is available to help acquire such background familiarity.
 
 This document also does not serve as a reference to the [standard]
 library included in the language distribution. Those libraries are
 documented separately by extracting documentation attributes from their
 source code.
 
-[tutorial]: tutorial.html
+[guide]: guide.html
 [standard]: std/index.html
 
 ## Disclaimer
@@ -349,7 +349,7 @@ enclosed within two `U+0022` (double-quote) characters,
 with the exception of `U+0022` itself,
 which must be _escaped_ by a preceding `U+005C` character (`\`),
 or a _raw byte string literal_.
-It is equivalent to a `&'static [u8]` borrowed vector of unsigned 8-bit integers.
+It is equivalent to a `&'static [u8]` borrowed array of unsigned 8-bit integers.
 
 Some additional _escapes_ are available in either byte or non-raw byte string
 literals. An escape starts with a `U+005C` (`\`) and continues with one of
@@ -2811,16 +2811,17 @@ When the type providing the field inherits mutabilty, it can be [assigned](#assi
 Also, if the type of the expression to the left of the dot is a pointer,
 it is automatically dereferenced to make the field access possible.
 
-### Vector expressions
+### Array expressions
 
 ~~~~ {.ebnf .gram}
-vec_expr : '[' "mut" ? vec_elems? ']' ;
+array_expr : '[' "mut" ? vec_elems? ']' ;
 
-vec_elems : [expr [',' expr]*] | [expr ',' ".." expr] ;
+array_elems : [expr [',' expr]*] | [expr ',' ".." expr] ;
 ~~~~
 
-A [_vector_](#vector-types) _expression_ is written by enclosing zero or
-more comma-separated expressions of uniform type in square brackets.
+An [array](#vector,-array,-and-slice-types) _expression_ is written by
+enclosing zero or more comma-separated expressions of uniform type in square
+brackets.
 
 In the `[expr ',' ".." expr]` form, the expression after the `".."`
 must be a constant expression that can be evaluated at compile time, such
@@ -2829,7 +2830,7 @@ as a [literal](#literals) or a [static item](#static-items).
 ~~~~
 [1i, 2, 3, 4];
 ["a", "b", "c", "d"];
-[0i, ..128];             // vector with 128 zeros
+[0i, ..128];             // array with 128 zeros
 [0u8, 0u8, 0u8, 0u8];
 ~~~~
 
@@ -2839,9 +2840,9 @@ as a [literal](#literals) or a [static item](#static-items).
 idx_expr : expr '[' expr ']' ;
 ~~~~
 
-[Vector](#vector-types)-typed expressions can be indexed by writing a
+[Array](#vector,-array,-and-slice-types)-typed expressions can be indexed by writing a
 square-bracket-enclosed expression (the index) after them. When the
-vector is mutable, the resulting [lvalue](#lvalues,-rvalues-and-temporaries) can be assigned to.
+array is mutable, the resulting [lvalue](#lvalues,-rvalues-and-temporaries) can be assigned to.
 
 Indices are zero-based, and may be of any integral type. Vector access
 is bounds-checked at run-time. When the check fails, it will put the
@@ -2902,7 +2903,7 @@ This means that arithmetic operators can be overridden for user-defined types.
 The default meaning of the operators on standard types is given here.
 
 * `+`
-  : Addition and vector/string concatenation.
+  : Addition and array/string concatenation.
     Calls the `add` method on the `std::ops::Add` trait.
 * `-`
   : Subtraction.
@@ -3205,7 +3206,7 @@ for_expr : "for" pat "in" no_struct_literal_expr '{' block '}' ;
 A `for` expression is a syntactic construct for looping over elements
 provided by an implementation of `std::iter::Iterator`.
 
-An example of a for loop over the contents of a vector:
+An example of a for loop over the contents of an array:
 
 ~~~~
 # type Foo = int;
@@ -3263,7 +3264,7 @@ match_pat : pat [ '|' pat ] * [ "if" expr ] ? ;
 
 A `match` expression branches on a *pattern*. The exact form of matching that
 occurs depends on the pattern. Patterns consist of some combination of
-literals, destructured vectors or enum constructors, structures and
+literals, destructured arrays or enum constructors, structures and
 tuples, variable binding specifications, wildcards (`..`), and placeholders
 (`_`). A `match` expression has a *head expression*, which is the value to
 compare to the patterns. The type of the patterns must equal the type of the
@@ -3292,11 +3293,11 @@ between `_` and `..` is that the pattern `C(_)` is only type-correct if `C` has
 exactly one argument, while the pattern `C(..)` is type-correct for any enum
 variant `C`, regardless of how many arguments `C` has.
 
-Used inside a vector pattern, `..` stands for any number of elements, when the
+Used inside a array pattern, `..` stands for any number of elements, when the
 `advanced_slice_patterns` feature gate is turned on. This wildcard can be used
-at most once for a given vector, which implies that it cannot be used to
+at most once for a given array, which implies that it cannot be used to
 specifically match elements that are at an unknown distance from both ends of a
-vector, like `[.., 42, ..]`.  If followed by a variable name, it will bind the
+array, like `[.., 42, ..]`.  If followed by a variable name, it will bind the
 corresponding slice to the variable.  Example:
 
 ~~~~
@@ -3429,7 +3430,7 @@ let message = match x {
 ~~~~
 
 Range patterns only work on scalar types
-(like integers and characters; not like vectors and structs, which have sub-components).
+(like integers and characters; not like arrays and structs, which have sub-components).
 A range pattern may not be a sub-range of another range pattern inside the same `match`.
 
 Finally, match patterns can accept *pattern guards* to further refine the
@@ -3537,10 +3538,10 @@ http://www.unicode.org/glossary/#unicode_scalar_value)
 (ie. a code point that is not a surrogate),
 represented as a 32-bit unsigned word in the 0x0000 to 0xD7FF
 or 0xE000 to 0x10FFFF range.
-A `[char]` vector is effectively an UCS-4 / UTF-32 string.
+A `[char]` array is effectively an UCS-4 / UTF-32 string.
 
 A value of type `str` is a Unicode string,
-represented as a vector of 8-bit unsigned bytes holding a sequence of UTF-8 codepoints.
+represented as a array of 8-bit unsigned bytes holding a sequence of UTF-8 codepoints.
 Since `str` is of unknown size, it is not a _first class_ type,
 but can only be instantiated through a pointer type,
 such as `&str` or `String`.
@@ -3651,7 +3652,7 @@ Such recursion has restrictions:
 
 * Recursive types must include a nominal type in the recursion
   (not mere [type definitions](#type-definitions),
-   or other structural types such as [vectors](#vector-types) or [tuples](#tuple-types)).
+   or other structural types such as [arrays](#vector,-array,-and-slice-types) or [tuples](#tuple-types)).
 * A recursive `enum` item must have at least one non-recursive constructor
   (in order to give the recursion a basis case).
 * The size of a recursive type must be finite;
@@ -4155,7 +4156,7 @@ heap data.
 ### Built in types
 
 The runtime provides C and Rust code to assist with various built-in types,
-such as vectors, strings, and the low level communication system (ports,
+such as arrays, strings, and the low level communication system (ports,
 channels, tasks).
 
 Support for other built-in types such as simple types, tuples and
@@ -4174,7 +4175,7 @@ communication facilities.
 The Rust compiler supports various methods to link crates together both
 statically and dynamically. This section will explore the various methods to
 link Rust crates together, and more information about native libraries can be
-found in the [ffi tutorial][ffi].
+found in the [ffi guide][ffi].
 
 In one session of compilation, the compiler can generate multiple artifacts
 through the usage of either command line flags or the `crate_type` attribute.
index 0e5a624b273336953726d98ac298e62ed0fef6e2..f6e64d899607455e8433df1c69d6b6f3d76ca70b 100644 (file)
-% The Rust Language Tutorial
+% The Rust Tutorial
 
-<div style="border: 2px solid red; padding:5px;">
-The tutorial is undergoing a complete re-write as <a href="guide.html">the Guide</a>.
-Until it's ready, this tutorial is the right place to come to start learning
-Rust.  Please submit improvements as pull requests, but understand that
-eventually it will be going away.
-</div>
-
-# Introduction
-
-Rust is a programming language with a focus on type safety, memory
-safety, concurrency and performance. It is intended for writing
-large-scale, high-performance software that is free from several
-classes of common errors. Rust has a sophisticated memory model that
-encourages efficient data structures and safe concurrency patterns,
-forbidding invalid memory accesses that would otherwise cause
-segmentation faults. It is statically typed and compiled ahead of
-time.
-
-As a multi-paradigm language, Rust supports writing code in
-procedural, functional and object-oriented styles. Some of its
-pleasant high-level features include:
-
-* **Type inference.** Type annotations on local variable declarations
-  are optional.
-* **Safe task-based concurrency.** Rust's lightweight tasks do not share
-  memory, instead communicating through messages.
-* **Higher-order functions.** Efficient and flexible closures provide
-  iteration and other control structures
-* **Pattern matching and algebraic data types.** Pattern matching on
-  Rust's enumeration types (a more powerful version of C's enums,
-  similar to algebraic data types in functional languages) is a
-  compact and expressive way to encode program logic.
-* **Polymorphism.** Rust has type-parametric functions and
-  types, type classes and OO-style interfaces.
-
-## Scope
-
-This is an introductory tutorial for the Rust programming language. It
-covers the fundamentals of the language, including the syntax, the
-type system and memory model, generics, and modules. [Additional
-tutorials](#what-next?) cover specific language features in greater
-depth.
-
-This tutorial assumes that the reader is already familiar with one or
-more languages in the C family. Understanding of pointers and general
-memory management techniques will help.
-
-## Conventions
-
-Throughout the tutorial, language keywords and identifiers defined in
-example code are displayed in `code font`.
-
-Code snippets are indented, and also shown in a monospaced font. Not
-all snippets constitute whole programs. For brevity, we'll often show
-fragments of programs that don't compile on their own. To try them
-out, you might have to wrap them in `fn main() { ... }`, and make sure
-they don't contain references to names that aren't actually defined.
-
-> *Warning:* Rust is a language under ongoing development. Notes
-> about potential changes to the language, implementation
-> deficiencies, and other caveats appear offset in blockquotes.
-
-# Getting started
-
-There are two ways to install the Rust compiler: by building from source or
-by downloading prebuilt binaries or installers for your platform. The
-[install page][rust-install] contains links to download binaries for both
-the nightly build and the most current Rust major release. For Windows and
-OS X, the install page provides links to native installers.
-
-> *Note:* Windows users should read the detailed
-> [Getting started][wiki-start] notes on the wiki. Even when using
-> the binary installer, the Windows build requires a MinGW installation,
-> the precise details of which are not discussed here.
-
-For Linux and OS X, the install page provides links to binary tarballs.
-To install the Rust compiler from a binary tarball, download
-the binary package, extract it, and execute the `install.sh` script in
-the root directory of the package.
-
-To build the Rust compiler from source, you will need to obtain the source through
-[Git][git] or by downloading the source package from the [install page][rust-install].
-
-Since the Rust compiler is written in Rust, it must be built by
-a precompiled "snapshot" version of itself (made in an earlier state
-of development). The source build automatically fetches these snapshots
-from the Internet on our supported platforms.
-
-Snapshot binaries are currently built and tested on several platforms:
-
-* Windows (7, 8, Server 2008 R2), x86 only
-* Linux (2.6.18 or later, various distributions), x86 and x86-64
-* OSX 10.7 (Lion) or greater, x86 and x86-64
-
-You may find that other platforms work, but these are our "tier 1"
-supported build environments that are most likely to work.
-
-[wiki-start]: https://github.com/rust-lang/rust/wiki/Note-getting-started-developing-Rust
-[git]: https://github.com/rust-lang/rust.git
-[rust-install]: http://www.rust-lang.org/install.html
-
-To build from source you will also need the following prerequisite
-packages:
-
-* g++ 4.7 or clang++ 3.x
-* python 2.6 or later (but not 3.x)
-* perl 5.0 or later
-* gnu make 3.81 or later
-* curl
-
-If you've fulfilled those prerequisites, something along these lines
-should work.
-
-~~~~console
-$ curl -O https://static.rust-lang.org/dist/rust-nightly.tar.gz
-$ tar -xzf rust-nightly.tar.gz
-$ cd rust-nightly
-$ ./configure
-$ make && make install
-~~~~
-
-You may need to use `sudo make install` if you do not normally have
-permission to modify the destination directory. The install locations
-can be adjusted by passing a `--prefix` argument to
-`configure`. Various other options are also supported: pass `--help`
-for more information on them.
-
-When complete, `make install` will place several programs into
-`/usr/local/bin`: `rustc`, the Rust compiler, and `rustdoc`, the
-API-documentation tool.
-
-[tarball]: https://static.rust-lang.org/dist/rust-nightly.tar.gz
-[win-exe]: https://static.rust-lang.org/dist/rust-nightly-install.exe
-
-## Compiling your first program
-
-Rust program files are, by convention, given the extension `.rs`. Say
-we have a file `hello.rs` containing this program:
-
-~~~~
-fn main() {
-    println!("hello?");
-}
-~~~~
-> *Note:* An identifier followed by an exclamation point, like
-> `println!`, is a macro invocation.  Macros are explained
-> [later](#syntax-extensions); for now just remember to include the
-> exclamation point.
-
-If the Rust compiler was installed successfully, running `rustc
-hello.rs` will produce an executable called `hello` (or `hello.exe` on
-Windows) which, upon running, will likely do exactly what you expect.
-
-The Rust compiler tries to provide useful information when it encounters an
-error. If you introduce an error into the program (for example, by changing
-`println!` to some nonexistent macro), and then compile it, you'll see
-an error message like this:
-
-~~~~text
-hello.rs:2:5: 2:24 error: macro undefined: 'print_with_unicorns'
-hello.rs:2     print_with_unicorns!("hello?");
-               ^~~~~~~~~~~~~~~~~~~
-~~~~
-
-In its simplest form, a Rust program is a `.rs` file with some types
-and functions defined in it. If it has a `main` function, it can be
-compiled to an executable. Rust does not allow code that's not a
-declaration to appear at the top level of the file: all statements must
-live inside a function.  Rust programs can also be compiled as
-libraries, and included in other programs, even ones not written in Rust.
-
-## Editing Rust code
-
-There are vim highlighting and indentation scripts in the Rust source
-distribution under `src/etc/vim/`. There is an emacs mode under
-`src/etc/emacs/` called `rust-mode`, but do read the instructions
-included in that directory. In particular, if you are running emacs
-24, then using emacs's internal package manager to install `rust-mode`
-is the easiest way to keep it up to date. There is also a package for
-Sublime Text 2, available both [standalone][sublime] and through
-[Sublime Package Control][sublime-pkg], and support for Kate
-under `src/etc/kate`.
-
-A community-maintained list of available Rust tooling is [on the
-wiki][wiki-packages].
-
-There is ctags support via `src/etc/ctags.rust`, but many other
-tools and editors are not yet supported. If you end up writing a Rust
-mode for your favorite editor, let us know so that we can link to it.
-
-[sublime]: http://github.com/jhasse/sublime-rust
-[sublime-pkg]: http://wbond.net/sublime_packages/package_control
-
-# Syntax basics
-
-Assuming you've programmed in any C-family language (C++, Java,
-JavaScript, C#, or PHP), Rust will feel familiar. Code is arranged
-in blocks delineated by curly braces; there are control structures
-for branching and looping, like the familiar `if` and `while`; function
-calls are written `myfunc(arg1, arg2)`; operators are written the same
-and mostly have the same precedence as in C; comments are again like C;
-module names are separated with double-colon (`::`) as with C++.
-
-The main surface difference to be aware of is that the condition at
-the head of control structures like `if` and `while` does not require
-parentheses, while their bodies *must* be wrapped in
-braces. Single-statement, unbraced bodies are not allowed.
-
-~~~~
-# mod universe { pub fn recalibrate() -> bool { true } }
-fn main() {
-    /* A simple loop */
-    loop {
-        // A tricky calculation
-        if universe::recalibrate() {
-            return;
-        }
-    }
-}
-~~~~
-
-The `let` keyword introduces a local variable. Variables are immutable by
-default. To introduce a local variable that you can re-assign later, use `let
-mut` instead.
-
-~~~~
-let hi = "hi";
-let mut count = 0i;
-
-while count < 10 {
-    println!("count is {}", count);
-    count += 1;
-}
-~~~~
-
-Although Rust can almost always infer the types of local variables, you can
-specify a variable's type by following it in the `let` with a colon, then the
-type name. Static items, on the other hand, always require a type annotation.
-
-
-~~~~
-static MONSTER_FACTOR: f64 = 57.8;
-let monster_size = MONSTER_FACTOR * 10.0;
-let monster_size: int = 50;
-~~~~
-
-Local variables may shadow earlier declarations, as in the previous example:
-`monster_size` was first declared as a `f64`, and then a second
-`monster_size` was declared as an `int`. If you were to actually compile this
-example, though, the compiler would determine that the first `monster_size` is
-unused and issue a warning (because this situation is likely to indicate a
-programmer error). For occasions where unused variables are intentional, their
-names may be prefixed with an underscore to silence the warning, like `let
-_monster_size = 50;`.
-
-Rust identifiers start with an alphabetic
-character or an underscore, and after that may contain any sequence of
-alphabetic characters, numbers, or underscores. The preferred style is to
-write function, variable, and module names with lowercase letters, using
-underscores where they help readability, while writing types in camel case.
-
-~~~
-let my_variable = 100i;
-type MyType = int;     // primitive types are _not_ camel case
-~~~
-
-## Expressions and semicolons
-
-Though it isn't apparent in all code, there is a fundamental
-difference between Rust's syntax and predecessors like C.
-Many constructs that are statements in C are expressions
-in Rust, allowing code to be more concise. For example, you might
-write a piece of code like this:
-
-~~~~
-# let item = "salad";
-let price: f64;
-if item == "salad" {
-    price = 3.50;
-} else if item == "muffin" {
-    price = 2.25;
-} else {
-    price = 2.00;
-}
-~~~~
-
-But, in Rust, you don't have to repeat the name `price`:
-
-~~~~
-# let item = "salad";
-let price: f64 =
-    if item == "salad" {
-        3.50
-    } else if item == "muffin" {
-        2.25
-    } else {
-        2.00
-    };
-~~~~
-
-Both pieces of code are exactly equivalent: they assign a value to
-`price` depending on the condition that holds. Note that there
-are no semicolons in the blocks of the second snippet. This is
-important: the lack of a semicolon after the last statement in a
-braced block gives the whole block the value of that last expression.
-
-Put another way, the semicolon in Rust *ignores the value of an expression*.
-Thus, if the branches of the `if` had looked like `{ 4; }`, the above example
-would simply assign `()` (unit or void) to `price`. But without the semicolon, each
-branch has a different value, and `price` gets the value of the branch that
-was taken.
-
-In short, everything that's not a declaration (declarations are `let` for
-variables; `fn` for functions; and any top-level named items such as
-[traits](#traits), [enum types](#enums), and static items) is an
-expression, including function bodies.
-
-~~~~
-fn is_four(x: int) -> bool {
-   // No need for a return statement. The result of the expression
-   // is used as the return value.
-   x == 4
-}
-~~~~
-
-## Primitive types and literals
-
-There are general signed and unsigned integer types, `int` and `uint`,
-as well as 8-, 16-, 32-, and 64-bit variants, `i8`, `u16`, etc.
-Integers can be written in decimal (`144`), hexadecimal (`0x90`), octal (`0o70`), or
-binary (`0b10010000`) base. Each integral type has a corresponding literal
-suffix that can be used to indicate the type of a literal: `i` for `int`,
-`u` for `uint`, `i8` for the `i8` type.
-
-In the absence of an integer literal suffix, Rust will infer the
-integer type based on type annotations and function signatures in the
-surrounding program. In the absence of any type information at all,
-Rust will report an error and request that the type be specified explicitly.
-
-~~~~
-let a: int = 1;  // `a` is an `int`
-let b = 10i;     // `b` is an `int`, due to the `i` suffix
-let c = 100u;    // `c` is a `uint`
-let d = 1000i32; // `d` is an `i32`
-~~~~
-
-There are two floating-point types: `f32`, and `f64`.
-Floating-point numbers are written `0.0`, `1e6`, or `2.1e-4`.
-Like integers, floating-point literals are inferred to the correct type.
-Suffixes `f32`, and `f64` can be used to create literals of a specific type.
-
-The keywords `true` and `false` produce literals of type `bool`.
-
-Characters, the `char` type, are four-byte Unicode codepoints,
-whose literals are written between single quotes, as in `'x'`.
-Just like C, Rust understands a number of character escapes, using the backslash
-character, such as `\n`, `\r`, and `\t`. String literals,
-written between double quotes, allow the same escape sequences, and do no
-other processing, unlike languages such as PHP or shell.
-
-On the other hand, raw string literals do not process any escape sequences.
-They are written as `r##"blah"##`, with a matching number of zero or more `#`
-before the opening and after the closing quote, and can contain any sequence of
-characters except their closing delimiter.  More on strings
-[later](#vectors-and-strings).
-
-The unit type, written `()`, has a single value, also written `()`.
-
-## Operators
-
-Rust's set of operators contains very few surprises. Arithmetic is done with
-`*`, `/`, `%`, `+`, and `-` (multiply, quotient, remainder, add, and subtract). `-` is
-also a unary prefix operator that negates numbers. As in C, the bitwise operators
-`>>`, `<<`, `&`, `|`, and `^` are also supported.
-
-Note that, if applied to an integer value, `!` flips all the bits (bitwise
-NOT, like `~` in C).
-
-The comparison operators are the traditional `==`, `!=`, `<`, `>`,
-`<=`, and `>=`. Short-circuiting (lazy) boolean operators are written
-`&&` (and) and `||` (or).
-
-For compile-time type casting, Rust uses the binary `as` operator.  It takes
-an expression on the left side and a type on the right side and will, if a
-meaningful conversion exists, convert the result of the expression to the
-given type. Generally, `as` is only used with the primitive numeric types or
-pointers, and is not overloadable.  [`transmute`][transmute] can be used for
-unsafe C-like casting of same-sized types.
-
-~~~~
-let x: f64 = 4.0;
-let y: uint = x as uint;
-assert!(y == 4u);
-~~~~
-
-[transmute]: http://doc.rust-lang.org/std/mem/fn.transmute.html
-
-## Syntax extensions
-
-*Syntax extensions* are special forms that are not built into the language,
-but are instead provided by the libraries. To make it clear to the reader when
-a name refers to a syntax extension, the names of all syntax extensions end
-with `!`. The standard library defines a few syntax extensions, the most
-useful of which is [`format!`][fmt], a `sprintf`-like text formatter that you
-will often see in examples, and its related family of macros: `print!`,
-`println!`, and `write!`.
-
-`format!` draws syntax from Python, but contains many of the same principles
-that [printf][pf] has. Unlike printf, `format!` will give you a compile-time
-error when the types of the directives don't match the types of the arguments.
-
-~~~
-// `{}` will print the "default format" of a type
-println!("{} is {}", "the answer", 43i);
-~~~
-
-~~~~
-extern crate debug;
-
-# fn main() {
-# let mystery_object = ();
-// `{:?}` will conveniently print any type,
-// but requires the `debug` crate to be linked in
-println!("what is this thing: {:?}", mystery_object);
-# }
-~~~~
-
-[pf]: http://en.cppreference.com/w/cpp/io/c/fprintf
-[fmt]: http://doc.rust-lang.org/std/fmt/
-
-You can define your own syntax extensions with the macro system. For details,
-see the [macro tutorial][macros]. Note that macro definition is currently
-considered an unstable feature.
-
-# Control structures
-
-## Conditionals
-
-We've seen `if` expressions a few times already. To recap, braces are
-compulsory, an `if` can have an optional `else` clause, and multiple
-`if`/`else` constructs can be chained together:
-
-~~~~
-if false {
-    println!("that's odd");
-} else if true {
-    println!("right");
-} else {
-    println!("neither true nor false");
-}
-~~~~
-
-The condition given to an `if` construct *must* be of type `bool` (no
-implicit conversion happens). If the arms are blocks that have a
-value, this value must be of the same type for every arm in which
-control reaches the end of the block:
-
-~~~~
-fn signum(x: int) -> int {
-    if x < 0 { -1 }
-    else if x > 0 { 1 }
-    else { 0 }
-}
-~~~~
-
-## Pattern matching
-
-Rust's `match` construct is a generalized, cleaned-up version of C's
-`switch` construct. You provide it with a value and a number of
-*arms*, each labeled with a pattern, and the code compares the value
-against each pattern in order until one matches. The matching pattern
-executes its corresponding arm.
-
-~~~~
-let my_number = 1i;
-match my_number {
-  0     => println!("zero"),
-  1 | 2 => println!("one or two"),
-  3..10 => println!("three to ten"),
-  _     => println!("something else")
-}
-~~~~
-
-Unlike in C, there is no "falling through" between arms: only one arm
-executes, and it doesn't have to explicitly `break` out of the
-construct when it is finished.
-
-A `match` arm consists of a *pattern*, then a fat arrow `=>`, followed
-by an *action* (expression). Each case is separated by commas. It is
-often convenient to use a block expression for each case, in which case
-the commas are optional as shown below. Literals are valid patterns and
-match only their own value. A single arm may match multiple different
-patterns by combining them with the pipe operator (`|`), so long as
-every pattern binds the same set of variables (see "destructuring"
-below). Ranges of numeric literal patterns can be expressed with two
-dots, as in `M..N`. The underscore (`_`) is a wildcard pattern that
-matches any single value. (`..`) is a different wildcard that can match
-one or more fields in an `enum` variant.
-
-~~~
-# let my_number = 1i;
-match my_number {
-  0 => { println!("zero") }
-  _ => { println!("something else") }
-}
-~~~
-
-`match` constructs must be *exhaustive*: they must have an arm
-covering every possible case. For example, the typechecker would
-reject the previous example if the arm with the wildcard pattern was
-omitted.
-
-A powerful application of pattern matching is *destructuring*:
-matching in order to bind names to the contents of data types.
-
-> *Note:* The following code makes use of tuples (`(f64, f64)`) which
-> are explained in section 5.3. For now you can think of tuples as a list of
-> items.
-
-~~~~
-use std::f64;
-fn angle(vector: (f64, f64)) -> f64 {
-    let pi = f64::consts::PI;
-    match vector {
-      (0.0, y) if y < 0.0 => 1.5 * pi,
-      (0.0, _) => 0.5 * pi,
-      (x, y) => (y / x).atan()
-    }
-}
-~~~~
-
-A variable name in a pattern matches any value, *and* binds that name
-to the value of the matched value inside of the arm's action. Thus, `(0.0,
-y)` matches any tuple whose first element is zero, and binds `y` to
-the second element. `(x, y)` matches any two-element tuple, and binds both
-elements to variables. `(0.0,_)` matches any tuple whose first element is zero
-and does not bind anything to the second element.
-
-A subpattern can also be bound to a variable, using `variable @ pattern`. For
-example:
-
-~~~~
-# let age = 23i;
-match age {
-    a @ 0..20 => println!("{} years old", a),
-    _ => println!("older than 21")
-}
-~~~~
-
-Any `match` arm can have a guard clause (written `if EXPR`), called a
-*pattern guard*, which is an expression of type `bool` that
-determines, after the pattern is found to match, whether the arm is
-taken or not. The variables bound by the pattern are in scope in this
-guard expression. The first arm in the `angle` example shows an
-example of a pattern guard.
-
-You've already seen simple `let` bindings, but `let` is a little
-fancier than you've been led to believe. It, too, supports destructuring
-patterns. For example, you can write this to extract the fields from a
-tuple, introducing two variables at once: `a` and `b`.
-
-~~~~
-# fn get_tuple_of_two_ints() -> (int, int) { (1, 1) }
-let (a, b) = get_tuple_of_two_ints();
-~~~~
-
-Let bindings only work with _irrefutable_ patterns: that is, patterns that can
-never fail to match. This excludes `let` from matching literals and most `enum`
-variants as binding patterns, since most such patterns are not irrefutable. For
-example, this will not compile:
-
-~~~~{ignore}
-let (a, 2) = (1, 2);
-~~~~
-
-## Loops
-
-`while` denotes a loop that iterates as long as its given condition
-(which must have type `bool`) evaluates to `true`. Inside a loop, the
-keyword `break` aborts the loop, and `continue` aborts the current
-iteration and continues with the next.
-
-~~~~
-let mut cake_amount = 8i;
-while cake_amount > 0 {
-    cake_amount -= 1;
-}
-~~~~
-
-`loop` denotes an infinite loop, and is the preferred way of writing `while true`:
-
-~~~~
-let mut x = 5u;
-loop {
-    x += x - 3;
-    if x % 5 == 0 { break; }
-    println!("{}", x);
-}
-~~~~
-
-This code prints out a weird sequence of numbers and stops as soon as
-it finds one that can be divided by five.
-
-There is also a for-loop that can be used to iterate over a range of numbers:
-
-~~~~
-for n in range(0u, 5) {
-    println!("{}", n);
-}
-~~~~
-
-The snippet above prints integer numbers under 5 starting at 0.
-
-More generally, a for loop works with anything implementing the `Iterator` trait.
-Data structures can provide one or more methods that return iterators over
-their contents. For example, strings support iteration over their contents in
-various ways:
-
-~~~~
-let s = "Hello";
-for c in s.chars() {
-    println!("{}", c);
-}
-~~~~
-
-The snippet above prints the characters in "Hello" vertically, adding a new
-line after each character.
-
-
-# Data structures
-
-## Structs
-
-Rust struct types must be declared before they are used using the `struct`
-syntax: `struct Name { field1: T1, field2: T2 [, ...] }`, where `T1`, `T2`,
-... denote types. To construct a struct, use the same syntax, but leave off
-the `struct`: for example: `Point { x: 1.0, y: 2.0 }`.
-
-Structs are quite similar to C structs and are even laid out the same way in
-memory (so you can read from a Rust struct in C, and vice-versa). Use the dot
-operator to access struct fields, as in `mypoint.x`.
-
-~~~~
-struct Point {
-    x: f64,
-    y: f64
-}
-~~~~
-
-Structs have "inherited mutability", which means that any field of a struct
-may be mutable, if the struct is in a mutable slot.
-
-With a value (say, `mypoint`) of such a type in a mutable location, you can do
-`mypoint.y += 1.0`. But in an immutable location, such an assignment to a
-struct without inherited mutability would result in a type error.
-
-~~~~ {.ignore}
-# struct Point { x: f64, y: f64 }
-let mut mypoint = Point { x: 1.0, y: 1.0 };
-let origin = Point { x: 0.0, y: 0.0 };
-
-mypoint.y += 1.0; // `mypoint` is mutable, and its fields as well
-origin.y += 1.0; // ERROR: assigning to immutable field
-~~~~
-
-`match` patterns destructure structs. The basic syntax is
-`Name { fieldname: pattern, ... }`:
-
-~~~~
-# struct Point { x: f64, y: f64 }
-# let mypoint = Point { x: 0.0, y: 0.0 };
-match mypoint {
-    Point { x: 0.0, y: yy } => println!("{}", yy),
-    Point { x: xx,  y: yy } => println!("{} {}", xx, yy)
-}
-~~~~
-
-In general, the field names of a struct do not have to appear in the same
-order they appear in the type. When you are not interested in all
-the fields of a struct, a struct pattern may end with `, ..` (as in
-`Name { field1, .. }`) to indicate that you're ignoring all other fields.
-Additionally, struct fields have a shorthand matching form that simply
-reuses the field name as the binding name.
-
-~~~
-# struct Point { x: f64, y: f64 }
-# let mypoint = Point { x: 0.0, y: 0.0 };
-match mypoint {
-    Point { x, .. } => println!("{}", x)
-}
-~~~
-
-## Enums
-
-Enums are datatypes with several alternate representations. A simple `enum`
-defines one or more constants, all of which have the same type:
-
-~~~~
-enum Direction {
-    North,
-    East,
-    South,
-    West
-}
-~~~~
-
-Each variant of this enum has a unique and constant integral discriminator
-value. If no explicit discriminator is specified for a variant, the value
-defaults to the value of the previous variant plus one. If the first variant
-does not have a discriminator, it defaults to 0. For example, the value of
-`North` is 0, `East` is 1, `South` is 2, and `West` is 3.
-
-When an enum has simple integer discriminators, you can apply the `as` cast
-operator to convert a variant to its discriminator value as an `int`:
-
-~~~~
-# enum Direction { North, East, South, West }
-println!( "North => {}", North as int );
-~~~~
-
-It is possible to set the discriminator values to chosen constant values:
-
-~~~~
-enum Color {
-  Red = 0xff0000,
-  Green = 0x00ff00,
-  Blue = 0x0000ff
-}
-~~~~
-
-Variants do not have to be simple values; they may be more complex:
-
-~~~~
-# struct Point { x: f64, y: f64 }
-enum Shape {
-    Circle(Point, f64),
-    Rectangle(Point, Point)
-}
-~~~~
-
-A value of this type is either a `Circle`, in which case it contains a
-`Point` struct and a f64, or a `Rectangle`, in which case it contains
-two `Point` structs. The run-time representation of such a value
-includes an identifier of the actual form that it holds, much like the
-"tagged union" pattern in C, but with better static guarantees.
-
-This declaration defines a type `Shape` that can refer to such shapes, and two
-functions, `Circle` and `Rectangle`, which can be used to construct values of
-the type.
-
-To create a new `Circle`, write:
-
-~~~~
-# struct Point { x: f64, y: f64 }
-# enum Shape { Circle(Point, f64), Rectangle(Point, Point) }
-let circle = Circle(Point { x: 0.0, y: 0.0 }, 10.0);
-~~~~
-
-All of these variant constructors may be used as patterns. The only way to
-access the contents of an enum instance is the destructuring of a match. For
-example:
-
-~~~~
-use std::f64;
-
-# struct Point {x: f64, y: f64}
-# enum Shape { Circle(Point, f64), Rectangle(Point, Point) }
-fn area(sh: Shape) -> f64 {
-    match sh {
-        Circle(_, size) => f64::consts::PI * size * size,
-        Rectangle(Point { x, y }, Point { x: x2, y: y2 }) => (x2 - x) * (y2 - y)
-    }
-}
-
-let rect = Rectangle(Point { x: 0.0, y: 0.0 }, Point { x: 2.0, y: 2.0 });
-println!("area: {}", area(rect));
-~~~~
-
-Use a lone `_` to ignore an individual field. Ignore all fields of a variant
-like: `Circle(..)`. Nullary enum patterns are written without parentheses:
-
-~~~~
-# struct Point { x: f64, y: f64 }
-# enum Direction { North, East, South, West }
-fn point_from_direction(dir: Direction) -> Point {
-    match dir {
-        North => Point { x:  0.0, y:  1.0 },
-        East  => Point { x:  1.0, y:  0.0 },
-        South => Point { x:  0.0, y: -1.0 },
-        West  => Point { x: -1.0, y:  0.0 }
-    }
-}
-~~~~
-
-Enum variants may also be structs. For example:
-
-~~~~
-#![feature(struct_variant)]
-use std::f64;
-
-# struct Point { x: f64, y: f64 }
-# fn square(x: f64) -> f64 { x * x }
-enum Shape {
-    Circle { center: Point, radius: f64 },
-    Rectangle { top_left: Point, bottom_right: Point }
-}
-fn area(sh: Shape) -> f64 {
-    match sh {
-        Circle { radius: radius, .. } => f64::consts::PI * square(radius),
-        Rectangle { top_left: top_left, bottom_right: bottom_right } => {
-            (bottom_right.x - top_left.x) * (top_left.y - bottom_right.y)
-        }
-    }
-}
-
-fn main() {
-    let rect = Rectangle {
-        top_left: Point { x: 0.0, y: 0.0 },
-        bottom_right: Point { x: 2.0, y: -2.0 }
-    };
-    println!("area: {}", area(rect));
-}
-~~~~
-
-> *Note:* This feature of the compiler is currently gated behind the
-> `#[feature(struct_variant)]` directive. More about these directives can be
-> found in the manual.
-
-## Tuples
-
-Tuples in Rust behave exactly like structs, except that their fields do not
-have names. Thus, you cannot access their fields with dot notation.  Tuples
-can have any arity (number of elements) except for 0 (though you may consider
-unit, `()`, as the empty tuple if you like).
-
-~~~~
-let mytup: (int, int, f64) = (10, 20, 30.0);
-match mytup {
-  (a, b, c) => println!("{}", a + b + (c as int))
-}
-~~~~
-
-## Tuple structs
-
-Rust also has _tuple structs_, which behave like both structs and tuples,
-except that, unlike tuples, tuple structs have names (so `Foo(1, 2)` has a
-different type from `Bar(1, 2)`), and tuple structs' _fields_ do not have
-names.
-
-For example:
-
-~~~~
-struct MyTup(int, int, f64);
-let mytup: MyTup = MyTup(10, 20, 30.0);
-match mytup {
-  MyTup(a, b, c) => println!("{}", a + b + (c as int))
-}
-~~~~
-
-<a name="newtype"></a>
-
-There is a special case for tuple structs with a single field, which are
-sometimes called "newtypes" (after Haskell's "newtype" feature). These are
-used to define new types in such a way that the new name is not just a
-synonym for an existing type but is rather its own distinct type.
-
-~~~~
-struct GizmoId(int);
-~~~~
-
-Types like this can be useful to differentiate between data that have
-the same underlying type but must be used in different ways.
-
-~~~~
-struct Inches(int);
-struct Centimeters(int);
-~~~~
-
-The above definitions allow for a simple way for programs to avoid
-confusing numbers that correspond to different units. Their integer
-values can be extracted with pattern matching:
-
-~~~
-# struct Inches(int);
-let length_with_unit = Inches(10);
-let Inches(integer_length) = length_with_unit;
-println!("length is {} inches", integer_length);
-~~~
-
-# Functions
-
-We've already seen several function definitions. Like all other static
-declarations, such as `type`, functions can be declared both at the
-top level and inside other functions (or in modules, which we'll come
-back to [later](#crates-and-the-module-system)). The `fn` keyword introduces a
-function. A function has an argument list, which is a parenthesized
-list of `name: type` pairs separated by commas. An arrow `->`
-separates the argument list and the function's return type.
-
-~~~~
-fn line(a: int, b: int, x: int) -> int {
-    return a * x + b;
-}
-~~~~
-
-The `return` keyword immediately returns from the body of a function. It
-is optionally followed by an expression to return. A function can
-also return a value by having its top-level block produce an
-expression.
-
-~~~~
-fn line(a: int, b: int, x: int) -> int {
-    a * x + b
-}
-~~~~
-
-It's better Rust style to write a return value this way instead of
-writing an explicit `return`. The utility of `return` comes in when
-returning early from a function. Functions that do not return a value
-are said to return unit, `()`, and both the return type and the return
-value may be omitted from the definition. The following two functions
-are equivalent.
-
-~~~~
-fn do_nothing_the_hard_way() -> () { return (); }
-
-fn do_nothing_the_easy_way() { }
-~~~~
-
-Ending the function with a semicolon like so is equivalent to returning `()`.
-
-~~~~
-fn line(a: int, b: int, x: int) -> int { a * x + b  }
-fn oops(a: int, b: int, x: int) -> ()  { a * x + b; }
-
-assert!(8 == line(5, 3, 1));
-assert!(() == oops(5, 3, 1));
-~~~~
-
-As with `match` expressions and `let` bindings, function arguments support
-pattern destructuring. Like `let`, argument patterns must be irrefutable,
-as in this example that unpacks the first value from a tuple and returns it.
-
-~~~
-fn first((value, _): (int, f64)) -> int { value }
-~~~
-
-# Destructors
-
-A *destructor* is a function responsible for cleaning up the resources used by
-an object when it is no longer accessible. Destructors can be defined to handle
-the release of resources like files, sockets and heap memory.
-
-Objects are never accessible after their destructor has been called, so no
-dynamic failures are possible from accessing freed resources. When a task
-fails, destructors of all objects in the task are called.
-
-The `box` operator performs memory allocation on the heap:
-
-~~~~
-{
-    // an integer allocated on the heap
-    let y = box 10i;
-}
-// the destructor frees the heap memory as soon as `y` goes out of scope
-~~~~
-
-Rust includes syntax for heap memory allocation in the language since it's
-commonly used, but the same semantics can be implemented by a type with a
-custom destructor.
-
-# Ownership
-
-Rust formalizes the concept of object ownership to delegate management of an
-object's lifetime to either a variable or a task-local garbage collector. An
-object's owner is responsible for managing the lifetime of the object by
-calling the destructor, and the owner determines whether the object is mutable.
-
-Ownership is recursive, so mutability is inherited recursively and a destructor
-destroys the contained tree of owned objects. Variables are top-level owners
-and destroy the contained object when they go out of scope.
-
-~~~~
-// the struct owns the objects contained in the `x` and `y` fields
-struct Foo { x: int, y: Box<int> }
-
-{
-    // `a` is the owner of the struct, and thus the owner of the struct's fields
-    let a = Foo { x: 5, y: box 10 };
-}
-// when `a` goes out of scope, the destructor for the `Box<int>` in the struct's
-// field is called
-
-// `b` is mutable, and the mutability is inherited by the objects it owns
-let mut b = Foo { x: 5, y: box 10 };
-b.x = 10;
-~~~~
-
-If an object doesn't contain any non-`Send` types, it consists of a single
-ownership tree and is itself given the `Send` trait which allows it to be sent
-between tasks. Custom destructors can only be implemented directly on types
-that are `Send`, but non-`Send` types can still *contain* types with custom
-destructors. Example of types which are not `Send` are [`Gc<T>`][gc] and
-[`Rc<T>`][rc], the shared-ownership types.
-
-> *Note:* See a [later chapter](#ownership-escape-hatches) for a discussion about
-> [`Gc<T>`][gc] and [`Rc<T>`][rc], and the [chapter about traits](#traits) for
-> a discussion about `Send`.
-
-[gc]: http://doc.rust-lang.org/std/gc/struct.Gc.html
-[rc]: http://doc.rust-lang.org/std/rc/struct.Rc.html
-
-# Implementing a linked list
-
-An `enum` is a natural fit for describing a linked list, because it can express
-a `List` type as being *either* the end of the list (`Nil`) or another node
-(`Cons`). The full definition of the `Cons` variant will require some thought.
-
-~~~ {.ignore}
-enum List {
-    Cons(...), // an incomplete definition of the next element in a List
-    Nil        // the end of a List
-}
-~~~
-
-The obvious approach is to define `Cons` as containing an element in the list
-along with the next `List` node. However, this will generate a compiler error.
-
-~~~ {.ignore}
-// error: illegal recursive enum type; wrap the inner value in a box to make it
-// representable
-enum List {
-    Cons(u32, List), // an element (`u32`) and the next node in the list
-    Nil
-}
-~~~
-
-This error message is related to Rust's precise control over memory layout, and
-solving it will require introducing the concept of *boxing*.
-
-## Boxes
-
-A value in Rust is stored directly inside the owner. If a `struct` contains
-four `u32` fields, it will be four times as large as a single `u32`.
-
-~~~
-use std::mem::size_of; // bring `size_of` into the current scope, for convenience
-
-struct Foo {
-    a: u32,
-    b: u32,
-    c: u32,
-    d: u32
-}
-
-assert_eq!(size_of::<Foo>(), size_of::<u32>() * 4);
-
-struct Bar {
-    a: Foo,
-    b: Foo,
-    c: Foo,
-    d: Foo
-}
-
-assert_eq!(size_of::<Bar>(), size_of::<u32>() * 16);
-~~~
-
-Our previous attempt at defining the `List` type included an `u32` and a `List`
-directly inside `Cons`, making it at least as big as the sum of both types. The
-type was invalid because the size was infinite!
-
-An *owned box* (`Box`, located in the `std::owned` module) uses a dynamic memory
-allocation to provide the invariant of always being the size of a pointer,
-regardless of the contained type. This can be leveraged to create a valid `List`
-definition:
-
-~~~
-
-enum List {
-    Cons(u32, Box<List>),
-    Nil
-}
-~~~
-
-Defining a recursive data structure like this is the canonical example of an
-owned box. Much like an unboxed value, an owned box has a single owner and is
-therefore limited to expressing a tree-like data structure.
-
-Consider an instance of our `List` type:
-
-~~~
-# enum List {
-#     Cons(u32, Box<List>),
-#     Nil
-# }
-let list = Cons(1, box Cons(2, box Cons(3, box Nil)));
-~~~
-
-It represents an owned tree of values, inheriting mutability down the tree and
-being destroyed along with the owner. Since the `list` variable above is
-immutable, the whole list is immutable. The memory allocation itself is the
-box, while the owner holds onto a pointer to it:
-
-~~~text
-            List box            List box            List box          List box
-        +--------------+    +--------------+    +--------------+    +----------+
-list -> | Cons | 1 |   | -> | Cons | 2 |   | -> | Cons | 3 |   | -> | Nil      |
-        +--------------+    +--------------+    +--------------+    +----------+
-~~~
-
-> *Note:* the above diagram shows the logical contents of the enum. The actual
-> memory layout of the enum may vary. For example, for the `List` enum shown
-> above, Rust guarantees that there will be no enum tag field in the actual
-> structure. See the language reference for more details.
-
-An owned box is a common example of a type with a destructor. The allocated
-memory is cleaned up when the box is destroyed.
-
-## Move semantics
-
-Rust uses a shallow copy for parameter passing, assignment and returning from
-functions. Passing around the `List` will copy only as deep as the pointer to
-the box rather than doing an implicit heap allocation.
-
-~~~
-# enum List {
-#     Cons(u32, Box<List>),
-#     Nil
-# }
-let xs = Cons(1, box Cons(2, box Cons(3, box Nil)));
-let ys = xs; // copies `Cons(u32, pointer)` shallowly
-~~~
-
-> *Note:* Names like `xs` and `ys` are a naming
-> convention for collection-like data structures
-> (like our `List`). These collections are given 
-> names appended with 's' to signify plurality, 
-> i.e. that the data structure stores multiple 
-> elements.  For example, `xs` in this case can 
-> be read as "a list of ex-es", where "x" here 
-> are elements of type `u32`.
-
-
-Rust will consider a shallow copy of a type with a destructor like `List` to
-*move ownership* of the value. After a value has been moved, the source
-location cannot be used unless it is reinitialized.
-
-~~~
-# enum List {
-#     Cons(u32, Box<List>),
-#     Nil
-# }
-let mut xs = Nil;
-let ys = xs;
-
-// attempting to use `xs` will result in an error here
-
-xs = Nil;
-
-// `xs` can be used again
-~~~
-
-A destructor call will only occur for a variable that has not been moved from,
-as it is only called a single time.
-
-
-Avoiding a move can be done with the library-defined `clone` method:
-
-~~~~
-let x = box 5i;
-let y = x.clone(); // `y` is a newly allocated box
-let z = x; // no new memory allocated, `x` can no longer be used
-~~~~
-
-The `clone` method is provided by the `Clone` trait, and can be derived for
-our `List` type. Traits will be explained in detail [later](#traits).
-
-~~~{.ignore}
-#[deriving(Clone)]
-enum List {
-    Cons(u32, Box<List>),
-    Nil
-}
-
-let x = Cons(5, box Nil);
-let y = x.clone();
-
-// `x` can still be used!
-
-let z = x;
-
-// and now, it can no longer be used since it has been moved
-~~~
-
-The mutability of a value may be changed by moving it to a new owner:
-
-~~~~
-let r = box 13i;
-let mut s = r; // box becomes mutable
-*s += 1;
-let t = s; // box becomes immutable
-~~~~
-
-A simple way to define a function prepending to the `List` type is to take
-advantage of moves:
-
-~~~
-enum List {
-    Cons(u32, Box<List>),
-    Nil
-}
-
-fn prepend(xs: List, value: u32) -> List {
-    Cons(value, box xs)
-}
-
-let mut xs = Nil;
-xs = prepend(xs, 1);
-xs = prepend(xs, 2);
-xs = prepend(xs, 3);
-~~~
-
-However, this is not a very flexible definition of `prepend` as it requires
-ownership of a list to be passed in rather than just mutating it in-place.
-
-## References
-
-The obvious signature for a `List` equality comparison is the following:
-
-~~~{.ignore}
-fn eq(xs: List, ys: List) -> bool { /* ... */ }
-~~~
-
-However, this will cause both lists to be moved into the function. Ownership
-isn't required to compare the lists, so the function should take *references*
-(&T) instead.
-
-~~~{.ignore}
-fn eq(xs: &List, ys: &List) -> bool { /* ... */ }
-~~~
-
-A reference is a *non-owning* view of a value. A reference can be obtained with the `&` (address-of)
-operator. It can be dereferenced by using the `*` operator. In a pattern, such as `match` expression
-branches, the `ref` keyword can be used to bind to a variable name by-reference rather than
-by-value. A recursive definition of equality using references is as follows:
-
-~~~
-# enum List {
-#     Cons(u32, Box<List>),
-#     Nil
-# }
-fn eq(xs: &List, ys: &List) -> bool {
-    // Match on the next node in both lists.
-    match (xs, ys) {
-        // If we have reached the end of both lists, they are equal.
-        (&Nil, &Nil) => true,
-        // If the current elements of both lists are equal, keep going.
-        (&Cons(x, box ref next_xs), &Cons(y, box ref next_ys))
-                if x == y => eq(next_xs, next_ys),
-        // If the current elements are not equal, the lists are not equal.
-        _ => false
-    }
-}
-
-let xs = Cons(5, box Cons(10, box Nil));
-let ys = Cons(5, box Cons(10, box Nil));
-assert!(eq(&xs, &ys));
-~~~
-
-> *Note:* Rust doesn't guarantee [tail-call](http://en.wikipedia.org/wiki/Tail_call) optimization,
-> but LLVM is able to handle a simple case like this with optimizations enabled.
-
-## Lists of other types
-
-Our `List` type is currently always a list of 32-bit unsigned integers. By
-leveraging Rust's support for generics, it can be extended to work for any
-element type.
-
-The `u32` in the previous definition can be substituted with a type parameter:
-
-> *Note:* The following code introduces generics, which are explained in a
-> [dedicated section](#generics).
-
-~~~
-enum List<T> {
-    Cons(T, Box<List<T>>),
-    Nil
-}
-~~~
-
-The old `List` of `u32` is now available as `List<u32>`. The `prepend`
-definition has to be updated too:
-
-~~~
-# enum List<T> {
-#     Cons(T, Box<List<T>>),
-#     Nil
-# }
-fn prepend<T>(xs: List<T>, value: T) -> List<T> {
-    Cons(value, box xs)
-}
-~~~
-
-Generic functions and types like this are equivalent to defining specialized
-versions for each set of type parameters.
-
-Using the generic `List<T>` works much like before, thanks to type inference:
-
-~~~
-# enum List<T> {
-#     Cons(T, Box<List<T>>),
-#     Nil
-# }
-# fn prepend<T>(xs: List<T>, value: T) -> List<T> {
-#     Cons(value, box xs)
-# }
-let mut xs = Nil; // Unknown type! This is a `List<T>`, but `T` can be anything.
-xs = prepend(xs, 10i); // Here the compiler infers `xs`'s type as `List<int>`.
-xs = prepend(xs, 15i);
-xs = prepend(xs, 20i);
-~~~
-
-The code sample above demonstrates type inference making most type annotations optional. It is
-equivalent to the following type-annotated code:
-
-~~~
-# enum List<T> {
-#     Cons(T, Box<List<T>>),
-#     Nil
-# }
-# fn prepend<T>(xs: List<T>, value: T) -> List<T> {
-#     Cons(value, box xs)
-# }
-let mut xs: List<int> = Nil::<int>;
-xs = prepend::<int>(xs, 10);
-xs = prepend::<int>(xs, 15);
-xs = prepend::<int>(xs, 20);
-~~~
-
-In declarations, the language uses `Type<T, U, V>` to describe a list of type
-parameters, but expressions use `identifier::<T, U, V>`, to disambiguate the
-`<` operator.
-
-## Defining list equality with generics
-
-Generic functions are type-checked from the definition, so any necessary properties of the type must
-be specified up-front. Our previous definition of list equality relied on the element type having
-the `==` operator available, and took advantage of the lack of a destructor on `u32` to copy it
-without a move of ownership.
-
-We can add a *trait bound* on the `PartialEq` trait to require that the type implement the `==` operator.
-Two more `ref` annotations need to be added to avoid attempting to move out the element types:
-
-~~~
-# enum List<T> {
-#     Cons(T, Box<List<T>>),
-#     Nil
-# }
-fn eq<T: PartialEq>(xs: &List<T>, ys: &List<T>) -> bool {
-    // Match on the next node in both lists.
-    match (xs, ys) {
-        // If we have reached the end of both lists, they are equal.
-        (&Nil, &Nil) => true,
-        // If the current elements of both lists are equal, keep going.
-        (&Cons(ref x, box ref next_xs), &Cons(ref y, box ref next_ys))
-                if x == y => eq(next_xs, next_ys),
-        // If the current elements are not equal, the lists are not equal.
-        _ => false
-    }
-}
-
-let xs = Cons('c', box Cons('a', box Cons('t', box Nil)));
-let ys = Cons('c', box Cons('a', box Cons('t', box Nil)));
-assert!(eq(&xs, &ys));
-~~~
-
-This would be a good opportunity to implement the `PartialEq` trait for our list type, making the `==` and
-`!=` operators available. We'll need to provide an `impl` for the `PartialEq` trait and a definition of the
-`eq` method. In a method, the `self` parameter refers to an instance of the type we're implementing
-on.
-
-~~~
-# enum List<T> {
-#     Cons(T, Box<List<T>>),
-#     Nil
-# }
-impl<T: PartialEq> PartialEq for List<T> {
-    fn eq(&self, ys: &List<T>) -> bool {
-        // Match on the next node in both lists.
-        match (self, ys) {
-            // If we have reached the end of both lists, they are equal.
-            (&Nil, &Nil) => true,
-            // If the current elements of both lists are equal, keep going.
-            (&Cons(ref x, box ref next_xs), &Cons(ref y, box ref next_ys))
-                    if x == y => next_xs == next_ys,
-            // If the current elements are not equal, the lists are not equal.
-            _ => false
-        }
-    }
-}
-
-let xs = Cons(5i, box Cons(10i, box Nil));
-let ys = Cons(5i, box Cons(10i, box Nil));
-// The methods below are part of the PartialEq trait,
-// which we implemented on our linked list.
-assert!(xs.eq(&ys));
-assert!(!xs.ne(&ys));
-
-// The PartialEq trait also allows us to use the shorthand infix operators.
-assert!(xs == ys);    // `xs == ys` is short for `xs.eq(&ys)`
-assert!(!(xs != ys)); // `xs != ys` is short for `xs.ne(&ys)`
-~~~
-
-# More on boxes
-
-The most common use case for owned boxes is creating recursive data structures
-like a binary search tree. Rust's trait-based generics system (covered later in
-the tutorial) is usually used for static dispatch, but also provides dynamic
-dispatch via boxing. Values of different types may have different sizes, but a
-box is able to *erase* the difference via the layer of indirection they
-provide.
-
-In uncommon cases, the indirection can provide a performance gain or memory
-reduction by making values smaller. However, unboxed values should almost
-always be preferred when they are usable.
-
-Note that returning large unboxed values via boxes is unnecessary. A large
-value is returned via a hidden output parameter, and the decision on where to
-place the return value should be left to the caller:
-
-~~~~
-fn foo() -> (u64, u64, u64, u64, u64, u64) {
-    (5, 5, 5, 5, 5, 5)
-}
-
-let x = box foo(); // allocates a box, and writes the integers directly to it
-~~~~
-
-Beyond the properties granted by the size, an owned box behaves as a regular
-value by inheriting the mutability and lifetime of the owner:
-
-~~~~
-let x = 5i; // immutable
-let mut y = 5i; // mutable
-y += 2;
-
-let x = box 5i; // immutable
-let mut y = box 5i; // mutable
-*y += 2; // the `*` operator is needed to access the contained value
-~~~~
-
-# References
-
-In contrast with
-owned boxes, where the holder of an owned box is the owner of the pointed-to
-memory, references never imply ownership - they are "borrowed".
-You can borrow a reference to
-any object, and the compiler verifies that it cannot outlive the lifetime of
-the object.
-
-As an example, consider a simple struct type, `Point`:
-
-~~~
-struct Point {
-    x: f64,
-    y: f64
-}
-~~~
-
-We can use this simple definition to allocate points in many different
-ways. For example, in this code, each of these local variables
-contains a point, but allocated in a different location:
-
-~~~
-# struct Point { x: f64, y: f64 }
-let on_the_stack :     Point  =     Point { x: 3.0, y: 4.0 };
-let on_the_heap  : Box<Point> = box Point { x: 7.0, y: 9.0 };
-~~~
-
-Suppose we want to write a procedure that computes the distance
-between any two points, no matter where they are stored. One option is
-to define a function that takes two arguments of type point—that is,
-it takes the points by value. But this will cause the points to be
-copied when we call the function. For points, this is probably not so
-bad, but often copies are expensive. So we’d like to define a function
-that takes the points by pointer. We can use references to do this:
-
-~~~
-# struct Point { x: f64, y: f64 }
-fn compute_distance(p1: &Point, p2: &Point) -> f64 {
-    let x_d = p1.x - p2.x;
-    let y_d = p1.y - p2.y;
-    (x_d * x_d + y_d * y_d).sqrt()
-}
-~~~
-
-Now we can call `compute_distance()` in various ways:
-
-~~~
-# struct Point{ x: f64, y: f64 };
-# let on_the_stack :     Point  =     Point { x: 3.0, y: 4.0 };
-# let on_the_heap  : Box<Point> = box Point { x: 7.0, y: 9.0 };
-# fn compute_distance(p1: &Point, p2: &Point) -> f64 { 0.0 }
-compute_distance(&on_the_stack, &*on_the_heap);
-~~~
-
-Here the `&` operator is used to take the address of the variable
-`on_the_stack`; this is because `on_the_stack` has the type `Point`
-(that is, a struct value) and we have to take its address to get a
-reference. We also call this _borrowing_ the local variable
-`on_the_stack`, because we are creating an alias: that is, another
-route to the same data.
-
-Likewise, in the case of `on_the_heap`,
-the `&` operator is used in conjunction with the `*` operator
-to take a reference to the contents of the box.
-
-Whenever a value is borrowed, there are some limitations on what you
-can do with the original. For example, if the contents of a variable
-have been lent out, you cannot send that variable to another task, nor
-will you be permitted to take actions that might cause the borrowed
-value to be freed or to change its type. This rule should make
-intuitive sense: you must wait for a borrowed value to be returned
-(that is, for the reference to go out of scope) before you can
-make full use of it again.
-
-For a more in-depth explanation of references and lifetimes, read the
-[references and lifetimes guide][lifetimes].
-
-## Freezing
-
-Lending an &-pointer to an object freezes the pointed-to object and prevents
-mutation—even if the object was declared as `mut`.  `Freeze` objects have
-freezing enforced statically at compile-time. An example of a non-`Freeze` type
-is [`RefCell<T>`][refcell].
-
-~~~~
-let mut x = 5i;
-{
-    let y = &x; // `x` is now frozen. It cannot be modified or re-assigned.
-}
-// `x` is now unfrozen again
-# x = 3;
-~~~~
-
-[refcell]: http://doc.rust-lang.org/std/cell/struct.RefCell.html
-
-# Dereferencing pointers
-
-Rust uses the unary star operator (`*`) to access the contents of a
-box or pointer, similarly to C.
-
-~~~
-let owned = box 10i;
-let borrowed = &20i;
-
-let sum = *owned + *borrowed;
-~~~
-
-Dereferenced mutable pointers may appear on the left hand side of
-assignments. Such an assignment modifies the value that the pointer
-points to.
-
-~~~
-let mut owned = box 10i;
-
-let mut value = 20i;
-let borrowed = &mut value;
-
-*owned = *borrowed + 100;
-*borrowed = *owned + 1000;
-~~~
-
-Pointers have high operator precedence, but lower precedence than the
-dot operator used for field and method access. This precedence order
-can sometimes make code awkward and parenthesis-filled.
-
-~~~
-# struct Point { x: f64, y: f64 }
-# enum Shape { Rectangle(Point, Point) }
-# impl Shape { fn area(&self) -> int { 0 } }
-let start = box Point { x: 10.0, y: 20.0 };
-let end = box Point { x: (*start).x + 100.0, y: (*start).y + 100.0 };
-let rect = &Rectangle(*start, *end);
-let area = (*rect).area();
-~~~
-
-To combat this ugliness the dot operator applies _automatic pointer
-dereferencing_ to the receiver (the value on the left-hand side of the
-dot), so in most cases, explicitly dereferencing the receiver is not necessary.
-
-~~~
-# struct Point { x: f64, y: f64 }
-# enum Shape { Rectangle(Point, Point) }
-# impl Shape { fn area(&self) -> int { 0 } }
-let start = box Point { x: 10.0, y: 20.0 };
-let end = box Point { x: start.x + 100.0, y: start.y + 100.0 };
-let rect = &Rectangle(*start, *end);
-let area = rect.area();
-~~~
-
-You can write an expression that dereferences any number of pointers
-automatically. For example, if you feel inclined, you could write
-something silly like
-
-~~~
-# struct Point { x: f64, y: f64 }
-let point = &box Point { x: 10.0, y: 20.0 };
-println!("{:f}", point.x);
-~~~
-
-The indexing operator (`[]`) also auto-dereferences.
-
-# Vectors and strings
-
-A vector is a contiguous block of memory containing zero or more values of the
-same type. Rust also supports vector reference types, called slices, which are
-a view into a block of memory represented as a pointer and a length.
-
-Strings are represented as vectors of `u8`, with the guarantee of containing a
-valid UTF-8 sequence.
-
-Fixed-size vectors are an unboxed block of memory, with the element length as
-part of the type. A fixed-size vector owns the elements it contains, so the
-elements are mutable if the vector is mutable. Fixed-size strings do not exist.
-
-~~~
-// A fixed-size vector
-let numbers = [1i, 2, 3];
-let more_numbers = numbers;
-
-// The type of a fixed-size vector is written as `[Type, ..length]`
-let five_zeroes: [int, ..5] = [0, ..5];
-~~~
-
-A unique vector is dynamically sized, and has a destructor to clean up
-allocated memory on the heap. A unique vector owns the elements it contains, so
-the elements are mutable if the vector is mutable.
-
-~~~
-use std::string::String;
-
-// A dynamically sized vector (unique vector)
-let mut numbers = vec![1i, 2, 3];
-numbers.push(4);
-numbers.push(5);
-
-// The type of a unique vector is written as `Vec<int>`
-let more_numbers: Vec<int> = numbers.move_iter().map(|i| i+1).collect();
-
-// The original `numbers` value can no longer be used, due to move semantics.
-
-let mut string = String::from_str("fo");
-string.push_char('o');
-~~~
-
-Slices are similar to fixed-size vectors, but the length is not part of the
-type. They simply point into a block of memory and do not have ownership over
-the elements.
-
-~~~
-// A slice
-let xs = &[1, 2, 3];
-
-// Slices have their type written as `&[int]`
-let ys: &[int] = xs;
-
-// Other vector types coerce to slices
-let three = [1, 2, 3];
-let zs: &[int] = three;
-
-// An unadorned string literal is an immutable string slice
-let string = "foobar";
-
-// A string slice type is written as `&str`
-let view: &str = string.slice(0, 3);
-~~~
-
-Square brackets denote indexing into a slice or fixed-size vector:
-
-~~~~
-let crayons: [&str, ..3] = ["BananaMania", "Beaver", "Bittersweet"];
-println!("Crayon 2 is '{}'", crayons[2]);
-~~~~
-
-Mutable slices also exist, just as there are mutable references. However, there
-are no mutable string slices. Strings are a multi-byte encoding (UTF-8) of
-Unicode code points, so they cannot be freely mutated without the ability to
-alter the length.
-
-~~~
-let mut xs = [1i, 2i, 3i];
-let view = xs.mut_slice(0, 2);
-view[0] = 5;
-
-// The type of a mutable slice is written as `&mut [T]`
-let ys: &mut [int] = &mut [1i, 2i, 3i];
-~~~
-
-A slice or fixed-size vector can be destructured using pattern matching:
-
-~~~~
-let numbers: &[int] = &[1, 2, 3];
-let score = match numbers {
-    [] => 0,
-    [a] => a * 10,
-    [a, b] => a * 6 + b * 4,
-    [a, b, c, rest..] => a * 5 + b * 3 + c * 2 + rest.len() as int
-};
-~~~~
-
-Both vectors and strings support a number of useful [methods](#methods),
-defined in [`std::vec`], [`std::slice`], and [`std::str`].
-
-[`std::vec`]: std/vec/index.html
-[`std::slice`]: std/slice/index.html
-[`std::str`]: std/str/index.html
-
-# Ownership escape hatches
-
-Ownership can cleanly describe tree-like data structures, and references provide non-owning pointers. However, more flexibility is often desired and Rust provides ways to escape from strict
-single parent ownership.
-
-The standard library provides the `std::rc::Rc` pointer type to express *shared ownership* over a
-reference counted box. As soon as all of the `Rc` pointers go out of scope, the box and the
-contained value are destroyed.
-
-~~~
-use std::rc::Rc;
-
-// A fixed-size array allocated in a reference-counted box
-let x = Rc::new([1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
-let y = x.clone(); // a new owner
-let z = x; // this moves `x` into `z`, rather than creating a new owner
-
-assert!(*z == [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
-
-// the variable is mutable, but not the contents of the box
-let mut a = Rc::new([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
-a = z;
-~~~
-
-A garbage collected pointer is provided via `std::gc::Gc`, with a task-local garbage collector
-having ownership of the box. It allows the creation of cycles, and the individual `Gc` pointers do
-not have a destructor.
-
-~~~
-use std::gc::GC;
-
-// A fixed-size array allocated in a garbage-collected box
-let x = box(GC) [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10];
-let y = x; // does not perform a move, unlike with `Rc`
-let z = x;
-
-assert!(*z == [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
-~~~
-
-With shared ownership, mutability cannot be inherited so the boxes are always immutable. However,
-it's possible to use *dynamic* mutability via types like `std::cell::Cell` where freezing is handled
-via dynamic checks and can fail at runtime.
-
-The `Rc` and `Gc` types are not sendable, so they cannot be used to share memory between tasks. Safe
-immutable and mutable shared memory is provided by the `sync::arc` module.
-
-> *Note:* See a [later chapter](#traits) for a discussion about `Send` and sendable types.
-
-# Closures
-
-Named functions, like those we've seen so far, may not refer to local
-variables declared outside the function: they do not close over their
-environment (sometimes referred to as "capturing" variables in their
-environment). For example, you couldn't write the following:
-
-~~~~ {.ignore}
-let x = 3;
-
-// `fun` cannot refer to `x`
-fn fun() -> () { println!("{}", x); }
-~~~~
-
-A _closure_ does support accessing the enclosing scope; below we will create
-2 _closures_ (nameless functions). Compare how `||` replaces `()` and how
-they try to access `x`:
-
-~~~~ {.ignore}
-let x = 3;
-
-// `fun` is an invalid definition
-fn  fun       () -> () { println!("{}", x) }  // cannot capture from enclosing scope
-let closure = || -> () { println!("{}", x) }; // can capture from enclosing scope
-
-// `fun_arg` is an invalid definition
-fn  fun_arg       (arg: int) -> () { println!("{}", arg + x) }  // cannot capture
-let closure_arg = |arg: int| -> () { println!("{}", arg + x) }; // can capture
-//                      ^
-// Requires a type because the implementation needs to know which `+` to use.
-// In the future, the implementation may not need the help.
-
-fun();          // Still won't work
-closure();      // Prints: 3
-
-fun_arg(7);     // Still won't work
-closure_arg(7); // Prints: 10
-~~~~
-
-Closures begin with the argument list between vertical bars and are followed by
-a single expression. Remember that a block, `{ <expr1>; <expr2>; ... }`, is
-considered a single expression: it evaluates to the result of the last
-expression it contains if that expression is not followed by a semicolon,
-otherwise the block evaluates to `()`, the unit value.
-
-In general, return types and all argument types must be specified
-explicitly for function definitions.  (As previously mentioned in the
-[Functions section](#functions), omitting the return type from a
-function declaration is synonymous with an explicit declaration of
-return type unit, `()`.)
-
-~~~~ {.ignore}
-fn  fun   (x: int)         { println!("{}", x) } // this is same as saying `-> ()`
-fn  square(x: int) -> uint { (x * x) as uint }   // other return types are explicit
-
-// Error: mismatched types: expected `()` but found `uint`
-fn  badfun(x: int)         { (x * x) as uint }
-~~~~
-
-On the other hand, the compiler can usually infer both the argument
-and return types for a closure expression; therefore they are often
-omitted, since both a human reader and the compiler can deduce the
-types from the immediate context.  This is in contrast to function
-declarations, which require types to be specified and are not subject
-to type inference. Compare:
-
-~~~~ {.ignore}
-// `fun` as a function declaration cannot infer the type of `x`, so it must be provided
-fn  fun       (x: int) { println!("{}", x) }
-let closure = |x     | { println!("{}", x) }; // infers `x: int`, return type `()`
-
-// For closures, omitting a return type is *not* synonymous with `-> ()`
-let add_3   = |y     | { 3i + y }; // infers `y: int`, return type `int`.
-
-fun(10);            // Prints 10
-closure(20);        // Prints 20
-closure(add_3(30)); // Prints 33
-
-fun("String"); // Error: mismatched types
-
-// Error: mismatched types
-// inference already assigned `closure` the type `|int| -> ()`
-closure("String");
-~~~~
-
-In cases where the compiler needs assistance, the arguments and return
-types may be annotated on closures, using the same notation as shown
-earlier.  In the example below, since different types provide an
-implementation for the operator `*`, the argument type for the `x`
-parameter must be explicitly provided.
-
-~~~~{.ignore}
-// Error: the type of `x` must be known to be used with `x * x`
-let square = |x     | -> uint { (x * x) as uint };
-~~~~
-
-In the corrected version, the argument type is explicitly annotated,
-while the return type can still be inferred.
-
-~~~~
-let square_explicit = |x: int| -> uint { (x * x) as uint };
-let square_infer    = |x: int|         { (x * x) as uint };
-
-println!("{}", square_explicit(20));  // 400
-println!("{}", square_infer(-20));    // 400
-~~~~
-
-There are several forms of closure, each with its own role. The most
-common, called a _stack closure_, has type `||` and can directly
-access local variables in the enclosing scope.
-
-~~~~
-let mut max = 0;
-let f = |x: int| if x > max { max = x };
-for x in [1, 2, 3].iter() {
-    f(*x);
-}
-~~~~
-
-Stack closures are very efficient because their environment is
-allocated on the call stack and refers by pointer to captured
-locals. To ensure that stack closures never outlive the local
-variables to which they refer, stack closures are not
-first-class. That is, they can only be used in argument position; they
-cannot be stored in data structures or returned from
-functions. Despite these limitations, stack closures are used
-pervasively in Rust code.
-
-## Owned closures
-
-Owned closures, written `proc`,
-hold on to things that can safely be sent between
-processes. They copy the values they close over,
-but they also own them: that is, no other code can access
-them. Owned closures are used in concurrent code, particularly
-for spawning [tasks][tasks].
-
-Closures can be used to spawn tasks.
-A practical example of this pattern is found when using the `spawn` function,
-which starts a new task.
-
-~~~~
-use std::task::spawn;
-
-// proc is the closure which will be spawned.
-spawn(proc() {
-    println!("I'm a new task")
-});
-~~~~
-
-## Closure compatibility
-
-Rust closures have a convenient subtyping property: you can pass any kind of
-closure (as long as the arguments and return types match) to functions
-that expect a `||`. Thus, when writing a higher-order function that
-only calls its function argument, and does nothing else with it, you
-should almost always declare the type of that argument as `||`. That way,
-callers may pass any kind of closure.
-
-~~~~
-fn call_twice(f: ||) { f(); f(); }
-let closure = || { "I'm a closure, and it doesn't matter what type I am"; };
-fn function() { "I'm a normal function"; }
-call_twice(closure);
-call_twice(function);
-~~~~
-
-> *Note:* Both the syntax and the semantics will be changing
-> in small ways. At the moment they can be unsound in some
-> scenarios, particularly with non-copyable types.
-
-# Methods
-
-Methods are like functions except that they always begin with a special argument,
-called `self`,
-which has the type of the method's receiver. The
-`self` argument is like `this` in C++ and many other languages.
-Methods are called with dot notation, as in `my_vec.len()`.
-
-_Implementations_, written with the `impl` keyword, can define
-methods on most Rust types, including structs and enums.
-As an example, let's define a `draw` method on our `Shape` enum.
-
-~~~
-# fn draw_circle(p: Point, f: f64) { }
-# fn draw_rectangle(p: Point, p: Point) { }
-struct Point {
-    x: f64,
-    y: f64
-}
-
-enum Shape {
-    Circle(Point, f64),
-    Rectangle(Point, Point)
-}
-
-impl Shape {
-    fn draw(&self) {
-        match *self {
-            Circle(p, f) => draw_circle(p, f),
-            Rectangle(p1, p2) => draw_rectangle(p1, p2)
-        }
-    }
-}
-
-let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
-s.draw();
-~~~
-
-This defines an _implementation_ for `Shape` containing a single
-method, `draw`. In most respects the `draw` method is defined
-like any other function, except for the name `self`.
-
-The type of `self` is the type on which the method is implemented,
-or a pointer thereof. As an argument it is written either `self`,
-`&self`, or `self: TYPE`.
-A caller must in turn have a compatible pointer type to call the method.
-
-~~~
-# fn draw_circle(p: Point, f: f64) { }
-# fn draw_rectangle(p: Point, p: Point) { }
-# struct Point { x: f64, y: f64 }
-# enum Shape {
-#     Circle(Point, f64),
-#     Rectangle(Point, Point)
-# }
-impl Shape {
-    fn draw_reference(&self) { /* ... */ }
-    fn draw_owned(self: Box<Shape>) { /* ... */ }
-    fn draw_value(self) { /* ... */ }
-}
-
-let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
-
-(&s).draw_reference();
-(box s).draw_owned();
-s.draw_value();
-~~~
-
-Methods typically take a reference self type,
-so the compiler will go to great lengths to convert a callee
-to a reference.
-
-~~~
-# fn draw_circle(p: Point, f: f64) { }
-# fn draw_rectangle(p: Point, p: Point) { }
-# struct Point { x: f64, y: f64 }
-# enum Shape {
-#     Circle(Point, f64),
-#     Rectangle(Point, Point)
-# }
-# impl Shape {
-#    fn draw_reference(&self) { /* ... */ }
-#    fn draw_owned(self: Box<Shape>) { /* ... */ }
-#    fn draw_value(self) { /* ... */ }
-# }
-# let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
-// As with typical function arguments, owned pointers
-// are automatically converted to references
-
-(box s).draw_reference();
-
-// Unlike typical function arguments, the self value will
-// automatically be referenced ...
-s.draw_reference();
-
-// ... and dereferenced
-(& &s).draw_reference();
-
-// ... and dereferenced and borrowed
-(&box s).draw_reference();
-~~~
-
-Implementations may also define standalone (sometimes called "static")
-methods. The absence of a `self` parameter distinguishes such methods.
-These methods are the preferred way to define constructor functions.
-
-~~~~ {.ignore}
-impl Circle {
-    fn area(&self) -> f64 { /* ... */ }
-    fn new(area: f64) -> Circle { /* ... */ }
-}
-~~~~
-
-To call such a method, just prefix it with the type name and a double colon:
-
-~~~~
-use std::f64::consts::PI;
-struct Circle { radius: f64 }
-impl Circle {
-    fn new(area: f64) -> Circle { Circle { radius: (area / PI).sqrt() } }
-}
-let c = Circle::new(42.5);
-~~~~
-
-# Generics
-
-Throughout this tutorial, we've been defining functions that act only
-on specific data types. With type parameters we can also define
-functions whose arguments have generic types, and which can be invoked
-with a variety of types. Consider a generic `map` function, which
-takes a function `function` and a vector `vector` and returns a new
-vector consisting of the result of applying `function` to each element
-of `vector`:
-
-~~~~
-fn map<T, U>(vector: &[T], function: |v: &T| -> U) -> Vec<U> {
-    let mut accumulator = Vec::new();
-    for element in vector.iter() {
-        accumulator.push(function(element));
-    }
-    return accumulator;
-}
-~~~~
-
-When defined with type parameters, as denoted by `<T, U>`, this
-function can be applied to any type of vector, as long as the type of
-`function`'s argument and the type of the vector's contents agree with
-each other.
-
-Inside a generic function, the names of the type parameters
-(capitalized by convention) stand for opaque types. All you can do
-with instances of these types is pass them around: you can't apply any
-operations to them or pattern-match on them. Note that instances of
-generic types are often passed by pointer. For example, the parameter
-`function()` is supplied with a pointer to a value of type `T` and not
-a value of type `T` itself. This ensures that the function works with
-the broadest set of types possible, since some types are expensive or
-illegal to copy and pass by value.
-
-Generic `type`, `struct`, and `enum` declarations follow the same pattern:
-
-~~~~
-type Set<T> = std::collections::HashMap<T, ()>;
-
-struct Stack<T> {
-    elements: Vec<T>
-}
-
-enum Option<T> {
-    Some(T),
-    None
-}
-# fn main() {}
-~~~~
-
-These declarations can be instantiated to valid types like `Set<int>`,
-`Stack<int>`, and `Option<int>`.
-
-The last type in that example, `Option`, appears frequently in Rust code.
-Because Rust does not have null pointers (except in unsafe code), we need
-another way to write a function whose result isn't defined on every possible
-combination of arguments of the appropriate types. The usual way is to write
-a function that returns `Option<T>` instead of `T`.
-
-~~~~
-# struct Point { x: f64, y: f64 }
-# enum Shape { Circle(Point, f64), Rectangle(Point, Point) }
-fn radius(shape: Shape) -> Option<f64> {
-    match shape {
-        Circle(_, radius) => Some(radius),
-        Rectangle(..)     => None
-    }
-}
-~~~~
-
-The Rust compiler compiles generic functions very efficiently by
-*monomorphizing* them. *Monomorphization* is a fancy name for a simple
-idea: generate a separate copy of each generic function at each call site,
-a copy that is specialized to the argument
-types and can thus be optimized specifically for them. In this
-respect, Rust's generics have similar performance characteristics to
-C++ templates.
-
-## Traits
-
-Within a generic function—that is, a function parameterized by a
-type parameter, say, `T`—the operations we can do on arguments of
-type `T` are quite limited.  After all, since we don't know what type
-`T` will be instantiated with, we can't safely modify or query values
-of type `T`.  This is where _traits_ come into play. Traits are Rust's
-most powerful tool for writing polymorphic code. Java developers will
-see them as similar to Java interfaces, and Haskellers will notice
-their similarities to type classes. Rust's traits give us a way to
-express *bounded polymorphism*: by limiting the set of possible types
-that a type parameter could refer to, they expand the number of
-operations we can safely perform on arguments of that type.
-
-As motivation, let us consider copying of values in Rust.  The `clone`
-method is not defined for values of every type.  One reason is
-user-defined destructors: copying a value of a type that has a
-destructor could result in the destructor running multiple times.
-Therefore, values of types that have destructors cannot be copied
-unless we explicitly implement `clone` for them.
-
-This complicates handling of generic functions.
-If we have a function with a type parameter `T`,
-can we copy values of type `T` inside that function?
-In Rust, we can't,
-and if we try to run the following code the compiler will complain.
-
-~~~~ {.ignore}
-// This does not compile
-fn head_bad<T>(v: &[T]) -> T {
-    v[0] // error: copying a non-copyable value
-}
-~~~~
-
-However, we can tell the compiler
-that the `head` function is only for copyable types.
-In Rust, copyable types are those that _implement the `Clone` trait_.
-We can then explicitly create a second copy of the value we are returning
-by calling the `clone` method:
-
-~~~~
-// This does
-fn head<T: Clone>(v: &[T]) -> T {
-    v[0].clone()
-}
-~~~~
-
-The bounded type parameter `T: Clone` says that `head`
-can be called on an argument of type `&[T]` for any `T`,
-so long as there is an implementation of the
-`Clone` trait for `T`.
-When instantiating a generic function,
-we can only instantiate it with types
-that implement the correct trait,
-so we could not apply `head` to a vector whose elements are of some type
-that does not implement `Clone`.
-
-While most traits can be defined and implemented by user code,
-three traits are automatically derived and implemented
-for all applicable types by the compiler,
-and may not be overridden:
-
-* `Send` - Sendable types.
-Types are sendable
-unless they contain references.
-
-* `Sync` - Types that are *threadsafe*.
-These are types that are safe to be used across several threads with access to
-a `&T` pointer. `Mutex<T>` is an example of a *sharable* type with internal mutable data.
-
-* `'static` - Non-borrowed types.
-These are types that do not contain any data whose lifetime is bound to
-a particular stack frame. These are types that do not contain any
-references, or types where the only contained references
-have the `'static` lifetime. (For more on named lifetimes and their uses,
-see the [references and lifetimes guide][lifetimes].)
-
-> *Note:* These built-in traits were referred to as 'kinds' in earlier
-> iterations of the language, and often still are.
-
-Additionally, the `Drop` trait is used to define destructors. This
-trait provides one method called `drop`, which is automatically
-called when a value of the type that implements this trait is
-destroyed, either because the value went out of scope or because the
-garbage collector reclaimed it.
-
-~~~
-struct TimeBomb {
-    explosivity: uint
-}
-
-impl Drop for TimeBomb {
-    fn drop(&mut self) {
-        for _ in range(0, self.explosivity) {
-            println!("blam!");
-        }
-    }
-}
-~~~
-
-It is illegal to call `drop` directly. Only code inserted by the compiler
-may call it.
-
-## Declaring and implementing traits
-
-At its simplest, a trait is a set of zero or more _method signatures_.
-For example, we could declare the trait
-`Printable` for things that can be printed to the console,
-with a single method signature:
-
-~~~~
-trait Printable {
-    fn print(&self);
-}
-~~~~
-
-We say that the `Printable` trait _provides_ a `print` method with the
-given signature.  This means that we can call `print` on an argument
-of any type that implements the `Printable` trait.
-
-Rust's built-in `Send` and `Sync` types are examples of traits that
-don't provide any methods.
-
-Traits may be implemented for specific types with [impls]. An impl for
-a particular trait gives an implementation of the methods that
-trait provides.  For instance, the following impls of
-`Printable` for `int` and `String` give implementations of the `print`
-method.
-
-[impls]: #methods
-
-~~~~
-# trait Printable { fn print(&self); }
-impl Printable for int {
-    fn print(&self) { println!("{}", *self) }
-}
-
-impl Printable for String {
-    fn print(&self) { println!("{}", *self) }
-}
-
-# 1.print();
-# ("foo".to_string()).print();
-~~~~
-
-Methods defined in an impl for a trait may be called just like
-any other method, using dot notation, as in `1.print()`.
-
-## Default method implementations in trait definitions
-
-Sometimes, a method that a trait provides will have the same
-implementation for most or all of the types that implement that trait.
-For instance, suppose that we wanted `bool`s and `f32`s to be
-printable, and that we wanted the implementation of `print` for those
-types to be exactly as it is for `int`, above:
-
-~~~~
-# trait Printable { fn print(&self); }
-impl Printable for f32 {
-    fn print(&self) { println!("{}", *self) }
-}
-
-impl Printable for bool {
-    fn print(&self) { println!("{}", *self) }
-}
-
-# true.print();
-# 3.14159.print();
-~~~~
-
-This works fine, but we've now repeated the same definition of `print`
-in three places.  Instead of doing that, we can simply include the
-definition of `print` right in the trait definition, instead of just
-giving its signature.  That is, we can write the following:
-
-~~~~
-extern crate debug;
-
-# fn main() {
-trait Printable {
-    // Default method implementation
-    fn print(&self) { println!("{:?}", *self) }
-}
-
-impl Printable for int {}
-
-impl Printable for String {
-    fn print(&self) { println!("{}", *self) }
-}
-
-impl Printable for bool {}
-
-impl Printable for f32 {}
-
-# 1.print();
-# ("foo".to_string()).print();
-# true.print();
-# 3.14159.print();
-# }
-~~~~
-
-Here, the impls of `Printable` for `int`, `bool`, and `f32` don't
-need to provide an implementation of `print`, because in the absence
-of a specific implementation, Rust just uses the _default method_
-provided in the trait definition.  Depending on the trait, default
-methods can save a great deal of boilerplate code from having to be
-written in impls.  Of course, individual impls can still override the
-default method for `print`, as is being done above in the impl for
-`String`.
-
-## Type-parameterized traits
-
-Traits may be parameterized by type variables.  For example, a trait
-for generalized sequence types might look like the following:
-
-~~~~
-trait Seq<T> {
-    fn length(&self) -> uint;
-}
-
-impl<T> Seq<T> for Vec<T> {
-    fn length(&self) -> uint { self.len() }
-}
-~~~~
-
-The implementation has to explicitly declare the type parameter that
-it binds, `T`, before using it to specify its trait type. Rust
-requires this declaration because the `impl` could also, for example,
-specify an implementation of `Seq<int>`. The trait type (appearing
-between `impl` and `for`) *refers* to a type, rather than
-defining one.
-
-The type parameters bound by a trait are in scope in each of the
-method declarations. So, re-declaring the type parameter
-`T` as an explicit type parameter for `length`, in either the trait or
-the impl, would be a compile-time error.
-
-Within a trait definition, `Self` is a special type that you can think
-of as a type parameter. An implementation of the trait for any given
-type `T` replaces the `Self` type parameter with `T`. The following
-trait describes types that support an equality operation:
-
-~~~~
-// In a trait, `self` refers to the self argument.
-// `Self` refers to the type implementing the trait.
-trait PartialEq {
-    fn equals(&self, other: &Self) -> bool;
-}
-
-// In an impl, `self` refers just to the value of the receiver
-impl PartialEq for int {
-    fn equals(&self, other: &int) -> bool { *other == *self }
-}
-~~~~
-
-Notice that in the trait definition, `equals` takes a
-second parameter of type `Self`.
-In contrast, in the `impl`, `equals` takes a second parameter of
-type `int`, only using `self` as the name of the receiver.
-
-Just as in type implementations, traits can define standalone (static)
-methods.  These methods are called by prefixing the method name with the trait
-name and a double colon.  The compiler uses type inference to decide which
-implementation to use.
-
-~~~~
-use std::f64::consts::PI;
-trait Shape { fn new(area: f64) -> Self; }
-struct Circle { radius: f64 }
-struct Square { length: f64 }
-
-impl Shape for Circle {
-    fn new(area: f64) -> Circle { Circle { radius: (area / PI).sqrt() } }
-}
-impl Shape for Square {
-    fn new(area: f64) -> Square { Square { length: area.sqrt() } }
-}
-
-let area = 42.5;
-let c: Circle = Shape::new(area);
-let s: Square = Shape::new(area);
-~~~~
-
-## Bounded type parameters and static method dispatch
-
-Traits give us a language for defining predicates on types, or
-abstract properties that types can have. We can use this language to
-define _bounds_ on type parameters, so that we can then operate on
-generic types.
-
-~~~~
-# trait Printable { fn print(&self); }
-fn print_all<T: Printable>(printable_things: Vec<T>) {
-    for thing in printable_things.iter() {
-        thing.print();
-    }
-}
-~~~~
-
-Declaring `T` as conforming to the `Printable` trait (as we earlier
-did with `Clone`) makes it possible to call methods from that trait
-on values of type `T` inside the function. It will also cause a
-compile-time error when anyone tries to call `print_all` on a vector
-whose element type does not have a `Printable` implementation.
-
-Type parameters can have multiple bounds by separating them with `+`,
-as in this version of `print_all` that copies elements.
-
-~~~
-# trait Printable { fn print(&self); }
-fn print_all<T: Printable + Clone>(printable_things: Vec<T>) {
-    let mut i = 0;
-    while i < printable_things.len() {
-        let copy_of_thing = printable_things[i].clone();
-        copy_of_thing.print();
-        i += 1;
-    }
-}
-~~~
-
-Method calls to bounded type parameters are _statically dispatched_,
-imposing no more overhead than normal function invocation, so are
-the preferred way to use traits polymorphically.
-
-This usage of traits is similar to Haskell type classes.
-
-## Trait objects and dynamic method dispatch
-
-The above allows us to define functions that polymorphically act on
-values of a single unknown type that conforms to a given trait.
-However, consider this function:
-
-~~~~
-# type Circle = int; type Rectangle = int;
-# impl Drawable for int { fn draw(&self) {} }
-# fn new_circle() -> int { 1 }
-trait Drawable { fn draw(&self); }
-
-fn draw_all<T: Drawable>(shapes: Vec<T>) {
-    for shape in shapes.iter() { shape.draw(); }
-}
-# let c: Circle = new_circle();
-# draw_all(vec![c]);
-~~~~
-
-You can call that on a vector of circles, or a vector of rectangles
-(assuming those have suitable `Drawable` traits defined), but not on
-a vector containing both circles and rectangles. When such behavior is
-needed, a trait name can alternately be used as a type, called
-an _object_.
-
-~~~~
-# trait Drawable { fn draw(&self); }
-fn draw_all(shapes: &[Box<Drawable>]) {
-    for shape in shapes.iter() { shape.draw(); }
-}
-~~~~
-
-In this example, there is no type parameter. Instead, the `Box<Drawable>`
-type denotes any owned box value that implements the `Drawable` trait.
-To construct such a value, you use the `as` operator to cast a value
-to an object:
-
-~~~~
-# type Circle = int; type Rectangle = bool;
-# trait Drawable { fn draw(&self); }
-# fn new_circle() -> Circle { 1 }
-# fn new_rectangle() -> Rectangle { true }
-# fn draw_all(shapes: &[Box<Drawable>]) {}
-
-impl Drawable for Circle { fn draw(&self) { /* ... */ } }
-impl Drawable for Rectangle { fn draw(&self) { /* ... */ } }
-
-let c: Box<Circle> = box new_circle();
-let r: Box<Rectangle> = box new_rectangle();
-draw_all([c as Box<Drawable>, r as Box<Drawable>]);
-~~~~
-
-We omit the code for `new_circle` and `new_rectangle`; imagine that
-these just return `Circle`s and `Rectangle`s with a default size. Note
-that, like strings and vectors, objects have dynamic size and may
-only be referred to via one of the pointer types.
-Other pointer types work as well.
-Casts to traits may only be done with compatible pointers so,
-for example, an `&Circle` may not be cast to a `Box<Drawable>`.
-
-~~~
-# type Circle = int; type Rectangle = int;
-# trait Drawable { fn draw(&self); }
-# impl Drawable for int { fn draw(&self) {} }
-# fn new_circle() -> int { 1 }
-# fn new_rectangle() -> int { 2 }
-// An owned object
-let owny: Box<Drawable> = box new_circle() as Box<Drawable>;
-// A borrowed object
-let stacky: &Drawable = &new_circle() as &Drawable;
-~~~
-
-Method calls to trait types are _dynamically dispatched_. Since the
-compiler doesn't know specifically which functions to call at compile
-time, it uses a lookup table (also known as a vtable or dictionary) to
-select the method to call at runtime.
-
-This usage of traits is similar to Java interfaces.
-
-There are some built-in bounds, such as `Send` and `Sync`, which are properties
-of the components of types. By design, trait objects don't know the exact type
-of their contents and so the compiler cannot reason about those properties.
-
-You can instruct the compiler, however, that the contents of a trait object must
-ascribe to a particular bound with a trailing colon (`:`). These are examples of
-valid types:
-
-~~~rust
-trait Foo {}
-trait Bar<T> {}
-
-fn sendable_foo(f: Box<Foo + Send>) { /* ... */ }
-fn sync_bar<T: Sync>(b: &Bar<T> + Sync) { /* ... */ }
-~~~
-
-When no colon is specified (such as the type `Box<Foo>`), it is inferred that the
-value ascribes to no bounds. They must be added manually if any bounds are
-necessary for usage.
-
-Builtin kind bounds can also be specified on closure types in the same way (for
-example, by writing `fn:Send()`), and the default behaviours are the same as
-for traits of the same storage class.
-
-## Trait inheritance
-
-We can write a trait declaration that _inherits_ from other traits, called _supertraits_.
-Types that implement a trait must also implement its supertraits.
-For example,
-we can define a `Circle` trait that inherits from `Shape`.
-
-~~~~
-trait Shape { fn area(&self) -> f64; }
-trait Circle : Shape { fn radius(&self) -> f64; }
-~~~~
-
-Now, we can implement `Circle` on a type only if we also implement `Shape`.
-
-~~~~
-use std::f64::consts::PI;
-# trait Shape { fn area(&self) -> f64; }
-# trait Circle : Shape { fn radius(&self) -> f64; }
-# struct Point { x: f64, y: f64 }
-# fn square(x: f64) -> f64 { x * x }
-struct CircleStruct { center: Point, radius: f64 }
-impl Circle for CircleStruct {
-    fn radius(&self) -> f64 { (self.area() / PI).sqrt() }
-}
-impl Shape for CircleStruct {
-    fn area(&self) -> f64 { PI * square(self.radius) }
-}
-~~~~
-
-Notice that methods of `Circle` can call methods on `Shape`, as our
-`radius` implementation calls the `area` method.
-This is a silly way to compute the radius of a circle
-(since we could just return the `radius` field), but you get the idea.
-
-In type-parameterized functions,
-methods of the supertrait may be called on values of subtrait-bound type parameters.
-Referring to the previous example of `trait Circle : Shape`:
-
-~~~
-# trait Shape { fn area(&self) -> f64; }
-# trait Circle : Shape { fn radius(&self) -> f64; }
-fn radius_times_area<T: Circle>(c: T) -> f64 {
-    // `c` is both a Circle and a Shape
-    c.radius() * c.area()
-}
-~~~
-
-Likewise, supertrait methods may also be called on trait objects.
-
-~~~
-use std::f64::consts::PI;
-# trait Shape { fn area(&self) -> f64; }
-# trait Circle : Shape { fn radius(&self) -> f64; }
-# struct Point { x: f64, y: f64 }
-# struct CircleStruct { center: Point, radius: f64 }
-# impl Circle for CircleStruct { fn radius(&self) -> f64 { (self.area() / PI).sqrt() } }
-# impl Shape for CircleStruct { fn area(&self) -> f64 { PI * square(self.radius) } }
-# fn square(x: f64) -> f64 { x * x }
-
-let concrete = box CircleStruct{center:Point{x:3.0,y:4.0},radius:5.0};
-let mycircle: Box<Circle> = concrete as Box<Circle>;
-let nonsense = mycircle.radius() * mycircle.area();
-~~~
-
-> *Note:* Trait inheritance does not actually work with objects yet
-
-## Deriving implementations for traits
-
-A small number of traits in can have implementations
-that can be automatically derived. These instances are specified by
-placing the `deriving` attribute on a data type declaration. For
-example, the following will mean that `Circle` has an implementation
-for `PartialEq` and can be used with the equality operators, and that a value
-of type `ABC` can be randomly generated and converted to a string:
-
-~~~
-extern crate rand;
-use std::rand::{task_rng, Rng};
-
-#[deriving(PartialEq)]
-struct Circle { radius: f64 }
-
-#[deriving(Rand, Show)]
-enum ABC { A, B, C }
-
-fn main() {
-    // Use the Show trait to print "A, B, C."
-    println!("{}, {}, {}", A, B, C);
-
-    let mut rng = task_rng();
-
-    // Use the Rand trait to generate a random variants.
-    for _ in range(0i, 10) {
-        println!("{}", rng.gen::<ABC>());
-    }
-}
-~~~
-
-The full list of derivable traits is `PartialEq`, `Eq`, `PartialOrd`,
-`Ord`, `Encodable`, `Decodable`, `Clone`,
-`Hash`, `Rand`, `Default`, `Zero`, `FromPrimitive` and `Show`.
-
-# Crates and the module system
-
-Rust's module system is very powerful, but because of that also somewhat complex.
-Nevertheless, this section will try to explain every important aspect of it.
-
-## Crates
-
-In order to speak about the module system, we first need to define the medium it exists in:
-
-Let's say you've written a program or a library, compiled it, and got the resulting binary.
-In Rust, the content of all source code that the compiler directly had to compile in order to end up with
-that binary is collectively called a 'crate'.
-
-For example, for a simple hello world program your crate only consists of this code:
-
-~~~~
-// `main.rs`
-fn main() {
-    println!("Hello world!");
-}
-~~~~
-
-A crate is also the unit of independent compilation in Rust: `rustc` always compiles a single crate at a time,
-from which it produces either a library or an executable.
-
-Note that merely using an already compiled library in your code does not make it part of your crate.
-
-## The module hierarchy
-
-For every crate, all the code in it is arranged in a hierarchy of modules starting with a single
-root module. That root module is called the 'crate root'.
-
-All modules in a crate below the crate root are declared with the `mod` keyword:
-
-~~~~
-// This is the crate root
-
-mod farm {
-    // This is the body of module 'farm' declared in the crate root.
-
-    fn chicken() { println!("cluck cluck"); }
-    fn cow() { println!("mooo"); }
-
-    mod barn {
-        // Body of module 'barn'
-
-        fn hay() { println!("..."); }
-    }
-}
-
-fn main() {
-    println!("Hello farm!");
-}
-~~~~
-
-As you can see, your module hierarchy is now three modules deep: There is the crate root, which contains your `main()`
-function, and the module `farm`. The module `farm` also contains two functions and a third module `barn`,
-which contains a function `hay`.
-
-## Paths and visibility
-
-We've now defined a nice module hierarchy. But how do we access the items in it from our `main` function?
-One way to do it is to simply fully qualifying it:
-
-~~~~ {.ignore}
-mod farm {
-    fn chicken() { println!("cluck cluck"); }
-    // ...
-}
-
-fn main() {
-    println!("Hello chicken!");
-
-    ::farm::chicken(); // Won't compile yet, see further down
-}
-~~~~
-
-The `::farm::chicken` construct is what we call a 'path'.
-
-Because it's starting with a `::`, it's also a 'global path', which qualifies
-an item by its full path in the module hierarchy relative to the crate root.
-
-If the path were to start with a regular identifier, like `farm::chicken`, it
-would be a 'local path' instead. We'll get to them later.
-
-Now, if you actually tried to compile this code example, you'll notice that you
-get a `function 'chicken' is private` error. That's because by default, items
-(`fn`, `struct`, `static`, `mod`, ...) are private.
-
-To make them visible outside their containing modules, you need to mark them
-_public_ with `pub`:
-
-~~~~
-mod farm {
-    pub fn chicken() { println!("cluck cluck"); }
-    pub fn cow() { println!("mooo"); }
-    // ...
-}
-
-fn main() {
-    println!("Hello chicken!");
-    ::farm::chicken(); // This compiles now
-}
-~~~~
-
-Visibility restrictions in Rust exist only at module boundaries. This
-is quite different from most object-oriented languages that also
-enforce restrictions on objects themselves. That's not to say that
-Rust doesn't support encapsulation: both struct fields and methods can
-be private. But this encapsulation is at the module level, not the
-struct level.
-
-Fields are _private_ by default, and can be made _public_ with
-the `pub` keyword:
-
-~~~
-mod farm {
-# pub type Chicken = int;
-# struct Human(int);
-# impl Human { pub fn rest(&self) { } }
-# pub fn make_me_a_farm() -> Farm { Farm { chickens: vec![], farmer: Human(0) } }
-    pub struct Farm {
-        chickens: Vec<Chicken>,
-        pub farmer: Human
-    }
-
-    impl Farm {
-        fn feed_chickens(&self) { /* ... */ }
-        pub fn add_chicken(&self, c: Chicken) { /* ... */ }
-    }
-
-    pub fn feed_animals(farm: &Farm) {
-        farm.feed_chickens();
-    }
-}
-
-fn main() {
-    let f = make_me_a_farm();
-    f.add_chicken(make_me_a_chicken());
-    farm::feed_animals(&f);
-    f.farmer.rest();
-
-    // This wouldn't compile because both are private:
-    // `f.feed_chickens();`
-    // `let chicken_counter = f.chickens.len();`
-}
-# fn make_me_a_farm() -> farm::Farm { farm::make_me_a_farm() }
-# fn make_me_a_chicken() -> farm::Chicken { 0 }
-~~~
-
-Exact details and specifications about visibility rules can be found in the Rust
-manual.
-
-## Files and modules
-
-One important aspect of Rust's module system is that source files and modules are not the same thing. You define a module hierarchy, populate it with all your definitions, define visibility, maybe put in a `fn main()`, and that's it.
-
-The only file that's relevant when compiling is the one that contains the body
-of your crate root, and it's only relevant because you have to pass that file
-to `rustc` to compile your crate.
-
-In principle, that's all you need: You can write any Rust program as one giant source file that contains your
-crate root and everything else in `mod ... { ... }` declarations.
-
-However, in practice you usually want to split up your code into multiple
-source files to make it more manageable. Rust allows you to move the body of
-any module into its own source file. If you declare a module without its body,
-like `mod foo;`, the compiler will look for the files `foo.rs` and `foo/mod.rs`
-inside some directory (usually the same as of the source file containing the
-`mod foo;` declaration). If it finds either, it uses the content of that file
-as the body of the module. If it finds both, that's a compile error.
-
-To move the content of `mod farm` into its own file, you can write:
-
-~~~~ {.ignore}
-// `main.rs` - contains body of the crate root
-mod farm; // Compiler will look for `farm.rs` and `farm/mod.rs`
-
-fn main() {
-    println!("Hello farm!");
-    ::farm::cow();
-}
-~~~~
-
-~~~~
-// `farm.rs` - contains body of module 'farm' in the crate root
-pub fn chicken() { println!("cluck cluck"); }
-pub fn cow() { println!("mooo"); }
-
-pub mod barn {
-    pub fn hay() { println!("..."); }
-}
-# fn main() { }
-~~~~
-
-In short, `mod foo;` is just syntactic sugar for `mod foo { /* content of <...>/foo.rs or <...>/foo/mod.rs */ }`.
-
-This also means that having two or more identical `mod foo;` declarations
-somewhere in your crate hierarchy is generally a bad idea,
-just like copy-and-paste-ing a module into multiple places is a bad idea.
-Both will result in duplicate and mutually incompatible definitions.
-
-When `rustc` resolves these module declarations, it starts by looking in the
-parent directory of the file containing the `mod foo` declaration. For example,
-given a file with the module body:
-
-~~~ {.ignore}
-// `src/main.rs`
-mod plants;
-mod animals {
-    mod fish;
-    mod mammals {
-        mod humans;
-    }
-}
-~~~
-
-The compiler will look for these files, in this order:
-
-~~~text
-src/plants.rs
-src/plants/mod.rs
-
-src/animals/fish.rs
-src/animals/fish/mod.rs
-
-src/animals/mammals/humans.rs
-src/animals/mammals/humans/mod.rs
-~~~
-
-Keep in mind that identical module hierarchies can still lead to different path
-lookups depending on how and where you've moved a module body to its own file.
-For example, if you move the `animals` module into its own file:
-
-~~~ {.ignore}
-// `src/main.rs`
-mod plants;
-mod animals;
-~~~
-
-~~~ {.ignore}
-// `src/animals.rs` or `src/animals/mod.rs`
-mod fish;
-mod mammals {
-    mod humans;
-}
-~~~
-
-...then the source files of `mod animals`'s submodules can either be in the same directory as the animals source file or in a subdirectory of its directory. If the animals file is `src/animals.rs`, `rustc` will look for:
-
-~~~text
-src/animals.rs
-    src/fish.rs
-    src/fish/mod.rs
-
-    src/mammals/humans.rs
-    src/mammals/humans/mod.rs
-~~~
-
-If the animals file is `src/animals/mod.rs`, `rustc` will look for:
-
-~~~text
-src/animals/mod.rs
-    src/animals/fish.rs
-    src/animals/fish/mod.rs
-
-    src/animals/mammals/humans.rs
-    src/animals/mammals/humans/mod.rs
-
-~~~
-
-These rules allow you to write small modules consisting of single source files which can live in the same directory as well as large modules which group submodule source files in subdirectories.
-
-If you need to override where `rustc` will look for the file containing a
-module's source code, use the `path` compiler directive. For example, to load a
-`classified` module from a different file:
-
-~~~ {.ignore}
-#[path="../../area51/alien.rs"]
-mod classified;
-~~~
-
-## Importing names into the local scope
-
-Always referring to definitions in other modules with their global
-path gets old really fast, so Rust has a way to import
-them into the local scope of your module: `use`-statements.
-
-They work like this: At the beginning of any module body, `fn` body, or any other block
-you can write a list of `use`-statements, consisting of the keyword `use` and a __global path__ to an item
-without the `::` prefix. For example, this imports `cow` into the local scope:
-
-~~~
-use farm::cow;
-# mod farm { pub fn cow() { println!("I'm a hidden ninja cow!") } }
-# fn main() { cow() }
-~~~
-
-The path you give to `use` is per default global, meaning relative to the crate root,
-no matter how deep the module hierarchy is, or whether the module body it's written in
-is contained in its own file. (Remember: files are irrelevant.)
-
-This is different from other languages, where you often only find a single import construct that combines the semantic
-of `mod foo;` and `use`-statements, and which tend to work relative to the source file or use an absolute file path
-- Ruby's `require` or C/C++'s `#include` come to mind.
-
-However, it's also possible to import things relative to the module of the `use`-statement:
-Adding a `super::` in front of the path will start in the parent module,
-while adding a `self::` prefix will start in the current module:
-
-~~~
-# mod workaround {
-# pub fn some_parent_item(){ println!("...") }
-# mod foo {
-use super::some_parent_item;
-use self::some_child_module::some_item;
-# pub fn bar() { some_parent_item(); some_item() }
-# pub mod some_child_module { pub fn some_item() {} }
-# }
-# }
-~~~
-
-Again - relative to the module, not to the file.
-
-Imports are also shadowed by local definitions:
-For each name you mention in a module/block, `rust`
-will first look at all items that are defined locally,
-and only if that results in no match look at items you brought in
-scope with corresponding `use` statements.
-
-~~~ {.ignore}
-# // FIXME: Allow unused import in doc test
-use farm::cow;
-// ...
-# mod farm { pub fn cow() { println!("Hidden ninja cow is hidden.") } }
-fn cow() { println!("Mooo!") }
-
-fn main() {
-    cow() // resolves to the locally defined `cow()` function
-}
-~~~
-
-To make this behavior more obvious, the rule has been made that `use`-statement always need to be written
-before any declaration, like in the example above. This is a purely artificial rule introduced
-because people always assumed they shadowed each other based on order, despite the fact that all items in rust are
-mutually recursive, order independent definitions.
-
-One odd consequence of that rule is that `use` statements also go in front of any `mod` declaration,
-even if they refer to things inside them:
-
-~~~
-use farm::cow;
-mod farm {
-    pub fn cow() { println!("Moooooo?") }
-}
-
-fn main() { cow() }
-~~~
-
-This is what our `farm` example looks like with `use` statements:
-
-~~~~
-use farm::chicken;
-use farm::cow;
-use farm::barn;
-
-mod farm {
-    pub fn chicken() { println!("cluck cluck"); }
-    pub fn cow() { println!("mooo"); }
-
-    pub mod barn {
-        pub fn hay() { println!("..."); }
-    }
-}
-
-fn main() {
-    println!("Hello farm!");
-
-    // Can now refer to those names directly:
-    chicken();
-    cow();
-    barn::hay();
-}
-~~~~
-
-And here an example with multiple files:
-
-~~~{.ignore}
-// `a.rs` - crate root
-use b::foo;
-use b::c::bar;
-mod b;
-fn main() {
-    foo();
-    bar();
-}
-~~~
-
-~~~{.ignore}
-// `b/mod.rs`
-pub mod c;
-pub fn foo() { println!("Foo!"); }
-~~~
-
-~~~{.ignore}
-// `b/c.rs`
-pub fn bar() { println!("Bar!"); }
-~~~
-
-There also exist two short forms for importing multiple names at once:
-
-1. Explicit mention multiple names as the last element of an `use` path:
-
-~~~
-use farm::{chicken, cow};
-# mod farm {
-#     pub fn cow() { println!("Did I already mention how hidden and ninja I am?") }
-#     pub fn chicken() { println!("I'm Bat-chicken, guardian of the hidden tutorial code.") }
-# }
-# fn main() { cow(); chicken() }
-~~~
-
-2. Import everything in a module with a wildcard:
-
-~~~
-# #![feature(globs)]
-use farm::*;
-# mod farm {
-#     pub fn cow() { println!("Bat-chicken? What a stupid name!") }
-#     pub fn chicken() { println!("Says the 'hidden ninja' cow.") }
-# }
-# fn main() { cow(); chicken() }
-~~~
-
-> *Note:* This feature of the compiler is currently gated behind the
-> `#![feature(globs)]` directive. More about these directives can be found in
-> the manual.
-
-However, that's not all. You can also rename an item while you're bringing it into scope:
-
-~~~
-use farm::chicken as egg_layer;
-# mod farm { pub fn chicken() { println!("Laying eggs is fun!")  } }
-// ...
-
-fn main() {
-    egg_layer();
-}
-~~~
-
-In general, `use` creates a local alias:
-An alternate path and a possibly different name to access the same item,
-without touching the original, and with both being interchangeable.
-
-## Reexporting names
-
-It is also possible to reexport items to be accessible under your module.
-
-For that, you write `pub use`:
-
-~~~
-mod farm {
-    pub use self::barn::hay;
-
-    pub fn chicken() { println!("cluck cluck"); }
-    pub fn cow() { println!("mooo"); }
-
-    mod barn {
-        pub fn hay() { println!("..."); }
-    }
-}
-
-fn main() {
-    farm::chicken();
-    farm::cow();
-    farm::hay();
-}
-~~~
-
-Just like in normal `use` statements, the exported names
-merely represent an alias to the same thing and can also be renamed.
-
-The above example also demonstrate what you can use `pub use` for:
-The nested `barn` module is private, but the `pub use` allows users
-of the module `farm` to access a function from `barn` without needing
-to know that `barn` exists.
-
-In other words, you can use it to decouple a public api from its internal implementation.
-
-## Using libraries
-
-So far we've only talked about how to define and structure your own crate.
-
-However, most code out there will want to use preexisting libraries,
-as there really is no reason to start from scratch each time you start a new project.
-
-In Rust terminology, we need a way to refer to other crates.
-
-For that, Rust offers you the `extern crate` declaration:
-
-~~~
-// `num` ships with Rust.
-extern crate num;
-
-fn main() {
-    // The rational number '1/2':
-    let one_half = ::num::rational::Ratio::new(1i, 2);
-}
-~~~
-
-A statement of the form `extern crate foo;` will cause `rustc` to search for the crate `foo`,
-and if it finds a matching binary it lets you use it from inside your crate.
-
-The effect it has on your module hierarchy mirrors aspects of both `mod` and `use`:
-
-- Like `mod`, it causes `rustc` to actually emit code:
-  The linkage information the binary needs to use the library `foo`.
-
-- But like `use`, all `extern crate` statements that refer to the same library are interchangeable,
-  as each one really just presents an alias to an external module (the crate root of the library
-  you're linking against).
-
-Remember how `use`-statements have to go before local declarations because the latter shadows the former?
-Well, `extern crate` statements also have their own rules in that regard:
-Both `use` and local declarations can shadow them, so the rule is that `extern crate` has to go in front
-of both `use` and local declarations.
-
-Which can result in something like this:
-
-~~~
-extern crate num;
-
-use farm::dog;
-use num::rational::Ratio;
-
-mod farm {
-    pub fn dog() { println!("woof"); }
-}
-
-fn main() {
-    farm::dog();
-    let a_third = Ratio::new(1i, 3);
-}
-~~~
-
-It's a bit weird, but it's the result of shadowing rules that have been set that way because
-they model most closely what people expect to shadow.
-
-## Crate metadata and settings
-
-For every crate you can define a number of metadata items, such as link name, version or author.
-You can also toggle settings that have crate-global consequences. Both mechanism
-work by providing attributes in the crate root.
-
-For example, Rust uniquely identifies crates by their link metadata, which includes
-the link name and the version. It also hashes the filename and the symbols in a binary
-based on the link metadata, allowing you to use two different versions of the same library in a crate
-without conflict.
-
-Therefore, if you plan to compile your crate as a library, you should annotate it with that information:
-
-~~~~
-# #![allow(unused_attribute)]
-// `lib.rs`
-
-# #![crate_type = "lib"]
-#![crate_id = "farm#2.5"]
-
-// ...
-# fn farm() {}
-~~~~
-
-You can also specify crate id information in a `extern crate` statement.  For
-example, these `extern crate` statements would both accept and select the
-crate define above:
-
-~~~~ {.ignore}
-extern crate farm;
-extern crate farm = "farm#2.5";
-extern crate my_farm = "farm";
-~~~~
-
-Other crate settings and metadata include things like enabling/disabling certain errors or warnings,
-or setting the crate type (library or executable) explicitly:
-
-~~~~
-# #![allow(unused_attribute)]
-// `lib.rs`
-// ...
-
-// This crate is a library ("bin" is the default)
-#![crate_id = "farm#2.5"]
-#![crate_type = "lib"]
-
-// Turn on a warning
-#[warn(non_camel_case_types)]
-# fn farm() {}
-~~~~
-
-## A minimal example
-
-Now for something that you can actually compile yourself.
-
-We define two crates, and use one of them as a library in the other.
-
-~~~~
-# #![allow(unused_attribute)]
-// `world.rs`
-#![crate_id = "world#0.42"]
-
-# mod secret_module_to_make_this_test_run {
-pub fn explore() -> &'static str { "world" }
-# }
-~~~~
-
-~~~~ {.ignore}
-// `main.rs`
-extern crate world;
-fn main() { println!("hello {}", world::explore()); }
-~~~~
-
-Now compile and run like this (adjust to your platform if necessary):
-
-~~~~console
-$ rustc --crate-type=lib world.rs  # compiles libworld-<HASH>-0.42.rlib
-$ rustc main.rs -L .               # compiles main
-$ ./main
-"hello world"
-~~~~
-
-Notice that the library produced contains the version in the file name
-as well as an inscrutable string of alphanumerics. As explained in the previous paragraph,
-these are both part of Rust's library versioning scheme. The alphanumerics are
-a hash representing the crate's id.
-
-## The standard library and the prelude
-
-While reading the examples in this tutorial, you might have asked yourself where all
-those magical predefined items like `range` are coming from.
-
-The truth is, there's nothing magical about them: They are all defined normally
-in the `std` library, which is a crate that ships with Rust.
-
-The only magical thing that happens is that `rustc` automatically inserts this line into your crate root:
-
-~~~ {.ignore}
-extern crate std;
-~~~
-
-As well as this line into every module body:
-
-~~~ {.ignore}
-use std::prelude::*;
-~~~
-
-The role of the `prelude` module is to re-export common definitions from `std`.
-
-This allows you to use common types and functions like `Option<T>` or `range`
-without needing to import them. And if you need something from `std` that's not in the prelude,
-you just have to import it with an `use` statement.
-
-For example, it re-exports `range` which is defined in `std::iter::range`:
-
-~~~
-use std::iter::range as iter_range;
-
-fn main() {
-    // `range` is imported by default
-    for _ in range(0u, 10) {}
-
-    // Doesn't hinder you from importing it under a different name yourself
-    for _ in iter_range(0u, 10) {}
-
-    // Or from not using the automatic import.
-    for _ in ::std::iter::range(0u, 10) {}
-}
-~~~
-
-Both auto-insertions can be disabled with an attribute if necessary:
-
-~~~
-# #![allow(unused_attribute)]
-// In the crate root:
-#![no_std]
-~~~
-
-~~~
-# #![allow(unused_attribute)]
-// In any module:
-#![no_implicit_prelude]
-~~~
-
-See the [API documentation][stddoc] for details.
-
-[stddoc]: std/index.html
-
-# What next?
-
-Now that you know the essentials, check out any of the additional
-guides on individual topics.
-
-* [Pointers][pointers]
-* [Lifetimes][lifetimes]
-* [Tasks and communication][tasks]
-* [Macros][macros]
-* [The foreign function interface][ffi]
-* [Containers and iterators][container]
-* [Documenting Rust code][rustdoc]
-* [Testing Rust code][testing]
-* [The Rust Runtime][runtime]
-
-There is further documentation on the [wiki], however those tend to be even more out of date than this document.
-
-[pointers]: guide-pointers.html
-[lifetimes]: guide-lifetimes.html
-[tasks]: guide-tasks.html
-[macros]: guide-macros.html
-[ffi]: guide-ffi.html
-[container]: guide-container.html
-[testing]: guide-testing.html
-[runtime]: guide-runtime.html
-[rustdoc]: rustdoc.html
-[wiki]: https://github.com/rust-lang/rust/wiki/Docs
-
-[wiki-packages]: https://github.com/rust-lang/rust/wiki/Doc-packages,-editors,-and-other-tools
+This tutorial has been deprecated in favor of [the Guide](guide.html). Go check that out instead!
diff --git a/src/etc/copy-runtime-deps.py b/src/etc/copy-runtime-deps.py
deleted file mode 100644 (file)
index fd829cd..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-# Copyright 2013-2014 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.
-
-# Copies Rust runtime dependencies to the specified directory.
-
-import snapshot, sys, os, shutil
-
-def copy_runtime_deps(dest_dir, triple):
-    for path in snapshot.get_winnt_runtime_deps(snapshot.get_platform(triple)):
-        shutil.copy(path, dest_dir)
-
-    lic_dest = os.path.join(dest_dir, "third-party")
-    if os.path.exists(lic_dest):
-        shutil.rmtree(lic_dest) # copytree() won't overwrite existing files
-    shutil.copytree(os.path.join(os.path.dirname(__file__), "third-party"), lic_dest)
-
-copy_runtime_deps(sys.argv[1], sys.argv[2])
index c5acb69df8d732653d4aadd505bb50cc2f6d7f7a..886a84bd819a9ec60dd958ec2746b4d5513d7399 100755 (executable)
@@ -52,9 +52,7 @@ triple = sys.argv[1]
 if len(sys.argv) == 3:
   dl_path = sys.argv[2]
 else:
-  # There are no 64-bit Windows snapshots yet, so we'll use 32-bit ones instead, for now
-  snap_triple = triple if triple != "x86_64-w64-mingw32" else "i686-w64-mingw32"
-  snap = determine_curr_snapshot(snap_triple)
+  snap = determine_curr_snapshot(triple)
   dl = os.path.join(download_dir_base, snap)
   url = download_url_base + "/" + snap
   print("determined most recent snapshot: " + snap)
diff --git a/src/etc/make-win-dist.py b/src/etc/make-win-dist.py
new file mode 100644 (file)
index 0000000..bb9a112
--- /dev/null
@@ -0,0 +1,82 @@
+# Copyright 2013-2014 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.
+
+import sys, os, shutil, subprocess
+
+def find_files(files, path):
+    found = []
+    for fname in files:
+        for dir in path:
+            filepath = os.path.normpath(os.path.join(dir, fname))
+            if os.path.isfile(filepath):
+                found.append(filepath)
+                break
+        else:
+            raise Exception("Could not find '%s' in %s" % (fname, path))
+    return found
+
+def make_win_dist(dist_root, target_triple):
+    # Ask gcc where it keeps its' stuff
+    gcc_out = subprocess.check_output(["gcc.exe", "-print-search-dirs"])
+    bin_path = os.environ["PATH"].split(os.pathsep)
+    lib_path = []
+    for line in gcc_out.splitlines():
+        key, val = line.split(':', 1)
+        if key == "programs":
+            bin_path.extend(val.lstrip(' =').split(';'))
+        elif key == "libraries":
+            lib_path.extend(val.lstrip(' =').split(';'))
+
+    target_tools = ["gcc.exe", "ld.exe", "ar.exe", "dlltool.exe", "windres.exe"]
+
+    rustc_dlls = ["libstdc++-6.dll"]
+    if target_triple.startswith("i686-"):
+        rustc_dlls.append("libgcc_s_dw2-1.dll")
+    else:
+        rustc_dlls.append("libgcc_s_seh-1.dll")
+
+    target_libs = ["crtbegin.o", "crtend.o", "crt2.o", "dllcrt2.o",
+                   "libadvapi32.a", "libcrypt32.a", "libgcc.a", "libgcc_eh.a", "libgcc_s.a",
+                   "libimagehlp.a", "libiphlpapi.a", "libkernel32.a", "libm.a", "libmingw32.a",
+                   "libmingwex.a", "libmsvcrt.a", "libpsapi.a", "libshell32.a", "libstdc++.a",
+                   "libuser32.a", "libws2_32.a", "libiconv.a", "libmoldname.a"]
+
+    # Find mingw artifacts we want to bundle
+    target_tools = find_files(target_tools, bin_path)
+    rustc_dlls = find_files(rustc_dlls, bin_path)
+    target_libs = find_files(target_libs, lib_path)
+
+    # Copy runtime dlls next to rustc.exe
+    dist_bin_dir = os.path.join(dist_root, "bin")
+    for src in rustc_dlls:
+        shutil.copy(src, dist_bin_dir)
+
+    # Copy platform tools (and another copy of runtime dlls) to platform-spcific bin directory
+    target_bin_dir = os.path.join(dist_root, "bin", "rustlib", target_triple, "bin")
+    if not os.path.exists(target_bin_dir):
+        os.makedirs(target_bin_dir)
+    for src in target_tools:
+        shutil.copy(src, target_bin_dir)
+
+    # Copy platform libs to platform-spcific lib directory
+    target_lib_dir = os.path.join(dist_root, "bin", "rustlib", target_triple, "lib")
+    if not os.path.exists(target_lib_dir):
+        os.makedirs(target_lib_dir)
+    for src in target_libs:
+        shutil.copy(src, target_lib_dir)
+
+    # Copy license files
+    lic_dir = os.path.join(dist_root, "bin", "third-party")
+    if os.path.exists(lic_dir):
+        shutil.rmtree(lic_dir) # copytree() won't overwrite existing files
+    shutil.copytree(os.path.join(os.path.dirname(__file__), "third-party"), lic_dir)
+
+if __name__=="__main__":
+    make_win_dist(sys.argv[1], sys.argv[2])
index 24255c0cc5df2c706d3a935f0aceda06d83b9159..268b82bdca38e5d7a7cab24b37b4cb65ff0ed666 100644 (file)
@@ -157,9 +157,9 @@ def get_winnt_runtime_deps(platform):
     path_dirs = os.environ["PATH"].split(os.pathsep)
     for name in deps:
       for dir in path_dirs:
-        matches = glob.glob(os.path.join(dir, name))
-        if matches:
-          runtime_deps.append(matches[0])
+        filepath = os.path.join(dir, name)
+        if os.path.isfile(filepath):
+          runtime_deps.append(filepath)
           break
       else:
         raise Exception("Could not find runtime dependency: %s" % name)
index a77c0e77efd3fbeb22fec7e18679347406ddd900..2544bfa2da363c895c9abc31cda803eb6b29ec25 100644 (file)
@@ -1,8 +1,5 @@
-Certain files in this distribution are covered by a different license than the rest of the Rust Project.
-Specifically:
+Certain binaries in this distribution do not originate from the Rust project, but are distributed with it in its binary form. These binaries, including gcc and other parts of the GNU compiler toolchain, are licensed either under the terms of the GNU General Public License, or the GNU General Public License with the GCC Runtime Library Exception, as published by the Free Software Foundation, either version 3, or (at your option) any later version. See the files COPYING3 and COPYING.RUNTIME respectively.
 
-   - libgcc_s_dw2-1.dll and libstdc++6.dll are distributed under the terms of the GNU General Public License 
-     with the GCC Runtime Library Exception as published by the Free Software Foundation; either version 3, 
-     or (at your option) any later version.  See the files COPYING3 and COPYING.RUNTIME respectively.
-     You can obtain a copy of the source of these libraries either here: http://sourceforge.net/projects/mingw/files/MinGW/Base/gcc/Version4/gcc-4.5.2-1/,
-     or from the project website at http://gcc.gnu.org
+You can obtain a copy of the source of these libraries from the MinGW-w64 project[1].
+
+[1]: http://mingw-w64.sourceforge.net/
index be75bfec32c86dd9fb172a5e42ce8dbbee0c39fd..f41d02070c9ee720c56c6ff2dff8c579a2066bf0 100644 (file)
@@ -113,7 +113,6 @@ impl<'a> Arguments<'a> {
     /// Arguments structure. The compiler inserts an `unsafe` block to call this,
     /// which is valid because the compiler performs all necessary validation to
     /// ensure that the resulting call to format/write would be safe.
-    #[cfg(not(stage0))]
     #[doc(hidden)] #[inline]
     pub unsafe fn new<'a>(pieces: &'static [&'static str],
                           args: &'a [Argument<'a>]) -> Arguments<'a> {
@@ -127,7 +126,6 @@ pub unsafe fn new<'a>(pieces: &'static [&'static str],
     /// This function is used to specify nonstandard formatting parameters.
     /// The `pieces` array must be at least as long as `fmt` to construct
     /// a valid Arguments structure.
-    #[cfg(not(stage0))]
     #[doc(hidden)] #[inline]
     pub unsafe fn with_placeholders<'a>(pieces: &'static [&'static str],
                                         fmt: &'static [rt::Argument<'static>],
@@ -138,13 +136,6 @@ pub unsafe fn with_placeholders<'a>(pieces: &'static [&'static str],
             args: args
         }
     }
-
-    #[cfg(stage0)]
-    #[doc(hidden)] #[inline]
-    pub unsafe fn new<'a>(fmt: &'static [rt::Piece<'static>],
-                          args: &'a [Argument<'a>]) -> Arguments<'a> {
-        Arguments{ fmt: mem::transmute(fmt), args: args }
-    }
 }
 
 /// This structure represents a safely precompiled version of a format string
@@ -156,7 +147,6 @@ pub unsafe fn new<'a>(fmt: &'static [rt::Piece<'static>],
 /// and pass it to a function or closure, passed as the first argument. The
 /// macro validates the format string at compile-time so usage of the `write`
 /// and `format` functions can be safely performed.
-#[cfg(not(stage0))]
 pub struct Arguments<'a> {
     // Format string pieces to print.
     pieces: &'a [&'a str],
@@ -169,12 +159,6 @@ pub struct Arguments<'a> {
     args: &'a [Argument<'a>],
 }
 
-#[cfg(stage0)] #[doc(hidden)]
-pub struct Arguments<'a> {
-    fmt: &'a [rt::Piece<'a>],
-    args: &'a [Argument<'a>],
-}
-
 impl<'a> Show for Arguments<'a> {
     fn fmt(&self, fmt: &mut Formatter) -> Result {
         write(fmt.buf, self)
@@ -296,7 +280,6 @@ pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
     secret_upper_exp, UpperExp;
 }
 
-#[cfg(not(stage0))]
 static DEFAULT_ARGUMENT: rt::Argument<'static> = rt::Argument {
     position: rt::ArgumentNext,
     format: rt::FormatSpec {
@@ -316,7 +299,6 @@ pub fn $name<T: $trait_>(x: &T, fmt: &mut Formatter) -> Result {
 ///
 ///   * output - the buffer to write output to
 ///   * args - the precompiled arguments generated by `format_args!`
-#[cfg(not(stage0))]
 pub fn write(output: &mut FormatWriter, args: &Arguments) -> Result {
     let mut formatter = Formatter {
         flags: 0,
@@ -360,30 +342,11 @@ pub fn write(output: &mut FormatWriter, args: &Arguments) -> Result {
     Ok(())
 }
 
-#[cfg(stage0)] #[doc(hidden)]
-pub fn write(output: &mut FormatWriter, args: &Arguments) -> Result {
-    let mut formatter = Formatter {
-        flags: 0,
-        width: None,
-        precision: None,
-        buf: output,
-        align: rt::AlignUnknown,
-        fill: ' ',
-        args: args.args,
-        curarg: args.args.iter(),
-    };
-    for piece in args.fmt.iter() {
-        try!(formatter.run(piece));
-    }
-    Ok(())
-}
-
 impl<'a> Formatter<'a> {
 
     // First up is the collection of functions used to execute a format string
     // at runtime. This consumes all of the compile-time statics generated by
     // the format! syntax extension.
-    #[cfg(not(stage0))]
     fn run(&mut self, arg: &rt::Argument) -> Result {
         // Fill in the format parameters into the formatter
         self.fill = arg.format.fill;
@@ -402,30 +365,6 @@ fn run(&mut self, arg: &rt::Argument) -> Result {
         (value.formatter)(value.value, self)
     }
 
-    #[cfg(stage0)] #[doc(hidden)]
-    fn run(&mut self, piece: &rt::Piece) -> Result {
-        match *piece {
-            rt::String(s) => self.buf.write(s.as_bytes()),
-            rt::Argument(ref arg) => {
-                // Fill in the format parameters into the formatter
-                self.fill = arg.format.fill;
-                self.align = arg.format.align;
-                self.flags = arg.format.flags;
-                self.width = self.getcount(&arg.format.width);
-                self.precision = self.getcount(&arg.format.precision);
-
-                // Extract the correct argument
-                let value = match arg.position {
-                    rt::ArgumentNext => { *self.curarg.next().unwrap() }
-                    rt::ArgumentIs(i) => self.args[i],
-                };
-
-                // Then actually do some printing
-                (value.formatter)(value.value, self)
-            }
-        }
-    }
-
     fn getcount(&mut self, cnt: &rt::Count) -> Option<uint> {
         match *cnt {
             rt::CountIs(n) => { Some(n) }
@@ -476,7 +415,7 @@ pub fn pad_integral(&mut self,
 
         let mut prefixed = false;
         if self.flags & (1 << (FlagAlternate as uint)) != 0 {
-            prefixed = true; width += prefix.len();
+            prefixed = true; width += prefix.char_len();
         }
 
         // Writes the sign if it exists, and then the prefix if it was requested
@@ -562,7 +501,7 @@ pub fn pad(&mut self, s: &str) -> Result {
             // If we're under both the maximum and the minimum width, then fill
             // up the minimum width with the specified string + some alignment.
             Some(width) => {
-                self.with_padding(width - s.len(), rt::AlignLeft, |me| {
+                self.with_padding(width - s.char_len(), rt::AlignLeft, |me| {
                     me.buf.write(s.as_bytes())
                 })
             }
index bf026560c6afd9ccfb552919ac27abd1d7619a54..e418284ffce7ab9c8f6eaf192ffbd43699483682 100644 (file)
@@ -929,6 +929,9 @@ fn link_args(cmd: &mut Command,
         cmd.arg("-nodefaultlibs");
     }
 
+    // Rust does its' own LTO
+    cmd.arg("-fno-lto").arg("-fno-use-linker-plugin");
+
     // If we're building a dylib, we don't use --gc-sections because LLVM has
     // already done the best it can do, and we also don't want to eliminate the
     // metadata. If we're building an executable, however, --gc-sections drops
index 4c71c2df44d3e167ab159ba25cd1f2f3b4d71215..018bfecd369a7128617b343adc962780b5f112d8 100644 (file)
@@ -32,6 +32,7 @@
 
 use std::io;
 use std::io::fs;
+use std::os;
 use arena::TypedArena;
 use syntax::ast;
 use syntax::attr;
@@ -258,18 +259,26 @@ pub fn phase_2_configure_and_expand(sess: &Session,
             // dependent dlls. Note that this uses cfg!(windows) as opposed to
             // targ_cfg because syntax extensions are always loaded for the host
             // compiler, not for the target.
+            let mut _old_path = String::new();
             if cfg!(windows) {
-                sess.host_filesearch().add_dylib_search_paths();
+                _old_path = os::getenv("PATH").unwrap_or(_old_path);
+                let mut new_path = sess.host_filesearch().get_dylib_search_paths();
+                new_path.push_all_move(os::split_paths(_old_path.as_slice()));
+                os::setenv("PATH", os::join_paths(new_path.as_slice()).unwrap());
             }
             let cfg = syntax::ext::expand::ExpansionConfig {
                 deriving_hash_type_parameter: sess.features.default_type_params.get(),
                 crate_name: crate_name.to_string(),
             };
-            syntax::ext::expand::expand_crate(&sess.parse_sess,
+            let ret = syntax::ext::expand::expand_crate(&sess.parse_sess,
                                               cfg,
                                               macros,
                                               syntax_exts,
-                                              krate)
+                                              krate);
+            if cfg!(windows) {
+                os::setenv("PATH", _old_path);
+            }
+            ret
         }
     );
 
@@ -509,11 +518,18 @@ pub fn phase_5_run_llvm_passes(sess: &Session,
 pub fn phase_6_link_output(sess: &Session,
                            trans: &CrateTranslation,
                            outputs: &OutputFilenames) {
+    let old_path = os::getenv("PATH").unwrap_or_else(||String::new());
+    let mut new_path = os::split_paths(old_path.as_slice());
+    new_path.push_all_move(sess.host_filesearch().get_tools_search_paths());
+    os::setenv("PATH", os::join_paths(new_path.as_slice()).unwrap());
+
     time(sess.time_passes(), "linking", (), |_|
          link::link_binary(sess,
                            trans,
                            outputs,
                            trans.link.crate_name.as_slice()));
+
+    os::setenv("PATH", old_path);
 }
 
 pub fn stop_after_phase_3(sess: &Session) -> bool {
index 225fc28cd6d9888b8a2ff022f6e4566a9b4509ee..7750ddc91e1a62061ce59682239aad38e714e956 100644 (file)
@@ -143,15 +143,15 @@ fn has_feature(&self, feature: &str) -> bool {
     }
 }
 
-impl<'a> Visitor<()> for Context<'a> {
-    fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) {
+impl<'a, 'v> Visitor<'v> for Context<'a> {
+    fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
         if !token::get_ident(id).get().is_ascii() {
             self.gate_feature("non_ascii_idents", sp,
                               "non-ascii idents are not fully supported.");
         }
     }
 
-    fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
+    fn visit_view_item(&mut self, i: &ast::ViewItem) {
         match i.node {
             ast::ViewItemUse(ref path) => {
                 match path.node {
@@ -173,10 +173,10 @@ fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
                 }
             }
         }
-        visit::walk_view_item(self, i, ())
+        visit::walk_view_item(self, i)
     }
 
-    fn visit_item(&mut self, i: &ast::Item, _:()) {
+    fn visit_item(&mut self, i: &ast::Item) {
         for attr in i.attrs.iter() {
             if attr.name().equiv(&("thread_local")) {
                 self.gate_feature("thread_local", i.span,
@@ -252,10 +252,10 @@ fn visit_item(&mut self, i: &ast::Item, _:()) {
             _ => {}
         }
 
-        visit::walk_item(self, i, ());
+        visit::walk_item(self, i);
     }
 
-    fn visit_mac(&mut self, macro: &ast::Mac, _: ()) {
+    fn visit_mac(&mut self, macro: &ast::Mac) {
         let ast::MacInvocTT(ref path, _, _) = macro.node;
         let id = path.segments.last().unwrap().identifier;
         let quotes = ["quote_tokens", "quote_expr", "quote_ty",
@@ -299,16 +299,16 @@ fn visit_mac(&mut self, macro: &ast::Mac, _: ()) {
         }
     }
 
-    fn visit_foreign_item(&mut self, i: &ast::ForeignItem, _: ()) {
+    fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
         if attr::contains_name(i.attrs.as_slice(), "linkage") {
             self.gate_feature("linkage", i.span,
                               "the `linkage` attribute is experimental \
                                and not portable across platforms")
         }
-        visit::walk_foreign_item(self, i, ())
+        visit::walk_foreign_item(self, i)
     }
 
-    fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
+    fn visit_ty(&mut self, t: &ast::Ty) {
         match t.node {
             ast::TyClosure(closure) if closure.onceness == ast::Once => {
                 self.gate_feature("once_fns", t.span,
@@ -325,10 +325,10 @@ fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
             _ => {}
         }
 
-        visit::walk_ty(self, t, ());
+        visit::walk_ty(self, t);
     }
 
-    fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
+    fn visit_expr(&mut self, e: &ast::Expr) {
         match e.node {
             ast::ExprUnary(ast::UnBox, _) => {
                 self.gate_box(e.span);
@@ -346,10 +346,10 @@ fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
             }
             _ => {}
         }
-        visit::walk_expr(self, e, ());
+        visit::walk_expr(self, e);
     }
 
-    fn visit_generics(&mut self, generics: &ast::Generics, _: ()) {
+    fn visit_generics(&mut self, generics: &ast::Generics) {
         for type_parameter in generics.ty_params.iter() {
             match type_parameter.default {
                 Some(ty) => {
@@ -360,10 +360,10 @@ fn visit_generics(&mut self, generics: &ast::Generics, _: ()) {
                 None => {}
             }
         }
-        visit::walk_generics(self, generics, ());
+        visit::walk_generics(self, generics);
     }
 
-    fn visit_attribute(&mut self, attr: &ast::Attribute, _: ()) {
+    fn visit_attribute(&mut self, attr: &ast::Attribute) {
         if attr::contains_name([*attr], "lang") {
             self.gate_feature("lang_items",
                               attr.span,
@@ -371,7 +371,7 @@ fn visit_attribute(&mut self, attr: &ast::Attribute, _: ()) {
         }
     }
 
-    fn visit_pat(&mut self, pattern: &ast::Pat, (): ()) {
+    fn visit_pat(&mut self, pattern: &ast::Pat) {
         match pattern.node {
             ast::PatVec(_, Some(_), ref last) if !last.is_empty() => {
                 self.gate_feature("advanced_slice_patterns",
@@ -382,25 +382,24 @@ fn visit_pat(&mut self, pattern: &ast::Pat, (): ()) {
             }
             _ => {}
         }
-        visit::walk_pat(self, pattern, ())
+        visit::walk_pat(self, pattern)
     }
 
     fn visit_fn(&mut self,
-                fn_kind: &visit::FnKind,
-                fn_decl: &ast::FnDecl,
-                block: &ast::Block,
+                fn_kind: visit::FnKind<'v>,
+                fn_decl: &'v ast::FnDecl,
+                block: &'v ast::Block,
                 span: Span,
-                _: NodeId,
-                (): ()) {
-        match *fn_kind {
-            visit::FkItemFn(_, _, _, ref abi) if *abi == RustIntrinsic => {
+                _: NodeId) {
+        match fn_kind {
+            visit::FkItemFn(_, _, _, abi) if abi == RustIntrinsic => {
                 self.gate_feature("intrinsics",
                                   span,
                                   "intrinsics are subject to change")
             }
             _ => {}
         }
-        visit::walk_fn(self, fn_kind, fn_decl, block, span, ());
+        visit::walk_fn(self, fn_kind, fn_decl, block, span);
     }
 }
 
@@ -453,7 +452,7 @@ pub fn check_crate(sess: &Session, krate: &ast::Crate) {
         }
     }
 
-    visit::walk_crate(&mut cx, krate, ());
+    visit::walk_crate(&mut cx, krate);
 
     sess.abort_if_errors();
 
index 1a59b3603de58b53a8102b6cad6a4bf572ca8060..df0b02261b149b44d820f9024423d195a787617a 100644 (file)
@@ -23,18 +23,18 @@ struct ShowSpanVisitor<'a> {
     sess: &'a Session
 }
 
-impl<'a> Visitor<()> for ShowSpanVisitor<'a> {
-    fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
+impl<'a, 'v> Visitor<'v> for ShowSpanVisitor<'a> {
+    fn visit_expr(&mut self, e: &ast::Expr) {
         self.sess.span_note(e.span, "expression");
-        visit::walk_expr(self, e, ());
+        visit::walk_expr(self, e);
     }
 
-    fn visit_mac(&mut self, macro: &ast::Mac, e: ()) {
-        visit::walk_mac(self, macro, e);
+    fn visit_mac(&mut self, macro: &ast::Mac) {
+        visit::walk_mac(self, macro);
     }
 }
 
 pub fn run(sess: &Session, krate: &ast::Crate) {
     let mut v = ShowSpanVisitor { sess: sess };
-    visit::walk_crate(&mut v, krate, ());
+    visit::walk_crate(&mut v, krate);
 }
index 138947e8a873b5cdbf754e24d628f0e4bb711a30..616219a3cb99510e63a3010bd15306e4067831ce 100644 (file)
@@ -366,13 +366,13 @@ fn check_def(&mut self, sp: Span, ty_id: ast::NodeId, path_id: ast::NodeId) {
     }
 }
 
-impl<'a, 'tcx> Visitor<()> for CTypesVisitor<'a, 'tcx> {
-    fn visit_ty(&mut self, ty: &ast::Ty, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for CTypesVisitor<'a, 'tcx> {
+    fn visit_ty(&mut self, ty: &ast::Ty) {
         match ty.node {
             ast::TyPath(_, _, id) => self.check_def(ty.span, ty.id, id),
             _ => (),
         }
-        visit::walk_ty(self, ty, ());
+        visit::walk_ty(self, ty);
     }
 }
 
@@ -386,7 +386,7 @@ fn get_lints(&self) -> LintArray {
     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
         fn check_ty(cx: &Context, ty: &ast::Ty) {
             let mut vis = CTypesVisitor { cx: cx };
-            vis.visit_ty(ty, ());
+            vis.visit_ty(ty);
         }
 
         fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
@@ -500,18 +500,18 @@ struct RawPtrDerivingVisitor<'a, 'tcx: 'a> {
     cx: &'a Context<'a, 'tcx>
 }
 
-impl<'a, 'tcx> Visitor<()> for RawPtrDerivingVisitor<'a, 'tcx> {
-    fn visit_ty(&mut self, ty: &ast::Ty, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDerivingVisitor<'a, 'tcx> {
+    fn visit_ty(&mut self, ty: &ast::Ty) {
         static MSG: &'static str = "use of `#[deriving]` with a raw pointer";
         match ty.node {
             ast::TyPtr(..) => self.cx.span_lint(RAW_POINTER_DERIVING, ty.span, MSG),
             _ => {}
         }
-        visit::walk_ty(self, ty, ());
+        visit::walk_ty(self, ty);
     }
     // explicit override to a no-op to reduce code bloat
-    fn visit_expr(&mut self, _: &ast::Expr, _: ()) {}
-    fn visit_block(&mut self, _: &ast::Block, _: ()) {}
+    fn visit_expr(&mut self, _: &ast::Expr) {}
+    fn visit_block(&mut self, _: &ast::Block) {}
 }
 
 pub struct RawPointerDeriving {
@@ -554,7 +554,7 @@ fn check_item(&mut self, cx: &Context, item: &ast::Item) {
         match item.node {
             ast::ItemStruct(..) | ast::ItemEnum(..) => {
                 let mut visitor = RawPtrDerivingVisitor { cx: cx };
-                visit::walk_item(&mut visitor, &*item, ());
+                visit::walk_item(&mut visitor, &*item);
             }
             _ => {}
         }
@@ -908,9 +908,9 @@ fn get_lints(&self) -> LintArray {
     }
 
     fn check_fn(&mut self, cx: &Context,
-                fk: &visit::FnKind, _: &ast::FnDecl,
+                fk: visit::FnKind, _: &ast::FnDecl,
                 _: &ast::Block, span: Span, _: ast::NodeId) {
-        match *fk {
+        match fk {
             visit::FkMethod(ident, _, m) => match method_context(cx, m) {
                 PlainImpl
                     => self.check_snake_case(cx, "method", ident, span),
@@ -1218,7 +1218,7 @@ fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
     }
 
     fn check_fn(&mut self, cx: &Context,
-                _: &visit::FnKind, decl: &ast::FnDecl,
+                _: visit::FnKind, decl: &ast::FnDecl,
                 _: &ast::Block, _: Span, _: ast::NodeId) {
         for a in decl.inputs.iter() {
             self.check_unused_mut_pat(cx, &[a.pat]);
@@ -1387,9 +1387,9 @@ fn check_item(&mut self, cx: &Context, it: &ast::Item) {
     }
 
     fn check_fn(&mut self, cx: &Context,
-            fk: &visit::FnKind, _: &ast::FnDecl,
+            fk: visit::FnKind, _: &ast::FnDecl,
             _: &ast::Block, _: Span, _: ast::NodeId) {
-        match *fk {
+        match fk {
             visit::FkMethod(_, _, m) => {
                 // If the method is an impl for a trait, don't doc.
                 if method_context(cx, m) == TraitImpl { return; }
@@ -1525,6 +1525,9 @@ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
 declare_lint!(pub UNUSED_IMPORTS, Warn,
               "imports that are never used")
 
+declare_lint!(pub UNUSED_EXTERN_CRATE, Allow,
+              "extern crates that are never used")
+
 declare_lint!(pub UNNECESSARY_QUALIFICATION, Allow,
               "detects unnecessarily qualified names")
 
@@ -1569,6 +1572,7 @@ impl LintPass for HardwiredLints {
     fn get_lints(&self) -> LintArray {
         lint_array!(
             UNUSED_IMPORTS,
+            UNUSED_EXTERN_CRATE,
             UNNECESSARY_QUALIFICATION,
             UNRECOGNIZED_LINT,
             UNUSED_VARIABLE,
index 26ed5cbfb2cc1b89491c5bfb2fb3502183e11a4f..b1975ab913fc2e1d7b04ca338883ca552889a9b0 100644 (file)
@@ -201,7 +201,7 @@ macro_rules! add_lint_group ( ( $sess:ident, $name:expr, $($lint:ident),* ) => (
 
         add_lint_group!(sess, "unused",
                         UNUSED_IMPORTS, UNUSED_VARIABLE, DEAD_ASSIGNMENT, DEAD_CODE,
-                        UNUSED_MUT, UNREACHABLE_CODE)
+                        UNUSED_MUT, UNREACHABLE_CODE, UNUSED_EXTERN_CRATE)
 
         // We have one lint pass defined in this module.
         self.register_pass(sess, false, box GatherNodeLevels as LintPassObject);
@@ -492,68 +492,68 @@ fn ty_infer(&self, _span: Span) -> ty::t {
     }
 }
 
-impl<'a, 'tcx> Visitor<()> for Context<'a, 'tcx> {
-    fn visit_item(&mut self, it: &ast::Item, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> {
+    fn visit_item(&mut self, it: &ast::Item) {
         self.with_lint_attrs(it.attrs.as_slice(), |cx| {
             run_lints!(cx, check_item, it);
-            cx.visit_ids(|v| v.visit_item(it, ()));
-            visit::walk_item(cx, it, ());
+            cx.visit_ids(|v| v.visit_item(it));
+            visit::walk_item(cx, it);
         })
     }
 
-    fn visit_foreign_item(&mut self, it: &ast::ForeignItem, _: ()) {
+    fn visit_foreign_item(&mut self, it: &ast::ForeignItem) {
         self.with_lint_attrs(it.attrs.as_slice(), |cx| {
             run_lints!(cx, check_foreign_item, it);
-            visit::walk_foreign_item(cx, it, ());
+            visit::walk_foreign_item(cx, it);
         })
     }
 
-    fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
+    fn visit_view_item(&mut self, i: &ast::ViewItem) {
         self.with_lint_attrs(i.attrs.as_slice(), |cx| {
             run_lints!(cx, check_view_item, i);
-            cx.visit_ids(|v| v.visit_view_item(i, ()));
-            visit::walk_view_item(cx, i, ());
+            cx.visit_ids(|v| v.visit_view_item(i));
+            visit::walk_view_item(cx, i);
         })
     }
 
-    fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
+    fn visit_pat(&mut self, p: &ast::Pat) {
         run_lints!(self, check_pat, p);
-        visit::walk_pat(self, p, ());
+        visit::walk_pat(self, p);
     }
 
-    fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
+    fn visit_expr(&mut self, e: &ast::Expr) {
         run_lints!(self, check_expr, e);
-        visit::walk_expr(self, e, ());
+        visit::walk_expr(self, e);
     }
 
-    fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
+    fn visit_stmt(&mut self, s: &ast::Stmt) {
         run_lints!(self, check_stmt, s);
-        visit::walk_stmt(self, s, ());
+        visit::walk_stmt(self, s);
     }
 
-    fn visit_fn(&mut self, fk: &FnKind, decl: &ast::FnDecl,
-                body: &ast::Block, span: Span, id: ast::NodeId, _: ()) {
-        match *fk {
+    fn visit_fn(&mut self, fk: FnKind<'v>, decl: &'v ast::FnDecl,
+                body: &'v ast::Block, span: Span, id: ast::NodeId) {
+        match fk {
             visit::FkMethod(_, _, m) => {
                 self.with_lint_attrs(m.attrs.as_slice(), |cx| {
                     run_lints!(cx, check_fn, fk, decl, body, span, id);
                     cx.visit_ids(|v| {
-                        v.visit_fn(fk, decl, body, span, id, ());
+                        v.visit_fn(fk, decl, body, span, id);
                     });
-                    visit::walk_fn(cx, fk, decl, body, span, ());
+                    visit::walk_fn(cx, fk, decl, body, span);
                 })
             },
             _ => {
                 run_lints!(self, check_fn, fk, decl, body, span, id);
-                visit::walk_fn(self, fk, decl, body, span, ());
+                visit::walk_fn(self, fk, decl, body, span);
             }
         }
     }
 
-    fn visit_ty_method(&mut self, t: &ast::TypeMethod, _: ()) {
+    fn visit_ty_method(&mut self, t: &ast::TypeMethod) {
         self.with_lint_attrs(t.attrs.as_slice(), |cx| {
             run_lints!(cx, check_ty_method, t);
-            visit::walk_ty_method(cx, t, ());
+            visit::walk_ty_method(cx, t);
         })
     }
 
@@ -561,103 +561,102 @@ fn visit_struct_def(&mut self,
                         s: &ast::StructDef,
                         ident: ast::Ident,
                         g: &ast::Generics,
-                        id: ast::NodeId,
-                        _: ()) {
+                        id: ast::NodeId) {
         run_lints!(self, check_struct_def, s, ident, g, id);
-        visit::walk_struct_def(self, s, ());
+        visit::walk_struct_def(self, s);
         run_lints!(self, check_struct_def_post, s, ident, g, id);
     }
 
-    fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
+    fn visit_struct_field(&mut self, s: &ast::StructField) {
         self.with_lint_attrs(s.node.attrs.as_slice(), |cx| {
             run_lints!(cx, check_struct_field, s);
-            visit::walk_struct_field(cx, s, ());
+            visit::walk_struct_field(cx, s);
         })
     }
 
-    fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
+    fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
         self.with_lint_attrs(v.node.attrs.as_slice(), |cx| {
             run_lints!(cx, check_variant, v, g);
-            visit::walk_variant(cx, v, g, ());
+            visit::walk_variant(cx, v, g);
         })
     }
 
     // FIXME(#10894) should continue recursing
-    fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
+    fn visit_ty(&mut self, t: &ast::Ty) {
         run_lints!(self, check_ty, t);
     }
 
-    fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) {
+    fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
         run_lints!(self, check_ident, sp, id);
     }
 
-    fn visit_mod(&mut self, m: &ast::Mod, s: Span, n: ast::NodeId, _: ()) {
+    fn visit_mod(&mut self, m: &ast::Mod, s: Span, n: ast::NodeId) {
         run_lints!(self, check_mod, m, s, n);
-        visit::walk_mod(self, m, ());
+        visit::walk_mod(self, m);
     }
 
-    fn visit_local(&mut self, l: &ast::Local, _: ()) {
+    fn visit_local(&mut self, l: &ast::Local) {
         run_lints!(self, check_local, l);
-        visit::walk_local(self, l, ());
+        visit::walk_local(self, l);
     }
 
-    fn visit_block(&mut self, b: &ast::Block, _: ()) {
+    fn visit_block(&mut self, b: &ast::Block) {
         run_lints!(self, check_block, b);
-        visit::walk_block(self, b, ());
+        visit::walk_block(self, b);
     }
 
-    fn visit_arm(&mut self, a: &ast::Arm, _: ()) {
+    fn visit_arm(&mut self, a: &ast::Arm) {
         run_lints!(self, check_arm, a);
-        visit::walk_arm(self, a, ());
+        visit::walk_arm(self, a);
     }
 
-    fn visit_decl(&mut self, d: &ast::Decl, _: ()) {
+    fn visit_decl(&mut self, d: &ast::Decl) {
         run_lints!(self, check_decl, d);
-        visit::walk_decl(self, d, ());
+        visit::walk_decl(self, d);
     }
 
-    fn visit_expr_post(&mut self, e: &ast::Expr, _: ()) {
+    fn visit_expr_post(&mut self, e: &ast::Expr) {
         run_lints!(self, check_expr_post, e);
     }
 
-    fn visit_generics(&mut self, g: &ast::Generics, _: ()) {
+    fn visit_generics(&mut self, g: &ast::Generics) {
         run_lints!(self, check_generics, g);
-        visit::walk_generics(self, g, ());
+        visit::walk_generics(self, g);
     }
 
-    fn visit_trait_item(&mut self, m: &ast::TraitItem, _: ()) {
+    fn visit_trait_item(&mut self, m: &ast::TraitItem) {
         run_lints!(self, check_trait_method, m);
-        visit::walk_trait_item(self, m, ());
+        visit::walk_trait_item(self, m);
     }
 
-    fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option<ast::Lifetime>, _: ()) {
+    fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option<ast::Lifetime>) {
         run_lints!(self, check_opt_lifetime_ref, sp, lt);
     }
 
-    fn visit_lifetime_ref(&mut self, lt: &ast::Lifetime, _: ()) {
+    fn visit_lifetime_ref(&mut self, lt: &ast::Lifetime) {
         run_lints!(self, check_lifetime_ref, lt);
     }
 
-    fn visit_lifetime_decl(&mut self, lt: &ast::LifetimeDef, _: ()) {
+    fn visit_lifetime_decl(&mut self, lt: &ast::LifetimeDef) {
         run_lints!(self, check_lifetime_decl, lt);
     }
 
-    fn visit_explicit_self(&mut self, es: &ast::ExplicitSelf, _: ()) {
+    fn visit_explicit_self(&mut self, es: &ast::ExplicitSelf) {
         run_lints!(self, check_explicit_self, es);
-        visit::walk_explicit_self(self, es, ());
+        visit::walk_explicit_self(self, es);
     }
 
-    fn visit_mac(&mut self, mac: &ast::Mac, _: ()) {
+    fn visit_mac(&mut self, mac: &ast::Mac) {
         run_lints!(self, check_mac, mac);
-        visit::walk_mac(self, mac, ());
+        visit::walk_mac(self, mac);
     }
 
-    fn visit_path(&mut self, p: &ast::Path, id: ast::NodeId, _: ()) {
+    fn visit_path(&mut self, p: &ast::Path, id: ast::NodeId) {
         run_lints!(self, check_path, p, id);
-        visit::walk_path(self, p, ());
+        visit::walk_path(self, p);
     }
 
-    fn visit_attribute(&mut self, attr: &ast::Attribute, _: ()) {
+    fn visit_attribute(&mut self, attr: &ast::Attribute) {
         run_lints!(self, check_attribute, attr);
     }
 }
@@ -719,14 +718,14 @@ pub fn check_crate(tcx: &ty::ctxt,
         cx.visit_id(ast::CRATE_NODE_ID);
         cx.visit_ids(|v| {
             v.visited_outermost = true;
-            visit::walk_crate(v, krate, ());
+            visit::walk_crate(v, krate);
         });
 
         // since the root module isn't visited as an item (because it isn't an
         // item), warn for it here.
         run_lints!(cx, check_crate, krate);
 
-        visit::walk_crate(cx, krate, ());
+        visit::walk_crate(cx, krate);
     });
 
     // If we missed any lints added to the session, then there's a bug somewhere
index dbdda96dcb84fb7f9e1c785309d8f96a01363f35..9a3edbbb70bb05a49f39a808a6b635db8d51a56c 100644 (file)
@@ -139,7 +139,7 @@ fn check_expr_post(&mut self, _: &Context, _: &ast::Expr) { }
     fn check_ty(&mut self, _: &Context, _: &ast::Ty) { }
     fn check_generics(&mut self, _: &Context, _: &ast::Generics) { }
     fn check_fn(&mut self, _: &Context,
-        _: &FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { }
+        _: FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { }
     fn check_ty_method(&mut self, _: &Context, _: &ast::TypeMethod) { }
     fn check_trait_method(&mut self, _: &Context, _: &ast::TraitItem) { }
     fn check_struct_def(&mut self, _: &Context,
index 321eee3d5fcefa664df18b69c24e79208ecbcfb8..8c17c16afee1b11b8bbe2ba44ee9316d6e78ea32 100644 (file)
@@ -49,19 +49,19 @@ pub fn read_crates(sess: &Session,
         next_crate_num: sess.cstore.next_crate_num(),
     };
     visit_crate(&e, krate);
-    visit::walk_crate(&mut e, krate, ());
+    visit::walk_crate(&mut e, krate);
     dump_crates(&sess.cstore);
     warn_if_multiple_versions(sess.diagnostic(), &sess.cstore)
 }
 
-impl<'a> visit::Visitor<()> for Env<'a> {
-    fn visit_view_item(&mut self, a: &ast::ViewItem, _: ()) {
+impl<'a, 'v> visit::Visitor<'v> for Env<'a> {
+    fn visit_view_item(&mut self, a: &ast::ViewItem) {
         visit_view_item(self, a);
-        visit::walk_view_item(self, a, ());
+        visit::walk_view_item(self, a);
     }
-    fn visit_item(&mut self, a: &ast::Item, _: ()) {
+    fn visit_item(&mut self, a: &ast::Item) {
         visit_item(self, a);
-        visit::walk_item(self, a, ());
+        visit::walk_item(self, a);
     }
 }
 
index a105a56a09b15d9ef0afe3a34bb3a8bcf253b314..209a09dbfafdfb87f88e5b27bbf67b46cac78628 100644 (file)
@@ -1473,20 +1473,20 @@ struct EncodeVisitor<'a,'b:'a> {
     index: &'a mut Vec<entry<i64>>,
 }
 
-impl<'a,'b> visit::Visitor<()> for EncodeVisitor<'a,'b> {
-    fn visit_expr(&mut self, ex: &Expr, _: ()) {
-        visit::walk_expr(self, ex, ());
+impl<'a, 'b, 'v> Visitor<'v> for EncodeVisitor<'a, 'b> {
+    fn visit_expr(&mut self, ex: &Expr) {
+        visit::walk_expr(self, ex);
         my_visit_expr(ex);
     }
-    fn visit_item(&mut self, i: &Item, _: ()) {
-        visit::walk_item(self, i, ());
+    fn visit_item(&mut self, i: &Item) {
+        visit::walk_item(self, i);
         my_visit_item(i,
                       self.rbml_w_for_visit_item,
                       self.ecx_ptr,
                       self.index);
     }
-    fn visit_foreign_item(&mut self, ni: &ForeignItem, _: ()) {
-        visit::walk_foreign_item(self, ni, ());
+    fn visit_foreign_item(&mut self, ni: &ForeignItem) {
+        visit::walk_foreign_item(self, ni);
         my_visit_foreign_item(ni,
                               self.rbml_w_for_visit_item,
                               self.ecx_ptr,
@@ -1519,7 +1519,7 @@ fn encode_info_for_items(ecx: &EncodeContext,
         index: &mut index,
         ecx_ptr: ecx_ptr,
         rbml_w_for_visit_item: &mut *rbml_w,
-    }, krate, ());
+    }, krate);
 
     rbml_w.end_tag();
     index
@@ -1775,8 +1775,8 @@ struct StructFieldVisitor<'a, 'b:'a> {
         rbml_w: &'a mut Encoder<'b>,
     }
 
-    impl<'a, 'b> Visitor<()> for StructFieldVisitor<'a, 'b> {
-        fn visit_struct_field(&mut self, field: &ast::StructField, _: ()) {
+    impl<'a, 'b, 'v> Visitor<'v> for StructFieldVisitor<'a, 'b> {
+        fn visit_struct_field(&mut self, field: &ast::StructField) {
             self.rbml_w.start_tag(tag_struct_field);
             self.rbml_w.wr_tagged_u32(tag_struct_field_id, field.node.id);
             encode_attributes(self.rbml_w, field.node.attrs.as_slice());
@@ -1787,7 +1787,7 @@ fn visit_struct_field(&mut self, field: &ast::StructField, _: ()) {
     rbml_w.start_tag(tag_struct_fields);
     visit::walk_crate(&mut StructFieldVisitor {
         rbml_w: rbml_w
-    }, krate, ());
+    }, krate);
     rbml_w.end_tag();
 }
 
@@ -1798,8 +1798,8 @@ struct ImplVisitor<'a, 'b:'a, 'c:'a, 'tcx:'b> {
     rbml_w: &'a mut Encoder<'c>,
 }
 
-impl<'a, 'b, 'c, 'tcx> Visitor<()> for ImplVisitor<'a, 'b, 'c, 'tcx> {
-    fn visit_item(&mut self, item: &Item, _: ()) {
+impl<'a, 'b, 'c, 'tcx, 'v> Visitor<'v> for ImplVisitor<'a, 'b, 'c, 'tcx> {
+    fn visit_item(&mut self, item: &Item) {
         match item.node {
             ItemImpl(_, Some(ref trait_ref), _, _) => {
                 let def_map = &self.ecx.tcx.def_map;
@@ -1817,7 +1817,7 @@ fn visit_item(&mut self, item: &Item, _: ()) {
             }
             _ => {}
         }
-        visit::walk_item(self, item, ());
+        visit::walk_item(self, item);
     }
 }
 
@@ -1841,7 +1841,7 @@ fn encode_impls<'a>(ecx: &'a EncodeContext,
             ecx: ecx,
             rbml_w: rbml_w,
         };
-        visit::walk_crate(&mut visitor, krate, ());
+        visit::walk_crate(&mut visitor, krate);
     }
 
     rbml_w.end_tag();
index 49c24b190b22b98003b6786de8b3fac27a214b21..bdabb3efb98ba5dbbb9fb3a4cfb424997d3cbec4 100644 (file)
@@ -13,7 +13,6 @@
 use std::cell::RefCell;
 use std::os;
 use std::io::fs;
-use std::dynamic_lib::DynamicLibrary;
 use std::collections::HashSet;
 
 use util::fs as myfs;
@@ -134,11 +133,24 @@ pub fn new(sysroot: &'a Path,
         }
     }
 
-    pub fn add_dylib_search_paths(&self) {
+    // Returns a list of directories where target-specific dylibs might be located.
+    pub fn get_dylib_search_paths(&self) -> Vec<Path> {
+        let mut paths = Vec::new();
         self.for_each_lib_search_path(|lib_search_path| {
-            DynamicLibrary::prepend_search_path(lib_search_path);
+            paths.push(lib_search_path.clone());
             FileDoesntMatch
-        })
+        });
+        paths
+    }
+
+    // Returns a list of directories where target-specific tool binaries are located.
+    pub fn get_tools_search_paths(&self) -> Vec<Path> {
+        let mut p = Path::new(self.sysroot);
+        p.push(find_libdir(self.sysroot));
+        p.push(rustlibdir());
+        p.push(self.triple);
+        p.push("bin");
+        vec![p]
     }
 }
 
index 11189390df565921317ae28cb11b24c1bc6b00bb..cd003432ef22c4a3705ddc63f6342af5cb97067c 100644 (file)
@@ -26,7 +26,7 @@
 use syntax::ast;
 use syntax::codemap::Span;
 use syntax::visit;
-use syntax::visit::{Visitor};
+use syntax::visit::Visitor;
 use syntax::ast::{Expr, FnDecl, Block, NodeId, Pat};
 
 mod lifetime;
@@ -471,8 +471,8 @@ struct StaticInitializerCtxt<'a, 'tcx: 'a> {
     bccx: &'a BorrowckCtxt<'a, 'tcx>
 }
 
-impl<'a, 'tcx> visit::Visitor<()> for StaticInitializerCtxt<'a, 'tcx> {
-    fn visit_expr(&mut self, ex: &Expr, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for StaticInitializerCtxt<'a, 'tcx> {
+    fn visit_expr(&mut self, ex: &Expr) {
         match ex.node {
             ast::ExprAddrOf(mutbl, ref base) => {
                 let base_cmt = self.bccx.cat_expr(&**base);
@@ -486,7 +486,7 @@ fn visit_expr(&mut self, ex: &Expr, _: ()) {
             _ => {}
         }
 
-        visit::walk_expr(self, ex, ());
+        visit::walk_expr(self, ex);
     }
 }
 
@@ -498,5 +498,5 @@ pub fn gather_loans_in_static_initializer(bccx: &mut BorrowckCtxt, expr: &ast::E
         bccx: bccx
     };
 
-    sicx.visit_expr(expr, ());
+    sicx.visit_expr(expr);
 }
index 5969e7e0c42d5a8a286035d370be9d324e5e04fa..acc2f47a0fe6834dda54b9660f7bd99afe7ac824 100644 (file)
@@ -60,13 +60,13 @@ macro_rules! if_ok(
 
 pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
 
-impl<'a, 'tcx> Visitor<()> for BorrowckCtxt<'a, 'tcx> {
-    fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl,
-                b: &Block, s: Span, n: NodeId, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for BorrowckCtxt<'a, 'tcx> {
+    fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
+                b: &'v Block, s: Span, n: NodeId) {
         borrowck_fn(self, fk, fd, b, s, n);
     }
 
-    fn visit_item(&mut self, item: &ast::Item, _: ()) {
+    fn visit_item(&mut self, item: &ast::Item) {
         borrowck_item(self, item);
     }
 }
@@ -83,7 +83,7 @@ pub fn check_crate(tcx: &ty::ctxt,
         }
     };
 
-    visit::walk_crate(&mut bccx, krate, ());
+    visit::walk_crate(&mut bccx, krate);
 
     if tcx.sess.borrowck_stats() {
         println!("--- borrowck stats ---");
@@ -114,7 +114,7 @@ fn borrowck_item(this: &mut BorrowckCtxt, item: &ast::Item) {
             gather_loans::gather_loans_in_static_initializer(this, &*ex);
         }
         _ => {
-            visit::walk_item(this, item, ());
+            visit::walk_item(this, item);
         }
     }
 }
@@ -127,7 +127,7 @@ pub struct AnalysisData<'a, 'tcx: 'a> {
 }
 
 fn borrowck_fn(this: &mut BorrowckCtxt,
-               fk: &FnKind,
+               fk: FnKind,
                decl: &ast::FnDecl,
                body: &ast::Block,
                sp: Span,
@@ -142,11 +142,11 @@ fn borrowck_fn(this: &mut BorrowckCtxt,
     check_loans::check_loans(this, &loan_dfcx, flowed_moves,
                              all_loans.as_slice(), decl, body);
 
-    visit::walk_fn(this, fk, decl, body, sp, ());
+    visit::walk_fn(this, fk, decl, body, sp);
 }
 
 fn build_borrowck_dataflow_data<'a, 'tcx>(this: &mut BorrowckCtxt<'a, 'tcx>,
-                                          fk: &FnKind,
+                                          fk: FnKind,
                                           decl: &ast::FnDecl,
                                           cfg: &cfg::CFG,
                                           body: &ast::Block,
@@ -217,7 +217,7 @@ pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
     let p = input.fn_parts;
 
     let dataflow_data = build_borrowck_dataflow_data(&mut bccx,
-                                                     &p.kind,
+                                                     p.kind,
                                                      &*p.decl,
                                                      input.cfg,
                                                      &*p.body,
index a9a3d94ded897a0ce2bede4f0738b6260b582725..c0160b72784ca14a2e489e252b25099651b02285 100644 (file)
 use syntax::visit::Visitor;
 use syntax::visit;
 
-pub struct CheckCrateVisitor<'a, 'tcx: 'a> {
+struct CheckCrateVisitor<'a, 'tcx: 'a> {
     tcx: &'a ty::ctxt<'tcx>,
+    in_const: bool
 }
 
-impl<'a, 'tcx> Visitor<bool> for CheckCrateVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, i: &Item, env: bool) {
-        check_item(self, i, env);
+impl<'a, 'tcx> CheckCrateVisitor<'a, 'tcx> {
+    fn with_const(&mut self, in_const: bool, f: |&mut CheckCrateVisitor<'a, 'tcx>|) {
+        let was_const = self.in_const;
+        self.in_const = in_const;
+        f(self);
+        self.in_const = was_const;
     }
-    fn visit_pat(&mut self, p: &Pat, env: bool) {
-        check_pat(self, p, env);
+    fn inside_const(&mut self, f: |&mut CheckCrateVisitor<'a, 'tcx>|) {
+        self.with_const(true, f);
     }
-    fn visit_expr(&mut self, ex: &Expr, env: bool) {
-        check_expr(self, ex, env);
+    fn outside_const(&mut self, f: |&mut CheckCrateVisitor<'a, 'tcx>|) {
+        self.with_const(false, f);
+    }
+}
+
+impl<'a, 'tcx, 'v> Visitor<'v> for CheckCrateVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, i: &Item) {
+        check_item(self, i);
+    }
+    fn visit_pat(&mut self, p: &Pat) {
+        check_pat(self, p);
+    }
+    fn visit_expr(&mut self, ex: &Expr) {
+        check_expr(self, ex);
     }
 }
 
 pub fn check_crate(krate: &Crate, tcx: &ty::ctxt) {
-    visit::walk_crate(&mut CheckCrateVisitor { tcx: tcx }, krate, false);
+    visit::walk_crate(&mut CheckCrateVisitor { tcx: tcx, in_const: false }, krate);
     tcx.sess.abort_if_errors();
 }
 
-fn check_item(v: &mut CheckCrateVisitor, it: &Item, _is_const: bool) {
+fn check_item(v: &mut CheckCrateVisitor, it: &Item) {
     match it.node {
         ItemStatic(_, _, ex) => {
-            v.visit_expr(&*ex, true);
+            v.inside_const(|v| v.visit_expr(&*ex));
             check_item_recursion(&v.tcx.sess, &v.tcx.map, &v.tcx.def_map, it);
         }
         ItemEnum(ref enum_definition, _) => {
             for var in (*enum_definition).variants.iter() {
                 for ex in var.node.disr_expr.iter() {
-                    v.visit_expr(&**ex, true);
+                    v.inside_const(|v| v.visit_expr(&**ex));
                 }
             }
         }
-        _ => visit::walk_item(v, it, false)
+        _ => v.outside_const(|v| visit::walk_item(v, it))
     }
 }
 
-fn check_pat(v: &mut CheckCrateVisitor, p: &Pat, _is_const: bool) {
+fn check_pat(v: &mut CheckCrateVisitor, p: &Pat) {
     fn is_str(e: &Expr) -> bool {
         match e.node {
             ExprBox(_, expr) => {
@@ -72,18 +88,18 @@ fn is_str(e: &Expr) -> bool {
         }
     }
     match p.node {
-      // Let through plain ~-string literals here
-      PatLit(ref a) => if !is_str(&**a) { v.visit_expr(&**a, true); },
-      PatRange(ref a, ref b) => {
-        if !is_str(&**a) { v.visit_expr(&**a, true); }
-        if !is_str(&**b) { v.visit_expr(&**b, true); }
-      }
-      _ => visit::walk_pat(v, p, false)
+        // Let through plain ~-string literals here
+        PatLit(ref a) => if !is_str(&**a) { v.inside_const(|v| v.visit_expr(&**a)); },
+        PatRange(ref a, ref b) => {
+            if !is_str(&**a) { v.inside_const(|v| v.visit_expr(&**a)); }
+            if !is_str(&**b) { v.inside_const(|v| v.visit_expr(&**b)); }
+        }
+        _ => v.outside_const(|v| visit::walk_pat(v, p))
     }
 }
 
-fn check_expr(v: &mut CheckCrateVisitor, e: &Expr, is_const: bool) {
-    if is_const {
+fn check_expr(v: &mut CheckCrateVisitor, e: &Expr) {
+    if v.in_const {
         match e.node {
           ExprUnary(UnDeref, _) => { }
           ExprUnary(UnBox, _) | ExprUnary(UnUniq, _) => {
@@ -165,7 +181,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &Expr, is_const: bool) {
                 }
             }
             match block.expr {
-                Some(ref expr) => check_expr(v, &**expr, true),
+                Some(ref expr) => check_expr(v, &**expr),
                 None => {}
             }
           }
@@ -195,7 +211,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &Expr, is_const: bool) {
           }
         }
     }
-    visit::walk_expr(v, e, is_const);
+    visit::walk_expr(v, e);
 }
 
 struct CheckItemRecursionVisitor<'a> {
@@ -219,32 +235,32 @@ pub fn check_item_recursion<'a>(sess: &'a Session,
         def_map: def_map,
         idstack: Vec::new()
     };
-    visitor.visit_item(it, ());
+    visitor.visit_item(it);
 }
 
-impl<'a> Visitor<()> for CheckItemRecursionVisitor<'a> {
-    fn visit_item(&mut self, it: &Item, _: ()) {
+impl<'a, 'v> Visitor<'v> for CheckItemRecursionVisitor<'a> {
+    fn visit_item(&mut self, it: &Item) {
         if self.idstack.iter().any(|x| x == &(it.id)) {
             self.sess.span_fatal(self.root_it.span, "recursive constant");
         }
         self.idstack.push(it.id);
-        visit::walk_item(self, it, ());
+        visit::walk_item(self, it);
         self.idstack.pop();
     }
 
-    fn visit_expr(&mut self, e: &Expr, _: ()) {
+    fn visit_expr(&mut self, e: &Expr) {
         match e.node {
             ExprPath(..) => {
                 match self.def_map.borrow().find(&e.id) {
                     Some(&DefStatic(def_id, _)) if
                             ast_util::is_local(def_id) => {
-                        self.visit_item(&*self.ast_map.expect_item(def_id.node), ());
+                        self.visit_item(&*self.ast_map.expect_item(def_id.node));
                     }
                     _ => ()
                 }
             },
             _ => ()
         }
-        visit::walk_expr(self, e, ());
+        visit::walk_expr(self, e);
     }
 }
index a40294328c71be484b64d33dcff380736a789cac..3abf49bdfb2923c161003080566880e2b887d0f1 100644 (file)
@@ -22,45 +22,53 @@ enum Context {
 
 struct CheckLoopVisitor<'a> {
     sess: &'a Session,
+    cx: Context
 }
 
 pub fn check_crate(sess: &Session, krate: &ast::Crate) {
-    visit::walk_crate(&mut CheckLoopVisitor { sess: sess }, krate, Normal)
+    visit::walk_crate(&mut CheckLoopVisitor { sess: sess, cx: Normal }, krate)
 }
 
-impl<'a> Visitor<Context> for CheckLoopVisitor<'a> {
-    fn visit_item(&mut self, i: &ast::Item, _cx: Context) {
-        visit::walk_item(self, i, Normal);
+impl<'a, 'v> Visitor<'v> for CheckLoopVisitor<'a> {
+    fn visit_item(&mut self, i: &ast::Item) {
+        self.with_context(Normal, |v| visit::walk_item(v, i));
     }
 
-    fn visit_expr(&mut self, e: &ast::Expr, cx:Context) {
+    fn visit_expr(&mut self, e: &ast::Expr) {
         match e.node {
             ast::ExprWhile(ref e, ref b, _) => {
-                self.visit_expr(&**e, cx);
-                self.visit_block(&**b, Loop);
+                self.visit_expr(&**e);
+                self.with_context(Loop, |v| v.visit_block(&**b));
             }
             ast::ExprLoop(ref b, _) => {
-                self.visit_block(&**b, Loop);
+                self.with_context(Loop, |v| v.visit_block(&**b));
             }
             ast::ExprForLoop(_, ref e, ref b, _) => {
-                self.visit_expr(&**e, cx);
-                self.visit_block(&**b, Loop);
+                self.visit_expr(&**e);
+                self.with_context(Loop, |v| v.visit_block(&**b));
             }
             ast::ExprFnBlock(_, _, ref b) |
             ast::ExprProc(_, ref b) |
             ast::ExprUnboxedFn(_, _, _, ref b) => {
-                self.visit_block(&**b, Closure);
+                self.with_context(Closure, |v| v.visit_block(&**b));
             }
-            ast::ExprBreak(_) => self.require_loop("break", cx, e.span),
-            ast::ExprAgain(_) => self.require_loop("continue", cx, e.span),
-            _ => visit::walk_expr(self, e, cx)
+            ast::ExprBreak(_) => self.require_loop("break", e.span),
+            ast::ExprAgain(_) => self.require_loop("continue", e.span),
+            _ => visit::walk_expr(self, e)
         }
     }
 }
 
 impl<'a> CheckLoopVisitor<'a> {
-    fn require_loop(&self, name: &str, cx: Context, span: Span) {
-        match cx {
+    fn with_context(&mut self, cx: Context, f: |&mut CheckLoopVisitor<'a>|) {
+        let old_cx = self.cx;
+        self.cx = cx;
+        f(self);
+        self.cx = old_cx;
+    }
+
+    fn require_loop(&self, name: &str, span: Span) {
+        match self.cx {
             Loop => {}
             Closure => {
                 self.sess.span_err(span,
index 6676ea9851db0113bbfb9ab11be9ac32266c0625..6e8f6530075e6310680b8438c9bbebdafcd41f63 100644 (file)
@@ -119,26 +119,27 @@ enum WitnessPreference {
     LeaveOutWitness
 }
 
-impl<'a, 'tcx> Visitor<()> for MatchCheckCtxt<'a, 'tcx> {
-    fn visit_expr(&mut self, ex: &Expr, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for MatchCheckCtxt<'a, 'tcx> {
+    fn visit_expr(&mut self, ex: &Expr) {
         check_expr(self, ex);
     }
-    fn visit_local(&mut self, l: &Local, _: ()) {
+    fn visit_local(&mut self, l: &Local) {
         check_local(self, l);
     }
-    fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl, b: &Block, s: Span, _: NodeId, _: ()) {
+    fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
+                b: &'v Block, s: Span, _: NodeId) {
         check_fn(self, fk, fd, b, s);
     }
 }
 
 pub fn check_crate(tcx: &ty::ctxt, krate: &Crate) {
     let mut cx = MatchCheckCtxt { tcx: tcx };
-    visit::walk_crate(&mut cx, krate, ());
+    visit::walk_crate(&mut cx, krate);
     tcx.sess.abort_if_errors();
 }
 
 fn check_expr(cx: &mut MatchCheckCtxt, ex: &Expr) {
-    visit::walk_expr(cx, ex, ());
+    visit::walk_expr(cx, ex);
     match ex.node {
         ExprMatch(scrut, ref arms) => {
             // First, check legality of move bindings.
@@ -844,7 +845,7 @@ fn default(cx: &MatchCheckCtxt, r: &[Gc<Pat>]) -> Option<Vec<Gc<Pat>>> {
 }
 
 fn check_local(cx: &mut MatchCheckCtxt, loc: &Local) {
-    visit::walk_local(cx, loc, ());
+    visit::walk_local(cx, loc);
 
     let name = match loc.source {
         LocalLet => "local",
@@ -868,11 +869,11 @@ fn check_local(cx: &mut MatchCheckCtxt, loc: &Local) {
 }
 
 fn check_fn(cx: &mut MatchCheckCtxt,
-            kind: &FnKind,
+            kind: FnKind,
             decl: &FnDecl,
             body: &Block,
             sp: Span) {
-    visit::walk_fn(cx, kind, decl, body, sp, ());
+    visit::walk_fn(cx, kind, decl, body, sp);
     for input in decl.inputs.iter() {
         match is_refutable(cx, input.pat) {
             Some(pat) => {
@@ -1014,27 +1015,30 @@ fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) {
 /// because of the way rvalues are handled in the borrow check. (See issue
 /// #14587.)
 fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) {
-    let mut visitor = AtBindingPatternVisitor {
-        cx: cx,
-    };
-    visitor.visit_pat(pat, true);
+    AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
 }
 
 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
     cx: &'a MatchCheckCtxt<'b, 'tcx>,
+    bindings_allowed: bool
 }
 
-impl<'a, 'b, 'tcx> Visitor<bool> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
-    fn visit_pat(&mut self, pat: &Pat, bindings_allowed: bool) {
-        if !bindings_allowed && pat_is_binding(&self.cx.tcx.def_map, pat) {
+impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
+    fn visit_pat(&mut self, pat: &Pat) {
+        if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map, pat) {
             self.cx.tcx.sess.span_err(pat.span,
                                       "pattern bindings are not allowed \
                                        after an `@`");
         }
 
         match pat.node {
-            PatIdent(_, _, Some(_)) => visit::walk_pat(self, pat, false),
-            _ => visit::walk_pat(self, pat, bindings_allowed),
+            PatIdent(_, _, Some(_)) => {
+                let bindings_were_allowed = self.bindings_allowed;
+                self.bindings_allowed = false;
+                visit::walk_pat(self, pat);
+                self.bindings_allowed = bindings_were_allowed;
+            }
+            _ => visit::walk_pat(self, pat),
         }
     }
 }
index f851ddbeeac238f3e88b6d389c84296e9b1bbbcd..21023986e1c2e68705472ad870ac7d44d6008b6e 100644 (file)
 pub fn check_crate(tcx: &ty::ctxt,
                    krate: &ast::Crate) {
     let mut rvcx = RvalueContext { tcx: tcx };
-    visit::walk_crate(&mut rvcx, krate, ());
+    visit::walk_crate(&mut rvcx, krate);
 }
 
 struct RvalueContext<'a, 'tcx: 'a> {
     tcx: &'a ty::ctxt<'tcx>
 }
 
-impl<'a, 'tcx> visit::Visitor<()> for RvalueContext<'a, 'tcx> {
+impl<'a, 'tcx, 'v> visit::Visitor<'v> for RvalueContext<'a, 'tcx> {
     fn visit_fn(&mut self,
-                _: &visit::FnKind,
-                fd: &ast::FnDecl,
-                b: &ast::Block,
+                _: visit::FnKind<'v>,
+                fd: &'v ast::FnDecl,
+                b: &'v ast::Block,
                 _: Span,
-                _: ast::NodeId,
-                _: ()) {
+                _: ast::NodeId) {
         let mut euv = euv::ExprUseVisitor::new(self, self.tcx);
         euv.walk_fn(fd, b);
     }
index ca58b4b6e60a40d8f498880c7b4c24d5d48b7e2a..46896b8811f00597ce4bb198b1a9ef7c5b77573b 100644 (file)
@@ -27,7 +27,6 @@
 use middle::ty;
 
 use syntax::ast;
-use syntax::codemap::Span;
 use syntax::visit::Visitor;
 use syntax::visit;
 use syntax::print::pprust;
@@ -54,41 +53,42 @@ fn safe_type_for_static_mut(cx: &ty::ctxt, e: &ast::Expr) -> Option<String> {
 
 struct CheckStaticVisitor<'a, 'tcx: 'a> {
     tcx: &'a ty::ctxt<'tcx>,
+    in_const: bool
 }
 
 pub fn check_crate(tcx: &ty::ctxt, krate: &ast::Crate) {
-    visit::walk_crate(&mut CheckStaticVisitor { tcx: tcx }, krate, false)
+    visit::walk_crate(&mut CheckStaticVisitor { tcx: tcx, in_const: false }, krate)
 }
 
 impl<'a, 'tcx> CheckStaticVisitor<'a, 'tcx> {
-    fn report_error(&self, span: Span, result: Option<String>) -> bool {
-        match result {
-            None => { false }
-            Some(msg) => {
-                self.tcx.sess.span_err(span, msg.as_slice());
-                true
-            }
-        }
+    fn with_const(&mut self, in_const: bool, f: |&mut CheckStaticVisitor<'a, 'tcx>|) {
+        let was_const = self.in_const;
+        self.in_const = in_const;
+        f(self);
+        self.in_const = was_const;
     }
 }
 
-impl<'a, 'tcx> Visitor<bool> for CheckStaticVisitor<'a, 'tcx> {
-
-    fn visit_item(&mut self, i: &ast::Item, _is_const: bool) {
+impl<'a, 'tcx, 'v> Visitor<'v> for CheckStaticVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, i: &ast::Item) {
         debug!("visit_item(item={})", pprust::item_to_string(i));
         match i.node {
             ast::ItemStatic(_, mutability, ref expr) => {
                 match mutability {
                     ast::MutImmutable => {
-                        self.visit_expr(&**expr, true);
+                        self.with_const(true, |v| v.visit_expr(&**expr));
                     }
                     ast::MutMutable => {
-                        let safe = safe_type_for_static_mut(self.tcx, &**expr);
-                        self.report_error(expr.span, safe);
+                        match safe_type_for_static_mut(self.tcx, &**expr) {
+                            Some(msg) => {
+                                self.tcx.sess.span_err(expr.span, msg.as_slice());
+                            }
+                            None => {}
+                        }
                     }
                 }
             }
-            _ => { visit::walk_item(self, i, false) }
+            _ => self.with_const(false, |v| visit::walk_item(v, i))
         }
     }
 
@@ -98,17 +98,17 @@ fn visit_item(&mut self, i: &ast::Item, _is_const: bool) {
     /// every nested expression. if the expression is not part
     /// of a static item, this method does nothing but walking
     /// down through it.
-    fn visit_expr(&mut self, e: &ast::Expr, is_const: bool) {
+    fn visit_expr(&mut self, e: &ast::Expr) {
         debug!("visit_expr(expr={})", pprust::expr_to_string(e));
 
-        if !is_const {
-            return visit::walk_expr(self, e, is_const);
+        if !self.in_const {
+            return visit::walk_expr(self, e);
         }
 
         match e.node {
             ast::ExprField(..) | ast::ExprTupField(..) | ast::ExprVec(..) |
             ast::ExprBlock(..) | ast::ExprTup(..)  => {
-                visit::walk_expr(self, e, is_const);
+                visit::walk_expr(self, e);
             }
             ast::ExprAddrOf(ast::MutMutable, _) => {
                 span_err!(self.tcx.sess, e.span, E0020,
@@ -130,15 +130,14 @@ fn visit_expr(&mut self, e: &ast::Expr, is_const: bool) {
                     ty::ty_struct(did, _) |
                     ty::ty_enum(did, _) => {
                         if ty::has_dtor(self.tcx, did) {
-                            self.report_error(e.span,
-                             Some("static items are not allowed to have \
-                                   destructors".to_string()));
+                            self.tcx.sess.span_err(e.span,
+                                "static items are not allowed to have destructors");
                             return;
                         }
                     }
                     _ => {}
                 }
-                visit::walk_expr(self, e, is_const);
+                visit::walk_expr(self, e);
             }
         }
     }
index 2b4b6756f9f859ce046b06e4084a5461423f2f2f..23ab6f4585b1fb1f9408bf0231e19955f784ecd3 100644 (file)
@@ -268,8 +268,8 @@ fn lookup_constness(&self, e: &Expr) -> constness {
 
 }
 
-impl<'a, 'tcx> Visitor<()> for ConstEvalVisitor<'a, 'tcx> {
-    fn visit_ty(&mut self, t: &Ty, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for ConstEvalVisitor<'a, 'tcx> {
+    fn visit_ty(&mut self, t: &Ty) {
         match t.node {
             TyFixedLengthVec(_, expr) => {
                 check::check_const_in_type(self.tcx, &*expr, ty::mk_uint());
@@ -277,10 +277,10 @@ fn visit_ty(&mut self, t: &Ty, _: ()) {
             _ => {}
         }
 
-        visit::walk_ty(self, t, ());
+        visit::walk_ty(self, t);
     }
 
-    fn visit_expr_post(&mut self, e: &Expr, _: ()) {
+    fn visit_expr_post(&mut self, e: &Expr) {
         self.classify(e);
     }
 }
@@ -291,7 +291,7 @@ pub fn process_crate(krate: &ast::Crate,
         tcx: tcx,
         ccache: DefIdMap::new(),
     };
-    visit::walk_crate(&mut v, krate, ());
+    visit::walk_crate(&mut v, krate);
     tcx.sess.abort_if_errors();
 }
 
index c32f8db2380e428456e96553142398e8622a9962..d39b560c6d5305ce3b638079fed68b87e1fb9299 100644 (file)
@@ -172,11 +172,11 @@ struct Formals<'a> {
             index: &'a mut NodeMap<CFGIndex>,
         }
         let mut formals = Formals { entry: entry, index: index };
-        visit::walk_fn_decl(&mut formals, decl, ());
-        impl<'a> visit::Visitor<()> for Formals<'a> {
-            fn visit_pat(&mut self, p: &ast::Pat, e: ()) {
+        visit::walk_fn_decl(&mut formals, decl);
+        impl<'a, 'v> visit::Visitor<'v> for Formals<'a> {
+            fn visit_pat(&mut self, p: &ast::Pat) {
                 self.index.insert(p.id, self.entry);
-                visit::walk_pat(self, p, e)
+                visit::walk_pat(self, p)
             }
         }
     }
index f275c818716599a9fee9ad6577c3ed8aea074299..68bcd950f9ce7207ecba2f97cfa47c2bca000ce5 100644 (file)
@@ -51,10 +51,6 @@ struct MarkSymbolVisitor<'a, 'tcx: 'a> {
     worklist: Vec<ast::NodeId>,
     tcx: &'a ty::ctxt<'tcx>,
     live_symbols: Box<HashSet<ast::NodeId>>,
-}
-
-#[deriving(Clone)]
-struct MarkSymbolVisitorContext {
     struct_has_extern_repr: bool
 }
 
@@ -65,6 +61,7 @@ fn new(tcx: &'a ty::ctxt<'tcx>,
             worklist: worklist,
             tcx: tcx,
             live_symbols: box HashSet::new(),
+            struct_has_extern_repr: false
         }
     }
 
@@ -199,66 +196,64 @@ fn mark_live_symbols(&mut self) {
     }
 
     fn visit_node(&mut self, node: &ast_map::Node) {
-        let ctxt = MarkSymbolVisitorContext {
-            struct_has_extern_repr: false
-        };
+        let had_extern_repr = self.struct_has_extern_repr;
+        self.struct_has_extern_repr = false;
         match *node {
             ast_map::NodeItem(item) => {
                 match item.node {
                     ast::ItemStruct(..) => {
-                        let has_extern_repr = item.attrs.iter().fold(false, |acc, attr| {
-                            acc || attr::find_repr_attrs(self.tcx.sess.diagnostic(), attr)
-                                         .iter().any(|&x| x == attr::ReprExtern)
+                        self.struct_has_extern_repr = item.attrs.iter().any(|attr| {
+                            attr::find_repr_attrs(self.tcx.sess.diagnostic(), attr)
+                                .contains(&attr::ReprExtern)
                         });
 
-                        visit::walk_item(self, &*item, MarkSymbolVisitorContext {
-                            struct_has_extern_repr: has_extern_repr,
-                            ..(ctxt)
-                        });
+                        visit::walk_item(self, &*item);
                     }
                     ast::ItemFn(..)
                     | ast::ItemEnum(..)
                     | ast::ItemTy(..)
                     | ast::ItemStatic(..) => {
-                        visit::walk_item(self, &*item, ctxt);
+                        visit::walk_item(self, &*item);
                     }
                     _ => ()
                 }
             }
             ast_map::NodeTraitItem(trait_method) => {
-                visit::walk_trait_item(self, &*trait_method, ctxt);
+                visit::walk_trait_item(self, &*trait_method);
             }
             ast_map::NodeImplItem(impl_item) => {
                 match *impl_item {
                     ast::MethodImplItem(method) => {
-                        visit::walk_block(self, &*method.pe_body(), ctxt);
+                        visit::walk_block(self, &*method.pe_body());
                     }
                 }
             }
             ast_map::NodeForeignItem(foreign_item) => {
-                visit::walk_foreign_item(self, &*foreign_item, ctxt);
+                visit::walk_foreign_item(self, &*foreign_item);
             }
             _ => ()
         }
+        self.struct_has_extern_repr = had_extern_repr;
     }
 }
 
-impl<'a, 'tcx> Visitor<MarkSymbolVisitorContext> for MarkSymbolVisitor<'a, 'tcx> {
+impl<'a, 'tcx, 'v> Visitor<'v> for MarkSymbolVisitor<'a, 'tcx> {
 
-    fn visit_struct_def(&mut self, def: &ast::StructDef, _: ast::Ident, _: &ast::Generics,
-                        _: ast::NodeId, ctxt: MarkSymbolVisitorContext) {
+    fn visit_struct_def(&mut self, def: &ast::StructDef, _: ast::Ident,
+                        _: &ast::Generics, _: ast::NodeId) {
+        let has_extern_repr = self.struct_has_extern_repr;
         let live_fields = def.fields.iter().filter(|f| {
-            ctxt.struct_has_extern_repr || match f.node.kind {
+            has_extern_repr || match f.node.kind {
                 ast::NamedField(_, ast::Public) => true,
                 _ => false
             }
         });
         self.live_symbols.extend(live_fields.map(|f| f.node.id));
 
-        visit::walk_struct_def(self, def, ctxt);
+        visit::walk_struct_def(self, def);
     }
 
-    fn visit_expr(&mut self, expr: &ast::Expr, ctxt: MarkSymbolVisitorContext) {
+    fn visit_expr(&mut self, expr: &ast::Expr) {
         match expr.node {
             ast::ExprMethodCall(..) => {
                 self.lookup_and_handle_method(expr.id, expr.span);
@@ -272,10 +267,10 @@ fn visit_expr(&mut self, expr: &ast::Expr, ctxt: MarkSymbolVisitorContext) {
             _ => ()
         }
 
-        visit::walk_expr(self, expr, ctxt);
+        visit::walk_expr(self, expr);
     }
 
-    fn visit_pat(&mut self, pat: &ast::Pat, ctxt: MarkSymbolVisitorContext) {
+    fn visit_pat(&mut self, pat: &ast::Pat) {
         match pat.node {
             ast::PatStruct(_, ref fields, _) => {
                 self.handle_field_pattern_match(pat, fields.as_slice());
@@ -287,15 +282,15 @@ fn visit_pat(&mut self, pat: &ast::Pat, ctxt: MarkSymbolVisitorContext) {
             _ => ()
         }
 
-        visit::walk_pat(self, pat, ctxt);
+        visit::walk_pat(self, pat);
     }
 
-    fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId, ctxt: MarkSymbolVisitorContext) {
+    fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId) {
         self.lookup_and_handle_definition(&id);
-        visit::walk_path(self, path, ctxt);
+        visit::walk_path(self, path);
     }
 
-    fn visit_item(&mut self, _: &ast::Item, _: MarkSymbolVisitorContext) {
+    fn visit_item(&mut self, _: &ast::Item) {
         // Do not recurse into items. These items will be added to the
         // worklist and recursed into manually if necessary.
     }
@@ -334,8 +329,8 @@ struct LifeSeeder {
     worklist: Vec<ast::NodeId> ,
 }
 
-impl Visitor<()> for LifeSeeder {
-    fn visit_item(&mut self, item: &ast::Item, _: ()) {
+impl<'v> Visitor<'v> for LifeSeeder {
+    fn visit_item(&mut self, item: &ast::Item) {
         if has_allow_dead_code_or_lang_attr(item.attrs.as_slice()) {
             self.worklist.push(item.id);
         }
@@ -351,14 +346,14 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
             }
             _ => ()
         }
-        visit::walk_item(self, item, ());
+        visit::walk_item(self, item);
     }
 
-    fn visit_fn(&mut self, fk: &visit::FnKind,
-                _: &ast::FnDecl, block: &ast::Block,
-                _: codemap::Span, id: ast::NodeId, _: ()) {
+    fn visit_fn(&mut self, fk: visit::FnKind<'v>,
+                _: &'v ast::FnDecl, block: &'v ast::Block,
+                _: codemap::Span, id: ast::NodeId) {
         // Check for method here because methods are not ast::Item
-        match *fk {
+        match fk {
             visit::FkMethod(_, _, method) => {
                 if has_allow_dead_code_or_lang_attr(method.attrs.as_slice()) {
                     self.worklist.push(id);
@@ -366,7 +361,7 @@ fn visit_fn(&mut self, fk: &visit::FnKind,
             }
             _ => ()
         }
-        visit::walk_block(self, block, ());
+        visit::walk_block(self, block);
     }
 }
 
@@ -398,7 +393,7 @@ fn create_and_seed_worklist(tcx: &ty::ctxt,
     let mut life_seeder = LifeSeeder {
         worklist: worklist
     };
-    visit::walk_crate(&mut life_seeder, krate, ());
+    visit::walk_crate(&mut life_seeder, krate);
 
     return life_seeder.worklist;
 }
@@ -504,51 +499,50 @@ fn warn_dead_code(&mut self,
     }
 }
 
-impl<'a, 'tcx> Visitor<()> for DeadVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, item: &ast::Item, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for DeadVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, item: &ast::Item) {
         let ctor_id = get_struct_ctor_id(item);
         if !self.symbol_is_live(item.id, ctor_id) && should_warn(item) {
             self.warn_dead_code(item.id, item.span, item.ident);
         }
-        visit::walk_item(self, item, ());
+        visit::walk_item(self, item);
     }
 
-    fn visit_foreign_item(&mut self, fi: &ast::ForeignItem, _: ()) {
+    fn visit_foreign_item(&mut self, fi: &ast::ForeignItem) {
         if !self.symbol_is_live(fi.id, None) {
             self.warn_dead_code(fi.id, fi.span, fi.ident);
         }
-        visit::walk_foreign_item(self, fi, ());
+        visit::walk_foreign_item(self, fi);
     }
 
-    fn visit_fn(&mut self, fk: &visit::FnKind,
-                _: &ast::FnDecl, block: &ast::Block,
-                span: codemap::Span, id: ast::NodeId, _: ()) {
+    fn visit_fn(&mut self, fk: visit::FnKind<'v>,
+                _: &'v ast::FnDecl, block: &'v ast::Block,
+                span: codemap::Span, id: ast::NodeId) {
         // Have to warn method here because methods are not ast::Item
-        match *fk {
-            visit::FkMethod(..) => {
-                let ident = visit::name_of_fn(fk);
+        match fk {
+            visit::FkMethod(name, _, _) => {
                 if !self.symbol_is_live(id, None) {
-                    self.warn_dead_code(id, span, ident);
+                    self.warn_dead_code(id, span, name);
                 }
             }
             _ => ()
         }
-        visit::walk_block(self, block, ());
+        visit::walk_block(self, block);
     }
 
-    fn visit_struct_field(&mut self, field: &ast::StructField, _: ()) {
+    fn visit_struct_field(&mut self, field: &ast::StructField) {
         if self.should_warn_about_field(&field.node) {
             self.warn_dead_code(field.node.id, field.span, field.node.ident().unwrap());
         }
 
-        visit::walk_struct_field(self, field, ());
+        visit::walk_struct_field(self, field);
     }
 
     // Overwrite so that we don't warn the trait method itself.
-    fn visit_trait_item(&mut self, trait_method: &ast::TraitItem, _: ()) {
+    fn visit_trait_item(&mut self, trait_method: &ast::TraitItem) {
         match *trait_method {
             ast::ProvidedMethod(ref method) => {
-                visit::walk_block(self, &*method.pe_body(), ())
+                visit::walk_block(self, &*method.pe_body())
             }
             ast::RequiredMethod(_) => ()
         }
@@ -562,5 +556,5 @@ pub fn check_crate(tcx: &ty::ctxt,
     let live_symbols = find_live(tcx, exported_items,
                                  reachable_symbols, krate);
     let mut visitor = DeadVisitor { tcx: tcx, live_symbols: live_symbols };
-    visit::walk_crate(&mut visitor, krate, ());
+    visit::walk_crate(&mut visitor, krate);
 }
index ec1430edcddb9c1e02a23edcaff134eedfb34660..db9eb90b6ec02e0a40edcb568acc648267432c1a 100644 (file)
@@ -86,11 +86,11 @@ fn check_str_index(&mut self, e: &ast::Expr) {
     }
 }
 
-impl<'a, 'tcx> Visitor<()> for EffectCheckVisitor<'a, 'tcx> {
-    fn visit_fn(&mut self, fn_kind: &visit::FnKind, fn_decl: &ast::FnDecl,
-                block: &ast::Block, span: Span, _: ast::NodeId, _:()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for EffectCheckVisitor<'a, 'tcx> {
+    fn visit_fn(&mut self, fn_kind: visit::FnKind<'v>, fn_decl: &'v ast::FnDecl,
+                block: &'v ast::Block, span: Span, _: ast::NodeId) {
 
-        let (is_item_fn, is_unsafe_fn) = match *fn_kind {
+        let (is_item_fn, is_unsafe_fn) = match fn_kind {
             visit::FkItemFn(_, _, fn_style, _) =>
                 (true, fn_style == ast::UnsafeFn),
             visit::FkMethod(_, _, method) =>
@@ -105,12 +105,12 @@ fn visit_fn(&mut self, fn_kind: &visit::FnKind, fn_decl: &ast::FnDecl,
             self.unsafe_context = SafeContext
         }
 
-        visit::walk_fn(self, fn_kind, fn_decl, block, span, ());
+        visit::walk_fn(self, fn_kind, fn_decl, block, span);
 
         self.unsafe_context = old_unsafe_context
     }
 
-    fn visit_block(&mut self, block: &ast::Block, _:()) {
+    fn visit_block(&mut self, block: &ast::Block) {
         let old_unsafe_context = self.unsafe_context;
         match block.rules {
             ast::DefaultBlock => {}
@@ -136,12 +136,12 @@ fn visit_block(&mut self, block: &ast::Block, _:()) {
             }
         }
 
-        visit::walk_block(self, block, ());
+        visit::walk_block(self, block);
 
         self.unsafe_context = old_unsafe_context
     }
 
-    fn visit_expr(&mut self, expr: &ast::Expr, _:()) {
+    fn visit_expr(&mut self, expr: &ast::Expr) {
         match expr.node {
             ast::ExprMethodCall(_, _, _) => {
                 let method_call = MethodCall::expr(expr.id);
@@ -193,7 +193,7 @@ fn visit_expr(&mut self, expr: &ast::Expr, _:()) {
             _ => {}
         }
 
-        visit::walk_expr(self, expr, ());
+        visit::walk_expr(self, expr);
     }
 }
 
@@ -203,5 +203,5 @@ pub fn check_crate(tcx: &ty::ctxt, krate: &ast::Crate) {
         unsafe_context: SafeContext,
     };
 
-    visit::walk_crate(&mut visitor, krate, ());
+    visit::walk_crate(&mut visitor, krate);
 }
index 3debdc158fe26c0d8c64f33cb454c1f0452284bd..2b96eb717ea860bad06a658f653f6a3fb415daaa 100644 (file)
@@ -41,8 +41,8 @@ struct EntryContext<'a> {
     non_main_fns: Vec<(NodeId, Span)> ,
 }
 
-impl<'a> Visitor<()> for EntryContext<'a> {
-    fn visit_item(&mut self, item: &Item, _:()) {
+impl<'a, 'v> Visitor<'v> for EntryContext<'a> {
+    fn visit_item(&mut self, item: &Item) {
         find_item(item, self);
     }
 }
@@ -72,7 +72,7 @@ pub fn find_entry_point(session: &Session, krate: &Crate, ast_map: &ast_map::Map
         non_main_fns: Vec::new(),
     };
 
-    visit::walk_crate(&mut ctxt, krate, ());
+    visit::walk_crate(&mut ctxt, krate);
 
     configure_main(&mut ctxt);
 }
@@ -118,7 +118,7 @@ fn find_item(item: &Item, ctxt: &mut EntryContext) {
         _ => ()
     }
 
-    visit::walk_item(ctxt, item, ());
+    visit::walk_item(ctxt, item);
 }
 
 fn configure_main(this: &mut EntryContext) {
index df5a6b6d2a113003dcbf2e39329bebeb67ec51f6..5b7c72208ea7d181976aa2d0a0913c425352dbdf 100644 (file)
@@ -50,18 +50,21 @@ struct CollectFreevarsVisitor<'a> {
     refs: Vec<freevar_entry>,
     def_map: &'a resolve::DefMap,
     capture_mode_map: &'a mut CaptureModeMap,
+    depth: uint
 }
 
-impl<'a> Visitor<int> for CollectFreevarsVisitor<'a> {
-    fn visit_item(&mut self, _: &ast::Item, _: int) {
+impl<'a, 'v> Visitor<'v> for CollectFreevarsVisitor<'a> {
+    fn visit_item(&mut self, _: &ast::Item) {
         // ignore_item
     }
 
-    fn visit_expr(&mut self, expr: &ast::Expr, depth: int) {
+    fn visit_expr(&mut self, expr: &ast::Expr) {
         match expr.node {
             ast::ExprProc(..) => {
                 self.capture_mode_map.insert(expr.id, CaptureByValue);
-                visit::walk_expr(self, expr, depth + 1)
+                self.depth += 1;
+                visit::walk_expr(self, expr);
+                self.depth -= 1;
             }
             ast::ExprFnBlock(_, _, _) => {
                 // NOTE(stage0): After snapshot, change to:
@@ -72,7 +75,9 @@ fn visit_expr(&mut self, expr: &ast::Expr, depth: int) {
                 //};
                 let capture_mode = CaptureByRef;
                 self.capture_mode_map.insert(expr.id, capture_mode);
-                visit::walk_expr(self, expr, depth + 1)
+                self.depth += 1;
+                visit::walk_expr(self, expr);
+                self.depth -= 1;
             }
             ast::ExprUnboxedFn(capture_clause, _, _, _) => {
                 let capture_mode = match capture_clause {
@@ -80,35 +85,33 @@ fn visit_expr(&mut self, expr: &ast::Expr, depth: int) {
                     ast::CaptureByRef => CaptureByRef,
                 };
                 self.capture_mode_map.insert(expr.id, capture_mode);
-                visit::walk_expr(self, expr, depth + 1)
+                self.depth += 1;
+                visit::walk_expr(self, expr);
+                self.depth -= 1;
             }
             ast::ExprPath(..) => {
+                let mut def = *self.def_map.borrow().find(&expr.id)
+                                                    .expect("path not found");
                 let mut i = 0;
-                match self.def_map.borrow().find(&expr.id) {
-                    None => fail!("path not found"),
-                    Some(&df) => {
-                        let mut def = df;
-                        while i < depth {
-                            match def {
-                                def::DefUpvar(_, inner, _, _) => { def = *inner; }
-                                _ => break
-                            }
-                            i += 1;
-                        }
-                        if i == depth { // Made it to end of loop
-                            let dnum = def.def_id().node;
-                            if !self.seen.contains(&dnum) {
-                                self.refs.push(freevar_entry {
-                                    def: def,
-                                    span: expr.span,
-                                });
-                                self.seen.insert(dnum);
-                            }
-                        }
+                while i < self.depth {
+                    match def {
+                        def::DefUpvar(_, inner, _, _) => { def = *inner; }
+                        _ => break
+                    }
+                    i += 1;
+                }
+                if i == self.depth { // Made it to end of loop
+                    let dnum = def.def_id().node;
+                    if !self.seen.contains(&dnum) {
+                        self.refs.push(freevar_entry {
+                            def: def,
+                            span: expr.span,
+                        });
+                        self.seen.insert(dnum);
                     }
                 }
             }
-            _ => visit::walk_expr(self, expr, depth)
+            _ => visit::walk_expr(self, expr)
         }
     }
 }
@@ -127,9 +130,10 @@ fn collect_freevars(def_map: &resolve::DefMap,
         refs: Vec::new(),
         def_map: def_map,
         capture_mode_map: &mut *capture_mode_map,
+        depth: 1
     };
 
-    v.visit_block(blk, 1);
+    v.visit_block(blk);
 
     v.refs
 }
@@ -140,14 +144,14 @@ struct AnnotateFreevarsVisitor<'a> {
     capture_mode_map: CaptureModeMap,
 }
 
-impl<'a> Visitor<()> for AnnotateFreevarsVisitor<'a> {
-    fn visit_fn(&mut self, fk: &visit::FnKind, fd: &ast::FnDecl,
-                blk: &ast::Block, s: Span, nid: ast::NodeId, _: ()) {
+impl<'a, 'v> Visitor<'v> for AnnotateFreevarsVisitor<'a> {
+    fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
+                blk: &'v ast::Block, s: Span, nid: ast::NodeId) {
         let vars = collect_freevars(self.def_map,
                                     blk,
                                     &mut self.capture_mode_map);
         self.freevars.insert(nid, vars);
-        visit::walk_fn(self, fk, fd, blk, s, ());
+        visit::walk_fn(self, fk, fd, blk, s);
     }
 }
 
@@ -163,7 +167,7 @@ pub fn annotate_freevars(def_map: &resolve::DefMap, krate: &ast::Crate)
         freevars: NodeMap::new(),
         capture_mode_map: NodeMap::new(),
     };
-    visit::walk_crate(&mut visitor, krate, ());
+    visit::walk_crate(&mut visitor, krate);
 
     let AnnotateFreevarsVisitor {
         freevars,
index 25a8555565c93ae8e6e62a75ee0461431fd2ef97..76ade1a7504eb69cf2d6cd31a20e28efee424883 100644 (file)
@@ -116,8 +116,8 @@ fn check_transmute(&self, span: Span, from: ty::t, to: ty::t, id: ast::NodeId) {
     }
 }
 
-impl<'a, 'tcx> Visitor<()> for IntrinsicCheckingVisitor<'a, 'tcx> {
-    fn visit_expr(&mut self, expr: &ast::Expr, (): ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for IntrinsicCheckingVisitor<'a, 'tcx> {
+    fn visit_expr(&mut self, expr: &ast::Expr) {
         match expr.node {
             ast::ExprPath(..) => {
                 match ty::resolve_expr(self.tcx, expr) {
@@ -144,7 +144,7 @@ fn visit_expr(&mut self, expr: &ast::Expr, (): ()) {
             _ => {}
         }
 
-        visit::walk_expr(self, expr, ());
+        visit::walk_expr(self, expr);
     }
 }
 
@@ -153,6 +153,6 @@ pub fn check_crate(tcx: &ctxt, krate: &ast::Crate) {
         tcx: tcx,
     };
 
-    visit::walk_crate(&mut visitor, krate, ());
+    visit::walk_crate(&mut visitor, krate);
 }
 
index e8b0afa98c2d0487c78f0f2d54ae4e0f5a723adb..1e398ce210b57c928a881b9f73a38e3e6e6b4717 100644 (file)
@@ -56,29 +56,29 @@ pub struct Context<'a, 'tcx: 'a> {
     parameter_environments: Vec<ParameterEnvironment>,
 }
 
-impl<'a, 'tcx> Visitor<()> for Context<'a, 'tcx> {
-    fn visit_expr(&mut self, ex: &Expr, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> {
+    fn visit_expr(&mut self, ex: &Expr) {
         check_expr(self, ex);
     }
 
-    fn visit_fn(&mut self, fk: &visit::FnKind, fd: &FnDecl,
-                b: &Block, s: Span, n: NodeId, _: ()) {
+    fn visit_fn(&mut self, fk: visit::FnKind, fd: &'v FnDecl,
+                b: &'v Block, s: Span, n: NodeId) {
         check_fn(self, fk, fd, b, s, n);
     }
 
-    fn visit_ty(&mut self, t: &Ty, _: ()) {
+    fn visit_ty(&mut self, t: &Ty) {
         check_ty(self, t);
     }
 
-    fn visit_item(&mut self, i: &Item, _: ()) {
+    fn visit_item(&mut self, i: &Item) {
         check_item(self, i);
     }
 
-    fn visit_pat(&mut self, p: &Pat, _: ()) {
+    fn visit_pat(&mut self, p: &Pat) {
         check_pat(self, p);
     }
 
-    fn visit_local(&mut self, l: &Local, _: ()) {
+    fn visit_local(&mut self, l: &Local) {
         check_local(self, l);
     }
 }
@@ -90,7 +90,7 @@ pub fn check_crate(tcx: &ty::ctxt,
         struct_and_enum_bounds_checked: HashSet::new(),
         parameter_environments: Vec::new(),
     };
-    visit::walk_crate(&mut ctx, krate, ());
+    visit::walk_crate(&mut ctx, krate);
     tcx.sess.abort_if_errors();
 }
 
@@ -265,7 +265,7 @@ fn check_item(cx: &mut Context, item: &Item) {
         }
     }
 
-    visit::walk_item(cx, item, ())
+    visit::walk_item(cx, item)
 }
 
 fn check_local(cx: &mut Context, local: &Local) {
@@ -274,7 +274,7 @@ fn check_local(cx: &mut Context, local: &Local) {
         local.span,
         ty::node_id_to_type(cx.tcx, local.id));
 
-    visit::walk_local(cx, local, ())
+    visit::walk_local(cx, local)
 }
 
 // Yields the appropriate function to check the kind of closed over
@@ -341,7 +341,7 @@ fn check_for_bare(cx: &Context, fv: &freevar_entry) {
 // to the copy/move kind bounds. Then recursively check the function body.
 fn check_fn(
     cx: &mut Context,
-    fk: &visit::FnKind,
+    fk: visit::FnKind,
     decl: &FnDecl,
     body: &Block,
     sp: Span,
@@ -356,12 +356,12 @@ fn check_fn(
         });
     });
 
-    match *fk {
+    match fk {
         visit::FkFnBlock(..) => {
             let ty = ty::node_id_to_type(cx.tcx, fn_id);
             check_bounds_on_structs_or_enums_in_type_if_possible(cx, sp, ty);
 
-            visit::walk_fn(cx, fk, decl, body, sp, ())
+            visit::walk_fn(cx, fk, decl, body, sp)
         }
         visit::FkItemFn(..) | visit::FkMethod(..) => {
             let parameter_environment = ParameterEnvironment::for_item(cx.tcx,
@@ -371,7 +371,7 @@ fn check_fn(
             let ty = ty::node_id_to_type(cx.tcx, fn_id);
             check_bounds_on_structs_or_enums_in_type_if_possible(cx, sp, ty);
 
-            visit::walk_fn(cx, fk, decl, body, sp, ());
+            visit::walk_fn(cx, fk, decl, body, sp);
             drop(cx.parameter_environments.pop());
         }
     }
@@ -451,7 +451,7 @@ pub fn check_expr(cx: &mut Context, e: &Expr) {
         None => {}
     }
 
-    visit::walk_expr(cx, e, ());
+    visit::walk_expr(cx, e);
 }
 
 fn check_bounds_on_type_parameters(cx: &mut Context, e: &Expr) {
@@ -616,7 +616,7 @@ fn check_ty(cx: &mut Context, aty: &Ty) {
         _ => {}
     }
 
-    visit::walk_ty(cx, aty, ());
+    visit::walk_ty(cx, aty);
 }
 
 // Calls "any_missing" if any bounds were missing.
@@ -804,5 +804,5 @@ fn check_pat(cx: &mut Context, pat: &Pat) {
         None => {}
     }
 
-    visit::walk_pat(cx, pat, ());
+    visit::walk_pat(cx, pat);
 }
index 2602ec4920e33714df2c6cdc329a132da24b33bb..24782240f06c4d3a58b30a24e11bfcf8188f4837 100644 (file)
@@ -115,8 +115,8 @@ struct LanguageItemCollector<'a> {
     item_refs: HashMap<&'static str, uint>,
 }
 
-impl<'a> Visitor<()> for LanguageItemCollector<'a> {
-    fn visit_item(&mut self, item: &ast::Item, _: ()) {
+impl<'a, 'v> Visitor<'v> for LanguageItemCollector<'a> {
+    fn visit_item(&mut self, item: &ast::Item) {
         match extract(item.attrs.as_slice()) {
             Some(value) => {
                 let item_index = self.item_refs.find_equiv(&value).map(|x| *x);
@@ -131,7 +131,7 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
             None => {}
         }
 
-        visit::walk_item(self, item, ());
+        visit::walk_item(self, item);
     }
 }
 
@@ -166,7 +166,7 @@ pub fn collect_item(&mut self, item_index: uint,
     }
 
     pub fn collect_local_language_items(&mut self, krate: &ast::Crate) {
-        visit::walk_crate(self, krate, ());
+        visit::walk_crate(self, krate);
     }
 
     pub fn collect_external_language_items(&mut self) {
index 84fc8ff2c38cae28d24d06b6887f1e6afd08c9f9..18f3de82280ef41a1278bf54df975f104817e8f5 100644 (file)
@@ -179,18 +179,19 @@ fn live_node_kind_to_string(lnk: LiveNodeKind, cx: &ty::ctxt) -> String {
     }
 }
 
-impl<'a, 'tcx> Visitor<()> for IrMaps<'a, 'tcx> {
-    fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl, b: &Block, s: Span, n: NodeId, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for IrMaps<'a, 'tcx> {
+    fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
+                b: &'v Block, s: Span, n: NodeId) {
         visit_fn(self, fk, fd, b, s, n);
     }
-    fn visit_local(&mut self, l: &Local, _: ()) { visit_local(self, l); }
-    fn visit_expr(&mut self, ex: &Expr, _: ()) { visit_expr(self, ex); }
-    fn visit_arm(&mut self, a: &Arm, _: ()) { visit_arm(self, a); }
+    fn visit_local(&mut self, l: &Local) { visit_local(self, l); }
+    fn visit_expr(&mut self, ex: &Expr) { visit_expr(self, ex); }
+    fn visit_arm(&mut self, a: &Arm) { visit_arm(self, a); }
 }
 
 pub fn check_crate(tcx: &ty::ctxt,
                    krate: &Crate) {
-    visit::walk_crate(&mut IrMaps::new(tcx), krate, ());
+    visit::walk_crate(&mut IrMaps::new(tcx), krate);
     tcx.sess.abort_if_errors();
 }
 
@@ -343,23 +344,23 @@ fn lnk(&self, ln: LiveNode) -> LiveNodeKind {
     }
 }
 
-impl<'a, 'tcx> Visitor<()> for Liveness<'a, 'tcx> {
-    fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl, b: &Block, s: Span, n: NodeId, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for Liveness<'a, 'tcx> {
+    fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl, b: &'v Block, s: Span, n: NodeId) {
         check_fn(self, fk, fd, b, s, n);
     }
-    fn visit_local(&mut self, l: &Local, _: ()) {
+    fn visit_local(&mut self, l: &Local) {
         check_local(self, l);
     }
-    fn visit_expr(&mut self, ex: &Expr, _: ()) {
+    fn visit_expr(&mut self, ex: &Expr) {
         check_expr(self, ex);
     }
-    fn visit_arm(&mut self, a: &Arm, _: ()) {
+    fn visit_arm(&mut self, a: &Arm) {
         check_arm(self, a);
     }
 }
 
 fn visit_fn(ir: &mut IrMaps,
-            fk: &FnKind,
+            fk: FnKind,
             decl: &FnDecl,
             body: &Block,
             sp: Span,
@@ -387,7 +388,7 @@ fn visit_fn(ir: &mut IrMaps,
 
     // gather up the various local variables, significant expressions,
     // and so forth:
-    visit::walk_fn(&mut fn_maps, fk, decl, body, sp, ());
+    visit::walk_fn(&mut fn_maps, fk, decl, body, sp);
 
     // Special nodes and variables:
     // - exit_ln represents the end of the fn, either by return or fail
@@ -404,7 +405,7 @@ fn visit_fn(ir: &mut IrMaps,
     let entry_ln = lsets.compute(decl, body);
 
     // check for various error conditions
-    lsets.visit_block(body, ());
+    lsets.visit_block(body);
     lsets.check_ret(id, sp, fk, entry_ln, body);
     lsets.warn_about_unused_args(decl, entry_ln);
 }
@@ -419,7 +420,7 @@ fn visit_local(ir: &mut IrMaps, local: &Local) {
           ident: name
         }));
     });
-    visit::walk_local(ir, local, ());
+    visit::walk_local(ir, local);
 }
 
 fn visit_arm(ir: &mut IrMaps, arm: &Arm) {
@@ -435,7 +436,7 @@ fn visit_arm(ir: &mut IrMaps, arm: &Arm) {
             }));
         })
     }
-    visit::walk_arm(ir, arm, ());
+    visit::walk_arm(ir, arm);
 }
 
 fn moved_variable_node_id_from_def(def: Def) -> Option<NodeId> {
@@ -457,7 +458,7 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) {
         if moved_variable_node_id_from_def(def).is_some() {
             ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
         }
-        visit::walk_expr(ir, expr, ());
+        visit::walk_expr(ir, expr);
       }
       ExprFnBlock(..) | ExprProc(..) | ExprUnboxedFn(..) => {
         // Interesting control flow (for loops can contain labeled
@@ -483,13 +484,13 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) {
         });
         ir.set_captures(expr.id, call_caps);
 
-        visit::walk_expr(ir, expr, ());
+        visit::walk_expr(ir, expr);
       }
 
       // live nodes required for interesting control flow:
       ExprIf(..) | ExprMatch(..) | ExprWhile(..) | ExprLoop(..) => {
         ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
-        visit::walk_expr(ir, expr, ());
+        visit::walk_expr(ir, expr);
       }
       ExprForLoop(ref pat, _, _, _) => {
         pat_util::pat_bindings(&ir.tcx.def_map, &**pat, |bm, p_id, sp, path1| {
@@ -503,11 +504,11 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) {
             }));
         });
         ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
-        visit::walk_expr(ir, expr, ());
+        visit::walk_expr(ir, expr);
       }
       ExprBinary(op, _, _) if ast_util::lazy_binop(op) => {
         ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
-        visit::walk_expr(ir, expr, ());
+        visit::walk_expr(ir, expr);
       }
 
       // otherwise, live nodes are not required:
@@ -519,7 +520,7 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) {
       ExprAssign(..) | ExprAssignOp(..) | ExprMac(..) |
       ExprStruct(..) | ExprRepeat(..) | ExprParen(..) |
       ExprInlineAsm(..) | ExprBox(..) => {
-          visit::walk_expr(ir, expr, ());
+          visit::walk_expr(ir, expr);
       }
     }
 }
@@ -1408,43 +1409,43 @@ fn check_local(this: &mut Liveness, local: &Local) {
         }
     }
 
-    visit::walk_local(this, local, ());
+    visit::walk_local(this, local);
 }
 
 fn check_arm(this: &mut Liveness, arm: &Arm) {
     this.arm_pats_bindings(arm.pats.as_slice(), |this, ln, var, sp, id| {
         this.warn_about_unused(sp, id, ln, var);
     });
-    visit::walk_arm(this, arm, ());
+    visit::walk_arm(this, arm);
 }
 
 fn check_expr(this: &mut Liveness, expr: &Expr) {
     match expr.node {
       ExprAssign(ref l, ref r) => {
         this.check_lvalue(&**l);
-        this.visit_expr(&**r, ());
+        this.visit_expr(&**r);
 
-        visit::walk_expr(this, expr, ());
+        visit::walk_expr(this, expr);
       }
 
       ExprAssignOp(_, ref l, _) => {
         this.check_lvalue(&**l);
 
-        visit::walk_expr(this, expr, ());
+        visit::walk_expr(this, expr);
       }
 
       ExprInlineAsm(ref ia) => {
         for &(_, ref input) in ia.inputs.iter() {
-          this.visit_expr(&**input, ());
+          this.visit_expr(&**input);
         }
 
         // Output operands must be lvalues
         for &(_, ref out, _) in ia.outputs.iter() {
           this.check_lvalue(&**out);
-          this.visit_expr(&**out, ());
+          this.visit_expr(&**out);
         }
 
-        visit::walk_expr(this, expr, ());
+        visit::walk_expr(this, expr);
       }
 
       // no correctness conditions related to liveness
@@ -1456,13 +1457,13 @@ fn check_expr(this: &mut Liveness, expr: &Expr) {
       ExprMac(..) | ExprAddrOf(..) | ExprStruct(..) | ExprRepeat(..) |
       ExprParen(..) | ExprFnBlock(..) | ExprProc(..) | ExprUnboxedFn(..) |
       ExprPath(..) | ExprBox(..) | ExprForLoop(..) => {
-        visit::walk_expr(this, expr, ());
+        visit::walk_expr(this, expr);
       }
     }
 }
 
 fn check_fn(_v: &Liveness,
-            _fk: &FnKind,
+            _fk: FnKind,
             _decl: &FnDecl,
             _body: &Block,
             _sp: Span,
@@ -1474,7 +1475,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
     fn check_ret(&self,
                  id: NodeId,
                  sp: Span,
-                 _fk: &FnKind,
+                 _fk: FnKind,
                  entry_ln: LiveNode,
                  body: &Block) {
         if self.live_on_entry(entry_ln, self.s.no_ret_var).is_some() {
@@ -1546,7 +1547,7 @@ fn check_lvalue(&mut self, expr: &Expr) {
           _ => {
             // For other kinds of lvalues, no checks are required,
             // and any embedded expressions are actually rvalues
-            visit::walk_expr(self, expr, ());
+            visit::walk_expr(self, expr);
           }
        }
     }
index cdb7d114af90306c792fd289eea0574c2d46a1bf..da957024b9a2e70669eddcfe42e690b9754fa635 100644 (file)
@@ -57,8 +57,8 @@ struct ParentVisitor {
     curparent: ast::NodeId,
 }
 
-impl Visitor<()> for ParentVisitor {
-    fn visit_item(&mut self, item: &ast::Item, _: ()) {
+impl<'v> Visitor<'v> for ParentVisitor {
+    fn visit_item(&mut self, item: &ast::Item) {
         self.parents.insert(item.id, self.curparent);
 
         let prev = self.curparent;
@@ -91,28 +91,28 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
 
             _ => {}
         }
-        visit::walk_item(self, item, ());
+        visit::walk_item(self, item);
         self.curparent = prev;
     }
 
-    fn visit_foreign_item(&mut self, a: &ast::ForeignItem, _: ()) {
+    fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
         self.parents.insert(a.id, self.curparent);
-        visit::walk_foreign_item(self, a, ());
+        visit::walk_foreign_item(self, a);
     }
 
-    fn visit_fn(&mut self, a: &visit::FnKind, b: &ast::FnDecl,
-                c: &ast::Block, d: Span, id: ast::NodeId, _: ()) {
+    fn visit_fn(&mut self, a: visit::FnKind<'v>, b: &'v ast::FnDecl,
+                c: &'v ast::Block, d: Span, id: ast::NodeId) {
         // We already took care of some trait methods above, otherwise things
         // like impl methods and pub trait methods are parented to the
         // containing module, not the containing trait.
         if !self.parents.contains_key(&id) {
             self.parents.insert(id, self.curparent);
         }
-        visit::walk_fn(self, a, b, c, d, ());
+        visit::walk_fn(self, a, b, c, d);
     }
 
     fn visit_struct_def(&mut self, s: &ast::StructDef, _: ast::Ident,
-                        _: &ast::Generics, n: ast::NodeId, _: ()) {
+                        _: &'v ast::Generics, n: ast::NodeId) {
         // Struct constructors are parented to their struct definitions because
         // they essentially are the struct definitions.
         match s.ctor_id {
@@ -125,7 +125,7 @@ fn visit_struct_def(&mut self, s: &ast::StructDef, _: ast::Ident,
         for field in s.fields.iter() {
             self.parents.insert(field.node.id, self.curparent);
         }
-        visit::walk_struct_def(self, s, ())
+        visit::walk_struct_def(self, s)
     }
 }
 
@@ -180,8 +180,8 @@ fn exported_trait(&self, _id: ast::NodeId) -> bool {
     }
 }
 
-impl<'a, 'tcx> Visitor<()> for EmbargoVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, item: &ast::Item, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, item: &ast::Item) {
         let orig_all_pub = self.prev_public;
         self.prev_public = orig_all_pub && item.vis == ast::Public;
         if self.prev_public {
@@ -323,19 +323,19 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
             _ => {}
         }
 
-        visit::walk_item(self, item, ());
+        visit::walk_item(self, item);
 
         self.prev_exported = orig_all_exported;
         self.prev_public = orig_all_pub;
     }
 
-    fn visit_foreign_item(&mut self, a: &ast::ForeignItem, _: ()) {
+    fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
         if (self.prev_exported && a.vis == ast::Public) || self.reexports.contains(&a.id) {
             self.exported_items.insert(a.id);
         }
     }
 
-    fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId, _: ()) {
+    fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId) {
         // This code is here instead of in visit_item so that the
         // crate module gets processed as well.
         if self.prev_exported {
@@ -347,7 +347,7 @@ fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId, _: ()) {
                 }
             }
         }
-        visit::walk_mod(self, m, ())
+        visit::walk_mod(self, m)
     }
 }
 
@@ -802,14 +802,14 @@ fn check_method(&mut self, span: Span, origin: MethodOrigin,
     }
 }
 
-impl<'a, 'tcx> Visitor<()> for PrivacyVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, item: &ast::Item, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, item: &ast::Item) {
         let orig_curitem = replace(&mut self.curitem, item.id);
-        visit::walk_item(self, item, ());
+        visit::walk_item(self, item);
         self.curitem = orig_curitem;
     }
 
-    fn visit_expr(&mut self, expr: &ast::Expr, _: ()) {
+    fn visit_expr(&mut self, expr: &ast::Expr) {
         match expr.node {
             ast::ExprField(ref base, ident, _) => {
                 match ty::get(ty::expr_ty_adjusted(self.tcx, &**base)).sty {
@@ -912,10 +912,10 @@ struct type?!"),
             _ => {}
         }
 
-        visit::walk_expr(self, expr, ());
+        visit::walk_expr(self, expr);
     }
 
-    fn visit_view_item(&mut self, a: &ast::ViewItem, _: ()) {
+    fn visit_view_item(&mut self, a: &ast::ViewItem) {
         match a.node {
             ast::ViewItemExternCrate(..) => {}
             ast::ViewItemUse(ref vpath) => {
@@ -949,10 +949,10 @@ fn visit_view_item(&mut self, a: &ast::ViewItem, _: ()) {
                 }
             }
         }
-        visit::walk_view_item(self, a, ());
+        visit::walk_view_item(self, a);
     }
 
-    fn visit_pat(&mut self, pattern: &ast::Pat, _: ()) {
+    fn visit_pat(&mut self, pattern: &ast::Pat) {
         // Foreign functions do not have their patterns mapped in the def_map,
         // and there's nothing really relevant there anyway, so don't bother
         // checking privacy. If you can name the type then you can pass it to an
@@ -1012,18 +1012,18 @@ struct type?!"),
             _ => {}
         }
 
-        visit::walk_pat(self, pattern, ());
+        visit::walk_pat(self, pattern);
     }
 
-    fn visit_foreign_item(&mut self, fi: &ast::ForeignItem, _: ()) {
+    fn visit_foreign_item(&mut self, fi: &ast::ForeignItem) {
         self.in_foreign = true;
-        visit::walk_foreign_item(self, fi, ());
+        visit::walk_foreign_item(self, fi);
         self.in_foreign = false;
     }
 
-    fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId, _: ()) {
+    fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId) {
         self.check_path(path.span, id, path);
-        visit::walk_path(self, path, ());
+        visit::walk_path(self, path);
     }
 }
 
@@ -1036,8 +1036,8 @@ struct SanePrivacyVisitor<'a, 'tcx: 'a> {
     in_fn: bool,
 }
 
-impl<'a, 'tcx> Visitor<()> for SanePrivacyVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, item: &ast::Item, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, item: &ast::Item) {
         if self.in_fn {
             self.check_all_inherited(item);
         } else {
@@ -1049,19 +1049,19 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
             ast::ItemMod(..) => false, // modules turn privacy back on
             _ => in_fn,           // otherwise we inherit
         });
-        visit::walk_item(self, item, ());
+        visit::walk_item(self, item);
         self.in_fn = orig_in_fn;
     }
 
-    fn visit_fn(&mut self, fk: &visit::FnKind, fd: &ast::FnDecl,
-                b: &ast::Block, s: Span, _: ast::NodeId, _: ()) {
+    fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
+                b: &'v ast::Block, s: Span, _: ast::NodeId) {
         // This catches both functions and methods
         let orig_in_fn = replace(&mut self.in_fn, true);
-        visit::walk_fn(self, fk, fd, b, s, ());
+        visit::walk_fn(self, fk, fd, b, s);
         self.in_fn = orig_in_fn;
     }
 
-    fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
+    fn visit_view_item(&mut self, i: &ast::ViewItem) {
         match i.vis {
             ast::Inherited => {}
             ast::Public => {
@@ -1080,7 +1080,7 @@ fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
                 }
             }
         }
-        visit::walk_view_item(self, i, ());
+        visit::walk_view_item(self, i);
     }
 }
 
@@ -1264,8 +1264,8 @@ fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
     }
 }
 
-impl<'a, 'b, 'tcx> Visitor<()> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
-    fn visit_ty(&mut self, ty: &ast::Ty, _: ()) {
+impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
+    fn visit_ty(&mut self, ty: &ast::Ty) {
         match ty.node {
             ast::TyPath(_, _, path_id) => {
                 if self.inner.path_is_private_type(path_id) {
@@ -1280,15 +1280,15 @@ fn visit_ty(&mut self, ty: &ast::Ty, _: ()) {
             _ => {}
         }
         self.at_outer_type = false;
-        visit::walk_ty(self, ty, ())
+        visit::walk_ty(self, ty)
     }
 
     // don't want to recurse into [, .. expr]
-    fn visit_expr(&mut self, _: &ast::Expr, _: ()) {}
+    fn visit_expr(&mut self, _: &ast::Expr) {}
 }
 
-impl<'a, 'tcx> Visitor<()> for VisiblePrivateTypesVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, item: &ast::Item, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, item: &ast::Item) {
         match item.node {
             // contents of a private mod can be reexported, so we need
             // to check internals.
@@ -1320,7 +1320,7 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
                         at_outer_type: true,
                         outer_type_is_public_path: false,
                     };
-                    visitor.visit_ty(&*self_, ());
+                    visitor.visit_ty(&*self_);
                     self_contains_private = visitor.contains_private;
                     self_is_public_path = visitor.outer_type_is_public_path;
                 }
@@ -1359,16 +1359,14 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
                         not_private_trait &&
                         trait_or_some_public_method {
 
-                    visit::walk_generics(self, g, ());
+                    visit::walk_generics(self, g);
 
                     match *trait_ref {
                         None => {
                             for impl_item in impl_items.iter() {
                                 match *impl_item {
                                     ast::MethodImplItem(method) => {
-                                        visit::walk_method_helper(self,
-                                                                  &*method,
-                                                                  ())
+                                        visit::walk_method_helper(self, &*method)
                                     }
                                 }
                             }
@@ -1386,7 +1384,7 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
                             //
                             // Those in 2. are warned via walk_generics and this
                             // call here.
-                            visit::walk_trait_ref_helper(self, tr, ())
+                            visit::walk_trait_ref_helper(self, tr)
                         }
                     }
                 } else if trait_ref.is_none() && self_is_public_path {
@@ -1401,15 +1399,13 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
                                         self.exported_items
                                             .contains(&method.id) {
                                     found_pub_static = true;
-                                    visit::walk_method_helper(self,
-                                                              &*method,
-                                                              ());
+                                    visit::walk_method_helper(self, &*method);
                                 }
                             }
                         }
                     }
                     if found_pub_static {
-                        visit::walk_generics(self, g, ())
+                        visit::walk_generics(self, g)
                     }
                 }
                 return
@@ -1429,25 +1425,24 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
         // any `visit_ty`'s will be called on things that are in
         // public signatures, i.e. things that we're interested in for
         // this visitor.
-        visit::walk_item(self, item, ());
+        visit::walk_item(self, item);
     }
 
-    fn visit_foreign_item(&mut self, item: &ast::ForeignItem, _: ()) {
+    fn visit_foreign_item(&mut self, item: &ast::ForeignItem) {
         if self.exported_items.contains(&item.id) {
-            visit::walk_foreign_item(self, item, ())
+            visit::walk_foreign_item(self, item)
         }
     }
 
-    fn visit_fn(&mut self,
-                fk: &visit::FnKind, fd: &ast::FnDecl, b: &ast::Block, s: Span, id: ast::NodeId,
-                _: ()) {
+    fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
+                b: &'v ast::Block, s: Span, id: ast::NodeId) {
         // needs special handling for methods.
         if self.exported_items.contains(&id) {
-            visit::walk_fn(self, fk, fd, b, s, ());
+            visit::walk_fn(self, fk, fd, b, s);
         }
     }
 
-    fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
+    fn visit_ty(&mut self, t: &ast::Ty) {
         match t.node {
             ast::TyPath(ref p, _, path_id) => {
                 if self.path_is_private_type(path_id) {
@@ -1460,19 +1455,19 @@ fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
             }
             _ => {}
         }
-        visit::walk_ty(self, t, ())
+        visit::walk_ty(self, t)
     }
 
-    fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
+    fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
         if self.exported_items.contains(&v.node.id) {
-            visit::walk_variant(self, v, g, ());
+            visit::walk_variant(self, v, g);
         }
     }
 
-    fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
+    fn visit_struct_field(&mut self, s: &ast::StructField) {
         match s.node.kind {
             ast::NamedField(_, ast::Public)  => {
-                visit::walk_struct_field(self, s, ());
+                visit::walk_struct_field(self, s);
             }
             _ => {}
         }
@@ -1484,9 +1479,9 @@ fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
     // things, and neither do view_items. (Making them no-ops stops us
     // from traversing the whole AST without having to be super
     // careful about our `walk_...` calls above.)
-    fn visit_view_item(&mut self, _: &ast::ViewItem, _: ()) {}
-    fn visit_block(&mut self, _: &ast::Block, _: ()) {}
-    fn visit_expr(&mut self, _: &ast::Expr, _: ()) {}
+    fn visit_view_item(&mut self, _: &ast::ViewItem) {}
+    fn visit_block(&mut self, _: &ast::Block) {}
+    fn visit_expr(&mut self, _: &ast::Expr) {}
 }
 
 pub fn check_crate(tcx: &ty::ctxt,
@@ -1499,7 +1494,7 @@ pub fn check_crate(tcx: &ty::ctxt,
         parents: NodeMap::new(),
         curparent: ast::DUMMY_NODE_ID,
     };
-    visit::walk_crate(&mut visitor, krate, ());
+    visit::walk_crate(&mut visitor, krate);
 
     // Use the parent map to check the privacy of everything
     let mut visitor = PrivacyVisitor {
@@ -1510,7 +1505,7 @@ pub fn check_crate(tcx: &ty::ctxt,
         external_exports: external_exports,
         last_private_map: last_private_map,
     };
-    visit::walk_crate(&mut visitor, krate, ());
+    visit::walk_crate(&mut visitor, krate);
 
     // Sanity check to make sure that all privacy usage and controls are
     // reasonable.
@@ -1518,7 +1513,7 @@ pub fn check_crate(tcx: &ty::ctxt,
         in_fn: false,
         tcx: tcx,
     };
-    visit::walk_crate(&mut visitor, krate, ());
+    visit::walk_crate(&mut visitor, krate);
 
     tcx.sess.abort_if_errors();
 
@@ -1535,7 +1530,7 @@ pub fn check_crate(tcx: &ty::ctxt,
     };
     loop {
         let before = visitor.exported_items.len();
-        visit::walk_crate(&mut visitor, krate, ());
+        visit::walk_crate(&mut visitor, krate);
         if before == visitor.exported_items.len() {
             break
         }
@@ -1549,7 +1544,7 @@ pub fn check_crate(tcx: &ty::ctxt,
             exported_items: &exported_items,
             public_items: &public_items
         };
-        visit::walk_crate(&mut visitor, krate, ());
+        visit::walk_crate(&mut visitor, krate);
     }
     return (exported_items, public_items);
 }
index 7ba5144985ef206a3e40ab9a156a0b2263632d00..d7cf25e7410e696edfd597cdb2057f468fed32a8 100644 (file)
@@ -101,9 +101,9 @@ struct ReachableContext<'a, 'tcx: 'a> {
     any_library: bool,
 }
 
-impl<'a, 'tcx> Visitor<()> for ReachableContext<'a, 'tcx> {
+impl<'a, 'tcx, 'v> Visitor<'v> for ReachableContext<'a, 'tcx> {
 
-    fn visit_expr(&mut self, expr: &ast::Expr, _: ()) {
+    fn visit_expr(&mut self, expr: &ast::Expr) {
 
         match expr.node {
             ast::ExprPath(_) => {
@@ -155,10 +155,10 @@ fn visit_expr(&mut self, expr: &ast::Expr, _: ()) {
             _ => {}
         }
 
-        visit::walk_expr(self, expr, ())
+        visit::walk_expr(self, expr)
     }
 
-    fn visit_item(&mut self, _item: &ast::Item, _: ()) {
+    fn visit_item(&mut self, _item: &ast::Item) {
         // Do not recurse into items. These items will be added to the worklist
         // and recursed into manually if necessary.
     }
@@ -291,7 +291,7 @@ fn propagate_node(&mut self, node: &ast_map::Node,
                 match item.node {
                     ast::ItemFn(_, _, _, _, ref search_block) => {
                         if item_might_be_inlined(&*item) {
-                            visit::walk_block(self, &**search_block, ())
+                            visit::walk_block(self, &**search_block)
                         }
                     }
 
@@ -303,7 +303,7 @@ fn propagate_node(&mut self, node: &ast_map::Node,
                                 item.attrs.as_slice()) {
                             self.reachable_symbols.remove(&search_item);
                         }
-                        visit::walk_expr(self, &**init, ());
+                        visit::walk_expr(self, &**init);
                     }
 
                     // These are normal, nothing reachable about these
@@ -327,7 +327,7 @@ fn propagate_node(&mut self, node: &ast_map::Node,
                         // Keep going, nothing to get exported
                     }
                     ast::ProvidedMethod(ref method) => {
-                        visit::walk_block(self, &*method.pe_body(), ())
+                        visit::walk_block(self, &*method.pe_body())
                     }
                 }
             }
@@ -336,7 +336,7 @@ fn propagate_node(&mut self, node: &ast_map::Node,
                     ast::MethodImplItem(method) => {
                         let did = self.tcx.map.get_parent_did(search_item);
                         if method_might_be_inlined(self.tcx, &*method, did) {
-                            visit::walk_block(self, &*method.pe_body(), ())
+                            visit::walk_block(self, &*method.pe_body())
                         }
                     }
                 }
index 0db3864a06bb8fefeb48ac74da23014b0670da5e..45107d26f2f8998663ca2b21b9445d57f6fa269d 100644 (file)
@@ -84,7 +84,6 @@ pub struct RegionMaps {
     terminating_scopes: RefCell<HashSet<ast::NodeId>>,
 }
 
-#[deriving(Clone)]
 pub struct Context {
     var_parent: Option<ast::NodeId>,
 
@@ -97,6 +96,8 @@ struct RegionResolutionVisitor<'a> {
 
     // Generated maps:
     region_maps: &'a RegionMaps,
+
+    cx: Context
 }
 
 
@@ -370,20 +371,21 @@ fn ancestors_of(this: &RegionMaps, scope: ast::NodeId)
 
 /// Records the current parent (if any) as the parent of `child_id`.
 fn record_superlifetime(visitor: &mut RegionResolutionVisitor,
-                        cx: Context,
                         child_id: ast::NodeId,
                         _sp: Span) {
-    for &parent_id in cx.parent.iter() {
-        visitor.region_maps.record_encl_scope(child_id, parent_id);
+    match visitor.cx.parent {
+        Some(parent_id) => {
+            visitor.region_maps.record_encl_scope(child_id, parent_id);
+        }
+        None => {}
     }
 }
 
 /// Records the lifetime of a local variable as `cx.var_parent`
 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
-                       cx: Context,
                        var_id: ast::NodeId,
                        _sp: Span) {
-    match cx.var_parent {
+    match visitor.cx.var_parent {
         Some(parent_id) => {
             visitor.region_maps.record_var_scope(var_id, parent_id);
         }
@@ -395,13 +397,11 @@ fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
     }
 }
 
-fn resolve_block(visitor: &mut RegionResolutionVisitor,
-                 blk: &ast::Block,
-                 cx: Context) {
+fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) {
     debug!("resolve_block(blk.id={})", blk.id);
 
     // Record the parent of this block.
-    record_superlifetime(visitor, cx, blk.id, blk.span);
+    record_superlifetime(visitor, blk.id, blk.span);
 
     // We treat the tail expression in the block (if any) somewhat
     // differently from the statements. The issue has to do with
@@ -412,13 +412,13 @@ fn resolve_block(visitor: &mut RegionResolutionVisitor,
     //   }
     //
 
-    let subcx = Context {var_parent: Some(blk.id), parent: Some(blk.id)};
-    visit::walk_block(visitor, blk, subcx);
+    let prev_cx = visitor.cx;
+    visitor.cx = Context {var_parent: Some(blk.id), parent: Some(blk.id)};
+    visit::walk_block(visitor, blk);
+    visitor.cx = prev_cx;
 }
 
-fn resolve_arm(visitor: &mut RegionResolutionVisitor,
-               arm: &ast::Arm,
-               cx: Context) {
+fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) {
     visitor.region_maps.mark_as_terminating_scope(arm.body.id);
 
     match arm.guard {
@@ -428,48 +428,44 @@ fn resolve_arm(visitor: &mut RegionResolutionVisitor,
         None => { }
     }
 
-    visit::walk_arm(visitor, arm, cx);
+    visit::walk_arm(visitor, arm);
 }
 
-fn resolve_pat(visitor: &mut RegionResolutionVisitor,
-               pat: &ast::Pat,
-               cx: Context) {
-    record_superlifetime(visitor, cx, pat.id, pat.span);
+fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) {
+    record_superlifetime(visitor, pat.id, pat.span);
 
     // If this is a binding (or maybe a binding, I'm too lazy to check
     // the def map) then record the lifetime of that binding.
     match pat.node {
         ast::PatIdent(..) => {
-            record_var_lifetime(visitor, cx, pat.id, pat.span);
+            record_var_lifetime(visitor, pat.id, pat.span);
         }
         _ => { }
     }
 
-    visit::walk_pat(visitor, pat, cx);
+    visit::walk_pat(visitor, pat);
 }
 
-fn resolve_stmt(visitor: &mut RegionResolutionVisitor,
-                stmt: &ast::Stmt,
-                cx: Context) {
+fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) {
     let stmt_id = stmt_id(stmt);
     debug!("resolve_stmt(stmt.id={})", stmt_id);
 
     visitor.region_maps.mark_as_terminating_scope(stmt_id);
-    record_superlifetime(visitor, cx, stmt_id, stmt.span);
+    record_superlifetime(visitor, stmt_id, stmt.span);
 
-    let subcx = Context {parent: Some(stmt_id), ..cx};
-    visit::walk_stmt(visitor, stmt, subcx);
+    let prev_parent = visitor.cx.parent;
+    visitor.cx.parent = Some(stmt_id);
+    visit::walk_stmt(visitor, stmt);
+    visitor.cx.parent = prev_parent;
 }
 
-fn resolve_expr(visitor: &mut RegionResolutionVisitor,
-                expr: &ast::Expr,
-                cx: Context) {
+fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) {
     debug!("resolve_expr(expr.id={})", expr.id);
 
-    record_superlifetime(visitor, cx, expr.id, expr.span);
+    record_superlifetime(visitor, expr.id, expr.span);
 
-    let mut new_cx = cx;
-    new_cx.parent = Some(expr.id);
+    let prev_cx = visitor.cx;
+    visitor.cx.parent = Some(expr.id);
     match expr.node {
         // Conditional or repeating scopes are always terminating
         // scopes, meaning that temporaries cannot outlive them.
@@ -506,11 +502,11 @@ fn resolve_expr(visitor: &mut RegionResolutionVisitor,
 
             // The variable parent of everything inside (most importantly, the
             // pattern) is the body.
-            new_cx.var_parent = Some(body.id);
+            visitor.cx.var_parent = Some(body.id);
         }
 
         ast::ExprMatch(..) => {
-            new_cx.var_parent = Some(expr.id);
+            visitor.cx.var_parent = Some(expr.id);
         }
 
         ast::ExprAssignOp(..) | ast::ExprIndex(..) |
@@ -538,17 +534,15 @@ fn resolve_expr(visitor: &mut RegionResolutionVisitor,
         _ => {}
     };
 
-
-    visit::walk_expr(visitor, expr, new_cx);
+    visit::walk_expr(visitor, expr);
+    visitor.cx = prev_cx;
 }
 
-fn resolve_local(visitor: &mut RegionResolutionVisitor,
-                 local: &ast::Local,
-                 cx: Context) {
+fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) {
     debug!("resolve_local(local.id={},local.init={})",
            local.id,local.init.is_some());
 
-    let blk_id = match cx.var_parent {
+    let blk_id = match visitor.cx.var_parent {
         Some(id) => id,
         None => {
             visitor.sess.span_bug(
@@ -635,7 +629,7 @@ fn resolve_local(visitor: &mut RegionResolutionVisitor,
         None => { }
     }
 
-    visit::walk_local(visitor, local, cx);
+    visit::walk_local(visitor, local);
 
     fn is_binding_pat(pat: &ast::Pat) -> bool {
         /*!
@@ -793,21 +787,20 @@ fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
     }
 }
 
-fn resolve_item(visitor: &mut RegionResolutionVisitor,
-                item: &ast::Item,
-                cx: Context) {
+fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &ast::Item) {
     // Items create a new outer block scope as far as we're concerned.
-    let new_cx = Context {var_parent: None, parent: None, ..cx};
-    visit::walk_item(visitor, item, new_cx);
+    let prev_cx = visitor.cx;
+    visitor.cx = Context {var_parent: None, parent: None};
+    visit::walk_item(visitor, item);
+    visitor.cx = prev_cx;
 }
 
 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
-              fk: &FnKind,
+              fk: FnKind,
               decl: &ast::FnDecl,
               body: &ast::Block,
               sp: Span,
-              id: ast::NodeId,
-              cx: Context) {
+              id: ast::NodeId) {
     debug!("region::resolve_fn(id={}, \
                                span={:?}, \
                                body.id={}, \
@@ -815,20 +808,24 @@ fn resolve_fn(visitor: &mut RegionResolutionVisitor,
            id,
            visitor.sess.codemap().span_to_string(sp),
            body.id,
-           cx.parent);
+           visitor.cx.parent);
 
     visitor.region_maps.mark_as_terminating_scope(body.id);
 
+    let outer_cx = visitor.cx;
+
     // The arguments and `self` are parented to the body of the fn.
-    let decl_cx = Context {parent: Some(body.id),
-                           var_parent: Some(body.id)};
-    visit::walk_fn_decl(visitor, decl, decl_cx);
+    visitor.cx = Context { parent: Some(body.id),
+                           var_parent: Some(body.id) };
+    visit::walk_fn_decl(visitor, decl);
 
     // The body of the fn itself is either a root scope (top-level fn)
     // or it continues with the inherited scope (closures).
-    let body_cx = match *fk {
+    match fk {
         visit::FkItemFn(..) | visit::FkMethod(..) => {
-            Context {parent: None, var_parent: None, ..cx}
+            visitor.cx = Context { parent: None, var_parent: None };
+            visitor.visit_block(body);
+            visitor.cx = outer_cx;
         }
         visit::FkFnBlock(..) => {
             // FIXME(#3696) -- at present we are place the closure body
@@ -838,40 +835,40 @@ fn resolve_fn(visitor: &mut RegionResolutionVisitor,
             // but the correct fix is a bit subtle, and I am also not sure
             // that the present approach is unsound -- it may not permit
             // any illegal programs. See issue for more details.
-            cx
+            visitor.cx = outer_cx;
+            visitor.visit_block(body);
         }
-    };
-    visitor.visit_block(body, body_cx);
+    }
 }
 
-impl<'a> Visitor<Context> for RegionResolutionVisitor<'a> {
+impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
 
-    fn visit_block(&mut self, b: &Block, cx: Context) {
-        resolve_block(self, b, cx);
+    fn visit_block(&mut self, b: &Block) {
+        resolve_block(self, b);
     }
 
-    fn visit_item(&mut self, i: &Item, cx: Context) {
-        resolve_item(self, i, cx);
+    fn visit_item(&mut self, i: &Item) {
+        resolve_item(self, i);
     }
 
-    fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl,
-                b: &Block, s: Span, n: NodeId, cx: Context) {
-        resolve_fn(self, fk, fd, b, s, n, cx);
+    fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
+                b: &'v Block, s: Span, n: NodeId) {
+        resolve_fn(self, fk, fd, b, s, n);
     }
-    fn visit_arm(&mut self, a: &Arm, cx: Context) {
-        resolve_arm(self, a, cx);
+    fn visit_arm(&mut self, a: &Arm) {
+        resolve_arm(self, a);
     }
-    fn visit_pat(&mut self, p: &Pat, cx: Context) {
-        resolve_pat(self, p, cx);
+    fn visit_pat(&mut self, p: &Pat) {
+        resolve_pat(self, p);
     }
-    fn visit_stmt(&mut self, s: &Stmt, cx: Context) {
-        resolve_stmt(self, s, cx);
+    fn visit_stmt(&mut self, s: &Stmt) {
+        resolve_stmt(self, s);
     }
-    fn visit_expr(&mut self, ex: &Expr, cx: Context) {
-        resolve_expr(self, ex, cx);
+    fn visit_expr(&mut self, ex: &Expr) {
+        resolve_expr(self, ex);
     }
-    fn visit_local(&mut self, l: &Local, cx: Context) {
-        resolve_local(self, l, cx);
+    fn visit_local(&mut self, l: &Local) {
+        resolve_local(self, l);
     }
 }
 
@@ -886,10 +883,10 @@ pub fn resolve_crate(sess: &Session, krate: &ast::Crate) -> RegionMaps {
     {
         let mut visitor = RegionResolutionVisitor {
             sess: sess,
-            region_maps: &maps
+            region_maps: &maps,
+            cx: Context { parent: None, var_parent: None }
         };
-        let cx = Context { parent: None, var_parent: None };
-        visit::walk_crate(&mut visitor, krate, cx);
+        visit::walk_crate(&mut visitor, krate);
     }
     return maps;
 }
@@ -897,12 +894,11 @@ pub fn resolve_crate(sess: &Session, krate: &ast::Crate) -> RegionMaps {
 pub fn resolve_inlined_item(sess: &Session,
                             region_maps: &RegionMaps,
                             item: &ast::InlinedItem) {
-    let cx = Context {parent: None,
-                      var_parent: None};
     let mut visitor = RegionResolutionVisitor {
         sess: sess,
         region_maps: region_maps,
+        cx: Context { parent: None, var_parent: None }
     };
-    visit::walk_inlined_item(&mut visitor, item, cx);
+    visit::walk_inlined_item(&mut visitor, item);
 }
 
index 854b8b9ba77112337d729054f7676badf65ef1e3..ed795ff0aacc4a816f1db9bf442ff5df989c9474 100644 (file)
@@ -21,7 +21,7 @@
 use middle::ty::{ExplicitSelfCategory, StaticExplicitSelfCategory};
 use util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
 
-use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block, Crate};
+use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block, Crate, CrateNum};
 use syntax::ast::{DeclItem, DefId, Expr, ExprAgain, ExprBreak, ExprField};
 use syntax::ast::{ExprFnBlock, ExprForLoop, ExprLoop, ExprWhile, ExprMethodCall};
 use syntax::ast::{ExprPath, ExprProc, ExprStruct, ExprUnboxedFn, FnDecl};
@@ -185,23 +185,23 @@ enum NameDefinition {
     ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
 }
 
-impl<'a> Visitor<()> for Resolver<'a> {
-    fn visit_item(&mut self, item: &Item, _: ()) {
+impl<'a, 'v> Visitor<'v> for Resolver<'a> {
+    fn visit_item(&mut self, item: &Item) {
         self.resolve_item(item);
     }
-    fn visit_arm(&mut self, arm: &Arm, _: ()) {
+    fn visit_arm(&mut self, arm: &Arm) {
         self.resolve_arm(arm);
     }
-    fn visit_block(&mut self, block: &Block, _: ()) {
+    fn visit_block(&mut self, block: &Block) {
         self.resolve_block(block);
     }
-    fn visit_expr(&mut self, expr: &Expr, _: ()) {
+    fn visit_expr(&mut self, expr: &Expr) {
         self.resolve_expr(expr);
     }
-    fn visit_local(&mut self, local: &Local, _: ()) {
+    fn visit_local(&mut self, local: &Local) {
         self.resolve_local(local);
     }
-    fn visit_ty(&mut self, ty: &Ty, _: ()) {
+    fn visit_ty(&mut self, ty: &Ty) {
         self.resolve_type(ty);
     }
 }
@@ -899,36 +899,45 @@ struct Resolver<'a> {
     emit_errors: bool,
 
     used_imports: HashSet<(NodeId, Namespace)>,
+    used_crates: HashSet<CrateNum>,
 }
 
 struct BuildReducedGraphVisitor<'a, 'b:'a> {
     resolver: &'a mut Resolver<'b>,
+    parent: ReducedGraphParent
 }
 
-impl<'a, 'b> Visitor<ReducedGraphParent> for BuildReducedGraphVisitor<'a, 'b> {
+impl<'a, 'b, 'v> Visitor<'v> for BuildReducedGraphVisitor<'a, 'b> {
 
-    fn visit_item(&mut self, item: &Item, context: ReducedGraphParent) {
-        let p = self.resolver.build_reduced_graph_for_item(item, context);
-        visit::walk_item(self, item, p);
+    fn visit_item(&mut self, item: &Item) {
+        let p = self.resolver.build_reduced_graph_for_item(item, self.parent.clone());
+        let old_parent = replace(&mut self.parent, p);
+        visit::walk_item(self, item);
+        self.parent = old_parent;
     }
 
-    fn visit_foreign_item(&mut self, foreign_item: &ForeignItem,
-                          context: ReducedGraphParent) {
+    fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
+        let parent = self.parent.clone();
         self.resolver.build_reduced_graph_for_foreign_item(foreign_item,
-                                                           context.clone(),
+                                                           parent.clone(),
                                                            |r| {
-            let mut v = BuildReducedGraphVisitor{ resolver: r };
-            visit::walk_foreign_item(&mut v, foreign_item, context.clone());
+            let mut v = BuildReducedGraphVisitor {
+                resolver: r,
+                parent: parent.clone()
+            };
+            visit::walk_foreign_item(&mut v, foreign_item);
         })
     }
 
-    fn visit_view_item(&mut self, view_item: &ViewItem, context: ReducedGraphParent) {
-        self.resolver.build_reduced_graph_for_view_item(view_item, context);
+    fn visit_view_item(&mut self, view_item: &ViewItem) {
+        self.resolver.build_reduced_graph_for_view_item(view_item, self.parent.clone());
     }
 
-    fn visit_block(&mut self, block: &Block, context: ReducedGraphParent) {
-        let np = self.resolver.build_reduced_graph_for_block(block, context);
-        visit::walk_block(self, block, np);
+    fn visit_block(&mut self, block: &Block) {
+        let np = self.resolver.build_reduced_graph_for_block(block, self.parent.clone());
+        let old_parent = replace(&mut self.parent, np);
+        visit::walk_block(self, block);
+        self.parent = old_parent;
     }
 
 }
@@ -937,10 +946,10 @@ struct UnusedImportCheckVisitor<'a, 'b:'a> {
     resolver: &'a mut Resolver<'b>
 }
 
-impl<'a, 'b> Visitor<()> for UnusedImportCheckVisitor<'a, 'b> {
-    fn visit_view_item(&mut self, vi: &ViewItem, _: ()) {
+impl<'a, 'b, 'v> Visitor<'v> for UnusedImportCheckVisitor<'a, 'b> {
+    fn visit_view_item(&mut self, vi: &ViewItem) {
         self.resolver.check_for_item_unused_imports(vi);
-        visit::walk_view_item(self, vi, ());
+        visit::walk_view_item(self, vi);
     }
 }
 
@@ -987,6 +996,7 @@ fn new(session: &'a Session, crate_span: Span) -> Resolver<'a> {
             export_map2: RefCell::new(NodeMap::new()),
             trait_map: NodeMap::new(),
             used_imports: HashSet::new(),
+            used_crates: HashSet::new(),
             external_exports: DefIdSet::new(),
             last_private: NodeMap::new(),
 
@@ -1019,11 +1029,12 @@ fn resolve(&mut self, krate: &ast::Crate) {
 
     /// Constructs the reduced graph for the entire crate.
     fn build_reduced_graph(&mut self, krate: &ast::Crate) {
-        let initial_parent =
-            ModuleReducedGraphParent(self.graph_root.get_module());
-
-        let mut visitor = BuildReducedGraphVisitor { resolver: self, };
-        visit::walk_crate(&mut visitor, krate, initial_parent);
+        let parent = ModuleReducedGraphParent(self.graph_root.get_module());
+        let mut visitor = BuildReducedGraphVisitor {
+            resolver: self,
+            parent: parent
+        };
+        visit::walk_crate(&mut visitor, krate);
     }
 
     /**
@@ -2453,7 +2464,14 @@ fn get_binding(this: &mut Resolver,
                                     debug!("(resolving single import) found \
                                             import in ns {:?}", namespace);
                                     let id = import_resolution.id(namespace);
+                                    // track used imports and extern crates as well
                                     this.used_imports.insert((id, namespace));
+                                    match target_module.def_id.get() {
+                                        Some(DefId{krate: kid, ..}) => {
+                                            this.used_crates.insert(kid);
+                                        },
+                                        _ => {}
+                                    }
                                     return BoundResult(target_module, bindings);
                                 }
                             }
@@ -2496,6 +2514,11 @@ fn get_binding(this: &mut Resolver,
                     Some(module) => {
                         debug!("(resolving single import) found external \
                                 module");
+                        // track the module as used.
+                        match module.def_id.get() {
+                            Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
+                            _ => {}
+                        }
                         let name_bindings =
                             Rc::new(Resolver::create_name_bindings_from_module(
                                 module));
@@ -3030,6 +3053,14 @@ fn search_parent_externals(needle: Name, module: &Rc<Module>)
                                         (_, _) => {
                                             search_module = module_def.clone();
 
+                                            // track extern crates for unused_extern_crate lint
+                                            match module_def.def_id.get() {
+                                                Some(did) => {
+                                                    self.used_crates.insert(did.krate);
+                                                }
+                                                _ => {}
+                                            }
+
                                             // Keep track of the closest
                                             // private module used when
                                             // resolving this import chain.
@@ -3213,7 +3244,12 @@ fn resolve_item_in_lexical_scope(&mut self,
                     Some(target) => {
                         debug!("(resolving item in lexical scope) using \
                                 import resolution");
+                        // track used imports and extern crates as well
                         self.used_imports.insert((import_resolution.id(namespace), namespace));
+                        match target.target_module.def_id.get() {
+                            Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
+                            _ => {}
+                        }
                         return Success((target, false));
                     }
                 }
@@ -3492,7 +3528,12 @@ fn resolve_name_in_module(&mut self,
                     Some(target) => {
                         debug!("(resolving name in module) resolved to \
                                 import");
+                        // track used imports and extern crates as well
                         self.used_imports.insert((import_resolution.id(namespace), namespace));
+                        match target.target_module.def_id.get() {
+                            Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
+                            _ => {}
+                        }
                         return Success((target, true));
                     }
                 }
@@ -3889,7 +3930,7 @@ fn search_ribs(&self,
     fn resolve_crate(&mut self, krate: &ast::Crate) {
         debug!("(resolving crate) starting");
 
-        visit::walk_crate(self, krate, ());
+        visit::walk_crate(self, krate);
     }
 
     fn resolve_item(&mut self, item: &Item) {
@@ -3921,7 +3962,7 @@ fn resolve_item(&mut self, item: &Item) {
                                              |this| {
                     this.resolve_type_parameters(&generics.ty_params);
                     this.resolve_where_clause(&generics.where_clause);
-                    visit::walk_item(this, item, ());
+                    visit::walk_item(this, item);
                 });
             }
 
@@ -3932,7 +3973,7 @@ fn resolve_item(&mut self, item: &Item) {
                                                                ItemRibKind),
                                              |this| {
                     this.resolve_type_parameters(&generics.ty_params);
-                    visit::walk_item(this, item, ());
+                    visit::walk_item(this, item);
                 });
             }
 
@@ -4048,13 +4089,11 @@ fn resolve_item(&mut self, item: &Item) {
                                         generics, FnSpace, foreign_item.id,
                                         ItemRibKind),
                                     |this| visit::walk_foreign_item(this,
-                                                                &**foreign_item,
-                                                                ()));
+                                                                    &**foreign_item));
                             }
                             ForeignItemStatic(..) => {
                                 visit::walk_foreign_item(this,
-                                                         &**foreign_item,
-                                                         ());
+                                                         &**foreign_item);
                             }
                         }
                     }
@@ -4074,7 +4113,7 @@ fn resolve_item(&mut self, item: &Item) {
 
             ItemStatic(..) => {
                 self.with_constant_rib(|this| {
-                    visit::walk_item(this, item, ());
+                    visit::walk_item(this, item);
                 });
             }
 
@@ -4489,7 +4528,7 @@ fn resolve_module(&mut self, module: &Mod, _span: Span,
                       _name: Ident, id: NodeId) {
         // Write the implementations in scope into the module metadata.
         debug!("(resolving module) resolving module ID {}", id);
-        visit::walk_mod(self, module, ());
+        visit::walk_mod(self, module);
     }
 
     fn resolve_local(&mut self, local: &Local) {
@@ -4586,7 +4625,7 @@ fn resolve_arm(&mut self, arm: &Arm) {
         // pat_idents are variants
         self.check_consistent_bindings(arm);
 
-        visit::walk_expr_opt(self, arm.guard, ());
+        visit::walk_expr_opt(self, &arm.guard);
         self.resolve_expr(&*arm.body);
 
         self.value_ribs.borrow_mut().pop();
@@ -4608,7 +4647,7 @@ fn resolve_block(&mut self, block: &Block) {
         }
 
         // Descend into the block.
-        visit::walk_block(self, block, ());
+        visit::walk_block(self, block);
 
         // Move back up.
         self.current_module = orig_module;
@@ -4702,12 +4741,12 @@ fn resolve_type(&mut self, ty: &Ty) {
             TyClosure(c) | TyProc(c) => {
                 self.resolve_type_parameter_bounds(ty.id, &c.bounds,
                                                    TraitBoundingTypeParameter);
-                visit::walk_ty(self, ty, ());
+                visit::walk_ty(self, ty);
             }
 
             _ => {
                 // Just resolve embedded types.
-                visit::walk_ty(self, ty, ());
+                visit::walk_ty(self, ty);
             }
         }
     }
@@ -5061,7 +5100,14 @@ fn resolve_definition_of_name_in_module(&mut self,
                             Some(def) => {
                                 // Found it.
                                 let id = import_resolution.id(namespace);
+                                // track imports and extern crates as well
                                 self.used_imports.insert((id, namespace));
+                                match target.target_module.def_id.get() {
+                                    Some(DefId{krate: kid, ..}) => {
+                                        self.used_crates.insert(kid);
+                                    },
+                                    _ => {}
+                                }
                                 return ImportNameDefinition(def, LastMod(AllPublic));
                             }
                             None => {
@@ -5085,6 +5131,8 @@ fn resolve_definition_of_name_in_module(&mut self,
                     match module.def_id.get() {
                         None => {} // Continue.
                         Some(def_id) => {
+                            // track used crates
+                            self.used_crates.insert(def_id.krate);
                             let lp = if module.is_public {LastMod(AllPublic)} else {
                                 LastMod(DependsOn(def_id))
                             };
@@ -5168,6 +5216,10 @@ fn resolve_module_relative_path(&mut self,
             },
             _ => (),
         }
+        match containing_module.def_id.get() {
+            Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
+            _ => {}
+        }
         return Some(def);
     }
 
@@ -5592,7 +5644,7 @@ fn resolve_expr(&mut self, expr: &Expr) {
                     }
                 }
 
-                visit::walk_expr(self, expr, ());
+                visit::walk_expr(self, expr);
             }
 
             ExprFnBlock(_, fn_decl, block) |
@@ -5618,7 +5670,7 @@ fn resolve_expr(&mut self, expr: &Expr) {
                     }
                 }
 
-                visit::walk_expr(self, expr, ());
+                visit::walk_expr(self, expr);
             }
 
             ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
@@ -5633,7 +5685,7 @@ fn resolve_expr(&mut self, expr: &Expr) {
                         rib.bindings.borrow_mut().insert(renamed, def_like);
                     }
 
-                    visit::walk_expr(this, expr, ());
+                    visit::walk_expr(this, expr);
                 })
             }
 
@@ -5697,7 +5749,7 @@ fn resolve_expr(&mut self, expr: &Expr) {
             }
 
             _ => {
-                visit::walk_expr(self, expr, ());
+                visit::walk_expr(self, expr);
             }
         }
     }
@@ -5787,6 +5839,10 @@ fn add_trait_info(found_traits: &mut Vec<DefId>,
                 if self.trait_item_map.borrow().contains_key(&(name, did)) {
                     add_trait_info(&mut found_traits, did, name);
                     self.used_imports.insert((import.type_id, TypeNS));
+                    match target.target_module.def_id.get() {
+                        Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
+                        _ => {}
+                    }
                 }
             }
 
@@ -5847,7 +5903,7 @@ fn enforce_default_binding_mode(&mut self,
 
     fn check_for_unused_imports(&mut self, krate: &ast::Crate) {
         let mut visitor = UnusedImportCheckVisitor{ resolver: self };
-        visit::walk_crate(&mut visitor, krate, ());
+        visit::walk_crate(&mut visitor, krate);
     }
 
     fn check_for_item_unused_imports(&mut self, vi: &ViewItem) {
@@ -5859,10 +5915,22 @@ fn check_for_item_unused_imports(&mut self, vi: &ViewItem) {
         if vi.span == DUMMY_SP { return }
 
         match vi.node {
-            ViewItemExternCrate(..) => {} // ignore
+            ViewItemExternCrate(_, _, id) => {
+                match self.session.cstore.find_extern_mod_stmt_cnum(id)
+                {
+                    Some(crate_num) => if !self.used_crates.contains(&crate_num) {
+                    self.session.add_lint(lint::builtin::UNUSED_EXTERN_CRATE,
+                                          id,
+                                          vi.span,
+                                          "unused extern crate".to_string());
+                    },
+                    _ => {}
+                }
+            },
             ViewItemUse(ref p) => {
                 match p.node {
                     ViewPathSimple(_, _, id) => self.finalize_import(id, p.span),
+
                     ViewPathList(_, ref list, _) => {
                         for i in list.iter() {
                             self.finalize_import(i.node.id(), i.span);
index 1bc37e2f1e445709f1cd58ea6c08aa094036a20d..22acdca5f9bdb06f7e4e9403da21463232c9cdf5 100644 (file)
@@ -52,7 +52,8 @@ fn lifetime_show(lt_name: &ast::Name) -> token::InternedString {
 
 struct LifetimeContext<'a> {
     sess: &'a Session,
-    named_region_map: NamedRegionMap,
+    named_region_map: &'a mut NamedRegionMap,
+    scope: Scope<'a>
 }
 
 enum ScopeChain<'a> {
@@ -70,117 +71,107 @@ enum ScopeChain<'a> {
 
 type Scope<'a> = &'a ScopeChain<'a>;
 
+static ROOT_SCOPE: ScopeChain<'static> = RootScope;
+
 pub fn krate(sess: &Session, krate: &ast::Crate) -> NamedRegionMap {
-    let mut ctxt = LifetimeContext {
+    let mut named_region_map = NodeMap::new();
+    visit::walk_crate(&mut LifetimeContext {
         sess: sess,
-        named_region_map: NodeMap::new()
-    };
-    visit::walk_crate(&mut ctxt, krate, &RootScope);
+        named_region_map: &mut named_region_map,
+        scope: &ROOT_SCOPE
+    }, krate);
     sess.abort_if_errors();
-    ctxt.named_region_map
+    named_region_map
 }
 
-impl<'a, 'b> Visitor<Scope<'a>> for LifetimeContext<'b> {
-    fn visit_item(&mut self,
-                  item: &ast::Item,
-                  _: Scope<'a>) {
-        let root = RootScope;
-        let scope = match item.node {
+impl<'a, 'v> Visitor<'v> for LifetimeContext<'a> {
+    fn visit_item(&mut self, item: &ast::Item) {
+        let lifetimes = match item.node {
             ast::ItemFn(..) | // fn lifetimes get added in visit_fn below
             ast::ItemMod(..) |
             ast::ItemMac(..) |
             ast::ItemForeignMod(..) |
             ast::ItemStatic(..) => {
-                RootScope
+                self.with(|_, f| f(RootScope), |v| visit::walk_item(v, item));
+                return;
             }
             ast::ItemTy(_, ref generics) |
             ast::ItemEnum(_, ref generics) |
             ast::ItemStruct(_, ref generics) |
             ast::ItemImpl(ref generics, _, _, _) |
-            ast::ItemTrait(ref generics, _, _, _) => {
-                let scope: ScopeChain =
-                    EarlyScope(subst::TypeSpace, &generics.lifetimes, &root);
-                self.check_lifetime_defs(&generics.lifetimes, &scope);
-                scope
-            }
+            ast::ItemTrait(ref generics, _, _, _) => &generics.lifetimes
         };
-        debug!("entering scope {:?}", scope);
-        visit::walk_item(self, item, &scope);
-        debug!("exiting scope {:?}", scope);
+
+        self.with(|_, f| f(EarlyScope(subst::TypeSpace, lifetimes, &ROOT_SCOPE)), |v| {
+            debug!("entering scope {:?}", v.scope);
+            v.check_lifetime_defs(lifetimes);
+            visit::walk_item(v, item);
+            debug!("exiting scope {:?}", v.scope);
+        });
     }
 
-    fn visit_fn(&mut self, fk: &visit::FnKind, fd: &ast::FnDecl,
-                b: &ast::Block, s: Span, n: ast::NodeId,
-                scope: Scope<'a>) {
-        match *fk {
+    fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
+                b: &'v ast::Block, s: Span, n: ast::NodeId) {
+        match fk {
             visit::FkItemFn(_, generics, _, _) |
             visit::FkMethod(_, generics, _) => {
-                self.visit_fn_decl(
-                    n, generics, scope,
-                    |this, scope1| visit::walk_fn(this, fk, fd, b, s, scope1))
+                self.visit_fn_decl(n, generics, |v| visit::walk_fn(v, fk, fd, b, s))
             }
             visit::FkFnBlock(..) => {
-                visit::walk_fn(self, fk, fd, b, s, scope)
+                visit::walk_fn(self, fk, fd, b, s)
             }
         }
     }
 
-    fn visit_ty(&mut self, ty: &ast::Ty, scope: Scope<'a>) {
-        match ty.node {
-            ast::TyClosure(c) | ast::TyProc(c) => {
-                push_fn_scope(self, ty, scope, &c.lifetimes);
-            }
-            ast::TyBareFn(c) => push_fn_scope(self, ty, scope, &c.lifetimes),
-            _ => visit::walk_ty(self, ty, scope),
-        }
+    fn visit_ty(&mut self, ty: &ast::Ty) {
+        let lifetimes = match ty.node {
+            ast::TyClosure(ref c) | ast::TyProc(ref c) => &c.lifetimes,
+            ast::TyBareFn(ref c) => &c.lifetimes,
+            _ => return visit::walk_ty(self, ty)
+        };
 
-        fn push_fn_scope(this: &mut LifetimeContext,
-                         ty: &ast::Ty,
-                         scope: Scope,
-                         lifetimes: &Vec<ast::LifetimeDef>) {
-            let scope1: ScopeChain = LateScope(ty.id, lifetimes, scope);
-            this.check_lifetime_defs(lifetimes, &scope1);
+        self.with(|scope, f| f(LateScope(ty.id, lifetimes, scope)), |v| {
+            v.check_lifetime_defs(lifetimes);
             debug!("pushing fn scope id={} due to type", ty.id);
-            visit::walk_ty(this, ty, &scope1);
+            visit::walk_ty(v, ty);
             debug!("popping fn scope id={} due to type", ty.id);
-        }
+        });
     }
 
-    fn visit_ty_method(&mut self,
-                       m: &ast::TypeMethod,
-                       scope: Scope<'a>) {
-        self.visit_fn_decl(
-            m.id, &m.generics, scope,
-            |this, scope1| visit::walk_ty_method(this, m, scope1))
+    fn visit_ty_method(&mut self, m: &ast::TypeMethod) {
+        self.visit_fn_decl(m.id, &m.generics, |v| visit::walk_ty_method(v, m))
     }
 
-    fn visit_block(&mut self,
-                   b: &ast::Block,
-                   scope: Scope<'a>) {
-        let scope1 = BlockScope(b.id, scope);
+    fn visit_block(&mut self, b: &ast::Block) {
         debug!("pushing block scope {}", b.id);
-        visit::walk_block(self, b, &scope1);
+        self.with(|scope, f| f(BlockScope(b.id, scope)), |v| visit::walk_block(v, b));
         debug!("popping block scope {}", b.id);
     }
 
-    fn visit_lifetime_ref(&mut self,
-                          lifetime_ref: &ast::Lifetime,
-                          scope: Scope<'a>) {
+    fn visit_lifetime_ref(&mut self, lifetime_ref: &ast::Lifetime) {
         if lifetime_ref.name == special_idents::static_lifetime.name {
             self.insert_lifetime(lifetime_ref, DefStaticRegion);
             return;
         }
-        self.resolve_lifetime_ref(lifetime_ref, scope);
+        self.resolve_lifetime_ref(lifetime_ref);
     }
 }
 
 impl<'a> LifetimeContext<'a> {
+    fn with(&mut self, wrap_scope: |Scope, |ScopeChain||, f: |&mut LifetimeContext|) {
+        let LifetimeContext { sess, ref mut named_region_map, scope} = *self;
+        wrap_scope(scope, |scope1| f(&mut LifetimeContext {
+            sess: sess,
+            named_region_map: *named_region_map,
+            scope: &scope1
+        }))
+    }
+
     /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
     fn visit_fn_decl(&mut self,
                      n: ast::NodeId,
                      generics: &ast::Generics,
-                     scope: Scope,
-                     walk: |&mut LifetimeContext, Scope|) {
+                     walk: |&mut LifetimeContext|) {
         /*!
          * Handles visiting fns and methods. These are a bit
          * complicated because we must distinguish early- vs late-bound
@@ -210,25 +201,27 @@ fn visit_fn_decl(&mut self,
                referenced_idents={:?}",
                n,
                referenced_idents.iter().map(lifetime_show).collect::<Vec<token::InternedString>>());
+        let lifetimes = &generics.lifetimes;
         if referenced_idents.is_empty() {
-            let scope1: ScopeChain = LateScope(n, &generics.lifetimes, scope);
-            self.check_lifetime_defs(&generics.lifetimes, &scope1);
-            walk(self, &scope1);
+            self.with(|scope, f| f(LateScope(n, lifetimes, scope)), |v| {
+                v.check_lifetime_defs(lifetimes);
+                walk(v);
+            });
         } else {
-            let (early, late) = generics.lifetimes.clone().partition(
+            let (early, late) = lifetimes.clone().partition(
                 |l| referenced_idents.iter().any(|&i| i == l.lifetime.name));
 
-            let scope1 = EarlyScope(subst::FnSpace, &early, scope);
-            let scope2: ScopeChain = LateScope(n, &late, &scope1);
-            self.check_lifetime_defs(&generics.lifetimes, &scope2);
-            walk(self, &scope2);
+            self.with(|scope, f| f(EarlyScope(subst::FnSpace, &early, scope)), |v| {
+                v.with(|scope1, f| f(LateScope(n, &late, scope1)), |v| {
+                    v.check_lifetime_defs(lifetimes);
+                    walk(v);
+                });
+            });
         }
         debug!("popping fn scope id={} due to fn item/method", n);
     }
 
-    fn resolve_lifetime_ref(&mut self,
-                            lifetime_ref: &ast::Lifetime,
-                            scope: Scope) {
+    fn resolve_lifetime_ref(&mut self, lifetime_ref: &ast::Lifetime) {
         // Walk up the scope chain, tracking the number of fn scopes
         // that we pass through, until we find a lifetime with the
         // given name or we run out of scopes. If we encounter a code
@@ -236,7 +229,7 @@ fn resolve_lifetime_ref(&mut self,
         // over to `resolve_free_lifetime_ref()` to complete the
         // search.
         let mut depth = 0;
-        let mut scope = scope;
+        let mut scope = self.scope;
         loop {
             match *scope {
                 BlockScope(id, s) => {
@@ -326,17 +319,14 @@ fn resolve_free_lifetime_ref(&mut self,
 
     }
 
-    fn unresolved_lifetime_ref(&self,
-                               lifetime_ref: &ast::Lifetime) {
+    fn unresolved_lifetime_ref(&self, lifetime_ref: &ast::Lifetime) {
         self.sess.span_err(
             lifetime_ref.span,
             format!("use of undeclared lifetime name `{}`",
                     token::get_name(lifetime_ref.name)).as_slice());
     }
 
-    fn check_lifetime_defs<'b>(&mut self,
-                               lifetimes: &Vec<ast::LifetimeDef>,
-                               scope: Scope<'b>) {
+    fn check_lifetime_defs(&mut self, lifetimes: &Vec<ast::LifetimeDef>) {
         for i in range(0, lifetimes.len()) {
             let lifetime_i = lifetimes.get(i);
 
@@ -365,7 +355,7 @@ fn check_lifetime_defs<'b>(&mut self,
             }
 
             for bound in lifetime_i.bounds.iter() {
-                self.resolve_lifetime_ref(bound, scope);
+                self.resolve_lifetime_ref(bound);
             }
         }
     }
@@ -434,10 +424,10 @@ fn early_bound_lifetime_names(generics: &ast::Generics) -> Vec<ast::Name> {
             FreeLifetimeCollector { early_bound: &mut early_bound,
                                     late_bound: &mut late_bound };
         for ty_param in generics.ty_params.iter() {
-            visit::walk_ty_param_bounds(&mut collector, &ty_param.bounds, ());
+            visit::walk_ty_param_bounds(&mut collector, &ty_param.bounds);
         }
         for predicate in generics.where_clause.predicates.iter() {
-            visit::walk_ty_param_bounds(&mut collector, &predicate.bounds, ());
+            visit::walk_ty_param_bounds(&mut collector, &predicate.bounds);
         }
     }
 
@@ -460,10 +450,8 @@ struct FreeLifetimeCollector<'a> {
         late_bound: &'a mut Vec<ast::Name>,
     }
 
-    impl<'a> Visitor<()> for FreeLifetimeCollector<'a> {
-        fn visit_lifetime_ref(&mut self,
-                              lifetime_ref: &ast::Lifetime,
-                              _: ()) {
+    impl<'a, 'v> Visitor<'v> for FreeLifetimeCollector<'a> {
+        fn visit_lifetime_ref(&mut self, lifetime_ref: &ast::Lifetime) {
             shuffle(self.early_bound, self.late_bound,
                     lifetime_ref.name);
         }
index 7350413643c8da460fb03b10e250c2b47f7fff9b..1d4050c71b18ace1d04b6b77e1de1f913bc299a5 100644 (file)
@@ -83,9 +83,18 @@ struct DxrVisitor<'l, 'tcx: 'l> {
 
     span: SpanUtils<'l>,
     fmt: FmtStrs<'l>,
+
+    cur_scope: NodeId
 }
 
 impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
+    fn nest(&mut self, scope_id: NodeId, f: |&mut DxrVisitor<'l, 'tcx>|) {
+        let parent_scope = self.cur_scope;
+        self.cur_scope = scope_id;
+        f(self);
+        self.cur_scope = parent_scope;
+    }
+
     fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
         // the current crate
         self.fmt.crate_str(krate.span, name);
@@ -136,19 +145,19 @@ fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
         result
     }
 
-    fn write_sub_paths(&mut self, path: &ast::Path, scope_id: NodeId) {
+    fn write_sub_paths(&mut self, path: &ast::Path) {
         let sub_paths = self.process_path_prefixes(path);
         for &(ref span, ref qualname) in sub_paths.iter() {
             self.fmt.sub_mod_ref_str(path.span,
                                      *span,
                                      qualname.as_slice(),
-                                     scope_id);
+                                     self.cur_scope);
         }
     }
 
     // As write_sub_paths, but does not process the last ident in the path (assuming it
     // will be processed elsewhere).
-    fn write_sub_paths_truncated(&mut self, path: &ast::Path, scope_id: NodeId) {
+    fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
         let sub_paths = self.process_path_prefixes(path);
         let len = sub_paths.len();
         if len <= 1 {
@@ -160,13 +169,13 @@ fn write_sub_paths_truncated(&mut self, path: &ast::Path, scope_id: NodeId) {
             self.fmt.sub_mod_ref_str(path.span,
                                      *span,
                                      qualname.as_slice(),
-                                     scope_id);
+                                     self.cur_scope);
         }
     }
 
     // As write_sub_paths, but expects a path of the form module_path::trait::method
     // Where trait could actually be a struct too.
-    fn write_sub_path_trait_truncated(&mut self, path: &ast::Path, scope_id: NodeId) {
+    fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
         let sub_paths = self.process_path_prefixes(path);
         let len = sub_paths.len();
         if len <= 1 {
@@ -189,7 +198,7 @@ fn write_sub_path_trait_truncated(&mut self, path: &ast::Path, scope_id: NodeId)
             self.fmt.sub_mod_ref_str(path.span,
                                      *span,
                                      qualname.as_slice(),
-                                     scope_id);
+                                     self.cur_scope);
         }
     }
 
@@ -243,11 +252,11 @@ fn lookup_def_kind(&self, ref_id: NodeId, span: Span) -> Option<recorder::Row> {
         }
     }
 
-    fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str, e:DxrVisitorEnv) {
+    fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str) {
         for arg in formals.iter() {
             assert!(self.collected_paths.len() == 0 && !self.collecting);
             self.collecting = true;
-            self.visit_pat(&*arg.pat, e);
+            self.visit_pat(&*arg.pat);
             self.collecting = false;
             let span_utils = self.span;
             for &(id, ref p, _, _) in self.collected_paths.iter() {
@@ -266,7 +275,7 @@ fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str, e:DxrVisi
         }
     }
 
-    fn process_method(&mut self, method: &ast::Method, e:DxrVisitorEnv) {
+    fn process_method(&mut self, method: &ast::Method) {
         if generated_code(method.span) {
             return;
         }
@@ -361,27 +370,24 @@ fn process_method(&mut self, method: &ast::Method, e:DxrVisitorEnv) {
                             decl_id,
                             scope_id);
 
-        self.process_formals(&method.pe_fn_decl().inputs, qualname, e);
+        self.process_formals(&method.pe_fn_decl().inputs, qualname);
 
         // walk arg and return types
         for arg in method.pe_fn_decl().inputs.iter() {
-            self.visit_ty(&*arg.ty, e);
+            self.visit_ty(&*arg.ty);
         }
-        self.visit_ty(&*method.pe_fn_decl().output, e);
+        self.visit_ty(&*method.pe_fn_decl().output);
         // walk the fn body
-        self.visit_block(&*method.pe_body(),
-                         DxrVisitorEnv::new_nested(method.id));
+        self.nest(method.id, |v| v.visit_block(&*method.pe_body()));
 
         self.process_generic_params(method.pe_generics(),
                                     method.span,
                                     qualname,
-                                    method.id,
-                                    e);
+                                    method.id);
     }
 
     fn process_trait_ref(&mut self,
                          trait_ref: &ast::TraitRef,
-                         e: DxrVisitorEnv,
                          impl_id: Option<NodeId>) {
         match self.lookup_type_ref(trait_ref.ref_id) {
             Some(id) => {
@@ -390,16 +396,16 @@ fn process_trait_ref(&mut self,
                                  trait_ref.path.span,
                                  sub_span,
                                  id,
-                                 e.cur_scope);
+                                 self.cur_scope);
                 match impl_id {
                     Some(impl_id) => self.fmt.impl_str(trait_ref.path.span,
                                                        sub_span,
                                                        impl_id,
                                                        id,
-                                                       e.cur_scope),
+                                                       self.cur_scope),
                     None => (),
                 }
-                visit::walk_path(self, &trait_ref.path, e);
+                visit::walk_path(self, &trait_ref.path);
             },
             None => ()
         }
@@ -436,8 +442,7 @@ fn process_struct_field_def(&mut self,
     fn process_generic_params(&mut self, generics:&ast::Generics,
                               full_span: Span,
                               prefix: &str,
-                              id: NodeId,
-                              e: DxrVisitorEnv) {
+                              id: NodeId) {
         // We can't only use visit_generics since we don't have spans for param
         // bindings, so we reparse the full_span to get those sub spans.
         // However full span is the entire enum/fn/struct block, so we only want
@@ -456,12 +461,11 @@ fn process_generic_params(&mut self, generics:&ast::Generics,
                                  name.as_slice(),
                                  "");
         }
-        self.visit_generics(generics, e);
+        self.visit_generics(generics);
     }
 
     fn process_fn(&mut self,
                   item: &ast::Item,
-                  e: DxrVisitorEnv,
                   decl: ast::P<ast::FnDecl>,
                   ty_params: &ast::Generics,
                   body: ast::P<ast::Block>) {
@@ -472,25 +476,24 @@ fn process_fn(&mut self,
                         sub_span,
                         item.id,
                         qualname.as_slice(),
-                        e.cur_scope);
+                        self.cur_scope);
 
-        self.process_formals(&decl.inputs, qualname.as_slice(), e);
+        self.process_formals(&decl.inputs, qualname.as_slice());
 
         // walk arg and return types
         for arg in decl.inputs.iter() {
-            self.visit_ty(&*arg.ty, e);
+            self.visit_ty(&*arg.ty);
         }
-        self.visit_ty(&*decl.output, e);
+        self.visit_ty(&*decl.output);
 
         // walk the body
-        self.visit_block(&*body, DxrVisitorEnv::new_nested(item.id));
+        self.nest(item.id, |v| v.visit_block(&*body));
 
-        self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id, e);
+        self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
     }
 
     fn process_static(&mut self,
                       item: &ast::Item,
-                      e: DxrVisitorEnv,
                       typ: ast::P<ast::Ty>,
                       mt: ast::Mutability,
                       expr: &ast::Expr)
@@ -511,16 +514,15 @@ fn process_static(&mut self,
                             qualname.as_slice(),
                             value.as_slice(),
                             ty_to_string(&*typ).as_slice(),
-                            e.cur_scope);
+                            self.cur_scope);
 
         // walk type and init value
-        self.visit_ty(&*typ, e);
-        self.visit_expr(expr, e);
+        self.visit_ty(&*typ);
+        self.visit_expr(expr);
     }
 
     fn process_struct(&mut self,
                       item: &ast::Item,
-                      e: DxrVisitorEnv,
                       def: &ast::StructDef,
                       ty_params: &ast::Generics) {
         let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
@@ -535,20 +537,19 @@ fn process_struct(&mut self,
                             item.id,
                             ctor_id,
                             qualname.as_slice(),
-                            e.cur_scope);
+                            self.cur_scope);
 
         // fields
         for field in def.fields.iter() {
             self.process_struct_field_def(field, qualname.as_slice(), item.id);
-            self.visit_ty(&*field.node.ty, e);
+            self.visit_ty(&*field.node.ty);
         }
 
-        self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id, e);
+        self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
     }
 
     fn process_enum(&mut self,
                     item: &ast::Item,
-                    e: DxrVisitorEnv,
                     enum_definition: &ast::EnumDef,
                     ty_params: &ast::Generics) {
         let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
@@ -557,7 +558,7 @@ fn process_enum(&mut self,
                                                 Some(sub_span),
                                                 item.id,
                                                 qualname.as_slice(),
-                                                e.cur_scope),
+                                                self.cur_scope),
             None => self.sess.span_bug(item.span,
                                        format!("Could not find subspan for enum {}",
                                                qualname).as_slice()),
@@ -578,7 +579,7 @@ fn process_enum(&mut self,
                                                val.as_slice(),
                                                item.id);
                     for arg in args.iter() {
-                        self.visit_ty(&*arg.ty, e);
+                        self.visit_ty(&*arg.ty);
                     }
                 }
                 ast::StructVariantKind(ref struct_def) => {
@@ -597,18 +598,17 @@ fn process_enum(&mut self,
 
                     for field in struct_def.fields.iter() {
                         self.process_struct_field_def(field, qualname.as_slice(), variant.node.id);
-                        self.visit_ty(&*field.node.ty, e);
+                        self.visit_ty(&*field.node.ty);
                     }
                 }
             }
         }
 
-        self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id, e);
+        self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
     }
 
     fn process_impl(&mut self,
                     item: &ast::Item,
-                    e: DxrVisitorEnv,
                     type_parameters: &ast::Generics,
                     trait_ref: &Option<ast::TraitRef>,
                     typ: ast::P<ast::Ty>,
@@ -622,29 +622,29 @@ fn process_impl(&mut self,
                                          path.span,
                                          sub_span,
                                          id,
-                                         e.cur_scope);
+                                         self.cur_scope);
                         self.fmt.impl_str(path.span,
                                           sub_span,
                                           item.id,
                                           id,
-                                          e.cur_scope);
+                                          self.cur_scope);
                     },
                     None => ()
                 }
             },
-            _ => self.visit_ty(&*typ, e),
+            _ => self.visit_ty(&*typ),
         }
 
         match *trait_ref {
-            Some(ref trait_ref) => self.process_trait_ref(trait_ref, e, Some(item.id)),
+            Some(ref trait_ref) => self.process_trait_ref(trait_ref, Some(item.id)),
             None => (),
         }
 
-        self.process_generic_params(type_parameters, item.span, "", item.id, e);
+        self.process_generic_params(type_parameters, item.span, "", item.id);
         for impl_item in impl_items.iter() {
             match *impl_item {
                 ast::MethodImplItem(method) => {
-                    visit::walk_method_helper(self, &*method, e)
+                    visit::walk_method_helper(self, &*method)
                 }
             }
         }
@@ -652,7 +652,6 @@ fn process_impl(&mut self,
 
     fn process_trait(&mut self,
                      item: &ast::Item,
-                     e: DxrVisitorEnv,
                      generics: &ast::Generics,
                      trait_refs: &OwnedSlice<ast::TyParamBound>,
                      methods: &Vec<ast::TraitItem>) {
@@ -663,7 +662,7 @@ fn process_trait(&mut self,
                            sub_span,
                            item.id,
                            qualname.as_slice(),
-                           e.cur_scope);
+                           self.cur_scope);
 
         // super-traits
         for super_bound in trait_refs.iter() {
@@ -683,7 +682,7 @@ fn process_trait(&mut self,
                                      trait_ref.path.span,
                                      sub_span,
                                      id,
-                                     e.cur_scope);
+                                     self.cur_scope);
                     self.fmt.inherit_str(trait_ref.path.span,
                                          sub_span,
                                          id,
@@ -694,15 +693,14 @@ fn process_trait(&mut self,
         }
 
         // walk generics and methods
-        self.process_generic_params(generics, item.span, qualname.as_slice(), item.id, e);
+        self.process_generic_params(generics, item.span, qualname.as_slice(), item.id);
         for method in methods.iter() {
-            self.visit_trait_item(method, e)
+            self.visit_trait_item(method)
         }
     }
 
     fn process_mod(&mut self,
                    item: &ast::Item,  // The module in question, represented as an item.
-                   e: DxrVisitorEnv,
                    m: &ast::Mod) {
         let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
 
@@ -714,15 +712,14 @@ fn process_mod(&mut self,
                          sub_span,
                          item.id,
                          qualname.as_slice(),
-                         e.cur_scope,
+                         self.cur_scope,
                          filename.as_slice());
 
-        visit::walk_mod(self, m, DxrVisitorEnv::new_nested(item.id));
+        self.nest(item.id, |v| visit::walk_mod(v, m));
     }
 
     fn process_path(&mut self,
                     ex: &ast::Expr,
-                    e: DxrVisitorEnv,
                     path: &ast::Path) {
         if generated_code(path.span) {
             return
@@ -744,18 +741,18 @@ fn process_path(&mut self,
                                                        ex.span,
                                                        sub_span,
                                                        ast_util::local_def(id),
-                                                       e.cur_scope),
+                                                       self.cur_scope),
             def::DefStatic(def_id,_) |
             def::DefVariant(_, def_id, _) => self.fmt.ref_str(recorder::VarRef,
                                                               ex.span,
                                                               sub_span,
                                                               def_id,
-                                                              e.cur_scope),
+                                                              self.cur_scope),
             def::DefStruct(def_id) => self.fmt.ref_str(recorder::StructRef,
                                                        ex.span,
                                                        sub_span,
                                                        def_id,
-                                                        e.cur_scope),
+                                                        self.cur_scope),
             def::DefStaticMethod(declid, provenence, _) => {
                 let sub_span = self.span.sub_span_for_meth_name(ex.span);
                 let defid = if declid.krate == ast::LOCAL_CRATE {
@@ -806,12 +803,12 @@ fn process_path(&mut self,
                                        sub_span,
                                        defid,
                                        Some(declid),
-                                       e.cur_scope);
+                                       self.cur_scope);
             },
             def::DefFn(def_id, _) => self.fmt.fn_call_str(ex.span,
                                                           sub_span,
                                                           def_id,
-                                                          e.cur_scope),
+                                                          self.cur_scope),
             _ => self.sess.span_bug(ex.span,
                                     format!("Unexpected def kind while looking up path in '{}'",
                                             self.span.snippet(ex.span)).as_slice()),
@@ -819,25 +816,24 @@ fn process_path(&mut self,
         // modules or types in the path prefix
         match *def {
             def::DefStaticMethod(_, _, _) => {
-                self.write_sub_path_trait_truncated(path, e.cur_scope);
+                self.write_sub_path_trait_truncated(path);
             },
             def::DefLocal(_, _) |
             def::DefArg(_, _) |
             def::DefStatic(_,_) |
             def::DefStruct(_) |
-            def::DefFn(_, _) => self.write_sub_paths_truncated(path, e.cur_scope),
+            def::DefFn(_, _) => self.write_sub_paths_truncated(path),
             _ => {},
         }
 
-        visit::walk_path(self, path, e);
+        visit::walk_path(self, path);
     }
 
     fn process_struct_lit(&mut self,
                           ex: &ast::Expr,
-                          e: DxrVisitorEnv,
                           path: &ast::Path,
                           fields: &Vec<ast::Field>,
-                          base: Option<Gc<ast::Expr>>) {
+                          base: &Option<Gc<ast::Expr>>) {
         if generated_code(path.span) {
             return
         }
@@ -851,12 +847,12 @@ fn process_struct_lit(&mut self,
                                  path.span,
                                  sub_span,
                                  id,
-                                 e.cur_scope);
+                                 self.cur_scope);
             },
             None => ()
         }
 
-        self.write_sub_paths_truncated(path, e.cur_scope);
+        self.write_sub_paths_truncated(path);
 
         for field in fields.iter() {
             match struct_def {
@@ -873,21 +869,20 @@ fn process_struct_lit(&mut self,
                                              field.ident.span,
                                              sub_span,
                                              f.id,
-                                             e.cur_scope);
+                                             self.cur_scope);
                         }
                     }
                 }
                 None => {}
             }
 
-            self.visit_expr(&*field.expr, e)
+            self.visit_expr(&*field.expr)
         }
-        visit::walk_expr_opt(self, base, e)
+        visit::walk_expr_opt(self, base)
     }
 
     fn process_method_call(&mut self,
                            ex: &ast::Expr,
-                           e: DxrVisitorEnv,
                            args: &Vec<Gc<ast::Expr>>) {
         let method_map = self.analysis.ty_cx.method_map.borrow();
         let method_callee = method_map.get(&typeck::MethodCall::expr(ex.id));
@@ -941,13 +936,13 @@ fn process_method_call(&mut self,
                                sub_span,
                                def_id,
                                decl_id,
-                               e.cur_scope);
+                               self.cur_scope);
 
         // walk receiver and args
-        visit::walk_exprs(self, args.as_slice(), e);
+        visit::walk_exprs(self, args.as_slice());
     }
 
-    fn process_pat(&mut self, p:&ast::Pat, e: DxrVisitorEnv) {
+    fn process_pat(&mut self, p:&ast::Pat) {
         if generated_code(p.span) {
             return
         }
@@ -955,7 +950,7 @@ fn process_pat(&mut self, p:&ast::Pat, e: DxrVisitorEnv) {
         match p.node {
             ast::PatStruct(ref path, ref fields, _) => {
                 self.collected_paths.push((p.id, path.clone(), false, recorder::StructRef));
-                visit::walk_path(self, path, e);
+                visit::walk_path(self, path);
                 let struct_def = match self.lookup_type_ref(p.id) {
                     Some(sd) => sd,
                     None => {
@@ -976,7 +971,7 @@ fn process_pat(&mut self, p:&ast::Pat, e: DxrVisitorEnv) {
                                ).as_slice());
                 }
                 for (field, &span) in fields.iter().zip(field_spans.iter()) {
-                    self.visit_pat(&*field.pat, e);
+                    self.visit_pat(&*field.pat);
                     if span.is_none() {
                         continue;
                     }
@@ -987,7 +982,7 @@ fn process_pat(&mut self, p:&ast::Pat, e: DxrVisitorEnv) {
                                              p.span,
                                              span,
                                              f.id,
-                                             e.cur_scope);
+                                             self.cur_scope);
                             break;
                         }
                     }
@@ -995,7 +990,7 @@ fn process_pat(&mut self, p:&ast::Pat, e: DxrVisitorEnv) {
             }
             ast::PatEnum(ref path, _) => {
                 self.collected_paths.push((p.id, path.clone(), false, recorder::VarRef));
-                visit::walk_pat(self, p, e);
+                visit::walk_pat(self, p);
             }
             ast::PatIdent(bm, ref path1, ref optional_subpattern) => {
                 let immut = match bm {
@@ -1015,41 +1010,40 @@ fn process_pat(&mut self, p:&ast::Pat, e: DxrVisitorEnv) {
                 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
                 match *optional_subpattern {
                     None => {}
-                    Some(subpattern) => self.visit_pat(&*subpattern, e),
+                    Some(subpattern) => self.visit_pat(&*subpattern),
                 }
             }
-            _ => visit::walk_pat(self, p, e)
+            _ => visit::walk_pat(self, p)
         }
     }
 }
 
-impl<'l, 'tcx> Visitor<DxrVisitorEnv> for DxrVisitor<'l, 'tcx> {
-    fn visit_item(&mut self, item:&ast::Item, e: DxrVisitorEnv) {
+impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> {
+    fn visit_item(&mut self, item: &ast::Item) {
         if generated_code(item.span) {
             return
         }
 
         match item.node {
             ast::ItemFn(decl, _, _, ref ty_params, body) =>
-                self.process_fn(item, e, decl, ty_params, body),
+                self.process_fn(item, decl, ty_params, body),
             ast::ItemStatic(typ, mt, expr) =>
-                self.process_static(item, e, typ, mt, &*expr),
-            ast::ItemStruct(def, ref ty_params) => self.process_struct(item, e, &*def, ty_params),
-            ast::ItemEnum(ref def, ref ty_params) => self.process_enum(item, e, def, ty_params),
+                self.process_static(item, typ, mt, &*expr),
+            ast::ItemStruct(def, ref ty_params) => self.process_struct(item, &*def, ty_params),
+            ast::ItemEnum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
             ast::ItemImpl(ref ty_params,
                           ref trait_ref,
                           typ,
                           ref impl_items) => {
                 self.process_impl(item,
-                                  e,
                                   ty_params,
                                   trait_ref,
                                   typ,
                                   impl_items)
             }
             ast::ItemTrait(ref generics, _, ref trait_refs, ref methods) =>
-                self.process_trait(item, e, generics, trait_refs, methods),
-            ast::ItemMod(ref m) => self.process_mod(item, e, m),
+                self.process_trait(item, generics, trait_refs, methods),
+            ast::ItemMod(ref m) => self.process_mod(item, m),
             ast::ItemTy(ty, ref ty_params) => {
                 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
                 let value = ty_to_string(&*ty);
@@ -1060,26 +1054,26 @@ fn visit_item(&mut self, item:&ast::Item, e: DxrVisitorEnv) {
                                      qualname.as_slice(),
                                      value.as_slice());
 
-                self.visit_ty(&*ty, e);
-                self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id, e);
+                self.visit_ty(&*ty);
+                self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
             },
             ast::ItemMac(_) => (),
-            _ => visit::walk_item(self, item, e),
+            _ => visit::walk_item(self, item),
         }
     }
 
-    fn visit_generics(&mut self, generics: &ast::Generics, e: DxrVisitorEnv) {
+    fn visit_generics(&mut self, generics: &ast::Generics) {
         for param in generics.ty_params.iter() {
             for bound in param.bounds.iter() {
                 match *bound {
                     ast::TraitTyParamBound(ref trait_ref) => {
-                        self.process_trait_ref(trait_ref, e, None);
+                        self.process_trait_ref(trait_ref, None);
                     }
                     _ => {}
                 }
             }
             match param.default {
-                Some(ty) => self.visit_ty(&*ty, e),
+                Some(ty) => self.visit_ty(&*ty),
                 None => (),
             }
         }
@@ -1088,23 +1082,22 @@ fn visit_generics(&mut self, generics: &ast::Generics, e: DxrVisitorEnv) {
     // We don't actually index functions here, that is done in visit_item/ItemFn.
     // Here we just visit methods.
     fn visit_fn(&mut self,
-                fk: &visit::FnKind,
-                fd: &ast::FnDecl,
-                b: &ast::Block,
+                fk: visit::FnKind<'v>,
+                fd: &'v ast::FnDecl,
+                b: &'v ast::Block,
                 s: Span,
-                _: NodeId,
-                e: DxrVisitorEnv) {
+                _: NodeId) {
         if generated_code(s) {
             return;
         }
 
-        match *fk {
-            visit::FkMethod(_, _, method) => self.process_method(method, e),
-            _ => visit::walk_fn(self, fk, fd, b, s, e),
+        match fk {
+            visit::FkMethod(_, _, method) => self.process_method(method),
+            _ => visit::walk_fn(self, fk, fd, b, s),
         }
     }
 
-    fn visit_trait_item(&mut self, tm: &ast::TraitItem, e: DxrVisitorEnv) {
+    fn visit_trait_item(&mut self, tm: &ast::TraitItem) {
         match *tm {
             ast::RequiredMethod(ref method_type) => {
                 if generated_code(method_type.span) {
@@ -1137,21 +1130,20 @@ fn visit_trait_item(&mut self, tm: &ast::TraitItem, e: DxrVisitorEnv) {
 
                 // walk arg and return types
                 for arg in method_type.decl.inputs.iter() {
-                    self.visit_ty(&*arg.ty, e);
+                    self.visit_ty(&*arg.ty);
                 }
-                self.visit_ty(&*method_type.decl.output, e);
+                self.visit_ty(&*method_type.decl.output);
 
                 self.process_generic_params(&method_type.generics,
                                             method_type.span,
                                             qualname,
-                                            method_type.id,
-                                            e);
+                                            method_type.id);
             }
-            ast::ProvidedMethod(method) => self.process_method(&*method, e),
+            ast::ProvidedMethod(method) => self.process_method(&*method),
         }
     }
 
-    fn visit_view_item(&mut self, i:&ast::ViewItem, e:DxrVisitorEnv) {
+    fn visit_view_item(&mut self, i: &ast::ViewItem) {
         if generated_code(i.span) {
             return
         }
@@ -1168,7 +1160,7 @@ fn visit_view_item(&mut self, i:&ast::ViewItem, e:DxrVisitorEnv) {
                                                                    path.span,
                                                                    sub_span,
                                                                    def_id,
-                                                                   e.cur_scope),
+                                                                   self.cur_scope),
                                     None => {},
                                 }
                                 Some(def_id)
@@ -1189,11 +1181,11 @@ fn visit_view_item(&mut self, i:&ast::ViewItem, e:DxrVisitorEnv) {
                                                id,
                                                mod_id,
                                                get_ident(ident).get(),
-                                               e.cur_scope);
-                        self.write_sub_paths_truncated(path, e.cur_scope);
+                                               self.cur_scope);
+                        self.write_sub_paths_truncated(path);
                     }
                     ast::ViewPathGlob(ref path, _) => {
-                        self.write_sub_paths(path, e.cur_scope);
+                        self.write_sub_paths(path);
                     }
                     ast::ViewPathList(ref path, ref list, _) => {
                         for plid in list.iter() {
@@ -1206,7 +1198,7 @@ fn visit_view_item(&mut self, i:&ast::ViewItem, e:DxrVisitorEnv) {
                                                     self.fmt.ref_str(
                                                         kind, plid.span,
                                                         Some(plid.span),
-                                                        def_id, e.cur_scope);
+                                                        def_id, self.cur_scope);
                                                 }
                                                 None => ()
                                             },
@@ -1217,7 +1209,7 @@ fn visit_view_item(&mut self, i:&ast::ViewItem, e:DxrVisitorEnv) {
                             }
                         }
 
-                        self.write_sub_paths(path, e.cur_scope);
+                        self.write_sub_paths(path);
                     }
                 }
             },
@@ -1239,12 +1231,12 @@ fn visit_view_item(&mut self, i:&ast::ViewItem, e:DxrVisitorEnv) {
                                           cnum,
                                           name,
                                           s.as_slice(),
-                                          e.cur_scope);
+                                          self.cur_scope);
             },
         }
     }
 
-    fn visit_ty(&mut self, t: &ast::Ty, e: DxrVisitorEnv) {
+    fn visit_ty(&mut self, t: &ast::Ty) {
         if generated_code(t.span) {
             return
         }
@@ -1258,20 +1250,20 @@ fn visit_ty(&mut self, t: &ast::Ty, e: DxrVisitorEnv) {
                                          t.span,
                                          sub_span,
                                          id,
-                                         e.cur_scope);
+                                         self.cur_scope);
                     },
                     None => ()
                 }
 
-                self.write_sub_paths_truncated(path, e.cur_scope);
+                self.write_sub_paths_truncated(path);
 
-                visit::walk_path(self, path, e);
+                visit::walk_path(self, path);
             },
-            _ => visit::walk_ty(self, t, e),
+            _ => visit::walk_ty(self, t),
         }
     }
 
-    fn visit_expr(&mut self, ex: &ast::Expr, e: DxrVisitorEnv) {
+    fn visit_expr(&mut self, ex: &ast::Expr) {
         if generated_code(ex.span) {
             return
         }
@@ -1280,18 +1272,18 @@ fn visit_expr(&mut self, ex: &ast::Expr, e: DxrVisitorEnv) {
             ast::ExprCall(_f, ref _args) => {
                 // Don't need to do anything for function calls,
                 // because just walking the callee path does what we want.
-                visit::walk_expr(self, ex, e);
+                visit::walk_expr(self, ex);
             },
-            ast::ExprPath(ref path) => self.process_path(ex, e, path),
-            ast::ExprStruct(ref path, ref fields, base) =>
-                self.process_struct_lit(ex, e, path, fields, base),
-            ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, e, args),
+            ast::ExprPath(ref path) => self.process_path(ex, path),
+            ast::ExprStruct(ref path, ref fields, ref base) =>
+                self.process_struct_lit(ex, path, fields, base),
+            ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, args),
             ast::ExprField(sub_ex, ident, _) => {
                 if generated_code(sub_ex.span) {
                     return
                 }
 
-                self.visit_expr(&*sub_ex, e);
+                self.visit_expr(&*sub_ex);
 
                 let t = ty::expr_ty_adjusted(&self.analysis.ty_cx, &*sub_ex);
                 let t_box = ty::get(t);
@@ -1305,7 +1297,7 @@ fn visit_expr(&mut self, ex: &ast::Expr, e: DxrVisitorEnv) {
                                                  ex.span,
                                                  sub_span,
                                                  f.id,
-                                                 e.cur_scope);
+                                                 self.cur_scope);
                                 break;
                             }
                         }
@@ -1319,7 +1311,7 @@ fn visit_expr(&mut self, ex: &ast::Expr, e: DxrVisitorEnv) {
                     return
                 }
 
-                self.visit_expr(&*sub_ex, e);
+                self.visit_expr(&*sub_ex);
 
                 let t = ty::expr_ty_adjusted(&self.analysis.ty_cx, &*sub_ex);
                 let t_box = ty::get(t);
@@ -1333,7 +1325,7 @@ fn visit_expr(&mut self, ex: &ast::Expr, e: DxrVisitorEnv) {
                                                  ex.span,
                                                  sub_span,
                                                  f.id,
-                                                 e.cur_scope);
+                                                 self.cur_scope);
                                 break;
                             }
                         }
@@ -1348,41 +1340,41 @@ fn visit_expr(&mut self, ex: &ast::Expr, e: DxrVisitorEnv) {
                 }
 
                 let id = String::from_str("$").append(ex.id.to_string().as_slice());
-                self.process_formals(&decl.inputs, id.as_slice(), e);
+                self.process_formals(&decl.inputs, id.as_slice());
 
                 // walk arg and return types
                 for arg in decl.inputs.iter() {
-                    self.visit_ty(&*arg.ty, e);
+                    self.visit_ty(&*arg.ty);
                 }
-                self.visit_ty(&*decl.output, e);
+                self.visit_ty(&*decl.output);
 
                 // walk the body
-                self.visit_block(&*body, DxrVisitorEnv::new_nested(ex.id));
+                self.nest(ex.id, |v| v.visit_block(&*body));
             },
             _ => {
-                visit::walk_expr(self, ex, e)
+                visit::walk_expr(self, ex)
             },
         }
     }
 
-    fn visit_mac(&mut self, _: &ast::Mac, _: DxrVisitorEnv) {
+    fn visit_mac(&mut self, _: &ast::Mac) {
         // Just stop, macros are poison to us.
     }
 
-    fn visit_pat(&mut self, p: &ast::Pat, e: DxrVisitorEnv) {
-        self.process_pat(p, e);
+    fn visit_pat(&mut self, p: &ast::Pat) {
+        self.process_pat(p);
         if !self.collecting {
             self.collected_paths.clear();
         }
     }
 
-    fn visit_arm(&mut self, arm: &ast::Arm, e: DxrVisitorEnv) {
+    fn visit_arm(&mut self, arm: &ast::Arm) {
         assert!(self.collected_paths.len() == 0 && !self.collecting);
         self.collecting = true;
 
         for pattern in arm.pats.iter() {
             // collect paths from the arm's patterns
-            self.visit_pat(&**pattern, e);
+            self.visit_pat(&**pattern);
         }
         self.collecting = false;
         // process collected paths
@@ -1411,26 +1403,26 @@ fn visit_arm(&mut self, arm: &ast::Arm, e: DxrVisitorEnv) {
                                                             p.span,
                                                             sub_span,
                                                             id,
-                                                            e.cur_scope),
+                                                            self.cur_scope),
                 // FIXME(nrc) what is this doing here?
                 def::DefStatic(_, _) => {}
                 _ => error!("unexpected defintion kind when processing collected paths: {:?}", *def)
             }
         }
         self.collected_paths.clear();
-        visit::walk_expr_opt(self, arm.guard, e);
-        self.visit_expr(&*arm.body, e);
+        visit::walk_expr_opt(self, &arm.guard);
+        self.visit_expr(&*arm.body);
     }
 
-    fn visit_stmt(&mut self, s:&ast::Stmt, e:DxrVisitorEnv) {
+    fn visit_stmt(&mut self, s: &ast::Stmt) {
         if generated_code(s.span) {
             return
         }
 
-        visit::walk_stmt(self, s, e)
+        visit::walk_stmt(self, s)
     }
 
-    fn visit_local(&mut self, l:&ast::Local, e: DxrVisitorEnv) {
+    fn visit_local(&mut self, l: &ast::Local) {
         if generated_code(l.span) {
             return
         }
@@ -1439,7 +1431,7 @@ fn visit_local(&mut self, l:&ast::Local, e: DxrVisitorEnv) {
         // pattern and collect them all.
         assert!(self.collected_paths.len() == 0 && !self.collecting);
         self.collecting = true;
-        self.visit_pat(&*l.pat, e);
+        self.visit_pat(&*l.pat);
         self.collecting = false;
 
         let value = self.span.snippet(l.span);
@@ -1462,22 +1454,8 @@ fn visit_local(&mut self, l:&ast::Local, e: DxrVisitorEnv) {
         self.collected_paths.clear();
 
         // Just walk the initialiser and type (don't want to walk the pattern again).
-        self.visit_ty(&*l.ty, e);
-        visit::walk_expr_opt(self, l.init, e);
-    }
-}
-
-#[deriving(Clone)]
-struct DxrVisitorEnv {
-    cur_scope: NodeId,
-}
-
-impl DxrVisitorEnv {
-    fn new() -> DxrVisitorEnv {
-        DxrVisitorEnv{cur_scope: 0}
-    }
-    fn new_nested(new_mod: NodeId) -> DxrVisitorEnv {
-        DxrVisitorEnv{cur_scope: new_mod}
+        self.visit_ty(&*l.ty);
+        visit::walk_expr_opt(self, &l.init);
     }
 }
 
@@ -1532,25 +1510,28 @@ pub fn process_crate(sess: &Session,
     };
     root_path.pop();
 
-    let mut visitor = DxrVisitor{ sess: sess,
-                                  analysis: analysis,
-                                  collected_paths: vec!(),
-                                  collecting: false,
-                                  fmt: FmtStrs::new(box Recorder {
-                                                        out: output_file as Box<Writer+'static>,
-                                                        dump_spans: false,
-                                                    },
-                                                    SpanUtils {
-                                                        sess: sess,
-                                                        err_count: Cell::new(0)
-                                                    },
-                                                    cratename.clone()),
-                                  span: SpanUtils {
-                                      sess: sess,
-                                      err_count: Cell::new(0)
-                                  }};
+    let mut visitor = DxrVisitor {
+        sess: sess,
+        analysis: analysis,
+        collected_paths: vec!(),
+        collecting: false,
+        fmt: FmtStrs::new(box Recorder {
+                            out: output_file as Box<Writer+'static>,
+                            dump_spans: false,
+                        },
+                        SpanUtils {
+                            sess: sess,
+                            err_count: Cell::new(0)
+                        },
+                        cratename.clone()),
+        span: SpanUtils {
+            sess: sess,
+            err_count: Cell::new(0)
+        },
+        cur_scope: 0
+    };
 
     visitor.dump_crate_info(cratename.as_slice(), krate);
 
-    visit::walk_crate(&mut visitor, krate, DxrVisitorEnv::new());
+    visit::walk_crate(&mut visitor, krate);
 }
index e73d81d9bf5974923a14383547eb37ea6bb37da5..eb736ae8a76661feebfc2fa93c444eafa1702c48 100644 (file)
@@ -24,6 +24,8 @@
 use middle::ty;
 use metadata::csearch;
 
+use std::mem::replace;
+
 /// A stability index, giving the stability level for items and methods.
 pub struct Index {
     // stability for crate-local items; unmarked stability == no entry
@@ -34,68 +36,69 @@ pub struct Index {
 
 // A private tree-walker for producing an Index.
 struct Annotator {
-    index: Index
+    index: Index,
+    parent: Option<Stability>
 }
 
 impl Annotator {
     // Determine the stability for a node based on its attributes and inherited
-    // stability. The stability is recorded in the index and returned.
-    fn annotate(&mut self, id: NodeId, attrs: &[Attribute],
-                parent: Option<Stability>) -> Option<Stability> {
-        match attr::find_stability(attrs).or(parent) {
+    // stability. The stability is recorded in the index and used as the parent.
+    fn annotate(&mut self, id: NodeId, attrs: &Vec<Attribute>, f: |&mut Annotator|) {
+        match attr::find_stability(attrs.as_slice()) {
             Some(stab) => {
                 self.index.local.insert(id, stab.clone());
-                Some(stab)
+                let parent = replace(&mut self.parent, Some(stab));
+                f(self);
+                self.parent = parent;
+            }
+            None => {
+                self.parent.clone().map(|stab| self.index.local.insert(id, stab));
+                f(self);
             }
-            None => None
         }
     }
 }
 
-impl Visitor<Option<Stability>> for Annotator {
-    fn visit_item(&mut self, i: &Item, parent: Option<Stability>) {
-        let stab = self.annotate(i.id, i.attrs.as_slice(), parent);
-        visit::walk_item(self, i, stab)
+impl<'v> Visitor<'v> for Annotator {
+    fn visit_item(&mut self, i: &Item) {
+        self.annotate(i.id, &i.attrs, |v| visit::walk_item(v, i));
     }
 
-    fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl, b: &Block,
-                s: Span, _: NodeId, parent: Option<Stability>) {
-        let stab = match *fk {
-            FkMethod(_, _, meth) =>
-                self.annotate(meth.id, meth.attrs.as_slice(), parent),
-            _ => parent
-        };
-        visit::walk_fn(self, fk, fd, b, s, stab)
+    fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
+                b: &'v Block, s: Span, _: NodeId) {
+        match fk {
+            FkMethod(_, _, meth) => {
+                self.annotate(meth.id, &meth.attrs, |v| visit::walk_fn(v, fk, fd, b, s));
+            }
+            _ => visit::walk_fn(self, fk, fd, b, s)
+        }
     }
 
-    fn visit_trait_item(&mut self, t: &TraitItem, parent: Option<Stability>) {
-        let stab = match *t {
-            RequiredMethod(TypeMethod {attrs: ref attrs, id: id, ..}) =>
-                self.annotate(id, attrs.as_slice(), parent),
+    fn visit_trait_item(&mut self, t: &TraitItem) {
+        let (id, attrs) = match *t {
+            RequiredMethod(TypeMethod {id, ref attrs, ..}) => (id, attrs),
 
             // work around lack of pattern matching for @ types
-            ProvidedMethod(method) => match *method {
-                Method {attrs: ref attrs, id: id, ..} =>
-                    self.annotate(id, attrs.as_slice(), parent)
+            ProvidedMethod(ref method) => match **method {
+                Method {id, ref attrs, ..} => (id, attrs)
             }
         };
-        visit::walk_trait_item(self, t, stab)
+        self.annotate(id, attrs, |v| visit::walk_trait_item(v, t));
     }
 
-    fn visit_variant(&mut self, v: &Variant, g: &Generics, parent: Option<Stability>) {
-        let stab = self.annotate(v.node.id, v.node.attrs.as_slice(), parent);
-        visit::walk_variant(self, v, g, stab)
+    fn visit_variant(&mut self, var: &Variant, g: &'v Generics) {
+        self.annotate(var.node.id, &var.node.attrs, |v| visit::walk_variant(v, var, g))
     }
 
-    fn visit_struct_def(&mut self, s: &StructDef, _: Ident, _: &Generics,
-                        _: NodeId, parent: Option<Stability>) {
-        s.ctor_id.map(|id| self.annotate(id, &[], parent.clone()));
-        visit::walk_struct_def(self, s, parent)
+    fn visit_struct_def(&mut self, s: &StructDef, _: Ident, _: &Generics, _: NodeId) {
+        match s.ctor_id {
+            Some(id) => self.annotate(id, &vec![], |v| visit::walk_struct_def(v, s)),
+            None => visit::walk_struct_def(self, s)
+        }
     }
 
-    fn visit_struct_field(&mut self, s: &StructField, parent: Option<Stability>) {
-        let stab = self.annotate(s.node.id, s.node.attrs.as_slice(), parent);
-        visit::walk_struct_field(self, s, stab)
+    fn visit_struct_field(&mut self, s: &StructField) {
+        self.annotate(s.node.id, &s.node.attrs, |v| visit::walk_struct_field(v, s));
     }
 }
 
@@ -106,10 +109,10 @@ pub fn build(krate: &Crate) -> Index {
             index: Index {
                 local: NodeMap::new(),
                 extern_cache: DefIdMap::new()
-            }
+            },
+            parent: None
         };
-        let stab = annotator.annotate(ast::CRATE_NODE_ID, krate.attrs.as_slice(), None);
-        visit::walk_crate(&mut annotator, krate, stab);
+        annotator.annotate(ast::CRATE_NODE_ID, &krate.attrs, |v| visit::walk_crate(v, krate));
         annotator.index
     }
 }
index dc2aa16eb728494a612c869615a18043e3fc099b..c023b7a9534932c1ecdbcb5819e1f29070e04731 100644 (file)
@@ -1322,18 +1322,32 @@ pub fn make_return_slot_pointer(fcx: &FunctionContext, output_type: ty::t) -> Va
 }
 
 struct CheckForNestedReturnsVisitor {
-    found: bool
+    found: bool,
+    in_return: bool
 }
 
-impl Visitor<bool> for CheckForNestedReturnsVisitor {
-    fn visit_expr(&mut self, e: &ast::Expr, in_return: bool) {
+impl CheckForNestedReturnsVisitor {
+    fn explicit() -> CheckForNestedReturnsVisitor {
+        CheckForNestedReturnsVisitor { found: false, in_return: false }
+    }
+    fn implicit() -> CheckForNestedReturnsVisitor {
+        CheckForNestedReturnsVisitor { found: false, in_return: true }
+    }
+}
+
+impl<'v> Visitor<'v> for CheckForNestedReturnsVisitor {
+    fn visit_expr(&mut self, e: &ast::Expr) {
         match e.node {
-            ast::ExprRet(..) if in_return => {
-                self.found = true;
-                return;
+            ast::ExprRet(..) => {
+                if self.in_return {
+                    self.found = true;
+                } else {
+                    self.in_return = true;
+                    visit::walk_expr(self, e);
+                    self.in_return = false;
+                }
             }
-            ast::ExprRet(..) => visit::walk_expr(self, e, true),
-            _ => visit::walk_expr(self, e, in_return)
+            _ => visit::walk_expr(self, e)
         }
     }
 }
@@ -1343,10 +1357,10 @@ fn has_nested_returns(tcx: &ty::ctxt, id: ast::NodeId) -> bool {
         Some(ast_map::NodeItem(i)) => {
             match i.node {
                 ast::ItemFn(_, _, _, _, blk) => {
-                    let mut explicit = CheckForNestedReturnsVisitor { found: false };
-                    let mut implicit = CheckForNestedReturnsVisitor { found: false };
-                    visit::walk_item(&mut explicit, &*i, false);
-                    visit::walk_expr_opt(&mut implicit, blk.expr, true);
+                    let mut explicit = CheckForNestedReturnsVisitor::explicit();
+                    let mut implicit = CheckForNestedReturnsVisitor::implicit();
+                    visit::walk_item(&mut explicit, &*i);
+                    visit::walk_expr_opt(&mut implicit, &blk.expr);
                     explicit.found || implicit.found
                 }
                 _ => tcx.sess.bug("unexpected item variant in has_nested_returns")
@@ -1357,10 +1371,10 @@ fn has_nested_returns(tcx: &ty::ctxt, id: ast::NodeId) -> bool {
                 ast::ProvidedMethod(m) => {
                     match m.node {
                         ast::MethDecl(_, _, _, _, _, _, blk, _) => {
-                            let mut explicit = CheckForNestedReturnsVisitor { found: false };
-                            let mut implicit = CheckForNestedReturnsVisitor { found: false };
-                            visit::walk_method_helper(&mut explicit, &*m, false);
-                            visit::walk_expr_opt(&mut implicit, blk.expr, true);
+                            let mut explicit = CheckForNestedReturnsVisitor::explicit();
+                            let mut implicit = CheckForNestedReturnsVisitor::implicit();
+                            visit::walk_method_helper(&mut explicit, &*m);
+                            visit::walk_expr_opt(&mut implicit, &blk.expr);
                             explicit.found || implicit.found
                         }
                         ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
@@ -1377,18 +1391,10 @@ fn has_nested_returns(tcx: &ty::ctxt, id: ast::NodeId) -> bool {
                 ast::MethodImplItem(ref m) => {
                     match m.node {
                         ast::MethDecl(_, _, _, _, _, _, blk, _) => {
-                            let mut explicit = CheckForNestedReturnsVisitor {
-                                found: false,
-                            };
-                            let mut implicit = CheckForNestedReturnsVisitor {
-                                found: false,
-                            };
-                            visit::walk_method_helper(&mut explicit,
-                                                      &**m,
-                                                      false);
-                            visit::walk_expr_opt(&mut implicit,
-                                                 blk.expr,
-                                                 true);
+                            let mut explicit = CheckForNestedReturnsVisitor::explicit();
+                            let mut implicit = CheckForNestedReturnsVisitor::implicit();
+                            visit::walk_method_helper(&mut explicit, &**m);
+                            visit::walk_expr_opt(&mut implicit, &blk.expr);
                             explicit.found || implicit.found
                         }
                         ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
@@ -1401,10 +1407,10 @@ fn has_nested_returns(tcx: &ty::ctxt, id: ast::NodeId) -> bool {
                 ast::ExprFnBlock(_, _, blk) |
                 ast::ExprProc(_, blk) |
                 ast::ExprUnboxedFn(_, _, _, blk) => {
-                    let mut explicit = CheckForNestedReturnsVisitor { found: false };
-                    let mut implicit = CheckForNestedReturnsVisitor { found: false };
-                    visit::walk_expr(&mut explicit, &*e, false);
-                    visit::walk_expr_opt(&mut implicit, blk.expr, true);
+                    let mut explicit = CheckForNestedReturnsVisitor::explicit();
+                    let mut implicit = CheckForNestedReturnsVisitor::implicit();
+                    visit::walk_expr(&mut explicit, &*e);
+                    visit::walk_expr_opt(&mut implicit, &blk.expr);
                     explicit.found || implicit.found
                 }
                 _ => tcx.sess.bug("unexpected expr variant in has_nested_returns")
@@ -2135,8 +2141,8 @@ pub struct TransItemVisitor<'a, 'tcx: 'a> {
     pub ccx: &'a CrateContext<'a, 'tcx>,
 }
 
-impl<'a, 'tcx> Visitor<()> for TransItemVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, i: &ast::Item, _:()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for TransItemVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, i: &ast::Item) {
         trans_item(self.ccx, i);
     }
 }
@@ -2236,7 +2242,7 @@ pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
         // Be sure to travel more than just one layer deep to catch nested
         // items in blocks and such.
         let mut v = TransItemVisitor{ ccx: ccx };
-        v.visit_block(&**body, ());
+        v.visit_block(&**body);
       }
       ast::ItemImpl(ref generics, _, _, ref impl_items) => {
         meth::trans_impl(ccx,
@@ -2254,7 +2260,7 @@ pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
       ast::ItemStatic(_, m, ref expr) => {
           // Recurse on the expression to catch items in blocks
           let mut v = TransItemVisitor{ ccx: ccx };
-          v.visit_expr(&**expr, ());
+          v.visit_expr(&**expr);
 
           let trans_everywhere = attr::requests_inline(item.attrs.as_slice());
           for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
@@ -2293,7 +2299,7 @@ pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
         // methods with items will not get translated and will cause ICE's when
         // metadata time comes around.
         let mut v = TransItemVisitor{ ccx: ccx };
-        visit::walk_item(&mut v, item, ());
+        visit::walk_item(&mut v, item);
       }
       _ => {/* fall through */ }
     }
index dd9e41a61bf8748fa0adc29b3f8d6a00976e84cf..164ddd65f3540b608a473f80ffc7b9128a184c7e 100644 (file)
@@ -150,7 +150,7 @@ pub fn trans_if<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
             match els {
                 Some(elexpr) => {
                     let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx };
-                    trans.visit_expr(&*elexpr, ());
+                    trans.visit_expr(&*elexpr);
                 }
                 None => {}
             }
@@ -159,7 +159,7 @@ pub fn trans_if<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
             trans::debuginfo::clear_source_location(bcx.fcx);
         } else {
             let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx } ;
-            trans.visit_block(&*thn, ());
+            trans.visit_block(&*thn);
 
             match els {
                 // if false { .. } else { .. }
index fb1a764f0fce51eefb7051e7eeeac44cf3791017..384502025cb1f469627ae119a8545efd5bc34745 100644 (file)
@@ -67,7 +67,7 @@ pub fn trans_impl(ccx: &CrateContext,
         for impl_item in impl_items.iter() {
             match *impl_item {
                 ast::MethodImplItem(method) => {
-                    visit::walk_method_helper(&mut v, &*method, ());
+                    visit::walk_method_helper(&mut v, &*method);
                 }
             }
         }
@@ -96,7 +96,7 @@ pub fn trans_impl(ccx: &CrateContext,
                 let mut v = TransItemVisitor {
                     ccx: ccx,
                 };
-                visit::walk_method_helper(&mut v, &*method, ());
+                visit::walk_method_helper(&mut v, &*method);
             }
         }
     }
index e196304b82ac39a6b65ae086bbef84e8b480884e..48173cc6804283d77992f9d7ba6b1fc7e22f9021 100644 (file)
@@ -2992,14 +2992,13 @@ pub fn lltype_is_sized(cx: &ctxt, ty: t) -> bool {
 pub fn unsized_part_of_type(cx: &ctxt, ty: t) -> t {
     match get(ty).sty {
         ty_str | ty_trait(..) | ty_vec(..) => ty,
-        ty_struct(_, ref substs) => {
-            // Exactly one of the type parameters must be unsized.
-            for tp in substs.types.get_slice(subst::TypeSpace).iter() {
-                if !type_is_sized(cx, *tp) {
-                    return unsized_part_of_type(cx, *tp);
-                }
-            }
-            fail!("Unsized struct type with no unsized type params? {}", ty_to_string(cx, ty));
+        ty_struct(def_id, ref substs) => {
+            let unsized_fields: Vec<_> = struct_fields(cx, def_id, substs).iter()
+                .map(|f| f.mt.ty).filter(|ty| !type_is_sized(cx, *ty)).collect();
+            // Exactly one of the fields must be unsized.
+            assert!(unsized_fields.len() == 1)
+
+            unsized_part_of_type(cx, unsized_fields[0])
         }
         _ => {
             assert!(type_is_sized(cx, ty),
index 4f0f6121904a128e5d4011bbfc2f8fc655bb3247..47a4b6f86229e13709387876c0b88f1f5e316673 100644 (file)
@@ -375,18 +375,18 @@ fn static_inherited_fields<'a, 'tcx>(ccx: &'a CrateCtxt<'a, 'tcx>)
 struct CheckItemTypesVisitor<'a, 'tcx: 'a> { ccx: &'a CrateCtxt<'a, 'tcx> }
 struct CheckTypeWellFormedVisitor<'a, 'tcx: 'a> { ccx: &'a CrateCtxt<'a, 'tcx> }
 
-impl<'a, 'tcx> Visitor<()> for CheckTypeWellFormedVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, i: &ast::Item, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, i: &ast::Item) {
         check_type_well_formed(self.ccx, i);
-        visit::walk_item(self, i, ());
+        visit::walk_item(self, i);
     }
 }
 
 
-impl<'a, 'tcx> Visitor<()> for CheckItemTypesVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, i: &ast::Item, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for CheckItemTypesVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, i: &ast::Item) {
         check_item(self.ccx, i);
-        visit::walk_item(self, i, ());
+        visit::walk_item(self, i);
     }
 }
 
@@ -394,28 +394,28 @@ struct CheckItemSizedTypesVisitor<'a, 'tcx: 'a> {
     ccx: &'a CrateCtxt<'a, 'tcx>
 }
 
-impl<'a, 'tcx> Visitor<()> for CheckItemSizedTypesVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, i: &ast::Item, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for CheckItemSizedTypesVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, i: &ast::Item) {
         check_item_sized(self.ccx, i);
-        visit::walk_item(self, i, ());
+        visit::walk_item(self, i);
     }
 }
 
 pub fn check_item_types(ccx: &CrateCtxt, krate: &ast::Crate) {
     let mut visit = CheckTypeWellFormedVisitor { ccx: ccx };
-    visit::walk_crate(&mut visit, krate, ());
+    visit::walk_crate(&mut visit, krate);
 
     // If types are not well-formed, it leads to all manner of errors
     // downstream, so stop reporting errors at this point.
     ccx.tcx.sess.abort_if_errors();
 
     let mut visit = CheckItemTypesVisitor { ccx: ccx };
-    visit::walk_crate(&mut visit, krate, ());
+    visit::walk_crate(&mut visit, krate);
 
     ccx.tcx.sess.abort_if_errors();
 
     let mut visit = CheckItemSizedTypesVisitor { ccx: ccx };
-    visit::walk_crate(&mut visit, krate, ());
+    visit::walk_crate(&mut visit, krate);
 }
 
 fn check_bare_fn(ccx: &CrateCtxt,
@@ -464,9 +464,9 @@ fn assign(&mut self, nid: ast::NodeId, ty_opt: Option<ty::t>) {
     }
 }
 
-impl<'a, 'tcx> Visitor<()> for GatherLocalsVisitor<'a, 'tcx> {
+impl<'a, 'tcx, 'v> Visitor<'v> for GatherLocalsVisitor<'a, 'tcx> {
     // Add explicitly-declared locals.
-    fn visit_local(&mut self, local: &ast::Local, _: ()) {
+    fn visit_local(&mut self, local: &ast::Local) {
         let o_ty = match local.ty.node {
             ast::TyInfer => None,
             _ => Some(self.fcx.to_ty(&*local.ty))
@@ -476,11 +476,11 @@ fn visit_local(&mut self, local: &ast::Local, _: ()) {
                self.fcx.pat_to_string(&*local.pat),
                self.fcx.infcx().ty_to_string(
                    self.fcx.inh.locals.borrow().get_copy(&local.id)));
-        visit::walk_local(self, local, ());
+        visit::walk_local(self, local);
     }
 
     // Add pattern bindings.
-    fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
+    fn visit_pat(&mut self, p: &ast::Pat) {
             match p.node {
               ast::PatIdent(_, ref path1, _)
                   if pat_util::pat_is_binding(&self.fcx.ccx.tcx.def_map, p) => {
@@ -492,33 +492,33 @@ fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
               }
               _ => {}
             }
-            visit::walk_pat(self, p, ());
+            visit::walk_pat(self, p);
 
     }
 
-    fn visit_block(&mut self, b: &ast::Block, _: ()) {
+    fn visit_block(&mut self, b: &ast::Block) {
         // non-obvious: the `blk` variable maps to region lb, so
         // we have to keep this up-to-date.  This
         // is... unfortunate.  It'd be nice to not need this.
-        visit::walk_block(self, b, ());
+        visit::walk_block(self, b);
     }
 
     // Since an expr occurs as part of the type fixed size arrays we
     // need to record the type for that node
-    fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
+    fn visit_ty(&mut self, t: &ast::Ty) {
         match t.node {
             ast::TyFixedLengthVec(ref ty, ref count_expr) => {
-                self.visit_ty(&**ty, ());
+                self.visit_ty(&**ty);
                 check_expr_with_hint(self.fcx, &**count_expr, ty::mk_uint());
             }
-            _ => visit::walk_ty(self, t, ())
+            _ => visit::walk_ty(self, t)
         }
     }
 
     // Don't descend into fns and items
-    fn visit_fn(&mut self, _: &visit::FnKind, _: &ast::FnDecl,
-                _: &ast::Block, _: Span, _: ast::NodeId, _: ()) { }
-    fn visit_item(&mut self, _: &ast::Item, _: ()) { }
+    fn visit_fn(&mut self, _: visit::FnKind<'v>, _: &'v ast::FnDecl,
+                _: &'v ast::Block, _: Span, _: ast::NodeId) { }
+    fn visit_item(&mut self, _: &ast::Item) { }
 
 }
 
@@ -603,7 +603,7 @@ fn check_fn<'a, 'tcx>(ccx: &'a CrateCtxt<'a, 'tcx>,
             _match::check_pat(&pcx, &*input.pat, *arg_ty);
         }
 
-        visit.visit_block(body, ());
+        visit.visit_block(body);
     }
 
     check_block_with_expected(&fcx, body, ExpectHasType(ret_ty));
@@ -4508,7 +4508,7 @@ pub fn check_const_with_ty(fcx: &FnCtxt,
     // This is technically unnecessary because locals in static items are forbidden,
     // but prevents type checking from blowing up before const checking can properly
     // emit a error.
-    GatherLocalsVisitor { fcx: fcx }.visit_expr(e, ());
+    GatherLocalsVisitor { fcx: fcx }.visit_expr(e);
 
     check_expr_with_hint(fcx, e, declty);
     demand::coerce(fcx, e.span, declty, e);
index 6ddb10cc8ca6fb136cc37b48d1917df1ece22091..843d6a582eac3a04df67ef3b5c2c5157efc5bad4 100644 (file)
@@ -150,7 +150,7 @@ pub fn regionck_expr(fcx: &FnCtxt, e: &ast::Expr) {
     let mut rcx = Rcx::new(fcx, e.id);
     if fcx.err_count_since_creation() == 0 {
         // regionck assumes typeck succeeded
-        rcx.visit_expr(e, ());
+        rcx.visit_expr(e);
         rcx.visit_region_obligations(e.id);
     }
     fcx.infcx().resolve_regions_and_report_errors();
@@ -346,7 +346,7 @@ fn visit_fn_body(&mut self,
 
         let len = self.region_param_pairs.len();
         self.relate_free_regions(fn_sig.as_slice(), body.id);
-        self.visit_block(body, ());
+        self.visit_block(body);
         self.visit_region_obligations(body.id);
         self.region_param_pairs.truncate(len);
     }
@@ -479,7 +479,7 @@ fn unboxed_closures<'a>(&'a self)
     }
 }
 
-impl<'a, 'tcx> Visitor<()> for Rcx<'a, 'tcx> {
+impl<'a, 'tcx, 'v> Visitor<'v> for Rcx<'a, 'tcx> {
     // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
     // However, right now we run into an issue whereby some free
     // regions are not properly related if they appear within the
@@ -488,22 +488,22 @@ impl<'a, 'tcx> Visitor<()> for Rcx<'a, 'tcx> {
     // hierarchy, and in particular the relationships between free
     // regions, until regionck, as described in #3238.
 
-    fn visit_fn(&mut self, _fk: &visit::FnKind, _fd: &ast::FnDecl,
-                b: &ast::Block, _s: Span, id: ast::NodeId, _e: ()) {
+    fn visit_fn(&mut self, _fk: visit::FnKind<'v>, _fd: &'v ast::FnDecl,
+                b: &'v ast::Block, _s: Span, id: ast::NodeId) {
         self.visit_fn_body(id, b)
     }
 
-    fn visit_item(&mut self, i: &ast::Item, _: ()) { visit_item(self, i); }
+    fn visit_item(&mut self, i: &ast::Item) { visit_item(self, i); }
 
-    fn visit_expr(&mut self, ex: &ast::Expr, _: ()) { visit_expr(self, ex); }
+    fn visit_expr(&mut self, ex: &ast::Expr) { visit_expr(self, ex); }
 
     //visit_pat: visit_pat, // (..) see above
 
-    fn visit_arm(&mut self, a: &ast::Arm, _: ()) { visit_arm(self, a); }
+    fn visit_arm(&mut self, a: &ast::Arm) { visit_arm(self, a); }
 
-    fn visit_local(&mut self, l: &ast::Local, _: ()) { visit_local(self, l); }
+    fn visit_local(&mut self, l: &ast::Local) { visit_local(self, l); }
 
-    fn visit_block(&mut self, b: &ast::Block, _: ()) { visit_block(self, b); }
+    fn visit_block(&mut self, b: &ast::Block) { visit_block(self, b); }
 }
 
 fn visit_item(_rcx: &mut Rcx, _item: &ast::Item) {
@@ -511,7 +511,7 @@ fn visit_item(_rcx: &mut Rcx, _item: &ast::Item) {
 }
 
 fn visit_block(rcx: &mut Rcx, b: &ast::Block) {
-    visit::walk_block(rcx, b, ());
+    visit::walk_block(rcx, b);
 }
 
 fn visit_arm(rcx: &mut Rcx, arm: &ast::Arm) {
@@ -520,14 +520,14 @@ fn visit_arm(rcx: &mut Rcx, arm: &ast::Arm) {
         constrain_bindings_in_pat(&**p, rcx);
     }
 
-    visit::walk_arm(rcx, arm, ());
+    visit::walk_arm(rcx, arm);
 }
 
 fn visit_local(rcx: &mut Rcx, l: &ast::Local) {
     // see above
     constrain_bindings_in_pat(&*l.pat, rcx);
     link_local(rcx, l);
-    visit::walk_local(rcx, l, ());
+    visit::walk_local(rcx, l);
 }
 
 fn constrain_bindings_in_pat(pat: &ast::Pat, rcx: &mut Rcx) {
@@ -625,19 +625,19 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) {
                                false);
             }
 
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
         }
 
         ast::ExprMethodCall(_, _, ref args) => {
             constrain_call(rcx, expr, Some(*args.get(0)),
                            args.slice_from(1), false);
 
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
         }
 
         ast::ExprAssign(ref lhs, _) => {
             adjust_borrow_kind_for_assignment_lhs(rcx, &**lhs);
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
         }
 
         ast::ExprAssignOp(_, ref lhs, ref rhs) => {
@@ -648,7 +648,7 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) {
 
             adjust_borrow_kind_for_assignment_lhs(rcx, &**lhs);
 
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
         }
 
         ast::ExprIndex(ref lhs, ref rhs) |
@@ -660,14 +660,14 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) {
             constrain_call(rcx, expr, Some(lhs.clone()),
                            [rhs.clone()], true);
 
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
         }
 
         ast::ExprUnary(_, ref lhs) if has_method_map => {
             // As above.
             constrain_call(rcx, expr, Some(lhs.clone()), [], true);
 
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
         }
 
         ast::ExprUnary(ast::UnBox, ref base) => {
@@ -675,7 +675,7 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) {
             let base_ty = rcx.resolve_node_type(base.id);
             type_must_outlive(rcx, infer::Managed(expr.span),
                               base_ty, ty::ReStatic);
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
         }
 
         ast::ExprUnary(ast::UnDeref, ref base) => {
@@ -696,7 +696,7 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) {
                 _ => {}
             }
 
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
         }
 
         ast::ExprIndex(ref vec_expr, _) => {
@@ -704,7 +704,7 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) {
             let vec_type = rcx.resolve_expr_type_adjusted(&**vec_expr);
             constrain_index(rcx, expr, vec_type);
 
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
         }
 
         ast::ExprCast(ref source, _) => {
@@ -712,7 +712,7 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) {
             // instance.  If so, we have to be sure that the type of
             // the source obeys the trait's region bound.
             constrain_cast(rcx, expr, &**source);
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
         }
 
         ast::ExprAddrOf(m, ref base) => {
@@ -728,13 +728,13 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) {
             let ty0 = rcx.resolve_node_type(expr.id);
             type_must_outlive(rcx, infer::AddrOf(expr.span),
                               ty0, ty::ReScope(expr.id));
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
         }
 
         ast::ExprMatch(ref discr, ref arms) => {
             link_match(rcx, &**discr, arms.as_slice());
 
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
         }
 
         ast::ExprFnBlock(_, _, ref body) |
@@ -745,16 +745,16 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) {
 
         ast::ExprLoop(ref body, _) => {
             let repeating_scope = rcx.set_repeating_scope(body.id);
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
             rcx.set_repeating_scope(repeating_scope);
         }
 
         ast::ExprWhile(ref cond, ref body, _) => {
             let repeating_scope = rcx.set_repeating_scope(cond.id);
-            rcx.visit_expr(&**cond, ());
+            rcx.visit_expr(&**cond);
 
             rcx.set_repeating_scope(body.id);
-            rcx.visit_block(&**body, ());
+            rcx.visit_block(&**body);
 
             rcx.set_repeating_scope(repeating_scope);
         }
@@ -768,19 +768,19 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) {
                 link_pattern(rcx, mc, head_cmt, &**pat);
             }
 
-            rcx.visit_expr(&**head, ());
+            rcx.visit_expr(&**head);
             type_of_node_must_outlive(rcx,
                                       infer::AddrOf(expr.span),
                                       head.id,
                                       ty::ReScope(expr.id));
 
             let repeating_scope = rcx.set_repeating_scope(body.id);
-            rcx.visit_block(&**body, ());
+            rcx.visit_block(&**body);
             rcx.set_repeating_scope(repeating_scope);
         }
 
         _ => {
-            visit::walk_expr(rcx, expr, ());
+            visit::walk_expr(rcx, expr);
         }
     }
 }
@@ -890,7 +890,7 @@ fn check_expr_fn_block(rcx: &mut Rcx,
     }
 
     let repeating_scope = rcx.set_repeating_scope(body.id);
-    visit::walk_expr(rcx, expr, ());
+    visit::walk_expr(rcx, expr);
     rcx.set_repeating_scope(repeating_scope);
 
     match ty::get(function_type).sty {
index 16136fcf3e840c5046d7f96e500373142cfcfcbf..9a70cf574fc4d942ecae922180f0eb7a0fa79aef 100644 (file)
@@ -1025,12 +1025,12 @@ pub fn trans_resolve_method(tcx: &ty::ctxt, id: ast::NodeId,
                    false)
 }
 
-impl<'a, 'b, 'tcx> visit::Visitor<()> for &'a FnCtxt<'b, 'tcx> {
-    fn visit_expr(&mut self, ex: &ast::Expr, _: ()) {
+impl<'a, 'b, 'tcx, 'v> Visitor<'v> for &'a FnCtxt<'b, 'tcx> {
+    fn visit_expr(&mut self, ex: &ast::Expr) {
         early_resolve_expr(ex, *self, false);
-        visit::walk_expr(self, ex, ());
+        visit::walk_expr(self, ex);
     }
-    fn visit_item(&mut self, _: &ast::Item, _: ()) {
+    fn visit_item(&mut self, _: &ast::Item) {
         // no-op
     }
 }
@@ -1038,7 +1038,7 @@ fn visit_item(&mut self, _: &ast::Item, _: ()) {
 // Detect points where a trait-bounded type parameter is
 // instantiated, resolve the impls for the parameters.
 pub fn resolve_in_block(mut fcx: &FnCtxt, bl: &ast::Block) {
-    visit::walk_block(&mut fcx, bl, ());
+    visit::walk_block(&mut fcx, bl);
 }
 
 /// Used in the kind checker after typechecking has finished. Calls
index d65172cc0c167a57e922aef74994ed9c7f720a80..4716ffe700b502db96ebd69284aaa8c2ee42b557 100644 (file)
@@ -41,7 +41,7 @@
 pub fn resolve_type_vars_in_expr(fcx: &FnCtxt, e: &ast::Expr) {
     assert_eq!(fcx.writeback_errors.get(), false);
     let mut wbcx = WritebackCx::new(fcx);
-    wbcx.visit_expr(e, ());
+    wbcx.visit_expr(e);
     wbcx.visit_upvar_borrow_map();
     wbcx.visit_unboxed_closures();
 }
@@ -51,9 +51,9 @@ pub fn resolve_type_vars_in_fn(fcx: &FnCtxt,
                                blk: &ast::Block) {
     assert_eq!(fcx.writeback_errors.get(), false);
     let mut wbcx = WritebackCx::new(fcx);
-    wbcx.visit_block(blk, ());
+    wbcx.visit_block(blk);
     for arg in decl.inputs.iter() {
-        wbcx.visit_pat(&*arg.pat, ());
+        wbcx.visit_pat(&*arg.pat);
 
         // Privacy needs the type for the whole pattern, not just each binding
         if !pat_util::pat_is_binding(&fcx.tcx().def_map, &*arg.pat) {
@@ -106,21 +106,21 @@ fn tcx(&self) -> &'cx ty::ctxt<'tcx> {
 // below. In general, a function is made into a `visitor` if it must
 // traffic in node-ids or update tables in the type context etc.
 
-impl<'cx, 'tcx> Visitor<()> for WritebackCx<'cx, 'tcx> {
-    fn visit_item(&mut self, _: &ast::Item, _: ()) {
+impl<'cx, 'tcx, 'v> Visitor<'v> for WritebackCx<'cx, 'tcx> {
+    fn visit_item(&mut self, _: &ast::Item) {
         // Ignore items
     }
 
-    fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
+    fn visit_stmt(&mut self, s: &ast::Stmt) {
         if self.fcx.writeback_errors.get() {
             return;
         }
 
         self.visit_node_id(ResolvingExpr(s.span), ty::stmt_node_id(s));
-        visit::walk_stmt(self, s, ());
+        visit::walk_stmt(self, s);
     }
 
-    fn visit_expr(&mut self, e:&ast::Expr, _: ()) {
+    fn visit_expr(&mut self, e: &ast::Expr) {
         if self.fcx.writeback_errors.get() {
             return;
         }
@@ -143,19 +143,19 @@ fn visit_expr(&mut self, e:&ast::Expr, _: ()) {
             _ => {}
         }
 
-        visit::walk_expr(self, e, ());
+        visit::walk_expr(self, e);
     }
 
-    fn visit_block(&mut self, b: &ast::Block, _: ()) {
+    fn visit_block(&mut self, b: &ast::Block) {
         if self.fcx.writeback_errors.get() {
             return;
         }
 
         self.visit_node_id(ResolvingExpr(b.span), b.id);
-        visit::walk_block(self, b, ());
+        visit::walk_block(self, b);
     }
 
-    fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
+    fn visit_pat(&mut self, p: &ast::Pat) {
         if self.fcx.writeback_errors.get() {
             return;
         }
@@ -167,10 +167,10 @@ fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
                p.id,
                ty::node_id_to_type(self.tcx(), p.id).repr(self.tcx()));
 
-        visit::walk_pat(self, p, ());
+        visit::walk_pat(self, p);
     }
 
-    fn visit_local(&mut self, l: &ast::Local, _: ()) {
+    fn visit_local(&mut self, l: &ast::Local) {
         if self.fcx.writeback_errors.get() {
             return;
         }
@@ -178,16 +178,16 @@ fn visit_local(&mut self, l: &ast::Local, _: ()) {
         let var_ty = self.fcx.local_ty(l.span, l.id);
         let var_ty = self.resolve(&var_ty, ResolvingLocal(l.span));
         write_ty_to_tcx(self.tcx(), l.id, var_ty);
-        visit::walk_local(self, l, ());
+        visit::walk_local(self, l);
     }
 
-    fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
+    fn visit_ty(&mut self, t: &ast::Ty) {
         match t.node {
             ast::TyFixedLengthVec(ref ty, ref count_expr) => {
-                self.visit_ty(&**ty, ());
+                self.visit_ty(&**ty);
                 write_ty_to_tcx(self.tcx(), count_expr.id, ty::mk_uint());
             }
-            _ => visit::walk_ty(self, t, ())
+            _ => visit::walk_ty(self, t)
         }
     }
 }
index 2c6dc94f182b4bd56b4e01062b617fe2410680ca..ff3372b307260945951ee5696ff68c8290f964c3 100644 (file)
@@ -191,8 +191,8 @@ struct CoherenceCheckVisitor<'a, 'tcx: 'a> {
     cc: &'a CoherenceChecker<'a, 'tcx>
 }
 
-impl<'a, 'tcx> visit::Visitor<()> for CoherenceCheckVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, item: &Item, _: ()) {
+impl<'a, 'tcx, 'v> visit::Visitor<'v> for CoherenceCheckVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, item: &Item) {
 
         //debug!("(checking coherence) item '{}'", token::get_ident(item.ident));
 
@@ -210,7 +210,7 @@ fn visit_item(&mut self, item: &Item, _: ()) {
             }
         };
 
-        visit::walk_item(self, item, ());
+        visit::walk_item(self, item);
     }
 }
 
@@ -218,13 +218,13 @@ struct PrivilegedScopeVisitor<'a, 'tcx: 'a> {
     cc: &'a CoherenceChecker<'a, 'tcx>
 }
 
-impl<'a, 'tcx> visit::Visitor<()> for PrivilegedScopeVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, item: &Item, _: ()) {
+impl<'a, 'tcx, 'v> visit::Visitor<'v> for PrivilegedScopeVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, item: &Item) {
 
         match item.node {
             ItemMod(ref module_) => {
                 // Then visit the module items.
-                visit::walk_mod(self, module_, ());
+                visit::walk_mod(self, module_);
             }
             ItemImpl(_, None, ref ast_ty, _) => {
                 if !self.cc.ast_type_is_defined_in_local_crate(&**ast_ty) {
@@ -256,10 +256,10 @@ fn visit_item(&mut self, item: &Item, _: ()) {
                     }
                 }
 
-                visit::walk_item(self, item, ());
+                visit::walk_item(self, item);
             }
             _ => {
-                visit::walk_item(self, item, ());
+                visit::walk_item(self, item);
             }
         }
     }
@@ -271,7 +271,7 @@ fn check(&self, krate: &Crate) {
         // containing the inherent methods and extension methods. It also
         // builds up the trait inheritance table.
         let mut visitor = CoherenceCheckVisitor { cc: self };
-        visit::walk_crate(&mut visitor, krate, ());
+        visit::walk_crate(&mut visitor, krate);
 
         // Check that there are no overlapping trait instances
         self.check_implementation_coherence();
@@ -543,7 +543,7 @@ fn get_self_type_for_implementation(&self, impl_did: DefId)
     // Privileged scope checking
     fn check_privileged_scopes(&self, krate: &Crate) {
         let mut visitor = PrivilegedScopeVisitor{ cc: self };
-        visit::walk_crate(&mut visitor, krate, ());
+        visit::walk_crate(&mut visitor, krate);
     }
 
     fn trait_ref_to_trait_def_id(&self, trait_ref: &TraitRef) -> DefId {
index d1d76734941e8b68cac3fde546cd8f00bd02a144..20e76b01317b8dccd5116982e2253a982668c609 100644 (file)
@@ -84,10 +84,10 @@ fn collect_intrinsic_type(ccx: &CrateCtxt,
     }
 
     let mut visitor = CollectTraitDefVisitor{ ccx: ccx };
-    visit::walk_crate(&mut visitor, krate, ());
+    visit::walk_crate(&mut visitor, krate);
 
     let mut visitor = CollectItemTypesVisitor{ ccx: ccx };
-    visit::walk_crate(&mut visitor, krate, ());
+    visit::walk_crate(&mut visitor, krate);
 }
 
 ///////////////////////////////////////////////////////////////////////////
@@ -99,8 +99,8 @@ struct CollectTraitDefVisitor<'a, 'tcx: 'a> {
     ccx: &'a CrateCtxt<'a, 'tcx>
 }
 
-impl<'a, 'tcx> visit::Visitor<()> for CollectTraitDefVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, i: &ast::Item, _: ()) {
+impl<'a, 'tcx, 'v> visit::Visitor<'v> for CollectTraitDefVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, i: &ast::Item) {
         match i.node {
             ast::ItemTrait(..) => {
                 // computing the trait def also fills in the table
@@ -109,7 +109,7 @@ fn visit_item(&mut self, i: &ast::Item, _: ()) {
             _ => { }
         }
 
-        visit::walk_item(self, i, ());
+        visit::walk_item(self, i);
     }
 }
 
@@ -120,14 +120,14 @@ struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
     ccx: &'a CrateCtxt<'a, 'tcx>
 }
 
-impl<'a, 'tcx> visit::Visitor<()> for CollectItemTypesVisitor<'a, 'tcx> {
-    fn visit_item(&mut self, i: &ast::Item, _: ()) {
+impl<'a, 'tcx, 'v> visit::Visitor<'v> for CollectItemTypesVisitor<'a, 'tcx> {
+    fn visit_item(&mut self, i: &ast::Item) {
         convert(self.ccx, i);
-        visit::walk_item(self, i, ());
+        visit::walk_item(self, i);
     }
-    fn visit_foreign_item(&mut self, i: &ast::ForeignItem, _: ()) {
+    fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
         convert_foreign(self.ccx, i);
-        visit::walk_foreign_item(self, i, ());
+        visit::walk_foreign_item(self, i);
     }
 }
 
index 7e8c53159fb8d0a39e6f6468db91f71b800d9763..9526e5d3eb5b5b82b735b2a6a1675bf670829a68 100644 (file)
@@ -301,7 +301,7 @@ fn determine_parameters_to_be_inferred<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
         })
     };
 
-    visit::walk_crate(&mut terms_cx, krate, ());
+    visit::walk_crate(&mut terms_cx, krate);
 
     terms_cx
 }
@@ -337,8 +337,8 @@ fn num_inferred(&self) -> uint {
     }
 }
 
-impl<'a, 'tcx> Visitor<()> for TermsContext<'a, 'tcx> {
-    fn visit_item(&mut self, item: &ast::Item, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for TermsContext<'a, 'tcx> {
+    fn visit_item(&mut self, item: &ast::Item) {
         debug!("add_inferreds for item {}", item.repr(self.tcx));
 
         let inferreds_on_entry = self.num_inferred();
@@ -379,7 +379,7 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
                     assert!(newly_added);
                 }
 
-                visit::walk_item(self, item, ());
+                visit::walk_item(self, item);
             }
 
             ast::ItemImpl(..) |
@@ -389,7 +389,7 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
             ast::ItemForeignMod(..) |
             ast::ItemTy(..) |
             ast::ItemMac(..) => {
-                visit::walk_item(self, item, ());
+                visit::walk_item(self, item);
             }
         }
     }
@@ -473,12 +473,12 @@ fn add_constraints_from_crate<'a, 'tcx>(terms_cx: TermsContext<'a, 'tcx>,
         bivariant: bivariant,
         constraints: Vec::new(),
     };
-    visit::walk_crate(&mut constraint_cx, krate, ());
+    visit::walk_crate(&mut constraint_cx, krate);
     constraint_cx
 }
 
-impl<'a, 'tcx> Visitor<()> for ConstraintContext<'a, 'tcx> {
-    fn visit_item(&mut self, item: &ast::Item, _: ()) {
+impl<'a, 'tcx, 'v> Visitor<'v> for ConstraintContext<'a, 'tcx> {
+    fn visit_item(&mut self, item: &ast::Item) {
         let did = ast_util::local_def(item.id);
         let tcx = self.terms_cx.tcx;
 
@@ -533,7 +533,7 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
             ast::ItemTy(..) |
             ast::ItemImpl(..) |
             ast::ItemMac(..) => {
-                visit::walk_item(self, item, ());
+                visit::walk_item(self, item);
             }
         }
     }
index 7a36c423add04ecde310ba0669de6dafd7d96c88..81099da3fac0561f838e3e8138b8454de48728e3 100644 (file)
@@ -47,7 +47,7 @@ pub fn check_crate(krate: &ast::Crate,
 
     {
         let mut cx = Context { sess: sess, items: items };
-        visit::walk_crate(&mut cx, krate, ());
+        visit::walk_crate(&mut cx, krate);
     }
     verify(sess, items);
 }
@@ -105,13 +105,13 @@ fn register(&mut self, name: &str, span: Span) {
     }
 }
 
-impl<'a> Visitor<()> for Context<'a> {
-    fn visit_foreign_item(&mut self, i: &ast::ForeignItem, _: ()) {
+impl<'a, 'v> Visitor<'v> for Context<'a> {
+    fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
         match lang_items::extract(i.attrs.as_slice()) {
             None => {}
             Some(lang_item) => self.register(lang_item.get(), i.span),
         }
-        visit::walk_foreign_item(self, i, ())
+        visit::walk_foreign_item(self, i)
     }
 }
 
index ad35c4efe1138adc6eb2a48b86c62ab83e3aeadf..457fcb861e6de58e3b4cab91ad8348059da31023 100644 (file)
@@ -21,8 +21,8 @@ struct RegistrarFinder {
     registrars: Vec<(ast::NodeId, Span)> ,
 }
 
-impl Visitor<()> for RegistrarFinder {
-    fn visit_item(&mut self, item: &ast::Item, _: ()) {
+impl<'v> Visitor<'v> for RegistrarFinder {
+    fn visit_item(&mut self, item: &ast::Item) {
         match item.node {
             ast::ItemFn(..) => {
                 if attr::contains_name(item.attrs.as_slice(),
@@ -33,7 +33,7 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
             _ => {}
         }
 
-        visit::walk_item(self, item, ());
+        visit::walk_item(self, item);
     }
 }
 
@@ -41,7 +41,7 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) {
 pub fn find_plugin_registrar(diagnostic: &diagnostic::SpanHandler,
                              krate: &ast::Crate) -> Option<ast::NodeId> {
     let mut finder = RegistrarFinder { registrars: Vec::new() };
-    visit::walk_crate(&mut finder, krate, ());
+    visit::walk_crate(&mut finder, krate);
 
     match finder.registrars.len() {
         0 => None,
index 4f38c74893e46630c08420440a49160938272d37..ecbe3409139f7649738233ad8e68abe93764ae3b 100644 (file)
@@ -69,7 +69,7 @@ fn new(sess: &'a Session) -> PluginLoader<'a> {
 pub fn load_plugins(sess: &Session, krate: &ast::Crate,
                     addl_plugins: Option<Plugins>) -> Plugins {
     let mut loader = PluginLoader::new(sess);
-    visit::walk_crate(&mut loader, krate, ());
+    visit::walk_crate(&mut loader, krate);
 
     let mut plugins = loader.plugins;
 
@@ -87,8 +87,8 @@ pub fn load_plugins(sess: &Session, krate: &ast::Crate,
 }
 
 // note that macros aren't expanded yet, and therefore macros can't add plugins.
-impl<'a> Visitor<()> for PluginLoader<'a> {
-    fn visit_view_item(&mut self, vi: &ast::ViewItem, _: ()) {
+impl<'a, 'v> Visitor<'v> for PluginLoader<'a> {
+    fn visit_view_item(&mut self, vi: &ast::ViewItem) {
         match vi.node {
             ast::ViewItemExternCrate(name, _, _) => {
                 let mut plugin_phase = false;
@@ -124,7 +124,7 @@ fn visit_view_item(&mut self, vi: &ast::ViewItem, _: ()) {
             _ => (),
         }
     }
-    fn visit_mac(&mut self, _: &ast::Mac, _:()) {
+    fn visit_mac(&mut self, _: &ast::Mac) {
         // bummer... can't see plugins inside macros.
         // do nothing.
     }
index 7fa3ee0ac63ed1cb5e82331dc36d2a463bba3030..2b2fc8c94d4acefb122f65dd686cfadf42abd3df 100644 (file)
@@ -13,7 +13,7 @@
 use lint::{LintPassObject, LintId, Lint};
 
 use syntax::ext::base::{SyntaxExtension, NamedSyntaxExtension, NormalTT};
-use syntax::ext::base::{IdentTT, LetSyntaxTT, ItemDecorator, ItemModifier, BasicMacroExpander};
+use syntax::ext::base::{IdentTT, LetSyntaxTT, ItemDecorator, ItemModifier};
 use syntax::ext::base::{MacroExpanderFn};
 use syntax::codemap::Span;
 use syntax::parse::token;
@@ -71,15 +71,10 @@ pub fn register_syntax_extension(&mut self, name: ast::Name, extension: SyntaxEx
     /// Register a macro of the usual kind.
     ///
     /// This is a convenience wrapper for `register_syntax_extension`.
-    /// It builds for you a `NormalTT` with a `BasicMacroExpander`,
+    /// It builds for you a `NormalTT` that calls `expander`,
     /// and also takes care of interning the macro's name.
     pub fn register_macro(&mut self, name: &str, expander: MacroExpanderFn) {
-        self.register_syntax_extension(
-            token::intern(name),
-            NormalTT(box BasicMacroExpander {
-                expander: expander,
-                span: None,
-            }, None));
+        self.register_syntax_extension(token::intern(name), NormalTT(box expander, None));
     }
 
     /// Register a compiler lint pass.
index 61ef9df99e86d364edab6734b553e2aac1cee1e7..b3ac44a3574d95079d66cab5c5d8610726ae2e64 100644 (file)
@@ -62,14 +62,14 @@ struct LoopQueryVisitor<'a> {
     flag: bool,
 }
 
-impl<'a> Visitor<()> for LoopQueryVisitor<'a> {
-    fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
+impl<'a, 'v> Visitor<'v> for LoopQueryVisitor<'a> {
+    fn visit_expr(&mut self, e: &ast::Expr) {
         self.flag |= (self.p)(&e.node);
         match e.node {
           // Skip inner loops, since a break in the inner loop isn't a
           // break inside the outer loop
           ast::ExprLoop(..) | ast::ExprWhile(..) | ast::ExprForLoop(..) => {}
-          _ => visit::walk_expr(self, e, ())
+          _ => visit::walk_expr(self, e)
         }
     }
 }
@@ -81,7 +81,7 @@ pub fn loop_query(b: &ast::Block, p: |&ast::Expr_| -> bool) -> bool {
         p: p,
         flag: false,
     };
-    visit::walk_block(&mut v, b, ());
+    visit::walk_block(&mut v, b);
     return v.flag;
 }
 
@@ -90,10 +90,10 @@ struct BlockQueryVisitor<'a> {
     flag: bool,
 }
 
-impl<'a> Visitor<()> for BlockQueryVisitor<'a> {
-    fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
+impl<'a, 'v> Visitor<'v> for BlockQueryVisitor<'a> {
+    fn visit_expr(&mut self, e: &ast::Expr) {
         self.flag |= (self.p)(e);
-        visit::walk_expr(self, e, ())
+        visit::walk_expr(self, e)
     }
 }
 
@@ -104,7 +104,7 @@ pub fn block_query(b: ast::P<ast::Block>, p: |&ast::Expr| -> bool) -> bool {
         p: p,
         flag: false,
     };
-    visit::walk_block(&mut v, &*b, ());
+    visit::walk_block(&mut v, &*b);
     return v.flag;
 }
 
index 5db6c72975587346501822b62cb04c847a37b942..e48f9df75648f75fab9f982c68825d5a8bb2c29d 100644 (file)
@@ -36,8 +36,6 @@
 #[phase(plugin, link)]
 extern crate log;
 extern crate syntax;
-extern crate libc;
-extern crate flate;
 extern crate serialize;
 
 pub mod abi;
index 8e24fc1ad5bff80de9df5e5a5443f0ddd24bf2b4..c3d9edecc6e2bb1045c890c79720133288283243 100644 (file)
@@ -86,7 +86,7 @@ pub fn calculate(metadata: &Vec<String>, krate: &ast::Crate) -> Svh {
 
         {
             let mut visit = svh_visitor::make(&mut state);
-            visit::walk_crate(&mut visit, krate, ());
+            visit::walk_crate(&mut visit, krate);
         }
 
         // FIXME (#14132): This hash is still sensitive to e.g. the
@@ -322,12 +322,9 @@ fn get_content(self) -> token::InternedString { token::get_name(self) }
     }
     fn content<K:InternKey>(k: K) -> token::InternedString { k.get_content() }
 
-    // local short-hand eases writing signatures of syntax::visit mod.
-    type E = ();
+    impl<'a, 'v> Visitor<'v> for StrictVersionHashVisitor<'a> {
 
-    impl<'a> Visitor<E> for StrictVersionHashVisitor<'a> {
-
-        fn visit_mac(&mut self, macro: &Mac, e: E) {
+        fn visit_mac(&mut self, macro: &Mac) {
             // macro invocations, namely macro_rules definitions,
             // *can* appear as items, even in the expanded crate AST.
 
@@ -350,7 +347,7 @@ fn visit_mac(&mut self, macro: &Mac, e: E) {
                       pprust::to_string(|pp_state| pp_state.print_mac(macro)));
             }
 
-            visit::walk_mac(self, macro, e);
+            visit::walk_mac(self, macro);
 
             fn macro_name(macro: &Mac) -> token::InternedString {
                 match &macro.node {
@@ -364,26 +361,26 @@ fn macro_name(macro: &Mac) -> token::InternedString {
         }
 
         fn visit_struct_def(&mut self, s: &StructDef, ident: Ident,
-                            g: &Generics, _: NodeId, e: E) {
+                            g: &Generics, _: NodeId) {
             SawStructDef(content(ident)).hash(self.st);
-            visit::walk_generics(self, g, e.clone());
-            visit::walk_struct_def(self, s, e)
+            visit::walk_generics(self, g);
+            visit::walk_struct_def(self, s)
         }
 
-        fn visit_variant(&mut self, v: &Variant, g: &Generics, e: E) {
+        fn visit_variant(&mut self, v: &Variant, g: &Generics) {
             SawVariant.hash(self.st);
             // walk_variant does not call walk_generics, so do it here.
-            visit::walk_generics(self, g, e.clone());
-            visit::walk_variant(self, v, g, e)
+            visit::walk_generics(self, g);
+            visit::walk_variant(self, v, g)
         }
 
-        fn visit_opt_lifetime_ref(&mut self, _: Span, l: &Option<Lifetime>, env: E) {
+        fn visit_opt_lifetime_ref(&mut self, _: Span, l: &Option<Lifetime>) {
             SawOptLifetimeRef.hash(self.st);
             // (This is a strange method in the visitor trait, in that
             // it does not expose a walk function to do the subroutine
             // calls.)
             match *l {
-                Some(ref l) => self.visit_lifetime_ref(l, env),
+                Some(ref l) => self.visit_lifetime_ref(l),
                 None => ()
             }
         }
@@ -402,15 +399,15 @@ fn visit_opt_lifetime_ref(&mut self, _: Span, l: &Option<Lifetime>, env: E) {
         // (If you edit a method such that it deviates from the
         // pattern, please move that method up above this comment.)
 
-        fn visit_ident(&mut self, _: Span, ident: Ident, _: E) {
+        fn visit_ident(&mut self, _: Span, ident: Ident) {
             SawIdent(content(ident)).hash(self.st);
         }
 
-        fn visit_lifetime_ref(&mut self, l: &Lifetime, _: E) {
+        fn visit_lifetime_ref(&mut self, l: &Lifetime) {
             SawLifetimeRef(content(l.name)).hash(self.st);
         }
 
-        fn visit_lifetime_decl(&mut self, l: &LifetimeDef, _: E) {
+        fn visit_lifetime_decl(&mut self, l: &LifetimeDef) {
             SawLifetimeDecl(content(l.lifetime.name)).hash(self.st);
         }
 
@@ -419,15 +416,15 @@ fn visit_lifetime_decl(&mut self, l: &LifetimeDef, _: E) {
         // monomorphization and cross-crate inlining generally implies
         // that a change to a crate body will require downstream
         // crates to be recompiled.
-        fn visit_expr(&mut self, ex: &Expr, e: E) {
-            SawExpr(saw_expr(&ex.node)).hash(self.st); visit::walk_expr(self, ex, e)
+        fn visit_expr(&mut self, ex: &Expr) {
+            SawExpr(saw_expr(&ex.node)).hash(self.st); visit::walk_expr(self, ex)
         }
 
-        fn visit_stmt(&mut self, s: &Stmt, e: E) {
-            SawStmt(saw_stmt(&s.node)).hash(self.st); visit::walk_stmt(self, s, e)
+        fn visit_stmt(&mut self, s: &Stmt) {
+            SawStmt(saw_stmt(&s.node)).hash(self.st); visit::walk_stmt(self, s)
         }
 
-        fn visit_view_item(&mut self, i: &ViewItem, e: E) {
+        fn visit_view_item(&mut self, i: &ViewItem) {
             // Two kinds of view items can affect the ABI for a crate:
             // exported `pub use` view items (since that may expose
             // items that downstream crates can call), and `use
@@ -437,79 +434,80 @@ fn visit_view_item(&mut self, i: &ViewItem, e: E) {
             // The simplest approach to handling both of the above is
             // just to adopt the same simple-minded (fine-grained)
             // hash that I am deploying elsewhere here.
-            SawViewItem.hash(self.st); visit::walk_view_item(self, i, e)
+            SawViewItem.hash(self.st); visit::walk_view_item(self, i)
         }
 
-        fn visit_foreign_item(&mut self, i: &ForeignItem, e: E) {
+        fn visit_foreign_item(&mut self, i: &ForeignItem) {
             // FIXME (#14132) ideally we would incorporate privacy (or
             // perhaps reachability) somewhere here, so foreign items
             // that do not leak into downstream crates would not be
             // part of the ABI.
-            SawForeignItem.hash(self.st); visit::walk_foreign_item(self, i, e)
+            SawForeignItem.hash(self.st); visit::walk_foreign_item(self, i)
         }
 
-        fn visit_item(&mut self, i: &Item, e: E) {
+        fn visit_item(&mut self, i: &Item) {
             // FIXME (#14132) ideally would incorporate reachability
             // analysis somewhere here, so items that never leak into
             // downstream crates (e.g. via monomorphisation or
             // inlining) would not be part of the ABI.
-            SawItem.hash(self.st); visit::walk_item(self, i, e)
+            SawItem.hash(self.st); visit::walk_item(self, i)
         }
 
-        fn visit_mod(&mut self, m: &Mod, _s: Span, _n: NodeId, e: E) {
-            SawMod.hash(self.st); visit::walk_mod(self, m, e)
+        fn visit_mod(&mut self, m: &Mod, _s: Span, _n: NodeId) {
+            SawMod.hash(self.st); visit::walk_mod(self, m)
         }
 
-        fn visit_decl(&mut self, d: &Decl, e: E) {
-            SawDecl.hash(self.st); visit::walk_decl(self, d, e)
+        fn visit_decl(&mut self, d: &Decl) {
+            SawDecl.hash(self.st); visit::walk_decl(self, d)
         }
 
-        fn visit_ty(&mut self, t: &Ty, e: E) {
-            SawTy.hash(self.st); visit::walk_ty(self, t, e)
+        fn visit_ty(&mut self, t: &Ty) {
+            SawTy.hash(self.st); visit::walk_ty(self, t)
         }
 
-        fn visit_generics(&mut self, g: &Generics, e: E) {
-            SawGenerics.hash(self.st); visit::walk_generics(self, g, e)
+        fn visit_generics(&mut self, g: &Generics) {
+            SawGenerics.hash(self.st); visit::walk_generics(self, g)
         }
 
-        fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl, b: &Block, s: Span, _: NodeId, e: E) {
-            SawFn.hash(self.st); visit::walk_fn(self, fk, fd, b, s, e)
+        fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
+                    b: &'v Block, s: Span, _: NodeId) {
+            SawFn.hash(self.st); visit::walk_fn(self, fk, fd, b, s)
         }
 
-        fn visit_ty_method(&mut self, t: &TypeMethod, e: E) {
-            SawTyMethod.hash(self.st); visit::walk_ty_method(self, t, e)
+        fn visit_ty_method(&mut self, t: &TypeMethod) {
+            SawTyMethod.hash(self.st); visit::walk_ty_method(self, t)
         }
 
-        fn visit_trait_item(&mut self, t: &TraitItem, e: E) {
-            SawTraitMethod.hash(self.st); visit::walk_trait_item(self, t, e)
+        fn visit_trait_item(&mut self, t: &TraitItem) {
+            SawTraitMethod.hash(self.st); visit::walk_trait_item(self, t)
         }
 
-        fn visit_struct_field(&mut self, s: &StructField, e: E) {
-            SawStructField.hash(self.st); visit::walk_struct_field(self, s, e)
+        fn visit_struct_field(&mut self, s: &StructField) {
+            SawStructField.hash(self.st); visit::walk_struct_field(self, s)
         }
 
-        fn visit_explicit_self(&mut self, es: &ExplicitSelf, e: E) {
-            SawExplicitSelf.hash(self.st); visit::walk_explicit_self(self, es, e)
+        fn visit_explicit_self(&mut self, es: &ExplicitSelf) {
+            SawExplicitSelf.hash(self.st); visit::walk_explicit_self(self, es)
         }
 
-        fn visit_path(&mut self, path: &Path, _: ast::NodeId, e: E) {
-            SawPath.hash(self.st); visit::walk_path(self, path, e)
+        fn visit_path(&mut self, path: &Path, _: ast::NodeId) {
+            SawPath.hash(self.st); visit::walk_path(self, path)
         }
 
-        fn visit_block(&mut self, b: &Block, e: E) {
-            SawBlock.hash(self.st); visit::walk_block(self, b, e)
+        fn visit_block(&mut self, b: &Block) {
+            SawBlock.hash(self.st); visit::walk_block(self, b)
         }
 
-        fn visit_pat(&mut self, p: &Pat, e: E) {
-            SawPat.hash(self.st); visit::walk_pat(self, p, e)
+        fn visit_pat(&mut self, p: &Pat) {
+            SawPat.hash(self.st); visit::walk_pat(self, p)
         }
 
-        fn visit_local(&mut self, l: &Local, e: E) {
-            SawLocal.hash(self.st); visit::walk_local(self, l, e)
+        fn visit_local(&mut self, l: &Local) {
+            SawLocal.hash(self.st); visit::walk_local(self, l)
         }
 
-        fn visit_arm(&mut self, a: &Arm, e: E) {
-            SawArm.hash(self.st); visit::walk_arm(self, a, e)
+        fn visit_arm(&mut self, a: &Arm) {
+            SawArm.hash(self.st); visit::walk_arm(self, a)
         }
     }
 }
index 8ef13ef2604241476872ac3748d668d399d07df7..ff733673bd26263220446459c2bd33c06e5ab60d 100644 (file)
@@ -366,17 +366,16 @@ fn visit_generics_helper(&self, generics: &Generics) {
     }
 }
 
-impl<'a, O: IdVisitingOperation> Visitor<()> for IdVisitor<'a, O> {
+impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
     fn visit_mod(&mut self,
                  module: &Mod,
                  _: Span,
-                 node_id: NodeId,
-                 env: ()) {
+                 node_id: NodeId) {
         self.operation.visit_id(node_id);
-        visit::walk_mod(self, module, env)
+        visit::walk_mod(self, module)
     }
 
-    fn visit_view_item(&mut self, view_item: &ViewItem, env: ()) {
+    fn visit_view_item(&mut self, view_item: &ViewItem) {
         if !self.pass_through_items {
             if self.visited_outermost {
                 return;
@@ -403,16 +402,16 @@ fn visit_view_item(&mut self, view_item: &ViewItem, env: ()) {
                 }
             }
         }
-        visit::walk_view_item(self, view_item, env);
+        visit::walk_view_item(self, view_item);
         self.visited_outermost = false;
     }
 
-    fn visit_foreign_item(&mut self, foreign_item: &ForeignItem, env: ()) {
+    fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
         self.operation.visit_id(foreign_item.id);
-        visit::walk_foreign_item(self, foreign_item, env)
+        visit::walk_foreign_item(self, foreign_item)
     }
 
-    fn visit_item(&mut self, item: &Item, env: ()) {
+    fn visit_item(&mut self, item: &Item) {
         if !self.pass_through_items {
             if self.visited_outermost {
                 return
@@ -431,59 +430,58 @@ fn visit_item(&mut self, item: &Item, env: ()) {
             _ => {}
         }
 
-        visit::walk_item(self, item, env);
+        visit::walk_item(self, item);
 
         self.visited_outermost = false
     }
 
-    fn visit_local(&mut self, local: &Local, env: ()) {
+    fn visit_local(&mut self, local: &Local) {
         self.operation.visit_id(local.id);
-        visit::walk_local(self, local, env)
+        visit::walk_local(self, local)
     }
 
-    fn visit_block(&mut self, block: &Block, env: ()) {
+    fn visit_block(&mut self, block: &Block) {
         self.operation.visit_id(block.id);
-        visit::walk_block(self, block, env)
+        visit::walk_block(self, block)
     }
 
-    fn visit_stmt(&mut self, statement: &Stmt, env: ()) {
+    fn visit_stmt(&mut self, statement: &Stmt) {
         self.operation.visit_id(ast_util::stmt_id(statement));
-        visit::walk_stmt(self, statement, env)
+        visit::walk_stmt(self, statement)
     }
 
-    fn visit_pat(&mut self, pattern: &Pat, env: ()) {
+    fn visit_pat(&mut self, pattern: &Pat) {
         self.operation.visit_id(pattern.id);
-        visit::walk_pat(self, pattern, env)
+        visit::walk_pat(self, pattern)
     }
 
-    fn visit_expr(&mut self, expression: &Expr, env: ()) {
+    fn visit_expr(&mut self, expression: &Expr) {
         self.operation.visit_id(expression.id);
-        visit::walk_expr(self, expression, env)
+        visit::walk_expr(self, expression)
     }
 
-    fn visit_ty(&mut self, typ: &Ty, env: ()) {
+    fn visit_ty(&mut self, typ: &Ty) {
         self.operation.visit_id(typ.id);
         match typ.node {
             TyPath(_, _, id) => self.operation.visit_id(id),
             _ => {}
         }
-        visit::walk_ty(self, typ, env)
+        visit::walk_ty(self, typ)
     }
 
-    fn visit_generics(&mut self, generics: &Generics, env: ()) {
+    fn visit_generics(&mut self, generics: &Generics) {
         self.visit_generics_helper(generics);
-        visit::walk_generics(self, generics, env)
+        visit::walk_generics(self, generics)
     }
 
     fn visit_fn(&mut self,
-                function_kind: &visit::FnKind,
-                function_declaration: &FnDecl,
-                block: &Block,
+                function_kind: visit::FnKind<'v>,
+                function_declaration: &'v FnDecl,
+                block: &'v Block,
                 span: Span,
-                node_id: NodeId,
-                env: ()) {
+                node_id: NodeId) {
         if !self.pass_through_items {
-            match *function_kind {
+            match function_kind {
                 visit::FkMethod(..) if self.visited_outermost => return,
                 visit::FkMethod(..) => self.visited_outermost = true,
                 _ => {}
@@ -492,7 +490,7 @@ fn visit_fn(&mut self,
 
         self.operation.visit_id(node_id);
 
-        match *function_kind {
+        match function_kind {
             visit::FkItemFn(_, generics, _, _) |
             visit::FkMethod(_, generics, _) => {
                 self.visit_generics_helper(generics)
@@ -508,39 +506,37 @@ fn visit_fn(&mut self,
                         function_kind,
                         function_declaration,
                         block,
-                        span,
-                        env);
+                        span);
 
         if !self.pass_through_items {
-            match *function_kind {
+            match function_kind {
                 visit::FkMethod(..) => self.visited_outermost = false,
                 _ => {}
             }
         }
     }
 
-    fn visit_struct_field(&mut self, struct_field: &StructField, env: ()) {
+    fn visit_struct_field(&mut self, struct_field: &StructField) {
         self.operation.visit_id(struct_field.node.id);
-        visit::walk_struct_field(self, struct_field, env)
+        visit::walk_struct_field(self, struct_field)
     }
 
     fn visit_struct_def(&mut self,
                         struct_def: &StructDef,
                         _: ast::Ident,
                         _: &ast::Generics,
-                        id: NodeId,
-                        _: ()) {
+                        id: NodeId) {
         self.operation.visit_id(id);
         struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
-        visit::walk_struct_def(self, struct_def, ());
+        visit::walk_struct_def(self, struct_def);
     }
 
-    fn visit_trait_item(&mut self, tm: &ast::TraitItem, _: ()) {
+    fn visit_trait_item(&mut self, tm: &ast::TraitItem) {
         match *tm {
             ast::RequiredMethod(ref m) => self.operation.visit_id(m.id),
             ast::ProvidedMethod(ref m) => self.operation.visit_id(m.id),
         }
-        visit::walk_trait_item(self, tm, ());
+        visit::walk_trait_item(self, tm);
     }
 }
 
@@ -552,7 +548,7 @@ pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
         visited_outermost: false,
     };
 
-    visit::walk_inlined_item(&mut id_visitor, item, ());
+    visit::walk_inlined_item(&mut id_visitor, item);
 }
 
 struct IdRangeComputingVisitor {
@@ -575,7 +571,7 @@ pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
     visitor.result.get()
 }
 
-pub fn compute_id_range_for_fn_body(fk: &visit::FnKind,
+pub fn compute_id_range_for_fn_body(fk: visit::FnKind,
                                     decl: &FnDecl,
                                     body: &Block,
                                     sp: Span,
@@ -595,7 +591,7 @@ pub fn compute_id_range_for_fn_body(fk: &visit::FnKind,
         pass_through_items: false,
         visited_outermost: false,
     };
-    id_visitor.visit_fn(fk, decl, body, sp, id, ());
+    id_visitor.visit_fn(fk, decl, body, sp, id);
     visitor.result.get()
 }
 
@@ -643,8 +639,8 @@ struct EachViewItemData<'a> {
     callback: |&ast::ViewItem|: 'a -> bool,
 }
 
-impl<'a> Visitor<()> for EachViewItemData<'a> {
-    fn visit_view_item(&mut self, view_item: &ast::ViewItem, _: ()) {
+impl<'a, 'v> Visitor<'v> for EachViewItemData<'a> {
+    fn visit_view_item(&mut self, view_item: &ast::ViewItem) {
         let _ = (self.callback)(view_item);
     }
 }
@@ -654,7 +650,7 @@ fn each_view_item(&self, f: |&ast::ViewItem| -> bool) -> bool {
         let mut visit = EachViewItemData {
             callback: f,
         };
-        visit::walk_crate(&mut visit, self, ());
+        visit::walk_crate(&mut visit, self);
         true
     }
 }
index c026a1c97c13936e27b9b94c038a72c01d9ae691..78d3d86b29692d5483fa587d96e3458d51b355f2 100644 (file)
@@ -8,8 +8,6 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-extern crate libc;
-
 use codemap::{Pos, Span};
 use codemap;
 use diagnostics;
index d59b20dfc4c68f4781914136229f7359269e2f69..4976e68cc64644976deb6de33fc686646c5dcab1 100644 (file)
@@ -39,15 +39,44 @@ pub struct MacroDef {
     pub ext: SyntaxExtension
 }
 
-pub type ItemDecorator =
-    fn(&mut ExtCtxt, Span, Gc<ast::MetaItem>, Gc<ast::Item>, |Gc<ast::Item>|);
+pub trait ItemDecorator {
+    fn expand(&self,
+              ecx: &mut ExtCtxt,
+              sp: Span,
+              meta_item: Gc<ast::MetaItem>,
+              item: Gc<ast::Item>,
+              push: |Gc<ast::Item>|);
+}
 
-pub type ItemModifier =
-    fn(&mut ExtCtxt, Span, Gc<ast::MetaItem>, Gc<ast::Item>) -> Gc<ast::Item>;
+impl ItemDecorator for fn(&mut ExtCtxt, Span, Gc<ast::MetaItem>, Gc<ast::Item>, |Gc<ast::Item>|) {
+    fn expand(&self,
+              ecx: &mut ExtCtxt,
+              sp: Span,
+              meta_item: Gc<ast::MetaItem>,
+              item: Gc<ast::Item>,
+              push: |Gc<ast::Item>|) {
+        (*self)(ecx, sp, meta_item, item, push)
+    }
+}
 
-pub struct BasicMacroExpander {
-    pub expander: MacroExpanderFn,
-    pub span: Option<Span>
+pub trait ItemModifier {
+    fn expand(&self,
+              ecx: &mut ExtCtxt,
+              span: Span,
+              meta_item: Gc<ast::MetaItem>,
+              item: Gc<ast::Item>)
+              -> Gc<ast::Item>;
+}
+
+impl ItemModifier for fn(&mut ExtCtxt, Span, Gc<ast::MetaItem>, Gc<ast::Item>) -> Gc<ast::Item> {
+    fn expand(&self,
+              ecx: &mut ExtCtxt,
+              span: Span,
+              meta_item: Gc<ast::MetaItem>,
+              item: Gc<ast::Item>)
+              -> Gc<ast::Item> {
+        (*self)(ecx, span, meta_item, item)
+    }
 }
 
 /// Represents a thing that maps token trees to Macro Results
@@ -60,24 +89,18 @@ fn expand<'cx>(&self,
 }
 
 pub type MacroExpanderFn =
-    fn<'cx>(ecx: &'cx mut ExtCtxt, span: codemap::Span, token_tree: &[ast::TokenTree])
-            -> Box<MacResult+'cx>;
+    fn<'cx>(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>;
 
-impl TTMacroExpander for BasicMacroExpander {
+impl TTMacroExpander for MacroExpanderFn {
     fn expand<'cx>(&self,
                    ecx: &'cx mut ExtCtxt,
                    span: Span,
                    token_tree: &[ast::TokenTree])
                    -> Box<MacResult+'cx> {
-        (self.expander)(ecx, span, token_tree)
+        (*self)(ecx, span, token_tree)
     }
 }
 
-pub struct BasicIdentMacroExpander {
-    pub expander: IdentMacroExpanderFn,
-    pub span: Option<Span>
-}
-
 pub trait IdentMacroExpander {
     fn expand<'cx>(&self,
                    cx: &'cx mut ExtCtxt,
@@ -87,20 +110,20 @@ fn expand<'cx>(&self,
                    -> Box<MacResult+'cx>;
 }
 
-impl IdentMacroExpander for BasicIdentMacroExpander {
+pub type IdentMacroExpanderFn =
+    fn<'cx>(&'cx mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult+'cx>;
+
+impl IdentMacroExpander for IdentMacroExpanderFn {
     fn expand<'cx>(&self,
                    cx: &'cx mut ExtCtxt,
                    sp: Span,
                    ident: ast::Ident,
                    token_tree: Vec<ast::TokenTree> )
                    -> Box<MacResult+'cx> {
-        (self.expander)(cx, sp, ident, token_tree)
+        (*self)(cx, sp, ident, token_tree)
     }
 }
 
-pub type IdentMacroExpanderFn =
-    fn<'cx>(&'cx mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult+'cx>;
-
 /// The result of a macro expansion. The return values of the various
 /// methods are spliced into the AST at the callsite of the macro (or
 /// just into the compiler's internal macro table, for `make_def`).
@@ -281,11 +304,11 @@ pub enum SyntaxExtension {
     /// based upon it.
     ///
     /// `#[deriving(...)]` is an `ItemDecorator`.
-    ItemDecorator(ItemDecorator),
+    ItemDecorator(Box<ItemDecorator + 'static>),
 
     /// A syntax extension that is attached to an item and modifies it
     /// in-place.
-    ItemModifier(ItemModifier),
+    ItemModifier(Box<ItemModifier + 'static>),
 
     /// A normal, function-like syntax extension.
     ///
@@ -329,20 +352,12 @@ pub fn new() -> BlockInfo {
 fn initial_syntax_expander_table() -> SyntaxEnv {
     // utility function to simplify creating NormalTT syntax extensions
     fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
-        NormalTT(box BasicMacroExpander {
-                expander: f,
-                span: None,
-            },
-            None)
+        NormalTT(box f, None)
     }
 
     let mut syntax_expanders = SyntaxEnv::new();
     syntax_expanders.insert(intern("macro_rules"),
-                            LetSyntaxTT(box BasicIdentMacroExpander {
-                                expander: ext::tt::macro_rules::add_new_extension,
-                                span: None,
-                            },
-                            None));
+                            LetSyntaxTT(box ext::tt::macro_rules::add_new_extension, None));
     syntax_expanders.insert(intern("fmt"),
                             builtin_normal_expander(
                                 ext::fmt::expand_syntax_ext));
@@ -371,7 +386,7 @@ fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
                             builtin_normal_expander(
                                     ext::log_syntax::expand_syntax_ext));
     syntax_expanders.insert(intern("deriving"),
-                            ItemDecorator(ext::deriving::expand_meta_deriving));
+                            ItemDecorator(box ext::deriving::expand_meta_deriving));
 
     // Quasi-quoting expanders
     syntax_expanders.insert(intern("quote_tokens"),
index d0f3cf6f9d7ad4a70c71bac1de7d5bdc8084a2d3..d15d6b3f8f127beb6821d946ad9ec1c5402038f2 100644 (file)
@@ -251,7 +251,7 @@ fn expand_item(it: Gc<ast::Item>, fld: &mut MacroExpander)
 
         match fld.cx.syntax_env.find(&intern(mname.get())) {
             Some(rc) => match *rc {
-                ItemDecorator(dec_fn) => {
+                ItemDecorator(ref dec) => {
                     attr::mark_used(attr);
 
                     fld.cx.bt_push(ExpnInfo {
@@ -266,8 +266,7 @@ fn expand_item(it: Gc<ast::Item>, fld: &mut MacroExpander)
                     // we'd ideally decorator_items.push_all(expand_item(item, fld)),
                     // but that double-mut-borrows fld
                     let mut items: SmallVector<Gc<ast::Item>> = SmallVector::zero();
-                    dec_fn(fld.cx, attr.span, attr.node.value, it,
-                        |item| items.push(item));
+                    dec.expand(fld.cx, attr.span, attr.node.value, it, |item| items.push(item));
                     decorator_items.extend(items.move_iter()
                         .flat_map(|item| expand_item(item, fld).move_iter()));
 
@@ -328,7 +327,7 @@ fn expand_item_modifiers(mut it: Gc<ast::Item>, fld: &mut MacroExpander)
 
         match fld.cx.syntax_env.find(&intern(mname.get())) {
             Some(rc) => match *rc {
-                ItemModifier(dec_fn) => {
+                ItemModifier(ref mac) => {
                     attr::mark_used(attr);
                     fld.cx.bt_push(ExpnInfo {
                         call_site: attr.span,
@@ -338,7 +337,7 @@ fn expand_item_modifiers(mut it: Gc<ast::Item>, fld: &mut MacroExpander)
                             span: None,
                         }
                     });
-                    it = dec_fn(fld.cx, attr.span, attr.node.value, it);
+                    it = mac.expand(fld.cx, attr.span, attr.node.value, it);
                     fld.cx.bt_pop();
                 }
                 _ => unreachable!()
@@ -648,29 +647,29 @@ fn expand_arm(arm: &ast::Arm, fld: &mut MacroExpander) -> ast::Arm {
 /// array
 #[deriving(Clone)]
 struct PatIdentFinder {
-    ident_accumulator: Vec<ast::Ident> ,
+    ident_accumulator: Vec<ast::Ident>
 }
 
-impl Visitor<()> for PatIdentFinder {
-    fn visit_pat(&mut self, pattern: &ast::Pat, _: ()) {
+impl<'v> Visitor<'v> for PatIdentFinder {
+    fn visit_pat(&mut self, pattern: &ast::Pat) {
         match *pattern {
             ast::Pat { id: _, node: ast::PatIdent(_, ref path1, ref inner), span: _ } => {
                 self.ident_accumulator.push(path1.node);
                 // visit optional subpattern of PatIdent:
                 for subpat in inner.iter() {
-                    self.visit_pat(&**subpat, ())
+                    self.visit_pat(&**subpat)
                 }
             }
             // use the default traversal for non-PatIdents
-            _ => visit::walk_pat(self, pattern, ())
+            _ => visit::walk_pat(self, pattern)
         }
     }
 }
 
 /// find the PatIdent paths in a pattern
-fn pattern_bindings(pat : &ast::Pat) -> Vec<ast::Ident> {
+fn pattern_bindings(pat: &ast::Pat) -> Vec<ast::Ident> {
     let mut name_finder = PatIdentFinder{ident_accumulator:Vec::new()};
-    name_finder.visit_pat(pat,());
+    name_finder.visit_pat(pat);
     name_finder.ident_accumulator
 }
 
@@ -678,7 +677,7 @@ fn pattern_bindings(pat : &ast::Pat) -> Vec<ast::Ident> {
 fn fn_decl_arg_bindings(fn_decl: &ast::FnDecl) -> Vec<ast::Ident> {
     let mut pat_idents = PatIdentFinder{ident_accumulator:Vec::new()};
     for arg in fn_decl.inputs.iter() {
-        pat_idents.visit_pat(&*arg.pat, ());
+        pat_idents.visit_pat(&*arg.pat);
     }
     pat_idents.ident_accumulator
 }
@@ -1099,7 +1098,7 @@ fn original_span(cx: &ExtCtxt) -> Gc<codemap::ExpnInfo> {
 
 /// Check that there are no macro invocations left in the AST:
 pub fn check_for_macros(sess: &parse::ParseSess, krate: &ast::Crate) {
-    visit::walk_crate(&mut MacroExterminator{sess:sess}, krate, ());
+    visit::walk_crate(&mut MacroExterminator{sess:sess}, krate);
 }
 
 /// A visitor that ensures that no macro invocations remain in an AST.
@@ -1107,8 +1106,8 @@ struct MacroExterminator<'a>{
     sess: &'a parse::ParseSess
 }
 
-impl<'a> visit::Visitor<()> for MacroExterminator<'a> {
-    fn visit_mac(&mut self, macro: &ast::Mac, _:()) {
+impl<'a, 'v> Visitor<'v> for MacroExterminator<'a> {
+    fn visit_mac(&mut self, macro: &ast::Mac) {
         self.sess.span_diagnostic.span_bug(macro.span,
                                            "macro exterminator: expected AST \
                                            with no macro invocations");
@@ -1144,15 +1143,14 @@ struct PathExprFinderContext {
         path_accumulator: Vec<ast::Path> ,
     }
 
-    impl Visitor<()> for PathExprFinderContext {
-
-        fn visit_expr(&mut self, expr: &ast::Expr, _: ()) {
-            match *expr {
-                ast::Expr{id:_,span:_,node:ast::ExprPath(ref p)} => {
+    impl<'v> Visitor<'v> for PathExprFinderContext {
+        fn visit_expr(&mut self, expr: &ast::Expr) {
+            match expr.node {
+                ast::ExprPath(ref p) => {
                     self.path_accumulator.push(p.clone());
                     // not calling visit_path, but it should be fine.
                 }
-                _ => visit::walk_expr(self,expr,())
+                _ => visit::walk_expr(self, expr)
             }
         }
     }
@@ -1160,18 +1158,18 @@ fn visit_expr(&mut self, expr: &ast::Expr, _: ()) {
     // find the variable references in a crate
     fn crate_varrefs(the_crate : &ast::Crate) -> Vec<ast::Path> {
         let mut path_finder = PathExprFinderContext{path_accumulator:Vec::new()};
-        visit::walk_crate(&mut path_finder, the_crate, ());
+        visit::walk_crate(&mut path_finder, the_crate);
         path_finder.path_accumulator
     }
 
     /// A Visitor that extracts the identifiers from a thingy.
     // as a side note, I'm starting to want to abstract over these....
-    struct IdentFinder{
+    struct IdentFinder {
         ident_accumulator: Vec<ast::Ident>
     }
 
-    impl Visitor<()> for IdentFinder {
-        fn visit_ident(&mut self, _: codemap::Span, id: ast::Ident, _: ()){
+    impl<'v> Visitor<'v> for IdentFinder {
+        fn visit_ident(&mut self, _: codemap::Span, id: ast::Ident){
             self.ident_accumulator.push(id);
         }
     }
@@ -1179,7 +1177,7 @@ fn visit_ident(&mut self, _: codemap::Span, id: ast::Ident, _: ()){
     /// Find the idents in a crate
     fn crate_idents(the_crate: &ast::Crate) -> Vec<ast::Ident> {
         let mut ident_finder = IdentFinder{ident_accumulator: Vec::new()};
-        visit::walk_crate(&mut ident_finder, the_crate, ());
+        visit::walk_crate(&mut ident_finder, the_crate);
         ident_finder.ident_accumulator
     }
 
@@ -1277,7 +1275,7 @@ fn expand_crate_str(crate_str: String) -> ast::Crate {
     // find the pat_ident paths in a crate
     fn crate_bindings(the_crate : &ast::Crate) -> Vec<ast::Ident> {
         let mut name_finder = PatIdentFinder{ident_accumulator:Vec::new()};
-        visit::walk_crate(&mut name_finder, the_crate, ());
+        visit::walk_crate(&mut name_finder, the_crate);
         name_finder.ident_accumulator
     }
 
index 50b42ea2c0fd90fcd8df36e514ca24318f8b96fe..2a989e6d63a2349a3ef51bef68346d999806181d 100644 (file)
@@ -8,11 +8,10 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-//! Context-passing AST walker. Each overridden visit method has full control
-//! over what happens with its node, it can do its own traversal of the node's
-//! children (potentially passing in different contexts to each), call
-//! `visit::visit_*` to apply the default traversal algorithm (again, it can
-//! override the context), or prevent deeper traversal by doing nothing.
+//! AST walker. Each overridden visit method has full control over what
+//! happens with its node, it can do its own traversal of the node's children,
+//! call `visit::walk_*` to apply the default traversal algorithm, or prevent
+//! deeper traversal by doing nothing.
 //!
 //! Note: it is an important invariant that the default visitor walks the body
 //! of a function in "execution order" (more concretely, reverse post-order
@@ -27,9 +26,7 @@
 use abi::Abi;
 use ast::*;
 use ast;
-use ast_util;
 use codemap::Span;
-use parse;
 use owned_slice::OwnedSlice;
 
 use std::gc::Gc;
@@ -46,23 +43,6 @@ pub enum FnKind<'a> {
     FkFnBlock,
 }
 
-pub fn name_of_fn(fk: &FnKind) -> Ident {
-    match *fk {
-        FkItemFn(name, _, _, _) | FkMethod(name, _, _) => name,
-        FkFnBlock(..) => parse::token::special_idents::invalid
-    }
-}
-
-pub fn generics_of_fn(fk: &FnKind) -> Generics {
-    match *fk {
-        FkItemFn(_, generics, _, _) |
-        FkMethod(_, generics, _) => {
-            (*generics).clone()
-        }
-        FkFnBlock(..) => ast_util::empty_generics(),
-    }
-}
-
 /// Each method of the Visitor trait is a hook to be potentially
 /// overridden.  Each method's default implementation recursively visits
 /// the substructure of the input via the corresponding `walk` method;
@@ -72,85 +52,82 @@ pub fn generics_of_fn(fk: &FnKind) -> Generics {
 /// explicitly, you need to override each method.  (And you also need
 /// to monitor future changes to `Visitor` in case a new method with a
 /// new default implementation gets introduced.)
-pub trait Visitor<E: Clone> {
+pub trait Visitor<'v> {
 
-    fn visit_ident(&mut self, _sp: Span, _ident: Ident, _e: E) {
+    fn visit_ident(&mut self, _sp: Span, _ident: Ident) {
         /*! Visit the idents */
     }
-    fn visit_mod(&mut self, m: &Mod, _s: Span, _n: NodeId, e: E) { walk_mod(self, m, e) }
-    fn visit_view_item(&mut self, i: &ViewItem, e: E) { walk_view_item(self, i, e) }
-    fn visit_foreign_item(&mut self, i: &ForeignItem, e: E) { walk_foreign_item(self, i, e) }
-    fn visit_item(&mut self, i: &Item, e: E) { walk_item(self, i, e) }
-    fn visit_local(&mut self, l: &Local, e: E) { walk_local(self, l, e) }
-    fn visit_block(&mut self, b: &Block, e: E) { walk_block(self, b, e) }
-    fn visit_stmt(&mut self, s: &Stmt, e: E) { walk_stmt(self, s, e) }
-    fn visit_arm(&mut self, a: &Arm, e: E) { walk_arm(self, a, e) }
-    fn visit_pat(&mut self, p: &Pat, e: E) { walk_pat(self, p, e) }
-    fn visit_decl(&mut self, d: &Decl, e: E) { walk_decl(self, d, e) }
-    fn visit_expr(&mut self, ex: &Expr, e: E) { walk_expr(self, ex, e) }
-    fn visit_expr_post(&mut self, _ex: &Expr, _e: E) { }
-    fn visit_ty(&mut self, t: &Ty, e: E) { walk_ty(self, t, e) }
-    fn visit_generics(&mut self, g: &Generics, e: E) { walk_generics(self, g, e) }
-    fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl, b: &Block, s: Span, _: NodeId, e: E) {
-        walk_fn(self, fk, fd, b, s, e)
-    }
-    fn visit_ty_method(&mut self, t: &TypeMethod, e: E) { walk_ty_method(self, t, e) }
-    fn visit_trait_item(&mut self, t: &TraitItem, e: E) { walk_trait_item(self, t, e) }
-    fn visit_struct_def(&mut self, s: &StructDef, _: Ident, _: &Generics, _: NodeId, e: E) {
-        walk_struct_def(self, s, e)
-    }
-    fn visit_struct_field(&mut self, s: &StructField, e: E) { walk_struct_field(self, s, e) }
-    fn visit_variant(&mut self, v: &Variant, g: &Generics, e: E) { walk_variant(self, v, g, e) }
+    fn visit_mod(&mut self, m: &'v Mod, _s: Span, _n: NodeId) { walk_mod(self, m) }
+    fn visit_view_item(&mut self, i: &'v ViewItem) { walk_view_item(self, i) }
+    fn visit_foreign_item(&mut self, i: &'v ForeignItem) { walk_foreign_item(self, i) }
+    fn visit_item(&mut self, i: &'v Item) { walk_item(self, i) }
+    fn visit_local(&mut self, l: &'v Local) { walk_local(self, l) }
+    fn visit_block(&mut self, b: &'v Block) { walk_block(self, b) }
+    fn visit_stmt(&mut self, s: &'v Stmt) { walk_stmt(self, s) }
+    fn visit_arm(&mut self, a: &'v Arm) { walk_arm(self, a) }
+    fn visit_pat(&mut self, p: &'v Pat) { walk_pat(self, p) }
+    fn visit_decl(&mut self, d: &'v Decl) { walk_decl(self, d) }
+    fn visit_expr(&mut self, ex: &'v Expr) { walk_expr(self, ex) }
+    fn visit_expr_post(&mut self, _ex: &'v Expr) { }
+    fn visit_ty(&mut self, t: &'v Ty) { walk_ty(self, t) }
+    fn visit_generics(&mut self, g: &'v Generics) { walk_generics(self, g) }
+    fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl, b: &'v Block, s: Span, _: NodeId) {
+        walk_fn(self, fk, fd, b, s)
+    }
+    fn visit_ty_method(&mut self, t: &'v TypeMethod) { walk_ty_method(self, t) }
+    fn visit_trait_item(&mut self, t: &'v TraitItem) { walk_trait_item(self, t) }
+    fn visit_struct_def(&mut self, s: &'v StructDef, _: Ident, _: &'v Generics, _: NodeId) {
+        walk_struct_def(self, s)
+    }
+    fn visit_struct_field(&mut self, s: &'v StructField) { walk_struct_field(self, s) }
+    fn visit_variant(&mut self, v: &'v Variant, g: &'v Generics) { walk_variant(self, v, g) }
     fn visit_opt_lifetime_ref(&mut self,
                               _span: Span,
-                              opt_lifetime: &Option<Lifetime>,
-                              env: E) {
+                              opt_lifetime: &'v Option<Lifetime>) {
         /*!
          * Visits an optional reference to a lifetime. The `span` is
          * the span of some surrounding reference should opt_lifetime
          * be None.
          */
         match *opt_lifetime {
-            Some(ref l) => self.visit_lifetime_ref(l, env),
+            Some(ref l) => self.visit_lifetime_ref(l),
             None => ()
         }
     }
-    fn visit_lifetime_ref(&mut self, _lifetime: &Lifetime, _e: E) {
+    fn visit_lifetime_ref(&mut self, _lifetime: &'v Lifetime) {
         /*! Visits a reference to a lifetime */
     }
-    fn visit_lifetime_decl(&mut self, _lifetime: &LifetimeDef, _e: E) {
+    fn visit_lifetime_decl(&mut self, _lifetime: &'v LifetimeDef) {
         /*! Visits a declaration of a lifetime */
     }
-    fn visit_explicit_self(&mut self, es: &ExplicitSelf, e: E) {
-        walk_explicit_self(self, es, e)
+    fn visit_explicit_self(&mut self, es: &'v ExplicitSelf) {
+        walk_explicit_self(self, es)
     }
-    fn visit_mac(&mut self, _macro: &Mac, _e: E) {
+    fn visit_mac(&mut self, _macro: &'v Mac) {
         fail!("visit_mac disabled by default");
         // NB: see note about macros above.
         // if you really want a visitor that
         // works on macros, use this
         // definition in your trait impl:
-        // visit::walk_mac(self, _macro, _e)
+        // visit::walk_mac(self, _macro)
     }
-    fn visit_path(&mut self, path: &Path, _id: ast::NodeId, e: E) {
-        walk_path(self, path, e)
+    fn visit_path(&mut self, path: &'v Path, _id: ast::NodeId) {
+        walk_path(self, path)
     }
-    fn visit_attribute(&mut self, _attr: &Attribute, _e: E) {}
+    fn visit_attribute(&mut self, _attr: &'v Attribute) {}
 }
 
-pub fn walk_inlined_item<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                                  item: &ast::InlinedItem,
-                                                  env: E) {
+pub fn walk_inlined_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v InlinedItem) {
     match *item {
-        IIItem(i) => visitor.visit_item(&*i, env),
-        IIForeign(i) => visitor.visit_foreign_item(&*i, env),
-        IITraitItem(_, iti) => {
-            match iti {
-                ProvidedInlinedTraitItem(m) => {
-                    walk_method_helper(visitor, &*m, env)
+        IIItem(ref i) => visitor.visit_item(&**i),
+        IIForeign(ref i) => visitor.visit_foreign_item(&**i),
+        IITraitItem(_, ref iti) => {
+            match *iti {
+                ProvidedInlinedTraitItem(ref m) => {
+                    walk_method_helper(visitor, &**m)
                 }
-                RequiredInlinedTraitItem(m) => {
-                    walk_method_helper(visitor, &*m, env)
+                RequiredInlinedTraitItem(ref m) => {
+                    walk_method_helper(visitor, &**m)
                 }
             }
         }
@@ -158,719 +135,681 @@ pub fn walk_inlined_item<E: Clone, V: Visitor<E>>(visitor: &mut V,
 }
 
 
-pub fn walk_crate<E: Clone, V: Visitor<E>>(visitor: &mut V, krate: &Crate, env: E) {
-    visitor.visit_mod(&krate.module, krate.span, CRATE_NODE_ID, env.clone());
+pub fn walk_crate<'v, V: Visitor<'v>>(visitor: &mut V, krate: &'v Crate) {
+    visitor.visit_mod(&krate.module, krate.span, CRATE_NODE_ID);
     for attr in krate.attrs.iter() {
-        visitor.visit_attribute(attr, env.clone());
+        visitor.visit_attribute(attr);
     }
 }
 
-pub fn walk_mod<E: Clone, V: Visitor<E>>(visitor: &mut V, module: &Mod, env: E) {
+pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod) {
     for view_item in module.view_items.iter() {
-        visitor.visit_view_item(view_item, env.clone())
+        visitor.visit_view_item(view_item)
     }
 
     for item in module.items.iter() {
-        visitor.visit_item(&**item, env.clone())
+        visitor.visit_item(&**item)
     }
 }
 
-pub fn walk_view_item<E: Clone, V: Visitor<E>>(visitor: &mut V, vi: &ViewItem, env: E) {
+pub fn walk_view_item<'v, V: Visitor<'v>>(visitor: &mut V, vi: &'v ViewItem) {
     match vi.node {
         ViewItemExternCrate(name, _, _) => {
-            visitor.visit_ident(vi.span, name, env.clone())
+            visitor.visit_ident(vi.span, name)
         }
         ViewItemUse(ref vp) => {
             match vp.node {
                 ViewPathSimple(ident, ref path, id) => {
-                    visitor.visit_ident(vp.span, ident, env.clone());
-                    visitor.visit_path(path, id, env.clone());
+                    visitor.visit_ident(vp.span, ident);
+                    visitor.visit_path(path, id);
                 }
                 ViewPathGlob(ref path, id) => {
-                    visitor.visit_path(path, id, env.clone());
+                    visitor.visit_path(path, id);
                 }
                 ViewPathList(ref path, ref list, _) => {
                     for id in list.iter() {
                         match id.node {
                             PathListIdent { name, .. } => {
-                                visitor.visit_ident(id.span, name, env.clone());
+                                visitor.visit_ident(id.span, name);
                             }
                             PathListMod { .. } => ()
                         }
                     }
-                    walk_path(visitor, path, env.clone());
+                    walk_path(visitor, path);
                 }
             }
         }
     }
     for attr in vi.attrs.iter() {
-        visitor.visit_attribute(attr, env.clone());
+        visitor.visit_attribute(attr);
     }
 }
 
-pub fn walk_local<E: Clone, V: Visitor<E>>(visitor: &mut V, local: &Local, env: E) {
-    visitor.visit_pat(&*local.pat, env.clone());
-    visitor.visit_ty(&*local.ty, env.clone());
-    match local.init {
-        None => {}
-        Some(initializer) => visitor.visit_expr(&*initializer, env),
-    }
+pub fn walk_local<'v, V: Visitor<'v>>(visitor: &mut V, local: &'v Local) {
+    visitor.visit_pat(&*local.pat);
+    visitor.visit_ty(&*local.ty);
+    walk_expr_opt(visitor, &local.init);
 }
 
-pub fn walk_explicit_self<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                                   explicit_self: &ExplicitSelf,
-                                                   env: E) {
+pub fn walk_explicit_self<'v, V: Visitor<'v>>(visitor: &mut V,
+                                              explicit_self: &'v ExplicitSelf) {
     match explicit_self.node {
         SelfStatic | SelfValue(_) => {},
         SelfRegion(ref lifetime, _, _) => {
-            visitor.visit_opt_lifetime_ref(explicit_self.span, lifetime, env)
+            visitor.visit_opt_lifetime_ref(explicit_self.span, lifetime)
         }
-        SelfExplicit(ref typ, _) => visitor.visit_ty(&**typ, env.clone()),
+        SelfExplicit(ref typ, _) => visitor.visit_ty(&**typ),
     }
 }
 
 /// Like with walk_method_helper this doesn't correspond to a method
 /// in Visitor, and so it gets a _helper suffix.
-pub fn walk_trait_ref_helper<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                                      trait_ref: &TraitRef,
-                                                      env: E) {
-    visitor.visit_path(&trait_ref.path, trait_ref.ref_id, env)
+pub fn walk_trait_ref_helper<'v, V: Visitor<'v>>(visitor: &mut V, trait_ref: &'v TraitRef) {
+    visitor.visit_path(&trait_ref.path, trait_ref.ref_id)
 }
 
-pub fn walk_item<E: Clone, V: Visitor<E>>(visitor: &mut V, item: &Item, env: E) {
-    visitor.visit_ident(item.span, item.ident, env.clone());
+pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) {
+    visitor.visit_ident(item.span, item.ident);
     match item.node {
         ItemStatic(ref typ, _, ref expr) => {
-            visitor.visit_ty(&**typ, env.clone());
-            visitor.visit_expr(&**expr, env.clone());
+            visitor.visit_ty(&**typ);
+            visitor.visit_expr(&**expr);
         }
-        ItemFn(declaration, fn_style, abi, ref generics, body) => {
-            visitor.visit_fn(&FkItemFn(item.ident, generics, fn_style, abi),
-                             &*declaration,
-                             &*body,
+        ItemFn(ref declaration, fn_style, abi, ref generics, ref body) => {
+            visitor.visit_fn(FkItemFn(item.ident, generics, fn_style, abi),
+                             &**declaration,
+                             &**body,
                              item.span,
-                             item.id,
-                             env.clone())
+                             item.id)
         }
         ItemMod(ref module) => {
-            visitor.visit_mod(module, item.span, item.id, env.clone())
+            visitor.visit_mod(module, item.span, item.id)
         }
         ItemForeignMod(ref foreign_module) => {
             for view_item in foreign_module.view_items.iter() {
-                visitor.visit_view_item(view_item, env.clone())
+                visitor.visit_view_item(view_item)
             }
             for foreign_item in foreign_module.items.iter() {
-                visitor.visit_foreign_item(&**foreign_item, env.clone())
+                visitor.visit_foreign_item(&**foreign_item)
             }
         }
         ItemTy(ref typ, ref type_parameters) => {
-            visitor.visit_ty(&**typ, env.clone());
-            visitor.visit_generics(type_parameters, env.clone())
+            visitor.visit_ty(&**typ);
+            visitor.visit_generics(type_parameters)
         }
         ItemEnum(ref enum_definition, ref type_parameters) => {
-            visitor.visit_generics(type_parameters, env.clone());
-            walk_enum_def(visitor, enum_definition, type_parameters, env.clone())
+            visitor.visit_generics(type_parameters);
+            walk_enum_def(visitor, enum_definition, type_parameters)
         }
         ItemImpl(ref type_parameters,
                  ref trait_reference,
-                 typ,
+                 ref typ,
                  ref impl_items) => {
-            visitor.visit_generics(type_parameters, env.clone());
+            visitor.visit_generics(type_parameters);
             match *trait_reference {
                 Some(ref trait_reference) => walk_trait_ref_helper(visitor,
-                                                                   trait_reference, env.clone()),
+                                                                   trait_reference),
                 None => ()
             }
-            visitor.visit_ty(&*typ, env.clone());
+            visitor.visit_ty(&**typ);
             for impl_item in impl_items.iter() {
                 match *impl_item {
-                    MethodImplItem(method) => {
-                        walk_method_helper(visitor, &*method, env.clone())
+                    MethodImplItem(ref method) => {
+                        walk_method_helper(visitor, &**method)
                     }
                 }
             }
         }
         ItemStruct(ref struct_definition, ref generics) => {
-            visitor.visit_generics(generics, env.clone());
+            visitor.visit_generics(generics);
             visitor.visit_struct_def(&**struct_definition,
                                      item.ident,
                                      generics,
-                                     item.id,
-                                     env.clone())
+                                     item.id)
         }
         ItemTrait(ref generics, _, ref bounds, ref methods) => {
-            visitor.visit_generics(generics, env.clone());
-            walk_ty_param_bounds(visitor, bounds, env.clone());
+            visitor.visit_generics(generics);
+            walk_ty_param_bounds(visitor, bounds);
             for method in methods.iter() {
-                visitor.visit_trait_item(method, env.clone())
+                visitor.visit_trait_item(method)
             }
         }
-        ItemMac(ref macro) => visitor.visit_mac(macro, env.clone()),
+        ItemMac(ref macro) => visitor.visit_mac(macro),
     }
     for attr in item.attrs.iter() {
-        visitor.visit_attribute(attr, env.clone());
+        visitor.visit_attribute(attr);
     }
 }
 
-pub fn walk_enum_def<E: Clone, V:Visitor<E>>(visitor: &mut V,
-                                             enum_definition: &EnumDef,
-                                             generics: &Generics,
-                                             env: E) {
-    for &variant in enum_definition.variants.iter() {
-        visitor.visit_variant(&*variant, generics, env.clone());
+pub fn walk_enum_def<'v, V: Visitor<'v>>(visitor: &mut V,
+                                         enum_definition: &'v EnumDef,
+                                         generics: &'v Generics) {
+    for variant in enum_definition.variants.iter() {
+        visitor.visit_variant(&**variant, generics);
     }
 }
 
-pub fn walk_variant<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                             variant: &Variant,
-                                             generics: &Generics,
-                                             env: E) {
-    visitor.visit_ident(variant.span, variant.node.name, env.clone());
+pub fn walk_variant<'v, V: Visitor<'v>>(visitor: &mut V,
+                                        variant: &'v Variant,
+                                        generics: &'v Generics) {
+    visitor.visit_ident(variant.span, variant.node.name);
 
     match variant.node.kind {
         TupleVariantKind(ref variant_arguments) => {
             for variant_argument in variant_arguments.iter() {
-                visitor.visit_ty(&*variant_argument.ty, env.clone())
+                visitor.visit_ty(&*variant_argument.ty)
             }
         }
         StructVariantKind(ref struct_definition) => {
             visitor.visit_struct_def(&**struct_definition,
                                      variant.node.name,
                                      generics,
-                                     variant.node.id,
-                                     env.clone())
+                                     variant.node.id)
         }
     }
     match variant.node.disr_expr {
-        Some(ref expr) => visitor.visit_expr(&**expr, env.clone()),
+        Some(ref expr) => visitor.visit_expr(&**expr),
         None => ()
     }
     for attr in variant.node.attrs.iter() {
-        visitor.visit_attribute(attr, env.clone());
+        visitor.visit_attribute(attr);
     }
 }
 
-pub fn skip_ty<E, V: Visitor<E>>(_: &mut V, _: &Ty, _: E) {
+pub fn skip_ty<'v, V: Visitor<'v>>(_: &mut V, _: &'v Ty) {
     // Empty!
 }
 
-pub fn walk_ty<E: Clone, V: Visitor<E>>(visitor: &mut V, typ: &Ty, env: E) {
+pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty) {
     match typ.node {
-        TyUniq(ty) | TyVec(ty) | TyBox(ty) | TyParen(ty) => {
-            visitor.visit_ty(&*ty, env)
+        TyUniq(ref ty) | TyVec(ref ty) | TyBox(ref ty) | TyParen(ref ty) => {
+            visitor.visit_ty(&**ty)
         }
         TyPtr(ref mutable_type) => {
-            visitor.visit_ty(&*mutable_type.ty, env)
+            visitor.visit_ty(&*mutable_type.ty)
         }
         TyRptr(ref lifetime, ref mutable_type) => {
-            visitor.visit_opt_lifetime_ref(typ.span, lifetime, env.clone());
-            visitor.visit_ty(&*mutable_type.ty, env)
+            visitor.visit_opt_lifetime_ref(typ.span, lifetime);
+            visitor.visit_ty(&*mutable_type.ty)
         }
         TyTup(ref tuple_element_types) => {
-            for &tuple_element_type in tuple_element_types.iter() {
-                visitor.visit_ty(&*tuple_element_type, env.clone())
+            for tuple_element_type in tuple_element_types.iter() {
+                visitor.visit_ty(&**tuple_element_type)
             }
         }
         TyClosure(ref function_declaration) => {
             for argument in function_declaration.decl.inputs.iter() {
-                visitor.visit_ty(&*argument.ty, env.clone())
+                visitor.visit_ty(&*argument.ty)
             }
-            visitor.visit_ty(&*function_declaration.decl.output, env.clone());
-            walk_ty_param_bounds(visitor, &function_declaration.bounds,
-                                 env.clone());
-            walk_lifetime_decls(visitor, &function_declaration.lifetimes,
-                                env.clone());
+            visitor.visit_ty(&*function_declaration.decl.output);
+            walk_ty_param_bounds(visitor, &function_declaration.bounds);
+            walk_lifetime_decls(visitor, &function_declaration.lifetimes);
         }
         TyProc(ref function_declaration) => {
             for argument in function_declaration.decl.inputs.iter() {
-                visitor.visit_ty(&*argument.ty, env.clone())
+                visitor.visit_ty(&*argument.ty)
             }
-            visitor.visit_ty(&*function_declaration.decl.output, env.clone());
-            walk_ty_param_bounds(visitor, &function_declaration.bounds,
-                                 env.clone());
-            walk_lifetime_decls(visitor, &function_declaration.lifetimes,
-                                env.clone());
+            visitor.visit_ty(&*function_declaration.decl.output);
+            walk_ty_param_bounds(visitor, &function_declaration.bounds);
+            walk_lifetime_decls(visitor, &function_declaration.lifetimes);
         }
         TyBareFn(ref function_declaration) => {
             for argument in function_declaration.decl.inputs.iter() {
-                visitor.visit_ty(&*argument.ty, env.clone())
+                visitor.visit_ty(&*argument.ty)
             }
-            visitor.visit_ty(&*function_declaration.decl.output, env.clone());
-            walk_lifetime_decls(visitor, &function_declaration.lifetimes,
-                                env.clone());
+            visitor.visit_ty(&*function_declaration.decl.output);
+            walk_lifetime_decls(visitor, &function_declaration.lifetimes);
         }
         TyUnboxedFn(ref function_declaration) => {
             for argument in function_declaration.decl.inputs.iter() {
-                visitor.visit_ty(&*argument.ty, env.clone())
+                visitor.visit_ty(&*argument.ty)
             }
-            visitor.visit_ty(&*function_declaration.decl.output, env.clone());
+            visitor.visit_ty(&*function_declaration.decl.output);
         }
         TyPath(ref path, ref opt_bounds, id) => {
-            visitor.visit_path(path, id, env.clone());
+            visitor.visit_path(path, id);
             match *opt_bounds {
                 Some(ref bounds) => {
-                    walk_ty_param_bounds(visitor, bounds, env.clone());
+                    walk_ty_param_bounds(visitor, bounds);
                 }
                 None => { }
             }
         }
         TyFixedLengthVec(ref ty, ref expression) => {
-            visitor.visit_ty(&**ty, env.clone());
-            visitor.visit_expr(&**expression, env)
+            visitor.visit_ty(&**ty);
+            visitor.visit_expr(&**expression)
         }
         TyTypeof(ref expression) => {
-            visitor.visit_expr(&**expression, env)
+            visitor.visit_expr(&**expression)
         }
         TyNil | TyBot | TyInfer => {}
     }
 }
 
-fn walk_lifetime_decls<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                                lifetimes: &Vec<LifetimeDef>,
-                                                env: E) {
+fn walk_lifetime_decls<'v, V: Visitor<'v>>(visitor: &mut V,
+                                           lifetimes: &'v Vec<LifetimeDef>) {
     for l in lifetimes.iter() {
-        visitor.visit_lifetime_decl(l, env.clone());
+        visitor.visit_lifetime_decl(l);
     }
 }
 
-pub fn walk_path<E: Clone, V: Visitor<E>>(visitor: &mut V, path: &Path, env: E) {
+pub fn walk_path<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path) {
     for segment in path.segments.iter() {
-        visitor.visit_ident(path.span, segment.identifier, env.clone());
+        visitor.visit_ident(path.span, segment.identifier);
 
         for typ in segment.types.iter() {
-            visitor.visit_ty(&**typ, env.clone());
+            visitor.visit_ty(&**typ);
         }
         for lifetime in segment.lifetimes.iter() {
-            visitor.visit_lifetime_ref(lifetime, env.clone());
+            visitor.visit_lifetime_ref(lifetime);
         }
     }
 }
 
-pub fn walk_pat<E: Clone, V: Visitor<E>>(visitor: &mut V, pattern: &Pat, env: E) {
+pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat) {
     match pattern.node {
         PatEnum(ref path, ref children) => {
-            visitor.visit_path(path, pattern.id, env.clone());
+            visitor.visit_path(path, pattern.id);
             for children in children.iter() {
                 for child in children.iter() {
-                    visitor.visit_pat(&**child, env.clone())
+                    visitor.visit_pat(&**child)
                 }
             }
         }
         PatStruct(ref path, ref fields, _) => {
-            visitor.visit_path(path, pattern.id, env.clone());
+            visitor.visit_path(path, pattern.id);
             for field in fields.iter() {
-                visitor.visit_pat(&*field.pat, env.clone())
+                visitor.visit_pat(&*field.pat)
             }
         }
         PatTup(ref tuple_elements) => {
             for tuple_element in tuple_elements.iter() {
-                visitor.visit_pat(&**tuple_element, env.clone())
+                visitor.visit_pat(&**tuple_element)
             }
         }
         PatBox(ref subpattern) |
         PatRegion(ref subpattern) => {
-            visitor.visit_pat(&**subpattern, env)
+            visitor.visit_pat(&**subpattern)
         }
         PatIdent(_, ref pth1, ref optional_subpattern) => {
-            visitor.visit_ident(pth1.span, pth1.node, env.clone());
+            visitor.visit_ident(pth1.span, pth1.node);
             match *optional_subpattern {
                 None => {}
-                Some(ref subpattern) => visitor.visit_pat(&**subpattern, env),
+                Some(ref subpattern) => visitor.visit_pat(&**subpattern),
             }
         }
-        PatLit(ref expression) => visitor.visit_expr(&**expression, env),
+        PatLit(ref expression) => visitor.visit_expr(&**expression),
         PatRange(ref lower_bound, ref upper_bound) => {
-            visitor.visit_expr(&**lower_bound, env.clone());
-            visitor.visit_expr(&**upper_bound, env)
+            visitor.visit_expr(&**lower_bound);
+            visitor.visit_expr(&**upper_bound)
         }
         PatWild(_) => (),
         PatVec(ref prepattern, ref slice_pattern, ref postpatterns) => {
             for prepattern in prepattern.iter() {
-                visitor.visit_pat(&**prepattern, env.clone())
+                visitor.visit_pat(&**prepattern)
             }
             for slice_pattern in slice_pattern.iter() {
-                visitor.visit_pat(&**slice_pattern, env.clone())
+                visitor.visit_pat(&**slice_pattern)
             }
             for postpattern in postpatterns.iter() {
-                visitor.visit_pat(&**postpattern, env.clone())
+                visitor.visit_pat(&**postpattern)
             }
         }
-        PatMac(ref macro) => visitor.visit_mac(macro, env),
+        PatMac(ref macro) => visitor.visit_mac(macro),
     }
 }
 
-pub fn walk_foreign_item<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                                  foreign_item: &ForeignItem,
-                                                  env: E) {
-    visitor.visit_ident(foreign_item.span, foreign_item.ident, env.clone());
+pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V,
+                                             foreign_item: &'v ForeignItem) {
+    visitor.visit_ident(foreign_item.span, foreign_item.ident);
 
     match foreign_item.node {
         ForeignItemFn(ref function_declaration, ref generics) => {
-            walk_fn_decl(visitor, &**function_declaration, env.clone());
-            visitor.visit_generics(generics, env.clone())
+            walk_fn_decl(visitor, &**function_declaration);
+            visitor.visit_generics(generics)
         }
-        ForeignItemStatic(ref typ, _) => visitor.visit_ty(&**typ, env.clone()),
+        ForeignItemStatic(ref typ, _) => visitor.visit_ty(&**typ),
     }
 
     for attr in foreign_item.attrs.iter() {
-        visitor.visit_attribute(attr, env.clone());
+        visitor.visit_attribute(attr);
     }
 }
 
-pub fn walk_ty_param_bounds<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                                     bounds: &OwnedSlice<TyParamBound>,
-                                                     env: E) {
+pub fn walk_ty_param_bounds<'v, V: Visitor<'v>>(visitor: &mut V,
+                                                bounds: &'v OwnedSlice<TyParamBound>) {
     for bound in bounds.iter() {
         match *bound {
             TraitTyParamBound(ref typ) => {
-                walk_trait_ref_helper(visitor, typ, env.clone())
+                walk_trait_ref_helper(visitor, typ)
             }
             UnboxedFnTyParamBound(ref function_declaration) => {
                 for argument in function_declaration.decl.inputs.iter() {
-                    visitor.visit_ty(&*argument.ty, env.clone())
+                    visitor.visit_ty(&*argument.ty)
                 }
-                visitor.visit_ty(&*function_declaration.decl.output,
-                                 env.clone());
+                visitor.visit_ty(&*function_declaration.decl.output);
             }
             RegionTyParamBound(ref lifetime) => {
-                visitor.visit_lifetime_ref(lifetime, env.clone());
+                visitor.visit_lifetime_ref(lifetime);
             }
         }
     }
 }
 
-pub fn walk_generics<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                              generics: &Generics,
-                                              env: E) {
+pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics) {
     for type_parameter in generics.ty_params.iter() {
-        walk_ty_param_bounds(visitor, &type_parameter.bounds, env.clone());
+        walk_ty_param_bounds(visitor, &type_parameter.bounds);
         match type_parameter.default {
-            Some(ref ty) => visitor.visit_ty(&**ty, env.clone()),
+            Some(ref ty) => visitor.visit_ty(&**ty),
             None => {}
         }
     }
-    walk_lifetime_decls(visitor, &generics.lifetimes, env.clone());
+    walk_lifetime_decls(visitor, &generics.lifetimes);
     for predicate in generics.where_clause.predicates.iter() {
-        visitor.visit_ident(predicate.span, predicate.ident, env.clone());
-        walk_ty_param_bounds(visitor, &predicate.bounds, env.clone());
+        visitor.visit_ident(predicate.span, predicate.ident);
+        walk_ty_param_bounds(visitor, &predicate.bounds);
     }
 }
 
-pub fn walk_fn_decl<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                             function_declaration: &FnDecl,
-                                             env: E) {
+pub fn walk_fn_decl<'v, V: Visitor<'v>>(visitor: &mut V, function_declaration: &'v FnDecl) {
     for argument in function_declaration.inputs.iter() {
-        visitor.visit_pat(&*argument.pat, env.clone());
-        visitor.visit_ty(&*argument.ty, env.clone())
+        visitor.visit_pat(&*argument.pat);
+        visitor.visit_ty(&*argument.ty)
     }
-    visitor.visit_ty(&*function_declaration.output, env)
+    visitor.visit_ty(&*function_declaration.output)
 }
 
 // Note: there is no visit_method() method in the visitor, instead override
 // visit_fn() and check for FkMethod().  I named this visit_method_helper()
 // because it is not a default impl of any method, though I doubt that really
 // clarifies anything. - Niko
-pub fn walk_method_helper<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                                   method: &Method,
-                                                   env: E) {
+pub fn walk_method_helper<'v, V: Visitor<'v>>(visitor: &mut V, method: &'v Method) {
     match method.node {
-        MethDecl(ident, ref generics, _, _, _, decl, body, _) => {
-            visitor.visit_ident(method.span, ident, env.clone());
-            visitor.visit_fn(&FkMethod(ident, generics, method),
-                             &*decl,
-                             &*body,
+        MethDecl(ident, ref generics, _, _, _, ref decl, ref body, _) => {
+            visitor.visit_ident(method.span, ident);
+            visitor.visit_fn(FkMethod(ident, generics, method),
+                             &**decl,
+                             &**body,
                              method.span,
-                             method.id,
-                             env.clone());
+                             method.id);
             for attr in method.attrs.iter() {
-                visitor.visit_attribute(attr, env.clone());
+                visitor.visit_attribute(attr);
             }
 
         },
-        MethMac(ref mac) => visitor.visit_mac(mac, env.clone())
+        MethMac(ref mac) => visitor.visit_mac(mac)
     }
 }
 
-pub fn walk_fn<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                        function_kind: &FnKind,
-                                        function_declaration: &FnDecl,
-                                        function_body: &Block,
-                                        _span: Span,
-                                        env: E) {
-    walk_fn_decl(visitor, function_declaration, env.clone());
+pub fn walk_fn<'v, V: Visitor<'v>>(visitor: &mut V,
+                                   function_kind: FnKind<'v>,
+                                   function_declaration: &'v FnDecl,
+                                   function_body: &'v Block,
+                                   _span: Span) {
+    walk_fn_decl(visitor, function_declaration);
 
-    match *function_kind {
+    match function_kind {
         FkItemFn(_, generics, _, _) => {
-            visitor.visit_generics(generics, env.clone());
+            visitor.visit_generics(generics);
         }
         FkMethod(_, generics, method) => {
-            visitor.visit_generics(generics, env.clone());
+            visitor.visit_generics(generics);
             match method.node {
                 MethDecl(_, _, _, ref explicit_self, _, _, _, _) =>
-                    visitor.visit_explicit_self(explicit_self, env.clone()),
+                    visitor.visit_explicit_self(explicit_self),
                 MethMac(ref mac) =>
-                    visitor.visit_mac(mac, env.clone())
+                    visitor.visit_mac(mac)
             }
         }
         FkFnBlock(..) => {}
     }
 
-    visitor.visit_block(function_body, env)
+    visitor.visit_block(function_body)
 }
 
-pub fn walk_ty_method<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                               method_type: &TypeMethod,
-                                               env: E) {
-    visitor.visit_ident(method_type.span, method_type.ident, env.clone());
-    visitor.visit_explicit_self(&method_type.explicit_self, env.clone());
+pub fn walk_ty_method<'v, V: Visitor<'v>>(visitor: &mut V, method_type: &'v TypeMethod) {
+    visitor.visit_ident(method_type.span, method_type.ident);
+    visitor.visit_explicit_self(&method_type.explicit_self);
     for argument_type in method_type.decl.inputs.iter() {
-        visitor.visit_ty(&*argument_type.ty, env.clone())
+        visitor.visit_ty(&*argument_type.ty)
     }
-    visitor.visit_generics(&method_type.generics, env.clone());
-    visitor.visit_ty(&*method_type.decl.output, env.clone());
+    visitor.visit_generics(&method_type.generics);
+    visitor.visit_ty(&*method_type.decl.output);
     for attr in method_type.attrs.iter() {
-        visitor.visit_attribute(attr, env.clone());
+        visitor.visit_attribute(attr);
     }
 }
 
-pub fn walk_trait_item<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                                  trait_method: &TraitItem,
-                                                  env: E) {
+pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_method: &'v TraitItem) {
     match *trait_method {
         RequiredMethod(ref method_type) => {
-            visitor.visit_ty_method(method_type, env)
+            visitor.visit_ty_method(method_type)
         }
-        ProvidedMethod(ref method) => walk_method_helper(visitor, &**method, env),
+        ProvidedMethod(ref method) => walk_method_helper(visitor, &**method),
     }
 }
 
-pub fn walk_struct_def<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                                struct_definition: &StructDef,
-                                                env: E) {
+pub fn walk_struct_def<'v, V: Visitor<'v>>(visitor: &mut V,
+                                           struct_definition: &'v StructDef) {
     match struct_definition.super_struct {
-        Some(ref t) => visitor.visit_ty(&**t, env.clone()),
+        Some(ref t) => visitor.visit_ty(&**t),
         None => {},
     }
     for field in struct_definition.fields.iter() {
-        visitor.visit_struct_field(field, env.clone())
+        visitor.visit_struct_field(field)
     }
 }
 
-pub fn walk_struct_field<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                                  struct_field: &StructField,
-                                                  env: E) {
+pub fn walk_struct_field<'v, V: Visitor<'v>>(visitor: &mut V,
+                                             struct_field: &'v StructField) {
     match struct_field.node.kind {
         NamedField(name, _) => {
-            visitor.visit_ident(struct_field.span, name, env.clone())
+            visitor.visit_ident(struct_field.span, name)
         }
         _ => {}
     }
 
-    visitor.visit_ty(&*struct_field.node.ty, env.clone());
+    visitor.visit_ty(&*struct_field.node.ty);
 
     for attr in struct_field.node.attrs.iter() {
-        visitor.visit_attribute(attr, env.clone());
+        visitor.visit_attribute(attr);
     }
 }
 
-pub fn walk_block<E: Clone, V: Visitor<E>>(visitor: &mut V, block: &Block, env: E) {
+pub fn walk_block<'v, V: Visitor<'v>>(visitor: &mut V, block: &'v Block) {
     for view_item in block.view_items.iter() {
-        visitor.visit_view_item(view_item, env.clone())
+        visitor.visit_view_item(view_item)
     }
     for statement in block.stmts.iter() {
-        visitor.visit_stmt(&**statement, env.clone())
+        visitor.visit_stmt(&**statement)
     }
-    walk_expr_opt(visitor, block.expr, env)
+    walk_expr_opt(visitor, &block.expr)
 }
 
-pub fn walk_stmt<E: Clone, V: Visitor<E>>(visitor: &mut V, statement: &Stmt, env: E) {
+pub fn walk_stmt<'v, V: Visitor<'v>>(visitor: &mut V, statement: &'v Stmt) {
     match statement.node {
-        StmtDecl(ref declaration, _) => visitor.visit_decl(&**declaration, env),
+        StmtDecl(ref declaration, _) => visitor.visit_decl(&**declaration),
         StmtExpr(ref expression, _) | StmtSemi(ref expression, _) => {
-            visitor.visit_expr(&**expression, env)
+            visitor.visit_expr(&**expression)
         }
-        StmtMac(ref macro, _) => visitor.visit_mac(macro, env),
+        StmtMac(ref macro, _) => visitor.visit_mac(macro),
     }
 }
 
-pub fn walk_decl<E: Clone, V: Visitor<E>>(visitor: &mut V, declaration: &Decl, env: E) {
+pub fn walk_decl<'v, V: Visitor<'v>>(visitor: &mut V, declaration: &'v Decl) {
     match declaration.node {
-        DeclLocal(ref local) => visitor.visit_local(&**local, env),
-        DeclItem(ref item) => visitor.visit_item(&**item, env),
+        DeclLocal(ref local) => visitor.visit_local(&**local),
+        DeclItem(ref item) => visitor.visit_item(&**item),
     }
 }
 
-pub fn walk_expr_opt<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                              optional_expression: Option<Gc<Expr>>,
-                                              env: E) {
-    match optional_expression {
+pub fn walk_expr_opt<'v, V: Visitor<'v>>(visitor: &mut V,
+                                         optional_expression: &'v Option<Gc<Expr>>) {
+    match *optional_expression {
         None => {}
-        Some(ref expression) => visitor.visit_expr(&**expression, env),
+        Some(ref expression) => visitor.visit_expr(&**expression),
     }
 }
 
-pub fn walk_exprs<E: Clone, V: Visitor<E>>(visitor: &mut V,
-                                           expressions: &[Gc<Expr>],
-                                           env: E) {
+pub fn walk_exprs<'v, V: Visitor<'v>>(visitor: &mut V, expressions: &'v [Gc<Expr>]) {
     for expression in expressions.iter() {
-        visitor.visit_expr(&**expression, env.clone())
+        visitor.visit_expr(&**expression)
     }
 }
 
-pub fn walk_mac<E, V: Visitor<E>>(_: &mut V, _: &Mac, _: E) {
+pub fn walk_mac<'v, V: Visitor<'v>>(_: &mut V, _: &'v Mac) {
     // Empty!
 }
 
-pub fn walk_expr<E: Clone, V: Visitor<E>>(visitor: &mut V, expression: &Expr, env: E) {
+pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) {
     match expression.node {
         ExprBox(ref place, ref subexpression) => {
-            visitor.visit_expr(&**place, env.clone());
-            visitor.visit_expr(&**subexpression, env.clone())
+            visitor.visit_expr(&**place);
+            visitor.visit_expr(&**subexpression)
         }
         ExprVec(ref subexpressions) => {
-            walk_exprs(visitor, subexpressions.as_slice(), env.clone())
+            walk_exprs(visitor, subexpressions.as_slice())
         }
         ExprRepeat(ref element, ref count) => {
-            visitor.visit_expr(&**element, env.clone());
-            visitor.visit_expr(&**count, env.clone())
+            visitor.visit_expr(&**element);
+            visitor.visit_expr(&**count)
         }
-        ExprStruct(ref path, ref fields, optional_base) => {
-            visitor.visit_path(path, expression.id, env.clone());
+        ExprStruct(ref path, ref fields, ref optional_base) => {
+            visitor.visit_path(path, expression.id);
             for field in fields.iter() {
-                visitor.visit_expr(&*field.expr, env.clone())
+                visitor.visit_expr(&*field.expr)
             }
-            walk_expr_opt(visitor, optional_base, env.clone())
+            walk_expr_opt(visitor, optional_base)
         }
         ExprTup(ref subexpressions) => {
             for subexpression in subexpressions.iter() {
-                visitor.visit_expr(&**subexpression, env.clone())
+                visitor.visit_expr(&**subexpression)
             }
         }
         ExprCall(ref callee_expression, ref arguments) => {
             for argument in arguments.iter() {
-                visitor.visit_expr(&**argument, env.clone())
+                visitor.visit_expr(&**argument)
             }
-            visitor.visit_expr(&**callee_expression, env.clone())
+            visitor.visit_expr(&**callee_expression)
         }
         ExprMethodCall(_, ref types, ref arguments) => {
-            walk_exprs(visitor, arguments.as_slice(), env.clone());
+            walk_exprs(visitor, arguments.as_slice());
             for typ in types.iter() {
-                visitor.visit_ty(&**typ, env.clone())
+                visitor.visit_ty(&**typ)
             }
         }
         ExprBinary(_, ref left_expression, ref right_expression) => {
-            visitor.visit_expr(&**left_expression, env.clone());
-            visitor.visit_expr(&**right_expression, env.clone())
+            visitor.visit_expr(&**left_expression);
+            visitor.visit_expr(&**right_expression)
         }
         ExprAddrOf(_, ref subexpression) | ExprUnary(_, ref subexpression) => {
-            visitor.visit_expr(&**subexpression, env.clone())
+            visitor.visit_expr(&**subexpression)
         }
         ExprLit(_) => {}
         ExprCast(ref subexpression, ref typ) => {
-            visitor.visit_expr(&**subexpression, env.clone());
-            visitor.visit_ty(&**typ, env.clone())
+            visitor.visit_expr(&**subexpression);
+            visitor.visit_ty(&**typ)
         }
-        ExprIf(ref head_expression, ref if_block, optional_else) => {
-            visitor.visit_expr(&**head_expression, env.clone());
-            visitor.visit_block(&**if_block, env.clone());
-            walk_expr_opt(visitor, optional_else, env.clone())
+        ExprIf(ref head_expression, ref if_block, ref optional_else) => {
+            visitor.visit_expr(&**head_expression);
+            visitor.visit_block(&**if_block);
+            walk_expr_opt(visitor, optional_else)
         }
         ExprWhile(ref subexpression, ref block, _) => {
-            visitor.visit_expr(&**subexpression, env.clone());
-            visitor.visit_block(&**block, env.clone())
+            visitor.visit_expr(&**subexpression);
+            visitor.visit_block(&**block)
         }
         ExprForLoop(ref pattern, ref subexpression, ref block, _) => {
-            visitor.visit_pat(&**pattern, env.clone());
-            visitor.visit_expr(&**subexpression, env.clone());
-            visitor.visit_block(&**block, env.clone())
+            visitor.visit_pat(&**pattern);
+            visitor.visit_expr(&**subexpression);
+            visitor.visit_block(&**block)
         }
-        ExprLoop(ref block, _) => visitor.visit_block(&**block, env.clone()),
+        ExprLoop(ref block, _) => visitor.visit_block(&**block),
         ExprMatch(ref subexpression, ref arms) => {
-            visitor.visit_expr(&**subexpression, env.clone());
+            visitor.visit_expr(&**subexpression);
             for arm in arms.iter() {
-                visitor.visit_arm(arm, env.clone())
+                visitor.visit_arm(arm)
             }
         }
         ExprFnBlock(_, ref function_declaration, ref body) => {
-            visitor.visit_fn(&FkFnBlock,
+            visitor.visit_fn(FkFnBlock,
                              &**function_declaration,
                              &**body,
                              expression.span,
-                             expression.id,
-                             env.clone())
+                             expression.id)
         }
         ExprUnboxedFn(_, _, ref function_declaration, ref body) => {
-            visitor.visit_fn(&FkFnBlock,
+            visitor.visit_fn(FkFnBlock,
                              &**function_declaration,
                              &**body,
                              expression.span,
-                             expression.id,
-                             env.clone())
+                             expression.id)
         }
         ExprProc(ref function_declaration, ref body) => {
-            visitor.visit_fn(&FkFnBlock,
+            visitor.visit_fn(FkFnBlock,
                              &**function_declaration,
                              &**body,
                              expression.span,
-                             expression.id,
-                             env.clone())
+                             expression.id)
         }
-        ExprBlock(ref block) => visitor.visit_block(&**block, env.clone()),
+        ExprBlock(ref block) => visitor.visit_block(&**block),
         ExprAssign(ref left_hand_expression, ref right_hand_expression) => {
-            visitor.visit_expr(&**right_hand_expression, env.clone());
-            visitor.visit_expr(&**left_hand_expression, env.clone())
+            visitor.visit_expr(&**right_hand_expression);
+            visitor.visit_expr(&**left_hand_expression)
         }
         ExprAssignOp(_, ref left_expression, ref right_expression) => {
-            visitor.visit_expr(&**right_expression, env.clone());
-            visitor.visit_expr(&**left_expression, env.clone())
+            visitor.visit_expr(&**right_expression);
+            visitor.visit_expr(&**left_expression)
         }
         ExprField(ref subexpression, _, ref types) => {
-            visitor.visit_expr(&**subexpression, env.clone());
+            visitor.visit_expr(&**subexpression);
             for typ in types.iter() {
-                visitor.visit_ty(&**typ, env.clone())
+                visitor.visit_ty(&**typ)
             }
         }
         ExprTupField(ref subexpression, _, ref types) => {
-            visitor.visit_expr(&**subexpression, env.clone());
+            visitor.visit_expr(&**subexpression);
             for typ in types.iter() {
-                visitor.visit_ty(&**typ, env.clone())
+                visitor.visit_ty(&**typ)
             }
         }
         ExprIndex(ref main_expression, ref index_expression) => {
-            visitor.visit_expr(&**main_expression, env.clone());
-            visitor.visit_expr(&**index_expression, env.clone())
+            visitor.visit_expr(&**main_expression);
+            visitor.visit_expr(&**index_expression)
         }
         ExprPath(ref path) => {
-            visitor.visit_path(path, expression.id, env.clone())
+            visitor.visit_path(path, expression.id)
         }
         ExprBreak(_) | ExprAgain(_) => {}
-        ExprRet(optional_expression) => {
-            walk_expr_opt(visitor, optional_expression, env.clone())
+        ExprRet(ref optional_expression) => {
+            walk_expr_opt(visitor, optional_expression)
         }
-        ExprMac(ref macro) => visitor.visit_mac(macro, env.clone()),
+        ExprMac(ref macro) => visitor.visit_mac(macro),
         ExprParen(ref subexpression) => {
-            visitor.visit_expr(&**subexpression, env.clone())
+            visitor.visit_expr(&**subexpression)
         }
         ExprInlineAsm(ref ia) => {
-            for &(_, ref input) in ia.inputs.iter() {
-                visitor.visit_expr(&**input, env.clone())
+            for input in ia.inputs.iter() {
+                let (_, ref input) = *input;
+                visitor.visit_expr(&**input)
             }
-            for &(_, ref output, _) in ia.outputs.iter() {
-                visitor.visit_expr(&**output, env.clone())
+            for output in ia.outputs.iter() {
+                let (_, ref output, _) = *output;
+                visitor.visit_expr(&**output)
             }
         }
     }
 
-    visitor.visit_expr_post(expression, env.clone())
+    visitor.visit_expr_post(expression)
 }
 
-pub fn walk_arm<E: Clone, V: Visitor<E>>(visitor: &mut V, arm: &Arm, env: E) {
+pub fn walk_arm<'v, V: Visitor<'v>>(visitor: &mut V, arm: &'v Arm) {
     for pattern in arm.pats.iter() {
-        visitor.visit_pat(&**pattern, env.clone())
+        visitor.visit_pat(&**pattern)
     }
-    walk_expr_opt(visitor, arm.guard, env.clone());
-    visitor.visit_expr(&*arm.body, env.clone());
+    walk_expr_opt(visitor, &arm.guard);
+    visitor.visit_expr(&*arm.body);
     for attr in arm.attrs.iter() {
-        visitor.visit_attribute(attr, env.clone());
+        visitor.visit_attribute(attr);
     }
 }
index 359b253d6b867fed9865d36a1b270c132153e415..300a9f9eb4906e894eeea19703532cea1e945715 100644 (file)
@@ -1,3 +1,12 @@
+S 2014-09-10 6faa4f3
+  winnt-x86_64 939eb546469cb936441cff3b6f2478f562f77c46
+  winnt-i386 cfe4f8b519bb9d62588f9310a8f94bc919d5423b
+  linux-x86_64 72c92895fa9a1dba7880073f2b2b5d0e3e1a2ab6
+  linux-i386 6f5464c9ab191d93bfea0894ca7c6f90c3506f2b
+  freebsd-x86_64 648f35800ba98f1121d418b6d0c13c63b7a8951b
+  macos-i386 545fc45a0071142714639c6be377e6d308c3a4e1
+  macos-x86_64 8b44fbbbd1ba519d2e83d0d5ce1f6053d3cab8c6
+
 S 2014-09-05 67b97ab
   freebsd-x86_64 5ed208394cb2a378ddfaa005b6298d2f142ad47f
   linux-i386 d90866947bfa09738cf8540d17a8eedc70988fcc
index 0a9cfb5884fcf7bad1f7a6433810c825e5fe98cd..fbbee2e625a8c996bd5b9705c585f258c6243904 100644 (file)
@@ -36,7 +36,7 @@ pub fn plugin_registrar(reg: &mut Registry) {
     reg.register_macro("identity", expand_identity);
     reg.register_syntax_extension(
         token::intern("into_foo"),
-        ItemModifier(expand_into_foo));
+        ItemModifier(box expand_into_foo));
 }
 
 fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
diff --git a/src/test/compile-fail/lint-unused-extern-crate.rs b/src/test/compile-fail/lint-unused-extern-crate.rs
new file mode 100644 (file)
index 0000000..a4dfdbd
--- /dev/null
@@ -0,0 +1,32 @@
+// Copyright 2014 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.
+
+#![feature(globs)]
+#![deny(unused_extern_crate)]
+#![allow(unused_variable)]
+
+extern crate libc; //~ ERROR: unused extern crate
+
+extern crate "collections" as collecs; // no error, it is used
+
+extern crate rand; // no error, the use marks it as used
+                   // even if imported objects aren't used
+
+extern crate time; // no error, the use * marks it as used
+
+#[allow(unused_imports)]
+use rand::isaac::IsaacRng;
+
+use time::*;
+
+fn main() {
+    let x: collecs::vec::Vec<uint> = Vec::new();
+    let y = now();
+}
index 7028f7e798b014b99f1a529c7ec795f23281e7e7..6eecc723431ca21ba3655f4d469722cf0baa3823 100644 (file)
@@ -9,7 +9,7 @@
 // except according to those terms.
 #![feature(struct_variant)]
 
-// Test `Sized?` types not allowed in fields.
+// Test `Sized?` types not allowed in fields (except the last one).
 
 struct S1<Sized? X> {
     f1: X, //~ ERROR type `f1` is dynamically sized. dynamically sized types may only appear as the
@@ -20,7 +20,14 @@ struct S2<Sized? X> {
     g: X, //~ ERROR type `g` is dynamically sized. dynamically sized types may only appear as the ty
     h: int,
 }
-
+struct S3 {
+    f: str, //~ ERROR type `f` is dynamically sized. dynamically sized types may only appear
+    g: [uint]
+}
+struct S4 {
+    f: str, //~ ERROR type `f` is dynamically sized. dynamically sized types may only appear
+    g: uint
+}
 enum E<Sized? X> {
     V1(X, int), //~ERROR type `X` is dynamically sized. dynamically sized types may only appear as t
     V2{f1: X, f: int}, //~ERROR type `f1` is dynamically sized. dynamically sized types may only app
index d582209a79eb1d36886ec70b44ac4dc8ca8d4cfc..78e17bb22bd0315c85abb1467a58adeb39efceb1 100644 (file)
@@ -25,6 +25,7 @@
 
 struct A;
 struct B;
+struct C;
 
 impl fmt::Signed for A {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
@@ -36,6 +37,11 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         f.write("adios".as_bytes())
     }
 }
+impl fmt::Show for C {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        f.pad_integral(true, "☃", "123".as_bytes())
+    }
+}
 
 macro_rules! t(($a:expr, $b:expr) => { assert_eq!($a.as_slice(), $b) })
 
@@ -81,6 +87,7 @@ pub fn main() {
     t!(format!("{} {0}", "a"), "a a");
     t!(format!("{foo_bar}", foo_bar=1i), "1");
     t!(format!("{:d}", 5i + 5i), "10");
+    t!(format!("{:#4}", C), "☃123");
 
     let a: &fmt::Show = &1i;
     t!(format!("{}", a), "1");
@@ -88,6 +95,7 @@ pub fn main() {
     // Formatting strings and their arguments
     t!(format!("{:s}", "a"), "a");
     t!(format!("{:4s}", "a"), "a   ");
+    t!(format!("{:4s}", "☃"), "☃   ");
     t!(format!("{:>4s}", "a"), "   a");
     t!(format!("{:<4s}", "a"), "a   ");
     t!(format!("{:^5s}", "a"),  "  a  ");
diff --git a/src/test/run-pass/unsized3.rs b/src/test/run-pass/unsized3.rs
new file mode 100644 (file)
index 0000000..e5e6ce6
--- /dev/null
@@ -0,0 +1,101 @@
+// Copyright 2014 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.
+
+// Test structs with always-unsized fields.
+
+use std::mem;
+use std::raw;
+
+struct Foo<T> {
+    f: [T],
+}
+
+struct Bar {
+    f1: uint,
+    f2: [uint],
+}
+
+struct Baz {
+    f1: uint,
+    f2: str,
+}
+
+trait Tr {
+    fn foo(&self) -> uint;
+}
+
+struct St {
+    f: uint
+}
+
+impl Tr for St {
+    fn foo(&self) -> uint {
+        self.f
+    }
+}
+
+struct Qux<'a> {
+    f: Tr+'a
+}
+
+pub fn main() {
+    let _: &Foo<f64>;
+    let _: &Bar;
+    let _: &Baz;
+
+    let _: Box<Foo<i32>>;
+    let _: Box<Bar>;
+    let _: Box<Baz>;
+
+    let _ = mem::size_of::<Box<Foo<u8>>>();
+    let _ = mem::size_of::<Box<Bar>>();
+    let _ = mem::size_of::<Box<Baz>>();
+
+    unsafe {
+        struct Foo_<T> {
+            f: [T, ..3]
+        }
+
+        let data = box Foo_{f: [1i32, 2, 3] };
+        let x: &Foo<i32> = mem::transmute(raw::Slice { len: 3, data: &*data });
+        assert!(x.f.len() == 3);
+        assert!(x.f[0] == 1);
+        assert!(x.f[1] == 2);
+        assert!(x.f[2] == 3);
+
+        struct Baz_ {
+            f1: uint,
+            f2: [u8, ..5],
+        }
+
+        let data = box Baz_{ f1: 42, f2: ['a' as u8, 'b' as u8, 'c' as u8, 'd' as u8, 'e' as u8] };
+        let x: &Baz = mem::transmute( raw::Slice { len: 5, data: &*data } );
+        assert!(x.f1 == 42);
+        let chs: Vec<char> = x.f2.chars().collect();
+        assert!(chs.len() == 5);
+        assert!(chs[0] == 'a');
+        assert!(chs[1] == 'b');
+        assert!(chs[2] == 'c');
+        assert!(chs[3] == 'd');
+        assert!(chs[4] == 'e');
+
+        struct Qux_ {
+            f: St
+        }
+
+        let obj: Box<St> = box St { f: 42 };
+        let obj: &Tr = &*obj;
+        let obj: raw::TraitObject = mem::transmute(&*obj);
+        let data = box Qux_{ f: St { f: 234 } };
+        let x: &Qux = mem::transmute(raw::TraitObject { vtable: obj.vtable,
+                                                        data: mem::transmute(&*data) });
+        assert!(x.f.foo() == 234);
+    }
+}