diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f81bb0bd69dd8..be938e6f35e04 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -225,7 +225,7 @@ are: * Although out of date, [Tom Lee's great blog article][tlgba] is very helpful * [rustaceans.org][ro] is helpful, but mostly dedicated to IRC * The [Rust Compiler Testing Docs][rctd] -* For @bors, [this cheetsheat][cheetsheat] is helpful (Remember to replace `@homu` with `@bors` in the commands that you use.) +* For @bors, [this cheat sheet][cheatsheet] is helpful (Remember to replace `@homu` with `@bors` in the commands that you use.) * **Google**! * Don't be afraid to ask! The Rust community is friendly and helpful. @@ -235,4 +235,4 @@ are: [tlgba]: http://tomlee.co/2014/04/03/a-more-detailed-tour-of-the-rust-compiler/ [ro]: http://www.rustaceans.org/ [rctd]: ./COMPILER_TESTS.md -[cheetsheat]: http://buildbot.rust-lang.org/homu/ +[cheatsheet]: http://buildbot.rust-lang.org/homu/ diff --git a/RELEASES.md b/RELEASES.md index 35e9f444523af..8d28535f62376 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,5 +1,211 @@ +Version 1.3.0 (September 2015) +============================== + +* ~900 changes, numerous bugfixes + +Highlights +---------- + +* The [new object lifetime defaults][nold] have been [turned + on][nold2] after a cycle of warnings about the change. Now types + like `&'a Box` (or `&'a Rc`, etc) will change from + being interpreted as `&'a Box` to `&'a + Box`. +* [The Rustonomicon][nom] is a new book in the official documentation + that dives into writing unsafe Rust. +* The [`Duration`] API, [has been stabilized][ds]. This basic unit of + timekeeping is employed by other std APIs, as well as out-of-tree + time crates. + +Breaking Changes +---------------- + +* The [new object lifetime defaults][nold] have been [turned + on][nold2] after a cycle of warnings about the change. +* There is a known [regression][lr] in how object lifetime elision is + interpreted, the proper solution for which is undetermined. +* The `#[prelude_import]` attribute, an internal implementation + detail, was accidentally stabilized previously. [It has been put + behind the `prelude_import` feature gate][pi]. This change is + believed to break no existing code. +* The behavior of [`size_of_val`][dst1] and [`align_of_val`][dst2] is + [more sane for dynamically sized types][dst3]. Code that relied on + the previous behavior is thought to be broken. +* The `dropck` rules, which checks that destructors can't access + destroyed values, [have been updated][dropck] to match the + [RFC][dropckrfc]. This fixes some soundness holes, and as such will + cause some previously-compiling code to no longer build. + +Language +-------- + +* The [new object lifetime defaults][nold] have been [turned + on][nold2] after a cycle of warnings about the change. +* Semicolons may [now follow types and paths in + macros](https://github.com/rust-lang/rust/pull/27000). +* The behavior of [`size_of_val`][dst1] and [`align_of_val`][dst2] is + [more sane for dynamically sized types][dst3]. Code that relied on + the previous behavior is not known to exist, and suspected to be + broken. +* `'static` variables [may now be recursive][st]. +* `ref` bindings choose between [`Deref`] and [`DerefMut`] + implementations correctly. +* The `dropck` rules, which checks that destructors can't access + destroyed values, [have been updated][dropck] to match the + [RFC][dropckrfc]. + +Libraries +--------- + +* The [`Duration`] API, [has been stabilized][ds], as well as the + `std::time` module, which presently contains only `Duration`. +* `Box` and `Box<[T]>` both implement `Clone`. +* The owned C string, [`CString`], implements [`Borrow`] and the + borrowed C string, [`CStr`], implements [`ToOwned`]. The two of + these allow C strings to be borrowed and cloned in generic code. +* [`CStr`] implements [`Debug`]. +* [`AtomicPtr`] implements [`Debug`]. +* [`Error`] trait objects [can be downcast to their concrete types][e] + in many common configurations, using the [`is`], [`downcast`], + [`downcast_ref`] and [`downcast_mut`] methods, similarly to the + [`Any`] trait. +* Searching for substrings now [employs the two-way algorithm][search] + instead of doing a naive search. This gives major speedups to a + number of methods, including [`contains`][sc], [`find`][sf], + [`rfind`][srf], [`split`][ss]. [`starts_with`][ssw] and + [`ends_with`][sew] are also faster. +* The performance of `PartialEq` for slices is [much faster][ps]. +* The [`Hash`] trait offers the default method, [`hash_slice`], which + is overridden and optimized by the implementations for scalars. +* The [`Hasher`] trait now has a number of specialized `write_*` + methods for primitive types, for efficiency. +* The I/O-specific error type, [`std::io::Error`][ie], gained a set of + methods for accessing the 'inner error', if any: [`get_ref`][iegr], + [`get_mut`][iegm], [`into_inner`][ieii]. As well, the implementation + of [`std::error::Error::cause`][iec] also delegates to the inner + error. +* [`process::Child`][pc] gained the [`id`] method, which returns a + `u32` representing the platform-specific process identifier. +* The [`connect`] method on slices is deprecated, replaced by the new + [`join`] method (note that both of these are on the *unstable* + [`SliceConcatExt`] trait, but through the magic of the prelude are + available to stable code anyway). +* The [`Div`] operator is implemented for [`Wrapping`] types. +* [`DerefMut` is implemented for `String`][dms]. +* Performance of SipHash (the default hasher for `HashMap`) is + [better for long data][sh]. +* [`AtomicPtr`] implements [`Send`]. +* The [`read_to_end`] implementations for [`Stdin`] and [`File`] + are now [specialized to use uninitalized buffers for increased + performance][rte]. +* Lifetime parameters of foreign functions [are now resolved + properly][f]. + +Misc +---- + +* Rust can now, with some coercion, [produce programs that run on + Windows XP][xp], though XP is not considered a supported platform. +* Porting Rust on Windows from the GNU toolchain to MSVC continues + ([1][win1], [2][win2], [3][win3], [4][win4]). It is still not + recommended for use in 1.3, though should be fully-functional + in the [64-bit 1.4 beta][b14]. +* On Fedora-based systems installation will [properly configure the + dynamic linker][fl]. +* The compiler gained many new extended error descriptions, which can + be accessed with the `--explain` flag. +* The `dropck` pass, which checks that destructors can't access + destroyed values, [has been rewritten][dropck]. This fixes some + soundness holes, and as such will cause some previously-compiling + code to no longer build. +* `rustc` now uses [LLVM to write archive files where possible][ar]. + Eventually this will eliminate the compiler's dependency on the ar + utility. +* Rust has [preliminary support for i686 FreeBSD][fb] (it has long + supported FreeBSD on x86_64). +* The [`unused_mut`][lum], [`unconditional_recursion`][lur], + [`improper_ctypes`][lic], and [`negate_unsigned`][lnu] lints are + more strict. +* If landing pads are disabled (with `-Z no-landing-pads`), [`panic!` + will kill the process instead of leaking][nlp]. + +[`Any`]: http://doc.rust-lang.org/nightly/std/any/trait.Any.html +[`AtomicPtr`]: http://doc.rust-lang.org/nightly/std/sync/atomic/struct.AtomicPtr.html +[`Borrow`]: http://doc.rust-lang.org/nightly/std/borrow/trait.Borrow.html +[`CStr`]: http://doc.rust-lang.org/nightly/std/ffi/struct.CStr.html +[`CString`]: http://doc.rust-lang.org/nightly/std/ffi/struct.CString.html +[`Debug`]: http://doc.rust-lang.org/nightly/std/fmt/trait.Debug.html +[`DerefMut`]: http://doc.rust-lang.org/nightly/std/ops/trait.DerefMut.html +[`Deref`]: http://doc.rust-lang.org/nightly/std/ops/trait.Deref.html +[`Div`]: http://doc.rust-lang.org/nightly/std/ops/trait.Div.html +[`Duration`]: http://doc.rust-lang.org/nightly/std/time/struct.Duration.html +[`Error`]: http://doc.rust-lang.org/nightly/std/error/trait.Error.html +[`File`]: http://doc.rust-lang.org/nightly/std/fs/struct.File.html +[`Hash`]: http://doc.rust-lang.org/nightly/std/hash/trait.Hash.html +[`Hasher`]: http://doc.rust-lang.org/nightly/std/hash/trait.Hasher.html +[`Send`]: http://doc.rust-lang.org/nightly/std/marker/trait.Send.html +[`SliceConcatExt`]: http://doc.rust-lang.org/nightly/std/slice/trait.SliceConcatExt.html +[`Stdin`]: http://doc.rust-lang.org/nightly/std/io/struct.Stdin.html +[`ToOwned`]: http://doc.rust-lang.org/nightly/std/borrow/trait.ToOwned.html +[`Wrapping`]: http://doc.rust-lang.org/nightly/std/num/struct.Wrapping.html +[`connect`]: http://doc.rust-lang.org/nightly/std/slice/trait.SliceConcatExt.html#method.connect +[`downcast_mut`]: http://doc.rust-lang.org/nightly/std/error/trait.Error.html#method.downcast_mut +[`downcast_ref`]: http://doc.rust-lang.org/nightly/std/error/trait.Error.html#method.downcast_ref +[`downcast`]: http://doc.rust-lang.org/nightly/std/error/trait.Error.html#method.downcast +[`hash_slice`]: http://doc.rust-lang.org/nightly/std/hash/trait.Hash.html#method.hash_slice +[`id`]: http://doc.rust-lang.org/nightly/std/process/struct.Child.html#method.id +[`is`]: http://doc.rust-lang.org/nightly/std/error/trait.Error.html#method.is +[`join`]: http://doc.rust-lang.org/nightly/std/slice/trait.SliceConcatExt.html#method.join +[`read_to_end`]: http://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_to_end +[ar]: https://github.com/rust-lang/rust/pull/26926 +[b14]: https://static.rust-lang.org/dist/rust-beta-x86_64-pc-windows-msvc.msi +[dms]: https://github.com/rust-lang/rust/pull/26241 +[dropck]: https://github.com/rust-lang/rust/pull/27261 +[dropckrfc]: https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md +[ds]: https://github.com/rust-lang/rust/pull/26818 +[dst1]: http://doc.rust-lang.org/nightly/std/mem/fn.size_of_val.html +[dst2]: http://doc.rust-lang.org/nightly/std/mem/fn.align_of_val.html +[dst3]: https://github.com/rust-lang/rust/pull/27351 +[e]: https://github.com/rust-lang/rust/pull/24793 +[f]: https://github.com/rust-lang/rust/pull/26588 +[fb]: https://github.com/rust-lang/rust/pull/26959 +[fl]: https://github.com/rust-lang/rust-installer/pull/41 +[hs]: http://doc.rust-lang.org/nightly/std/hash/trait.Hash.html#method.hash_slice +[ie]: http://doc.rust-lang.org/nightly/std/io/struct.Error.html +[iec]: http://doc.rust-lang.org/nightly/std/io/struct.Error.html#method.cause +[iegm]: http://doc.rust-lang.org/nightly/std/io/struct.Error.html#method.get_mut +[iegr]: http://doc.rust-lang.org/nightly/std/io/struct.Error.html#method.get_ref +[ieii]: http://doc.rust-lang.org/nightly/std/io/struct.Error.html#method.into_inner +[lic]: https://github.com/rust-lang/rust/pull/26583 +[lnu]: https://github.com/rust-lang/rust/pull/27026 +[lr]: https://github.com/rust-lang/rust/issues/27248 +[lum]: https://github.com/rust-lang/rust/pull/26378 +[lur]: https://github.com/rust-lang/rust/pull/26783 +[nlp]: https://github.com/rust-lang/rust/pull/27176 +[nold2]: https://github.com/rust-lang/rust/pull/27045 +[nold]: https://github.com/rust-lang/rfcs/blob/master/text/1156-adjust-default-object-bounds.md +[nom]: http://doc.rust-lang.org/nightly/nomicon/ +[pc]: http://doc.rust-lang.org/nightly/std/process/struct.Child.html +[pi]: https://github.com/rust-lang/rust/pull/26699 +[ps]: https://github.com/rust-lang/rust/pull/26884 +[rte]: https://github.com/rust-lang/rust/pull/26950 +[sc]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.contains +[search]: https://github.com/rust-lang/rust/pull/26327 +[sew]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.ends_with +[sf]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.find +[sh]: https://github.com/rust-lang/rust/pull/27280 +[srf]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.rfind +[ss]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.split +[ssw]: http://doc.rust-lang.org/nightly/std/primitive.str.html#method.starts_with +[st]: https://github.com/rust-lang/rust/pull/26630 +[win1]: https://github.com/rust-lang/rust/pull/26569 +[win2]: https://github.com/rust-lang/rust/pull/26741 +[win3]: https://github.com/rust-lang/rust/pull/26741 +[win4]: https://github.com/rust-lang/rust/pull/27210 +[xp]: https://github.com/rust-lang/rust/pull/26569 + Version 1.2.0 (2015-08-07) -=========================== +========================== * ~1200 changes, numerous bugfixes @@ -427,7 +633,7 @@ Misc [path-normalize]: https://github.com/rust-lang/rust/pull/23229 -Version 1.0.0-alpha.2 (February 2015) +Version 1.0.0-alpha.2 (2015-02-20) ===================================== * ~1300 changes, numerous bugfixes @@ -526,7 +732,7 @@ Version 1.0.0-alpha.2 (February 2015) [un]: https://github.com/rust-lang/rust/pull/22256 -Version 1.0.0-alpha (January 2015) +Version 1.0.0-alpha (2015-01-09) ================================== * ~2400 changes, numerous bugfixes @@ -713,7 +919,7 @@ Version 1.0.0-alpha (January 2015) [rbe]: http://rustbyexample.com/ -Version 0.12.0 (October 2014) +Version 0.12.0 (2014-10-09) ============================= * ~1900 changes, numerous bugfixes @@ -836,7 +1042,7 @@ Version 0.12.0 (October 2014) kernels and distributions, built on CentOS 5.10. -Version 0.11.0 (July 2014) +Version 0.11.0 (2014-07-02) ========================== * ~1700 changes, numerous bugfixes @@ -969,7 +1175,7 @@ Version 0.11.0 (July 2014) greatly improved. -Version 0.10 (April 2014) +Version 0.10 (2014-04-03) ========================= * ~1500 changes, numerous bugfixes @@ -1136,7 +1342,7 @@ Version 0.10 (April 2014) directory. -Version 0.9 (January 2014) +Version 0.9 (2014-01-09) ========================== * ~1800 changes, numerous bugfixes @@ -1302,7 +1508,7 @@ Version 0.9 (January 2014) build tools. -Version 0.8 (September 2013) +Version 0.8 (2013-09-26) ============================ * ~2200 changes, numerous bugfixes @@ -1458,7 +1664,7 @@ Version 0.8 (September 2013) still invoked through the normal `rustdoc` command. -Version 0.7 (July 2013) +Version 0.7 (2013-07-03) ======================= * ~2000 changes, numerous bugfixes @@ -1575,7 +1781,7 @@ Version 0.7 (July 2013) * Improvements to rustpkg (see the detailed release notes). -Version 0.6 (April 2013) +Version 0.6 (2013-04-03) ======================== * ~2100 changes, numerous bugfixes @@ -1678,7 +1884,7 @@ Version 0.6 (April 2013) * Inline assembler supported by new asm!() syntax extension. -Version 0.5 (December 2012) +Version 0.5 (2012-12-21) =========================== * ~900 changes, numerous bugfixes @@ -1735,7 +1941,7 @@ Version 0.5 (December 2012) * License changed from MIT to dual MIT/APL2 -Version 0.4 (October 2012) +Version 0.4 (2012-10-15) ========================== * ~2000 changes, numerous bugfixes @@ -1791,7 +1997,7 @@ Version 0.4 (October 2012) * All hash functions and tables converted to secure, randomized SipHash -Version 0.3 (July 2012) +Version 0.3 (2012-07-12) ======================== * ~1900 changes, numerous bugfixes @@ -1850,7 +2056,7 @@ Version 0.3 (July 2012) * Cargo automatically resolves dependencies -Version 0.2 (March 2012) +Version 0.2 (2012-03-29) ========================= * >1500 changes, numerous bugfixes @@ -1891,7 +2097,7 @@ Version 0.2 (March 2012) * Extensive cleanup, regularization in libstd, libcore -Version 0.1 (January 20, 2012) +Version 0.1 (2012-01-20) =============================== * Most language features work, including: diff --git a/mk/main.mk b/mk/main.mk index 9ede86937e8af..fa6d8097150f4 100644 --- a/mk/main.mk +++ b/mk/main.mk @@ -13,7 +13,7 @@ ###################################################################### # The version number -CFG_RELEASE_NUM=1.4.0 +CFG_RELEASE_NUM=1.5.0 # An optional number to put after the label, e.g. '.2' -> '-beta.2' # NB Make sure it starts with a dot to conform to semver pre-release diff --git a/mk/tests.mk b/mk/tests.mk index e0984cfe86f07..d004558d1bf3f 100644 --- a/mk/tests.mk +++ b/mk/tests.mk @@ -1046,6 +1046,10 @@ $$(call TEST_OK_FILE,$(1),$(2),$(3),rmake): \ $$(RMAKE_TESTS:%=$(3)/test/run-make/%-$(1)-T-$(2)-H-$(3).ok) @touch $$@ +$(3)/test/run-make/%-$(1)-T-$(2)-H-$(3).ok: \ + export INCLUDE := $$(CFG_MSVC_INCLUDE_PATH_$$(HOST_$(3))) +$(3)/test/run-make/%-$(1)-T-$(2)-H-$(3).ok: \ + export LIB := $$(CFG_MSVC_LIB_PATH_$$(HOST_$(3))) $(3)/test/run-make/%-$(1)-T-$(2)-H-$(3).ok: \ $(S)src/test/run-make/%/Makefile \ $$(CSREQ$(1)_T_$(2)_H_$(3)) @@ -1056,7 +1060,7 @@ $(3)/test/run-make/%-$(1)-T-$(2)-H-$(3).ok: \ $$(MAKE) \ $$(HBIN$(1)_H_$(3))/rustc$$(X_$(3)) \ $(3)/test/run-make/$$* \ - $$(CC_$(3)) \ + '$$(CC_$(3))' \ "$$(CFG_GCCISH_CFLAGS_$(3))" \ $$(HBIN$(1)_H_$(3))/rustdoc$$(X_$(3)) \ "$$(TESTNAME)" \ @@ -1064,7 +1068,8 @@ $(3)/test/run-make/%-$(1)-T-$(2)-H-$(3).ok: \ "$$(LD_LIBRARY_PATH_ENV_HOSTDIR$(1)_T_$(2)_H_$(3))" \ "$$(LD_LIBRARY_PATH_ENV_TARGETDIR$(1)_T_$(2)_H_$(3))" \ $(1) \ - $$(S) + $$(S) \ + $(3) @touch -r $$@.start_time $$@ && rm $$@.start_time else # FIXME #11094 - The above rule doesn't work right for multiple targets diff --git a/src/doc/reference.md b/src/doc/reference.md index d7d9f938ed87b..18feebf3d5689 100644 --- a/src/doc/reference.md +++ b/src/doc/reference.md @@ -2762,7 +2762,7 @@ The following expressions are equivalent. let x = std::ops::Range {start: 0, end: 10}; let y = 0..10; -assert_eq!(x,y); +assert_eq!(x, y); ``` ### Unary operator expressions @@ -3087,7 +3087,7 @@ loops](#infinite-loops), [break expressions](#break-expressions), and A `for` expression is a syntactic construct for looping over elements provided by an implementation of `std::iter::IntoIterator`. -An example of a for loop over the contents of an array: +An example of a `for` loop over the contents of an array: ``` # type Foo = i32; diff --git a/src/doc/trpl/error-handling.md b/src/doc/trpl/error-handling.md index 673dc950ecce4..230eb0a85ab0f 100644 --- a/src/doc/trpl/error-handling.md +++ b/src/doc/trpl/error-handling.md @@ -24,7 +24,7 @@ systems may want to jump around. * [The Basics](#the-basics) * [Unwrapping explained](#unwrapping-explained) * [The `Option` type](#the-option-type) - * [Composing `Option` values](#composing-optiont-values) + * [Composing `Option` values](#composing-option-values) * [The `Result` type](#the-result-type) * [Parsing integers](#parsing-integers) * [The `Result` type alias idiom](#the-result-type-alias-idiom) @@ -33,19 +33,19 @@ systems may want to jump around. * [Composing `Option` and `Result`](#composing-option-and-result) * [The limits of combinators](#the-limits-of-combinators) * [Early returns](#early-returns) - * [The `try!` macro](#the-try-macro) + * [The `try!` macro](#the-try!-macro) * [Defining your own error type](#defining-your-own-error-type) * [Standard library traits used for error handling](#standard-library-traits-used-for-error-handling) * [The `Error` trait](#the-error-trait) * [The `From` trait](#the-from-trait) - * [The real `try!` macro](#the-real-try-macro) + * [The real `try!` macro](#the-real-try!-macro) * [Composing custom error types](#composing-custom-error-types) * [Advice for library writers](#advice-for-library-writers) * [Case study: A program to read population data](#case-study-a-program-to-read-population-data) * [Initial setup](#initial-setup) * [Argument parsing](#argument-parsing) * [Writing the logic](#writing-the-logic) - * [Error handling with `Box`](#error-handling-with-boxerror) + * [Error handling with `Box`](#error-handling-with-box) * [Reading from stdin](#reading-from-stdin) * [Error handling with a custom type](#error-handling-with-a-custom-type) * [Adding functionality](#adding-functionality) @@ -87,7 +87,9 @@ thread '
' panicked at 'Invalid number: 11', src/bin/panic-simple.rs:5 Here's another example that is slightly less contrived. A program that accepts an integer as an argument, doubles it and prints it. + ```rust,should_panic + use std::env; fn main() { @@ -120,10 +122,9 @@ It would be better if we just showed the code for unwrapping because it is so simple, but to do that, we will first need to explore the `Option` and `Result` types. Both of these types have a method called `unwrap` defined on them. -## The `Option` type +### The `Option` type -The `Option` type is -[defined in the standard library][1]: +The `Option` type is [defined in the standard library][5]: ```rust enum Option { @@ -138,6 +139,7 @@ system is an important concept because it will cause the compiler to force the programmer to handle that absence. Let's take a look at an example that tries to find a character in a string: + ```rust // Searches `haystack` for the Unicode character `needle`. If one is found, the // byte offset of the character is returned. Otherwise, `None` is returned. diff --git a/src/doc/trpl/guessing-game.md b/src/doc/trpl/guessing-game.md index 4a35022b03c91..3a4328562f872 100644 --- a/src/doc/trpl/guessing-game.md +++ b/src/doc/trpl/guessing-game.md @@ -599,7 +599,7 @@ With this definition, anything of type `Foo` can be either a `Foo::Bar` or a `Foo::Baz`. We use the `::` to indicate the namespace for a particular `enum` variant. -The [`Ordering`][ordering] enum has three possible variants: `Less`, `Equal`, +The [`Ordering`][ordering] `enum` has three possible variants: `Less`, `Equal`, and `Greater`. The `match` statement takes a value of a type, and lets you create an ‘arm’ for each possible value. Since we have three types of `Ordering`, we have three arms: @@ -918,9 +918,9 @@ let guess: u32 = match guess.trim().parse() { This is how you generally move from ‘crash on error’ to ‘actually handle the error’, by switching from `ok().expect()` to a `match` statement. The `Result` -returned by `parse()` is an enum just like `Ordering`, but in this case, each +returned by `parse()` is an `enum` just like `Ordering`, but in this case, each variant has some data associated with it: `Ok` is a success, and `Err` is a -failure. Each contains more information: the successful parsed integer, or an +failure. Each contains more information: the successfully parsed integer, or an error type. In this case, we `match` on `Ok(num)`, which sets the inner value of the `Ok` to the name `num`, and then we just return it on the right-hand side. In the `Err` case, we don’t care what kind of error it is, so we just diff --git a/src/doc/trpl/installing-rust.md b/src/doc/trpl/installing-rust.md index f06005d55b961..366069ac9a3bf 100644 --- a/src/doc/trpl/installing-rust.md +++ b/src/doc/trpl/installing-rust.md @@ -64,7 +64,7 @@ Oh, we should also mention the officially supported platforms: * Windows (7, 8, Server 2008 R2) * Linux (2.6.18 or later, various distributions), x86 and x86-64 -* OSX 10.7 (Lion) or greater, x86 and x86-64 +* OSX 10.7 (Lion) or later, x86 and x86-64 We extensively test Rust on these platforms, and a few others, too, like Android. But these are the ones most likely to work, as they have the most diff --git a/src/doc/trpl/the-stack-and-the-heap.md b/src/doc/trpl/the-stack-and-the-heap.md index fb778b59a3d93..aca736ef2ac3b 100644 --- a/src/doc/trpl/the-stack-and-the-heap.md +++ b/src/doc/trpl/the-stack-and-the-heap.md @@ -217,18 +217,18 @@ on the heap. The actual value of the box is a structure which has a pointer to it allocates some memory for the heap, and puts `5` there. The memory now looks like this: -| Address | Name | Value | -|-----------------|------|------------------| -| 230 | | 5 | -| ... | ... | ... | -| 1 | y | 42 | -| 0 | x | → 230 | - -We have 230 in our hypothetical computer with 1GB of RAM. And since +| Address | Name | Value | +|----------------------|------|------------------------| +| (230) - 1 | | 5 | +| ... | ... | ... | +| 1 | y | 42 | +| 0 | x | → (230) - 1 | + +We have (230) - 1 in our hypothetical computer with 1GB of RAM. And since our stack grows from zero, the easiest place to allocate memory is from the other end. So our first value is at the highest place in memory. And the value of the struct at `x` has a [raw pointer][rawpointer] to the place we’ve -allocated on the heap, so the value of `x` is 230, the memory +allocated on the heap, so the value of `x` is (230) - 1, the memory location we’ve asked for. [rawpointer]: raw-pointers.html @@ -244,18 +244,18 @@ layout of a program which has been running for a while now: | Address | Name | Value | |----------------------|------|------------------------| -| 230 | | 5 | -| (230) - 1 | | | +| (230) - 1 | | 5 | | (230) - 2 | | | -| (230) - 3 | | 42 | +| (230) - 3 | | | +| (230) - 4 | | 42 | | ... | ... | ... | -| 3 | y | → (230) - 3 | +| 3 | y | → (230) - 4 | | 2 | y | 42 | | 1 | y | 42 | -| 0 | x | → 230 | +| 0 | x | → (230) - 1 | In this case, we’ve allocated four things on the heap, but deallocated two of -them. There’s a gap between 230 and (230) - 3 which isn’t +them. There’s a gap between (230) - 1 and (230) - 4 which isn’t currently being used. The specific details of how and why this happens depends on what kind of strategy you use to manage the heap. Different programs can use different ‘memory allocators’, which are libraries that manage this for you. @@ -366,29 +366,29 @@ fn main() { First, we call `main()`: -| Address | Name | Value | -|-----------------|------|------------------| -| 230 | | 20 | -| ... | ... | ... | -| 2 | j | → 0 | -| 1 | i | → 230 | -| 0 | h | 3 | +| Address | Name | Value | +|----------------------|------|------------------------| +| (230) - 1 | | 20 | +| ... | ... | ... | +| 2 | j | → 0 | +| 1 | i | → (230) - 1 | +| 0 | h | 3 | We allocate memory for `j`, `i`, and `h`. `i` is on the heap, and so has a value pointing there. Next, at the end of `main()`, `foo()` gets called: -| Address | Name | Value | -|-----------------|------|-----------------| -| 230 | | 20 | -| ... | ... | ... | -| 5 | z | → 4 | -| 4 | y | 10 | -| 3 | x | → 0 | -| 2 | j | → 0 | -| 1 | i | → 230| -| 0 | h | 3 | +| Address | Name | Value | +|----------------------|------|------------------------| +| (230) - 1 | | 20 | +| ... | ... | ... | +| 5 | z | → 4 | +| 4 | y | 10 | +| 3 | x | → 0 | +| 2 | j | → 0 | +| 1 | i | → (230) - 1 | +| 0 | h | 3 | Space gets allocated for `x`, `y`, and `z`. The argument `x` has the same value as `j`, since that’s what we passed it in. It’s a pointer to the `0` address, @@ -396,42 +396,42 @@ since `j` points at `h`. Next, `foo()` calls `baz()`, passing `z`: -| Address | Name | Value | -|-----------------|------|------------------| -| 230 | | 20 | -| ... | ... | ... | -| 7 | g | 100 | -| 6 | f | → 4 | -| 5 | z | → 4 | -| 4 | y | 10 | -| 3 | x | → 0 | -| 2 | j | → 0 | -| 1 | i | → 230 | -| 0 | h | 3 | +| Address | Name | Value | +|----------------------|------|------------------------| +| (230) - 1 | | 20 | +| ... | ... | ... | +| 7 | g | 100 | +| 6 | f | → 4 | +| 5 | z | → 4 | +| 4 | y | 10 | +| 3 | x | → 0 | +| 2 | j | → 0 | +| 1 | i | → (230) - 1 | +| 0 | h | 3 | We’ve allocated memory for `f` and `g`. `baz()` is very short, so when it’s over, we get rid of its stack frame: -| Address | Name | Value | -|-----------------|------|------------------| -| 230 | | 20 | -| ... | ... | ... | -| 5 | z | → 4 | -| 4 | y | 10 | -| 3 | x | → 0 | -| 2 | j | → 0 | -| 1 | i | → 230 | -| 0 | h | 3 | +| Address | Name | Value | +|----------------------|------|------------------------| +| (230) - 1 | | 20 | +| ... | ... | ... | +| 5 | z | → 4 | +| 4 | y | 10 | +| 3 | x | → 0 | +| 2 | j | → 0 | +| 1 | i | → (230) - 1 | +| 0 | h | 3 | Next, `foo()` calls `bar()` with `x` and `z`: | Address | Name | Value | |----------------------|------|------------------------| -| 230 | | 20 | -| (230) - 1 | | 5 | +| (230) - 1 | | 20 | +| (230) - 2 | | 5 | | ... | ... | ... | | 10 | e | → 9 | -| 9 | d | → (230) - 1 | +| 9 | d | → (230) - 2 | | 8 | c | 5 | | 7 | b | → 4 | | 6 | a | → 0 | @@ -439,24 +439,24 @@ Next, `foo()` calls `bar()` with `x` and `z`: | 4 | y | 10 | | 3 | x | → 0 | | 2 | j | → 0 | -| 1 | i | → 230 | +| 1 | i | → (230) - 1 | | 0 | h | 3 | We end up allocating another value on the heap, and so we have to subtract one -from 230. It’s easier to just write that than `1,073,741,823`. In any +from (230) - 1. It’s easier to just write that than `1,073,741,822`. In any case, we set up the variables as usual. At the end of `bar()`, it calls `baz()`: | Address | Name | Value | |----------------------|------|------------------------| -| 230 | | 20 | -| (230) - 1 | | 5 | +| (230) - 1 | | 20 | +| (230) - 2 | | 5 | | ... | ... | ... | | 12 | g | 100 | | 11 | f | → 9 | | 10 | e | → 9 | -| 9 | d | → (230) - 1 | +| 9 | d | → (230) - 2 | | 8 | c | 5 | | 7 | b | → 4 | | 6 | a | → 0 | @@ -464,7 +464,7 @@ At the end of `bar()`, it calls `baz()`: | 4 | y | 10 | | 3 | x | → 0 | | 2 | j | → 0 | -| 1 | i | → 230 | +| 1 | i | → (230) - 1 | | 0 | h | 3 | With this, we’re at our deepest point! Whew! Congrats for following along this @@ -474,11 +474,11 @@ After `baz()` is over, we get rid of `f` and `g`: | Address | Name | Value | |----------------------|------|------------------------| -| 230 | | 20 | -| (230) - 1 | | 5 | +| (230) - 1 | | 20 | +| (230) - 2 | | 5 | | ... | ... | ... | | 10 | e | → 9 | -| 9 | d | → (230) - 1 | +| 9 | d | → (230) - 2 | | 8 | c | 5 | | 7 | b | → 4 | | 6 | a | → 0 | @@ -486,32 +486,32 @@ After `baz()` is over, we get rid of `f` and `g`: | 4 | y | 10 | | 3 | x | → 0 | | 2 | j | → 0 | -| 1 | i | → 230 | +| 1 | i | → (230) - 1 | | 0 | h | 3 | Next, we return from `bar()`. `d` in this case is a `Box`, so it also frees -what it points to: (230) - 1. - -| Address | Name | Value | -|-----------------|------|------------------| -| 230 | | 20 | -| ... | ... | ... | -| 5 | z | → 4 | -| 4 | y | 10 | -| 3 | x | → 0 | -| 2 | j | → 0 | -| 1 | i | → 230 | -| 0 | h | 3 | +what it points to: (230) - 2. + +| Address | Name | Value | +|----------------------|------|------------------------| +| (230) - 1 | | 20 | +| ... | ... | ... | +| 5 | z | → 4 | +| 4 | y | 10 | +| 3 | x | → 0 | +| 2 | j | → 0 | +| 1 | i | → (230) - 1 | +| 0 | h | 3 | And after that, `foo()` returns: -| Address | Name | Value | -|-----------------|------|------------------| -| 230 | | 20 | -| ... | ... | ... | -| 2 | j | → 0 | -| 1 | i | → 230 | -| 0 | h | 3 | +| Address | Name | Value | +|----------------------|------|------------------------| +| (230) - 1 | | 20 | +| ... | ... | ... | +| 2 | j | → 0 | +| 1 | i | → (230) - 1 | +| 0 | h | 3 | And then, finally, `main()`, which cleans the rest up. When `i` is `Drop`ped, it will clean up the last of the heap too. diff --git a/src/etc/maketest.py b/src/etc/maketest.py index 04bf81a96aaf3..c2958caddc400 100644 --- a/src/etc/maketest.py +++ b/src/etc/maketest.py @@ -12,6 +12,7 @@ import os import sys +target_triple = sys.argv[14] def normalize_path(v): """msys1/msys2 automatically converts `/abs/path1:/abs/path2` into @@ -22,8 +23,11 @@ def normalize_path(v): windows paths so it is really error-prone. revert it for peace.""" v = v.replace('\\', '/') # c:/path -> /c/path - if ':/' in v: - v = '/' + v.replace(':/', '/') + # "c:/path" -> "/c/path" + start = v.find(':/') + while start != -1: + v = v[:start - 1] + '/' + v[start - 1:start] + v[start + 1:] + start = v.find(':/') return v @@ -50,6 +54,10 @@ def convert_path_spec(name, value): putenv('RUST_BUILD_STAGE', sys.argv[12]) putenv('S', os.path.abspath(sys.argv[13])) putenv('PYTHON', sys.executable) +os.putenv('TARGET', target_triple) + +if 'msvc' in target_triple: + os.putenv('IS_MSVC', '1') if filt not in sys.argv[1]: sys.exit(0) diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index aea5feb4be1ff..3344d7ea5d7fc 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -463,17 +463,33 @@ mod impls { } } - partial_ord_impl! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 } + partial_ord_impl! { f32 f64 } macro_rules! ord_impl { ($($t:ty)*) => ($( + #[stable(feature = "rust1", since = "1.0.0")] + impl PartialOrd for $t { + #[inline] + fn partial_cmp(&self, other: &$t) -> Option { + Some(self.cmp(other)) + } + #[inline] + fn lt(&self, other: &$t) -> bool { (*self) < (*other) } + #[inline] + fn le(&self, other: &$t) -> bool { (*self) <= (*other) } + #[inline] + fn ge(&self, other: &$t) -> bool { (*self) >= (*other) } + #[inline] + fn gt(&self, other: &$t) -> bool { (*self) > (*other) } + } + #[stable(feature = "rust1", since = "1.0.0")] impl Ord for $t { #[inline] fn cmp(&self, other: &$t) -> Ordering { - if *self < *other { Less } - else if *self > *other { Greater } - else { Equal } + if *self == *other { Equal } + else if *self < *other { Less } + else { Greater } } } )*) diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 07de4d0761baa..5f0eb63edbc45 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -94,7 +94,7 @@ use fmt; #[lang = "drop"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Drop { - /// The `drop` method, called when the value goes out of scope. + /// A method called when the value goes out of scope. #[stable(feature = "rust1", since = "1.0.0")] fn drop(&mut self); } diff --git a/src/libcore/option.rs b/src/libcore/option.rs index a539ef81db89c..d1bb65d22904a 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -541,7 +541,7 @@ impl Option { /// ``` /// let mut x = Some(4); /// match x.iter_mut().next() { - /// Some(&mut ref mut v) => *v = 42, + /// Some(v) => *v = 42, /// None => {}, /// } /// assert_eq!(x, Some(42)); diff --git a/src/libcore/result.rs b/src/libcore/result.rs index e9a67196751e0..fe0fdb5baa5f3 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -538,7 +538,7 @@ impl Result { /// ``` /// let mut x: Result = Ok(7); /// match x.iter_mut().next() { - /// Some(&mut ref mut x) => *x = 40, + /// Some(v) => *v = 40, /// None => {}, /// } /// assert_eq!(x, Ok(40)); diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 8d3d798afef13..5518bacb019e8 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -1559,30 +1559,41 @@ impl Eq for [T] {} #[stable(feature = "rust1", since = "1.0.0")] impl Ord for [T] { fn cmp(&self, other: &[T]) -> Ordering { - self.iter().cmp(other.iter()) + let l = cmp::min(self.len(), other.len()); + + // Slice to the loop iteration range to enable bound check + // elimination in the compiler + let lhs = &self[..l]; + let rhs = &other[..l]; + + for i in 0..l { + match lhs[i].cmp(&rhs[i]) { + Ordering::Equal => (), + non_eq => return non_eq, + } + } + + self.len().cmp(&other.len()) } } #[stable(feature = "rust1", since = "1.0.0")] impl PartialOrd for [T] { - #[inline] fn partial_cmp(&self, other: &[T]) -> Option { - self.iter().partial_cmp(other.iter()) - } - #[inline] - fn lt(&self, other: &[T]) -> bool { - self.iter().lt(other.iter()) - } - #[inline] - fn le(&self, other: &[T]) -> bool { - self.iter().le(other.iter()) - } - #[inline] - fn ge(&self, other: &[T]) -> bool { - self.iter().ge(other.iter()) - } - #[inline] - fn gt(&self, other: &[T]) -> bool { - self.iter().gt(other.iter()) + let l = cmp::min(self.len(), other.len()); + + // Slice to the loop iteration range to enable bound check + // elimination in the compiler + let lhs = &self[..l]; + let rhs = &other[..l]; + + for i in 0..l { + match lhs[i].partial_cmp(&rhs[i]) { + Some(Ordering::Equal) => (), + non_eq => return non_eq, + } + } + + self.len().partial_cmp(&other.len()) } } diff --git a/src/libcore/sync/atomic.rs b/src/libcore/sync/atomic.rs index 53952cdc9080b..0f72dcc1281a4 100644 --- a/src/libcore/sync/atomic.rs +++ b/src/libcore/sync/atomic.rs @@ -92,6 +92,7 @@ impl Default for AtomicBool { } } +// Send is implicitly implemented for AtomicBool. unsafe impl Sync for AtomicBool {} /// A signed integer type which can be safely shared between threads. @@ -106,6 +107,7 @@ impl Default for AtomicIsize { } } +// Send is implicitly implemented for AtomicIsize. unsafe impl Sync for AtomicIsize {} /// An unsigned integer type which can be safely shared between threads. @@ -120,6 +122,7 @@ impl Default for AtomicUsize { } } +// Send is implicitly implemented for AtomicUsize. unsafe impl Sync for AtomicUsize {} /// A raw pointer type which can be safely shared between threads. diff --git a/src/librustc/diagnostics.rs b/src/librustc/diagnostics.rs index 9616b596c0638..19c880905aeb8 100644 --- a/src/librustc/diagnostics.rs +++ b/src/librustc/diagnostics.rs @@ -1886,7 +1886,117 @@ This explicitly states that you expect the trait object `SomeTrait` to contain references (with a maximum lifetime of `'a`). [1]: https://github.com/rust-lang/rfcs/pull/1156 -"## +"##, + +E0454: r##" +A link name was given with an empty name. Erroneous code example: + +``` +#[link(name = "")] extern {} // error: #[link(name = "")] given with empty name +``` + +The rust compiler cannot link to an external library if you don't give it its +name. Example: + +``` +#[link(name = "some_lib")] extern {} // ok! +``` +"##, + +E0458: r##" +An unknown "kind" was specified for a link attribute. Erroneous code example: + +``` +#[link(kind = "wonderful_unicorn")] extern {} +// error: unknown kind: `wonderful_unicorn` +``` + +Please specify a valid "kind" value, from one of the following: + * static + * dylib + * framework +"##, + +E0459: r##" +A link was used without a name parameter. Erroneous code example: + +``` +#[link(kind = "dylib")] extern {} +// error: #[link(...)] specified without `name = "foo"` +``` + +Please add the name parameter to allow the rust compiler to find the library +you want. Example: + +``` +#[link(kind = "dylib", name = "some_lib")] extern {} // ok! +``` +"##, + +E0493: r##" +A type with a destructor was assigned to an invalid type of variable. Erroneous +code example: + +``` +struct Foo { + a: u32 +} + +impl Drop for Foo { + fn drop(&mut self) {} +} + +const F : Foo = Foo { a : 0 }; +// error: constants are not allowed to have destructors +static S : Foo = Foo { a : 0 }; +// error: statics are not allowed to have destructors +``` + +To solve this issue, please use a type which does allow the usage of type with +destructors. +"##, + +E0494: r##" +A reference of an interior static was assigned to another const/static. +Erroneous code example: + +``` +struct Foo { + a: u32 +} + +static S : Foo = Foo { a : 0 }; +static A : &'static u32 = &S.a; +// error: cannot refer to the interior of another static, use a +// constant instead +``` + +The "base" variable has to be a const if you want another static/const variable +to refer to one of its fields. Example: + +``` +struct Foo { + a: u32 +} + +const S : Foo = Foo { a : 0 }; +static A : &'static u32 = &S.a; // ok! +``` +"##, + +E0497: r##" +A stability attribute was used outside of the standard library. Erroneous code +example: + +``` +#[stable] // error: stability attributes may not be used outside of the + // standard library +fn foo() {} +``` + +It is not possible to use stability attributes outside of the standard library. +Also, for now, it is not possible to write deprecation messages either. +"##, } @@ -1914,5 +2024,46 @@ register_diagnostics! { E0314, // closure outlives stack frame E0315, // cannot invoke closure outside of its lifetime E0316, // nested quantification of lifetimes - E0400 // overloaded derefs are not allowed in constants + E0400, // overloaded derefs are not allowed in constants + E0452, // malformed lint attribute + E0453, // overruled by outer forbid + E0455, // native frameworks are only available on OSX targets + E0456, // plugin `..` is not available for triple `..` + E0457, // plugin `..` only found in rlib format, but must be available... + E0460, // found possibly newer version of crate `..` + E0461, // couldn't find crate `..` with expected target triple .. + E0462, // found staticlib `..` instead of rlib or dylib + E0463, // can't find crate for `..` + E0464, // multiple matching crates for `..` + E0465, // multiple .. candidates for `..` found + E0466, // bad macro import + E0467, // bad macro reexport + E0468, // an `extern crate` loading macros must be at the crate root + E0469, // imported macro not found + E0470, // reexported macro not found + E0471, // constant evaluation error: .. + E0472, // asm! is unsupported on this target + E0473, // dereference of reference outside its lifetime + E0474, // captured variable `..` does not outlive the enclosing closure + E0475, // index of slice outside its lifetime + E0476, // lifetime of the source pointer does not outlive lifetime bound... + E0477, // the type `..` does not fulfill the required lifetime... + E0478, // lifetime bound not satisfied + E0479, // the type `..` (provided as the value of a type parameter) is... + E0480, // lifetime of method receiver does not outlive the method call + E0481, // lifetime of function argument does not outlive the function call + E0482, // lifetime of return value does not outlive the function call + E0483, // lifetime of operand does not outlive the operation + E0484, // reference is not valid at the time of borrow + E0485, // automatically reference is not valid at the time of borrow + E0486, // type of expression contains references that are not valid during... + E0487, // unsafe use of destructor: destructor might be called while... + E0488, // lifetime of variable does not enclose its declaration + E0489, // type/lifetime parameter not in scope here + E0490, // a value of type `..` is borrowed for too long + E0491, // in type `..`, reference has a longer lifetime than the data it... + E0492, // cannot borrow a constant which contains interior mutability + E0495, // cannot infer an appropriate lifetime due to conflicting requirements + E0496, // .. name `..` shadows a .. name that is already in scope + E0498, // malformed plugin attribute } diff --git a/src/librustc/front/map/mod.rs b/src/librustc/front/map/mod.rs index 764f54ce0f0c1..03a52e3cfe469 100644 --- a/src/librustc/front/map/mod.rs +++ b/src/librustc/front/map/mod.rs @@ -17,7 +17,7 @@ use metadata::inline::InlinedItem as II; use middle::def_id::DefId; use syntax::abi; -use syntax::ast::{Name, NodeId, Ident, CRATE_NODE_ID, DUMMY_NODE_ID}; +use syntax::ast::{self, Name, NodeId, Ident, CRATE_NODE_ID, DUMMY_NODE_ID}; use syntax::codemap::{Span, Spanned}; use syntax::parse::token; @@ -538,7 +538,7 @@ impl<'ast> Map<'ast> { /// Given a node ID, get a list of of attributes associated with the AST /// corresponding to the Node ID - pub fn attrs(&self, id: NodeId) -> &'ast [Attribute] { + pub fn attrs(&self, id: NodeId) -> &'ast [ast::Attribute] { let attrs = match self.find(id) { Some(NodeItem(i)) => Some(&i.attrs[..]), Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]), diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index 495044f945949..d9b05d804000a 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -14,7 +14,7 @@ //! compiler code, rather than using their own custom pass. Those //! lints are all available in `rustc_lint::builtin`. -use lint::{LintPass, LintArray}; +use lint::{LintPass, LateLintPass, LintArray}; declare_lint! { pub UNUSED_IMPORTS, @@ -138,3 +138,5 @@ impl LintPass for HardwiredLints { ) } } + +impl LateLintPass for HardwiredLints {} diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index 67be93cc2bdc6..9a736747d5291 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -28,7 +28,8 @@ use self::TargetLint::*; use middle::privacy::ExportedItems; use middle::ty::{self, Ty}; use session::{early_error, Session}; -use lint::{Level, LevelSource, Lint, LintId, LintArray, LintPass, LintPassObject}; +use lint::{Level, LevelSource, Lint, LintId, LintArray, LintPass}; +use lint::{EarlyLintPass, EarlyLintPassObject, LateLintPass, LateLintPassObject}; use lint::{Default, CommandLine, Node, Allow, Warn, Deny, Forbid}; use lint::builtin; use util::nodemap::FnvHashMap; @@ -36,15 +37,15 @@ use util::nodemap::FnvHashMap; use std::cell::RefCell; use std::cmp; use std::mem; -use syntax::ast_util::IdVisitingOperation; -use rustc_front::attr::{self, AttrMetaMethods}; -use rustc_front::util; +use syntax::ast_util::{self, IdVisitingOperation}; +use syntax::attr::{self, AttrMetaMethods}; use syntax::codemap::Span; use syntax::parse::token::InternedString; use syntax::ast; use rustc_front::hir; -use rustc_front::visit::{self, Visitor, FnKind}; -use syntax::visit::Visitor as SyntaxVisitor; +use rustc_front::util; +use rustc_front::visit as hir_visit; +use syntax::visit as ast_visit; use syntax::diagnostic; /// Information about the registered lints. @@ -59,7 +60,8 @@ pub struct LintStore { /// Trait objects for each lint pass. /// This is only `None` while iterating over the objects. See the definition /// of run_lints. - passes: Option>, + early_passes: Option>, + late_passes: Option>, /// Lints indexed by name. by_name: FnvHashMap, @@ -115,7 +117,8 @@ impl LintStore { pub fn new() -> LintStore { LintStore { lints: vec!(), - passes: Some(vec!()), + early_passes: Some(vec!()), + late_passes: Some(vec!()), by_name: FnvHashMap(), levels: FnvHashMap(), lint_groups: FnvHashMap(), @@ -133,8 +136,27 @@ impl LintStore { v.1)).collect() } - pub fn register_pass(&mut self, sess: Option<&Session>, - from_plugin: bool, pass: LintPassObject) { + pub fn register_early_pass(&mut self, + sess: Option<&Session>, + from_plugin: bool, + pass: EarlyLintPassObject) { + self.push_pass(sess, from_plugin, &pass); + self.early_passes.as_mut().unwrap().push(pass); + } + + pub fn register_late_pass(&mut self, + sess: Option<&Session>, + from_plugin: bool, + pass: LateLintPassObject) { + self.push_pass(sess, from_plugin, &pass); + self.late_passes.as_mut().unwrap().push(pass); + } + + // Helper method for register_early/late_pass + fn push_pass(&mut self, + sess: Option<&Session>, + from_plugin: bool, + pass: &Box

) { for &lint in pass.get_lints() { self.lints.push((*lint, from_plugin)); @@ -156,7 +178,6 @@ impl LintStore { self.levels.insert(id, (lint.default_level, Default)); } } - self.passes.as_mut().unwrap().push(pass); } pub fn register_group(&mut self, sess: Option<&Session>, @@ -248,8 +269,8 @@ impl LintStore { } } -/// Context for lint checking. -pub struct Context<'a, 'tcx: 'a> { +/// Context for lint checking after type checking. +pub struct LateContext<'a, 'tcx: 'a> { /// Type context we're checking in. pub tcx: &'a ty::ctxt<'tcx>, @@ -272,21 +293,39 @@ pub struct Context<'a, 'tcx: 'a> { node_levels: RefCell>, } +/// Context for lint checking of the AST, after expansion, before lowering to +/// HIR. +pub struct EarlyContext<'a> { + /// Type context we're checking in. + pub sess: &'a Session, + + /// The crate being checked. + pub krate: &'a ast::Crate, + + /// The store of registered lints. + lints: LintStore, + + /// When recursing into an attributed node of the ast which modifies lint + /// levels, this stack keeps track of the previous lint levels of whatever + /// was modified. + level_stack: Vec<(LintId, LevelSource)>, +} + /// Convenience macro for calling a `LintPass` method on every pass in the context. -macro_rules! run_lints { ($cx:expr, $f:ident, $($args:expr),*) => ({ +macro_rules! run_lints { ($cx:expr, $f:ident, $ps:ident, $($args:expr),*) => ({ // Move the vector of passes out of `$cx` so that we can // iterate over it mutably while passing `$cx` to the methods. - let mut passes = $cx.lints.passes.take().unwrap(); + let mut passes = $cx.mut_lints().$ps.take().unwrap(); for obj in &mut passes { obj.$f($cx, $($args),*); } - $cx.lints.passes = Some(passes); + $cx.mut_lints().$ps = Some(passes); }) } /// Parse the lint attributes into a vector, with `Err`s for malformed lint /// attributes. Writing this as an iterator is an enormous mess. // See also the hir version just below. -pub fn gather_attrs(attrs: &[hir::Attribute]) +pub fn gather_attrs(attrs: &[ast::Attribute]) -> Vec> { let mut out = vec!(); for attr in attrs { @@ -299,39 +338,7 @@ pub fn gather_attrs(attrs: &[hir::Attribute]) let meta = &attr.node.value; let metas = match meta.node { - hir::MetaList(_, ref metas) => metas, - _ => { - out.push(Err(meta.span)); - continue; - } - }; - - for meta in metas { - out.push(match meta.node { - hir::MetaWord(ref lint_name) => Ok((lint_name.clone(), level, meta.span)), - _ => Err(meta.span), - }); - } - } - out -} -// Copy-pasted from the above function :-( -pub fn gather_attrs_from_hir(attrs: &[::rustc_front::hir::Attribute]) - -> Vec> { - use ::rustc_front::attr::AttrMetaMethods; - - let mut out = vec!(); - for attr in attrs { - let level = match Level::from_str(&attr.name()) { - None => continue, - Some(lvl) => lvl, - }; - - ::rustc_front::attr::mark_used(attr); - - let meta = &attr.node.value; - let metas = match meta.node { - ::rustc_front::hir::MetaList(_, ref metas) => metas, + ast::MetaList(_, ref metas) => metas, _ => { out.push(Err(meta.span)); continue; @@ -340,9 +347,7 @@ pub fn gather_attrs_from_hir(attrs: &[::rustc_front::hir::Attribute]) for meta in metas { out.push(match meta.node { - ::rustc_front::hir::MetaWord(ref lint_name) => { - Ok((lint_name.clone(), level, meta.span)) - } + ast::MetaWord(ref lint_name) => Ok((lint_name.clone(), level, meta.span)), _ => Err(meta.span), }); } @@ -398,65 +403,50 @@ pub fn raw_emit_lint(sess: &Session, lint: &'static Lint, } } -impl<'a, 'tcx> Context<'a, 'tcx> { - fn new(tcx: &'a ty::ctxt<'tcx>, - krate: &'a hir::Crate, - exported_items: &'a ExportedItems) -> Context<'a, 'tcx> { - // We want to own the lint store, so move it out of the session. - let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(), - LintStore::new()); - - Context { - tcx: tcx, - krate: krate, - exported_items: exported_items, - lints: lint_store, - level_stack: vec![], - node_levels: RefCell::new(FnvHashMap()), - } - } - - /// Get the overall compiler `Session` object. - pub fn sess(&'a self) -> &'a Session { - &self.tcx.sess - } +pub trait LintContext: Sized { + fn sess(&self) -> &Session; + fn lints(&self) -> &LintStore; + fn mut_lints(&mut self) -> &mut LintStore; + fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)>; + fn enter_attrs(&mut self, attrs: &[ast::Attribute]); + fn exit_attrs(&mut self, attrs: &[ast::Attribute]); /// Get the level of `lint` at the current position of the lint /// traversal. - pub fn current_level(&self, lint: &'static Lint) -> Level { - self.lints.levels.get(&LintId::of(lint)).map_or(Allow, |&(lvl, _)| lvl) + fn current_level(&self, lint: &'static Lint) -> Level { + self.lints().levels.get(&LintId::of(lint)).map_or(Allow, |&(lvl, _)| lvl) } fn lookup_and_emit(&self, lint: &'static Lint, span: Option, msg: &str) { - let (level, src) = match self.lints.levels.get(&LintId::of(lint)) { + let (level, src) = match self.lints().levels.get(&LintId::of(lint)) { None => return, Some(&(Warn, src)) => { let lint_id = LintId::of(builtin::WARNINGS); - (self.lints.get_level_source(lint_id).0, src) + (self.lints().get_level_source(lint_id).0, src) } Some(&pair) => pair, }; - raw_emit_lint(&self.tcx.sess, lint, (level, src), span, msg); - } - - /// Emit a lint at the appropriate level, with no associated span. - pub fn lint(&self, lint: &'static Lint, msg: &str) { - self.lookup_and_emit(lint, None, msg); + raw_emit_lint(&self.sess(), lint, (level, src), span, msg); } /// Emit a lint at the appropriate level, for a particular span. - pub fn span_lint(&self, lint: &'static Lint, span: Span, msg: &str) { + fn span_lint(&self, lint: &'static Lint, span: Span, msg: &str) { self.lookup_and_emit(lint, Some(span), msg); } + /// Emit a lint at the appropriate level, with no associated span. + fn lint(&self, lint: &'static Lint, msg: &str) { + self.lookup_and_emit(lint, None, msg); + } + /// Merge the lints specified by any lint attributes into the /// current lint context, call the provided function, then reset the /// lints in effect to their previous state. fn with_lint_attrs(&mut self, - attrs: &[hir::Attribute], - f: F) where - F: FnOnce(&mut Context), + attrs: &[ast::Attribute], + f: F) + where F: FnOnce(&mut Self), { // Parse all of the lint attributes, and then add them all to the // current dictionary of lint information. Along the way, keep a history @@ -467,14 +457,15 @@ impl<'a, 'tcx> Context<'a, 'tcx> { for result in gather_attrs(attrs) { let v = match result { Err(span) => { - self.tcx.sess.span_err(span, "malformed lint attribute"); + span_err!(self.sess(), span, E0452, + "malformed lint attribute"); continue; } Ok((lint_name, level, span)) => { - match self.lints.find_lint(&lint_name, &self.tcx.sess, Some(span)) { + match self.lints().find_lint(&lint_name, &self.sess(), Some(span)) { Ok(lint_id) => vec![(lint_id, level, span)], Err(FindLintError::NotFound) => { - match self.lints.lint_groups.get(&lint_name[..]) { + match self.lints().lint_groups.get(&lint_name[..]) { Some(&(ref v, _)) => v.iter() .map(|lint_id: &LintId| (*lint_id, level, span)) @@ -493,35 +484,82 @@ impl<'a, 'tcx> Context<'a, 'tcx> { }; for (lint_id, level, span) in v { - let now = self.lints.get_level_source(lint_id).0; + let now = self.lints().get_level_source(lint_id).0; if now == Forbid && level != Forbid { let lint_name = lint_id.as_str(); - self.tcx.sess.span_err(span, - &format!("{}({}) overruled by outer forbid({})", - level.as_str(), lint_name, - lint_name)); + span_err!(self.sess(), span, E0453, + "{}({}) overruled by outer forbid({})", + level.as_str(), lint_name, + lint_name); } else if now != level { - let src = self.lints.get_level_source(lint_id).1; - self.level_stack.push((lint_id, (now, src))); + let src = self.lints().get_level_source(lint_id).1; + self.level_stack().push((lint_id, (now, src))); pushed += 1; - self.lints.set_level(lint_id, (level, Node(span))); + self.mut_lints().set_level(lint_id, (level, Node(span))); } } } - run_lints!(self, enter_lint_attrs, attrs); + self.enter_attrs(attrs); f(self); - run_lints!(self, exit_lint_attrs, attrs); + self.exit_attrs(attrs); // rollback for _ in 0..pushed { - let (lint, lvlsrc) = self.level_stack.pop().unwrap(); - self.lints.set_level(lint, lvlsrc); + let (lint, lvlsrc) = self.level_stack().pop().unwrap(); + self.mut_lints().set_level(lint, lvlsrc); + } + } +} + + +impl<'a> EarlyContext<'a> { + fn new(sess: &'a Session, + krate: &'a ast::Crate) -> EarlyContext<'a> { + // We want to own the lint store, so move it out of the session. Remember + // to put it back later... + let lint_store = mem::replace(&mut *sess.lint_store.borrow_mut(), + LintStore::new()); + EarlyContext { + sess: sess, + krate: krate, + lints: lint_store, + level_stack: vec![], + } + } + + fn visit_ids(&mut self, f: F) + where F: FnOnce(&mut ast_util::IdVisitor) + { + let mut v = ast_util::IdVisitor { + operation: self, + pass_through_items: false, + visited_outermost: false, + }; + f(&mut v); + } +} + +impl<'a, 'tcx> LateContext<'a, 'tcx> { + fn new(tcx: &'a ty::ctxt<'tcx>, + krate: &'a hir::Crate, + exported_items: &'a ExportedItems) -> LateContext<'a, 'tcx> { + // We want to own the lint store, so move it out of the session. + let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(), + LintStore::new()); + + LateContext { + tcx: tcx, + krate: krate, + exported_items: exported_items, + lints: lint_store, + level_stack: vec![], + node_levels: RefCell::new(FnvHashMap()), } } - fn visit_ids(&mut self, f: F) where - F: FnOnce(&mut util::IdVisitor) + fn visit_ids(&mut self, f: F) + where F: FnOnce(&mut util::IdVisitor) { let mut v = util::IdVisitor { operation: self, @@ -532,41 +570,95 @@ impl<'a, 'tcx> Context<'a, 'tcx> { } } -impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { +impl<'a, 'tcx> LintContext for LateContext<'a, 'tcx> { + /// Get the overall compiler `Session` object. + fn sess(&self) -> &Session { + &self.tcx.sess + } + + fn lints(&self) -> &LintStore { + &self.lints + } + + fn mut_lints(&mut self) -> &mut LintStore { + &mut self.lints + } + + fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> { + &mut self.level_stack + } + + fn enter_attrs(&mut self, attrs: &[ast::Attribute]) { + run_lints!(self, enter_lint_attrs, late_passes, attrs); + } + + fn exit_attrs(&mut self, attrs: &[ast::Attribute]) { + run_lints!(self, exit_lint_attrs, late_passes, attrs); + } +} + +impl<'a> LintContext for EarlyContext<'a> { + /// Get the overall compiler `Session` object. + fn sess(&self) -> &Session { + &self.sess + } + + fn lints(&self) -> &LintStore { + &self.lints + } + + fn mut_lints(&mut self) -> &mut LintStore { + &mut self.lints + } + + fn level_stack(&mut self) -> &mut Vec<(LintId, LevelSource)> { + &mut self.level_stack + } + + fn enter_attrs(&mut self, attrs: &[ast::Attribute]) { + run_lints!(self, enter_lint_attrs, early_passes, attrs); + } + + fn exit_attrs(&mut self, attrs: &[ast::Attribute]) { + run_lints!(self, exit_lint_attrs, early_passes, attrs); + } +} + +impl<'a, 'tcx, 'v> hir_visit::Visitor<'v> for LateContext<'a, 'tcx> { fn visit_item(&mut self, it: &hir::Item) { self.with_lint_attrs(&it.attrs, |cx| { - run_lints!(cx, check_item, it); + run_lints!(cx, check_item, late_passes, it); cx.visit_ids(|v| v.visit_item(it)); - visit::walk_item(cx, it); + hir_visit::walk_item(cx, it); }) } fn visit_foreign_item(&mut self, it: &hir::ForeignItem) { self.with_lint_attrs(&it.attrs, |cx| { - run_lints!(cx, check_foreign_item, it); - visit::walk_foreign_item(cx, it); + run_lints!(cx, check_foreign_item, late_passes, it); + hir_visit::walk_foreign_item(cx, it); }) } fn visit_pat(&mut self, p: &hir::Pat) { - run_lints!(self, check_pat, p); - visit::walk_pat(self, p); + run_lints!(self, check_pat, late_passes, p); + hir_visit::walk_pat(self, p); } fn visit_expr(&mut self, e: &hir::Expr) { - run_lints!(self, check_expr, e); - visit::walk_expr(self, e); + run_lints!(self, check_expr, late_passes, e); + hir_visit::walk_expr(self, e); } fn visit_stmt(&mut self, s: &hir::Stmt) { - run_lints!(self, check_stmt, s); - visit::walk_stmt(self, s); + run_lints!(self, check_stmt, late_passes, s); + hir_visit::walk_stmt(self, s); } - fn visit_fn(&mut self, fk: FnKind<'v>, decl: &'v hir::FnDecl, + fn visit_fn(&mut self, fk: hir_visit::FnKind<'v>, decl: &'v hir::FnDecl, body: &'v hir::Block, span: Span, id: ast::NodeId) { - run_lints!(self, check_fn, fk, decl, body, span, id); - visit::walk_fn(self, fk, decl, body, span); + run_lints!(self, check_fn, late_passes, fk, decl, body, span, id); + hir_visit::walk_fn(self, fk, decl, body, span); } fn visit_struct_def(&mut self, @@ -574,116 +666,276 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { ident: ast::Ident, g: &hir::Generics, id: ast::NodeId) { - run_lints!(self, check_struct_def, s, ident, g, id); - visit::walk_struct_def(self, s); - run_lints!(self, check_struct_def_post, s, ident, g, id); + run_lints!(self, check_struct_def, late_passes, s, ident, g, id); + hir_visit::walk_struct_def(self, s); + run_lints!(self, check_struct_def_post, late_passes, s, ident, g, id); } fn visit_struct_field(&mut self, s: &hir::StructField) { self.with_lint_attrs(&s.node.attrs, |cx| { - run_lints!(cx, check_struct_field, s); - visit::walk_struct_field(cx, s); + run_lints!(cx, check_struct_field, late_passes, s); + hir_visit::walk_struct_field(cx, s); }) } fn visit_variant(&mut self, v: &hir::Variant, g: &hir::Generics) { self.with_lint_attrs(&v.node.attrs, |cx| { - run_lints!(cx, check_variant, v, g); - visit::walk_variant(cx, v, g); - run_lints!(cx, check_variant_post, v, g); + run_lints!(cx, check_variant, late_passes, v, g); + hir_visit::walk_variant(cx, v, g); + run_lints!(cx, check_variant_post, late_passes, v, g); }) } fn visit_ty(&mut self, t: &hir::Ty) { - run_lints!(self, check_ty, t); - visit::walk_ty(self, t); + run_lints!(self, check_ty, late_passes, t); + hir_visit::walk_ty(self, t); } fn visit_ident(&mut self, sp: Span, id: ast::Ident) { - run_lints!(self, check_ident, sp, id); + run_lints!(self, check_ident, late_passes, sp, id); } fn visit_mod(&mut self, m: &hir::Mod, s: Span, n: ast::NodeId) { - run_lints!(self, check_mod, m, s, n); - visit::walk_mod(self, m); + run_lints!(self, check_mod, late_passes, m, s, n); + hir_visit::walk_mod(self, m); } fn visit_local(&mut self, l: &hir::Local) { - run_lints!(self, check_local, l); - visit::walk_local(self, l); + run_lints!(self, check_local, late_passes, l); + hir_visit::walk_local(self, l); } fn visit_block(&mut self, b: &hir::Block) { - run_lints!(self, check_block, b); - visit::walk_block(self, b); + run_lints!(self, check_block, late_passes, b); + hir_visit::walk_block(self, b); } fn visit_arm(&mut self, a: &hir::Arm) { - run_lints!(self, check_arm, a); - visit::walk_arm(self, a); + run_lints!(self, check_arm, late_passes, a); + hir_visit::walk_arm(self, a); } fn visit_decl(&mut self, d: &hir::Decl) { - run_lints!(self, check_decl, d); - visit::walk_decl(self, d); + run_lints!(self, check_decl, late_passes, d); + hir_visit::walk_decl(self, d); } fn visit_expr_post(&mut self, e: &hir::Expr) { - run_lints!(self, check_expr_post, e); + run_lints!(self, check_expr_post, late_passes, e); } fn visit_generics(&mut self, g: &hir::Generics) { - run_lints!(self, check_generics, g); - visit::walk_generics(self, g); + run_lints!(self, check_generics, late_passes, g); + hir_visit::walk_generics(self, g); } fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) { self.with_lint_attrs(&trait_item.attrs, |cx| { - run_lints!(cx, check_trait_item, trait_item); + run_lints!(cx, check_trait_item, late_passes, trait_item); cx.visit_ids(|v| v.visit_trait_item(trait_item)); - visit::walk_trait_item(cx, trait_item); + hir_visit::walk_trait_item(cx, trait_item); }); } fn visit_impl_item(&mut self, impl_item: &hir::ImplItem) { self.with_lint_attrs(&impl_item.attrs, |cx| { - run_lints!(cx, check_impl_item, impl_item); + run_lints!(cx, check_impl_item, late_passes, impl_item); cx.visit_ids(|v| v.visit_impl_item(impl_item)); - visit::walk_impl_item(cx, impl_item); + hir_visit::walk_impl_item(cx, impl_item); }); } fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option) { - run_lints!(self, check_opt_lifetime_ref, sp, lt); + run_lints!(self, check_opt_lifetime_ref, late_passes, sp, lt); } fn visit_lifetime_ref(&mut self, lt: &hir::Lifetime) { - run_lints!(self, check_lifetime_ref, lt); + run_lints!(self, check_lifetime_ref, late_passes, lt); } fn visit_lifetime_def(&mut self, lt: &hir::LifetimeDef) { - run_lints!(self, check_lifetime_def, lt); + run_lints!(self, check_lifetime_def, late_passes, lt); } fn visit_explicit_self(&mut self, es: &hir::ExplicitSelf) { - run_lints!(self, check_explicit_self, es); - visit::walk_explicit_self(self, es); + run_lints!(self, check_explicit_self, late_passes, es); + hir_visit::walk_explicit_self(self, es); } fn visit_path(&mut self, p: &hir::Path, id: ast::NodeId) { - run_lints!(self, check_path, p, id); - visit::walk_path(self, p); + run_lints!(self, check_path, late_passes, p, id); + hir_visit::walk_path(self, p); } - fn visit_attribute(&mut self, attr: &hir::Attribute) { - run_lints!(self, check_attribute, attr); + fn visit_attribute(&mut self, attr: &ast::Attribute) { + run_lints!(self, check_attribute, late_passes, attr); + } +} + +impl<'a, 'v> ast_visit::Visitor<'v> for EarlyContext<'a> { + fn visit_item(&mut self, it: &ast::Item) { + self.with_lint_attrs(&it.attrs, |cx| { + run_lints!(cx, check_item, early_passes, it); + cx.visit_ids(|v| v.visit_item(it)); + ast_visit::walk_item(cx, it); + }) + } + + fn visit_foreign_item(&mut self, it: &ast::ForeignItem) { + self.with_lint_attrs(&it.attrs, |cx| { + run_lints!(cx, check_foreign_item, early_passes, it); + ast_visit::walk_foreign_item(cx, it); + }) + } + + fn visit_pat(&mut self, p: &ast::Pat) { + run_lints!(self, check_pat, early_passes, p); + ast_visit::walk_pat(self, p); + } + + fn visit_expr(&mut self, e: &ast::Expr) { + run_lints!(self, check_expr, early_passes, e); + ast_visit::walk_expr(self, e); + } + + fn visit_stmt(&mut self, s: &ast::Stmt) { + run_lints!(self, check_stmt, early_passes, s); + ast_visit::walk_stmt(self, s); + } + + fn visit_fn(&mut self, fk: ast_visit::FnKind<'v>, decl: &'v ast::FnDecl, + body: &'v ast::Block, span: Span, id: ast::NodeId) { + run_lints!(self, check_fn, early_passes, fk, decl, body, span, id); + ast_visit::walk_fn(self, fk, decl, body, span); + } + + fn visit_struct_def(&mut self, + s: &ast::StructDef, + ident: ast::Ident, + g: &ast::Generics, + id: ast::NodeId) { + run_lints!(self, check_struct_def, early_passes, s, ident, g, id); + ast_visit::walk_struct_def(self, s); + run_lints!(self, check_struct_def_post, early_passes, s, ident, g, id); + } + + fn visit_struct_field(&mut self, s: &ast::StructField) { + self.with_lint_attrs(&s.node.attrs, |cx| { + run_lints!(cx, check_struct_field, early_passes, s); + ast_visit::walk_struct_field(cx, s); + }) + } + + fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) { + self.with_lint_attrs(&v.node.attrs, |cx| { + run_lints!(cx, check_variant, early_passes, v, g); + ast_visit::walk_variant(cx, v, g); + run_lints!(cx, check_variant_post, early_passes, v, g); + }) + } + + fn visit_ty(&mut self, t: &ast::Ty) { + run_lints!(self, check_ty, early_passes, t); + ast_visit::walk_ty(self, t); + } + + fn visit_ident(&mut self, sp: Span, id: ast::Ident) { + run_lints!(self, check_ident, early_passes, sp, id); + } + + fn visit_mod(&mut self, m: &ast::Mod, s: Span, n: ast::NodeId) { + run_lints!(self, check_mod, early_passes, m, s, n); + ast_visit::walk_mod(self, m); + } + + fn visit_local(&mut self, l: &ast::Local) { + run_lints!(self, check_local, early_passes, l); + ast_visit::walk_local(self, l); + } + + fn visit_block(&mut self, b: &ast::Block) { + run_lints!(self, check_block, early_passes, b); + ast_visit::walk_block(self, b); + } + + fn visit_arm(&mut self, a: &ast::Arm) { + run_lints!(self, check_arm, early_passes, a); + ast_visit::walk_arm(self, a); + } + + fn visit_decl(&mut self, d: &ast::Decl) { + run_lints!(self, check_decl, early_passes, d); + ast_visit::walk_decl(self, d); + } + + fn visit_expr_post(&mut self, e: &ast::Expr) { + run_lints!(self, check_expr_post, early_passes, e); + } + + fn visit_generics(&mut self, g: &ast::Generics) { + run_lints!(self, check_generics, early_passes, g); + ast_visit::walk_generics(self, g); + } + + fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) { + self.with_lint_attrs(&trait_item.attrs, |cx| { + run_lints!(cx, check_trait_item, early_passes, trait_item); + cx.visit_ids(|v| v.visit_trait_item(trait_item)); + ast_visit::walk_trait_item(cx, trait_item); + }); + } + + fn visit_impl_item(&mut self, impl_item: &ast::ImplItem) { + self.with_lint_attrs(&impl_item.attrs, |cx| { + run_lints!(cx, check_impl_item, early_passes, impl_item); + cx.visit_ids(|v| v.visit_impl_item(impl_item)); + ast_visit::walk_impl_item(cx, impl_item); + }); + } + + fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option) { + run_lints!(self, check_opt_lifetime_ref, early_passes, sp, lt); + } + + fn visit_lifetime_ref(&mut self, lt: &ast::Lifetime) { + run_lints!(self, check_lifetime_ref, early_passes, lt); + } + + fn visit_lifetime_def(&mut self, lt: &ast::LifetimeDef) { + run_lints!(self, check_lifetime_def, early_passes, lt); + } + + fn visit_explicit_self(&mut self, es: &ast::ExplicitSelf) { + run_lints!(self, check_explicit_self, early_passes, es); + ast_visit::walk_explicit_self(self, es); + } + + fn visit_path(&mut self, p: &ast::Path, id: ast::NodeId) { + run_lints!(self, check_path, early_passes, p, id); + ast_visit::walk_path(self, p); + } + + fn visit_attribute(&mut self, attr: &ast::Attribute) { + run_lints!(self, check_attribute, early_passes, attr); } } // Output any lints that were previously added to the session. -impl<'a, 'tcx> IdVisitingOperation for Context<'a, 'tcx> { +impl<'a, 'tcx> IdVisitingOperation for LateContext<'a, 'tcx> { fn visit_id(&mut self, id: ast::NodeId) { - match self.tcx.sess.lints.borrow_mut().remove(&id) { + match self.sess().lints.borrow_mut().remove(&id) { + None => {} + Some(lints) => { + for (lint_id, span, msg) in lints { + self.span_lint(lint_id.lint, span, &msg[..]) + } + } + } + } +} +impl<'a> IdVisitingOperation for EarlyContext<'a> { + fn visit_id(&mut self, id: ast::NodeId) { + match self.sess.lints.borrow_mut().remove(&id) { None => {} Some(lints) => { for (lint_id, span, msg) in lints { @@ -694,7 +946,7 @@ impl<'a, 'tcx> IdVisitingOperation for Context<'a, 'tcx> { } } -// This lint pass is defined here because it touches parts of the `Context` +// This lint pass is defined here because it touches parts of the `LateContext` // that we don't want to expose. It records the lint level at certain AST // nodes, so that the variant size difference check in trans can call // `raw_emit_lint`. @@ -705,8 +957,10 @@ impl LintPass for GatherNodeLevels { fn get_lints(&self) -> LintArray { lint_array!() } +} - fn check_item(&mut self, cx: &Context, it: &hir::Item) { +impl LateLintPass for GatherNodeLevels { + fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { match it.node { hir::ItemEnum(..) => { let lint_id = LintId::of(builtin::VARIANT_SIZE_DIFFERENCES); @@ -731,21 +985,21 @@ pub fn check_crate(tcx: &ty::ctxt, krate: &hir::Crate, exported_items: &ExportedItems) { - let mut cx = Context::new(tcx, krate, exported_items); + let mut cx = LateContext::new(tcx, krate, exported_items); // Visit the whole crate. cx.with_lint_attrs(&krate.attrs, |cx| { cx.visit_id(ast::CRATE_NODE_ID); cx.visit_ids(|v| { v.visited_outermost = true; - visit::walk_crate(v, krate); + hir_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); + run_lints!(cx, check_crate, late_passes, krate); - visit::walk_crate(cx, krate); + hir_visit::walk_crate(cx, krate); }); // If we missed any lints added to the session, then there's a bug somewhere @@ -760,3 +1014,35 @@ pub fn check_crate(tcx: &ty::ctxt, *tcx.node_lint_levels.borrow_mut() = cx.node_levels.into_inner(); } + +pub fn check_ast_crate(sess: &Session, krate: &ast::Crate) { + let mut cx = EarlyContext::new(sess, krate); + + // Visit the whole crate. + cx.with_lint_attrs(&krate.attrs, |cx| { + cx.visit_id(ast::CRATE_NODE_ID); + cx.visit_ids(|v| { + v.visited_outermost = true; + ast_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, early_passes, krate); + + ast_visit::walk_crate(cx, krate); + }); + + // Put the lint store back in the session. + mem::replace(&mut *sess.lint_store.borrow_mut(), cx.lints); + + // If we missed any lints added to the session, then there's a bug somewhere + // in the iteration code. + for (_, v) in sess.lints.borrow().iter() { + for &(lint, span, ref msg) in v { + sess.span_bug(span, + &format!("unprocessed lint {}: {}", + lint.as_str(), *msg)) + } + } +} diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs index 2b3a6c6e287f9..e52b6e91f68cd 100644 --- a/src/librustc/lint/mod.rs +++ b/src/librustc/lint/mod.rs @@ -35,11 +35,13 @@ use std::hash; use std::ascii::AsciiExt; use syntax::codemap::Span; use rustc_front::visit::FnKind; +use syntax::visit as ast_visit; use syntax::ast; use rustc_front::hir; -pub use lint::context::{Context, LintStore, raw_emit_lint, check_crate, gather_attrs, - gather_attrs_from_hir, GatherNodeLevels}; +pub use lint::context::{LateContext, EarlyContext, LintContext, LintStore, + raw_emit_lint, check_crate, check_ast_crate, gather_attrs, + GatherNodeLevels}; /// Specification of a single lint. #[derive(Copy, Clone, Debug)] @@ -109,14 +111,6 @@ macro_rules! lint_array { ($( $lint:expr ),*) => ( pub type LintArray = &'static [&'static &'static Lint]; -/// Trait for types providing lint checks. -/// -/// Each `check` method checks a single syntax node, and should not -/// invoke methods recursively (unlike `Visitor`). By default they -/// do nothing. -// -// FIXME: eliminate the duplication with `Visitor`. But this also -// contains a few lint-specific methods with no equivalent in `Visitor`. pub trait LintPass { /// Get descriptions of the lints this `LintPass` object can emit. /// @@ -125,51 +119,111 @@ pub trait LintPass { /// parts of the compiler. If you want enforced access restrictions for your /// `Lint`, make it a private `static` item in its own module. fn get_lints(&self) -> LintArray; +} + - fn check_crate(&mut self, _: &Context, _: &hir::Crate) { } - fn check_ident(&mut self, _: &Context, _: Span, _: ast::Ident) { } - fn check_mod(&mut self, _: &Context, _: &hir::Mod, _: Span, _: ast::NodeId) { } - fn check_foreign_item(&mut self, _: &Context, _: &hir::ForeignItem) { } - fn check_item(&mut self, _: &Context, _: &hir::Item) { } - fn check_local(&mut self, _: &Context, _: &hir::Local) { } - fn check_block(&mut self, _: &Context, _: &hir::Block) { } - fn check_stmt(&mut self, _: &Context, _: &hir::Stmt) { } - fn check_arm(&mut self, _: &Context, _: &hir::Arm) { } - fn check_pat(&mut self, _: &Context, _: &hir::Pat) { } - fn check_decl(&mut self, _: &Context, _: &hir::Decl) { } - fn check_expr(&mut self, _: &Context, _: &hir::Expr) { } - fn check_expr_post(&mut self, _: &Context, _: &hir::Expr) { } - fn check_ty(&mut self, _: &Context, _: &hir::Ty) { } - fn check_generics(&mut self, _: &Context, _: &hir::Generics) { } - fn check_fn(&mut self, _: &Context, +/// Trait for types providing lint checks. +/// +/// Each `check` method checks a single syntax node, and should not +/// invoke methods recursively (unlike `Visitor`). By default they +/// do nothing. +// +// FIXME: eliminate the duplication with `Visitor`. But this also +// contains a few lint-specific methods with no equivalent in `Visitor`. +pub trait LateLintPass: LintPass { + fn check_ident(&mut self, _: &LateContext, _: Span, _: ast::Ident) { } + fn check_crate(&mut self, _: &LateContext, _: &hir::Crate) { } + fn check_mod(&mut self, _: &LateContext, _: &hir::Mod, _: Span, _: ast::NodeId) { } + fn check_foreign_item(&mut self, _: &LateContext, _: &hir::ForeignItem) { } + fn check_item(&mut self, _: &LateContext, _: &hir::Item) { } + fn check_local(&mut self, _: &LateContext, _: &hir::Local) { } + fn check_block(&mut self, _: &LateContext, _: &hir::Block) { } + fn check_stmt(&mut self, _: &LateContext, _: &hir::Stmt) { } + fn check_arm(&mut self, _: &LateContext, _: &hir::Arm) { } + fn check_pat(&mut self, _: &LateContext, _: &hir::Pat) { } + fn check_decl(&mut self, _: &LateContext, _: &hir::Decl) { } + fn check_expr(&mut self, _: &LateContext, _: &hir::Expr) { } + fn check_expr_post(&mut self, _: &LateContext, _: &hir::Expr) { } + fn check_ty(&mut self, _: &LateContext, _: &hir::Ty) { } + fn check_generics(&mut self, _: &LateContext, _: &hir::Generics) { } + fn check_fn(&mut self, _: &LateContext, _: FnKind, _: &hir::FnDecl, _: &hir::Block, _: Span, _: ast::NodeId) { } - fn check_trait_item(&mut self, _: &Context, _: &hir::TraitItem) { } - fn check_impl_item(&mut self, _: &Context, _: &hir::ImplItem) { } - fn check_struct_def(&mut self, _: &Context, + fn check_trait_item(&mut self, _: &LateContext, _: &hir::TraitItem) { } + fn check_impl_item(&mut self, _: &LateContext, _: &hir::ImplItem) { } + fn check_struct_def(&mut self, _: &LateContext, _: &hir::StructDef, _: ast::Ident, _: &hir::Generics, _: ast::NodeId) { } - fn check_struct_def_post(&mut self, _: &Context, + fn check_struct_def_post(&mut self, _: &LateContext, _: &hir::StructDef, _: ast::Ident, _: &hir::Generics, _: ast::NodeId) { } - fn check_struct_field(&mut self, _: &Context, _: &hir::StructField) { } - fn check_variant(&mut self, _: &Context, _: &hir::Variant, _: &hir::Generics) { } - fn check_variant_post(&mut self, _: &Context, _: &hir::Variant, _: &hir::Generics) { } - fn check_opt_lifetime_ref(&mut self, _: &Context, _: Span, _: &Option) { } - fn check_lifetime_ref(&mut self, _: &Context, _: &hir::Lifetime) { } - fn check_lifetime_def(&mut self, _: &Context, _: &hir::LifetimeDef) { } - fn check_explicit_self(&mut self, _: &Context, _: &hir::ExplicitSelf) { } - fn check_mac(&mut self, _: &Context, _: &ast::Mac) { } - fn check_path(&mut self, _: &Context, _: &hir::Path, _: ast::NodeId) { } - fn check_attribute(&mut self, _: &Context, _: &hir::Attribute) { } + fn check_struct_field(&mut self, _: &LateContext, _: &hir::StructField) { } + fn check_variant(&mut self, _: &LateContext, _: &hir::Variant, _: &hir::Generics) { } + fn check_variant_post(&mut self, _: &LateContext, _: &hir::Variant, _: &hir::Generics) { } + fn check_opt_lifetime_ref(&mut self, _: &LateContext, _: Span, _: &Option) { } + fn check_lifetime_ref(&mut self, _: &LateContext, _: &hir::Lifetime) { } + fn check_lifetime_def(&mut self, _: &LateContext, _: &hir::LifetimeDef) { } + fn check_explicit_self(&mut self, _: &LateContext, _: &hir::ExplicitSelf) { } + // Note that you shouldn't implement both check_mac and check_ast_mac, + // because then your lint will be called twice. Prefer check_ast_mac. + fn check_mac(&mut self, _: &LateContext, _: &ast::Mac) { } + fn check_path(&mut self, _: &LateContext, _: &hir::Path, _: ast::NodeId) { } + fn check_attribute(&mut self, _: &LateContext, _: &ast::Attribute) { } + + /// Called when entering a syntax node that can have lint attributes such + /// as `#[allow(...)]`. Called with *all* the attributes of that node. + fn enter_lint_attrs(&mut self, _: &LateContext, _: &[ast::Attribute]) { } + + /// Counterpart to `enter_lint_attrs`. + fn exit_lint_attrs(&mut self, _: &LateContext, _: &[ast::Attribute]) { } +} + +pub trait EarlyLintPass: LintPass { + fn check_ident(&mut self, _: &EarlyContext, _: Span, _: ast::Ident) { } + fn check_crate(&mut self, _: &EarlyContext, _: &ast::Crate) { } + fn check_mod(&mut self, _: &EarlyContext, _: &ast::Mod, _: Span, _: ast::NodeId) { } + fn check_foreign_item(&mut self, _: &EarlyContext, _: &ast::ForeignItem) { } + fn check_item(&mut self, _: &EarlyContext, _: &ast::Item) { } + fn check_local(&mut self, _: &EarlyContext, _: &ast::Local) { } + fn check_block(&mut self, _: &EarlyContext, _: &ast::Block) { } + fn check_stmt(&mut self, _: &EarlyContext, _: &ast::Stmt) { } + fn check_arm(&mut self, _: &EarlyContext, _: &ast::Arm) { } + fn check_pat(&mut self, _: &EarlyContext, _: &ast::Pat) { } + fn check_decl(&mut self, _: &EarlyContext, _: &ast::Decl) { } + fn check_expr(&mut self, _: &EarlyContext, _: &ast::Expr) { } + fn check_expr_post(&mut self, _: &EarlyContext, _: &ast::Expr) { } + fn check_ty(&mut self, _: &EarlyContext, _: &ast::Ty) { } + fn check_generics(&mut self, _: &EarlyContext, _: &ast::Generics) { } + fn check_fn(&mut self, _: &EarlyContext, + _: ast_visit::FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { } + fn check_trait_item(&mut self, _: &EarlyContext, _: &ast::TraitItem) { } + fn check_impl_item(&mut self, _: &EarlyContext, _: &ast::ImplItem) { } + fn check_struct_def(&mut self, _: &EarlyContext, + _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { } + fn check_struct_def_post(&mut self, _: &EarlyContext, + _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { } + fn check_struct_field(&mut self, _: &EarlyContext, _: &ast::StructField) { } + fn check_variant(&mut self, _: &EarlyContext, _: &ast::Variant, _: &ast::Generics) { } + fn check_variant_post(&mut self, _: &EarlyContext, _: &ast::Variant, _: &ast::Generics) { } + fn check_opt_lifetime_ref(&mut self, + _: &EarlyContext, + _: Span, + _: &Option) { } + fn check_lifetime_ref(&mut self, _: &EarlyContext, _: &ast::Lifetime) { } + fn check_lifetime_def(&mut self, _: &EarlyContext, _: &ast::LifetimeDef) { } + fn check_explicit_self(&mut self, _: &EarlyContext, _: &ast::ExplicitSelf) { } + fn check_mac(&mut self, _: &EarlyContext, _: &ast::Mac) { } + fn check_path(&mut self, _: &EarlyContext, _: &ast::Path, _: ast::NodeId) { } + fn check_attribute(&mut self, _: &EarlyContext, _: &ast::Attribute) { } /// Called when entering a syntax node that can have lint attributes such /// as `#[allow(...)]`. Called with *all* the attributes of that node. - fn enter_lint_attrs(&mut self, _: &Context, _: &[hir::Attribute]) { } + fn enter_lint_attrs(&mut self, _: &EarlyContext, _: &[ast::Attribute]) { } /// Counterpart to `enter_lint_attrs`. - fn exit_lint_attrs(&mut self, _: &Context, _: &[hir::Attribute]) { } + fn exit_lint_attrs(&mut self, _: &EarlyContext, _: &[ast::Attribute]) { } } /// A lint pass boxed up as a trait object. -pub type LintPassObject = Box; +pub type EarlyLintPassObject = Box; +pub type LateLintPassObject = Box; /// Identifies a lint known to the compiler. #[derive(Clone, Copy)] diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index 5ac84578369d2..64f808dc67805 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -33,13 +33,11 @@ use syntax::abi; use syntax::codemap::{self, Span, mk_sp, Pos}; use syntax::parse; use syntax::attr; +use syntax::attr::AttrMetaMethods; use syntax::parse::token::InternedString; use syntax::util::small_vector::SmallVector; use rustc_front::visit; use rustc_front::hir; -use rustc_front::attr as attr_front; -use rustc_front::attr::AttrMetaMethods; -use rustc_front::lowering::unlower_attribute; use log; pub struct LocalCrateReader<'a, 'b:'a> { @@ -79,10 +77,9 @@ fn dump_crates(cstore: &CStore) { fn should_link(i: &ast::Item) -> bool { !attr::contains_name(&i.attrs, "no_link") } - // Dup for the hir fn should_link_hir(i: &hir::Item) -> bool { - !attr_front::contains_name(&i.attrs, "no_link") + !attr::contains_name(&i.attrs, "no_link") } struct CrateInfo { @@ -122,8 +119,8 @@ fn register_native_lib(sess: &Session, if name.is_empty() { match span { Some(span) => { - sess.span_err(span, "#[link(name = \"\")] given with \ - empty name"); + span_err!(sess, span, E0454, + "#[link(name = \"\")] given with empty name"); } None => { sess.err("empty library name given via `-l`"); @@ -135,7 +132,10 @@ fn register_native_lib(sess: &Session, if kind == cstore::NativeFramework && !is_osx { let msg = "native frameworks are only available on OSX targets"; match span { - Some(span) => sess.span_err(span, msg), + Some(span) => { + span_err!(sess, span, E0455, + "{}", msg) + } None => sess.err(msg), } } @@ -329,7 +329,7 @@ impl<'a> CrateReader<'a> { let attrs = decoder::get_crate_attributes(data); for attr in &attrs { if &attr.name()[..] == "staged_api" { - match attr.node.value.node { hir::MetaWord(_) => return true, _ => (/*pass*/) } + match attr.node.value.node { ast::MetaWord(_) => return true, _ => (/*pass*/) } } } @@ -483,7 +483,7 @@ impl<'a> CrateReader<'a> { p.abort_if_errors(); macros.push(ast::MacroDef { ident: name.ident(), - attrs: attrs.iter().map(|a| unlower_attribute(a)).collect(), + attrs: attrs, id: ast::DUMMY_NODE_ID, span: span, imported_from: Some(item.ident), @@ -517,7 +517,7 @@ impl<'a> CrateReader<'a> { name, config::host_triple(), self.sess.opts.target_triple); - self.sess.span_err(span, &message[..]); + span_err!(self.sess, span, E0456, "{}", &message[..]); self.sess.abort_if_errors(); } @@ -527,10 +527,10 @@ impl<'a> CrateReader<'a> { match (ekrate.dylib.as_ref(), registrar) { (Some(dylib), Some(reg)) => Some((dylib.to_path_buf(), reg)), (None, Some(_)) => { - let message = format!("plugin `{}` only found in rlib format, \ - but must be available in dylib format", - name); - self.sess.span_err(span, &message[..]); + span_err!(self.sess, span, E0457, + "plugin `{}` only found in rlib format, but must be available \ + in dylib format", + name); // No need to abort because the loading code will just ignore this // empty dylib. None @@ -763,7 +763,8 @@ impl<'a, 'b> LocalCrateReader<'a, 'b> { Some("dylib") => cstore::NativeUnknown, Some("framework") => cstore::NativeFramework, Some(k) => { - self.sess.span_err(m.span, &format!("unknown kind: `{}`", k)); + span_err!(self.sess, m.span, E0458, + "unknown kind: `{}`", k); cstore::NativeUnknown } None => cstore::NativeUnknown @@ -774,8 +775,8 @@ impl<'a, 'b> LocalCrateReader<'a, 'b> { let n = match n { Some(n) => n, None => { - self.sess.span_err(m.span, "#[link(...)] specified without \ - `name = \"foo\"`"); + span_err!(self.sess, m.span, E0459, + "#[link(...)] specified without `name = \"foo\"`"); InternedString::new("foo") } }; diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index e1cb9bd0e77cf..88d73b3feb390 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -21,7 +21,7 @@ use util::nodemap::FnvHashMap; use std::rc::Rc; use syntax::ast; -use rustc_front::attr; +use syntax::attr; use rustc_front::hir; #[derive(Copy, Clone)] @@ -186,7 +186,7 @@ pub fn get_methods_if_impl(cstore: &cstore::CStore, pub fn get_item_attrs(cstore: &cstore::CStore, def_id: DefId) - -> Vec { + -> Vec { let cdata = cstore.get_crate_data(def_id.krate); decoder::get_item_attrs(&*cdata, def_id.node) } @@ -197,7 +197,7 @@ pub fn get_struct_field_names(cstore: &cstore::CStore, def: DefId) -> Vec FnvHashMap> { + Vec> { let cdata = cstore.get_crate_data(def.krate); decoder::get_struct_field_attrs(&*cdata) } diff --git a/src/librustc/metadata/cstore.rs b/src/librustc/metadata/cstore.rs index 42f52b2d20b1b..5f60fa8ff40e3 100644 --- a/src/librustc/metadata/cstore.rs +++ b/src/librustc/metadata/cstore.rs @@ -27,7 +27,7 @@ use std::rc::Rc; use std::path::PathBuf; use flate::Bytes; use syntax::ast; -use rustc_front::attr; +use syntax::attr; use syntax::codemap; use syntax::parse::token; use syntax::parse::token::IdentInterner; diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index e2cf50cf30ad0..050e04bff8307 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -16,7 +16,6 @@ pub use self::DefLike::*; use self::Family::*; use front::map as ast_map; -use rustc_front::print::pprust; use rustc_front::hir; use back::svh::Svh; @@ -46,12 +45,13 @@ use std::str; use rbml::reader; use rbml; use serialize::Decodable; -use rustc_front::attr; +use syntax::attr; use syntax::parse::token::{IdentInterner, special_idents}; use syntax::parse::token; use syntax::ast; use syntax::abi; use syntax::codemap; +use syntax::print::pprust; use syntax::ptr::P; @@ -1041,7 +1041,7 @@ pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd, pub fn get_item_attrs(cdata: Cmd, orig_node_id: ast::NodeId) - -> Vec { + -> Vec { // The attributes for a tuple struct are attached to the definition, not the ctor; // we assume that someone passing in a tuple struct ctor is actually wanting to // look at the definition @@ -1051,7 +1051,7 @@ pub fn get_item_attrs(cdata: Cmd, get_attributes(item) } -pub fn get_struct_field_attrs(cdata: Cmd) -> FnvHashMap> { +pub fn get_struct_field_attrs(cdata: Cmd) -> FnvHashMap> { let data = rbml::Doc::new(cdata.data()); let fields = reader::get_doc(data, tag_struct_fields); reader::tagged_docs(fields, tag_struct_field).map(|field| { @@ -1079,7 +1079,7 @@ pub fn get_struct_field_names(intr: &IdentInterner, cdata: Cmd, id: ast::NodeId) })).collect() } -fn get_meta_items(md: rbml::Doc) -> Vec> { +fn get_meta_items(md: rbml::Doc) -> Vec> { reader::tagged_docs(md, tag_meta_item_word).map(|meta_item_doc| { let nd = reader::get_doc(meta_item_doc, tag_meta_item_name); let n = token::intern_and_get_ident(nd.as_str_slice()); @@ -1100,7 +1100,7 @@ fn get_meta_items(md: rbml::Doc) -> Vec> { })).collect() } -fn get_attributes(md: rbml::Doc) -> Vec { +fn get_attributes(md: rbml::Doc) -> Vec { match reader::maybe_get_doc(md, tag_attributes) { Some(attrs_d) => { reader::tagged_docs(attrs_d, tag_attribute).map(|attr_doc| { @@ -1113,9 +1113,9 @@ fn get_attributes(md: rbml::Doc) -> Vec { assert_eq!(meta_items.len(), 1); let meta_item = meta_items.into_iter().nth(0).unwrap(); codemap::Spanned { - node: hir::Attribute_ { + node: ast::Attribute_ { id: attr::mk_attr_id(), - style: hir::AttrOuter, + style: ast::AttrOuter, value: meta_item, is_sugared_doc: is_sugared_doc, }, @@ -1139,7 +1139,7 @@ fn list_crate_attributes(md: rbml::Doc, hash: &Svh, write!(out, "\n\n") } -pub fn get_crate_attributes(data: &[u8]) -> Vec { +pub fn get_crate_attributes(data: &[u8]) -> Vec { get_attributes(rbml::Doc::new(data)) } @@ -1337,7 +1337,7 @@ pub fn get_plugin_registrar_fn(data: &[u8]) -> Option { } pub fn each_exported_macro(data: &[u8], intr: &IdentInterner, mut f: F) where - F: FnMut(ast::Name, Vec, String) -> bool, + F: FnMut(ast::Name, Vec, String) -> bool, { let macros = reader::get_doc(rbml::Doc::new(data), tag_macro_defs); for macro_doc in reader::tagged_docs(macros, tag_macro_def) { diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index ff24541692ecc..83dc2f04e4682 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -34,17 +34,17 @@ use std::io::prelude::*; use std::io::{Cursor, SeekFrom}; use std::rc::Rc; use syntax::abi; -use syntax::ast::{NodeId, Name, CRATE_NODE_ID, CrateNum}; +use syntax::ast::{self, NodeId, Name, CRATE_NODE_ID, CrateNum}; +use syntax::attr; +use syntax::attr::AttrMetaMethods; use syntax::diagnostic::SpanHandler; use syntax::parse::token::special_idents; use syntax; use rbml::writer::Encoder; -use rustc_front::hir as ast; +use rustc_front::hir; use rustc_front::visit::Visitor; use rustc_front::visit; -use rustc_front::attr; -use rustc_front::attr::AttrMetaMethods; use front::map::{LinkedPath, PathElem, PathElems}; use front::map as ast_map; @@ -272,7 +272,7 @@ fn encode_struct_fields(rbml_w: &mut Encoder, fn encode_enum_variant_info(ecx: &EncodeContext, rbml_w: &mut Encoder, id: NodeId, - vis: ast::Visibility, + vis: hir::Visibility, index: &mut Vec) { debug!("encode_enum_variant_info(id={})", id); @@ -445,12 +445,12 @@ fn encode_reexported_static_methods(ecx: &EncodeContext, /// top-level items that are sub-items of the given item. Specifically: /// /// * For newtype structs, iterates through the node ID of the constructor. -fn each_auxiliary_node_id(item: &ast::Item, callback: F) -> bool where +fn each_auxiliary_node_id(item: &hir::Item, callback: F) -> bool where F: FnOnce(NodeId) -> bool, { let mut continue_ = true; match item.node { - ast::ItemStruct(ref struct_def, _) => { + hir::ItemStruct(ref struct_def, _) => { // If this is a newtype struct, return the constructor. match struct_def.ctor_id { Some(ctor_id) if !struct_def.fields.is_empty() && @@ -496,12 +496,12 @@ fn encode_reexports(ecx: &EncodeContext, fn encode_info_for_mod(ecx: &EncodeContext, rbml_w: &mut Encoder, - md: &ast::Mod, + md: &hir::Mod, attrs: &[ast::Attribute], id: NodeId, path: PathElems, name: Name, - vis: ast::Visibility) { + vis: hir::Visibility) { rbml_w.start_tag(tag_items_data_item); encode_def_id(rbml_w, DefId::local(id)); encode_family(rbml_w, 'm'); @@ -519,7 +519,7 @@ fn encode_info_for_mod(ecx: &EncodeContext, true }); - if let ast::ItemImpl(..) = item.node { + if let hir::ItemImpl(..) = item.node { let (ident, did) = (item.ident, item.id); debug!("(encoding info for module) ... encoding impl {} ({}/{})", ident, @@ -536,7 +536,7 @@ fn encode_info_for_mod(ecx: &EncodeContext, encode_stability(rbml_w, stab); // Encode the reexports of this module, if this module is public. - if vis == ast::Public { + if vis == hir::Public { debug!("(encoding info for module) encoding reexports for {}", id); encode_reexports(ecx, rbml_w, id, path); } @@ -546,26 +546,26 @@ fn encode_info_for_mod(ecx: &EncodeContext, } fn encode_struct_field_family(rbml_w: &mut Encoder, - visibility: ast::Visibility) { + visibility: hir::Visibility) { encode_family(rbml_w, match visibility { - ast::Public => 'g', - ast::Inherited => 'N' + hir::Public => 'g', + hir::Inherited => 'N' }); } -fn encode_visibility(rbml_w: &mut Encoder, visibility: ast::Visibility) { +fn encode_visibility(rbml_w: &mut Encoder, visibility: hir::Visibility) { let ch = match visibility { - ast::Public => 'y', - ast::Inherited => 'i', + hir::Public => 'y', + hir::Inherited => 'i', }; rbml_w.wr_tagged_u8(tag_items_data_item_visibility, ch as u8); } -fn encode_constness(rbml_w: &mut Encoder, constness: ast::Constness) { +fn encode_constness(rbml_w: &mut Encoder, constness: hir::Constness) { rbml_w.start_tag(tag_items_data_item_constness); let ch = match constness { - ast::Constness::Const => 'c', - ast::Constness::NotConst => 'n', + hir::Constness::Const => 'c', + hir::Constness::NotConst => 'n', }; rbml_w.wr_str(&ch.to_string()); rbml_w.end_tag(); @@ -593,10 +593,10 @@ fn encode_explicit_self(rbml_w: &mut Encoder, } } - fn encode_mutability(m: ast::Mutability) -> u8 { + fn encode_mutability(m: hir::Mutability) -> u8 { match m { - ast::MutImmutable => 'i' as u8, - ast::MutMutable => 'm' as u8, + hir::MutImmutable => 'i' as u8, + hir::MutMutable => 'm' as u8, } } } @@ -784,7 +784,7 @@ fn encode_info_for_associated_const(ecx: &EncodeContext, associated_const: &ty::AssociatedConst, impl_path: PathElems, parent_id: NodeId, - impl_item_opt: Option<&ast::ImplItem>) { + impl_item_opt: Option<&hir::ImplItem>) { debug!("encode_info_for_associated_const({:?},{:?})", associated_const.def_id, associated_const.name); @@ -822,7 +822,7 @@ fn encode_info_for_method<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>, impl_path: PathElems, is_default_impl: bool, parent_id: NodeId, - impl_item_opt: Option<&ast::ImplItem>) { + impl_item_opt: Option<&hir::ImplItem>) { debug!("encode_info_for_method: {:?} {:?}", m.def_id, m.name); @@ -841,13 +841,13 @@ fn encode_info_for_method<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>, let elem = ast_map::PathName(m.name); encode_path(rbml_w, impl_path.chain(Some(elem))); if let Some(impl_item) = impl_item_opt { - if let ast::MethodImplItem(ref sig, _) = impl_item.node { + if let hir::MethodImplItem(ref sig, _) = impl_item.node { encode_attributes(rbml_w, &impl_item.attrs); let scheme = ecx.tcx.lookup_item_type(m.def_id); let any_types = !scheme.generics.types.is_empty(); let needs_inline = any_types || is_default_impl || attr::requests_inline(&impl_item.attrs); - if needs_inline || sig.constness == ast::Constness::Const { + if needs_inline || sig.constness == hir::Constness::Const { encode_inlined_item(ecx, rbml_w, InlinedItemRef::ImplItem(DefId::local(parent_id), impl_item)); } @@ -867,7 +867,7 @@ fn encode_info_for_associated_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>, associated_type: &ty::AssociatedType<'tcx>, impl_path: PathElems, parent_id: NodeId, - impl_item_opt: Option<&ast::ImplItem>) { + impl_item_opt: Option<&hir::ImplItem>) { debug!("encode_info_for_associated_type({:?},{:?})", associated_type.def_id, associated_type.name); @@ -903,11 +903,11 @@ fn encode_info_for_associated_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>, } fn encode_method_argument_names(rbml_w: &mut Encoder, - decl: &ast::FnDecl) { + decl: &hir::FnDecl) { rbml_w.start_tag(tag_method_argument_names); for arg in &decl.inputs { let tag = tag_method_argument_name; - if let ast::PatIdent(_, ref path1, _) = arg.pat.node { + if let hir::PatIdent(_, ref path1, _) = arg.pat.node { let name = path1.node.name.as_str(); rbml_w.wr_tagged_bytes(tag, name.as_bytes()); } else { @@ -982,13 +982,13 @@ fn encode_stability(rbml_w: &mut Encoder, stab_opt: Option<&attr::Stability>) { fn encode_info_for_item(ecx: &EncodeContext, rbml_w: &mut Encoder, - item: &ast::Item, + item: &hir::Item, index: &mut Vec, path: PathElems, - vis: ast::Visibility) { + vis: hir::Visibility) { let tcx = ecx.tcx; - fn add_to_index(item: &ast::Item, rbml_w: &mut Encoder, + fn add_to_index(item: &hir::Item, rbml_w: &mut Encoder, index: &mut Vec) { index.push(IndexEntry { node: item.id, @@ -1003,11 +1003,11 @@ fn encode_info_for_item(ecx: &EncodeContext, let stab = stability::lookup(tcx, DefId::local(item.id)); match item.node { - ast::ItemStatic(_, m, _) => { + hir::ItemStatic(_, m, _) => { add_to_index(item, rbml_w, index); rbml_w.start_tag(tag_items_data_item); encode_def_id(rbml_w, def_id); - if m == ast::MutMutable { + if m == hir::MutMutable { encode_family(rbml_w, 'b'); } else { encode_family(rbml_w, 'c'); @@ -1021,7 +1021,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_attributes(rbml_w, &item.attrs); rbml_w.end_tag(); } - ast::ItemConst(_, _) => { + hir::ItemConst(_, _) => { add_to_index(item, rbml_w, index); rbml_w.start_tag(tag_items_data_item); encode_def_id(rbml_w, def_id); @@ -1035,7 +1035,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_stability(rbml_w, stab); rbml_w.end_tag(); } - ast::ItemFn(ref decl, _, constness, _, ref generics, _) => { + hir::ItemFn(ref decl, _, constness, _, ref generics, _) => { add_to_index(item, rbml_w, index); rbml_w.start_tag(tag_items_data_item); encode_def_id(rbml_w, def_id); @@ -1046,7 +1046,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_path(rbml_w, path); encode_attributes(rbml_w, &item.attrs); let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs); - if needs_inline || constness == ast::Constness::Const { + if needs_inline || constness == hir::Constness::Const { encode_inlined_item(ecx, rbml_w, InlinedItemRef::Item(item)); } if tps_len == 0 { @@ -1058,7 +1058,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_method_argument_names(rbml_w, &**decl); rbml_w.end_tag(); } - ast::ItemMod(ref m) => { + hir::ItemMod(ref m) => { add_to_index(item, rbml_w, index); encode_info_for_mod(ecx, rbml_w, @@ -1069,7 +1069,7 @@ fn encode_info_for_item(ecx: &EncodeContext, item.ident.name, item.vis); } - ast::ItemForeignMod(ref fm) => { + hir::ItemForeignMod(ref fm) => { add_to_index(item, rbml_w, index); rbml_w.start_tag(tag_items_data_item); encode_def_id(rbml_w, def_id); @@ -1086,7 +1086,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_stability(rbml_w, stab); rbml_w.end_tag(); } - ast::ItemTy(..) => { + hir::ItemTy(..) => { add_to_index(item, rbml_w, index); rbml_w.start_tag(tag_items_data_item); encode_def_id(rbml_w, def_id); @@ -1098,7 +1098,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_stability(rbml_w, stab); rbml_w.end_tag(); } - ast::ItemEnum(ref enum_definition, _) => { + hir::ItemEnum(ref enum_definition, _) => { add_to_index(item, rbml_w, index); rbml_w.start_tag(tag_items_data_item); @@ -1128,7 +1128,7 @@ fn encode_info_for_item(ecx: &EncodeContext, vis, index); } - ast::ItemStruct(ref struct_def, _) => { + hir::ItemStruct(ref struct_def, _) => { let def = ecx.tcx.lookup_adt_def(def_id); let variant = def.struct_variant(); @@ -1174,7 +1174,7 @@ fn encode_info_for_item(ecx: &EncodeContext, None => {} } } - ast::ItemDefaultImpl(unsafety, _) => { + hir::ItemDefaultImpl(unsafety, _) => { add_to_index(item, rbml_w, index); rbml_w.start_tag(tag_items_data_item); encode_def_id(rbml_w, def_id); @@ -1186,7 +1186,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_trait_ref(rbml_w, ecx, trait_ref, tag_item_trait_ref); rbml_w.end_tag(); } - ast::ItemImpl(unsafety, polarity, _, _, ref ty, ref ast_items) => { + hir::ItemImpl(unsafety, polarity, _, _, ref ty, ref ast_items) => { // We need to encode information about the default methods we // have inherited, so we drive this based on the impl structure. let impl_items = tcx.impl_items.borrow(); @@ -1212,7 +1212,7 @@ fn encode_info_for_item(ecx: &EncodeContext, } match ty.node { - ast::TyPath(None, ref path) if path.segments.len() == 1 => { + hir::TyPath(None, ref path) if path.segments.len() == 1 => { let name = path.segments.last().unwrap().identifier.name; encode_impl_type_basename(rbml_w, name); } @@ -1289,7 +1289,7 @@ fn encode_info_for_item(ecx: &EncodeContext, } } } - ast::ItemTrait(_, _, _, ref ms) => { + hir::ItemTrait(_, _, _, ref ms) => { add_to_index(item, rbml_w, index); rbml_w.start_tag(tag_items_data_item); encode_def_id(rbml_w, def_id); @@ -1429,11 +1429,11 @@ fn encode_info_for_item(ecx: &EncodeContext, let trait_item = &*ms[i]; encode_attributes(rbml_w, &trait_item.attrs); match trait_item.node { - ast::ConstTraitItem(_, _) => { + hir::ConstTraitItem(_, _) => { encode_inlined_item(ecx, rbml_w, InlinedItemRef::TraitItem(def_id, trait_item)); } - ast::MethodTraitItem(ref sig, ref body) => { + hir::MethodTraitItem(ref sig, ref body) => { // If this is a static method, we've already // encoded this. if is_nonstatic_method { @@ -1453,13 +1453,13 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_method_argument_names(rbml_w, &sig.decl); } - ast::TypeTraitItem(..) => {} + hir::TypeTraitItem(..) => {} } rbml_w.end_tag(); } } - ast::ItemExternCrate(_) | ast::ItemUse(_) => { + hir::ItemExternCrate(_) | hir::ItemUse(_) => { // these are encoded separately } } @@ -1467,7 +1467,7 @@ fn encode_info_for_item(ecx: &EncodeContext, fn encode_info_for_foreign_item(ecx: &EncodeContext, rbml_w: &mut Encoder, - nitem: &ast::ForeignItem, + nitem: &hir::ForeignItem, index: &mut Vec, path: PathElems, abi: abi::Abi) { @@ -1480,7 +1480,7 @@ fn encode_info_for_foreign_item(ecx: &EncodeContext, encode_def_id(rbml_w, DefId::local(nitem.id)); encode_visibility(rbml_w, nitem.vis); match nitem.node { - ast::ForeignItemFn(ref fndecl, _) => { + hir::ForeignItemFn(ref fndecl, _) => { encode_family(rbml_w, FN_FAMILY); encode_bounds_and_type_for_item(rbml_w, ecx, nitem.id); encode_name(rbml_w, nitem.ident.name); @@ -1493,7 +1493,7 @@ fn encode_info_for_foreign_item(ecx: &EncodeContext, encode_symbol(ecx, rbml_w, nitem.id); encode_method_argument_names(rbml_w, &*fndecl); } - ast::ForeignItemStatic(_, mutbl) => { + hir::ForeignItemStatic(_, mutbl) => { if mutbl { encode_family(rbml_w, 'b'); } else { @@ -1511,9 +1511,9 @@ fn encode_info_for_foreign_item(ecx: &EncodeContext, rbml_w.end_tag(); } -fn my_visit_expr(_e: &ast::Expr) { } +fn my_visit_expr(_e: &hir::Expr) { } -fn my_visit_item(i: &ast::Item, +fn my_visit_item(i: &hir::Item, rbml_w: &mut Encoder, ecx: &EncodeContext, index: &mut Vec) { @@ -1522,7 +1522,7 @@ fn my_visit_item(i: &ast::Item, }); } -fn my_visit_foreign_item(ni: &ast::ForeignItem, +fn my_visit_foreign_item(ni: &hir::ForeignItem, rbml_w: &mut Encoder, ecx: &EncodeContext, index: &mut Vec) { @@ -1545,18 +1545,18 @@ struct EncodeVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> { } impl<'a, 'b, 'c, 'tcx, 'v> Visitor<'v> for EncodeVisitor<'a, 'b, 'c, 'tcx> { - fn visit_expr(&mut self, ex: &ast::Expr) { + fn visit_expr(&mut self, ex: &hir::Expr) { visit::walk_expr(self, ex); my_visit_expr(ex); } - fn visit_item(&mut self, i: &ast::Item) { + fn visit_item(&mut self, i: &hir::Item) { visit::walk_item(self, i); my_visit_item(i, self.rbml_w_for_visit_item, self.ecx, self.index); } - fn visit_foreign_item(&mut self, ni: &ast::ForeignItem) { + fn visit_foreign_item(&mut self, ni: &hir::ForeignItem) { visit::walk_foreign_item(self, ni); my_visit_foreign_item(ni, self.rbml_w_for_visit_item, @@ -1567,7 +1567,7 @@ impl<'a, 'b, 'c, 'tcx, 'v> Visitor<'v> for EncodeVisitor<'a, 'b, 'c, 'tcx> { fn encode_info_for_items(ecx: &EncodeContext, rbml_w: &mut Encoder, - krate: &ast::Crate) + krate: &hir::Crate) -> Vec { let mut index = Vec::new(); rbml_w.start_tag(tag_items_data); @@ -1582,7 +1582,7 @@ fn encode_info_for_items(ecx: &EncodeContext, CRATE_NODE_ID, [].iter().cloned().chain(LinkedPath::empty()), syntax::parse::token::special_idents::invalid.name, - ast::Public); + hir::Public); visit::walk_crate(&mut EncodeVisitor { index: &mut index, @@ -1644,10 +1644,10 @@ fn encode_attributes(rbml_w: &mut Encoder, attrs: &[ast::Attribute]) { rbml_w.end_tag(); } -fn encode_unsafety(rbml_w: &mut Encoder, unsafety: ast::Unsafety) { +fn encode_unsafety(rbml_w: &mut Encoder, unsafety: hir::Unsafety) { let byte: u8 = match unsafety { - ast::Unsafety::Normal => 0, - ast::Unsafety::Unsafe => 1, + hir::Unsafety::Normal => 0, + hir::Unsafety::Unsafe => 1, }; rbml_w.wr_tagged_u8(tag_unsafety, byte); } @@ -1670,10 +1670,10 @@ fn encode_associated_type_names(rbml_w: &mut Encoder, names: &[Name]) { rbml_w.end_tag(); } -fn encode_polarity(rbml_w: &mut Encoder, polarity: ast::ImplPolarity) { +fn encode_polarity(rbml_w: &mut Encoder, polarity: hir::ImplPolarity) { let byte: u8 = match polarity { - ast::ImplPolarity::Positive => 0, - ast::ImplPolarity::Negative => 1, + hir::ImplPolarity::Positive => 0, + hir::ImplPolarity::Negative => 1, }; rbml_w.wr_tagged_u8(tag_polarity, byte); } @@ -1782,7 +1782,7 @@ fn encode_codemap(ecx: &EncodeContext, rbml_w: &mut Encoder) { /// Serialize the text of the exported macros fn encode_macro_defs(rbml_w: &mut Encoder, - krate: &ast::Crate) { + krate: &hir::Crate) { rbml_w.start_tag(tag_macro_defs); for def in &krate.exported_macros { rbml_w.start_tag(tag_macro_def); @@ -1798,13 +1798,13 @@ fn encode_macro_defs(rbml_w: &mut Encoder, rbml_w.end_tag(); } -fn encode_struct_field_attrs(rbml_w: &mut Encoder, krate: &ast::Crate) { +fn encode_struct_field_attrs(rbml_w: &mut Encoder, krate: &hir::Crate) { struct StructFieldVisitor<'a, 'b:'a> { rbml_w: &'a mut Encoder<'b>, } impl<'a, 'b, 'v> Visitor<'v> for StructFieldVisitor<'a, 'b> { - fn visit_struct_field(&mut self, field: &ast::StructField) { + fn visit_struct_field(&mut self, field: &hir::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); @@ -1827,8 +1827,8 @@ struct ImplVisitor<'a, 'b:'a, 'c:'a, 'tcx:'b> { } impl<'a, 'b, 'c, 'tcx, 'v> Visitor<'v> for ImplVisitor<'a, 'b, 'c, 'tcx> { - fn visit_item(&mut self, item: &ast::Item) { - if let ast::ItemImpl(_, _, _, Some(ref trait_ref), _, _) = item.node { + fn visit_item(&mut self, item: &hir::Item) { + if let hir::ItemImpl(_, _, _, Some(ref trait_ref), _, _) = item.node { let def_id = self.ecx.tcx.def_map.borrow().get(&trait_ref.ref_id).unwrap().def_id(); // Load eagerly if this is an implementation of the Drop trait @@ -1856,7 +1856,7 @@ impl<'a, 'b, 'c, 'tcx, 'v> Visitor<'v> for ImplVisitor<'a, 'b, 'c, 'tcx> { /// /// * Implementations of traits not defined in this crate. fn encode_impls<'a>(ecx: &'a EncodeContext, - krate: &ast::Crate, + krate: &hir::Crate, rbml_w: &'a mut Encoder) { rbml_w.start_tag(tag_impls); @@ -1872,7 +1872,7 @@ fn encode_impls<'a>(ecx: &'a EncodeContext, } fn encode_misc_info(ecx: &EncodeContext, - krate: &ast::Crate, + krate: &hir::Crate, rbml_w: &mut Encoder) { rbml_w.start_tag(tag_misc_info); rbml_w.start_tag(tag_misc_info_crate_items); @@ -1956,7 +1956,7 @@ fn encode_dylib_dependency_formats(rbml_w: &mut Encoder, ecx: &EncodeContext) { #[allow(non_upper_case_globals)] pub const metadata_encoding_version : &'static [u8] = &[b'r', b'u', b's', b't', 0, 0, 0, 2 ]; -pub fn encode_metadata(parms: EncodeParams, krate: &ast::Crate) -> Vec { +pub fn encode_metadata(parms: EncodeParams, krate: &hir::Crate) -> Vec { let mut wr = Cursor::new(Vec::new()); encode_metadata_inner(&mut wr, parms, krate); @@ -1995,7 +1995,7 @@ pub fn encode_metadata(parms: EncodeParams, krate: &ast::Crate) -> Vec { fn encode_metadata_inner(wr: &mut Cursor>, parms: EncodeParams, - krate: &ast::Crate) { + krate: &hir::Crate) { struct Stats { attr_bytes: u64, dep_bytes: u64, diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index 2f481f70aafe9..99d1eaebdb251 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -308,23 +308,28 @@ impl<'a> Context<'a> { } pub fn report_load_errs(&mut self) { - let message = if !self.rejected_via_hash.is_empty() { - format!("found possibly newer version of crate `{}`", - self.ident) + let add = match self.root { + &None => String::new(), + &Some(ref r) => format!(" which `{}` depends on", + r.ident) + }; + if !self.rejected_via_hash.is_empty() { + span_err!(self.sess, self.span, E0460, + "found possibly newer version of crate `{}`{}", + self.ident, add); } else if !self.rejected_via_triple.is_empty() { - format!("couldn't find crate `{}` with expected target triple {}", - self.ident, self.triple) + span_err!(self.sess, self.span, E0461, + "couldn't find crate `{}` with expected target triple {}{}", + self.ident, self.triple, add); } else if !self.rejected_via_kind.is_empty() { - format!("found staticlib `{}` instead of rlib or dylib", self.ident) + span_err!(self.sess, self.span, E0462, + "found staticlib `{}` instead of rlib or dylib{}", + self.ident, add); } else { - format!("can't find crate for `{}`", self.ident) - }; - let message = match self.root { - &None => message, - &Some(ref r) => format!("{} which `{}` depends on", - message, r.ident) - }; - self.sess.span_err(self.span, &message[..]); + span_err!(self.sess, self.span, E0463, + "can't find crate for `{}`{}", + self.ident, add); + } if !self.rejected_via_triple.is_empty() { let mismatches = self.rejected_via_triple.iter(); @@ -473,9 +478,9 @@ impl<'a> Context<'a> { 0 => None, 1 => Some(libraries.into_iter().next().unwrap()), _ => { - self.sess.span_err(self.span, - &format!("multiple matching crates for `{}`", - self.crate_name)); + span_err!(self.sess, self.span, E0464, + "multiple matching crates for `{}`", + self.crate_name); self.sess.note("candidates:"); for lib in &libraries { match lib.dylib { @@ -543,11 +548,9 @@ impl<'a> Context<'a> { } }; if ret.is_some() { - self.sess.span_err(self.span, - &format!("multiple {} candidates for `{}` \ - found", - flavor, - self.crate_name)); + span_err!(self.sess, self.span, E0465, + "multiple {} candidates for `{}` found", + flavor, self.crate_name); self.sess.span_note(self.span, &format!(r"candidate #1: {}", ret.as_ref().unwrap().0 diff --git a/src/librustc/metadata/macro_import.rs b/src/librustc/metadata/macro_import.rs index 527f5919e2ddc..ca5999afbd3af 100644 --- a/src/librustc/metadata/macro_import.rs +++ b/src/librustc/metadata/macro_import.rs @@ -21,7 +21,6 @@ use syntax::attr; use syntax::visit; use syntax::visit::Visitor; use syntax::attr::AttrMetaMethods; -use rustc_front::attr::AttrMetaMethods as FrontAttrMetaMethods; struct MacroLoader<'a> { sess: &'a Session, @@ -41,6 +40,10 @@ impl<'a> MacroLoader<'a> { } } +pub fn call_bad_macro_reexport(a: &Session, b: Span) { + span_err!(a, b, E0467, "bad macro reexport"); +} + /// Read exported macros. pub fn read_macro_defs(sess: &Session, krate: &ast::Crate) -> Vec { let mut loader = MacroLoader::new(sess); @@ -91,7 +94,7 @@ impl<'a, 'v> Visitor<'v> for MacroLoader<'a> { if let ast::MetaWord(ref name) = attr.node { sel.insert(name.clone(), attr.span); } else { - self.sess.span_err(attr.span, "bad macro import"); + span_err!(self.sess, attr.span, E0466, "bad macro import"); } } } @@ -100,7 +103,7 @@ impl<'a, 'v> Visitor<'v> for MacroLoader<'a> { let names = match attr.meta_item_list() { Some(names) => names, None => { - self.sess.span_err(attr.span, "bad macro reexport"); + call_bad_macro_reexport(self.sess, attr.span); continue; } }; @@ -109,7 +112,7 @@ impl<'a, 'v> Visitor<'v> for MacroLoader<'a> { if let ast::MetaWord(ref name) = attr.node { reexport.insert(name.clone(), attr.span); } else { - self.sess.span_err(attr.span, "bad macro reexport"); + call_bad_macro_reexport(self.sess, attr.span); } } } @@ -141,8 +144,8 @@ impl<'a> MacroLoader<'a> { } if !self.span_whitelist.contains(&vi.span) { - self.sess.span_err(vi.span, "an `extern crate` loading macros must be at \ - the crate root"); + span_err!(self.sess, vi.span, E0468, + "an `extern crate` loading macros must be at the crate root"); return; } @@ -167,14 +170,16 @@ impl<'a> MacroLoader<'a> { if let Some(sel) = import.as_ref() { for (name, span) in sel { if !seen.contains(&name) { - self.sess.span_err(*span, "imported macro not found"); + span_err!(self.sess, *span, E0469, + "imported macro not found"); } } } for (name, span) in &reexport { if !seen.contains(&name) { - self.sess.span_err(*span, "reexported macro not found"); + span_err!(self.sess, *span, E0470, + "reexported macro not found"); } } } diff --git a/src/librustc/metadata/tyencode.rs b/src/librustc/metadata/tyencode.rs index d7554c4cf7501..3176f5c9cc42f 100644 --- a/src/librustc/metadata/tyencode.rs +++ b/src/librustc/metadata/tyencode.rs @@ -27,6 +27,7 @@ use util::nodemap::FnvHashMap; use rustc_front::hir; use syntax::abi::Abi; +use syntax::ast; use syntax::diagnostic::SpanHandler; use rbml::writer::Encoder; @@ -65,26 +66,26 @@ pub fn enc_ty<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, t: Ty<'tcx>) { ty::TyChar => mywrite!(w, "c"), ty::TyInt(t) => { match t { - hir::TyIs => mywrite!(w, "is"), - hir::TyI8 => mywrite!(w, "MB"), - hir::TyI16 => mywrite!(w, "MW"), - hir::TyI32 => mywrite!(w, "ML"), - hir::TyI64 => mywrite!(w, "MD") + ast::TyIs => mywrite!(w, "is"), + ast::TyI8 => mywrite!(w, "MB"), + ast::TyI16 => mywrite!(w, "MW"), + ast::TyI32 => mywrite!(w, "ML"), + ast::TyI64 => mywrite!(w, "MD") } } ty::TyUint(t) => { match t { - hir::TyUs => mywrite!(w, "us"), - hir::TyU8 => mywrite!(w, "Mb"), - hir::TyU16 => mywrite!(w, "Mw"), - hir::TyU32 => mywrite!(w, "Ml"), - hir::TyU64 => mywrite!(w, "Md") + ast::TyUs => mywrite!(w, "us"), + ast::TyU8 => mywrite!(w, "Mb"), + ast::TyU16 => mywrite!(w, "Mw"), + ast::TyU32 => mywrite!(w, "Ml"), + ast::TyU64 => mywrite!(w, "Md") } } ty::TyFloat(t) => { match t { - hir::TyF32 => mywrite!(w, "Mf"), - hir::TyF64 => mywrite!(w, "MF"), + ast::TyF32 => mywrite!(w, "Mf"), + ast::TyF64 => mywrite!(w, "MF"), } } ty::TyEnum(def, substs) => { diff --git a/src/librustc/middle/cfg/construct.rs b/src/librustc/middle/cfg/construct.rs index 3f6385ad82cc4..60aebd9cd4226 100644 --- a/src/librustc/middle/cfg/construct.rs +++ b/src/librustc/middle/cfg/construct.rs @@ -354,7 +354,6 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { hir::ExprAddrOf(_, ref e) | hir::ExprCast(ref e, _) | hir::ExprUnary(_, ref e) | - hir::ExprParen(ref e) | hir::ExprField(ref e, _) | hir::ExprTupField(ref e, _) => { self.straightline(expr, pred, Some(&**e).into_iter()) diff --git a/src/librustc/middle/check_const.rs b/src/librustc/middle/check_const.rs index 661299cd7f3fc..7da2c8f1492df 100644 --- a/src/librustc/middle/check_const.rs +++ b/src/librustc/middle/check_const.rs @@ -499,9 +499,9 @@ impl<'a, 'tcx, 'v> Visitor<'v> for CheckCrateVisitor<'a, 'tcx> { if self.qualif.intersects(ConstQualif::MUTABLE_MEM) && tc.interior_unsafe() { outer = outer | ConstQualif::NOT_CONST; if self.mode != Mode::Var { - self.tcx.sess.span_err(ex.span, - "cannot borrow a constant which contains \ - interior mutability, create a static instead"); + span_err!(self.tcx.sess, ex.span, E0492, + "cannot borrow a constant which contains \ + interior mutability, create a static instead"); } } // If the reference has to be 'static, avoid in-place initialization @@ -548,9 +548,9 @@ fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, ty::TyEnum(def, _) if def.has_dtor() => { v.add_qualif(ConstQualif::NEEDS_DROP); if v.mode != Mode::Var { - v.tcx.sess.span_err(e.span, - &format!("{}s are not allowed to have destructors", - v.msg())); + span_err!(v.tcx.sess, e.span, E0493, + "{}s are not allowed to have destructors", + v.msg()); } } _ => {} @@ -678,7 +678,6 @@ fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, let mut callee = &**callee; loop { callee = match callee.node { - hir::ExprParen(ref inner) => &**inner, hir::ExprBlock(ref block) => match block.expr { Some(ref tail) => &**tail, None => break @@ -763,7 +762,6 @@ fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, hir::ExprField(..) | hir::ExprTupField(..) | hir::ExprVec(_) | - hir::ExprParen(..) | hir::ExprTup(..) => {} // Conditional control flow (possible to implement). @@ -909,9 +907,9 @@ impl<'a, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'tcx> { // Borrowed statics can specifically *only* have their address taken, // not any number of other borrows such as borrowing fields, reading // elements of an array, etc. - self.tcx.sess.span_err(borrow_span, - "cannot refer to the interior of another \ - static, use a constant instead"); + span_err!(self.tcx.sess, borrow_span, E0494, + "cannot refer to the interior of another \ + static, use a constant instead"); } break; } diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index 8d592c9262958..85abfc16628da 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -282,9 +282,9 @@ fn check_for_static_nan(cx: &MatchCheckCtxt, pat: &Pat) { Err(err) => { let subspan = p.span.lo <= err.span.lo && err.span.hi <= p.span.hi; - cx.tcx.sess.span_err(err.span, - &format!("constant evaluation error: {}", - err.description())); + span_err!(cx.tcx.sess, err.span, E0471, + "constant evaluation error: {}", + err.description()); if !subspan { cx.tcx.sess.span_note(p.span, "in pattern here") @@ -404,7 +404,7 @@ fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, matrix: &Matrix, source: hir: fn const_val_to_expr(value: &ConstVal) -> P { let node = match value { - &ConstVal::Bool(b) => hir::LitBool(b), + &ConstVal::Bool(b) => ast::LitBool(b), _ => unreachable!() }; P(hir::Expr { diff --git a/src/librustc/middle/check_no_asm.rs b/src/librustc/middle/check_no_asm.rs index aa1b7457aa90a..b9f8f20536a13 100644 --- a/src/librustc/middle/check_no_asm.rs +++ b/src/librustc/middle/check_no_asm.rs @@ -32,8 +32,8 @@ struct CheckNoAsm<'a> { impl<'a, 'v> Visitor<'v> for CheckNoAsm<'a> { fn visit_expr(&mut self, e: &ast::Expr) { match e.node { - ast::ExprInlineAsm(_) => self.sess.span_err(e.span, - "asm! is unsupported on this target"), + ast::ExprInlineAsm(_) => span_err!(self.sess, e.span, E0472, + "asm! is unsupported on this target"), _ => {}, } visit::walk_expr(self, e) diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index e1cf6ace8432e..8f5cf36278d52 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -466,35 +466,35 @@ pub enum IntTy { I8, I16, I32, I64 } pub enum UintTy { U8, U16, U32, U64 } impl IntTy { - pub fn from(tcx: &ty::ctxt, t: hir::IntTy) -> IntTy { - let t = if let hir::TyIs = t { + pub fn from(tcx: &ty::ctxt, t: ast::IntTy) -> IntTy { + let t = if let ast::TyIs = t { tcx.sess.target.int_type } else { t }; match t { - hir::TyIs => unreachable!(), - hir::TyI8 => IntTy::I8, - hir::TyI16 => IntTy::I16, - hir::TyI32 => IntTy::I32, - hir::TyI64 => IntTy::I64, + ast::TyIs => unreachable!(), + ast::TyI8 => IntTy::I8, + ast::TyI16 => IntTy::I16, + ast::TyI32 => IntTy::I32, + ast::TyI64 => IntTy::I64, } } } impl UintTy { - pub fn from(tcx: &ty::ctxt, t: hir::UintTy) -> UintTy { - let t = if let hir::TyUs = t { + pub fn from(tcx: &ty::ctxt, t: ast::UintTy) -> UintTy { + let t = if let ast::TyUs = t { tcx.sess.target.uint_type } else { t }; match t { - hir::TyUs => unreachable!(), - hir::TyU8 => UintTy::U8, - hir::TyU16 => UintTy::U16, - hir::TyU32 => UintTy::U32, - hir::TyU64 => UintTy::U64, + ast::TyUs => unreachable!(), + ast::TyU8 => UintTy::U8, + ast::TyU16 => UintTy::U16, + ast::TyU32 => UintTy::U32, + ast::TyU64 => UintTy::U64, } } } @@ -996,7 +996,6 @@ pub fn eval_const_expr_partial<'tcx>(tcx: &ty::ctxt<'tcx>, hir::ExprLit(ref lit) => { lit_to_const(&**lit, ety) } - hir::ExprParen(ref e) => try!(eval_const_expr_partial(tcx, &**e, ty_hint)), hir::ExprBlock(ref block) => { match block.expr { Some(ref expr) => try!(eval_const_expr_partial(tcx, &**expr, ty_hint)), @@ -1141,60 +1140,60 @@ fn cast_const<'tcx>(tcx: &ty::ctxt<'tcx>, val: ConstVal, ty: Ty) -> CastResult { // Issue #23890: If isize/usize, then dispatch to appropriate target representation type match (&ty.sty, tcx.sess.target.int_type, tcx.sess.target.uint_type) { - (&ty::TyInt(hir::TyIs), hir::TyI32, _) => return convert_val!(i32, Int, i64), - (&ty::TyInt(hir::TyIs), hir::TyI64, _) => return convert_val!(i64, Int, i64), - (&ty::TyInt(hir::TyIs), _, _) => panic!("unexpected target.int_type"), + (&ty::TyInt(ast::TyIs), ast::TyI32, _) => return convert_val!(i32, Int, i64), + (&ty::TyInt(ast::TyIs), ast::TyI64, _) => return convert_val!(i64, Int, i64), + (&ty::TyInt(ast::TyIs), _, _) => panic!("unexpected target.int_type"), - (&ty::TyUint(hir::TyUs), _, hir::TyU32) => return convert_val!(u32, Uint, u64), - (&ty::TyUint(hir::TyUs), _, hir::TyU64) => return convert_val!(u64, Uint, u64), - (&ty::TyUint(hir::TyUs), _, _) => panic!("unexpected target.uint_type"), + (&ty::TyUint(ast::TyUs), _, ast::TyU32) => return convert_val!(u32, Uint, u64), + (&ty::TyUint(ast::TyUs), _, ast::TyU64) => return convert_val!(u64, Uint, u64), + (&ty::TyUint(ast::TyUs), _, _) => panic!("unexpected target.uint_type"), _ => {} } match ty.sty { - ty::TyInt(hir::TyIs) => unreachable!(), - ty::TyUint(hir::TyUs) => unreachable!(), + ty::TyInt(ast::TyIs) => unreachable!(), + ty::TyUint(ast::TyUs) => unreachable!(), - ty::TyInt(hir::TyI8) => convert_val!(i8, Int, i64), - ty::TyInt(hir::TyI16) => convert_val!(i16, Int, i64), - ty::TyInt(hir::TyI32) => convert_val!(i32, Int, i64), - ty::TyInt(hir::TyI64) => convert_val!(i64, Int, i64), + ty::TyInt(ast::TyI8) => convert_val!(i8, Int, i64), + ty::TyInt(ast::TyI16) => convert_val!(i16, Int, i64), + ty::TyInt(ast::TyI32) => convert_val!(i32, Int, i64), + ty::TyInt(ast::TyI64) => convert_val!(i64, Int, i64), - ty::TyUint(hir::TyU8) => convert_val!(u8, Uint, u64), - ty::TyUint(hir::TyU16) => convert_val!(u16, Uint, u64), - ty::TyUint(hir::TyU32) => convert_val!(u32, Uint, u64), - ty::TyUint(hir::TyU64) => convert_val!(u64, Uint, u64), + ty::TyUint(ast::TyU8) => convert_val!(u8, Uint, u64), + ty::TyUint(ast::TyU16) => convert_val!(u16, Uint, u64), + ty::TyUint(ast::TyU32) => convert_val!(u32, Uint, u64), + ty::TyUint(ast::TyU64) => convert_val!(u64, Uint, u64), - ty::TyFloat(hir::TyF32) => convert_val!(f32, Float, f64), - ty::TyFloat(hir::TyF64) => convert_val!(f64, Float, f64), + ty::TyFloat(ast::TyF32) => convert_val!(f32, Float, f64), + ty::TyFloat(ast::TyF64) => convert_val!(f64, Float, f64), _ => Err(ErrKind::CannotCast), } } -fn lit_to_const(lit: &hir::Lit, ty_hint: Option) -> ConstVal { +fn lit_to_const(lit: &ast::Lit, ty_hint: Option) -> ConstVal { match lit.node { - hir::LitStr(ref s, _) => Str((*s).clone()), - hir::LitByteStr(ref data) => { + ast::LitStr(ref s, _) => Str((*s).clone()), + ast::LitByteStr(ref data) => { ByteStr(data.clone()) } - hir::LitByte(n) => Uint(n as u64), - hir::LitChar(n) => Uint(n as u64), - hir::LitInt(n, hir::SignedIntLit(_, hir::Plus)) => Int(n as i64), - hir::LitInt(n, hir::UnsuffixedIntLit(hir::Plus)) => { + ast::LitByte(n) => Uint(n as u64), + ast::LitChar(n) => Uint(n as u64), + ast::LitInt(n, ast::SignedIntLit(_, ast::Plus)) => Int(n as i64), + ast::LitInt(n, ast::UnsuffixedIntLit(ast::Plus)) => { match ty_hint.map(|ty| &ty.sty) { Some(&ty::TyUint(_)) => Uint(n), _ => Int(n as i64) } } - hir::LitInt(n, hir::SignedIntLit(_, hir::Minus)) | - hir::LitInt(n, hir::UnsuffixedIntLit(hir::Minus)) => Int(-(n as i64)), - hir::LitInt(n, hir::UnsignedIntLit(_)) => Uint(n), - hir::LitFloat(ref n, _) | - hir::LitFloatUnsuffixed(ref n) => { + ast::LitInt(n, ast::SignedIntLit(_, ast::Minus)) | + ast::LitInt(n, ast::UnsuffixedIntLit(ast::Minus)) => Int(-(n as i64)), + ast::LitInt(n, ast::UnsignedIntLit(_)) => Uint(n), + ast::LitFloat(ref n, _) | + ast::LitFloatUnsuffixed(ref n) => { Float(n.parse::().unwrap() as f64) } - hir::LitBool(b) => Bool(b) + ast::LitBool(b) => Bool(b) } } diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index 14ba241f62b0f..132efc1ff8826 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -24,6 +24,7 @@ use std::usize; use syntax::ast; use syntax::ast_util::IdRange; use syntax::print::pp; +use syntax::print::pprust::PrintState; use util::nodemap::NodeMap; use rustc_front::hir; use rustc_front::visit; diff --git a/src/librustc/middle/dead.rs b/src/librustc/middle/dead.rs index ed9ca48b39ca2..182bc067a7fc1 100644 --- a/src/librustc/middle/dead.rs +++ b/src/librustc/middle/dead.rs @@ -15,7 +15,6 @@ use front::map as ast_map; use rustc_front::hir; use rustc_front::visit::{self, Visitor}; -use rustc_front::attr::{self, AttrMetaMethods}; use middle::{def, pat_util, privacy, ty}; use middle::def_id::{DefId}; @@ -24,6 +23,7 @@ use util::nodemap::NodeSet; use std::collections::HashSet; use syntax::{ast, codemap}; +use syntax::attr::{self, AttrMetaMethods}; // Any local node that may call something in its body block should be // explored. For example, if it's a live NodeItem that is a @@ -285,13 +285,13 @@ impl<'a, 'tcx, 'v> Visitor<'v> for MarkSymbolVisitor<'a, 'tcx> { } } -fn has_allow_dead_code_or_lang_attr(attrs: &[hir::Attribute]) -> bool { +fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool { if attr::contains_name(attrs, "lang") { return true; } let dead_code = lint::builtin::DEAD_CODE.name_lower(); - for attr in lint::gather_attrs_from_hir(attrs) { + for attr in lint::gather_attrs(attrs) { match attr { Ok((ref name, lint::Allow, _)) if &name[..] == dead_code => return true, diff --git a/src/librustc/middle/entry.rs b/src/librustc/middle/entry.rs index e32a9b280f3d5..841859ffec42c 100644 --- a/src/librustc/middle/entry.rs +++ b/src/librustc/middle/entry.rs @@ -12,10 +12,10 @@ use front::map as ast_map; use session::{config, Session}; use syntax::ast::NodeId; -use rustc_front::hir::{Item, ItemFn}; -use rustc_front::attr; +use syntax::attr; use syntax::codemap::Span; use syntax::entry::EntryPointType; +use rustc_front::hir::{Item, ItemFn}; use rustc_front::visit; use rustc_front::visit::Visitor; diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index a8fed5eab16be..c067c9b4d6313 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -362,9 +362,6 @@ impl<'d,'t,'a,'tcx> ExprUseVisitor<'d,'t,'a,'tcx> { let cmt = return_if_err!(self.mc.cat_expr(expr)); self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause); - // Note: Unlike consume, we can ignore ExprParen. cat_expr - // already skips over them, and walk will uncover any - // attachments or whatever. self.walk_expr(expr) } @@ -378,10 +375,6 @@ impl<'d,'t,'a,'tcx> ExprUseVisitor<'d,'t,'a,'tcx> { self.walk_adjustment(expr); match expr.node { - hir::ExprParen(ref subexpr) => { - self.walk_expr(&**subexpr) - } - hir::ExprPath(..) => { } hir::ExprUnary(hir::UnDeref, ref base) => { // *base diff --git a/src/librustc/middle/infer/combine.rs b/src/librustc/middle/infer/combine.rs index 2447a8cee7bbb..03554a59655b1 100644 --- a/src/librustc/middle/infer/combine.rs +++ b/src/librustc/middle/infer/combine.rs @@ -48,8 +48,8 @@ use middle::ty::error::TypeError; use middle::ty::fold::{TypeFolder, TypeFoldable}; use middle::ty::relate::{Relate, RelateResult, TypeRelation}; +use syntax::ast; use syntax::codemap::Span; -use rustc_front::hir; #[derive(Clone)] pub struct CombineFields<'a, 'tcx: 'a> { @@ -138,7 +138,7 @@ fn unify_integral_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, fn unify_float_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, vid_is_expected: bool, vid: ty::FloatVid, - val: hir::FloatTy) + val: ast::FloatTy) -> RelateResult<'tcx, Ty<'tcx>> { try!(infcx @@ -388,7 +388,7 @@ fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::Int } fn float_unification_error<'tcx>(a_is_expected: bool, - v: (hir::FloatTy, hir::FloatTy)) + v: (ast::FloatTy, ast::FloatTy)) -> TypeError<'tcx> { let (a, b) = v; diff --git a/src/librustc/middle/infer/error_reporting.rs b/src/librustc/middle/infer/error_reporting.rs index f0fa7d7cdf851..69911c7683d8a 100644 --- a/src/librustc/middle/infer/error_reporting.rs +++ b/src/librustc/middle/infer/error_reporting.rs @@ -718,20 +718,17 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { ""); } infer::DerefPointer(span) => { - self.tcx.sess.span_err( - span, - "dereference of reference outside its lifetime"); + span_err!(self.tcx.sess, span, E0473, + "dereference of reference outside its lifetime"); self.tcx.note_and_explain_region( "the reference is only valid for ", sup, ""); } infer::FreeVariable(span, id) => { - self.tcx.sess.span_err( - span, - &format!("captured variable `{}` does not \ - outlive the enclosing closure", - self.tcx.local_var_name_str(id))); + span_err!(self.tcx.sess, span, E0474, + "captured variable `{}` does not outlive the enclosing closure", + self.tcx.local_var_name_str(id)); self.tcx.note_and_explain_region( "captured variable is valid for ", sup, @@ -742,18 +739,17 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { ""); } infer::IndexSlice(span) => { - self.tcx.sess.span_err(span, - "index of slice outside its lifetime"); + span_err!(self.tcx.sess, span, E0475, + "index of slice outside its lifetime"); self.tcx.note_and_explain_region( "the slice is only valid for ", sup, ""); } infer::RelateObjectBound(span) => { - self.tcx.sess.span_err( - span, - "lifetime of the source pointer does not outlive \ - lifetime bound of the object type"); + span_err!(self.tcx.sess, span, E0476, + "lifetime of the source pointer does not outlive \ + lifetime bound of the object type"); self.tcx.note_and_explain_region( "object type is valid for ", sub, @@ -764,20 +760,17 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { ""); } infer::RelateParamBound(span, ty) => { - self.tcx.sess.span_err( - span, - &format!("the type `{}` does not fulfill the \ - required lifetime", - self.ty_to_string(ty))); + span_err!(self.tcx.sess, span, E0477, + "the type `{}` does not fulfill the required lifetime", + self.ty_to_string(ty)); self.tcx.note_and_explain_region( "type must outlive ", sub, ""); } infer::RelateRegionParamBound(span) => { - self.tcx.sess.span_err( - span, - "lifetime bound not satisfied"); + span_err!(self.tcx.sess, span, E0478, + "lifetime bound not satisfied"); self.tcx.note_and_explain_region( "lifetime parameter instantiated with ", sup, @@ -788,92 +781,82 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { ""); } infer::RelateDefaultParamBound(span, ty) => { - self.tcx.sess.span_err( - span, - &format!("the type `{}` (provided as the value of \ - a type parameter) is not valid at this point", - self.ty_to_string(ty))); + span_err!(self.tcx.sess, span, E0479, + "the type `{}` (provided as the value of \ + a type parameter) is not valid at this point", + self.ty_to_string(ty)); self.tcx.note_and_explain_region( "type must outlive ", sub, ""); } infer::CallRcvr(span) => { - self.tcx.sess.span_err( - span, - "lifetime of method receiver does not outlive \ - the method call"); + span_err!(self.tcx.sess, span, E0480, + "lifetime of method receiver does not outlive \ + the method call"); self.tcx.note_and_explain_region( "the receiver is only valid for ", sup, ""); } infer::CallArg(span) => { - self.tcx.sess.span_err( - span, - "lifetime of function argument does not outlive \ - the function call"); + span_err!(self.tcx.sess, span, E0481, + "lifetime of function argument does not outlive \ + the function call"); self.tcx.note_and_explain_region( "the function argument is only valid for ", sup, ""); } infer::CallReturn(span) => { - self.tcx.sess.span_err( - span, - "lifetime of return value does not outlive \ - the function call"); + span_err!(self.tcx.sess, span, E0482, + "lifetime of return value does not outlive \ + the function call"); self.tcx.note_and_explain_region( "the return value is only valid for ", sup, ""); } infer::Operand(span) => { - self.tcx.sess.span_err( - span, - "lifetime of operand does not outlive \ - the operation"); + span_err!(self.tcx.sess, span, E0483, + "lifetime of operand does not outlive \ + the operation"); self.tcx.note_and_explain_region( "the operand is only valid for ", sup, ""); } infer::AddrOf(span) => { - self.tcx.sess.span_err( - span, - "reference is not valid \ - at the time of borrow"); + span_err!(self.tcx.sess, span, E0484, + "reference is not valid at the time of borrow"); self.tcx.note_and_explain_region( "the borrow is only valid for ", sup, ""); } infer::AutoBorrow(span) => { - self.tcx.sess.span_err( - span, - "automatically reference is not valid \ - at the time of borrow"); + span_err!(self.tcx.sess, span, E0485, + "automatically reference is not valid \ + at the time of borrow"); self.tcx.note_and_explain_region( "the automatic borrow is only valid for ", sup, ""); } infer::ExprTypeIsNotInScope(t, span) => { - self.tcx.sess.span_err( - span, - &format!("type of expression contains references \ - that are not valid during the expression: `{}`", - self.ty_to_string(t))); + span_err!(self.tcx.sess, span, E0486, + "type of expression contains references \ + that are not valid during the expression: `{}`", + self.ty_to_string(t)); self.tcx.note_and_explain_region( "type is only valid for ", sup, ""); } infer::SafeDestructor(span) => { - self.tcx.sess.span_err( - span, - "unsafe use of destructor: destructor might be called \ - while references are dead"); + span_err!(self.tcx.sess, span, E0487, + "unsafe use of destructor: destructor might be called \ + while references are dead"); // FIXME (22171): terms "super/subregion" are suboptimal self.tcx.note_and_explain_region( "superregion: ", @@ -885,37 +868,33 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { ""); } infer::BindingTypeIsNotValidAtDecl(span) => { - self.tcx.sess.span_err( - span, - "lifetime of variable does not enclose its declaration"); + span_err!(self.tcx.sess, span, E0488, + "lifetime of variable does not enclose its declaration"); self.tcx.note_and_explain_region( "the variable is only valid for ", sup, ""); } infer::ParameterInScope(_, span) => { - self.tcx.sess.span_err( - span, - &format!("type/lifetime parameter not in scope here")); + span_err!(self.tcx.sess, span, E0489, + "type/lifetime parameter not in scope here"); self.tcx.note_and_explain_region( "the parameter is only valid for ", sub, ""); } infer::DataBorrowed(ty, span) => { - self.tcx.sess.span_err( - span, - &format!("a value of type `{}` is borrowed for too long", - self.ty_to_string(ty))); + span_err!(self.tcx.sess, span, E0490, + "a value of type `{}` is borrowed for too long", + self.ty_to_string(ty)); self.tcx.note_and_explain_region("the type is valid for ", sub, ""); self.tcx.note_and_explain_region("but the borrow lasts for ", sup, ""); } infer::ReferenceOutlivesReferent(ty, span) => { - self.tcx.sess.span_err( - span, - &format!("in type `{}`, reference has a longer lifetime \ - than the data it references", - self.ty_to_string(ty))); + span_err!(self.tcx.sess, span, E0491, + "in type `{}`, reference has a longer lifetime \ + than the data it references", + self.ty_to_string(ty)); self.tcx.note_and_explain_region( "the pointer is valid for ", sub, @@ -1648,11 +1627,10 @@ impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> { } }; - self.tcx.sess.span_err( - var_origin.span(), - &format!("cannot infer an appropriate lifetime{} \ - due to conflicting requirements", - var_description)); + span_err!(self.tcx.sess, var_origin.span(), E0495, + "cannot infer an appropriate lifetime{} \ + due to conflicting requirements", + var_description); } fn note_region_origin(&self, origin: &SubregionOrigin<'tcx>) { @@ -1779,7 +1757,7 @@ impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> { "...so that return value is valid for the call"); } infer::Operand(span) => { - self.tcx.sess.span_err( + self.tcx.sess.span_note( span, "...so that operand is valid for operation"); } diff --git a/src/librustc/middle/infer/unify_key.rs b/src/librustc/middle/infer/unify_key.rs index 6bb46ac787073..41aa191ac24d2 100644 --- a/src/librustc/middle/infer/unify_key.rs +++ b/src/librustc/middle/infer/unify_key.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use syntax::ast; use middle::ty::{self, IntVarValue, Ty}; use rustc_data_structures::unify::UnifyKey; -use rustc_front::hir as ast; pub trait ToType<'tcx> { fn to_type(&self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx>; diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index a34571e4acac7..f0aa824c589d3 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -28,7 +28,8 @@ use middle::ty; use middle::weak_lang_items; use util::nodemap::FnvHashMap; -use rustc_front::attr::AttrMetaMethods; +use syntax::ast; +use syntax::attr::AttrMetaMethods; use syntax::codemap::{DUMMY_SP, Span}; use syntax::parse::token::InternedString; use rustc_front::visit::Visitor; @@ -216,7 +217,7 @@ impl<'a> LanguageItemCollector<'a> { } } -pub fn extract(attrs: &[hir::Attribute]) -> Option { +pub fn extract(attrs: &[ast::Attribute]) -> Option { for attribute in attrs { match attribute.value_str() { Some(ref value) if attribute.check_name("lang") => { diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 561760b29f19e..9bb19bb37d8e4 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -495,7 +495,7 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) { hir::ExprAgain(_) | hir::ExprLit(_) | hir::ExprRet(..) | hir::ExprBlock(..) | hir::ExprAssign(..) | hir::ExprAssignOp(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) | - hir::ExprParen(..) | hir::ExprInlineAsm(..) | hir::ExprBox(..) | + hir::ExprInlineAsm(..) | hir::ExprBox(..) | hir::ExprRange(..) => { visit::walk_expr(ir, expr); } @@ -1161,8 +1161,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { hir::ExprBox(None, ref e) | hir::ExprAddrOf(_, ref e) | hir::ExprCast(ref e, _) | - hir::ExprUnary(_, ref e) | - hir::ExprParen(ref e) => { + hir::ExprUnary(_, ref e) => { self.propagate_through_expr(&**e, succ) } @@ -1435,7 +1434,7 @@ fn check_expr(this: &mut Liveness, expr: &Expr) { hir::ExprCast(..) | hir::ExprUnary(..) | hir::ExprRet(..) | hir::ExprBreak(..) | hir::ExprAgain(..) | hir::ExprLit(_) | hir::ExprBlock(..) | hir::ExprAddrOf(..) | - hir::ExprStruct(..) | hir::ExprRepeat(..) | hir::ExprParen(..) | + hir::ExprStruct(..) | hir::ExprRepeat(..) | hir::ExprClosure(..) | hir::ExprPath(..) | hir::ExprBox(..) | hir::ExprRange(..) => { visit::walk_expr(this, expr); diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index dd2f48d25b4b0..2078ee2c57b8f 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -519,10 +519,6 @@ impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> { self.cat_def(expr.id, expr.span, expr_ty, def) } - hir::ExprParen(ref e) => { - self.cat_expr(&**e) - } - hir::ExprAddrOf(..) | hir::ExprCall(..) | hir::ExprAssign(..) | hir::ExprAssignOp(..) | hir::ExprClosure(..) | hir::ExprRet(..) | diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index 215368754c999..3fb3d575f93c6 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -26,8 +26,8 @@ use util::nodemap::NodeSet; use std::collections::HashSet; use syntax::abi; use syntax::ast; +use syntax::attr; use rustc_front::hir; -use rustc_front::attr; use rustc_front::visit::Visitor; use rustc_front::visit; diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index f08cbb4143851..c26982ff5ede1 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -997,8 +997,7 @@ fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &hir::Local) { hir::ExprUnary(hir::UnUniq, ref subexpr) => { record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id); } - hir::ExprCast(ref subexpr, _) | - hir::ExprParen(ref subexpr) => { + hir::ExprCast(ref subexpr, _) => { record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id) } hir::ExprBlock(ref block) => { @@ -1047,8 +1046,7 @@ fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &hir::Local) { hir::ExprUnary(hir::UnDeref, ref subexpr) | hir::ExprField(ref subexpr, _) | hir::ExprTupField(ref subexpr, _) | - hir::ExprIndex(ref subexpr, _) | - hir::ExprParen(ref subexpr) => { + hir::ExprIndex(ref subexpr, _) => { expr = &**subexpr; } _ => { diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 73b3b32f64871..c21999c2dbc32 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -357,10 +357,10 @@ fn signal_shadowing_problem( sess: &Session, name: ast::Name, orig: Original, shadower: Shadower) { if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) { // lifetime/lifetime shadowing is an error - sess.span_err(shadower.span, - &format!("{} name `{}` shadows a \ - {} name that is already in scope", - shadower.kind.desc(), name, orig.kind.desc())); + span_err!(sess, shadower.span, E0496, + "{} name `{}` shadows a \ + {} name that is already in scope", + shadower.kind.desc(), name, orig.kind.desc()); } else { // shadowing involving a label is only a warning, due to issues with // labels and lifetimes not being macro-hygienic. diff --git a/src/librustc/middle/stability.rs b/src/librustc/middle/stability.rs index 9c4697404201e..e29d432707104 100644 --- a/src/librustc/middle/stability.rs +++ b/src/librustc/middle/stability.rs @@ -21,13 +21,13 @@ use metadata::csearch; use syntax::parse::token::InternedString; use syntax::codemap::{Span, DUMMY_SP}; use syntax::ast; -use syntax::ast::NodeId; +use syntax::ast::{NodeId, Attribute}; use syntax::feature_gate::{GateIssue, emit_feature_err}; +use syntax::attr::{self, Stability, AttrMetaMethods}; use util::nodemap::{DefIdMap, FnvHashSet, FnvHashMap}; use rustc_front::hir; -use rustc_front::hir::{FnDecl, Attribute, Block, Crate, Item, Generics, StructField, Variant}; -use rustc_front::attr::{self, Stability, AttrMetaMethods}; +use rustc_front::hir::{FnDecl, Block, Crate, Item, Generics, StructField, Variant}; use rustc_front::visit::{self, FnKind, Visitor}; use std::mem::replace; @@ -237,7 +237,7 @@ impl<'tcx> Index<'tcx> { for attr in &krate.attrs { if &attr.name()[..] == "staged_api" { match attr.node.value.node { - hir::MetaWord(_) => { + ast::MetaWord(_) => { attr::mark_used(attr); is_staged_api = true; } diff --git a/src/librustc/middle/traits/error_reporting.rs b/src/librustc/middle/traits/error_reporting.rs index 2ed53f16afd28..5248cb7f30e97 100644 --- a/src/librustc/middle/traits/error_reporting.rs +++ b/src/librustc/middle/traits/error_reporting.rs @@ -31,7 +31,7 @@ use middle::ty::fold::TypeFoldable; use std::collections::HashMap; use std::fmt; use syntax::codemap::Span; -use rustc_front::attr::{AttributeMethods, AttrMetaMethods}; +use syntax::attr::{AttributeMethods, AttrMetaMethods}; pub fn report_fulfillment_errors<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, errors: &Vec>) { diff --git a/src/librustc/middle/ty/cast.rs b/src/librustc/middle/ty/cast.rs index 8cb4f941a2264..8233b6b2b2b6e 100644 --- a/src/librustc/middle/ty/cast.rs +++ b/src/librustc/middle/ty/cast.rs @@ -13,7 +13,7 @@ use middle::ty::{self, Ty}; -use rustc_front::hir as ast; +use syntax::ast; /// Types that are represented as ints. #[derive(Copy, Clone, Debug, PartialEq, Eq)] diff --git a/src/librustc/middle/ty/contents.rs b/src/librustc/middle/ty/contents.rs index bcce9e8ea5476..afe88f70d9450 100644 --- a/src/librustc/middle/ty/contents.rs +++ b/src/librustc/middle/ty/contents.rs @@ -16,7 +16,7 @@ use util::nodemap::FnvHashMap; use std::fmt; use std::ops; -use rustc_front::hir; +use syntax::ast; /// Type contents is how the type checker reasons about kinds. /// They track what kinds of things are found within a type. You can @@ -182,7 +182,7 @@ impl<'tcx> ty::TyS<'tcx> { let result = match ty.sty { // usize and isize are ffi-unsafe - ty::TyUint(hir::TyUs) | ty::TyInt(hir::TyIs) => { + ty::TyUint(ast::TyUs) | ty::TyInt(ast::TyIs) => { TC::None } diff --git a/src/librustc/middle/ty/context.rs b/src/librustc/middle/ty/context.rs index e3b6da56680da..31e4765aaaa60 100644 --- a/src/librustc/middle/ty/context.rs +++ b/src/librustc/middle/ty/context.rs @@ -41,11 +41,11 @@ use std::cell::{Cell, RefCell, Ref}; use std::hash::{Hash, Hasher}; use std::rc::Rc; use syntax::abi; -use syntax::ast::{Name, NodeId}; +use syntax::ast::{self, Name, NodeId}; +use syntax::attr; use syntax::parse::token::special_idents; use rustc_front::hir; -use rustc_front::attr; /// Internal storage pub struct CtxtArenas<'tcx> { @@ -146,18 +146,18 @@ impl<'tcx> CommonTypes<'tcx> { bool: mk(TyBool), char: mk(TyChar), err: mk(TyError), - isize: mk(TyInt(hir::TyIs)), - i8: mk(TyInt(hir::TyI8)), - i16: mk(TyInt(hir::TyI16)), - i32: mk(TyInt(hir::TyI32)), - i64: mk(TyInt(hir::TyI64)), - usize: mk(TyUint(hir::TyUs)), - u8: mk(TyUint(hir::TyU8)), - u16: mk(TyUint(hir::TyU16)), - u32: mk(TyUint(hir::TyU32)), - u64: mk(TyUint(hir::TyU64)), - f32: mk(TyFloat(hir::TyF32)), - f64: mk(TyFloat(hir::TyF64)), + isize: mk(TyInt(ast::TyIs)), + i8: mk(TyInt(ast::TyI8)), + i16: mk(TyInt(ast::TyI16)), + i32: mk(TyInt(ast::TyI32)), + i64: mk(TyInt(ast::TyI64)), + usize: mk(TyUint(ast::TyUs)), + u8: mk(TyUint(ast::TyU8)), + u16: mk(TyUint(ast::TyU16)), + u32: mk(TyUint(ast::TyU32)), + u64: mk(TyUint(ast::TyU64)), + f32: mk(TyFloat(ast::TyF32)), + f64: mk(TyFloat(ast::TyF64)), } } } @@ -771,30 +771,30 @@ impl<'tcx> ctxt<'tcx> { ctxt::intern_ty(&self.arenas.type_, &self.interner, st) } - pub fn mk_mach_int(&self, tm: hir::IntTy) -> Ty<'tcx> { + pub fn mk_mach_int(&self, tm: ast::IntTy) -> Ty<'tcx> { match tm { - hir::TyIs => self.types.isize, - hir::TyI8 => self.types.i8, - hir::TyI16 => self.types.i16, - hir::TyI32 => self.types.i32, - hir::TyI64 => self.types.i64, + ast::TyIs => self.types.isize, + ast::TyI8 => self.types.i8, + ast::TyI16 => self.types.i16, + ast::TyI32 => self.types.i32, + ast::TyI64 => self.types.i64, } } - pub fn mk_mach_uint(&self, tm: hir::UintTy) -> Ty<'tcx> { + pub fn mk_mach_uint(&self, tm: ast::UintTy) -> Ty<'tcx> { match tm { - hir::TyUs => self.types.usize, - hir::TyU8 => self.types.u8, - hir::TyU16 => self.types.u16, - hir::TyU32 => self.types.u32, - hir::TyU64 => self.types.u64, + ast::TyUs => self.types.usize, + ast::TyU8 => self.types.u8, + ast::TyU16 => self.types.u16, + ast::TyU32 => self.types.u32, + ast::TyU64 => self.types.u64, } } - pub fn mk_mach_float(&self, tm: hir::FloatTy) -> Ty<'tcx> { + pub fn mk_mach_float(&self, tm: ast::FloatTy) -> Ty<'tcx> { match tm { - hir::TyF32 => self.types.f32, - hir::TyF64 => self.types.f64, + ast::TyF32 => self.types.f32, + ast::TyF64 => self.types.f64, } } diff --git a/src/librustc/middle/ty/error.rs b/src/librustc/middle/ty/error.rs index 72c4366c5bcd5..ba7be3e2c9948 100644 --- a/src/librustc/middle/ty/error.rs +++ b/src/librustc/middle/ty/error.rs @@ -15,7 +15,7 @@ use middle::ty::{self, BoundRegion, Region, Ty}; use std::fmt; use syntax::abi; -use syntax::ast::Name; +use syntax::ast::{self, Name}; use syntax::codemap::Span; use rustc_front::hir; @@ -49,7 +49,7 @@ pub enum TypeError<'tcx> { Sorts(ExpectedFound>), IntegerAsChar, IntMismatch(ExpectedFound), - FloatMismatch(ExpectedFound), + FloatMismatch(ExpectedFound), Traits(ExpectedFound), BuiltinBoundsMismatch(ExpectedFound), VariadicMismatch(ExpectedFound), diff --git a/src/librustc/middle/ty/fast_reject.rs b/src/librustc/middle/ty/fast_reject.rs index 2b81be19182e2..77608f4012845 100644 --- a/src/librustc/middle/ty/fast_reject.rs +++ b/src/librustc/middle/ty/fast_reject.rs @@ -10,7 +10,7 @@ use middle::def_id::DefId; use middle::ty::{self, Ty}; -use rustc_front::hir; +use syntax::ast; use self::SimplifiedType::*; @@ -19,9 +19,9 @@ use self::SimplifiedType::*; pub enum SimplifiedType { BoolSimplifiedType, CharSimplifiedType, - IntSimplifiedType(hir::IntTy), - UintSimplifiedType(hir::UintTy), - FloatSimplifiedType(hir::FloatTy), + IntSimplifiedType(ast::IntTy), + UintSimplifiedType(ast::UintTy), + FloatSimplifiedType(ast::FloatTy), EnumSimplifiedType(DefId), StrSimplifiedType, VecSimplifiedType, diff --git a/src/librustc/middle/ty/mod.rs b/src/librustc/middle/ty/mod.rs index a8adb38864424..972f7242808b6 100644 --- a/src/librustc/middle/ty/mod.rs +++ b/src/librustc/middle/ty/mod.rs @@ -44,13 +44,13 @@ use std::slice; use std::vec::IntoIter; use std::collections::{HashMap, HashSet}; use syntax::ast::{self, CrateNum, Name, NodeId}; +use syntax::attr::{self, AttrMetaMethods}; use syntax::codemap::Span; use syntax::parse::token::{InternedString, special_idents}; use rustc_front::hir; use rustc_front::hir::{ItemImpl, ItemTrait}; use rustc_front::hir::{MutImmutable, MutMutable, Visibility}; -use rustc_front::attr::{self, AttrMetaMethods}; pub use self::sty::{Binder, DebruijnIndex}; pub use self::sty::{BuiltinBound, BuiltinBounds, ExistentialBounds}; @@ -563,8 +563,8 @@ pub struct ClosureUpvar<'tcx> { #[derive(Clone, Copy, PartialEq)] pub enum IntVarValue { - IntType(hir::IntTy), - UintType(hir::UintTy), + IntType(ast::IntTy), + UintType(ast::UintTy), } /// Default region to use for the bound of objects that are @@ -2089,8 +2089,6 @@ impl<'tcx> ctxt<'tcx> { hir::ExprCast(..) => { false } - - hir::ExprParen(ref e) => self.expr_is_lval(e), } } @@ -2337,7 +2335,7 @@ impl<'tcx> ctxt<'tcx> { } /// Get the attributes of a definition. - pub fn get_attrs(&self, did: DefId) -> Cow<'tcx, [hir::Attribute]> { + pub fn get_attrs(&self, did: DefId) -> Cow<'tcx, [ast::Attribute]> { if did.is_local() { Cow::Borrowed(self.map.attrs(did.node)) } else { diff --git a/src/librustc/middle/ty/sty.rs b/src/librustc/middle/ty/sty.rs index 3969738a22e86..44f97a6b9e3c3 100644 --- a/src/librustc/middle/ty/sty.rs +++ b/src/librustc/middle/ty/sty.rs @@ -23,7 +23,7 @@ use std::fmt; use std::ops; use std::mem; use syntax::abi; -use syntax::ast::{Name, NodeId}; +use syntax::ast::{self, Name, NodeId}; use syntax::parse::token::special_idents; use rustc_front::hir; @@ -79,13 +79,13 @@ pub enum TypeVariants<'tcx> { TyChar, /// A primitive signed integer type. For example, `i32`. - TyInt(hir::IntTy), + TyInt(ast::IntTy), /// A primitive unsigned integer type. For example, `u32`. - TyUint(hir::UintTy), + TyUint(ast::UintTy), /// A primitive floating-point type. For example, `f64`. - TyFloat(hir::FloatTy), + TyFloat(ast::FloatTy), /// An enumerated type, defined with `enum`. /// @@ -93,7 +93,7 @@ pub enum TypeVariants<'tcx> { /// That is, even after substitution it is possible that there are type /// variables. This happens when the `TyEnum` corresponds to an enum /// definition and not a concrete use of it. To get the correct `TyEnum` - /// from the tcx, use the `NodeId` from the `hir::Ty` and look it up in + /// from the tcx, use the `NodeId` from the `ast::Ty` and look it up in /// the `ast_ty_to_ty_cache`. This is probably true for `TyStruct` as /// well. TyEnum(AdtDef<'tcx>, &'tcx Substs<'tcx>), @@ -899,6 +899,14 @@ impl<'tcx> TyS<'tcx> { } } + pub fn is_phantom_data(&self) -> bool { + if let TyStruct(def, _) = self.sty { + def.is_phantom_data() + } else { + false + } + } + pub fn is_bool(&self) -> bool { self.sty == TyBool } pub fn is_param(&self, space: subst::ParamSpace, index: u32) -> bool { @@ -944,7 +952,7 @@ impl<'tcx> TyS<'tcx> { pub fn sequence_element_type(&self, cx: &ty::ctxt<'tcx>) -> Ty<'tcx> { match self.sty { TyArray(ty, _) | TySlice(ty) => ty, - TyStr => cx.mk_mach_uint(hir::TyU8), + TyStr => cx.mk_mach_uint(ast::TyU8), _ => cx.sess.bug(&format!("sequence_element_type called on non-sequence value: {}", self)), } @@ -1035,7 +1043,7 @@ impl<'tcx> TyS<'tcx> { pub fn is_uint(&self) -> bool { match self.sty { - TyInfer(IntVar(_)) | TyUint(hir::TyUs) => true, + TyInfer(IntVar(_)) | TyUint(ast::TyUs) => true, _ => false } } @@ -1081,7 +1089,7 @@ impl<'tcx> TyS<'tcx> { pub fn is_machine(&self) -> bool { match self.sty { - TyInt(hir::TyIs) | TyUint(hir::TyUs) => false, + TyInt(ast::TyIs) | TyUint(ast::TyUs) => false, TyInt(..) | TyUint(..) | TyFloat(..) => true, _ => false } diff --git a/src/librustc/middle/ty/util.rs b/src/librustc/middle/ty/util.rs index 8831461853576..3a90f3e0136e5 100644 --- a/src/librustc/middle/ty/util.rs +++ b/src/librustc/middle/ty/util.rs @@ -26,11 +26,11 @@ use util::num::ToPrimitive; use std::cmp; use std::hash::{Hash, SipHasher, Hasher}; -use syntax::ast::Name; +use syntax::ast::{self, Name}; +use syntax::attr::{self, AttrMetaMethods, SignedInt, UnsignedInt}; use syntax::codemap::Span; use rustc_front::hir; -use rustc_front::attr::{self, AttrMetaMethods, SignedInt, UnsignedInt}; pub trait IntTypeExt { fn to_ty<'tcx>(&self, cx: &ty::ctxt<'tcx>) -> Ty<'tcx>; @@ -44,48 +44,48 @@ pub trait IntTypeExt { impl IntTypeExt for attr::IntType { fn to_ty<'tcx>(&self, cx: &ty::ctxt<'tcx>) -> Ty<'tcx> { match *self { - SignedInt(hir::TyI8) => cx.types.i8, - SignedInt(hir::TyI16) => cx.types.i16, - SignedInt(hir::TyI32) => cx.types.i32, - SignedInt(hir::TyI64) => cx.types.i64, - SignedInt(hir::TyIs) => cx.types.isize, - UnsignedInt(hir::TyU8) => cx.types.u8, - UnsignedInt(hir::TyU16) => cx.types.u16, - UnsignedInt(hir::TyU32) => cx.types.u32, - UnsignedInt(hir::TyU64) => cx.types.u64, - UnsignedInt(hir::TyUs) => cx.types.usize, + SignedInt(ast::TyI8) => cx.types.i8, + SignedInt(ast::TyI16) => cx.types.i16, + SignedInt(ast::TyI32) => cx.types.i32, + SignedInt(ast::TyI64) => cx.types.i64, + SignedInt(ast::TyIs) => cx.types.isize, + UnsignedInt(ast::TyU8) => cx.types.u8, + UnsignedInt(ast::TyU16) => cx.types.u16, + UnsignedInt(ast::TyU32) => cx.types.u32, + UnsignedInt(ast::TyU64) => cx.types.u64, + UnsignedInt(ast::TyUs) => cx.types.usize, } } fn i64_to_disr(&self, val: i64) -> Option { match *self { - SignedInt(hir::TyI8) => val.to_i8() .map(|v| v as Disr), - SignedInt(hir::TyI16) => val.to_i16() .map(|v| v as Disr), - SignedInt(hir::TyI32) => val.to_i32() .map(|v| v as Disr), - SignedInt(hir::TyI64) => val.to_i64() .map(|v| v as Disr), - UnsignedInt(hir::TyU8) => val.to_u8() .map(|v| v as Disr), - UnsignedInt(hir::TyU16) => val.to_u16() .map(|v| v as Disr), - UnsignedInt(hir::TyU32) => val.to_u32() .map(|v| v as Disr), - UnsignedInt(hir::TyU64) => val.to_u64() .map(|v| v as Disr), - - UnsignedInt(hir::TyUs) | - SignedInt(hir::TyIs) => unreachable!(), + SignedInt(ast::TyI8) => val.to_i8() .map(|v| v as Disr), + SignedInt(ast::TyI16) => val.to_i16() .map(|v| v as Disr), + SignedInt(ast::TyI32) => val.to_i32() .map(|v| v as Disr), + SignedInt(ast::TyI64) => val.to_i64() .map(|v| v as Disr), + UnsignedInt(ast::TyU8) => val.to_u8() .map(|v| v as Disr), + UnsignedInt(ast::TyU16) => val.to_u16() .map(|v| v as Disr), + UnsignedInt(ast::TyU32) => val.to_u32() .map(|v| v as Disr), + UnsignedInt(ast::TyU64) => val.to_u64() .map(|v| v as Disr), + + UnsignedInt(ast::TyUs) | + SignedInt(ast::TyIs) => unreachable!(), } } fn u64_to_disr(&self, val: u64) -> Option { match *self { - SignedInt(hir::TyI8) => val.to_i8() .map(|v| v as Disr), - SignedInt(hir::TyI16) => val.to_i16() .map(|v| v as Disr), - SignedInt(hir::TyI32) => val.to_i32() .map(|v| v as Disr), - SignedInt(hir::TyI64) => val.to_i64() .map(|v| v as Disr), - UnsignedInt(hir::TyU8) => val.to_u8() .map(|v| v as Disr), - UnsignedInt(hir::TyU16) => val.to_u16() .map(|v| v as Disr), - UnsignedInt(hir::TyU32) => val.to_u32() .map(|v| v as Disr), - UnsignedInt(hir::TyU64) => val.to_u64() .map(|v| v as Disr), - - UnsignedInt(hir::TyUs) | - SignedInt(hir::TyIs) => unreachable!(), + SignedInt(ast::TyI8) => val.to_i8() .map(|v| v as Disr), + SignedInt(ast::TyI16) => val.to_i16() .map(|v| v as Disr), + SignedInt(ast::TyI32) => val.to_i32() .map(|v| v as Disr), + SignedInt(ast::TyI64) => val.to_i64() .map(|v| v as Disr), + UnsignedInt(ast::TyU8) => val.to_u8() .map(|v| v as Disr), + UnsignedInt(ast::TyU16) => val.to_u16() .map(|v| v as Disr), + UnsignedInt(ast::TyU32) => val.to_u32() .map(|v| v as Disr), + UnsignedInt(ast::TyU64) => val.to_u64() .map(|v| v as Disr), + + UnsignedInt(ast::TyUs) | + SignedInt(ast::TyIs) => unreachable!(), } } @@ -97,18 +97,18 @@ impl IntTypeExt for attr::IntType { // SignedInt repr means we *want* to reinterpret the bits // treating the highest bit of Disr as a sign-bit, so // cast to i64 before range-checking. - SignedInt(hir::TyI8) => add1!((val as i64).to_i8()), - SignedInt(hir::TyI16) => add1!((val as i64).to_i16()), - SignedInt(hir::TyI32) => add1!((val as i64).to_i32()), - SignedInt(hir::TyI64) => add1!(Some(val as i64)), - - UnsignedInt(hir::TyU8) => add1!(val.to_u8()), - UnsignedInt(hir::TyU16) => add1!(val.to_u16()), - UnsignedInt(hir::TyU32) => add1!(val.to_u32()), - UnsignedInt(hir::TyU64) => add1!(Some(val)), - - UnsignedInt(hir::TyUs) | - SignedInt(hir::TyIs) => unreachable!(), + SignedInt(ast::TyI8) => add1!((val as i64).to_i8()), + SignedInt(ast::TyI16) => add1!((val as i64).to_i16()), + SignedInt(ast::TyI32) => add1!((val as i64).to_i32()), + SignedInt(ast::TyI64) => add1!(Some(val as i64)), + + UnsignedInt(ast::TyU8) => add1!(val.to_u8()), + UnsignedInt(ast::TyU16) => add1!(val.to_u16()), + UnsignedInt(ast::TyU32) => add1!(val.to_u32()), + UnsignedInt(ast::TyU64) => add1!(Some(val)), + + UnsignedInt(ast::TyUs) | + SignedInt(ast::TyIs) => unreachable!(), } } @@ -117,17 +117,17 @@ impl IntTypeExt for attr::IntType { // full range from `i64::MIN` through `u64::MAX`. fn disr_string(&self, val: Disr) -> String { match *self { - SignedInt(hir::TyI8) => format!("{}", val as i8 ), - SignedInt(hir::TyI16) => format!("{}", val as i16), - SignedInt(hir::TyI32) => format!("{}", val as i32), - SignedInt(hir::TyI64) => format!("{}", val as i64), - UnsignedInt(hir::TyU8) => format!("{}", val as u8 ), - UnsignedInt(hir::TyU16) => format!("{}", val as u16), - UnsignedInt(hir::TyU32) => format!("{}", val as u32), - UnsignedInt(hir::TyU64) => format!("{}", val as u64), - - UnsignedInt(hir::TyUs) | - SignedInt(hir::TyIs) => unreachable!(), + SignedInt(ast::TyI8) => format!("{}", val as i8 ), + SignedInt(ast::TyI16) => format!("{}", val as i16), + SignedInt(ast::TyI32) => format!("{}", val as i32), + SignedInt(ast::TyI64) => format!("{}", val as i64), + UnsignedInt(ast::TyU8) => format!("{}", val as u8 ), + UnsignedInt(ast::TyU16) => format!("{}", val as u16), + UnsignedInt(ast::TyU32) => format!("{}", val as u32), + UnsignedInt(ast::TyU64) => format!("{}", val as u64), + + UnsignedInt(ast::TyUs) | + SignedInt(ast::TyIs) => unreachable!(), } } @@ -137,17 +137,17 @@ impl IntTypeExt for attr::IntType { } let val = val.unwrap_or(ty::INITIAL_DISCRIMINANT_VALUE); match *self { - SignedInt(hir::TyI8) => add1!(val as i8 ), - SignedInt(hir::TyI16) => add1!(val as i16), - SignedInt(hir::TyI32) => add1!(val as i32), - SignedInt(hir::TyI64) => add1!(val as i64), - UnsignedInt(hir::TyU8) => add1!(val as u8 ), - UnsignedInt(hir::TyU16) => add1!(val as u16), - UnsignedInt(hir::TyU32) => add1!(val as u32), - UnsignedInt(hir::TyU64) => add1!(val as u64), - - UnsignedInt(hir::TyUs) | - SignedInt(hir::TyIs) => unreachable!(), + SignedInt(ast::TyI8) => add1!(val as i8 ), + SignedInt(ast::TyI16) => add1!(val as i16), + SignedInt(ast::TyI32) => add1!(val as i32), + SignedInt(ast::TyI64) => add1!(val as i64), + UnsignedInt(ast::TyU8) => add1!(val as u8 ), + UnsignedInt(ast::TyU16) => add1!(val as u16), + UnsignedInt(ast::TyU32) => add1!(val as u32), + UnsignedInt(ast::TyU64) => add1!(val as u64), + + UnsignedInt(ast::TyUs) | + SignedInt(ast::TyIs) => unreachable!(), } } } @@ -279,14 +279,14 @@ impl<'tcx> ty::ctxt<'tcx> { // // NB. Historically `fn enum_variants` generate i64 here, while // rustc_typeck::check would generate isize. - _ => SignedInt(hir::TyIs), + _ => SignedInt(ast::TyIs), }; let repr_type_ty = repr_type.to_ty(self); let repr_type = match repr_type { - SignedInt(hir::TyIs) => + SignedInt(ast::TyIs) => SignedInt(self.sess.target.int_type), - UnsignedInt(hir::TyUs) => + UnsignedInt(ast::TyUs) => UnsignedInt(self.sess.target.uint_type), other => other }; diff --git a/src/librustc/middle/weak_lang_items.rs b/src/librustc/middle/weak_lang_items.rs index 43b7943fd2096..96c8e5c7d5218 100644 --- a/src/librustc/middle/weak_lang_items.rs +++ b/src/librustc/middle/weak_lang_items.rs @@ -15,6 +15,7 @@ use session::Session; use metadata::csearch; use middle::lang_items; +use syntax::ast; use syntax::codemap::Span; use syntax::parse::token::InternedString; use rustc_front::visit::Visitor; @@ -54,7 +55,7 @@ pub fn check_crate(krate: &hir::Crate, verify(sess, items); } -pub fn link_name(attrs: &[hir::Attribute]) -> Option { +pub fn link_name(attrs: &[ast::Attribute]) -> Option { lang_items::extract(attrs).and_then(|name| { $(if &name[..] == stringify!($name) { Some(InternedString::new(stringify!($sym))) diff --git a/src/librustc/plugin/build.rs b/src/librustc/plugin/build.rs index 55fd63b753472..ea85b264261cd 100644 --- a/src/librustc/plugin/build.rs +++ b/src/librustc/plugin/build.rs @@ -11,12 +11,12 @@ //! Used by `rustc` when compiling a plugin crate. use syntax::ast; +use syntax::attr; use syntax::codemap::Span; use syntax::diagnostic; use rustc_front::visit; use rustc_front::visit::Visitor; use rustc_front::hir; -use rustc_front::attr; struct RegistrarFinder { registrars: Vec<(ast::NodeId, Span)> , diff --git a/src/librustc/plugin/load.rs b/src/librustc/plugin/load.rs index e0cb47d6c9523..288426830efaf 100644 --- a/src/librustc/plugin/load.rs +++ b/src/librustc/plugin/load.rs @@ -39,6 +39,10 @@ struct PluginLoader<'a> { plugins: Vec, } +fn call_malformed_plugin_attribute(a: &Session, b: Span) { + span_err!(a, b, E0498, "malformed plugin attribute"); +} + /// Read plugin metadata and dynamically load registrar functions. pub fn load_plugins(sess: &Session, krate: &ast::Crate, addl_plugins: Option>) -> Vec { @@ -52,14 +56,14 @@ pub fn load_plugins(sess: &Session, krate: &ast::Crate, let plugins = match attr.meta_item_list() { Some(xs) => xs, None => { - sess.span_err(attr.span, "malformed plugin attribute"); + call_malformed_plugin_attribute(sess, attr.span); continue; } }; for plugin in plugins { if plugin.value_str().is_some() { - sess.span_err(attr.span, "malformed plugin attribute"); + call_malformed_plugin_attribute(sess, attr.span); continue; } diff --git a/src/librustc/plugin/registry.rs b/src/librustc/plugin/registry.rs index e79721b4347a6..50ca092dfe64e 100644 --- a/src/librustc/plugin/registry.rs +++ b/src/librustc/plugin/registry.rs @@ -10,7 +10,7 @@ //! Used by plugin crates to tell `rustc` about the plugins they provide. -use lint::{LintPassObject, LintId, Lint}; +use lint::{EarlyLintPassObject, LateLintPassObject, LintId, Lint}; use session::Session; use syntax::ext::base::{SyntaxExtension, NamedSyntaxExtension, NormalTT}; @@ -48,7 +48,10 @@ pub struct Registry<'a> { pub syntax_exts: Vec, #[doc(hidden)] - pub lint_passes: Vec, + pub early_lint_passes: Vec, + + #[doc(hidden)] + pub late_lint_passes: Vec, #[doc(hidden)] pub lint_groups: HashMap<&'static str, Vec>, @@ -68,7 +71,8 @@ impl<'a> Registry<'a> { args_hidden: None, krate_span: krate.span, syntax_exts: vec!(), - lint_passes: vec!(), + early_lint_passes: vec!(), + late_lint_passes: vec!(), lint_groups: HashMap::new(), llvm_passes: vec!(), attributes: vec!(), @@ -89,7 +93,6 @@ impl<'a> Registry<'a> { /// Register a syntax extension of any kind. /// /// This is the most general hook into `libsyntax`'s expansion behavior. - #[allow(deprecated)] pub fn register_syntax_extension(&mut self, name: ast::Name, extension: SyntaxExtension) { self.syntax_exts.push((name, match extension { NormalTT(ext, _, allow_internal_unstable) => { @@ -118,10 +121,14 @@ impl<'a> Registry<'a> { } /// Register a compiler lint pass. - pub fn register_lint_pass(&mut self, lint_pass: LintPassObject) { - self.lint_passes.push(lint_pass); + pub fn register_early_lint_pass(&mut self, lint_pass: EarlyLintPassObject) { + self.early_lint_passes.push(lint_pass); } + /// Register a compiler lint pass. + pub fn register_late_lint_pass(&mut self, lint_pass: LateLintPassObject) { + self.late_lint_passes.push(lint_pass); + } /// Register a lint group. pub fn register_lint_group(&mut self, name: &'static str, to: Vec<&'static Lint>) { self.lint_groups.insert(name, to.into_iter().map(|x| LintId::of(x)).collect()); diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index b56283e756723..30f43baabba2f 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -25,11 +25,9 @@ use rustc_back::target::Target; use lint; use metadata::cstore; -use syntax::ast; -use rustc_front::hir::{IntTy, UintTy}; +use syntax::ast::{self, IntTy, UintTy}; use syntax::attr; use syntax::attr::AttrMetaMethods; -use rustc_front::hir; use syntax::diagnostic::{ColorConfig, Auto, Always, Never, SpanHandler}; use syntax::parse; use syntax::parse::token::InternedString; @@ -603,6 +601,8 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, "For every macro invocation, print its name and arguments"), enable_nonzeroing_move_hints: bool = (false, parse_bool, "Force nonzeroing move optimization on"), + keep_mtwt_tables: bool = (false, parse_bool, + "Don't clear the resolution tables after analysis"), } pub fn default_lib_output() -> CrateType { @@ -669,8 +669,8 @@ pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config { }; let (int_type, uint_type) = match &target.target_pointer_width[..] { - "32" => (hir::TyI32, hir::TyU32), - "64" => (hir::TyI64, hir::TyU64), + "32" => (ast::TyI32, ast::TyU32), + "64" => (ast::TyI64, ast::TyU64), w => sp.handler().fatal(&format!("target specification was invalid: unrecognized \ target-pointer-width {}", w)) }; diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index fee60d46dc001..68bfa42f6f6cb 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -25,9 +25,10 @@ use middle::ty::fold::TypeFoldable; use std::fmt; use syntax::abi; +use syntax::ast; use syntax::parse::token; use syntax::ast::DUMMY_NODE_ID; -use rustc_front::hir as ast; +use rustc_front::hir; pub fn verbose() -> bool { ty::tls::with(|tcx| tcx.sess.verbose()) @@ -334,7 +335,7 @@ impl<'tcx> fmt::Debug for ty::TyS<'tcx> { impl<'tcx> fmt::Display for ty::TypeAndMut<'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}{}", - if self.mutbl == ast::MutMutable { "mut " } else { "" }, + if self.mutbl == hir::MutMutable { "mut " } else { "" }, self.ty) } } @@ -825,8 +826,8 @@ impl<'tcx> fmt::Display for ty::TypeVariants<'tcx> { TyBox(typ) => write!(f, "Box<{}>", typ), TyRawPtr(ref tm) => { write!(f, "*{} {}", match tm.mutbl { - ast::MutMutable => "mut", - ast::MutImmutable => "const", + hir::MutMutable => "mut", + hir::MutImmutable => "const", }, tm.ty) } TyRef(r, ref tm) => { @@ -853,7 +854,7 @@ impl<'tcx> fmt::Display for ty::TypeVariants<'tcx> { write!(f, ")") } TyBareFn(opt_def_id, ref bare_fn) => { - if bare_fn.unsafety == ast::Unsafety::Unsafe { + if bare_fn.unsafety == hir::Unsafety::Unsafe { try!(write!(f, "unsafe ")); } @@ -966,10 +967,10 @@ impl fmt::Display for ty::ExplicitSelfCategory { f.write_str(match *self { ty::StaticExplicitSelfCategory => "static", ty::ByValueExplicitSelfCategory => "self", - ty::ByReferenceExplicitSelfCategory(_, ast::MutMutable) => { + ty::ByReferenceExplicitSelfCategory(_, hir::MutMutable) => { "&mut self" } - ty::ByReferenceExplicitSelfCategory(_, ast::MutImmutable) => "&self", + ty::ByReferenceExplicitSelfCategory(_, hir::MutImmutable) => "&self", ty::ByBoxExplicitSelfCategory => "Box", }) } diff --git a/src/librustc_back/svh.rs b/src/librustc_back/svh.rs index 5f6bf939fb2a8..7134066d08ce7 100644 --- a/src/librustc_back/svh.rs +++ b/src/librustc_back/svh.rs @@ -232,7 +232,7 @@ mod svh_visitor { SawExprTup, SawExprBinary(hir::BinOp_), SawExprUnary(hir::UnOp), - SawExprLit(hir::Lit_), + SawExprLit(ast::Lit_), SawExprCast, SawExprIf, SawExprWhile, @@ -249,7 +249,6 @@ mod svh_visitor { SawExprInlineAsm(&'a hir::InlineAsm), SawExprStruct, SawExprRepeat, - SawExprParen, } fn saw_expr<'a>(node: &'a Expr_) -> SawExprComponent<'a> { @@ -283,7 +282,6 @@ mod svh_visitor { ExprInlineAsm(ref asm) => SawExprInlineAsm(asm), ExprStruct(..) => SawExprStruct, ExprRepeat(..) => SawExprRepeat, - ExprParen(..) => SawExprParen, } } diff --git a/src/librustc_borrowck/borrowck/fragments.rs b/src/librustc_borrowck/borrowck/fragments.rs index 86b6314b57cc1..cecbeacadecce 100644 --- a/src/librustc_borrowck/borrowck/fragments.rs +++ b/src/librustc_borrowck/borrowck/fragments.rs @@ -28,7 +28,7 @@ use std::mem; use std::rc::Rc; use syntax::ast; use syntax::codemap::Span; -use rustc_front::attr::AttrMetaMethods; +use syntax::attr::AttrMetaMethods; #[derive(PartialEq, Eq, PartialOrd, Ord)] enum Fragment { diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index f3038624ac107..ce04a5befd939 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -129,10 +129,12 @@ pub fn compile_input(sess: Session, &ast_map.krate(), &id[..])); + time(sess.time_passes(), "early lint checks", || { + lint::check_ast_crate(&sess, &expanded_crate) + }); phase_3_run_analysis_passes(sess, ast_map, - &expanded_crate, &arenas, id, control.make_glob_map, @@ -480,13 +482,16 @@ pub fn phase_2_configure_and_expand(sess: &Session, } }); - let Registry { syntax_exts, lint_passes, lint_groups, + let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups, llvm_passes, attributes, .. } = registry; { let mut ls = sess.lint_store.borrow_mut(); - for pass in lint_passes { - ls.register_pass(Some(sess), true, pass); + for pass in early_lint_passes { + ls.register_early_pass(Some(sess), true, pass); + } + for pass in late_lint_passes { + ls.register_late_pass(Some(sess), true, pass); } for (name, to) in lint_groups { @@ -641,7 +646,6 @@ pub fn make_map<'ast>(sess: &Session, /// structures carrying the results of the analysis. pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: Session, ast_map: front::map::Map<'tcx>, - ast_crate: &ast::Crate, arenas: &'tcx ty::CtxtArenas<'tcx>, name: String, make_glob_map: resolve::MakeGlobMap, @@ -671,7 +675,9 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: Session, || resolve::resolve_crate(&sess, &ast_map, make_glob_map)); // Discard MTWT tables that aren't required past resolution. - syntax::ext::mtwt::clear_tables(); + if !sess.opts.debugging_opts.keep_mtwt_tables { + syntax::ext::mtwt::clear_tables(); + } let named_region_map = time(time_passes, "lifetime resolution", || middle::resolve_lifetime::krate(&sess, krate, &def_map)); @@ -765,7 +771,7 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: Session, &tcx.sess, lib_features_used)); time(time_passes, "lint checking", || - lint::check_crate(tcx, &lower_crate(ast_crate), &exported_items)); + lint::check_crate(tcx, krate, &exported_items)); // The above three passes generate errors w/o aborting tcx.sess.abort_if_errors(); diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 53beb6d312d89..75b57341d48df 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -32,6 +32,7 @@ use syntax::ast; use syntax::codemap; use syntax::fold::{self, Folder}; use syntax::print::{pp, pprust}; +use syntax::print::pprust::PrintState; use syntax::ptr::P; use syntax::util::small_vector::SmallVector; @@ -156,7 +157,6 @@ impl PpSourceMode { fn call_with_pp_support_hir<'tcx, A, B, F>(&self, sess: Session, ast_map: &hir_map::Map<'tcx>, - ast_crate: &ast::Crate, arenas: &'tcx ty::CtxtArenas<'tcx>, id: String, payload: B, @@ -179,7 +179,6 @@ impl PpSourceMode { PpmTyped => { driver::phase_3_run_analysis_passes(sess, ast_map.clone(), - ast_crate, arenas, id, resolve::MakeGlobMap::No, @@ -714,7 +713,7 @@ pub fn pretty_print_input(sess: Session, (PpmHir(s), None) => { let out: &mut Write = &mut out; s.call_with_pp_support_hir( - sess, &ast_map.unwrap(), &krate, &arenas, id, box out, |annotation, out, krate| { + sess, &ast_map.unwrap(), &arenas, id, box out, |annotation, out, krate| { debug!("pretty printing source code {:?}", s); let sess = annotation.sess(); pprust_hir::print_crate(sess.codemap(), @@ -732,7 +731,6 @@ pub fn pretty_print_input(sess: Session, let out: &mut Write = &mut out; s.call_with_pp_support_hir(sess, &ast_map.unwrap(), - &krate, &arenas, id, (out,uii), @@ -781,7 +779,6 @@ pub fn pretty_print_input(sess: Session, let variants = gather_flowgraph_variants(&sess); driver::phase_3_run_analysis_passes(sess, ast_map, - &krate, &arenas, id, resolve::MakeGlobMap::No, diff --git a/src/librustc_front/attr.rs b/src/librustc_front/attr.rs index 8609fd9b9d965..7041f29cffff8 100644 --- a/src/librustc_front/attr.rs +++ b/src/librustc_front/attr.rs @@ -15,8 +15,6 @@ pub use self::ReprAttr::*; pub use self::IntType::*; use hir; -use hir::{AttrId, Attribute, Attribute_, MetaItem, MetaWord, MetaNameValue, MetaList}; -use lowering::{lower_attr_style, unlower_attribute}; use syntax::codemap::{Span, Spanned, spanned, dummy_spanned}; use syntax::codemap::BytePos; use syntax::diagnostic::SpanHandler; diff --git a/src/librustc_front/fold.rs b/src/librustc_front/fold.rs index ba20b46090afc..0693092c04a40 100644 --- a/src/librustc_front/fold.rs +++ b/src/librustc_front/fold.rs @@ -12,7 +12,8 @@ //! and returns a piece of the same type. use hir::*; -use syntax::ast::{Ident, NodeId, DUMMY_NODE_ID}; +use syntax::ast::{Ident, NodeId, DUMMY_NODE_ID, Attribute, Attribute_, MetaItem}; +use syntax::ast::{MetaWord, MetaList, MetaNameValue}; use hir; use syntax::codemap::{respan, Span, Spanned}; use syntax::owned_slice::OwnedSlice; @@ -1163,7 +1164,6 @@ pub fn noop_fold_expr(Expr {id, node, span}: Expr, folder: &mut T) -> fields.move_map(|x| folder.fold_field(x)), maybe_expr.map(|x| folder.fold_expr(x))) }, - ExprParen(ex) => ExprParen(folder.fold_expr(ex)) }, span: folder.new_span(span) } diff --git a/src/librustc_front/hir.rs b/src/librustc_front/hir.rs index f8f17617310b7..8bc8bda9e066c 100644 --- a/src/librustc_front/hir.rs +++ b/src/librustc_front/hir.rs @@ -11,7 +11,6 @@ // The Rust HIR. pub use self::AsmDialect::*; -pub use self::AttrStyle::*; pub use self::BindingMode::*; pub use self::BinOp_::*; pub use self::BlockCheckMode::*; @@ -19,28 +18,20 @@ pub use self::CaptureClause::*; pub use self::Decl_::*; pub use self::ExplicitSelf_::*; pub use self::Expr_::*; -pub use self::FloatTy::*; pub use self::FunctionRetTy::*; pub use self::ForeignItem_::*; pub use self::ImplItem_::*; -pub use self::IntTy::*; pub use self::Item_::*; -pub use self::Lit_::*; -pub use self::LitIntType::*; -pub use self::MetaItem_::*; pub use self::Mutability::*; pub use self::Pat_::*; pub use self::PathListItem_::*; pub use self::PatWildKind::*; pub use self::PrimTy::*; -pub use self::Sign::*; pub use self::Stmt_::*; -pub use self::StrStyle::*; pub use self::StructFieldKind::*; pub use self::TraitItem_::*; pub use self::Ty_::*; pub use self::TyParamBound::*; -pub use self::UintTy::*; pub use self::UnOp::*; pub use self::UnsafeSource::*; pub use self::VariantKind::*; @@ -51,6 +42,7 @@ pub use self::PathParameters::*; use syntax::codemap::{self, Span, Spanned, DUMMY_SP, ExpnId}; use syntax::abi::Abi; use syntax::ast::{Name, Ident, NodeId, DUMMY_NODE_ID, TokenTree}; +use syntax::ast::{Attribute, Lit, StrStyle, FloatTy, IntTy, UintTy, CrateConfig}; use syntax::owned_slice::OwnedSlice; use syntax::parse::token::InternedString; use syntax::ptr::P; @@ -59,7 +51,6 @@ use print::pprust; use util; use std::fmt; -use std::rc::Rc; use serialize::{Encodable, Encoder, Decoder}; @@ -333,10 +324,6 @@ pub struct WhereEqPredicate { pub ty: P, } -/// The set of MetaItems that define the compilation environment of the crate, -/// used to drive conditional compilation -pub type CrateConfig = Vec> ; - #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct Crate { pub module: Mod, @@ -362,40 +349,6 @@ pub struct MacroDef { pub body: Vec, } -pub type MetaItem = Spanned; - -#[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum MetaItem_ { - MetaWord(InternedString), - MetaList(InternedString, Vec>), - MetaNameValue(InternedString, Lit), -} - -// can't be derived because the MetaList requires an unordered comparison -impl PartialEq for MetaItem_ { - fn eq(&self, other: &MetaItem_) -> bool { - match *self { - MetaWord(ref ns) => match *other { - MetaWord(ref no) => (*ns) == (*no), - _ => false - }, - MetaNameValue(ref ns, ref vs) => match *other { - MetaNameValue(ref no, ref vo) => { - (*ns) == (*no) && vs.node == vo.node - } - _ => false - }, - MetaList(ref ns, ref miss) => match *other { - MetaList(ref no, ref miso) => { - ns == no && - miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node)) - } - _ => false - } - } - } -} - #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct Block { /// Statements in a block @@ -750,9 +703,6 @@ pub enum Expr_ { /// For example, `[1u8; 5]`. The first expression is the element /// to be repeated; the second is the number of times to repeat it. ExprRepeat(P, P), - - /// No-op: used solely so we can pretty-print faithfully - ExprParen(P) } /// The explicit Self type in a "qualified path". The actual @@ -787,72 +737,6 @@ pub enum CaptureClause { CaptureByRef, } - -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] -pub enum StrStyle { - /// A regular string, like `"foo"` - CookedStr, - /// A raw string, like `r##"foo"##` - /// - /// The uint is the number of `#` symbols used - RawStr(usize) -} - -/// A literal -pub type Lit = Spanned; - -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] -pub enum Sign { - Minus, - Plus -} - -impl Sign { - pub fn new(n: T) -> Sign { - n.sign() - } -} - -pub trait IntSign { - fn sign(&self) -> Sign; -} -macro_rules! doit { - ($($t:ident)*) => ($(impl IntSign for $t { - #[allow(unused_comparisons)] - fn sign(&self) -> Sign { - if *self < 0 {Minus} else {Plus} - } - })*) -} -doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } - -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] -pub enum LitIntType { - SignedIntLit(IntTy, Sign), - UnsignedIntLit(UintTy), - UnsuffixedIntLit(Sign) -} - -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum Lit_ { - /// A string literal (`"foo"`) - LitStr(InternedString, StrStyle), - /// A byte string (`b"foo"`) - LitByteStr(Rc>), - /// A byte char (`b'f'`) - LitByte(u8), - /// A character literal (`'a'`) - LitChar(char), - /// An integer literal (`1u8`) - LitInt(u64, LitIntType), - /// A float literal (`1f64` or `1E10f64`) - LitFloat(InternedString, FloatTy), - /// A float literal without a suffix (`1.0 or 1.0E10`) - LitFloatUnsuffixed(InternedString), - /// A boolean literal - LitBool(bool), -} - // NB: If you change this, you'll probably want to change the corresponding // type structure in middle/ty.rs as well. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] @@ -917,99 +801,6 @@ pub enum ImplItem_ { TypeImplItem(P), } -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] -pub enum IntTy { - TyIs, - TyI8, - TyI16, - TyI32, - TyI64, -} - -impl fmt::Debug for IntTy { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(self, f) - } -} - -impl fmt::Display for IntTy { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", util::int_ty_to_string(*self, None)) - } -} - -impl IntTy { - pub fn bit_width(&self) -> Option { - Some(match *self { - TyIs => return None, - TyI8 => 8, - TyI16 => 16, - TyI32 => 32, - TyI64 => 64, - }) - } -} - -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] -pub enum UintTy { - TyUs, - TyU8, - TyU16, - TyU32, - TyU64, -} - -impl UintTy { - pub fn bit_width(&self) -> Option { - Some(match *self { - TyUs => return None, - TyU8 => 8, - TyU16 => 16, - TyU32 => 32, - TyU64 => 64, - }) - } -} - -impl fmt::Debug for UintTy { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(self, f) - } -} - -impl fmt::Display for UintTy { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", util::uint_ty_to_string(*self, None)) - } -} - -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] -pub enum FloatTy { - TyF32, - TyF64, -} - -impl fmt::Debug for FloatTy { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(self, f) - } -} - -impl fmt::Display for FloatTy { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", util::float_ty_to_string(*self)) - } -} - -impl FloatTy { - pub fn bit_width(&self) -> usize { - match *self { - TyF32 => 32, - TyF64 => 64, - } - } -} - // Bind a type to an associated type: `A=Foo`. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct TypeBinding { @@ -1316,30 +1107,6 @@ pub enum ViewPath_ { ViewPathList(Path, Vec) } -/// Meta-data associated with an item -pub type Attribute = Spanned; - -/// Distinguishes between Attributes that decorate items and Attributes that -/// are contained as statements within items. These two cases need to be -/// distinguished for pretty-printing. -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] -pub enum AttrStyle { - AttrOuter, - AttrInner, -} - -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] -pub struct AttrId(pub usize); - -/// Doc-comments are promoted to attributes that have is_sugared_doc = true -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub struct Attribute_ { - pub id: AttrId, - pub style: AttrStyle, - pub value: P, - pub is_sugared_doc: bool, -} - /// TraitRef's appear in impls. /// /// resolve maps each TraitRef's ref_id to its defining trait; that's all diff --git a/src/librustc_front/lib.rs b/src/librustc_front/lib.rs index fae4f15725534..4c6d8505c81f0 100644 --- a/src/librustc_front/lib.rs +++ b/src/librustc_front/lib.rs @@ -36,7 +36,6 @@ #![feature(staged_api)] #![feature(str_char)] #![feature(filling_drop)] -#![feature(str_escape)] #![cfg_attr(test, feature(test))] extern crate serialize; @@ -50,7 +49,6 @@ pub mod hir; pub mod lowering; pub mod fold; pub mod visit; -pub mod attr; pub mod util; pub mod print { diff --git a/src/librustc_front/lowering.rs b/src/librustc_front/lowering.rs index aa7545d52d11e..4f5f892043b08 100644 --- a/src/librustc_front/lowering.rs +++ b/src/librustc_front/lowering.rs @@ -18,10 +18,6 @@ use syntax::codemap::Spanned; use syntax::owned_slice::OwnedSlice; -pub fn lower_meta_items(meta_items: &Vec>) -> Vec> { - meta_items.iter().map(|x| lower_meta_item(x)).collect() -} - pub fn lower_view_path(view_path: &ViewPath) -> P { P(Spanned { node: match view_path.node { @@ -54,13 +50,9 @@ pub fn lower_view_path(view_path: &ViewPath) -> P { }) } -pub fn lower_attrs(attrs: &Vec) -> Vec { - attrs.iter().map(|x| lower_attribute(x)).collect() -} - pub fn lower_arm(arm: &Arm) -> hir::Arm { hir::Arm { - attrs: lower_attrs(&arm.attrs), + attrs: arm.attrs.clone(), pats: arm.pats.iter().map(|x| lower_pat(x)).collect(), guard: arm.guard.as_ref().map(|ref x| lower_expr(x)), body: lower_expr(&arm.body), @@ -144,7 +136,7 @@ pub fn lower_variant(v: &Variant) -> P { node: hir::Variant_ { id: v.node.id, name: v.node.name, - attrs: lower_attrs(&v.node.attrs), + attrs: v.node.attrs.clone(), kind: match v.node.kind { TupleVariantKind(ref variant_args) => { hir::TupleVariantKind(variant_args.iter().map(|ref x| @@ -212,31 +204,6 @@ pub fn lower_local(l: &Local) -> P { }) } -pub fn lower_attribute(at: &Attribute) -> hir::Attribute { - Spanned { - node: hir::Attribute_ { - id: hir::AttrId(at.node.id.0), - style: lower_attr_style(at.node.style), - value: lower_meta_item(&at.node.value), - is_sugared_doc: at.node.is_sugared_doc, - }, - span: at.span, - } -} - -// FIXME we should probably just unify hir and ast Attributes. -pub fn unlower_attribute(at: &hir::Attribute) -> Attribute { - Spanned { - node: Attribute_ { - id: AttrId(at.node.id.0), - style: unlower_attr_style(at.node.style), - value: unlower_meta_item(&at.node.value), - is_sugared_doc: at.node.is_sugared_doc, - }, - span: at.span, - } -} - pub fn lower_explicit_self_underscore(es: &ExplicitSelf_) -> hir::ExplicitSelf_ { match *es { SelfStatic => hir::SelfStatic, @@ -261,33 +228,6 @@ pub fn lower_explicit_self(s: &ExplicitSelf) -> hir::ExplicitSelf { Spanned { node: lower_explicit_self_underscore(&s.node), span: s.span } } - -pub fn lower_meta_item(mi: &MetaItem) -> P { - P(Spanned { - node: match mi.node { - MetaWord(ref id) => hir::MetaWord(id.clone()), - MetaList(ref id, ref mis) => { - hir::MetaList(id.clone(), mis.iter().map(|mi| lower_meta_item(mi)).collect()) - } - MetaNameValue(ref id, ref s) => hir::MetaNameValue(id.clone(), lower_lit(s)) - }, - span: mi.span, - }) -} - -pub fn unlower_meta_item(mi: &hir::MetaItem) -> P { - P(Spanned { - node: match mi.node { - hir::MetaWord(ref id) => MetaWord(id.clone()), - hir::MetaList(ref id, ref mis) => { - MetaList(id.clone(), mis.iter().map(|mi| unlower_meta_item(mi)).collect()) - } - hir::MetaNameValue(ref id, ref s) => MetaNameValue(id.clone(), unlower_lit(s)) - }, - span: mi.span, - }) -} - pub fn lower_arg(arg: &Arg) -> hir::Arg { hir::Arg { id: arg.id, pat: lower_pat(&arg.pat), ty: lower_ty(&arg.ty) } } @@ -424,7 +364,7 @@ pub fn lower_struct_field(f: &StructField) -> hir::StructField { id: f.node.id, kind: lower_struct_field_kind(&f.node.kind), ty: lower_ty(&f.node.ty), - attrs: lower_attrs(&f.node.attrs), + attrs: f.node.attrs.clone(), }, span: f.span, } @@ -528,7 +468,7 @@ pub fn lower_trait_item(i: &TraitItem) -> P { P(hir::TraitItem { id: i.id, ident: i.ident, - attrs: lower_attrs(&i.attrs), + attrs: i.attrs.clone(), node: match i.node { ConstTraitItem(ref ty, ref default) => { hir::ConstTraitItem(lower_ty(ty), @@ -551,7 +491,7 @@ pub fn lower_impl_item(i: &ImplItem) -> P { P(hir::ImplItem { id: i.id, ident: i.ident, - attrs: lower_attrs(&i.attrs), + attrs: i.attrs.clone(), vis: lower_visibility(i.vis), node: match i.node { ConstImplItem(ref ty, ref expr) => { @@ -573,12 +513,10 @@ pub fn lower_mod(m: &Mod) -> hir::Mod { } pub fn lower_crate(c: &Crate) -> hir::Crate { - let config = lower_meta_items(&c.config); - hir::Crate { module: lower_mod(&c.module), - attrs: lower_attrs(&c.attrs), - config: config, + attrs: c.attrs.clone(), + config: c.config.clone(), span: c.span, exported_macros: c.exported_macros.iter().map(|m| lower_macro_def(m)).collect(), } @@ -587,7 +525,7 @@ pub fn lower_crate(c: &Crate) -> hir::Crate { pub fn lower_macro_def(m: &MacroDef) -> hir::MacroDef { hir::MacroDef { ident: m.ident, - attrs: m.attrs.iter().map(|a| lower_attribute(a)).collect(), + attrs: m.attrs.clone(), id: m.id, span: m.span, imported_from: m.imported_from, @@ -610,7 +548,7 @@ pub fn lower_item_simple(i: &Item) -> hir::Item { hir::Item { id: i.id, ident: i.ident, - attrs: lower_attrs(&i.attrs), + attrs: i.attrs.clone(), node: node, vis: lower_visibility(i.vis), span: i.span, @@ -621,7 +559,7 @@ pub fn lower_foreign_item(i: &ForeignItem) -> P { P(hir::ForeignItem { id: i.id, ident: i.ident, - attrs: lower_attrs(&i.attrs), + attrs: i.attrs.clone(), node: match i.node { ForeignItemFn(ref fdec, ref generics) => { hir::ForeignItemFn(lower_fn_decl(fdec), lower_generics(generics)) @@ -660,37 +598,6 @@ pub fn lower_constness(c: Constness) -> hir::Constness { } } -pub fn lower_lit(l: &Lit) -> hir::Lit { - Spanned { - node: match l.node { - LitStr(ref i, s) => hir::LitStr(i.clone(), lower_string_style(s)), - LitByteStr(ref b) => hir::LitByteStr(b.clone()), - LitByte(u) => hir::LitByte(u), - LitChar(c) => hir::LitChar(c), - LitInt(u, ref t) => hir::LitInt(u, lower_lit_int_type(t)), - LitFloat(ref i, t) => hir::LitFloat(i.clone(), lower_float_ty(t)), - LitFloatUnsuffixed(ref i) => hir::LitFloatUnsuffixed(i.clone()), - LitBool(b) => hir::LitBool(b), - }, - span: l.span, - } -} - -pub fn unlower_lit(l: &hir::Lit) -> Lit { - Spanned { - node: match l.node { - hir::LitStr(ref i, s) => LitStr(i.clone(), unlower_string_style(s)), - hir::LitByteStr(ref b) => LitByteStr(b.clone()), - hir::LitByte(u) => LitByte(u), - hir::LitChar(c) => LitChar(c), - hir::LitInt(u, ref t) => LitInt(u, unlower_lit_int_type(t)), - hir::LitFloat(ref i, t) => LitFloat(i.clone(), unlower_float_ty(t)), - hir::LitFloatUnsuffixed(ref i) => LitFloatUnsuffixed(i.clone()), - hir::LitBool(b) => LitBool(b), - }, - span: l.span, - } -} pub fn lower_unop(u: UnOp) -> hir::UnOp { match u { UnUniq => hir::UnUniq, @@ -810,7 +717,7 @@ pub fn lower_expr(e: &Expr) -> P { ExprUnary(op, ref ohs) => { hir::ExprUnary(lower_unop(op), lower_expr(ohs)) } - ExprLit(ref l) => hir::ExprLit(P(lower_lit(l))), + ExprLit(ref l) => hir::ExprLit(P((**l).clone())), ExprCast(ref expr, ref ty) => { hir::ExprCast(lower_expr(expr), lower_ty(ty)) } @@ -891,7 +798,7 @@ pub fn lower_expr(e: &Expr) -> P { (c.clone(), lower_expr(out), *is_rw) }).collect(), asm: asm.clone(), - asm_str_style: lower_string_style(asm_str_style), + asm_str_style: asm_str_style, clobbers: clobbers.clone(), volatile: volatile, alignstack: alignstack, @@ -903,7 +810,9 @@ pub fn lower_expr(e: &Expr) -> P { fields.iter().map(|x| lower_field(x)).collect(), maybe_expr.as_ref().map(|x| lower_expr(x))) }, - ExprParen(ref ex) => hir::ExprParen(lower_expr(ex)), + ExprParen(ref ex) => { + return lower_expr(ex); + } ExprIfLet(..) | ExprWhileLet(..) | ExprForLoop(..) | @@ -937,20 +846,6 @@ pub fn lower_stmt(s: &Stmt) -> P { } } -pub fn lower_string_style(s: StrStyle) -> hir::StrStyle { - match s { - CookedStr => hir::CookedStr, - RawStr(u) => hir::RawStr(u), - } -} - -pub fn unlower_string_style(s: hir::StrStyle) -> StrStyle { - match s { - hir::CookedStr => CookedStr, - hir::RawStr(u) => RawStr(u), - } -} - pub fn lower_match_source(m: &MatchSource) -> hir::MatchSource { match *m { MatchSource::Normal => hir::MatchSource::Normal, @@ -1027,107 +922,9 @@ pub fn lower_impl_polarity(i: ImplPolarity) -> hir::ImplPolarity { } } -pub fn lower_float_ty(f: FloatTy) -> hir::FloatTy { - match f { - TyF32 => hir::TyF32, - TyF64 => hir::TyF64, - } -} - -pub fn unlower_float_ty(f: hir::FloatTy) -> FloatTy { - match f { - hir::TyF32 => TyF32, - hir::TyF64 => TyF64, - } -} - -pub fn lower_lit_int_type(i: &LitIntType) -> hir::LitIntType { - match *i { - SignedIntLit(i, s) => hir::SignedIntLit(lower_int_ty(i), lower_sign(s)), - UnsignedIntLit(u) => hir::UnsignedIntLit(lower_uint_ty(u)), - UnsuffixedIntLit(s) => hir::UnsuffixedIntLit(lower_sign(s)), - } -} - -pub fn unlower_lit_int_type(i: &hir::LitIntType) -> LitIntType { - match *i { - hir::SignedIntLit(i, s) => SignedIntLit(unlower_int_ty(i), unlower_sign(s)), - hir::UnsignedIntLit(u) => UnsignedIntLit(unlower_uint_ty(u)), - hir::UnsuffixedIntLit(s) => UnsuffixedIntLit(unlower_sign(s)), - } -} - -pub fn lower_int_ty(i: IntTy) -> hir::IntTy { - match i { - TyIs => hir::TyIs, - TyI8 => hir::TyI8, - TyI16 => hir::TyI16, - TyI32 => hir::TyI32, - TyI64 => hir::TyI64, - } -} - -pub fn unlower_int_ty(i: hir::IntTy) -> IntTy { - match i { - hir::TyIs => TyIs, - hir::TyI8 => TyI8, - hir::TyI16 => TyI16, - hir::TyI32 => TyI32, - hir::TyI64 => TyI64, - } -} - -pub fn lower_uint_ty(u: UintTy) -> hir::UintTy { - match u { - TyUs => hir::TyUs, - TyU8 => hir::TyU8, - TyU16 => hir::TyU16, - TyU32 => hir::TyU32, - TyU64 => hir::TyU64, - } -} - -pub fn unlower_uint_ty(u: hir::UintTy) -> UintTy { - match u { - hir::TyUs => TyUs, - hir::TyU8 => TyU8, - hir::TyU16 => TyU16, - hir::TyU32 => TyU32, - hir::TyU64 => TyU64, - } -} - -pub fn lower_sign(f: Sign) -> hir::Sign { - match f { - Minus => hir::Minus, - Plus => hir::Plus, - } -} - -pub fn unlower_sign(f: hir::Sign) -> Sign { - match f { - hir::Minus => Minus, - hir::Plus => Plus, - } -} - pub fn lower_trait_bound_modifier(f: TraitBoundModifier) -> hir::TraitBoundModifier { match f { TraitBoundModifier::None => hir::TraitBoundModifier::None, TraitBoundModifier::Maybe => hir::TraitBoundModifier::Maybe, } } - -pub fn lower_attr_style(f: AttrStyle) -> hir::AttrStyle { - match f { - AttrOuter => hir::AttrOuter, - AttrInner => hir::AttrInner, - } -} - -pub fn unlower_attr_style(f: hir::AttrStyle) -> AttrStyle { - match f { - hir::AttrOuter => AttrOuter, - hir::AttrInner => AttrInner, - } -} diff --git a/src/librustc_front/print/pp.rs b/src/librustc_front/print/pp.rs deleted file mode 100644 index 7c5a46465f513..0000000000000 --- a/src/librustc_front/print/pp.rs +++ /dev/null @@ -1,686 +0,0 @@ -// Copyright 2012 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! This pretty-printer is a direct reimplementation of Philip Karlton's -//! Mesa pretty-printer, as described in appendix A of -//! -//! STAN-CS-79-770: "Pretty Printing", by Derek C. Oppen. -//! Stanford Department of Computer Science, 1979. -//! -//! The algorithm's aim is to break a stream into as few lines as possible -//! while respecting the indentation-consistency requirements of the enclosing -//! block, and avoiding breaking at silly places on block boundaries, for -//! example, between "x" and ")" in "x)". -//! -//! I am implementing this algorithm because it comes with 20 pages of -//! documentation explaining its theory, and because it addresses the set of -//! concerns I've seen other pretty-printers fall down on. Weirdly. Even though -//! it's 32 years old. What can I say? -//! -//! Despite some redundancies and quirks in the way it's implemented in that -//! paper, I've opted to keep the implementation here as similar as I can, -//! changing only what was blatantly wrong, a typo, or sufficiently -//! non-idiomatic rust that it really stuck out. -//! -//! In particular you'll see a certain amount of churn related to INTEGER vs. -//! CARDINAL in the Mesa implementation. Mesa apparently interconverts the two -//! somewhat readily? In any case, I've used usize for indices-in-buffers and -//! ints for character-sizes-and-indentation-offsets. This respects the need -//! for ints to "go negative" while carrying a pending-calculation balance, and -//! helps differentiate all the numbers flying around internally (slightly). -//! -//! I also inverted the indentation arithmetic used in the print stack, since -//! the Mesa implementation (somewhat randomly) stores the offset on the print -//! stack in terms of margin-col rather than col itself. I store col. -//! -//! I also implemented a small change in the String token, in that I store an -//! explicit length for the string. For most tokens this is just the length of -//! the accompanying string. But it's necessary to permit it to differ, for -//! encoding things that are supposed to "go on their own line" -- certain -//! classes of comment and blank-line -- where relying on adjacent -//! hardbreak-like Break tokens with long blankness indication doesn't actually -//! work. To see why, consider when there is a "thing that should be on its own -//! line" between two long blocks, say functions. If you put a hardbreak after -//! each function (or before each) and the breaking algorithm decides to break -//! there anyways (because the functions themselves are long) you wind up with -//! extra blank lines. If you don't put hardbreaks you can wind up with the -//! "thing which should be on its own line" not getting its own line in the -//! rare case of "really small functions" or such. This re-occurs with comments -//! and explicit blank lines. So in those cases we use a string with a payload -//! we want isolated to a line and an explicit length that's huge, surrounded -//! by two zero-length breaks. The algorithm will try its best to fit it on a -//! line (which it can't) and so naturally place the content on its own line to -//! avoid combining it with other lines and making matters even worse. - -use std::io; -use std::string; - -#[derive(Clone, Copy, PartialEq)] -pub enum Breaks { - Consistent, - Inconsistent, -} - -#[derive(Clone, Copy)] -pub struct BreakToken { - offset: isize, - blank_space: isize -} - -#[derive(Clone, Copy)] -pub struct BeginToken { - offset: isize, - breaks: Breaks -} - -#[derive(Clone)] -pub enum Token { - String(String, isize), - Break(BreakToken), - Begin(BeginToken), - End, - Eof, -} - -impl Token { - pub fn is_eof(&self) -> bool { - match *self { - Token::Eof => true, - _ => false, - } - } - - pub fn is_hardbreak_tok(&self) -> bool { - match *self { - Token::Break(BreakToken { - offset: 0, - blank_space: bs - }) if bs == SIZE_INFINITY => - true, - _ => - false - } - } -} - -pub fn tok_str(token: &Token) -> String { - match *token { - Token::String(ref s, len) => format!("STR({},{})", s, len), - Token::Break(_) => "BREAK".to_string(), - Token::Begin(_) => "BEGIN".to_string(), - Token::End => "END".to_string(), - Token::Eof => "EOF".to_string() - } -} - -pub fn buf_str(toks: &[Token], - szs: &[isize], - left: usize, - right: usize, - lim: usize) - -> String { - let n = toks.len(); - assert_eq!(n, szs.len()); - let mut i = left; - let mut l = lim; - let mut s = string::String::from("["); - while i != right && l != 0 { - l -= 1; - if i != left { - s.push_str(", "); - } - s.push_str(&format!("{}={}", - szs[i], - tok_str(&toks[i]))); - i += 1; - i %= n; - } - s.push(']'); - s -} - -#[derive(Copy, Clone)] -pub enum PrintStackBreak { - Fits, - Broken(Breaks), -} - -#[derive(Copy, Clone)] -pub struct PrintStackElem { - offset: isize, - pbreak: PrintStackBreak -} - -const SIZE_INFINITY: isize = 0xffff; - -pub fn mk_printer<'a>(out: Box, linewidth: usize) -> Printer<'a> { - // Yes 3, it makes the ring buffers big enough to never - // fall behind. - let n: usize = 3 * linewidth; - debug!("mk_printer {}", linewidth); - let token = vec![Token::Eof; n]; - let size = vec![0_isize; n]; - let scan_stack = vec![0_usize; n]; - Printer { - out: out, - buf_len: n, - margin: linewidth as isize, - space: linewidth as isize, - left: 0, - right: 0, - token: token, - size: size, - left_total: 0, - right_total: 0, - scan_stack: scan_stack, - scan_stack_empty: true, - top: 0, - bottom: 0, - print_stack: Vec::new(), - pending_indentation: 0 - } -} - - -/// In case you do not have the paper, here is an explanation of what's going -/// on. -/// -/// There is a stream of input tokens flowing through this printer. -/// -/// The printer buffers up to 3N tokens inside itself, where N is linewidth. -/// Yes, linewidth is chars and tokens are multi-char, but in the worst -/// case every token worth buffering is 1 char long, so it's ok. -/// -/// Tokens are String, Break, and Begin/End to delimit blocks. -/// -/// Begin tokens can carry an offset, saying "how far to indent when you break -/// inside here", as well as a flag indicating "consistent" or "inconsistent" -/// breaking. Consistent breaking means that after the first break, no attempt -/// will be made to flow subsequent breaks together onto lines. Inconsistent -/// is the opposite. Inconsistent breaking example would be, say: -/// -/// foo(hello, there, good, friends) -/// -/// breaking inconsistently to become -/// -/// foo(hello, there -/// good, friends); -/// -/// whereas a consistent breaking would yield: -/// -/// foo(hello, -/// there -/// good, -/// friends); -/// -/// That is, in the consistent-break blocks we value vertical alignment -/// more than the ability to cram stuff onto a line. But in all cases if it -/// can make a block a one-liner, it'll do so. -/// -/// Carrying on with high-level logic: -/// -/// The buffered tokens go through a ring-buffer, 'tokens'. The 'left' and -/// 'right' indices denote the active portion of the ring buffer as well as -/// describing hypothetical points-in-the-infinite-stream at most 3N tokens -/// apart (i.e. "not wrapped to ring-buffer boundaries"). The paper will switch -/// between using 'left' and 'right' terms to denote the wrapped-to-ring-buffer -/// and point-in-infinite-stream senses freely. -/// -/// There is a parallel ring buffer, 'size', that holds the calculated size of -/// each token. Why calculated? Because for Begin/End pairs, the "size" -/// includes everything between the pair. That is, the "size" of Begin is -/// actually the sum of the sizes of everything between Begin and the paired -/// End that follows. Since that is arbitrarily far in the future, 'size' is -/// being rewritten regularly while the printer runs; in fact most of the -/// machinery is here to work out 'size' entries on the fly (and give up when -/// they're so obviously over-long that "infinity" is a good enough -/// approximation for purposes of line breaking). -/// -/// The "input side" of the printer is managed as an abstract process called -/// SCAN, which uses 'scan_stack', 'scan_stack_empty', 'top' and 'bottom', to -/// manage calculating 'size'. SCAN is, in other words, the process of -/// calculating 'size' entries. -/// -/// The "output side" of the printer is managed by an abstract process called -/// PRINT, which uses 'print_stack', 'margin' and 'space' to figure out what to -/// do with each token/size pair it consumes as it goes. It's trying to consume -/// the entire buffered window, but can't output anything until the size is >= -/// 0 (sizes are set to negative while they're pending calculation). -/// -/// So SCAN takes input and buffers tokens and pending calculations, while -/// PRINT gobbles up completed calculations and tokens from the buffer. The -/// theory is that the two can never get more than 3N tokens apart, because -/// once there's "obviously" too much data to fit on a line, in a size -/// calculation, SCAN will write "infinity" to the size and let PRINT consume -/// it. -/// -/// In this implementation (following the paper, again) the SCAN process is -/// the method called 'pretty_print', and the 'PRINT' process is the method -/// called 'print'. -pub struct Printer<'a> { - pub out: Box, - buf_len: usize, - /// Width of lines we're constrained to - margin: isize, - /// Number of spaces left on line - space: isize, - /// Index of left side of input stream - left: usize, - /// Index of right side of input stream - right: usize, - /// Ring-buffer stream goes through - token: Vec , - /// Ring-buffer of calculated sizes - size: Vec , - /// Running size of stream "...left" - left_total: isize, - /// Running size of stream "...right" - right_total: isize, - /// Pseudo-stack, really a ring too. Holds the - /// primary-ring-buffers index of the Begin that started the - /// current block, possibly with the most recent Break after that - /// Begin (if there is any) on top of it. Stuff is flushed off the - /// bottom as it becomes irrelevant due to the primary ring-buffer - /// advancing. - scan_stack: Vec , - /// Top==bottom disambiguator - scan_stack_empty: bool, - /// Index of top of scan_stack - top: usize, - /// Index of bottom of scan_stack - bottom: usize, - /// Stack of blocks-in-progress being flushed by print - print_stack: Vec , - /// Buffered indentation to avoid writing trailing whitespace - pending_indentation: isize, -} - -impl<'a> Printer<'a> { - pub fn last_token(&mut self) -> Token { - self.token[self.right].clone() - } - // be very careful with this! - pub fn replace_last_token(&mut self, t: Token) { - self.token[self.right] = t; - } - pub fn pretty_print(&mut self, token: Token) -> io::Result<()> { - debug!("pp Vec<{},{}>", self.left, self.right); - match token { - Token::Eof => { - if !self.scan_stack_empty { - self.check_stack(0); - try!(self.advance_left()); - } - self.indent(0); - Ok(()) - } - Token::Begin(b) => { - if self.scan_stack_empty { - self.left_total = 1; - self.right_total = 1; - self.left = 0; - self.right = 0; - } else { self.advance_right(); } - debug!("pp Begin({})/buffer Vec<{},{}>", - b.offset, self.left, self.right); - self.token[self.right] = token; - self.size[self.right] = -self.right_total; - let right = self.right; - self.scan_push(right); - Ok(()) - } - Token::End => { - if self.scan_stack_empty { - debug!("pp End/print Vec<{},{}>", self.left, self.right); - self.print(token, 0) - } else { - debug!("pp End/buffer Vec<{},{}>", self.left, self.right); - self.advance_right(); - self.token[self.right] = token; - self.size[self.right] = -1; - let right = self.right; - self.scan_push(right); - Ok(()) - } - } - Token::Break(b) => { - if self.scan_stack_empty { - self.left_total = 1; - self.right_total = 1; - self.left = 0; - self.right = 0; - } else { self.advance_right(); } - debug!("pp Break({})/buffer Vec<{},{}>", - b.offset, self.left, self.right); - self.check_stack(0); - let right = self.right; - self.scan_push(right); - self.token[self.right] = token; - self.size[self.right] = -self.right_total; - self.right_total += b.blank_space; - Ok(()) - } - Token::String(s, len) => { - if self.scan_stack_empty { - debug!("pp String('{}')/print Vec<{},{}>", - s, self.left, self.right); - self.print(Token::String(s, len), len) - } else { - debug!("pp String('{}')/buffer Vec<{},{}>", - s, self.left, self.right); - self.advance_right(); - self.token[self.right] = Token::String(s, len); - self.size[self.right] = len; - self.right_total += len; - self.check_stream() - } - } - } - } - pub fn check_stream(&mut self) -> io::Result<()> { - debug!("check_stream Vec<{}, {}> with left_total={}, right_total={}", - self.left, self.right, self.left_total, self.right_total); - if self.right_total - self.left_total > self.space { - debug!("scan window is {}, longer than space on line ({})", - self.right_total - self.left_total, self.space); - if !self.scan_stack_empty { - if self.left == self.scan_stack[self.bottom] { - debug!("setting {} to infinity and popping", self.left); - let scanned = self.scan_pop_bottom(); - self.size[scanned] = SIZE_INFINITY; - } - } - try!(self.advance_left()); - if self.left != self.right { - try!(self.check_stream()); - } - } - Ok(()) - } - pub fn scan_push(&mut self, x: usize) { - debug!("scan_push {}", x); - if self.scan_stack_empty { - self.scan_stack_empty = false; - } else { - self.top += 1; - self.top %= self.buf_len; - assert!((self.top != self.bottom)); - } - self.scan_stack[self.top] = x; - } - pub fn scan_pop(&mut self) -> usize { - assert!((!self.scan_stack_empty)); - let x = self.scan_stack[self.top]; - if self.top == self.bottom { - self.scan_stack_empty = true; - } else { - self.top += self.buf_len - 1; self.top %= self.buf_len; - } - return x; - } - pub fn scan_top(&mut self) -> usize { - assert!((!self.scan_stack_empty)); - return self.scan_stack[self.top]; - } - pub fn scan_pop_bottom(&mut self) -> usize { - assert!((!self.scan_stack_empty)); - let x = self.scan_stack[self.bottom]; - if self.top == self.bottom { - self.scan_stack_empty = true; - } else { - self.bottom += 1; self.bottom %= self.buf_len; - } - return x; - } - pub fn advance_right(&mut self) { - self.right += 1; - self.right %= self.buf_len; - assert!((self.right != self.left)); - } - pub fn advance_left(&mut self) -> io::Result<()> { - debug!("advance_left Vec<{},{}>, sizeof({})={}", self.left, self.right, - self.left, self.size[self.left]); - - let mut left_size = self.size[self.left]; - - while left_size >= 0 { - let left = self.token[self.left].clone(); - - let len = match left { - Token::Break(b) => b.blank_space, - Token::String(_, len) => { - assert_eq!(len, left_size); - len - } - _ => 0 - }; - - try!(self.print(left, left_size)); - - self.left_total += len; - - if self.left == self.right { - break; - } - - self.left += 1; - self.left %= self.buf_len; - - left_size = self.size[self.left]; - } - - Ok(()) - } - pub fn check_stack(&mut self, k: isize) { - if !self.scan_stack_empty { - let x = self.scan_top(); - match self.token[x] { - Token::Begin(_) => { - if k > 0 { - let popped = self.scan_pop(); - self.size[popped] = self.size[x] + self.right_total; - self.check_stack(k - 1); - } - } - Token::End => { - // paper says + not =, but that makes no sense. - let popped = self.scan_pop(); - self.size[popped] = 1; - self.check_stack(k + 1); - } - _ => { - let popped = self.scan_pop(); - self.size[popped] = self.size[x] + self.right_total; - if k > 0 { - self.check_stack(k); - } - } - } - } - } - pub fn print_newline(&mut self, amount: isize) -> io::Result<()> { - debug!("NEWLINE {}", amount); - let ret = write!(self.out, "\n"); - self.pending_indentation = 0; - self.indent(amount); - return ret; - } - pub fn indent(&mut self, amount: isize) { - debug!("INDENT {}", amount); - self.pending_indentation += amount; - } - pub fn get_top(&mut self) -> PrintStackElem { - let print_stack = &mut self.print_stack; - let n = print_stack.len(); - if n != 0 { - (*print_stack)[n - 1] - } else { - PrintStackElem { - offset: 0, - pbreak: PrintStackBreak::Broken(Breaks::Inconsistent) - } - } - } - pub fn print_str(&mut self, s: &str) -> io::Result<()> { - while self.pending_indentation > 0 { - try!(write!(self.out, " ")); - self.pending_indentation -= 1; - } - write!(self.out, "{}", s) - } - pub fn print(&mut self, token: Token, l: isize) -> io::Result<()> { - debug!("print {} {} (remaining line space={})", tok_str(&token), l, - self.space); - debug!("{}", buf_str(&self.token, - &self.size, - self.left, - self.right, - 6)); - match token { - Token::Begin(b) => { - if l > self.space { - let col = self.margin - self.space + b.offset; - debug!("print Begin -> push broken block at col {}", col); - self.print_stack.push(PrintStackElem { - offset: col, - pbreak: PrintStackBreak::Broken(b.breaks) - }); - } else { - debug!("print Begin -> push fitting block"); - self.print_stack.push(PrintStackElem { - offset: 0, - pbreak: PrintStackBreak::Fits - }); - } - Ok(()) - } - Token::End => { - debug!("print End -> pop End"); - let print_stack = &mut self.print_stack; - assert!((!print_stack.is_empty())); - print_stack.pop().unwrap(); - Ok(()) - } - Token::Break(b) => { - let top = self.get_top(); - match top.pbreak { - PrintStackBreak::Fits => { - debug!("print Break({}) in fitting block", b.blank_space); - self.space -= b.blank_space; - self.indent(b.blank_space); - Ok(()) - } - PrintStackBreak::Broken(Breaks::Consistent) => { - debug!("print Break({}+{}) in consistent block", - top.offset, b.offset); - let ret = self.print_newline(top.offset + b.offset); - self.space = self.margin - (top.offset + b.offset); - ret - } - PrintStackBreak::Broken(Breaks::Inconsistent) => { - if l > self.space { - debug!("print Break({}+{}) w/ newline in inconsistent", - top.offset, b.offset); - let ret = self.print_newline(top.offset + b.offset); - self.space = self.margin - (top.offset + b.offset); - ret - } else { - debug!("print Break({}) w/o newline in inconsistent", - b.blank_space); - self.indent(b.blank_space); - self.space -= b.blank_space; - Ok(()) - } - } - } - } - Token::String(s, len) => { - debug!("print String({})", s); - assert_eq!(l, len); - // assert!(l <= space); - self.space -= len; - self.print_str(&s[..]) - } - Token::Eof => { - // Eof should never get here. - panic!(); - } - } - } -} - -// Convenience functions to talk to the printer. -// -// "raw box" -pub fn rbox(p: &mut Printer, indent: usize, b: Breaks) -> io::Result<()> { - p.pretty_print(Token::Begin(BeginToken { - offset: indent as isize, - breaks: b - })) -} - -pub fn ibox(p: &mut Printer, indent: usize) -> io::Result<()> { - rbox(p, indent, Breaks::Inconsistent) -} - -pub fn cbox(p: &mut Printer, indent: usize) -> io::Result<()> { - rbox(p, indent, Breaks::Consistent) -} - -pub fn break_offset(p: &mut Printer, n: usize, off: isize) -> io::Result<()> { - p.pretty_print(Token::Break(BreakToken { - offset: off, - blank_space: n as isize - })) -} - -pub fn end(p: &mut Printer) -> io::Result<()> { - p.pretty_print(Token::End) -} - -pub fn eof(p: &mut Printer) -> io::Result<()> { - p.pretty_print(Token::Eof) -} - -pub fn word(p: &mut Printer, wrd: &str) -> io::Result<()> { - p.pretty_print(Token::String(/* bad */ wrd.to_string(), wrd.len() as isize)) -} - -pub fn huge_word(p: &mut Printer, wrd: &str) -> io::Result<()> { - p.pretty_print(Token::String(/* bad */ wrd.to_string(), SIZE_INFINITY)) -} - -pub fn zero_word(p: &mut Printer, wrd: &str) -> io::Result<()> { - p.pretty_print(Token::String(/* bad */ wrd.to_string(), 0)) -} - -pub fn spaces(p: &mut Printer, n: usize) -> io::Result<()> { - break_offset(p, n, 0) -} - -pub fn zerobreak(p: &mut Printer) -> io::Result<()> { - spaces(p, 0) -} - -pub fn space(p: &mut Printer) -> io::Result<()> { - spaces(p, 1) -} - -pub fn hardbreak(p: &mut Printer) -> io::Result<()> { - spaces(p, SIZE_INFINITY as usize) -} - -pub fn hardbreak_tok_offset(off: isize) -> Token { - Token::Break(BreakToken {offset: off, blank_space: SIZE_INFINITY}) -} - -pub fn hardbreak_tok() -> Token { - hardbreak_tok_offset(0) -} diff --git a/src/librustc_front/print/pprust.rs b/src/librustc_front/print/pprust.rs index a1382b467fb87..d4a52a5ed8eb0 100644 --- a/src/librustc_front/print/pprust.rs +++ b/src/librustc_front/print/pprust.rs @@ -18,18 +18,16 @@ use syntax::diagnostic; use syntax::parse::token::{self, BinOpToken}; use syntax::parse::lexer::comments; use syntax::parse; -use syntax::print::pp::{self, break_offset, word, space, zerobreak, hardbreak}; +use syntax::print::pp::{self, break_offset, word, space, hardbreak}; use syntax::print::pp::{Breaks, eof}; use syntax::print::pp::Breaks::{Consistent, Inconsistent}; +use syntax::print::pprust::{self as ast_pp, PrintState}; use syntax::ptr::P; use hir; use hir::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier}; -use attr::{AttrMetaMethods, AttributeMethods}; -use std::ascii; use std::io::{self, Write, Read}; -use std::iter; pub enum AnnNode<'a> { NodeIdent(&'a ast::Ident), @@ -51,22 +49,39 @@ pub struct NoAnn; impl PpAnn for NoAnn {} -#[derive(Copy, Clone)] -pub struct CurrentCommentAndLiteral { - cur_cmnt: usize, - cur_lit: usize, -} pub struct State<'a> { pub s: pp::Printer<'a>, cm: Option<&'a CodeMap>, - comments: Option >, - literals: Option >, - cur_cmnt_and_lit: CurrentCommentAndLiteral, + comments: Option>, + literals: Option>, + cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral, boxes: Vec, ann: &'a (PpAnn+'a), } +impl<'a> PrintState<'a> for State<'a> { + fn writer(&mut self) -> &mut pp::Printer<'a> { + &mut self.s + } + + fn boxes(&mut self) -> &mut Vec { + &mut self.boxes + } + + fn comments(&mut self) -> &mut Option> { + &mut self.comments + } + + fn cur_cmnt_and_lit(&mut self) -> &mut ast_pp::CurrentCommentAndLiteral { + &mut self.cur_cmnt_and_lit + } + + fn literals(&self) -> &Option> { + &self.literals + } +} + pub fn rust_printer<'a>(writer: Box) -> State<'a> { static NO_ANN: NoAnn = NoAnn; rust_printer_annotated(writer, &NO_ANN) @@ -79,7 +94,7 @@ pub fn rust_printer_annotated<'a>(writer: Box, cm: None, comments: None, literals: None, - cur_cmnt_and_lit: CurrentCommentAndLiteral { + cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral { cur_cmnt: 0, cur_lit: 0 }, @@ -154,9 +169,9 @@ impl<'a> State<'a> { State { s: pp::mk_printer(out, default_columns), cm: Some(cm), - comments: comments, - literals: literals, - cur_cmnt_and_lit: CurrentCommentAndLiteral { + comments: comments.clone(), + literals: literals.clone(), + cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral { cur_cmnt: 0, cur_lit: 0 }, @@ -221,10 +236,6 @@ pub fn stmt_to_string(stmt: &hir::Stmt) -> String { to_string(|s| s.print_stmt(stmt)) } -pub fn attr_to_string(attr: &hir::Attribute) -> String { - to_string(|s| s.print_attribute(attr)) -} - pub fn item_to_string(i: &hir::Item) -> String { to_string(|s| s.print_item(i)) } @@ -283,18 +294,6 @@ pub fn block_to_string(blk: &hir::Block) -> String { }) } -pub fn meta_item_to_string(mi: &hir::MetaItem) -> String { - to_string(|s| s.print_meta_item(mi)) -} - -pub fn attribute_to_string(attr: &hir::Attribute) -> String { - to_string(|s| s.print_attribute(attr)) -} - -pub fn lit_to_string(l: &hir::Lit) -> String { - to_string(|s| s.print_literal(l)) -} - pub fn explicit_self_to_string(explicit_self: &hir::ExplicitSelf_) -> String { to_string(|s| s.print_explicit_self(explicit_self, hir::MutImmutable).map(|_| {})) } @@ -324,27 +323,11 @@ fn needs_parentheses(expr: &hir::Expr) -> bool { } impl<'a> State<'a> { - pub fn ibox(&mut self, u: usize) -> io::Result<()> { - self.boxes.push(pp::Breaks::Inconsistent); - pp::ibox(&mut self.s, u) - } - - pub fn end(&mut self) -> io::Result<()> { - self.boxes.pop().unwrap(); - pp::end(&mut self.s) - } - pub fn cbox(&mut self, u: usize) -> io::Result<()> { self.boxes.push(pp::Breaks::Consistent); pp::cbox(&mut self.s, u) } - // "raw box" - pub fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> { - self.boxes.push(b); - pp::rbox(&mut self.s, u, b) - } - pub fn nbsp(&mut self) -> io::Result<()> { word(&mut self.s, " ") } pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> { @@ -352,15 +335,6 @@ impl<'a> State<'a> { self.nbsp() } - pub fn word_space(&mut self, w: &str) -> io::Result<()> { - try!(word(&mut self.s, w)); - space(&mut self.s) - } - - pub fn popen(&mut self) -> io::Result<()> { word(&mut self.s, "(") } - - pub fn pclose(&mut self) -> io::Result<()> { word(&mut self.s, ")") } - pub fn head(&mut self, w: &str) -> io::Result<()> { // outer-box is consistent try!(self.cbox(indent_unit)); @@ -396,38 +370,12 @@ impl<'a> State<'a> { self.bclose_(span, indent_unit) } - pub fn is_begin(&mut self) -> bool { - match self.s.last_token() { - pp::Token::Begin(_) => true, - _ => false, - } - } - - pub fn is_end(&mut self) -> bool { - match self.s.last_token() { - pp::Token::End => true, - _ => false, - } - } - - // is this the beginning of a line? - pub fn is_bol(&mut self) -> bool { - self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok() - } - pub fn in_cbox(&self) -> bool { match self.boxes.last() { Some(&last_box) => last_box == pp::Breaks::Consistent, None => false } } - - pub fn hardbreak_if_not_bol(&mut self) -> io::Result<()> { - if !self.is_bol() { - try!(hardbreak(&mut self.s)) - } - Ok(()) - } pub fn space_if_not_bol(&mut self) -> io::Result<()> { if !self.is_bol() { try!(space(&mut self.s)); } Ok(()) @@ -457,18 +405,6 @@ impl<'a> State<'a> { word(&mut self.s, "*/") } - pub fn commasep(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()> where - F: FnMut(&mut State, &T) -> io::Result<()>, - { - try!(self.rbox(0, b)); - let mut first = true; - for elt in elts { - if first { first = false; } else { try!(self.word_space(",")); } - try!(op(self, elt)); - } - self.end() - } - pub fn commasep_cmnt(&mut self, b: Breaks, @@ -501,7 +437,7 @@ impl<'a> State<'a> { } pub fn print_mod(&mut self, _mod: &hir::Mod, - attrs: &[hir::Attribute]) -> io::Result<()> { + attrs: &[ast::Attribute]) -> io::Result<()> { try!(self.print_inner_attributes(attrs)); for item in &_mod.items { try!(self.print_item(&**item)); @@ -510,7 +446,7 @@ impl<'a> State<'a> { } pub fn print_foreign_mod(&mut self, nmod: &hir::ForeignMod, - attrs: &[hir::Attribute]) -> io::Result<()> { + attrs: &[ast::Attribute]) -> io::Result<()> { try!(self.print_inner_attributes(attrs)); for item in &nmod.items { try!(self.print_foreign_item(&**item)); @@ -694,7 +630,7 @@ impl<'a> State<'a> { if let Some(p) = *optional_path { let val = p.as_str(); if val.contains("-") { - try!(self.print_string(&val, hir::CookedStr)); + try!(self.print_string(&val, ast::CookedStr)); } else { try!(self.print_name(p)); } @@ -1105,58 +1041,6 @@ impl<'a> State<'a> { self.ann.post(self, NodeSubItem(ii.id)) } - pub fn print_outer_attributes(&mut self, - attrs: &[hir::Attribute]) -> io::Result<()> { - let mut count = 0; - for attr in attrs { - match attr.node.style { - hir::AttrOuter => { - try!(self.print_attribute(attr)); - count += 1; - } - _ => {/* fallthrough */ } - } - } - if count > 0 { - try!(self.hardbreak_if_not_bol()); - } - Ok(()) - } - - pub fn print_inner_attributes(&mut self, - attrs: &[hir::Attribute]) -> io::Result<()> { - let mut count = 0; - for attr in attrs { - match attr.node.style { - hir::AttrInner => { - try!(self.print_attribute(attr)); - count += 1; - } - _ => {/* fallthrough */ } - } - } - if count > 0 { - try!(self.hardbreak_if_not_bol()); - } - Ok(()) - } - - pub fn print_attribute(&mut self, attr: &hir::Attribute) -> io::Result<()> { - try!(self.hardbreak_if_not_bol()); - try!(self.maybe_print_comment(attr.span.lo)); - if attr.node.is_sugared_doc { - word(&mut self.s, &attr.value_str().unwrap()) - } else { - match attr.node.style { - hir::AttrInner => try!(word(&mut self.s, "#![")), - hir::AttrOuter => try!(word(&mut self.s, "#[")), - } - try!(self.print_meta_item(&*attr.meta())); - word(&mut self.s, "]") - } - } - - pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> { try!(self.maybe_print_comment(st.span.lo)); match st.node { @@ -1194,14 +1078,14 @@ impl<'a> State<'a> { pub fn print_block_with_attrs(&mut self, blk: &hir::Block, - attrs: &[hir::Attribute]) -> io::Result<()> { + attrs: &[ast::Attribute]) -> io::Result<()> { self.print_block_maybe_unclosed(blk, indent_unit, attrs, true) } pub fn print_block_maybe_unclosed(&mut self, blk: &hir::Block, indented: usize, - attrs: &[hir::Attribute], + attrs: &[ast::Attribute], close_box: bool) -> io::Result<()> { match blk.rules { hir::UnsafeBlock(..) | hir::PushUnsafeBlock(..) => try!(self.word_space("unsafe")), @@ -1620,9 +1504,9 @@ impl<'a> State<'a> { match co.slice_shift_char() { Some(('=', operand)) if is_rw => { try!(s.print_string(&format!("+{}", operand), - hir::CookedStr)) + ast::CookedStr)) } - _ => try!(s.print_string(&co, hir::CookedStr)) + _ => try!(s.print_string(&co, ast::CookedStr)) } try!(s.popen()); try!(s.print_expr(&**o)); @@ -1634,7 +1518,7 @@ impl<'a> State<'a> { try!(self.commasep(Inconsistent, &a.inputs, |s, &(ref co, ref o)| { - try!(s.print_string(&co, hir::CookedStr)); + try!(s.print_string(&co, ast::CookedStr)); try!(s.popen()); try!(s.print_expr(&**o)); try!(s.pclose()); @@ -1645,7 +1529,7 @@ impl<'a> State<'a> { try!(self.commasep(Inconsistent, &a.clobbers, |s, co| { - try!(s.print_string(&co, hir::CookedStr)); + try!(s.print_string(&co, ast::CookedStr)); Ok(()) })); @@ -1665,18 +1549,13 @@ impl<'a> State<'a> { try!(self.word_space(":")); try!(self.commasep(Inconsistent, &*options, |s, &co| { - try!(s.print_string(co, hir::CookedStr)); + try!(s.print_string(co, ast::CookedStr)); Ok(()) })); } try!(self.pclose()); } - hir::ExprParen(ref e) => { - try!(self.popen()); - try!(self.print_expr(&**e)); - try!(self.pclose()); - } } try!(self.ann.post(self, NodeExpr(expr))); self.end() @@ -2294,29 +2173,6 @@ impl<'a> State<'a> { Ok(()) } - pub fn print_meta_item(&mut self, item: &hir::MetaItem) -> io::Result<()> { - try!(self.ibox(indent_unit)); - match item.node { - hir::MetaWord(ref name) => { - try!(word(&mut self.s, &name)); - } - hir::MetaNameValue(ref name, ref value) => { - try!(self.word_space(&name[..])); - try!(self.word_space("=")); - try!(self.print_literal(value)); - } - hir::MetaList(ref name, ref items) => { - try!(word(&mut self.s, &name)); - try!(self.popen()); - try!(self.commasep(Consistent, - &items[..], - |s, i| s.print_meta_item(&**i))); - try!(self.pclose()); - } - } - self.end() - } - pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> { match vp.node { hir::ViewPathSimple(ident, ref path) => { @@ -2494,181 +2350,6 @@ impl<'a> State<'a> { Ok(()) } - pub fn print_literal(&mut self, lit: &hir::Lit) -> io::Result<()> { - try!(self.maybe_print_comment(lit.span.lo)); - match self.next_lit(lit.span.lo) { - Some(ref ltrl) => { - return word(&mut self.s, &(*ltrl).lit); - } - _ => () - } - match lit.node { - hir::LitStr(ref st, style) => self.print_string(&st, style), - hir::LitByte(byte) => { - let mut res = String::from("b'"); - res.extend(ascii::escape_default(byte).map(|c| c as char)); - res.push('\''); - word(&mut self.s, &res[..]) - } - hir::LitChar(ch) => { - let mut res = String::from("'"); - res.extend(ch.escape_default()); - res.push('\''); - word(&mut self.s, &res[..]) - } - hir::LitInt(i, t) => { - match t { - hir::SignedIntLit(st, hir::Plus) => { - word(&mut self.s, - &::util::int_ty_to_string(st, Some(i as i64))) - } - hir::SignedIntLit(st, hir::Minus) => { - let istr = ::util::int_ty_to_string(st, Some(-(i as i64))); - word(&mut self.s, - &format!("-{}", istr)) - } - hir::UnsignedIntLit(ut) => { - word(&mut self.s, &::util::uint_ty_to_string(ut, Some(i))) - } - hir::UnsuffixedIntLit(hir::Plus) => { - word(&mut self.s, &format!("{}", i)) - } - hir::UnsuffixedIntLit(hir::Minus) => { - word(&mut self.s, &format!("-{}", i)) - } - } - } - hir::LitFloat(ref f, t) => { - word(&mut self.s, - &format!( - "{}{}", - &f, - &::util::float_ty_to_string(t))) - } - hir::LitFloatUnsuffixed(ref f) => word(&mut self.s, &f[..]), - hir::LitBool(val) => { - if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") } - } - hir::LitByteStr(ref v) => { - let mut escaped: String = String::new(); - for &ch in v.iter() { - escaped.extend(ascii::escape_default(ch) - .map(|c| c as char)); - } - word(&mut self.s, &format!("b\"{}\"", escaped)) - } - } - } - - pub fn next_lit(&mut self, pos: BytePos) -> Option { - match self.literals { - Some(ref lits) => { - while self.cur_cmnt_and_lit.cur_lit < lits.len() { - let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone(); - if ltrl.pos > pos { return None; } - self.cur_cmnt_and_lit.cur_lit += 1; - if ltrl.pos == pos { return Some(ltrl); } - } - None - } - _ => None - } - } - - pub fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> { - loop { - match self.next_comment() { - Some(ref cmnt) => { - if (*cmnt).pos < pos { - try!(self.print_comment(cmnt)); - self.cur_cmnt_and_lit.cur_cmnt += 1; - } else { break; } - } - _ => break - } - } - Ok(()) - } - - pub fn print_comment(&mut self, - cmnt: &comments::Comment) -> io::Result<()> { - match cmnt.style { - comments::Mixed => { - assert_eq!(cmnt.lines.len(), 1); - try!(zerobreak(&mut self.s)); - try!(word(&mut self.s, &cmnt.lines[0])); - zerobreak(&mut self.s) - } - comments::Isolated => { - try!(self.hardbreak_if_not_bol()); - for line in &cmnt.lines { - // Don't print empty lines because they will end up as trailing - // whitespace - if !line.is_empty() { - try!(word(&mut self.s, &line[..])); - } - try!(hardbreak(&mut self.s)); - } - Ok(()) - } - comments::Trailing => { - try!(word(&mut self.s, " ")); - if cmnt.lines.len() == 1 { - try!(word(&mut self.s, &cmnt.lines[0])); - hardbreak(&mut self.s) - } else { - try!(self.ibox(0)); - for line in &cmnt.lines { - if !line.is_empty() { - try!(word(&mut self.s, &line[..])); - } - try!(hardbreak(&mut self.s)); - } - self.end() - } - } - comments::BlankLine => { - // We need to do at least one, possibly two hardbreaks. - let is_semi = match self.s.last_token() { - pp::Token::String(s, _) => ";" == s, - _ => false - }; - if is_semi || self.is_begin() || self.is_end() { - try!(hardbreak(&mut self.s)); - } - hardbreak(&mut self.s) - } - } - } - - pub fn print_string(&mut self, st: &str, - style: hir::StrStyle) -> io::Result<()> { - let st = match style { - hir::CookedStr => { - (format!("\"{}\"", st.escape_default())) - } - hir::RawStr(n) => { - (format!("r{delim}\"{string}\"{delim}", - delim=repeat("#", n), - string=st)) - } - }; - word(&mut self.s, &st[..]) - } - - pub fn next_comment(&mut self) -> Option { - match self.comments { - Some(ref cmnts) => { - if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() { - Some(cmnts[self.cur_cmnt_and_lit.cur_cmnt].clone()) - } else { - None - } - } - _ => None - } - } - pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option) -> io::Result<()> { @@ -2722,8 +2403,6 @@ impl<'a> State<'a> { } } -fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() } - // Dup'ed from parse::classify, but adapted for the HIR. /// Does this expression require a semicolon to be treated /// as a statement? The negation of this: 'can this expression diff --git a/src/librustc_front/util.rs b/src/librustc_front/util.rs index 247ea2ea23b8c..0a47da77a8fce 100644 --- a/src/librustc_front/util.rs +++ b/src/librustc_front/util.rs @@ -338,64 +338,10 @@ pub fn compute_id_range_for_fn_body(fk: FnKind, id_visitor.operation.result } -/// Returns true if this literal is a string and false otherwise. -pub fn lit_is_str(lit: &Lit) -> bool { - match lit.node { - LitStr(..) => true, - _ => false, - } -} - pub fn is_path(e: P) -> bool { match e.node { ExprPath(..) => true, _ => false } } -/// Get a string representation of a signed int type, with its value. -/// We want to avoid "45int" and "-3int" in favor of "45" and "-3" -pub fn int_ty_to_string(t: IntTy, val: Option) -> String { - let s = match t { - TyIs => "isize", - TyI8 => "i8", - TyI16 => "i16", - TyI32 => "i32", - TyI64 => "i64" - }; - - match val { - // cast to a u64 so we can correctly print INT64_MIN. All integral types - // are parsed as u64, so we wouldn't want to print an extra negative - // sign. - Some(n) => format!("{}{}", n as u64, s), - None => s.to_string() - } -} - - -/// Get a string representation of an unsigned int type, with its value. -/// We want to avoid "42u" in favor of "42us". "42uint" is right out. -pub fn uint_ty_to_string(t: UintTy, val: Option) -> String { - let s = match t { - TyUs => "usize", - TyU8 => "u8", - TyU16 => "u16", - TyU32 => "u32", - TyU64 => "u64" - }; - - match val { - Some(n) => format!("{}{}", n, s), - None => s.to_string() - } -} - -pub fn float_ty_to_string(t: FloatTy) -> String { - match t { - TyF32 => "f32".to_string(), - TyF64 => "f64".to_string(), - } -} - - pub fn empty_generics() -> Generics { Generics { lifetimes: Vec::new(), diff --git a/src/librustc_front/visit.rs b/src/librustc_front/visit.rs index f20e5345f2066..d9b4f37411420 100644 --- a/src/librustc_front/visit.rs +++ b/src/librustc_front/visit.rs @@ -24,7 +24,7 @@ //! those that are created by the expansion of a macro. use syntax::abi::Abi; -use syntax::ast::{Ident, NodeId, CRATE_NODE_ID, Name}; +use syntax::ast::{Ident, NodeId, CRATE_NODE_ID, Name, Attribute}; use hir::*; use hir; use syntax::codemap::Span; @@ -814,9 +814,6 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) { ExprRet(ref optional_expression) => { walk_expr_opt(visitor, optional_expression) } - ExprParen(ref subexpression) => { - visitor.visit_expr(&**subexpression) - } ExprInlineAsm(ref ia) => { for input in &ia.inputs { let (_, ref input) = *input; diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index 4084f13e818f2..394bd2abc08c7 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -38,7 +38,8 @@ use middle::const_eval::{eval_const_expr_partial, ConstVal}; use middle::const_eval::EvalHint::ExprTypeChecked; use rustc::front::map as hir_map; use util::nodemap::{FnvHashMap, FnvHashSet, NodeSet}; -use lint::{Level, Context, LintPass, LintArray, Lint}; +use lint::{Level, LateContext, EarlyContext, LintContext, LintArray, Lint}; +use lint::{LintPass, EarlyLintPass, LateLintPass}; use std::collections::HashSet; use std::collections::hash_map::Entry::{Occupied, Vacant}; @@ -46,18 +47,14 @@ use std::{cmp, slice}; use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64}; use syntax::{abi, ast}; -use syntax::attr as syntax_attr; +use syntax::attr::{self, AttrMetaMethods}; use syntax::codemap::{self, Span}; use syntax::feature_gate::{KNOWN_ATTRIBUTES, AttributeType}; -use rustc_front::hir::{TyIs, TyUs, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64}; +use syntax::ast::{TyIs, TyUs, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64}; use syntax::ptr::P; use rustc_front::hir; - -use rustc_front::attr::{self, AttrMetaMethods}; use rustc_front::visit::{self, FnKind, Visitor}; -use rustc_front::lowering::unlower_attribute; - use rustc_front::util::is_shift_binop; // hardwired lints from librustc @@ -76,11 +73,13 @@ impl LintPass for WhileTrue { fn get_lints(&self) -> LintArray { lint_array!(WHILE_TRUE) } +} - fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { +impl LateLintPass for WhileTrue { + fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { if let hir::ExprWhile(ref cond, _, _) = e.node { if let hir::ExprLit(ref lit) = cond.node { - if let hir::LitBool(true) = lit.node { + if let ast::LitBool(true) = lit.node { cx.span_lint(WHILE_TRUE, e.span, "denote infinite loops with loop { ... }"); } @@ -125,17 +124,19 @@ impl LintPass for TypeLimits { fn get_lints(&self) -> LintArray { lint_array!(UNUSED_COMPARISONS, OVERFLOWING_LITERALS, EXCEEDING_BITSHIFTS) } +} - fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { +impl LateLintPass for TypeLimits { + fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { match e.node { hir::ExprUnary(hir::UnNeg, ref expr) => { match expr.node { hir::ExprLit(ref lit) => { match lit.node { - hir::LitInt(_, hir::UnsignedIntLit(_)) => { + ast::LitInt(_, ast::UnsignedIntLit(_)) => { check_unsigned_negation_feature(cx, e.span); }, - hir::LitInt(_, hir::UnsuffixedIntLit(_)) => { + ast::LitInt(_, ast::UnsuffixedIntLit(_)) => { if let ty::TyUint(_) = cx.tcx.node_id_to_type(e.id).sty { check_unsigned_negation_feature(cx, e.span); } @@ -158,9 +159,6 @@ impl LintPass for TypeLimits { self.negated_expr_id = expr.id; } }, - hir::ExprParen(ref expr) if self.negated_expr_id == e.id => { - self.negated_expr_id = expr.id; - }, hir::ExprBinary(binop, ref l, ref r) => { if is_comparison(binop) && !check_limits(cx.tcx, binop, &**l, &**r) { cx.span_lint(UNUSED_COMPARISONS, e.span, @@ -176,7 +174,7 @@ impl LintPass for TypeLimits { if let Some(bits) = opt_ty_bits { let exceeding = if let hir::ExprLit(ref lit) = r.node { - if let hir::LitInt(shift, _) = lit.node { shift >= bits } + if let ast::LitInt(shift, _) = lit.node { shift >= bits } else { false } } else { match eval_const_expr_partial(cx.tcx, &r, ExprTypeChecked) { @@ -196,9 +194,9 @@ impl LintPass for TypeLimits { match cx.tcx.node_id_to_type(e.id).sty { ty::TyInt(t) => { match lit.node { - hir::LitInt(v, hir::SignedIntLit(_, hir::Plus)) | - hir::LitInt(v, hir::UnsuffixedIntLit(hir::Plus)) => { - let int_type = if let hir::TyIs = t { + ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) | + ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => { + let int_type = if let ast::TyIs = t { cx.sess().target.int_type } else { t @@ -219,15 +217,15 @@ impl LintPass for TypeLimits { }; }, ty::TyUint(t) => { - let uint_type = if let hir::TyUs = t { + let uint_type = if let ast::TyUs = t { cx.sess().target.uint_type } else { t }; let (min, max) = uint_ty_range(uint_type); let lit_val: u64 = match lit.node { - hir::LitByte(_v) => return, // _v is u8, within range by definition - hir::LitInt(v, _) => v, + ast::LitByte(_v) => return, // _v is u8, within range by definition + ast::LitInt(v, _) => v, _ => panic!() }; if lit_val < min || lit_val > max { @@ -238,8 +236,8 @@ impl LintPass for TypeLimits { ty::TyFloat(t) => { let (min, max) = float_ty_range(t); let lit_val: f64 = match lit.node { - hir::LitFloat(ref v, _) | - hir::LitFloatUnsuffixed(ref v) => { + ast::LitFloat(ref v, _) | + ast::LitFloatUnsuffixed(ref v) => { match v.parse() { Ok(f) => f, Err(_) => return @@ -282,50 +280,50 @@ impl LintPass for TypeLimits { // for isize & usize, be conservative with the warnings, so that the // warnings are consistent between 32- and 64-bit platforms - fn int_ty_range(int_ty: hir::IntTy) -> (i64, i64) { + fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) { match int_ty { - hir::TyIs => (i64::MIN, i64::MAX), - hir::TyI8 => (i8::MIN as i64, i8::MAX as i64), - hir::TyI16 => (i16::MIN as i64, i16::MAX as i64), - hir::TyI32 => (i32::MIN as i64, i32::MAX as i64), - hir::TyI64 => (i64::MIN, i64::MAX) + ast::TyIs => (i64::MIN, i64::MAX), + ast::TyI8 => (i8::MIN as i64, i8::MAX as i64), + ast::TyI16 => (i16::MIN as i64, i16::MAX as i64), + ast::TyI32 => (i32::MIN as i64, i32::MAX as i64), + ast::TyI64 => (i64::MIN, i64::MAX) } } - fn uint_ty_range(uint_ty: hir::UintTy) -> (u64, u64) { + fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) { match uint_ty { - hir::TyUs => (u64::MIN, u64::MAX), - hir::TyU8 => (u8::MIN as u64, u8::MAX as u64), - hir::TyU16 => (u16::MIN as u64, u16::MAX as u64), - hir::TyU32 => (u32::MIN as u64, u32::MAX as u64), - hir::TyU64 => (u64::MIN, u64::MAX) + ast::TyUs => (u64::MIN, u64::MAX), + ast::TyU8 => (u8::MIN as u64, u8::MAX as u64), + ast::TyU16 => (u16::MIN as u64, u16::MAX as u64), + ast::TyU32 => (u32::MIN as u64, u32::MAX as u64), + ast::TyU64 => (u64::MIN, u64::MAX) } } - fn float_ty_range(float_ty: hir::FloatTy) -> (f64, f64) { + fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) { match float_ty { - hir::TyF32 => (f32::MIN as f64, f32::MAX as f64), - hir::TyF64 => (f64::MIN, f64::MAX) + ast::TyF32 => (f32::MIN as f64, f32::MAX as f64), + ast::TyF64 => (f64::MIN, f64::MAX) } } - fn int_ty_bits(int_ty: hir::IntTy, target_int_ty: hir::IntTy) -> u64 { + fn int_ty_bits(int_ty: ast::IntTy, target_int_ty: ast::IntTy) -> u64 { match int_ty { - hir::TyIs => int_ty_bits(target_int_ty, target_int_ty), - hir::TyI8 => i8::BITS as u64, - hir::TyI16 => i16::BITS as u64, - hir::TyI32 => i32::BITS as u64, - hir::TyI64 => i64::BITS as u64 + ast::TyIs => int_ty_bits(target_int_ty, target_int_ty), + ast::TyI8 => i8::BITS as u64, + ast::TyI16 => i16::BITS as u64, + ast::TyI32 => i32::BITS as u64, + ast::TyI64 => i64::BITS as u64 } } - fn uint_ty_bits(uint_ty: hir::UintTy, target_uint_ty: hir::UintTy) -> u64 { + fn uint_ty_bits(uint_ty: ast::UintTy, target_uint_ty: ast::UintTy) -> u64 { match uint_ty { - hir::TyUs => uint_ty_bits(target_uint_ty, target_uint_ty), - hir::TyU8 => u8::BITS as u64, - hir::TyU16 => u16::BITS as u64, - hir::TyU32 => u32::BITS as u64, - hir::TyU64 => u64::BITS as u64 + ast::TyUs => uint_ty_bits(target_uint_ty, target_uint_ty), + ast::TyU8 => u8::BITS as u64, + ast::TyU16 => u16::BITS as u64, + ast::TyU32 => u32::BITS as u64, + ast::TyU64 => u64::BITS as u64 } } @@ -348,10 +346,10 @@ impl LintPass for TypeLimits { let (min, max) = int_ty_range(int_ty); let lit_val: i64 = match lit.node { hir::ExprLit(ref li) => match li.node { - hir::LitInt(v, hir::SignedIntLit(_, hir::Plus)) | - hir::LitInt(v, hir::UnsuffixedIntLit(hir::Plus)) => v as i64, - hir::LitInt(v, hir::SignedIntLit(_, hir::Minus)) | - hir::LitInt(v, hir::UnsuffixedIntLit(hir::Minus)) => -(v as i64), + ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) | + ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => v as i64, + ast::LitInt(v, ast::SignedIntLit(_, ast::Minus)) | + ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64), _ => return true }, _ => panic!() @@ -362,7 +360,7 @@ impl LintPass for TypeLimits { let (min, max): (u64, u64) = uint_ty_range(uint_ty); let lit_val: u64 = match lit.node { hir::ExprLit(ref li) => match li.node { - hir::LitInt(v, _) => v, + ast::LitInt(v, _) => v, _ => return true }, _ => panic!() @@ -381,7 +379,7 @@ impl LintPass for TypeLimits { } } - fn check_unsigned_negation_feature(cx: &Context, span: Span) { + fn check_unsigned_negation_feature(cx: &LateContext, span: Span) { if !cx.sess().features.borrow().negate_unsigned { // FIXME(#27141): change this to syntax::feature_gate::emit_feature_err… cx.sess().span_warn(span, @@ -402,7 +400,7 @@ declare_lint! { } struct ImproperCTypesVisitor<'a, 'tcx: 'a> { - cx: &'a Context<'a, 'tcx> + cx: &'a LateContext<'a, 'tcx> } enum FfiResult { @@ -557,11 +555,11 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { FfiSafe } - ty::TyInt(hir::TyIs) => { + ty::TyInt(ast::TyIs) => { FfiUnsafe("found Rust type `isize` in foreign module, while \ `libc::c_int` or `libc::c_long` should be used") } - ty::TyUint(hir::TyUs) => { + ty::TyUint(ast::TyUs) => { FfiUnsafe("found Rust type `usize` in foreign module, while \ `libc::c_uint` or `libc::c_ulong` should be used") } @@ -706,14 +704,16 @@ impl LintPass for ImproperCTypes { fn get_lints(&self) -> LintArray { lint_array!(IMPROPER_CTYPES) } +} - fn check_item(&mut self, cx: &Context, it: &hir::Item) { - fn check_ty(cx: &Context, ty: &hir::Ty) { +impl LateLintPass for ImproperCTypes { + fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { + fn check_ty(cx: &LateContext, ty: &hir::Ty) { let mut vis = ImproperCTypesVisitor { cx: cx }; vis.visit_ty(ty); } - fn check_foreign_fn(cx: &Context, decl: &hir::FnDecl) { + fn check_foreign_fn(cx: &LateContext, decl: &hir::FnDecl) { for input in &decl.inputs { check_ty(cx, &*input.ty); } @@ -751,7 +751,7 @@ declare_lint! { pub struct BoxPointers; impl BoxPointers { - fn check_heap_type<'a, 'tcx>(&self, cx: &Context<'a, 'tcx>, + fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext<'a, 'tcx>, span: Span, ty: Ty<'tcx>) { for leaf_ty in ty.walk() { if let ty::TyBox(_) = leaf_ty.sty { @@ -766,8 +766,10 @@ impl LintPass for BoxPointers { fn get_lints(&self) -> LintArray { lint_array!(BOX_POINTERS) } +} - fn check_item(&mut self, cx: &Context, it: &hir::Item) { +impl LateLintPass for BoxPointers { + fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { match it.node { hir::ItemFn(..) | hir::ItemTy(..) | @@ -790,7 +792,7 @@ impl LintPass for BoxPointers { } } - fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { + fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { let ty = cx.tcx.node_id_to_type(e.id); self.check_heap_type(cx, e.span, ty); } @@ -803,7 +805,7 @@ declare_lint! { } struct RawPtrDeriveVisitor<'a, 'tcx: 'a> { - cx: &'a Context<'a, 'tcx> + cx: &'a LateContext<'a, 'tcx> } impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> { @@ -835,8 +837,10 @@ impl LintPass for RawPointerDerive { fn get_lints(&self) -> LintArray { lint_array!(RAW_POINTER_DERIVE) } +} - fn check_item(&mut self, cx: &Context, item: &hir::Item) { +impl LateLintPass for RawPointerDerive { + fn check_item(&mut self, cx: &LateContext, item: &hir::Item) { if !attr::contains_name(&item.attrs, "automatically_derived") { return; } @@ -891,8 +895,10 @@ impl LintPass for UnusedAttributes { fn get_lints(&self) -> LintArray { lint_array!(UNUSED_ATTRIBUTES) } +} - fn check_attribute(&mut self, cx: &Context, attr: &hir::Attribute) { +impl LateLintPass for UnusedAttributes { + fn check_attribute(&mut self, cx: &LateContext, attr: &ast::Attribute) { // Note that check_name() marks the attribute as used if it matches. for &(ref name, ty, _) in KNOWN_ATTRIBUTES { match ty { @@ -910,7 +916,7 @@ impl LintPass for UnusedAttributes { } } - if !syntax_attr::is_used(&unlower_attribute(attr)) { + if !attr::is_used(attr) { cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute"); // Is it a builtin attribute that must be used at the crate level? let known_crate = KNOWN_ATTRIBUTES.iter().find(|&&(name, ty, _)| { @@ -927,9 +933,9 @@ impl LintPass for UnusedAttributes { }).is_some(); if known_crate || plugin_crate { let msg = match attr.node.style { - hir::AttrOuter => "crate-level attribute should be an inner \ + ast::AttrOuter => "crate-level attribute should be an inner \ attribute: add an exclamation mark: #![foo]", - hir::AttrInner => "crate-level attribute should be in the \ + ast::AttrInner => "crate-level attribute should be in the \ root module", }; cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg); @@ -951,8 +957,10 @@ impl LintPass for PathStatements { fn get_lints(&self) -> LintArray { lint_array!(PATH_STATEMENTS) } +} - fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) { +impl LateLintPass for PathStatements { + fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) { match s.node { hir::StmtSemi(ref expr, _) => { match expr.node { @@ -985,8 +993,10 @@ impl LintPass for UnusedResults { fn get_lints(&self) -> LintArray { lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS) } +} - fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) { +impl LateLintPass for UnusedResults { + fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) { let expr = match s.node { hir::StmtSemi(ref expr, _) => &**expr, _ => return @@ -1019,7 +1029,7 @@ impl LintPass for UnusedResults { cx.span_lint(UNUSED_RESULTS, s.span, "unused result"); } - fn check_must_use(cx: &Context, attrs: &[hir::Attribute], sp: Span) -> bool { + fn check_must_use(cx: &LateContext, attrs: &[ast::Attribute], sp: Span) -> bool { for attr in attrs { if attr.check_name("must_use") { let mut msg = "unused result which must be used".to_string(); @@ -1050,7 +1060,7 @@ declare_lint! { pub struct NonCamelCaseTypes; impl NonCamelCaseTypes { - fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) { + fn check_case(&self, cx: &LateContext, sort: &str, ident: ast::Ident, span: Span) { fn is_camel_case(ident: ast::Ident) -> bool { let ident = ident.name.as_str(); if ident.is_empty() { @@ -1091,8 +1101,10 @@ impl LintPass for NonCamelCaseTypes { fn get_lints(&self) -> LintArray { lint_array!(NON_CAMEL_CASE_TYPES) } +} - fn check_item(&mut self, cx: &Context, it: &hir::Item) { +impl LateLintPass for NonCamelCaseTypes { + fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { let extern_repr_count = it.attrs.iter().filter(|attr| { attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter() .any(|r| r == &attr::ReprExtern) @@ -1123,7 +1135,7 @@ impl LintPass for NonCamelCaseTypes { } } - fn check_generics(&mut self, cx: &Context, it: &hir::Generics) { + fn check_generics(&mut self, cx: &LateContext, it: &hir::Generics) { for gen in it.ty_params.iter() { self.check_case(cx, "type parameter", gen.ident, gen.span); } @@ -1131,21 +1143,21 @@ impl LintPass for NonCamelCaseTypes { } #[derive(PartialEq)] -enum MethodContext { +enum MethodLateContext { TraitDefaultImpl, TraitImpl, PlainImpl } -fn method_context(cx: &Context, id: ast::NodeId, span: Span) -> MethodContext { +fn method_context(cx: &LateContext, id: ast::NodeId, span: Span) -> MethodLateContext { match cx.tcx.impl_or_trait_items.borrow().get(&DefId::local(id)) { None => cx.sess().span_bug(span, "missing method descriptor?!"), Some(item) => match item.container() { - ty::TraitContainer(..) => MethodContext::TraitDefaultImpl, + ty::TraitContainer(..) => MethodLateContext::TraitDefaultImpl, ty::ImplContainer(cid) => { match cx.tcx.impl_trait_ref(cid) { - Some(_) => MethodContext::TraitImpl, - None => MethodContext::PlainImpl + Some(_) => MethodLateContext::TraitImpl, + None => MethodLateContext::PlainImpl } } } @@ -1194,7 +1206,7 @@ impl NonSnakeCase { words.join("_") } - fn check_snake_case(&self, cx: &Context, sort: &str, name: &str, span: Option) { + fn check_snake_case(&self, cx: &LateContext, sort: &str, name: &str, span: Option) { fn is_snake_case(ident: &str) -> bool { if ident.is_empty() { return true; @@ -1237,8 +1249,10 @@ impl LintPass for NonSnakeCase { fn get_lints(&self) -> LintArray { lint_array!(NON_SNAKE_CASE) } +} - fn check_crate(&mut self, cx: &Context, cr: &hir::Crate) { +impl LateLintPass for NonSnakeCase { + fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) { let attr_crate_name = cr.attrs.iter().find(|at| at.check_name("crate_name")) .and_then(|at| at.value_str().map(|s| (at, s))); if let Some(ref name) = cx.tcx.sess.opts.crate_name { @@ -1248,15 +1262,15 @@ impl LintPass for NonSnakeCase { } } - fn check_fn(&mut self, cx: &Context, + fn check_fn(&mut self, cx: &LateContext, fk: FnKind, _: &hir::FnDecl, _: &hir::Block, span: Span, id: ast::NodeId) { match fk { FnKind::Method(ident, _, _) => match method_context(cx, id, span) { - MethodContext::PlainImpl => { + MethodLateContext::PlainImpl => { self.check_snake_case(cx, "method", &ident.name.as_str(), Some(span)) }, - MethodContext::TraitDefaultImpl => { + MethodLateContext::TraitDefaultImpl => { self.check_snake_case(cx, "trait method", &ident.name.as_str(), Some(span)) }, _ => (), @@ -1268,25 +1282,25 @@ impl LintPass for NonSnakeCase { } } - fn check_item(&mut self, cx: &Context, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { if let hir::ItemMod(_) = it.node { self.check_snake_case(cx, "module", &it.ident.name.as_str(), Some(it.span)); } } - fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) { + fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) { if let hir::MethodTraitItem(_, None) = trait_item.node { self.check_snake_case(cx, "trait method", &trait_item.ident.name.as_str(), Some(trait_item.span)); } } - fn check_lifetime_def(&mut self, cx: &Context, t: &hir::LifetimeDef) { + fn check_lifetime_def(&mut self, cx: &LateContext, t: &hir::LifetimeDef) { self.check_snake_case(cx, "lifetime", &t.lifetime.name.as_str(), Some(t.lifetime.span)); } - fn check_pat(&mut self, cx: &Context, p: &hir::Pat) { + fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) { if let &hir::PatIdent(_, ref path1, _) = &p.node { let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def()); if let Some(def::DefLocal(_)) = def { @@ -1295,7 +1309,7 @@ impl LintPass for NonSnakeCase { } } - fn check_struct_def(&mut self, cx: &Context, s: &hir::StructDef, + fn check_struct_def(&mut self, cx: &LateContext, s: &hir::StructDef, _: ast::Ident, _: &hir::Generics, _: ast::NodeId) { for sf in &s.fields { if let hir::StructField_ { kind: hir::NamedField(ident, _), .. } = sf.node { @@ -1316,7 +1330,7 @@ declare_lint! { pub struct NonUpperCaseGlobals; impl NonUpperCaseGlobals { - fn check_upper_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) { + fn check_upper_case(cx: &LateContext, sort: &str, ident: ast::Ident, span: Span) { let s = ident.name.as_str(); if s.chars().any(|c| c.is_lowercase()) { @@ -1338,8 +1352,10 @@ impl LintPass for NonUpperCaseGlobals { fn get_lints(&self) -> LintArray { lint_array!(NON_UPPER_CASE_GLOBALS) } +} - fn check_item(&mut self, cx: &Context, it: &hir::Item) { +impl LateLintPass for NonUpperCaseGlobals { + fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { match it.node { // only check static constants hir::ItemStatic(_, hir::MutImmutable, _) => { @@ -1352,7 +1368,7 @@ impl LintPass for NonUpperCaseGlobals { } } - fn check_trait_item(&mut self, cx: &Context, ti: &hir::TraitItem) { + fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) { match ti.node { hir::ConstTraitItem(..) => { NonUpperCaseGlobals::check_upper_case(cx, "associated constant", @@ -1362,7 +1378,7 @@ impl LintPass for NonUpperCaseGlobals { } } - fn check_impl_item(&mut self, cx: &Context, ii: &hir::ImplItem) { + fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) { match ii.node { hir::ConstImplItem(..) => { NonUpperCaseGlobals::check_upper_case(cx, "associated constant", @@ -1372,7 +1388,7 @@ impl LintPass for NonUpperCaseGlobals { } } - fn check_pat(&mut self, cx: &Context, p: &hir::Pat) { + fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) { // Lint for constants that look like binding identifiers (#7526) match (&p.node, cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def())) { (&hir::PatIdent(_, ref path1, _), Some(def::DefConst(..))) => { @@ -1394,9 +1410,9 @@ declare_lint! { pub struct UnusedParens; impl UnusedParens { - fn check_unused_parens_core(&self, cx: &Context, value: &hir::Expr, msg: &str, + fn check_unused_parens_core(&self, cx: &EarlyContext, value: &ast::Expr, msg: &str, struct_lit_needs_parens: bool) { - if let hir::ExprParen(ref inner) = value.node { + if let ast::ExprParen(ref inner) = value.node { let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner); if !necessary { cx.span_lint(UNUSED_PARENS, value.span, @@ -1409,27 +1425,27 @@ impl UnusedParens { /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X { /// y: 1 }) == foo` does not. - fn contains_exterior_struct_lit(value: &hir::Expr) -> bool { + fn contains_exterior_struct_lit(value: &ast::Expr) -> bool { match value.node { - hir::ExprStruct(..) => true, + ast::ExprStruct(..) => true, - hir::ExprAssign(ref lhs, ref rhs) | - hir::ExprAssignOp(_, ref lhs, ref rhs) | - hir::ExprBinary(_, ref lhs, ref rhs) => { + ast::ExprAssign(ref lhs, ref rhs) | + ast::ExprAssignOp(_, ref lhs, ref rhs) | + ast::ExprBinary(_, ref lhs, ref rhs) => { // X { y: 1 } + X { y: 2 } contains_exterior_struct_lit(&**lhs) || contains_exterior_struct_lit(&**rhs) } - hir::ExprUnary(_, ref x) | - hir::ExprCast(ref x, _) | - hir::ExprField(ref x, _) | - hir::ExprTupField(ref x, _) | - hir::ExprIndex(ref x, _) => { + ast::ExprUnary(_, ref x) | + ast::ExprCast(ref x, _) | + ast::ExprField(ref x, _) | + ast::ExprTupField(ref x, _) | + ast::ExprIndex(ref x, _) => { // &X { y: 1 }, X { y: 1 }.y contains_exterior_struct_lit(&**x) } - hir::ExprMethodCall(_, _, ref exprs) => { + ast::ExprMethodCall(_, _, ref exprs) => { // X { y: 1 }.bar(...) contains_exterior_struct_lit(&*exprs[0]) } @@ -1444,29 +1460,31 @@ impl LintPass for UnusedParens { fn get_lints(&self) -> LintArray { lint_array!(UNUSED_PARENS) } +} - fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { +impl EarlyLintPass for UnusedParens { + fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) { let (value, msg, struct_lit_needs_parens) = match e.node { - hir::ExprIf(ref cond, _, _) => (cond, "`if` condition", true), - hir::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true), - hir::ExprMatch(ref head, _, source) => match source { - hir::MatchSource::Normal => (head, "`match` head expression", true), - hir::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true), - hir::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true), - hir::MatchSource::ForLoopDesugar => (head, "`for` head expression", true), + ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true), + ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true), + ast::ExprMatch(ref head, _, source) => match source { + ast::MatchSource::Normal => (head, "`match` head expression", true), + ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true), + ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true), + ast::MatchSource::ForLoopDesugar => (head, "`for` head expression", true), }, - hir::ExprRet(Some(ref value)) => (value, "`return` value", false), - hir::ExprAssign(_, ref value) => (value, "assigned value", false), - hir::ExprAssignOp(_, _, ref value) => (value, "assigned value", false), + ast::ExprRet(Some(ref value)) => (value, "`return` value", false), + ast::ExprAssign(_, ref value) => (value, "assigned value", false), + ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false), _ => return }; self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens); } - fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) { + fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) { let (value, msg) = match s.node { - hir::StmtDecl(ref decl, _) => match decl.node { - hir::DeclLocal(ref local) => match local.init { + ast::StmtDecl(ref decl, _) => match decl.node { + ast::DeclLocal(ref local) => match local.init { Some(ref value) => (value, "assigned value"), None => return }, @@ -1491,8 +1509,10 @@ impl LintPass for UnusedImportBraces { fn get_lints(&self) -> LintArray { lint_array!(UNUSED_IMPORT_BRACES) } +} - fn check_item(&mut self, cx: &Context, item: &hir::Item) { +impl LateLintPass for UnusedImportBraces { + fn check_item(&mut self, cx: &LateContext, item: &hir::Item) { if let hir::ItemUse(ref view_path) = item.node { if let hir::ViewPathList(_, ref items) = view_path.node { if items.len() == 1 { @@ -1521,8 +1541,10 @@ impl LintPass for NonShorthandFieldPatterns { fn get_lints(&self) -> LintArray { lint_array!(NON_SHORTHAND_FIELD_PATTERNS) } +} - fn check_pat(&mut self, cx: &Context, pat: &hir::Pat) { +impl LateLintPass for NonShorthandFieldPatterns { + fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) { let def_map = cx.tcx.def_map.borrow(); if let hir::PatStruct(_, ref v, _) = pat.node { let field_pats = v.iter().filter(|fieldpat| { @@ -1560,8 +1582,10 @@ impl LintPass for UnusedUnsafe { fn get_lints(&self) -> LintArray { lint_array!(UNUSED_UNSAFE) } +} - fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { +impl LateLintPass for UnusedUnsafe { + fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { if let hir::ExprBlock(ref blk) = e.node { // Don't warn about generated blocks, that'll just pollute the output. if blk.rules == hir::UnsafeBlock(hir::UserProvided) && @@ -1585,8 +1609,10 @@ impl LintPass for UnsafeCode { fn get_lints(&self) -> LintArray { lint_array!(UNSAFE_CODE) } +} - fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { +impl LateLintPass for UnsafeCode { + fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { if let hir::ExprBlock(ref blk) = e.node { // Don't warn about generated blocks, that'll just pollute the output. if blk.rules == hir::UnsafeBlock(hir::UserProvided) { @@ -1595,7 +1621,7 @@ impl LintPass for UnsafeCode { } } - fn check_item(&mut self, cx: &Context, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { match it.node { hir::ItemTrait(hir::Unsafety::Unsafe, _, _, _) => cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait"), @@ -1607,7 +1633,7 @@ impl LintPass for UnsafeCode { } } - fn check_fn(&mut self, cx: &Context, fk: FnKind, _: &hir::FnDecl, + fn check_fn(&mut self, cx: &LateContext, fk: FnKind, _: &hir::FnDecl, _: &hir::Block, span: Span, _: ast::NodeId) { match fk { FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, _, _, _) => @@ -1623,7 +1649,7 @@ impl LintPass for UnsafeCode { } } - fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) { + fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) { if let hir::MethodTraitItem(ref sig, None) = trait_item.node { if sig.unsafety == hir::Unsafety::Unsafe { cx.span_lint(UNSAFE_CODE, trait_item.span, @@ -1643,7 +1669,7 @@ declare_lint! { pub struct UnusedMut; impl UnusedMut { - fn check_unused_mut_pat(&self, cx: &Context, pats: &[P]) { + fn check_unused_mut_pat(&self, cx: &LateContext, pats: &[P]) { // collect all mutable pattern and group their NodeIDs by their Identifier to // avoid false warnings in match arms with multiple patterns @@ -1676,8 +1702,10 @@ impl LintPass for UnusedMut { fn get_lints(&self) -> LintArray { lint_array!(UNUSED_MUT) } +} - fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { +impl LateLintPass for UnusedMut { + fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { if let hir::ExprMatch(_, ref arms, _) = e.node { for a in arms { self.check_unused_mut_pat(cx, &a.pats) @@ -1685,7 +1713,7 @@ impl LintPass for UnusedMut { } } - fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) { + fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) { if let hir::StmtDecl(ref d, _) = s.node { if let hir::DeclLocal(ref l) = d.node { self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat)); @@ -1693,7 +1721,7 @@ impl LintPass for UnusedMut { } } - fn check_fn(&mut self, cx: &Context, + fn check_fn(&mut self, cx: &LateContext, _: FnKind, decl: &hir::FnDecl, _: &hir::Block, _: Span, _: ast::NodeId) { for a in &decl.inputs { @@ -1715,8 +1743,10 @@ impl LintPass for UnusedAllocation { fn get_lints(&self) -> LintArray { lint_array!(UNUSED_ALLOCATION) } +} - fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { +impl LateLintPass for UnusedAllocation { + fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { match e.node { hir::ExprUnary(hir::UnUniq, _) => (), _ => return @@ -1778,9 +1808,9 @@ impl MissingDoc { } fn check_missing_docs_attrs(&self, - cx: &Context, + cx: &LateContext, id: Option, - attrs: &[hir::Attribute], + attrs: &[ast::Attribute], sp: Span, desc: &'static str) { // If we're building a test harness, then warning about @@ -1805,7 +1835,7 @@ impl MissingDoc { let has_doc = attrs.iter().any(|a| { match a.node.value.node { - hir::MetaNameValue(ref name, _) if *name == "doc" => true, + ast::MetaNameValue(ref name, _) if *name == "doc" => true, _ => false } }); @@ -1820,8 +1850,10 @@ impl LintPass for MissingDoc { fn get_lints(&self) -> LintArray { lint_array!(MISSING_DOCS) } +} - fn enter_lint_attrs(&mut self, _: &Context, attrs: &[hir::Attribute]) { +impl LateLintPass for MissingDoc { + fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) { let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| { attr.check_name("doc") && match attr.meta_item_list() { None => false, @@ -1831,26 +1863,26 @@ impl LintPass for MissingDoc { self.doc_hidden_stack.push(doc_hidden); } - fn exit_lint_attrs(&mut self, _: &Context, _: &[hir::Attribute]) { + fn exit_lint_attrs(&mut self, _: &LateContext, _: &[ast::Attribute]) { self.doc_hidden_stack.pop().expect("empty doc_hidden_stack"); } - fn check_struct_def(&mut self, _: &Context, _: &hir::StructDef, + fn check_struct_def(&mut self, _: &LateContext, _: &hir::StructDef, _: ast::Ident, _: &hir::Generics, id: ast::NodeId) { self.struct_def_stack.push(id); } - fn check_struct_def_post(&mut self, _: &Context, _: &hir::StructDef, + fn check_struct_def_post(&mut self, _: &LateContext, _: &hir::StructDef, _: ast::Ident, _: &hir::Generics, id: ast::NodeId) { let popped = self.struct_def_stack.pop().expect("empty struct_def_stack"); assert!(popped == id); } - fn check_crate(&mut self, cx: &Context, krate: &hir::Crate) { + fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) { self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate"); } - fn check_item(&mut self, cx: &Context, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { let desc = match it.node { hir::ItemFn(..) => "a function", hir::ItemMod(..) => "a module", @@ -1890,7 +1922,7 @@ impl LintPass for MissingDoc { self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc); } - fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) { + fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) { if self.private_traits.contains(&trait_item.id) { return } let desc = match trait_item.node { @@ -1904,9 +1936,9 @@ impl LintPass for MissingDoc { trait_item.span, desc); } - fn check_impl_item(&mut self, cx: &Context, impl_item: &hir::ImplItem) { + fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) { // If the method is an impl for a trait, don't doc. - if method_context(cx, impl_item.id, impl_item.span) == MethodContext::TraitImpl { + if method_context(cx, impl_item.id, impl_item.span) == MethodLateContext::TraitImpl { return; } @@ -1920,7 +1952,7 @@ impl LintPass for MissingDoc { impl_item.span, desc); } - fn check_struct_field(&mut self, cx: &Context, sf: &hir::StructField) { + fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) { if let hir::NamedField(_, vis) = sf.node.kind { if vis == hir::Public || self.in_variant { let cur_struct_def = *self.struct_def_stack.last() @@ -1932,13 +1964,13 @@ impl LintPass for MissingDoc { } } - fn check_variant(&mut self, cx: &Context, v: &hir::Variant, _: &hir::Generics) { + fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) { self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, v.span, "a variant"); assert!(!self.in_variant); self.in_variant = true; } - fn check_variant_post(&mut self, _: &Context, _: &hir::Variant, _: &hir::Generics) { + fn check_variant_post(&mut self, _: &LateContext, _: &hir::Variant, _: &hir::Generics) { assert!(self.in_variant); self.in_variant = false; } @@ -1957,8 +1989,10 @@ impl LintPass for MissingCopyImplementations { fn get_lints(&self) -> LintArray { lint_array!(MISSING_COPY_IMPLEMENTATIONS) } +} - fn check_item(&mut self, cx: &Context, item: &hir::Item) { +impl LateLintPass for MissingCopyImplementations { + fn check_item(&mut self, cx: &LateContext, item: &hir::Item) { if !cx.exported_items.contains(&item.id) { return; } @@ -2019,8 +2053,10 @@ impl LintPass for MissingDebugImplementations { fn get_lints(&self) -> LintArray { lint_array!(MISSING_DEBUG_IMPLEMENTATIONS) } +} - fn check_item(&mut self, cx: &Context, item: &hir::Item) { +impl LateLintPass for MissingDebugImplementations { + fn check_item(&mut self, cx: &LateContext, item: &hir::Item) { if !cx.exported_items.contains(&item.id) { return; } @@ -2070,7 +2106,7 @@ declare_lint! { pub struct Stability; impl Stability { - fn lint(&self, cx: &Context, _id: DefId, + fn lint(&self, cx: &LateContext, _id: DefId, span: Span, stability: &Option<&attr::Stability>) { // Deprecated attributes apply in-crate and cross-crate. let (lint, label) = match *stability { @@ -2081,7 +2117,7 @@ impl Stability { output(cx, span, stability, lint, label); - fn output(cx: &Context, span: Span, stability: &Option<&attr::Stability>, + fn output(cx: &LateContext, span: Span, stability: &Option<&attr::Stability>, lint: &'static Lint, label: &'static str) { let msg = match *stability { Some(&attr::Stability { reason: Some(ref s), .. }) => { @@ -2113,29 +2149,31 @@ impl LintPass for Stability { fn get_lints(&self) -> LintArray { lint_array!(DEPRECATED) } +} - fn check_item(&mut self, cx: &Context, item: &hir::Item) { +impl LateLintPass for Stability { + fn check_item(&mut self, cx: &LateContext, item: &hir::Item) { stability::check_item(cx.tcx, item, false, &mut |id, sp, stab| self.lint(cx, id, sp, &stab.map(|s| hir_to_ast_stability(s)).as_ref())); } - fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { + fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { stability::check_expr(cx.tcx, e, &mut |id, sp, stab| self.lint(cx, id, sp, &stab.map(|s| hir_to_ast_stability(s)).as_ref())); } - fn check_path(&mut self, cx: &Context, path: &hir::Path, id: ast::NodeId) { + fn check_path(&mut self, cx: &LateContext, path: &hir::Path, id: ast::NodeId) { stability::check_path(cx.tcx, path, id, &mut |id, sp, stab| self.lint(cx, id, sp, &stab.map(|s| hir_to_ast_stability(s)).as_ref())); } - fn check_pat(&mut self, cx: &Context, pat: &hir::Pat) { + fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) { stability::check_pat(cx.tcx, pat, &mut |id, sp, stab| self.lint(cx, id, sp, @@ -2157,8 +2195,10 @@ impl LintPass for UnconditionalRecursion { fn get_lints(&self) -> LintArray { lint_array![UNCONDITIONAL_RECURSION] } +} - fn check_fn(&mut self, cx: &Context, fn_kind: FnKind, _: &hir::FnDecl, +impl LateLintPass for UnconditionalRecursion { + fn check_fn(&mut self, cx: &LateContext, fn_kind: FnKind, _: &hir::FnDecl, blk: &hir::Block, sp: Span, id: ast::NodeId) { type F = for<'tcx> fn(&ty::ctxt<'tcx>, ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool; @@ -2404,8 +2444,10 @@ impl LintPass for PluginAsLibrary { fn get_lints(&self) -> LintArray { lint_array![PLUGIN_AS_LIBRARY] } +} - fn check_item(&mut self, cx: &Context, it: &hir::Item) { +impl LateLintPass for PluginAsLibrary { + fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { if cx.sess().plugin_registrar_fn.get().is_some() { // We're compiling a plugin; it's fine to link other plugins. return; @@ -2460,8 +2502,10 @@ impl LintPass for InvalidNoMangleItems { PRIVATE_NO_MANGLE_STATICS, NO_MANGLE_CONST_ITEMS) } +} - fn check_item(&mut self, cx: &Context, it: &hir::Item) { +impl LateLintPass for InvalidNoMangleItems { + fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { match it.node { hir::ItemFn(..) => { if attr::contains_name(&it.attrs, "no_mangle") && @@ -2506,8 +2550,10 @@ impl LintPass for MutableTransmutes { fn get_lints(&self) -> LintArray { lint_array!(MUTABLE_TRANSMUTES) } +} - fn check_expr(&mut self, cx: &Context, expr: &hir::Expr) { +impl LateLintPass for MutableTransmutes { + fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) { use syntax::abi::RustIntrinsic; let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\ @@ -2522,7 +2568,7 @@ impl LintPass for MutableTransmutes { _ => () } - fn get_transmute_from_to<'a, 'tcx>(cx: &Context<'a, 'tcx>, expr: &hir::Expr) + fn get_transmute_from_to<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr) -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> { match expr.node { hir::ExprPath(..) => (), @@ -2546,7 +2592,7 @@ impl LintPass for MutableTransmutes { None } - fn def_id_is_transmute(cx: &Context, def_id: DefId) -> bool { + fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool { match cx.tcx.lookup_item_type(def_id).ty.sty { ty::TyBareFn(_, ref bfty) if bfty.abi == RustIntrinsic => (), _ => return false @@ -2573,7 +2619,10 @@ impl LintPass for UnstableFeatures { fn get_lints(&self) -> LintArray { lint_array!(UNSTABLE_FEATURES) } - fn check_attribute(&mut self, ctx: &Context, attr: &hir::Attribute) { +} + +impl LateLintPass for UnstableFeatures { + fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) { if attr::contains_name(&[attr.node.value.clone()], "feature") { if let Some(items) = attr.node.value.meta_item_list() { for item in items { @@ -2599,7 +2648,10 @@ impl LintPass for DropWithReprExtern { fn get_lints(&self) -> LintArray { lint_array!(DROP_WITH_REPR_EXTERN) } - fn check_crate(&mut self, ctx: &Context, _: &hir::Crate) { +} + +impl LateLintPass for DropWithReprExtern { + fn check_crate(&mut self, ctx: &LateContext, _: &hir::Crate) { for dtor_did in ctx.tcx.destructors.borrow().iter() { let (drop_impl_did, dtor_self_type) = if dtor_did.is_local() { diff --git a/src/librustc_lint/lib.rs b/src/librustc_lint/lib.rs index 517a3d13ddf76..5338316406063 100644 --- a/src/librustc_lint/lib.rs +++ b/src/librustc_lint/lib.rs @@ -67,7 +67,15 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) { macro_rules! add_builtin { ($sess:ident, $($name:ident),*,) => ( {$( - store.register_pass($sess, false, box builtin::$name); + store.register_late_pass($sess, false, box builtin::$name); + )*} + ) + } + + macro_rules! add_early_builtin { + ($sess:ident, $($name:ident),*,) => ( + {$( + store.register_early_pass($sess, false, box builtin::$name); )*} ) } @@ -75,7 +83,7 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) { macro_rules! add_builtin_with_new { ($sess:ident, $($name:ident),*,) => ( {$( - store.register_pass($sess, false, box builtin::$name::new()); + store.register_late_pass($sess, false, box builtin::$name::new()); )*} ) } @@ -86,6 +94,10 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) { ) } + add_early_builtin!(sess, + UnusedParens, + ); + add_builtin!(sess, HardwiredLints, WhileTrue, @@ -97,7 +109,6 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) { NonCamelCaseTypes, NonSnakeCase, NonUpperCaseGlobals, - UnusedParens, UnusedImportBraces, NonShorthandFieldPatterns, UnusedUnsafe, @@ -130,7 +141,7 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) { UNUSED_UNSAFE, PATH_STATEMENTS); // We have one lint pass defined specially - store.register_pass(sess, false, box lint::GatherNodeLevels); + store.register_late_pass(sess, false, box lint::GatherNodeLevels); // Insert temporary renamings for a one-time deprecation store.register_renamed("raw_pointer_deriving", "raw_pointer_derive"); diff --git a/src/librustc_mir/build/expr/as_constant.rs b/src/librustc_mir/build/expr/as_constant.rs index a6d06c447a4c0..5d20fe4bab4fd 100644 --- a/src/librustc_mir/build/expr/as_constant.rs +++ b/src/librustc_mir/build/expr/as_constant.rs @@ -33,9 +33,6 @@ impl Builder { ExprKind::Scope { extent: _, value } => { return this.as_constant(value); } - ExprKind::Paren { arg } => { - return this.as_constant(arg); - } ExprKind::Literal { literal } => { ConstantKind::Literal(literal) } diff --git a/src/librustc_mir/build/expr/as_lvalue.rs b/src/librustc_mir/build/expr/as_lvalue.rs index 0ceafcc9a6266..ffbb9781bdce5 100644 --- a/src/librustc_mir/build/expr/as_lvalue.rs +++ b/src/librustc_mir/build/expr/as_lvalue.rs @@ -43,9 +43,6 @@ impl Builder { this.as_lvalue(block, value) }) } - ExprKind::Paren { arg } => { - this.as_lvalue(block, arg) - } ExprKind::Field { lhs, name } => { let lvalue = unpack!(block = this.as_lvalue(block, lhs)); let lvalue = lvalue.field(name); diff --git a/src/librustc_mir/build/expr/as_operand.rs b/src/librustc_mir/build/expr/as_operand.rs index ee090571b7cc5..0b236f3a1dcc3 100644 --- a/src/librustc_mir/build/expr/as_operand.rs +++ b/src/librustc_mir/build/expr/as_operand.rs @@ -39,16 +39,10 @@ impl Builder { block, expr); let this = self; - match expr.kind { - ExprKind::Scope { extent, value } => { - return this.in_scope(extent, block, |this| { - this.as_operand(block, value) - }); - } - ExprKind::Paren { arg } => { - return this.as_operand(block, arg); - } - _ => { } + if let ExprKind::Scope { extent, value } = expr.kind { + return this.in_scope(extent, block, |this| { + this.as_operand(block, value) + }); } let category = Category::of(&expr.kind).unwrap(); diff --git a/src/librustc_mir/build/expr/as_rvalue.rs b/src/librustc_mir/build/expr/as_rvalue.rs index e4d3ad21503ed..d03028ffea675 100644 --- a/src/librustc_mir/build/expr/as_rvalue.rs +++ b/src/librustc_mir/build/expr/as_rvalue.rs @@ -46,9 +46,6 @@ impl Builder { this.as_rvalue(block, value) }) } - ExprKind::Paren { arg } => { - this.as_rvalue(block, arg) - } ExprKind::InlineAsm { asm } => { block.and(Rvalue::InlineAsm(asm)) } diff --git a/src/librustc_mir/build/expr/as_temp.rs b/src/librustc_mir/build/expr/as_temp.rs index 50f04e0177b0b..cb652c8a5945e 100644 --- a/src/librustc_mir/build/expr/as_temp.rs +++ b/src/librustc_mir/build/expr/as_temp.rs @@ -37,16 +37,10 @@ impl Builder { block, expr); let this = self; - match expr.kind { - ExprKind::Scope { extent, value } => { - return this.in_scope(extent, block, |this| { - this.as_temp(block, value) - }); - } - ExprKind::Paren { arg } => { - return this.as_temp(block, arg); - } - _ => { } + if let ExprKind::Scope { extent, value } = expr.kind { + return this.in_scope(extent, block, |this| { + this.as_temp(block, value) + }); } let expr_ty = expr.ty.clone(); diff --git a/src/librustc_mir/build/expr/category.rs b/src/librustc_mir/build/expr/category.rs index 1f9928acdc81b..9cab2976b2c61 100644 --- a/src/librustc_mir/build/expr/category.rs +++ b/src/librustc_mir/build/expr/category.rs @@ -43,9 +43,7 @@ pub enum RvalueFunc { impl Category { pub fn of(ek: &ExprKind) -> Option { match *ek { - ExprKind::Scope { .. } | - ExprKind::Paren { .. } => - None, + ExprKind::Scope { .. } => None, ExprKind::Field { .. } | ExprKind::Deref { .. } | diff --git a/src/librustc_mir/build/expr/into.rs b/src/librustc_mir/build/expr/into.rs index b409903ad7eb5..72e505f2b6edd 100644 --- a/src/librustc_mir/build/expr/into.rs +++ b/src/librustc_mir/build/expr/into.rs @@ -40,9 +40,6 @@ impl Builder { this.into(destination, block, value) }) } - ExprKind::Paren { arg } => { - this.into(destination, block, arg) - } ExprKind::Block { body: ast_block } => { this.ast_block(destination, block, ast_block) } diff --git a/src/librustc_mir/dump.rs b/src/librustc_mir/dump.rs index 8e608de024e84..9b3514028afad 100644 --- a/src/librustc_mir/dump.rs +++ b/src/librustc_mir/dump.rs @@ -32,9 +32,9 @@ use self::rustc::middle::region::CodeExtentData; use self::rustc::middle::ty::{self, Ty}; use self::rustc::util::common::ErrorReported; use self::rustc_front::hir; -use self::rustc_front::attr::{AttrMetaMethods}; use self::rustc_front::visit; use self::syntax::ast; +use self::syntax::attr::AttrMetaMethods; use self::syntax::codemap::Span; pub fn dump_crate(tcx: &ty::ctxt) { @@ -50,7 +50,7 @@ struct OuterDump<'a,'tcx:'a> { } impl<'a, 'tcx> OuterDump<'a, 'tcx> { - fn visit_mir(&self, attributes: &'tcx [hir::Attribute], mut walk_op: OP) + fn visit_mir(&self, attributes: &'tcx [ast::Attribute], mut walk_op: OP) where OP: FnMut(&mut InnerDump<'a,'tcx>) { let mut built_mir = false; @@ -94,7 +94,7 @@ impl<'a, 'tcx> visit::Visitor<'tcx> for OuterDump<'a, 'tcx> { struct InnerDump<'a,'tcx:'a> { tcx: &'a ty::ctxt<'tcx>, - attr: Option<&'a hir::Attribute>, + attr: Option<&'a ast::Attribute>, } impl<'a, 'tcx> visit::Visitor<'tcx> for InnerDump<'a,'tcx> { diff --git a/src/librustc_mir/hair.rs b/src/librustc_mir/hair.rs index c63a034833712..f1450522dd83e 100644 --- a/src/librustc_mir/hair.rs +++ b/src/librustc_mir/hair.rs @@ -171,7 +171,6 @@ pub struct Expr { #[derive(Clone, Debug)] pub enum ExprKind { Scope { extent: H::CodeExtent, value: ExprRef }, - Paren { arg: ExprRef }, // ugh. should be able to remove this! Box { place: Option>, value: ExprRef }, Call { fun: ExprRef, args: Vec> }, Deref { arg: ExprRef }, // NOT overloaded! diff --git a/src/librustc_mir/tcx/expr.rs b/src/librustc_mir/tcx/expr.rs index f15470e7851d4..7e68993b1309b 100644 --- a/src/librustc_mir/tcx/expr.rs +++ b/src/librustc_mir/tcx/expr.rs @@ -23,6 +23,7 @@ use tcx::rustc::middle::pat_util; use tcx::rustc::middle::ty::{self, Ty}; use tcx::rustc_front::hir; use tcx::rustc_front::util as hir_util; +use tcx::syntax::ast; use tcx::syntax::codemap::Span; use tcx::syntax::parse::token; use tcx::syntax::ptr::P; @@ -266,8 +267,6 @@ impl<'a,'tcx:'a> Mirror> for &'tcx hir::Expr { // Now comes the rote stuff: - hir::ExprParen(ref p) => - ExprKind::Paren { arg: p.to_ref() }, hir::ExprRepeat(ref v, ref c) => ExprKind::Repeat { value: v.to_ref(), count: c.to_ref() }, hir::ExprRet(ref v) => @@ -462,56 +461,56 @@ fn to_borrow_kind(m: hir::Mutability) -> BorrowKind { fn convert_literal<'a,'tcx:'a>(cx: &mut Cx<'a,'tcx>, expr_span: Span, expr_ty: Ty<'tcx>, - literal: &hir::Lit) + literal: &ast::Lit) -> Literal> { use repr::IntegralBits::*; match (&literal.node, &expr_ty.sty) { - (&hir::LitStr(ref text, _), _) => + (&ast::LitStr(ref text, _), _) => Literal::String { value: text.clone() }, - (&hir::LitByteStr(ref bytes), _) => + (&ast::LitByteStr(ref bytes), _) => Literal::Bytes { value: bytes.clone() }, - (&hir::LitByte(c), _) => + (&ast::LitByte(c), _) => Literal::Uint { bits: B8, value: c as u64 }, - (&hir::LitChar(c), _) => + (&ast::LitChar(c), _) => Literal::Char { c: c }, - (&hir::LitInt(v, _), &ty::TyUint(hir::TyU8)) => + (&ast::LitInt(v, _), &ty::TyUint(ast::TyU8)) => Literal::Uint { bits: B8, value: v }, - (&hir::LitInt(v, _), &ty::TyUint(hir::TyU16)) => + (&ast::LitInt(v, _), &ty::TyUint(ast::TyU16)) => Literal::Uint { bits: B16, value: v }, - (&hir::LitInt(v, _), &ty::TyUint(hir::TyU32)) => + (&ast::LitInt(v, _), &ty::TyUint(ast::TyU32)) => Literal::Uint { bits: B32, value: v }, - (&hir::LitInt(v, _), &ty::TyUint(hir::TyU64)) => + (&ast::LitInt(v, _), &ty::TyUint(ast::TyU64)) => Literal::Uint { bits: B64, value: v }, - (&hir::LitInt(v, _), &ty::TyUint(hir::TyUs)) => + (&ast::LitInt(v, _), &ty::TyUint(ast::TyUs)) => Literal::Uint { bits: BSize, value: v }, - (&hir::LitInt(v, hir::SignedIntLit(_, hir::Sign::Minus)), &ty::TyInt(hir::TyI8)) => + (&ast::LitInt(v, ast::SignedIntLit(_, ast::Sign::Minus)), &ty::TyInt(ast::TyI8)) => Literal::Int { bits: B8, value: -(v as i64) }, - (&hir::LitInt(v, hir::SignedIntLit(_, hir::Sign::Minus)), &ty::TyInt(hir::TyI16)) => + (&ast::LitInt(v, ast::SignedIntLit(_, ast::Sign::Minus)), &ty::TyInt(ast::TyI16)) => Literal::Int { bits: B16, value: -(v as i64) }, - (&hir::LitInt(v, hir::SignedIntLit(_, hir::Sign::Minus)), &ty::TyInt(hir::TyI32)) => + (&ast::LitInt(v, ast::SignedIntLit(_, ast::Sign::Minus)), &ty::TyInt(ast::TyI32)) => Literal::Int { bits: B32, value: -(v as i64) }, - (&hir::LitInt(v, hir::SignedIntLit(_, hir::Sign::Minus)), &ty::TyInt(hir::TyI64)) => + (&ast::LitInt(v, ast::SignedIntLit(_, ast::Sign::Minus)), &ty::TyInt(ast::TyI64)) => Literal::Int { bits: B64, value: -(v as i64) }, - (&hir::LitInt(v, hir::SignedIntLit(_, hir::Sign::Minus)), &ty::TyInt(hir::TyIs)) => + (&ast::LitInt(v, ast::SignedIntLit(_, ast::Sign::Minus)), &ty::TyInt(ast::TyIs)) => Literal::Int { bits: BSize, value: -(v as i64) }, - (&hir::LitInt(v, _), &ty::TyInt(hir::TyI8)) => + (&ast::LitInt(v, _), &ty::TyInt(ast::TyI8)) => Literal::Int { bits: B8, value: v as i64 }, - (&hir::LitInt(v, _), &ty::TyInt(hir::TyI16)) => + (&ast::LitInt(v, _), &ty::TyInt(ast::TyI16)) => Literal::Int { bits: B16, value: v as i64 }, - (&hir::LitInt(v, _), &ty::TyInt(hir::TyI32)) => + (&ast::LitInt(v, _), &ty::TyInt(ast::TyI32)) => Literal::Int { bits: B32, value: v as i64 }, - (&hir::LitInt(v, _), &ty::TyInt(hir::TyI64)) => + (&ast::LitInt(v, _), &ty::TyInt(ast::TyI64)) => Literal::Int { bits: B64, value: v as i64 }, - (&hir::LitInt(v, _), &ty::TyInt(hir::TyIs)) => + (&ast::LitInt(v, _), &ty::TyInt(ast::TyIs)) => Literal::Int { bits: BSize, value: v as i64 }, - (&hir::LitFloat(ref v, _), &ty::TyFloat(hir::TyF32)) | - (&hir::LitFloatUnsuffixed(ref v), &ty::TyFloat(hir::TyF32)) => + (&ast::LitFloat(ref v, _), &ty::TyFloat(ast::TyF32)) | + (&ast::LitFloatUnsuffixed(ref v), &ty::TyFloat(ast::TyF32)) => Literal::Float { bits: FloatBits::F32, value: v.parse::().unwrap() }, - (&hir::LitFloat(ref v, _), &ty::TyFloat(hir::TyF64)) | - (&hir::LitFloatUnsuffixed(ref v), &ty::TyFloat(hir::TyF64)) => + (&ast::LitFloat(ref v, _), &ty::TyFloat(ast::TyF64)) | + (&ast::LitFloatUnsuffixed(ref v), &ty::TyFloat(ast::TyF64)) => Literal::Float { bits: FloatBits::F64, value: v.parse::().unwrap() }, - (&hir::LitBool(v), _) => + (&ast::LitBool(v), _) => Literal::Bool { value: v }, (ref l, ref t) => cx.tcx.sess.span_bug( diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index 6e72e51d9fefa..1a2498420faa2 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -37,6 +37,7 @@ use rustc::middle::def::*; use rustc::middle::def_id::DefId; use syntax::ast::{Name, NodeId}; +use syntax::attr::AttrMetaMethods; use syntax::parse::token::special_idents; use syntax::codemap::{Span, DUMMY_SP}; @@ -53,7 +54,6 @@ use rustc_front::hir::TupleVariantKind; use rustc_front::hir::UnnamedField; use rustc_front::hir::{Variant, ViewPathGlob, ViewPathList, ViewPathSimple}; use rustc_front::hir::Visibility; -use rustc_front::attr::AttrMetaMethods; use rustc_front::visit::{self, Visitor}; use std::mem::replace; diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 79aa4e535220e..8e34118957ebd 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -65,7 +65,8 @@ use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap}; use rustc::util::lev_distance::lev_distance; use syntax::ast; -use syntax::ast::{Ident, Name, NodeId, CrateNum}; +use syntax::ast::{Ident, Name, NodeId, CrateNum, TyIs, TyI8, TyI16, TyI32, TyI64}; +use syntax::ast::{TyUs, TyU8, TyU16, TyU32, TyU64, TyF64, TyF32}; use syntax::attr::AttrMetaMethods; use syntax::ext::mtwt; use syntax::parse::token::{self, special_names, special_idents}; @@ -86,10 +87,8 @@ use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse}; use rustc_front::hir::{Local, MethodImplItem}; use rustc_front::hir::{Pat, PatEnum, PatIdent, PatLit, PatQPath}; use rustc_front::hir::{PatRange, PatStruct, Path, PrimTy}; -use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyF32}; -use rustc_front::hir::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt}; -use rustc_front::hir::{TyPath, TyPtr}; -use rustc_front::hir::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint}; +use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt}; +use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr}; use rustc_front::hir::TypeImplItem; use rustc_front::util::walk_pat; diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index d5486e84fc431..83e33ede6f23f 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -46,7 +46,6 @@ use syntax::ast; use syntax::codemap::Span; use syntax::parse::token; use syntax::attr::AttrMetaMethods; -use rustc_front::attr::AttrMetaMethods as FrontAttrMetaMethods; use rustc_front::hir; diff --git a/src/librustc_trans/trans/_match.rs b/src/librustc_trans/trans/_match.rs index c6866004df949..aaa10aacd036b 100644 --- a/src/librustc_trans/trans/_match.rs +++ b/src/librustc_trans/trans/_match.rs @@ -905,7 +905,7 @@ fn compare_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>, compare_str(cx, lhs_data, lhs_len, rhs_data, rhs_len, rhs_t, debug_loc) } ty::TyArray(ty, _) | ty::TySlice(ty) => match ty.sty { - ty::TyUint(hir::TyU8) => { + ty::TyUint(ast::TyU8) => { // NOTE: cast &[u8] and &[u8; N] to &str and abuse the str_eq lang item, // which calls memcmp(). let pat_len = val_ty(rhs).element_type().array_length(); diff --git a/src/librustc_trans/trans/adt.rs b/src/librustc_trans/trans/adt.rs index 9b630037fe826..de09e33ec1427 100644 --- a/src/librustc_trans/trans/adt.rs +++ b/src/librustc_trans/trans/adt.rs @@ -51,9 +51,8 @@ use middle::subst; use middle::ty::{self, Ty}; use middle::ty::Disr; use syntax::ast; -use rustc_front::attr; -use rustc_front::attr::IntType; -use rustc_front::hir; +use syntax::attr; +use syntax::attr::IntType; use trans::_match; use trans::build::*; use trans::cleanup; @@ -387,11 +386,11 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, let ity = if use_align { // Use the overall alignment match align { - 1 => attr::UnsignedInt(hir::TyU8), - 2 => attr::UnsignedInt(hir::TyU16), - 4 => attr::UnsignedInt(hir::TyU32), + 1 => attr::UnsignedInt(ast::TyU8), + 2 => attr::UnsignedInt(ast::TyU16), + 4 => attr::UnsignedInt(ast::TyU32), 8 if machine::llalign_of_min(cx, Type::i64(cx)) == 8 => - attr::UnsignedInt(hir::TyU64), + attr::UnsignedInt(ast::TyU64), _ => min_ity // use min_ity as a fallback } } else { @@ -583,12 +582,12 @@ fn range_to_inttype(cx: &CrateContext, hint: Hint, bounds: &IntBounds) -> IntTyp // Lists of sizes to try. u64 is always allowed as a fallback. #[allow(non_upper_case_globals)] const choose_shortest: &'static [IntType] = &[ - attr::UnsignedInt(hir::TyU8), attr::SignedInt(hir::TyI8), - attr::UnsignedInt(hir::TyU16), attr::SignedInt(hir::TyI16), - attr::UnsignedInt(hir::TyU32), attr::SignedInt(hir::TyI32)]; + attr::UnsignedInt(ast::TyU8), attr::SignedInt(ast::TyI8), + attr::UnsignedInt(ast::TyU16), attr::SignedInt(ast::TyI16), + attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)]; #[allow(non_upper_case_globals)] const at_least_32: &'static [IntType] = &[ - attr::UnsignedInt(hir::TyU32), attr::SignedInt(hir::TyI32)]; + attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)]; let attempts; match hint { @@ -622,7 +621,7 @@ fn range_to_inttype(cx: &CrateContext, hint: Hint, bounds: &IntBounds) -> IntTyp return ity; } } - return attr::UnsignedInt(hir::TyU64); + return attr::UnsignedInt(ast::TyU64); } pub fn ll_inttype(cx: &CrateContext, ity: IntType) -> Type { diff --git a/src/librustc_trans/trans/attributes.rs b/src/librustc_trans/trans/attributes.rs index c77cb49144818..af4c2205e659b 100644 --- a/src/librustc_trans/trans/attributes.rs +++ b/src/librustc_trans/trans/attributes.rs @@ -15,8 +15,9 @@ use middle::ty; use middle::infer; use session::config::NoDebugInfo; use syntax::abi; +pub use syntax::attr::InlineAttr; +use syntax::ast; use rustc_front::hir; -pub use rustc_front::attr::InlineAttr; use trans::base; use trans::common; use trans::context::CrateContext; @@ -90,8 +91,8 @@ pub fn set_optimize_for_size(val: ValueRef, optimize: bool) { /// Composite function which sets LLVM attributes for function depending on its AST (#[attribute]) /// attributes. -pub fn from_fn_attrs(ccx: &CrateContext, attrs: &[hir::Attribute], llfn: ValueRef) { - use rustc_front::attr::*; +pub fn from_fn_attrs(ccx: &CrateContext, attrs: &[ast::Attribute], llfn: ValueRef) { + use syntax::attr::*; inline(llfn, find_inline_attr(Some(ccx.sess().diagnostic()), attrs)); // FIXME: #11906: Omitting frame pointers breaks retrieving the value of a diff --git a/src/librustc_trans/trans/base.rs b/src/librustc_trans/trans/base.rs index 1359252e0351a..89bd247b893a8 100644 --- a/src/librustc_trans/trans/base.rs +++ b/src/librustc_trans/trans/base.rs @@ -95,9 +95,9 @@ use std::{i8, i16, i32, i64}; use syntax::abi::{Rust, RustCall, RustIntrinsic, PlatformIntrinsic, Abi}; use syntax::codemap::Span; use syntax::parse::token::InternedString; +use syntax::attr::AttrMetaMethods; +use syntax::attr; use rustc_front; -use rustc_front::attr::AttrMetaMethods; -use rustc_front::attr; use rustc_front::visit::Visitor; use rustc_front::visit; use rustc_front::hir; @@ -581,12 +581,12 @@ pub fn llty_and_min_for_signed_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, ty::TyInt(t) => { let llty = Type::int_from_ty(cx.ccx(), t); let min = match t { - hir::TyIs if llty == Type::i32(cx.ccx()) => i32::MIN as u64, - hir::TyIs => i64::MIN as u64, - hir::TyI8 => i8::MIN as u64, - hir::TyI16 => i16::MIN as u64, - hir::TyI32 => i32::MIN as u64, - hir::TyI64 => i64::MIN as u64, + ast::TyIs if llty == Type::i32(cx.ccx()) => i32::MIN as u64, + ast::TyIs => i64::MIN as u64, + ast::TyI8 => i8::MIN as u64, + ast::TyI16 => i16::MIN as u64, + ast::TyI32 => i32::MIN as u64, + ast::TyI64 => i64::MIN as u64, }; (llty, min) } @@ -1563,7 +1563,7 @@ pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>, llfndecl: ValueRef, param_substs: &'tcx Substs<'tcx>, fn_ast_id: ast::NodeId, - _attributes: &[hir::Attribute], + _attributes: &[ast::Attribute], output_type: ty::FnOutput<'tcx>, abi: Abi, closure_env: closure::ClosureEnv<'b>) { @@ -1682,7 +1682,7 @@ pub fn trans_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, llfndecl: ValueRef, param_substs: &'tcx Substs<'tcx>, id: ast::NodeId, - attrs: &[hir::Attribute]) { + attrs: &[ast::Attribute]) { let _s = StatRecorder::new(ccx, ccx.tcx().map.path_to_string(id).to_string()); debug!("trans_fn(param_substs={:?})", param_substs); let _icx = push_ctxt("trans_fn"); @@ -2294,7 +2294,7 @@ pub fn create_entry_wrapper(ccx: &CrateContext, } fn exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, id: ast::NodeId, - ty: Ty<'tcx>, attrs: &[hir::Attribute]) -> String { + ty: Ty<'tcx>, attrs: &[ast::Attribute]) -> String { match ccx.external_srcs().borrow().get(&id) { Some(&did) => { let sym = csearch::get_symbol(&ccx.sess().cstore, did); @@ -2492,7 +2492,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef { } fn register_method(ccx: &CrateContext, id: ast::NodeId, - attrs: &[hir::Attribute], span: Span) -> ValueRef { + attrs: &[ast::Attribute], span: Span) -> ValueRef { let mty = ccx.tcx().node_id_to_type(id); let sym = exported_name(ccx, id, mty, &attrs); diff --git a/src/librustc_trans/trans/consts.rs b/src/librustc_trans/trans/consts.rs index a2d74635b5e1c..1d0c5137eceaa 100644 --- a/src/librustc_trans/trans/consts.rs +++ b/src/librustc_trans/trans/consts.rs @@ -41,30 +41,30 @@ use middle::ty::cast::{CastTy,IntTy}; use util::nodemap::NodeMap; use rustc_front::hir; -use rustc_front::attr; use std::ffi::{CStr, CString}; use libc::c_uint; use syntax::ast; +use syntax::attr; use syntax::parse::token; use syntax::ptr::P; pub type FnArgMap<'a> = Option<&'a NodeMap>; -pub fn const_lit(cx: &CrateContext, e: &hir::Expr, lit: &hir::Lit) +pub fn const_lit(cx: &CrateContext, e: &hir::Expr, lit: &ast::Lit) -> ValueRef { let _icx = push_ctxt("trans_lit"); debug!("const_lit: {:?}", lit); match lit.node { - hir::LitByte(b) => C_integral(Type::uint_from_ty(cx, hir::TyU8), b as u64, false), - hir::LitChar(i) => C_integral(Type::char(cx), i as u64, false), - hir::LitInt(i, hir::SignedIntLit(t, _)) => { + ast::LitByte(b) => C_integral(Type::uint_from_ty(cx, ast::TyU8), b as u64, false), + ast::LitChar(i) => C_integral(Type::char(cx), i as u64, false), + ast::LitInt(i, ast::SignedIntLit(t, _)) => { C_integral(Type::int_from_ty(cx, t), i, true) } - hir::LitInt(u, hir::UnsignedIntLit(t)) => { + ast::LitInt(u, ast::UnsignedIntLit(t)) => { C_integral(Type::uint_from_ty(cx, t), u, false) } - hir::LitInt(i, hir::UnsuffixedIntLit(_)) => { + ast::LitInt(i, ast::UnsuffixedIntLit(_)) => { let lit_int_ty = cx.tcx().node_id_to_type(e.id); match lit_int_ty.sty { ty::TyInt(t) => { @@ -79,10 +79,10 @@ pub fn const_lit(cx: &CrateContext, e: &hir::Expr, lit: &hir::Lit) lit_int_ty)) } } - hir::LitFloat(ref fs, t) => { + ast::LitFloat(ref fs, t) => { C_floating(&fs, Type::float_from_ty(cx, t)) } - hir::LitFloatUnsuffixed(ref fs) => { + ast::LitFloatUnsuffixed(ref fs) => { let lit_float_ty = cx.tcx().node_id_to_type(e.id); match lit_float_ty.sty { ty::TyFloat(t) => { @@ -94,9 +94,9 @@ pub fn const_lit(cx: &CrateContext, e: &hir::Expr, lit: &hir::Lit) } } } - hir::LitBool(b) => C_bool(cx, b), - hir::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()), - hir::LitByteStr(ref data) => { + ast::LitBool(b) => C_bool(cx, b), + ast::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()), + ast::LitByteStr(ref data) => { addr_of(cx, C_bytes(cx, &data[..]), "byte_str") } } @@ -703,7 +703,6 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, let mut cur = sub; loop { match cur.node { - hir::ExprParen(ref sub) => cur = sub, hir::ExprBlock(ref blk) => { if let Some(ref sub) = blk.expr { cur = sub; @@ -830,7 +829,6 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, let mut callee = &**callee; loop { callee = match callee.node { - hir::ExprParen(ref inner) => &**inner, hir::ExprBlock(ref block) => match block.expr { Some(ref tail) => &**tail, None => break, @@ -870,7 +868,6 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, const_fn_call(cx, MethodCallKey(method_call), method_did, &arg_vals, param_substs) }, - hir::ExprParen(ref e) => const_expr(cx, &**e, param_substs, fn_args).0, hir::ExprBlock(ref block) => { match block.expr { Some(ref expr) => const_expr(cx, &**expr, param_substs, fn_args).0, @@ -898,7 +895,7 @@ pub fn trans_static(ccx: &CrateContext, m: hir::Mutability, expr: &hir::Expr, id: ast::NodeId, - attrs: &Vec) + attrs: &Vec) -> ValueRef { unsafe { let _icx = push_ctxt("trans_static"); diff --git a/src/librustc_trans/trans/debuginfo/create_scope_map.rs b/src/librustc_trans/trans/debuginfo/create_scope_map.rs index ca616b5622a64..828086800499a 100644 --- a/src/librustc_trans/trans/debuginfo/create_scope_map.rs +++ b/src/librustc_trans/trans/debuginfo/create_scope_map.rs @@ -322,8 +322,7 @@ fn walk_expr(cx: &CrateContext, hir::ExprCast(ref sub_exp, _) | hir::ExprAddrOf(_, ref sub_exp) | hir::ExprField(ref sub_exp, _) | - hir::ExprTupField(ref sub_exp, _) | - hir::ExprParen(ref sub_exp) => + hir::ExprTupField(ref sub_exp, _) => walk_expr(cx, &**sub_exp, scope_stack, scope_map), hir::ExprBox(ref place, ref sub_expr) => { diff --git a/src/librustc_trans/trans/debuginfo/gdb.rs b/src/librustc_trans/trans/debuginfo/gdb.rs index 3d330fc1c7116..f7b0f37c9ff78 100644 --- a/src/librustc_trans/trans/debuginfo/gdb.rs +++ b/src/librustc_trans/trans/debuginfo/gdb.rs @@ -20,7 +20,7 @@ use session::config::NoDebugInfo; use std::ffi::CString; use std::ptr; -use rustc_front::attr; +use syntax::attr; /// Inserts a side-effect free instruction sequence that makes sure that the diff --git a/src/librustc_trans/trans/debuginfo/metadata.rs b/src/librustc_trans/trans/debuginfo/metadata.rs index a68eab953c3fa..33d79662d39da 100644 --- a/src/librustc_trans/trans/debuginfo/metadata.rs +++ b/src/librustc_trans/trans/debuginfo/metadata.rs @@ -27,7 +27,6 @@ use middle::def_id::DefId; use middle::pat_util; use middle::subst::{self, Substs}; use rustc::front::map as hir_map; -use rustc_front; use rustc_front::hir; use trans::{type_of, adt, machine, monomorphize}; use trans::common::{self, CrateContext, FunctionContext, Block}; @@ -43,6 +42,7 @@ use std::ffi::CString; use std::path::Path; use std::ptr; use std::rc::Rc; +use syntax; use syntax::util::interner::Interner; use syntax::codemap::Span; use syntax::{ast, codemap}; @@ -934,22 +934,22 @@ fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, ty::TyBool => ("bool".to_string(), DW_ATE_boolean), ty::TyChar => ("char".to_string(), DW_ATE_unsigned_char), ty::TyInt(int_ty) => match int_ty { - hir::TyIs => ("isize".to_string(), DW_ATE_signed), - hir::TyI8 => ("i8".to_string(), DW_ATE_signed), - hir::TyI16 => ("i16".to_string(), DW_ATE_signed), - hir::TyI32 => ("i32".to_string(), DW_ATE_signed), - hir::TyI64 => ("i64".to_string(), DW_ATE_signed) + ast::TyIs => ("isize".to_string(), DW_ATE_signed), + ast::TyI8 => ("i8".to_string(), DW_ATE_signed), + ast::TyI16 => ("i16".to_string(), DW_ATE_signed), + ast::TyI32 => ("i32".to_string(), DW_ATE_signed), + ast::TyI64 => ("i64".to_string(), DW_ATE_signed) }, ty::TyUint(uint_ty) => match uint_ty { - hir::TyUs => ("usize".to_string(), DW_ATE_unsigned), - hir::TyU8 => ("u8".to_string(), DW_ATE_unsigned), - hir::TyU16 => ("u16".to_string(), DW_ATE_unsigned), - hir::TyU32 => ("u32".to_string(), DW_ATE_unsigned), - hir::TyU64 => ("u64".to_string(), DW_ATE_unsigned) + ast::TyUs => ("usize".to_string(), DW_ATE_unsigned), + ast::TyU8 => ("u8".to_string(), DW_ATE_unsigned), + ast::TyU16 => ("u16".to_string(), DW_ATE_unsigned), + ast::TyU32 => ("u32".to_string(), DW_ATE_unsigned), + ast::TyU64 => ("u64".to_string(), DW_ATE_unsigned) }, ty::TyFloat(float_ty) => match float_ty { - hir::TyF32 => ("f32".to_string(), DW_ATE_float), - hir::TyF64 => ("f64".to_string(), DW_ATE_float), + ast::TyF32 => ("f32".to_string(), DW_ATE_float), + ast::TyF64 => ("f64".to_string(), DW_ATE_float), }, _ => cx.sess().bug("debuginfo::basic_type_metadata - t is invalid type") }; @@ -1608,7 +1608,7 @@ fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, }) .collect(); - let discriminant_type_metadata = |inttype: rustc_front::attr::IntType| { + let discriminant_type_metadata = |inttype: syntax::attr::IntType| { let disr_type_key = (enum_def_id, inttype); let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types .borrow() diff --git a/src/librustc_trans/trans/debuginfo/mod.rs b/src/librustc_trans/trans/debuginfo/mod.rs index dbb1355c9e612..10b9ee2ac7502 100644 --- a/src/librustc_trans/trans/debuginfo/mod.rs +++ b/src/librustc_trans/trans/debuginfo/mod.rs @@ -31,7 +31,6 @@ use middle::infer::normalize_associated_type; use middle::subst::{self, Substs}; use rustc_front; use rustc_front::hir; -use rustc_front::attr::IntType; use trans::common::{NodeIdAndSpan, CrateContext, FunctionContext, Block}; use trans; @@ -49,6 +48,7 @@ use std::rc::Rc; use syntax::codemap::{Span, Pos}; use syntax::{abi, ast, codemap}; +use syntax::attr::IntType; use syntax::parse::token::{self, special_idents}; pub mod gdb; diff --git a/src/librustc_trans/trans/debuginfo/type_names.rs b/src/librustc_trans/trans/debuginfo/type_names.rs index 425364407b51b..7400ec3cbcd4a 100644 --- a/src/librustc_trans/trans/debuginfo/type_names.rs +++ b/src/librustc_trans/trans/debuginfo/type_names.rs @@ -18,7 +18,7 @@ use middle::subst::{self, Substs}; use middle::ty::{self, Ty}; use rustc_front::hir; - +use syntax::ast; // Compute the name of the type as it should be stored in debuginfo. Does not do // any caching, i.e. calling the function twice with the same type will also do @@ -43,18 +43,18 @@ pub fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, ty::TyBool => output.push_str("bool"), ty::TyChar => output.push_str("char"), ty::TyStr => output.push_str("str"), - ty::TyInt(hir::TyIs) => output.push_str("isize"), - ty::TyInt(hir::TyI8) => output.push_str("i8"), - ty::TyInt(hir::TyI16) => output.push_str("i16"), - ty::TyInt(hir::TyI32) => output.push_str("i32"), - ty::TyInt(hir::TyI64) => output.push_str("i64"), - ty::TyUint(hir::TyUs) => output.push_str("usize"), - ty::TyUint(hir::TyU8) => output.push_str("u8"), - ty::TyUint(hir::TyU16) => output.push_str("u16"), - ty::TyUint(hir::TyU32) => output.push_str("u32"), - ty::TyUint(hir::TyU64) => output.push_str("u64"), - ty::TyFloat(hir::TyF32) => output.push_str("f32"), - ty::TyFloat(hir::TyF64) => output.push_str("f64"), + ty::TyInt(ast::TyIs) => output.push_str("isize"), + ty::TyInt(ast::TyI8) => output.push_str("i8"), + ty::TyInt(ast::TyI16) => output.push_str("i16"), + ty::TyInt(ast::TyI32) => output.push_str("i32"), + ty::TyInt(ast::TyI64) => output.push_str("i64"), + ty::TyUint(ast::TyUs) => output.push_str("usize"), + ty::TyUint(ast::TyU8) => output.push_str("u8"), + ty::TyUint(ast::TyU16) => output.push_str("u16"), + ty::TyUint(ast::TyU32) => output.push_str("u32"), + ty::TyUint(ast::TyU64) => output.push_str("u64"), + ty::TyFloat(ast::TyF32) => output.push_str("f32"), + ty::TyFloat(ast::TyF64) => output.push_str("f64"), ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => { push_item_name(cx, def.did, qualified, output); diff --git a/src/librustc_trans/trans/debuginfo/utils.rs b/src/librustc_trans/trans/debuginfo/utils.rs index c019a0a950cba..09d014a33823e 100644 --- a/src/librustc_trans/trans/debuginfo/utils.rs +++ b/src/librustc_trans/trans/debuginfo/utils.rs @@ -21,8 +21,6 @@ use trans::machine; use trans::common::{CrateContext, FunctionContext}; use trans::type_::Type; -use rustc_front::hir; - use syntax::codemap::Span; use syntax::{ast, codemap}; @@ -46,11 +44,11 @@ pub fn create_DIArray(builder: DIBuilderRef, arr: &[DIDescriptor]) -> DIArray { }; } -pub fn contains_nodebug_attribute(attributes: &[hir::Attribute]) -> bool { +pub fn contains_nodebug_attribute(attributes: &[ast::Attribute]) -> bool { attributes.iter().any(|attr| { - let meta_item: &hir::MetaItem = &*attr.node.value; + let meta_item: &ast::MetaItem = &*attr.node.value; match meta_item.node { - hir::MetaWord(ref value) => &value[..] == "no_debug", + ast::MetaWord(ref value) => &value[..] == "no_debug", _ => false } }) diff --git a/src/librustc_trans/trans/expr.rs b/src/librustc_trans/trans/expr.rs index 7d8996867c016..5b0dae23807a9 100644 --- a/src/librustc_trans/trans/expr.rs +++ b/src/librustc_trans/trans/expr.rs @@ -83,7 +83,7 @@ use trans::type_::Type; use rustc_front; use rustc_front::hir; -use syntax::{ast, codemap}; +use syntax::{ast, ast_util, codemap}; use syntax::parse::token::InternedString; use syntax::ptr::P; use syntax::parse::token; @@ -533,7 +533,7 @@ fn coerce_unsized<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, Rvalue::new(ByRef))); } else { // Otherwise, simply copy the data from the source. - assert_eq!(src_ty, target_ty); + assert!(src_ty.is_phantom_data() || src_ty == target_ty); memcpy_ty(bcx, ll_target, ll_source, src_ty); } } @@ -630,9 +630,6 @@ fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let _icx = push_ctxt("trans_datum_unadjusted"); match expr.node { - hir::ExprParen(ref e) => { - trans(bcx, &**e) - } hir::ExprPath(..) => { trans_def(bcx, expr, bcx.def(expr.id)) } @@ -934,9 +931,6 @@ fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, debuginfo::set_source_location(bcx.fcx, expr.id, expr.span); match expr.node { - hir::ExprParen(ref e) => { - trans_into(bcx, &**e, Ignore) - } hir::ExprBreak(label_opt) => { controlflow::trans_break(bcx, expr, label_opt.map(|l| l.node)) } @@ -1050,9 +1044,6 @@ fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, debuginfo::set_source_location(bcx.fcx, expr.id, expr.span); match expr.node { - hir::ExprParen(ref e) => { - trans_into(bcx, &**e, dest) - } hir::ExprPath(..) => { trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest) } @@ -1140,7 +1131,7 @@ fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, } hir::ExprLit(ref lit) => { match lit.node { - hir::LitStr(ref s, _) => { + ast::LitStr(ref s, _) => { tvec::trans_lit_str(bcx, expr, (*s).clone(), dest) } _ => { @@ -1549,7 +1540,7 @@ pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &hir::Expr, - lit: &hir::Lit) + lit: &ast::Lit) -> DatumBlock<'blk, 'tcx, Expr> { // must not be a string constant, that is a RvalueDpsExpr let _icx = push_ctxt("trans_immediate_lit"); @@ -2381,8 +2372,8 @@ impl OverflowOpViaIntrinsic { bcx.ccx().get_intrinsic(&name) } fn to_intrinsic_name(&self, tcx: &ty::ctxt, ty: Ty) -> &'static str { - use rustc_front::hir::IntTy::*; - use rustc_front::hir::UintTy::*; + use syntax::ast::IntTy::*; + use syntax::ast::UintTy::*; use middle::ty::{TyInt, TyUint}; let new_sty = match ty.sty { @@ -2714,7 +2705,7 @@ fn expr_kind(tcx: &ty::ctxt, expr: &hir::Expr) -> ExprKind { ExprKind::RvalueDps } - hir::ExprLit(ref lit) if rustc_front::util::lit_is_str(&**lit) => { + hir::ExprLit(ref lit) if ast_util::lit_is_str(&**lit) => { ExprKind::RvalueDps } @@ -2750,7 +2741,5 @@ fn expr_kind(tcx: &ty::ctxt, expr: &hir::Expr) -> ExprKind { ExprKind::RvalueDps } } - - hir::ExprParen(ref e) => expr_kind(tcx, &**e), } } diff --git a/src/librustc_trans/trans/foreign.rs b/src/librustc_trans/trans/foreign.rs index cbb092aa4eb33..38b4cc630f8c7 100644 --- a/src/librustc_trans/trans/foreign.rs +++ b/src/librustc_trans/trans/foreign.rs @@ -35,12 +35,12 @@ use std::cmp; use libc::c_uint; use syntax::abi::{Cdecl, Aapcs, C, Win64, Abi}; use syntax::abi::{PlatformIntrinsic, RustIntrinsic, Rust, RustCall, Stdcall, Fastcall, System}; +use syntax::attr; use syntax::codemap::Span; use syntax::parse::token::{InternedString, special_idents}; use syntax::ast; use rustc_front::print::pprust; -use rustc_front::attr; use rustc_front::hir; /////////////////////////////////////////////////////////////////////////// @@ -188,7 +188,7 @@ pub fn get_extern_fn(ccx: &CrateContext, pub fn register_foreign_item_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, abi: Abi, fty: Ty<'tcx>, name: &str, - attrs: &[hir::Attribute])-> ValueRef { + attrs: &[ast::Attribute])-> ValueRef { debug!("register_foreign_item_fn(abi={:?}, \ ty={:?}, \ name={})", @@ -577,7 +577,7 @@ pub fn register_rust_fn_with_foreign_abi(ccx: &CrateContext, pub fn trans_rust_fn_with_foreign_abi<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, decl: &hir::FnDecl, body: &hir::Block, - attrs: &[hir::Attribute], + attrs: &[ast::Attribute], llwrapfn: ValueRef, param_substs: &'tcx Substs<'tcx>, id: ast::NodeId, @@ -600,7 +600,7 @@ pub fn trans_rust_fn_with_foreign_abi<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, decl: &hir::FnDecl, body: &hir::Block, param_substs: &'tcx Substs<'tcx>, - attrs: &[hir::Attribute], + attrs: &[ast::Attribute], id: ast::NodeId, hash: Option<&str>) -> ValueRef diff --git a/src/librustc_trans/trans/meth.rs b/src/librustc_trans/trans/meth.rs index 4b36734c67fdf..d6f59bf5ca851 100644 --- a/src/librustc_trans/trans/meth.rs +++ b/src/librustc_trans/trans/meth.rs @@ -38,10 +38,10 @@ use middle::ty::{self, Ty, HasTypeFlags}; use middle::ty::MethodCall; use syntax::ast; +use syntax::attr; use syntax::codemap::DUMMY_SP; use syntax::ptr::P; -use rustc_front::attr; use rustc_front::visit; use rustc_front::hir; @@ -773,7 +773,7 @@ fn emit_vtable_methods<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn opaque_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>, method_ty: &ty::BareFnTy<'tcx>) -> &'tcx ty::BareFnTy<'tcx> { let mut inputs = method_ty.sig.0.inputs.clone(); - inputs[0] = tcx.mk_mut_ptr(tcx.mk_mach_int(hir::TyI8)); + inputs[0] = tcx.mk_mut_ptr(tcx.mk_mach_int(ast::TyI8)); tcx.mk_bare_fn(ty::BareFnTy { unsafety: method_ty.unsafety, diff --git a/src/librustc_trans/trans/monomorphize.rs b/src/librustc_trans/trans/monomorphize.rs index 20c3f356b1122..73784919c1391 100644 --- a/src/librustc_trans/trans/monomorphize.rs +++ b/src/librustc_trans/trans/monomorphize.rs @@ -28,10 +28,10 @@ use middle::ty::{self, HasTypeFlags, Ty}; use rustc::front::map as hir_map; use rustc_front::hir; -use rustc_front::attr; use syntax::abi; use syntax::ast; +use syntax::attr; use std::hash::{Hasher, Hash, SipHasher}; pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, @@ -146,7 +146,7 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ccx.monomorphized().borrow_mut().insert(hash_id.take().unwrap(), lldecl); lldecl }; - let setup_lldecl = |lldecl, attrs: &[hir::Attribute]| { + let setup_lldecl = |lldecl, attrs: &[ast::Attribute]| { base::update_linkage(ccx, lldecl, None, base::OriginalTranslation); attributes::from_fn_attrs(ccx, attrs, lldecl); diff --git a/src/librustc_trans/trans/tvec.rs b/src/librustc_trans/trans/tvec.rs index 8deaa045c84d5..c7e1af5853d11 100644 --- a/src/librustc_trans/trans/tvec.rs +++ b/src/librustc_trans/trans/tvec.rs @@ -30,6 +30,7 @@ use middle::ty::{self, Ty}; use rustc_front::hir; +use syntax::ast; use syntax::parse::token::InternedString; #[derive(Copy, Clone)] @@ -91,7 +92,7 @@ pub fn trans_slice_vec<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, // Handle the "..." case (returns a slice since strings are always unsized): if let hir::ExprLit(ref lit) = content_expr.node { - if let hir::LitStr(ref s, _) = lit.node { + if let ast::LitStr(ref s, _) = lit.node { let scratch = rvalue_scratch_datum(bcx, vec_ty, ""); bcx = trans_lit_str(bcx, content_expr, @@ -172,7 +173,7 @@ fn write_content<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, match content_expr.node { hir::ExprLit(ref lit) => { match lit.node { - hir::LitStr(ref s, _) => { + ast::LitStr(ref s, _) => { match dest { Ignore => return bcx, SaveIn(lldest) => { @@ -268,7 +269,7 @@ fn elements_required(bcx: Block, content_expr: &hir::Expr) -> usize { match content_expr.node { hir::ExprLit(ref lit) => { match lit.node { - hir::LitStr(ref s, _) => s.len(), + ast::LitStr(ref s, _) => s.len(), _ => { bcx.tcx().sess.span_bug(content_expr.span, "unexpected evec content") diff --git a/src/librustc_trans/trans/type_.rs b/src/librustc_trans/trans/type_.rs index e0df6ec35c2f9..c635d1ba233fd 100644 --- a/src/librustc_trans/trans/type_.rs +++ b/src/librustc_trans/trans/type_.rs @@ -17,7 +17,7 @@ use llvm::{Float, Double, X86_FP80, PPC_FP128, FP128}; use trans::context::CrateContext; use util::nodemap::FnvHashMap; -use rustc_front::hir; +use syntax::ast; use std::ffi::CString; use std::mem; @@ -125,30 +125,30 @@ impl Type { } } - pub fn int_from_ty(ccx: &CrateContext, t: hir::IntTy) -> Type { + pub fn int_from_ty(ccx: &CrateContext, t: ast::IntTy) -> Type { match t { - hir::TyIs => ccx.int_type(), - hir::TyI8 => Type::i8(ccx), - hir::TyI16 => Type::i16(ccx), - hir::TyI32 => Type::i32(ccx), - hir::TyI64 => Type::i64(ccx) + ast::TyIs => ccx.int_type(), + ast::TyI8 => Type::i8(ccx), + ast::TyI16 => Type::i16(ccx), + ast::TyI32 => Type::i32(ccx), + ast::TyI64 => Type::i64(ccx) } } - pub fn uint_from_ty(ccx: &CrateContext, t: hir::UintTy) -> Type { + pub fn uint_from_ty(ccx: &CrateContext, t: ast::UintTy) -> Type { match t { - hir::TyUs => ccx.int_type(), - hir::TyU8 => Type::i8(ccx), - hir::TyU16 => Type::i16(ccx), - hir::TyU32 => Type::i32(ccx), - hir::TyU64 => Type::i64(ccx) + ast::TyUs => ccx.int_type(), + ast::TyU8 => Type::i8(ccx), + ast::TyU16 => Type::i16(ccx), + ast::TyU32 => Type::i32(ccx), + ast::TyU64 => Type::i64(ccx) } } - pub fn float_from_ty(ccx: &CrateContext, t: hir::FloatTy) -> Type { + pub fn float_from_ty(ccx: &CrateContext, t: ast::FloatTy) -> Type { match t { - hir::TyF32 => Type::f32(ccx), - hir::TyF64 => Type::f64(ccx), + ast::TyF32 => Type::f32(ccx), + ast::TyF64 => Type::f64(ccx), } } diff --git a/src/librustc_trans/trans/type_of.rs b/src/librustc_trans/trans/type_of.rs index 43e1ad8115bed..b7a232822fe17 100644 --- a/src/librustc_trans/trans/type_of.rs +++ b/src/librustc_trans/trans/type_of.rs @@ -21,7 +21,7 @@ use middle::ty::{self, RegionEscape, Ty}; use trans::type_::Type; use syntax::abi; -use rustc_front::hir; +use syntax::ast; // LLVM doesn't like objects that are too big. Issue #17913 fn ensure_array_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, @@ -379,7 +379,7 @@ pub fn in_memory_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> let unsized_part = cx.tcx().struct_tail(ty); let info_ty = match unsized_part.sty { ty::TyStr | ty::TyArray(..) | ty::TySlice(_) => { - Type::uint_from_ty(cx, hir::TyUs) + Type::uint_from_ty(cx, ast::TyUs) } ty::TyTrait(_) => Type::vtable_ptr(cx), _ => panic!("Unexpected type returned from \ diff --git a/src/librustc_typeck/check/_match.rs b/src/librustc_typeck/check/_match.rs index 2ce06786db281..08cda74e3170d 100644 --- a/src/librustc_typeck/check/_match.rs +++ b/src/librustc_typeck/check/_match.rs @@ -56,7 +56,7 @@ pub fn check_pat<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, // They can denote both statically and dynamically sized byte arrays let mut pat_ty = expr_ty; if let hir::ExprLit(ref lt) = lt.node { - if let hir::LitByteStr(_) = lt.node { + if let ast::LitByteStr(_) = lt.node { let expected_ty = structurally_resolved_type(fcx, pat.span, expected); if let ty::TyRef(_, mt) = expected_ty.sty { if let ty::TySlice(_) = mt.ty.sty { diff --git a/src/librustc_typeck/check/cast.rs b/src/librustc_typeck/check/cast.rs index 98c8c0a319946..13e5e46ed2700 100644 --- a/src/librustc_typeck/check/cast.rs +++ b/src/librustc_typeck/check/cast.rs @@ -49,7 +49,8 @@ use middle::ty::{self, Ty, HasTypeFlags}; use middle::ty::cast::{CastKind, CastTy}; use syntax::codemap::Span; use rustc_front::hir; -use rustc_front::hir::UintTy::TyU8; +use syntax::ast; +use syntax::ast::UintTy::TyU8; /// Reifies a cast check to be checked once we have full type information for @@ -245,7 +246,7 @@ impl<'tcx> CastCheck<'tcx> { (_, Int(Bool)) => Err(CastError::CastToBool), // * -> Char - (Int(U(hir::TyU8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast + (Int(U(ast::TyU8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast (_, Int(Char)) => Err(CastError::CastToChar), // prim -> float,ptr diff --git a/src/librustc_typeck/check/coercion.rs b/src/librustc_typeck/check/coercion.rs index 69efaa792fe05..30b4cd01ade20 100644 --- a/src/librustc_typeck/check/coercion.rs +++ b/src/librustc_typeck/check/coercion.rs @@ -110,6 +110,10 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { a, b); + if a == b { + return Ok(None); + } + // Consider coercing the subtype to a DST let unsize = self.unpack_actual_value(a, |a| { self.coerce_unsized(a, b) diff --git a/src/librustc_typeck/check/intrinsic.rs b/src/librustc_typeck/check/intrinsic.rs index e7c7b5831d0fc..d87940bfa1eb2 100644 --- a/src/librustc_typeck/check/intrinsic.rs +++ b/src/librustc_typeck/check/intrinsic.rs @@ -22,6 +22,7 @@ use {CrateCtxt, require_same_types}; use std::collections::{HashMap}; use syntax::abi; +use syntax::ast; use syntax::attr::AttrMetaMethods; use syntax::codemap::Span; use syntax::parse::token; @@ -470,22 +471,22 @@ fn match_intrinsic_type_to_type<'tcx, 'a>( }, // (The width we pass to LLVM doesn't concern the type checker.) Integer(signed, bits, _llvm_width) => match (signed, bits, &t.sty) { - (true, 8, &ty::TyInt(hir::IntTy::TyI8)) | - (false, 8, &ty::TyUint(hir::UintTy::TyU8)) | - (true, 16, &ty::TyInt(hir::IntTy::TyI16)) | - (false, 16, &ty::TyUint(hir::UintTy::TyU16)) | - (true, 32, &ty::TyInt(hir::IntTy::TyI32)) | - (false, 32, &ty::TyUint(hir::UintTy::TyU32)) | - (true, 64, &ty::TyInt(hir::IntTy::TyI64)) | - (false, 64, &ty::TyUint(hir::UintTy::TyU64)) => {}, + (true, 8, &ty::TyInt(ast::IntTy::TyI8)) | + (false, 8, &ty::TyUint(ast::UintTy::TyU8)) | + (true, 16, &ty::TyInt(ast::IntTy::TyI16)) | + (false, 16, &ty::TyUint(ast::UintTy::TyU16)) | + (true, 32, &ty::TyInt(ast::IntTy::TyI32)) | + (false, 32, &ty::TyUint(ast::UintTy::TyU32)) | + (true, 64, &ty::TyInt(ast::IntTy::TyI64)) | + (false, 64, &ty::TyUint(ast::UintTy::TyU64)) => {}, _ => simple_error(&format!("`{}`", t), &format!("`{}{n}`", if signed {"i"} else {"u"}, n = bits)), }, Float(bits) => match (bits, &t.sty) { - (32, &ty::TyFloat(hir::FloatTy::TyF32)) | - (64, &ty::TyFloat(hir::FloatTy::TyF64)) => {}, + (32, &ty::TyFloat(ast::FloatTy::TyF32)) | + (64, &ty::TyFloat(ast::FloatTy::TyF64)) => {}, _ => simple_error(&format!("`{}`", t), &format!("`f{n}`", n = bits)), }, diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index 572ba7a848713..abdcbf099a57a 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -468,7 +468,6 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { loop { let last = exprs[exprs.len() - 1]; match last.node { - hir::ExprParen(ref expr) | hir::ExprField(ref expr, _) | hir::ExprTupField(ref expr, _) | hir::ExprIndex(ref expr, _) | diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs index f65602d9aaccb..c63b081c73c48 100644 --- a/src/librustc_typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -319,51 +319,51 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { let lang_def_id = self.tcx().lang_items.mut_ptr_impl(); self.assemble_inherent_impl_for_primitive(lang_def_id); } - ty::TyInt(hir::TyI8) => { + ty::TyInt(ast::TyI8) => { let lang_def_id = self.tcx().lang_items.i8_impl(); self.assemble_inherent_impl_for_primitive(lang_def_id); } - ty::TyInt(hir::TyI16) => { + ty::TyInt(ast::TyI16) => { let lang_def_id = self.tcx().lang_items.i16_impl(); self.assemble_inherent_impl_for_primitive(lang_def_id); } - ty::TyInt(hir::TyI32) => { + ty::TyInt(ast::TyI32) => { let lang_def_id = self.tcx().lang_items.i32_impl(); self.assemble_inherent_impl_for_primitive(lang_def_id); } - ty::TyInt(hir::TyI64) => { + ty::TyInt(ast::TyI64) => { let lang_def_id = self.tcx().lang_items.i64_impl(); self.assemble_inherent_impl_for_primitive(lang_def_id); } - ty::TyInt(hir::TyIs) => { + ty::TyInt(ast::TyIs) => { let lang_def_id = self.tcx().lang_items.isize_impl(); self.assemble_inherent_impl_for_primitive(lang_def_id); } - ty::TyUint(hir::TyU8) => { + ty::TyUint(ast::TyU8) => { let lang_def_id = self.tcx().lang_items.u8_impl(); self.assemble_inherent_impl_for_primitive(lang_def_id); } - ty::TyUint(hir::TyU16) => { + ty::TyUint(ast::TyU16) => { let lang_def_id = self.tcx().lang_items.u16_impl(); self.assemble_inherent_impl_for_primitive(lang_def_id); } - ty::TyUint(hir::TyU32) => { + ty::TyUint(ast::TyU32) => { let lang_def_id = self.tcx().lang_items.u32_impl(); self.assemble_inherent_impl_for_primitive(lang_def_id); } - ty::TyUint(hir::TyU64) => { + ty::TyUint(ast::TyU64) => { let lang_def_id = self.tcx().lang_items.u64_impl(); self.assemble_inherent_impl_for_primitive(lang_def_id); } - ty::TyUint(hir::TyUs) => { + ty::TyUint(ast::TyUs) => { let lang_def_id = self.tcx().lang_items.usize_impl(); self.assemble_inherent_impl_for_primitive(lang_def_id); } - ty::TyFloat(hir::TyF32) => { + ty::TyFloat(ast::TyF32) => { let lang_def_id = self.tcx().lang_items.f32_impl(); self.assemble_inherent_impl_for_primitive(lang_def_id); } - ty::TyFloat(hir::TyF64) => { + ty::TyFloat(ast::TyF64) => { let lang_def_id = self.tcx().lang_items.f64_impl(); self.assemble_inherent_impl_for_primitive(lang_def_id); } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 9dd7cfea43f69..e5dbfdf176739 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -117,6 +117,8 @@ use std::mem::replace; use std::slice; use syntax::abi; use syntax::ast; +use syntax::attr; +use syntax::attr::AttrMetaMethods; use syntax::codemap::{self, Span}; use syntax::owned_slice::OwnedSlice; use syntax::parse::token::{self, InternedString}; @@ -125,8 +127,6 @@ use syntax::ptr::P; use rustc_front::visit::{self, Visitor}; use rustc_front::hir; use rustc_front::hir::Visibility; -use rustc_front::attr; -use rustc_front::attr::AttrMetaMethods; use rustc_front::hir::{Item, ItemImpl}; use rustc_front::print::pprust; @@ -2309,7 +2309,7 @@ fn try_index_step<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, // First, try built-in indexing. match (adjusted_ty.builtin_index(), &index_ty.sty) { - (Some(ty), &ty::TyUint(hir::TyUs)) | (Some(ty), &ty::TyInfer(ty::IntVar(_))) => { + (Some(ty), &ty::TyUint(ast::TyUs)) | (Some(ty), &ty::TyInfer(ty::IntVar(_))) => { debug!("try_index_step: success, using built-in indexing"); // If we had `[T; N]`, we should've caught it before unsizing to `[T]`. assert!(!unsize); @@ -2573,21 +2573,21 @@ fn check_argument_types<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, let arg_ty = structurally_resolved_type(fcx, arg.span, fcx.expr_ty(&**arg)); match arg_ty.sty { - ty::TyFloat(hir::TyF32) => { + ty::TyFloat(ast::TyF32) => { fcx.type_error_message(arg.span, |t| { format!("can't pass an {} to variadic \ function, cast to c_double", t) }, arg_ty, None); } - ty::TyInt(hir::TyI8) | ty::TyInt(hir::TyI16) | ty::TyBool => { + ty::TyInt(ast::TyI8) | ty::TyInt(ast::TyI16) | ty::TyBool => { fcx.type_error_message(arg.span, |t| { format!("can't pass {} to variadic \ function, cast to c_int", t) }, arg_ty, None); } - ty::TyUint(hir::TyU8) | ty::TyUint(hir::TyU16) => { + ty::TyUint(ast::TyU8) | ty::TyUint(ast::TyU16) => { fcx.type_error_message(arg.span, |t| { format!("can't pass {} to variadic \ function, cast to c_uint", @@ -2616,23 +2616,23 @@ fn write_call<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, // AST fragment checking fn check_lit<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, - lit: &hir::Lit, + lit: &ast::Lit, expected: Expectation<'tcx>) -> Ty<'tcx> { let tcx = fcx.ccx.tcx; match lit.node { - hir::LitStr(..) => tcx.mk_static_str(), - hir::LitByteStr(ref v) => { + ast::LitStr(..) => tcx.mk_static_str(), + ast::LitByteStr(ref v) => { tcx.mk_imm_ref(tcx.mk_region(ty::ReStatic), tcx.mk_array(tcx.types.u8, v.len())) } - hir::LitByte(_) => tcx.types.u8, - hir::LitChar(_) => tcx.types.char, - hir::LitInt(_, hir::SignedIntLit(t, _)) => tcx.mk_mach_int(t), - hir::LitInt(_, hir::UnsignedIntLit(t)) => tcx.mk_mach_uint(t), - hir::LitInt(_, hir::UnsuffixedIntLit(_)) => { + ast::LitByte(_) => tcx.types.u8, + ast::LitChar(_) => tcx.types.char, + ast::LitInt(_, ast::SignedIntLit(t, _)) => tcx.mk_mach_int(t), + ast::LitInt(_, ast::UnsignedIntLit(t)) => tcx.mk_mach_uint(t), + ast::LitInt(_, ast::UnsuffixedIntLit(_)) => { let opt_ty = expected.to_option(fcx).and_then(|ty| { match ty.sty { ty::TyInt(_) | ty::TyUint(_) => Some(ty), @@ -2645,8 +2645,8 @@ fn check_lit<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, opt_ty.unwrap_or_else( || tcx.mk_int_var(fcx.infcx().next_int_var_id())) } - hir::LitFloat(_, t) => tcx.mk_mach_float(t), - hir::LitFloatUnsuffixed(_) => { + ast::LitFloat(_, t) => tcx.mk_mach_float(t), + ast::LitFloatUnsuffixed(_) => { let opt_ty = expected.to_option(fcx).and_then(|ty| { match ty.sty { ty::TyFloat(_) => Some(ty), @@ -2656,7 +2656,7 @@ fn check_lit<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, opt_ty.unwrap_or_else( || tcx.mk_float_var(fcx.infcx().next_float_var_id())) } - hir::LitBool(_) => tcx.types.bool + ast::LitBool(_) => tcx.types.bool } } @@ -3444,13 +3444,6 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, } fcx.write_ty(id, fcx.infcx().next_diverging_ty_var()); } - hir::ExprParen(ref a) => { - check_expr_with_expectation_and_lvalue_pref(fcx, - &**a, - expected, - lvalue_pref); - fcx.write_ty(id, fcx.expr_ty(&**a)); - } hir::ExprAssign(ref lhs, ref rhs) => { check_expr_with_lvalue_pref(fcx, &**lhs, PreferMutLvalue); @@ -4219,22 +4212,22 @@ pub fn check_enum_variants<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, fn disr_in_range(ccx: &CrateCtxt, ty: attr::IntType, disr: ty::Disr) -> bool { - fn uint_in_range(ccx: &CrateCtxt, ty: hir::UintTy, disr: ty::Disr) -> bool { + fn uint_in_range(ccx: &CrateCtxt, ty: ast::UintTy, disr: ty::Disr) -> bool { match ty { - hir::TyU8 => disr as u8 as Disr == disr, - hir::TyU16 => disr as u16 as Disr == disr, - hir::TyU32 => disr as u32 as Disr == disr, - hir::TyU64 => disr as u64 as Disr == disr, - hir::TyUs => uint_in_range(ccx, ccx.tcx.sess.target.uint_type, disr) + ast::TyU8 => disr as u8 as Disr == disr, + ast::TyU16 => disr as u16 as Disr == disr, + ast::TyU32 => disr as u32 as Disr == disr, + ast::TyU64 => disr as u64 as Disr == disr, + ast::TyUs => uint_in_range(ccx, ccx.tcx.sess.target.uint_type, disr) } } - fn int_in_range(ccx: &CrateCtxt, ty: hir::IntTy, disr: ty::Disr) -> bool { + fn int_in_range(ccx: &CrateCtxt, ty: ast::IntTy, disr: ty::Disr) -> bool { match ty { - hir::TyI8 => disr as i8 as Disr == disr, - hir::TyI16 => disr as i16 as Disr == disr, - hir::TyI32 => disr as i32 as Disr == disr, - hir::TyI64 => disr as i64 as Disr == disr, - hir::TyIs => int_in_range(ccx, ccx.tcx.sess.target.int_type, disr) + ast::TyI8 => disr as i8 as Disr == disr, + ast::TyI16 => disr as i16 as Disr == disr, + ast::TyI32 => disr as i32 as Disr == disr, + ast::TyI64 => disr as i64 as Disr == disr, + ast::TyIs => int_in_range(ccx, ccx.tcx.sess.target.int_type, disr) } } match ty { diff --git a/src/librustc_typeck/coherence/mod.rs b/src/librustc_typeck/coherence/mod.rs index 9ba6f1398e471..d5164af56b357 100644 --- a/src/librustc_typeck/coherence/mod.rs +++ b/src/librustc_typeck/coherence/mod.rs @@ -480,9 +480,16 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { let fields = &def_a.struct_variant().fields; let diff_fields = fields.iter().enumerate().filter_map(|(i, f)| { let (a, b) = (f.ty(tcx, substs_a), f.ty(tcx, substs_b)); - if infcx.sub_types(false, origin, b, a).is_ok() { + + if f.unsubst_ty().is_phantom_data() { + // Ignore PhantomData fields + None + } else if infcx.sub_types(false, origin, b, a).is_ok() { + // Ignore fields that aren't significantly changed None } else { + // Collect up all fields that were significantly changed + // i.e. those that contain T in coerce_unsized T -> U Some((i, a, b)) } }).collect::>(); diff --git a/src/librustc_typeck/coherence/orphan.rs b/src/librustc_typeck/coherence/orphan.rs index 022f1e3646a12..43ae33ac596a0 100644 --- a/src/librustc_typeck/coherence/orphan.rs +++ b/src/librustc_typeck/coherence/orphan.rs @@ -14,6 +14,7 @@ use middle::def_id::{DefId, LOCAL_CRATE}; use middle::traits; use middle::ty; +use syntax::ast; use syntax::codemap::Span; use rustc_front::visit; use rustc_front::hir; @@ -119,84 +120,84 @@ impl<'cx, 'tcx> OrphanChecker<'cx, 'tcx> { "*mut T", item.span); } - ty::TyInt(hir::TyI8) => { + ty::TyInt(ast::TyI8) => { self.check_primitive_impl(def_id, self.tcx.lang_items.i8_impl(), "i8", "i8", item.span); } - ty::TyInt(hir::TyI16) => { + ty::TyInt(ast::TyI16) => { self.check_primitive_impl(def_id, self.tcx.lang_items.i16_impl(), "i16", "i16", item.span); } - ty::TyInt(hir::TyI32) => { + ty::TyInt(ast::TyI32) => { self.check_primitive_impl(def_id, self.tcx.lang_items.i32_impl(), "i32", "i32", item.span); } - ty::TyInt(hir::TyI64) => { + ty::TyInt(ast::TyI64) => { self.check_primitive_impl(def_id, self.tcx.lang_items.i64_impl(), "i64", "i64", item.span); } - ty::TyInt(hir::TyIs) => { + ty::TyInt(ast::TyIs) => { self.check_primitive_impl(def_id, self.tcx.lang_items.isize_impl(), "isize", "isize", item.span); } - ty::TyUint(hir::TyU8) => { + ty::TyUint(ast::TyU8) => { self.check_primitive_impl(def_id, self.tcx.lang_items.u8_impl(), "u8", "u8", item.span); } - ty::TyUint(hir::TyU16) => { + ty::TyUint(ast::TyU16) => { self.check_primitive_impl(def_id, self.tcx.lang_items.u16_impl(), "u16", "u16", item.span); } - ty::TyUint(hir::TyU32) => { + ty::TyUint(ast::TyU32) => { self.check_primitive_impl(def_id, self.tcx.lang_items.u32_impl(), "u32", "u32", item.span); } - ty::TyUint(hir::TyU64) => { + ty::TyUint(ast::TyU64) => { self.check_primitive_impl(def_id, self.tcx.lang_items.u64_impl(), "u64", "u64", item.span); } - ty::TyUint(hir::TyUs) => { + ty::TyUint(ast::TyUs) => { self.check_primitive_impl(def_id, self.tcx.lang_items.usize_impl(), "usize", "usize", item.span); } - ty::TyFloat(hir::TyF32) => { + ty::TyFloat(ast::TyF32) => { self.check_primitive_impl(def_id, self.tcx.lang_items.f32_impl(), "f32", "f32", item.span); } - ty::TyFloat(hir::TyF64) => { + ty::TyFloat(ast::TyF64) => { self.check_primitive_impl(def_id, self.tcx.lang_items.f64_impl(), "f64", diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index f7520ed54b77e..f00e5465e4774 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -93,12 +93,12 @@ use std::rc::Rc; use syntax::abi; use syntax::ast; +use syntax::attr; use syntax::codemap::Span; use syntax::parse::token::special_idents; use syntax::ptr::P; use rustc_front::hir; use rustc_front::visit; -use rustc_front::attr; use rustc_front::print::pprust; /////////////////////////////////////////////////////////////////////////// diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index c9af86f06db93..930bc831028f0 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -13,7 +13,7 @@ use std::collections::HashSet; use syntax::ast; -use rustc_front::attr::AttrMetaMethods; +use syntax::attr::AttrMetaMethods; use rustc_front::hir; use rustc::metadata::csearch; diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 7ef359787e87e..8737957c06561 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -27,6 +27,8 @@ pub use self::FunctionRetTy::*; use syntax; use syntax::abi; use syntax::ast; +use syntax::attr; +use syntax::attr::{AttributeMethods, AttrMetaMethods}; use syntax::codemap; use syntax::codemap::{DUMMY_SP, Pos, Spanned}; use syntax::parse::token::{self, InternedString, special_idents}; @@ -43,9 +45,6 @@ use rustc::middle::ty; use rustc::middle::stability; use rustc_front::hir; -use rustc_front::attr; -use rustc_front::attr::{AttributeMethods, AttrMetaMethods}; -use rustc_front::lowering::unlower_attribute; use std::collections::HashMap; use std::path::PathBuf; @@ -143,8 +142,7 @@ impl<'a, 'tcx> Clean for visit_ast::RustdocVisitor<'a, 'tcx> { // Figure out the name of this crate let input = &cx.input; - let attrs: Vec<_> = self.attrs.iter().map(|a| unlower_attribute(a)).collect(); - let name = link::find_crate_name(None, &attrs, input); + let name = link::find_crate_name(None, &self.attrs, input); // Clean the crate, translating the entire libsyntax AST to one that is // understood by rustdoc. @@ -437,21 +435,21 @@ pub enum Attribute { NameValue(String, String) } -impl Clean for hir::MetaItem { +impl Clean for ast::MetaItem { fn clean(&self, cx: &DocContext) -> Attribute { match self.node { - hir::MetaWord(ref s) => Word(s.to_string()), - hir::MetaList(ref s, ref l) => { + ast::MetaWord(ref s) => Word(s.to_string()), + ast::MetaList(ref s, ref l) => { List(s.to_string(), l.clean(cx)) } - hir::MetaNameValue(ref s, ref v) => { + ast::MetaNameValue(ref s, ref v) => { NameValue(s.to_string(), lit_to_string(v)) } } } } -impl Clean for hir::Attribute { +impl Clean for ast::Attribute { fn clean(&self, cx: &DocContext) -> Attribute { self.with_desugared_doc(|a| a.node.value.clean(cx)) } @@ -475,13 +473,13 @@ impl attr::AttrMetaMethods for Attribute { _ => None, } } - fn meta_item_list<'a>(&'a self) -> Option<&'a [P]> { None } + fn meta_item_list<'a>(&'a self) -> Option<&'a [P]> { None } fn span(&self) -> codemap::Span { unimplemented!() } } impl<'a> attr::AttrMetaMethods for &'a Attribute { fn name(&self) -> InternedString { (**self).name() } fn value_str(&self) -> Option { (**self).value_str() } - fn meta_item_list(&self) -> Option<&[P]> { None } + fn meta_item_list(&self) -> Option<&[P]> { None } fn span(&self) -> codemap::Span { unimplemented!() } } @@ -1626,18 +1624,18 @@ impl<'tcx> Clean for ty::Ty<'tcx> { match self.sty { ty::TyBool => Primitive(Bool), ty::TyChar => Primitive(Char), - ty::TyInt(hir::TyIs) => Primitive(Isize), - ty::TyInt(hir::TyI8) => Primitive(I8), - ty::TyInt(hir::TyI16) => Primitive(I16), - ty::TyInt(hir::TyI32) => Primitive(I32), - ty::TyInt(hir::TyI64) => Primitive(I64), - ty::TyUint(hir::TyUs) => Primitive(Usize), - ty::TyUint(hir::TyU8) => Primitive(U8), - ty::TyUint(hir::TyU16) => Primitive(U16), - ty::TyUint(hir::TyU32) => Primitive(U32), - ty::TyUint(hir::TyU64) => Primitive(U64), - ty::TyFloat(hir::TyF32) => Primitive(F32), - ty::TyFloat(hir::TyF64) => Primitive(F64), + ty::TyInt(ast::TyIs) => Primitive(Isize), + ty::TyInt(ast::TyI8) => Primitive(I8), + ty::TyInt(ast::TyI16) => Primitive(I16), + ty::TyInt(ast::TyI32) => Primitive(I32), + ty::TyInt(ast::TyI64) => Primitive(I64), + ty::TyUint(ast::TyUs) => Primitive(Usize), + ty::TyUint(ast::TyU8) => Primitive(U8), + ty::TyUint(ast::TyU16) => Primitive(U16), + ty::TyUint(ast::TyU32) => Primitive(U32), + ty::TyUint(ast::TyU64) => Primitive(U64), + ty::TyFloat(ast::TyF32) => Primitive(F32), + ty::TyFloat(ast::TyF64) => Primitive(F64), ty::TyStr => Primitive(Str), ty::TyBox(t) => { let box_did = cx.tcx_opt().and_then(|tcx| { @@ -2515,11 +2513,11 @@ impl ToSource for syntax::codemap::Span { } } -fn lit_to_string(lit: &hir::Lit) -> String { +fn lit_to_string(lit: &ast::Lit) -> String { match lit.node { - hir::LitStr(ref st, _) => st.to_string(), - hir::LitByteStr(ref data) => format!("{:?}", data), - hir::LitByte(b) => { + ast::LitStr(ref st, _) => st.to_string(), + ast::LitByteStr(ref data) => format!("{:?}", data), + ast::LitByte(b) => { let mut res = String::from("b'"); for c in (b as char).escape_default() { res.push(c); @@ -2527,11 +2525,11 @@ fn lit_to_string(lit: &hir::Lit) -> String { res.push('\''); res }, - hir::LitChar(c) => format!("'{}'", c), - hir::LitInt(i, _t) => i.to_string(), - hir::LitFloat(ref f, _t) => f.to_string(), - hir::LitFloatUnsuffixed(ref f) => f.to_string(), - hir::LitBool(b) => b.to_string(), + ast::LitChar(c) => format!("'{}'", c), + ast::LitInt(i, _t) => i.to_string(), + ast::LitFloat(ref f, _t) => f.to_string(), + ast::LitFloatUnsuffixed(ref f) => f.to_string(), + ast::LitBool(b) => b.to_string(), } } @@ -2594,18 +2592,18 @@ fn resolve_type(cx: &DocContext, hir::TyStr => return Primitive(Str), hir::TyBool => return Primitive(Bool), hir::TyChar => return Primitive(Char), - hir::TyInt(hir::TyIs) => return Primitive(Isize), - hir::TyInt(hir::TyI8) => return Primitive(I8), - hir::TyInt(hir::TyI16) => return Primitive(I16), - hir::TyInt(hir::TyI32) => return Primitive(I32), - hir::TyInt(hir::TyI64) => return Primitive(I64), - hir::TyUint(hir::TyUs) => return Primitive(Usize), - hir::TyUint(hir::TyU8) => return Primitive(U8), - hir::TyUint(hir::TyU16) => return Primitive(U16), - hir::TyUint(hir::TyU32) => return Primitive(U32), - hir::TyUint(hir::TyU64) => return Primitive(U64), - hir::TyFloat(hir::TyF32) => return Primitive(F32), - hir::TyFloat(hir::TyF64) => return Primitive(F64), + hir::TyInt(ast::TyIs) => return Primitive(Isize), + hir::TyInt(ast::TyI8) => return Primitive(I8), + hir::TyInt(ast::TyI16) => return Primitive(I16), + hir::TyInt(ast::TyI32) => return Primitive(I32), + hir::TyInt(ast::TyI64) => return Primitive(I64), + hir::TyUint(ast::TyUs) => return Primitive(Usize), + hir::TyUint(ast::TyU8) => return Primitive(U8), + hir::TyUint(ast::TyU16) => return Primitive(U16), + hir::TyUint(ast::TyU32) => return Primitive(U32), + hir::TyUint(ast::TyU64) => return Primitive(U64), + hir::TyFloat(ast::TyF32) => return Primitive(F32), + hir::TyFloat(ast::TyF64) => return Primitive(F64), }, def::DefSelfTy(..) if path.segments.len() == 1 => { return Generic(special_idents::type_self.name.to_string()); diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 63468dd55f8a9..d7238c827ab57 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -141,7 +141,6 @@ pub fn run_core(search_paths: SearchPaths, cfgs: Vec, externs: Externs, driver::phase_3_run_analysis_passes(sess, hir_map, - &krate, &arenas, name, resolve::MakeGlobMap::No, diff --git a/src/librustdoc/doctree.rs b/src/librustdoc/doctree.rs index 5140cca03ea34..1a027a3d14636 100644 --- a/src/librustdoc/doctree.rs +++ b/src/librustdoc/doctree.rs @@ -18,13 +18,13 @@ use syntax::codemap::Span; use syntax::abi; use syntax::ast; use syntax::ast::{Ident, NodeId}; +use syntax::attr; use syntax::ptr::P; use rustc_front::hir; -use rustc_front::attr; pub struct Module { pub name: Option, - pub attrs: Vec, + pub attrs: Vec, pub where_outer: Span, pub where_inner: Span, pub extern_crates: Vec, @@ -100,7 +100,7 @@ pub struct Struct { pub struct_type: StructType, pub name: Ident, pub generics: hir::Generics, - pub attrs: Vec, + pub attrs: Vec, pub fields: Vec, pub whence: Span, } @@ -110,7 +110,7 @@ pub struct Enum { pub stab: Option, pub variants: Vec, pub generics: hir::Generics, - pub attrs: Vec, + pub attrs: Vec, pub id: NodeId, pub whence: Span, pub name: Ident, @@ -118,7 +118,7 @@ pub struct Enum { pub struct Variant { pub name: Ident, - pub attrs: Vec, + pub attrs: Vec, pub kind: hir::VariantKind, pub id: ast::NodeId, pub vis: hir::Visibility, @@ -128,7 +128,7 @@ pub struct Variant { pub struct Function { pub decl: hir::FnDecl, - pub attrs: Vec, + pub attrs: Vec, pub id: NodeId, pub name: Ident, pub vis: hir::Visibility, @@ -145,7 +145,7 @@ pub struct Typedef { pub gen: hir::Generics, pub name: Ident, pub id: ast::NodeId, - pub attrs: Vec, + pub attrs: Vec, pub whence: Span, pub vis: hir::Visibility, pub stab: Option, @@ -157,7 +157,7 @@ pub struct Static { pub mutability: hir::Mutability, pub expr: P, pub name: Ident, - pub attrs: Vec, + pub attrs: Vec, pub vis: hir::Visibility, pub stab: Option, pub id: ast::NodeId, @@ -168,7 +168,7 @@ pub struct Constant { pub type_: P, pub expr: P, pub name: Ident, - pub attrs: Vec, + pub attrs: Vec, pub vis: hir::Visibility, pub stab: Option, pub id: ast::NodeId, @@ -181,7 +181,7 @@ pub struct Trait { pub items: Vec>, //should be TraitItem pub generics: hir::Generics, pub bounds: Vec, - pub attrs: Vec, + pub attrs: Vec, pub id: ast::NodeId, pub whence: Span, pub vis: hir::Visibility, @@ -195,7 +195,7 @@ pub struct Impl { pub trait_: Option, pub for_: P, pub items: Vec>, - pub attrs: Vec, + pub attrs: Vec, pub whence: Span, pub vis: hir::Visibility, pub stab: Option, @@ -206,14 +206,14 @@ pub struct DefaultImpl { pub unsafety: hir::Unsafety, pub trait_: hir::TraitRef, pub id: ast::NodeId, - pub attrs: Vec, + pub attrs: Vec, pub whence: Span, } pub struct Macro { pub name: Ident, pub id: ast::NodeId, - pub attrs: Vec, + pub attrs: Vec, pub whence: Span, pub stab: Option, pub imported_from: Option, @@ -223,14 +223,14 @@ pub struct ExternCrate { pub name: Ident, pub path: Option, pub vis: hir::Visibility, - pub attrs: Vec, + pub attrs: Vec, pub whence: Span, } pub struct Import { pub id: NodeId, pub vis: hir::Visibility, - pub attrs: Vec, + pub attrs: Vec, pub node: hir::ViewPath_, pub whence: Span, } diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 86b268001a6ae..b34f1a01a2b0e 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -52,10 +52,10 @@ use std::sync::Arc; use externalfiles::ExternalHtml; use serialize::json::{self, ToJson}; -use syntax::{abi, ast}; +use syntax::{abi, ast, attr}; use rustc::middle::def_id::{DefId, LOCAL_CRATE}; use rustc::util::nodemap::NodeSet; -use rustc_front::{hir, attr}; +use rustc_front::hir; use clean::{self, SelfTy}; use doctree; diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 95215cf2d5caf..2f47353fee7b2 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -124,8 +124,8 @@ pub fn run(input: &str, // Look for #![doc(test(no_crate_inject))], used by crates in the std facade fn scrape_test_config(krate: &::rustc_front::hir::Crate) -> TestOptions { - use rustc_front::attr::AttrMetaMethods; - use rustc_front::print::pprust; + use syntax::attr::AttrMetaMethods; + use syntax::print::pprust; let mut opts = TestOptions { no_crate_inject: false, diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 978b572ac9372..e3fb13d13906d 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -16,14 +16,14 @@ use std::mem; use syntax::abi; use syntax::ast; +use syntax::attr; +use syntax::attr::AttrMetaMethods; use syntax::codemap::Span; use rustc::front::map as hir_map; use rustc::middle::def_id::DefId; use rustc::middle::stability; -use rustc_front::attr; -use rustc_front::attr::AttrMetaMethods; use rustc_front::hir; use core; @@ -39,7 +39,7 @@ use doctree::*; pub struct RustdocVisitor<'a, 'tcx: 'a> { pub module: Module, - pub attrs: Vec, + pub attrs: Vec, pub cx: &'a core::DocContext<'a, 'tcx>, pub analysis: Option<&'a core::CrateAnalysis>, view_item_stack: HashSet, @@ -146,7 +146,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { } } - pub fn visit_mod_contents(&mut self, span: Span, attrs: Vec , + pub fn visit_mod_contents(&mut self, span: Span, attrs: Vec , vis: hir::Visibility, id: ast::NodeId, m: &hir::Mod, name: Option) -> Module { diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index ff622859cf0b1..b6650b6f94420 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -1263,7 +1263,7 @@ impl<'a> Parser<'a> { pub fn parse_ret_ty(&mut self) -> PResult { if try!(self.eat(&token::RArrow) ){ if try!(self.eat(&token::Not) ){ - Ok(NoReturn(self.span)) + Ok(NoReturn(self.last_span)) } else { Ok(Return(try!(self.parse_ty_nopanic()))) } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 555fdc1ff8647..b00ff85051c9a 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -54,8 +54,8 @@ impl PpAnn for NoAnn {} #[derive(Copy, Clone)] pub struct CurrentCommentAndLiteral { - cur_cmnt: usize, - cur_lit: usize, + pub cur_cmnt: usize, + pub cur_lit: usize, } pub struct State<'a> { @@ -450,43 +450,369 @@ fn needs_parentheses(expr: &ast::Expr) -> bool { } } -impl<'a> State<'a> { - pub fn ibox(&mut self, u: usize) -> io::Result<()> { - self.boxes.push(pp::Breaks::Inconsistent); - pp::ibox(&mut self.s, u) +pub trait PrintState<'a> { + fn writer(&mut self) -> &mut pp::Printer<'a>; + fn boxes(&mut self) -> &mut Vec; + fn comments(&mut self) -> &mut Option>; + fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral; + fn literals(&self) -> &Option>; + + fn word_space(&mut self, w: &str) -> io::Result<()> { + try!(word(self.writer(), w)); + space(self.writer()) } - pub fn end(&mut self) -> io::Result<()> { - self.boxes.pop().unwrap(); - pp::end(&mut self.s) + fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") } + + fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") } + + fn is_begin(&mut self) -> bool { + match self.writer().last_token() { + pp::Token::Begin(_) => true, + _ => false, + } } - pub fn cbox(&mut self, u: usize) -> io::Result<()> { - self.boxes.push(pp::Breaks::Consistent); - pp::cbox(&mut self.s, u) + fn is_end(&mut self) -> bool { + match self.writer().last_token() { + pp::Token::End => true, + _ => false, + } + } + + // is this the beginning of a line? + fn is_bol(&mut self) -> bool { + self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok() + } + + fn hardbreak_if_not_bol(&mut self) -> io::Result<()> { + if !self.is_bol() { + try!(hardbreak(self.writer())) + } + Ok(()) } // "raw box" - pub fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> { - self.boxes.push(b); - pp::rbox(&mut self.s, u, b) + fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> { + self.boxes().push(b); + pp::rbox(self.writer(), u, b) } - pub fn nbsp(&mut self) -> io::Result<()> { word(&mut self.s, " ") } + fn ibox(&mut self, u: usize) -> io::Result<()> { + self.boxes().push(pp::Breaks::Inconsistent); + pp::ibox(self.writer(), u) + } - pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> { - try!(word(&mut self.s, w)); - self.nbsp() + fn end(&mut self) -> io::Result<()> { + self.boxes().pop().unwrap(); + pp::end(self.writer()) } - pub fn word_space(&mut self, w: &str) -> io::Result<()> { - try!(word(&mut self.s, w)); - space(&mut self.s) + fn commasep(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()> + where F: FnMut(&mut Self, &T) -> io::Result<()>, + { + try!(self.rbox(0, b)); + let mut first = true; + for elt in elts { + if first { first = false; } else { try!(self.word_space(",")); } + try!(op(self, elt)); + } + self.end() + } + + + fn next_lit(&mut self, pos: BytePos) -> Option { + let mut cur_lit = self.cur_cmnt_and_lit().cur_lit; + + let mut result = None; + + if let &Some(ref lits) = self.literals() + { + while cur_lit < lits.len() { + let ltrl = (*lits)[cur_lit].clone(); + if ltrl.pos > pos { break; } + cur_lit += 1; + if ltrl.pos == pos { + result = Some(ltrl); + break; + } + } + } + + self.cur_cmnt_and_lit().cur_lit = cur_lit; + result + } + + fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> { + loop { + match self.next_comment() { + Some(ref cmnt) => { + if (*cmnt).pos < pos { + try!(self.print_comment(cmnt)); + self.cur_cmnt_and_lit().cur_cmnt += 1; + } else { break; } + } + _ => break + } + } + Ok(()) + } + + fn print_comment(&mut self, + cmnt: &comments::Comment) -> io::Result<()> { + match cmnt.style { + comments::Mixed => { + assert_eq!(cmnt.lines.len(), 1); + try!(zerobreak(self.writer())); + try!(word(self.writer(), &cmnt.lines[0])); + zerobreak(self.writer()) + } + comments::Isolated => { + try!(self.hardbreak_if_not_bol()); + for line in &cmnt.lines { + // Don't print empty lines because they will end up as trailing + // whitespace + if !line.is_empty() { + try!(word(self.writer(), &line[..])); + } + try!(hardbreak(self.writer())); + } + Ok(()) + } + comments::Trailing => { + try!(word(self.writer(), " ")); + if cmnt.lines.len() == 1 { + try!(word(self.writer(), &cmnt.lines[0])); + hardbreak(self.writer()) + } else { + try!(self.ibox(0)); + for line in &cmnt.lines { + if !line.is_empty() { + try!(word(self.writer(), &line[..])); + } + try!(hardbreak(self.writer())); + } + self.end() + } + } + comments::BlankLine => { + // We need to do at least one, possibly two hardbreaks. + let is_semi = match self.writer().last_token() { + pp::Token::String(s, _) => ";" == s, + _ => false + }; + if is_semi || self.is_begin() || self.is_end() { + try!(hardbreak(self.writer())); + } + hardbreak(self.writer()) + } + } + } + + fn next_comment(&mut self) -> Option { + let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt; + match *self.comments() { + Some(ref cmnts) => { + if cur_cmnt < cmnts.len() { + Some(cmnts[cur_cmnt].clone()) + } else { + None + } + } + _ => None + } + } + + fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> { + try!(self.maybe_print_comment(lit.span.lo)); + match self.next_lit(lit.span.lo) { + Some(ref ltrl) => { + return word(self.writer(), &(*ltrl).lit); + } + _ => () + } + match lit.node { + ast::LitStr(ref st, style) => self.print_string(&st, style), + ast::LitByte(byte) => { + let mut res = String::from("b'"); + res.extend(ascii::escape_default(byte).map(|c| c as char)); + res.push('\''); + word(self.writer(), &res[..]) + } + ast::LitChar(ch) => { + let mut res = String::from("'"); + res.extend(ch.escape_default()); + res.push('\''); + word(self.writer(), &res[..]) + } + ast::LitInt(i, t) => { + match t { + ast::SignedIntLit(st, ast::Plus) => { + word(self.writer(), + &ast_util::int_ty_to_string(st, Some(i as i64))) + } + ast::SignedIntLit(st, ast::Minus) => { + let istr = ast_util::int_ty_to_string(st, Some(-(i as i64))); + word(self.writer(), + &format!("-{}", istr)) + } + ast::UnsignedIntLit(ut) => { + word(self.writer(), &ast_util::uint_ty_to_string(ut, Some(i))) + } + ast::UnsuffixedIntLit(ast::Plus) => { + word(self.writer(), &format!("{}", i)) + } + ast::UnsuffixedIntLit(ast::Minus) => { + word(self.writer(), &format!("-{}", i)) + } + } + } + ast::LitFloat(ref f, t) => { + word(self.writer(), + &format!( + "{}{}", + &f, + &ast_util::float_ty_to_string(t))) + } + ast::LitFloatUnsuffixed(ref f) => word(self.writer(), &f[..]), + ast::LitBool(val) => { + if val { word(self.writer(), "true") } else { word(self.writer(), "false") } + } + ast::LitByteStr(ref v) => { + let mut escaped: String = String::new(); + for &ch in v.iter() { + escaped.extend(ascii::escape_default(ch) + .map(|c| c as char)); + } + word(self.writer(), &format!("b\"{}\"", escaped)) + } + } + } + + fn print_string(&mut self, st: &str, + style: ast::StrStyle) -> io::Result<()> { + let st = match style { + ast::CookedStr => { + (format!("\"{}\"", st.escape_default())) + } + ast::RawStr(n) => { + (format!("r{delim}\"{string}\"{delim}", + delim=repeat("#", n), + string=st)) + } + }; + word(self.writer(), &st[..]) + } + + fn print_inner_attributes(&mut self, + attrs: &[ast::Attribute]) -> io::Result<()> { + let mut count = 0; + for attr in attrs { + match attr.node.style { + ast::AttrInner => { + try!(self.print_attribute(attr)); + count += 1; + } + _ => {/* fallthrough */ } + } + } + if count > 0 { + try!(self.hardbreak_if_not_bol()); + } + Ok(()) + } + + fn print_outer_attributes(&mut self, + attrs: &[ast::Attribute]) -> io::Result<()> { + let mut count = 0; + for attr in attrs { + match attr.node.style { + ast::AttrOuter => { + try!(self.print_attribute(attr)); + count += 1; + } + _ => {/* fallthrough */ } + } + } + if count > 0 { + try!(self.hardbreak_if_not_bol()); + } + Ok(()) + } + + fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> { + try!(self.hardbreak_if_not_bol()); + try!(self.maybe_print_comment(attr.span.lo)); + if attr.node.is_sugared_doc { + word(self.writer(), &attr.value_str().unwrap()) + } else { + match attr.node.style { + ast::AttrInner => try!(word(self.writer(), "#![")), + ast::AttrOuter => try!(word(self.writer(), "#[")), + } + try!(self.print_meta_item(&*attr.meta())); + word(self.writer(), "]") + } + } + + fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> { + try!(self.ibox(indent_unit)); + match item.node { + ast::MetaWord(ref name) => { + try!(word(self.writer(), &name)); + } + ast::MetaNameValue(ref name, ref value) => { + try!(self.word_space(&name[..])); + try!(self.word_space("=")); + try!(self.print_literal(value)); + } + ast::MetaList(ref name, ref items) => { + try!(word(self.writer(), &name)); + try!(self.popen()); + try!(self.commasep(Consistent, + &items[..], + |s, i| s.print_meta_item(&**i))); + try!(self.pclose()); + } + } + self.end() + } +} + +impl<'a> PrintState<'a> for State<'a> { + fn writer(&mut self) -> &mut pp::Printer<'a> { + &mut self.s + } + + fn boxes(&mut self) -> &mut Vec { + &mut self.boxes + } + + fn comments(&mut self) -> &mut Option> { + &mut self.comments + } + + fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral { + &mut self.cur_cmnt_and_lit } - pub fn popen(&mut self) -> io::Result<()> { word(&mut self.s, "(") } + fn literals(&self) -> &Option> { + &self.literals + } +} - pub fn pclose(&mut self) -> io::Result<()> { word(&mut self.s, ")") } +impl<'a> State<'a> { + pub fn cbox(&mut self, u: usize) -> io::Result<()> { + self.boxes.push(pp::Breaks::Consistent); + pp::cbox(&mut self.s, u) + } + + pub fn nbsp(&mut self) -> io::Result<()> { word(&mut self.s, " ") } + + pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> { + try!(word(&mut self.s, w)); + self.nbsp() + } pub fn head(&mut self, w: &str) -> io::Result<()> { // outer-box is consistent @@ -523,25 +849,6 @@ impl<'a> State<'a> { self.bclose_(span, indent_unit) } - pub fn is_begin(&mut self) -> bool { - match self.s.last_token() { - pp::Token::Begin(_) => true, - _ => false, - } - } - - pub fn is_end(&mut self) -> bool { - match self.s.last_token() { - pp::Token::End => true, - _ => false, - } - } - - // is this the beginning of a line? - pub fn is_bol(&mut self) -> bool { - self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok() - } - pub fn in_cbox(&self) -> bool { match self.boxes.last() { Some(&last_box) => last_box == pp::Breaks::Consistent, @@ -549,12 +856,6 @@ impl<'a> State<'a> { } } - pub fn hardbreak_if_not_bol(&mut self) -> io::Result<()> { - if !self.is_bol() { - try!(hardbreak(&mut self.s)) - } - Ok(()) - } pub fn space_if_not_bol(&mut self) -> io::Result<()> { if !self.is_bol() { try!(space(&mut self.s)); } Ok(()) @@ -584,17 +885,6 @@ impl<'a> State<'a> { word(&mut self.s, "*/") } - pub fn commasep(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()> where - F: FnMut(&mut State, &T) -> io::Result<()>, - { - try!(self.rbox(0, b)); - let mut first = true; - for elt in elts { - if first { first = false; } else { try!(self.word_space(",")); } - try!(op(self, elt)); - } - self.end() - } pub fn commasep_cmnt(&mut self, @@ -1326,58 +1616,6 @@ impl<'a> State<'a> { self.ann.post(self, NodeSubItem(ii.id)) } - pub fn print_outer_attributes(&mut self, - attrs: &[ast::Attribute]) -> io::Result<()> { - let mut count = 0; - for attr in attrs { - match attr.node.style { - ast::AttrOuter => { - try!(self.print_attribute(attr)); - count += 1; - } - _ => {/* fallthrough */ } - } - } - if count > 0 { - try!(self.hardbreak_if_not_bol()); - } - Ok(()) - } - - pub fn print_inner_attributes(&mut self, - attrs: &[ast::Attribute]) -> io::Result<()> { - let mut count = 0; - for attr in attrs { - match attr.node.style { - ast::AttrInner => { - try!(self.print_attribute(attr)); - count += 1; - } - _ => {/* fallthrough */ } - } - } - if count > 0 { - try!(self.hardbreak_if_not_bol()); - } - Ok(()) - } - - pub fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> { - try!(self.hardbreak_if_not_bol()); - try!(self.maybe_print_comment(attr.span.lo)); - if attr.node.is_sugared_doc { - word(&mut self.s, &attr.value_str().unwrap()) - } else { - match attr.node.style { - ast::AttrInner => try!(word(&mut self.s, "#![")), - ast::AttrOuter => try!(word(&mut self.s, "#[")), - } - try!(self.print_meta_item(&*attr.meta())); - word(&mut self.s, "]") - } - } - - pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> { try!(self.maybe_print_comment(st.span.lo)); match st.node { @@ -2620,29 +2858,6 @@ impl<'a> State<'a> { Ok(()) } - pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> { - try!(self.ibox(indent_unit)); - match item.node { - ast::MetaWord(ref name) => { - try!(word(&mut self.s, &name)); - } - ast::MetaNameValue(ref name, ref value) => { - try!(self.word_space(&name[..])); - try!(self.word_space("=")); - try!(self.print_literal(value)); - } - ast::MetaList(ref name, ref items) => { - try!(word(&mut self.s, &name)); - try!(self.popen()); - try!(self.commasep(Consistent, - &items[..], - |s, i| s.print_meta_item(&**i))); - try!(self.pclose()); - } - } - self.end() - } - pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> { match vp.node { ast::ViewPathSimple(ident, ref path) => { @@ -2832,181 +3047,6 @@ impl<'a> State<'a> { Ok(()) } - pub fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> { - try!(self.maybe_print_comment(lit.span.lo)); - match self.next_lit(lit.span.lo) { - Some(ref ltrl) => { - return word(&mut self.s, &(*ltrl).lit); - } - _ => () - } - match lit.node { - ast::LitStr(ref st, style) => self.print_string(&st, style), - ast::LitByte(byte) => { - let mut res = String::from("b'"); - res.extend(ascii::escape_default(byte).map(|c| c as char)); - res.push('\''); - word(&mut self.s, &res[..]) - } - ast::LitChar(ch) => { - let mut res = String::from("'"); - res.extend(ch.escape_default()); - res.push('\''); - word(&mut self.s, &res[..]) - } - ast::LitInt(i, t) => { - match t { - ast::SignedIntLit(st, ast::Plus) => { - word(&mut self.s, - &ast_util::int_ty_to_string(st, Some(i as i64))) - } - ast::SignedIntLit(st, ast::Minus) => { - let istr = ast_util::int_ty_to_string(st, Some(-(i as i64))); - word(&mut self.s, - &format!("-{}", istr)) - } - ast::UnsignedIntLit(ut) => { - word(&mut self.s, &ast_util::uint_ty_to_string(ut, Some(i))) - } - ast::UnsuffixedIntLit(ast::Plus) => { - word(&mut self.s, &format!("{}", i)) - } - ast::UnsuffixedIntLit(ast::Minus) => { - word(&mut self.s, &format!("-{}", i)) - } - } - } - ast::LitFloat(ref f, t) => { - word(&mut self.s, - &format!( - "{}{}", - &f, - &ast_util::float_ty_to_string(t))) - } - ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, &f[..]), - ast::LitBool(val) => { - if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") } - } - ast::LitByteStr(ref v) => { - let mut escaped: String = String::new(); - for &ch in v.iter() { - escaped.extend(ascii::escape_default(ch) - .map(|c| c as char)); - } - word(&mut self.s, &format!("b\"{}\"", escaped)) - } - } - } - - pub fn next_lit(&mut self, pos: BytePos) -> Option { - match self.literals { - Some(ref lits) => { - while self.cur_cmnt_and_lit.cur_lit < lits.len() { - let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone(); - if ltrl.pos > pos { return None; } - self.cur_cmnt_and_lit.cur_lit += 1; - if ltrl.pos == pos { return Some(ltrl); } - } - None - } - _ => None - } - } - - pub fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> { - loop { - match self.next_comment() { - Some(ref cmnt) => { - if (*cmnt).pos < pos { - try!(self.print_comment(cmnt)); - self.cur_cmnt_and_lit.cur_cmnt += 1; - } else { break; } - } - _ => break - } - } - Ok(()) - } - - pub fn print_comment(&mut self, - cmnt: &comments::Comment) -> io::Result<()> { - match cmnt.style { - comments::Mixed => { - assert_eq!(cmnt.lines.len(), 1); - try!(zerobreak(&mut self.s)); - try!(word(&mut self.s, &cmnt.lines[0])); - zerobreak(&mut self.s) - } - comments::Isolated => { - try!(self.hardbreak_if_not_bol()); - for line in &cmnt.lines { - // Don't print empty lines because they will end up as trailing - // whitespace - if !line.is_empty() { - try!(word(&mut self.s, &line[..])); - } - try!(hardbreak(&mut self.s)); - } - Ok(()) - } - comments::Trailing => { - try!(word(&mut self.s, " ")); - if cmnt.lines.len() == 1 { - try!(word(&mut self.s, &cmnt.lines[0])); - hardbreak(&mut self.s) - } else { - try!(self.ibox(0)); - for line in &cmnt.lines { - if !line.is_empty() { - try!(word(&mut self.s, &line[..])); - } - try!(hardbreak(&mut self.s)); - } - self.end() - } - } - comments::BlankLine => { - // We need to do at least one, possibly two hardbreaks. - let is_semi = match self.s.last_token() { - pp::Token::String(s, _) => ";" == s, - _ => false - }; - if is_semi || self.is_begin() || self.is_end() { - try!(hardbreak(&mut self.s)); - } - hardbreak(&mut self.s) - } - } - } - - pub fn print_string(&mut self, st: &str, - style: ast::StrStyle) -> io::Result<()> { - let st = match style { - ast::CookedStr => { - (format!("\"{}\"", st.escape_default())) - } - ast::RawStr(n) => { - (format!("r{delim}\"{string}\"{delim}", - delim=repeat("#", n), - string=st)) - } - }; - word(&mut self.s, &st[..]) - } - - pub fn next_comment(&mut self) -> Option { - match self.comments { - Some(ref cmnts) => { - if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() { - Some(cmnts[self.cur_cmnt_and_lit.cur_cmnt].clone()) - } else { - None - } - } - _ => None - } - } - pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option) -> io::Result<()> { diff --git a/src/test/auxiliary/lint_for_crate.rs b/src/test/auxiliary/lint_for_crate.rs index 708fcafcb5311..7ae161a86a361 100644 --- a/src/test/auxiliary/lint_for_crate.rs +++ b/src/test/auxiliary/lint_for_crate.rs @@ -15,10 +15,12 @@ #[macro_use] extern crate rustc; extern crate rustc_front; +extern crate syntax; -use rustc::lint::{Context, LintPass, LintPassObject, LintArray}; +use rustc::lint::{LateContext, LintContext, LintPass, LateLintPass, LateLintPassObject, LintArray}; use rustc::plugin::Registry; -use rustc_front::{hir, attr}; +use rustc_front::hir; +use syntax::attr; declare_lint!(CRATE_NOT_OKAY, Warn, "crate not marked with #![crate_okay]"); @@ -28,8 +30,10 @@ impl LintPass for Pass { fn get_lints(&self) -> LintArray { lint_array!(CRATE_NOT_OKAY) } +} - fn check_crate(&mut self, cx: &Context, krate: &hir::Crate) { +impl LateLintPass for Pass { + fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) { if !attr::contains_name(&krate.attrs, "crate_okay") { cx.span_lint(CRATE_NOT_OKAY, krate.span, "crate is not marked with #![crate_okay]"); @@ -39,5 +43,5 @@ impl LintPass for Pass { #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { - reg.register_lint_pass(box Pass as LintPassObject); + reg.register_late_lint_pass(box Pass as LateLintPassObject); } diff --git a/src/test/auxiliary/lint_group_plugin_test.rs b/src/test/auxiliary/lint_group_plugin_test.rs index adc194fa45486..13cf5f09db32b 100644 --- a/src/test/auxiliary/lint_group_plugin_test.rs +++ b/src/test/auxiliary/lint_group_plugin_test.rs @@ -20,7 +20,7 @@ extern crate rustc_front; extern crate rustc; use rustc_front::hir; -use rustc::lint::{Context, LintPass, LintPassObject, LintArray}; +use rustc::lint::{LateContext, LintContext, LintPass, LateLintPass, LateLintPassObject, LintArray}; use rustc::plugin::Registry; declare_lint!(TEST_LINT, Warn, "Warn about items named 'lintme'"); @@ -33,8 +33,10 @@ impl LintPass for Pass { fn get_lints(&self) -> LintArray { lint_array!(TEST_LINT, PLEASE_LINT) } +} - fn check_item(&mut self, cx: &Context, it: &hir::Item) { +impl LateLintPass for Pass { + fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { match &*it.ident.name.as_str() { "lintme" => cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'"), "pleaselintme" => cx.span_lint(PLEASE_LINT, it.span, "item is named 'pleaselintme'"), @@ -45,6 +47,6 @@ impl LintPass for Pass { #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { - reg.register_lint_pass(box Pass as LintPassObject); + reg.register_late_lint_pass(box Pass as LateLintPassObject); reg.register_lint_group("lint_me", vec![TEST_LINT, PLEASE_LINT]); } diff --git a/src/test/auxiliary/lint_plugin_test.rs b/src/test/auxiliary/lint_plugin_test.rs index e6f91db230009..4f5e8d6e0874c 100644 --- a/src/test/auxiliary/lint_plugin_test.rs +++ b/src/test/auxiliary/lint_plugin_test.rs @@ -13,15 +13,16 @@ #![feature(plugin_registrar)] #![feature(box_syntax, rustc_private)] -extern crate rustc_front; +extern crate syntax; // Load rustc as a plugin to get macros #[macro_use] extern crate rustc; -use rustc::lint::{Context, LintPass, LintPassObject, LintArray}; +use rustc::lint::{EarlyContext, LintContext, LintPass, EarlyLintPass, + EarlyLintPassObject, LintArray}; use rustc::plugin::Registry; -use rustc_front::hir; +use syntax::ast; declare_lint!(TEST_LINT, Warn, "Warn about items named 'lintme'"); struct Pass; @@ -30,8 +31,10 @@ impl LintPass for Pass { fn get_lints(&self) -> LintArray { lint_array!(TEST_LINT) } +} - fn check_item(&mut self, cx: &Context, it: &hir::Item) { +impl EarlyLintPass for Pass { + fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) { if it.ident.name == "lintme" { cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'"); } @@ -40,5 +43,5 @@ impl LintPass for Pass { #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { - reg.register_lint_pass(box Pass as LintPassObject); + reg.register_early_lint_pass(box Pass as EarlyLintPassObject); } diff --git a/src/test/codegen/adjustments.rs b/src/test/codegen/adjustments.rs new file mode 100644 index 0000000000000..b0438f561b935 --- /dev/null +++ b/src/test/codegen/adjustments.rs @@ -0,0 +1,28 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// compile-flags: -C no-prepopulate-passes + +// Hack to get the correct size for the length part in slices +// CHECK: @helper([[USIZE:i[0-9]+]]) +#[no_mangle] +fn helper(_: usize) { +} + +// CHECK-LABEL: @no_op_slice_adjustment +#[no_mangle] +pub fn no_op_slice_adjustment(x: &[u8]) -> &[u8] { + // We used to generate an extra alloca and memcpy for the block's trailing expression value, so + // check that we copy directly to the return value slot +// CHECK: [[SRC:%[0-9]+]] = bitcast { i8*, [[USIZE]] }* %x to +// CHECK: [[DST:%[0-9]+]] = bitcast { i8*, [[USIZE]] }* %sret_slot to i8* +// CHECK: call void @llvm.memcpy.{{.*}}(i8* [[DST]], i8* [[SRC]], + { x } +} diff --git a/src/test/compile-fail/autoderef-full-lval.rs b/src/test/compile-fail/autoderef-full-lval.rs index 2c5749e0d5d39..0d666a4920038 100644 --- a/src/test/compile-fail/autoderef-full-lval.rs +++ b/src/test/compile-fail/autoderef-full-lval.rs @@ -8,7 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![allow(unknown_features)] #![feature(box_syntax)] struct clam { diff --git a/src/test/compile-fail/borrow-tuple-fields.rs b/src/test/compile-fail/borrow-tuple-fields.rs index b1abbad525356..f3417fafe9037 100644 --- a/src/test/compile-fail/borrow-tuple-fields.rs +++ b/src/test/compile-fail/borrow-tuple-fields.rs @@ -8,7 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![allow(unknown_features)] #![feature(box_syntax)] struct Foo(Box, isize); diff --git a/src/test/compile-fail/cast-as-bool.rs b/src/test/compile-fail/cast-as-bool.rs index 92cbbaa1cb442..52a4950022d1e 100644 --- a/src/test/compile-fail/cast-as-bool.rs +++ b/src/test/compile-fail/cast-as-bool.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let u = (5 as bool); + let u = 5 as bool; //~^ ERROR cannot cast as `bool` //~^^ HELP compare with zero instead } diff --git a/src/test/compile-fail/dropck_arr_cycle_checked.rs b/src/test/compile-fail/dropck_arr_cycle_checked.rs index 19f790ddc9071..9cfeaca6dfadf 100644 --- a/src/test/compile-fail/dropck_arr_cycle_checked.rs +++ b/src/test/compile-fail/dropck_arr_cycle_checked.rs @@ -19,7 +19,6 @@ use std::cell::Cell; use id::Id; mod s { - #![allow(unstable)] use std::sync::atomic::{AtomicUsize, Ordering}; static S_COUNT: AtomicUsize = AtomicUsize::new(0); diff --git a/src/test/compile-fail/dropck_tarena_cycle_checked.rs b/src/test/compile-fail/dropck_tarena_cycle_checked.rs index 584e5eabf0cd8..d36293a484d4e 100644 --- a/src/test/compile-fail/dropck_tarena_cycle_checked.rs +++ b/src/test/compile-fail/dropck_tarena_cycle_checked.rs @@ -16,7 +16,6 @@ // which is a reduction of this code to more directly show the reason // for the error message we see here.) -#![allow(unstable)] #![feature(const_fn)] extern crate arena; @@ -26,7 +25,6 @@ use std::cell::Cell; use id::Id; mod s { - #![allow(unstable)] use std::sync::atomic::{AtomicUsize, Ordering}; static S_COUNT: AtomicUsize = AtomicUsize::new(0); diff --git a/src/test/compile-fail/dropck_tarena_unsound_drop.rs b/src/test/compile-fail/dropck_tarena_unsound_drop.rs index 7a204e6143eef..600c794109ccf 100644 --- a/src/test/compile-fail/dropck_tarena_unsound_drop.rs +++ b/src/test/compile-fail/dropck_tarena_unsound_drop.rs @@ -19,8 +19,6 @@ // (Also compare against dropck_tarena_cycle_checked.rs, from which // this was reduced to better understand its error message.) -#![allow(unstable)] - extern crate arena; use arena::TypedArena; diff --git a/src/test/compile-fail/dropck_vec_cycle_checked.rs b/src/test/compile-fail/dropck_vec_cycle_checked.rs index bc33ff8399aa5..caf25e68d568c 100644 --- a/src/test/compile-fail/dropck_vec_cycle_checked.rs +++ b/src/test/compile-fail/dropck_vec_cycle_checked.rs @@ -18,7 +18,6 @@ use std::cell::Cell; use id::Id; mod s { - #![allow(unstable)] use std::sync::atomic::{AtomicUsize, Ordering}; static S_COUNT: AtomicUsize = AtomicUsize::new(0); diff --git a/src/test/compile-fail/for-loop-hygiene.rs b/src/test/compile-fail/for-loop-hygiene.rs index ff6f848ab598d..f06882875fd9b 100644 --- a/src/test/compile-fail/for-loop-hygiene.rs +++ b/src/test/compile-fail/for-loop-hygiene.rs @@ -11,8 +11,6 @@ // for-loops are expanded in the front end, and use an `iter` ident in their expansion. Check that // `iter` is not accessible inside the for loop. -#![allow(unstable)] - fn main() { for _ in 0..10 { iter.next(); //~ error: unresolved name `iter` diff --git a/src/test/compile-fail/issue-17283.rs b/src/test/compile-fail/issue-17283.rs index a481fec6bf968..c7d6443663241 100644 --- a/src/test/compile-fail/issue-17283.rs +++ b/src/test/compile-fail/issue-17283.rs @@ -11,6 +11,8 @@ // Test that the parser does not attempt to parse struct literals // within assignments in if expressions. +#![allow(unused_parens)] + struct Foo { foo: usize } diff --git a/src/test/compile-fail/issue-22872.rs b/src/test/compile-fail/issue-22872.rs deleted file mode 100644 index 86982284ac2c0..0000000000000 --- a/src/test/compile-fail/issue-22872.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -trait Wrap<'b> { - fn foo(&'b mut self); -} - -struct Wrapper

(P); - -impl<'b, P> Wrap<'b> for Wrapper

-where P: Process<'b>, -

>::Item: Iterator { - fn foo(&mut self) {} -} - - -pub trait Process<'a> { - type Item; - fn bar(&'a self); -} - -fn push_process

(process: P) where P: Process<'static> { - let _: Box Wrap<'b>> = Box::new(Wrapper(process)); - //~^ ERROR the trait `for<'b> Process<'b>` is not implemented for the type `P` [E0277] - //~| ERROR the trait `for<'b> core::iter::Iterator` is not implemented for the type - //~| ERROR cannot infer an appropriate lifetime for lifetime parameter `'b` due to conflicting -} - -fn main() {} diff --git a/src/test/compile-fail/issue-23046.rs b/src/test/compile-fail/issue-23046.rs index 8c83c4cefd191..dba9c32f9b480 100644 --- a/src/test/compile-fail/issue-23046.rs +++ b/src/test/compile-fail/issue-23046.rs @@ -24,7 +24,7 @@ pub fn let_<'var, VAR, F: for<'v: 'var> Fn(Expr<'v, VAR>) -> Expr<'v, VAR>> } fn main() { - let ex = (|x| { + let ex = |x| { let_(add(x,x), |y| { //~ ERROR unable to infer enough type information about `_` - let_(add(x, x), |x|x)})}); + let_(add(x, x), |x|x)})}; } diff --git a/src/test/compile-fail/issue-23729.rs b/src/test/compile-fail/issue-23729.rs index 3d77d171acebf..f98cf6575d6ec 100644 --- a/src/test/compile-fail/issue-23729.rs +++ b/src/test/compile-fail/issue-23729.rs @@ -26,7 +26,7 @@ fn main() { self.pos += 1; Some(next_val) } else { - let next_val = (self.mem[0] + self.mem[1]); + let next_val = self.mem[0] + self.mem[1]; self.mem[0] = self.mem[1]; self.mem[1] = next_val; Some(next_val) diff --git a/src/test/compile-fail/issue-26905.rs b/src/test/compile-fail/issue-26905.rs new file mode 100644 index 0000000000000..3b8fac832a464 --- /dev/null +++ b/src/test/compile-fail/issue-26905.rs @@ -0,0 +1,34 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(unsize, coerce_unsized)] + +// Verfies that non-PhantomData ZSTs still cause coercions to fail. +// They might have additional semantics that we don't want to bulldoze. + +use std::marker::{Unsize, PhantomData}; +use std::ops::CoerceUnsized; + +struct NotPhantomData(PhantomData); + +struct MyRc { + _ptr: *const T, + _boo: NotPhantomData, +} + +impl, U: ?Sized> CoerceUnsized> for MyRc{ } //~ERROR + +fn main() { + let data = [1, 2, 3]; + let iter = data.iter(); + let x = MyRc { _ptr: &iter, _boo: NotPhantomData(PhantomData) }; + let _y: MyRc> = x; +} + diff --git a/src/test/compile-fail/lint-visible-private-types.rs b/src/test/compile-fail/lint-visible-private-types.rs index c6dc3b70bef37..d34738282eb26 100644 --- a/src/test/compile-fail/lint-visible-private-types.rs +++ b/src/test/compile-fail/lint-visible-private-types.rs @@ -8,7 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![deny(visible_private_types)] #![allow(dead_code)] #![crate_type="lib"] diff --git a/src/test/compile-fail/loop-does-not-diverge.rs b/src/test/compile-fail/loop-does-not-diverge.rs index 12de4a714efc5..cd320ba148aba 100644 --- a/src/test/compile-fail/loop-does-not-diverge.rs +++ b/src/test/compile-fail/loop-does-not-diverge.rs @@ -18,5 +18,5 @@ fn forever() -> ! { } fn main() { - if (1 == 2) { forever(); } + if 1 == 2 { forever(); } } diff --git a/src/test/compile-fail/variance-trait-bounds.rs b/src/test/compile-fail/variance-trait-bounds.rs index 222d8338aa2c4..b6f197987bab1 100644 --- a/src/test/compile-fail/variance-trait-bounds.rs +++ b/src/test/compile-fail/variance-trait-bounds.rs @@ -8,7 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![deny(bivariance)] #![allow(dead_code)] #![feature(rustc_attrs)] diff --git a/src/test/compile-fail/variance-types.rs b/src/test/compile-fail/variance-types.rs index e407ebe345a5b..2fd8bf20c7997 100644 --- a/src/test/compile-fail/variance-types.rs +++ b/src/test/compile-fail/variance-types.rs @@ -8,7 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![deny(bivariance)] #![allow(dead_code)] #![feature(rustc_attrs)] diff --git a/src/test/compile-fail/vec-must-not-hide-type-from-dropck.rs b/src/test/compile-fail/vec-must-not-hide-type-from-dropck.rs index 375289596841d..c8f4326bb2824 100644 --- a/src/test/compile-fail/vec-must-not-hide-type-from-dropck.rs +++ b/src/test/compile-fail/vec-must-not-hide-type-from-dropck.rs @@ -29,7 +29,6 @@ use std::cell::Cell; use id::Id; mod s { - #![allow(unstable)] use std::sync::atomic::{AtomicUsize, Ordering}; static S_COUNT: AtomicUsize = AtomicUsize::new(0); diff --git a/src/test/pretty/issue-4264.pp b/src/test/pretty/issue-4264.pp index 6398c76d0a351..835f7fc96c63f 100644 --- a/src/test/pretty/issue-4264.pp +++ b/src/test/pretty/issue-4264.pp @@ -27,10 +27,9 @@ let _: [(); (1 as usize)] = ([(() as ())] as [(); 1]); let _ = - (((&((([(1 as i32), (2 as i32), (3 as i32)] as [i32; 3])) as [i32; 3]) - as &[i32; 3]) as *const _ as *const [i32; 3]) as - *const [i32; (3 as usize)] as *const [i32; 3]); - + (((&([(1 as i32), (2 as i32), (3 as i32)] as [i32; 3]) as &[i32; 3]) + as *const _ as *const [i32; 3]) as *const [i32; (3 as usize)] as + *const [i32; 3]); diff --git a/src/test/run-make/archive-duplicate-names/Makefile b/src/test/run-make/archive-duplicate-names/Makefile index 72c2d389e2aac..5202e6dea541e 100644 --- a/src/test/run-make/archive-duplicate-names/Makefile +++ b/src/test/run-make/archive-duplicate-names/Makefile @@ -3,8 +3,8 @@ all: mkdir $(TMPDIR)/a mkdir $(TMPDIR)/b - $(CC) -c -o $(TMPDIR)/a/foo.o foo.c - $(CC) -c -o $(TMPDIR)/b/foo.o bar.c + $(call COMPILE_OBJ,$(TMPDIR)/a/foo.o,foo.c) + $(call COMPILE_OBJ,$(TMPDIR)/b/foo.o,bar.c) ar crus $(TMPDIR)/libfoo.a $(TMPDIR)/a/foo.o $(TMPDIR)/b/foo.o $(RUSTC) foo.rs $(RUSTC) bar.rs diff --git a/src/test/run-make/c-dynamic-dylib/cfoo.c b/src/test/run-make/c-dynamic-dylib/cfoo.c index 113717a776a99..a975549354123 100644 --- a/src/test/run-make/c-dynamic-dylib/cfoo.c +++ b/src/test/run-make/c-dynamic-dylib/cfoo.c @@ -1,2 +1,5 @@ // ignore-license +#ifdef _WIN32 +__declspec(dllexport) +#endif int foo() { return 0; } diff --git a/src/test/run-make/c-dynamic-rlib/cfoo.c b/src/test/run-make/c-dynamic-rlib/cfoo.c index 113717a776a99..b2849326a7588 100644 --- a/src/test/run-make/c-dynamic-rlib/cfoo.c +++ b/src/test/run-make/c-dynamic-rlib/cfoo.c @@ -1,2 +1,6 @@ // ignore-license + +#ifdef _WIN32 +__declspec(dllexport) +#endif int foo() { return 0; } diff --git a/src/test/run-make/c-link-to-rust-dylib/Makefile b/src/test/run-make/c-link-to-rust-dylib/Makefile index 2a6cc0394852e..7b2130cd4ed96 100644 --- a/src/test/run-make/c-link-to-rust-dylib/Makefile +++ b/src/test/run-make/c-link-to-rust-dylib/Makefile @@ -1,10 +1,17 @@ -include ../tools.mk -HOST_LIB_DIR=$(TMPDIR)/../../../stage$(RUST_BUILD_STAGE)/lib - -all: - $(RUSTC) foo.rs - $(CC) bar.c -lfoo -o $(call RUN_BINFILE,bar) $(call RPATH_LINK_SEARCH,$(HOST_LIB_DIR)) -Wl,-rpath,$(TMPDIR) $(EXTRACFLAGS) +all: $(TMPDIR)/$(call BIN,bar) $(call RUN,bar) $(call REMOVE_DYLIBS,foo) $(call FAIL,bar) + +ifdef IS_MSVC +$(TMPDIR)/$(call BIN,bar): $(call DYLIB,foo) + $(CC) bar.c $(TMPDIR)/foo.lib $(call OUT_EXE,bar) +else +$(TMPDIR)/$(call BIN,bar): $(call DYLIB,foo) + $(CC) bar.c -lfoo -o $(call RUN_BINFILE,bar) -L $(TMPDIR) +endif + +$(call DYLIB,foo): foo.rs + $(RUSTC) foo.rs diff --git a/src/test/run-make/c-link-to-rust-staticlib/Makefile b/src/test/run-make/c-link-to-rust-staticlib/Makefile index 2b927e3e4a730..3d44b3c256efc 100644 --- a/src/test/run-make/c-link-to-rust-staticlib/Makefile +++ b/src/test/run-make/c-link-to-rust-staticlib/Makefile @@ -1,12 +1,12 @@ -include ../tools.mk -EXTRAFLAGS := $(EXTRACFLAGS) - # FIXME: ignore freebsd ifneq ($(shell uname),FreeBSD) all: $(RUSTC) foo.rs - $(CC) bar.c -lfoo -o $(call RUN_BINFILE,bar) $(EXTRAFLAGS) $(EXTRACXXFLAGS) + cp $(TMPDIR)/libfoo.a $(call NATIVE_STATICLIB,foo2) + $(CC) bar.c $(call NATIVE_STATICLIB,foo2) $(call OUT_EXE,bar) \ + $(EXTRACFLAGS) $(EXTRACXXFLAGS) $(call RUN,bar) rm $(call STATICLIB,foo*) $(call RUN,bar) diff --git a/src/test/run-make/c-static-dylib/Makefile b/src/test/run-make/c-static-dylib/Makefile index 9914e12d5696e..f88786857ccdc 100644 --- a/src/test/run-make/c-static-dylib/Makefile +++ b/src/test/run-make/c-static-dylib/Makefile @@ -1,9 +1,9 @@ -include ../tools.mk -all: $(call STATICLIB,cfoo) +all: $(call NATIVE_STATICLIB,cfoo) $(RUSTC) foo.rs -C prefer-dynamic $(RUSTC) bar.rs - rm $(TMPDIR)/$(call STATICLIB_GLOB,cfoo) + rm $(call NATIVE_STATICLIB,cfoo) $(call RUN,bar) $(call REMOVE_DYLIBS,foo) $(call FAIL,bar) diff --git a/src/test/run-make/c-static-rlib/Makefile b/src/test/run-make/c-static-rlib/Makefile index 02b24ef9846dd..be22b2728f05b 100644 --- a/src/test/run-make/c-static-rlib/Makefile +++ b/src/test/run-make/c-static-rlib/Makefile @@ -1,8 +1,8 @@ -include ../tools.mk -all: $(call STATICLIB,cfoo) +all: $(call NATIVE_STATICLIB,cfoo) $(RUSTC) foo.rs $(RUSTC) bar.rs $(call REMOVE_RLIBS,foo) - rm $(TMPDIR)/$(call STATICLIB_GLOB,cfoo) + rm $(call NATIVE_STATICLIB,cfoo) $(call RUN,bar) diff --git a/src/test/run-make/crate-name-priority/Makefile b/src/test/run-make/crate-name-priority/Makefile index 2fe5183243361..17ecb33ab28d0 100644 --- a/src/test/run-make/crate-name-priority/Makefile +++ b/src/test/run-make/crate-name-priority/Makefile @@ -7,5 +7,5 @@ all: rm $(TMPDIR)/$(call BIN,bar) $(RUSTC) foo1.rs rm $(TMPDIR)/$(call BIN,foo) - $(RUSTC) foo1.rs -o $(TMPDIR)/bar1 + $(RUSTC) foo1.rs -o $(TMPDIR)/$(call BIN,bar1) rm $(TMPDIR)/$(call BIN,bar1) diff --git a/src/test/run-make/execution-engine/test.rs b/src/test/run-make/execution-engine/test.rs index a7c6f5225a652..6fc12d3a75078 100644 --- a/src/test/run-make/execution-engine/test.rs +++ b/src/test/run-make/execution-engine/test.rs @@ -228,7 +228,7 @@ fn compile_program(input: &str, sysroot: PathBuf) let ast_map = driver::make_map(&sess, &mut hir_forest); driver::phase_3_run_analysis_passes( - sess, ast_map, &krate, &arenas, id, MakeGlobMap::No, |tcx, analysis| { + sess, ast_map, &arenas, id, MakeGlobMap::No, |tcx, analysis| { let trans = driver::phase_4_translate_to_llvm(tcx, analysis); diff --git a/src/test/run-make/extern-fn-generic/Makefile b/src/test/run-make/extern-fn-generic/Makefile index a325acbf687b5..cf897dba1f279 100644 --- a/src/test/run-make/extern-fn-generic/Makefile +++ b/src/test/run-make/extern-fn-generic/Makefile @@ -1,8 +1,6 @@ -include ../tools.mk -all: - $(CC) -std=c99 test.c -c -o $(TMPDIR)/test.o - $(AR) rcs $(TMPDIR)/libtest.a $(TMPDIR)/test.o - $(RUSTC) testcrate.rs -L $(TMPDIR) - $(RUSTC) test.rs -L $(TMPDIR) +all: $(call NATIVE_STATICLIB,test) + $(RUSTC) testcrate.rs + $(RUSTC) test.rs $(call RUN,test) || exit 1 diff --git a/src/test/run-make/extern-fn-mangle/Makefile b/src/test/run-make/extern-fn-mangle/Makefile index ea6971853fe99..042048ec25f63 100644 --- a/src/test/run-make/extern-fn-mangle/Makefile +++ b/src/test/run-make/extern-fn-mangle/Makefile @@ -1,7 +1,5 @@ -include ../tools.mk -all: - $(CC) -std=c99 test.c -c -o $(TMPDIR)/test.o - $(AR) rcs $(TMPDIR)/libtest.a $(TMPDIR)/test.o - $(RUSTC) test.rs -L $(TMPDIR) +all: $(call NATIVE_STATICLIB,test) + $(RUSTC) test.rs $(call RUN,test) || exit 1 diff --git a/src/test/run-make/extern-fn-with-packed-struct/Makefile b/src/test/run-make/extern-fn-with-packed-struct/Makefile index ea6971853fe99..042048ec25f63 100644 --- a/src/test/run-make/extern-fn-with-packed-struct/Makefile +++ b/src/test/run-make/extern-fn-with-packed-struct/Makefile @@ -1,7 +1,5 @@ -include ../tools.mk -all: - $(CC) -std=c99 test.c -c -o $(TMPDIR)/test.o - $(AR) rcs $(TMPDIR)/libtest.a $(TMPDIR)/test.o - $(RUSTC) test.rs -L $(TMPDIR) +all: $(call NATIVE_STATICLIB,test) + $(RUSTC) test.rs $(call RUN,test) || exit 1 diff --git a/src/test/run-make/extern-fn-with-packed-struct/test.c b/src/test/run-make/extern-fn-with-packed-struct/test.c index 121e48e84e46f..506954fca4617 100644 --- a/src/test/run-make/extern-fn-with-packed-struct/test.c +++ b/src/test/run-make/extern-fn-with-packed-struct/test.c @@ -1,11 +1,21 @@ // ignore-license // Pragma needed cause of gcc bug on windows: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52991 + +#ifdef _MSC_VER +#pragma pack(push,1) +struct Foo { + char a; + short b; + char c; +}; +#else #pragma pack(1) struct __attribute__((packed)) Foo { char a; short b; char c; }; +#endif struct Foo foo(struct Foo foo) { return foo; diff --git a/src/test/run-make/extern-fn-with-union/Makefile b/src/test/run-make/extern-fn-with-union/Makefile index a325acbf687b5..cf897dba1f279 100644 --- a/src/test/run-make/extern-fn-with-union/Makefile +++ b/src/test/run-make/extern-fn-with-union/Makefile @@ -1,8 +1,6 @@ -include ../tools.mk -all: - $(CC) -std=c99 test.c -c -o $(TMPDIR)/test.o - $(AR) rcs $(TMPDIR)/libtest.a $(TMPDIR)/test.o - $(RUSTC) testcrate.rs -L $(TMPDIR) - $(RUSTC) test.rs -L $(TMPDIR) +all: $(call NATIVE_STATICLIB,test) + $(RUSTC) testcrate.rs + $(RUSTC) test.rs $(call RUN,test) || exit 1 diff --git a/src/test/run-make/interdependent-c-libraries/Makefile b/src/test/run-make/interdependent-c-libraries/Makefile index cf7683479f08e..1268022e37b74 100644 --- a/src/test/run-make/interdependent-c-libraries/Makefile +++ b/src/test/run-make/interdependent-c-libraries/Makefile @@ -8,7 +8,7 @@ # correct to complete the linkage. If passed as "-lfoo -lbar", then the 'foo' # library will be stripped out, and the linkage will fail. -all: $(call STATICLIB,foo) $(call STATICLIB,bar) +all: $(call NATIVE_STATICLIB,foo) $(call NATIVE_STATICLIB,bar) $(RUSTC) foo.rs $(RUSTC) bar.rs $(RUSTC) main.rs -Z print-link-args diff --git a/src/test/run-make/issue-12446/Makefile b/src/test/run-make/issue-12446/Makefile index e864ee0058c7e..c412b0479fb84 100644 --- a/src/test/run-make/issue-12446/Makefile +++ b/src/test/run-make/issue-12446/Makefile @@ -1,6 +1,6 @@ -include ../tools.mk -all: $(call STATICLIB,foo) +all: $(call NATIVE_STATICLIB,foo) $(RUSTC) foo.rs $(RUSTC) bar.rs $(call RUN,bar) diff --git a/src/test/run-make/issue-14500/Makefile b/src/test/run-make/issue-14500/Makefile index 6ea3cf48ffbbd..bd94db0952028 100644 --- a/src/test/run-make/issue-14500/Makefile +++ b/src/test/run-make/issue-14500/Makefile @@ -13,5 +13,5 @@ endif all: $(RUSTC) foo.rs --crate-type=rlib $(RUSTC) bar.rs --crate-type=staticlib -C lto -L. -o $(TMPDIR)/libbar.a - $(CC) foo.c -lbar -o $(call RUN_BINFILE,foo) $(EXTRACFLAGS) + $(CC) foo.c $(TMPDIR)/libbar.a $(EXTRACFLAGS) $(call OUT_EXE,foo) $(call RUN,foo) diff --git a/src/test/run-make/issue-15460/Makefile b/src/test/run-make/issue-15460/Makefile index bc5e9b728694f..846805686a12a 100644 --- a/src/test/run-make/issue-15460/Makefile +++ b/src/test/run-make/issue-15460/Makefile @@ -1,6 +1,6 @@ -include ../tools.mk -all: $(TMPDIR)/libfoo.a +all: $(call NATIVE_STATICLIB,foo) $(RUSTC) foo.rs -C extra-filename=-383hf8 -C prefer-dynamic $(RUSTC) bar.rs $(call RUN,bar) diff --git a/src/test/run-make/issue-15460/foo.c b/src/test/run-make/issue-15460/foo.c index 2895ad473bf96..fdf595b574e33 100644 --- a/src/test/run-make/issue-15460/foo.c +++ b/src/test/run-make/issue-15460/foo.c @@ -1,2 +1,6 @@ // ignore-license + +#ifdef _WIN32 +__declspec(dllexport) +#endif void foo() {} diff --git a/src/test/run-make/issue-15460/foo.rs b/src/test/run-make/issue-15460/foo.rs index 6917fa5557980..8b96fe3682471 100644 --- a/src/test/run-make/issue-15460/foo.rs +++ b/src/test/run-make/issue-15460/foo.rs @@ -8,9 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(linked_from)] #![crate_type = "dylib"] #[link(name = "foo", kind = "static")] +#[linked_from = "foo"] extern { pub fn foo(); } diff --git a/src/test/run-make/issue-25581/Makefile b/src/test/run-make/issue-25581/Makefile index ea6971853fe99..042048ec25f63 100644 --- a/src/test/run-make/issue-25581/Makefile +++ b/src/test/run-make/issue-25581/Makefile @@ -1,7 +1,5 @@ -include ../tools.mk -all: - $(CC) -std=c99 test.c -c -o $(TMPDIR)/test.o - $(AR) rcs $(TMPDIR)/libtest.a $(TMPDIR)/test.o - $(RUSTC) test.rs -L $(TMPDIR) +all: $(call NATIVE_STATICLIB,test) + $(RUSTC) test.rs $(call RUN,test) || exit 1 diff --git a/src/test/run-make/issue-26092/Makefile b/src/test/run-make/issue-26092/Makefile index 1e66e3a53804f..0d94c99a3948a 100644 --- a/src/test/run-make/issue-26092/Makefile +++ b/src/test/run-make/issue-26092/Makefile @@ -2,4 +2,4 @@ all: $(RUSTC) -o "" blank.rs 2>&1 | \ - grep 'No such file or directory' + grep -i 'No such file or directory' diff --git a/src/test/run-make/link-path-order/Makefile b/src/test/run-make/link-path-order/Makefile index 116c7ae991cf6..eeea0e3714e7f 100644 --- a/src/test/run-make/link-path-order/Makefile +++ b/src/test/run-make/link-path-order/Makefile @@ -6,10 +6,12 @@ CORRECT_DIR=$(TMPDIR)/correct WRONG_DIR=$(TMPDIR)/wrong -all: $(TMPDIR)/libcorrect.a $(TMPDIR)/libwrong.a +F := $(call NATIVE_STATICLIB_FILE,foo) + +all: $(call NATIVE_STATICLIB,correct) $(call NATIVE_STATICLIB,wrong) mkdir -p $(CORRECT_DIR) $(WRONG_DIR) - mv $(TMPDIR)/libcorrect.a $(CORRECT_DIR)/libfoo.a - mv $(TMPDIR)/libwrong.a $(WRONG_DIR)/libfoo.a + mv $(call NATIVE_STATICLIB,correct) $(CORRECT_DIR)/$(F) + mv $(call NATIVE_STATICLIB,wrong) $(WRONG_DIR)/$(F) $(RUSTC) main.rs -o $(TMPDIR)/should_succeed -L $(CORRECT_DIR) -L $(WRONG_DIR) $(call RUN,should_succeed) $(RUSTC) main.rs -o $(TMPDIR)/should_fail -L $(WRONG_DIR) -L $(CORRECT_DIR) diff --git a/src/test/run-make/linkage-attr-on-static/Makefile b/src/test/run-make/linkage-attr-on-static/Makefile index 1871a5bbdc7f6..4befbe1446542 100644 --- a/src/test/run-make/linkage-attr-on-static/Makefile +++ b/src/test/run-make/linkage-attr-on-static/Makefile @@ -1,7 +1,5 @@ -include ../tools.mk -all: - $(CC) foo.c -c -o $(TMPDIR)/foo.o - $(AR) rcs $(TMPDIR)/libfoo.a $(TMPDIR)/foo.o - $(RUSTC) bar.rs -lfoo -L $(TMPDIR) +all: $(call NATIVE_STATICLIB,foo) + $(RUSTC) bar.rs $(call RUN,bar) || exit 1 diff --git a/src/test/run-make/linkage-attr-on-static/bar.rs b/src/test/run-make/linkage-attr-on-static/bar.rs index 6125421bdeb6c..274401c448bad 100644 --- a/src/test/run-make/linkage-attr-on-static/bar.rs +++ b/src/test/run-make/linkage-attr-on-static/bar.rs @@ -14,6 +14,7 @@ #[linkage = "external"] static BAZ: i32 = 21; +#[link(name = "foo", kind = "static")] extern { fn what() -> i32; } diff --git a/src/test/run-make/lto-smoke-c/Makefile b/src/test/run-make/lto-smoke-c/Makefile index 6165afbeb222f..72c161abe9113 100644 --- a/src/test/run-make/lto-smoke-c/Makefile +++ b/src/test/run-make/lto-smoke-c/Makefile @@ -5,5 +5,7 @@ CC := $(CC:-g=) all: $(RUSTC) foo.rs -C lto - $(CC) bar.c -lfoo -o $(call RUN_BINFILE,bar) $(EXTRACFLAGS) $(EXTRACXXFLAGS) + $(CC) bar.c $(TMPDIR)/libfoo.a \ + $(call OUT_EXE,bar) \ + $(EXTRACFLAGS) $(EXTRACXXFLAGS) $(call RUN,bar) diff --git a/src/test/run-make/no-duplicate-libs/Makefile b/src/test/run-make/no-duplicate-libs/Makefile index fdb6048dc4d52..3f6a28c251a2f 100644 --- a/src/test/run-make/no-duplicate-libs/Makefile +++ b/src/test/run-make/no-duplicate-libs/Makefile @@ -1,7 +1,12 @@ -include ../tools.mk +ifdef IS_MSVC +# FIXME(#27979) +all: +else all: $(RUSTC) foo.rs $(RUSTC) bar.rs $(RUSTC) main.rs $(call RUN,main) +endif diff --git a/src/test/run-make/no-duplicate-libs/bar.c b/src/test/run-make/no-duplicate-libs/bar.c deleted file mode 100644 index a7b02a2f10b63..0000000000000 --- a/src/test/run-make/no-duplicate-libs/bar.c +++ /dev/null @@ -1,4 +0,0 @@ -// ignore-license -extern void foo(); - -void bar() { foo(); } diff --git a/src/test/run-make/no-duplicate-libs/foo.c b/src/test/run-make/no-duplicate-libs/foo.c deleted file mode 100644 index 2895ad473bf96..0000000000000 --- a/src/test/run-make/no-duplicate-libs/foo.c +++ /dev/null @@ -1,2 +0,0 @@ -// ignore-license -void foo() {} diff --git a/src/test/run-make/output-type-permutations/Makefile b/src/test/run-make/output-type-permutations/Makefile index 4efbd9ee48df2..e3c36b9c0b701 100644 --- a/src/test/run-make/output-type-permutations/Makefile +++ b/src/test/run-make/output-type-permutations/Makefile @@ -4,7 +4,8 @@ all: $(RUSTC) foo.rs --crate-type=rlib,dylib,staticlib $(call REMOVE_RLIBS,bar) $(call REMOVE_DYLIBS,bar) - rm $(TMPDIR)/$(call STATICLIB_GLOB,bar) + rm $(TMPDIR)/libbar.a + rm -f $(TMPDIR)/bar.{exp,lib} # Check that $(TMPDIR) is empty. [ "$$(ls -1 $(TMPDIR) | wc -l)" -eq "0" ] @@ -36,7 +37,7 @@ all: rm $(TMPDIR)/foo [ "$$(ls -1 $(TMPDIR) | wc -l)" -eq "0" ] - $(RUSTC) foo.rs --emit=link -o $(TMPDIR)/foo + $(RUSTC) foo.rs --emit=link -o $(TMPDIR)/$(call BIN,foo) rm $(TMPDIR)/$(call BIN,foo) [ "$$(ls -1 $(TMPDIR) | wc -l)" -eq "0" ] @@ -44,15 +45,16 @@ all: rm $(TMPDIR)/foo [ "$$(ls -1 $(TMPDIR) | wc -l)" -eq "0" ] - $(RUSTC) foo.rs --crate-type=dylib -o $(TMPDIR)/foo - rm $(TMPDIR)/$(call BIN,foo) # FIXME 13794 + $(RUSTC) foo.rs --crate-type=dylib -o $(TMPDIR)/$(call BIN,foo) + rm $(TMPDIR)/$(call BIN,foo) + rm -f $(TMPDIR)/foo.{exp,lib} [ "$$(ls -1 $(TMPDIR) | wc -l)" -eq "0" ] $(RUSTC) foo.rs --crate-type=staticlib -o $(TMPDIR)/foo rm $(TMPDIR)/foo [ "$$(ls -1 $(TMPDIR) | wc -l)" -eq "0" ] - $(RUSTC) foo.rs --crate-type=bin -o $(TMPDIR)/foo + $(RUSTC) foo.rs --crate-type=bin -o $(TMPDIR)/$(call BIN,foo) rm $(TMPDIR)/$(call BIN,foo) [ "$$(ls -1 $(TMPDIR) | wc -l)" -eq "0" ] @@ -60,7 +62,7 @@ all: rm $(TMPDIR)/bar.ll rm $(TMPDIR)/bar.s rm $(TMPDIR)/bar.o - rm $(TMPDIR)/$(call STATICLIB_GLOB,bar) + rm $(TMPDIR)/libbar.a mv $(TMPDIR)/bar.bc $(TMPDIR)/foo.bc # Don't check that the $(TMPDIR) is empty - we left `foo.bc` for later # comparison. diff --git a/src/test/run-make/relocation-model/Makefile b/src/test/run-make/relocation-model/Makefile index 2fcdd32bfcbd4..b22f34fa35b54 100644 --- a/src/test/run-make/relocation-model/Makefile +++ b/src/test/run-make/relocation-model/Makefile @@ -1,15 +1,21 @@ -include ../tools.mk -all: +all: others $(RUSTC) -C relocation-model=dynamic-no-pic foo.rs $(call RUN,foo) $(RUSTC) -C relocation-model=default foo.rs $(call RUN,foo) + $(RUSTC) -C relocation-model=default --crate-type=dylib foo.rs + $(RUSTC) -C relocation-model=dynamic-no-pic --crate-type=dylib foo.rs + +ifdef IS_MSVC +# FIXME(#28026) +others: +else +others: $(RUSTC) -C relocation-model=static foo.rs $(call RUN,foo) - - $(RUSTC) -C relocation-model=default --crate-type=dylib foo.rs $(RUSTC) -C relocation-model=static --crate-type=dylib foo.rs - $(RUSTC) -C relocation-model=dynamic-no-pic --crate-type=dylib foo.rs +endif diff --git a/src/test/run-make/static-dylib-by-default/Makefile b/src/test/run-make/static-dylib-by-default/Makefile index 1505e679af011..8bd05dc201fcf 100644 --- a/src/test/run-make/static-dylib-by-default/Makefile +++ b/src/test/run-make/static-dylib-by-default/Makefile @@ -1,9 +1,16 @@ -include ../tools.mk +TO_LINK := $(call DYLIB,bar) +ifdef IS_MSVC +LINK_ARG = $(TO_LINK:dll=lib) +else +LINK_ARG = $(TO_LINK) +endif + all: $(RUSTC) foo.rs $(RUSTC) bar.rs - $(CC) main.c -o $(call RUN_BINFILE,main) -lbar $(EXTRACFLAGS) + $(CC) main.c $(call OUT_EXE,main) $(LINK_ARG) $(EXTRACFLAGS) rm $(TMPDIR)/*.rlib rm $(call DYLIB,foo) $(call RUN,main) diff --git a/src/test/run-make/tools.mk b/src/test/run-make/tools.mk index 223296286bd89..14d8e468f50d3 100644 --- a/src/test/run-make/tools.mk +++ b/src/test/run-make/tools.mk @@ -7,7 +7,7 @@ TARGET_RPATH_ENV = \ BARE_RUSTC := $(HOST_RPATH_ENV) $(RUSTC) RUSTC := $(BARE_RUSTC) --out-dir $(TMPDIR) -L $(TMPDIR) -CC := $(CC) -L $(TMPDIR) +#CC := $(CC) -L $(TMPDIR) HTMLDOCCK := $(PYTHON) $(S)/src/etc/htmldocck.py # This is the name of the binary we will generate and run; use this @@ -19,8 +19,6 @@ RUN_BINFILE = $(TMPDIR)/$(1) # variable before running the binary. RLIB_GLOB = lib$(1)*.rlib -STATICLIB = $(TMPDIR)/lib$(1).a -STATICLIB_GLOB = lib$(1)*.a BIN = $(1) UNAME = $(shell uname) @@ -33,27 +31,48 @@ RUN = $(TARGET_RPATH_ENV) $(RUN_BINFILE) FAIL = $(TARGET_RPATH_ENV) $(RUN_BINFILE) && exit 1 || exit 0 DYLIB_GLOB = lib$(1)*.dylib DYLIB = $(TMPDIR)/lib$(1).dylib -RPATH_LINK_SEARCH = +STATICLIB = $(TMPDIR)/lib$(1).a +STATICLIB_GLOB = lib$(1)*.a else ifdef IS_WINDOWS RUN = PATH="$(PATH):$(TARGET_RPATH_DIR)" $(RUN_BINFILE) FAIL = PATH="$(PATH):$(TARGET_RPATH_DIR)" $(RUN_BINFILE) && exit 1 || exit 0 DYLIB_GLOB = $(1)*.dll DYLIB = $(TMPDIR)/$(1).dll +STATICLIB = $(TMPDIR)/$(1).lib +STATICLIB_GLOB = $(1)*.lib BIN = $(1).exe -RPATH_LINK_SEARCH = else RUN = $(TARGET_RPATH_ENV) $(RUN_BINFILE) FAIL = $(TARGET_RPATH_ENV) $(RUN_BINFILE) && exit 1 || exit 0 DYLIB_GLOB = lib$(1)*.so DYLIB = $(TMPDIR)/lib$(1).so -RPATH_LINK_SEARCH = -Wl,-rpath-link=$(1) +STATICLIB = $(TMPDIR)/lib$(1).a +STATICLIB_GLOB = lib$(1)*.a +endif endif + +ifdef IS_MSVC +COMPILE_OBJ = $(CC) -c -Fo:`cygpath -w $(1)` $(2) +NATIVE_STATICLIB_FILE = $(1).lib +NATIVE_STATICLIB = $(TMPDIR)/$(call NATIVE_STATICLIB_FILE,$(1)) +OUT_EXE=-Fe:`cygpath -w $(TMPDIR)/$(call BIN,$(1))` \ + -Fo:`cygpath -w $(TMPDIR)/$(1).obj` +else +COMPILE_OBJ = $(CC) -c -o $(1) $(2) +NATIVE_STATICLIB_FILE = lib$(1).a +NATIVE_STATICLIB = $(call STATICLIB,$(1)) +OUT_EXE=-o $(TMPDIR)/$(1) endif + # Extra flags needed to compile a working executable with the standard library ifdef IS_WINDOWS +ifdef IS_MSVC + EXTRACFLAGS := ws2_32.lib userenv.lib shell32.lib advapi32.lib +else EXTRACFLAGS := -lws2_32 -luserenv +endif else ifeq ($(UNAME),Darwin) else @@ -80,12 +99,20 @@ REMOVE_RLIBS = rm $(TMPDIR)/$(call RLIB_GLOB,$(1)) %.a: %.o ar crus $@ $< +%.lib: lib%.o + ar crus $@ $< %.dylib: %.o $(CC) -dynamiclib -Wl,-dylib -o $@ $< %.so: %.o $(CC) -o $@ $< -shared + +ifdef IS_MSVC +%.dll: lib%.o + $(CC) $< -link -dll -out:`cygpath -w $@` +else %.dll: lib%.o $(CC) -o $@ $< -shared +endif $(TMPDIR)/lib%.o: %.c - $(CC) -c -o $@ $< + $(call COMPILE_OBJ,$@,$<) diff --git a/src/test/run-pass/issue-23036.rs b/src/test/run-pass/issue-23036.rs new file mode 100644 index 0000000000000..0ed4126e6cd71 --- /dev/null +++ b/src/test/run-pass/issue-23036.rs @@ -0,0 +1,18 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::collections::HashMap; +use std::path::Path; + +fn main() { + let mut map = HashMap::new(); + map.insert(Path::new("a"), 0); + map.get(Path::new("a")); +} diff --git a/src/test/run-pass/issue-24533.rs b/src/test/run-pass/issue-24533.rs new file mode 100644 index 0000000000000..440a4184780cd --- /dev/null +++ b/src/test/run-pass/issue-24533.rs @@ -0,0 +1,32 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::slice::Iter; +use std::io::{Error, ErrorKind, Result}; +use std::vec::*; + +fn foo(it: &mut Iter) -> Result { + Ok(*it.next().unwrap()) +} + +fn bar() -> Result { + let data: Vec = Vec::new(); + + if true { + return Err(Error::new(ErrorKind::NotFound, "msg")); + } + + let mut it = data.iter(); + foo(&mut it) +} + +fn main() { + bar(); +} diff --git a/src/test/run-pass/issue-26905.rs b/src/test/run-pass/issue-26905.rs new file mode 100644 index 0000000000000..0ad193bb28c99 --- /dev/null +++ b/src/test/run-pass/issue-26905.rs @@ -0,0 +1,31 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(unsize, coerce_unsized)] + +// Verfies that PhantomData is ignored for DST coercions + +use std::marker::{Unsize, PhantomData}; +use std::ops::CoerceUnsized; + +struct MyRc { + _ptr: *const T, + _boo: PhantomData, +} + +impl, U: ?Sized> CoerceUnsized> for MyRc{ } + +fn main() { + let data = [1, 2, 3]; + let iter = data.iter(); + let x = MyRc { _ptr: &iter, _boo: PhantomData }; + let _y: MyRc> = x; +} + diff --git a/src/test/run-pass/x86stdcall2.rs b/src/test/run-pass/x86stdcall2.rs index c9742b0645e1d..f3bf5d9c6843f 100644 --- a/src/test/run-pass/x86stdcall2.rs +++ b/src/test/run-pass/x86stdcall2.rs @@ -10,7 +10,7 @@ #![feature(std_misc)] -pub type HANDLE = u32; +pub type HANDLE = usize; pub type DWORD = u32; pub type SIZE_T = u32; pub type LPVOID = usize;