From a72bd699cff26175be7156db13758d17bb88813e Mon Sep 17 00:00:00 2001 From: Daniel Raloff Date: Tue, 16 Dec 2014 00:43:57 -0800 Subject: [PATCH 01/96] added optional method chain indentations for emacs major mode --- src/etc/emacs/rust-mode.el | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/etc/emacs/rust-mode.el b/src/etc/emacs/rust-mode.el index 6917e9ee354..f66df6c0565 100644 --- a/src/etc/emacs/rust-mode.el +++ b/src/etc/emacs/rust-mode.el @@ -49,6 +49,11 @@ :type 'integer :group 'rust-mode) +(defcustom rust-indent-method-chain nil + "Indent Rust method chains, aligned by the '.' operators" + :type 'boolean + :group 'rust-mode) + (defun rust-paren-level () (nth 0 (syntax-ppss))) (defun rust-in-str-or-cmnt () (nth 8 (syntax-ppss))) (defun rust-rewind-past-str-cmnt () (goto-char (nth 8 (syntax-ppss)))) @@ -72,6 +77,15 @@ (backward-word 1)) (current-column)))) +(defun rust-align-to-method-chain () + (save-excursion + (previous-line) + (end-of-line) + (backward-word 1) + (backward-char) + (when (looking-at "\\..+\(.*\)\n") + (- (current-column) rust-indent-offset)))) + (defun rust-rewind-to-beginning-of-current-level-expr () (let ((current-level (rust-paren-level))) (back-to-indentation) @@ -94,10 +108,13 @@ ;; the inside of it correctly relative to the outside. (if (= 0 level) 0 + (or + (when rust-indent-method-chain + (rust-align-to-method-chain)) (save-excursion (backward-up-list) (rust-rewind-to-beginning-of-current-level-expr) - (+ (current-column) rust-indent-offset))))) + (+ (current-column) rust-indent-offset)))))) (cond ;; A function return type is indented to the corresponding function arguments ((looking-at "->") @@ -109,6 +126,16 @@ ;; A closing brace is 1 level unindended ((looking-at "}") (- baseline rust-indent-offset)) + ;;Line up method chains by their .'s + ((when (and rust-indent-method-chain + (looking-at "\..+\(.*\);?\n")) + (or + (let ((method-indent (rust-align-to-method-chain))) + (when method-indent + (+ method-indent rust-indent-offset))) + (+ baseline rust-indent-offset)))) + + ;; Doc comments in /** style with leading * indent to line up the *s ((and (nth 4 (syntax-ppss)) (looking-at "*")) (+ 1 baseline)) From bd621f0ccb3b6c657a056fd949ed105f77a7a01f Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Fri, 16 Jan 2015 14:57:07 -0500 Subject: [PATCH 02/96] Project region bounds out of the trait when deciding whether a projection type outlives a given region. Fixes #20890. --- src/librustc/middle/traits/fulfill.rs | 1 + src/librustc_typeck/check/regionck.rs | 94 ++++++++++++++++++- ...ssoc-type-region-bound-in-trait-not-met.rs | 31 ++++++ ...ssoc-type-static-bound-in-trait-not-met.rs | 26 +++++ .../regions-assoc-type-region-bound.rs | 28 ++++++ .../regions-assoc-type-static-bound.rs | 22 +++++ 6 files changed, 200 insertions(+), 2 deletions(-) create mode 100644 src/test/compile-fail/regions-assoc-type-region-bound-in-trait-not-met.rs create mode 100644 src/test/compile-fail/regions-assoc-type-static-bound-in-trait-not-met.rs create mode 100644 src/test/run-pass/regions-assoc-type-region-bound.rs create mode 100644 src/test/run-pass/regions-assoc-type-static-bound.rs diff --git a/src/librustc/middle/traits/fulfill.rs b/src/librustc/middle/traits/fulfill.rs index c3b9be85eb5..5c9face66e1 100644 --- a/src/librustc/middle/traits/fulfill.rs +++ b/src/librustc/middle/traits/fulfill.rs @@ -84,6 +84,7 @@ pub struct FulfillmentContext<'tcx> { region_obligations: NodeMap>>, } +#[derive(Clone)] pub struct RegionObligation<'tcx> { pub sub_region: ty::Region, pub sup_type: Ty<'tcx>, diff --git a/src/librustc_typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs index 3b5027dbb9e..6403c1af8e1 100644 --- a/src/librustc_typeck/check/regionck.rs +++ b/src/librustc_typeck/check/regionck.rs @@ -297,14 +297,25 @@ fn visit_fn_body(&mut self, fn visit_region_obligations(&mut self, node_id: ast::NodeId) { debug!("visit_region_obligations: node_id={}", node_id); - let fulfillment_cx = self.fcx.inh.fulfillment_cx.borrow(); - for r_o in fulfillment_cx.region_obligations(node_id).iter() { + + // Make a copy of the region obligations vec because we'll need + // to be able to borrow the fulfillment-cx below when projecting. + let region_obligations = + self.fcx.inh.fulfillment_cx.borrow() + .region_obligations(node_id) + .to_vec(); + + for r_o in region_obligations.iter() { debug!("visit_region_obligations: r_o={}", r_o.repr(self.tcx())); let sup_type = self.resolve_type(r_o.sup_type); let origin = infer::RelateRegionParamBound(r_o.cause.span); type_must_outlive(self, origin, sup_type, r_o.sub_region); } + + // Processing the region obligations should not cause the list to grow further: + assert_eq!(region_obligations.len(), + self.fcx.inh.fulfillment_cx.borrow().region_obligations(node_id).len()); } /// This method populates the region map's `free_region_map`. It walks over the transformed @@ -1480,6 +1491,15 @@ fn generic_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>, generic.to_ty(rcx.tcx()), param_env.caller_bounds.predicates.as_slice().to_vec()); + // In the case of a projection T::Foo, we may be able to extract bounds from the trait def: + match *generic { + GenericKind::Param(..) => { } + GenericKind::Projection(ref projection_ty) => { + param_bounds.push_all( + &projection_bounds(rcx, origin.span(), projection_ty)[]); + } + } + // Add in the default bound of fn body that applies to all in // scope type parameters: param_bounds.push(param_env.implicit_region_bound); @@ -1511,3 +1531,73 @@ fn generic_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>, region, param_bounds); } + +fn projection_bounds<'a,'tcx>(rcx: &Rcx<'a, 'tcx>, + span: Span, + projection_ty: &ty::ProjectionTy<'tcx>) + -> Vec +{ + let fcx = rcx.fcx; + let tcx = fcx.tcx(); + let infcx = fcx.infcx(); + + debug!("projection_bounds(projection_ty={})", + projection_ty.repr(tcx)); + + let ty = ty::mk_projection(tcx, projection_ty.trait_ref.clone(), projection_ty.item_name); + + // Say we have a projection `>::SomeType`. We are interested + // in looking for a trait definition like: + // + // ``` + // trait SomeTrait<'a> { + // type SomeType : 'a; + // } + // ``` + // + // we can thus deduce that `>::SomeType : 'a`. + let trait_def = ty::lookup_trait_def(tcx, projection_ty.trait_ref.def_id); + let predicates = trait_def.generics.predicates.as_slice().to_vec(); + traits::elaborate_predicates(tcx, predicates) + .filter_map(|predicate| { + // we're only interesting in `T : 'a` style predicates: + let outlives = match predicate { + ty::Predicate::TypeOutlives(data) => data, + _ => { return None; } + }; + + debug!("projection_bounds: outlives={} (1)", + outlives.repr(tcx)); + + // apply the substitutions (and normalize any projected types) + let outlives = fcx.instantiate_type_scheme(span, + projection_ty.trait_ref.substs, + &outlives); + + debug!("projection_bounds: outlives={} (2)", + outlives.repr(tcx)); + + let region_result = infcx.try(|_| { + let (outlives, _) = + infcx.replace_late_bound_regions_with_fresh_var( + span, + infer::AssocTypeProjection(projection_ty.item_name), + &outlives); + + debug!("projection_bounds: outlives={} (3)", + outlives.repr(tcx)); + + // check whether this predicate applies to our current projection + match infer::mk_eqty(infcx, false, infer::Misc(span), ty, outlives.0) { + Ok(()) => { Ok(outlives.1) } + Err(_) => { Err(()) } + } + }); + + debug!("projection_bounds: region_result={}", + region_result.repr(tcx)); + + region_result.ok() + }) + .collect() +} diff --git a/src/test/compile-fail/regions-assoc-type-region-bound-in-trait-not-met.rs b/src/test/compile-fail/regions-assoc-type-region-bound-in-trait-not-met.rs new file mode 100644 index 00000000000..f833361e3b5 --- /dev/null +++ b/src/test/compile-fail/regions-assoc-type-region-bound-in-trait-not-met.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. + +// Test that the compiler checks that arbitrary region bounds declared +// in the trait must be satisfied on the impl. Issue #20890. + +trait Foo<'a> { type Value: 'a; } + +impl<'a> Foo<'a> for &'a i16 { + // OK. + type Value = &'a i32; +} + +impl<'a> Foo<'static> for &'a i32 { + //~^ ERROR cannot infer + type Value = &'a i32; +} + +impl<'a,'b> Foo<'b> for &'a i64 { + //~^ ERROR cannot infer + type Value = &'a i32; +} + +fn main() { } diff --git a/src/test/compile-fail/regions-assoc-type-static-bound-in-trait-not-met.rs b/src/test/compile-fail/regions-assoc-type-static-bound-in-trait-not-met.rs new file mode 100644 index 00000000000..0871d8b01f6 --- /dev/null +++ b/src/test/compile-fail/regions-assoc-type-static-bound-in-trait-not-met.rs @@ -0,0 +1,26 @@ +// 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. + +// Test that the compiler checks that the 'static bound declared in +// the trait must be satisfied on the impl. Issue #20890. + +trait Foo { type Value: 'static; } + +impl<'a> Foo for &'a i32 { + //~^ ERROR cannot infer + type Value = &'a i32; +} + +impl<'a> Foo for i32 { + // OK. + type Value = i32; +} + +fn main() { } diff --git a/src/test/run-pass/regions-assoc-type-region-bound.rs b/src/test/run-pass/regions-assoc-type-region-bound.rs new file mode 100644 index 00000000000..77e1a214764 --- /dev/null +++ b/src/test/run-pass/regions-assoc-type-region-bound.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. + +// Test that the compiler considers the 'a bound declared in the +// trait. Issue #20890. + +trait Foo<'a> { + type Value: 'a; + + fn get(&self) -> &'a Self::Value; +} + +fn takes_foo<'a,F: Foo<'a>>(f: &'a F) { + // This call would be illegal, because it results in &'a F::Value, + // and the only way we know that `F::Value : 'a` is because of the + // trait declaration. + + f.get(); +} + +fn main() { } diff --git a/src/test/run-pass/regions-assoc-type-static-bound.rs b/src/test/run-pass/regions-assoc-type-static-bound.rs new file mode 100644 index 00000000000..6b629a9035d --- /dev/null +++ b/src/test/run-pass/regions-assoc-type-static-bound.rs @@ -0,0 +1,22 @@ +// 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. + +// Test that the compiler considers the 'static bound declared in the +// trait. Issue #20890. + +trait Foo { type Value: 'static; } + +fn require_static() {} + +fn takes_foo() { + require_static::() +} + +fn main() { } From b7ef34d0982ee28797fff346de899ea40de718b8 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Fri, 16 Jan 2015 15:27:26 -0500 Subject: [PATCH 03/96] Add regression test for #20971. Fixes #20791. --- src/test/run-pass/issue-20971.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/test/run-pass/issue-20971.rs diff --git a/src/test/run-pass/issue-20971.rs b/src/test/run-pass/issue-20971.rs new file mode 100644 index 00000000000..e854cce4446 --- /dev/null +++ b/src/test/run-pass/issue-20971.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. + +// Regression test for Issue #20971. + +pub trait Parser { + type Input; + fn parse(&mut self, input: ::Input); +} + +impl Parser for () { + type Input = (); + fn parse(&mut self, input: ()) { + + } +} + +pub fn many() -> Box::Input> + 'static> { + panic!() +} + +fn main() { + many() + .parse(()); +} From 1138579bf4783deda4115683277a4e95d0c2f12b Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Fri, 16 Jan 2015 17:19:41 -0500 Subject: [PATCH 04/96] Add regression test for #20797. Fixes #20797. --- src/test/run-pass/issue-20797.rs | 91 ++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 src/test/run-pass/issue-20797.rs diff --git a/src/test/run-pass/issue-20797.rs b/src/test/run-pass/issue-20797.rs new file mode 100644 index 00000000000..c4f3c33f269 --- /dev/null +++ b/src/test/run-pass/issue-20797.rs @@ -0,0 +1,91 @@ +// 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. + +// Regression test for #20797. + +use std::default::Default; +use std::io::IoResult; +use std::io::fs; +use std::io::fs::PathExtensions; + +/// A strategy for acquiring more subpaths to walk. +pub trait Strategy { + type P: PathExtensions; + /// Get additional subpaths from a given path. + fn get_more(&self, item: &Self::P) -> IoResult>; + /// Determine whether a path should be walked further. + /// This is run against each item from `get_more()`. + fn prune(&self, p: &Self::P) -> bool; +} + +/// The basic fully-recursive strategy. Nothing is pruned. +#[derive(Copy, Default)] +pub struct Recursive; + +impl Strategy for Recursive { + type P = Path; + fn get_more(&self, p: &Path) -> IoResult> { fs::readdir(p) } + + fn prune(&self, _: &Path) -> bool { false } +} + +/// A directory walker of `P` using strategy `S`. +pub struct Subpaths { + stack: Vec, + strategy: S, +} + +impl Subpaths { + /// Create a directory walker with a root path and strategy. + pub fn new(p: &S::P, strategy: S) -> IoResult> { + let stack = try!(strategy.get_more(p)); + Ok(Subpaths { stack: stack, strategy: strategy }) + } +} + +impl Subpaths { + /// Create a directory walker with a root path and a default strategy. + pub fn walk(p: &S::P) -> IoResult> { + Subpaths::new(p, Default::default()) + } +} + +impl Default for Subpaths { + fn default() -> Subpaths { + Subpaths { stack: Vec::new(), strategy: Default::default() } + } +} + +impl Iterator for Subpaths { + type Item = S::P; + fn next (&mut self) -> Option { + let mut opt_path = self.stack.pop(); + while opt_path.is_some() && self.strategy.prune(opt_path.as_ref().unwrap()) { + opt_path = self.stack.pop(); + } + match opt_path { + Some(path) => { + if PathExtensions::is_dir(&path) { + let result = self.strategy.get_more(&path); + match result { + Ok(dirs) => { self.stack.extend(dirs.into_iter()); }, + Err(..) => { } + } + } + Some(path) + } + None => None, + } + } +} + +fn main() { + let mut walker: Subpaths = Subpaths::walk(&Path::new("/home")).unwrap(); +} From fe0868b89b27e190562e9ae3d504693c902eace0 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Fri, 16 Jan 2015 17:22:28 -0500 Subject: [PATCH 05/96] Add regression tests for #20763. Fixes #20763. --- src/test/run-pass/issue-20763-1.rs | 32 ++++++++++++++++++++++++++++++ src/test/run-pass/issue-20763-2.rs | 27 +++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 src/test/run-pass/issue-20763-1.rs create mode 100644 src/test/run-pass/issue-20763-2.rs diff --git a/src/test/run-pass/issue-20763-1.rs b/src/test/run-pass/issue-20763-1.rs new file mode 100644 index 00000000000..911ee715da2 --- /dev/null +++ b/src/test/run-pass/issue-20763-1.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. + +trait T0 { type O; } + +struct S(A); +impl T0 for S { type O = A; } + +trait T1: T0 { + // this looks okay but as we see below, `f` is unusable + fn m0::O) -> bool>(self, f: F) -> bool; +} + +// complains about the bounds on F here not being required by the trait +impl T1 for S { + fn m0 bool>(self, f: F) -> bool { f(self.0) } +} + +// // complains about mismatched types: as T0>::O vs. A +// impl T1 for S +// { +// fn m0::O) -> bool>(self, f: F) -> bool { f(self.0) } +// } + +fn main() { } diff --git a/src/test/run-pass/issue-20763-2.rs b/src/test/run-pass/issue-20763-2.rs new file mode 100644 index 00000000000..a17c7b6ade4 --- /dev/null +++ b/src/test/run-pass/issue-20763-2.rs @@ -0,0 +1,27 @@ +// 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 T0 { type O; } + +struct S(A); +impl T0 for S { type O = A; } + +trait T1: T0 { + // this looks okay but as we see below, `f` is unusable + fn m0::O) -> bool>(self, f: F) -> bool; +} + +// complains about mismatched types: as T0>::O vs. A +impl T1 for S +{ + fn m0::O) -> bool>(self, f: F) -> bool { f(self.0) } +} + +fn main() { } From 785176b7ccc3f6acdf18496473ec5f2345897067 Mon Sep 17 00:00:00 2001 From: Michael Pankov Date: Thu, 15 Jan 2015 16:45:59 +0300 Subject: [PATCH 06/96] rustup: Don't attempt to download SHA if it exists This way installer can work fully in offline mode. Put pre-downloaded files (rust-nightly-x86_64-unknown-linux-gnu.tar.gz and rust-nightly-x86_64-unknown-linux-gnu.tar.gz.sha256) into the $HOME/.rustup/YYYY-MM-DD directory as it would be done by script itself. Specify --save and --date=YYYY-MM-DD when running. Files will be picked up and used to install in offline mode. --- src/etc/rustup.sh | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/etc/rustup.sh b/src/etc/rustup.sh index 749d9eaa173..5a34770b88e 100755 --- a/src/etc/rustup.sh +++ b/src/etc/rustup.sh @@ -453,16 +453,33 @@ then RUST_URL="${RUST_URL}/${CFG_DATE}" fi -verify_hash() { - remote_sha256="$1" - local_file="$2" - +download_hash() { msg "Downloading ${remote_sha256}" remote_sha256=`"${CFG_CURL}" -f "${remote_sha256}"` + if [ -n "${CFG_SAVE}" ]; then + echo "${remote_sha256}" > "${local_sha_file}" + fi if [ "$?" -ne 0 ]; then rm -Rf "${CFG_TMP_DIR}" err "Failed to download ${remote_url}" fi +} + +verify_hash() { + remote_sha256="$1" + local_file="$2" + local_sha_file="${local_file}.sha256" + + if [ -n "${CFG_SAVE}" ]; then + if [ -f "${local_sha_file}" ]; then + msg "Local ${local_sha_file} exists, treating as remote hash" + remote_sha256=`cat "${local_sha_file}"` + else + download_hash + fi + else + download_hash + fi msg "Verifying hash" local_sha256=$(calculate_hash "${local_file}") From a32249d4477f449646162bbad607c39d0ad7f3ca Mon Sep 17 00:00:00 2001 From: Paul Collier Date: Sat, 17 Jan 2015 23:33:05 +0000 Subject: [PATCH 07/96] libsyntax: uint types to usize --- src/libsyntax/abi.rs | 4 +- src/libsyntax/ast.rs | 28 +++++++------- src/libsyntax/ast_map/mod.rs | 12 +++--- src/libsyntax/ast_util.rs | 6 +-- src/libsyntax/attr.rs | 2 +- src/libsyntax/codemap.rs | 34 ++++++++--------- src/libsyntax/diagnostic.rs | 6 +-- src/libsyntax/ext/base.rs | 2 +- src/libsyntax/ext/build.rs | 8 ++-- src/libsyntax/ext/deriving/decodable.rs | 4 +- src/libsyntax/ext/deriving/encodable.rs | 2 +- src/libsyntax/ext/deriving/generic/mod.rs | 6 +-- src/libsyntax/ext/expand.rs | 6 +-- src/libsyntax/ext/format.rs | 8 ++-- src/libsyntax/ext/mtwt.rs | 8 ++-- src/libsyntax/ext/tt/macro_parser.rs | 18 ++++----- src/libsyntax/ext/tt/transcribe.rs | 8 ++-- src/libsyntax/fold.rs | 4 +- src/libsyntax/parse/lexer/comments.rs | 8 ++-- src/libsyntax/parse/lexer/mod.rs | 10 ++--- src/libsyntax/parse/mod.rs | 26 ++++++------- src/libsyntax/parse/obsolete.rs | 2 +- src/libsyntax/parse/parser.rs | 22 +++++------ src/libsyntax/parse/token.rs | 6 +-- src/libsyntax/print/pp.rs | 46 +++++++++++------------ src/libsyntax/print/pprust.rs | 28 +++++++------- src/libsyntax/util/interner.rs | 6 +-- src/libsyntax/util/parser_testing.rs | 4 +- src/libsyntax/util/small_vector.rs | 6 +-- 29 files changed, 165 insertions(+), 165 deletions(-) diff --git a/src/libsyntax/abi.rs b/src/libsyntax/abi.rs index 09235ee209c..72b9d4d1e63 100644 --- a/src/libsyntax/abi.rs +++ b/src/libsyntax/abi.rs @@ -105,8 +105,8 @@ pub fn all_names() -> Vec<&'static str> { impl Abi { #[inline] - pub fn index(&self) -> uint { - *self as uint + pub fn index(&self) -> usize { + *self as usize } #[inline] diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 0ea429116b0..81ce521f68c 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -152,7 +152,7 @@ fn ne(&self, other: &Ident) -> bool { /// A SyntaxContext represents a chain of macro-expandings /// and renamings. Each macro expansion corresponds to -/// a fresh uint +/// a fresh usize // I'm representing this syntax context as an index into // a table, in order to work around a compiler bug @@ -181,9 +181,9 @@ pub fn as_str<'a>(&'a self) -> &'a str { } } - pub fn uint(&self) -> uint { + pub fn uint(&self) -> usize { let Name(nm) = *self; - nm as uint + nm as usize } pub fn ident(&self) -> Ident { @@ -740,7 +740,7 @@ pub enum Expr_ { ExprAssign(P, P), ExprAssignOp(BinOp, P, P), ExprField(P, SpannedIdent), - ExprTupField(P, Spanned), + ExprTupField(P, Spanned), ExprIndex(P, P), ExprRange(Option>, Option>), @@ -839,7 +839,7 @@ pub struct SequenceRepetition { /// Whether the sequence can be repeated zero (*), or one or more times (+) pub op: KleeneOp, /// The number of `MatchNt`s that appear in the sequence (and subsequences) - pub num_captures: uint, + pub num_captures: usize, } /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star) @@ -878,7 +878,7 @@ pub enum TokenTree { } impl TokenTree { - pub fn len(&self) -> uint { + pub fn len(&self) -> usize { match *self { TtToken(_, token::DocComment(_)) => 2, TtToken(_, token::SpecialVarNt(..)) => 2, @@ -893,7 +893,7 @@ pub fn len(&self) -> uint { } } - pub fn get_tt(&self, index: uint) -> TokenTree { + pub fn get_tt(&self, index: usize) -> TokenTree { match (self, index) { (&TtToken(sp, token::DocComment(_)), 0) => { TtToken(sp, token::Pound) @@ -963,7 +963,7 @@ pub enum Mac_ { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)] pub enum StrStyle { CookedStr, - RawStr(uint) + RawStr(usize) } pub type Lit = Spanned; @@ -992,7 +992,7 @@ pub enum LitIntType { } impl LitIntType { - pub fn suffix_len(&self) -> uint { + pub fn suffix_len(&self) -> usize { match *self { UnsuffixedIntLit(_) => 0, SignedIntLit(s, _) => s.suffix_len(), @@ -1113,7 +1113,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } impl IntTy { - pub fn suffix_len(&self) -> uint { + pub fn suffix_len(&self) -> usize { match *self { TyIs(true) /* i */ => 1, TyIs(false) /* is */ | TyI8 => 2, @@ -1146,7 +1146,7 @@ fn eq(&self, other: &UintTy) -> bool { } impl UintTy { - pub fn suffix_len(&self) -> uint { + pub fn suffix_len(&self) -> usize { match *self { TyUs(true) /* u */ => 1, TyUs(false) /* us */ | TyU8 => 2, @@ -1186,7 +1186,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } impl FloatTy { - pub fn suffix_len(&self) -> uint { + pub fn suffix_len(&self) -> usize { match *self { TyF32 | TyF64 => 3, // add F128 handling here } @@ -1274,7 +1274,7 @@ pub enum Ty_ { TyPtr(MutTy), /// A reference (`&'a T` or `&'a mut T`) TyRptr(Option, MutTy), - /// A bare function (e.g. `fn(uint) -> bool`) + /// A bare function (e.g. `fn(usize) -> bool`) TyBareFn(P), /// A tuple (`(A, B, C, D,...)`) TyTup(Vec> ), @@ -1566,7 +1566,7 @@ pub enum AttrStyle { } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)] -pub struct AttrId(pub uint); +pub struct AttrId(pub usize); /// Doc-comments are promoted to attributes that have is_sugared_doc = true #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index f462a730d3a..d57a1356def 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -264,12 +264,12 @@ pub struct Map<'ast> { } impl<'ast> Map<'ast> { - fn entry_count(&self) -> uint { + fn entry_count(&self) -> usize { self.map.borrow().len() } fn find_entry(&self, id: NodeId) -> Option> { - self.map.borrow().get(id as uint).map(|e| *e) + self.map.borrow().get(id as usize).map(|e| *e) } pub fn krate(&self) -> &'ast Crate { @@ -652,7 +652,7 @@ impl<'a, 'ast> Iterator for NodesMatchingSuffix<'a, 'ast> { fn next(&mut self) -> Option { loop { let idx = self.idx; - if idx as uint >= self.map.entry_count() { + if idx as usize >= self.map.entry_count() { return None; } self.idx += 1; @@ -744,10 +744,10 @@ impl<'ast> NodeCollector<'ast> { fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) { debug!("ast_map: {:?} => {:?}", id, entry); let len = self.map.len(); - if id as uint >= len { - self.map.extend(repeat(NotPresent).take(id as uint - len + 1)); + if id as usize >= len { + self.map.extend(repeat(NotPresent).take(id as usize - len + 1)); } - self.map[id as uint] = entry; + self.map[id as usize] = entry; } fn insert(&mut self, id: NodeId, node: Node<'ast>) { diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index bc7fbd46fd8..73f84f4fbe7 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -156,7 +156,7 @@ pub fn int_ty_max(t: IntTy) -> u64 { } /// Get a string representation of an unsigned int type, with its value. -/// We want to avoid "42uint" in favor of "42u" +/// 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(true) if val.is_some() => "u", @@ -319,7 +319,7 @@ pub fn struct_field_visibility(field: ast::StructField) -> Visibility { } /// Maps a binary operator to its precedence -pub fn operator_prec(op: ast::BinOp) -> uint { +pub fn operator_prec(op: ast::BinOp) -> usize { match op { // 'as' sits here with 12 BiMul | BiDiv | BiRem => 11u, @@ -337,7 +337,7 @@ pub fn operator_prec(op: ast::BinOp) -> uint { /// Precedence of the `as` operator, which is a binary operator /// not appearing in the prior table. #[allow(non_upper_case_globals)] -pub static as_prec: uint = 12u; +pub static as_prec: usize = 12us; pub fn empty_generics() -> Generics { Generics { diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 6f57c06d33e..8f58b7694b6 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -170,7 +170,7 @@ pub fn mk_word_item(name: InternedString) -> P { P(dummy_spanned(MetaWord(name))) } -thread_local! { static NEXT_ATTR_ID: Cell = Cell::new(0) } +thread_local! { static NEXT_ATTR_ID: Cell = Cell::new(0) } pub fn mk_attr_id() -> AttrId { let id = NEXT_ATTR_ID.with(|slot| { diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index bf26687deed..6b9dda88a36 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -30,8 +30,8 @@ use serialize::{Encodable, Decodable, Encoder, Decoder}; pub trait Pos { - fn from_uint(n: uint) -> Self; - fn to_uint(&self) -> uint; + fn from_uint(n: usize) -> Self; + fn to_uint(&self) -> usize; } /// A byte offset. Keep this small (currently 32-bits), as AST contains @@ -43,14 +43,14 @@ pub trait Pos { /// is not equivalent to a character offset. The CodeMap will convert BytePos /// values to CharPos values as necessary. #[derive(Copy, PartialEq, Hash, PartialOrd, Show)] -pub struct CharPos(pub uint); +pub struct CharPos(pub usize); // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix // have been unsuccessful impl Pos for BytePos { - fn from_uint(n: uint) -> BytePos { BytePos(n as u32) } - fn to_uint(&self) -> uint { let BytePos(n) = *self; n as uint } + fn from_uint(n: usize) -> BytePos { BytePos(n as u32) } + fn to_uint(&self) -> usize { let BytePos(n) = *self; n as usize } } impl Add for BytePos { @@ -70,8 +70,8 @@ fn sub(self, rhs: BytePos) -> BytePos { } impl Pos for CharPos { - fn from_uint(n: uint) -> CharPos { CharPos(n) } - fn to_uint(&self) -> uint { let CharPos(n) = *self; n } + fn from_uint(n: usize) -> CharPos { CharPos(n) } + fn to_uint(&self) -> usize { let CharPos(n) = *self; n } } impl Add for CharPos { @@ -173,7 +173,7 @@ pub struct Loc { /// Information about the original source pub file: Rc, /// The (1-based) line number - pub line: uint, + pub line: usize, /// The (0-based) column offset pub col: CharPos } @@ -183,13 +183,13 @@ pub struct Loc { // perhaps they should just be removed. pub struct LocWithOpt { pub filename: FileName, - pub line: uint, + pub line: usize, pub col: CharPos, pub file: Option>, } // used to be structural records. Better names, anyone? -pub struct FileMapAndLine { pub fm: Rc, pub line: uint } +pub struct FileMapAndLine { pub fm: Rc, pub line: usize } pub struct FileMapAndBytePos { pub fm: Rc, pub pos: BytePos } /// The syntax with which a macro was invoked. @@ -258,7 +258,7 @@ pub fn to_llvm_cookie(self) -> i32 { pub struct FileLines { pub file: Rc, - pub lines: Vec + pub lines: Vec } /// Identifies an offset of a multi-byte character in a FileMap @@ -267,7 +267,7 @@ pub struct MultiByteChar { /// The absolute offset of the character in the CodeMap pub pos: BytePos, /// The number of bytes, >=2 - pub bytes: uint, + pub bytes: usize, } /// A single source in the CodeMap @@ -306,7 +306,7 @@ pub fn next_line(&self, pos: BytePos) { /// get a line from the list of pre-computed line-beginnings /// - pub fn get_line(&self, line_number: uint) -> Option { + pub fn get_line(&self, line_number: usize) -> Option { let lines = self.lines.borrow(); lines.get(line_number).map(|&line| { let begin: BytePos = line - self.start_pos; @@ -319,7 +319,7 @@ pub fn get_line(&self, line_number: uint) -> Option { }) } - pub fn record_multibyte_char(&self, pos: BytePos, bytes: uint) { + pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) { assert!(bytes >=2 && bytes <= 4); let mbc = MultiByteChar { pos: pos, @@ -430,7 +430,7 @@ pub fn span_to_lines(&self, sp: Span) -> FileLines { let lo = self.lookup_char_pos(sp.lo); let hi = self.lookup_char_pos(sp.hi); let mut lines = Vec::new(); - for i in range(lo.line - 1u, hi.line as uint) { + for i in range(lo.line - 1u, hi.line as usize) { lines.push(i); }; FileLines {file: lo.file, lines: lines} @@ -494,7 +494,7 @@ pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { CharPos(bpos.to_uint() - map.start_pos.to_uint() - total_extra_bytes) } - fn lookup_filemap_idx(&self, pos: BytePos) -> uint { + fn lookup_filemap_idx(&self, pos: BytePos) -> usize { let files = self.files.borrow(); let files = &*files; let len = files.len(); @@ -579,7 +579,7 @@ pub fn with_expn_info(&self, id: ExpnId, f: F) -> T where { match id { NO_EXPANSION => f(None), - ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as uint])) + ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as usize])) } } diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 7213b0fa955..9c8ea7d9d68 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -26,7 +26,7 @@ use term; /// maximum number of lines we will print for each error; arbitrary. -static MAX_LINES: uint = 6u; +static MAX_LINES: usize = 6u; #[derive(Clone, Copy)] pub enum RenderSpan { @@ -137,7 +137,7 @@ pub fn handler<'a>(&'a self) -> &'a Handler { /// (fatal, bug, unimpl) may cause immediate exit, /// others log errors for later reporting. pub struct Handler { - err_count: Cell, + err_count: Cell, emit: RefCell>, } @@ -153,7 +153,7 @@ pub fn err(&self, msg: &str) { pub fn bump_err_count(&self) { self.err_count.set(self.err_count.get() + 1u); } - pub fn err_count(&self) -> uint { + pub fn err_count(&self) -> usize { self.err_count.get() } pub fn has_errors(&self) -> bool { diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index f2498abfa6a..9128bc05f6f 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -548,7 +548,7 @@ pub struct ExtCtxt<'a> { pub exported_macros: Vec, pub syntax_env: SyntaxEnv, - pub recursion_count: uint, + pub recursion_count: usize, } impl<'a> ExtCtxt<'a> { diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index c34142aec39..d960186cdd8 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -116,7 +116,7 @@ fn expr_binary(&self, sp: Span, op: ast::BinOp, fn expr_mut_addr_of(&self, sp: Span, e: P) -> P; fn expr_field_access(&self, span: Span, expr: P, ident: ast::Ident) -> P; fn expr_tup_field_access(&self, sp: Span, expr: P, - idx: uint) -> P; + idx: usize) -> P; fn expr_call(&self, span: Span, expr: P, args: Vec>) -> P; fn expr_call_ident(&self, span: Span, id: ast::Ident, args: Vec>) -> P; fn expr_call_global(&self, sp: Span, fn_path: Vec, @@ -134,7 +134,7 @@ fn expr_struct_ident(&self, span: Span, id: ast::Ident, fn expr_lit(&self, sp: Span, lit: ast::Lit_) -> P; - fn expr_uint(&self, span: Span, i: uint) -> P; + fn expr_uint(&self, span: Span, i: usize) -> P; fn expr_int(&self, sp: Span, i: int) -> P; fn expr_u8(&self, sp: Span, u: u8) -> P; fn expr_bool(&self, sp: Span, value: bool) -> P; @@ -587,7 +587,7 @@ fn expr_field_access(&self, sp: Span, expr: P, ident: ast::Ident) -> let id = Spanned { node: ident, span: field_span }; self.expr(sp, ast::ExprField(expr, id)) } - fn expr_tup_field_access(&self, sp: Span, expr: P, idx: uint) -> P { + fn expr_tup_field_access(&self, sp: Span, expr: P, idx: usize) -> P { let field_span = Span { lo: sp.lo - Pos::from_uint(idx.to_string().len()), hi: sp.hi, @@ -641,7 +641,7 @@ fn expr_struct_ident(&self, span: Span, fn expr_lit(&self, sp: Span, lit: ast::Lit_) -> P { self.expr(sp, ast::ExprLit(P(respan(sp, lit)))) } - fn expr_uint(&self, span: Span, i: uint) -> P { + fn expr_uint(&self, span: Span, i: usize) -> P { self.expr_lit(span, ast::LitInt(i as u64, ast::UnsignedIntLit(ast::TyUs(false)))) } fn expr_int(&self, sp: Span, i: int) -> P { diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index f73023ddd1e..6a41874b935 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -179,14 +179,14 @@ fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span, /// Create a decoder for a single enum variant/struct: /// - `outer_pat_path` is the path to this enum variant/struct -/// - `getarg` should retrieve the `uint`-th field with name `@str`. +/// - `getarg` should retrieve the `usize`-th field with name `@str`. fn decode_static_fields(cx: &mut ExtCtxt, trait_span: Span, outer_pat_path: ast::Path, fields: &StaticFields, mut getarg: F) -> P where - F: FnMut(&mut ExtCtxt, Span, InternedString, uint) -> P, + F: FnMut(&mut ExtCtxt, Span, InternedString, usize) -> P, { match *fields { Unnamed(ref fields) => { diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index 616390467f0..496aec556f1 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -16,7 +16,7 @@ //! //! ```ignore //! #[derive(Encodable, Decodable)] -//! struct Node { id: uint } +//! struct Node { id: usize } //! ``` //! //! would generate two implementations like: diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index 161b27d7abb..27199de0ea8 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -294,7 +294,7 @@ pub enum SubstructureFields<'a> { /// Matching variants of the enum: variant index, ast::Variant, /// fields: the field name is only non-`None` in the case of a struct /// variant. - EnumMatching(uint, &'a ast::Variant, Vec), + EnumMatching(usize, &'a ast::Variant, Vec), /// Non-matching variants of the enum, but with all state hidden from /// the consequent code. The first component holds `Ident`s for all of @@ -915,7 +915,7 @@ fn build_enum_match_tuple( .collect::>(); // The `vi_idents` will be bound, solely in the catch-all, to - // a series of let statements mapping each self_arg to a uint + // a series of let statements mapping each self_arg to a usize // corresponding to its variant index. let vi_idents: Vec = self_arg_names.iter() .map(|name| { let vi_suffix = format!("{}_vi", &name[]); @@ -1039,7 +1039,7 @@ fn build_enum_match_tuple( }).collect(); // Build a series of let statements mapping each self_arg - // to a uint corresponding to its variant index. + // to a usize corresponding to its variant index. // i.e. for `enum E { A, B(1), C(T, T) }`, and a deriving // with three Self args, builds three statements: // diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index c95bdeefd45..1fd0334c016 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -1311,7 +1311,7 @@ fn new_span(cx: &ExtCtxt, sp: Span) -> Span { pub struct ExpansionConfig { pub crate_name: String, pub enable_quotes: bool, - pub recursion_limit: uint, + pub recursion_limit: usize, } impl ExpansionConfig { @@ -1595,7 +1595,7 @@ fn crate_bindings(the_crate : &ast::Crate) -> Vec { // in principle, you might want to control this boolean on a per-varref basis, // but that would make things even harder to understand, and might not be // necessary for thorough testing. - type RenamingTest = (&'static str, Vec>, bool); + type RenamingTest = (&'static str, Vec>, bool); #[test] fn automatic_renaming () { @@ -1749,7 +1749,7 @@ macro_rules! iterator_impl { } // run one of the renaming tests - fn run_renaming_test(t: &RenamingTest, test_idx: uint) { + fn run_renaming_test(t: &RenamingTest, test_idx: usize) { let invalid_name = token::special_idents::invalid.name; let (teststr, bound_connections, bound_ident_check) = match *t { (ref str,ref conns, bic) => (str.to_string(), conns.clone(), bic) diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index f512b33f024..684ae84872b 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -31,7 +31,7 @@ enum ArgumentType { } enum Position { - Exact(uint), + Exact(usize), Named(String), } @@ -61,11 +61,11 @@ struct Context<'a, 'b:'a> { /// Stays `true` if all formatting parameters are default (as in "{}{}"). all_pieces_simple: bool, - name_positions: HashMap, + name_positions: HashMap, /// Updated as arguments are consumed or methods are entered - nest_level: uint, - next_arg: uint, + nest_level: usize, + next_arg: usize, } /// Parses the arguments from the given list of tokens, returning None diff --git a/src/libsyntax/ext/mtwt.rs b/src/libsyntax/ext/mtwt.rs index ae8ff118fcc..9bcb026a550 100644 --- a/src/libsyntax/ext/mtwt.rs +++ b/src/libsyntax/ext/mtwt.rs @@ -187,7 +187,7 @@ fn resolve_internal(id: Ident, } let resolved = { - let result = (*table.table.borrow())[id.ctxt as uint]; + let result = (*table.table.borrow())[id.ctxt as usize]; match result { EmptyCtxt => id.name, // ignore marks here: @@ -231,7 +231,7 @@ fn marksof_internal(ctxt: SyntaxContext, let mut result = Vec::new(); let mut loopvar = ctxt; loop { - let table_entry = (*table.table.borrow())[loopvar as uint]; + let table_entry = (*table.table.borrow())[loopvar as usize]; match table_entry { EmptyCtxt => { return result; @@ -258,7 +258,7 @@ fn marksof_internal(ctxt: SyntaxContext, /// FAILS when outside is not a mark. pub fn outer_mark(ctxt: SyntaxContext) -> Mrk { with_sctable(|sctable| { - match (*sctable.table.borrow())[ctxt as uint] { + match (*sctable.table.borrow())[ctxt as usize] { Mark(mrk, _) => mrk, _ => panic!("can't retrieve outer mark when outside is not a mark") } @@ -330,7 +330,7 @@ fn refold_test_sc(mut sc: SyntaxContext, table : &SCTable) -> Vec { let mut result = Vec::new(); loop { let table = table.table.borrow(); - match (*table)[sc as uint] { + match (*table)[sc as usize] { EmptyCtxt => {return result;}, Mark(mrk,tail) => { result.push(M(mrk)); diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 9eda4bcef99..75d904a4632 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -110,14 +110,14 @@ enum TokenTreeOrTokenTreeVec { } impl TokenTreeOrTokenTreeVec { - fn len(&self) -> uint { + fn len(&self) -> usize { match self { &TtSeq(ref v) => v.len(), &Tt(ref tt) => tt.len(), } } - fn get_tt(&self, index: uint) -> TokenTree { + fn get_tt(&self, index: usize) -> TokenTree { match self { &TtSeq(ref v) => v[index].clone(), &Tt(ref tt) => tt.get_tt(index), @@ -129,7 +129,7 @@ fn get_tt(&self, index: uint) -> TokenTree { #[derive(Clone)] struct MatcherTtFrame { elts: TokenTreeOrTokenTreeVec, - idx: uint, + idx: usize, } #[derive(Clone)] @@ -137,16 +137,16 @@ pub struct MatcherPos { stack: Vec, top_elts: TokenTreeOrTokenTreeVec, sep: Option, - idx: uint, + idx: usize, up: Option>, matches: Vec>>, - match_lo: uint, - match_cur: uint, - match_hi: uint, + match_lo: usize, + match_cur: usize, + match_hi: usize, sp_lo: BytePos, } -pub fn count_names(ms: &[TokenTree]) -> uint { +pub fn count_names(ms: &[TokenTree]) -> usize { ms.iter().fold(0, |count, elt| { count + match elt { &TtSequence(_, ref seq) => { @@ -206,7 +206,7 @@ pub enum NamedMatch { pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc]) -> HashMap> { fn n_rec(p_s: &ParseSess, m: &TokenTree, res: &[Rc], - ret_val: &mut HashMap>, idx: &mut uint) { + ret_val: &mut HashMap>, idx: &mut usize) { match m { &TtSequence(_, ref seq) => { for next_m in seq.tts.iter() { diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index 94b8356130a..7936b9fcfc7 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -27,7 +27,7 @@ #[derive(Clone)] struct TtFrame { forest: TokenTree, - idx: uint, + idx: usize, dotdotdoted: bool, sep: Option, } @@ -43,8 +43,8 @@ pub struct TtReader<'a> { // Some => return imported_from as the next token crate_name_next: Option, - repeat_idx: Vec, - repeat_len: Vec, + repeat_idx: Vec, + repeat_len: Vec, /* cached: */ pub cur_tok: Token, pub cur_span: Span, @@ -124,7 +124,7 @@ fn lookup_cur_matched(r: &TtReader, name: Ident) -> Option> { #[derive(Clone)] enum LockstepIterSize { LisUnconstrained, - LisConstraint(uint, Ident), + LisConstraint(usize, Ident), LisContradiction(String), } diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 16c29c9b5eb..cae0cf904f6 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -174,7 +174,7 @@ fn fold_ident(&mut self, i: Ident) -> Ident { noop_fold_ident(i, self) } - fn fold_uint(&mut self, i: uint) -> uint { + fn fold_uint(&mut self, i: usize) -> usize { noop_fold_uint(i, self) } @@ -505,7 +505,7 @@ pub fn noop_fold_ident(i: Ident, _: &mut T) -> Ident { i } -pub fn noop_fold_uint(i: uint, _: &mut T) -> uint { +pub fn noop_fold_uint(i: usize, _: &mut T) -> usize { i } diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index 16ade904be8..59a3c3bcb3e 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -22,7 +22,7 @@ use std::io; use std::str; use std::string::String; -use std::uint; +use std::usize; #[derive(Clone, Copy, PartialEq)] pub enum CommentStyle { @@ -87,7 +87,7 @@ fn vertical_trim(lines: Vec ) -> Vec { /// remove a "[ \t]*\*" block from each line, if possible fn horizontal_trim(lines: Vec ) -> Vec { - let mut i = uint::MAX; + let mut i = usize::MAX; let mut can_trim = true; let mut first = true; for line in lines.iter() { @@ -206,10 +206,10 @@ fn read_line_comments(rdr: &mut StringReader, code_to_the_left: bool, /// Returns None if the first col chars of s contain a non-whitespace char. /// Otherwise returns Some(k) where k is first char offset after that leading /// whitespace. Note k may be outside bounds of s. -fn all_whitespace(s: &str, col: CharPos) -> Option { +fn all_whitespace(s: &str, col: CharPos) -> Option { let len = s.len(); let mut col = col.to_uint(); - let mut cursor: uint = 0; + let mut cursor: usize = 0; while col > 0 && cursor < len { let r: str::CharRange = s.char_range_at(cursor); if !r.ch.is_whitespace() { diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 4cdafb36eec..cd159f7c599 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -295,7 +295,7 @@ fn translate_crlf<'b>(&self, start: BytePos, return s.into_cow(); fn translate_crlf_(rdr: &StringReader, start: BytePos, - s: &str, errmsg: &str, mut i: uint) -> String { + s: &str, errmsg: &str, mut i: usize) -> String { let mut buf = String::with_capacity(s.len()); let mut j = 0; while i < s.len() { @@ -645,7 +645,7 @@ fn bump_expecting_char<'a,D:fmt::Show>(r: &mut StringReader<'a>, /// Scan through any digits (base `radix`) or underscores, and return how /// many digits there were. - fn scan_digits(&mut self, radix: uint) -> uint { + fn scan_digits(&mut self, radix: usize) -> usize { let mut len = 0u; loop { let c = self.curr; @@ -724,7 +724,7 @@ fn scan_number(&mut self, c: char) -> token::Lit { /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an /// error if too many or too few digits are encountered. fn scan_hex_digits(&mut self, - n_digits: uint, + n_digits: usize, delim: char, below_0x7f_only: bool) -> bool { @@ -877,7 +877,7 @@ fn scan_char_or_byte(&mut self, start: BytePos, first_source_char: char, fn scan_unicode_escape(&mut self, delim: char) -> bool { self.bump(); // past the { let start_bpos = self.last_pos; - let mut count: uint = 0; + let mut count = 0us; let mut accum_int = 0; while !self.curr_is('}') && count <= 6 { @@ -935,7 +935,7 @@ fn scan_float_exponent(&mut self) { /// Check that a base is valid for a floating literal, emitting a nice /// error if it isn't. - fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: uint) { + fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) { match base { 16u => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \ supported"), diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index f1f547ba0c7..7bde32326fa 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -374,7 +374,7 @@ pub fn maybe_aborted(result: T, mut p: Parser) -> T { /// Rather than just accepting/rejecting a given literal, unescapes it as /// well. Can take any slice prefixed by a character escape. Returns the /// character and the number of characters consumed. -pub fn char_lit(lit: &str) -> (char, int) { +pub fn char_lit(lit: &str) -> (char, isize) { use std::{num, char}; let mut chars = lit.chars(); @@ -401,19 +401,19 @@ pub fn char_lit(lit: &str) -> (char, int) { let msg = format!("lexer should have rejected a bad character escape {}", lit); let msg2 = &msg[]; - fn esc(len: uint, lit: &str) -> Option<(char, int)> { + fn esc(len: usize, lit: &str) -> Option<(char, isize)> { num::from_str_radix(&lit[2..len], 16) .and_then(char::from_u32) - .map(|x| (x, len as int)) + .map(|x| (x, len as isize)) } - let unicode_escape = |&: | -> Option<(char, int)> + let unicode_escape = |&: | -> Option<(char, isize)> if lit.as_bytes()[2] == b'{' { let idx = lit.find('}').expect(msg2); let subslice = &lit[3..idx]; num::from_str_radix(subslice, 16) .and_then(char::from_u32) - .map(|x| (x, subslice.chars().count() as int + 4)) + .map(|x| (x, subslice.chars().count() as isize + 4)) } else { esc(6, lit) }; @@ -437,7 +437,7 @@ pub fn str_lit(lit: &str) -> String { let error = |&: i| format!("lexer should have rejected {} at {}", lit, i); /// Eat everything up to a non-whitespace - fn eat<'a>(it: &mut iter::Peekable<(uint, char), str::CharIndices<'a>>) { + fn eat<'a>(it: &mut iter::Peekable<(usize, char), str::CharIndices<'a>>) { loop { match it.peek().map(|x| x.1) { Some(' ') | Some('\n') | Some('\r') | Some('\t') => { @@ -568,7 +568,7 @@ pub fn float_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> a } /// Parse a string representing a byte literal into its final form. Similar to `char_lit` -pub fn byte_lit(lit: &str) -> (u8, uint) { +pub fn byte_lit(lit: &str) -> (u8, usize) { let err = |&: i| format!("lexer accepted invalid byte literal {} step {}", lit, i); if lit.len() == 1 { @@ -606,7 +606,7 @@ pub fn binary_lit(lit: &str) -> Rc> { let error = |&: i| format!("lexer should have rejected {} at {}", lit, i); /// Eat everything up to a non-whitespace - fn eat<'a, I: Iterator>(it: &mut iter::Peekable<(uint, u8), I>) { + fn eat<'a, I: Iterator>(it: &mut iter::Peekable<(usize, u8), I>) { loop { match it.peek().map(|x| x.1) { Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => { @@ -1161,11 +1161,11 @@ fn visit_pat(&mut self, p: &'v ast::Pat) { #[test] fn span_of_self_arg_pat_idents_are_correct() { - let srcs = ["impl z { fn a (&self, &myarg: int) {} }", - "impl z { fn a (&mut self, &myarg: int) {} }", - "impl z { fn a (&'a self, &myarg: int) {} }", - "impl z { fn a (self, &myarg: int) {} }", - "impl z { fn a (self: Foo, &myarg: int) {} }", + let srcs = ["impl z { fn a (&self, &myarg: i32) {} }", + "impl z { fn a (&mut self, &myarg: i32) {} }", + "impl z { fn a (&'a self, &myarg: i32) {} }", + "impl z { fn a (self, &myarg: i32) {} }", + "impl z { fn a (self: Foo, &myarg: i32) {} }", ]; for &src in srcs.iter() { diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index 9d03ec73af8..a3600506057 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -62,7 +62,7 @@ fn obsolete(&mut self, sp: Span, kind: ObsoleteSyntax) { "use a `move ||` expression instead", ), ObsoleteSyntax::ClosureType => ( - "`|uint| -> bool` closure type syntax", + "`|usize| -> bool` closure type syntax", "use unboxed closures instead, no type annotation needed" ), ObsoleteSyntax::Sized => ( diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 30cc9836374..9822dcef0c0 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -292,9 +292,9 @@ pub struct Parser<'a> { pub buffer: [TokenAndSpan; 4], pub buffer_start: int, pub buffer_end: int, - pub tokens_consumed: uint, + pub tokens_consumed: usize, pub restrictions: Restrictions, - pub quote_depth: uint, // not (yet) related to the quasiquoter + pub quote_depth: usize, // not (yet) related to the quasiquoter pub reader: Box, pub interner: Rc, /// The set of seen errors about obsolete syntax. Used to suppress @@ -932,8 +932,8 @@ pub fn bump(&mut self) { self.reader.real_token() } else { // Avoid token copies with `replace`. - let buffer_start = self.buffer_start as uint; - let next_index = (buffer_start + 1) & 3 as uint; + let buffer_start = self.buffer_start as usize; + let next_index = (buffer_start + 1) & 3 as usize; self.buffer_start = next_index as int; let placeholder = TokenAndSpan { @@ -972,15 +972,15 @@ pub fn buffer_length(&mut self) -> int { } return (4 - self.buffer_start) + self.buffer_end; } - pub fn look_ahead(&mut self, distance: uint, f: F) -> R where + pub fn look_ahead(&mut self, distance: usize, f: F) -> R where F: FnOnce(&token::Token) -> R, { let dist = distance as int; while self.buffer_length() < dist { - self.buffer[self.buffer_end as uint] = self.reader.real_token(); + self.buffer[self.buffer_end as usize] = self.reader.real_token(); self.buffer_end = (self.buffer_end + 1) & 3; } - f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok) + f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok) } pub fn fatal(&mut self, m: &str) -> ! { self.sess.span_diagnostic.span_fatal(self.span, m) @@ -2087,7 +2087,7 @@ pub fn mk_field(&mut self, expr: P, ident: ast::SpannedIdent) -> ast::Expr ExprField(expr, ident) } - pub fn mk_tup_field(&mut self, expr: P, idx: codemap::Spanned) -> ast::Expr_ { + pub fn mk_tup_field(&mut self, expr: P, idx: codemap::Spanned) -> ast::Expr_ { ExprTupField(expr, idx) } @@ -2485,7 +2485,7 @@ pub fn parse_dot_or_call_expr_with(&mut self, e0: P) -> P { hi = self.span.hi; self.bump(); - let index = n.as_str().parse::(); + let index = n.as_str().parse::(); match index { Some(n) => { let id = spanned(dot, hi, n); @@ -2511,7 +2511,7 @@ pub fn parse_dot_or_call_expr_with(&mut self, e0: P) -> P { }; self.span_help(last_span, &format!("try parenthesizing the first index; e.g., `(foo.{}){}`", - float.trunc() as uint, + float.trunc() as usize, &float.fract().to_string()[1..])[]); } self.abort_if_errors(); @@ -2864,7 +2864,7 @@ pub fn parse_binops(&mut self) -> P { } /// Parse an expression of binops of at least min_prec precedence - pub fn parse_more_binops(&mut self, lhs: P, min_prec: uint) -> P { + pub fn parse_more_binops(&mut self, lhs: P, min_prec: usize) -> P { if self.expr_is_complete(&*lhs) { return lhs; } // Prevent dynamic borrow errors later on by limiting the diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 4b3573f84c5..aeb9599923e 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -83,9 +83,9 @@ pub enum Lit { Integer(ast::Name), Float(ast::Name), Str_(ast::Name), - StrRaw(ast::Name, uint), /* raw str delimited by n hash symbols */ + StrRaw(ast::Name, usize), /* raw str delimited by n hash symbols */ Binary(ast::Name), - BinaryRaw(ast::Name, uint), /* raw binary str delimited by n hash symbols */ + BinaryRaw(ast::Name, usize), /* raw binary str delimited by n hash symbols */ } impl Lit { @@ -724,7 +724,7 @@ pub fn intern(s: &str) -> ast::Name { get_ident_interner().intern(s) } -/// gensym's a new uint, using the current interner. +/// gensym's a new usize, using the current interner. #[inline] pub fn gensym(s: &str) -> ast::Name { get_ident_interner().gensym(s) diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 06d510d37bd..0cfc3d38e15 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -31,7 +31,7 @@ //! //! 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 uint for indices-in-buffers and +//! 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). @@ -123,9 +123,9 @@ pub fn tok_str(token: &Token) -> String { pub fn buf_str(toks: &[Token], szs: &[int], - left: uint, - right: uint, - lim: uint) + left: usize, + right: usize, + lim: usize) -> String { let n = toks.len(); assert_eq!(n, szs.len()); @@ -161,14 +161,14 @@ pub struct PrintStackElem { static SIZE_INFINITY: int = 0xffff; -pub fn mk_printer(out: Box, linewidth: uint) -> Printer { +pub fn mk_printer(out: Box, linewidth: usize) -> Printer { // Yes 3, it makes the ring buffers big enough to never // fall behind. - let n: uint = 3 * linewidth; + let n: usize = 3 * linewidth; debug!("mk_printer {}", linewidth); let token: Vec = repeat(Token::Eof).take(n).collect(); let size: Vec = repeat(0i).take(n).collect(); - let scan_stack: Vec = repeat(0u).take(n).collect(); + let scan_stack: Vec = repeat(0us).take(n).collect(); Printer { out: out, buf_len: n, @@ -267,15 +267,15 @@ pub fn mk_printer(out: Box, linewidth: uint) -> Printer { /// called 'print'. pub struct Printer { pub out: Box, - buf_len: uint, + buf_len: usize, /// Width of lines we're constrained to margin: int, /// Number of spaces left on line space: int, /// Index of left side of input stream - left: uint, + left: usize, /// Index of right side of input stream - right: uint, + right: usize, /// Ring-buffer stream goes through token: Vec , /// Ring-buffer of calculated sizes @@ -290,13 +290,13 @@ pub struct Printer { /// 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 , + scan_stack: Vec , /// Top==bottom disambiguator scan_stack_empty: bool, /// Index of top of scan_stack - top: uint, + top: usize, /// Index of bottom of scan_stack - bottom: uint, + bottom: usize, /// Stack of blocks-in-progress being flushed by print print_stack: Vec , /// Buffered indentation to avoid writing trailing whitespace @@ -405,7 +405,7 @@ pub fn check_stream(&mut self) -> io::IoResult<()> { } Ok(()) } - pub fn scan_push(&mut self, x: uint) { + pub fn scan_push(&mut self, x: usize) { debug!("scan_push {}", x); if self.scan_stack_empty { self.scan_stack_empty = false; @@ -416,7 +416,7 @@ pub fn scan_push(&mut self, x: uint) { } self.scan_stack[self.top] = x; } - pub fn scan_pop(&mut self) -> uint { + pub fn scan_pop(&mut self) -> usize { assert!((!self.scan_stack_empty)); let x = self.scan_stack[self.top]; if self.top == self.bottom { @@ -426,11 +426,11 @@ pub fn scan_pop(&mut self) -> uint { } return x; } - pub fn scan_top(&mut self) -> uint { + 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) -> uint { + 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 { @@ -620,22 +620,22 @@ pub fn print(&mut self, token: Token, l: int) -> io::IoResult<()> { // Convenience functions to talk to the printer. // // "raw box" -pub fn rbox(p: &mut Printer, indent: uint, b: Breaks) -> io::IoResult<()> { +pub fn rbox(p: &mut Printer, indent: usize, b: Breaks) -> io::IoResult<()> { p.pretty_print(Token::Begin(BeginToken { offset: indent as int, breaks: b })) } -pub fn ibox(p: &mut Printer, indent: uint) -> io::IoResult<()> { +pub fn ibox(p: &mut Printer, indent: usize) -> io::IoResult<()> { rbox(p, indent, Breaks::Inconsistent) } -pub fn cbox(p: &mut Printer, indent: uint) -> io::IoResult<()> { +pub fn cbox(p: &mut Printer, indent: usize) -> io::IoResult<()> { rbox(p, indent, Breaks::Consistent) } -pub fn break_offset(p: &mut Printer, n: uint, off: int) -> io::IoResult<()> { +pub fn break_offset(p: &mut Printer, n: usize, off: int) -> io::IoResult<()> { p.pretty_print(Token::Break(BreakToken { offset: off, blank_space: n as int @@ -662,7 +662,7 @@ pub fn zero_word(p: &mut Printer, wrd: &str) -> io::IoResult<()> { p.pretty_print(Token::String(/* bad */ wrd.to_string(), 0)) } -pub fn spaces(p: &mut Printer, n: uint) -> io::IoResult<()> { +pub fn spaces(p: &mut Printer, n: usize) -> io::IoResult<()> { break_offset(p, n, 0) } @@ -675,7 +675,7 @@ pub fn space(p: &mut Printer) -> io::IoResult<()> { } pub fn hardbreak(p: &mut Printer) -> io::IoResult<()> { - spaces(p, SIZE_INFINITY as uint) + spaces(p, SIZE_INFINITY as usize) } pub fn hardbreak_tok_offset(off: int) -> Token { diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 5d76dc71006..2583c302293 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -54,8 +54,8 @@ impl PpAnn for NoAnn {} #[derive(Copy)] pub struct CurrentCommentAndLiteral { - cur_cmnt: uint, - cur_lit: uint, + cur_cmnt: usize, + cur_lit: usize, } pub struct State<'a> { @@ -92,10 +92,10 @@ pub fn rust_printer_annotated<'a>(writer: Box, } #[allow(non_upper_case_globals)] -pub const indent_unit: uint = 4u; +pub const indent_unit: usize = 4us; #[allow(non_upper_case_globals)] -pub const default_columns: uint = 78u; +pub const default_columns: usize = 78us; /// Requires you to pass an input filename and reader so that /// it can scan the input text for comments and literals to @@ -459,7 +459,7 @@ fn needs_parentheses(expr: &ast::Expr) -> bool { } impl<'a> State<'a> { - pub fn ibox(&mut self, u: uint) -> IoResult<()> { + pub fn ibox(&mut self, u: usize) -> IoResult<()> { self.boxes.push(pp::Breaks::Inconsistent); pp::ibox(&mut self.s, u) } @@ -469,13 +469,13 @@ pub fn end(&mut self) -> IoResult<()> { pp::end(&mut self.s) } - pub fn cbox(&mut self, u: uint) -> IoResult<()> { + pub fn cbox(&mut self, u: usize) -> IoResult<()> { self.boxes.push(pp::Breaks::Consistent); pp::cbox(&mut self.s, u) } // "raw box" - pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> { + pub fn rbox(&mut self, u: usize, b: pp::Breaks) -> IoResult<()> { self.boxes.push(b); pp::rbox(&mut self.s, u, b) } @@ -514,11 +514,11 @@ pub fn bopen(&mut self) -> IoResult<()> { } pub fn bclose_(&mut self, span: codemap::Span, - indented: uint) -> IoResult<()> { + indented: usize) -> IoResult<()> { self.bclose_maybe_open(span, indented, true) } pub fn bclose_maybe_open (&mut self, span: codemap::Span, - indented: uint, close_box: bool) -> IoResult<()> { + indented: usize, close_box: bool) -> IoResult<()> { try!(self.maybe_print_comment(span.hi)); try!(self.break_offset_if_not_bol(1u, -(indented as int))); try!(word(&mut self.s, "}")); @@ -567,7 +567,7 @@ pub fn space_if_not_bol(&mut self) -> IoResult<()> { if !self.is_bol() { try!(space(&mut self.s)); } Ok(()) } - pub fn break_offset_if_not_bol(&mut self, n: uint, + pub fn break_offset_if_not_bol(&mut self, n: usize, off: int) -> IoResult<()> { if !self.is_bol() { break_offset(&mut self.s, n, off) @@ -1355,7 +1355,7 @@ pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> { } pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block, - indented: uint) -> IoResult<()> { + indented: usize) -> IoResult<()> { self.print_block_maybe_unclosed(blk, indented, &[], false) } @@ -1367,7 +1367,7 @@ pub fn print_block_with_attrs(&mut self, pub fn print_block_maybe_unclosed(&mut self, blk: &ast::Block, - indented: uint, + indented: usize, attrs: &[ast::Attribute], close_box: bool) -> IoResult<()> { match blk.rules { @@ -1951,7 +1951,7 @@ pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> { self.ann.post(self, NodeIdent(&ident)) } - pub fn print_uint(&mut self, i: uint) -> IoResult<()> { + pub fn print_uint(&mut self, i: usize) -> IoResult<()> { word(&mut self.s, &i.to_string()[]) } @@ -3053,7 +3053,7 @@ pub fn print_unsafety(&mut self, s: ast::Unsafety) -> IoResult<()> { } } -fn repeat(s: &str, n: uint) -> String { iter::repeat(s).take(n).collect() } +fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() } #[cfg(test)] mod test { diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 5dca39f1aea..757bafaf5cb 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! An "interner" is a data structure that associates values with uint tags and +//! An "interner" is a data structure that associates values with usize tags and //! allows bidirectional lookup; i.e. given a value, one can easily find the //! type, and vice versa. @@ -73,7 +73,7 @@ pub fn get(&self, idx: Name) -> T { (*vect)[idx.uint()].clone() } - pub fn len(&self) -> uint { + pub fn len(&self) -> usize { let vect = self.vect.borrow(); (*vect).len() } @@ -199,7 +199,7 @@ pub fn get(&self, idx: Name) -> RcStr { (*self.vect.borrow())[idx.uint()].clone() } - pub fn len(&self) -> uint { + pub fn len(&self) -> usize { self.vect.borrow().len() } diff --git a/src/libsyntax/util/parser_testing.rs b/src/libsyntax/util/parser_testing.rs index 83bbff8473d..5466b7337e7 100644 --- a/src/libsyntax/util/parser_testing.rs +++ b/src/libsyntax/util/parser_testing.rs @@ -130,10 +130,10 @@ pub fn matches_codepattern(a : &str, b : &str) -> bool { } } -/// Given a string and an index, return the first uint >= idx +/// Given a string and an index, return the first usize >= idx /// that is a non-ws-char or is outside of the legal range of /// the string. -fn scan_for_non_ws_or_end(a : &str, idx: uint) -> uint { +fn scan_for_non_ws_or_end(a : &str, idx: usize) -> usize { let mut i = idx; let len = a.len(); while (i < len) && (is_whitespace(a.char_at(i))) { diff --git a/src/libsyntax/util/small_vector.rs b/src/libsyntax/util/small_vector.rs index b68c9926391..a4494a98864 100644 --- a/src/libsyntax/util/small_vector.rs +++ b/src/libsyntax/util/small_vector.rs @@ -89,7 +89,7 @@ pub fn push_all(&mut self, other: SmallVector) { } } - pub fn get<'a>(&'a self, idx: uint) -> &'a T { + pub fn get<'a>(&'a self, idx: usize) -> &'a T { match self.repr { One(ref v) if idx == 0 => v, Many(ref vs) => &vs[idx], @@ -126,7 +126,7 @@ pub fn into_iter(self) -> IntoIter { IntoIter { repr: repr } } - pub fn len(&self) -> uint { + pub fn len(&self) -> usize { match self.repr { Zero => 0, One(..) => 1, @@ -165,7 +165,7 @@ fn next(&mut self) -> Option { } } - fn size_hint(&self) -> (uint, Option) { + fn size_hint(&self) -> (usize, Option) { match self.repr { ZeroIterator => (0, Some(0)), OneIterator(..) => (1, Some(1)), From fa01251a8c106b14170b3ac85edcbb7450e61d58 Mon Sep 17 00:00:00 2001 From: Stepan Koltsov Date: Sun, 18 Jan 2015 03:32:11 +0300 Subject: [PATCH 08/96] rustc: print filename if file cannot be written File cannot be written, for example, if directory does not exist. Before this commit: ``` % rustc -o nonexistent/program program.rs error: could not write output: No such file or directory ``` With this commit: ``` % rustc -o nonexistent/program program.rs error: could not write output to nonexistent/program.0.o: No such file or directory ``` This is useful when full rust command is not displayed, or when last error is preceded by thousands of warnings. --- src/librustc_trans/back/write.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index aa51b0c5ee2..85bff4c4924 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -67,11 +67,11 @@ pub fn write_output_file( output: &Path, file_type: llvm::FileType) { unsafe { - let output = CString::from_slice(output.as_vec()); + let output_c = CString::from_slice(output.as_vec()); let result = llvm::LLVMRustWriteOutputFile( - target, pm, m, output.as_ptr(), file_type); + target, pm, m, output_c.as_ptr(), file_type); if !result { - llvm_err(handler, "could not write output".to_string()); + llvm_err(handler, format!("could not write output to {}", output.display())); } } } From d5c83652b33a6e5049699ccc7e6bd6fffb42c2b8 Mon Sep 17 00:00:00 2001 From: Paul Collier Date: Sat, 17 Jan 2015 23:49:08 +0000 Subject: [PATCH 09/96] libsyntax: rename functions from uint to usize --- src/librustc/lint/builtin.rs | 2 +- src/librustc/util/ppaux.rs | 2 +- src/librustc_resolve/lib.rs | 2 +- src/librustc_trans/save/span_utils.rs | 4 +-- src/librustc_trans/trans/common.rs | 6 ++-- src/librustc_trans/trans/debuginfo.rs | 8 ++--- src/librustc_trans/trans/meth.rs | 2 +- src/librustdoc/clean/mod.rs | 4 +-- src/libsyntax/ast.rs | 4 +-- src/libsyntax/codemap.rs | 44 ++++++++++++------------- src/libsyntax/diagnostic.rs | 6 ++-- src/libsyntax/ext/build.rs | 10 +++--- src/libsyntax/ext/deriving/decodable.rs | 8 ++--- src/libsyntax/ext/deriving/default.rs | 2 +- src/libsyntax/ext/deriving/encodable.rs | 12 +++---- src/libsyntax/ext/deriving/hash.rs | 2 +- src/libsyntax/ext/deriving/rand.rs | 6 ++-- src/libsyntax/ext/env.rs | 2 +- src/libsyntax/ext/format.rs | 12 +++---- src/libsyntax/ext/mtwt.rs | 4 +-- src/libsyntax/ext/quote.rs | 2 +- src/libsyntax/ext/source_util.rs | 4 +-- src/libsyntax/fold.rs | 8 ++--- src/libsyntax/parse/lexer/comments.rs | 2 +- src/libsyntax/parse/lexer/mod.rs | 16 ++++----- src/libsyntax/parse/mod.rs | 4 +-- src/libsyntax/parse/token.rs | 2 +- src/libsyntax/print/pprust.rs | 4 +-- src/libsyntax/util/interner.rs | 6 ++-- src/test/auxiliary/roman_numerals.rs | 4 +-- 30 files changed, 97 insertions(+), 97 deletions(-) diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index 59808b302f4..75897fe6d7c 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -1329,7 +1329,7 @@ fn check_unused_mut_pat(&self, cx: &Context, pats: &[P]) { let ident = path1.node; if let ast::BindByValue(ast::MutMutable) = mode { if !token::get_ident(ident).get().starts_with("_") { - match mutables.entry(ident.name.uint()) { + match mutables.entry(ident.name.usize()) { Vacant(entry) => { entry.insert(vec![id]); }, Occupied(mut entry) => { entry.get_mut().push(id); }, } diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index fb44d0cadfa..8427c471eee 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -164,7 +164,7 @@ pub fn explain_region_and_span(cx: &ctxt, region: ty::Region) fn explain_span(cx: &ctxt, heading: &str, span: Span) -> (String, Option) { let lo = cx.sess.codemap().lookup_char_pos_adj(span.lo); - (format!("the {} at {}:{}", heading, lo.line, lo.col.to_uint()), + (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize()), Some(span)) } } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 7743a437858..19992164118 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -1962,7 +1962,7 @@ fn search_parent_externals(needle: Name, module: &Rc) let module_name = self.module_to_string(&*search_module); let mut span = span; let msg = if "???" == &module_name[] { - span.hi = span.lo + Pos::from_uint(segment_name.get().len()); + span.hi = span.lo + Pos::from_usize(segment_name.get().len()); match search_parent_externals(name, &self.current_module) { diff --git a/src/librustc_trans/save/span_utils.rs b/src/librustc_trans/save/span_utils.rs index 77343612ac8..97b3cda006b 100644 --- a/src/librustc_trans/save/span_utils.rs +++ b/src/librustc_trans/save/span_utils.rs @@ -40,8 +40,8 @@ pub fn extent_str(&self, span: Span) -> String { format!("file_name,{},file_line,{},file_col,{},extent_start,{},extent_start_bytes,{},\ file_line_end,{},file_col_end,{},extent_end,{},extent_end_bytes,{}", lo_loc.file.name, - lo_loc.line, lo_loc.col.to_uint(), lo_pos.to_uint(), lo_pos_byte.to_uint(), - hi_loc.line, hi_loc.col.to_uint(), hi_pos.to_uint(), hi_pos_byte.to_uint()) + lo_loc.line, lo_loc.col.to_usize(), lo_pos.to_usize(), lo_pos_byte.to_usize(), + hi_loc.line, hi_loc.col.to_usize(), hi_pos.to_usize(), hi_pos_byte.to_usize()) } // sub_span starts at span.lo, so we need to adjust the positions etc. diff --git a/src/librustc_trans/trans/common.rs b/src/librustc_trans/trans/common.rs index 3eee4637de1..519b4f628e2 100644 --- a/src/librustc_trans/trans/common.rs +++ b/src/librustc_trans/trans/common.rs @@ -275,7 +275,7 @@ pub fn return_type_is_void(ccx: &CrateContext, ty: Ty) -> bool { /// Generates a unique symbol based off the name given. This is used to create /// unique symbols for things like closures. pub fn gensym_name(name: &str) -> PathElem { - let num = token::gensym(name).uint(); + let num = token::gensym(name).usize(); // use one colon which will get translated to a period by the mangler, and // we're guaranteed that `num` is globally unique for this crate. PathName(token::gensym(&format!("{}:{}", name, num)[])) @@ -848,7 +848,7 @@ pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> Va !null_terminated as Bool); let gsym = token::gensym("str"); - let buf = CString::from_vec(format!("str{}", gsym.uint()).into_bytes()); + let buf = CString::from_vec(format!("str{}", gsym.usize()).into_bytes()); let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(sc).to_ref(), buf.as_ptr()); llvm::LLVMSetInitializer(g, sc); llvm::LLVMSetGlobalConstant(g, True); @@ -873,7 +873,7 @@ pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef { let lldata = C_bytes(cx, data); let gsym = token::gensym("binary"); - let name = format!("binary{}", gsym.uint()); + let name = format!("binary{}", gsym.usize()); let name = CString::from_vec(name.into_bytes()); let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(lldata).to_ref(), name.as_ptr()); diff --git a/src/librustc_trans/trans/debuginfo.rs b/src/librustc_trans/trans/debuginfo.rs index a03a5090c05..4b52e5f989f 100644 --- a/src/librustc_trans/trans/debuginfo.rs +++ b/src/librustc_trans/trans/debuginfo.rs @@ -1204,7 +1204,7 @@ pub fn set_source_location(fcx: &FunctionContext, set_debug_location(cx, DebugLocation::new(scope, loc.line, - loc.col.to_uint())); + loc.col.to_usize())); } else { set_debug_location(cx, UnknownLocation); } @@ -1719,7 +1719,7 @@ fn declare_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, set_debug_location(cx, DebugLocation::new(scope_metadata, loc.line, - loc.col.to_uint())); + loc.col.to_usize())); unsafe { let instr = llvm::LLVMDIBuilderInsertDeclareAtEnd( DIB(cx), @@ -3282,7 +3282,7 @@ fn with_new_scope(cx: &CrateContext, parent_scope, file_metadata, loc.line as c_uint, - loc.col.to_uint() as c_uint) + loc.col.to_usize() as c_uint) }; scope_stack.push(ScopeStackEntry { scope_metadata: scope_metadata, @@ -3404,7 +3404,7 @@ fn walk_pattern(cx: &CrateContext, parent_scope, file_metadata, loc.line as c_uint, - loc.col.to_uint() as c_uint) + loc.col.to_usize() as c_uint) }; scope_stack.push(ScopeStackEntry { diff --git a/src/librustc_trans/trans/meth.rs b/src/librustc_trans/trans/meth.rs index 0fb0dffe930..712f5fa53c9 100644 --- a/src/librustc_trans/trans/meth.rs +++ b/src/librustc_trans/trans/meth.rs @@ -785,7 +785,7 @@ pub fn make_vtable>(ccx: &CrateContext, unsafe { let tbl = C_struct(ccx, &components[], false); let sym = token::gensym("vtable"); - let buf = CString::from_vec(format!("vtable{}", sym.uint()).into_bytes()); + let buf = CString::from_vec(format!("vtable{}", sym.usize()).into_bytes()); let vt_gvar = llvm::LLVMAddGlobal(ccx.llmod(), val_ty(tbl).to_ref(), buf.as_ptr()); llvm::LLVMSetInitializer(vt_gvar, tbl); diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 8dc3adad3b2..c6ac616932d 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1870,9 +1870,9 @@ fn clean(&self, cx: &DocContext) -> Span { Span { filename: filename.to_string(), loline: lo.line, - locol: lo.col.to_uint(), + locol: lo.col.to_usize(), hiline: hi.line, - hicol: hi.col.to_uint(), + hicol: hi.col.to_usize(), } } } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 81ce521f68c..47d55818f5e 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -95,7 +95,7 @@ pub fn as_str<'a>(&'a self) -> &'a str { pub fn encode_with_hygiene(&self) -> String { format!("\x00name_{},ctxt_{}\x00", - self.name.uint(), + self.name.usize(), self.ctxt) } } @@ -181,7 +181,7 @@ pub fn as_str<'a>(&'a self) -> &'a str { } } - pub fn uint(&self) -> usize { + pub fn usize(&self) -> usize { let Name(nm) = *self; nm as usize } diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 6b9dda88a36..07544f35b19 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -30,8 +30,8 @@ use serialize::{Encodable, Decodable, Encoder, Decoder}; pub trait Pos { - fn from_uint(n: usize) -> Self; - fn to_uint(&self) -> usize; + fn from_usize(n: usize) -> Self; + fn to_usize(&self) -> usize; } /// A byte offset. Keep this small (currently 32-bits), as AST contains @@ -49,15 +49,15 @@ pub trait Pos { // have been unsuccessful impl Pos for BytePos { - fn from_uint(n: usize) -> BytePos { BytePos(n as u32) } - fn to_uint(&self) -> usize { let BytePos(n) = *self; n as usize } + fn from_usize(n: usize) -> BytePos { BytePos(n as u32) } + fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize } } impl Add for BytePos { type Output = BytePos; fn add(self, rhs: BytePos) -> BytePos { - BytePos((self.to_uint() + rhs.to_uint()) as u32) + BytePos((self.to_usize() + rhs.to_usize()) as u32) } } @@ -65,20 +65,20 @@ impl Sub for BytePos { type Output = BytePos; fn sub(self, rhs: BytePos) -> BytePos { - BytePos((self.to_uint() - rhs.to_uint()) as u32) + BytePos((self.to_usize() - rhs.to_usize()) as u32) } } impl Pos for CharPos { - fn from_uint(n: usize) -> CharPos { CharPos(n) } - fn to_uint(&self) -> usize { let CharPos(n) = *self; n } + fn from_usize(n: usize) -> CharPos { CharPos(n) } + fn to_usize(&self) -> usize { let CharPos(n) = *self; n } } impl Add for CharPos { type Output = CharPos; fn add(self, rhs: CharPos) -> CharPos { - CharPos(self.to_uint() + rhs.to_uint()) + CharPos(self.to_usize() + rhs.to_usize()) } } @@ -86,7 +86,7 @@ impl Sub for CharPos { type Output = CharPos; fn sub(self, rhs: CharPos) -> CharPos { - CharPos(self.to_uint() - rhs.to_uint()) + CharPos(self.to_usize() - rhs.to_usize()) } } @@ -310,7 +310,7 @@ pub fn get_line(&self, line_number: usize) -> Option { let lines = self.lines.borrow(); lines.get(line_number).map(|&line| { let begin: BytePos = line - self.start_pos; - let begin = begin.to_uint(); + let begin = begin.to_usize(); let slice = &self.src[begin..]; match slice.find('\n') { Some(e) => &slice[..e], @@ -351,7 +351,7 @@ pub fn new_filemap(&self, filename: FileName, src: String) -> Rc { let mut files = self.files.borrow_mut(); let start_pos = match files.last() { None => 0, - Some(last) => last.start_pos.to_uint() + last.src.len(), + Some(last) => last.start_pos.to_usize() + last.src.len(), }; // Remove utf-8 BOM if any. @@ -374,7 +374,7 @@ pub fn new_filemap(&self, filename: FileName, src: String) -> Rc { let filemap = Rc::new(FileMap { name: filename, src: src.to_string(), - start_pos: Pos::from_uint(start_pos), + start_pos: Pos::from_usize(start_pos), lines: RefCell::new(Vec::new()), multibyte_chars: RefCell::new(Vec::new()), }); @@ -389,7 +389,7 @@ pub fn mk_substr_filename(&self, sp: Span) -> String { (format!("<{}:{}:{}>", pos.file.name, pos.line, - pos.col.to_uint() + 1)).to_string() + pos.col.to_usize() + 1)).to_string() } /// Lookup source information about a BytePos @@ -417,9 +417,9 @@ pub fn span_to_string(&self, sp: Span) -> String { return (format!("{}:{}:{}: {}:{}", lo.filename, lo.line, - lo.col.to_uint() + 1, + lo.col.to_usize() + 1, hi.line, - hi.col.to_uint() + 1)).to_string() + hi.col.to_usize() + 1)).to_string() } pub fn span_to_filename(&self, sp: Span) -> FileName { @@ -447,7 +447,7 @@ pub fn span_to_snippet(&self, sp: Span) -> Option { if begin.fm.start_pos != end.fm.start_pos { None } else { - Some((&begin.fm.src[begin.pos.to_uint()..end.pos.to_uint()]).to_string()) + Some((&begin.fm.src[begin.pos.to_usize()..end.pos.to_usize()]).to_string()) } } @@ -484,14 +484,14 @@ pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { total_extra_bytes += mbc.bytes - 1; // We should never see a byte position in the middle of a // character - assert!(bpos.to_uint() >= mbc.pos.to_uint() + mbc.bytes); + assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes); } else { break; } } - assert!(map.start_pos.to_uint() + total_extra_bytes <= bpos.to_uint()); - CharPos(bpos.to_uint() - map.start_pos.to_uint() - total_extra_bytes) + assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize()); + CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes) } fn lookup_filemap_idx(&self, pos: BytePos) -> usize { @@ -520,13 +520,13 @@ fn lookup_filemap_idx(&self, pos: BytePos) -> usize { } if a == 0 { panic!("position {} does not resolve to a source location", - pos.to_uint()); + pos.to_usize()); } a -= 1; } if a >= len { panic!("position {} does not resolve to a source location", - pos.to_uint()) + pos.to_usize()) } return a; diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 9c8ea7d9d68..c86991b6e40 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -475,7 +475,7 @@ fn highlight_lines(err: &mut EmitterWriter, while num > 0u { num /= 10u; digits += 1u; } // indent past |name:## | and the 0-offset column location - let left = fm.name.len() + digits + lo.col.to_uint() + 3u; + let left = fm.name.len() + digits + lo.col.to_usize() + 3u; let mut s = String::new(); // Skip is the number of characters we need to skip because they are // part of the 'filename:line ' part of the previous line. @@ -502,7 +502,7 @@ fn highlight_lines(err: &mut EmitterWriter, let hi = cm.lookup_char_pos(sp.hi); if hi.col != lo.col { // the ^ already takes up one space - let num_squigglies = hi.col.to_uint() - lo.col.to_uint() - 1u; + let num_squigglies = hi.col.to_usize() - lo.col.to_usize() - 1us; for _ in range(0, num_squigglies) { s.push('~'); } @@ -551,7 +551,7 @@ fn custom_highlight_lines(w: &mut EmitterWriter, let last_line_start = format!("{}:{} ", fm.name, lines[lines.len()-1]+1); let hi = cm.lookup_char_pos(sp.hi); // Span seems to use half-opened interval, so subtract 1 - let skip = last_line_start.len() + hi.col.to_uint() - 1; + let skip = last_line_start.len() + hi.col.to_usize() - 1; let mut s = String::new(); for _ in range(0, skip) { s.push(' '); diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index d960186cdd8..3bac972dbb5 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -134,7 +134,7 @@ fn expr_struct_ident(&self, span: Span, id: ast::Ident, fn expr_lit(&self, sp: Span, lit: ast::Lit_) -> P; - fn expr_uint(&self, span: Span, i: usize) -> P; + fn expr_usize(&self, span: Span, i: usize) -> P; fn expr_int(&self, sp: Span, i: int) -> P; fn expr_u8(&self, sp: Span, u: u8) -> P; fn expr_bool(&self, sp: Span, value: bool) -> P; @@ -579,7 +579,7 @@ fn expr_unary(&self, sp: Span, op: ast::UnOp, e: P) -> P { fn expr_field_access(&self, sp: Span, expr: P, ident: ast::Ident) -> P { let field_name = token::get_ident(ident); let field_span = Span { - lo: sp.lo - Pos::from_uint(field_name.get().len()), + lo: sp.lo - Pos::from_usize(field_name.get().len()), hi: sp.hi, expn_id: sp.expn_id, }; @@ -589,7 +589,7 @@ fn expr_field_access(&self, sp: Span, expr: P, ident: ast::Ident) -> } fn expr_tup_field_access(&self, sp: Span, expr: P, idx: usize) -> P { let field_span = Span { - lo: sp.lo - Pos::from_uint(idx.to_string().len()), + lo: sp.lo - Pos::from_usize(idx.to_string().len()), hi: sp.hi, expn_id: sp.expn_id, }; @@ -641,7 +641,7 @@ fn expr_struct_ident(&self, span: Span, fn expr_lit(&self, sp: Span, lit: ast::Lit_) -> P { self.expr(sp, ast::ExprLit(P(respan(sp, lit)))) } - fn expr_uint(&self, span: Span, i: usize) -> P { + fn expr_usize(&self, span: Span, i: usize) -> P { self.expr_lit(span, ast::LitInt(i as u64, ast::UnsignedIntLit(ast::TyUs(false)))) } fn expr_int(&self, sp: Span, i: int) -> P { @@ -710,7 +710,7 @@ fn expr_fail(&self, span: Span, msg: InternedString) -> P { let loc = self.codemap().lookup_char_pos(span.lo); let expr_file = self.expr_str(span, token::intern_and_get_ident(&loc.file.name[])); - let expr_line = self.expr_uint(span, loc.line); + let expr_line = self.expr_usize(span, loc.line); let expr_file_line_tuple = self.expr_tuple(span, vec!(expr_file, expr_line)); let expr_file_line_ptr = self.expr_addr_of(span, expr_file_line_tuple); self.expr_call_global( diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index 6a41874b935..62304265dfa 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -114,7 +114,7 @@ fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span, cx.expr_try(span, cx.expr_method_call(span, blkdecoder.clone(), read_struct_field, vec!(cx.expr_str(span, name), - cx.expr_uint(span, field), + cx.expr_usize(span, field), exprdecode.clone()))) }); let result = cx.expr_ok(trait_span, result); @@ -123,7 +123,7 @@ fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span, cx.ident_of("read_struct"), vec!( cx.expr_str(trait_span, token::get_ident(substr.type_ident)), - cx.expr_uint(trait_span, nfields), + cx.expr_usize(trait_span, nfields), cx.lambda_expr_1(trait_span, result, blkarg) )) } @@ -143,14 +143,14 @@ fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span, path, parts, |cx, span, _, field| { - let idx = cx.expr_uint(span, field); + let idx = cx.expr_usize(span, field); cx.expr_try(span, cx.expr_method_call(span, blkdecoder.clone(), rvariant_arg, vec!(idx, exprdecode.clone()))) }); arms.push(cx.arm(v_span, - vec!(cx.pat_lit(v_span, cx.expr_uint(v_span, i))), + vec!(cx.pat_lit(v_span, cx.expr_usize(v_span, i))), decoded)); } diff --git a/src/libsyntax/ext/deriving/default.rs b/src/libsyntax/ext/deriving/default.rs index 047c4fef3c4..f22e02d7b8d 100644 --- a/src/libsyntax/ext/deriving/default.rs +++ b/src/libsyntax/ext/deriving/default.rs @@ -79,7 +79,7 @@ fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructur StaticEnum(..) => { cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs"); // let compilation continue - cx.expr_uint(trait_span, 0) + cx.expr_usize(trait_span, 0) } _ => cx.span_bug(trait_span, "Non-static method in `deriving(Default)`") }; diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index 496aec556f1..3189a39160e 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -27,7 +27,7 @@ //! s.emit_struct("Node", 1, |this| { //! this.emit_struct_field("id", 0, |this| { //! Encodable::encode(&self.id, this) -//! /* this.emit_uint(self.id) can also be used */ +//! /* this.emit_usize(self.id) can also be used */ //! }) //! }) //! } @@ -192,7 +192,7 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span, let call = cx.expr_method_call(span, blkencoder.clone(), emit_struct_field, vec!(cx.expr_str(span, name), - cx.expr_uint(span, i), + cx.expr_usize(span, i), lambda)); // last call doesn't need a try! @@ -218,7 +218,7 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span, cx.ident_of("emit_struct"), vec!( cx.expr_str(trait_span, token::get_ident(substr.type_ident)), - cx.expr_uint(trait_span, fields.len()), + cx.expr_usize(trait_span, fields.len()), blk )) } @@ -239,7 +239,7 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span, let lambda = cx.lambda_expr_1(span, enc, blkarg); let call = cx.expr_method_call(span, blkencoder.clone(), emit_variant_arg, - vec!(cx.expr_uint(span, i), + vec!(cx.expr_usize(span, i), lambda)); let call = if i != last { cx.expr_try(span, call) @@ -262,8 +262,8 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span, let call = cx.expr_method_call(trait_span, blkencoder, cx.ident_of("emit_enum_variant"), vec!(name, - cx.expr_uint(trait_span, idx), - cx.expr_uint(trait_span, fields.len()), + cx.expr_usize(trait_span, idx), + cx.expr_usize(trait_span, fields.len()), blk)); let blk = cx.lambda_expr_1(trait_span, call, blkarg); let ret = cx.expr_method_call(trait_span, diff --git a/src/libsyntax/ext/deriving/hash.rs b/src/libsyntax/ext/deriving/hash.rs index 08336be87d1..8dac864c2ae 100644 --- a/src/libsyntax/ext/deriving/hash.rs +++ b/src/libsyntax/ext/deriving/hash.rs @@ -89,7 +89,7 @@ fn hash_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) // iteration function. let discriminant = match variant.node.disr_expr { Some(ref d) => d.clone(), - None => cx.expr_uint(trait_span, index) + None => cx.expr_usize(trait_span, index) }; stmts.push(call_hash(trait_span, discriminant)); diff --git a/src/libsyntax/ext/deriving/rand.rs b/src/libsyntax/ext/deriving/rand.rs index 1359cada673..be45a54e710 100644 --- a/src/libsyntax/ext/deriving/rand.rs +++ b/src/libsyntax/ext/deriving/rand.rs @@ -80,10 +80,10 @@ fn rand_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) if variants.is_empty() { cx.span_err(trait_span, "`Rand` cannot be derived for enums with no variants"); // let compilation continue - return cx.expr_uint(trait_span, 0); + return cx.expr_usize(trait_span, 0); } - let variant_count = cx.expr_uint(trait_span, variants.len()); + let variant_count = cx.expr_usize(trait_span, variants.len()); let rand_name = cx.path_all(trait_span, true, @@ -115,7 +115,7 @@ fn rand_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) variant_count); let mut arms = variants.iter().enumerate().map(|(i, &(ident, v_span, ref summary))| { - let i_expr = cx.expr_uint(v_span, i); + let i_expr = cx.expr_usize(v_span, i); let pat = cx.pat_lit(v_span, i_expr); let path = cx.path(v_span, vec![substr.type_ident, ident]); diff --git a/src/libsyntax/ext/env.rs b/src/libsyntax/ext/env.rs index 9b54e259761..9f6bf352b04 100644 --- a/src/libsyntax/ext/env.rs +++ b/src/libsyntax/ext/env.rs @@ -104,7 +104,7 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let e = match os::getenv(var.get()) { None => { cx.span_err(sp, msg.get()); - cx.expr_uint(sp, 0) + cx.expr_usize(sp, 0) } Some(s) => cx.expr_str(sp, token::intern_and_get_ident(&s[])) }; diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index 684ae84872b..068c7ec0867 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -326,11 +326,11 @@ fn trans_count(&self, c: parse::Count) -> P { match c { parse::CountIs(i) => { self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "CountIs"), - vec!(self.ecx.expr_uint(sp, i))) + vec!(self.ecx.expr_usize(sp, i))) } parse::CountIsParam(i) => { self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "CountIsParam"), - vec!(self.ecx.expr_uint(sp, i))) + vec!(self.ecx.expr_usize(sp, i))) } parse::CountImplied => { let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, @@ -349,7 +349,7 @@ fn trans_count(&self, c: parse::Count) -> P { }; let i = i + self.args.len(); self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "CountIsParam"), - vec!(self.ecx.expr_uint(sp, i))) + vec!(self.ecx.expr_usize(sp, i))) } } } @@ -382,7 +382,7 @@ fn trans_piece(&mut self, piece: &parse::Piece) -> Option> { } parse::ArgumentIs(i) => { self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "ArgumentIs"), - vec!(self.ecx.expr_uint(sp, i))) + vec!(self.ecx.expr_usize(sp, i))) } // Named arguments are converted to positional arguments at // the end of the list of arguments @@ -393,7 +393,7 @@ fn trans_piece(&mut self, piece: &parse::Piece) -> Option> { }; let i = i + self.args.len(); self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "ArgumentIs"), - vec!(self.ecx.expr_uint(sp, i))) + vec!(self.ecx.expr_usize(sp, i))) } }; @@ -432,7 +432,7 @@ fn trans_piece(&mut self, piece: &parse::Piece) -> Option> { } }; let align = self.ecx.expr_path(align); - let flags = self.ecx.expr_uint(sp, arg.format.flags); + let flags = self.ecx.expr_usize(sp, arg.format.flags); let prec = self.trans_count(arg.format.precision); let width = self.trans_count(arg.format.width); let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "FormatSpec")); diff --git a/src/libsyntax/ext/mtwt.rs b/src/libsyntax/ext/mtwt.rs index 9bcb026a550..7adc443759f 100644 --- a/src/libsyntax/ext/mtwt.rs +++ b/src/libsyntax/ext/mtwt.rs @@ -398,7 +398,7 @@ fn test_marksof () { assert_eq! (marksof_internal (ans, stopname,&t), vec!(16));} // rename where stop doesn't match: { let chain = vec!(M(9), - R(id(name1.uint() as u32, + R(id(name1.usize() as u32, apply_mark_internal (4, EMPTY_CTXT,&mut t)), Name(100101102)), M(14)); @@ -407,7 +407,7 @@ fn test_marksof () { // rename where stop does match { let name1sc = apply_mark_internal(4, EMPTY_CTXT, &mut t); let chain = vec!(M(9), - R(id(name1.uint() as u32, name1sc), + R(id(name1.usize() as u32, name1sc), stopname), M(14)); let ans = unfold_test_sc(chain,EMPTY_CTXT,&mut t); diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index c42b188302c..a5885ac6c5d 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -588,7 +588,7 @@ macro_rules! mk_lit { } token::Literal(token::StrRaw(ident, n), suf) => { - return mk_lit!("StrRaw", suf, mk_name(cx, sp, ident.ident()), cx.expr_uint(sp, n)) + return mk_lit!("StrRaw", suf, mk_name(cx, sp, ident.ident()), cx.expr_usize(sp, n)) } token::Ident(ident, style) => { diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 31a1a838b13..a74adbf4085 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -35,7 +35,7 @@ pub fn expand_line(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let topmost = cx.original_span_in_file(); let loc = cx.codemap().lookup_char_pos(topmost.lo); - base::MacExpr::new(cx.expr_uint(topmost, loc.line)) + base::MacExpr::new(cx.expr_usize(topmost, loc.line)) } /* column!(): expands to the current column number */ @@ -45,7 +45,7 @@ pub fn expand_column(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let topmost = cx.original_span_in_file(); let loc = cx.codemap().lookup_char_pos(topmost.lo); - base::MacExpr::new(cx.expr_uint(topmost, loc.col.to_uint())) + base::MacExpr::new(cx.expr_usize(topmost, loc.col.to_usize())) } /// file!(): expands to the current filename */ diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index cae0cf904f6..1649075fd71 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -174,8 +174,8 @@ fn fold_ident(&mut self, i: Ident) -> Ident { noop_fold_ident(i, self) } - fn fold_uint(&mut self, i: usize) -> usize { - noop_fold_uint(i, self) + fn fold_usize(&mut self, i: usize) -> usize { + noop_fold_usize(i, self) } fn fold_path(&mut self, p: Path) -> Path { @@ -505,7 +505,7 @@ pub fn noop_fold_ident(i: Ident, _: &mut T) -> Ident { i } -pub fn noop_fold_uint(i: usize, _: &mut T) -> usize { +pub fn noop_fold_usize(i: usize, _: &mut T) -> usize { i } @@ -1377,7 +1377,7 @@ pub fn noop_fold_expr(Expr {id, node, span}: Expr, folder: &mut T) -> } ExprTupField(el, ident) => { ExprTupField(folder.fold_expr(el), - respan(ident.span, folder.fold_uint(ident.node))) + respan(ident.span, folder.fold_usize(ident.node))) } ExprIndex(el, er) => { ExprIndex(folder.fold_expr(el), folder.fold_expr(er)) diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index 59a3c3bcb3e..d710c6d6c0f 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -208,7 +208,7 @@ fn read_line_comments(rdr: &mut StringReader, code_to_the_left: bool, /// whitespace. Note k may be outside bounds of s. fn all_whitespace(s: &str, col: CharPos) -> Option { let len = s.len(); - let mut col = col.to_uint(); + let mut col = col.to_usize(); let mut cursor: usize = 0; while col > 0 && cursor < len { let r: str::CharRange = s.char_range_at(cursor); diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index cd159f7c599..dfb0230cf34 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -212,8 +212,8 @@ fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) { /// offending string to the error message fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> ! { m.push_str(": "); - let from = self.byte_offset(from_pos).to_uint(); - let to = self.byte_offset(to_pos).to_uint(); + let from = self.byte_offset(from_pos).to_usize(); + let to = self.byte_offset(to_pos).to_usize(); m.push_str(&self.filemap.src[from..to]); self.fatal_span_(from_pos, to_pos, &m[]); } @@ -272,8 +272,8 @@ fn with_str_from_to(&self, start: BytePos, end: BytePos, f: F) -> T where F: FnOnce(&str) -> T, { f(self.filemap.src.slice( - self.byte_offset(start).to_uint(), - self.byte_offset(end).to_uint())) + self.byte_offset(start).to_usize(), + self.byte_offset(end).to_usize())) } /// Converts CRLF to LF in the given string, raising an error on bare CR. @@ -321,7 +321,7 @@ fn translate_crlf_(rdr: &StringReader, start: BytePos, /// discovered, add it to the FileMap's list of line start offsets. pub fn bump(&mut self) { self.last_pos = self.pos; - let current_byte_offset = self.byte_offset(self.pos).to_uint(); + let current_byte_offset = self.byte_offset(self.pos).to_usize(); if current_byte_offset < self.filemap.src.len() { assert!(self.curr.is_some()); let last_char = self.curr.unwrap(); @@ -329,7 +329,7 @@ pub fn bump(&mut self) { .src .char_range_at(current_byte_offset); let byte_offset_diff = next.next - current_byte_offset; - self.pos = self.pos + Pos::from_uint(byte_offset_diff); + self.pos = self.pos + Pos::from_usize(byte_offset_diff); self.curr = Some(next.ch); self.col = self.col + CharPos(1u); if last_char == '\n' { @@ -346,7 +346,7 @@ pub fn bump(&mut self) { } pub fn nextch(&self) -> Option { - let offset = self.byte_offset(self.pos).to_uint(); + let offset = self.byte_offset(self.pos).to_usize(); if offset < self.filemap.src.len() { Some(self.filemap.src.char_at(offset)) } else { @@ -359,7 +359,7 @@ pub fn nextch_is(&self, c: char) -> bool { } pub fn nextnextch(&self) -> Option { - let offset = self.byte_offset(self.pos).to_uint(); + let offset = self.byte_offset(self.pos).to_usize(); let s = self.filemap.src.as_slice(); if offset >= s.len() { return None } let str::CharRange { next, .. } = s.char_range_at(offset); diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 7bde32326fa..1a29766cee6 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -1171,9 +1171,9 @@ fn visit_pat(&mut self, p: &'v ast::Pat) { for &src in srcs.iter() { let spans = get_spans_of_pat_idents(src); let Span{ lo, hi, .. } = spans[0]; - assert!("self" == &src[lo.to_uint()..hi.to_uint()], + assert!("self" == &src[lo.to_usize()..hi.to_usize()], "\"{}\" != \"self\". src=\"{}\"", - &src[lo.to_uint()..hi.to_uint()], src) + &src[lo.to_usize()..hi.to_usize()], src) } } diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index aeb9599923e..08d0e5e997c 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -757,7 +757,7 @@ pub fn fresh_name(src: &ast::Ident) -> ast::Name { // create a fresh mark. pub fn fresh_mark() -> ast::Mrk { - gensym("mark").uint() as u32 + gensym("mark").usize() as u32 } #[cfg(test)] diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 2583c302293..83ac8432f98 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1789,7 +1789,7 @@ pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> { ast::ExprTupField(ref expr, id) => { try!(self.print_expr(&**expr)); try!(word(&mut self.s, ".")); - try!(self.print_uint(id.node)); + try!(self.print_usize(id.node)); } ast::ExprIndex(ref expr, ref index) => { try!(self.print_expr(&**expr)); @@ -1951,7 +1951,7 @@ pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> { self.ann.post(self, NodeIdent(&ident)) } - pub fn print_uint(&mut self, i: usize) -> IoResult<()> { + pub fn print_usize(&mut self, i: usize) -> IoResult<()> { word(&mut self.s, &i.to_string()[]) } diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 757bafaf5cb..66b225f30dd 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -70,7 +70,7 @@ pub fn gensym(&self, val: T) -> Name { pub fn get(&self, idx: Name) -> T { let vect = self.vect.borrow(); - (*vect)[idx.uint()].clone() + (*vect)[idx.usize()].clone() } pub fn len(&self) -> usize { @@ -190,13 +190,13 @@ pub fn gensym_copy(&self, idx : Name) -> Name { let new_idx = Name(self.len() as u32); // leave out of map to avoid colliding let mut vect = self.vect.borrow_mut(); - let existing = (*vect)[idx.uint()].clone(); + let existing = (*vect)[idx.usize()].clone(); vect.push(existing); new_idx } pub fn get(&self, idx: Name) -> RcStr { - (*self.vect.borrow())[idx.uint()].clone() + (*self.vect.borrow())[idx.usize()].clone() } pub fn len(&self) -> usize { diff --git a/src/test/auxiliary/roman_numerals.rs b/src/test/auxiliary/roman_numerals.rs index 519f32fc248..a4edc607279 100644 --- a/src/test/auxiliary/roman_numerals.rs +++ b/src/test/auxiliary/roman_numerals.rs @@ -20,7 +20,7 @@ use syntax::parse::token; use syntax::ast::{TokenTree, TtToken}; use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacExpr}; -use syntax::ext::build::AstBuilder; // trait for expr_uint +use syntax::ext::build::AstBuilder; // trait for expr_usize use rustc::plugin::Registry; // WARNING WARNING WARNING WARNING WARNING @@ -61,7 +61,7 @@ fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree]) } } - MacExpr::new(cx.expr_uint(sp, total)) + MacExpr::new(cx.expr_usize(sp, total)) } #[plugin_registrar] From 7b4c50821a62bd6cd0df6810cd07db363bd003ac Mon Sep 17 00:00:00 2001 From: Tom Jakubowski Date: Wed, 14 Jan 2015 05:51:56 -0800 Subject: [PATCH 10/96] rustdoc: Add Show impls to more clean types --- src/librustdoc/clean/mod.rs | 58 ++++++++++++++++++------------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 8dc3adad3b2..c3cd81d3a95 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -116,7 +116,7 @@ fn clean(&self, cx: &DocContext) -> Vec { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct Crate { pub name: String, pub src: FsPath, @@ -198,7 +198,7 @@ fn clean(&self, cx: &DocContext) -> Crate { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct ExternalCrate { pub name: String, pub attrs: Vec, @@ -231,7 +231,7 @@ fn clean(&self, cx: &DocContext) -> ExternalCrate { /// Anything with a source location and set of attributes and, optionally, a /// name. That is, anything that can be documented. This doesn't correspond /// directly to the AST's concept of an item; it's a strict superset. -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct Item { /// Stringified span pub source: Span, @@ -307,7 +307,7 @@ pub fn is_fn(&self) -> bool { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub enum ItemEnum { StructItem(Struct), EnumItem(Enum), @@ -336,7 +336,7 @@ pub enum ItemEnum { AssociatedTypeItem(TyParam), } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct Module { pub items: Vec, pub is_crate: bool, @@ -938,7 +938,7 @@ fn has_sized_bound(bounds: &[TyParamBound], cx: &DocContext) -> bool { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct Method { pub generics: Generics, pub self_: SelfTy, @@ -977,7 +977,7 @@ fn clean(&self, cx: &DocContext) -> Item { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct TyMethod { pub unsafety: ast::Unsafety, pub decl: FnDecl, @@ -1015,7 +1015,7 @@ fn clean(&self, cx: &DocContext) -> Item { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub enum SelfTy { SelfStatic, SelfValue, @@ -1036,7 +1036,7 @@ fn clean(&self, cx: &DocContext) -> SelfTy { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct Function { pub decl: FnDecl, pub generics: Generics, @@ -1153,7 +1153,7 @@ fn clean(&self, cx: &DocContext) -> FunctionRetTy { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct Trait { pub unsafety: ast::Unsafety, pub items: Vec, @@ -1197,11 +1197,11 @@ fn clean(&self, cx: &DocContext) -> PolyTrait { /// An item belonging to a trait, whether a method or associated. Could be named /// TraitItem except that's already taken by an exported enum variant. -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub enum TraitMethod { RequiredMethod(Item), ProvidedMethod(Item), - TypeTraitItem(Item), + TypeTraitItem(Item), // an associated type } impl TraitMethod { @@ -1242,7 +1242,7 @@ fn clean(&self, cx: &DocContext) -> TraitMethod { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub enum ImplMethod { MethodImplItem(Item), TypeImplItem(Item), @@ -1378,7 +1378,7 @@ pub enum PrimitiveType { PrimitiveTuple, } -#[derive(Clone, RustcEncodable, RustcDecodable, Copy)] +#[derive(Clone, RustcEncodable, RustcDecodable, Copy, Show)] pub enum TypeKind { TypeEnum, TypeFunction, @@ -1621,7 +1621,7 @@ fn clean(&self, cx: &DocContext) -> Type { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub enum StructField { HiddenStructField, // inserted later by strip passes TypedStructField(Type), @@ -1680,7 +1680,7 @@ fn clean(&self, _: &DocContext) -> Option { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct Struct { pub struct_type: doctree::StructType, pub generics: Generics, @@ -1710,7 +1710,7 @@ fn clean(&self, cx: &DocContext) -> Item { /// This is a more limited form of the standard Struct, different in that /// it lacks the things most items have (name, id, parameterization). Found /// only as a variant in an enum. -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct VariantStruct { pub struct_type: doctree::StructType, pub fields: Vec, @@ -1727,7 +1727,7 @@ fn clean(&self, cx: &DocContext) -> VariantStruct { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct Enum { pub variants: Vec, pub generics: Generics, @@ -1752,7 +1752,7 @@ fn clean(&self, cx: &DocContext) -> Item { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct Variant { pub kind: VariantKind, } @@ -1820,7 +1820,7 @@ fn clean(&self, cx: &DocContext) -> Item { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub enum VariantKind { CLikeVariant, TupleVariant(Vec), @@ -1967,7 +1967,7 @@ fn clean(&self, _: &DocContext) -> String { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct Typedef { pub type_: Type, pub generics: Generics, @@ -2080,7 +2080,7 @@ fn clean(&self, _: &DocContext) -> Mutability { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct Impl { pub generics: Generics, pub trait_: Option, @@ -2118,7 +2118,7 @@ fn clean(&self, cx: &DocContext) -> Item { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct ViewItem { pub inner: ViewItemInner, } @@ -2184,7 +2184,7 @@ fn clean(&self, cx: &DocContext) -> Vec { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub enum ViewItemInner { ExternCrate(String, Option, ast::NodeId), Import(ViewPath) @@ -2207,7 +2207,7 @@ fn clean(&self, cx: &DocContext) -> ViewItemInner { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub enum ViewPath { // use source as str; SimpleImport(String, ImportSource), @@ -2217,7 +2217,7 @@ pub enum ViewPath { ImportList(ImportSource, Vec), } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct ImportSource { pub path: Path, pub did: Option, @@ -2238,7 +2238,7 @@ fn clean(&self, cx: &DocContext) -> ViewPath { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct ViewListIdent { pub name: String, pub source: Option, @@ -2457,7 +2457,7 @@ fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option { }) } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct Macro { pub source: String, } @@ -2478,7 +2478,7 @@ fn clean(&self, cx: &DocContext) -> Item { } } -#[derive(Clone, RustcEncodable, RustcDecodable)] +#[derive(Clone, RustcEncodable, RustcDecodable, Show)] pub struct Stability { pub level: attr::StabilityLevel, pub text: String From d47a11353d2c254d4644b998b81779887e525bee Mon Sep 17 00:00:00 2001 From: Tom Jakubowski Date: Wed, 14 Jan 2015 06:32:43 -0800 Subject: [PATCH 11/96] Remove some dead code from rustc::middle::ty --- src/librustc/middle/ty.rs | 21 +-------------------- 1 file changed, 1 insertion(+), 20 deletions(-) diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index c72fbc74565..e3b57b78190 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -70,7 +70,7 @@ use arena::TypedArena; use std::borrow::{BorrowFrom, Cow}; use std::cell::{Cell, RefCell}; -use std::cmp::{self, Ordering}; +use std::cmp; use std::fmt::{self, Show}; use std::hash::{Hash, Writer, SipHasher, Hasher}; use std::mem; @@ -5096,25 +5096,6 @@ pub fn associated_type_parameter_index(cx: &ctxt, cx.sess.bug("couldn't find associated type parameter index") } -#[derive(Copy, PartialEq, Eq)] -pub struct AssociatedTypeInfo { - pub def_id: ast::DefId, - pub index: uint, - pub name: ast::Name, -} - -impl PartialOrd for AssociatedTypeInfo { - fn partial_cmp(&self, other: &AssociatedTypeInfo) -> Option { - Some(self.index.cmp(&other.index)) - } -} - -impl Ord for AssociatedTypeInfo { - fn cmp(&self, other: &AssociatedTypeInfo) -> Ordering { - self.index.cmp(&other.index) - } -} - pub fn trait_item_def_ids(cx: &ctxt, id: ast::DefId) -> Rc> { lookup_locally_or_in_crate_store("trait_item_def_ids", From aaf595eab9e57c7c2f301fb0e4054a03df23324d Mon Sep 17 00:00:00 2001 From: Tom Jakubowski Date: Wed, 14 Jan 2015 07:28:37 -0800 Subject: [PATCH 12/96] rustdoc: Separate associated types from methods Fix #21142 --- src/librustdoc/clean/inline.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index ccaefadc1fc..432748b40e4 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -147,14 +147,22 @@ pub fn record_extern_fqn(cx: &DocContext, did: ast::DefId, kind: clean::TypeKind pub fn build_external_trait(cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId) -> clean::Trait { + use clean::TraitMethod; + let def = ty::lookup_trait_def(tcx, did); let trait_items = ty::trait_items(tcx, did).clean(cx); let provided = ty::provided_trait_methods(tcx, did); let items = trait_items.into_iter().map(|trait_item| { - if provided.iter().any(|a| a.def_id == trait_item.def_id) { - clean::ProvidedMethod(trait_item) - } else { - clean::RequiredMethod(trait_item) + match trait_item.inner { + clean::TyMethodItem(_) => { + if provided.iter().any(|a| a.def_id == trait_item.def_id) { + TraitMethod::ProvidedMethod(trait_item) + } else { + TraitMethod::RequiredMethod(trait_item) + } + }, + clean::AssociatedTypeItem(_) => TraitMethod::TypeTraitItem(trait_item), + _ => unreachable!() } }); let trait_def = ty::lookup_trait_def(tcx, did); From e930aeb32b82181e3941c1c9f149057ac3a56537 Mon Sep 17 00:00:00 2001 From: Tom Jakubowski Date: Sat, 17 Jan 2015 21:02:31 -0800 Subject: [PATCH 13/96] rustdoc: Accept string source in core::run_core This is wanted by external tooling that uses rustdoc. There are likely some bugs when actually generating HTML output (which may expect to be able to read the source) but all I need for now is the cleaned crate and analysis. --- src/librustdoc/clean/mod.rs | 14 ++++++++++---- src/librustdoc/core.rs | 16 +++++++++------- src/librustdoc/lib.rs | 4 +++- src/librustdoc/test.rs | 2 +- 4 files changed, 23 insertions(+), 13 deletions(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index c3cd81d3a95..a522cbf72fa 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -45,7 +45,6 @@ use rustc::middle::subst::{self, ParamSpace, VecPerParamSpace}; use rustc::middle::ty; use rustc::middle::stability; -use rustc::session::config; use std::rc::Rc; use std::u32; @@ -127,6 +126,8 @@ pub struct Crate { impl<'a, 'tcx> Clean for visit_ast::RustdocVisitor<'a, 'tcx> { fn clean(&self, cx: &DocContext) -> Crate { + use rustc::session::config::Input; + let mut externs = Vec::new(); cx.sess().cstore.iter_crate_data(|n, meta| { externs.push((n, meta.clean(cx))); @@ -134,8 +135,8 @@ fn clean(&self, cx: &DocContext) -> Crate { externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b)); // Figure out the name of this crate - let input = config::Input::File(cx.src.clone()); - let name = link::find_crate_name(None, self.attrs.as_slice(), &input); + let input = &cx.input; + let name = link::find_crate_name(None, self.attrs.as_slice(), input); // Clean the crate, translating the entire libsyntax AST to one that is // understood by rustdoc. @@ -188,9 +189,14 @@ fn clean(&self, cx: &DocContext) -> Crate { m.items.extend(tmp.into_iter()); } + let src = match cx.input { + Input::File(ref path) => path.clone(), + Input::Str(_) => FsPath::new("") // FIXME: this is wrong + }; + Crate { name: name.to_string(), - src: cx.src.clone(), + src: src, module: Some(module), externs: externs, primitives: primitives, diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 5bef0195874..437ff666497 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -11,7 +11,7 @@ use rustc_driver::driver; use rustc::session::{self, config}; -use rustc::session::config::UnstableFeatures; +use rustc::session::config::{Input, UnstableFeatures}; use rustc::session::search_paths::SearchPaths; use rustc::middle::{privacy, ty}; use rustc::lint; @@ -39,7 +39,7 @@ pub enum MaybeTyped<'tcx> { pub struct DocContext<'tcx> { pub krate: &'tcx ast::Crate, pub maybe_typed: MaybeTyped<'tcx>, - pub src: Path, + pub input: Input, pub external_paths: ExternalPaths, pub external_traits: RefCell>>, pub external_typarams: RefCell>>, @@ -80,12 +80,15 @@ pub struct CrateAnalysis { pub type Externs = HashMap>; pub fn run_core(search_paths: SearchPaths, cfgs: Vec, externs: Externs, - cpath: &Path, triple: Option) + input: Input, triple: Option) -> (clean::Crate, CrateAnalysis) { // Parse, resolve, and typecheck the given crate. - let input = config::Input::File(cpath.clone()); + let cpath = match input { + Input::File(ref p) => Some(p.clone()), + _ => None + }; let warning_lint = lint::builtin::WARNINGS.name_lower(); @@ -107,8 +110,7 @@ pub fn run_core(search_paths: SearchPaths, cfgs: Vec, externs: Externs, let span_diagnostic_handler = diagnostic::mk_span_handler(diagnostic_handler, codemap); - let sess = session::build_session_(sessopts, - Some(cpath.clone()), + let sess = session::build_session_(sessopts, cpath, span_diagnostic_handler); let cfg = config::build_configuration(&sess); @@ -136,7 +138,7 @@ pub fn run_core(search_paths: SearchPaths, cfgs: Vec, externs: Externs, let ctxt = DocContext { krate: ty_cx.map.krate(), maybe_typed: Typed(ty_cx), - src: cpath.clone(), + input: input, external_traits: RefCell::new(Some(HashMap::new())), external_typarams: RefCell::new(Some(HashMap::new())), external_paths: RefCell::new(Some(HashMap::new())), diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index e6eed480633..11135ed436e 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -350,8 +350,10 @@ fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matche info!("starting to run rustc"); let (mut krate, analysis) = std::thread::Thread::scoped(move |:| { + use rustc::session::config::Input; + let cr = cr; - core::run_core(paths, cfgs, externs, &cr, triple) + core::run_core(paths, cfgs, externs, Input::File(cr), triple) }).join().map_err(|_| "rustc failed").unwrap(); info!("finished with rustc"); let mut analysis = Some(analysis); diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 9b8d220acc3..7f1bd9e6d59 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -79,7 +79,7 @@ pub fn run(input: &str, let ctx = core::DocContext { krate: &krate, maybe_typed: core::NotTyped(sess), - src: input_path, + input: input, external_paths: RefCell::new(Some(HashMap::new())), external_traits: RefCell::new(None), external_typarams: RefCell::new(None), From 8224e0ed3d65748df4e3a89a1076ffae629e2acb Mon Sep 17 00:00:00 2001 From: Tom Jakubowski Date: Sat, 17 Jan 2015 21:23:05 -0800 Subject: [PATCH 14/96] rustdoc: Add some re-exports --- src/librustdoc/core.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 437ff666497..04947e41663 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -11,8 +11,7 @@ use rustc_driver::driver; use rustc::session::{self, config}; -use rustc::session::config::{Input, UnstableFeatures}; -use rustc::session::search_paths::SearchPaths; +use rustc::session::config::UnstableFeatures; use rustc::middle::{privacy, ty}; use rustc::lint; use rustc_trans::back::link; @@ -27,6 +26,9 @@ use clean; use clean::Clean; +pub use rustc::session::config::Input; +pub use rustc::session::search_paths::SearchPaths; + /// Are we generating documentation (`Typed`) or tests (`NotTyped`)? pub enum MaybeTyped<'tcx> { Typed(ty::ctxt<'tcx>), From 159236a63b64fec9aec6e1d36ee4e1c811747240 Mon Sep 17 00:00:00 2001 From: Tom Jakubowski Date: Sat, 17 Jan 2015 22:39:01 -0800 Subject: [PATCH 15/96] rustdoc: Handle associated types on inlined impls Fix #21348 --- src/librustdoc/clean/inline.rs | 18 +++++++++++++++--- src/librustdoc/clean/mod.rs | 14 ++++++++++++-- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 432748b40e4..21e0fee33dd 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -319,9 +319,21 @@ fn build_impl(cx: &DocContext, tcx: &ty::ctxt, }; Some(item) } - ty::TypeTraitItem(_) => { - // FIXME(pcwalton): Implement. - None + ty::TypeTraitItem(ref assoc_ty) => { + let did = assoc_ty.def_id; + let type_scheme = ty::lookup_item_type(tcx, did); + // Not sure the choice of ParamSpace actually matters here, because an + // associated type won't have generics on the LHS + let typedef = (type_scheme, subst::ParamSpace::TypeSpace).clean(cx); + Some(clean::Item { + name: Some(assoc_ty.name.clean(cx)), + inner: clean::TypedefItem(typedef), + source: clean::Span::empty(), + attrs: vec![], + visibility: None, + stability: stability::lookup(tcx, did).clean(cx), + def_id: did + }) } } }).collect(); diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index a522cbf72fa..0d82efbdbde 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2520,14 +2520,14 @@ fn clean(&self, cx: &DocContext) -> Item { source: DUMMY_SP.clean(cx), name: Some(self.name.clean(cx)), attrs: Vec::new(), - // FIXME(#18048): this is wrong, but cross-crate associated types are broken - // anyway, for the time being. inner: AssociatedTypeItem(TyParam { name: self.name.clean(cx), did: ast::DefId { krate: 0, node: ast::DUMMY_NODE_ID }, + // FIXME(#20727): bounds are missing and need to be filled in from the + // predicates on the trait itself bounds: vec![], default: None, }), @@ -2559,6 +2559,16 @@ fn clean(&self, cx: &DocContext) -> Item { } } +impl<'a> Clean for (ty::TypeScheme<'a>, ParamSpace) { + fn clean(&self, cx: &DocContext) -> Typedef { + let (ref ty_scheme, ps) = *self; + Typedef { + type_: ty_scheme.ty.clean(cx), + generics: (&ty_scheme.generics, ps).clean(cx) + } + } +} + fn lang_struct(cx: &DocContext, did: Option, t: ty::Ty, name: &str, fallback: fn(Box) -> Type) -> Type { From 23a553a30398c856ae7d7179b751024334444296 Mon Sep 17 00:00:00 2001 From: Eduard Burtescu Date: Sun, 18 Jan 2015 13:13:23 +0200 Subject: [PATCH 16/96] Improve the vec![...] macro with UFCS. There are two limitations to the macro that this addresses: 1. the expected type is not propagated, coercions don't trigger 2. references inside element expressions don't outlive the `Vec` Both of these limitations are caused by the block in the macro expansion, previously needed to trigger a coercion from `Box<[T; N]>` to `Box<[T]>`, now possible with UFCS. --- src/libcollections/macros.rs | 16 ++++++++-------- src/test/run-pass/coerce-expect-unsized.rs | 5 +++++ src/test/run-pass/vec-macro-rvalue-scope.rs | 18 ++++++++++++++++++ 3 files changed, 31 insertions(+), 8 deletions(-) create mode 100644 src/test/run-pass/vec-macro-rvalue-scope.rs diff --git a/src/libcollections/macros.rs b/src/libcollections/macros.rs index c078db7d46f..85aedaeb010 100644 --- a/src/libcollections/macros.rs +++ b/src/libcollections/macros.rs @@ -12,13 +12,13 @@ #[macro_export] #[stable] macro_rules! vec { - ($x:expr; $y:expr) => ({ - let xs: $crate::boxed::Box<[_]> = $crate::boxed::Box::new([$x; $y]); - $crate::slice::SliceExt::into_vec(xs) - }); - ($($x:expr),*) => ({ - let xs: $crate::boxed::Box<[_]> = $crate::boxed::Box::new([$($x),*]); - $crate::slice::SliceExt::into_vec(xs) - }); + ($x:expr; $y:expr) => ( + <[_] as $crate::slice::SliceExt>::into_vec( + $crate::boxed::Box::new([$x; $y])) + ); + ($($x:expr),*) => ( + <[_] as $crate::slice::SliceExt>::into_vec( + $crate::boxed::Box::new([$($x),*])) + ); ($($x:expr,)*) => (vec![$($x),*]) } diff --git a/src/test/run-pass/coerce-expect-unsized.rs b/src/test/run-pass/coerce-expect-unsized.rs index f590e6e0728..200d3fd6935 100644 --- a/src/test/run-pass/coerce-expect-unsized.rs +++ b/src/test/run-pass/coerce-expect-unsized.rs @@ -33,4 +33,9 @@ pub fn main() { let _: Box<[int]> = Box::new([1, 2, 3]); let _: Box _> = Box::new(|x| (x as u8)); + + let _: Vec _>> = vec![ + Box::new(|x| (x as u8)), + box |x| (x as i16 as u8), + ]; } diff --git a/src/test/run-pass/vec-macro-rvalue-scope.rs b/src/test/run-pass/vec-macro-rvalue-scope.rs new file mode 100644 index 00000000000..68dedfc6a2e --- /dev/null +++ b/src/test/run-pass/vec-macro-rvalue-scope.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. + +fn one() -> i32 { 1 } + +// Make sure the vec![...] macro doesn't introduce hidden rvalue +// scopes (such as blocks) around the element expressions. +pub fn main() { + assert_eq!(vec![&one(), &one(), &2], vec![&1, &1, &(one()+one())]); + assert_eq!(vec![&one(); 2], vec![&1, &one()]); +} From f7fe249bbcdd5f3b3f8b35d33ee3cc6ec422ce95 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Sun, 18 Jan 2015 11:28:17 -0500 Subject: [PATCH 17/96] Remove associated_types gate from std::ops docs --- src/libcore/ops.rs | 30 ------------------------------ 1 file changed, 30 deletions(-) diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index db7177e26fa..431447b3b4a 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -25,8 +25,6 @@ //! demonstrates adding and subtracting two `Point`s. //! //! ```rust -//! #![feature(associated_types)] -//! //! use std::ops::{Add, Sub}; //! //! #[derive(Show)] @@ -104,8 +102,6 @@ pub trait Drop { /// calling `add`, and therefore, `main` prints `Adding!`. /// /// ```rust -/// #![feature(associated_types)] -/// /// use std::ops::Add; /// /// #[derive(Copy)] @@ -157,8 +153,6 @@ fn add(self, other: $t) -> $t { self + other } /// calling `sub`, and therefore, `main` prints `Subtracting!`. /// /// ```rust -/// #![feature(associated_types)] -/// /// use std::ops::Sub; /// /// #[derive(Copy)] @@ -210,8 +204,6 @@ fn sub(self, other: $t) -> $t { self - other } /// calling `mul`, and therefore, `main` prints `Multiplying!`. /// /// ```rust -/// #![feature(associated_types)] -/// /// use std::ops::Mul; /// /// #[derive(Copy)] @@ -263,8 +255,6 @@ fn mul(self, other: $t) -> $t { self * other } /// calling `div`, and therefore, `main` prints `Dividing!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Div; /// /// #[derive(Copy)] @@ -316,8 +306,6 @@ fn div(self, other: $t) -> $t { self / other } /// calling `rem`, and therefore, `main` prints `Remainder-ing!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Rem; /// /// #[derive(Copy)] @@ -386,8 +374,6 @@ fn rem(self, other: $t) -> $t { /// `neg`, and therefore, `main` prints `Negating!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Neg; /// /// struct Foo; @@ -461,8 +447,6 @@ fn neg(self) -> $t { -(self as $t_signed) as $t } /// `not`, and therefore, `main` prints `Not-ing!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Not; /// /// struct Foo; @@ -515,8 +499,6 @@ fn not(self) -> $t { !self } /// calling `bitand`, and therefore, `main` prints `Bitwise And-ing!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::BitAnd; /// /// #[derive(Copy)] @@ -568,8 +550,6 @@ fn bitand(self, rhs: $t) -> $t { self & rhs } /// calling `bitor`, and therefore, `main` prints `Bitwise Or-ing!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::BitOr; /// /// #[derive(Copy)] @@ -621,8 +601,6 @@ fn bitor(self, rhs: $t) -> $t { self | rhs } /// calling `bitxor`, and therefore, `main` prints `Bitwise Xor-ing!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::BitXor; /// /// #[derive(Copy)] @@ -674,8 +652,6 @@ fn bitxor(self, other: $t) -> $t { self ^ other } /// calling `shl`, and therefore, `main` prints `Shifting left!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Shl; /// /// #[derive(Copy)] @@ -745,8 +721,6 @@ macro_rules! shl_impl_all { /// calling `shr`, and therefore, `main` prints `Shifting right!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Shr; /// /// #[derive(Copy)] @@ -1006,8 +980,6 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { /// struct. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Deref; /// /// struct DerefExample { @@ -1061,8 +1033,6 @@ fn deref(&self) -> &T { *self } /// struct. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::{Deref, DerefMut}; /// /// struct DerefMutExample { From e3d099de6f46616ac5c0eea957ceebfa50419c6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adolfo=20Ochagav=C3=ADa?= Date: Sun, 18 Jan 2015 17:18:29 +0100 Subject: [PATCH 18/96] Fix #21356 --- src/libsyntax/ext/tt/macro_rules.rs | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index fc341e3bd85..957e59cbcdd 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -8,8 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use ast::{TokenTree, TtDelimited, TtSequence, TtToken}; -use ast; +use ast::{self, TokenTree, TtDelimited, TtSequence, TtToken}; use codemap::{Span, DUMMY_SP}; use ext::base::{ExtCtxt, MacResult, SyntaxExtension}; use ext::base::{NormalTT, TTMacroExpander}; @@ -19,9 +18,8 @@ use parse::lexer::{new_tt_reader, new_tt_reader_with_doc_flag}; use parse::parser::Parser; use parse::attr::ParserAttr; -use parse::token::{special_idents, gensym_ident, NtTT, Token}; +use parse::token::{self, special_idents, gensym_ident, NtTT, Token}; use parse::token::Token::*; -use parse::token; use print; use ptr::P; @@ -333,16 +331,20 @@ fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token) let tok = if let TtToken(_, ref tok) = *token { tok } else { unreachable!() }; // If T' is in the set FOLLOW(NT), continue. Else, reject. - match &next_token { - &Eof => return Some((sp, tok.clone())), - _ if is_in_follow(cx, &next_token, frag_spec.as_str()) => continue, - next => { + match (&next_token, is_in_follow(cx, &next_token, frag_spec.as_str())) { + (&Eof, _) => return Some((sp, tok.clone())), + (_, Ok(true)) => continue, + (next, Ok(false)) => { cx.span_err(sp, format!("`${0}:{1}` is followed by `{2}`, which \ is not allowed for `{1}` fragments", name.as_str(), frag_spec.as_str(), token_to_string(next)).as_slice()); continue }, + (_, Err(msg)) => { + cx.span_err(sp, msg.as_slice()); + continue + } } }, TtSequence(sp, ref seq) => { @@ -409,12 +411,12 @@ fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token) last } -fn is_in_follow(cx: &ExtCtxt, tok: &Token, frag: &str) -> bool { +fn is_in_follow(_: &ExtCtxt, tok: &Token, frag: &str) -> Result { if let &CloseDelim(_) = tok { - return true; + return Ok(true); } - match frag { + Ok(match frag { "item" => { // since items *must* be followed by either a `;` or a `}`, we can // accept anything after them @@ -453,7 +455,6 @@ fn is_in_follow(cx: &ExtCtxt, tok: &Token, frag: &str) -> bool { // harmless true }, - _ => cx.bug(format!("unrecognized builtin nonterminal {}", - frag).as_slice()), - } + _ => return Err(format!("unrecognized builtin nonterminal `{}`", frag)), + }) } From c821e5c915f886f496d877e267f5a83a7096501f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adolfo=20Ochagav=C3=ADa?= Date: Sun, 18 Jan 2015 17:18:42 +0100 Subject: [PATCH 19/96] Add test for issue #21356 --- src/test/compile-fail/issue-21356.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/test/compile-fail/issue-21356.rs diff --git a/src/test/compile-fail/issue-21356.rs b/src/test/compile-fail/issue-21356.rs new file mode 100644 index 00000000000..979534ab30c --- /dev/null +++ b/src/test/compile-fail/issue-21356.rs @@ -0,0 +1,14 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +macro_rules! test { ($wrong:t_ty ..) => () } + //~^ ERROR: unrecognized builtin nonterminal `t_ty` + +fn main() {} From c034f4a44a4b3d69f4f7f2efeecb5f9742ec0d24 Mon Sep 17 00:00:00 2001 From: Earl St Sauver Date: Fri, 16 Jan 2015 16:54:11 -0800 Subject: [PATCH 20/96] Make date of nightly in rustup match server TZ --- src/etc/rustup.sh | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/etc/rustup.sh b/src/etc/rustup.sh index 749d9eaa173..476d19d0b45 100755 --- a/src/etc/rustup.sh +++ b/src/etc/rustup.sh @@ -433,11 +433,16 @@ CFG_TMP_DIR=$(mktemp -d 2>/dev/null \ || mktemp -d -t 'rustup-tmp-install' 2>/dev/null \ || create_tmp_dir) -# If we're saving nightlies and we didn't specify which one, grab todays. -# Otherwise we'll use the latest version. +# If we're saving nightlies and we didn't specify which one, grab the latest +# verison from the perspective of the server. Buildbot has typically finished +# building and uploading by ~8UTC, but we want to include a little buffer. +# +# FIXME It would be better to use the known most recent nightly that has been +# built. This is waiting on a change to have buildbot publish metadata that +# can be queried. if [ -n "${CFG_SAVE}" -a -z "${CFG_DATE}" ]; then - CFG_DATE=`date "+%Y-%m-%d"` + CFG_DATE=`TZ=Etc/UTC+9 date "+%Y-%m-%d"` fi RUST_URL="https://static.rust-lang.org/dist" From 7a24b3a4d7769ad9a4863a2cc61c009056459a67 Mon Sep 17 00:00:00 2001 From: Paul Collier Date: Sat, 17 Jan 2015 23:55:21 +0000 Subject: [PATCH 21/96] libsyntax: int => i32 in appropriate places --- src/libsyntax/ext/deriving/generic/mod.rs | 26 ++++++------- src/libsyntax/ext/deriving/generic/ty.rs | 4 +- src/libsyntax/ext/expand.rs | 46 +++++++++++------------ src/libsyntax/parse/lexer/comments.rs | 4 +- src/libsyntax/parse/mod.rs | 10 ++--- src/libsyntax/parse/parser.rs | 6 +-- 6 files changed, 48 insertions(+), 48 deletions(-) diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index 27199de0ea8..ca3c1d36fba 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -28,7 +28,7 @@ //! arguments: //! //! - `Struct`, when `Self` is a struct (including tuple structs, e.g -//! `struct T(int, char)`). +//! `struct T(i32, char)`). //! - `EnumMatching`, when `Self` is an enum and all the arguments are the //! same variant of the enum (e.g. `Some(1)`, `Some(3)` and `Some(4)`) //! - `EnumNonMatchingCollapsed` when `Self` is an enum and the arguments @@ -54,17 +54,17 @@ //! following snippet //! //! ```rust -//! struct A { x : int } +//! struct A { x : i32 } //! -//! struct B(int); +//! struct B(i32); //! //! enum C { -//! C0(int), -//! C1 { x: int } +//! C0(i32), +//! C1 { x: i32 } //! } //! ``` //! -//! The `int`s in `B` and `C0` don't have an identifier, so the +//! The `i32`s in `B` and `C0` don't have an identifier, so the //! `Option`s would be `None` for them. //! //! In the static cases, the structure is summarised, either into the just @@ -90,8 +90,8 @@ //! trait PartialEq { //! fn eq(&self, other: &Self); //! } -//! impl PartialEq for int { -//! fn eq(&self, other: &int) -> bool { +//! impl PartialEq for i32 { +//! fn eq(&self, other: &i32) -> bool { //! *self == *other //! } //! } @@ -117,7 +117,7 @@ //! //! ```{.text} //! Struct(vec![FieldInfo { -//! span: , +//! span: , //! name: None, //! self_: //! other: vec![] @@ -132,7 +132,7 @@ //! ```{.text} //! EnumMatching(0, , //! vec![FieldInfo { -//! span: +//! span: //! name: None, //! self_: , //! other: vec![] @@ -179,7 +179,7 @@ //! StaticStruct(, Unnamed(vec![])) //! //! StaticEnum(, -//! vec![(, , Unnamed(vec![])), +//! vec![(, , Unnamed(vec![])), //! (, , Named(vec![(, )]))]) //! ``` @@ -719,7 +719,7 @@ fn create_method(&self, /// ``` /// #[derive(PartialEq)] - /// struct A { x: int, y: int } + /// struct A { x: i32, y: i32 } /// /// // equivalent to: /// impl PartialEq for A { @@ -825,7 +825,7 @@ fn expand_static_struct_method_body(&self, /// #[derive(PartialEq)] /// enum A { /// A1, - /// A2(int) + /// A2(i32) /// } /// /// // is equivalent to diff --git a/src/libsyntax/ext/deriving/generic/ty.rs b/src/libsyntax/ext/deriving/generic/ty.rs index a236fa33eb1..e7634716ed7 100644 --- a/src/libsyntax/ext/deriving/generic/ty.rs +++ b/src/libsyntax/ext/deriving/generic/ty.rs @@ -32,7 +32,7 @@ pub enum PtrTy<'a> { Raw(ast::Mutability), } -/// A path, e.g. `::std::option::Option::` (global). Has support +/// A path, e.g. `::std::option::Option::` (global). Has support /// for type parameters and a lifetime. #[derive(Clone)] pub struct Path<'a> { @@ -91,7 +91,7 @@ pub enum Ty<'a> { /// &/Box/ Ty Ptr(Box>, PtrTy<'a>), /// mod::mod::Type<[lifetime], [Params...]>, including a plain type - /// parameter, and things like `int` + /// parameter, and things like `i32` Literal(Path<'a>), /// includes unit Tuple(Vec> ) diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 1fd0334c016..4f614c1a937 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -1507,7 +1507,7 @@ fn test_ecfg() -> ExpansionConfig { #[should_fail] #[test] fn macros_cant_escape_fns_test () { let src = "fn bogus() {macro_rules! z (() => (3+4));}\ - fn inty() -> int { z!() }".to_string(); + fn inty() -> i32 { z!() }".to_string(); let sess = parse::new_parse_sess(); let crate_ast = parse::parse_crate_from_source_str( "".to_string(), @@ -1521,7 +1521,7 @@ fn test_ecfg() -> ExpansionConfig { #[should_fail] #[test] fn macros_cant_escape_mods_test () { let src = "mod foo {macro_rules! z (() => (3+4));}\ - fn inty() -> int { z!() }".to_string(); + fn inty() -> i32 { z!() }".to_string(); let sess = parse::new_parse_sess(); let crate_ast = parse::parse_crate_from_source_str( "".to_string(), @@ -1533,7 +1533,7 @@ fn test_ecfg() -> ExpansionConfig { // macro_use modules should allow macros to escape #[test] fn macros_can_escape_flattened_mods_test () { let src = "#[macro_use] mod foo {macro_rules! z (() => (3+4));}\ - fn inty() -> int { z!() }".to_string(); + fn inty() -> i32 { z!() }".to_string(); let sess = parse::new_parse_sess(); let crate_ast = parse::parse_crate_from_source_str( "".to_string(), @@ -1564,8 +1564,8 @@ fn crate_bindings(the_crate : &ast::Crate) -> Vec { // should be able to use a bound identifier as a literal in a macro definition: #[test] fn self_macro_parsing(){ expand_crate_str( - "macro_rules! foo ((zz) => (287u;)); - fn f(zz : int) {foo!(zz);}".to_string() + "macro_rules! foo ((zz) => (287;)); + fn f(zz: i32) {foo!(zz);}".to_string() ); } @@ -1601,23 +1601,23 @@ fn crate_bindings(the_crate : &ast::Crate) -> Vec { fn automatic_renaming () { let tests: Vec = vec!(// b & c should get new names throughout, in the expr too: - ("fn a() -> int { let b = 13; let c = b; b+c }", + ("fn a() -> i32 { let b = 13; let c = b; b+c }", vec!(vec!(0,1),vec!(2)), false), // both x's should be renamed (how is this causing a bug?) - ("fn main () {let x: int = 13;x;}", + ("fn main () {let x: i32 = 13;x;}", vec!(vec!(0)), false), // the use of b after the + should be renamed, the other one not: - ("macro_rules! f (($x:ident) => (b + $x)); fn a() -> int { let b = 13; f!(b)}", + ("macro_rules! f (($x:ident) => (b + $x)); fn a() -> i32 { let b = 13; f!(b)}", vec!(vec!(1)), false), // the b before the plus should not be renamed (requires marks) - ("macro_rules! f (($x:ident) => ({let b=9; ($x + b)})); fn a() -> int { f!(b)}", + ("macro_rules! f (($x:ident) => ({let b=9; ($x + b)})); fn a() -> i32 { f!(b)}", vec!(vec!(1)), false), // the marks going in and out of letty should cancel, allowing that $x to // capture the one following the semicolon. // this was an awesome test case, and caught a *lot* of bugs. ("macro_rules! letty(($x:ident) => (let $x = 15;)); macro_rules! user(($x:ident) => ({letty!($x); $x})); - fn main() -> int {user!(z)}", + fn main() -> i32 {user!(z)}", vec!(vec!(0)), false) ); for (idx,s) in tests.iter().enumerate() { @@ -1680,13 +1680,13 @@ fn z() {match 8 {x => bad_macro!(x)}}", // can't write this test case until we have macro-generating macros. // method arg hygiene - // method expands to fn get_x(&self_0, x_1:int) {self_0 + self_2 + x_3 + x_1} + // method expands to fn get_x(&self_0, x_1: i32) {self_0 + self_2 + x_3 + x_1} #[test] fn method_arg_hygiene(){ run_renaming_test( &("macro_rules! inject_x (()=>(x)); macro_rules! inject_self (()=>(self)); struct A; - impl A{fn get_x(&self, x: int) {self + inject_self!() + inject_x!() + x;} }", + impl A{fn get_x(&self, x: i32) {self + inject_self!() + inject_x!() + x;} }", vec!(vec!(0),vec!(3)), true), 0) @@ -1706,21 +1706,21 @@ macro_rules! add_method (($T:ty) => } // item fn hygiene - // expands to fn q(x_1:int){fn g(x_2:int){x_2 + x_1};} + // expands to fn q(x_1: i32){fn g(x_2: i32){x_2 + x_1};} #[test] fn issue_9383(){ run_renaming_test( - &("macro_rules! bad_macro (($ex:expr) => (fn g(x:int){ x + $ex })); - fn q(x:int) { bad_macro!(x); }", + &("macro_rules! bad_macro (($ex:expr) => (fn g(x: i32){ x + $ex })); + fn q(x: i32) { bad_macro!(x); }", vec!(vec!(1),vec!(0)),true), 0) } // closure arg hygiene (ExprClosure) - // expands to fn f(){(|x_1 : int| {(x_2 + x_1)})(3);} + // expands to fn f(){(|x_1 : i32| {(x_2 + x_1)})(3);} #[test] fn closure_arg_hygiene(){ run_renaming_test( &("macro_rules! inject_x (()=>(x)); - fn f(){(|x : int| {(inject_x!() + x)})(3);}", + fn f(){(|x : i32| {(inject_x!() + x)})(3);}", vec!(vec!(1)), true), 0) @@ -1729,7 +1729,7 @@ macro_rules! add_method (($T:ty) => // macro_rules in method position. Sadly, unimplemented. #[test] fn macro_in_method_posn(){ expand_crate_str( - "macro_rules! my_method (() => (fn thirteen(&self) -> int {13})); + "macro_rules! my_method (() => (fn thirteen(&self) -> i32 {13})); struct A; impl A{ my_method!(); } fn f(){A.thirteen;}".to_string()); @@ -1876,7 +1876,7 @@ fn pat_idents(){ // it's the name of a 0-ary variant, and that 'i' appears twice in succession. #[test] fn crate_bindings_test(){ - let the_crate = string_to_crate("fn main (a : int) -> int {|b| { + let the_crate = string_to_crate("fn main (a: i32) -> i32 {|b| { match 34 {None => 3, Some(i) | i => j, Foo{k:z,l:y} => \"banana\"}} }".to_string()); let idents = crate_bindings(&the_crate); assert_eq!(idents, strs_to_idents(vec!("a","b","None","i","i","z","y"))); @@ -1885,10 +1885,10 @@ fn crate_bindings_test(){ // test the IdentRenamer directly #[test] fn ident_renamer_test () { - let the_crate = string_to_crate("fn f(x : int){let x = x; x}".to_string()); + let the_crate = string_to_crate("fn f(x: i32){let x = x; x}".to_string()); let f_ident = token::str_to_ident("f"); let x_ident = token::str_to_ident("x"); - let int_ident = token::str_to_ident("int"); + let int_ident = token::str_to_ident("i32"); let renames = vec!((x_ident,Name(16))); let mut renamer = IdentRenamer{renames: &renames}; let renamed_crate = renamer.fold_crate(the_crate); @@ -1900,10 +1900,10 @@ fn ident_renamer_test () { // test the PatIdentRenamer; only PatIdents get renamed #[test] fn pat_ident_renamer_test () { - let the_crate = string_to_crate("fn f(x : int){let x = x; x}".to_string()); + let the_crate = string_to_crate("fn f(x: i32){let x = x; x}".to_string()); let f_ident = token::str_to_ident("f"); let x_ident = token::str_to_ident("x"); - let int_ident = token::str_to_ident("int"); + let int_ident = token::str_to_ident("i32"); let renames = vec!((x_ident,Name(16))); let mut renamer = PatIdentRenamer{renames: &renames}; let renamed_crate = renamer.fold_crate(the_crate); diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index d710c6d6c0f..58d114fb2a7 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -399,9 +399,9 @@ mod test { } #[test] fn test_block_doc_comment_3() { - let comment = "/**\n let a: *int;\n *a = 5;\n*/"; + let comment = "/**\n let a: *i32;\n *a = 5;\n*/"; let stripped = strip_doc_comment_decoration(comment); - assert_eq!(stripped, " let a: *int;\n *a = 5;"); + assert_eq!(stripped, " let a: *i32;\n *a = 5;"); } #[test] fn test_block_doc_comment_4() { diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 1a29766cee6..33da7c160d9 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -855,7 +855,7 @@ fn string_to_tts_macro () { #[test] fn string_to_tts_1 () { - let tts = string_to_tts("fn a (b : int) { b; }".to_string()); + let tts = string_to_tts("fn a (b : i32) { b; }".to_string()); assert_eq!(json::encode(&tts), "[\ {\ @@ -919,7 +919,7 @@ fn string_to_tts_1 () { {\ \"variant\":\"Ident\",\ \"fields\":[\ - \"int\",\ + \"i32\",\ \"Plain\"\ ]\ }\ @@ -1031,8 +1031,8 @@ fn parser_done(p: Parser){ // check the contents of the tt manually: #[test] fn parse_fundecl () { - // this test depends on the intern order of "fn" and "int" - assert!(string_to_item("fn a (b : int) { b; }".to_string()) == + // this test depends on the intern order of "fn" and "i32" + assert_eq!(string_to_item("fn a (b : i32) { b; }".to_string()), Some( P(ast::Item{ident:str_to_ident("a"), attrs:Vec::new(), @@ -1046,7 +1046,7 @@ fn parser_done(p: Parser){ segments: vec!( ast::PathSegment { identifier: - str_to_ident("int"), + str_to_ident("i32"), parameters: ast::PathParameters::none(), } ), diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 9822dcef0c0..920cfeb3693 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -1499,7 +1499,7 @@ pub fn parse_ty(&mut self) -> P { self.expect(&token::OpenDelim(token::Bracket)); let t = self.parse_ty_sum(); - // Parse the `; e` in `[ int; e ]` + // Parse the `; e` in `[ i32; e ]` // where `e` is a const expression let t = match self.maybe_parse_fixed_length_of_vec() { None => TyVec(t), @@ -4803,7 +4803,7 @@ fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> ItemInfo { Some(attrs)) } - /// Parse a::B + /// Parse a::B fn parse_trait_ref(&mut self) -> TraitRef { ast::TraitRef { path: self.parse_path(LifetimeAndTypesWithoutColons), @@ -4822,7 +4822,7 @@ fn parse_late_bound_lifetime_defs(&mut self) -> Vec { } } - /// Parse for<'l> a::B + /// Parse for<'l> a::B fn parse_poly_trait_ref(&mut self) -> PolyTraitRef { let lifetime_defs = self.parse_late_bound_lifetime_defs(); From 591337431df612dd4e0df8d46b6291358085ac7c Mon Sep 17 00:00:00 2001 From: Paul Collier Date: Sun, 18 Jan 2015 00:18:19 +0000 Subject: [PATCH 22/96] libsyntax: int types -> isize --- src/libsyntax/ext/build.rs | 4 +-- src/libsyntax/parse/lexer/comments.rs | 2 +- src/libsyntax/parse/lexer/mod.rs | 2 +- src/libsyntax/parse/parser.rs | 10 +++--- src/libsyntax/print/pp.rs | 50 +++++++++++++-------------- src/libsyntax/print/pprust.rs | 4 +-- src/libsyntax/util/small_vector.rs | 8 ++--- 7 files changed, 40 insertions(+), 40 deletions(-) diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 3bac972dbb5..8773c0f2f79 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -135,7 +135,7 @@ fn expr_struct_ident(&self, span: Span, id: ast::Ident, fn expr_lit(&self, sp: Span, lit: ast::Lit_) -> P; fn expr_usize(&self, span: Span, i: usize) -> P; - fn expr_int(&self, sp: Span, i: int) -> P; + fn expr_int(&self, sp: Span, i: isize) -> P; fn expr_u8(&self, sp: Span, u: u8) -> P; fn expr_bool(&self, sp: Span, value: bool) -> P; @@ -644,7 +644,7 @@ fn expr_lit(&self, sp: Span, lit: ast::Lit_) -> P { fn expr_usize(&self, span: Span, i: usize) -> P { self.expr_lit(span, ast::LitInt(i as u64, ast::UnsignedIntLit(ast::TyUs(false)))) } - fn expr_int(&self, sp: Span, i: int) -> P { + fn expr_int(&self, sp: Span, i: isize) -> P { self.expr_lit(sp, ast::LitInt(i as u64, ast::SignedIntLit(ast::TyIs(false), ast::Sign::new(i)))) } diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index 58d114fb2a7..ca9091856d6 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -267,7 +267,7 @@ fn read_block_comment(rdr: &mut StringReader, assert!(!curr_line.contains_char('\n')); lines.push(curr_line); } else { - let mut level: int = 1; + let mut level: isize = 1; while level > 0 { debug!("=== block comment level {}", level); if rdr.is_eof() { diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index dfb0230cf34..2fcf43f9ead 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -519,7 +519,7 @@ fn scan_block_comment(&mut self) -> Option { let is_doc_comment = self.curr_is('*') || self.curr_is('!'); let start_bpos = self.last_pos - BytePos(2); - let mut level: int = 1; + let mut level: isize = 1; let mut has_cr = false; while level > 0 { if self.is_eof() { diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 920cfeb3693..88825cb3f34 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -290,8 +290,8 @@ pub struct Parser<'a> { /// the previous token or None (only stashed sometimes). pub last_token: Option>, pub buffer: [TokenAndSpan; 4], - pub buffer_start: int, - pub buffer_end: int, + pub buffer_start: isize, + pub buffer_end: isize, pub tokens_consumed: usize, pub restrictions: Restrictions, pub quote_depth: usize, // not (yet) related to the quasiquoter @@ -934,7 +934,7 @@ pub fn bump(&mut self) { // Avoid token copies with `replace`. let buffer_start = self.buffer_start as usize; let next_index = (buffer_start + 1) & 3 as usize; - self.buffer_start = next_index as int; + self.buffer_start = next_index as isize; let placeholder = TokenAndSpan { tok: token::Underscore, @@ -966,7 +966,7 @@ pub fn replace_token(&mut self, self.token = next; self.span = mk_sp(lo, hi); } - pub fn buffer_length(&mut self) -> int { + pub fn buffer_length(&mut self) -> isize { if self.buffer_start <= self.buffer_end { return self.buffer_end - self.buffer_start; } @@ -975,7 +975,7 @@ pub fn buffer_length(&mut self) -> int { pub fn look_ahead(&mut self, distance: usize, f: F) -> R where F: FnOnce(&token::Token) -> R, { - let dist = distance as int; + let dist = distance as isize; while self.buffer_length() < dist { self.buffer[self.buffer_end as usize] = self.reader.real_token(); self.buffer_end = (self.buffer_end + 1) & 3; diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 0cfc3d38e15..ca99fb2ef89 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -71,19 +71,19 @@ pub enum Breaks { #[derive(Clone, Copy)] pub struct BreakToken { - offset: int, - blank_space: int + offset: isize, + blank_space: isize } #[derive(Clone, Copy)] pub struct BeginToken { - offset: int, + offset: isize, breaks: Breaks } #[derive(Clone)] pub enum Token { - String(String, int), + String(String, isize), Break(BreakToken), Begin(BeginToken), End, @@ -122,7 +122,7 @@ pub fn tok_str(token: &Token) -> String { } pub fn buf_str(toks: &[Token], - szs: &[int], + szs: &[isize], left: usize, right: usize, lim: usize) @@ -155,11 +155,11 @@ pub enum PrintStackBreak { #[derive(Copy)] pub struct PrintStackElem { - offset: int, + offset: isize, pbreak: PrintStackBreak } -static SIZE_INFINITY: int = 0xffff; +static SIZE_INFINITY: isize = 0xffff; pub fn mk_printer(out: Box, linewidth: usize) -> Printer { // Yes 3, it makes the ring buffers big enough to never @@ -167,13 +167,13 @@ pub fn mk_printer(out: Box, linewidth: usize) -> Printer { let n: usize = 3 * linewidth; debug!("mk_printer {}", linewidth); let token: Vec = repeat(Token::Eof).take(n).collect(); - let size: Vec = repeat(0i).take(n).collect(); + let size: Vec = repeat(0i).take(n).collect(); let scan_stack: Vec = repeat(0us).take(n).collect(); Printer { out: out, buf_len: n, - margin: linewidth as int, - space: linewidth as int, + margin: linewidth as isize, + space: linewidth as isize, left: 0, right: 0, token: token, @@ -269,9 +269,9 @@ pub struct Printer { pub out: Box, buf_len: usize, /// Width of lines we're constrained to - margin: int, + margin: isize, /// Number of spaces left on line - space: int, + space: isize, /// Index of left side of input stream left: usize, /// Index of right side of input stream @@ -279,11 +279,11 @@ pub struct Printer { /// Ring-buffer stream goes through token: Vec , /// Ring-buffer of calculated sizes - size: Vec , + size: Vec , /// Running size of stream "...left" - left_total: int, + left_total: isize, /// Running size of stream "...right" - right_total: int, + 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 @@ -300,7 +300,7 @@ pub struct Printer { /// Stack of blocks-in-progress being flushed by print print_stack: Vec , /// Buffered indentation to avoid writing trailing whitespace - pending_indentation: int, + pending_indentation: isize, } impl Printer { @@ -479,7 +479,7 @@ pub fn advance_left(&mut self) -> io::IoResult<()> { Ok(()) } - pub fn check_stack(&mut self, k: int) { + pub fn check_stack(&mut self, k: isize) { if !self.scan_stack_empty { let x = self.scan_top(); match self.token[x] { @@ -506,14 +506,14 @@ pub fn check_stack(&mut self, k: int) { } } } - pub fn print_newline(&mut self, amount: int) -> io::IoResult<()> { + pub fn print_newline(&mut self, amount: isize) -> io::IoResult<()> { debug!("NEWLINE {}", amount); let ret = write!(self.out, "\n"); self.pending_indentation = 0; self.indent(amount); return ret; } - pub fn indent(&mut self, amount: int) { + pub fn indent(&mut self, amount: isize) { debug!("INDENT {}", amount); self.pending_indentation += amount; } @@ -536,7 +536,7 @@ pub fn print_str(&mut self, s: &str) -> io::IoResult<()> { } write!(self.out, "{}", s) } - pub fn print(&mut self, token: Token, l: int) -> io::IoResult<()> { + pub fn print(&mut self, token: Token, l: isize) -> io::IoResult<()> { debug!("print {} {} (remaining line space={})", tok_str(&token), l, self.space); debug!("{}", buf_str(&self.token[], @@ -622,7 +622,7 @@ pub fn print(&mut self, token: Token, l: int) -> io::IoResult<()> { // "raw box" pub fn rbox(p: &mut Printer, indent: usize, b: Breaks) -> io::IoResult<()> { p.pretty_print(Token::Begin(BeginToken { - offset: indent as int, + offset: indent as isize, breaks: b })) } @@ -635,10 +635,10 @@ pub fn cbox(p: &mut Printer, indent: usize) -> io::IoResult<()> { rbox(p, indent, Breaks::Consistent) } -pub fn break_offset(p: &mut Printer, n: usize, off: int) -> io::IoResult<()> { +pub fn break_offset(p: &mut Printer, n: usize, off: isize) -> io::IoResult<()> { p.pretty_print(Token::Break(BreakToken { offset: off, - blank_space: n as int + blank_space: n as isize })) } @@ -651,7 +651,7 @@ pub fn eof(p: &mut Printer) -> io::IoResult<()> { } pub fn word(p: &mut Printer, wrd: &str) -> io::IoResult<()> { - p.pretty_print(Token::String(/* bad */ wrd.to_string(), wrd.len() as int)) + p.pretty_print(Token::String(/* bad */ wrd.to_string(), wrd.len() as isize)) } pub fn huge_word(p: &mut Printer, wrd: &str) -> io::IoResult<()> { @@ -678,7 +678,7 @@ pub fn hardbreak(p: &mut Printer) -> io::IoResult<()> { spaces(p, SIZE_INFINITY as usize) } -pub fn hardbreak_tok_offset(off: int) -> Token { +pub fn hardbreak_tok_offset(off: isize) -> Token { Token::Break(BreakToken {offset: off, blank_space: SIZE_INFINITY}) } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 83ac8432f98..c537ca60b18 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -520,7 +520,7 @@ pub fn bclose_(&mut self, span: codemap::Span, pub fn bclose_maybe_open (&mut self, span: codemap::Span, indented: usize, close_box: bool) -> IoResult<()> { try!(self.maybe_print_comment(span.hi)); - try!(self.break_offset_if_not_bol(1u, -(indented as int))); + try!(self.break_offset_if_not_bol(1u, -(indented as isize))); try!(word(&mut self.s, "}")); if close_box { try!(self.end()); // close the outer-box @@ -568,7 +568,7 @@ pub fn space_if_not_bol(&mut self) -> IoResult<()> { Ok(()) } pub fn break_offset_if_not_bol(&mut self, n: usize, - off: int) -> IoResult<()> { + off: isize) -> IoResult<()> { if !self.is_bol() { break_offset(&mut self.s, n, off) } else { diff --git a/src/libsyntax/util/small_vector.rs b/src/libsyntax/util/small_vector.rs index a4494a98864..da358b70225 100644 --- a/src/libsyntax/util/small_vector.rs +++ b/src/libsyntax/util/small_vector.rs @@ -191,7 +191,7 @@ mod test { #[test] fn test_len() { - let v: SmallVector = SmallVector::zero(); + let v: SmallVector = SmallVector::zero(); assert_eq!(0, v.len()); assert_eq!(1, SmallVector::one(1i).len()); @@ -214,7 +214,7 @@ fn test_push_get() { #[test] fn test_from_iter() { - let v: SmallVector = (vec!(1i, 2, 3)).into_iter().collect(); + let v: SmallVector = (vec![1is, 2, 3]).into_iter().collect(); assert_eq!(3, v.len()); assert_eq!(&1, v.get(0)); assert_eq!(&2, v.get(1)); @@ -224,7 +224,7 @@ fn test_from_iter() { #[test] fn test_move_iter() { let v = SmallVector::zero(); - let v: Vec = v.into_iter().collect(); + let v: Vec = v.into_iter().collect(); assert_eq!(Vec::new(), v); let v = SmallVector::one(1i); @@ -237,7 +237,7 @@ fn test_move_iter() { #[test] #[should_fail] fn test_expect_one_zero() { - let _: int = SmallVector::zero().expect_one(""); + let _: isize = SmallVector::zero().expect_one(""); } #[test] From 3c32cd1be27f321658382e39d34f5d993d99ae8b Mon Sep 17 00:00:00 2001 From: Paul Collier Date: Sun, 18 Jan 2015 00:41:56 +0000 Subject: [PATCH 23/96] libsyntax: 0u -> 0us, 0i -> 0is --- src/libsyntax/ast_util.rs | 18 +++---- src/libsyntax/codemap.rs | 18 +++---- src/libsyntax/diagnostic.rs | 32 ++++++------- src/libsyntax/ext/deriving/generic/mod.rs | 16 +++---- src/libsyntax/ext/expand.rs | 4 +- src/libsyntax/ext/quote.rs | 2 +- src/libsyntax/ext/tt/macro_parser.rs | 34 ++++++------- src/libsyntax/ext/tt/transcribe.rs | 2 +- src/libsyntax/parse/lexer/comments.rs | 8 ++-- src/libsyntax/parse/lexer/mod.rs | 32 ++++++------- src/libsyntax/parse/mod.rs | 12 ++--- src/libsyntax/parse/parser.rs | 18 +++---- src/libsyntax/print/pp.rs | 34 ++++++------- src/libsyntax/print/pprust.rs | 58 +++++++++++------------ src/libsyntax/test.rs | 4 +- src/libsyntax/util/small_vector.rs | 20 ++++---- 16 files changed, 156 insertions(+), 156 deletions(-) diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index 73f84f4fbe7..34fd498322c 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -322,15 +322,15 @@ pub fn struct_field_visibility(field: ast::StructField) -> Visibility { pub fn operator_prec(op: ast::BinOp) -> usize { match op { // 'as' sits here with 12 - BiMul | BiDiv | BiRem => 11u, - BiAdd | BiSub => 10u, - BiShl | BiShr => 9u, - BiBitAnd => 8u, - BiBitXor => 7u, - BiBitOr => 6u, - BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3u, - BiAnd => 2u, - BiOr => 1u + BiMul | BiDiv | BiRem => 11us, + BiAdd | BiSub => 10us, + BiShl | BiShr => 9us, + BiBitAnd => 8us, + BiBitXor => 7us, + BiBitOr => 6us, + BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3us, + BiAnd => 2us, + BiOr => 1us } } diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 07544f35b19..a5e10f42750 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -430,7 +430,7 @@ pub fn span_to_lines(&self, sp: Span) -> FileLines { let lo = self.lookup_char_pos(sp.lo); let hi = self.lookup_char_pos(sp.hi); let mut lines = Vec::new(); - for i in range(lo.line - 1u, hi.line as usize) { + for i in range(lo.line - 1us, hi.line as usize) { lines.push(i); }; FileLines {file: lo.file, lines: lines} @@ -498,10 +498,10 @@ fn lookup_filemap_idx(&self, pos: BytePos) -> usize { let files = self.files.borrow(); let files = &*files; let len = files.len(); - let mut a = 0u; + let mut a = 0us; let mut b = len; - while b - a > 1u { - let m = (a + b) / 2u; + while b - a > 1us { + let m = (a + b) / 2us; if files[m].start_pos > pos { b = m; } else { @@ -537,12 +537,12 @@ fn lookup_line(&self, pos: BytePos) -> FileMapAndLine { let files = self.files.borrow(); let f = (*files)[idx].clone(); - let mut a = 0u; + let mut a = 0us; { let lines = f.lines.borrow(); let mut b = lines.len(); - while b - a > 1u { - let m = (a + b) / 2u; + while b - a > 1us { + let m = (a + b) / 2us; if (*lines)[m] > pos { b = m; } else { a = m; } } } @@ -551,7 +551,7 @@ fn lookup_line(&self, pos: BytePos) -> FileMapAndLine { fn lookup_pos(&self, pos: BytePos) -> Loc { let FileMapAndLine {fm: f, line: a} = self.lookup_line(pos); - let line = a + 1u; // Line numbers start at 1 + let line = a + 1us; // Line numbers start at 1 let chpos = self.bytepos_to_file_charpos(pos); let linebpos = (*f.lines.borrow())[a]; let linechpos = self.bytepos_to_file_charpos(linebpos); @@ -762,7 +762,7 @@ fn t7() { assert_eq!(file_lines.file.name, "blork.rs"); assert_eq!(file_lines.lines.len(), 1); - assert_eq!(file_lines.lines[0], 1u); + assert_eq!(file_lines.lines[0], 1us); } #[test] diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index c86991b6e40..6de466ea9bd 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -26,7 +26,7 @@ use term; /// maximum number of lines we will print for each error; arbitrary. -static MAX_LINES: usize = 6u; +static MAX_LINES: usize = 6us; #[derive(Clone, Copy)] pub enum RenderSpan { @@ -151,20 +151,20 @@ pub fn err(&self, msg: &str) { self.bump_err_count(); } pub fn bump_err_count(&self) { - self.err_count.set(self.err_count.get() + 1u); + self.err_count.set(self.err_count.get() + 1us); } pub fn err_count(&self) -> usize { self.err_count.get() } pub fn has_errors(&self) -> bool { - self.err_count.get()> 0u + self.err_count.get() > 0us } pub fn abort_if_errors(&self) { let s; match self.err_count.get() { - 0u => return, - 1u => s = "aborting due to previous error".to_string(), - _ => { + 0us => return, + 1us => s = "aborting due to previous error".to_string(), + _ => { s = format!("aborting due to {} previous errors", self.err_count.get()); } @@ -448,7 +448,7 @@ fn highlight_lines(err: &mut EmitterWriter, let mut elided = false; let mut display_lines = &lines.lines[]; if display_lines.len() > MAX_LINES { - display_lines = &display_lines[0u..MAX_LINES]; + display_lines = &display_lines[0us..MAX_LINES]; elided = true; } // Print the offending lines @@ -459,32 +459,32 @@ fn highlight_lines(err: &mut EmitterWriter, } } if elided { - let last_line = display_lines[display_lines.len() - 1u]; - let s = format!("{}:{} ", fm.name, last_line + 1u); + let last_line = display_lines[display_lines.len() - 1us]; + let s = format!("{}:{} ", fm.name, last_line + 1us); try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len())); } // FIXME (#3260) // If there's one line at fault we can easily point to the problem - if lines.lines.len() == 1u { + if lines.lines.len() == 1us { let lo = cm.lookup_char_pos(sp.lo); - let mut digits = 0u; - let mut num = (lines.lines[0] + 1u) / 10u; + let mut digits = 0us; + let mut num = (lines.lines[0] + 1us) / 10us; // how many digits must be indent past? - while num > 0u { num /= 10u; digits += 1u; } + while num > 0us { num /= 10us; digits += 1us; } // indent past |name:## | and the 0-offset column location - let left = fm.name.len() + digits + lo.col.to_usize() + 3u; + let left = fm.name.len() + digits + lo.col.to_usize() + 3us; let mut s = String::new(); // Skip is the number of characters we need to skip because they are // part of the 'filename:line ' part of the previous line. - let skip = fm.name.len() + digits + 3u; + let skip = fm.name.len() + digits + 3us; for _ in range(0, skip) { s.push(' '); } if let Some(orig) = fm.get_line(lines.lines[0]) { - for pos in range(0u, left - skip) { + for pos in range(0us, left - skip) { let cur_char = orig.as_bytes()[pos] as char; // Whenever a tab occurs on the previous line, we insert one on // the error-point-squiggly-line as well (instead of a space). diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index ca3c1d36fba..b77c203acfb 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -748,7 +748,7 @@ fn expand_struct_method_body(&self, let mut raw_fields = Vec::new(); // ~[[fields of self], // [fields of next Self arg], [etc]] let mut patterns = Vec::new(); - for i in range(0u, self_args.len()) { + for i in range(0us, self_args.len()) { let struct_path= cx.path(DUMMY_SP, vec!( type_ident )); let (pat, ident_expr) = trait_.create_struct_pattern(cx, @@ -837,8 +837,8 @@ fn expand_static_struct_method_body(&self, /// (&A2(ref __self_0), /// &A2(ref __arg_1_0)) => (*__self_0).eq(&(*__arg_1_0)), /// _ => { - /// let __self_vi = match *self { A1(..) => 0u, A2(..) => 1u }; - /// let __arg_1_vi = match *__arg_1 { A1(..) => 0u, A2(..) => 1u }; + /// let __self_vi = match *self { A1(..) => 0us, A2(..) => 1us }; + /// let __arg_1_vi = match *__arg_1 { A1(..) => 0us, A2(..) => 1us }; /// false /// } /// } @@ -882,8 +882,8 @@ fn expand_enum_method_body(&self, /// (Variant2, Variant2, Variant2) => ... // delegate Matching on Variant2 /// ... /// _ => { - /// let __this_vi = match this { Variant1 => 0u, Variant2 => 1u, ... }; - /// let __that_vi = match that { Variant1 => 0u, Variant2 => 1u, ... }; + /// let __this_vi = match this { Variant1 => 0us, Variant2 => 1us, ... }; + /// let __that_vi = match that { Variant1 => 0us, Variant2 => 1us, ... }; /// ... // catch-all remainder can inspect above variant index values. /// } /// } @@ -1045,13 +1045,13 @@ fn build_enum_match_tuple( // // ``` // let __self0_vi = match self { - // A => 0u, B(..) => 1u, C(..) => 2u + // A => 0us, B(..) => 1us, C(..) => 2us // }; // let __self1_vi = match __arg1 { - // A => 0u, B(..) => 1u, C(..) => 2u + // A => 0us, B(..) => 1us, C(..) => 2us // }; // let __self2_vi = match __arg2 { - // A => 0u, B(..) => 1u, C(..) => 2u + // A => 0us, B(..) => 1us, C(..) => 2us // }; // ``` let mut index_let_stmts: Vec> = Vec::new(); diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 4f614c1a937..9aa602b39b4 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -273,7 +273,7 @@ fn expand_mac_invoc(mac: ast::Mac, span: codemap::Span, // in this file. // Token-tree macros: MacInvocTT(pth, tts, _) => { - if pth.segments.len() > 1u { + if pth.segments.len() > 1us { fld.cx.span_err(pth.span, "expected macro name without module \ separators"); @@ -844,7 +844,7 @@ fn expand_pat(p: P, fld: &mut MacroExpander) -> P { }, _ => unreachable!() }; - if pth.segments.len() > 1u { + if pth.segments.len() > 1us { fld.cx.span_err(pth.span, "expected macro name without module separators"); return DummyResult::raw_pat(span); } diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index a5885ac6c5d..5339c3d77c6 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -716,7 +716,7 @@ fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree]) // try removing it when enough of them are gone. let mut p = cx.new_parser_from_tts(tts); - p.quote_depth += 1u; + p.quote_depth += 1us; let cx_expr = p.parse_expr(); if !p.eat(&token::Comma) { diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 75d904a4632..d115f2ed620 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -171,11 +171,11 @@ pub fn initial_matcher_pos(ms: Rc>, sep: Option, lo: ByteP stack: vec![], top_elts: TtSeq(ms), sep: sep, - idx: 0u, + idx: 0us, up: None, matches: matches, - match_lo: 0u, - match_cur: 0u, + match_lo: 0us, + match_cur: 0us, match_hi: match_idx_hi, sp_lo: lo } @@ -238,7 +238,7 @@ fn n_rec(p_s: &ParseSess, m: &TokenTree, res: &[Rc], } } let mut ret_val = HashMap::new(); - let mut idx = 0u; + let mut idx = 0us; for m in ms.iter() { n_rec(p_s, m, res, &mut ret_val, &mut idx) } ret_val } @@ -383,7 +383,7 @@ pub fn parse(sess: &ParseSess, if seq.op == ast::ZeroOrMore { let mut new_ei = ei.clone(); new_ei.match_cur += seq.num_captures; - new_ei.idx += 1u; + new_ei.idx += 1us; //we specifically matched zero repeats. for idx in range(ei.match_cur, ei.match_cur + seq.num_captures) { (&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp))); @@ -398,7 +398,7 @@ pub fn parse(sess: &ParseSess, cur_eis.push(box MatcherPos { stack: vec![], sep: seq.separator.clone(), - idx: 0u, + idx: 0us, matches: matches, match_lo: ei_t.match_cur, match_cur: ei_t.match_cur, @@ -442,20 +442,20 @@ pub fn parse(sess: &ParseSess, /* error messages here could be improved with links to orig. rules */ if token_name_eq(&tok, &token::Eof) { - if eof_eis.len() == 1u { + if eof_eis.len() == 1us { let mut v = Vec::new(); for dv in (&mut eof_eis[0]).matches.iter_mut() { v.push(dv.pop().unwrap()); } return Success(nameize(sess, ms, &v[])); - } else if eof_eis.len() > 1u { + } else if eof_eis.len() > 1us { return Error(sp, "ambiguity: multiple successful parses".to_string()); } else { return Failure(sp, "unexpected end of macro invocation".to_string()); } } else { - if (bb_eis.len() > 0u && next_eis.len() > 0u) - || bb_eis.len() > 1u { + if (bb_eis.len() > 0us && next_eis.len() > 0us) + || bb_eis.len() > 1us { let nts = bb_eis.iter().map(|ei| { match ei.top_elts.get_tt(ei.idx) { TtToken(_, MatchNt(bind, name, _, _)) => { @@ -469,12 +469,12 @@ pub fn parse(sess: &ParseSess, "local ambiguity: multiple parsing options: \ built-in NTs {} or {} other options.", nts, next_eis.len()).to_string()); - } else if bb_eis.len() == 0u && next_eis.len() == 0u { + } else if bb_eis.len() == 0us && next_eis.len() == 0us { return Failure(sp, format!("no rules expected the token `{}`", pprust::token_to_string(&tok)).to_string()); - } else if next_eis.len() > 0u { + } else if next_eis.len() > 0us { /* Now process the next token */ - while next_eis.len() > 0u { + while next_eis.len() > 0us { cur_eis.push(next_eis.pop().unwrap()); } rdr.next_token(); @@ -488,7 +488,7 @@ pub fn parse(sess: &ParseSess, let match_cur = ei.match_cur; (&mut ei.matches[match_cur]).push(Rc::new(MatchedNonterminal( parse_nt(&mut rust_parser, name_string.get())))); - ei.idx += 1u; + ei.idx += 1us; ei.match_cur += 1; } _ => panic!() @@ -501,16 +501,16 @@ pub fn parse(sess: &ParseSess, } } - assert!(cur_eis.len() > 0u); + assert!(cur_eis.len() > 0us); } } pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal { match name { "tt" => { - p.quote_depth += 1u; //but in theory, non-quoted tts might be useful + p.quote_depth += 1us; //but in theory, non-quoted tts might be useful let res = token::NtTT(P(p.parse_token_tree())); - p.quote_depth -= 1u; + p.quote_depth -= 1us; return res; } _ => {} diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index 7936b9fcfc7..0bf20b8f3e1 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -223,7 +223,7 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { r.repeat_len.pop(); } } else { /* repeat */ - *r.repeat_idx.last_mut().unwrap() += 1u; + *r.repeat_idx.last_mut().unwrap() += 1us; r.stack.last_mut().unwrap().idx = 0; match r.stack.last().unwrap().sep.clone() { Some(tk) => { diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index ca9091856d6..2799696e8eb 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -62,7 +62,7 @@ pub fn doc_comment_style(comment: &str) -> ast::AttrStyle { pub fn strip_doc_comment_decoration(comment: &str) -> String { /// remove whitespace-only lines from the start/end of lines fn vertical_trim(lines: Vec ) -> Vec { - let mut i = 0u; + let mut i = 0us; let mut j = lines.len(); // first line of all-stars should be omitted if lines.len() > 0 && @@ -132,7 +132,7 @@ fn horizontal_trim(lines: Vec ) -> Vec { } if comment.starts_with("/*") { - let lines = comment[3u..(comment.len() - 2u)] + let lines = comment[3us..(comment.len() - 2us)] .lines_any() .map(|s| s.to_string()) .collect:: >(); @@ -158,7 +158,7 @@ fn push_blank_line_comment(rdr: &StringReader, comments: &mut Vec) { fn consume_whitespace_counting_blank_lines(rdr: &mut StringReader, comments: &mut Vec) { while is_whitespace(rdr.curr) && !rdr.is_eof() { - if rdr.col == CharPos(0u) && rdr.curr_is('\n') { + if rdr.col == CharPos(0us) && rdr.curr_is('\n') { push_blank_line_comment(rdr, &mut *comments); } rdr.bump(); @@ -305,7 +305,7 @@ fn read_block_comment(rdr: &mut StringReader, let mut style = if code_to_the_left { Trailing } else { Isolated }; rdr.consume_non_eol_whitespace(); - if !rdr.is_eof() && !rdr.curr_is('\n') && lines.len() == 1u { + if !rdr.is_eof() && !rdr.curr_is('\n') && lines.len() == 1us { style = Mixed; } debug!("<<< block comment"); diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 2fcf43f9ead..d18bf554975 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -279,7 +279,7 @@ fn with_str_from_to(&self, start: BytePos, end: BytePos, f: F) -> T where /// Converts CRLF to LF in the given string, raising an error on bare CR. fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> CowString<'b> { - let mut i = 0u; + let mut i = 0us; while i < s.len() { let str::CharRange { ch, next } = s.char_range_at(i); if ch == '\r' { @@ -331,10 +331,10 @@ pub fn bump(&mut self) { let byte_offset_diff = next.next - current_byte_offset; self.pos = self.pos + Pos::from_usize(byte_offset_diff); self.curr = Some(next.ch); - self.col = self.col + CharPos(1u); + self.col = self.col + CharPos(1us); if last_char == '\n' { self.filemap.next_line(self.last_pos); - self.col = CharPos(0u); + self.col = CharPos(0us); } if byte_offset_diff > 1 { @@ -472,7 +472,7 @@ fn scan_comment(&mut self) -> Option { cmap.files.borrow_mut().push(self.filemap.clone()); let loc = cmap.lookup_char_pos_adj(self.last_pos); debug!("Skipping a shebang"); - if loc.line == 1u && loc.col == CharPos(0u) { + if loc.line == 1us && loc.col == CharPos(0us) { // FIXME: Add shebang "token", return it let start = self.last_pos; while !self.curr_is('\n') && !self.is_eof() { self.bump(); } @@ -646,7 +646,7 @@ fn bump_expecting_char<'a,D:fmt::Show>(r: &mut StringReader<'a>, /// Scan through any digits (base `radix`) or underscores, and return how /// many digits there were. fn scan_digits(&mut self, radix: usize) -> usize { - let mut len = 0u; + let mut len = 0us; loop { let c = self.curr; if c == Some('_') { debug!("skipping a _"); self.bump(); continue; } @@ -799,14 +799,14 @@ fn scan_char_or_byte(&mut self, start: BytePos, first_source_char: char, if self.curr == Some('{') { self.scan_unicode_escape(delim) } else { - let res = self.scan_hex_digits(4u, delim, false); + let res = self.scan_hex_digits(4us, delim, false); let sp = codemap::mk_sp(escaped_pos, self.last_pos); self.old_escape_warning(sp); res } } 'U' if !ascii_only => { - let res = self.scan_hex_digits(8u, delim, false); + let res = self.scan_hex_digits(8us, delim, false); let sp = codemap::mk_sp(escaped_pos, self.last_pos); self.old_escape_warning(sp); res @@ -937,11 +937,11 @@ fn scan_float_exponent(&mut self) { /// error if it isn't. fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) { match base { - 16u => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \ - supported"), - 8u => self.err_span_(start_bpos, last_bpos, "octal float literal is not supported"), - 2u => self.err_span_(start_bpos, last_bpos, "binary float literal is not supported"), - _ => () + 16us => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \ + supported"), + 8us => self.err_span_(start_bpos, last_bpos, "octal float literal is not supported"), + 2us => self.err_span_(start_bpos, last_bpos, "binary float literal is not supported"), + _ => () } } @@ -1189,7 +1189,7 @@ fn next_token_inner(&mut self) -> token::Token { 'r' => { let start_bpos = self.last_pos; self.bump(); - let mut hash_count = 0u; + let mut hash_count = 0us; while self.curr_is('#') { self.bump(); hash_count += 1; @@ -1374,7 +1374,7 @@ fn scan_byte_string(&mut self) -> token::Lit { fn scan_raw_byte_string(&mut self) -> token::Lit { let start_bpos = self.last_pos; self.bump(); - let mut hash_count = 0u; + let mut hash_count = 0us; while self.curr_is('#') { self.bump(); hash_count += 1; @@ -1616,9 +1616,9 @@ macro_rules! test { test!("1.0", Float, "1.0"); test!("1.0e10", Float, "1.0e10"); - assert_eq!(setup(&mk_sh(), "2u".to_string()).next_token().tok, + assert_eq!(setup(&mk_sh(), "2us".to_string()).next_token().tok, token::Literal(token::Integer(token::intern("2")), - Some(token::intern("u")))); + Some(token::intern("us")))); assert_eq!(setup(&mk_sh(), "r###\"raw\"###suffix".to_string()).next_token().tok, token::Literal(token::StrRaw(token::intern("raw"), 3), Some(token::intern("suffix")))); diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 33da7c160d9..29414ef94b5 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -181,7 +181,7 @@ pub fn parse_tts_from_source_str(name: String, name, source ); - p.quote_depth += 1u; + p.quote_depth += 1us; // right now this is re-creating the token trees from ... token trees. maybe_aborted(p.parse_all_token_trees(),p) } @@ -325,7 +325,7 @@ pub fn parse_tts_from_source_str(name: String, name, source ); - p.quote_depth += 1u; + p.quote_depth += 1us; // right now this is re-creating the token trees from ... token trees. maybe_aborted(p.parse_all_token_trees(),p) } @@ -574,7 +574,7 @@ pub fn byte_lit(lit: &str) -> (u8, usize) { if lit.len() == 1 { (lit.as_bytes()[0], 1) } else { - assert!(lit.as_bytes()[0] == b'\\', err(0i)); + assert!(lit.as_bytes()[0] == b'\\', err(0is)); let b = match lit.as_bytes()[1] { b'"' => b'"', b'n' => b'\n', @@ -684,9 +684,9 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> match suffix { Some(suf) if looks_like_width_suffix(&['f'], suf) => { match base { - 16u => sd.span_err(sp, "hexadecimal float literal is not supported"), - 8u => sd.span_err(sp, "octal float literal is not supported"), - 2u => sd.span_err(sp, "binary float literal is not supported"), + 16us => sd.span_err(sp, "hexadecimal float literal is not supported"), + 8us => sd.span_err(sp, "octal float literal is not supported"), + 2us => sd.span_err(sp, "binary float literal is not supported"), _ => () } let ident = token::intern_and_get_ident(&*s); diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 88825cb3f34..ea7c80d3fc4 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -767,7 +767,7 @@ pub fn parse_seq_to_before_gt_or_return(&mut self, // would encounter a `>` and stop. This lets the parser handle trailing // commas in generic parameters, because it can stop either after // parsing a type or after parsing a comma. - for i in iter::count(0u, 1) { + for i in iter::count(0us, 1) { if self.check(&token::Gt) || self.token == token::BinOp(token::Shr) || self.token == token::Ge @@ -944,7 +944,7 @@ pub fn bump(&mut self) { }; self.span = next.sp; self.token = next.tok; - self.tokens_consumed += 1u; + self.tokens_consumed += 1us; self.expected_tokens.clear(); // check after each token self.check_unknown_macro_variable(); @@ -2638,7 +2638,7 @@ fn parse_unquoted(&mut self) -> TokenTree { } pub fn check_unknown_macro_variable(&mut self) { - if self.quote_depth == 0u { + if self.quote_depth == 0us { match self.token { token::SubstNt(name, _) => self.fatal(&format!("unknown macro variable `{}`", @@ -2707,7 +2707,7 @@ fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree { token_str)[]) }, /* we ought to allow different depths of unquotation */ - token::Dollar | token::SubstNt(..) if p.quote_depth > 0u => { + token::Dollar | token::SubstNt(..) if p.quote_depth > 0us => { p.parse_unquoted() } _ => { @@ -5079,7 +5079,7 @@ fn parse_mod_items(&mut self, } } - if first && attrs_remaining_len > 0u { + if first && attrs_remaining_len > 0us { // We parsed attributes for the first item but didn't find it let last_span = self.last_span; self.span_err(last_span, @@ -5683,7 +5683,7 @@ fn parse_item_or_view_item(&mut self, return IoviItem(item); } if self.token.is_keyword(keywords::Unsafe) && - self.look_ahead(1u, |t| t.is_keyword(keywords::Trait)) + self.look_ahead(1us, |t| t.is_keyword(keywords::Trait)) { // UNSAFE TRAIT ITEM self.expect_keyword(keywords::Unsafe); @@ -5700,7 +5700,7 @@ fn parse_item_or_view_item(&mut self, return IoviItem(item); } if self.token.is_keyword(keywords::Unsafe) && - self.look_ahead(1u, |t| t.is_keyword(keywords::Impl)) + self.look_ahead(1us, |t| t.is_keyword(keywords::Impl)) { // IMPL ITEM self.expect_keyword(keywords::Unsafe); @@ -5731,7 +5731,7 @@ fn parse_item_or_view_item(&mut self, return IoviItem(item); } if self.token.is_keyword(keywords::Unsafe) - && self.look_ahead(1u, |t| *t != token::OpenDelim(token::Brace)) { + && self.look_ahead(1us, |t| *t != token::OpenDelim(token::Brace)) { // UNSAFE FUNCTION ITEM self.bump(); let abi = if self.eat_keyword(keywords::Extern) { @@ -6035,7 +6035,7 @@ fn parse_view_path(&mut self) -> P { } } } - let mut rename_to = path[path.len() - 1u]; + let mut rename_to = path[path.len() - 1us]; let path = ast::Path { span: mk_sp(lo, self.last_span.hi), global: false, diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index ca99fb2ef89..0b1bd282941 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -132,15 +132,15 @@ pub fn buf_str(toks: &[Token], let mut i = left; let mut l = lim; let mut s = string::String::from_str("["); - while i != right && l != 0u { - l -= 1u; + while i != right && l != 0us { + l -= 1us; if i != left { s.push_str(", "); } s.push_str(&format!("{}={}", szs[i], tok_str(&toks[i]))[]); - i += 1u; + i += 1us; i %= n; } s.push(']'); @@ -167,7 +167,7 @@ pub fn mk_printer(out: Box, linewidth: usize) -> Printer { let n: usize = 3 * linewidth; debug!("mk_printer {}", linewidth); let token: Vec = repeat(Token::Eof).take(n).collect(); - let size: Vec = repeat(0i).take(n).collect(); + let size: Vec = repeat(0is).take(n).collect(); let scan_stack: Vec = repeat(0us).take(n).collect(); Printer { out: out, @@ -326,8 +326,8 @@ pub fn pretty_print(&mut self, token: Token) -> io::IoResult<()> { if self.scan_stack_empty { self.left_total = 1; self.right_total = 1; - self.left = 0u; - self.right = 0u; + self.left = 0us; + self.right = 0us; } else { self.advance_right(); } debug!("pp Begin({})/buffer ~[{},{}]", b.offset, self.left, self.right); @@ -355,8 +355,8 @@ pub fn pretty_print(&mut self, token: Token) -> io::IoResult<()> { if self.scan_stack_empty { self.left_total = 1; self.right_total = 1; - self.left = 0u; - self.right = 0u; + self.left = 0us; + self.right = 0us; } else { self.advance_right(); } debug!("pp Break({})/buffer ~[{},{}]", b.offset, self.left, self.right); @@ -410,7 +410,7 @@ pub fn scan_push(&mut self, x: usize) { if self.scan_stack_empty { self.scan_stack_empty = false; } else { - self.top += 1u; + self.top += 1us; self.top %= self.buf_len; assert!((self.top != self.bottom)); } @@ -422,7 +422,7 @@ pub fn scan_pop(&mut self) -> usize { if self.top == self.bottom { self.scan_stack_empty = true; } else { - self.top += self.buf_len - 1u; self.top %= self.buf_len; + self.top += self.buf_len - 1us; self.top %= self.buf_len; } return x; } @@ -436,12 +436,12 @@ pub fn scan_pop_bottom(&mut self) -> usize { if self.top == self.bottom { self.scan_stack_empty = true; } else { - self.bottom += 1u; self.bottom %= self.buf_len; + self.bottom += 1us; self.bottom %= self.buf_len; } return x; } pub fn advance_right(&mut self) { - self.right += 1u; + self.right += 1us; self.right %= self.buf_len; assert!((self.right != self.left)); } @@ -471,7 +471,7 @@ pub fn advance_left(&mut self) -> io::IoResult<()> { break; } - self.left += 1u; + self.left += 1us; self.left %= self.buf_len; left_size = self.size[self.left]; @@ -520,7 +520,7 @@ pub fn indent(&mut self, amount: isize) { pub fn get_top(&mut self) -> PrintStackElem { let print_stack = &mut self.print_stack; let n = print_stack.len(); - if n != 0u { + if n != 0us { (*print_stack)[n - 1] } else { PrintStackElem { @@ -565,7 +565,7 @@ pub fn print(&mut self, token: Token, l: isize) -> io::IoResult<()> { Token::End => { debug!("print End -> pop End"); let print_stack = &mut self.print_stack; - assert!((print_stack.len() != 0u)); + assert!((print_stack.len() != 0us)); print_stack.pop().unwrap(); Ok(()) } @@ -667,11 +667,11 @@ pub fn spaces(p: &mut Printer, n: usize) -> io::IoResult<()> { } pub fn zerobreak(p: &mut Printer) -> io::IoResult<()> { - spaces(p, 0u) + spaces(p, 0us) } pub fn space(p: &mut Printer) -> io::IoResult<()> { - spaces(p, 1u) + spaces(p, 1us) } pub fn hardbreak(p: &mut Printer) -> io::IoResult<()> { diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index c537ca60b18..78a97f310d2 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -381,7 +381,7 @@ pub fn block_to_string(blk: &ast::Block) -> String { // containing cbox, will be closed by print-block at } try!(s.cbox(indent_unit)); // head-ibox, will be closed by print-block after { - try!(s.ibox(0u)); + try!(s.ibox(0us)); s.print_block(blk) }) } @@ -520,7 +520,7 @@ pub fn bclose_(&mut self, span: codemap::Span, pub fn bclose_maybe_open (&mut self, span: codemap::Span, indented: usize, close_box: bool) -> IoResult<()> { try!(self.maybe_print_comment(span.hi)); - try!(self.break_offset_if_not_bol(1u, -(indented as isize))); + try!(self.break_offset_if_not_bol(1us, -(indented as isize))); try!(word(&mut self.s, "}")); if close_box { try!(self.end()); // close the outer-box @@ -595,7 +595,7 @@ pub fn synth_comment(&mut self, text: String) -> IoResult<()> { pub fn commasep(&mut self, b: Breaks, elts: &[T], mut op: F) -> IoResult<()> where F: FnMut(&mut State, &T) -> IoResult<()>, { - try!(self.rbox(0u, b)); + try!(self.rbox(0us, b)); let mut first = true; for elt in elts.iter() { if first { first = false; } else { try!(self.word_space(",")); } @@ -613,13 +613,13 @@ pub fn commasep_cmnt(&mut self, F: FnMut(&mut State, &T) -> IoResult<()>, G: FnMut(&T) -> codemap::Span, { - try!(self.rbox(0u, b)); + try!(self.rbox(0us, b)); let len = elts.len(); - let mut i = 0u; + let mut i = 0us; for elt in elts.iter() { try!(self.maybe_print_comment(get_span(elt).hi)); try!(op(self, elt)); - i += 1u; + i += 1us; if i < len { try!(word(&mut self.s, ",")); try!(self.maybe_print_trailing_comment(get_span(elt), @@ -670,7 +670,7 @@ pub fn print_opt_lifetime(&mut self, pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> { try!(self.maybe_print_comment(ty.span.lo)); - try!(self.ibox(0u)); + try!(self.ibox(0us)); match ty.node { ast::TyVec(ref ty) => { try!(word(&mut self.s, "[")); @@ -871,7 +871,7 @@ pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> { } ast::ItemTy(ref ty, ref params) => { try!(self.ibox(indent_unit)); - try!(self.ibox(0u)); + try!(self.ibox(0us)); try!(self.word_nbsp(&visibility_qualified(item.vis, "type")[])); try!(self.print_ident(item.ident)); try!(self.print_generics(params)); @@ -1262,7 +1262,7 @@ pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> { pub fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) -> IoResult<()> { - let mut count = 0u; + let mut count = 0us; for attr in attrs.iter() { match attr.node.style { ast::AttrOuter => { @@ -1280,7 +1280,7 @@ pub fn print_outer_attributes(&mut self, pub fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) -> IoResult<()> { - let mut count = 0u; + let mut count = 0us; for attr in attrs.iter() { match attr.node.style { ast::AttrInner => { @@ -1404,8 +1404,8 @@ fn print_else(&mut self, els: Option<&ast::Expr>) -> IoResult<()> { match _else.node { // "another else-if" ast::ExprIf(ref i, ref then, ref e) => { - try!(self.cbox(indent_unit - 1u)); - try!(self.ibox(0u)); + try!(self.cbox(indent_unit - 1us)); + try!(self.ibox(0us)); try!(word(&mut self.s, " else if ")); try!(self.print_expr(&**i)); try!(space(&mut self.s)); @@ -1414,8 +1414,8 @@ fn print_else(&mut self, els: Option<&ast::Expr>) -> IoResult<()> { } // "another else-if-let" ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => { - try!(self.cbox(indent_unit - 1u)); - try!(self.ibox(0u)); + try!(self.cbox(indent_unit - 1us)); + try!(self.ibox(0us)); try!(word(&mut self.s, " else if let ")); try!(self.print_pat(&**pat)); try!(space(&mut self.s)); @@ -1427,8 +1427,8 @@ fn print_else(&mut self, els: Option<&ast::Expr>) -> IoResult<()> { } // "final else" ast::ExprBlock(ref b) => { - try!(self.cbox(indent_unit - 1u)); - try!(self.ibox(0u)); + try!(self.cbox(indent_unit - 1us)); + try!(self.ibox(0us)); try!(word(&mut self.s, " else ")); self.print_block(&**b) } @@ -1594,7 +1594,7 @@ fn print_expr_method_call(&mut self, try!(self.print_expr(&*args[0])); try!(word(&mut self.s, ".")); try!(self.print_ident(ident.node)); - if tys.len() > 0u { + if tys.len() > 0us { try!(word(&mut self.s, "::<")); try!(self.commasep(Inconsistent, tys, |s, ty| s.print_type(&**ty))); @@ -1765,7 +1765,7 @@ pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> { // containing cbox, will be closed by print-block at } try!(self.cbox(indent_unit)); // head-box, will be closed by print-block after { - try!(self.ibox(0u)); + try!(self.ibox(0us)); try!(self.print_block(&**blk)); } ast::ExprAssign(ref lhs, ref rhs) => { @@ -2142,7 +2142,7 @@ pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> { }, |f| f.node.pat.span)); if etc { - if fields.len() != 0u { try!(self.word_space(",")); } + if fields.len() != 0us { try!(self.word_space(",")); } try!(word(&mut self.s, "..")); } try!(space(&mut self.s)); @@ -2209,7 +2209,7 @@ fn print_arm(&mut self, arm: &ast::Arm) -> IoResult<()> { try!(space(&mut self.s)); } try!(self.cbox(indent_unit)); - try!(self.ibox(0u)); + try!(self.ibox(0us)); try!(self.print_outer_attributes(&arm.attrs[])); let mut first = true; for p in arm.pats.iter() { @@ -2295,7 +2295,7 @@ pub fn print_fn_args(&mut self, decl: &ast::FnDecl, -> IoResult<()> { // It is unfortunate to duplicate the commasep logic, but we want the // self type and the args all in the same box. - try!(self.rbox(0u, Inconsistent)); + try!(self.rbox(0us, Inconsistent)); let mut first = true; for &explicit_self in opt_explicit_self.iter() { let m = match explicit_self { @@ -2472,7 +2472,7 @@ pub fn print_generics(&mut self, try!(word(&mut self.s, "<")); let mut ints = Vec::new(); - for i in range(0u, total) { + for i in range(0us, total) { ints.push(i); } @@ -2794,7 +2794,7 @@ pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span, if span.hi < (*cmnt).pos && (*cmnt).pos < next && span_line.line == comment_line.line { try!(self.print_comment(cmnt)); - self.cur_cmnt_and_lit.cur_cmnt += 1u; + self.cur_cmnt_and_lit.cur_cmnt += 1us; } } _ => () @@ -2812,7 +2812,7 @@ pub fn print_remaining_comments(&mut self) -> IoResult<()> { match self.next_comment() { Some(ref cmnt) => { try!(self.print_comment(cmnt)); - self.cur_cmnt_and_lit.cur_cmnt += 1u; + self.cur_cmnt_and_lit.cur_cmnt += 1us; } _ => break } @@ -2894,7 +2894,7 @@ pub fn next_lit(&mut self, pos: BytePos) -> Option { 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 += 1u; + self.cur_cmnt_and_lit.cur_lit += 1us; if ltrl.pos == pos { return Some(ltrl); } } None @@ -2909,7 +2909,7 @@ pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> { Some(ref cmnt) => { if (*cmnt).pos < pos { try!(self.print_comment(cmnt)); - self.cur_cmnt_and_lit.cur_cmnt += 1u; + self.cur_cmnt_and_lit.cur_cmnt += 1us; } else { break; } } _ => break @@ -2922,7 +2922,7 @@ pub fn print_comment(&mut self, cmnt: &comments::Comment) -> IoResult<()> { match cmnt.style { comments::Mixed => { - assert_eq!(cmnt.lines.len(), 1u); + assert_eq!(cmnt.lines.len(), 1us); try!(zerobreak(&mut self.s)); try!(word(&mut self.s, &cmnt.lines[0][])); zerobreak(&mut self.s) @@ -2941,11 +2941,11 @@ pub fn print_comment(&mut self, } comments::Trailing => { try!(word(&mut self.s, " ")); - if cmnt.lines.len() == 1u { + if cmnt.lines.len() == 1us { try!(word(&mut self.s, &cmnt.lines[0][])); hardbreak(&mut self.s) } else { - try!(self.ibox(0u)); + try!(self.ibox(0us)); for line in cmnt.lines.iter() { if !line.is_empty() { try!(word(&mut self.s, &line[])); diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index 895268f96c8..ee8742825f4 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -345,8 +345,8 @@ fn has_test_signature(i: &ast::Item) -> bool { let tparm_cnt = generics.ty_params.len(); // NB: inadequate check, but we're running // well before resolve, can't get too deep. - input_cnt == 1u - && no_output && tparm_cnt == 0u + input_cnt == 1us + && no_output && tparm_cnt == 0us } _ => false } diff --git a/src/libsyntax/util/small_vector.rs b/src/libsyntax/util/small_vector.rs index da358b70225..d8bac19805b 100644 --- a/src/libsyntax/util/small_vector.rs +++ b/src/libsyntax/util/small_vector.rs @@ -194,14 +194,14 @@ fn test_len() { let v: SmallVector = SmallVector::zero(); assert_eq!(0, v.len()); - assert_eq!(1, SmallVector::one(1i).len()); - assert_eq!(5, SmallVector::many(vec!(1i, 2, 3, 4, 5)).len()); + assert_eq!(1, SmallVector::one(1is).len()); + assert_eq!(5, SmallVector::many(vec!(1is, 2, 3, 4, 5)).len()); } #[test] fn test_push_get() { let mut v = SmallVector::zero(); - v.push(1i); + v.push(1is); assert_eq!(1, v.len()); assert_eq!(&1, v.get(0)); v.push(2); @@ -227,11 +227,11 @@ fn test_move_iter() { let v: Vec = v.into_iter().collect(); assert_eq!(Vec::new(), v); - let v = SmallVector::one(1i); - assert_eq!(vec!(1i), v.into_iter().collect::>()); + let v = SmallVector::one(1is); + assert_eq!(vec!(1is), v.into_iter().collect::>()); - let v = SmallVector::many(vec!(1i, 2i, 3i)); - assert_eq!(vec!(1i, 2i, 3i), v.into_iter().collect::>()); + let v = SmallVector::many(vec!(1is, 2is, 3is)); + assert_eq!(vec!(1is, 2is, 3is), v.into_iter().collect::>()); } #[test] @@ -243,12 +243,12 @@ fn test_expect_one_zero() { #[test] #[should_fail] fn test_expect_one_many() { - SmallVector::many(vec!(1i, 2)).expect_one(""); + SmallVector::many(vec!(1is, 2)).expect_one(""); } #[test] fn test_expect_one_one() { - assert_eq!(1i, SmallVector::one(1i).expect_one("")); - assert_eq!(1i, SmallVector::many(vec!(1i)).expect_one("")); + assert_eq!(1is, SmallVector::one(1is).expect_one("")); + assert_eq!(1is, SmallVector::many(vec!(1is)).expect_one("")); } } From 2c2480df5d340f4c7b2deeef0177e4fd22f2b03a Mon Sep 17 00:00:00 2001 From: we Date: Mon, 19 Jan 2015 08:27:09 +0300 Subject: [PATCH 24/96] Replace `0 as *const/mut T` with `ptr::null/null_mut()` --- src/liballoc/heap.rs | 2 +- src/liblog/lib.rs | 5 +++-- src/librustc_llvm/diagnostic.rs | 9 +++++---- src/librustc_llvm/lib.rs | 21 ++++++++++----------- src/librustc_trans/trans/type_.rs | 5 +++-- src/libstd/io/stdio.rs | 3 ++- src/libstd/sync/mpsc/mpsc_queue.rs | 3 ++- src/libstd/sync/mpsc/select.rs | 17 +++++++++-------- src/libstd/sync/mpsc/spsc_queue.rs | 5 +++-- src/libstd/sync/mpsc/sync.rs | 17 +++++++++-------- src/libstd/sys/common/helper_thread.rs | 3 ++- src/libstd/sys/unix/backtrace.rs | 2 +- src/libstd/sys/unix/condvar.rs | 3 ++- src/libstd/sys/unix/fs.rs | 3 ++- src/libstd/sys/unix/os.rs | 2 +- src/libstd/sys/unix/process.rs | 2 +- src/libstd/sys/windows/backtrace.rs | 10 +++++----- src/libstd/sys/windows/thread_local.rs | 4 ++-- src/libstd/thread_local/mod.rs | 4 ++-- 19 files changed, 65 insertions(+), 55 deletions(-) diff --git a/src/liballoc/heap.rs b/src/liballoc/heap.rs index b7bc1b47646..d3041eaa884 100644 --- a/src/liballoc/heap.rs +++ b/src/liballoc/heap.rs @@ -280,7 +280,7 @@ pub unsafe fn allocate(size: uint, align: uint) -> *mut u8 { if align <= MIN_ALIGN { libc::malloc(size as libc::size_t) as *mut u8 } else { - let mut out = 0 as *mut libc::c_void; + let mut out = ptr::null(); let ret = posix_memalign(&mut out, align as libc::size_t, size as libc::size_t); diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index a166dc369cb..433b8aa6941 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -179,6 +179,7 @@ use std::io; use std::mem; use std::os; +use std::ptr; use std::rt; use std::slice; use std::sync::{Once, ONCE_INIT}; @@ -436,11 +437,11 @@ fn init() { assert!(!DIRECTIVES.is_null()); let _directives: Box> = mem::transmute(DIRECTIVES); - DIRECTIVES = 0 as *const Vec; + DIRECTIVES = ptr::null(); if !FILTER.is_null() { let _filter: Box = mem::transmute(FILTER); - FILTER = 0 as *const _; + FILTER = ptr::null(); } }); } diff --git a/src/librustc_llvm/diagnostic.rs b/src/librustc_llvm/diagnostic.rs index 464f9f98e7f..db2a569cdef 100644 --- a/src/librustc_llvm/diagnostic.rs +++ b/src/librustc_llvm/diagnostic.rs @@ -14,6 +14,7 @@ pub use self::Diagnostic::*; use libc::c_char; +use std::ptr; use {ValueRef, TwineRef, DebugLocRef, DiagnosticInfoRef}; @@ -52,10 +53,10 @@ unsafe fn unpack(kind: OptimizationDiagnosticKind, di: DiagnosticInfoRef) let mut opt = OptimizationDiagnostic { kind: kind, - pass_name: 0 as *const c_char, - function: 0 as ValueRef, - debug_loc: 0 as DebugLocRef, - message: 0 as TwineRef, + pass_name: ptr::null(), + function: ptr::null_mut(), + debug_loc: ptr::null_mut(), + message: ptr::null_mut(), }; super::LLVMUnpackOptimizationDiagnostic(di, diff --git a/src/librustc_llvm/lib.rs b/src/librustc_llvm/lib.rs index 3edb1ec48a0..03021b7700c 100644 --- a/src/librustc_llvm/lib.rs +++ b/src/librustc_llvm/lib.rs @@ -51,7 +51,7 @@ use std::ffi::CString; use std::cell::RefCell; -use std::{raw, mem}; +use std::{raw, mem, ptr}; use libc::{c_uint, c_ushort, uint64_t, c_int, size_t, c_char}; use libc::{c_longlong, c_ulonglong, c_void}; use debuginfo::{DIBuilderRef, DIDescriptor, @@ -2260,19 +2260,18 @@ pub unsafe fn static_link_hack_this_sucks() { LLVMInitializePowerPCAsmPrinter(); LLVMInitializePowerPCAsmParser(); - LLVMRustSetLLVMOptions(0 as c_int, - 0 as *const _); + LLVMRustSetLLVMOptions(0 as c_int, ptr::null()); - LLVMPassManagerBuilderPopulateModulePassManager(0 as *mut _, 0 as *mut _); - LLVMPassManagerBuilderPopulateLTOPassManager(0 as *mut _, 0 as *mut _, False, False); - LLVMPassManagerBuilderPopulateFunctionPassManager(0 as *mut _, 0 as *mut _); - LLVMPassManagerBuilderSetOptLevel(0 as *mut _, 0 as c_uint); - LLVMPassManagerBuilderUseInlinerWithThreshold(0 as *mut _, 0 as c_uint); - LLVMWriteBitcodeToFile(0 as *mut _, 0 as *const _); + LLVMPassManagerBuilderPopulateModulePassManager(ptr::null_mut(), ptr::null_mut()); + LLVMPassManagerBuilderPopulateLTOPassManager(ptr::null_mut(), ptr::null_mut(), False, False); + LLVMPassManagerBuilderPopulateFunctionPassManager(ptr::null_mut(), ptr::null_mut()); + LLVMPassManagerBuilderSetOptLevel(ptr::null_mut(), 0 as c_uint); + LLVMPassManagerBuilderUseInlinerWithThreshold(ptr::null_mut(), 0 as c_uint); + LLVMWriteBitcodeToFile(ptr::null_mut(), ptr::null()); LLVMPassManagerBuilderCreate(); - LLVMPassManagerBuilderDispose(0 as *mut _); + LLVMPassManagerBuilderDispose(ptr::null_mut()); - LLVMRustLinkInExternalBitcode(0 as *mut _, 0 as *const _, 0 as size_t); + LLVMRustLinkInExternalBitcode(ptr::null_mut(), ptr::null(), 0 as size_t); LLVMLinkInMCJIT(); LLVMLinkInInterpreter(); diff --git a/src/librustc_trans/trans/type_.rs b/src/librustc_trans/trans/type_.rs index 9cae142c03a..469d351f61a 100644 --- a/src/librustc_trans/trans/type_.rs +++ b/src/librustc_trans/trans/type_.rs @@ -21,6 +21,7 @@ use std::ffi::CString; use std::mem; +use std::ptr; use std::cell::RefCell; use std::iter::repeat; @@ -296,7 +297,7 @@ pub fn field_types(&self) -> Vec { if n_elts == 0 { return Vec::new(); } - let mut elts: Vec<_> = repeat(Type { rf: 0 as TypeRef }).take(n_elts).collect(); + let mut elts: Vec<_> = repeat(Type { rf: ptr::null_mut() }).take(n_elts).collect(); llvm::LLVMGetStructElementTypes(self.to_ref(), elts.as_mut_ptr() as *mut TypeRef); elts @@ -310,7 +311,7 @@ pub fn return_type(&self) -> Type { pub fn func_params(&self) -> Vec { unsafe { let n_args = llvm::LLVMCountParamTypes(self.to_ref()) as uint; - let mut args: Vec<_> = repeat(Type { rf: 0 as TypeRef }).take(n_args).collect(); + let mut args: Vec<_> = repeat(Type { rf: ptr::null_mut() }).take(n_args).collect(); llvm::LLVMGetParamTypes(self.to_ref(), args.as_mut_ptr() as *mut TypeRef); args diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index 9ee2f5705b8..a5664b9f013 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -40,6 +40,7 @@ use option::Option; use option::Option::{Some, None}; use ops::{Deref, DerefMut, FnOnce}; +use ptr; use result::Result::{Ok, Err}; use rt; use slice::SliceExt; @@ -238,7 +239,7 @@ pub fn stdin() -> StdinReader { // Make sure to free it at exit rt::at_exit(|| { mem::transmute::<_, Box>(STDIN); - STDIN = 0 as *const _; + STDIN = ptr::null(); }); }); diff --git a/src/libstd/sync/mpsc/mpsc_queue.rs b/src/libstd/sync/mpsc/mpsc_queue.rs index 83de98fdbff..ea81ed30a9c 100644 --- a/src/libstd/sync/mpsc/mpsc_queue.rs +++ b/src/libstd/sync/mpsc/mpsc_queue.rs @@ -46,6 +46,7 @@ use alloc::boxed::Box; use core::mem; +use core::ptr; use core::cell::UnsafeCell; use sync::atomic::{AtomicPtr, Ordering}; @@ -82,7 +83,7 @@ unsafe impl Sync for Queue { } impl Node { unsafe fn new(v: Option) -> *mut Node { mem::transmute(box Node { - next: AtomicPtr::new(0 as *mut Node), + next: AtomicPtr::new(ptr::null_mut()), value: v, }) } diff --git a/src/libstd/sync/mpsc/select.rs b/src/libstd/sync/mpsc/select.rs index 62a7b823ec8..3331411eee7 100644 --- a/src/libstd/sync/mpsc/select.rs +++ b/src/libstd/sync/mpsc/select.rs @@ -59,6 +59,7 @@ use core::cell::Cell; use core::marker; use core::mem; +use core::ptr; use core::uint; use sync::mpsc::{Receiver, RecvError}; @@ -130,8 +131,8 @@ impl Select { pub fn new() -> Select { Select { marker1: marker::NoSend, - head: 0 as *mut Handle<'static, ()>, - tail: 0 as *mut Handle<'static, ()>, + head: ptr::null_mut(), + tail: ptr::null_mut(), next_id: Cell::new(1), } } @@ -144,8 +145,8 @@ pub fn new() -> Select { #[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub fn new() -> Select { Select { - head: 0 as *mut Handle<'static, ()>, - tail: 0 as *mut Handle<'static, ()>, + head: ptr::null_mut(), + tail: ptr::null_mut(), next_id: Cell::new(1), } } @@ -159,8 +160,8 @@ pub fn handle<'a, T: Send>(&'a self, rx: &'a Receiver) -> Handle<'a, T> { Handle { id: id, selector: self, - next: 0 as *mut Handle<'static, ()>, - prev: 0 as *mut Handle<'static, ()>, + next: ptr::null_mut(), + prev: ptr::null_mut(), added: false, rx: rx, packet: rx, @@ -325,8 +326,8 @@ pub unsafe fn remove(&mut self) { (*self.next).prev = self.prev; } - self.next = 0 as *mut Handle<'static, ()>; - self.prev = 0 as *mut Handle<'static, ()>; + self.next = ptr::null_mut(); + self.prev = ptr::null_mut(); self.added = false; } diff --git a/src/libstd/sync/mpsc/spsc_queue.rs b/src/libstd/sync/mpsc/spsc_queue.rs index 34fd6bb70dc..8cd88cedf6b 100644 --- a/src/libstd/sync/mpsc/spsc_queue.rs +++ b/src/libstd/sync/mpsc/spsc_queue.rs @@ -39,6 +39,7 @@ use alloc::boxed::Box; use core::mem; +use core::ptr; use core::cell::UnsafeCell; use sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; @@ -82,7 +83,7 @@ fn new() -> *mut Node { unsafe { mem::transmute(box Node { value: None, - next: AtomicPtr::new(0 as *mut Node), + next: AtomicPtr::new(ptr::null_mut::>()), }) } } @@ -131,7 +132,7 @@ pub fn push(&self, t: T) { let n = self.alloc(); assert!((*n).value.is_none()); (*n).value = Some(t); - (*n).next.store(0 as *mut Node, Ordering::Relaxed); + (*n).next.store(ptr::null_mut(), Ordering::Relaxed); (**self.head.get()).next.store(n, Ordering::Release); *self.head.get() = n; } diff --git a/src/libstd/sync/mpsc/sync.rs b/src/libstd/sync/mpsc/sync.rs index 30304dffb75..d38f14a9130 100644 --- a/src/libstd/sync/mpsc/sync.rs +++ b/src/libstd/sync/mpsc/sync.rs @@ -40,6 +40,7 @@ use vec::Vec; use core::mem; +use core::ptr; use sync::atomic::{Ordering, AtomicUsize}; use sync::mpsc::blocking::{self, WaitToken, SignalToken}; @@ -145,8 +146,8 @@ pub fn new(cap: uint) -> Packet { cap: cap, canceled: None, queue: Queue { - head: 0 as *mut Node, - tail: 0 as *mut Node, + head: ptr::null_mut(), + tail: ptr::null_mut(), }, buf: Buffer { buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(), @@ -160,7 +161,7 @@ pub fn new(cap: uint) -> Packet { // wait until a send slot is available, returning locked access to // the channel state. fn acquire_send_slot(&self) -> MutexGuard> { - let mut node = Node { token: None, next: 0 as *mut Node }; + let mut node = Node { token: None, next: ptr::null_mut() }; loop { let mut guard = self.lock.lock().unwrap(); // are we ready to go? @@ -343,8 +344,8 @@ pub fn drop_port(&self) { Vec::new() }; let mut queue = mem::replace(&mut guard.queue, Queue { - head: 0 as *mut Node, - tail: 0 as *mut Node, + head: ptr::null_mut(), + tail: ptr::null_mut(), }); let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) { @@ -453,7 +454,7 @@ impl Queue { fn enqueue(&mut self, node: &mut Node) -> WaitToken { let (wait_token, signal_token) = blocking::tokens(); node.token = Some(signal_token); - node.next = 0 as *mut Node; + node.next = ptr::null_mut(); if self.tail.is_null() { self.head = node as *mut Node; @@ -475,10 +476,10 @@ fn dequeue(&mut self) -> Option { let node = self.head; self.head = unsafe { (*node).next }; if self.head.is_null() { - self.tail = 0 as *mut Node; + self.tail = ptr::null_mut(); } unsafe { - (*node).next = 0 as *mut Node; + (*node).next = ptr::null_mut(); Some((*node).token.take().unwrap()) } } diff --git a/src/libstd/sys/common/helper_thread.rs b/src/libstd/sys/common/helper_thread.rs index f940b6ed368..6f6179a436e 100644 --- a/src/libstd/sys/common/helper_thread.rs +++ b/src/libstd/sys/common/helper_thread.rs @@ -24,6 +24,7 @@ use cell::UnsafeCell; use mem; +use ptr; use rt; use sync::{StaticMutex, StaticCondvar}; use sync::mpsc::{channel, Sender, Receiver}; @@ -132,7 +133,7 @@ fn shutdown(&'static self) { // Close the channel by destroying it let chan: Box> = mem::transmute(*self.chan.get()); - *self.chan.get() = 0 as *mut Sender; + *self.chan.get() = ptr::null_mut(); drop(chan); helper_signal::signal(*self.signal.get() as helper_signal::signal); diff --git a/src/libstd/sys/unix/backtrace.rs b/src/libstd/sys/unix/backtrace.rs index 7164931c55a..3340a018d94 100644 --- a/src/libstd/sys/unix/backtrace.rs +++ b/src/libstd/sys/unix/backtrace.rs @@ -353,7 +353,7 @@ unsafe fn init_state() -> *mut backtrace_state { if state.is_null() { return output(w, idx, addr, None) } - let mut data = 0 as *const libc::c_char; + let mut data = ptr::null(); let data_addr = &mut data as *mut *const libc::c_char; let ret = unsafe { backtrace_syminfo(state, addr as libc::uintptr_t, diff --git a/src/libstd/sys/unix/condvar.rs b/src/libstd/sys/unix/condvar.rs index 85a65bbef50..3bc41473152 100644 --- a/src/libstd/sys/unix/condvar.rs +++ b/src/libstd/sys/unix/condvar.rs @@ -10,6 +10,7 @@ use cell::UnsafeCell; use libc; +use ptr; use std::option::Option::{Some, None}; use sys::mutex::{self, Mutex}; use sys::time; @@ -62,7 +63,7 @@ pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool { // time. let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 }; let stable_now = time::SteadyTime::now(); - let r = ffi::gettimeofday(&mut sys_now, 0 as *mut _); + let r = ffi::gettimeofday(&mut sys_now, ptr::null_mut()); debug_assert_eq!(r, 0); let seconds = NumCast::from(dur.num_seconds()); diff --git a/src/libstd/sys/unix/fs.rs b/src/libstd/sys/unix/fs.rs index c53f9d22790..dd478347f81 100644 --- a/src/libstd/sys/unix/fs.rs +++ b/src/libstd/sys/unix/fs.rs @@ -19,6 +19,7 @@ use io; use libc::{self, c_int, c_void}; use mem; +use ptr; use sys::retry; use sys_common::{keep_going, eof, mkerr_libc}; @@ -207,7 +208,7 @@ fn prune(root: &CString, dirs: Vec) -> Vec { if dir_ptr as uint != 0 { let mut paths = vec!(); - let mut entry_ptr = 0 as *mut dirent_t; + let mut entry_ptr = ptr::null_mut(); while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } { if entry_ptr.is_null() { break } paths.push(unsafe { diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index 175c4e2e353..2c25af055ee 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -143,7 +143,7 @@ pub unsafe fn get_env_pairs() -> Vec> { os::last_os_error()); } let mut result = Vec::new(); - while *environ != 0 as *const _ { + while *environ != ptr::null() { let env_pair = ffi::c_str_to_bytes(&*environ).to_vec(); result.push(env_pair); environ = environ.offset(1); diff --git a/src/libstd/sys/unix/process.rs b/src/libstd/sys/unix/process.rs index 36bf696dba5..0eab27de43a 100644 --- a/src/libstd/sys/unix/process.rs +++ b/src/libstd/sys/unix/process.rs @@ -251,7 +251,7 @@ fn fail(output: &mut FileDesc) -> ! { fn setgroups(ngroups: libc::c_int, ptr: *const libc::c_void) -> libc::c_int; } - let _ = setgroups(0, 0 as *const libc::c_void); + let _ = setgroups(0, ptr::null()); if libc::setuid(u as libc::uid_t) != 0 { fail(&mut output); diff --git a/src/libstd/sys/windows/backtrace.rs b/src/libstd/sys/windows/backtrace.rs index ee2dd14955b..ce6af9fab8b 100644 --- a/src/libstd/sys/windows/backtrace.rs +++ b/src/libstd/sys/windows/backtrace.rs @@ -327,7 +327,7 @@ macro_rules! sym{ ($e:expr, $t:ident) => (unsafe { let image = arch::init_frame(&mut frame, &context); // Initialize this process's symbols - let ret = SymInitialize(process, 0 as *mut libc::c_void, libc::TRUE); + let ret = SymInitialize(process, ptr::null_mut(), libc::TRUE); if ret != libc::TRUE { return Ok(()) } let _c = Cleanup { handle: process, SymCleanup: SymCleanup }; @@ -335,10 +335,10 @@ macro_rules! sym{ ($e:expr, $t:ident) => (unsafe { let mut i = 0i; try!(write!(w, "stack backtrace:\n")); while StackWalk64(image, process, thread, &mut frame, &mut context, - 0 as *mut libc::c_void, - 0 as *mut libc::c_void, - 0 as *mut libc::c_void, - 0 as *mut libc::c_void) == libc::TRUE{ + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut()) == libc::TRUE{ let addr = frame.AddrPC.Offset; if addr == frame.AddrReturn.Offset || addr == 0 || frame.AddrReturn.Offset == 0 { break } diff --git a/src/libstd/sys/windows/thread_local.rs b/src/libstd/sys/windows/thread_local.rs index d371023f218..83c116e9b05 100644 --- a/src/libstd/sys/windows/thread_local.rs +++ b/src/libstd/sys/windows/thread_local.rs @@ -137,7 +137,7 @@ unsafe fn init_dtors() { rt::at_exit(move|| { DTOR_LOCK.lock(); let dtors = DTORS; - DTORS = 0 as *mut _; + DTORS = ptr::null_mut(); mem::transmute::<_, Box>>(dtors); assert!(DTORS.is_null()); // can't re-init after destructing DTOR_LOCK.unlock(); @@ -250,7 +250,7 @@ unsafe fn run_dtors() { for &(key, dtor) in dtors.iter() { let ptr = TlsGetValue(key); if !ptr.is_null() { - TlsSetValue(key, 0 as *mut _); + TlsSetValue(key, ptr::null_mut()); dtor(ptr as *mut _); any_run = true; } diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index e7c4e4ccdfb..cd2a5134e3c 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -425,7 +425,7 @@ unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { dtor(ptr); } ptr = DTORS.get(); - DTORS.set(0 as *mut _); + DTORS.set(ptr::null_mut()); } } } @@ -522,7 +522,7 @@ unsafe fn ptr(&'static self) -> Option<*mut T> { let key = ptr.key; key.os.set(1 as *mut u8); drop(ptr); - key.os.set(0 as *mut u8); + key.os.set(ptr::null_mut()); } } From abccfa4018a407bbe80e8acd0f83c023664ea49a Mon Sep 17 00:00:00 2001 From: Peter Atashian Date: Mon, 19 Jan 2015 05:55:15 -0500 Subject: [PATCH 25/96] Impl Send for Timer on Windows Fixes #20943 Signed-off-by: Peter Atashian --- src/libstd/io/timer.rs | 6 ++++++ src/libstd/sys/windows/timer.rs | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/libstd/io/timer.rs b/src/libstd/io/timer.rs index 844a97dea2d..68ae7d0ff20 100644 --- a/src/libstd/io/timer.rs +++ b/src/libstd/io/timer.rs @@ -227,6 +227,12 @@ mod test { use thread::Thread; use time::Duration; + #[test] + fn test_timer_send() { + let mut timer = Timer::new().unwrap(); + Thread::spawn(move || timer.sleep(Duration::milliseconds(1))); + } + #[test] fn test_io_timer_sleep_simple() { let mut timer = Timer::new().unwrap(); diff --git a/src/libstd/sys/windows/timer.rs b/src/libstd/sys/windows/timer.rs index 1ae3979cd9a..12b4e56bf52 100644 --- a/src/libstd/sys/windows/timer.rs +++ b/src/libstd/sys/windows/timer.rs @@ -48,9 +48,9 @@ pub enum Req { RemoveTimer(libc::HANDLE, Sender<()>), } +unsafe impl Send for Timer {} unsafe impl Send for Req {} - fn helper(input: libc::HANDLE, messages: Receiver, _: ()) { let mut objs = vec![input]; let mut chans = vec![]; From d2623f2a9c2fd9ca4734cdcc25e61f66c479112a Mon Sep 17 00:00:00 2001 From: klutzy Date: Mon, 19 Jan 2015 22:58:39 +0900 Subject: [PATCH 26/96] rt: Remove libtime wrappers They are unused since libtime is gone. --- src/rt/rust_builtin.c | 138 ------------------------------------------ 1 file changed, 138 deletions(-) diff --git a/src/rt/rust_builtin.c b/src/rt/rust_builtin.c index 5dc07f859ae..03cd3fd6b88 100644 --- a/src/rt/rust_builtin.c +++ b/src/rt/rust_builtin.c @@ -41,29 +41,6 @@ //include valgrind.h after stdint.h so that uintptr_t is defined for msys2 w64 #include "valgrind/valgrind.h" -#ifdef __ANDROID__ -time_t -timegm(struct tm *tm) -{ - time_t ret; - char *tz; - - tz = getenv("TZ"); - if (tz) - tz = strdup(tz); - setenv("TZ", "", 1); - tzset(); - ret = mktime(tm); - if (tz) { - setenv("TZ", tz, 1); - free(tz); - } else - unsetenv("TZ"); - tzset(); - return ret; -} -#endif - #ifdef __APPLE__ #if (TARGET_OS_IPHONE) extern char **environ; @@ -100,121 +77,6 @@ rust_list_dir_val(struct dirent* entry_ptr) { } #endif -typedef struct { - int32_t tm_sec; - int32_t tm_min; - int32_t tm_hour; - int32_t tm_mday; - int32_t tm_mon; - int32_t tm_year; - int32_t tm_wday; - int32_t tm_yday; - int32_t tm_isdst; - int32_t tm_gmtoff; - int32_t tm_nsec; -} rust_tm; - -void rust_tm_to_tm(rust_tm* in_tm, struct tm* out_tm) { - memset(out_tm, 0, sizeof(struct tm)); - out_tm->tm_sec = in_tm->tm_sec; - out_tm->tm_min = in_tm->tm_min; - out_tm->tm_hour = in_tm->tm_hour; - out_tm->tm_mday = in_tm->tm_mday; - out_tm->tm_mon = in_tm->tm_mon; - out_tm->tm_year = in_tm->tm_year; - out_tm->tm_wday = in_tm->tm_wday; - out_tm->tm_yday = in_tm->tm_yday; - out_tm->tm_isdst = in_tm->tm_isdst; -} - -void tm_to_rust_tm(struct tm* in_tm, - rust_tm* out_tm, - int32_t gmtoff, - int32_t nsec) { - out_tm->tm_sec = in_tm->tm_sec; - out_tm->tm_min = in_tm->tm_min; - out_tm->tm_hour = in_tm->tm_hour; - out_tm->tm_mday = in_tm->tm_mday; - out_tm->tm_mon = in_tm->tm_mon; - out_tm->tm_year = in_tm->tm_year; - out_tm->tm_wday = in_tm->tm_wday; - out_tm->tm_yday = in_tm->tm_yday; - out_tm->tm_isdst = in_tm->tm_isdst; - out_tm->tm_gmtoff = gmtoff; - out_tm->tm_nsec = nsec; -} - -#if defined(__WIN32__) -#define TZSET() _tzset() -#if defined(_MSC_VER) && (_MSC_VER >= 1400) -#define GMTIME(clock, result) gmtime_s((result), (clock)) -#define LOCALTIME(clock, result) localtime_s((result), (clock)) -#define TIMEGM(result) _mkgmtime64(result) -#else -struct tm* GMTIME(const time_t *clock, struct tm *result) { - struct tm* t = gmtime(clock); - if (t == NULL || result == NULL) { return NULL; } - *result = *t; - return result; -} -struct tm* LOCALTIME(const time_t *clock, struct tm *result) { - struct tm* t = localtime(clock); - if (t == NULL || result == NULL) { return NULL; } - *result = *t; - return result; -} -#define TIMEGM(result) mktime((result)) - _timezone -#endif -#else -#define TZSET() tzset() -#define GMTIME(clock, result) gmtime_r((clock), (result)) -#define LOCALTIME(clock, result) localtime_r((clock), (result)) -#define TIMEGM(result) timegm(result) -#endif - -void -rust_tzset() { - TZSET(); -} - -void -rust_gmtime(int64_t sec, int32_t nsec, rust_tm *timeptr) { - struct tm tm; - time_t s = sec; - GMTIME(&s, &tm); - - tm_to_rust_tm(&tm, timeptr, 0, nsec); -} - -void -rust_localtime(int64_t sec, int32_t nsec, rust_tm *timeptr) { - struct tm tm; - time_t s = sec; - LOCALTIME(&s, &tm); - -#if defined(__WIN32__) - int32_t gmtoff = -timezone; -#else - int32_t gmtoff = tm.tm_gmtoff; -#endif - - tm_to_rust_tm(&tm, timeptr, gmtoff, nsec); -} - -int64_t -rust_timegm(rust_tm* timeptr) { - struct tm t; - rust_tm_to_tm(timeptr, &t); - return TIMEGM(&t); -} - -int64_t -rust_mktime(rust_tm* timeptr) { - struct tm t; - rust_tm_to_tm(timeptr, &t); - return mktime(&t); -} - #ifndef _WIN32 DIR* From 74e111caf6d9634917f77977a4e51e562498be87 Mon Sep 17 00:00:00 2001 From: Jorge Aparicio Date: Mon, 19 Jan 2015 09:48:05 -0500 Subject: [PATCH 27/96] impl Iterator for &mut Iterator and Box closes #20953 closes #21361 --- src/liballoc/boxed.rs | 11 +++++++++++ src/liballoc/lib.rs | 2 ++ src/libcore/iter.rs | 10 ++++++++++ src/libcore/lib.rs | 2 ++ src/test/run-pass/issue-20953.rs | 19 +++++++++++++++++++ src/test/run-pass/issue-21361.rs | 19 +++++++++++++++++++ 6 files changed, 63 insertions(+) create mode 100644 src/test/run-pass/issue-20953.rs create mode 100644 src/test/run-pass/issue-21361.rs diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 8ad0c152dc8..89de2c953e4 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -18,6 +18,7 @@ use core::default::Default; use core::fmt; use core::hash::{self, Hash}; +use core::iter::Iterator; use core::marker::Sized; use core::mem; use core::option::Option; @@ -185,6 +186,16 @@ impl DerefMut for Box { fn deref_mut(&mut self) -> &mut T { &mut **self } } +// FIXME(#21363) remove `old_impl_check` when bug is fixed +#[old_impl_check] +impl<'a, T> Iterator for Box + 'a> { + type Item = T; + + fn next(&mut self) -> Option { + (**self).next() + } +} + #[cfg(test)] mod test { #[test] diff --git a/src/liballoc/lib.rs b/src/liballoc/lib.rs index 811e32e747d..47715fe9e5d 100644 --- a/src/liballoc/lib.rs +++ b/src/liballoc/lib.rs @@ -70,6 +70,8 @@ #![feature(lang_items, unsafe_destructor)] #![feature(box_syntax)] #![feature(optin_builtin_traits)] +// FIXME(#21363) remove `old_impl_check` when bug is fixed +#![feature(old_impl_check)] #![allow(unknown_features)] #![feature(int_uint)] #[macro_use] diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 0005db36c27..3d51f75d9b3 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -99,6 +99,16 @@ pub trait Iterator { fn size_hint(&self) -> (uint, Option) { (0, None) } } +// FIXME(#21363) remove `old_impl_check` when bug is fixed +#[old_impl_check] +impl<'a, T> Iterator for &'a mut (Iterator + 'a) { + type Item = T; + + fn next(&mut self) -> Option { + (**self).next() + } +} + /// Conversion from an `Iterator` #[stable] #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \ diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 0b150d1ecf9..f7ba07fd2a6 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -63,6 +63,8 @@ #![feature(unboxed_closures)] #![allow(unknown_features)] #![feature(int_uint)] #![feature(on_unimplemented)] +// FIXME(#21363) remove `old_impl_check` when bug is fixed +#![feature(old_impl_check)] #![deny(missing_docs)] #[macro_use] diff --git a/src/test/run-pass/issue-20953.rs b/src/test/run-pass/issue-20953.rs new file mode 100644 index 00000000000..647302bbc93 --- /dev/null +++ b/src/test/run-pass/issue-20953.rs @@ -0,0 +1,19 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn main() { + let mut shrinker: Box> = Box::new(vec![1].into_iter()); + println!("{:?}", shrinker.next()); + for v in shrinker { assert!(false); } + + let mut shrinker: &mut Iterator = &mut vec![1].into_iter(); + println!("{:?}", shrinker.next()); + for v in shrinker { assert!(false); } +} diff --git a/src/test/run-pass/issue-21361.rs b/src/test/run-pass/issue-21361.rs new file mode 100644 index 00000000000..bb20b3a3215 --- /dev/null +++ b/src/test/run-pass/issue-21361.rs @@ -0,0 +1,19 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn main() { + let v = vec![1, 2, 3]; + let boxed: Box> = Box::new(v.into_iter()); + assert_eq!(boxed.max(), Some(3)); + + let v = vec![1, 2, 3]; + let boxed: &mut Iterator = &mut v.into_iter(); + assert_eq!(boxed.max(), Some(3)); +} From 8c3d914ca469fa603b7872514de2c55e9df4dd77 Mon Sep 17 00:00:00 2001 From: Logan Chien Date: Tue, 20 Jan 2015 00:41:53 +0800 Subject: [PATCH 28/96] Change the title of if statement in trpl book. --- src/doc/trpl/if.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/trpl/if.md b/src/doc/trpl/if.md index ea1da167458..a350df67b17 100644 --- a/src/doc/trpl/if.md +++ b/src/doc/trpl/if.md @@ -1,4 +1,4 @@ -% `if` +% If Rust's take on `if` is not particularly complex, but it's much more like the `if` you'll find in a dynamically typed language than in a more traditional From 49684850bedcef007a2949c97872606d1d6dc325 Mon Sep 17 00:00:00 2001 From: Jorge Aparicio Date: Mon, 19 Jan 2015 11:07:13 -0500 Subject: [PATCH 29/96] remove unnecessary parentheses from range notation --- src/libcollections/bit.rs | 2 +- src/libcollections/vec.rs | 4 ++-- src/libcore/slice.rs | 8 ++++---- src/libcore/str/mod.rs | 2 +- src/libcoretest/iter.rs | 2 +- src/libgetopts/lib.rs | 2 +- src/libregex/parse.rs | 2 +- src/librustc/metadata/decoder.rs | 2 +- src/librustc/metadata/tydecode.rs | 2 +- src/librustc/middle/check_match.rs | 2 +- src/librustc/util/ppaux.rs | 6 +++--- src/librustc_back/sha2.rs | 2 +- src/librustc_resolve/lib.rs | 6 +++--- src/librustc_trans/back/link.rs | 2 +- src/librustc_trans/back/lto.rs | 4 ++-- src/librustc_trans/save/mod.rs | 2 +- src/librustc_trans/trans/_match.rs | 4 ++-- src/librustc_trans/trans/cabi_x86_64.rs | 2 +- src/librustc_trans/trans/debuginfo.rs | 4 ++-- src/librustdoc/html/format.rs | 2 +- src/librustdoc/html/render.rs | 12 ++++++------ src/libserialize/json.rs | 4 ++-- src/libstd/io/buffered.rs | 4 ++-- src/libstd/io/mem.rs | 4 ++-- src/libstd/io/mod.rs | 2 +- src/libstd/path/mod.rs | 2 +- src/libstd/path/posix.rs | 10 +++++----- src/libstd/path/windows.rs | 14 +++++++------- src/libstd/sys/windows/backtrace.rs | 2 +- src/libsyntax/ast_map/mod.rs | 2 +- src/libsyntax/diagnostic.rs | 2 +- src/libsyntax/parse/lexer/comments.rs | 4 ++-- src/libterm/terminfo/parser/compiled.rs | 4 ++-- src/test/bench/shootout-fannkuch-redux.rs | 2 +- src/test/bench/shootout-fasta.rs | 2 +- src/test/bench/shootout-k-nucleotide-pipes.rs | 4 ++-- src/test/compile-fail/range-1.rs | 2 +- src/test/compile-fail/range-2.rs | 2 +- 38 files changed, 70 insertions(+), 70 deletions(-) diff --git a/src/libcollections/bit.rs b/src/libcollections/bit.rs index efd056b0d66..13e7e88d516 100644 --- a/src/libcollections/bit.rs +++ b/src/libcollections/bit.rs @@ -330,7 +330,7 @@ pub fn from_bytes(bytes: &[u8]) -> Bitv { if extra_bytes > 0 { let mut last_word = 0u32; - for (i, &byte) in bytes[(complete_words*4)..].iter().enumerate() { + for (i, &byte) in bytes[complete_words*4..].iter().enumerate() { last_word |= (reverse_bits(byte) as u32) << (i * 8); } bitv.storage.push(last_word); diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 689d96b4b29..27232007d92 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -2158,7 +2158,7 @@ fn test_index_out_of_bounds() { #[should_fail] fn test_slice_out_of_bounds_1() { let x: Vec = vec![1, 2, 3, 4, 5]; - &x[(-1)..]; + &x[-1..]; } #[test] @@ -2172,7 +2172,7 @@ fn test_slice_out_of_bounds_2() { #[should_fail] fn test_slice_out_of_bounds_3() { let x: Vec = vec![1, 2, 3, 4, 5]; - &x[(-1)..4]; + &x[-1..4]; } #[test] diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 22da168911d..4c97472c001 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -240,7 +240,7 @@ fn tail(&self) -> &[T] { &self[1..] } #[inline] fn init(&self) -> &[T] { - &self[..(self.len() - 1)] + &self[..self.len() - 1] } #[inline] @@ -449,7 +449,7 @@ fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq { #[inline] fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq { let (m, n) = (self.len(), needle.len()); - m >= n && needle == &self[(m-n)..] + m >= n && needle == &self[m-n..] } #[unstable] @@ -973,7 +973,7 @@ fn next(&mut self) -> Option<&'a [T]> { None => self.finish(), Some(idx) => { let ret = Some(&self.v[..idx]); - self.v = &self.v[(idx + 1)..]; + self.v = &self.v[idx + 1..]; ret } } @@ -998,7 +998,7 @@ fn next_back(&mut self) -> Option<&'a [T]> { match self.v.iter().rposition(|x| (self.pred)(x)) { None => self.finish(), Some(idx) => { - let ret = Some(&self.v[(idx + 1)..]); + let ret = Some(&self.v[idx + 1..]); self.v = &self.v[..idx]; ret } diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index d9cf6dc086d..a54d8570795 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -1418,7 +1418,7 @@ fn starts_with(&self, needle: &str) -> bool { #[inline] fn ends_with(&self, needle: &str) -> bool { let (m, n) = (self.len(), needle.len()); - m >= n && needle.as_bytes() == &self.as_bytes()[(m-n)..] + m >= n && needle.as_bytes() == &self.as_bytes()[m-n..] } #[inline] diff --git a/src/libcoretest/iter.rs b/src/libcoretest/iter.rs index 26819bf9209..4bbbde6b48c 100644 --- a/src/libcoretest/iter.rs +++ b/src/libcoretest/iter.rs @@ -585,7 +585,7 @@ fn check_randacc_iter(a: T, len: uint) where fn test_double_ended_flat_map() { let u = [0u,1]; let v = [5u,6,7,8]; - let mut it = u.iter().flat_map(|x| v[(*x)..v.len()].iter()); + let mut it = u.iter().flat_map(|x| v[*x..v.len()].iter()); assert_eq!(it.next_back().unwrap(), &8); assert_eq!(it.next().unwrap(), &5); assert_eq!(it.next_back().unwrap(), &7); diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index c2114d4c6df..86dad55a318 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -893,7 +893,7 @@ fn each_split_within(ss: &str, lim: uint, mut it: F) -> bool where (B, Cr, UnderLim) => { B } (B, Cr, OverLim) if (i - last_start + 1) > lim => panic!("word starting with {} longer than limit!", - &ss[last_start..(i + 1)]), + &ss[last_start..i + 1]), (B, Cr, OverLim) => { *cont = it(&ss[slice_start..last_end]); slice_start = last_start; diff --git a/src/libregex/parse.rs b/src/libregex/parse.rs index 1cc2b271e9c..a54db2654ab 100644 --- a/src/libregex/parse.rs +++ b/src/libregex/parse.rs @@ -518,7 +518,7 @@ fn parse_counted(&mut self) -> Result<(), Error> { }; self.chari = closer; let greed = try!(self.get_next_greedy()); - let inner = self.chars[(start+1)..closer].iter().cloned() + let inner = self.chars[start+1..closer].iter().cloned() .collect::(); // Parse the min and max values from the regex. diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 6bf1798d246..1197276b990 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -74,7 +74,7 @@ fn lookup_hash<'a, F>(d: rbml::Doc<'a>, mut eq_fn: F, hash: u64) -> Option ast::DefId { } let crate_part = &buf[0u..colon_idx]; - let def_part = &buf[(colon_idx + 1u)..len]; + let def_part = &buf[colon_idx + 1u..len]; let crate_num = match str::from_utf8(crate_part).ok().and_then(|s| s.parse::()) { Some(cn) => cn as ast::CrateNum, diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index a1a90395b3b..92603174266 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -927,7 +927,7 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat], }; head.map(|mut head| { head.push_all(&r[..col]); - head.push_all(&r[(col + 1)..]); + head.push_all(&r[col + 1..]); head }) } diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index fb44d0cadfa..1be6c84f8e9 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -542,7 +542,7 @@ pub fn parameterized<'tcx>(cx: &ctxt<'tcx>, 0 }; - for t in tps[..(tps.len() - num_defaults)].iter() { + for t in tps[..tps.len() - num_defaults].iter() { strs.push(ty_to_string(cx, *t)) } @@ -550,9 +550,9 @@ pub fn parameterized<'tcx>(cx: &ctxt<'tcx>, format!("{}({}){}", base, if strs[0].starts_with("(") && strs[0].ends_with(",)") { - &strs[0][1 .. (strs[0].len() - 2)] // Remove '(' and ',)' + &strs[0][1 .. strs[0].len() - 2] // Remove '(' and ',)' } else if strs[0].starts_with("(") && strs[0].ends_with(")") { - &strs[0][1 .. (strs[0].len() - 1)] // Remove '(' and ')' + &strs[0][1 .. strs[0].len() - 1] // Remove '(' and ')' } else { &strs[0][] }, diff --git a/src/librustc_back/sha2.rs b/src/librustc_back/sha2.rs index e376ac50dcd..0228098b8f8 100644 --- a/src/librustc_back/sha2.rs +++ b/src/librustc_back/sha2.rs @@ -156,7 +156,7 @@ fn input(&mut self, input: &[u8], mut func: F) where // While we have at least a full buffer size chunk's worth of data, process that data // without copying it into the buffer while input.len() - i >= size { - func(&input[i..(i + size)]); + func(&input[i..i + size]); i += size; } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 8c1e847748c..7353de8f260 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -2082,8 +2082,8 @@ fn resolve_module_path(&mut self, let msg = format!("Could not find `{}` in `{}`", // idx +- 1 to account for the // colons on either side - &mpath[(idx + 1)..], - &mpath[..(idx - 1)]); + &mpath[idx + 1..], + &mpath[..idx - 1]); return Failed(Some((span, msg))); }, None => { @@ -2756,7 +2756,7 @@ fn search_ribs(&self, for (i, rib) in ribs.iter().enumerate().rev() { match rib.bindings.get(&name).cloned() { Some(def_like) => { - return self.upvarify(&ribs[(i + 1)..], def_like, span); + return self.upvarify(&ribs[i + 1..], def_like, span); } None => { // Continue. diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index dacf620cbd1..cfb8c88ce40 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -1183,7 +1183,7 @@ fn add_static_crate(cmd: &mut Command, sess: &Session, tmpdir: &Path, // against the archive. if sess.lto() { let name = cratepath.filename_str().unwrap(); - let name = &name[3..(name.len() - 5)]; // chop off lib/.rlib + let name = &name[3..name.len() - 5]; // chop off lib/.rlib time(sess.time_passes(), &format!("altering {}.rlib", name)[], (), |()| { diff --git a/src/librustc_trans/back/lto.rs b/src/librustc_trans/back/lto.rs index c0b1492a784..590354ab54e 100644 --- a/src/librustc_trans/back/lto.rs +++ b/src/librustc_trans/back/lto.rs @@ -60,7 +60,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, let archive = ArchiveRO::open(&path).expect("wanted an rlib"); let file = path.filename_str().unwrap(); - let file = &file[3..(file.len() - 5)]; // chop off lib/.rlib + let file = &file[3..file.len() - 5]; // chop off lib/.rlib debug!("reading {}", file); for i in iter::count(0u, 1) { let bc_encoded = time(sess.time_passes(), @@ -201,7 +201,7 @@ fn extract_compressed_bytecode_size_v1(bc: &[u8]) -> u64 { } fn read_from_le_bytes(bytes: &[u8], position_in_bytes: uint) -> T { - let byte_data = &bytes[position_in_bytes..(position_in_bytes + mem::size_of::())]; + let byte_data = &bytes[position_in_bytes..position_in_bytes + mem::size_of::()]; let data = unsafe { *(byte_data.as_ptr() as *const T) }; diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index b12903c814c..f5bf8b2d3e3 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -186,7 +186,7 @@ fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) { if len <= 2 { return; } - let sub_paths = &sub_paths[..(len-2)]; + let sub_paths = &sub_paths[..len-2]; for &(ref span, ref qualname) in sub_paths.iter() { self.fmt.sub_mod_ref_str(path.span, *span, diff --git a/src/librustc_trans/trans/_match.rs b/src/librustc_trans/trans/_match.rs index be927503bad..4fc3159ad46 100644 --- a/src/librustc_trans/trans/_match.rs +++ b/src/librustc_trans/trans/_match.rs @@ -472,7 +472,7 @@ fn enter_default<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>, enter_match(bcx, dm, m, col, val, |pats| { if pat_is_binding_or_wild(dm, &*pats[col]) { let mut r = pats[..col].to_vec(); - r.push_all(&pats[(col + 1)..]); + r.push_all(&pats[col + 1..]); Some(r) } else { None @@ -983,7 +983,7 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, let dm = &tcx.def_map; let mut vals_left = vals[0u..col].to_vec(); - vals_left.push_all(&vals[(col + 1u)..]); + vals_left.push_all(&vals[col + 1u..]); let ccx = bcx.fcx.ccx; // Find a real id (we're adding placeholder wildcard patterns, but diff --git a/src/librustc_trans/trans/cabi_x86_64.rs b/src/librustc_trans/trans/cabi_x86_64.rs index 980a70256e9..3c0530bbb9a 100644 --- a/src/librustc_trans/trans/cabi_x86_64.rs +++ b/src/librustc_trans/trans/cabi_x86_64.rs @@ -361,7 +361,7 @@ fn llvec_len(cls: &[RegClass]) -> uint { } _ => unreachable!(), }; - let vec_len = llvec_len(&cls[(i + 1u)..]); + let vec_len = llvec_len(&cls[i + 1u..]); let vec_ty = Type::vector(&elt_ty, vec_len as u64 * elts_per_word); tys.push(vec_ty); i += vec_len; diff --git a/src/librustc_trans/trans/debuginfo.rs b/src/librustc_trans/trans/debuginfo.rs index ea66b97bbf9..cda9110e024 100644 --- a/src/librustc_trans/trans/debuginfo.rs +++ b/src/librustc_trans/trans/debuginfo.rs @@ -1163,7 +1163,7 @@ pub fn get_cleanup_debug_loc_for_ast_node<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, if let Some(code_snippet) = code_snippet { let bytes = code_snippet.as_bytes(); - if bytes.len() > 0 && &bytes[(bytes.len()-1)..] == b"}" { + if bytes.len() > 0 && &bytes[bytes.len()-1..] == b"}" { cleanup_span = Span { lo: node_span.hi - codemap::BytePos(1), hi: node_span.hi, @@ -1752,7 +1752,7 @@ fn file_metadata(cx: &CrateContext, full_path: &str) -> DIFile { let work_dir = cx.sess().working_dir.as_str().unwrap(); let file_name = if full_path.starts_with(work_dir) { - &full_path[(work_dir.len() + 1u)..full_path.len()] + &full_path[work_dir.len() + 1u..full_path.len()] } else { full_path }; diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 57b8d666c95..928618467c4 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -358,7 +358,7 @@ fn path(w: &mut fmt::Formatter, // This is a documented path, link to it! Some((ref fqp, shortty)) if abs_root.is_some() => { let mut url = String::from_str(abs_root.unwrap().as_slice()); - let to_link = &fqp[..(fqp.len() - 1)]; + let to_link = &fqp[..fqp.len() - 1]; for component in to_link.iter() { url.push_str(component.as_slice()); url.push_str("/"); diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 839dfa339b3..403bd1c2961 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -404,7 +404,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult search_index.push(IndexItem { ty: shortty(item), name: item.name.clone().unwrap(), - path: fqp[..(fqp.len() - 1)].connect("::"), + path: fqp[..fqp.len() - 1].connect("::"), desc: shorter(item.doc_value()).to_string(), parent: Some(did), }); @@ -559,7 +559,7 @@ fn collect(path: &Path, krate: &str, }; let mut mydst = dst.clone(); - for part in remote_path[..(remote_path.len() - 1)].iter() { + for part in remote_path[..remote_path.len() - 1].iter() { mydst.push(part.as_slice()); try!(mkdir(&mydst)); } @@ -842,7 +842,7 @@ fn fold_item(&mut self, item: clean::Item) -> Option { clean::StructFieldItem(..) | clean::VariantItem(..) => { ((Some(*self.parent_stack.last().unwrap()), - Some(&self.stack[..(self.stack.len() - 1)])), + Some(&self.stack[..self.stack.len() - 1])), false) } clean::MethodItem(..) => { @@ -853,13 +853,13 @@ fn fold_item(&mut self, item: clean::Item) -> Option { let did = *last; let path = match self.paths.get(&did) { Some(&(_, ItemType::Trait)) => - Some(&self.stack[..(self.stack.len() - 1)]), + Some(&self.stack[..self.stack.len() - 1]), // The current stack not necessarily has correlation for // where the type was defined. On the other hand, // `paths` always has the right information if present. Some(&(ref fqp, ItemType::Struct)) | Some(&(ref fqp, ItemType::Enum)) => - Some(&fqp[..(fqp.len() - 1)]), + Some(&fqp[..fqp.len() - 1]), Some(..) => Some(self.stack.as_slice()), None => None }; @@ -1185,7 +1185,7 @@ fn render(w: io::File, cx: &Context, it: &clean::Item, .collect::(); match cache().paths.get(&it.def_id) { Some(&(ref names, _)) => { - for name in (&names[..(names.len() - 1)]).iter() { + for name in (&names[..names.len() - 1]).iter() { url.push_str(name.as_slice()); url.push_str("/"); } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 41499b5ae0e..92e2bd622d4 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -1222,7 +1222,7 @@ pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> { InternalIndex(i) => StackElement::Index(i), InternalKey(start, size) => { StackElement::Key(str::from_utf8( - &self.str_buffer[(start as uint) .. (start as uint + size as uint)]) + &self.str_buffer[start as uint .. start as uint + size as uint]) .unwrap()) } } @@ -1265,7 +1265,7 @@ pub fn top<'l>(&'l self) -> Option> { Some(&InternalIndex(i)) => Some(StackElement::Index(i)), Some(&InternalKey(start, size)) => { Some(StackElement::Key(str::from_utf8( - &self.str_buffer[(start as uint) .. (start+size) as uint] + &self.str_buffer[start as uint .. (start+size) as uint] ).unwrap())) } } diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 8c38bc009cc..542a2d45237 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -281,9 +281,9 @@ impl Writer for LineBufferedWriter { fn write(&mut self, buf: &[u8]) -> IoResult<()> { match buf.iter().rposition(|&b| b == b'\n') { Some(i) => { - try!(self.inner.write(&buf[..(i + 1)])); + try!(self.inner.write(&buf[..i + 1])); try!(self.inner.flush()); - try!(self.inner.write(&buf[(i + 1)..])); + try!(self.inner.write(&buf[i + 1..])); Ok(()) } None => self.inner.write(buf), diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index ee05a9e5596..8d3c4f3053b 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -159,7 +159,7 @@ fn read(&mut self, buf: &mut [u8]) -> IoResult { let write_len = min(buf.len(), self.buf.len() - self.pos); { - let input = &self.buf[self.pos.. (self.pos + write_len)]; + let input = &self.buf[self.pos.. self.pos + write_len]; let output = buf.slice_to_mut(write_len); assert_eq!(input.len(), output.len()); slice::bytes::copy_memory(output, input); @@ -349,7 +349,7 @@ fn read(&mut self, buf: &mut [u8]) -> IoResult { let write_len = min(buf.len(), self.buf.len() - self.pos); { - let input = &self.buf[self.pos.. (self.pos + write_len)]; + let input = &self.buf[self.pos.. self.pos + write_len]; let output = buf.slice_to_mut(write_len); assert_eq!(input.len(), output.len()); slice::bytes::copy_memory(output, input); diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index e2b71cd43af..d1ce0125fbb 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -1449,7 +1449,7 @@ fn read_until(&mut self, byte: u8) -> IoResult> { }; match available.iter().position(|&b| b == byte) { Some(i) => { - res.push_all(&available[..(i + 1)]); + res.push_all(&available[..i + 1]); used = i + 1; break } diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 541f1e77140..f4b99b4c793 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -399,7 +399,7 @@ fn extension<'a>(&'a self) -> Option<&'a [u8]> { match name.rposition_elem(&dot) { None | Some(0) => None, Some(1) if name == b".." => None, - Some(pos) => Some(&name[(pos+1)..]) + Some(pos) => Some(&name[pos+1..]) } } } diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index aab64639ab5..422e2cedc48 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -126,7 +126,7 @@ unsafe fn set_filename_unchecked(&mut self, filename: T) { None => { self.repr = Path::normalize(filename); } - Some(idx) if &self.repr[(idx+1)..] == b".." => { + Some(idx) if &self.repr[idx+1..] == b".." => { let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len()); v.push_all(self.repr.as_slice()); v.push(SEP_BYTE); @@ -136,7 +136,7 @@ unsafe fn set_filename_unchecked(&mut self, filename: T) { } Some(idx) => { let mut v = Vec::with_capacity(idx + 1 + filename.len()); - v.push_all(&self.repr[..(idx+1)]); + v.push_all(&self.repr[..idx+1]); v.push_all(filename); // FIXME: this is slow self.repr = Path::normalize(v.as_slice()); @@ -178,7 +178,7 @@ fn dirname<'a>(&'a self) -> &'a [u8] { None if b".." == self.repr => self.repr.as_slice(), None => dot_static, Some(0) => &self.repr[..1], - Some(idx) if &self.repr[(idx+1)..] == b".." => self.repr.as_slice(), + Some(idx) if &self.repr[idx+1..] == b".." => self.repr.as_slice(), Some(idx) => &self.repr[..idx] } } @@ -188,9 +188,9 @@ fn filename<'a>(&'a self) -> Option<&'a [u8]> { None if b"." == self.repr || b".." == self.repr => None, None => Some(self.repr.as_slice()), - Some(idx) if &self.repr[(idx+1)..] == b".." => None, + Some(idx) if &self.repr[idx+1..] == b".." => None, Some(0) if self.repr[1..].is_empty() => None, - Some(idx) => Some(&self.repr[(idx+1)..]) + Some(idx) => Some(&self.repr[idx+1..]) } } diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 3cff1c67be3..6802b411d1e 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -428,10 +428,10 @@ fn root_path(&self) -> Option { if self.prefix.is_some() { Some(Path::new(match self.prefix { Some(DiskPrefix) if self.is_absolute() => { - &self.repr[..(self.prefix_len()+1)] + &self.repr[..self.prefix_len()+1] } Some(VerbatimDiskPrefix) => { - &self.repr[..(self.prefix_len()+1)] + &self.repr[..self.prefix_len()+1] } _ => &self.repr[..self.prefix_len()] })) @@ -635,7 +635,7 @@ pub fn str_components<'a>(&'a self) -> StrComponents<'a> { Some(_) => { let plen = self.prefix_len(); if repr.len() > plen && repr.as_bytes()[plen] == SEP_BYTE { - &repr[(plen+1)..] + &repr[plen+1..] } else { &repr[plen..] } } None if repr.as_bytes()[0] == SEP_BYTE => &repr[1..], @@ -786,9 +786,9 @@ fn normalize__(s: &str, prefix: Option) -> Option { } Some(UNCPrefix(a,b)) => { s.push_str("\\\\"); - s.push_str(&prefix_[2..(a+2)]); + s.push_str(&prefix_[2..a+2]); s.push(SEP); - s.push_str(&prefix_[(3+a)..(3+a+b)]); + s.push_str(&prefix_[3+a..3+a+b]); } Some(_) => s.push_str(prefix_), None => () @@ -813,7 +813,7 @@ fn normalize__(s: &str, prefix: Option) -> Option { fn update_sepidx(&mut self) { let s = if self.has_nonsemantic_trailing_slash() { - &self.repr[..(self.repr.len()-1)] + &self.repr[..self.repr.len()-1] } else { &self.repr[] }; let sep_test: fn(char) -> bool = if !prefix_is_verbatim(self.prefix) { is_sep @@ -1029,7 +1029,7 @@ fn parse_two_comps(mut path: &str, f: fn(char) -> bool) -> Option<(uint, uint)> None => return None, Some(x) => x }; - path = &path[(idx_a+1)..]; + path = &path[idx_a+1..]; let idx_b = path.find(f).unwrap_or(path.len()); Some((idx_a, idx_b)) } diff --git a/src/libstd/sys/windows/backtrace.rs b/src/libstd/sys/windows/backtrace.rs index ee2dd14955b..03a23214cf3 100644 --- a/src/libstd/sys/windows/backtrace.rs +++ b/src/libstd/sys/windows/backtrace.rs @@ -362,7 +362,7 @@ macro_rules! sym{ ($e:expr, $t:ident) => (unsafe { let bytes = unsafe { ffi::c_str_to_bytes(&ptr) }; match str::from_utf8(bytes) { Ok(s) => try!(demangle(w, s)), - Err(..) => try!(w.write(&bytes[..(bytes.len()-1)])), + Err(..) => try!(w.write(&bytes[..bytes.len()-1])), } } try!(w.write(&['\n' as u8])); diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index f462a730d3a..baa9516ae5d 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -525,7 +525,7 @@ pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String]) NodesMatchingSuffix { map: self, item_name: parts.last().unwrap(), - in_which: &parts[..(parts.len() - 1)], + in_which: &parts[..parts.len() - 1], idx: 0, } } diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 7213b0fa955..745343ade63 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -280,7 +280,7 @@ fn print_maybe_styled(w: &mut EmitterWriter, // to be miscolored. We assume this is rare enough that we don't // have to worry about it. if msg.ends_with("\n") { - try!(t.write_str(&msg[..(msg.len()-1)])); + try!(t.write_str(&msg[..msg.len()-1])); try!(t.reset()); try!(t.write_str("\n")); } else { diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index 16ade904be8..79a85e9afbd 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -116,7 +116,7 @@ fn horizontal_trim(lines: Vec ) -> Vec { if can_trim { lines.iter().map(|line| { - (&line[(i + 1)..line.len()]).to_string() + (&line[i + 1..line.len()]).to_string() }).collect() } else { lines @@ -132,7 +132,7 @@ fn horizontal_trim(lines: Vec ) -> Vec { } if comment.starts_with("/*") { - let lines = comment[3u..(comment.len() - 2u)] + let lines = comment[3u..comment.len() - 2u] .lines_any() .map(|s| s.to_string()) .collect:: >(); diff --git a/src/libterm/terminfo/parser/compiled.rs b/src/libterm/terminfo/parser/compiled.rs index 4735b6e8f2a..eb300beae9f 100644 --- a/src/libterm/terminfo/parser/compiled.rs +++ b/src/libterm/terminfo/parser/compiled.rs @@ -284,12 +284,12 @@ macro_rules! try { ($e:expr) => ( // Find the offset of the NUL we want to go to - let nulpos = string_table[(offset as uint) .. (string_table_bytes as uint)] + let nulpos = string_table[offset as uint .. string_table_bytes as uint] .iter().position(|&b| b == 0); match nulpos { Some(len) => { string_map.insert(name.to_string(), - string_table[(offset as uint) .. + string_table[offset as uint .. (offset as uint + len)].to_vec()) }, None => { diff --git a/src/test/bench/shootout-fannkuch-redux.rs b/src/test/bench/shootout-fannkuch-redux.rs index e8e8ac48485..daabae88bdf 100644 --- a/src/test/bench/shootout-fannkuch-redux.rs +++ b/src/test/bench/shootout-fannkuch-redux.rs @@ -103,7 +103,7 @@ fn get(&mut self, mut idx: i32) -> P { let d = idx / self.fact[i] as i32; self.cnt[i] = d; idx %= self.fact[i] as i32; - for (place, val) in pp.iter_mut().zip(self.perm.p[..(i+1)].iter()) { + for (place, val) in pp.iter_mut().zip(self.perm.p[..i+1].iter()) { *place = (*val) as u8 } diff --git a/src/test/bench/shootout-fasta.rs b/src/test/bench/shootout-fasta.rs index e9da34615c1..1b849cd12f5 100644 --- a/src/test/bench/shootout-fasta.rs +++ b/src/test/bench/shootout-fasta.rs @@ -97,7 +97,7 @@ fn make_fasta>( } n -= nb; line[nb] = '\n' as u8; - try!(wr.write(&line[..(nb+1)])); + try!(wr.write(&line[..nb+1])); } Ok(()) } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 03268b40193..fdaeb9e74f5 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -101,11 +101,11 @@ fn windows_with_carry(bb: &[u8], nn: uint, mut it: F) -> Vec where let len = bb.len(); while ii < len - (nn - 1u) { - it(&bb[ii..(ii+nn)]); + it(&bb[ii..ii+nn]); ii += 1u; } - return bb[(len - (nn - 1u))..len].to_vec(); + return bb[len - (nn - 1u)..len].to_vec(); } fn make_sequence_processor(sz: uint, diff --git a/src/test/compile-fail/range-1.rs b/src/test/compile-fail/range-1.rs index 9888c085695..fdae5f79546 100644 --- a/src/test/compile-fail/range-1.rs +++ b/src/test/compile-fail/range-1.rs @@ -21,6 +21,6 @@ pub fn main() { // Unsized type. let arr: &[_] = &[1us, 2, 3]; - let range = (*arr)..; + let range = *arr..; //~^ ERROR the trait `core::marker::Sized` is not implemented } diff --git a/src/test/compile-fail/range-2.rs b/src/test/compile-fail/range-2.rs index 6d176ca3700..9d89f4b05c5 100644 --- a/src/test/compile-fail/range-2.rs +++ b/src/test/compile-fail/range-2.rs @@ -12,7 +12,7 @@ pub fn main() { let r = { - (&42is)..&42 + &42is..&42 //~^ ERROR borrowed value does not live long enough //~^^ ERROR borrowed value does not live long enough }; From 3c37a952e738e4fe608a7870a751bbe96d9250e0 Mon Sep 17 00:00:00 2001 From: GuillaumeGomez Date: Mon, 19 Jan 2015 22:43:15 +0100 Subject: [PATCH 30/96] Updates of the fix --- src/libsyntax/ext/tt/macro_rules.rs | 86 ++++++++++++++--------------- 1 file changed, 43 insertions(+), 43 deletions(-) diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 957e59cbcdd..67ad668f169 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -413,48 +413,48 @@ fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token) fn is_in_follow(_: &ExtCtxt, tok: &Token, frag: &str) -> Result { if let &CloseDelim(_) = tok { - return Ok(true); + Ok(true) + } else { + match frag { + "item" => { + // since items *must* be followed by either a `;` or a `}`, we can + // accept anything after them + Ok(true) + }, + "block" => { + // anything can follow block, the braces provide a easy boundary to + // maintain + Ok(true) + }, + "stmt" | "expr" => { + match *tok { + FatArrow | Comma | Semi => Ok(true), + _ => Ok(false) + } + }, + "pat" => { + match *tok { + FatArrow | Comma | Eq => Ok(true), + _ => Ok(false) + } + }, + "path" | "ty" => { + match *tok { + Comma | FatArrow | Colon | Eq | Gt => Ok(true), + Ident(i, _) if i.as_str() == "as" => Ok(true), + _ => Ok(false) + } + }, + "ident" => { + // being a single token, idents are harmless + Ok(true) + }, + "meta" | "tt" => { + // being either a single token or a delimited sequence, tt is + // harmless + Ok(true) + }, + _ => Err(format!("unrecognized builtin nonterminal `{}`", frag)) + } } - - Ok(match frag { - "item" => { - // since items *must* be followed by either a `;` or a `}`, we can - // accept anything after them - true - }, - "block" => { - // anything can follow block, the braces provide a easy boundary to - // maintain - true - }, - "stmt" | "expr" => { - match *tok { - FatArrow | Comma | Semi => true, - _ => false - } - }, - "pat" => { - match *tok { - FatArrow | Comma | Eq => true, - _ => false - } - }, - "path" | "ty" => { - match *tok { - Comma | FatArrow | Colon | Eq | Gt => true, - Ident(i, _) if i.as_str() == "as" => true, - _ => false - } - }, - "ident" => { - // being a single token, idents are harmless - true - }, - "meta" | "tt" => { - // being either a single token or a delimited sequence, tt is - // harmless - true - }, - _ => return Err(format!("unrecognized builtin nonterminal `{}`", frag)), - }) } From e0eb3ccba0346db9fc8a65161006dcbaabe866f9 Mon Sep 17 00:00:00 2001 From: Ariel Ben-Yehuda Date: Sun, 18 Jan 2015 20:27:41 +0200 Subject: [PATCH 31/96] Kill TraitStore --- src/librustc/metadata/tydecode.rs | 15 -- src/librustc/metadata/tyencode.rs | 12 - src/librustc/middle/astencode.rs | 11 - src/librustc/middle/infer/combine.rs | 58 ----- src/librustc/middle/ty.rs | 47 +--- src/librustc/middle/ty_fold.rs | 22 -- src/librustc/util/ppaux.rs | 42 +--- src/librustc_trans/trans/base.rs | 16 +- src/librustc_trans/trans/closure.rs | 322 +------------------------- src/librustc_trans/trans/debuginfo.rs | 11 +- src/librustc_trans/trans/expr.rs | 13 +- src/librustc_trans/trans/type_.rs | 8 - src/librustc_typeck/astconv.rs | 2 - src/librustc_typeck/check/closure.rs | 1 - 14 files changed, 14 insertions(+), 566 deletions(-) diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index 5aacaa04e46..d18c12b308d 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -243,19 +243,6 @@ fn parse_size(st: &mut PState) -> Option { } } -fn parse_trait_store_(st: &mut PState, conv: &mut F) -> ty::TraitStore where - F: FnMut(DefIdSource, ast::DefId) -> ast::DefId, -{ - match next(st) { - '~' => ty::UniqTraitStore, - '&' => ty::RegionTraitStore(parse_region_(st, conv), parse_mutability(st)), - c => { - st.tcx.sess.bug(&format!("parse_trait_store(): bad input '{}'", - c)[]) - } - } -} - fn parse_vec_per_param_space<'a, 'tcx, T, F>(st: &mut PState<'a, 'tcx>, mut f: F) -> VecPerParamSpace where @@ -662,14 +649,12 @@ fn parse_closure_ty_<'a, 'tcx, F>(st: &mut PState<'a, 'tcx>, { let unsafety = parse_unsafety(next(st)); let onceness = parse_onceness(next(st)); - let store = parse_trait_store_(st, conv); let bounds = parse_existential_bounds_(st, conv); let sig = parse_sig_(st, conv); let abi = parse_abi_set(st); ty::ClosureTy { unsafety: unsafety, onceness: onceness, - store: store, bounds: bounds, sig: sig, abi: abi, diff --git a/src/librustc/metadata/tyencode.rs b/src/librustc/metadata/tyencode.rs index bdd08ad6c49..4727c5dddf7 100644 --- a/src/librustc/metadata/tyencode.rs +++ b/src/librustc/metadata/tyencode.rs @@ -305,17 +305,6 @@ pub fn enc_trait_ref<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, enc_substs(w, cx, s.substs); } -pub fn enc_trait_store(w: &mut SeekableMemWriter, cx: &ctxt, s: ty::TraitStore) { - match s { - ty::UniqTraitStore => mywrite!(w, "~"), - ty::RegionTraitStore(re, m) => { - mywrite!(w, "&"); - enc_region(w, cx, re); - enc_mutability(w, m); - } - } -} - fn enc_unsafety(w: &mut SeekableMemWriter, p: ast::Unsafety) { match p { ast::Unsafety::Normal => mywrite!(w, "n"), @@ -347,7 +336,6 @@ pub fn enc_closure_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, ft: &ty::ClosureTy<'tcx>) { enc_unsafety(w, ft.unsafety); enc_onceness(w, ft.onceness); - enc_trait_store(w, cx, ft.store); enc_existential_bounds(w, cx, &ft.bounds); enc_fn_sig(w, cx, &ft.sig); enc_abi(w, ft.abi); diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 550c0f34caf..9fc445d9cb6 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -515,17 +515,6 @@ fn tr(&self, dcx: &DecodeContext) -> ty::BoundRegion { } } -impl tr for ty::TraitStore { - fn tr(&self, dcx: &DecodeContext) -> ty::TraitStore { - match *self { - ty::RegionTraitStore(r, m) => { - ty::RegionTraitStore(r.tr(dcx), m) - } - ty::UniqTraitStore => ty::UniqTraitStore - } - } -} - // ______________________________________________________________________ // Encoding and decoding of freevar information diff --git a/src/librustc/middle/infer/combine.rs b/src/librustc/middle/infer/combine.rs index 4a4328fa98b..3280769ff03 100644 --- a/src/librustc/middle/infer/combine.rs +++ b/src/librustc/middle/infer/combine.rs @@ -202,39 +202,6 @@ fn bare_fn_tys(&self, a: &ty::BareFnTy<'tcx>, sig: sig}) } - fn closure_tys(&self, a: &ty::ClosureTy<'tcx>, - b: &ty::ClosureTy<'tcx>) -> cres<'tcx, ty::ClosureTy<'tcx>> { - - let store = match (a.store, b.store) { - (ty::RegionTraitStore(a_r, a_m), - ty::RegionTraitStore(b_r, b_m)) if a_m == b_m => { - let r = try!(self.contraregions(a_r, b_r)); - ty::RegionTraitStore(r, a_m) - } - - _ if a.store == b.store => { - a.store - } - - _ => { - return Err(ty::terr_sigil_mismatch(expected_found(self, a.store, b.store))) - } - }; - let unsafety = try!(self.unsafeties(a.unsafety, b.unsafety)); - let onceness = try!(self.oncenesses(a.onceness, b.onceness)); - let bounds = try!(self.existential_bounds(&a.bounds, &b.bounds)); - let sig = try!(self.binders(&a.sig, &b.sig)); - let abi = try!(self.abi(a.abi, b.abi)); - Ok(ty::ClosureTy { - unsafety: unsafety, - onceness: onceness, - store: store, - bounds: bounds, - sig: sig, - abi: abi, - }) - } - fn fn_sigs(&self, a: &ty::FnSig<'tcx>, b: &ty::FnSig<'tcx>) -> cres<'tcx, ty::FnSig<'tcx>> { if a.variadic != b.variadic { return Err(ty::terr_variadic_mismatch(expected_found(self, a.variadic, b.variadic))); @@ -356,31 +323,6 @@ fn contraregions(&self, a: ty::Region, b: ty::Region) fn regions(&self, a: ty::Region, b: ty::Region) -> cres<'tcx, ty::Region>; - fn trait_stores(&self, - vk: ty::terr_vstore_kind, - a: ty::TraitStore, - b: ty::TraitStore) - -> cres<'tcx, ty::TraitStore> { - debug!("{}.trait_stores(a={:?}, b={:?})", self.tag(), a, b); - - match (a, b) { - (ty::RegionTraitStore(a_r, a_m), - ty::RegionTraitStore(b_r, b_m)) if a_m == b_m => { - self.contraregions(a_r, b_r).and_then(|r| { - Ok(ty::RegionTraitStore(r, a_m)) - }) - } - - _ if a == b => { - Ok(a) - } - - _ => { - Err(ty::terr_trait_stores_differ(vk, expected_found(self, a, b))) - } - } - } - fn trait_refs(&self, a: &ty::TraitRef<'tcx>, b: &ty::TraitRef<'tcx>) diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index be6c6b9d34f..8d1a4108590 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -17,7 +17,6 @@ pub use self::InferRegion::*; pub use self::ImplOrTraitItemId::*; pub use self::UnboxedClosureKind::*; -pub use self::TraitStore::*; pub use self::ast_ty_to_ty_cache_entry::*; pub use self::Variance::*; pub use self::AutoAdjustment::*; @@ -61,7 +60,7 @@ use middle::ty_fold::{self, TypeFoldable, TypeFolder}; use middle::ty_walk::TypeWalker; use util::ppaux::{note_and_explain_region, bound_region_ptr_to_string}; -use util::ppaux::{trait_store_to_string, ty_to_string}; +use util::ppaux::ty_to_string; use util::ppaux::{Repr, UserString}; use util::common::{memoized, ErrorReported}; use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet}; @@ -247,14 +246,6 @@ pub struct mt<'tcx> { pub mutbl: ast::Mutability, } -#[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show)] -pub enum TraitStore { - /// Box - UniqTraitStore, - /// &Trait and &mut Trait - RegionTraitStore(Region, ast::Mutability), -} - #[derive(Clone, Copy, Show)] pub struct field_ty { pub name: Name, @@ -1042,7 +1033,6 @@ pub struct BareFnTy<'tcx> { pub struct ClosureTy<'tcx> { pub unsafety: ast::Unsafety, pub onceness: ast::Onceness, - pub store: TraitStore, pub bounds: ExistentialBounds<'tcx>, pub sig: PolyFnSig<'tcx>, pub abi: abi::Abi, @@ -1545,7 +1535,6 @@ pub enum type_err<'tcx> { terr_onceness_mismatch(expected_found), terr_abi_mismatch(expected_found), terr_mutability, - terr_sigil_mismatch(expected_found), terr_box_mutability, terr_ptr_mutability, terr_ref_mutability, @@ -1559,7 +1548,6 @@ pub enum type_err<'tcx> { terr_regions_no_overlap(Region, Region), terr_regions_insufficiently_polymorphic(BoundRegion, Region), terr_regions_overly_polymorphic(BoundRegion, Region), - terr_trait_stores_differ(terr_vstore_kind, expected_found), terr_sorts(expected_found>), terr_integer_as_char, terr_int_mismatch(expected_found), @@ -4194,19 +4182,6 @@ pub fn ty_fn_args<'tcx>(fty: Ty<'tcx>) -> ty::Binder>> { ty_fn_sig(fty).inputs() } -pub fn ty_closure_store(fty: Ty) -> TraitStore { - match fty.sty { - ty_unboxed_closure(..) => { - // Close enough for the purposes of all the callers of this - // function (which is soon to be deprecated anyhow). - UniqTraitStore - } - ref s => { - panic!("ty_closure_store() called on non-closure type: {:?}", s) - } - } -} - pub fn ty_fn_ret<'tcx>(fty: Ty<'tcx>) -> Binder> { match fty.sty { ty_bare_fn(_, ref f) => f.sig.output(), @@ -4751,13 +4726,6 @@ fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String { /// afterwards to present additional details, particularly when it comes to lifetime-related /// errors. pub fn type_err_to_str<'tcx>(cx: &ctxt<'tcx>, err: &type_err<'tcx>) -> String { - fn tstore_to_closure(s: &TraitStore) -> String { - match s { - &UniqTraitStore => "proc".to_string(), - &RegionTraitStore(..) => "closure".to_string() - } - } - match *err { terr_cyclic_ty => "cyclic type of infinite size".to_string(), terr_mismatch => "types differ".to_string(), @@ -4776,11 +4744,6 @@ fn tstore_to_closure(s: &TraitStore) -> String { values.expected, values.found) } - terr_sigil_mismatch(values) => { - format!("expected {}, found {}", - tstore_to_closure(&values.expected), - tstore_to_closure(&values.found)) - } terr_mutability => "values differ in mutability".to_string(), terr_box_mutability => { "boxed values differ in mutability".to_string() @@ -4828,11 +4791,6 @@ fn tstore_to_closure(s: &TraitStore) -> String { found bound lifetime parameter {}", bound_region_ptr_to_string(cx, br)) } - terr_trait_stores_differ(_, ref values) => { - format!("trait storage differs: expected `{}`, found `{}`", - trait_store_to_string(cx, (*values).expected), - trait_store_to_string(cx, (*values).found)) - } terr_sorts(values) => { // A naive approach to making sure that we're not reporting silly errors such as: // (expected closure, found closure). @@ -7338,10 +7296,9 @@ fn references_error(&self) -> bool { impl<'tcx> Repr<'tcx> for ClosureTy<'tcx> { fn repr(&self, tcx: &ctxt<'tcx>) -> String { - format!("ClosureTy({},{},{:?},{},{},{})", + format!("ClosureTy({},{},{},{},{})", self.unsafety, self.onceness, - self.store, self.bounds.repr(tcx), self.sig.repr(tcx), self.abi) diff --git a/src/librustc/middle/ty_fold.rs b/src/librustc/middle/ty_fold.rs index 37886b4a1e1..c2bbfca07bf 100644 --- a/src/librustc/middle/ty_fold.rs +++ b/src/librustc/middle/ty_fold.rs @@ -124,10 +124,6 @@ fn fold_region(&mut self, r: ty::Region) -> ty::Region { r } - fn fold_trait_store(&mut self, s: ty::TraitStore) -> ty::TraitStore { - super_fold_trait_store(self, s) - } - fn fold_existential_bounds(&mut self, s: &ty::ExistentialBounds<'tcx>) -> ty::ExistentialBounds<'tcx> { super_fold_existential_bounds(self, s) @@ -225,12 +221,6 @@ fn fold_with>(&self, folder: &mut F) -> VecPerParamSpace } } -impl<'tcx> TypeFoldable<'tcx> for ty::TraitStore { - fn fold_with>(&self, folder: &mut F) -> ty::TraitStore { - folder.fold_trait_store(*self) - } -} - impl<'tcx> TypeFoldable<'tcx> for Ty<'tcx> { fn fold_with>(&self, folder: &mut F) -> Ty<'tcx> { folder.fold_ty(*self) @@ -699,7 +689,6 @@ pub fn super_fold_closure_ty<'tcx, T: TypeFolder<'tcx>>(this: &mut T, -> ty::ClosureTy<'tcx> { ty::ClosureTy { - store: fty.store.fold_with(this), sig: fty.sig.fold_with(this), unsafety: fty.unsafety, onceness: fty.onceness, @@ -726,17 +715,6 @@ pub fn super_fold_mt<'tcx, T: TypeFolder<'tcx>>(this: &mut T, mutbl: mt.mutbl} } -pub fn super_fold_trait_store<'tcx, T: TypeFolder<'tcx>>(this: &mut T, - trait_store: ty::TraitStore) - -> ty::TraitStore { - match trait_store { - ty::UniqTraitStore => ty::UniqTraitStore, - ty::RegionTraitStore(r, m) => { - ty::RegionTraitStore(r.fold_with(this), m) - } - } -} - pub fn super_fold_existential_bounds<'tcx, T: TypeFolder<'tcx>>( this: &mut T, bounds: &ty::ExistentialBounds<'tcx>) diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index fb44d0cadfa..ba97331d183 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -237,15 +237,6 @@ pub fn mt_to_string<'tcx>(cx: &ctxt<'tcx>, m: &mt<'tcx>) -> String { ty_to_string(cx, m.ty)) } -pub fn trait_store_to_string(cx: &ctxt, s: ty::TraitStore) -> String { - match s { - ty::UniqTraitStore => "Box ".to_string(), - ty::RegionTraitStore(r, m) => { - format!("{}{}", region_ptr_to_string(cx, r), mutability_to_string(m)) - } - } -} - pub fn vec_map_to_string(ts: &[T], f: F) -> String where F: FnMut(&T) -> String, { @@ -303,13 +294,6 @@ fn bare_fn_to_string<'tcx>(cx: &ctxt<'tcx>, fn closure_to_string<'tcx>(cx: &ctxt<'tcx>, cty: &ty::ClosureTy<'tcx>) -> String { let mut s = String::new(); - match cty.store { - ty::UniqTraitStore => {} - ty::RegionTraitStore(region, _) => { - s.push_str(®ion_to_string(cx, "", true, region)[]); - } - } - match cty.unsafety { ast::Unsafety::Normal => {} ast::Unsafety::Unsafe => { @@ -320,22 +304,12 @@ fn closure_to_string<'tcx>(cx: &ctxt<'tcx>, cty: &ty::ClosureTy<'tcx>) -> String let bounds_str = cty.bounds.user_string(cx); - match cty.store { - ty::UniqTraitStore => { - assert_eq!(cty.onceness, ast::Once); - s.push_str("proc"); - push_sig_to_string(cx, &mut s, '(', ')', &cty.sig, - &bounds_str[]); - } - ty::RegionTraitStore(..) => { - match cty.onceness { - ast::Many => {} - ast::Once => s.push_str("once ") - } - push_sig_to_string(cx, &mut s, '|', '|', &cty.sig, - &bounds_str[]); - } + match cty.onceness { + ast::Many => {} + ast::Once => s.push_str("once ") } + push_sig_to_string(cx, &mut s, '|', '|', &cty.sig, + &bounds_str[]); s } @@ -1090,12 +1064,6 @@ fn repr(&self, tcx: &ctxt<'tcx>) -> String { } } -impl<'tcx> Repr<'tcx> for ty::TraitStore { - fn repr(&self, tcx: &ctxt) -> String { - trait_store_to_string(tcx, *self) - } -} - impl<'tcx> Repr<'tcx> for ty::BuiltinBound { fn repr(&self, _tcx: &ctxt) -> String { format!("{:?}", *self) diff --git a/src/librustc_trans/trans/base.rs b/src/librustc_trans/trans/base.rs index eed61ae59a2..56fdab6e040 100644 --- a/src/librustc_trans/trans/base.rs +++ b/src/librustc_trans/trans/base.rs @@ -362,18 +362,6 @@ pub fn get_extern_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId, } } -// Returns a pointer to the body for the box. The box may be an opaque -// box. The result will be casted to the type of body_t, if it is statically -// known. -pub fn at_box_body<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, - body_t: Ty<'tcx>, boxptr: ValueRef) -> ValueRef { - let _icx = push_ctxt("at_box_body"); - let ccx = bcx.ccx(); - let ty = Type::at_box(ccx, type_of(ccx, body_t)); - let boxptr = PointerCast(bcx, boxptr, ty.ptr_to()); - GEPi(bcx, boxptr, &[0u, abi::BOX_FIELD_BODY]) -} - fn require_alloc_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, info_ty: Ty<'tcx>, it: LangItem) -> ast::DefId { match bcx.tcx().lang_items.require(it) { @@ -1832,7 +1820,7 @@ pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>, .map(|arg| node_id_type(bcx, arg.id)) .collect::>(); let monomorphized_arg_types = match closure_env.kind { - closure::NotClosure | closure::BoxedClosure(..) => { + closure::NotClosure => { monomorphized_arg_types } @@ -1859,7 +1847,7 @@ pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>, }; bcx = match closure_env.kind { - closure::NotClosure | closure::BoxedClosure(..) => { + closure::NotClosure => { copy_args_to_allocas(bcx, arg_scope, &decl.inputs[], diff --git a/src/librustc_trans/trans/closure.rs b/src/librustc_trans/trans/closure.rs index 8989dfd4932..7a6c0c50dd1 100644 --- a/src/librustc_trans/trans/closure.rs +++ b/src/librustc_trans/trans/closure.rs @@ -10,270 +10,26 @@ pub use self::ClosureKind::*; -use back::abi; use back::link::mangle_internal_name_by_path_and_seq; -use llvm::ValueRef; use middle::mem_categorization::Typer; use trans::adt; use trans::base::*; use trans::build::*; use trans::cleanup::{CleanupMethods, ScopeId}; use trans::common::*; -use trans::datum::{Datum, Lvalue, rvalue_scratch_datum}; +use trans::datum::{Datum, rvalue_scratch_datum}; use trans::datum::{Rvalue, ByValue}; use trans::debuginfo; use trans::expr; use trans::monomorphize::{self, MonoId}; use trans::type_of::*; -use trans::type_::Type; -use middle::ty::{self, Ty, UnboxedClosureTyper}; +use middle::ty::{self, UnboxedClosureTyper}; use middle::subst::{Substs}; use session::config::FullDebugInfo; -use util::ppaux::ty_to_string; use syntax::ast; use syntax::ast_util; -// ___Good to know (tm)__________________________________________________ -// -// The layout of a closure environment in memory is -// roughly as follows: -// -// struct rust_opaque_box { // see rust_internal.h -// unsigned ref_count; // obsolete (part of @T's header) -// fn(void*) *drop_glue; // destructor (for proc) -// rust_opaque_box *prev; // obsolete (part of @T's header) -// rust_opaque_box *next; // obsolete (part of @T's header) -// struct closure_data { -// upvar1_t upvar1; -// ... -// upvarN_t upvarN; -// } -// }; -// -// Note that the closure is itself a rust_opaque_box. This is true -// even for ~fn and ||, because we wish to keep binary compatibility -// between all kinds of closures. The allocation strategy for this -// closure depends on the closure type. For a sendfn, the closure -// (and the referenced type descriptors) will be allocated in the -// exchange heap. For a fn, the closure is allocated in the task heap -// and is reference counted. For a block, the closure is allocated on -// the stack. -// -// ## Opaque closures and the embedded type descriptor ## -// -// One interesting part of closures is that they encapsulate the data -// that they close over. So when I have a ptr to a closure, I do not -// know how many type descriptors it contains nor what upvars are -// captured within. That means I do not know precisely how big it is -// nor where its fields are located. This is called an "opaque -// closure". -// -// Typically an opaque closure suffices because we only manipulate it -// by ptr. The routine Type::at_box().ptr_to() returns an appropriate -// type for such an opaque closure; it allows access to the box fields, -// but not the closure_data itself. -// -// But sometimes, such as when cloning or freeing a closure, we need -// to know the full information. That is where the type descriptor -// that defines the closure comes in handy. We can use its take and -// drop glue functions to allocate/free data as needed. -// -// ## Subtleties concerning alignment ## -// -// It is important that we be able to locate the closure data *without -// knowing the kind of data that is being bound*. This can be tricky -// because the alignment requirements of the bound data affects the -// alignment requires of the closure_data struct as a whole. However, -// right now this is a non-issue in any case, because the size of the -// rust_opaque_box header is always a multiple of 16-bytes, which is -// the maximum alignment requirement we ever have to worry about. -// -// The only reason alignment matters is that, in order to learn what data -// is bound, we would normally first load the type descriptors: but their -// location is ultimately depend on their content! There is, however, a -// workaround. We can load the tydesc from the rust_opaque_box, which -// describes the closure_data struct and has self-contained derived type -// descriptors, and read the alignment from there. It's just annoying to -// do. Hopefully should this ever become an issue we'll have monomorphized -// and type descriptors will all be a bad dream. -// -// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -#[derive(Copy)] -pub struct EnvValue<'tcx> { - action: ast::CaptureClause, - datum: Datum<'tcx, Lvalue> -} - -impl<'tcx> EnvValue<'tcx> { - pub fn to_string<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> String { - format!("{:?}({})", self.action, self.datum.to_string(ccx)) - } -} - -// Given a closure ty, emits a corresponding tuple ty -pub fn mk_closure_tys<'tcx>(tcx: &ty::ctxt<'tcx>, - bound_values: &[EnvValue<'tcx>]) - -> Ty<'tcx> { - // determine the types of the values in the env. Note that this - // is the actual types that will be stored in the map, not the - // logical types as the user sees them, so by-ref upvars must be - // converted to ptrs. - let bound_tys = bound_values.iter().map(|bv| { - match bv.action { - ast::CaptureByValue => bv.datum.ty, - ast::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty) - } - }).collect(); - let cdata_ty = ty::mk_tup(tcx, bound_tys); - debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty)); - return cdata_ty; -} - -fn tuplify_box_ty<'tcx>(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>) -> Ty<'tcx> { - let ptr = ty::mk_imm_ptr(tcx, tcx.types.i8); - ty::mk_tup(tcx, vec!(tcx.types.uint, ty::mk_nil_ptr(tcx), ptr, ptr, t)) -} - -pub struct ClosureResult<'blk, 'tcx: 'blk> { - llbox: ValueRef, // llvalue of ptr to closure - cdata_ty: Ty<'tcx>, // type of the closure data - bcx: Block<'blk, 'tcx> // final bcx -} - -// Given a block context and a list of tydescs and values to bind -// construct a closure out of them. If copying is true, it is a -// heap allocated closure that copies the upvars into environment. -// Otherwise, it is stack allocated and copies pointers to the upvars. -pub fn store_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, - bound_values: Vec>) - -> ClosureResult<'blk, 'tcx> { - let _icx = push_ctxt("closure::store_environment"); - let ccx = bcx.ccx(); - let tcx = ccx.tcx(); - - // compute the type of the closure - let cdata_ty = mk_closure_tys(tcx, &bound_values[]); - - // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a - // tuple. This could be a ptr in uniq or a box or on stack, - // whatever. - let cbox_ty = tuplify_box_ty(tcx, cdata_ty); - let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable}); - let llboxptr_ty = type_of(ccx, cboxptr_ty); - - // If there are no bound values, no point in allocating anything. - if bound_values.is_empty() { - return ClosureResult {llbox: C_null(llboxptr_ty), - cdata_ty: cdata_ty, - bcx: bcx}; - } - - // allocate closure in the heap - let llbox = alloc_ty(bcx, cbox_ty, "__closure"); - - let llbox = PointerCast(bcx, llbox, llboxptr_ty); - debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty)); - - // Copy expr values into boxed bindings. - let mut bcx = bcx; - for (i, bv) in bound_values.into_iter().enumerate() { - debug!("Copy {} into closure", bv.to_string(ccx)); - - if ccx.sess().asm_comments() { - add_comment(bcx, &format!("Copy {} into closure", - bv.to_string(ccx))[]); - } - - let bound_data = GEPi(bcx, llbox, &[0u, abi::BOX_FIELD_BODY, i]); - - match bv.action { - ast::CaptureByValue => { - bcx = bv.datum.store_to(bcx, bound_data); - } - ast::CaptureByRef => { - Store(bcx, bv.datum.to_llref(), bound_data); - } - } - } - - ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx } -} - -// Given a context and a list of upvars, build a closure. This just -// collects the upvars and packages them up for store_environment. -fn build_closure<'blk, 'tcx>(bcx0: Block<'blk, 'tcx>, - freevar_mode: ast::CaptureClause, - freevars: &Vec) - -> ClosureResult<'blk, 'tcx> { - let _icx = push_ctxt("closure::build_closure"); - - // If we need to, package up the iterator body to call - let bcx = bcx0; - - // Package up the captured upvars - let mut env_vals = Vec::new(); - for freevar in freevars.iter() { - let datum = expr::trans_local_var(bcx, freevar.def); - env_vals.push(EnvValue {action: freevar_mode, datum: datum}); - } - - store_environment(bcx, env_vals) -} - -// Given an enclosing block context, a new function context, a closure type, -// and a list of upvars, generate code to load and populate the environment -// with the upvars and type descriptors. -fn load_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, - cdata_ty: Ty<'tcx>, - freevars: &[ty::Freevar], - store: ty::TraitStore) - -> Block<'blk, 'tcx> { - let _icx = push_ctxt("closure::load_environment"); - - // Load a pointer to the closure data, skipping over the box header: - let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap()); - - // Store the pointer to closure data in an alloca for debug info because that's what the - // llvm.dbg.declare intrinsic expects - let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo { - let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr"); - Store(bcx, llcdata, alloc); - Some(alloc) - } else { - None - }; - - // Populate the upvars from the environment - let mut i = 0u; - for freevar in freevars.iter() { - let mut upvarptr = GEPi(bcx, llcdata, &[0u, i]); - let captured_by_ref = match store { - ty::RegionTraitStore(..) => { - upvarptr = Load(bcx, upvarptr); - true - } - ty::UniqTraitStore => false - }; - let def_id = freevar.def.def_id(); - - bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr); - if let Some(env_pointer_alloca) = env_pointer_alloca { - debuginfo::create_captured_var_metadata( - bcx, - def_id.node, - env_pointer_alloca, - i, - captured_by_ref, - freevar.span); - } - - i += 1u; - } - - bcx -} fn load_unboxed_closure_environment<'blk, 'tcx>( bcx: Block<'blk, 'tcx>, @@ -281,7 +37,7 @@ fn load_unboxed_closure_environment<'blk, 'tcx>( freevar_mode: ast::CaptureClause, freevars: &[ty::Freevar]) -> Block<'blk, 'tcx> { - let _icx = push_ctxt("closure::load_environment"); + let _icx = push_ctxt("closure::load_unboxed_closure_environment"); // Special case for small by-value selfs. let closure_id = ast_util::local_def(bcx.fcx.id); @@ -341,17 +97,9 @@ fn load_unboxed_closure_environment<'blk, 'tcx>( bcx } -fn fill_fn_pair(bcx: Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) { - Store(bcx, llfn, GEPi(bcx, pair, &[0u, abi::FAT_PTR_ADDR])); - let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx())); - Store(bcx, llenvptr, GEPi(bcx, pair, &[0u, abi::FAT_PTR_EXTRA])); -} - #[derive(PartialEq)] pub enum ClosureKind<'tcx> { NotClosure, - // See load_environment. - BoxedClosure(Ty<'tcx>, ty::TraitStore), // See load_unboxed_closure_environment. UnboxedClosure(ast::CaptureClause) } @@ -379,9 +127,6 @@ pub fn load<'blk>(self, bcx: Block<'blk, 'tcx>, arg_scope: ScopeId) match self.kind { NotClosure => bcx, - BoxedClosure(cdata_ty, store) => { - load_environment(bcx, cdata_ty, self.freevars, store) - } UnboxedClosure(freevar_mode) => { load_unboxed_closure_environment(bcx, arg_scope, freevar_mode, self.freevars) } @@ -389,67 +134,6 @@ pub fn load<'blk>(self, bcx: Block<'blk, 'tcx>, arg_scope: ScopeId) } } -/// Translates the body of a closure expression. -/// -/// - `store` -/// - `decl` -/// - `body` -/// - `id`: The id of the closure expression. -/// - `cap_clause`: information about captured variables, if any. -/// - `dest`: where to write the closure value, which must be a -/// (fn ptr, env) pair -pub fn trans_expr_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, - store: ty::TraitStore, - decl: &ast::FnDecl, - body: &ast::Block, - id: ast::NodeId, - dest: expr::Dest) - -> Block<'blk, 'tcx> { - let _icx = push_ctxt("closure::trans_expr_fn"); - - let dest_addr = match dest { - expr::SaveIn(p) => p, - expr::Ignore => { - return bcx; // closure construction is non-side-effecting - } - }; - - let ccx = bcx.ccx(); - let tcx = bcx.tcx(); - let fty = node_id_type(bcx, id); - let s = tcx.map.with_path(id, |path| { - mangle_internal_name_by_path_and_seq(path, "closure") - }); - let llfn = decl_internal_rust_fn(ccx, fty, &s[]); - - // set an inline hint for all closures - set_inline_hint(llfn); - - let freevar_mode = tcx.capture_mode(id); - let freevars: Vec = - ty::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect()); - - let ClosureResult { - llbox, - cdata_ty, - bcx - } = build_closure(bcx, freevar_mode, &freevars); - - trans_closure(ccx, - decl, - body, - llfn, - bcx.fcx.param_substs, - id, - &[], - ty::erase_late_bound_regions(ccx.tcx(), &ty::ty_fn_ret(fty)), - ty::ty_fn_abi(fty), - ClosureEnv::new(&freevars[], - BoxedClosure(cdata_ty, store))); - fill_fn_pair(bcx, dest_addr, llfn, llbox); - bcx -} - /// Returns the LLVM function declaration for an unboxed closure, creating it /// if necessary. If the ID does not correspond to a closure ID, returns None. pub fn get_or_create_declaration_if_unboxed_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, diff --git a/src/librustc_trans/trans/debuginfo.rs b/src/librustc_trans/trans/debuginfo.rs index 2f01f0328e2..a8a7b7243f1 100644 --- a/src/librustc_trans/trans/debuginfo.rs +++ b/src/librustc_trans/trans/debuginfo.rs @@ -552,7 +552,6 @@ fn get_unique_type_id_of_closure_type<'a>(&mut self, unique_type_id: &mut String) { let ty::ClosureTy { unsafety, onceness, - store, ref bounds, ref sig, abi: _ } = closure_ty; @@ -564,15 +563,7 @@ fn get_unique_type_id_of_closure_type<'a>(&mut self, unique_type_id.push_str("once "); } - match store { - ty::UniqTraitStore => unique_type_id.push_str("~|"), - ty::RegionTraitStore(_, ast::MutMutable) => { - unique_type_id.push_str("&mut|") - } - ty::RegionTraitStore(_, ast::MutImmutable) => { - unique_type_id.push_str("&|") - } - }; + unique_type_id.push_str("|"); let sig = ty::erase_late_bound_regions(cx.tcx(), sig); diff --git a/src/librustc_trans/trans/expr.rs b/src/librustc_trans/trans/expr.rs index 11d1c7e6796..da900f0a59e 100644 --- a/src/librustc_trans/trans/expr.rs +++ b/src/librustc_trans/trans/expr.rs @@ -65,7 +65,6 @@ use trans::type_::Type; use syntax::{ast, ast_util, codemap}; -use syntax::print::pprust::{expr_to_string}; use syntax::ptr::P; use syntax::parse::token; use std::rc::Rc; @@ -1102,17 +1101,7 @@ fn make_field(field_name: &str, expr: P) -> ast::Field { // closure or an older, legacy style closure. Store this // into a variable to ensure the the RefCell-lock is // released before we recurse. - let is_unboxed_closure = - bcx.tcx().unboxed_closures.borrow().contains_key(&ast_util::local_def(expr.id)); - if is_unboxed_closure { - closure::trans_unboxed_closure(bcx, &**decl, &**body, expr.id, dest) - } else { - let expr_ty = expr_ty(bcx, expr); - let store = ty::ty_closure_store(expr_ty); - debug!("translating block function {} with type {}", - expr_to_string(expr), expr_ty.repr(tcx)); - closure::trans_expr_fn(bcx, store, &**decl, &**body, expr.id, dest) - } + closure::trans_unboxed_closure(bcx, &**decl, &**body, expr.id, dest) } ast::ExprCall(ref f, ref args) => { if bcx.tcx().is_method_call(expr.id) { diff --git a/src/librustc_trans/trans/type_.rs b/src/librustc_trans/trans/type_.rs index 07eb17e6300..5710fa24925 100644 --- a/src/librustc_trans/trans/type_.rs +++ b/src/librustc_trans/trans/type_.rs @@ -227,14 +227,6 @@ pub fn opaque_vec(ccx: &CrateContext) -> Type { Type::vec(ccx, &Type::i8(ccx)) } - // The box pointed to by @T. - pub fn at_box(ccx: &CrateContext, ty: Type) -> Type { - Type::struct_(ccx, &[ - ccx.int_type(), Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to(), - Type::i8p(ccx), Type::i8p(ccx), ty - ], false) - } - pub fn vtable_ptr(ccx: &CrateContext) -> Type { Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to().ptr_to() } diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 42b12c15866..44434c2e91b 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -1459,7 +1459,6 @@ pub fn ty_of_closure<'tcx>( unsafety: ast::Unsafety, onceness: ast::Onceness, bounds: ty::ExistentialBounds<'tcx>, - store: ty::TraitStore, decl: &ast::FnDecl, abi: abi::Abi, expected_sig: Option>) @@ -1510,7 +1509,6 @@ pub fn ty_of_closure<'tcx>( ty::ClosureTy { unsafety: unsafety, onceness: onceness, - store: store, bounds: bounds, abi: abi, sig: ty::Binder(ty::FnSig {inputs: input_tys, diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index bfe43086aab..4c1083c4b63 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -96,7 +96,6 @@ fn check_unboxed_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, // // FIXME(pcwalton): Refactor this API. ty::region_existential_bound(ty::ReStatic), - ty::RegionTraitStore(ty::ReStatic, ast::MutImmutable), decl, abi::RustCall, From 8e1e0f0b5743405f3487d765cd6cbe230ddca738 Mon Sep 17 00:00:00 2001 From: Ariel Ben-Yehuda Date: Sun, 18 Jan 2015 21:01:58 +0200 Subject: [PATCH 32/96] Remove onceness & bounds - they don't do anything. --- src/librustc/metadata/tydecode.rs | 12 ------------ src/librustc/metadata/tyencode.rs | 9 --------- src/librustc/middle/ty.rs | 10 +++------- src/librustc/middle/ty_fold.rs | 2 -- src/librustc/util/ppaux.rs | 19 +++---------------- src/librustc_trans/trans/debuginfo.rs | 19 +------------------ src/librustc_typeck/astconv.rs | 4 ---- src/librustc_typeck/check/closure.rs | 8 -------- 8 files changed, 7 insertions(+), 76 deletions(-) diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index d18c12b308d..861aaa36103 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -628,14 +628,6 @@ fn parse_abi_set(st: &mut PState) -> abi::Abi { }) } -fn parse_onceness(c: char) -> ast::Onceness { - match c { - 'o' => ast::Once, - 'm' => ast::Many, - _ => panic!("parse_onceness: bad onceness") - } -} - fn parse_closure_ty<'a, 'tcx, F>(st: &mut PState<'a, 'tcx>, mut conv: F) -> ty::ClosureTy<'tcx> where F: FnMut(DefIdSource, ast::DefId) -> ast::DefId, @@ -648,14 +640,10 @@ fn parse_closure_ty_<'a, 'tcx, F>(st: &mut PState<'a, 'tcx>, F: FnMut(DefIdSource, ast::DefId) -> ast::DefId, { let unsafety = parse_unsafety(next(st)); - let onceness = parse_onceness(next(st)); - let bounds = parse_existential_bounds_(st, conv); let sig = parse_sig_(st, conv); let abi = parse_abi_set(st); ty::ClosureTy { unsafety: unsafety, - onceness: onceness, - bounds: bounds, sig: sig, abi: abi, } diff --git a/src/librustc/metadata/tyencode.rs b/src/librustc/metadata/tyencode.rs index 4727c5dddf7..9aead5bf4e7 100644 --- a/src/librustc/metadata/tyencode.rs +++ b/src/librustc/metadata/tyencode.rs @@ -318,13 +318,6 @@ fn enc_abi(w: &mut SeekableMemWriter, abi: Abi) { mywrite!(w, "]") } -fn enc_onceness(w: &mut SeekableMemWriter, o: ast::Onceness) { - match o { - ast::Once => mywrite!(w, "o"), - ast::Many => mywrite!(w, "m") - } -} - pub fn enc_bare_fn_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, ft: &ty::BareFnTy<'tcx>) { enc_unsafety(w, ft.unsafety); @@ -335,8 +328,6 @@ pub fn enc_bare_fn_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, pub fn enc_closure_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, ft: &ty::ClosureTy<'tcx>) { enc_unsafety(w, ft.unsafety); - enc_onceness(w, ft.onceness); - enc_existential_bounds(w, cx, &ft.bounds); enc_fn_sig(w, cx, &ft.sig); enc_abi(w, ft.abi); } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 8d1a4108590..6c4d49ab274 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -1032,10 +1032,8 @@ pub struct BareFnTy<'tcx> { #[derive(Clone, PartialEq, Eq, Hash, Show)] pub struct ClosureTy<'tcx> { pub unsafety: ast::Unsafety, - pub onceness: ast::Onceness, - pub bounds: ExistentialBounds<'tcx>, - pub sig: PolyFnSig<'tcx>, pub abi: abi::Abi, + pub sig: PolyFnSig<'tcx>, } #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)] @@ -7296,10 +7294,8 @@ fn references_error(&self) -> bool { impl<'tcx> Repr<'tcx> for ClosureTy<'tcx> { fn repr(&self, tcx: &ctxt<'tcx>) -> String { - format!("ClosureTy({},{},{},{},{})", + format!("ClosureTy({},{},{})", self.unsafety, - self.onceness, - self.bounds.repr(tcx), self.sig.repr(tcx), self.abi) } @@ -7330,5 +7326,5 @@ fn repr(&self, tcx: &ctxt<'tcx>) -> String { self.free_substs.repr(tcx), self.implicit_region_bound.repr(tcx), self.caller_bounds.repr(tcx)) - } } +} \ No newline at end of file diff --git a/src/librustc/middle/ty_fold.rs b/src/librustc/middle/ty_fold.rs index c2bbfca07bf..b4e6cff954b 100644 --- a/src/librustc/middle/ty_fold.rs +++ b/src/librustc/middle/ty_fold.rs @@ -691,8 +691,6 @@ pub fn super_fold_closure_ty<'tcx, T: TypeFolder<'tcx>>(this: &mut T, ty::ClosureTy { sig: fty.sig.fold_with(this), unsafety: fty.unsafety, - onceness: fty.onceness, - bounds: fty.bounds.fold_with(this), abi: fty.abi, } } diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index ba97331d183..eeed91918cf 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -276,7 +276,7 @@ fn bare_fn_to_string<'tcx>(cx: &ctxt<'tcx>, _ => { } } - push_sig_to_string(cx, &mut s, '(', ')', sig, ""); + push_sig_to_string(cx, &mut s, '(', ')', sig); match opt_def_id { Some(def_id) => { @@ -302,14 +302,7 @@ fn closure_to_string<'tcx>(cx: &ctxt<'tcx>, cty: &ty::ClosureTy<'tcx>) -> String } }; - let bounds_str = cty.bounds.user_string(cx); - - match cty.onceness { - ast::Many => {} - ast::Once => s.push_str("once ") - } - push_sig_to_string(cx, &mut s, '|', '|', &cty.sig, - &bounds_str[]); + push_sig_to_string(cx, &mut s, '|', '|', &cty.sig); s } @@ -318,8 +311,7 @@ fn push_sig_to_string<'tcx>(cx: &ctxt<'tcx>, s: &mut String, bra: char, ket: char, - sig: &ty::PolyFnSig<'tcx>, - bounds: &str) { + sig: &ty::PolyFnSig<'tcx>) { s.push(bra); let strs = sig.0.inputs .iter() @@ -331,11 +323,6 @@ fn push_sig_to_string<'tcx>(cx: &ctxt<'tcx>, } s.push(ket); - if !bounds.is_empty() { - s.push_str(":"); - s.push_str(bounds); - } - match sig.0.output { ty::FnConverging(t) => { if !ty::type_is_nil(t) { diff --git a/src/librustc_trans/trans/debuginfo.rs b/src/librustc_trans/trans/debuginfo.rs index a8a7b7243f1..d6fbb44fc0a 100644 --- a/src/librustc_trans/trans/debuginfo.rs +++ b/src/librustc_trans/trans/debuginfo.rs @@ -551,18 +551,13 @@ fn get_unique_type_id_of_closure_type<'a>(&mut self, closure_ty: ty::ClosureTy<'tcx>, unique_type_id: &mut String) { let ty::ClosureTy { unsafety, - onceness, - ref bounds, ref sig, abi: _ } = closure_ty; + if unsafety == ast::Unsafety::Unsafe { unique_type_id.push_str("unsafe "); } - if onceness == ast::Once { - unique_type_id.push_str("once "); - } - unique_type_id.push_str("|"); let sig = ty::erase_late_bound_regions(cx.tcx(), sig); @@ -592,18 +587,6 @@ fn get_unique_type_id_of_closure_type<'a>(&mut self, unique_type_id.push_str("!"); } } - - unique_type_id.push(':'); - - for bound in bounds.builtin_bounds.iter() { - match bound { - ty::BoundSend => unique_type_id.push_str("Send"), - ty::BoundSized => unique_type_id.push_str("Sized"), - ty::BoundCopy => unique_type_id.push_str("Copy"), - ty::BoundSync => unique_type_id.push_str("Sync"), - }; - unique_type_id.push('+'); - } } // Get the UniqueTypeId for an enum variant. Enum variants are not really diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 44434c2e91b..47a28684940 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -1457,8 +1457,6 @@ fn count_modifiers(ty: Ty) -> uint { pub fn ty_of_closure<'tcx>( this: &AstConv<'tcx>, unsafety: ast::Unsafety, - onceness: ast::Onceness, - bounds: ty::ExistentialBounds<'tcx>, decl: &ast::FnDecl, abi: abi::Abi, expected_sig: Option>) @@ -1508,8 +1506,6 @@ pub fn ty_of_closure<'tcx>( ty::ClosureTy { unsafety: unsafety, - onceness: onceness, - bounds: bounds, abi: abi, sig: ty::Binder(ty::FnSig {inputs: input_tys, output: output_ty, diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index 4c1083c4b63..9b25910ab91 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -89,14 +89,6 @@ fn check_unboxed_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, let mut fn_ty = astconv::ty_of_closure( fcx, ast::Unsafety::Normal, - ast::Many, - - // The `RegionTraitStore` and region_existential_bounds - // are lies, but we ignore them so it doesn't matter. - // - // FIXME(pcwalton): Refactor this API. - ty::region_existential_bound(ty::ReStatic), - decl, abi::RustCall, expected_sig); From ed769bf87f1e0ff03cd8ccbdfd90195a8126f135 Mon Sep 17 00:00:00 2001 From: P1start Date: Tue, 20 Jan 2015 19:25:28 +1300 Subject: [PATCH 33/96] =?UTF-8?q?Fix=20up=20some=20=E2=80=98help=E2=80=99?= =?UTF-8?q?=C2=A0messages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/librustc/middle/resolve_lifetime.rs | 4 ++-- src/librustc_typeck/astconv.rs | 6 +++--- src/librustc_typeck/check/closure.rs | 2 +- src/libsyntax/parse/parser.rs | 2 +- .../compile-fail/hrtb-precedence-of-plus-error-message.rs | 6 +++--- .../compile-fail/require-parens-for-chained-comparison.rs | 2 +- src/test/compile-fail/shadowed-lifetime.rs | 8 ++++---- src/test/compile-fail/unsized2.rs | 2 +- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index eff0018becc..354c476cdd8 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -462,11 +462,11 @@ fn check_lifetime_def_for_shadowing(&self, format!("lifetime name `{}` shadows another \ lifetime name that is already in scope", token::get_name(lifetime.name)).as_slice()); - self.sess.span_help( + self.sess.span_note( lifetime_def.span, format!("shadowed lifetime `{}` declared here", token::get_name(lifetime.name)).as_slice()); - self.sess.span_help( + self.sess.span_note( lifetime.span, "shadowed lifetimes are deprecated \ and will become a hard error before 1.0"); diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 42b12c15866..14f727cb583 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -893,14 +893,14 @@ fn ast_ty_to_trait_ref<'tcx>(this: &AstConv<'tcx>, pprust::ty_to_string(ty)); match ty.node { ast::TyRptr(None, ref mut_ty) => { - span_note!(this.tcx().sess, ty.span, + span_help!(this.tcx().sess, ty.span, "perhaps you meant `&{}({} +{})`? (per RFC 438)", ppaux::mutability_to_string(mut_ty.mutbl), pprust::ty_to_string(&*mut_ty.ty), pprust::bounds_to_string(bounds)); } ast::TyRptr(Some(ref lt), ref mut_ty) => { - span_note!(this.tcx().sess, ty.span, + span_help!(this.tcx().sess, ty.span, "perhaps you meant `&{} {}({} +{})`? (per RFC 438)", pprust::lifetime_to_string(lt), ppaux::mutability_to_string(mut_ty.mutbl), @@ -909,7 +909,7 @@ fn ast_ty_to_trait_ref<'tcx>(this: &AstConv<'tcx>, } _ => { - span_note!(this.tcx().sess, ty.span, + span_help!(this.tcx().sess, ty.span, "perhaps you forgot parentheses? (per RFC 438)"); } } diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index bfe43086aab..0847807c1c0 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -52,7 +52,7 @@ pub fn check_expr_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, fcx.ccx.tcx.sess.span_err( expr.span, - "can't infer the \"kind\" of the closure, explicitly annotate it. e.g. \ + "can't infer the \"kind\" of the closure; explicitly annotate it; e.g. \ `|&:| {}`"); }, Some((sig, kind)) => { diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 83a7504bc49..f5204478906 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -2921,7 +2921,7 @@ fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp) { "Chained comparison operators require parentheses"); if op == BiLt && outer_op == BiGt { self.span_help(op_span, - "Use ::< instead of < if you meant to specify type arguments."); + "use ::< instead of < if you meant to specify type arguments"); } } _ => {} diff --git a/src/test/compile-fail/hrtb-precedence-of-plus-error-message.rs b/src/test/compile-fail/hrtb-precedence-of-plus-error-message.rs index 41a0be37add..db67249bbd9 100644 --- a/src/test/compile-fail/hrtb-precedence-of-plus-error-message.rs +++ b/src/test/compile-fail/hrtb-precedence-of-plus-error-message.rs @@ -19,17 +19,17 @@ fn dummy(&self) { } struct Foo<'a> { a: &'a Bar+'a, //~^ ERROR E0178 - //~^^ NOTE perhaps you meant `&'a (Bar + 'a)`? + //~^^ HELP perhaps you meant `&'a (Bar + 'a)`? b: &'a mut Bar+'a, //~^ ERROR E0178 - //~^^ NOTE perhaps you meant `&'a mut (Bar + 'a)`? + //~^^ HELP perhaps you meant `&'a mut (Bar + 'a)`? c: Box, // OK, no paren needed in this context d: fn() -> Bar+'a, //~^ ERROR E0178 - //~^^ NOTE perhaps you forgot parentheses + //~^^ HELP perhaps you forgot parentheses //~^^^ WARN deprecated syntax } diff --git a/src/test/compile-fail/require-parens-for-chained-comparison.rs b/src/test/compile-fail/require-parens-for-chained-comparison.rs index 7513815ad73..f5d8c574814 100644 --- a/src/test/compile-fail/require-parens-for-chained-comparison.rs +++ b/src/test/compile-fail/require-parens-for-chained-comparison.rs @@ -19,5 +19,5 @@ fn main() { f(); //~^ ERROR: Chained comparison operators require parentheses - //~^^ HELP: Use ::< instead of < if you meant to specify type arguments. + //~^^ HELP: use ::< instead of < if you meant to specify type arguments } diff --git a/src/test/compile-fail/shadowed-lifetime.rs b/src/test/compile-fail/shadowed-lifetime.rs index 57a2744d8f8..bf8a8f5046e 100644 --- a/src/test/compile-fail/shadowed-lifetime.rs +++ b/src/test/compile-fail/shadowed-lifetime.rs @@ -13,18 +13,18 @@ struct Foo<'a>(&'a isize); impl<'a> Foo<'a> { - //~^ HELP shadowed lifetime `'a` declared here + //~^ NOTE shadowed lifetime `'a` declared here fn shadow_in_method<'a>(&'a self) -> &'a isize { //~^ WARNING lifetime name `'a` shadows another lifetime name that is already in scope - //~| HELP deprecated + //~| NOTE deprecated self.0 } fn shadow_in_type<'b>(&'b self) -> &'b isize { - //~^ HELP shadowed lifetime `'b` declared here + //~^ NOTE shadowed lifetime `'b` declared here let x: for<'b> fn(&'b isize) = panic!(); //~^ WARNING lifetime name `'b` shadows another lifetime name that is already in scope - //~| HELP deprecated + //~| NOTE deprecated self.0 } diff --git a/src/test/compile-fail/unsized2.rs b/src/test/compile-fail/unsized2.rs index 604f7ba3255..a47d81e38cc 100644 --- a/src/test/compile-fail/unsized2.rs +++ b/src/test/compile-fail/unsized2.rs @@ -16,5 +16,5 @@ pub fn main() { f(); //~^ ERROR expected identifier, found keyword `type` //~^^ ERROR: Chained comparison operators require parentheses - //~^^^ HELP: Use ::< instead of < if you meant to specify type arguments. + //~^^^ HELP: use ::< instead of < if you meant to specify type arguments } From d7b30f9c0a35a56dc77cbe79d950a7888522abf7 Mon Sep 17 00:00:00 2001 From: Ahmed Charles Date: Sun, 18 Jan 2015 21:03:46 -0800 Subject: [PATCH 34/96] Remove ratchet-bench from configure. --- configure | 1 - 1 file changed, 1 deletion(-) diff --git a/configure b/configure index 712db849039..9a7900b6502 100755 --- a/configure +++ b/configure @@ -509,7 +509,6 @@ opt optimize-tests 1 "build tests with optimizations" opt libcpp 1 "build with llvm with libc++ instead of libstdc++ when using clang" opt llvm-assertions 1 "build LLVM with assertions" opt debug 1 "build with extra debug fun" -opt ratchet-bench 0 "ratchet benchmarks" opt fast-make 0 "use .gitmodules as timestamp for submodule deps" opt ccache 0 "invoke gcc/clang via ccache to reuse object files between builds" opt local-rust 0 "use an installed rustc rather than downloading a snapshot" From ec4178597271bfb6cb5e01af8d62b30f3c7793d6 Mon Sep 17 00:00:00 2001 From: Ahmed Charles Date: Mon, 19 Jan 2015 00:20:31 -0800 Subject: [PATCH 35/96] Remove unsupported test features from compiletest. Removes test-shard, ratchet-metrics and save-metrics from Config in compiletest/common.rs. --- src/compiletest/common.rs | 14 -------------- src/compiletest/compiletest.rs | 24 ++++-------------------- 2 files changed, 4 insertions(+), 34 deletions(-) diff --git a/src/compiletest/common.rs b/src/compiletest/common.rs index c29f74d7418..1058a489037 100644 --- a/src/compiletest/common.rs +++ b/src/compiletest/common.rs @@ -115,20 +115,6 @@ pub struct Config { // Write out a parseable log of tests that were run pub logfile: Option, - // Write out a json file containing any metrics of the run - pub save_metrics: Option, - - // Write and ratchet a metrics file - pub ratchet_metrics: Option, - - // Percent change in metrics to consider noise - pub ratchet_noise_percent: Option, - - // "Shard" of the testsuite to pub run: this has the form of - // two numbers (a,b), and causes only those tests with - // positional order equal to a mod b to run. - pub test_shard: Option<(uint,uint)>, - // A command line to prefix program execution with, // for running under valgrind pub runtool: Option, diff --git a/src/compiletest/compiletest.rs b/src/compiletest/compiletest.rs index f3514c6e7bc..17a39bc1c74 100644 --- a/src/compiletest/compiletest.rs +++ b/src/compiletest/compiletest.rs @@ -77,10 +77,6 @@ pub fn parse_config(args: Vec ) -> Config { optopt("", "target-rustcflags", "flags to pass to rustc for target", "FLAGS"), optflag("", "verbose", "run tests verbosely, showing all output"), optopt("", "logfile", "file to log test execution to", "FILE"), - optopt("", "save-metrics", "file to save metrics to", "FILE"), - optopt("", "ratchet-metrics", "file to ratchet metrics against", "FILE"), - optopt("", "ratchet-noise-percent", - "percent change in metrics to consider noise", "N"), optflag("", "jit", "run tests under the JIT"), optopt("", "target", "the target to build for", "TARGET"), optopt("", "host", "the host to build for", "HOST"), @@ -90,7 +86,6 @@ pub fn parse_config(args: Vec ) -> Config { optopt("", "adb-path", "path to the android debugger", "PATH"), optopt("", "adb-test-dir", "path to tests for the android debugger", "PATH"), optopt("", "lldb-python-dir", "directory containing LLDB's python module", "PATH"), - optopt("", "test-shard", "run shard A, of B shards, worth of the testsuite", "A.B"), optflag("h", "help", "show this message")); assert!(!args.is_empty()); @@ -152,12 +147,6 @@ fn opt_path(m: &getopts::Matches, nm: &str) -> Path { filter: filter, cfail_regex: Regex::new(errors::EXPECTED_PATTERN).unwrap(), logfile: matches.opt_str("logfile").map(|s| Path::new(s)), - save_metrics: matches.opt_str("save-metrics").map(|s| Path::new(s)), - ratchet_metrics: - matches.opt_str("ratchet-metrics").map(|s| Path::new(s)), - ratchet_noise_percent: - matches.opt_str("ratchet-noise-percent") - .and_then(|s| s.as_slice().parse::()), runtool: matches.opt_str("runtool"), host_rustcflags: matches.opt_str("host-rustcflags"), target_rustcflags: matches.opt_str("target-rustcflags"), @@ -176,7 +165,6 @@ fn opt_path(m: &getopts::Matches, nm: &str) -> Path { opt_str2(matches.opt_str("adb-test-dir")).as_slice() && !opt_str2(matches.opt_str("adb-test-dir")).is_empty(), lldb_python_dir: matches.opt_str("lldb-python-dir"), - test_shard: test::opt_shard(matches.opt_str("test-shard")), verbose: matches.opt_present("verbose"), } } @@ -210,10 +198,6 @@ pub fn log_config(config: &Config) { logv(c, format!("adb_test_dir: {:?}", config.adb_test_dir)); logv(c, format!("adb_device_status: {}", config.adb_device_status)); - match config.test_shard { - None => logv(c, "test_shard: (all)".to_string()), - Some((a,b)) => logv(c, format!("test_shard: {}.{}", a, b)) - } logv(c, format!("verbose: {}", config.verbose)); logv(c, format!("\n")); } @@ -284,10 +268,10 @@ pub fn test_opts(config: &Config) -> test::TestOpts { logfile: config.logfile.clone(), run_tests: true, run_benchmarks: true, - ratchet_metrics: config.ratchet_metrics.clone(), - ratchet_noise_percent: config.ratchet_noise_percent.clone(), - save_metrics: config.save_metrics.clone(), - test_shard: config.test_shard.clone(), + ratchet_metrics: None, + ratchet_noise_percent: None, + save_metrics: None, + test_shard: None, nocapture: false, color: test::AutoColor, show_boxplot: false, From 4f6f7e5d1dc791e77184641d3230a9b857b34e47 Mon Sep 17 00:00:00 2001 From: Ahmed Charles Date: Mon, 19 Jan 2015 00:20:55 -0800 Subject: [PATCH 36/96] Remove unsupported test features from libtest. Removes test-shard, ratchet-metrics, boxplot, stats and save-metrics from Config in libtest/lib.rs. --- src/compiletest/compiletest.rs | 7 -- src/libtest/lib.rs | 116 ++------------------------------- 2 files changed, 6 insertions(+), 117 deletions(-) diff --git a/src/compiletest/compiletest.rs b/src/compiletest/compiletest.rs index 17a39bc1c74..1a9a1c08b07 100644 --- a/src/compiletest/compiletest.rs +++ b/src/compiletest/compiletest.rs @@ -268,15 +268,8 @@ pub fn test_opts(config: &Config) -> test::TestOpts { logfile: config.logfile.clone(), run_tests: true, run_benchmarks: true, - ratchet_metrics: None, - ratchet_noise_percent: None, - save_metrics: None, - test_shard: None, nocapture: false, color: test::AutoColor, - show_boxplot: false, - boxplot_width: 50, - show_all_stats: false, } } diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index b9e37156dc7..be790245deb 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -300,16 +300,9 @@ pub struct TestOpts { pub run_ignored: bool, pub run_tests: bool, pub run_benchmarks: bool, - pub ratchet_metrics: Option, - pub ratchet_noise_percent: Option, - pub save_metrics: Option, - pub test_shard: Option<(uint,uint)>, pub logfile: Option, pub nocapture: bool, pub color: ColorConfig, - pub show_boxplot: bool, - pub boxplot_width: uint, - pub show_all_stats: bool, } impl TestOpts { @@ -320,16 +313,9 @@ fn new() -> TestOpts { run_ignored: false, run_tests: false, run_benchmarks: false, - ratchet_metrics: None, - ratchet_noise_percent: None, - save_metrics: None, - test_shard: None, logfile: None, nocapture: false, color: AutoColor, - show_boxplot: false, - boxplot_width: 50, - show_all_stats: false, } } } @@ -342,28 +328,14 @@ fn optgroups() -> Vec { getopts::optflag("", "test", "Run tests and not benchmarks"), getopts::optflag("", "bench", "Run benchmarks instead of tests"), getopts::optflag("h", "help", "Display this message (longer with --help)"), - getopts::optopt("", "save-metrics", "Location to save bench metrics", - "PATH"), - getopts::optopt("", "ratchet-metrics", - "Location to load and save metrics from. The metrics \ - loaded are cause benchmarks to fail if they run too \ - slowly", "PATH"), - getopts::optopt("", "ratchet-noise-percent", - "Tests within N% of the recorded metrics will be \ - considered as passing", "PERCENTAGE"), getopts::optopt("", "logfile", "Write logs to the specified file instead \ of stdout", "PATH"), - getopts::optopt("", "test-shard", "run shard A, of B shards, worth of the testsuite", - "A.B"), getopts::optflag("", "nocapture", "don't capture stdout/stderr of each \ task, allow printing directly"), getopts::optopt("", "color", "Configure coloring of output: auto = colorize if stdout is a tty and tests are run on serially (default); always = always colorize output; - never = never colorize output;", "auto|always|never"), - getopts::optflag("", "boxplot", "Display a boxplot of the benchmark statistics"), - getopts::optopt("", "boxplot-width", "Set the boxplot width (default 50)", "WIDTH"), - getopts::optflag("", "stats", "Display the benchmark min, max, and quartiles")) + never = never colorize output;", "auto|always|never")) } fn usage(binary: &str) { @@ -428,19 +400,6 @@ pub fn parse_opts(args: &[String]) -> Option { let run_tests = ! run_benchmarks || matches.opt_present("test"); - let ratchet_metrics = matches.opt_str("ratchet-metrics"); - let ratchet_metrics = ratchet_metrics.map(|s| Path::new(s)); - - let ratchet_noise_percent = matches.opt_str("ratchet-noise-percent"); - let ratchet_noise_percent = - ratchet_noise_percent.map(|s| s.as_slice().parse::().unwrap()); - - let save_metrics = matches.opt_str("save-metrics"); - let save_metrics = save_metrics.map(|s| Path::new(s)); - - let test_shard = matches.opt_str("test-shard"); - let test_shard = opt_shard(test_shard); - let mut nocapture = matches.opt_present("nocapture"); if !nocapture { nocapture = os::getenv("RUST_TEST_NOCAPTURE").is_some(); @@ -456,63 +415,19 @@ pub fn parse_opts(args: &[String]) -> Option { v))), }; - let show_boxplot = matches.opt_present("boxplot"); - let boxplot_width = match matches.opt_str("boxplot-width") { - Some(width) => { - match FromStr::from_str(width.as_slice()) { - Some(width) => width, - None => { - return Some(Err(format!("argument for --boxplot-width must be a uint"))); - } - } - } - None => 50, - }; - - let show_all_stats = matches.opt_present("stats"); - let test_opts = TestOpts { filter: filter, run_ignored: run_ignored, run_tests: run_tests, run_benchmarks: run_benchmarks, - ratchet_metrics: ratchet_metrics, - ratchet_noise_percent: ratchet_noise_percent, - save_metrics: save_metrics, - test_shard: test_shard, logfile: logfile, nocapture: nocapture, color: color, - show_boxplot: show_boxplot, - boxplot_width: boxplot_width, - show_all_stats: show_all_stats, }; Some(Ok(test_opts)) } -pub fn opt_shard(maybestr: Option) -> Option<(uint,uint)> { - match maybestr { - None => None, - Some(s) => { - let mut it = s.split('.'); - match (it.next().and_then(|s| s.parse::()), - it.next().and_then(|s| s.parse::()), - it.next()) { - (Some(a), Some(b), None) => { - if a <= 0 || a > b { - panic!("tried to run shard {a}.{b}, but {a} is out of bounds \ - (should be between 1 and {b}", a=a, b=b) - } - Some((a, b)) - } - _ => None, - } - } - } -} - - #[derive(Clone, PartialEq)] pub struct BenchSamples { ns_iter_summ: stats::Summary, @@ -568,9 +483,9 @@ pub fn new(opts: &TestOpts, out: out, log_out: log_out, use_color: use_color(opts), - show_boxplot: opts.show_boxplot, - boxplot_width: opts.boxplot_width, - show_all_stats: opts.show_all_stats, + show_boxplot: false, + boxplot_width: 50, + show_all_stats: false, total: 0u, passed: 0u, failed: 0u, @@ -913,15 +828,7 @@ fn len_if_padded(t: &TestDescAndFn) -> uint { None => {} } try!(run_tests(opts, tests, |x| callback(&x, &mut st))); - match opts.save_metrics { - None => (), - Some(ref pth) => { - try!(st.metrics.save(pth)); - try!(st.write_plain(format!("\nmetrics saved to: {:?}", - pth.display()).as_slice())); - } - } - return st.write_run_finish(&opts.ratchet_metrics, opts.ratchet_noise_percent); + return st.write_run_finish(&None, None); } #[test] @@ -1095,18 +1002,7 @@ fn filter(test: TestDescAndFn) -> Option { // Sort the tests alphabetically filtered.sort_by(|t1, t2| t1.desc.name.as_slice().cmp(t2.desc.name.as_slice())); - // Shard the remaining tests, if sharding requested. - match opts.test_shard { - None => filtered, - Some((a,b)) => { - filtered.into_iter().enumerate() - // note: using a - 1 so that the valid shards, for example, are - // 1.2 and 2.2 instead of 0.2 and 1.2 - .filter(|&(i,_)| i % b == (a - 1)) - .map(|(_,t)| t) - .collect() - } - } + filtered } pub fn run_test(opts: &TestOpts, From 940080501b76e559e3a2c0de1b15dc7b2353fd85 Mon Sep 17 00:00:00 2001 From: Eunji Jeong Date: Tue, 20 Jan 2015 15:03:44 +0900 Subject: [PATCH 37/96] Initial support for aarch64-linux-android --- mk/cfg/aarch64-linux-android.mk | 30 +++++++++++++++++++ mk/rt.mk | 2 ++ src/liblibc/lib.rs | 4 +-- .../target/aarch64_linux_android.rs | 28 +++++++++++++++++ src/librustc_back/target/mod.rs | 2 ++ src/libstd/sys/unix/backtrace.rs | 4 +-- 6 files changed, 66 insertions(+), 4 deletions(-) create mode 100644 mk/cfg/aarch64-linux-android.mk create mode 100644 src/librustc_back/target/aarch64_linux_android.rs diff --git a/mk/cfg/aarch64-linux-android.mk b/mk/cfg/aarch64-linux-android.mk new file mode 100644 index 00000000000..a6f7f2ba1d6 --- /dev/null +++ b/mk/cfg/aarch64-linux-android.mk @@ -0,0 +1,30 @@ +# aarch64-linux-android configuration +# CROSS_PREFIX_aarch64-linux-android- +CC_aarch64-linux-android=$(CFG_ANDROID_CROSS_PATH)/bin/aarch64-linux-android-gcc +CXX_aarch64-linux-android=$(CFG_ANDROID_CROSS_PATH)/bin/aarch64-linux-android-g++ +CPP_aarch64-linux-android=$(CFG_ANDROID_CROSS_PATH)/bin/aarch64-linux-android-gcc -E +AR_aarch64-linux-android=$(CFG_ANDROID_CROSS_PATH)/bin/aarch64-linux-android-ar +CFG_LIB_NAME_aarch64-linux-android=lib$(1).so +CFG_STATIC_LIB_NAME_aarch64-linux-android=lib$(1).a +CFG_LIB_GLOB_aarch64-linux-android=lib$(1)-*.so +CFG_LIB_DSYM_GLOB_aarch64-linux-android=lib$(1)-*.dylib.dSYM +CFG_JEMALLOC_CFLAGS_aarch64-linux-android := -D__aarch64__ -DANDROID -D__ANDROID__ $(CFLAGS) +CFG_GCCISH_CFLAGS_aarch64-linux-android := -Wall -g -fPIC -D__aarch64__ -DANDROID -D__ANDROID__ $(CFLAGS) +CFG_GCCISH_CXXFLAGS_aarch64-linux-android := -fno-rtti $(CXXFLAGS) +CFG_GCCISH_LINK_FLAGS_aarch64-linux-android := -shared -fPIC -ldl -g -lm -lsupc++ +CFG_GCCISH_DEF_FLAG_aarch64-linux-android := -Wl,--export-dynamic,--dynamic-list= +CFG_GCCISH_PRE_LIB_FLAGS_aarch64-linux-android := -Wl,-whole-archive +CFG_GCCISH_POST_LIB_FLAGS_aarch64-linux-android := -Wl,-no-whole-archive +CFG_DEF_SUFFIX_aarch64-linux-android := .android.def +CFG_LLC_FLAGS_aarch64-linux-android := +CFG_INSTALL_NAME_aarch64-linux-android = +CFG_EXE_SUFFIX_aarch64-linux-android := +CFG_WINDOWSY_aarch64-linux-android := +CFG_UNIXY_aarch64-linux-android := 1 +CFG_PATH_MUNGE_aarch64-linux-android := true +CFG_LDPATH_aarch64-linux-android := +CFG_RUN_aarch64-linux-android= +CFG_RUN_TARG_aarch64-linux-android= +RUSTC_FLAGS_aarch64-linux-android := +RUSTC_CROSS_FLAGS_aarch64-linux-android := +CFG_GNU_TRIPLE_aarch64-linux-android := aarch64-linux-android diff --git a/mk/rt.mk b/mk/rt.mk index 6a7be26c7a6..a8bbeb41517 100644 --- a/mk/rt.mk +++ b/mk/rt.mk @@ -141,6 +141,8 @@ else ifeq ($(OSTYPE_$(1)), apple-ios) JEMALLOC_ARGS_$(1) := --disable-tls else ifeq ($(OSTYPE_$(1)), linux-androideabi) JEMALLOC_ARGS_$(1) := --disable-tls +else ifeq ($(OSTYPE_$(1)), linux-android) + JEMALLOC_ARGS_$(1) := --disable-tls endif ################################################################################ diff --git a/src/liblibc/lib.rs b/src/liblibc/lib.rs index d010615a24c..2fd92695fe3 100644 --- a/src/liblibc/lib.rs +++ b/src/liblibc/lib.rs @@ -4647,13 +4647,13 @@ pub mod signal { use types::os::arch::c95::c_int; use types::os::common::posix01::sighandler_t; - #[cfg(not(target_os = "android"))] + #[cfg(not(all(target_os = "android", target_arch = "arm")))] extern { pub fn signal(signum: c_int, handler: sighandler_t) -> sighandler_t; } - #[cfg(target_os = "android")] + #[cfg(all(target_os = "android", target_arch = "arm"))] extern { #[link_name = "bsd_signal"] pub fn signal(signum: c_int, diff --git a/src/librustc_back/target/aarch64_linux_android.rs b/src/librustc_back/target/aarch64_linux_android.rs new file mode 100644 index 00000000000..313c0dc2a6e --- /dev/null +++ b/src/librustc_back/target/aarch64_linux_android.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. + +use target::Target; + +pub fn target() -> Target { + let mut base = super::linux_base::opts(); + base.pre_link_args.push("-Wl,--allow-multiple-definition".to_string()); + base.position_independent_executables = true; + Target { + data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\ + f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\ + n32:64-S128".to_string(), + llvm_target: "aarch64-linux-android".to_string(), + target_endian: "little".to_string(), + target_pointer_width: "64".to_string(), + arch: "aarch64".to_string(), + target_os: "android".to_string(), + options: base, + } +} diff --git a/src/librustc_back/target/mod.rs b/src/librustc_back/target/mod.rs index f8eabb4375f..4626f2dc483 100644 --- a/src/librustc_back/target/mod.rs +++ b/src/librustc_back/target/mod.rs @@ -65,6 +65,7 @@ mod arm_unknown_linux_gnueabi; mod arm_unknown_linux_gnueabihf; mod aarch64_apple_ios; +mod aarch64_linux_android; mod aarch64_unknown_linux_gnu; mod i686_apple_darwin; mod i686_pc_windows_gnu; @@ -357,6 +358,7 @@ macro_rules! load_specific { i386_apple_ios, x86_64_apple_ios, aarch64_apple_ios, + aarch64_linux_android, armv7_apple_ios, armv7s_apple_ios, diff --git a/src/libstd/sys/unix/backtrace.rs b/src/libstd/sys/unix/backtrace.rs index 7164931c55a..fe9c77c219a 100644 --- a/src/libstd/sys/unix/backtrace.rs +++ b/src/libstd/sys/unix/backtrace.rs @@ -418,7 +418,7 @@ pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn, trace_argument: *mut libc::c_void) -> _Unwind_Reason_Code; - #[cfg(all(not(target_os = "android"), + #[cfg(all(not(all(target_os = "android", target_arch = "arm")), not(all(target_os = "linux", target_arch = "arm"))))] pub fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t; @@ -431,7 +431,7 @@ pub fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void) // On android, the function _Unwind_GetIP is a macro, and this is the // expansion of the macro. This is all copy/pasted directly from the // header file with the definition of _Unwind_GetIP. - #[cfg(any(target_os = "android", + #[cfg(any(all(target_os = "android", target_arch = "arm"), all(target_os = "linux", target_arch = "arm")))] pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t { #[repr(C)] From a729a404945de10f99e2530a5c28952996532b29 Mon Sep 17 00:00:00 2001 From: James Miller Date: Wed, 21 Jan 2015 00:46:02 +1300 Subject: [PATCH 38/96] Use assume to inform the optimiser about refcount invariants The reference count can never be 0, unless we're about to drop the data completely. Using the `assume` intrinsic allows us to inform LLVM about that invariant, meaning it can avoid unnecessary drops. --- src/liballoc/rc.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 7191a7af346..0f2a11cc1db 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -160,6 +160,7 @@ use core::ptr::{self, PtrExt}; use core::result::Result; use core::result::Result::{Ok, Err}; +use core::intrinsics::assume; use heap::deallocate; @@ -905,10 +906,20 @@ trait RcBoxPtr { fn strong(&self) -> uint { self.inner().strong.get() } #[inline] - fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); } + fn inc_strong(&self) { + let strong = self.strong(); + // The reference count is always at least one unless we're about to drop the type + unsafe { assume(strong > 0); } + self.inner().strong.set(strong + 1); + } #[inline] - fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); } + fn dec_strong(&self) { + let strong = self.strong(); + // The reference count is always at least one unless we're about to drop the type + unsafe { assume(strong > 0); } + self.inner().strong.set(strong - 1); + } #[inline] fn weak(&self) -> uint { self.inner().weak.get() } From 849a38ad86bc94832f2a931557a92e528c0d32e7 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Tue, 20 Jan 2015 23:09:50 +1100 Subject: [PATCH 39/96] Avoid suggesting traits multiple times. This is clearly useless, the user doesn't need to know that they could implement/import `foo::bar::Baz` 4 times. Fixes #21405. --- src/librustc_typeck/check/method/suggest.rs | 2 ++ .../method-suggestion-no-duplication.rs | 22 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 src/test/compile-fail/method-suggestion-no-duplication.rs diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs index 2a89a1d28bf..3cf9a1a9456 100644 --- a/src/librustc_typeck/check/method/suggest.rs +++ b/src/librustc_typeck/check/method/suggest.rs @@ -145,6 +145,7 @@ fn suggest_traits_to_import<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, if !valid_out_of_scope_traits.is_empty() { let mut candidates = valid_out_of_scope_traits; candidates.sort(); + candidates.dedup(); let msg = format!( "methods from traits can only be called if the trait is in scope; \ the following {traits_are} implemented but not in scope, \ @@ -172,6 +173,7 @@ fn suggest_traits_to_import<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, if candidates.len() > 0 { // sort from most relevant to least relevant candidates.sort_by(|a, b| a.cmp(b).reverse()); + candidates.dedup(); let msg = format!( "methods from traits can only be called if the trait is implemented and in scope; \ diff --git a/src/test/compile-fail/method-suggestion-no-duplication.rs b/src/test/compile-fail/method-suggestion-no-duplication.rs new file mode 100644 index 00000000000..627fc6f0b05 --- /dev/null +++ b/src/test/compile-fail/method-suggestion-no-duplication.rs @@ -0,0 +1,22 @@ +// 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. + +// issue #21405 + +fn foo(f: F) where F: FnMut(usize) {} + +fn main() { + foo(|s| s.is_empty()); + //~^ ERROR does not implement any method + //~^^ HELP #1: `core::slice::SliceExt` + //~^^^ HELP #2: `core::str::StrExt` + //~^^^^ HELP #3: `collections::slice::SliceExt` + //~^^^^^ HELP #4: `collections::str::StrExt` +} From 01d7b8c6698311b1c610ae98e37839895a440951 Mon Sep 17 00:00:00 2001 From: Toby Scrace Date: Tue, 20 Jan 2015 12:18:23 +0000 Subject: [PATCH 40/96] Correct small typos in map.rs. This just corrects a couple of typos in doc comments, and changes some to conform to the Rust guidelines. --- src/libstd/collections/hash/map.rs | 46 +++++++++++++++--------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 80ae3076df3..09700673f0c 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -1,4 +1,4 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -76,7 +76,7 @@ fn usable_capacity(&self, cap: uint) -> uint { // min_capacity(size) must be smaller than the internal capacity, // so that the map is not resized: // `min_capacity(usable_capacity(x)) <= x`. - // The lef-hand side can only be smaller due to flooring by integer + // The left-hand side can only be smaller due to flooring by integer // division. // // This doesn't have to be checked for overflow since allocation size @@ -838,8 +838,8 @@ fn first((a, _): (A, B)) -> A { a } /// map.insert("b", 2); /// map.insert("c", 3); /// - /// for key in map.values() { - /// println!("{}", key); + /// for val in map.values() { + /// println!("{}", val); /// } /// ``` #[stable] @@ -938,7 +938,7 @@ pub fn entry<'a>(&'a mut self, key: K) -> Entry<'a, K, V> search_entry_hashed(&mut self.table, hash, key) } - /// Return the number of elements in the map. + /// Returns the number of elements in the map. /// /// # Example /// @@ -953,7 +953,7 @@ pub fn entry<'a>(&'a mut self, key: K) -> Entry<'a, K, V> #[stable] pub fn len(&self) -> uint { self.table.size() } - /// Return true if the map contains no elements. + /// Returns true if the map contains no elements. /// /// # Example /// @@ -1274,7 +1274,7 @@ fn index_mut<'a>(&'a mut self, index: &Q) -> &'a mut V { } } -/// HashMap iterator +/// HashMap iterator. #[stable] pub struct Iter<'a, K: 'a, V: 'a> { inner: table::Iter<'a, K, V> @@ -1289,13 +1289,13 @@ fn clone(&self) -> Iter<'a, K, V> { } } -/// HashMap mutable values iterator +/// HashMap mutable values iterator. #[stable] pub struct IterMut<'a, K: 'a, V: 'a> { inner: table::IterMut<'a, K, V> } -/// HashMap move iterator +/// HashMap move iterator. #[stable] pub struct IntoIter { inner: iter::Map< @@ -1306,7 +1306,7 @@ pub struct IntoIter { > } -/// HashMap keys iterator +/// HashMap keys iterator. #[stable] pub struct Keys<'a, K: 'a, V: 'a> { inner: Map<(&'a K, &'a V), &'a K, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K> @@ -1321,7 +1321,7 @@ fn clone(&self) -> Keys<'a, K, V> { } } -/// HashMap values iterator +/// HashMap values iterator. #[stable] pub struct Values<'a, K: 'a, V: 'a> { inner: Map<(&'a K, &'a V), &'a V, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V> @@ -1336,7 +1336,7 @@ fn clone(&self) -> Values<'a, K, V> { } } -/// HashMap drain iterator +/// HashMap drain iterator. #[unstable = "matches collection reform specification, waiting for dust to settle"] pub struct Drain<'a, K: 'a, V: 'a> { inner: iter::Map< @@ -1347,13 +1347,13 @@ pub struct Drain<'a, K: 'a, V: 'a> { > } -/// A view into a single occupied location in a HashMap +/// A view into a single occupied location in a HashMap. #[unstable = "precise API still being fleshed out"] pub struct OccupiedEntry<'a, K: 'a, V: 'a> { elem: FullBucket>, } -/// A view into a single empty location in a HashMap +/// A view into a single empty location in a HashMap. #[unstable = "precise API still being fleshed out"] pub struct VacantEntry<'a, K: 'a, V: 'a> { hash: SafeHash, @@ -1361,21 +1361,21 @@ pub struct VacantEntry<'a, K: 'a, V: 'a> { elem: VacantEntryState>, } -/// A view into a single location in a map, which may be vacant or occupied +/// A view into a single location in a map, which may be vacant or occupied. #[unstable = "precise API still being fleshed out"] pub enum Entry<'a, K: 'a, V: 'a> { - /// An occupied Entry + /// An occupied Entry. Occupied(OccupiedEntry<'a, K, V>), - /// A vacant Entry + /// A vacant Entry. Vacant(VacantEntry<'a, K, V>), } -/// Possible states of a VacantEntry +/// Possible states of a VacantEntry. enum VacantEntryState { /// The index is occupied, but the key to insert has precedence, - /// and will kick the current one out on insertion + /// and will kick the current one out on insertion. NeqElem(FullBucket, uint), - /// The index is genuinely vacant + /// The index is genuinely vacant. NoElem(EmptyBucket), } @@ -1453,7 +1453,7 @@ impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> { #[unstable = "matches collection reform v2 specification, waiting for dust to settle"] impl<'a, K, V> Entry<'a, K, V> { - /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant + /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant. pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> { match self { Occupied(entry) => Ok(entry.into_mut()), @@ -1464,12 +1464,12 @@ pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> { #[unstable = "matches collection reform v2 specification, waiting for dust to settle"] impl<'a, K, V> OccupiedEntry<'a, K, V> { - /// Gets a reference to the value in the entry + /// Gets a reference to the value in the entry. pub fn get(&self) -> &V { self.elem.read().1 } - /// Gets a mutable reference to the value in the entry + /// Gets a mutable reference to the value in the entry. pub fn get_mut(&mut self) -> &mut V { self.elem.read_mut().1 } From f2b8404bcb095235efeaf7a39536cd55172ac18e Mon Sep 17 00:00:00 2001 From: Oliver Schneider Date: Fri, 16 Jan 2015 10:49:35 +0100 Subject: [PATCH 41/96] prettier Buffer::read_until --- src/libstd/io/mod.rs | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index e2b71cd43af..88be8d1189e 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -1436,33 +1436,31 @@ fn read_line(&mut self) -> IoResult { fn read_until(&mut self, byte: u8) -> IoResult> { let mut res = Vec::new(); - let mut used; loop { - { + let (done, used) = { let available = match self.fill_buf() { Ok(n) => n, Err(ref e) if res.len() > 0 && e.kind == EndOfFile => { - used = 0; - break + return Ok(res); } Err(e) => return Err(e) }; match available.iter().position(|&b| b == byte) { Some(i) => { res.push_all(&available[..(i + 1)]); - used = i + 1; - break + (true, i + 1) } None => { res.push_all(available); - used = available.len(); + (false, available.len()) } } + }; + buffer.consume(used); + if done { + return Ok(res); } - self.consume(used); } - self.consume(used); - Ok(res) } /// Reads the next utf8-encoded character from the underlying stream. From 1f50542a0dc58165810f12b52f59d63f7dab9aaa Mon Sep 17 00:00:00 2001 From: Alfie John Date: Tue, 20 Jan 2015 19:02:09 +0000 Subject: [PATCH 42/96] docs: typo --- src/doc/trpl/crates-and-modules.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/trpl/crates-and-modules.md b/src/doc/trpl/crates-and-modules.md index 6c5c14fe311..fdd772a0cd7 100644 --- a/src/doc/trpl/crates-and-modules.md +++ b/src/doc/trpl/crates-and-modules.md @@ -258,7 +258,7 @@ fn goodbye() -> String { (This is "Sayōnara", if you're curious.) -Now that we have our some functionality in our crate, let's try to use it from +Now that we have some functionality in our crate, let's try to use it from another crate. # Importing External Crates From 953f294ea30253bb5578e3c895d17fcc97c20dce Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 20 Jan 2015 10:57:10 -0800 Subject: [PATCH 43/96] rustc: Remove deprecated flags This commit removes a number of deprecated flags from the compiler: * opt-level => -C opt-level * debuginfo => -C debuginfo * print-crate-name => --print crate-name * print-file-name => --print file-names * no-trans => -Z no-trans * no-analysis => -Z no-analysis * parse-only => -Z parse-only * dep-info => --emit dep-info This commit also moves the --pretty flag behind `-Z unstable-options` as the pretty printer will likely not be stable for 1.0 cc #19051 --- src/compiletest/runtest.rs | 3 +- src/librustc/session/config.rs | 102 ++---------------- src/librustc_driver/lib.rs | 12 ++- src/test/debuginfo/issue7712.rs | 2 +- .../lexical-scope-in-parameterless-closure.rs | 2 +- src/test/debuginfo/limited-debuginfo.rs | 2 +- src/test/run-make/crate-data-smoke/Makefile | 12 +-- src/test/run-make/dep-info-custom/Makefile | 25 ----- .../run-make/dep-info-custom/Makefile.foo | 7 -- src/test/run-make/dep-info-custom/bar.rs | 11 -- src/test/run-make/dep-info-custom/foo.rs | 11 -- src/test/run-make/dep-info-custom/lib.rs | 14 --- src/test/run-make/dep-info-spaces/Makefile | 2 +- .../run-make/dep-info-spaces/Makefile.foo | 6 +- src/test/run-make/dep-info/Makefile | 2 +- .../error-writing-dependencies/Makefile | 4 +- src/test/run-make/graphviz-flowgraph/Makefile | 2 +- .../run-make/pretty-expanded-hygiene/Makefile | 3 +- src/test/run-make/pretty-expanded/Makefile | 3 +- .../pretty-print-path-suffix/Makefile | 6 +- .../run-make/pretty-print-to-file/Makefile | 2 +- src/test/run-make/tools.mk | 3 +- 22 files changed, 43 insertions(+), 193 deletions(-) delete mode 100644 src/test/run-make/dep-info-custom/Makefile delete mode 100644 src/test/run-make/dep-info-custom/Makefile.foo delete mode 100644 src/test/run-make/dep-info-custom/bar.rs delete mode 100644 src/test/run-make/dep-info-custom/foo.rs delete mode 100644 src/test/run-make/dep-info-custom/lib.rs diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index 5579479c5e5..9eac187a8e2 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -294,6 +294,7 @@ fn make_pp_args(config: &Config, let aux_dir = aux_output_dir_name(config, testfile); // FIXME (#9639): This needs to handle non-utf8 paths let mut args = vec!("-".to_string(), + "-Zunstable-options".to_string(), "--pretty".to_string(), pretty_type, format!("--target={}", config.target), @@ -340,7 +341,7 @@ fn make_typecheck_args(config: &Config, props: &TestProps, testfile: &Path) -> P }; // FIXME (#9639): This needs to handle non-utf8 paths let mut args = vec!("-".to_string(), - "--no-trans".to_string(), + "-Zno-trans".to_string(), "--crate-type=lib".to_string(), format!("--target={}", target), "-L".to_string(), diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index d9bb1d769bf..1e4babef9f5 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -786,7 +786,6 @@ pub fn rustc_optgroups() -> Vec { opt::multi("", "extern", "Specify where an external rust library is \ located", "NAME=PATH"), - opt::opt("", "opt-level", "Optimize with possible levels 0-3", "LEVEL"), opt::opt("", "sysroot", "Override the system root", "PATH"), opt::multi("Z", "", "Set internal debugging options", "FLAG"), opt::opt("", "color", "Configure coloring of output: @@ -794,22 +793,7 @@ pub fn rustc_optgroups() -> Vec { always = always colorize output; never = never colorize output", "auto|always|never"), - // DEPRECATED - opt::flag("", "print-crate-name", "Output the crate name and exit"), - opt::flag("", "print-file-name", "Output the file(s) that would be \ - written if compilation \ - continued and exit"), - opt::opt("", "debuginfo", "Emit DWARF debug info to the objects created: - 0 = no debug info, - 1 = line-tables only (for stacktraces and breakpoints), - 2 = full debug info with variable and type information \ - (same as -g)", "LEVEL"), - opt::flag("", "no-trans", "Run all passes except translation; no output"), - opt::flag("", "no-analysis", "Parse and expand the source, but run no \ - analysis and produce no output"), - opt::flag("", "parse-only", "Parse only; do not compile, assemble, \ - or link"), - opt::flagopt("", "pretty", + opt::flagopt_u("", "pretty", "Pretty-print the input instead of compiling; valid types are: `normal` (un-annotated source), `expanded` (crates expanded), @@ -823,9 +807,6 @@ pub fn rustc_optgroups() -> Vec { `everybody_loops` (all function bodies replaced with `loop {}`).", "TYPE"), opt::opt_u("", "show-span", "Show spans for compiler debugging", "expr|pat|ty"), - opt::flagopt("", "dep-info", - "Output dependency info to after compiling, \ - in a format suitable for use by Makefiles", "FILENAME"), ]); opts } @@ -861,27 +842,9 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { let debugging_opts = build_debugging_options(matches); - let parse_only = if matches.opt_present("parse-only") { - // FIXME(acrichto) remove this eventually - early_warn("--parse-only is deprecated in favor of -Z parse-only"); - true - } else { - debugging_opts.parse_only - }; - let no_trans = if matches.opt_present("no-trans") { - // FIXME(acrichto) remove this eventually - early_warn("--no-trans is deprecated in favor of -Z no-trans"); - true - } else { - debugging_opts.no_trans - }; - let no_analysis = if matches.opt_present("no-analysis") { - // FIXME(acrichto) remove this eventually - early_warn("--no-analysis is deprecated in favor of -Z no-analysis"); - true - } else { - debugging_opts.no_analysis - }; + let parse_only = debugging_opts.parse_only; + let no_trans = debugging_opts.no_trans; + let no_analysis = debugging_opts.no_analysis; if debugging_opts.debug_llvm { unsafe { llvm::LLVMSetDebug(1); } @@ -921,28 +884,10 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { host_triple().to_string()); let opt_level = { if matches.opt_present("O") { - if matches.opt_present("opt-level") { - early_error("-O and --opt-level both provided"); - } if cg.opt_level.is_some() { early_error("-O and -C opt-level both provided"); } Default - } else if matches.opt_present("opt-level") { - // FIXME(acrichto) remove this eventually - early_warn("--opt-level=N is deprecated in favor of -C opt-level=N"); - match matches.opt_str("opt-level").as_ref().map(|s| s.as_slice()) { - None | - Some("0") => No, - Some("1") => Less, - Some("2") => Default, - Some("3") => Aggressive, - Some(arg) => { - early_error(&format!("optimization level needs to be \ - between 0-3 (instead was `{}`)", - arg)[]); - } - } } else { match cg.opt_level { None => No, @@ -960,27 +905,10 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { }; let gc = debugging_opts.gc; let debuginfo = if matches.opt_present("g") { - if matches.opt_present("debuginfo") { - early_error("-g and --debuginfo both provided"); - } if cg.debuginfo.is_some() { early_error("-g and -C debuginfo both provided"); } FullDebugInfo - } else if matches.opt_present("debuginfo") { - // FIXME(acrichto) remove this eventually - early_warn("--debuginfo=N is deprecated in favor of -C debuginfo=N"); - match matches.opt_str("debuginfo").as_ref().map(|s| s.as_slice()) { - Some("0") => NoDebugInfo, - Some("1") => LimitedDebugInfo, - None | - Some("2") => FullDebugInfo, - Some(arg) => { - early_error(&format!("debug info level needs to be between \ - 0-2 (instead was `{}`)", - arg)[]); - } - } } else { match cg.debuginfo { None | Some(0) => NoDebugInfo, @@ -1036,15 +964,9 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { let cfg = parse_cfgspecs(matches.opt_strs("cfg")); let test = matches.opt_present("test"); - let write_dependency_info = if matches.opt_present("dep-info") { - // FIXME(acrichto) remove this eventually - early_warn("--dep-info has been deprecated in favor of --emit"); - (true, matches.opt_str("dep-info").map(|p| Path::new(p))) - } else { - (output_types.contains(&OutputTypeDepInfo), None) - }; + let write_dependency_info = (output_types.contains(&OutputTypeDepInfo), None); - let mut prints = matches.opt_strs("print").into_iter().map(|s| { + let prints = matches.opt_strs("print").into_iter().map(|s| { match s.as_slice() { "crate-name" => PrintRequest::CrateName, "file-names" => PrintRequest::FileNames, @@ -1054,18 +976,6 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { } } }).collect::>(); - if matches.opt_present("print-crate-name") { - // FIXME(acrichto) remove this eventually - early_warn("--print-crate-name has been deprecated in favor of \ - --print crate-name"); - prints.push(PrintRequest::CrateName); - } - if matches.opt_present("print-file-name") { - // FIXME(acrichto) remove this eventually - early_warn("--print-file-name has been deprecated in favor of \ - --print file-names"); - prints.push(PrintRequest::FileNames); - } if !cg.remark.is_empty() && debuginfo == NoDebugInfo { early_warn("-C remark will not show source locations without \ diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 50ff4546c37..355d8ecf9ff 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -154,10 +154,14 @@ fn run_compiler(args: &[String]) { return } - let pretty = matches.opt_default("pretty", "normal").map(|a| { - // stable pretty-print variants only - pretty::parse_pretty(&sess, a.as_slice(), false) - }); + let pretty = if sess.opts.debugging_opts.unstable_options { + matches.opt_default("pretty", "normal").map(|a| { + // stable pretty-print variants only + pretty::parse_pretty(&sess, a.as_slice(), false) + }) + } else { + None + }; let pretty = if pretty.is_none() && sess.unstable_options() { matches.opt_str("xpretty").map(|a| { diff --git a/src/test/debuginfo/issue7712.rs b/src/test/debuginfo/issue7712.rs index 94458a7fb4b..124cdfb436c 100644 --- a/src/test/debuginfo/issue7712.rs +++ b/src/test/debuginfo/issue7712.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// compile-flags:--debuginfo=1 +// compile-flags:-C debuginfo=1 // min-lldb-version: 310 pub trait TraitWithDefaultMethod : Sized { diff --git a/src/test/debuginfo/lexical-scope-in-parameterless-closure.rs b/src/test/debuginfo/lexical-scope-in-parameterless-closure.rs index b2617c57742..0050b9273e8 100644 --- a/src/test/debuginfo/lexical-scope-in-parameterless-closure.rs +++ b/src/test/debuginfo/lexical-scope-in-parameterless-closure.rs @@ -11,7 +11,7 @@ // ignore-android: FIXME(#10381) // min-lldb-version: 310 -// compile-flags:--debuginfo=1 +// compile-flags:-C debuginfo=1 // gdb-command:run // lldb-command:run diff --git a/src/test/debuginfo/limited-debuginfo.rs b/src/test/debuginfo/limited-debuginfo.rs index 00de4497ced..76a0fd58395 100644 --- a/src/test/debuginfo/limited-debuginfo.rs +++ b/src/test/debuginfo/limited-debuginfo.rs @@ -12,7 +12,7 @@ // ignore-lldb -// compile-flags:--debuginfo=1 +// compile-flags:-C debuginfo=1 // Make sure functions have proper names // gdb-command:info functions diff --git a/src/test/run-make/crate-data-smoke/Makefile b/src/test/run-make/crate-data-smoke/Makefile index 093796e1dc2..1afda457411 100644 --- a/src/test/run-make/crate-data-smoke/Makefile +++ b/src/test/run-make/crate-data-smoke/Makefile @@ -1,10 +1,10 @@ -include ../tools.mk all: - [ `$(RUSTC) --print-crate-name crate.rs` = "foo" ] - [ `$(RUSTC) --print-file-name crate.rs` = "$(call BIN,foo)" ] - [ `$(RUSTC) --print-file-name --crate-type=lib \ + [ `$(RUSTC) --print crate-name crate.rs` = "foo" ] + [ `$(RUSTC) --print file-names crate.rs` = "$(call BIN,foo)" ] + [ `$(RUSTC) --print file-names --crate-type=lib \ --test crate.rs` = "$(call BIN,foo)" ] - [ `$(RUSTC) --print-file-name --test lib.rs` = "$(call BIN,mylib)" ] - $(RUSTC) --print-file-name lib.rs - $(RUSTC) --print-file-name rlib.rs + [ `$(RUSTC) --print file-names --test lib.rs` = "$(call BIN,mylib)" ] + $(RUSTC) --print file-names lib.rs + $(RUSTC) --print file-names rlib.rs diff --git a/src/test/run-make/dep-info-custom/Makefile b/src/test/run-make/dep-info-custom/Makefile deleted file mode 100644 index efa6dfe981b..00000000000 --- a/src/test/run-make/dep-info-custom/Makefile +++ /dev/null @@ -1,25 +0,0 @@ --include ../tools.mk - -# FIXME: ignore freebsd/windows -# (windows: see `../dep-info/Makefile`) -ifneq ($(shell uname),FreeBSD) -ifndef IS_WINDOWS -all: - $(RUSTC) --dep-info $(TMPDIR)/custom-deps-file.d --crate-type=lib lib.rs - sleep 1 - touch foo.rs - -rm -f $(TMPDIR)/done - $(MAKE) -drf Makefile.foo - rm $(TMPDIR)/done - pwd - $(MAKE) -drf Makefile.foo - rm $(TMPDIR)/done && exit 1 || exit 0 -else -all: - -endif - -else -all: - -endif diff --git a/src/test/run-make/dep-info-custom/Makefile.foo b/src/test/run-make/dep-info-custom/Makefile.foo deleted file mode 100644 index 88be7630e83..00000000000 --- a/src/test/run-make/dep-info-custom/Makefile.foo +++ /dev/null @@ -1,7 +0,0 @@ -LIB := $(shell $(RUSTC) --print file-names --crate-type=lib lib.rs) - -$(TMPDIR)/$(LIB): - $(RUSTC) --dep-info $(TMPDIR)/custom-deps-file.d --crate-type=lib lib.rs - touch $(TMPDIR)/done - --include $(TMPDIR)/custom-deps-file.d diff --git a/src/test/run-make/dep-info-custom/bar.rs b/src/test/run-make/dep-info-custom/bar.rs deleted file mode 100644 index 4c79f7e2855..00000000000 --- a/src/test/run-make/dep-info-custom/bar.rs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -pub fn bar() {} diff --git a/src/test/run-make/dep-info-custom/foo.rs b/src/test/run-make/dep-info-custom/foo.rs deleted file mode 100644 index 2661b1f4eb4..00000000000 --- a/src/test/run-make/dep-info-custom/foo.rs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -pub fn foo() {} diff --git a/src/test/run-make/dep-info-custom/lib.rs b/src/test/run-make/dep-info-custom/lib.rs deleted file mode 100644 index 14baa8ca55a..00000000000 --- a/src/test/run-make/dep-info-custom/lib.rs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![crate_name="foo"] - -pub mod foo; -pub mod bar; diff --git a/src/test/run-make/dep-info-spaces/Makefile b/src/test/run-make/dep-info-spaces/Makefile index 72dca3d3c90..eda8cb70081 100644 --- a/src/test/run-make/dep-info-spaces/Makefile +++ b/src/test/run-make/dep-info-spaces/Makefile @@ -5,7 +5,7 @@ ifneq ($(shell uname),FreeBSD) ifndef IS_WINDOWS all: - $(RUSTC) --dep-info $(TMPDIR)/custom-deps-file.d --crate-type=lib lib.rs + $(RUSTC) --emit link,dep-info --crate-type=lib lib.rs sleep 1 touch 'foo foo.rs' -rm -f $(TMPDIR)/done diff --git a/src/test/run-make/dep-info-spaces/Makefile.foo b/src/test/run-make/dep-info-spaces/Makefile.foo index 0e187565d6d..2f4cc486d86 100644 --- a/src/test/run-make/dep-info-spaces/Makefile.foo +++ b/src/test/run-make/dep-info-spaces/Makefile.foo @@ -1,7 +1,7 @@ -LIB := $(shell $(RUSTC) --print-file-name --crate-type=lib lib.rs) +LIB := $(shell $(RUSTC) --print file-names --crate-type=lib lib.rs) $(TMPDIR)/$(LIB): - $(RUSTC) --dep-info $(TMPDIR)/custom-deps-file.d --crate-type=lib lib.rs + $(RUSTC) --emit link,dep-info --crate-type=lib lib.rs touch $(TMPDIR)/done --include $(TMPDIR)/custom-deps-file.d +-include $(TMPDIR)/lib.d diff --git a/src/test/run-make/dep-info/Makefile b/src/test/run-make/dep-info/Makefile index 6835ef34b0b..a1828cd1f5d 100644 --- a/src/test/run-make/dep-info/Makefile +++ b/src/test/run-make/dep-info/Makefile @@ -7,7 +7,7 @@ ifneq ($(shell uname),FreeBSD) ifndef IS_WINDOWS all: - $(RUSTC) --dep-info --crate-type=lib lib.rs + $(RUSTC) --emit dep-info,link --crate-type=lib lib.rs sleep 2 touch foo.rs -rm -f $(TMPDIR)/done diff --git a/src/test/run-make/error-writing-dependencies/Makefile b/src/test/run-make/error-writing-dependencies/Makefile index 9f91618bda4..89fbfa0a1bf 100644 --- a/src/test/run-make/error-writing-dependencies/Makefile +++ b/src/test/run-make/error-writing-dependencies/Makefile @@ -2,7 +2,7 @@ all: # Let's get a nice error message - $(RUSTC) foo.rs --dep-info foo/bar/baz 2>&1 | \ + $(BARE_RUSTC) foo.rs --emit dep-info --out-dir foo/bar/baz 2>&1 | \ grep "error writing dependencies" # Make sure the filename shows up - $(RUSTC) foo.rs --dep-info foo/bar/baz 2>&1 | grep "baz" + $(BARE_RUSTC) foo.rs --emit dep-info --out-dir foo/bar/baz 2>&1 | grep "baz" diff --git a/src/test/run-make/graphviz-flowgraph/Makefile b/src/test/run-make/graphviz-flowgraph/Makefile index 4ac8cb7ae1d..1533729de94 100644 --- a/src/test/run-make/graphviz-flowgraph/Makefile +++ b/src/test/run-make/graphviz-flowgraph/Makefile @@ -13,7 +13,7 @@ all: $(patsubst %.rs,$(TMPDIR)/%.check,$(FILES)) RUSTC_LIB=$(RUSTC) --crate-type=lib define FIND_LAST_BLOCK -LASTBLOCKNUM_$(1) := $(shell $(RUSTC_LIB) --pretty=expanded,identified $(1) \ +LASTBLOCKNUM_$(1) := $(shell $(RUSTC_LIB) -Z unstable-options --pretty=expanded,identified $(1) \ | grep block | tail -1 | sed -e 's@.*/\* block \([0-9]*\) \*/.*@\1@') diff --git a/src/test/run-make/pretty-expanded-hygiene/Makefile b/src/test/run-make/pretty-expanded-hygiene/Makefile index 11763446437..136d7643ade 100644 --- a/src/test/run-make/pretty-expanded-hygiene/Makefile +++ b/src/test/run-make/pretty-expanded-hygiene/Makefile @@ -3,7 +3,8 @@ REPLACEMENT := s/[0-9][0-9]*\#[0-9][0-9]*/$(shell date)/g all: - $(RUSTC) -o $(TMPDIR)/input.out --pretty expanded,hygiene input.rs + $(RUSTC) -o $(TMPDIR)/input.out -Z unstable-options \ + --pretty expanded,hygiene input.rs # the name/ctxt numbers are very internals-dependent and thus # change relatively frequently, and testing for their exact values diff --git a/src/test/run-make/pretty-expanded/Makefile b/src/test/run-make/pretty-expanded/Makefile index dda441ae3d1..7a8dc8d871c 100644 --- a/src/test/run-make/pretty-expanded/Makefile +++ b/src/test/run-make/pretty-expanded/Makefile @@ -1,4 +1,5 @@ -include ../tools.mk all: - $(RUSTC) -o $(TMPDIR)/input.expanded.rs --pretty=expanded input.rs + $(RUSTC) -o $(TMPDIR)/input.expanded.rs -Z unstable-options \ + --pretty=expanded input.rs diff --git a/src/test/run-make/pretty-print-path-suffix/Makefile b/src/test/run-make/pretty-print-path-suffix/Makefile index f58a6527ac6..9f0c3f5120d 100644 --- a/src/test/run-make/pretty-print-path-suffix/Makefile +++ b/src/test/run-make/pretty-print-path-suffix/Makefile @@ -1,9 +1,9 @@ -include ../tools.mk all: - $(RUSTC) -o $(TMPDIR)/foo.out --pretty normal=foo input.rs - $(RUSTC) -o $(TMPDIR)/nest_foo.out --pretty normal=nest::foo input.rs - $(RUSTC) -o $(TMPDIR)/foo_method.out --pretty normal=foo_method input.rs + $(RUSTC) -o $(TMPDIR)/foo.out -Z unstable-options --pretty normal=foo input.rs + $(RUSTC) -o $(TMPDIR)/nest_foo.out -Z unstable-options --pretty normal=nest::foo input.rs + $(RUSTC) -o $(TMPDIR)/foo_method.out -Z unstable-options --pretty normal=foo_method input.rs diff -u $(TMPDIR)/foo.out foo.pp diff -u $(TMPDIR)/nest_foo.out nest_foo.pp diff -u $(TMPDIR)/foo_method.out foo_method.pp diff --git a/src/test/run-make/pretty-print-to-file/Makefile b/src/test/run-make/pretty-print-to-file/Makefile index 1c1242ada8a..8909dee11f0 100644 --- a/src/test/run-make/pretty-print-to-file/Makefile +++ b/src/test/run-make/pretty-print-to-file/Makefile @@ -1,5 +1,5 @@ -include ../tools.mk all: - $(RUSTC) -o $(TMPDIR)/input.out --pretty=normal input.rs + $(RUSTC) -o $(TMPDIR)/input.out --pretty=normal -Z unstable-options input.rs diff -u $(TMPDIR)/input.out input.pp diff --git a/src/test/run-make/tools.mk b/src/test/run-make/tools.mk index 971295405aa..1c791f0690c 100644 --- a/src/test/run-make/tools.mk +++ b/src/test/run-make/tools.mk @@ -5,7 +5,8 @@ HOST_RPATH_ENV = \ TARGET_RPATH_ENV = \ $(LD_LIB_PATH_ENVVAR)="$(TMPDIR):$(TARGET_RPATH_DIR):$($(LD_LIB_PATH_ENVVAR))" -RUSTC := $(HOST_RPATH_ENV) $(RUSTC) --out-dir $(TMPDIR) -L $(TMPDIR) +BARE_RUSTC := $(HOST_RPATH_ENV) $(RUSTC) +RUSTC := $(BARE_RUSTC) --out-dir $(TMPDIR) -L $(TMPDIR) CC := $(CC) -L $(TMPDIR) HTMLDOCCK := $(PYTHON) $(S)/src/etc/htmldocck.py From 953d6dfd7e1b1d5c5b17314b6e3bdec15d8e7a01 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 16 Jan 2015 15:54:58 -0800 Subject: [PATCH 44/96] Make error code registration work again. #19624 --- mk/tests.mk | 1 + src/etc/errorck.py | 70 ++++++++++++++++++++++++++++ src/librustc/diagnostics.rs | 20 ++------ src/librustc/lib.rs | 6 +-- src/librustc_driver/lib.rs | 15 +++++- src/librustc_resolve/diagnostics.rs | 18 +++++++ src/librustc_resolve/lib.rs | 4 ++ src/librustc_typeck/diagnostics.rs | 61 ++---------------------- src/librustc_typeck/lib.rs | 4 ++ src/libsyntax/diagnostics/plugin.rs | 7 +++ src/test/run-make/issue-19371/foo.rs | 2 +- 11 files changed, 128 insertions(+), 80 deletions(-) create mode 100644 src/etc/errorck.py create mode 100644 src/librustc_resolve/diagnostics.rs diff --git a/mk/tests.mk b/mk/tests.mk index 10452d91275..7a7287a2fbf 100644 --- a/mk/tests.mk +++ b/mk/tests.mk @@ -302,6 +302,7 @@ tidy: | grep '^$(S)src/libbacktrace' -v \ | grep '^$(S)src/rust-installer' -v \ | xargs $(CFG_PYTHON) $(S)src/etc/check-binaries.py + $(Q) $(CFG_PYTHON) $(S)src/etc/errorck.py $(S)src/ endif diff --git a/src/etc/errorck.py b/src/etc/errorck.py new file mode 100644 index 00000000000..17659309d3b --- /dev/null +++ b/src/etc/errorck.py @@ -0,0 +1,70 @@ +# 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. + +# Digs error codes out of files named 'diagnostics.rs' across +# the tree, and ensures thare are no duplicates. + +import sys, os, re + +src_dir = sys.argv[1] + +errcode_map = { } + +for (dirpath, dirnames, filenames) in os.walk(src_dir): + + if "src/test" in dirpath or "src/llvm" in dirpath: + # Short circuit for fast + continue + + for filename in filenames: + if filename != "diagnostics.rs": + continue + + path = os.path.join(dirpath, filename) + line_num = 1 + with open(path, 'r') as f: + for line in f: + + p = re.compile("(E\d\d\d\d)") + m = p.search(line) + if not m is None: + errcode = m.group(1) + + new_record = [(errcode, path, line_num, line)] + existing = errcode_map.get(errcode) + if existing is not None: + # This is a dupe + errcode_map[errcode] = existing + new_record + else: + errcode_map[errcode] = new_record + + line_num += 1 + +errors = False +all_errors = [] +for errcode in errcode_map: + entries = errcode_map[errcode] + all_errors += [entries[0][0]] + if len(entries) > 1: + print "error: duplicate error code " + errcode + for entry in entries: + print entry[1] + ": " + str(entry[2]) + print entry[3] + errors = True + +print str(len(errcode_map)) + " error codes" + +all_errors.sort() +all_errors.reverse() + +print "highest error code: " + all_errors[0] + +if errors: + sys.exit(1) diff --git a/src/librustc/diagnostics.rs b/src/librustc/diagnostics.rs index 1ea79bdf606..c3b87fdd8aa 100644 --- a/src/librustc/diagnostics.rs +++ b/src/librustc/diagnostics.rs @@ -31,7 +31,6 @@ E0010, E0011, E0012, - E0013, E0014, E0015, E0016, @@ -49,24 +48,13 @@ E0137, E0138, E0139, - E0140, E0152, - E0153, - E0157, E0158, E0161, E0162, E0165, - E0166, - E0167, - E0168, - E0169, - E0170, - E0171, - E0172, - E0173, - E0174, - E0177, - E0178, - E0179 + E0170 } + +__build_diagnostic_array! { DIAGNOSTICS } + diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index 62869064551..377e5dd39ff 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -54,7 +54,9 @@ pub use rustc_llvm as llvm; -mod diagnostics; +// NB: This module needs to be declared first so diagnostics are +// registered before they are used. +pub mod diagnostics; pub mod back { pub use rustc_back::abi; @@ -132,8 +134,6 @@ pub mod lib { pub use llvm; } -__build_diagnostic_array! { DIAGNOSTICS } - // A private module so that macro-expanded idents like // `::rustc::lint::Lint` will also work in `rustc` itself. // diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 50ff4546c37..f8e889fc711 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -61,7 +61,6 @@ use rustc::lint; use rustc::metadata; use rustc::metadata::creader::CrateOrString::Str; -use rustc::DIAGNOSTICS; use rustc::util::common::time; use std::cmp::Ordering::Equal; @@ -98,7 +97,7 @@ fn run_compiler(args: &[String]) { None => return }; - let descriptions = diagnostics::registry::Registry::new(&DIAGNOSTICS); + let descriptions = diagnostics_registry(); match matches.opt_str("explain") { Some(ref code) => { match descriptions.find_description(&code[]) { @@ -659,8 +658,20 @@ pub fn monitor(f: F) { } } +pub fn diagnostics_registry() -> diagnostics::registry::Registry { + use syntax::diagnostics::registry::Registry; + + let all_errors = Vec::new() + + rustc::diagnostics::DIAGNOSTICS.as_slice() + + rustc_typeck::diagnostics::DIAGNOSTICS.as_slice() + + rustc_resolve::diagnostics::DIAGNOSTICS.as_slice(); + + Registry::new(&*all_errors) +} + pub fn main() { let args = std::os::args(); let result = run(args); std::os::set_exit_status(result); } + diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs new file mode 100644 index 00000000000..eed808bcd77 --- /dev/null +++ b/src/librustc_resolve/diagnostics.rs @@ -0,0 +1,18 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_snake_case)] + +register_diagnostics! { + E0157, + E0153 +} + +__build_diagnostic_array! { DIAGNOSTICS } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 31999faa6df..19b93ab2599 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -97,6 +97,10 @@ use std::rc::{Rc, Weak}; use std::uint; +// NB: This module needs to be declared first so diagnostics are +// registered before they are used. +pub mod diagnostics; + mod check_unused; mod record_exports; mod build_reduced_graph; diff --git a/src/librustc_typeck/diagnostics.rs b/src/librustc_typeck/diagnostics.rs index c9e15b93ad4..68cf9ce0707 100644 --- a/src/librustc_typeck/diagnostics.rs +++ b/src/librustc_typeck/diagnostics.rs @@ -10,38 +10,7 @@ #![allow(non_snake_case)] -register_diagnostic! { - E0001, -r##" - This error suggests that the expression arm corresponding to the noted pattern - will never be reached as for all possible values of the expression being matched, - one of the preceeding patterns will match. - - This means that perhaps some of the preceeding patterns are too general, this - one is too specific or the ordering is incorrect. -"## } - register_diagnostics! { - E0002, - E0003, - E0004, - E0005, - E0006, - E0007, - E0008, - E0009, - E0010, - E0011, - E0012, - E0013, - E0014, - E0015, - E0016, - E0017, - E0018, - E0019, - E0020, - E0022, E0023, E0024, E0025, @@ -61,12 +30,9 @@ E0046, E0049, E0050, - E0051, - E0052, E0053, E0054, E0055, - E0056, E0057, E0059, E0060, @@ -101,16 +67,12 @@ E0092, E0093, E0094, - E0100, E0101, E0102, E0103, E0104, E0106, E0107, - E0108, - E0109, - E0110, E0116, E0117, E0118, @@ -125,38 +87,21 @@ E0130, E0131, E0132, - E0133, - E0134, - E0135, - E0136, - E0137, - E0138, - E0139, - E0140, E0141, - E0152, - E0153, - E0157, - E0158, E0159, - E0161, - E0162, E0163, E0164, - E0165, E0166, E0167, E0168, - E0169, - E0171, E0172, E0173, // manual implementations of unboxed closure traits are experimental E0174, // explicit use of unboxed closure methods are experimental - E0177, E0178, - E0180, - E0181, E0182, E0183, E0184 } + +__build_diagnostic_array! { DIAGNOSTICS } + diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index 47b5cd4b11e..1fb292b86bf 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -111,6 +111,10 @@ use std::cell::RefCell; +// NB: This module needs to be declared first so diagnostics are +// registered before they are used. +pub mod diagnostics; + mod check; mod rscope; mod astconv; diff --git a/src/libsyntax/diagnostics/plugin.rs b/src/libsyntax/diagnostics/plugin.rs index 1469c50061c..0e99829fa1c 100644 --- a/src/libsyntax/diagnostics/plugin.rs +++ b/src/libsyntax/diagnostics/plugin.rs @@ -65,6 +65,13 @@ pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt, } () }); + with_registered_diagnostics(|diagnostics| { + if !diagnostics.contains_key(&code.name) { + ecx.span_err(span, &format!( + "used diagnostic code {} not registered", token::get_ident(code).get() + )[]); + } + }); MacExpr::new(quote_expr!(ecx, ())) } diff --git a/src/test/run-make/issue-19371/foo.rs b/src/test/run-make/issue-19371/foo.rs index fe7df641159..867008cd259 100644 --- a/src/test/run-make/issue-19371/foo.rs +++ b/src/test/run-make/issue-19371/foo.rs @@ -44,7 +44,7 @@ fn basic_sess(sysroot: Path) -> Session { opts.output_types = vec![OutputTypeExe]; opts.maybe_sysroot = Some(sysroot); - let descriptions = Registry::new(&rustc::DIAGNOSTICS); + let descriptions = Registry::new(&rustc::diagnostics::DIAGNOSTICS); let sess = build_session(opts, None, descriptions); sess } From 0c5225c5bf31dcca141c36ce1b5850ff2df79b9c Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 17 Jan 2015 13:36:59 -0800 Subject: [PATCH 45/96] Add error codes to rustc_typeck --- src/librustc_typeck/astconv.rs | 84 +++++++++------------ src/librustc_typeck/check/closure.rs | 5 +- src/librustc_typeck/check/compare_method.rs | 21 +++--- src/librustc_typeck/check/mod.rs | 44 +++++------ src/librustc_typeck/check/vtable.rs | 23 +++--- src/librustc_typeck/check/wf.rs | 21 +++--- src/librustc_typeck/check/writeback.rs | 2 +- src/librustc_typeck/coherence/impls.rs | 7 +- src/librustc_typeck/coherence/mod.rs | 17 ++--- src/librustc_typeck/coherence/orphan.rs | 6 +- src/librustc_typeck/coherence/unsafety.rs | 22 +++--- src/librustc_typeck/collect.rs | 14 ++-- src/librustc_typeck/diagnostics.rs | 62 ++++++++++++++- src/librustc_typeck/lib.rs | 6 +- src/librustc_typeck/variance.rs | 2 +- 15 files changed, 179 insertions(+), 157 deletions(-) diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 42b12c15866..080959cae0c 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -100,8 +100,7 @@ fn projected_ty_from_poly_trait_ref(&self, -> Ty<'tcx> { if ty::binds_late_bound_regions(self.tcx(), &poly_trait_ref) { - self.tcx().sess.span_err( - span, + span_err!(self.tcx().sess, span, E0212, "cannot extract an associated type from a higher-ranked trait bound \ in this context"); self.tcx().types.err @@ -119,8 +118,7 @@ fn projected_ty(&self, _item_name: ast::Name) -> Ty<'tcx> { - self.tcx().sess.span_err( - span, + span_err!(self.tcx().sess, span, E0213, "associated types are not accepted in this context"); self.tcx().types.err @@ -268,8 +266,7 @@ pub fn ast_path_substs_for_ty<'tcx>( convert_angle_bracketed_parameters(this, rscope, data) } ast::ParenthesizedParameters(ref data) => { - tcx.sess.span_err( - path.span, + span_err!(tcx.sess, path.span, E0214, "parenthesized parameters may only be used with a trait"); (Vec::new(), convert_parenthesized_parameters(this, data), Vec::new()) } @@ -610,7 +607,7 @@ fn ast_path_to_trait_ref<'a,'tcx>( if !this.tcx().sess.features.borrow().unboxed_closures && this.tcx().lang_items.fn_trait_kind(trait_def_id).is_some() { - this.tcx().sess.span_err(path.span, + span_err!(this.tcx().sess, path.span, E0215, "angle-bracket notation is not stable when \ used with the `Fn` family of traits, use parentheses"); span_help!(this.tcx().sess, path.span, @@ -626,7 +623,7 @@ fn ast_path_to_trait_ref<'a,'tcx>( if !this.tcx().sess.features.borrow().unboxed_closures && this.tcx().lang_items.fn_trait_kind(trait_def_id).is_none() { - this.tcx().sess.span_err(path.span, + span_err!(this.tcx().sess, path.span, E0216, "parenthetical notation is only stable when \ used with the `Fn` family of traits"); span_help!(this.tcx().sess, path.span, @@ -738,32 +735,29 @@ fn ast_type_binding_to_projection_predicate<'tcx>( } if candidates.len() > 1 { - tcx.sess.span_err( - binding.span, - format!("ambiguous associated type: `{}` defined in multiple supertraits `{}`", + span_err!(tcx.sess, binding.span, E0217, + "ambiguous associated type: `{}` defined in multiple supertraits `{}`", token::get_name(binding.item_name), - candidates.user_string(tcx)).as_slice()); + candidates.user_string(tcx)); return Err(ErrorReported); } let candidate = match candidates.pop() { Some(c) => c, None => { - tcx.sess.span_err( - binding.span, - format!("no associated type `{}` defined in `{}`", + span_err!(tcx.sess, binding.span, E0218, + "no associated type `{}` defined in `{}`", token::get_name(binding.item_name), - trait_ref.user_string(tcx)).as_slice()); + trait_ref.user_string(tcx)); return Err(ErrorReported); } }; if ty::binds_late_bound_regions(tcx, &candidate) { - tcx.sess.span_err( - binding.span, - format!("associated type `{}` defined in higher-ranked supertrait `{}`", + span_err!(tcx.sess, binding.span, E0219, + "associated type `{}` defined in higher-ranked supertrait `{}`", token::get_name(binding.item_name), - candidate.user_string(tcx)).as_slice()); + candidate.user_string(tcx)); return Err(ErrorReported); } @@ -964,18 +958,18 @@ fn associated_path_def_to_ty<'tcx>(this: &AstConv<'tcx>, } if suitable_bounds.len() == 0 { - tcx.sess.span_err(ast_ty.span, - format!("associated type `{}` not found for type parameter `{}`", + span_err!(tcx.sess, ast_ty.span, E0220, + "associated type `{}` not found for type parameter `{}`", token::get_name(assoc_name), - token::get_name(ty_param_name)).as_slice()); + token::get_name(ty_param_name)); return this.tcx().types.err; } if suitable_bounds.len() > 1 { - tcx.sess.span_err(ast_ty.span, - format!("ambiguous associated type `{}` in bounds of `{}`", + span_err!(tcx.sess, ast_ty.span, E0221, + "ambiguous associated type `{}` in bounds of `{}`", token::get_name(assoc_name), - token::get_name(ty_param_name)).as_slice()); + token::get_name(ty_param_name)); for suitable_bound in suitable_bounds.iter() { span_note!(this.tcx().sess, ast_ty.span, @@ -1093,7 +1087,7 @@ pub fn ast_ty_to_ty<'tcx>( ast::TyParen(ref typ) => ast_ty_to_ty(this, rscope, &**typ), ast::TyBareFn(ref bf) => { if bf.decl.variadic && bf.abi != abi::C { - tcx.sess.span_err(ast_ty.span, + span_err!(tcx.sess, ast_ty.span, E0222, "variadic function must have C calling convention"); } let bare_fn = ty_of_bare_fn(this, bf.unsafety, bf.abi, &*bf.decl); @@ -1152,8 +1146,8 @@ pub fn ast_ty_to_ty<'tcx>( def::DefAssociatedTy(trait_type_id) => { let path_str = tcx.map.path_to_string( tcx.map.get_parent(trait_type_id.node)); - tcx.sess.span_err(ast_ty.span, - &format!("ambiguous associated \ + span_err!(tcx.sess, ast_ty.span, E0223, + "ambiguous associated \ type; specify the type \ using the syntax `::{}`", @@ -1163,7 +1157,7 @@ pub fn ast_ty_to_ty<'tcx>( .last() .unwrap() .identifier) - .get())[]); + .get()); this.tcx().types.err } def::DefAssociatedPath(provenance, assoc_ident) => { @@ -1557,8 +1551,7 @@ fn conv_ty_poly_trait_ref<'tcx>( None, &mut projection_bounds)) } else { - this.tcx().sess.span_err( - span, + span_err!(this.tcx().sess, span, E0224, "at least one non-builtin trait is required for an object type"); None }; @@ -1593,10 +1586,9 @@ pub fn conv_existential_bounds_from_partitioned_bounds<'tcx>( if !trait_bounds.is_empty() { let b = &trait_bounds[0]; - this.tcx().sess.span_err( - b.trait_ref.path.span, - &format!("only the builtin traits can be used \ - as closure or object bounds")[]); + span_err!(this.tcx().sess, b.trait_ref.path.span, E0225, + "only the builtin traits can be used \ + as closure or object bounds"); } let region_bound = compute_region_bound(this, @@ -1633,9 +1625,8 @@ fn compute_opt_region_bound<'tcx>(tcx: &ty::ctxt<'tcx>, builtin_bounds.repr(tcx)); if explicit_region_bounds.len() > 1 { - tcx.sess.span_err( - explicit_region_bounds[1].span, - format!("only a single explicit lifetime bound is permitted").as_slice()); + span_err!(tcx.sess, explicit_region_bounds[1].span, E0226, + "only a single explicit lifetime bound is permitted"); } if explicit_region_bounds.len() != 0 { @@ -1666,10 +1657,9 @@ fn compute_opt_region_bound<'tcx>(tcx: &ty::ctxt<'tcx>, // error. let r = derived_region_bounds[0]; if derived_region_bounds.slice_from(1).iter().any(|r1| r != *r1) { - tcx.sess.span_err( - span, - &format!("ambiguous lifetime bound, \ - explicit lifetime bound required")[]); + span_err!(tcx.sess, span, E0227, + "ambiguous lifetime bound, \ + explicit lifetime bound required"); } return Some(r); } @@ -1693,9 +1683,8 @@ fn compute_region_bound<'tcx>( match rscope.default_region_bound(span) { Some(r) => { r } None => { - this.tcx().sess.span_err( - span, - &format!("explicit lifetime bound required")[]); + span_err!(this.tcx().sess, span, E0228, + "explicit lifetime bound required"); ty::ReStatic } } @@ -1779,8 +1768,7 @@ fn prohibit_projections<'tcx>(tcx: &ty::ctxt<'tcx>, bindings: &[ConvertedBinding<'tcx>]) { for binding in bindings.iter().take(1) { - tcx.sess.span_err( - binding.span, + span_err!(tcx.sess, binding.span, E0229, "associated type bindings are not allowed here"); } } diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index bfe43086aab..33cce67c780 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -50,10 +50,9 @@ pub fn check_expr_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, check_unboxed_closure(fcx, expr, kind, decl, body, None); - fcx.ccx.tcx.sess.span_err( - expr.span, + span_err!(fcx.ccx.tcx.sess, expr.span, E0187, "can't infer the \"kind\" of the closure, explicitly annotate it. e.g. \ - `|&:| {}`"); + `|&:| {{}}`"); }, Some((sig, kind)) => { check_unboxed_closure(fcx, expr, kind, decl, body, Some(sig)); diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index 27d4b2055d4..e3e5d67869f 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -59,23 +59,21 @@ pub fn compare_impl_method<'tcx>(tcx: &ty::ctxt<'tcx>, (&ty::StaticExplicitSelfCategory, &ty::StaticExplicitSelfCategory) => {} (&ty::StaticExplicitSelfCategory, _) => { - tcx.sess.span_err( - impl_m_span, - format!("method `{}` has a `{}` declaration in the impl, \ + span_err!(tcx.sess, impl_m_span, E0185, + "method `{}` has a `{}` declaration in the impl, \ but not in the trait", token::get_name(trait_m.name), ppaux::explicit_self_category_to_str( - &impl_m.explicit_self)).as_slice()); + &impl_m.explicit_self)); return; } (_, &ty::StaticExplicitSelfCategory) => { - tcx.sess.span_err( - impl_m_span, - format!("method `{}` has a `{}` declaration in the trait, \ + span_err!(tcx.sess, impl_m_span, E0186, + "method `{}` has a `{}` declaration in the trait, \ but not in the impl", token::get_name(trait_m.name), ppaux::explicit_self_category_to_str( - &trait_m.explicit_self)).as_slice()); + &trait_m.explicit_self)); return; } _ => { @@ -400,11 +398,10 @@ fn check_region_bounds_on_impl_method<'tcx>(tcx: &ty::ctxt<'tcx>, // are zero. Since I don't quite know how to phrase things at // the moment, give a kind of vague error message. if trait_params.len() != impl_params.len() { - tcx.sess.span_err( - span, - &format!("lifetime parameters or bounds on method `{}` do \ + span_err!(tcx.sess, span, E0195, + "lifetime parameters or bounds on method `{}` do \ not match the trait declaration", - token::get_name(impl_m.name))[]); + token::get_name(impl_m.name)); return false; } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index f610456f73c..58b655d7585 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -801,16 +801,15 @@ fn check_trait_on_unimplemented<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, }) { Some(_) => (), None => { - ccx.tcx.sess.span_err(attr.span, - format!("there is no type parameter \ + span_err!(ccx.tcx.sess, attr.span, E0230, + "there is no type parameter \ {} on trait {}", - s, item.ident.as_str()) - .as_slice()); + s, item.ident.as_str()); } }, // `{:1}` and `{}` are not to be used Position::ArgumentIs(_) | Position::ArgumentNext => { - ccx.tcx.sess.span_err(attr.span, + span_err!(ccx.tcx.sess, attr.span, E0231, "only named substitution \ parameters are allowed"); } @@ -818,7 +817,7 @@ fn check_trait_on_unimplemented<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, } } } else { - ccx.tcx.sess.span_err(attr.span, + span_err!(ccx.tcx.sess, attr.span, E0232, "this attribute must have a value, \ eg `#[rustc_on_unimplemented = \"foo\"]`") } @@ -2099,8 +2098,8 @@ fn lookup_method_for_for_loop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, let trait_did = match fcx.tcx().lang_items.require(IteratorItem) { Ok(trait_did) => trait_did, Err(ref err_string) => { - fcx.tcx().sess.span_err(iterator_expr.span, - &err_string[]); + span_err!(fcx.tcx().sess, iterator_expr.span, E0233, + "{}", &err_string[]); return fcx.tcx().types.err } }; @@ -2123,11 +2122,10 @@ fn lookup_method_for_for_loop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, if !ty::type_is_error(true_expr_type) { let ty_string = fcx.infcx().ty_to_string(true_expr_type); - fcx.tcx().sess.span_err(iterator_expr.span, - &format!("`for` loop expression has type `{}` which does \ + span_err!(fcx.tcx().sess, iterator_expr.span, E0234, + "`for` loop expression has type `{}` which does \ not implement the `Iterator` trait; \ - maybe try .iter()", - ty_string)[]); + maybe try .iter()", ty_string); } fcx.tcx().types.err } @@ -2162,11 +2160,10 @@ fn lookup_method_for_for_loop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, fcx.tcx().types.err } _ => { - fcx.tcx().sess.span_err(iterator_expr.span, - &format!("`next` method of the `Iterator` \ + span_err!(fcx.tcx().sess, iterator_expr.span, E0239, + "`next` method of the `Iterator` \ trait has an unexpected type `{}`", - fcx.infcx().ty_to_string(return_type)) - []); + fcx.infcx().ty_to_string(return_type)); fcx.tcx().types.err } } @@ -3880,10 +3877,8 @@ fn check_struct_fields_on_error(fcx: &FnCtxt, Err(type_error) => { let type_error_description = ty::type_err_to_str(tcx, &type_error); - fcx.tcx() - .sess - .span_err(path.span, - &format!("structure constructor specifies a \ + span_err!(fcx.tcx().sess, path.span, E0235, + "structure constructor specifies a \ structure of type `{}`, but this \ structure has type `{}`: {}", fcx.infcx() @@ -3891,7 +3886,7 @@ fn check_struct_fields_on_error(fcx: &FnCtxt, fcx.infcx() .ty_to_string( actual_structure_type), - type_error_description)[]); + type_error_description); ty::note_and_explain_type_err(tcx, &type_error); } } @@ -4012,7 +4007,7 @@ fn check_struct_fields_on_error(fcx: &FnCtxt, ty::mk_struct(tcx, did, tcx.mk_substs(substs)) } else { - tcx.sess.span_err(expr.span, "No lang item for range syntax"); + span_err!(tcx.sess, expr.span, E0236, "no lang item for range syntax"); fcx.tcx().types.err } } @@ -4022,7 +4017,7 @@ fn check_struct_fields_on_error(fcx: &FnCtxt, let substs = Substs::new_type(vec![], vec![]); ty::mk_struct(tcx, did, tcx.mk_substs(substs)) } else { - tcx.sess.span_err(expr.span, "No lang item for range syntax"); + span_err!(tcx.sess, expr.span, E0237, "no lang item for range syntax"); fcx.tcx().types.err } } @@ -4872,8 +4867,7 @@ fn push_explicit_parameters_from_segment_to_substs<'a, 'tcx>( } ast::ParenthesizedParameters(ref data) => { - fcx.tcx().sess.span_err( - span, + span_err!(fcx.tcx().sess, span, E0238, "parenthesized parameters may only be used with a trait"); push_explicit_parenthesized_parameters_from_segment_to_substs( fcx, space, span, type_defs, data, substs); diff --git a/src/librustc_typeck/check/vtable.rs b/src/librustc_typeck/check/vtable.rs index 3940092eb72..41b63830279 100644 --- a/src/librustc_typeck/check/vtable.rs +++ b/src/librustc_typeck/check/vtable.rs @@ -51,7 +51,7 @@ pub fn check_object_cast<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, { let object_trait = object_trait(&object_trait_ty); if !mutability_allowed(referent_mutbl, target_mutbl) { - fcx.tcx().sess.span_err(source_expr.span, + span_err!(fcx.tcx().sess, source_expr.span, E0188, "types differ in mutability"); } else { // Ensure that if &'a T is cast to &'b Trait, then T : Trait @@ -70,19 +70,17 @@ pub fn check_object_cast<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, } (_, &ty::ty_uniq(..)) => { - fcx.ccx.tcx.sess.span_err( - source_expr.span, - &format!("can only cast an boxed pointer \ + span_err!(fcx.ccx.tcx.sess, source_expr.span, E0189, + "can only cast a boxed pointer \ to a boxed object, not a {}", - ty::ty_sort_string(fcx.tcx(), source_ty))[]); + ty::ty_sort_string(fcx.tcx(), source_ty)); } (_, &ty::ty_rptr(..)) => { - fcx.ccx.tcx.sess.span_err( - source_expr.span, - &format!("can only cast a &-pointer \ + span_err!(fcx.ccx.tcx.sess, source_expr.span, E0190, + "can only cast a &-pointer \ to an &-object, not a {}", - ty::ty_sort_string(fcx.tcx(), source_ty))[]); + ty::ty_sort_string(fcx.tcx(), source_ty)); } _ => { @@ -272,11 +270,10 @@ fn check_object_type_binds_all_associated_types<'tcx>(tcx: &ty::ctxt<'tcx>, } for (trait_def_id, name) in associated_types.into_iter() { - tcx.sess.span_err( - span, - format!("the value of the associated type `{}` (from the trait `{}`) must be specified", + span_err!(tcx.sess, span, E0191, + "the value of the associated type `{}` (from the trait `{}`) must be specified", name.user_string(tcx), - ty::item_path_str(tcx, trait_def_id)).as_slice()); + ty::item_path_str(tcx, trait_def_id)); } } diff --git a/src/librustc_typeck/check/wf.rs b/src/librustc_typeck/check/wf.rs index e6390212c60..60284433ffe 100644 --- a/src/librustc_typeck/check/wf.rs +++ b/src/librustc_typeck/check/wf.rs @@ -81,10 +81,9 @@ fn check_item_well_formed(&mut self, item: &ast::Item) { match ccx.tcx.lang_items.to_builtin_kind(trait_ref.def_id) { Some(ty::BoundSend) | Some(ty::BoundSync) => {} Some(_) | None => { - ccx.tcx.sess.span_err( - item.span, - format!("negative impls are currently \ - allowed just for `Send` and `Sync`").as_slice()) + span_err!(ccx.tcx.sess, item.span, E0192, + "negative impls are currently \ + allowed just for `Send` and `Sync`") } } } @@ -302,12 +301,11 @@ fn reject_non_type_param_bounds<'tcx>(tcx: &ty::ctxt<'tcx>, fn report_bound_error<'t>(tcx: &ty::ctxt<'t>, span: Span, bounded_ty: ty::Ty<'t>) { - tcx.sess.span_err( - span, - format!("cannot bound type `{}`, where clause \ + span_err!(tcx.sess, span, E0193, + "cannot bound type `{}`, where clause \ bounds may only be attached to types involving \ type parameters", - bounded_ty.repr(tcx)).as_slice()) + bounded_ty.repr(tcx)) } fn is_ty_param(ty: ty::Ty) -> bool { @@ -326,10 +324,9 @@ fn reject_shadowing_type_parameters<'tcx>(tcx: &ty::ctxt<'tcx>, for method_param in generics.types.get_slice(subst::FnSpace).iter() { if impl_params.contains(&method_param.name) { - tcx.sess.span_err( - span, - &*format!("type parameter `{}` shadows another type parameter of the same name", - token::get_name(method_param.name))); + span_err!(tcx.sess, span, E0194, + "type parameter `{}` shadows another type parameter of the same name", + token::get_name(method_param.name)); } } } diff --git a/src/librustc_typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs index 82da22eab98..52e81585875 100644 --- a/src/librustc_typeck/check/writeback.rs +++ b/src/librustc_typeck/check/writeback.rs @@ -416,7 +416,7 @@ fn report_error(&self, e: infer::fixup_err) { ResolvingUnboxedClosure(_) => { let span = self.reason.span(self.tcx); - self.tcx.sess.span_err(span, + span_err!(self.tcx.sess, span, E0196, "cannot determine a type for this \ unboxed closure") } diff --git a/src/librustc_typeck/coherence/impls.rs b/src/librustc_typeck/coherence/impls.rs index 2719a09f4f5..e535b86a7bf 100644 --- a/src/librustc_typeck/coherence/impls.rs +++ b/src/librustc_typeck/coherence/impls.rs @@ -34,10 +34,9 @@ fn visit_item(&mut self, item: &'v ast::Item) { match trait_ref.self_ty().sty { ty::ty_struct(..) | ty::ty_enum(..) => {} _ => { - self.tcx.sess.span_err( - item.span, - &format!("builtin traits can only be \ - implemented on structs or enums")[]); + span_err!(self.tcx.sess, item.span, E0209, + "builtin traits can only be \ + implemented on structs or enums"); } } } diff --git a/src/librustc_typeck/coherence/mod.rs b/src/librustc_typeck/coherence/mod.rs index 350cee99f6a..7d59c3f9d3f 100644 --- a/src/librustc_typeck/coherence/mod.rs +++ b/src/librustc_typeck/coherence/mod.rs @@ -490,24 +490,21 @@ fn check_implementations_of_copy(&self) { match ty::can_type_implement_copy(¶m_env, span, self_type) { Ok(()) => {} Err(ty::FieldDoesNotImplementCopy(name)) => { - tcx.sess - .span_err(span, - &format!("the trait `Copy` may not be \ + span_err!(tcx.sess, span, E0204, + "the trait `Copy` may not be \ implemented for this type; field \ `{}` does not implement `Copy`", - token::get_name(name))[]) + token::get_name(name)) } Err(ty::VariantDoesNotImplementCopy(name)) => { - tcx.sess - .span_err(span, - &format!("the trait `Copy` may not be \ + span_err!(tcx.sess, span, E0205, + "the trait `Copy` may not be \ implemented for this type; variant \ `{}` does not implement `Copy`", - token::get_name(name))[]) + token::get_name(name)) } Err(ty::TypeIsStructural) => { - tcx.sess - .span_err(span, + span_err!(tcx.sess, span, E0206, "the trait `Copy` may not be implemented \ for this type; type is not a structure or \ enumeration") diff --git a/src/librustc_typeck/coherence/orphan.rs b/src/librustc_typeck/coherence/orphan.rs index 77d71e740d6..60b1fa5f4cf 100644 --- a/src/librustc_typeck/coherence/orphan.rs +++ b/src/librustc_typeck/coherence/orphan.rs @@ -89,13 +89,11 @@ fn visit_item(&mut self, item: &'v ast::Item) { } Err(traits::OrphanCheckErr::UncoveredTy(param_ty)) => { if !ty::has_attr(self.tcx, trait_def_id, "old_orphan_check") { - self.tcx.sess.span_err( - item.span, - format!( + span_err!(self.tcx.sess, item.span, E0210, "type parameter `{}` is not constrained by any local type; \ only traits defined in the current crate can be implemented \ for a type parameter", - param_ty.user_string(self.tcx)).as_slice()); + param_ty.user_string(self.tcx)); self.tcx.sess.span_note( item.span, format!("for a limited time, you can add \ diff --git a/src/librustc_typeck/coherence/unsafety.rs b/src/librustc_typeck/coherence/unsafety.rs index e30d0a29938..867dea95885 100644 --- a/src/librustc_typeck/coherence/unsafety.rs +++ b/src/librustc_typeck/coherence/unsafety.rs @@ -37,8 +37,7 @@ fn visit_item(&mut self, item: &'v ast::Item) { match unsafety { ast::Unsafety::Normal => { /* OK */ } ast::Unsafety::Unsafe => { - self.tcx.sess.span_err( - item.span, + span_err!(self.tcx.sess, item.span, E0197, "inherent impls cannot be declared as unsafe"); } } @@ -49,24 +48,21 @@ fn visit_item(&mut self, item: &'v ast::Item) { match (trait_def.unsafety, unsafety, polarity) { (ast::Unsafety::Unsafe, ast::Unsafety::Unsafe, ast::ImplPolarity::Negative) => { - self.tcx.sess.span_err( - item.span, - format!("negative implementations are not unsafe").as_slice()); + span_err!(self.tcx.sess, item.span, E0198, + "negative implementations are not unsafe"); } (ast::Unsafety::Normal, ast::Unsafety::Unsafe, _) => { - self.tcx.sess.span_err( - item.span, - format!("implementing the trait `{}` is not unsafe", - trait_ref.user_string(self.tcx)).as_slice()); + span_err!(self.tcx.sess, item.span, E0199, + "implementing the trait `{}` is not unsafe", + trait_ref.user_string(self.tcx)); } (ast::Unsafety::Unsafe, ast::Unsafety::Normal, ast::ImplPolarity::Positive) => { - self.tcx.sess.span_err( - item.span, - format!("the trait `{}` requires an `unsafe impl` declaration", - trait_ref.user_string(self.tcx)).as_slice()); + span_err!(self.tcx.sess, item.span, E0200, + "the trait `{}` requires an `unsafe impl` declaration", + trait_ref.user_string(self.tcx)); } (ast::Unsafety::Unsafe, diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 80c0a72db83..664e5eaa45b 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -452,7 +452,7 @@ fn convert_methods<'a,'tcx,'i,I>(ccx: &CollectCtxt<'a, 'tcx>, let mut seen_methods = FnvHashSet(); for m in ms { if !seen_methods.insert(m.pe_ident().repr(tcx)) { - tcx.sess.span_err(m.span, "duplicate method in trait impl"); + span_err!(tcx.sess, m.span, E0201, "duplicate method in trait impl"); } let m_def_id = local_def(m.id); @@ -608,7 +608,7 @@ fn convert(ccx: &CollectCtxt, it: &ast::Item) { } ast::TypeImplItem(ref typedef) => { if opt_trait_ref.is_none() { - tcx.sess.span_err(typedef.span, + span_err!(tcx.sess, typedef.span, E0202, "associated items are not allowed in inherent impls"); } @@ -1160,7 +1160,8 @@ fn add_unsized_bound<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>, assert!(ptr.bound_lifetimes.is_empty()); unbound = Some(ptr.trait_ref.clone()); } else { - ccx.tcx.sess.span_err(span, "type parameter has more than one relaxed default \ + span_err!(ccx.tcx.sess, span, E0203, + "type parameter has more than one relaxed default \ bound, only one is supported"); } } @@ -1690,11 +1691,10 @@ fn enforce_impl_ty_params_are_constrained<'tcx>(tcx: &ty::ctxt<'tcx>, impl trait, self type, or predicates", param_ty.user_string(tcx)).as_slice()); } else { - tcx.sess.span_err( - ty_param.span, - format!("the type parameter `{}` is not constrained by the \ + span_err!(tcx.sess, ty_param.span, E0207, + "the type parameter `{}` is not constrained by the \ impl trait, self type, or predicates", - param_ty.user_string(tcx)).as_slice()); + param_ty.user_string(tcx)); tcx.sess.span_help( ty_param.span, format!("you can temporarily opt out of this rule by placing \ diff --git a/src/librustc_typeck/diagnostics.rs b/src/librustc_typeck/diagnostics.rs index 68cf9ce0707..ce30cb91c91 100644 --- a/src/librustc_typeck/diagnostics.rs +++ b/src/librustc_typeck/diagnostics.rs @@ -100,7 +100,67 @@ E0178, E0182, E0183, - E0184 + E0184, + E0185, + E0186, + E0187, // can't infer the kind of the closure + E0188, // types differ in mutability + E0189, // can only cast a boxed pointer to a boxed object + E0190, // can only cast a &-pointer to an &-object + E0191, // value of the associated type must be specified + E0192, // negative imples are allowed just fo `Send` and `Sync` + E0193, // cannot bound type where clause bounds may only be attached to types + // involving type parameters + E0194, + E0195, // lifetime parameters or bounds on method do not match the trait declaration + E0196, // cannot determine a type for this unboxed closure + E0197, // inherent impls cannot be declared as unsafe + E0198, // negative implementations are not unsafe + E0199, // implementing trait is not unsafe + E0200, // trait requires an `unsafe impl` declaration + E0201, // duplicate method in trait impl + E0202, // associated items are not allowed in inherint impls + E0203, // type parameter has more than one relaxed default bound, + // and only one is supported + E0204, // trait `Copy` may not be implemented for this type; field + // does not implement `Copy` + E0205, // trait `Copy` may not be implemented for this type; variant + // does not implement `copy` + E0206, // trait `Copy` may not be implemented for this type; type is + // not a structure or enumeration + E0207, // type parameter is not constrained by the impl trait, self type, or predicate + E0208, + E0209, // builtin traits can only be implemented on structs or enums + E0210, // type parameter is not constrained by any local type + E0211, + E0212, // cannot extract an associated type from a higher-ranked trait bound + E0213, // associated types are not accepted in this context + E0214, // parenthesized parameters may only be used with a trait + E0215, // angle-bracket notation is not stable with `Fn` + E0216, // parenthetical notation is only stable with `Fn` + E0217, // ambiguous associated type, defined in multiple supertraits + E0218, // no associated type defined + E0219, // associated type defined in higher-ranked supertrait + E0220, // associated type not found for type parameter + E0221, // ambiguous associated type in bounds + E0222, // variadic function must have C calling convention + E0223, // ambiguous associated type + E0224, // at least one non-builtin train is required for an object type + E0225, // only the builtin traits can be used as closure or object bounds + E0226, // only a single explicit lifetime bound is permitted + E0227, // ambiguous lifetime bound, explicit lifetime bound required + E0228, // explicit lifetime bound required + E0229, // associated type bindings are not allowed here + E0230, // there is no type parameter on trait + E0231, // only named substitution parameters are allowed + E0232, // this attribute must have a value + E0233, + E0234, // `for` loop expression has type which does not implement the `Iterator` trait + E0235, // structure constructor specifies a structure of type but + E0236, // no lang item for range syntax + E0237, // no lang item for range syntax + E0238, // parenthesized parameters may only be used with a trait + E0239 // `next` method of `Iterator` trait has unexpected type } __build_diagnostic_array! { DIAGNOSTICS } diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index 1fb292b86bf..aa99549bcd6 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -206,11 +206,11 @@ fn require_same_types<'a, 'tcx, M>(tcx: &ty::ctxt<'tcx>, match result { Ok(_) => true, Err(ref terr) => { - tcx.sess.span_err(span, - &format!("{}: {}", + span_err!(tcx.sess, span, E0211, + "{}: {}", msg(), ty::type_err_to_str(tcx, - terr))[]); + terr)); ty::note_and_explain_type_err(tcx, terr); false } diff --git a/src/librustc_typeck/variance.rs b/src/librustc_typeck/variance.rs index 86447e76a89..3df3e1bddc5 100644 --- a/src/librustc_typeck/variance.rs +++ b/src/librustc_typeck/variance.rs @@ -1055,7 +1055,7 @@ fn write(&self) { // attribute and report an error with various results if found. if ty::has_attr(tcx, item_def_id, "rustc_variance") { let found = item_variances.repr(tcx); - tcx.sess.span_err(tcx.map.span(item_id), &found[]); + span_err!(tcx.sess, tcx.map.span(item_id), E0208, "{}", &found[]); } let newly_added = tcx.item_variance_map.borrow_mut() From f68029ec94415298e56ab20f73bcf2a1224ace4d Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 18 Jan 2015 13:39:18 -0800 Subject: [PATCH 46/96] Make fatal errors work with codes, add to typeck --- src/librustc/session/mod.rs | 3 ++ src/librustc_typeck/astconv.rs | 44 ++++++++++++++--------------- src/librustc_typeck/check/mod.rs | 2 +- src/librustc_typeck/diagnostics.rs | 13 ++++++++- src/librustc_typeck/lib.rs | 2 +- src/libsyntax/diagnostic.rs | 4 +++ src/libsyntax/diagnostics/macros.rs | 8 ++++++ 7 files changed, 50 insertions(+), 26 deletions(-) diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index 5424b1c8cae..0392fbfdeae 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -69,6 +69,9 @@ impl Session { pub fn span_fatal(&self, sp: Span, msg: &str) -> ! { self.diagnostic().span_fatal(sp, msg) } + pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! { + self.diagnostic().span_fatal_with_code(sp, msg, code) + } pub fn fatal(&self, msg: &str) -> ! { self.diagnostic().handler().fatal(msg) } diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 080959cae0c..cfcc65bd15a 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -339,22 +339,22 @@ fn create_substs_for_ast_path<'tcx>( } else { "expected" }; - this.tcx().sess.span_fatal(span, - &format!("wrong number of type arguments: {} {}, found {}", + span_fatal!(this.tcx().sess, span, E0243, + "wrong number of type arguments: {} {}, found {}", expected, required_ty_param_count, - supplied_ty_param_count)[]); + supplied_ty_param_count); } else if supplied_ty_param_count > formal_ty_param_count { let expected = if required_ty_param_count < formal_ty_param_count { "expected at most" } else { "expected" }; - this.tcx().sess.span_fatal(span, - &format!("wrong number of type arguments: {} {}, found {}", + span_fatal!(this.tcx().sess, span, E0244, + "wrong number of type arguments: {} {}, found {}", expected, formal_ty_param_count, - supplied_ty_param_count)[]); + supplied_ty_param_count); } let mut substs = Substs::new_type(types, regions); @@ -557,10 +557,9 @@ pub fn instantiate_trait_ref<'tcx>( trait_ref } _ => { - this.tcx().sess.span_fatal( - ast_trait_ref.path.span, - &format!("`{}` is not a trait", - ast_trait_ref.path.user_string(this.tcx()))[]); + span_fatal!(this.tcx().sess, ast_trait_ref.path.span, E0245, + "`{}` is not a trait", + ast_trait_ref.path.user_string(this.tcx())); } } } @@ -1036,7 +1035,7 @@ pub fn ast_ty_to_ty<'tcx>( match ast_ty_to_ty_cache.get(&ast_ty.id) { Some(&ty::atttce_resolved(ty)) => return ty, Some(&ty::atttce_unresolved) => { - tcx.sess.span_fatal(ast_ty.span, + span_fatal!(tcx.sess, ast_ty.span, E0246, "illegal recursive type; insert an enum \ or struct in the cycle, if this is \ desired"); @@ -1136,9 +1135,9 @@ pub fn ast_ty_to_ty<'tcx>( ty::mk_self_type(tcx) } def::DefMod(id) => { - tcx.sess.span_fatal(ast_ty.span, - &format!("found module name used as a type: {}", - tcx.map.node_to_string(id.node))[]); + span_fatal!(tcx.sess, ast_ty.span, E0247, + "found module name used as a type: {}", + tcx.map.node_to_string(id.node)); } def::DefPrimTy(_) => { panic!("DefPrimTy arm missed in previous ast_ty_to_prim_ty call"); @@ -1164,10 +1163,10 @@ pub fn ast_ty_to_ty<'tcx>( associated_path_def_to_ty(this, ast_ty, provenance, assoc_ident.name) } _ => { - tcx.sess.span_fatal(ast_ty.span, - &format!("found value name used \ + span_fatal!(tcx.sess, ast_ty.span, E0248, + "found value name used \ as a type: {:?}", - a_def)[]); + a_def); } } } @@ -1185,17 +1184,16 @@ pub fn ast_ty_to_ty<'tcx>( ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty), Some(i as uint)), _ => { - tcx.sess.span_fatal( - ast_ty.span, "expected constant expr for array length"); + span_fatal!(tcx.sess, ast_ty.span, E0249, + "expected constant expr for array length"); } } } Err(ref r) => { - tcx.sess.span_fatal( - ast_ty.span, - &format!("expected constant expr for array \ + span_fatal!(tcx.sess, ast_ty.span, E0250, + "expected constant expr for array \ length: {}", - *r)[]); + *r); } } } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 58b655d7585..db4962b0d22 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -5224,7 +5224,7 @@ fn param<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, n: u32) -> Ty<'tcx> { "get_tydesc" => { let tydesc_ty = match ty::get_tydesc_ty(ccx.tcx) { Ok(t) => t, - Err(s) => { tcx.sess.span_fatal(it.span, &s[]); } + Err(s) => { span_fatal!(tcx.sess, it.span, E0240, "{}", &s[]); } }; let td_ptr = ty::mk_ptr(ccx.tcx, ty::mt { ty: tydesc_ty, diff --git a/src/librustc_typeck/diagnostics.rs b/src/librustc_typeck/diagnostics.rs index ce30cb91c91..3627fa41160 100644 --- a/src/librustc_typeck/diagnostics.rs +++ b/src/librustc_typeck/diagnostics.rs @@ -160,7 +160,18 @@ E0236, // no lang item for range syntax E0237, // no lang item for range syntax E0238, // parenthesized parameters may only be used with a trait - E0239 // `next` method of `Iterator` trait has unexpected type + E0239, // `next` method of `Iterator` trait has unexpected type + E0240, + E0241, + E0242, // internal error looking up a definition + E0243, // wrong number of type arguments + E0244, // wrong number of type arguments + E0245, // not a trait + E0246, // illegal recursive type + E0247, // found module name used as a type + E0248, // found value name used as a type + E0249, // expected constant expr for array length + E0250 // expected constant expr for array length } __build_diagnostic_array! { DIAGNOSTICS } diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index aa99549bcd6..78007f3552e 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -162,7 +162,7 @@ fn lookup_def_tcx(tcx:&ty::ctxt, sp: Span, id: ast::NodeId) -> def::Def { match tcx.def_map.borrow().get(&id) { Some(x) => x.clone(), _ => { - tcx.sess.span_fatal(sp, "internal error looking up a definition") + span_fatal!(tcx.sess, sp, E0242, "internal error looking up a definition") } } } diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 7213b0fa955..b26ec64c24b 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -92,6 +92,10 @@ pub fn span_fatal(&self, sp: Span, msg: &str) -> ! { self.handler.emit(Some((&self.cm, sp)), msg, Fatal); panic!(FatalError); } + pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! { + self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Fatal); + panic!(FatalError); + } pub fn span_err(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Error); self.handler.bump_err_count(); diff --git a/src/libsyntax/diagnostics/macros.rs b/src/libsyntax/diagnostics/macros.rs index 34a193dffd3..5bd683c86ae 100644 --- a/src/libsyntax/diagnostics/macros.rs +++ b/src/libsyntax/diagnostics/macros.rs @@ -14,6 +14,14 @@ macro_rules! register_diagnostic { ($code:tt) => (__register_diagnostic! { $code }) } +#[macro_export] +macro_rules! span_fatal { + ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ + __diagnostic_used!($code); + $session.span_fatal_with_code($span, format!($($message)*).as_slice(), stringify!($code)) + }) +} + #[macro_export] macro_rules! span_err { ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ From cf629e7cfa54e4bd641dbbafa2297159a7c52749 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 18 Jan 2015 13:46:57 -0800 Subject: [PATCH 47/96] Add error codes to resolve --- src/librustc_resolve/diagnostics.rs | 12 +++++++++++- src/librustc_resolve/lib.rs | 30 ++++++++++++++--------------- 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index eed808bcd77..2a4c31d62ab 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -12,7 +12,17 @@ register_diagnostics! { E0157, - E0153 + E0153, + E0251, // a named type or value has already been imported in this module + E0252, // a named type or value has already been imported in this module + E0253, // not directly importable + E0254, // import conflicts with imported crate in this module + E0255, // import conflicts with value in this module + E0256, // import conflicts with type in this module + E0257, // inherent implementations are only allowen on types defined in the current module + E0258, // import conflicts with existing submodule + E0259, // an extern crate has already been imported into this module + E0260 // name conflicts with an external crate that has been imported into this module } __build_diagnostic_array! { DIAGNOSTICS } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 19b93ab2599..6b45c2443d3 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -1722,7 +1722,7 @@ fn merge_import_resolution(&mut self, in this module", namespace_name, token::get_name(name).get()); - self.session.span_err(import_directive.span, msg.as_slice()); + span_err!(self.session, import_directive.span, E0251, "{}", msg.as_slice()); } else { let target = Target::new(containing_module.clone(), name_bindings.clone(), @@ -1769,7 +1769,7 @@ fn check_for_conflicting_import(&mut self, ValueNS => "value", }, token::get_name(name).get()); - self.session.span_err(import_span, &msg[]); + span_err!(self.session, import_span, E0252, "{}", &msg[]); } Some(_) | None => {} } @@ -1784,7 +1784,7 @@ fn check_that_import_is_importable(&mut self, if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) { let msg = format!("`{}` is not directly importable", token::get_name(name)); - self.session.span_err(import_span, &msg[]); + span_err!(self.session, import_span, E0253, "{}", &msg[]); } } @@ -1809,7 +1809,7 @@ fn check_for_conflicts_between_imports_and_items(&mut self, crate in this module \ (maybe you meant `use {0}::*`?)", token::get_name(name).get()); - self.session.span_err(import_span, &msg[]); + span_err!(self.session, import_span, E0254, "{}", &msg[]); } Some(_) | None => {} } @@ -1831,7 +1831,7 @@ fn check_for_conflicts_between_imports_and_items(&mut self, let msg = format!("import `{}` conflicts with value \ in this module", token::get_name(name).get()); - self.session.span_err(import_span, &msg[]); + span_err!(self.session, import_span, E0255, "{}", &msg[]); if let Some(span) = value.value_span { self.session.span_note(span, "conflicting value here"); @@ -1849,7 +1849,7 @@ fn check_for_conflicts_between_imports_and_items(&mut self, let msg = format!("import `{}` conflicts with type in \ this module", token::get_name(name).get()); - self.session.span_err(import_span, &msg[]); + span_err!(self.session, import_span, E0256, "{}", &msg[]); if let Some(span) = ty.type_span { self.session.span_note(span, "note conflicting type here") @@ -1862,7 +1862,7 @@ fn check_for_conflicts_between_imports_and_items(&mut self, let msg = format!("inherent implementations \ are only allowed on types \ defined in the current module"); - self.session.span_err(span, &msg[]); + span_err!(self.session, span, E0257, "{}", &msg[]); self.session.span_note(import_span, "import from other module here") } @@ -1871,7 +1871,7 @@ fn check_for_conflicts_between_imports_and_items(&mut self, let msg = format!("import `{}` conflicts with existing \ submodule", token::get_name(name).get()); - self.session.span_err(import_span, &msg[]); + span_err!(self.session, import_span, E0258, "{}", &msg[]); if let Some(span) = ty.type_span { self.session.span_note(span, "note conflicting module here") @@ -1897,11 +1897,10 @@ fn check_for_conflicts_between_external_crates(&self, } if module.external_module_children.borrow().contains_key(&name) { - self.session - .span_err(span, - &format!("an external crate named `{}` has already \ + span_err!(self.session, span, E0259, + "an external crate named `{}` has already \ been imported into this module", - token::get_name(name).get())[]); + token::get_name(name).get()); } } @@ -1915,12 +1914,11 @@ fn check_for_conflicts_between_external_crates_and_items(&self, } if module.external_module_children.borrow().contains_key(&name) { - self.session - .span_err(span, - &format!("the name `{}` conflicts with an external \ + span_err!(self.session, span, E0260, + "the name `{}` conflicts with an external \ crate that has been imported into this \ module", - token::get_name(name).get())[]); + token::get_name(name).get()); } } From 9f59f7e0525ad44a11fb0614ef1626274ddaa918 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 18 Jan 2015 16:58:25 -0800 Subject: [PATCH 48/96] Add error codes to rustc --- src/librustc/diagnostics.rs | 47 +++++++++- src/librustc/middle/check_loop.rs | 8 +- src/librustc/middle/check_match.rs | 27 +++--- src/librustc/middle/check_static_recursion.rs | 8 +- src/librustc/middle/infer/error_reporting.rs | 39 ++++----- src/librustc/middle/liveness.rs | 5 +- src/librustc/middle/recursion_limit.rs | 2 +- src/librustc/middle/resolve_lifetime.rs | 23 ++--- src/librustc/middle/traits/error_reporting.rs | 87 +++++++------------ src/librustc/middle/traits/mod.rs | 9 +- src/librustc/middle/ty.rs | 18 ++-- src/librustc/middle/weak_lang_items.rs | 6 +- 12 files changed, 137 insertions(+), 142 deletions(-) diff --git a/src/librustc/diagnostics.rs b/src/librustc/diagnostics.rs index c3b87fdd8aa..1dbd6eb4e8d 100644 --- a/src/librustc/diagnostics.rs +++ b/src/librustc/diagnostics.rs @@ -53,7 +53,52 @@ E0161, E0162, E0165, - E0170 + E0170, + E0261, // use of undeclared lifetime name + E0262, // illegal lifetime parameter name + E0263, // lifetime name declared twice in same scope + E0264, // unknown external lang item + E0265, // recursive constant + E0266, // expected item + E0267, // thing inside of a closure + E0268, // thing outside of a loop + E0269, // not all control paths return a value + E0270, // computation may converge in a function marked as diverging + E0271, // type mismatch resolving + E0272, // rustc_on_unimplemented attribute refers to non-existent type parameter + E0273, // rustc_on_unimplemented must have named format arguments + E0274, // rustc_on_unimplemented must have a value + E0275, // overflow evaluating requirement + E0276, // requirement appears on impl method but not on corresponding trait method + E0277, // trait is not implemented for type + E0278, // requirement is not satisfied + E0279, // requirement is not satisfied + E0280, // requirement is not satisfied + E0281, // type implements trait but other trait is required + E0282, // unable to infer enough type information about + E0283, // cannot resolve type + E0284, // cannot resolve type + E0285, // overflow evaluation builtin bounds + E0296, // malformed recursion limit attribute + E0297, // refutable pattern in for loop binding + E0298, // mismatched types between arms + E0299, // mismatched types between arms + E0300, // unexpanded macro + E0301, // cannot mutable borrow in a pattern guard + E0302, // cannot assign in a pattern guard + E0303, // pattern bindings are not allowed after an `@` + E0304, // expected signed integer constant + E0305, // expected constant + E0306, // expected positive integer for repeat count + E0307, // expected constant integer for repeat count + E0308, + E0309, // thing may not live long enough + E0310, // thing may not live long enough + E0311, // thing may not live long enough + E0312, // lifetime of reference outlives lifetime of borrowed content + E0313, // lifetime of borrowed pointer outlives lifetime of captured variable + E0314, // closure outlives stack frame + E0315 // cannot invoke closure outside of its lifetime } __build_diagnostic_array! { DIAGNOSTICS } diff --git a/src/librustc/middle/check_loop.rs b/src/librustc/middle/check_loop.rs index 1f779acac25..623f3525d4a 100644 --- a/src/librustc/middle/check_loop.rs +++ b/src/librustc/middle/check_loop.rs @@ -73,12 +73,12 @@ fn require_loop(&self, name: &str, span: Span) { match self.cx { Loop => {} Closure => { - self.sess.span_err(span, - &format!("`{}` inside of a closure", name)[]); + span_err!(self.sess, span, E0267, + "`{}` inside of a closure", name); } Normal => { - self.sess.span_err(span, - &format!("`{}` outside of loop", name)[]); + span_err!(self.sess, span, E0268, + "`{}` outside of loop", name); } } } diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index a1a90395b3b..f6db0cf755b 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -226,11 +226,10 @@ fn check_expr(cx: &mut MatchCheckCtxt, ex: &ast::Expr) { ast::ExprForLoop(ref pat, _, _, _) => { let mut static_inliner = StaticInliner::new(cx.tcx); is_refutable(cx, &*static_inliner.fold_pat((*pat).clone()), |uncovered_pat| { - cx.tcx.sess.span_err( - pat.span, - &format!("refutable pattern in `for` loop binding: \ + span_err!(cx.tcx.sess, pat.span, E0297, + "refutable pattern in `for` loop binding: \ `{}` not covered", - pat_to_string(uncovered_pat))[]); + pat_to_string(uncovered_pat)); }); // Check legality of move bindings. @@ -869,7 +868,7 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat], Some(true) => Some(vec![]), Some(false) => None, None => { - cx.tcx.sess.span_err(pat_span, "mismatched types between arms"); + span_err!(cx.tcx.sess, pat_span, E0298, "mismatched types between arms"); None } } @@ -882,7 +881,7 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat], Some(true) => Some(vec![]), Some(false) => None, None => { - cx.tcx.sess.span_err(pat_span, "mismatched types between arms"); + span_err!(cx.tcx.sess, pat_span, E0299, "mismatched types between arms"); None } } @@ -921,7 +920,7 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat], } ast::PatMac(_) => { - cx.tcx.sess.span_err(pat_span, "unexpanded macro"); + span_err!(cx.tcx.sess, pat_span, E0300, "unexpanded macro"); None } }; @@ -1082,11 +1081,8 @@ fn borrow(&mut self, _: LoanCause) { match kind { MutBorrow => { - self.cx - .tcx - .sess - .span_err(span, - "cannot mutably borrow in a pattern guard") + span_err!(self.cx.tcx.sess, span, E0301, + "cannot mutably borrow in a pattern guard") } ImmBorrow | UniqueImmBorrow => {} } @@ -1095,10 +1091,7 @@ fn decl_without_init(&mut self, _: NodeId, _: Span) {} fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) { match mode { JustWrite | WriteAndRead => { - self.cx - .tcx - .sess - .span_err(span, "cannot assign in a pattern guard") + span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard") } Init => {} } @@ -1120,7 +1113,7 @@ struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> { impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> { fn visit_pat(&mut self, pat: &Pat) { if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map, pat) { - self.cx.tcx.sess.span_err(pat.span, + span_err!(self.cx.tcx.sess, pat.span, E0303, "pattern bindings are not allowed \ after an `@`"); } diff --git a/src/librustc/middle/check_static_recursion.rs b/src/librustc/middle/check_static_recursion.rs index 86a58dae45a..4280b7fe3f0 100644 --- a/src/librustc/middle/check_static_recursion.rs +++ b/src/librustc/middle/check_static_recursion.rs @@ -83,7 +83,7 @@ pub fn check_item_recursion<'a>(sess: &'a Session, impl<'a, 'ast, 'v> Visitor<'v> for CheckItemRecursionVisitor<'a, 'ast> { fn visit_item(&mut self, it: &ast::Item) { if self.idstack.iter().any(|x| x == &(it.id)) { - self.sess.span_err(self.root_it.span, "recursive constant"); + span_err!(self.sess, self.root_it.span, E0265, "recursive constant"); return; } self.idstack.push(it.id); @@ -103,9 +103,9 @@ fn visit_expr(&mut self, e: &ast::Expr) { self.visit_item(item), ast_map::NodeForeignItem(_) => {}, _ => { - self.sess.span_err(e.span, - &format!("expected item, found {}", - self.ast_map.node_to_string(def_id.node))[]); + span_err!(self.sess, e.span, E0266, + "expected item, found {}", + self.ast_map.node_to_string(def_id.node)); return; }, } diff --git a/src/librustc/middle/infer/error_reporting.rs b/src/librustc/middle/infer/error_reporting.rs index 1b9d6ec6c33..18c36f870b5 100644 --- a/src/librustc/middle/infer/error_reporting.rs +++ b/src/librustc/middle/infer/error_reporting.rs @@ -371,12 +371,11 @@ fn report_type_error(&self, trace: TypeTrace<'tcx>, terr: &ty::type_err<'tcx>) { infer::EquatePredicate(_) => "equality predicate not satisfied", }; - self.tcx.sess.span_err( - trace.origin.span(), - &format!("{}: {} ({})", + span_err!(self.tcx.sess, trace.origin.span(), E0308, + "{}: {} ({})", message_root_str, expected_found_str, - ty::type_err_to_str(self.tcx, terr))[]); + ty::type_err_to_str(self.tcx, terr)); match trace.origin { infer::MatchExpressionArm(_, arm_span) => @@ -443,9 +442,8 @@ fn report_generic_bound_failure(&self, match sub { ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => { // Does the required lifetime have a nice name we can print? - self.tcx.sess.span_err( - origin.span(), - &format!("{} may not live long enough", labeled_user_string)[]); + span_err!(self.tcx.sess, origin.span(), E0309, + "{} may not live long enough", labeled_user_string); self.tcx.sess.span_help( origin.span(), &format!( @@ -456,9 +454,8 @@ fn report_generic_bound_failure(&self, ty::ReStatic => { // Does the required lifetime have a nice name we can print? - self.tcx.sess.span_err( - origin.span(), - &format!("{} may not live long enough", labeled_user_string)[]); + span_err!(self.tcx.sess, origin.span(), E0310, + "{} may not live long enough", labeled_user_string); self.tcx.sess.span_help( origin.span(), &format!( @@ -468,11 +465,9 @@ fn report_generic_bound_failure(&self, _ => { // If not, be less specific. - self.tcx.sess.span_err( - origin.span(), - &format!( + span_err!(self.tcx.sess, origin.span(), E0311, "{} may not live long enough", - labeled_user_string)[]); + labeled_user_string); self.tcx.sess.span_help( origin.span(), &format!( @@ -499,8 +494,7 @@ fn report_concrete_failure(&self, self.report_and_explain_type_error(trace, &terr); } infer::Reborrow(span) => { - self.tcx.sess.span_err( - span, + span_err!(self.tcx.sess, span, E0312, "lifetime of reference outlines \ lifetime of borrowed content..."); note_and_explain_region( @@ -515,14 +509,13 @@ fn report_concrete_failure(&self, ""); } infer::ReborrowUpvar(span, ref upvar_id) => { - self.tcx.sess.span_err( - span, - &format!("lifetime of borrowed pointer outlives \ + span_err!(self.tcx.sess, span, E0313, + "lifetime of borrowed pointer outlives \ lifetime of captured variable `{}`...", ty::local_var_name_str(self.tcx, upvar_id.var_id) .get() - .to_string())[]); + .to_string()); note_and_explain_region( self.tcx, "...the borrowed pointer is valid for ", @@ -539,8 +532,7 @@ fn report_concrete_failure(&self, ""); } infer::InfStackClosure(span) => { - self.tcx.sess.span_err( - span, + span_err!(self.tcx.sess, span, E0314, "closure outlives stack frame"); note_and_explain_region( self.tcx, @@ -554,8 +546,7 @@ fn report_concrete_failure(&self, ""); } infer::InvokeClosure(span) => { - self.tcx.sess.span_err( - span, + span_err!(self.tcx.sess, span, E0315, "cannot invoke closure outside of its lifetime"); note_and_explain_region( self.tcx, diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 27a0324a3c4..f71779e2333 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -1557,8 +1557,7 @@ fn check_ret(&self, }, _ => false }; - self.ir.tcx.sess.span_err( - sp, "not all control paths return a value"); + span_err!(self.ir.tcx.sess, sp, E0269, "not all control paths return a value"); if ends_with_stmt { let last_stmt = body.stmts.first().unwrap(); let original_span = original_sp(self.ir.tcx.sess.codemap(), @@ -1575,7 +1574,7 @@ fn check_ret(&self, } ty::FnDiverging if self.live_on_entry(entry_ln, self.s.clean_exit_var).is_some() => { - self.ir.tcx.sess.span_err(sp, + span_err!(self.ir.tcx.sess, sp, E0270, "computation may converge in a function marked as diverging"); } diff --git a/src/librustc/middle/recursion_limit.rs b/src/librustc/middle/recursion_limit.rs index 017641bd3b7..81cbdf13c51 100644 --- a/src/librustc/middle/recursion_limit.rs +++ b/src/librustc/middle/recursion_limit.rs @@ -33,7 +33,7 @@ pub fn update_recursion_limit(sess: &Session, krate: &ast::Crate) { } } - sess.span_err(attr.span, "malformed recursion limit attribute, \ + span_err!(sess, attr.span, E0296, "malformed recursion limit attribute, \ expected #![recursion_limit=\"N\"]"); } } diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index eff0018becc..be2b3026755 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -396,10 +396,9 @@ fn resolve_free_lifetime_ref(&mut self, } fn unresolved_lifetime_ref(&self, lifetime_ref: &ast::Lifetime) { - self.sess.span_err( - lifetime_ref.span, - &format!("use of undeclared lifetime name `{}`", - token::get_name(lifetime_ref.name))[]); + span_err!(self.sess, lifetime_ref.span, E0261, + "use of undeclared lifetime name `{}`", + token::get_name(lifetime_ref.name)); } fn check_lifetime_defs(&mut self, old_scope: Scope, lifetimes: &Vec) { @@ -409,11 +408,9 @@ fn check_lifetime_defs(&mut self, old_scope: Scope, lifetimes: &Vec(infcx: &InferCtxt<'a, 'tcx>, let predicate = infcx.resolve_type_vars_if_possible(&obligation.predicate); if !predicate.references_error() { - infcx.tcx.sess.span_err( - obligation.cause.span, - format!( + span_err!(infcx.tcx.sess, obligation.cause.span, E0271, "type mismatch resolving `{}`: {}", predicate.user_string(infcx.tcx), - ty::type_err_to_str(infcx.tcx, &error.err)).as_slice()); + ty::type_err_to_str(infcx.tcx, &error.err)); note_obligation_cause(infcx, obligation); } } @@ -97,28 +95,25 @@ fn report_on_unimplemented<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, Position::ArgumentNamed(s) => match generic_map.get(s) { Some(val) => Some(val.as_slice()), None => { - infcx.tcx.sess - .span_err(err_sp, - format!("the #[rustc_on_unimplemented] \ + span_err!(infcx.tcx.sess, err_sp, E0272, + "the #[rustc_on_unimplemented] \ attribute on \ trait definition for {} refers to \ non-existent type parameter {}", - trait_str, s) - .as_slice()); + trait_str, s); errored = true; None } }, _ => { - infcx.tcx.sess - .span_err(err_sp, - format!("the #[rustc_on_unimplemented] \ + span_err!(infcx.tcx.sess, err_sp, E0273, + "the #[rustc_on_unimplemented] \ attribute on \ trait definition for {} must have named \ format arguments, \ eg `#[rustc_on_unimplemented = \ \"foo {{T}}\"]`", - trait_str).as_slice()); + trait_str); errored = true; None } @@ -130,11 +125,11 @@ trait definition for {} must have named \ report = Some(err); } } else { - infcx.tcx.sess.span_err(err_sp, - format!("the #[rustc_on_unimplemented] attribute on \ + span_err!(infcx.tcx.sess, err_sp, E0274, + "the #[rustc_on_unimplemented] attribute on \ trait definition for {} must have a value, \ eg `#[rustc_on_unimplemented = \"foo\"]`", - trait_str).as_slice()); + trait_str); } break; } @@ -151,11 +146,9 @@ pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, // We could track the stack here more precisely if we wanted, I imagine. let predicate = infcx.resolve_type_vars_if_possible(&obligation.predicate); - infcx.tcx.sess.span_err( - obligation.cause.span, - format!( + span_err!(infcx.tcx.sess, obligation.cause.span, E0275, "overflow evaluating the requirement `{}`", - predicate.user_string(infcx.tcx)).as_slice()); + predicate.user_string(infcx.tcx)); suggest_new_overflow_limit(infcx.tcx, obligation.cause.span); @@ -165,12 +158,10 @@ pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, SelectionError::Unimplemented => { match &obligation.cause.code { &ObligationCauseCode::CompareImplMethodObligation => { - infcx.tcx.sess.span_err( - obligation.cause.span, - format!( + span_err!(infcx.tcx.sess, obligation.cause.span, E0276, "the requirement `{}` appears on the impl \ method but not on the corresponding trait method", - obligation.predicate.user_string(infcx.tcx)).as_slice()); + obligation.predicate.user_string(infcx.tcx));; } _ => { match obligation.predicate { @@ -180,12 +171,10 @@ pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, if !trait_predicate.references_error() { let trait_ref = trait_predicate.to_poly_trait_ref(); - infcx.tcx.sess.span_err( - obligation.cause.span, - format!( + span_err!(infcx.tcx.sess, obligation.cause.span, E0277, "the trait `{}` is not implemented for the type `{}`", trait_ref.user_string(infcx.tcx), - trait_ref.self_ty().user_string(infcx.tcx)).as_slice()); + trait_ref.self_ty().user_string(infcx.tcx)); // Check if it has a custom "#[rustc_on_unimplemented]" // error message, report with that message if it does let custom_note = report_on_unimplemented(infcx, &*trait_ref.0, @@ -201,34 +190,28 @@ pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, let predicate = infcx.resolve_type_vars_if_possible(predicate); let err = infcx.equality_predicate(obligation.cause.span, &predicate).unwrap_err(); - infcx.tcx.sess.span_err( - obligation.cause.span, - format!( + span_err!(infcx.tcx.sess, obligation.cause.span, E0278, "the requirement `{}` is not satisfied (`{}`)", predicate.user_string(infcx.tcx), - ty::type_err_to_str(infcx.tcx, &err)).as_slice()); + ty::type_err_to_str(infcx.tcx, &err)); } ty::Predicate::RegionOutlives(ref predicate) => { let predicate = infcx.resolve_type_vars_if_possible(predicate); let err = infcx.region_outlives_predicate(obligation.cause.span, &predicate).unwrap_err(); - infcx.tcx.sess.span_err( - obligation.cause.span, - format!( + span_err!(infcx.tcx.sess, obligation.cause.span, E0279, "the requirement `{}` is not satisfied (`{}`)", predicate.user_string(infcx.tcx), - ty::type_err_to_str(infcx.tcx, &err)).as_slice()); + ty::type_err_to_str(infcx.tcx, &err)); } ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => { let predicate = infcx.resolve_type_vars_if_possible(&obligation.predicate); - infcx.tcx.sess.span_err( - obligation.cause.span, - format!( + span_err!(infcx.tcx.sess, obligation.cause.span, E0280, "the requirement `{}` is not satisfied", - predicate.user_string(infcx.tcx)).as_slice()); + predicate.user_string(infcx.tcx)); } } } @@ -239,15 +222,13 @@ pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, let expected_trait_ref = infcx.resolve_type_vars_if_possible(&*expected_trait_ref); let actual_trait_ref = infcx.resolve_type_vars_if_possible(&*actual_trait_ref); if !ty::type_is_error(actual_trait_ref.self_ty()) { - infcx.tcx.sess.span_err( - obligation.cause.span, - format!( + span_err!(infcx.tcx.sess, obligation.cause.span, E0281, "type mismatch: the type `{}` implements the trait `{}`, \ but the trait `{}` is required ({})", expected_trait_ref.self_ty().user_string(infcx.tcx), expected_trait_ref.user_string(infcx.tcx), actual_trait_ref.user_string(infcx.tcx), - ty::type_err_to_str(infcx.tcx, e)).as_slice()); + ty::type_err_to_str(infcx.tcx, e)); note_obligation_cause(infcx, obligation); } } @@ -293,18 +274,14 @@ pub fn maybe_report_ambiguity<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, infcx.tcx.lang_items.sized_trait() .map_or(false, |sized_id| sized_id == trait_ref.def_id()) { - infcx.tcx.sess.span_err( - obligation.cause.span, - format!( + span_err!(infcx.tcx.sess, obligation.cause.span, E0282, "unable to infer enough type information about `{}`; \ type annotations required", - self_ty.user_string(infcx.tcx)).as_slice()); + self_ty.user_string(infcx.tcx)); } else { - infcx.tcx.sess.span_err( - obligation.cause.span, - format!( + span_err!(infcx.tcx.sess, obligation.cause.span, E0283, "type annotations required: cannot resolve `{}`", - predicate.user_string(infcx.tcx)).as_slice()); + predicate.user_string(infcx.tcx));; note_obligation_cause(infcx, obligation); } } @@ -323,11 +300,9 @@ pub fn maybe_report_ambiguity<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, _ => { if !infcx.tcx.sess.has_errors() { - infcx.tcx.sess.span_err( - obligation.cause.span, - format!( + span_err!(infcx.tcx.sess, obligation.cause.span, E0284, "type annotations required: cannot resolve `{}`", - predicate.user_string(infcx.tcx)).as_slice()); + predicate.user_string(infcx.tcx));; note_obligation_cause(infcx, obligation); } } diff --git a/src/librustc/middle/traits/mod.rs b/src/librustc/middle/traits/mod.rs index 425765edf87..89459f95b87 100644 --- a/src/librustc/middle/traits/mod.rs +++ b/src/librustc/middle/traits/mod.rs @@ -379,11 +379,10 @@ pub fn type_known_to_meet_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, false } Err(Overflow) => { - infcx.tcx.sess.span_err( - span, - format!("overflow evaluating whether `{}` is `{}`", - ty.user_string(infcx.tcx), - bound.user_string(infcx.tcx)).as_slice()); + span_err!(infcx.tcx.sess, span, E0285, + "overflow evaluating whether `{}` is `{}`", + ty.user_string(infcx.tcx), + bound.user_string(infcx.tcx)); suggest_new_overflow_limit(infcx.tcx, span); false } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index be6c6b9d34f..e5bbd01dde6 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -5369,15 +5369,13 @@ pub fn enum_variants<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId) discriminant = val as Disr } Ok(_) => { - cx.sess - .span_err(e.span, + span_err!(cx.sess, e.span, E0304, "expected signed integer constant"); } Err(ref err) => { - cx.sess - .span_err(e.span, - &format!("expected constant: {}", - *err)[]); + span_err!(cx.sess, e.span, E0305, + "expected constant: {}", + *err); } }, None => {} @@ -5851,9 +5849,9 @@ pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> uint { const_eval::const_binary(_) => "binary array" }; - tcx.sess.span_err(count_expr.span, &format!( + span_err!(tcx.sess, count_expr.span, E0306, "expected positive integer for repeat count, found {}", - found)[]); + found); } Err(_) => { let found = match count_expr.node { @@ -5866,9 +5864,9 @@ pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> uint { _ => "non-constant expression" }; - tcx.sess.span_err(count_expr.span, &format!( + span_err!(tcx.sess, count_expr.span, E0307, "expected constant integer for repeat count, found {}", - found)[]); + found); } } 0 diff --git a/src/librustc/middle/weak_lang_items.rs b/src/librustc/middle/weak_lang_items.rs index 892a8004fec..25cca98c5fb 100644 --- a/src/librustc/middle/weak_lang_items.rs +++ b/src/librustc/middle/weak_lang_items.rs @@ -99,9 +99,9 @@ fn register(&mut self, name: &str, span: Span) { self.items.missing.push(lang_items::$item); } } else)* { - self.sess.span_err(span, - format!("unknown external lang item: `{}`", - name).as_slice()); + span_err!(self.sess, span, E0264, + "unknown external lang item: `{}`", + name); } } } From 9a4401fe828f2f29c359bc3c83f6f3b7eed27d83 Mon Sep 17 00:00:00 2001 From: Michael Sproul Date: Sat, 17 Jan 2015 17:20:24 -0800 Subject: [PATCH 49/96] Add some extended errors. --- src/librustc/diagnostics.rs | 40 ++++++++++++++++++++++++----- src/libsyntax/diagnostics/macros.rs | 6 +++++ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/librustc/diagnostics.rs b/src/librustc/diagnostics.rs index 1dbd6eb4e8d..b48df36a679 100644 --- a/src/librustc/diagnostics.rs +++ b/src/librustc/diagnostics.rs @@ -10,21 +10,49 @@ #![allow(non_snake_case)] -register_diagnostic! { E0001, r##" +register_long_diagnostics! { + E0001: r##" This error suggests that the expression arm corresponding to the noted pattern will never be reached as for all possible values of the expression being matched, one of the preceeding patterns will match. This means that perhaps some of the preceeding patterns are too general, this one is too specific or the ordering is incorrect. -"## } +"##, + + E0003: r##" + Not-a-Number (NaN) values can not be compared for equality and hence can never match + the input to a match expression. To match against NaN values, you should instead use + the `is_nan` method in a guard, as in: x if x.is_nan() => ... +"##, + + E0004: r##" + This error indicates that the compiler can not guarantee a matching pattern for one + or more possible inputs to a match expression. Guaranteed matches are required in order + to assign values to match expressions, or alternatively, determine the flow of execution. + + If you encounter this error you must alter your patterns so that every possible value of + the input type is matched. For types with a small number of variants (like enums) you + should probably cover all cases explicitly. Alternatively, the underscore `_` wildcard + pattern can be added after all other patterns to match "anything else". +"##, + + // FIXME: Remove duplication here? + E0005: r##" + Patterns used to bind names must be irrefutable, that is, they must guarantee that a + name will be extracted in all cases. If you encounter this error you probably need + to use a `match` or `if let` to deal with the possibility of failure. +"##, + + E0006: r##" + Patterns used to bind names must be irrefutable, that is, they must guarantee that a + name will be extracted in all cases. If you encounter this error you probably need + to use a `match` or `if let` to deal with the possibility of failure. +"## +} register_diagnostics! { E0002, - E0003, - E0004, - E0005, - E0006, E0007, E0008, E0009, diff --git a/src/libsyntax/diagnostics/macros.rs b/src/libsyntax/diagnostics/macros.rs index 5bd683c86ae..9321d3ca3df 100644 --- a/src/libsyntax/diagnostics/macros.rs +++ b/src/libsyntax/diagnostics/macros.rs @@ -59,3 +59,9 @@ macro_rules! register_diagnostics { ) } +#[macro_export] +macro_rules! register_long_diagnostics { + ($($code:tt: $description:tt),*) => ( + $(register_diagnostic! { $code, $description })* + ) +} From b6380f5c67cace73a1170f282e6cd7f8c65a0625 Mon Sep 17 00:00:00 2001 From: JP Sugarbroad Date: Tue, 20 Jan 2015 12:00:12 -0800 Subject: [PATCH 50/96] Kill RacyCell in favor of marking SyncSender explicitly Send. --- src/libstd/sync/mpsc/mod.rs | 51 +++++++++++++------------------------ 1 file changed, 17 insertions(+), 34 deletions(-) diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 0ba19b70617..e1ad02498db 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -319,6 +319,7 @@ use sync::Arc; use fmt; +#[cfg(stage0)] // NOTE remove use after next snapshot use marker; use mem; use cell::UnsafeCell; @@ -372,7 +373,7 @@ unsafe impl Send for Sender { } #[stable] #[cfg(stage0)] // NOTE remove impl after next snapshot pub struct SyncSender { - inner: Arc>>, + inner: Arc>>, // can't share in an arc _marker: marker::NoSync, } @@ -382,11 +383,13 @@ pub struct SyncSender { #[stable] #[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub struct SyncSender { - inner: Arc>>, + inner: Arc>>, } +unsafe impl Send for SyncSender {} + #[cfg(not(stage0))] // NOTE remove cfg after next snapshot -impl !marker::Sync for SyncSender {} +impl !Sync for SyncSender {} /// An error returned from the `send` function on channels. /// @@ -442,10 +445,10 @@ pub enum TrySendError { } enum Flavor { - Oneshot(Arc>>), - Stream(Arc>>), - Shared(Arc>>), - Sync(Arc>>), + Oneshot(Arc>>), + Stream(Arc>>), + Shared(Arc>>), + Sync(Arc>>), } #[doc(hidden)] @@ -497,7 +500,7 @@ fn inner_unsafe<'a>(&'a self) -> &'a UnsafeCell> { /// ``` #[stable] pub fn channel() -> (Sender, Receiver) { - let a = Arc::new(RacyCell::new(oneshot::Packet::new())); + let a = Arc::new(UnsafeCell::new(oneshot::Packet::new())); (Sender::new(Flavor::Oneshot(a.clone())), Receiver::new(Flavor::Oneshot(a))) } @@ -537,7 +540,7 @@ pub fn channel() -> (Sender, Receiver) { /// ``` #[stable] pub fn sync_channel(bound: uint) -> (SyncSender, Receiver) { - let a = Arc::new(RacyCell::new(sync::Packet::new(bound))); + let a = Arc::new(UnsafeCell::new(sync::Packet::new(bound))); (SyncSender::new(a.clone()), Receiver::new(Flavor::Sync(a))) } @@ -589,7 +592,7 @@ pub fn send(&self, t: T) -> Result<(), SendError> { return (*p).send(t).map_err(SendError); } else { let a = - Arc::new(RacyCell::new(stream::Packet::new())); + Arc::new(UnsafeCell::new(stream::Packet::new())); let rx = Receiver::new(Flavor::Stream(a.clone())); match (*p).upgrade(rx) { oneshot::UpSuccess => { @@ -631,7 +634,7 @@ impl Clone for Sender { fn clone(&self) -> Sender { let (packet, sleeper, guard) = match *unsafe { self.inner() } { Flavor::Oneshot(ref p) => { - let a = Arc::new(RacyCell::new(shared::Packet::new())); + let a = Arc::new(UnsafeCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); let rx = Receiver::new(Flavor::Shared(a.clone())); @@ -643,7 +646,7 @@ fn clone(&self) -> Sender { } } Flavor::Stream(ref p) => { - let a = Arc::new(RacyCell::new(shared::Packet::new())); + let a = Arc::new(UnsafeCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); let rx = Receiver::new(Flavor::Shared(a.clone())); @@ -690,12 +693,12 @@ fn drop(&mut self) { impl SyncSender { #[cfg(stage0)] // NOTE remove impl after next snapshot - fn new(inner: Arc>>) -> SyncSender { + fn new(inner: Arc>>) -> SyncSender { SyncSender { inner: inner, _marker: marker::NoSync } } #[cfg(not(stage0))] // NOTE remove cfg after next snapshot - fn new(inner: Arc>>) -> SyncSender { + fn new(inner: Arc>>) -> SyncSender { SyncSender { inner: inner } } @@ -978,26 +981,6 @@ fn drop(&mut self) { } } -/// A version of `UnsafeCell` intended for use in concurrent data -/// structures (for example, you might put it in an `Arc`). -struct RacyCell(pub UnsafeCell); - -impl RacyCell { - - fn new(value: T) -> RacyCell { - RacyCell(UnsafeCell { value: value }) - } - - unsafe fn get(&self) -> *mut T { - self.0.get() - } - -} - -unsafe impl Send for RacyCell { } - -unsafe impl Sync for RacyCell { } // Oh dear - impl fmt::Show for SendError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "sending on a closed channel".fmt(f) From 9bbfd681c9fa47f462a89e8f5eedd3fa2a5de2e7 Mon Sep 17 00:00:00 2001 From: James Miller Date: Wed, 21 Jan 2015 09:35:24 +1300 Subject: [PATCH 51/96] Add assumptions that the pointer is non-null --- src/liballoc/rc.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 0f2a11cc1db..837d709e882 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -933,12 +933,26 @@ fn weak(&self) -> uint { self.inner().weak.get() } impl RcBoxPtr for Rc { #[inline(always)] - fn inner(&self) -> &RcBox { unsafe { &(**self._ptr) } } + fn inner(&self) -> &RcBox { + unsafe { + // Safe to assume this here, as if it weren't true, we'd be breaking + // the contract anyway + assume(!self._ptr.is_null()); + &(**self._ptr) + } + } } impl RcBoxPtr for Weak { #[inline(always)] - fn inner(&self) -> &RcBox { unsafe { &(**self._ptr) } } + fn inner(&self) -> &RcBox { + unsafe { + // Safe to assume this here, as if it weren't true, we'd be breaking + // the contract anyway + assume(!self._ptr.is_null()); + &(**self._ptr) + } + } } #[cfg(test)] From 64914d9d39aaa06f3796b412e90065d26a704eea Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 20 Jan 2015 11:20:22 -0800 Subject: [PATCH 52/96] rustc: Remove deprecated lint names These were all renamed quite some time ago, so remove their old names from the compiler. --- src/librustc/lint/context.rs | 25 +------------------- src/test/compile-fail/lint-renaming.rs | 16 ------------- src/test/compile-fail/lint-type-limits.rs | 2 +- src/test/compile-fail/warn-path-statement.rs | 2 +- src/test/run-pass/crate-name-attr-used.rs | 2 +- src/test/run-pass/warn-ctypes-inhibit.rs | 4 ++-- 6 files changed, 6 insertions(+), 45 deletions(-) delete mode 100644 src/test/compile-fail/lint-renaming.rs diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index de4efe09f27..fcb3200089b 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -231,30 +231,7 @@ macro_rules! add_lint_group { // We have one lint pass defined in this module. self.register_pass(sess, false, box GatherNodeLevels as LintPassObject); - // Insert temporary renamings for a one-time deprecation (#16545) - self.register_renamed("unnecessary_typecast", "unused_typecasts"); - self.register_renamed("unsigned_negate", "unsigned_negation"); - self.register_renamed("type_limits", "unused_comparisons"); - self.register_renamed("type_overflow", "overflowing_literals"); - self.register_renamed("ctypes", "improper_ctypes"); - self.register_renamed("owned_heap_memory", "box_pointers"); - self.register_renamed("unused_attribute", "unused_attributes"); - self.register_renamed("path_statement", "path_statements"); - self.register_renamed("unused_result", "unused_results"); - self.register_renamed("non_uppercase_statics", "non_upper_case_globals"); - self.register_renamed("unnecessary_parens", "unused_parens"); - self.register_renamed("unnecessary_import_braces", "unused_import_braces"); - self.register_renamed("unsafe_block", "unsafe_blocks"); - self.register_renamed("unnecessary_allocation", "unused_allocation"); - self.register_renamed("missing_doc", "missing_docs"); - self.register_renamed("unused_extern_crate", "unused_extern_crates"); - self.register_renamed("unnecessary_qualification", "unused_qualifications"); - self.register_renamed("unrecognized_lint", "unknown_lints"); - self.register_renamed("unused_variable", "unused_variables"); - self.register_renamed("dead_assignment", "unused_assignments"); - self.register_renamed("unknown_crate_type", "unknown_crate_types"); - self.register_renamed("variant_size_difference", "variant_size_differences"); - self.register_renamed("transmute_fat_ptr", "fat_ptr_transmutes"); + // Insert temporary renamings for a one-time deprecation self.register_renamed("raw_pointer_deriving", "raw_pointer_derive"); } diff --git a/src/test/compile-fail/lint-renaming.rs b/src/test/compile-fail/lint-renaming.rs deleted file mode 100644 index 7ffec37772f..00000000000 --- a/src/test/compile-fail/lint-renaming.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// Check that lint deprecation works - -#[deny(unused_variable)] //~ warning: lint unused_variable has been renamed to unused_variables -pub fn main() { - let x = 0u8; //~ error: unused variable: -} diff --git a/src/test/compile-fail/lint-type-limits.rs b/src/test/compile-fail/lint-type-limits.rs index a2bc464ac49..3eae12f234f 100644 --- a/src/test/compile-fail/lint-type-limits.rs +++ b/src/test/compile-fail/lint-type-limits.rs @@ -10,7 +10,7 @@ #![allow(dead_code)] -// compile-flags: -D type-limits +// compile-flags: -D unused-comparisons fn main() { } fn foo() { diff --git a/src/test/compile-fail/warn-path-statement.rs b/src/test/compile-fail/warn-path-statement.rs index 304900df776..d205e2a2e4e 100644 --- a/src/test/compile-fail/warn-path-statement.rs +++ b/src/test/compile-fail/warn-path-statement.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// compile-flags: -D path-statement +// compile-flags: -D path-statements fn main() { let x = 10is; diff --git a/src/test/run-pass/crate-name-attr-used.rs b/src/test/run-pass/crate-name-attr-used.rs index 95c7d331264..f04a760e5f6 100644 --- a/src/test/run-pass/crate-name-attr-used.rs +++ b/src/test/run-pass/crate-name-attr-used.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// compile-flags:--crate-name crate-name-attr-used -F unused-attribute +// compile-flags:--crate-name crate-name-attr-used -F unused-attributes #![crate_name = "crate-name-attr-used"] diff --git a/src/test/run-pass/warn-ctypes-inhibit.rs b/src/test/run-pass/warn-ctypes-inhibit.rs index 93112e3e7ec..73121918259 100644 --- a/src/test/run-pass/warn-ctypes-inhibit.rs +++ b/src/test/run-pass/warn-ctypes-inhibit.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// compile-flags:-D ctypes +// compile-flags:-D improper-ctypes -#![allow(ctypes)] +#![allow(improper_ctypes)] mod libc { extern { From a7525bc4c8eb8507a5c248d29286e77133217cf3 Mon Sep 17 00:00:00 2001 From: James Miller Date: Wed, 21 Jan 2015 09:56:59 +1300 Subject: [PATCH 53/96] Add more explanation for why the assumes are there --- src/liballoc/rc.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 837d709e882..e651e375e3d 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -909,6 +909,8 @@ fn strong(&self) -> uint { self.inner().strong.get() } fn inc_strong(&self) { let strong = self.strong(); // The reference count is always at least one unless we're about to drop the type + // This allows the bulk of the destructor to be omitted in cases where we know that + // the reference count must be > 0. unsafe { assume(strong > 0); } self.inner().strong.set(strong + 1); } @@ -917,6 +919,8 @@ fn inc_strong(&self) { fn dec_strong(&self) { let strong = self.strong(); // The reference count is always at least one unless we're about to drop the type + // This allows the bulk of the destructor to be omitted in cases where we know that + // the reference count must be > 0 unsafe { assume(strong > 0); } self.inner().strong.set(strong - 1); } @@ -936,7 +940,9 @@ impl RcBoxPtr for Rc { fn inner(&self) -> &RcBox { unsafe { // Safe to assume this here, as if it weren't true, we'd be breaking - // the contract anyway + // the contract anyway. + // This allows the null check to be elided in the destructor if we + // manipulated the reference count in the same function. assume(!self._ptr.is_null()); &(**self._ptr) } @@ -949,6 +955,8 @@ fn inner(&self) -> &RcBox { unsafe { // Safe to assume this here, as if it weren't true, we'd be breaking // the contract anyway + // This allows the null check to be elided in the destructor if we + // manipulated the reference count in the same function. assume(!self._ptr.is_null()); &(**self._ptr) } From ace2f09d3f89e20a7caa67bb0548212b07f696c2 Mon Sep 17 00:00:00 2001 From: Stepan Koltsov Date: Tue, 20 Jan 2015 23:57:56 +0300 Subject: [PATCH 54/96] alloc::boxed: enable test Previously test was disabled due to `#[cfg(test)]` before `mod boxed`. --- src/liballoc/boxed.rs | 53 --------------------------- src/liballoc/boxed_test.rs | 75 ++++++++++++++++++++++++++++++++++++++ src/liballoc/lib.rs | 2 + 3 files changed, 77 insertions(+), 53 deletions(-) create mode 100644 src/liballoc/boxed_test.rs diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index a2cc98c7d01..de18d7a4a01 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -187,56 +187,3 @@ impl DerefMut for Box { fn deref_mut(&mut self) -> &mut T { &mut **self } } -#[cfg(test)] -mod test { - #[test] - fn test_owned_clone() { - let a = Box::new(5i); - let b: Box = a.clone(); - assert!(a == b); - } - - #[test] - fn any_move() { - let a = Box::new(8u) as Box; - let b = Box::new(Test) as Box; - - match a.downcast::() { - Ok(a) => { assert!(a == Box::new(8u)); } - Err(..) => panic!() - } - match b.downcast::() { - Ok(a) => { assert!(a == Box::new(Test)); } - Err(..) => panic!() - } - - let a = Box::new(8u) as Box; - let b = Box::new(Test) as Box; - - assert!(a.downcast::>().is_err()); - assert!(b.downcast::>().is_err()); - } - - #[test] - fn test_show() { - let a = Box::new(8u) as Box; - let b = Box::new(Test) as Box; - let a_str = a.to_str(); - let b_str = b.to_str(); - assert_eq!(a_str, "Box"); - assert_eq!(b_str, "Box"); - - let a = &8u as &Any; - let b = &Test as &Any; - let s = format!("{}", a); - assert_eq!(s, "&Any"); - let s = format!("{}", b); - assert_eq!(s, "&Any"); - } - - #[test] - fn deref() { - fn homura>(_: T) { } - homura(Box::new(765i32)); - } -} diff --git a/src/liballoc/boxed_test.rs b/src/liballoc/boxed_test.rs new file mode 100644 index 00000000000..c47a771f60d --- /dev/null +++ b/src/liballoc/boxed_test.rs @@ -0,0 +1,75 @@ +// Copyright 2012-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. + +//! Test for `boxed` mod. + +use core::any::Any; +use core::ops::Deref; +use core::result::Result::{Ok, Err}; +use core::clone::Clone; + +use std::boxed::Box; +use std::boxed::BoxAny; + +#[test] +fn test_owned_clone() { + let a = Box::new(5i); + let b: Box = a.clone(); + assert!(a == b); +} + +#[derive(PartialEq, Eq)] +struct Test; + +#[test] +fn any_move() { + let a = Box::new(8u) as Box; + let b = Box::new(Test) as Box; + + match a.downcast::() { + Ok(a) => { assert!(a == Box::new(8u)); } + Err(..) => panic!() + } + match b.downcast::() { + Ok(a) => { assert!(a == Box::new(Test)); } + Err(..) => panic!() + } + + let a = Box::new(8u) as Box; + let b = Box::new(Test) as Box; + + assert!(a.downcast::>().is_err()); + assert!(b.downcast::>().is_err()); +} + +#[test] +fn test_show() { + let a = Box::new(8u) as Box; + let b = Box::new(Test) as Box; + let a_str = format!("{:?}", a); + let b_str = format!("{:?}", b); + assert_eq!(a_str, "Box"); + assert_eq!(b_str, "Box"); + + static EIGHT: usize = 8us; + static TEST: Test = Test; + let a = &EIGHT as &Any; + let b = &TEST as &Any; + let s = format!("{:?}", a); + assert_eq!(s, "&Any"); + let s = format!("{:?}", b); + assert_eq!(s, "&Any"); +} + +#[test] +fn deref() { + fn homura>(_: T) { } + homura(Box::new(765i32)); +} diff --git a/src/liballoc/lib.rs b/src/liballoc/lib.rs index 811e32e747d..be45429aa1a 100644 --- a/src/liballoc/lib.rs +++ b/src/liballoc/lib.rs @@ -91,6 +91,8 @@ #[cfg(not(test))] pub mod boxed; +#[cfg(test)] +mod boxed_test; pub mod arc; pub mod rc; From cd631c6914d384538352604059a7e4abb31d8c46 Mon Sep 17 00:00:00 2001 From: Flavio Percoco Date: Tue, 20 Jan 2015 15:51:09 +0100 Subject: [PATCH 55/96] Register snapshot for 9006c3c --- src/liballoc/rc.rs | 154 ------------------------------- src/libcollections/btree/set.rs | 3 - src/libcore/marker.rs | 19 ---- src/librustc/middle/region.rs | 3 - src/libstd/io/process.rs | 3 - src/libstd/sync/mpsc/blocking.rs | 30 ------ src/libstd/sync/mpsc/mod.rs | 17 ---- src/libstd/sync/mpsc/select.rs | 27 ------ src/libstd/sync/mutex.rs | 32 ------- src/libstd/sync/rwlock.rs | 52 ----------- src/snapshots.txt | 9 ++ 11 files changed, 9 insertions(+), 340 deletions(-) diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 7191a7af346..b516d9b4d31 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -174,61 +174,17 @@ struct RcBox { /// See the [module level documentation](../index.html) for more details. #[unsafe_no_drop_flag] #[stable] -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct Rc { - // FIXME #12808: strange names to try to avoid interfering with field accesses of the contained - // type via Deref - _ptr: NonZero<*mut RcBox>, - _nosend: marker::NoSend, - _noshare: marker::NoSync -} - -/// An immutable reference-counted pointer type. -/// -/// See the [module level documentation](../index.html) for more details. -#[unsafe_no_drop_flag] -#[stable] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub struct Rc { // FIXME #12808: strange names to try to avoid interfering with field accesses of the contained // type via Deref _ptr: NonZero<*mut RcBox>, } -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !marker::Send for Rc {} -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !marker::Sync for Rc {} impl Rc { - /// Constructs a new `Rc`. - /// - /// # Examples - /// - /// ``` - /// use std::rc::Rc; - /// - /// let five = Rc::new(5i); - /// ``` - #[stable] - #[cfg(stage0)] // NOTE remove after next snapshot - pub fn new(value: T) -> Rc { - unsafe { - Rc { - // there is an implicit weak pointer owned by all the strong pointers, which - // ensures that the weak destructor never frees the allocation while the strong - // destructor is running, even if the weak pointer is stored inside the strong one. - _ptr: NonZero::new(transmute(box RcBox { - value: value, - strong: Cell::new(1), - weak: Cell::new(1) - })), - _nosend: marker::NoSend, - _noshare: marker::NoSync - } - } - } /// Constructs a new `Rc`. /// @@ -240,7 +196,6 @@ pub fn new(value: T) -> Rc { /// let five = Rc::new(5i); /// ``` #[stable] - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub fn new(value: T) -> Rc { unsafe { Rc { @@ -267,29 +222,6 @@ pub fn new(value: T) -> Rc { /// /// let weak_five = five.downgrade(); /// ``` - #[cfg(stage0)] // NOTE remove after next snapshot - #[unstable = "Weak pointers may not belong in this module"] - pub fn downgrade(&self) -> Weak { - self.inc_weak(); - Weak { - _ptr: self._ptr, - _nosend: marker::NoSend, - _noshare: marker::NoSync - } - } - - /// Downgrades the `Rc` to a `Weak` reference. - /// - /// # Examples - /// - /// ``` - /// use std::rc::Rc; - /// - /// let five = Rc::new(5i); - /// - /// let weak_five = five.downgrade(); - /// ``` - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot #[unstable = "Weak pointers may not belong in this module"] pub fn downgrade(&self) -> Weak { self.inc_weak(); @@ -483,25 +415,6 @@ fn drop(&mut self) { #[stable] impl Clone for Rc { - /// Makes a clone of the `Rc`. - /// - /// This increases the strong reference count. - /// - /// # Examples - /// - /// ``` - /// use std::rc::Rc; - /// - /// let five = Rc::new(5i); - /// - /// five.clone(); - /// ``` - #[inline] - #[cfg(stage0)] // NOTE remove after next snapshot - fn clone(&self) -> Rc { - self.inc_strong(); - Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync } - } /// Makes a clone of the `Rc`. /// @@ -517,7 +430,6 @@ fn clone(&self) -> Rc { /// five.clone(); /// ``` #[inline] - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot fn clone(&self) -> Rc { self.inc_strong(); Rc { _ptr: self._ptr } @@ -714,66 +626,21 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { /// See the [module level documentation](../index.html) for more. #[unsafe_no_drop_flag] #[unstable = "Weak pointers may not belong in this module."] -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct Weak { - // FIXME #12808: strange names to try to avoid interfering with - // field accesses of the contained type via Deref - _ptr: NonZero<*mut RcBox>, - _nosend: marker::NoSend, - _noshare: marker::NoSync -} - -/// A weak version of `Rc`. -/// -/// Weak references do not count when determining if the inner value should be dropped. -/// -/// See the [module level documentation](../index.html) for more. -#[unsafe_no_drop_flag] -#[unstable = "Weak pointers may not belong in this module."] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub struct Weak { // FIXME #12808: strange names to try to avoid interfering with // field accesses of the contained type via Deref _ptr: NonZero<*mut RcBox>, } -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot #[allow(unstable)] impl !marker::Send for Weak {} -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot #[allow(unstable)] impl !marker::Sync for Weak {} #[unstable = "Weak pointers may not belong in this module."] impl Weak { - /// Upgrades a weak reference to a strong reference. - /// - /// Upgrades the `Weak` reference to an `Rc`, if possible. - /// - /// Returns `None` if there were no strong references and the data was destroyed. - /// - /// # Examples - /// - /// ``` - /// use std::rc::Rc; - /// - /// let five = Rc::new(5i); - /// - /// let weak_five = five.downgrade(); - /// - /// let strong_five: Option> = weak_five.upgrade(); - /// ``` - #[cfg(stage0)] // NOTE remove after next snapshot - pub fn upgrade(&self) -> Option> { - if self.strong() == 0 { - None - } else { - self.inc_strong(); - Some(Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync }) - } - } /// Upgrades a weak reference to a strong reference. /// @@ -792,7 +659,6 @@ pub fn upgrade(&self) -> Option> { /// /// let strong_five: Option> = weak_five.upgrade(); /// ``` - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub fn upgrade(&self) -> Option> { if self.strong() == 0 { None @@ -849,25 +715,6 @@ fn drop(&mut self) { #[unstable = "Weak pointers may not belong in this module."] impl Clone for Weak { - /// Makes a clone of the `Weak`. - /// - /// This increases the weak reference count. - /// - /// # Examples - /// - /// ``` - /// use std::rc::Rc; - /// - /// let weak_five = Rc::new(5i).downgrade(); - /// - /// weak_five.clone(); - /// ``` - #[inline] - #[cfg(stage0)] // NOTE remove after next snapshot - fn clone(&self) -> Weak { - self.inc_weak(); - Weak { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync } - } /// Makes a clone of the `Weak`. /// @@ -883,7 +730,6 @@ fn clone(&self) -> Weak { /// weak_five.clone(); /// ``` #[inline] - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot fn clone(&self) -> Weak { self.inc_weak(); Weak { _ptr: self._ptr } diff --git a/src/libcollections/btree/set.rs b/src/libcollections/btree/set.rs index 4d71f9dbea8..90b61d3c5d1 100644 --- a/src/libcollections/btree/set.rs +++ b/src/libcollections/btree/set.rs @@ -18,9 +18,6 @@ use core::default::Default; use core::fmt::Show; use core::fmt; -// NOTE(stage0) remove import after a snapshot -#[cfg(stage0)] -use core::hash::Hash; use core::iter::{Peekable, Map, FromIterator}; use core::ops::{BitOr, BitAnd, BitXor, Sub}; diff --git a/src/libcore/marker.rs b/src/libcore/marker.rs index 99ba9666cd2..a987a0a5068 100644 --- a/src/libcore/marker.rs +++ b/src/libcore/marker.rs @@ -376,16 +376,6 @@ fn clone(&self) -> InvariantType { *self } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct InvariantLifetime<'a>; -/// A type which is considered "not sendable", meaning that it cannot -/// be safely sent between tasks, even if it is owned. This is -/// typically embedded in other types, such as `Gc`, to ensure that -/// their instances remain thread-local. -#[unstable = "likely to change with new variance strategy"] -#[lang="no_send_bound"] -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct NoSend; - /// A type which is considered "not POD", meaning that it is not /// implicitly copyable. This is typically embedded in other types to /// ensure that they are never copied, even if they lack a destructor. @@ -395,15 +385,6 @@ fn clone(&self) -> InvariantType { *self } #[allow(missing_copy_implementations)] pub struct NoCopy; -/// A type which is considered "not sync", meaning that -/// its contents are not threadsafe, hence they cannot be -/// shared between tasks. -#[unstable = "likely to change with new variance strategy"] -#[lang="no_sync_bound"] -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct NoSync; - /// A type which is considered managed by the GC. This is typically /// embedded in other types. #[unstable = "likely to change with new variance strategy"] diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index 90ba442ee39..b4b2e1b63e8 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -22,9 +22,6 @@ use util::common::can_reach; use std::cell::RefCell; -// NOTE(stage0) remove import after a snapshot -#[cfg(stage0)] -use std::hash::{Hash}; use syntax::codemap::Span; use syntax::{ast, visit}; use syntax::ast::{Block, Item, FnDecl, NodeId, Arm, Pat, Stmt, Expr, Local}; diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index 43ca7b13145..d98f155ba83 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -21,9 +21,6 @@ use collections::HashMap; use ffi::CString; use fmt; -// NOTE(stage0) remove import after a snapshot -#[cfg(stage0)] -use hash::Hash; use io::pipe::{PipeStream, PipePair}; use io::{IoResult, IoError}; use io; diff --git a/src/libstd/sync/mpsc/blocking.rs b/src/libstd/sync/mpsc/blocking.rs index 17e690e9540..61ffb532d36 100644 --- a/src/libstd/sync/mpsc/blocking.rs +++ b/src/libstd/sync/mpsc/blocking.rs @@ -14,8 +14,6 @@ use sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; use sync::Arc; use marker::{Sync, Send}; -#[cfg(stage0)] // NOTE remove use after next snapshot -use marker::{NoSend, NoSync}; use mem; use clone::Clone; @@ -32,42 +30,14 @@ pub struct SignalToken { inner: Arc, } -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct WaitToken { - inner: Arc, - no_send: NoSend, - no_sync: NoSync, -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub struct WaitToken { inner: Arc, } -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !Send for WaitToken {} -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !Sync for WaitToken {} -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub fn tokens() -> (WaitToken, SignalToken) { - let inner = Arc::new(Inner { - thread: Thread::current(), - woken: ATOMIC_BOOL_INIT, - }); - let wait_token = WaitToken { - inner: inner.clone(), - no_send: NoSend, - no_sync: NoSync, - }; - let signal_token = SignalToken { - inner: inner - }; - (wait_token, signal_token) -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub fn tokens() -> (WaitToken, SignalToken) { let inner = Arc::new(Inner { thread: Thread::current(), diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 0ba19b70617..375a85eb879 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -370,22 +370,10 @@ unsafe impl Send for Sender { } /// The sending-half of Rust's synchronous channel type. This half can only be /// owned by one task, but it can be cloned to send to other tasks. #[stable] -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct SyncSender { - inner: Arc>>, - // can't share in an arc - _marker: marker::NoSync, -} - -/// The sending-half of Rust's synchronous channel type. This half can only be -/// owned by one task, but it can be cloned to send to other tasks. -#[stable] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub struct SyncSender { inner: Arc>>, } -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !marker::Sync for SyncSender {} /// An error returned from the `send` function on channels. @@ -689,12 +677,7 @@ fn drop(&mut self) { //////////////////////////////////////////////////////////////////////////////// impl SyncSender { - #[cfg(stage0)] // NOTE remove impl after next snapshot - fn new(inner: Arc>>) -> SyncSender { - SyncSender { inner: inner, _marker: marker::NoSync } - } - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot fn new(inner: Arc>>) -> SyncSender { SyncSender { inner: inner } } diff --git a/src/libstd/sync/mpsc/select.rs b/src/libstd/sync/mpsc/select.rs index 62a7b823ec8..e726b1f4846 100644 --- a/src/libstd/sync/mpsc/select.rs +++ b/src/libstd/sync/mpsc/select.rs @@ -66,24 +66,12 @@ /// The "receiver set" of the select interface. This structure is used to manage /// a set of receivers which are being selected over. -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct Select { - head: *mut Handle<'static, ()>, - tail: *mut Handle<'static, ()>, - next_id: Cell, - marker1: marker::NoSend, -} - -/// The "receiver set" of the select interface. This structure is used to manage -/// a set of receivers which are being selected over. -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub struct Select { head: *mut Handle<'static, ()>, tail: *mut Handle<'static, ()>, next_id: Cell, } -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !marker::Send for Select {} /// A handle to a receiver which is currently a member of a `Select` set of @@ -121,27 +109,12 @@ pub trait Packet { } impl Select { - /// Creates a new selection structure. This set is initially empty and - /// `wait` will panic!() if called. - /// - /// Usage of this struct directly can sometimes be burdensome, and usage is - /// rather much easier through the `select!` macro. - #[cfg(stage0)] // NOTE remove impl after next snapshot - pub fn new() -> Select { - Select { - marker1: marker::NoSend, - head: 0 as *mut Handle<'static, ()>, - tail: 0 as *mut Handle<'static, ()>, - next_id: Cell::new(1), - } - } /// Creates a new selection structure. This set is initially empty and /// `wait` will panic!() if called. /// /// Usage of this struct directly can sometimes be burdensome, and usage is /// rather much easier through the `select!` macro. - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub fn new() -> Select { Select { head: 0 as *mut Handle<'static, ()>, diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 73d5332d16f..6ddfe3e075b 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -160,24 +160,6 @@ unsafe impl Sync for StaticMutex {} /// Deref and DerefMut implementations #[must_use] #[stable] -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct MutexGuard<'a, T: 'a> { - // funny underscores due to how Deref/DerefMut currently work (they - // disregard field privacy). - __lock: &'a StaticMutex, - __data: &'a UnsafeCell, - __poison: poison::Guard, - __marker: marker::NoSend, -} - -/// An RAII implementation of a "scoped lock" of a mutex. When this structure is -/// dropped (falls out of scope), the lock will be unlocked. -/// -/// The data protected by the mutex can be access through this guard via its -/// Deref and DerefMut implementations -#[must_use] -#[stable] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub struct MutexGuard<'a, T: 'a> { // funny underscores due to how Deref/DerefMut currently work (they // disregard field privacy). @@ -186,7 +168,6 @@ pub struct MutexGuard<'a, T: 'a> { __poison: poison::Guard, } -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl<'a, T> !marker::Send for MutexGuard<'a, T> {} /// Static initialization of a mutex. This constant can be used to initialize @@ -299,20 +280,7 @@ pub unsafe fn destroy(&'static self) { } impl<'mutex, T> MutexGuard<'mutex, T> { - #[cfg(stage0)] // NOTE remove afte next snapshot - fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell) - -> LockResult> { - poison::map_result(lock.poison.borrow(), |guard| { - MutexGuard { - __lock: lock, - __data: data, - __poison: guard, - __marker: marker::NoSend, - } - }) - } - #[cfg(not(stage0))] // NOTE remove cfg afte next snapshot fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell) -> LockResult> { poison::map_result(lock.poison.borrow(), |guard| { diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 237f6d08a95..35d305466b5 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -110,50 +110,23 @@ unsafe impl Sync for StaticRwLock {} /// dropped. #[must_use] #[stable] -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct RwLockReadGuard<'a, T: 'a> { - __lock: &'a StaticRwLock, - __data: &'a UnsafeCell, - __marker: marker::NoSend, -} - -/// RAII structure used to release the shared read access of a lock when -/// dropped. -#[must_use] -#[stable] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub struct RwLockReadGuard<'a, T: 'a> { __lock: &'a StaticRwLock, __data: &'a UnsafeCell, } -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl<'a, T> !marker::Send for RwLockReadGuard<'a, T> {} /// RAII structure used to release the exclusive write access of a lock when /// dropped. #[must_use] #[stable] -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct RwLockWriteGuard<'a, T: 'a> { - __lock: &'a StaticRwLock, - __data: &'a UnsafeCell, - __poison: poison::Guard, - __marker: marker::NoSend, -} - -/// RAII structure used to release the exclusive write access of a lock when -/// dropped. -#[must_use] -#[stable] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub struct RwLockWriteGuard<'a, T: 'a> { __lock: &'a StaticRwLock, __data: &'a UnsafeCell, __poison: poison::Guard, } -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl<'a, T> !marker::Send for RwLockWriteGuard<'a, T> {} impl RwLock { @@ -332,19 +305,7 @@ pub unsafe fn destroy(&'static self) { } impl<'rwlock, T> RwLockReadGuard<'rwlock, T> { - #[cfg(stage0)] // NOTE remove impl after next snapshot - fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell) - -> LockResult> { - poison::map_result(lock.poison.borrow(), |_| { - RwLockReadGuard { - __lock: lock, - __data: data, - __marker: marker::NoSend, - } - }) - } - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell) -> LockResult> { poison::map_result(lock.poison.borrow(), |_| { @@ -356,20 +317,7 @@ fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell) } } impl<'rwlock, T> RwLockWriteGuard<'rwlock, T> { - #[cfg(stage0)] // NOTE remove impl after next snapshot - fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell) - -> LockResult> { - poison::map_result(lock.poison.borrow(), |guard| { - RwLockWriteGuard { - __lock: lock, - __data: data, - __poison: guard, - __marker: marker::NoSend, - } - }) - } - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell) -> LockResult> { poison::map_result(lock.poison.borrow(), |guard| { diff --git a/src/snapshots.txt b/src/snapshots.txt index 16fb109bb7d..8b502785733 100644 --- a/src/snapshots.txt +++ b/src/snapshots.txt @@ -1,3 +1,12 @@ +S 2015-01-20 9006c3c + freebsd-x86_64 240b30b33263d175e30f925ed1e1e1a4e553a513 + linux-i386 544c2063b8d5035342c705b881b8868244c1e9a1 + linux-x86_64 eb41db80978210a013a8dcf8f4fe804969197337 + macos-i386 3ed08c5ae66367e85b8f2b207615d45bfd9cf89d + macos-x86_64 d102760316b90b17d54b0bef02ca6dc35f82e6bd + winnt-i386 6940fef6caa2f64d158b8f5eb00afd5c8e0c71a5 + winnt-x86_64 36b6f239fe1264bceb4b8202e692b7d49947eebe + S 2015-01-15 9ade482 freebsd-x86_64 eb8f52c6e8dc24a293456d5e4dc5d1072442e758 linux-i386 0197ad7179d74eba06a8b46432548caf226aa03d From 8051bd06260e4587e183e6055a6794414e7c76f9 Mon Sep 17 00:00:00 2001 From: Daniel Raloff Date: Tue, 20 Jan 2015 14:07:10 -0800 Subject: [PATCH 56/96] Changed rust-mode code for tabs -> spaces --- src/etc/emacs/rust-mode.el | 40 +++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/etc/emacs/rust-mode.el b/src/etc/emacs/rust-mode.el index f66df6c0565..ed1523d64f9 100644 --- a/src/etc/emacs/rust-mode.el +++ b/src/etc/emacs/rust-mode.el @@ -73,18 +73,18 @@ ;; open bracket ends the line (when (not (looking-at "[[:blank:]]*\\(?://.*\\)?$")) (when (looking-at "[[:space:]]") - (forward-word 1) - (backward-word 1)) + (forward-word 1) + (backward-word 1)) (current-column)))) (defun rust-align-to-method-chain () (save-excursion - (previous-line) - (end-of-line) - (backward-word 1) - (backward-char) - (when (looking-at "\\..+\(.*\)\n") - (- (current-column) rust-indent-offset)))) + (previous-line) + (end-of-line) + (backward-word 1) + (backward-char) + (when (looking-at "\\..+\(.*\)\n") + (- (current-column) rust-indent-offset)))) (defun rust-rewind-to-beginning-of-current-level-expr () (let ((current-level (rust-paren-level))) @@ -108,9 +108,9 @@ ;; the inside of it correctly relative to the outside. (if (= 0 level) 0 - (or - (when rust-indent-method-chain - (rust-align-to-method-chain)) + (or + (when rust-indent-method-chain + (rust-align-to-method-chain)) (save-excursion (backward-up-list) (rust-rewind-to-beginning-of-current-level-expr) @@ -126,16 +126,16 @@ ;; A closing brace is 1 level unindended ((looking-at "}") (- baseline rust-indent-offset)) - ;;Line up method chains by their .'s - ((when (and rust-indent-method-chain - (looking-at "\..+\(.*\);?\n")) - (or - (let ((method-indent (rust-align-to-method-chain))) - (when method-indent - (+ method-indent rust-indent-offset))) - (+ baseline rust-indent-offset)))) + ;;Line up method chains by their .'s + ((when (and rust-indent-method-chain + (looking-at "\..+\(.*\);?\n")) + (or + (let ((method-indent (rust-align-to-method-chain))) + (when method-indent + (+ method-indent rust-indent-offset))) + (+ baseline rust-indent-offset)))) - + ;; Doc comments in /** style with leading * indent to line up the *s ((and (nth 4 (syntax-ppss)) (looking-at "*")) (+ 1 baseline)) From 876b26645913f7e600f5919db166ec5db0219aaf Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Tue, 20 Jan 2015 14:18:35 -0800 Subject: [PATCH 57/96] Make multiline errors work with codes --- src/librustc/session/mod.rs | 115 ++++++++++++++++++++---------------- 1 file changed, 63 insertions(+), 52 deletions(-) diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index 0392fbfdeae..4150335abc3 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -76,61 +76,16 @@ pub fn fatal(&self, msg: &str) -> ! { self.diagnostic().handler().fatal(msg) } pub fn span_err(&self, sp: Span, msg: &str) { - // Conditions for enabling multi-line errors: - if !msg.contains("mismatched types") && - !msg.contains("type mismatch resolving") && - !msg.contains("if and else have incompatible types") && - !msg.contains("if may be missing an else clause") && - !msg.contains("match arms have incompatible types") && - !msg.contains("structure constructor specifies a structure of type") { - return self.diagnostic().span_err(sp, msg); + match split_msg_into_multilines(msg) { + Some(msg) => self.diagnostic().span_err(sp, &msg[]), + None => self.diagnostic().span_err(sp, msg) } - - let first = Regex::new(r"[( ]expected").unwrap(); - let second = Regex::new(r" found").unwrap(); - let third = Regex::new( - r"\((values differ|lifetime|cyclic type of infinite size)").unwrap(); - - let mut new_msg = String::new(); - let mut head = 0u; - - // Insert `\n` before expected and found. - for (pos1, pos2) in first.find_iter(msg).zip( - second.find_iter(msg)) { - new_msg = new_msg + - // A `(` may be preceded by a space and it should be trimmed - msg[head..pos1.0].trim_right() + // prefix - "\n" + // insert before first - &msg[pos1.0..pos1.1] + // insert what first matched - &msg[pos1.1..pos2.0] + // between matches - "\n " + // insert before second - // 123 - // `expected` is 3 char longer than `found`. To align the types, `found` gets - // 3 spaces prepended. - &msg[pos2.0..pos2.1]; // insert what second matched - - head = pos2.1; - } - - let mut tail = &msg[head..]; - // Insert `\n` before any remaining messages which match. - for pos in third.find_iter(tail).take(1) { - // The end of the message may just be wrapped in `()` without `expected`/`found`. - // Push this also to a new line and add the final tail after. - new_msg = new_msg + - // `(` is usually preceded by a space and should be trimmed. - tail[..pos.0].trim_right() + // prefix - "\n" + // insert before paren - &tail[pos.0..]; // append the tail - - tail = ""; - } - - new_msg.push_str(tail); - self.diagnostic().span_err(sp, &new_msg[]) } pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) { - self.diagnostic().span_err_with_code(sp, msg, code) + match split_msg_into_multilines(msg) { + Some(msg) => self.diagnostic().span_err_with_code(sp, &msg[], code), + None => self.diagnostic().span_err_with_code(sp, msg, code) + } } pub fn err(&self, msg: &str) { self.diagnostic().handler().err(msg) @@ -288,6 +243,62 @@ pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch { } } +fn split_msg_into_multilines(msg: &str) -> Option { + // Conditions for enabling multi-line errors: + if !msg.contains("mismatched types") && + !msg.contains("type mismatch resolving") && + !msg.contains("if and else have incompatible types") && + !msg.contains("if may be missing an else clause") && + !msg.contains("match arms have incompatible types") && + !msg.contains("structure constructor specifies a structure of type") { + return None + } + + let first = Regex::new(r"[( ]expected").unwrap(); + let second = Regex::new(r" found").unwrap(); + let third = Regex::new( + r"\((values differ|lifetime|cyclic type of infinite size)").unwrap(); + + let mut new_msg = String::new(); + let mut head = 0u; + + // Insert `\n` before expected and found. + for (pos1, pos2) in first.find_iter(msg).zip( + second.find_iter(msg)) { + new_msg = new_msg + + // A `(` may be preceded by a space and it should be trimmed + msg[head..pos1.0].trim_right() + // prefix + "\n" + // insert before first + &msg[pos1.0..pos1.1] + // insert what first matched + &msg[pos1.1..pos2.0] + // between matches + "\n " + // insert before second + // 123 + // `expected` is 3 char longer than `found`. To align the types, `found` gets + // 3 spaces prepended. + &msg[pos2.0..pos2.1]; // insert what second matched + + head = pos2.1; + } + + let mut tail = &msg[head..]; + // Insert `\n` before any remaining messages which match. + for pos in third.find_iter(tail).take(1) { + // The end of the message may just be wrapped in `()` without `expected`/`found`. + // Push this also to a new line and add the final tail after. + new_msg = new_msg + + // `(` is usually preceded by a space and should be trimmed. + tail[..pos.0].trim_right() + // prefix + "\n" + // insert before paren + &tail[pos.0..]; // append the tail + + tail = ""; + } + + new_msg.push_str(tail); + + return Some(new_msg) +} + pub fn build_session(sopts: config::Options, local_crate_source_file: Option, registry: diagnostics::registry::Registry) From 00cddb068c4cb17a91cca646103e0fba8c0a8077 Mon Sep 17 00:00:00 2001 From: Jorge Aparicio Date: Tue, 20 Jan 2015 18:15:28 -0500 Subject: [PATCH 58/96] also forward Iterator::size_hint() --- src/liballoc/boxed.rs | 4 ++++ src/libcore/iter.rs | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 89de2c953e4..7965c00a365 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -194,6 +194,10 @@ impl<'a, T> Iterator for Box + 'a> { fn next(&mut self) -> Option { (**self).next() } + + fn size_hint(&self) -> (usize, Option) { + (**self).size_hint() + } } #[cfg(test)] diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 3d51f75d9b3..2a21ceef7a1 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -107,6 +107,10 @@ impl<'a, T> Iterator for &'a mut (Iterator + 'a) { fn next(&mut self) -> Option { (**self).next() } + + fn size_hint(&self) -> (usize, Option) { + (**self).size_hint() + } } /// Conversion from an `Iterator` From 9714d3cccfa1f317986d0f1d5cd4717b6e2bfcee Mon Sep 17 00:00:00 2001 From: Corey Richardson Date: Tue, 20 Jan 2015 18:43:38 -0500 Subject: [PATCH 59/96] tests: uncomment regression tests for 13970, 13971, 13972 Closes #13971 --- src/test/run-pass/const-block.rs | 44 ++++++++++++-------------------- 1 file changed, 17 insertions(+), 27 deletions(-) diff --git a/src/test/run-pass/const-block.rs b/src/test/run-pass/const-block.rs index 84acd3c4ecd..cdb96e5dcbf 100644 --- a/src/test/run-pass/const-block.rs +++ b/src/test/run-pass/const-block.rs @@ -14,7 +14,7 @@ use std::marker::Sync; struct Foo { - a: uint, + a: usize, b: *const () } @@ -24,27 +24,24 @@ fn foo(a: T) -> T { a } -static BLOCK_INTEGRAL: uint = { 1 }; +static BLOCK_INTEGRAL: usize = { 1 }; static BLOCK_EXPLICIT_UNIT: () = { () }; static BLOCK_IMPLICIT_UNIT: () = { }; static BLOCK_FLOAT: f64 = { 1.0 }; -static BLOCK_ENUM: Option = { Some(100) }; +static BLOCK_ENUM: Option = { Some(100) }; static BLOCK_STRUCT: Foo = { Foo { a: 12, b: 0 as *const () } }; -static BLOCK_UNSAFE: uint = unsafe { 1000 }; +static BLOCK_UNSAFE: usize = unsafe { 1000 }; -// FIXME: #13970 -// static BLOCK_FN_INFERRED: fn(uint) -> uint = { foo }; +static BLOCK_FN_INFERRED: fn(usize) -> usize = { foo }; -// FIXME: #13971 -// static BLOCK_FN: fn(uint) -> uint = { foo:: }; +static BLOCK_FN: fn(usize) -> usize = { foo:: }; -// FIXME: #13972 -// static BLOCK_ENUM_CONSTRUCTOR: fn(uint) -> Option = { Some }; +static BLOCK_ENUM_CONSTRUCTOR: fn(usize) -> Option = { Some }; -// FIXME: #13973 -// static BLOCK_UNSAFE_SAFE_PTR: &'static int = unsafe { &*(0xdeadbeef as *int) }; -// static BLOCK_UNSAFE_SAFE_PTR_2: &'static int = unsafe { -// static X: *int = 0xdeadbeef as *int; +// FIXME #13972 +// static BLOCK_UNSAFE_SAFE_PTR: &'static isize = unsafe { &*(0xdeadbeef as *const isize) }; +// static BLOCK_UNSAFE_SAFE_PTR_2: &'static isize = unsafe { +// const X: *const isize = 0xdeadbeef as *const isize; // &*X // }; @@ -57,17 +54,10 @@ pub fn main() { assert_eq!(BLOCK_STRUCT.b, 0 as *const ()); assert_eq!(BLOCK_ENUM, Some(100)); assert_eq!(BLOCK_UNSAFE, 1000); - - // FIXME: #13970 - // assert_eq!(BLOCK_FN_INFERRED(300), 300); - - // FIXME: #13971 - // assert_eq!(BLOCK_FN(300), 300); - - // FIXME: #13972 - // assert_eq!(BLOCK_ENUM_CONSTRUCTOR(200), Some(200)); - - // FIXME: #13973 - // assert_eq!(BLOCK_UNSAFE_SAFE_PTR as *int as uint, 0xdeadbeef_u); - // assert_eq!(BLOCK_UNSAFE_SAFE_PTR_2 as *int as uint, 0xdeadbeef_u); + assert_eq!(BLOCK_FN_INFERRED(300), 300); + assert_eq!(BLOCK_FN(300), 300); + assert_eq!(BLOCK_ENUM_CONSTRUCTOR(200), Some(200)); + // FIXME #13972 + // assert_eq!(BLOCK_UNSAFE_SAFE_PTR as *const isize as usize, 0xdeadbeef_us); + // assert_eq!(BLOCK_UNSAFE_SAFE_PTR_2 as *const isize as usize, 0xdeadbeef_us); } From 2cc7feb4f6019b36f84d56f3202361bace1e5503 Mon Sep 17 00:00:00 2001 From: Andrew Paseltiner Date: Mon, 12 Jan 2015 17:08:53 -0500 Subject: [PATCH 60/96] implement `ExactSizeIterator` for `slice::{Chunks,ChunksMut}` --- src/libcollections/slice.rs | 7 +++++++ src/libcore/slice.rs | 5 +++++ 2 files changed, 12 insertions(+) diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 4812ecc2c0b..9787c625806 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -2409,8 +2409,12 @@ fn test_windowsator_0() { #[test] fn test_chunksator() { + use core::iter::ExactSizeIterator; + let v = &[1i,2,3,4,5]; + assert_eq!(v.chunks(2).len(), 3); + let chunks: &[&[int]] = &[&[1i,2], &[3,4], &[5]]; assert_eq!(v.chunks(2).collect::>(), chunks); let chunks: &[&[int]] = &[&[1i,2,3], &[4,5]]; @@ -2675,7 +2679,10 @@ fn test_get_mut() { #[test] fn test_mut_chunks() { + use core::iter::ExactSizeIterator; + let mut v = [0u8, 1, 2, 3, 4, 5, 6]; + assert_eq!(v.chunks_mut(2).len(), 4); for (i, chunk) in v.chunks_mut(3).enumerate() { for x in chunk.iter_mut() { *x = i as u8; diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 22da168911d..c31e15795e6 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -1269,6 +1269,9 @@ fn next_back(&mut self) -> Option<&'a [T]> { } } +#[stable] +impl<'a, T> ExactSizeIterator for Chunks<'a, T> {} + #[unstable = "trait is experimental"] impl<'a, T> RandomAccessIterator for Chunks<'a, T> { #[inline] @@ -1347,6 +1350,8 @@ fn next_back(&mut self) -> Option<&'a mut [T]> { } } +#[stable] +impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {} // // Free functions From eb086505b805792a6afe67a644cde6b4ab002f14 Mon Sep 17 00:00:00 2001 From: Diggory Blake Date: Wed, 21 Jan 2015 04:35:57 +0000 Subject: [PATCH 61/96] Display negative trait implementations correctly in rustdoc Added doc test --- src/librustdoc/clean/inline.rs | 2 ++ src/librustdoc/clean/mod.rs | 17 ++++++++++++++ src/librustdoc/html/render.rs | 4 ++++ .../run-make/rustdoc-negative-impl/Makefile | 6 +++++ .../run-make/rustdoc-negative-impl/foo.rs | 22 +++++++++++++++++++ 5 files changed, 51 insertions(+) create mode 100644 src/test/run-make/rustdoc-negative-impl/Makefile create mode 100644 src/test/run-make/rustdoc-negative-impl/foo.rs diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index ccaefadc1fc..519292fa9e0 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -317,6 +317,7 @@ fn build_impl(cx: &DocContext, tcx: &ty::ctxt, } } }).collect(); + let polarity = csearch::get_impl_polarity(tcx, did); return Some(clean::Item { inner: clean::ImplItem(clean::Impl { derived: clean::detect_derived(attrs.as_slice()), @@ -329,6 +330,7 @@ fn build_impl(cx: &DocContext, tcx: &ty::ctxt, for_: ty.ty.clean(cx), generics: (&ty.generics, subst::TypeSpace).clean(cx), items: trait_items, + polarity: polarity.map(|p| { p.clean(cx) }), }), source: clean::Span::empty(), name: None, diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 7342c9f3e81..db945fe9a7b 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2082,6 +2082,21 @@ fn clean(&self, _: &DocContext) -> Mutability { } } +#[derive(Show, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)] +pub enum ImplPolarity { + Positive, + Negative, +} + +impl Clean for ast::ImplPolarity { + fn clean(&self, _: &DocContext) -> ImplPolarity { + match self { + &ast::ImplPolarity::Positive => ImplPolarity::Positive, + &ast::ImplPolarity::Negative => ImplPolarity::Negative, + } + } +} + #[derive(Clone, RustcEncodable, RustcDecodable)] pub struct Impl { pub generics: Generics, @@ -2089,6 +2104,7 @@ pub struct Impl { pub for_: Type, pub items: Vec, pub derived: bool, + pub polarity: Option, } fn detect_derived(attrs: &[M]) -> bool { @@ -2115,6 +2131,7 @@ fn clean(&self, cx: &DocContext) -> Item { } }).collect(), derived: detect_derived(self.attrs.as_slice()), + polarity: Some(self.polarity.clean(cx)), }), } } diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index ab9700d966a..9e94db33171 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -2085,6 +2085,10 @@ fn render_impl(w: &mut fmt::Formatter, i: &Impl) -> fmt::Result { try!(write!(w, "

{}impl{} ", ConciseStability(&i.stability), i.impl_.generics)); + match i.impl_.polarity { + Some(clean::ImplPolarity::Negative) => try!(write!(w, "!")), + _ => {} + } match i.impl_.trait_ { Some(ref ty) => try!(write!(w, "{} for ", *ty)), None => {} diff --git a/src/test/run-make/rustdoc-negative-impl/Makefile b/src/test/run-make/rustdoc-negative-impl/Makefile new file mode 100644 index 00000000000..1316ee256e1 --- /dev/null +++ b/src/test/run-make/rustdoc-negative-impl/Makefile @@ -0,0 +1,6 @@ +-include ../tools.mk + +all: foo.rs + $(HOST_RPATH_ENV) $(RUSTDOC) -w html -o $(TMPDIR)/doc foo.rs + $(HTMLDOCCK) $(TMPDIR)/doc foo.rs + diff --git a/src/test/run-make/rustdoc-negative-impl/foo.rs b/src/test/run-make/rustdoc-negative-impl/foo.rs new file mode 100644 index 00000000000..eaa3af86563 --- /dev/null +++ b/src/test/run-make/rustdoc-negative-impl/foo.rs @@ -0,0 +1,22 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(optin_builtin_traits)] + +// @matches foo/struct.Alpha.html '//pre' "pub struct Alpha" +pub struct Alpha; +// @matches foo/struct.Bravo.html '//pre' "pub struct Bravo" +pub struct Bravo; + +// @matches foo/struct.Alpha.html '//*[@class="impl"]//code' "impl !.*Send.* for .*Alpha" +impl !Send for Alpha {} + +// @matches foo/struct.Bravo.html '//*[@class="impl"]//code' "impl !.*Send.* for .*Bravo.*" +impl !Send for Bravo {} From ed56c15ceb3e8a6a30c46a4b7a1124d2086b5874 Mon Sep 17 00:00:00 2001 From: Jorge Aparicio Date: Mon, 19 Jan 2015 10:52:11 -0500 Subject: [PATCH 62/96] remove `NoSendItem` and `NoSyncItem` --- src/doc/reference.md | 4 ---- src/doc/trpl/unsafe.md | 2 +- src/librustc/middle/lang_items.rs | 2 -- src/librustc/middle/traits/select.rs | 6 +----- 4 files changed, 2 insertions(+), 12 deletions(-) diff --git a/src/doc/reference.md b/src/doc/reference.md index d3af4ab1c74..3cbfad52c05 100644 --- a/src/doc/reference.md +++ b/src/doc/reference.md @@ -2377,10 +2377,6 @@ These types help drive the compiler's analysis : ___Needs filling in___ * `no_copy_bound` : This type does not implement "copy", even if eligible. -* `no_send_bound` - : This type does not implement "send", even if eligible. -* `no_sync_bound` - : This type does not implement "sync", even if eligible. * `eh_personality` : ___Needs filling in___ * `exchange_free` diff --git a/src/doc/trpl/unsafe.md b/src/doc/trpl/unsafe.md index 2a66b4a01f7..3acd1eefe89 100644 --- a/src/doc/trpl/unsafe.md +++ b/src/doc/trpl/unsafe.md @@ -707,7 +707,7 @@ Other features provided by lang items include: various kinds; lang items `send`, `sync` and `copy`. - the marker types and variance indicators found in `std::marker`; lang items `covariant_type`, - `contravariant_lifetime`, `no_sync_bound`, etc. + `contravariant_lifetime`, etc. Lang items are loaded lazily by the compiler; e.g. if one never uses `Box` then there is no need to define functions for `exchange_malloc` diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index ff79ace9924..2c0de9d1634 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -320,9 +320,7 @@ pub fn collect_language_items(krate: &ast::Crate, ContravariantLifetimeItem, "contravariant_lifetime", contravariant_lifetime; InvariantLifetimeItem, "invariant_lifetime", invariant_lifetime; - NoSendItem, "no_send_bound", no_send_bound; NoCopyItem, "no_copy_bound", no_copy_bound; - NoSyncItem, "no_sync_bound", no_sync_bound; ManagedItem, "managed_bound", managed_bound; NonZeroItem, "non_zero", non_zero; diff --git a/src/librustc/middle/traits/select.rs b/src/librustc/middle/traits/select.rs index 62649653a69..e8d82150ade 100644 --- a/src/librustc/middle/traits/select.rs +++ b/src/librustc/middle/traits/select.rs @@ -1554,10 +1554,7 @@ fn nominal<'cx, 'tcx>(this: &mut SelectionContext<'cx, 'tcx>, let tcx = this.tcx(); match bound { ty::BoundSend => { - if - Some(def_id) == tcx.lang_items.no_send_bound() || - Some(def_id) == tcx.lang_items.managed_bound() - { + if Some(def_id) == tcx.lang_items.managed_bound() { return Err(Unimplemented) } } @@ -1568,7 +1565,6 @@ fn nominal<'cx, 'tcx>(this: &mut SelectionContext<'cx, 'tcx>, ty::BoundSync => { if - Some(def_id) == tcx.lang_items.no_sync_bound() || Some(def_id) == tcx.lang_items.managed_bound() || Some(def_id) == tcx.lang_items.unsafe_type() { From 3cb9fa26ef9905c00a29ea577fb55a12a91c8e7b Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 20 Jan 2015 15:45:07 -0800 Subject: [PATCH 63/96] std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl FromError for Box` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436 --- src/compiletest/common.rs | 12 +- src/compiletest/runtest.rs | 6 +- src/liballoc/arc.rs | 13 +- src/liballoc/boxed.rs | 23 ++- src/liballoc/rc.rs | 16 +- src/libcollections/bit.rs | 6 +- src/libcollections/btree/map.rs | 4 +- src/libcollections/btree/set.rs | 6 +- src/libcollections/dlist.rs | 4 +- src/libcollections/enum_set.rs | 2 +- src/libcollections/ring_buf.rs | 8 +- src/libcollections/slice.rs | 12 +- src/libcollections/string.rs | 43 +++--- src/libcollections/vec.rs | 6 +- src/libcollections/vec_map.rs | 4 +- src/libcore/any.rs | 8 +- src/libcore/array.rs | 6 +- src/libcore/borrow.rs | 24 ++- src/{libstd => libcore}/error.rs | 43 +----- src/libcore/fmt/mod.rs | 142 +++++++++++------- src/libcore/fmt/num.rs | 20 +-- src/libcore/lib.rs | 1 + src/libcore/ops.rs | 18 +-- src/libcore/result.rs | 10 +- src/libcore/str/mod.rs | 28 +++- src/libcoretest/finally.rs | 2 + src/libcoretest/fmt/num.rs | 24 +-- src/libcoretest/num/mod.rs | 4 +- src/libcoretest/result.rs | 6 +- src/libcoretest/tuple.rs | 6 +- src/libgetopts/lib.rs | 2 +- src/libgraphviz/lib.rs | 16 +- src/libgraphviz/maybe_owned_vec.rs | 2 +- src/liblog/lib.rs | 14 +- src/librbml/lib.rs | 8 + src/libregex/parse.rs | 3 +- src/libregex/re.rs | 4 +- src/librustc/middle/check_match.rs | 2 +- src/librustc/middle/graph.rs | 8 +- src/librustc/middle/infer/unify.rs | 4 +- src/librustc/middle/liveness.rs | 4 +- src/librustc/middle/resolve_lifetime.rs | 2 +- src/librustc/middle/subst.rs | 2 +- src/librustc/middle/traits/error_reporting.rs | 4 +- src/librustc/middle/traits/util.rs | 8 +- src/librustc/middle/ty.rs | 18 +-- src/librustc/session/config.rs | 4 +- src/librustc/util/common.rs | 4 +- src/librustc_back/archive.rs | 6 +- src/librustc_back/svh.rs | 10 +- .../borrowck/gather_loans/mod.rs | 2 +- src/librustc_resolve/lib.rs | 2 +- src/librustc_trans/back/link.rs | 6 +- src/librustc_trans/back/write.rs | 8 +- src/librustc_trans/trans/cleanup.rs | 2 +- src/librustc_trans/trans/datum.rs | 4 +- src/librustc_typeck/variance.rs | 2 +- src/librustdoc/html/escape.rs | 2 +- src/librustdoc/html/format.rs | 52 +++---- src/librustdoc/html/item_type.rs | 2 +- src/librustdoc/html/layout.rs | 2 +- src/librustdoc/html/markdown.rs | 4 +- src/librustdoc/html/render.rs | 8 +- src/librustdoc/html/toc.rs | 6 +- src/librustdoc/lib.rs | 2 +- src/libserialize/base64.rs | 8 +- src/libserialize/hex.rs | 8 +- src/libserialize/json.rs | 37 +++-- src/libstd/collections/hash/map.rs | 12 +- src/libstd/collections/hash/set.rs | 10 +- src/libstd/ffi/c_str.rs | 9 +- src/libstd/fmt.rs | 27 ++-- src/libstd/io/buffered.rs | 12 +- src/libstd/io/fs.rs | 50 +++--- src/libstd/io/mem.rs | 4 +- src/libstd/io/mod.rs | 32 +--- src/libstd/io/net/ip.rs | 6 +- src/libstd/io/process.rs | 15 +- src/libstd/lib.rs | 2 +- src/libstd/num/mod.rs | 4 +- src/libstd/os.rs | 12 +- src/libstd/path/mod.rs | 8 +- src/libstd/path/posix.rs | 5 +- src/libstd/path/windows.rs | 5 +- src/libstd/sync/mpsc/mod.rs | 20 ++- src/libstd/sync/poison.rs | 8 +- src/libstd/thread.rs | 12 +- src/libstd/time/duration.rs | 3 +- src/libsyntax/abi.rs | 20 +-- src/libsyntax/ast.rs | 51 +++---- src/libsyntax/ast_map/mod.rs | 2 +- src/libsyntax/attr.rs | 4 +- src/libsyntax/diagnostic.rs | 4 +- src/libsyntax/ext/deriving/mod.rs | 2 + src/libsyntax/ext/deriving/show.rs | 4 +- src/libsyntax/ext/format.rs | 4 +- src/libsyntax/owned_slice.rs | 2 +- src/libsyntax/parse/lexer/mod.rs | 8 +- src/libsyntax/parse/token.rs | 10 +- src/libsyntax/ptr.rs | 11 +- src/libsyntax/util/interner.rs | 11 +- src/libterm/terminfo/mod.rs | 2 +- src/libterm/terminfo/parm.rs | 16 +- src/libtest/lib.rs | 7 +- src/libtest/stats.rs | 4 +- src/test/compile-fail/dst-index.rs | 6 +- src/test/compile-fail/issue-14853.rs | 4 +- src/test/compile-fail/issue-15094.rs | 8 +- .../compile-fail/liveness-use-after-send.rs | 4 +- src/test/run-fail/assert-eq-macro-panic.rs | 2 +- src/test/run-pass/cfg_attr.rs | 38 ++--- src/test/run-pass/coerce-expect-unsized.rs | 10 +- src/test/run-pass/coherence-where-clause.rs | 6 +- src/test/run-pass/deriving-show-2.rs | 36 ++--- src/test/run-pass/deriving-show.rs | 16 +- src/test/run-pass/dst-index.rs | 10 +- src/test/run-pass/ifmt.rs | 24 +-- src/test/run-pass/issue-20676.rs | 2 +- src/test/run-pass/issue-3559.rs | 4 +- src/test/run-pass/issue-4252.rs | 12 +- src/test/run-pass/issue-8898.rs | 6 +- .../log-knows-the-names-of-variants-in-std.rs | 8 +- .../log-knows-the-names-of-variants.rs | 8 +- src/test/run-pass/multidispatch1.rs | 4 +- src/test/run-pass/multidispatch2.rs | 4 +- src/test/run-pass/no-landing-pads.rs | 2 +- .../run-pass/overloaded-index-assoc-list.rs | 2 +- src/test/run-pass/rec-align-u32.rs | 6 +- src/test/run-pass/rec-align-u64.rs | 6 +- src/test/run-pass/sepcomp-unwind.rs | 2 +- src/test/run-pass/show-boxed-slice.rs | 2 +- src/test/run-pass/small-enums-with-fields.rs | 14 +- src/test/run-pass/tag-align-shape.rs | 6 +- .../run-pass/unit-like-struct-drop-run.rs | 2 +- src/test/run-pass/vec-to_str.rs | 6 +- .../run-pass/wait-forked-but-failed-child.rs | 2 +- 136 files changed, 763 insertions(+), 706 deletions(-) rename src/{libstd => libcore}/error.rs (77%) diff --git a/src/compiletest/common.rs b/src/compiletest/common.rs index c29f74d7418..8de8d9ce741 100644 --- a/src/compiletest/common.rs +++ b/src/compiletest/common.rs @@ -13,7 +13,7 @@ use std::str::FromStr; use regex::Regex; -#[derive(Clone, PartialEq)] +#[derive(Clone, PartialEq, Debug)] pub enum Mode { CompileFail, RunFail, @@ -43,9 +43,9 @@ fn from_str(s: &str) -> Option { } } -impl fmt::String for Mode { +impl fmt::Display for Mode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(match *self { + fmt::Display::fmt(match *self { CompileFail => "compile-fail", RunFail => "run-fail", RunPass => "run-pass", @@ -58,12 +58,6 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::Show for Mode { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - #[derive(Clone)] pub struct Config { // The library paths required for running the compiler diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index 5579479c5e5..d9debb88a5c 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -547,7 +547,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) { // Add line breakpoints for line in breakpoint_lines.iter() { - script_str.push_str(&format!("break '{:?}':{}\n", + script_str.push_str(&format!("break '{}':{}\n", testfile.filename_display(), *line)[]); } @@ -750,7 +750,7 @@ fn run_lldb(config: &Config, status: status, stdout: out, stderr: err, - cmdline: format!("{}", cmd) + cmdline: format!("{:?}", cmd) }; } } @@ -953,7 +953,7 @@ fn check_expected_errors(expected_errors: Vec , } let prefixes = expected_errors.iter().map(|ee| { - format!("{:?}:{}:", testfile.display(), ee.line) + format!("{}:{}:", testfile.display(), ee.line) }).collect:: >(); #[cfg(windows)] diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index c0cd034abfa..5f8cd6baf9a 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -72,7 +72,7 @@ use core::atomic; use core::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst}; use core::borrow::BorrowFrom; -use core::fmt::{self, Show}; +use core::fmt; use core::cmp::{Ordering}; use core::default::Default; use core::mem::{min_align_of, size_of}; @@ -578,16 +578,17 @@ fn cmp(&self, other: &Arc) -> Ordering { (**self).cmp(&**other) } #[stable] impl Eq for Arc {} -impl fmt::Show for Arc { +#[stable] +impl fmt::Display for Arc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Arc({:?})", (**self)) + fmt::Display::fmt(&**self, f) } } #[stable] -impl fmt::String for Arc { +impl fmt::Debug for Arc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(&**self, f) + fmt::Debug::fmt(&**self, f) } } @@ -806,7 +807,7 @@ fn test_weak_count() { #[test] fn show_arc() { let a = Arc::new(5u32); - assert!(format!("{:?}", a) == "Arc(5u32)") + assert_eq!(format!("{:?}", a), "5"); } // Make sure deriving works with Arc diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index a2cc98c7d01..c2ee1a5d024 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -16,16 +16,17 @@ use core::clone::Clone; use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering}; use core::default::Default; +use core::error::{Error, FromError}; use core::fmt; use core::hash::{self, Hash}; use core::marker::Sized; use core::mem; +use core::ops::{Deref, DerefMut}; use core::option::Option; use core::ptr::Unique; use core::raw::TraitObject; -use core::result::Result; use core::result::Result::{Ok, Err}; -use core::ops::{Deref, DerefMut}; +use core::result::Result; /// A value that represents the global exchange heap. This is the default /// place that the `box` keyword allocates into when no place is supplied. @@ -156,20 +157,22 @@ fn downcast(self) -> Result, Box> { } } -impl fmt::Show for Box { +#[stable] +impl fmt::Display for Box { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Box({:?})", &**self) + fmt::Display::fmt(&**self, f) } } #[stable] -impl fmt::String for Box { +impl fmt::Debug for Box { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(&**self, f) + fmt::Debug::fmt(&**self, f) } } -impl fmt::Show for Box { +#[stable] +impl fmt::Debug for Box { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad("Box") } @@ -187,6 +190,12 @@ impl DerefMut for Box { fn deref_mut(&mut self) -> &mut T { &mut **self } } +impl<'a, E: Error + 'a> FromError for Box { + fn from_error(err: E) -> Box { + Box::new(err) + } +} + #[cfg(test)] mod test { #[test] diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 7191a7af346..9a4221699b1 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -693,17 +693,17 @@ fn hash(&self, state: &mut S) { } } -#[unstable = "Show is experimental."] -impl fmt::Show for Rc { +#[stable] +impl fmt::Display for Rc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Rc({:?})", **self) + fmt::Display::fmt(&**self, f) } } #[stable] -impl fmt::String for Rc { +impl fmt::Debug for Rc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(&**self, f) + fmt::Debug::fmt(&**self, f) } } @@ -890,8 +890,8 @@ fn clone(&self) -> Weak { } } -#[unstable = "Show is experimental."] -impl fmt::Show for Weak { +#[stable] +impl fmt::Debug for Weak { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "(Weak)") } @@ -1134,7 +1134,7 @@ fn test_cowrc_clone_weak() { #[test] fn test_show() { let foo = Rc::new(75u); - assert!(format!("{:?}", foo) == "Rc(75u)") + assert_eq!(format!("{:?}", foo), "75"); } } diff --git a/src/libcollections/bit.rs b/src/libcollections/bit.rs index efd056b0d66..605828567b3 100644 --- a/src/libcollections/bit.rs +++ b/src/libcollections/bit.rs @@ -972,7 +972,7 @@ fn cmp(&self, other: &Bitv) -> Ordering { } #[stable] -impl fmt::Show for Bitv { +impl fmt::Debug for Bitv { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { for bit in self.iter() { try!(write!(fmt, "{}", if bit { 1u32 } else { 0u32 })); @@ -1727,7 +1727,7 @@ pub fn remove(&mut self, value: &uint) -> bool { } } -impl fmt::Show for BitvSet { +impl fmt::Debug for BitvSet { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "BitvSet {{")); let mut first = true; @@ -2622,7 +2622,7 @@ fn test_bitv_set_show() { s.insert(10); s.insert(50); s.insert(2); - assert_eq!("BitvSet {1u, 2u, 10u, 50u}", format!("{:?}", s)); + assert_eq!("BitvSet {1, 2, 10, 50}", format!("{:?}", s)); } #[test] diff --git a/src/libcollections/btree/map.rs b/src/libcollections/btree/map.rs index c56592177b4..8c2f00a5695 100644 --- a/src/libcollections/btree/map.rs +++ b/src/libcollections/btree/map.rs @@ -22,7 +22,7 @@ use core::borrow::BorrowFrom; use core::cmp::Ordering; use core::default::Default; -use core::fmt::Show; +use core::fmt::Debug; use core::hash::{Hash, Hasher}; use core::iter::{Map, FromIterator}; use core::ops::{Index, IndexMut}; @@ -871,7 +871,7 @@ fn cmp(&self, other: &BTreeMap) -> Ordering { } #[stable] -impl Show for BTreeMap { +impl Debug for BTreeMap { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "BTreeMap {{")); diff --git a/src/libcollections/btree/set.rs b/src/libcollections/btree/set.rs index 4d71f9dbea8..5966c11be1b 100644 --- a/src/libcollections/btree/set.rs +++ b/src/libcollections/btree/set.rs @@ -16,7 +16,7 @@ use core::borrow::BorrowFrom; use core::cmp::Ordering::{self, Less, Greater, Equal}; use core::default::Default; -use core::fmt::Show; +use core::fmt::Debug; use core::fmt; // NOTE(stage0) remove import after a snapshot #[cfg(stage0)] @@ -592,7 +592,7 @@ fn bitor(self, rhs: &BTreeSet) -> BTreeSet { } #[stable] -impl Show for BTreeSet { +impl Debug for BTreeSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "BTreeSet {{")); @@ -892,7 +892,7 @@ fn test_show() { let set_str = format!("{:?}", set); - assert_eq!(set_str, "BTreeSet {1i, 2i}"); + assert_eq!(set_str, "BTreeSet {1, 2}"); assert_eq!(format!("{:?}", empty), "BTreeSet {}"); } } diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index cce8cf398e1..73fd806c907 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -874,7 +874,7 @@ fn clone(&self) -> DList { } #[stable] -impl fmt::Show for DList { +impl fmt::Debug for DList { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "DList [")); @@ -1333,7 +1333,7 @@ fn test_fuzz() { #[test] fn test_show() { let list: DList = range(0i, 10).collect(); - assert_eq!(format!("{:?}", list), "DList [0i, 1i, 2i, 3i, 4i, 5i, 6i, 7i, 8i, 9i]"); + assert_eq!(format!("{:?}", list), "DList [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); let list: DList<&str> = vec!["just", "one", "test", "more"].iter() .map(|&s| s) diff --git a/src/libcollections/enum_set.rs b/src/libcollections/enum_set.rs index 1b852d0ba68..a40a590c51a 100644 --- a/src/libcollections/enum_set.rs +++ b/src/libcollections/enum_set.rs @@ -31,7 +31,7 @@ pub struct EnumSet { impl Copy for EnumSet {} -impl fmt::Show for EnumSet { +impl fmt::Debug for EnumSet { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "EnumSet {{")); let mut first = true; diff --git a/src/libcollections/ring_buf.rs b/src/libcollections/ring_buf.rs index b9cb4be7c18..badd7a8d6cc 100644 --- a/src/libcollections/ring_buf.rs +++ b/src/libcollections/ring_buf.rs @@ -1611,7 +1611,7 @@ fn extend>(&mut self, mut iterator: T) { } #[stable] -impl fmt::Show for RingBuf { +impl fmt::Debug for RingBuf { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "RingBuf [")); @@ -1630,7 +1630,7 @@ mod tests { use self::Taggypar::*; use prelude::*; use core::iter; - use std::fmt::Show; + use std::fmt::Debug; use std::hash::{self, SipHasher}; use test::Bencher; use test; @@ -1678,7 +1678,7 @@ fn test_simple() { } #[cfg(test)] - fn test_parameterized(a: T, b: T, c: T, d: T) { + fn test_parameterized(a: T, b: T, c: T, d: T) { let mut deq = RingBuf::new(); assert_eq!(deq.len(), 0); deq.push_front(a.clone()); @@ -2302,7 +2302,7 @@ fn test_ord() { #[test] fn test_show() { let ringbuf: RingBuf = range(0i, 10).collect(); - assert_eq!(format!("{:?}", ringbuf), "RingBuf [0i, 1i, 2i, 3i, 4i, 5i, 6i, 7i, 8i, 9i]"); + assert_eq!(format!("{:?}", ringbuf), "RingBuf [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter() .map(|&s| s) diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 988ec4c661f..82966727037 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -2476,19 +2476,19 @@ macro_rules! test_show_vec { } let empty: Vec = vec![]; test_show_vec!(empty, "[]"); - test_show_vec!(vec![1i], "[1i]"); - test_show_vec!(vec![1i, 2, 3], "[1i, 2i, 3i]"); + test_show_vec!(vec![1i], "[1]"); + test_show_vec!(vec![1i, 2, 3], "[1, 2, 3]"); test_show_vec!(vec![vec![], vec![1u], vec![1u, 1u]], - "[[], [1u], [1u, 1u]]"); + "[[], [1], [1, 1]]"); let empty_mut: &mut [int] = &mut[]; test_show_vec!(empty_mut, "[]"); let v: &mut[int] = &mut[1]; - test_show_vec!(v, "[1i]"); + test_show_vec!(v, "[1]"); let v: &mut[int] = &mut[1, 2, 3]; - test_show_vec!(v, "[1i, 2i, 3i]"); + test_show_vec!(v, "[1, 2, 3]"); let v: &mut [&mut[uint]] = &mut[&mut[], &mut[1u], &mut[1u, 1u]]; - test_show_vec!(v, "[[], [1u], [1u, 1u]]"); + test_show_vec!(v, "[[], [1], [1, 1]]"); } #[test] diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 5d35d8a8679..e6f438ecded 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -18,6 +18,7 @@ use core::borrow::{Cow, IntoCow}; use core::default::Default; +use core::error::Error; use core::fmt; use core::hash; use core::iter::FromIterator; @@ -40,6 +41,7 @@ pub struct String { /// A possible error value from the `String::from_utf8` function. #[stable] +#[derive(Show)] pub struct FromUtf8Error { bytes: Vec, error: Utf8Error, @@ -48,6 +50,7 @@ pub struct FromUtf8Error { /// A possible error value from the `String::from_utf16` function. #[stable] #[allow(missing_copy_implementations)] +#[derive(Show)] pub struct FromUtf16Error(()); impl String { @@ -680,30 +683,28 @@ pub fn into_bytes(self) -> Vec { self.bytes } pub fn utf8_error(&self) -> Utf8Error { self.error } } -impl fmt::Show for FromUtf8Error { +#[stable] +impl fmt::Display for FromUtf8Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Display::fmt(&self.error, f) } } #[stable] -impl fmt::String for FromUtf8Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(&self.error, f) - } +impl Error for FromUtf8Error { + fn description(&self) -> &str { "invalid utf-8" } } -impl fmt::Show for FromUtf16Error { +#[stable] +impl fmt::Display for FromUtf16Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Display::fmt("invalid utf-16: lone surrogate found", f) } } #[stable] -impl fmt::String for FromUtf16Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt("invalid utf-16: lone surrogate found", f) - } +impl Error for FromUtf16Error { + fn description(&self) -> &str { "invalid utf-16" } } #[stable] @@ -814,18 +815,18 @@ fn default() -> String { } #[stable] -impl fmt::String for String { +impl fmt::Display for String { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(&**self, f) + fmt::Display::fmt(&**self, f) } } -#[unstable = "waiting on fmt stabilization"] -impl fmt::Show for String { +#[stable] +impl fmt::Debug for String { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(&**self, f) + fmt::Debug::fmt(&**self, f) } } @@ -934,7 +935,7 @@ pub trait ToString { fn to_string(&self) -> String; } -impl ToString for T { +impl ToString for T { #[inline] fn to_string(&self) -> String { use core::fmt::Writer; @@ -1295,10 +1296,10 @@ fn test_simple_types() { fn test_vectors() { let x: Vec = vec![]; assert_eq!(format!("{:?}", x), "[]"); - assert_eq!(format!("{:?}", vec![1i]), "[1i]"); - assert_eq!(format!("{:?}", vec![1i, 2, 3]), "[1i, 2i, 3i]"); + assert_eq!(format!("{:?}", vec![1i]), "[1]"); + assert_eq!(format!("{:?}", vec![1i, 2, 3]), "[1, 2, 3]"); assert!(format!("{:?}", vec![vec![], vec![1i], vec![1i, 1]]) == - "[[], [1i], [1i, 1i]]"); + "[[], [1], [1, 1]]"); } #[test] diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 4ddab8c533a..0b20a3a5f75 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -1486,10 +1486,10 @@ fn default() -> Vec { } } -#[unstable = "waiting on Show stability"] -impl fmt::Show for Vec { +#[stable] +impl fmt::Debug for Vec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(self.as_slice(), f) + fmt::Debug::fmt(self.as_slice(), f) } } diff --git a/src/libcollections/vec_map.rs b/src/libcollections/vec_map.rs index 7ff2e953588..f178d5bc7e9 100644 --- a/src/libcollections/vec_map.rs +++ b/src/libcollections/vec_map.rs @@ -513,7 +513,7 @@ fn cmp(&self, other: &VecMap) -> Ordering { } #[stable] -impl fmt::Show for VecMap { +impl fmt::Debug for VecMap { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "VecMap {{")); @@ -990,7 +990,7 @@ fn test_show() { map.insert(3, 4i); let map_str = format!("{:?}", map); - assert!(map_str == "VecMap {1: 2i, 3: 4i}" || map_str == "{3: 4i, 1: 2i}"); + assert!(map_str == "VecMap {1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}"); assert_eq!(format!("{:?}", empty), "VecMap {}"); } diff --git a/src/libcore/any.rs b/src/libcore/any.rs index 20ed2253861..6e9d2f349bf 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -34,11 +34,11 @@ //! use runtime reflection instead. //! //! ```rust -//! use std::fmt::Show; +//! use std::fmt::Debug; //! use std::any::Any; //! -//! // Logger function for any type that implements Show. -//! fn log(value: &T) { +//! // Logger function for any type that implements Debug. +//! fn log(value: &T) { //! let value_any = value as &Any; //! //! // try to convert our value to a String. If successful, we want to @@ -55,7 +55,7 @@ //! } //! //! // This function wants to log its parameter out prior to doing work with it. -//! fn do_work(value: &T) { +//! fn do_work(value: &T) { //! log(value); //! // ...do some other work //! } diff --git a/src/libcore/array.rs b/src/libcore/array.rs index 0cc31bf70de..a83537e12f7 100644 --- a/src/libcore/array.rs +++ b/src/libcore/array.rs @@ -39,10 +39,10 @@ fn hash(&self, state: &mut S) { } } - #[unstable = "waiting for Show to stabilize"] - impl fmt::Show for [T; $N] { + #[stable] + impl fmt::Debug for [T; $N] { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(&&self[], f) + fmt::Debug::fmt(&&self[], f) } } diff --git a/src/libcore/borrow.rs b/src/libcore/borrow.rs index 4363a0a4441..63614aaa463 100644 --- a/src/libcore/borrow.rs +++ b/src/libcore/borrow.rs @@ -133,7 +133,6 @@ fn to_owned(&self) -> T { self.clone() } /// } /// } /// ``` -#[derive(Show)] pub enum Cow<'a, T, B: ?Sized + 'a> where B: ToOwned { /// Borrowed data. Borrowed(&'a B), @@ -239,14 +238,27 @@ fn partial_cmp(&self, other: &Cow<'a, T, B>) -> Option { } #[stable] -impl<'a, T, B: ?Sized> fmt::String for Cow<'a, T, B> where - B: fmt::String + ToOwned, - T: fmt::String, +impl<'a, T, B: ?Sized> fmt::Debug for Cow<'a, T, B> where + B: fmt::Debug + ToOwned, + T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Borrowed(ref b) => fmt::String::fmt(b, f), - Owned(ref o) => fmt::String::fmt(o, f), + Borrowed(ref b) => fmt::Debug::fmt(b, f), + Owned(ref o) => fmt::Debug::fmt(o, f), + } + } +} + +#[stable] +impl<'a, T, B: ?Sized> fmt::Display for Cow<'a, T, B> where + B: fmt::Display + ToOwned, + T: fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Borrowed(ref b) => fmt::Display::fmt(b, f), + Owned(ref o) => fmt::Display::fmt(o, f), } } } diff --git a/src/libstd/error.rs b/src/libcore/error.rs similarity index 77% rename from src/libstd/error.rs rename to src/libcore/error.rs index ff128461978..9ff38028df9 100644 --- a/src/libstd/error.rs +++ b/src/libcore/error.rs @@ -14,14 +14,15 @@ //! //! `Error` is a trait representing the basic expectations for error values, //! i.e. values of type `E` in `Result`. At a minimum, errors must provide -//! a description, but they may optionally provide additional detail and cause -//! chain information: +//! a description, but they may optionally provide additional detail (via +//! `Display`) and cause chain information: //! //! ``` -//! trait Error { +//! use std::fmt::Display; +//! +//! trait Error: Display { //! fn description(&self) -> &str; //! -//! fn detail(&self) -> Option { None } //! fn cause(&self) -> Option<&Error> { None } //! } //! ``` @@ -80,20 +81,15 @@ #![stable] -use prelude::v1::*; - -use str::Utf8Error; -use string::{FromUtf8Error, FromUtf16Error}; +use prelude::*; +use fmt::Display; /// Base functionality for all errors in Rust. #[unstable = "the exact API of this trait may change"] -pub trait Error { +pub trait Error: Display { /// A short description of the error; usually a static string. fn description(&self) -> &str; - /// A detailed description of the error, usually including dynamic information. - fn detail(&self) -> Option { None } - /// The lower-level cause of this error, if any. fn cause(&self) -> Option<&Error> { None } } @@ -112,26 +108,3 @@ fn from_error(err: E) -> E { err } } - -#[stable] -impl Error for Utf8Error { - fn description(&self) -> &str { - match *self { - Utf8Error::TooShort => "invalid utf-8: not enough bytes", - Utf8Error::InvalidByte(..) => "invalid utf-8: corrupt contents", - } - } - - fn detail(&self) -> Option { Some(self.to_string()) } -} - -#[stable] -impl Error for FromUtf8Error { - fn description(&self) -> &str { "invalid utf-8" } - fn detail(&self) -> Option { Some(self.to_string()) } -} - -#[stable] -impl Error for FromUtf16Error { - fn description(&self) -> &str { "invalid utf-16" } -} diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index 535722f93bf..0e8d31a62ee 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -26,12 +26,15 @@ use result; use slice::SliceExt; use slice; -use str::{self, StrExt, Utf8Error}; +use str::{self, StrExt}; pub use self::num::radix; pub use self::num::Radix; pub use self::num::RadixFmt; +#[cfg(stage0)] pub use self::Debug as Show; +#[cfg(stage0)] pub use self::Display as String; + mod num; mod float; pub mod rt; @@ -46,7 +49,7 @@ /// occurred. Any extra information must be arranged to be transmitted through /// some other means. #[unstable = "core and I/O reconciliation may alter this definition"] -#[derive(Copy)] +#[derive(Copy, Show)] pub struct Error; /// A collection of methods that are required to format a message into a stream. @@ -133,7 +136,7 @@ pub struct Argument<'a> { impl<'a> Argument<'a> { #[inline(never)] fn show_uint(x: &uint, f: &mut Formatter) -> Result { - Show::fmt(x, f) + Display::fmt(x, f) } fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter) -> Result) -> Argument<'b> { @@ -214,14 +217,15 @@ pub struct Arguments<'a> { args: &'a [Argument<'a>], } -impl<'a> Show for Arguments<'a> { +#[stable] +impl<'a> Debug for Arguments<'a> { fn fmt(&self, fmt: &mut Formatter) -> Result { - String::fmt(self, fmt) + Display::fmt(self, fmt) } } #[stable] -impl<'a> String for Arguments<'a> { +impl<'a> Display for Arguments<'a> { fn fmt(&self, fmt: &mut Formatter) -> Result { write(fmt.buf, *self) } @@ -229,20 +233,49 @@ fn fmt(&self, fmt: &mut Formatter) -> Result { /// Format trait for the `:?` format. Useful for debugging, most all types /// should implement this. -#[unstable = "I/O and core have yet to be reconciled"] +#[deprecated = "renamed to Debug"] +#[cfg(not(stage0))] pub trait Show { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } +/// Format trait for the `:?` format. Useful for debugging, most all types +/// should implement this. +#[unstable = "I/O and core have yet to be reconciled"] +pub trait Debug { + /// Formats the value using the given formatter. + fn fmt(&self, &mut Formatter) -> Result; +} + +#[cfg(not(stage0))] +impl Debug for T { + #[allow(deprecated)] + fn fmt(&self, f: &mut Formatter) -> Result { Show::fmt(self, f) } +} + +/// When a value can be semantically expressed as a String, this trait may be +/// used. It corresponds to the default format, `{}`. +#[deprecated = "renamed to Display"] +#[cfg(not(stage0))] +pub trait String { + /// Formats the value using the given formatter. + fn fmt(&self, &mut Formatter) -> Result; +} + /// When a value can be semantically expressed as a String, this trait may be /// used. It corresponds to the default format, `{}`. #[unstable = "I/O and core have yet to be reconciled"] -pub trait String { +pub trait Display { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } +#[cfg(not(stage0))] +impl Display for T { + #[allow(deprecated)] + fn fmt(&self, f: &mut Formatter) -> Result { String::fmt(self, f) } +} /// Format trait for the `o` character #[unstable = "I/O and core have yet to be reconciled"] @@ -583,9 +616,10 @@ pub fn width(&self) -> Option { self.width } pub fn precision(&self) -> Option { self.precision } } -impl Show for Error { +#[stable] +impl Display for Error { fn fmt(&self, f: &mut Formatter) -> Result { - String::fmt("an error occurred when formatting an argument", f) + Display::fmt("an error occurred when formatting an argument", f) } } @@ -611,9 +645,11 @@ pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> { macro_rules! fmt_refs { ($($tr:ident),*) => { $( + #[stable] impl<'a, T: ?Sized + $tr> $tr for &'a T { fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) } } + #[stable] impl<'a, T: ?Sized + $tr> $tr for &'a mut T { fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) } } @@ -621,22 +657,24 @@ fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) } } } -fmt_refs! { Show, String, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp } +fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp } -impl Show for bool { +#[stable] +impl Debug for bool { fn fmt(&self, f: &mut Formatter) -> Result { - String::fmt(self, f) + Display::fmt(self, f) } } #[stable] -impl String for bool { +impl Display for bool { fn fmt(&self, f: &mut Formatter) -> Result { - String::fmt(if *self { "true" } else { "false" }, f) + Display::fmt(if *self { "true" } else { "false" }, f) } } -impl Show for str { +#[stable] +impl Debug for str { fn fmt(&self, f: &mut Formatter) -> Result { try!(write!(f, "\"")); for c in self.chars().flat_map(|c| c.escape_default()) { @@ -647,13 +685,14 @@ fn fmt(&self, f: &mut Formatter) -> Result { } #[stable] -impl String for str { +impl Display for str { fn fmt(&self, f: &mut Formatter) -> Result { f.pad(self) } } -impl Show for char { +#[stable] +impl Debug for char { fn fmt(&self, f: &mut Formatter) -> Result { use char::CharExt; try!(write!(f, "'")); @@ -665,15 +704,16 @@ fn fmt(&self, f: &mut Formatter) -> Result { } #[stable] -impl String for char { +impl Display for char { fn fmt(&self, f: &mut Formatter) -> Result { let mut utf8 = [0u8; 4]; let amt = self.encode_utf8(&mut utf8).unwrap_or(0); let s: &str = unsafe { mem::transmute(&utf8[..amt]) }; - String::fmt(s, f) + Display::fmt(s, f) } } +#[stable] impl Pointer for *const T { fn fmt(&self, f: &mut Formatter) -> Result { f.flags |= 1 << (rt::FlagAlternate as uint); @@ -683,18 +723,21 @@ fn fmt(&self, f: &mut Formatter) -> Result { } } +#[stable] impl Pointer for *mut T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(&(*self as *const T), f) } } +#[stable] impl<'a, T> Pointer for &'a T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(&(*self as *const T), f) } } +#[stable] impl<'a, T> Pointer for &'a mut T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(&(&**self as *const T), f) @@ -703,15 +746,15 @@ fn fmt(&self, f: &mut Formatter) -> Result { macro_rules! floating { ($ty:ident) => { - impl Show for $ty { + #[stable] + impl Debug for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { - try!(String::fmt(self, fmt)); - fmt.write_str(stringify!($ty)) + Display::fmt(self, fmt) } } #[stable] - impl String for $ty { + impl Display for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; @@ -732,6 +775,7 @@ fn fmt(&self, fmt: &mut Formatter) -> Result { } } + #[stable] impl LowerExp for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; @@ -753,6 +797,7 @@ fn fmt(&self, fmt: &mut Formatter) -> Result { } } + #[stable] impl UpperExp for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; @@ -777,12 +822,14 @@ fn fmt(&self, fmt: &mut Formatter) -> Result { floating! { f32 } floating! { f64 } -// Implementation of Show for various core types +// Implementation of Display/Debug for various core types -impl Show for *const T { +#[stable] +impl Debug for *const T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } } -impl Show for *mut T { +#[stable] +impl Debug for *mut T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } } @@ -793,7 +840,8 @@ macro_rules! peel { macro_rules! tuple { () => (); ( $($name:ident,)+ ) => ( - impl<$($name:Show),*> Show for ($($name,)*) { + #[stable] + impl<$($name:Debug),*> Debug for ($($name,)*) { #[allow(non_snake_case, unused_assignments)] fn fmt(&self, f: &mut Formatter) -> Result { try!(write!(f, "(")); @@ -818,11 +866,13 @@ fn fmt(&self, f: &mut Formatter) -> Result { tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, } -impl<'a> Show for &'a (any::Any+'a) { +#[stable] +impl<'a> Debug for &'a (any::Any+'a) { fn fmt(&self, f: &mut Formatter) -> Result { f.pad("&Any") } } -impl Show for [T] { +#[stable] +impl Debug for [T] { fn fmt(&self, f: &mut Formatter) -> Result { if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 { try!(write!(f, "[")); @@ -843,20 +893,22 @@ fn fmt(&self, f: &mut Formatter) -> Result { } } -impl Show for () { +#[stable] +impl Debug for () { fn fmt(&self, f: &mut Formatter) -> Result { f.pad("()") } } -impl Show for Cell { +#[stable] +impl Debug for Cell { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "Cell {{ value: {:?} }}", self.get()) } } -#[unstable] -impl Show for RefCell { +#[stable] +impl Debug for RefCell { fn fmt(&self, f: &mut Formatter) -> Result { match self.try_borrow() { Some(val) => write!(f, "RefCell {{ value: {:?} }}", val), @@ -865,29 +917,17 @@ fn fmt(&self, f: &mut Formatter) -> Result { } } -impl<'b, T: Show> Show for Ref<'b, T> { +#[stable] +impl<'b, T: Debug> Debug for Ref<'b, T> { fn fmt(&self, f: &mut Formatter) -> Result { - Show::fmt(&**self, f) - } -} - -impl<'b, T: Show> Show for RefMut<'b, T> { - fn fmt(&self, f: &mut Formatter) -> Result { - Show::fmt(&*(self.deref()), f) + Debug::fmt(&**self, f) } } #[stable] -impl String for Utf8Error { +impl<'b, T: Debug> Debug for RefMut<'b, T> { fn fmt(&self, f: &mut Formatter) -> Result { - match *self { - Utf8Error::InvalidByte(n) => { - write!(f, "invalid utf-8: invalid byte at index {}", n) - } - Utf8Error::TooShort => { - write!(f, "invalid utf-8: byte slice too short") - } - } + Debug::fmt(&*(self.deref()), f) } } diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs index 1df6f845225..c456b3379e8 100644 --- a/src/libcore/fmt/num.rs +++ b/src/libcore/fmt/num.rs @@ -154,13 +154,14 @@ pub fn radix(x: T, base: u8) -> RadixFmt { macro_rules! radix_fmt { ($T:ty as $U:ty, $fmt:ident, $S:expr) => { - impl fmt::Show for RadixFmt<$T, Radix> { + #[stable] + impl fmt::Debug for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(fmt::String::fmt(self, f)); - f.write_str($S) + fmt::Display::fmt(self, f) } } - impl fmt::String for RadixFmt<$T, Radix> { + #[stable] + impl fmt::Display for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) } } @@ -169,6 +170,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } macro_rules! int_base { ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => { + #[stable] impl fmt::$Trait for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { $Radix.fmt_int(*self as $U, f) @@ -179,10 +181,10 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { macro_rules! show { ($T:ident with $S:expr) => { - impl fmt::Show for $T { + #[stable] + impl fmt::Debug for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(fmt::String::fmt(self, f)); - f.write_str($S) + fmt::Display::fmt(self, f) } } } @@ -192,7 +194,7 @@ macro_rules! integer { integer! { $Int, $Uint, stringify!($Int), stringify!($Uint) } }; ($Int:ident, $Uint:ident, $SI:expr, $SU:expr) => { - int_base! { String for $Int as $Int -> Decimal } + int_base! { Display for $Int as $Int -> Decimal } int_base! { Binary for $Int as $Uint -> Binary } int_base! { Octal for $Int as $Uint -> Octal } int_base! { LowerHex for $Int as $Uint -> LowerHex } @@ -200,7 +202,7 @@ macro_rules! integer { radix_fmt! { $Int as $Int, fmt_int, $SI } show! { $Int with $SI } - int_base! { String for $Uint as $Uint -> Decimal } + int_base! { Display for $Uint as $Uint -> Decimal } int_base! { Binary for $Uint as $Uint -> Binary } int_base! { Octal for $Uint as $Uint -> Octal } int_base! { LowerHex for $Uint as $Uint -> LowerHex } diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 0b150d1ecf9..bbe5cfe1cbb 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -136,6 +136,7 @@ pub mod str; pub mod hash; pub mod fmt; +pub mod error; // note: does not need to be public mod tuple; diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 7131253d5c4..853e4adb892 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -885,10 +885,10 @@ pub trait IndexMut { #[unstable = "API still in development"] pub struct FullRange; -#[unstable = "API still in development"] -impl fmt::Show for FullRange { +#[stable] +impl fmt::Debug for FullRange { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt("..", fmt) + fmt::Debug::fmt("..", fmt) } } @@ -944,8 +944,8 @@ fn next_back(&mut self) -> Option { #[unstable = "API still in development"] impl ExactSizeIterator for Range {} -#[unstable = "API still in development"] -impl fmt::Show for Range { +#[stable] +impl fmt::Debug for Range { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{:?}..{:?}", self.start, self.end) } @@ -973,8 +973,8 @@ fn next(&mut self) -> Option { } } -#[unstable = "API still in development"] -impl fmt::Show for RangeFrom { +#[stable] +impl fmt::Debug for RangeFrom { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{:?}..", self.start) } @@ -989,8 +989,8 @@ pub struct RangeTo { pub end: Idx, } -#[unstable = "API still in development"] -impl fmt::Show for RangeTo { +#[stable] +impl fmt::Debug for RangeTo { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "..{:?}", self.end) } diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 1ab810f937d..c3d49e24978 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -229,7 +229,7 @@ use self::Result::{Ok, Err}; use clone::Clone; -use fmt::Show; +use fmt::Display; use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, ExactSizeIterator}; use ops::{FnMut, FnOnce}; use option::Option::{self, None, Some}; @@ -714,7 +714,7 @@ pub fn unwrap_or_else T>(self, op: F) -> T { } #[stable] -impl Result { +impl Result { /// Unwraps a result, yielding the content of an `Ok`. /// /// # Panics @@ -739,13 +739,13 @@ pub fn unwrap(self) -> T { match self { Ok(t) => t, Err(e) => - panic!("called `Result::unwrap()` on an `Err` value: {:?}", e) + panic!("called `Result::unwrap()` on an `Err` value: {}", e) } } } #[stable] -impl Result { +impl Result { /// Unwraps a result, yielding the content of an `Err`. /// /// # Panics @@ -769,7 +769,7 @@ impl Result { pub fn unwrap_err(self) -> E { match self { Ok(t) => - panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t), + panic!("called `Result::unwrap_err()` on an `Ok` value: {}", t), Err(e) => e } } diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 6a542b2c458..f8bd48220ba 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -20,8 +20,10 @@ use cmp::{self, Eq}; use default::Default; -use iter::range; +use error::Error; +use fmt; use iter::ExactSizeIterator; +use iter::range; use iter::{Map, Iterator, IteratorExt, DoubleEndedIterator}; use marker::Sized; use mem; @@ -242,6 +244,30 @@ fn only_ascii(&self) -> bool { } } +#[stable] +impl Error for Utf8Error { + fn description(&self) -> &str { + match *self { + Utf8Error::TooShort => "invalid utf-8: not enough bytes", + Utf8Error::InvalidByte(..) => "invalid utf-8: corrupt contents", + } + } +} + +#[stable] +impl fmt::Display for Utf8Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Utf8Error::InvalidByte(n) => { + write!(f, "invalid utf-8: invalid byte at index {}", n) + } + Utf8Error::TooShort => { + write!(f, "invalid utf-8: byte slice too short") + } + } + } +} + /* Section: Iterators */ diff --git a/src/libcoretest/finally.rs b/src/libcoretest/finally.rs index 979ddaecb4a..6ec87203e00 100644 --- a/src/libcoretest/finally.rs +++ b/src/libcoretest/finally.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(deprecated)] + use core::finally::{try_finally, Finally}; use std::thread::Thread; diff --git a/src/libcoretest/fmt/num.rs b/src/libcoretest/fmt/num.rs index c259e4cbb68..eb278d2cc90 100644 --- a/src/libcoretest/fmt/num.rs +++ b/src/libcoretest/fmt/num.rs @@ -26,11 +26,11 @@ fn test_format_int() { assert!(format!("{}", -1i16) == "-1"); assert!(format!("{}", -1i32) == "-1"); assert!(format!("{}", -1i64) == "-1"); - assert!(format!("{:?}", 1i) == "1i"); - assert!(format!("{:?}", 1i8) == "1i8"); - assert!(format!("{:?}", 1i16) == "1i16"); - assert!(format!("{:?}", 1i32) == "1i32"); - assert!(format!("{:?}", 1i64) == "1i64"); + assert!(format!("{:?}", 1i) == "1"); + assert!(format!("{:?}", 1i8) == "1"); + assert!(format!("{:?}", 1i16) == "1"); + assert!(format!("{:?}", 1i32) == "1"); + assert!(format!("{:?}", 1i64) == "1"); assert!(format!("{:b}", 1i) == "1"); assert!(format!("{:b}", 1i8) == "1"); assert!(format!("{:b}", 1i16) == "1"); @@ -57,11 +57,11 @@ fn test_format_int() { assert!(format!("{}", 1u16) == "1"); assert!(format!("{}", 1u32) == "1"); assert!(format!("{}", 1u64) == "1"); - assert!(format!("{:?}", 1u) == "1u"); - assert!(format!("{:?}", 1u8) == "1u8"); - assert!(format!("{:?}", 1u16) == "1u16"); - assert!(format!("{:?}", 1u32) == "1u32"); - assert!(format!("{:?}", 1u64) == "1u64"); + assert!(format!("{:?}", 1u) == "1"); + assert!(format!("{:?}", 1u8) == "1"); + assert!(format!("{:?}", 1u16) == "1"); + assert!(format!("{:?}", 1u32) == "1"); + assert!(format!("{:?}", 1u64) == "1"); assert!(format!("{:b}", 1u) == "1"); assert!(format!("{:b}", 1u8) == "1"); assert!(format!("{:b}", 1u16) == "1"); @@ -94,14 +94,14 @@ fn test_format_int() { #[test] fn test_format_int_zero() { assert!(format!("{}", 0i) == "0"); - assert!(format!("{:?}", 0i) == "0i"); + assert!(format!("{:?}", 0i) == "0"); assert!(format!("{:b}", 0i) == "0"); assert!(format!("{:o}", 0i) == "0"); assert!(format!("{:x}", 0i) == "0"); assert!(format!("{:X}", 0i) == "0"); assert!(format!("{}", 0u) == "0"); - assert!(format!("{:?}", 0u) == "0u"); + assert!(format!("{:?}", 0u) == "0"); assert!(format!("{:b}", 0u) == "0"); assert!(format!("{:o}", 0u) == "0"); assert!(format!("{:x}", 0u) == "0"); diff --git a/src/libcoretest/num/mod.rs b/src/libcoretest/num/mod.rs index 8186a4f0904..e0623bade5c 100644 --- a/src/libcoretest/num/mod.rs +++ b/src/libcoretest/num/mod.rs @@ -9,7 +9,7 @@ // except according to those terms. use core::cmp::PartialEq; -use core::fmt::Show; +use core::fmt::Debug; use core::num::{NumCast, cast}; use core::ops::{Add, Sub, Mul, Div, Rem}; use core::marker::Copy; @@ -37,7 +37,7 @@ pub fn test_num(ten: T, two: T) where T: PartialEq + NumCast + Add + Sub + Mul + Div - + Rem + Show + + Rem + Debug + Copy { assert_eq!(ten.add(two), cast(12i).unwrap()); diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs index 485549cc552..daccb709890 100644 --- a/src/libcoretest/result.rs +++ b/src/libcoretest/result.rs @@ -14,11 +14,11 @@ pub fn op2() -> Result { Err("sadface") } #[test] pub fn test_and() { assert_eq!(op1().and(Ok(667i)).unwrap(), 667); - assert_eq!(op1().and(Err::<(), &'static str>("bad")).unwrap_err(), + assert_eq!(op1().and(Err::("bad")).unwrap_err(), "bad"); assert_eq!(op2().and(Ok(667i)).unwrap_err(), "sadface"); - assert_eq!(op2().and(Err::<(),&'static str>("bad")).unwrap_err(), + assert_eq!(op2().and(Err::("bad")).unwrap_err(), "sadface"); } @@ -94,7 +94,7 @@ pub fn test_fmt_default() { let err: Result = Err("Err"); let s = format!("{:?}", ok); - assert_eq!(s, "Ok(100i)"); + assert_eq!(s, "Ok(100)"); let s = format!("{:?}", err); assert_eq!(s, "Err(\"Err\")"); } diff --git a/src/libcoretest/tuple.rs b/src/libcoretest/tuple.rs index 62eb9f4ad34..e524d8de056 100644 --- a/src/libcoretest/tuple.rs +++ b/src/libcoretest/tuple.rs @@ -60,9 +60,9 @@ fn test_tuple_cmp() { #[test] fn test_show() { let s = format!("{:?}", (1i,)); - assert_eq!(s, "(1i,)"); + assert_eq!(s, "(1,)"); let s = format!("{:?}", (1i, true)); - assert_eq!(s, "(1i, true)"); + assert_eq!(s, "(1, true)"); let s = format!("{:?}", (1i, "hi", true)); - assert_eq!(s, "(1i, \"hi\", true)"); + assert_eq!(s, "(1, \"hi\", true)"); } diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index c2114d4c6df..9b0b741e692 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -544,7 +544,7 @@ pub fn to_err_msg(self) -> String { } } -impl fmt::String for Fail { +impl fmt::Display for Fail { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ArgumentMissing(ref nm) => { diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index 2d7d88f0f35..0ed32b7bf4f 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -358,19 +358,19 @@ impl<'a> Id<'a> { /// /// Passing an invalid string (containing spaces, brackets, /// quotes, ...) will return an empty `Err` value. - pub fn new>(name: Name) -> Result, ()> { + pub fn new>(name: Name) -> Option> { let name = name.into_cow(); { let mut chars = name.chars(); match chars.next() { Some(c) if is_letter_or_underscore(c) => { ; }, - _ => return Err(()) + _ => return None } if !chars.all(is_constituent) { - return Err(()); + return None } } - return Ok(Id{ name: name }); + return Some(Id{ name: name }); fn is_letter_or_underscore(c: char) -> bool { in_range('a', c, 'z') || in_range('A', c, 'Z') || c == '_' @@ -874,8 +874,8 @@ fn left_aligned_text() { fn simple_id_construction() { let id1 = Id::new("hello"); match id1 { - Ok(_) => {;}, - Err(_) => panic!("'hello' is not a valid value for id anymore") + Some(_) => {;}, + None => panic!("'hello' is not a valid value for id anymore") } } @@ -883,8 +883,8 @@ fn simple_id_construction() { fn badly_formatted_id() { let id2 = Id::new("Weird { struct : ure } !!!"); match id2 { - Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"), - Err(_) => {;} + Some(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"), + None => {;} } } } diff --git a/src/libgraphviz/maybe_owned_vec.rs b/src/libgraphviz/maybe_owned_vec.rs index 567fe04c5af..4e6437a5e76 100644 --- a/src/libgraphviz/maybe_owned_vec.rs +++ b/src/libgraphviz/maybe_owned_vec.rs @@ -124,7 +124,7 @@ fn from_iter>(iterator: I) -> MaybeOwnedVector<'a,T> { } } -impl<'a,T:fmt::Show> fmt::Show for MaybeOwnedVector<'a,T> { +impl<'a,T:fmt::Debug> fmt::Debug for MaybeOwnedVector<'a,T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.as_slice().fmt(f) } diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index dbd88434127..ba0f04d67da 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -239,21 +239,15 @@ struct DefaultLogger { } /// Wraps the log level with fmt implementations. -#[derive(Copy, PartialEq, PartialOrd)] +#[derive(Copy, PartialEq, PartialOrd, Show)] pub struct LogLevel(pub u32); -impl fmt::Show for LogLevel { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, fmt) - } -} - -impl fmt::String for LogLevel { +impl fmt::Display for LogLevel { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let LogLevel(level) = *self; match LOG_LEVEL_NAMES.get(level as uint - 1) { - Some(ref name) => fmt::String::fmt(name, fmt), - None => fmt::String::fmt(&level, fmt) + Some(ref name) => fmt::Display::fmt(name, fmt), + None => fmt::Display::fmt(&level, fmt) } } } diff --git a/src/librbml/lib.rs b/src/librbml/lib.rs index 25279796c03..50fe56ff5c0 100644 --- a/src/librbml/lib.rs +++ b/src/librbml/lib.rs @@ -38,6 +38,7 @@ pub use self::Error::*; use std::str; +use std::fmt; pub mod io; @@ -113,6 +114,13 @@ pub enum Error { IoError(std::io::IoError), ApplicationError(String) } + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // FIXME: this should be a more useful display form + fmt::Debug::fmt(self, f) + } +} // -------------------------------------- pub mod reader { diff --git a/src/libregex/parse.rs b/src/libregex/parse.rs index 1cc2b271e9c..7331bc36d79 100644 --- a/src/libregex/parse.rs +++ b/src/libregex/parse.rs @@ -30,6 +30,7 @@ /// /// (Once an expression is compiled, it is not possible to produce an error /// via searching, splitting or replacing.) +#[derive(Show)] pub struct Error { /// The *approximate* character index of where the error occurred. pub pos: uint, @@ -37,7 +38,7 @@ pub struct Error { pub msg: String, } -impl fmt::Show for Error { +impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Regex syntax error near position {}: {:?}", self.pos, self.msg) diff --git a/src/libregex/re.rs b/src/libregex/re.rs index abc51d62404..a740e2043b9 100644 --- a/src/libregex/re.rs +++ b/src/libregex/re.rs @@ -90,10 +90,10 @@ fn clone(&self) -> ExNative { } } -impl fmt::String for Regex { +impl fmt::Display for Regex { /// Shows the original regular expression. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self.as_str(), f) + fmt::Display::fmt(self.as_str(), f) } } diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index a1a90395b3b..4d0cea8d7e3 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -57,7 +57,7 @@ /// ++++++++++++++++++++++++++ /// + _ + [_, _, ..tail] + /// ++++++++++++++++++++++++++ -impl<'a> fmt::Show for Matrix<'a> { +impl<'a> fmt::Debug for Matrix<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "\n")); diff --git a/src/librustc/middle/graph.rs b/src/librustc/middle/graph.rs index 30e0ce33018..affeef330c4 100644 --- a/src/librustc/middle/graph.rs +++ b/src/librustc/middle/graph.rs @@ -32,7 +32,7 @@ #![allow(dead_code)] // still WIP -use std::fmt::{Formatter, Error, Show}; +use std::fmt::{Formatter, Error, Debug}; use std::uint; use std::collections::BitvSet; @@ -53,7 +53,7 @@ pub struct Edge { pub data: E, } -impl Show for Edge { +impl Debug for Edge { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { write!(f, "Edge {{ next_edge: [{:?}, {:?}], source: {:?}, target: {:?}, data: {:?} }}", self.next_edge[0], self.next_edge[1], self.source, @@ -353,7 +353,7 @@ pub fn target(&self) -> NodeIndex { #[cfg(test)] mod test { use middle::graph::*; - use std::fmt::Show; + use std::fmt::Debug; type TestNode = Node<&'static str>; type TestEdge = Edge<&'static str>; @@ -408,7 +408,7 @@ fn each_edge() { }); } - fn test_adjacent_edges(graph: &Graph, + fn test_adjacent_edges(graph: &Graph, start_index: NodeIndex, start_data: N, expected_incoming: &[(E,N)], diff --git a/src/librustc/middle/infer/unify.rs b/src/librustc/middle/infer/unify.rs index 4fa8e07ddd4..ed11cafdca9 100644 --- a/src/librustc/middle/infer/unify.rs +++ b/src/librustc/middle/infer/unify.rs @@ -17,7 +17,7 @@ use middle::infer::{uok, ures}; use middle::infer::InferCtxt; use std::cell::RefCell; -use std::fmt::Show; +use std::fmt::Debug; use syntax::ast; use util::ppaux::Repr; use util::snapshot_vec as sv; @@ -32,7 +32,7 @@ /// (possibly not yet known) sort of integer. /// /// Implementations of this trait are at the end of this file. -pub trait UnifyKey<'tcx, V> : Clone + Show + PartialEq + Repr<'tcx> { +pub trait UnifyKey<'tcx, V> : Clone + Debug + PartialEq + Repr<'tcx> { fn index(&self) -> uint; fn from_index(u: uint) -> Self; diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 27a0324a3c4..7402bfc1efd 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -198,13 +198,13 @@ pub fn check_crate(tcx: &ty::ctxt) { tcx.sess.abort_if_errors(); } -impl fmt::Show for LiveNode { +impl fmt::Debug for LiveNode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ln({})", self.get()) } } -impl fmt::Show for Variable { +impl fmt::Debug for Variable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "v({})", self.get()) } diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index eff0018becc..7d879194067 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -602,7 +602,7 @@ fn shuffle(early_bound: &mut Vec, } } -impl<'a> fmt::Show for ScopeChain<'a> { +impl<'a> fmt::Debug for ScopeChain<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { EarlyScope(space, defs, _) => write!(fmt, "EarlyScope({:?}, {:?})", space, defs), diff --git a/src/librustc/middle/subst.rs b/src/librustc/middle/subst.rs index 9ad2dd499cc..83bb9a351e4 100644 --- a/src/librustc/middle/subst.rs +++ b/src/librustc/middle/subst.rs @@ -238,7 +238,7 @@ pub struct SeparateVecsPerParamSpace { pub fns: Vec, } -impl fmt::Show for VecPerParamSpace { +impl fmt::Debug for VecPerParamSpace { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "VecPerParamSpace {{")); for space in ParamSpace::all().iter() { diff --git a/src/librustc/middle/traits/error_reporting.rs b/src/librustc/middle/traits/error_reporting.rs index 6d0e60ec495..31f9d1bb2eb 100644 --- a/src/librustc/middle/traits/error_reporting.rs +++ b/src/librustc/middle/traits/error_reporting.rs @@ -200,7 +200,7 @@ pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, ty::Predicate::Equate(ref predicate) => { let predicate = infcx.resolve_type_vars_if_possible(predicate); let err = infcx.equality_predicate(obligation.cause.span, - &predicate).unwrap_err(); + &predicate).err().unwrap(); infcx.tcx.sess.span_err( obligation.cause.span, format!( @@ -212,7 +212,7 @@ pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, ty::Predicate::RegionOutlives(ref predicate) => { let predicate = infcx.resolve_type_vars_if_possible(predicate); let err = infcx.region_outlives_predicate(obligation.cause.span, - &predicate).unwrap_err(); + &predicate).err().unwrap(); infcx.tcx.sess.span_err( obligation.cause.span, format!( diff --git a/src/librustc/middle/traits/util.rs b/src/librustc/middle/traits/util.rs index fe8362223e3..bdf9b16f139 100644 --- a/src/librustc/middle/traits/util.rs +++ b/src/librustc/middle/traits/util.rs @@ -236,13 +236,13 @@ pub fn fresh_substs_for_impl<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, infcx.fresh_substs_for_generics(span, &impl_generics) } -impl<'tcx, N> fmt::Show for VtableImplData<'tcx, N> { +impl<'tcx, N> fmt::Debug for VtableImplData<'tcx, N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "VtableImpl({:?})", self.impl_def_id) } } -impl<'tcx> fmt::Show for super::VtableObjectData<'tcx> { +impl<'tcx> fmt::Debug for super::VtableObjectData<'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "VtableObject(...)") } @@ -449,7 +449,7 @@ fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String { } } -impl<'tcx> fmt::Show for super::FulfillmentErrorCode<'tcx> { +impl<'tcx> fmt::Debug for super::FulfillmentErrorCode<'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { super::CodeSelectionError(ref e) => write!(f, "{:?}", e), @@ -465,7 +465,7 @@ fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String { } } -impl<'tcx> fmt::Show for super::MismatchedProjectionTypes<'tcx> { +impl<'tcx> fmt::Debug for super::MismatchedProjectionTypes<'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "MismatchedProjectionTypes(..)") } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index be6c6b9d34f..8568f2c2946 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -934,7 +934,7 @@ pub struct TyS<'tcx> { region_depth: u32, } -impl fmt::Show for TypeFlags { +impl fmt::Debug for TypeFlags { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.bits) } @@ -1703,37 +1703,37 @@ fn ne(&self, other: &InferRegion) -> bool { } } -impl fmt::Show for TyVid { +impl fmt::Debug for TyVid { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{ write!(f, "_#{}t", self.index) } } -impl fmt::Show for IntVid { +impl fmt::Debug for IntVid { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "_#{}i", self.index) } } -impl fmt::Show for FloatVid { +impl fmt::Debug for FloatVid { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "_#{}f", self.index) } } -impl fmt::Show for RegionVid { +impl fmt::Debug for RegionVid { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "'_#{}r", self.index) } } -impl<'tcx> fmt::Show for FnSig<'tcx> { +impl<'tcx> fmt::Debug for FnSig<'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({:?}; variadic: {})->{:?}", self.inputs, self.variadic, self.output) } } -impl fmt::Show for InferTy { +impl fmt::Debug for InferTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { TyVar(ref v) => v.fmt(f), @@ -1745,7 +1745,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::Show for IntVarValue { +impl fmt::Debug for IntVarValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { IntType(ref v) => v.fmt(f), @@ -3319,7 +3319,7 @@ fn sub(self, other: TypeContents) -> TypeContents { } } -impl fmt::Show for TypeContents { +impl fmt::Debug for TypeContents { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "TypeContents({:b})", self.bits) } diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index d9bb1d769bf..ac0019fe1f5 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -249,7 +249,7 @@ pub enum EntryFnType { EntryNone, } -#[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash)] +#[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Show)] pub enum CrateType { CrateTypeExecutable, CrateTypeDylib, @@ -1159,7 +1159,7 @@ pub fn parse_crate_types_from_list(list_list: Vec) -> Result fmt::Result { match *self { CrateTypeExecutable => "bin".fmt(f), diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index c505e9e3112..8915d55e206 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -12,7 +12,7 @@ use std::cell::{RefCell, Cell}; use std::collections::HashMap; -use std::fmt::Show; +use std::fmt::Debug; use std::hash::{Hash, Hasher}; use std::iter::repeat; use std::time::Duration; @@ -58,7 +58,7 @@ pub fn time(do_it: bool, what: &str, u: U, f: F) -> T where } pub fn indent(op: F) -> R where - R: Show, + R: Debug, F: FnOnce() -> R, { // Use in conjunction with the log post-processor like `src/etc/indenter` diff --git a/src/librustc_back/archive.rs b/src/librustc_back/archive.rs index 7ea192b8d6b..fa754b4a301 100644 --- a/src/librustc_back/archive.rs +++ b/src/librustc_back/archive.rs @@ -59,7 +59,7 @@ fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option, let mut cmd = Command::new(ar); cmd.arg(args).args(paths); - debug!("{}", cmd); + debug!("{:?}", cmd); match cwd { Some(p) => { @@ -73,9 +73,7 @@ fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option, Ok(prog) => { let o = prog.wait_with_output().unwrap(); if !o.status.success() { - handler.err(&format!("{} failed with: {}", - cmd, - o.status)[]); + handler.err(&format!("{:?} failed with: {}", cmd, o.status)[]); handler.note(&format!("stdout ---\n{}", str::from_utf8(&o.output[]).unwrap())[]); handler.note(&format!("stderr ---\n{}", diff --git a/src/librustc_back/svh.rs b/src/librustc_back/svh.rs index b71e465b938..77ee59dc2ba 100644 --- a/src/librustc_back/svh.rs +++ b/src/librustc_back/svh.rs @@ -52,7 +52,7 @@ use syntax::ast; use syntax::visit; -#[derive(Clone, PartialEq)] +#[derive(Clone, PartialEq, Show)] pub struct Svh { hash: String, } @@ -117,13 +117,7 @@ fn hex(b: u64) -> char { } } -impl fmt::Show for Svh { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Svh {{ {} }}", self.as_str()) - } -} - -impl fmt::String for Svh { +impl fmt::Display for Svh { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad(self.as_str()) } diff --git a/src/librustc_borrowck/borrowck/gather_loans/mod.rs b/src/librustc_borrowck/borrowck/gather_loans/mod.rs index 889a359b019..b1cc3a65120 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/mod.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/mod.rs @@ -491,7 +491,7 @@ fn visit_expr(&mut self, ex: &Expr) { if let ast::ExprAddrOf(mutbl, ref base) = ex.node { let param_env = ty::empty_parameter_environment(self.bccx.tcx); let mc = mc::MemCategorizationContext::new(¶m_env); - let base_cmt = mc.cat_expr(&**base).unwrap(); + let base_cmt = mc.cat_expr(&**base).ok().unwrap(); let borrow_kind = ty::BorrowKind::from_mutbl(mutbl); // Check that we don't allow borrows of unsafe static items. if check_aliasability(self.bccx, ex.span, euv::AddrOf, diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 31999faa6df..37c75b45f0f 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -536,7 +536,7 @@ fn all_imports_resolved(&self) -> bool { } } -impl fmt::Show for Module { +impl fmt::Debug for Module { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}, kind: {:?}, {}", self.def_id, diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index dacf620cbd1..a46dc7b33f7 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -779,14 +779,14 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool, } if sess.opts.debugging_opts.print_link_args { - println!("{}", &cmd); + println!("{:?}", &cmd); } // May have not found libraries in the right formats. sess.abort_if_errors(); // Invoke the system linker - debug!("{}", &cmd); + debug!("{:?}", &cmd); let prog = time(sess.time_passes(), "running linker", (), |()| cmd.output()); match prog { Ok(prog) => { @@ -794,7 +794,7 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool, sess.err(&format!("linking with `{}` failed: {}", pname, prog.status)[]); - sess.note(&format!("{}", &cmd)[]); + sess.note(&format!("{:?}", &cmd)[]); let mut output = prog.error.clone(); output.push_all(&prog.output[]); sess.note(str::from_utf8(&output[]).unwrap()); diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index aa51b0c5ee2..0ade5aaab3d 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -716,7 +716,7 @@ pub fn run_passes(sess: &Session, cmd.args(&sess.target.target.options.post_link_args[]); if sess.opts.debugging_opts.print_link_args { - println!("{}", &cmd); + println!("{:?}", &cmd); } cmd.stdin(::std::io::process::Ignored) @@ -725,7 +725,7 @@ pub fn run_passes(sess: &Session, match cmd.status() { Ok(status) => { if !status.success() { - sess.err(&format!("linking of {} with `{}` failed", + sess.err(&format!("linking of {} with `{:?}` failed", output_path.display(), cmd)[]); sess.abort_if_errors(); } @@ -953,7 +953,7 @@ pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) { cmd.arg("-c").arg("-o").arg(outputs.path(config::OutputTypeObject)) .arg(outputs.temp_path(config::OutputTypeAssembly)); - debug!("{}", &cmd); + debug!("{:?}", &cmd); match cmd.output() { Ok(prog) => { @@ -961,7 +961,7 @@ pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) { sess.err(&format!("linking with `{}` failed: {}", pname, prog.status)[]); - sess.note(&format!("{}", &cmd)[]); + sess.note(&format!("{:?}", &cmd)[]); let mut note = prog.error.clone(); note.push_all(&prog.output[]); sess.note(str::from_utf8(¬e[]).unwrap()); diff --git a/src/librustc_trans/trans/cleanup.rs b/src/librustc_trans/trans/cleanup.rs index 5658889aaf3..de2a69226bd 100644 --- a/src/librustc_trans/trans/cleanup.rs +++ b/src/librustc_trans/trans/cleanup.rs @@ -65,7 +65,7 @@ pub enum CleanupScopeKind<'blk, 'tcx: 'blk> { LoopScopeKind(ast::NodeId, [Block<'blk, 'tcx>; EXIT_MAX]) } -impl<'blk, 'tcx: 'blk> fmt::Show for CleanupScopeKind<'blk, 'tcx> { +impl<'blk, 'tcx: 'blk> fmt::Debug for CleanupScopeKind<'blk, 'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { CustomScopeKind => write!(f, "CustomScopeKind"), diff --git a/src/librustc_trans/trans/datum.rs b/src/librustc_trans/trans/datum.rs index 8b52732f4ee..cba12babb9b 100644 --- a/src/librustc_trans/trans/datum.rs +++ b/src/librustc_trans/trans/datum.rs @@ -481,7 +481,7 @@ pub fn get_vec_base_and_len(&self, bcx: Block) -> (ValueRef, ValueRef) { } /// Generic methods applicable to any sort of datum. -impl<'tcx, K: KindOps + fmt::Show> Datum<'tcx, K> { +impl<'tcx, K: KindOps + fmt::Debug> Datum<'tcx, K> { pub fn new(val: ValueRef, ty: Ty<'tcx>, kind: K) -> Datum<'tcx, K> { Datum { val: val, ty: ty, kind: kind } } @@ -591,7 +591,7 @@ pub fn new(bcx: Block<'blk, 'tcx>, datum: Datum<'tcx, K>) } } -impl<'blk, 'tcx, K: KindOps + fmt::Show> DatumBlock<'blk, 'tcx, K> { +impl<'blk, 'tcx, K: KindOps + fmt::Debug> DatumBlock<'blk, 'tcx, K> { pub fn to_expr_datumblock(self) -> DatumBlock<'blk, 'tcx, Expr> { DatumBlock::new(self.bcx, self.datum.to_expr_datum()) } diff --git a/src/librustc_typeck/variance.rs b/src/librustc_typeck/variance.rs index 86447e76a89..1f10f8eb1b6 100644 --- a/src/librustc_typeck/variance.rs +++ b/src/librustc_typeck/variance.rs @@ -240,7 +240,7 @@ enum VarianceTerm<'a> { InferredTerm(InferredIndex), } -impl<'a> fmt::Show for VarianceTerm<'a> { +impl<'a> fmt::Debug for VarianceTerm<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ConstantTerm(c1) => write!(f, "{:?}", c1), diff --git a/src/librustdoc/html/escape.rs b/src/librustdoc/html/escape.rs index 6fb78d9a833..c2b18962192 100644 --- a/src/librustdoc/html/escape.rs +++ b/src/librustdoc/html/escape.rs @@ -19,7 +19,7 @@ /// string when passed to a format string. pub struct Escape<'a>(pub &'a str); -impl<'a> fmt::String for Escape<'a> { +impl<'a> fmt::Display for Escape<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Because the internet is always right, turns out there's not that many // characters to escape: http://stackoverflow.com/questions/7381974 diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 57b8d666c95..27b875ee286 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -66,7 +66,7 @@ pub fn get(&self) -> ast::Unsafety { } } -impl<'a, T: fmt::String> fmt::String for CommaSep<'a, T> { +impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, item) in self.0.iter().enumerate() { if i != 0 { try!(write!(f, ", ")); } @@ -76,7 +76,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl<'a> fmt::String for TyParamBounds<'a> { +impl<'a> fmt::Display for TyParamBounds<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &TyParamBounds(bounds) = self; for (i, bound) in bounds.iter().enumerate() { @@ -89,7 +89,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for clean::Generics { +impl fmt::Display for clean::Generics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.lifetimes.len() == 0 && self.type_params.len() == 0 { return Ok(()) } try!(f.write_str("<")); @@ -126,7 +126,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl<'a> fmt::String for WhereClause<'a> { +impl<'a> fmt::Display for WhereClause<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &WhereClause(gens) = self; if gens.where_predicates.len() == 0 { @@ -163,14 +163,14 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for clean::Lifetime { +impl fmt::Display for clean::Lifetime { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str(self.get_ref())); Ok(()) } } -impl fmt::String for clean::PolyTrait { +impl fmt::Display for clean::PolyTrait { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.lifetimes.len() > 0 { try!(f.write_str("for<")); @@ -186,7 +186,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for clean::TyParamBound { +impl fmt::Display for clean::TyParamBound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::RegionBound(ref lt) => { @@ -203,7 +203,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for clean::PathParameters { +impl fmt::Display for clean::PathParameters { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::PathParameters::AngleBracketed { @@ -257,14 +257,14 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for clean::PathSegment { +impl fmt::Display for clean::PathSegment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str(self.name.as_slice())); write!(f, "{}", self.params) } } -impl fmt::String for clean::Path { +impl fmt::Display for clean::Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.global { try!(f.write_str("::")) @@ -450,7 +450,7 @@ fn tybounds(w: &mut fmt::Formatter, } } -impl fmt::String for clean::Type { +impl fmt::Display for clean::Type { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::TyParamBinder(id) => { @@ -539,7 +539,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for clean::Arguments { +impl fmt::Display for clean::Arguments { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, input) in self.values.iter().enumerate() { if i > 0 { try!(write!(f, ", ")); } @@ -552,7 +552,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for clean::FunctionRetTy { +impl fmt::Display for clean::FunctionRetTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()), @@ -563,13 +563,13 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for clean::FnDecl { +impl fmt::Display for clean::FnDecl { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output) } } -impl<'a> fmt::String for Method<'a> { +impl<'a> fmt::Display for Method<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Method(selfty, d) = *self; let mut args = String::new(); @@ -599,7 +599,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for VisSpace { +impl fmt::Display for VisSpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.get() { Some(ast::Public) => write!(f, "pub "), @@ -608,7 +608,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for UnsafetySpace { +impl fmt::Display for UnsafetySpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.get() { ast::Unsafety::Unsafe => write!(f, "unsafe "), @@ -617,7 +617,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for clean::ViewPath { +impl fmt::Display for clean::ViewPath { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::SimpleImport(ref name, ref src) => { @@ -644,7 +644,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for clean::ImportSource { +impl fmt::Display for clean::ImportSource { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.did { Some(did) => resolved_path(f, did, &self.path, true), @@ -661,7 +661,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for clean::ViewListIdent { +impl fmt::Display for clean::ViewListIdent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.source { Some(did) => { @@ -683,13 +683,13 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for clean::TypeBinding { +impl fmt::Display for clean::TypeBinding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}={}", self.name, self.ty) } } -impl fmt::String for MutableSpace { +impl fmt::Display for MutableSpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { MutableSpace(clean::Immutable) => Ok(()), @@ -698,7 +698,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for RawMutableSpace { +impl fmt::Display for RawMutableSpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RawMutableSpace(clean::Immutable) => write!(f, "const "), @@ -707,7 +707,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl<'a> fmt::String for Stability<'a> { +impl<'a> fmt::Display for Stability<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Stability(stab) = *self; match *stab { @@ -721,7 +721,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl<'a> fmt::String for ConciseStability<'a> { +impl<'a> fmt::Display for ConciseStability<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ConciseStability(stab) = *self; match *stab { @@ -738,7 +738,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl fmt::String for ModuleSummary { +impl fmt::Display for ModuleSummary { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt_inner<'a>(f: &mut fmt::Formatter, context: &mut Vec<&'a str>, diff --git a/src/librustdoc/html/item_type.rs b/src/librustdoc/html/item_type.rs index db3319eb765..fbc8ae2c0b4 100644 --- a/src/librustdoc/html/item_type.rs +++ b/src/librustdoc/html/item_type.rs @@ -103,7 +103,7 @@ pub fn to_static_str(&self) -> &'static str { } } -impl fmt::String for ItemType { +impl fmt::Display for ItemType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.to_static_str().fmt(f) } diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs index f75ab3f431c..e3bd2b4e27f 100644 --- a/src/librustdoc/html/layout.rs +++ b/src/librustdoc/html/layout.rs @@ -30,7 +30,7 @@ pub struct Page<'a> { pub keywords: &'a str } -pub fn render( +pub fn render( dst: &mut io::Writer, layout: &Layout, page: &Page, sidebar: &S, t: &T) -> io::IoResult<()> { diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 0dbd13b4616..4bdc2a16482 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -426,7 +426,7 @@ pub fn reset_headers() { USED_HEADER_MAP.with(|s| s.borrow_mut().clear()); } -impl<'a> fmt::String for Markdown<'a> { +impl<'a> fmt::Display for Markdown<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let Markdown(md) = *self; // This is actually common enough to special-case @@ -435,7 +435,7 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { } } -impl<'a> fmt::String for MarkdownWithToc<'a> { +impl<'a> fmt::Display for MarkdownWithToc<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let MarkdownWithToc(md) = *self; render(fmt, md.as_slice(), true) diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index ab9700d966a..bd2213910be 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -1351,7 +1351,7 @@ fn href(&self, cx: &Context) -> Option { } -impl<'a> fmt::String for Item<'a> { +impl<'a> fmt::Display for Item<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Write the breadcrumb trail header for the top try!(write!(fmt, "\n

")); @@ -1626,7 +1626,7 @@ fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: uint, idx2: uint) -> Ordering { struct Initializer<'a>(&'a str); -impl<'a> fmt::String for Initializer<'a> { +impl<'a> fmt::Display for Initializer<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Initializer(s) = *self; if s.len() == 0 { return Ok(()); } @@ -2188,7 +2188,7 @@ fn item_typedef(w: &mut fmt::Formatter, it: &clean::Item, document(w, it) } -impl<'a> fmt::String for Sidebar<'a> { +impl<'a> fmt::Display for Sidebar<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let cx = self.cx; let it = self.item; @@ -2243,7 +2243,7 @@ fn block(w: &mut fmt::Formatter, short: &str, longty: &str, } } -impl<'a> fmt::String for Source<'a> { +impl<'a> fmt::Display for Source<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let Source(s) = *self; let lines = s.lines().count(); diff --git a/src/librustdoc/html/toc.rs b/src/librustdoc/html/toc.rs index 8d94e1857c4..aca6e5bb10e 100644 --- a/src/librustdoc/html/toc.rs +++ b/src/librustdoc/html/toc.rs @@ -176,13 +176,13 @@ pub fn push<'a>(&'a mut self, level: u32, name: String, id: String) -> &'a str { } } -impl fmt::Show for Toc { +impl fmt::Debug for Toc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Display::fmt(self, f) } } -impl fmt::String for Toc { +impl fmt::Display for Toc { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "