Skip to content

Commit

Permalink
auto merge of #18486 : nikomatsakis/rust/operator-dispatch, r=pcwalton
Browse files Browse the repository at this point in the history
This branch cleans up overloaded operator resolution so that it is strictly based on the traits in `ops`, rather than going through the normal method lookup mechanism. It also adds full support for autoderef to overloaded index (whereas before autoderef only worked for non-overloaded index) as well as for the slicing operators.

This is a [breaking-change]: in the past, we were accepting combinations of operands that were not intended to be accepted. For example, it was possible to compare a fixed-length array and a slice, or apply the `!` operator to a `&int`. See the first two commits in this pull-request for examples.

One downside of this change is that comparing fixed-length arrays doesn't always work as smoothly as it did before. Before this, comparisons sometimes worked due to various coercions to slices. I've added impls for `Eq`, `Ord`, etc for fixed-lengths arrays up to and including length 32, but if the array is longer than that you'll need to either newtype the array or convert to slices. Note that this plays better with deriving in any case than the previous scheme.

Fixes #4920.
Fixes #16821.
Fixes #15757.

cc @alexcrichton 
cc @aturon
  • Loading branch information
bors committed Nov 5, 2014
2 parents 5c1fd5f + 81c00e6 commit 63c4f22
Show file tree
Hide file tree
Showing 31 changed files with 1,009 additions and 263 deletions.
10 changes: 7 additions & 3 deletions src/doc/guide.md
Expand Up @@ -4601,20 +4601,24 @@ returns `true` or `false`. The new iterator `filter()` produces
only the elements that that closure returns `true` for:

```{rust}
for i in range(1i, 100i).filter(|x| x % 2 == 0) {
for i in range(1i, 100i).filter(|&x| x % 2 == 0) {
println!("{}", i);
}
```

This will print all of the even numbers between one and a hundred.
(Note that because `filter` doesn't consume the elements that are
being iterated over, it is passed a reference to each element, and
thus the filter predicate uses the `&x` pattern to extract the integer
itself.)

You can chain all three things together: start with an iterator, adapt it
a few times, and then consume the result. Check it out:

```{rust}
range(1i, 1000i)
.filter(|x| x % 2 == 0)
.filter(|x| x % 3 == 0)
.filter(|&x| x % 2 == 0)
.filter(|&x| x % 3 == 0)
.take(5)
.collect::<Vec<int>>();
```
Expand Down
2 changes: 1 addition & 1 deletion src/libarena/lib.rs
Expand Up @@ -132,7 +132,7 @@ impl Drop for Arena {

#[inline]
fn round_up(base: uint, align: uint) -> uint {
(base.checked_add(&(align - 1))).unwrap() & !(&(align - 1))
(base.checked_add(&(align - 1))).unwrap() & !(align - 1)
}

// Walk down a chunk, running the destructors for any objects stored
Expand Down
14 changes: 7 additions & 7 deletions src/libcollections/slice.rs
Expand Up @@ -1598,15 +1598,15 @@ mod tests {
#[test]
fn test_total_ord() {
let c: &[int] = &[1, 2, 3];
[1, 2, 3, 4].cmp(& c) == Greater;
[1, 2, 3, 4][].cmp(& c) == Greater;
let c: &[int] = &[1, 2, 3, 4];
[1, 2, 3].cmp(& c) == Less;
[1, 2, 3][].cmp(& c) == Less;
let c: &[int] = &[1, 2, 3, 6];
[1, 2, 3, 4].cmp(& c) == Equal;
[1, 2, 3, 4][].cmp(& c) == Equal;
let c: &[int] = &[1, 2, 3, 4, 5, 6];
[1, 2, 3, 4, 5, 5, 5, 5].cmp(& c) == Less;
[1, 2, 3, 4, 5, 5, 5, 5][].cmp(& c) == Less;
let c: &[int] = &[1, 2, 3, 4];
[2, 2].cmp(& c) == Greater;
[2, 2][].cmp(& c) == Greater;
}

#[test]
Expand Down Expand Up @@ -1980,15 +1980,15 @@ mod tests {
let (left, right) = values.split_at_mut(2);
{
let left: &[_] = left;
assert!(left[0..left.len()] == [1, 2]);
assert!(left[0..left.len()] == [1, 2][]);
}
for p in left.iter_mut() {
*p += 1;
}

{
let right: &[_] = right;
assert!(right[0..right.len()] == [3, 4, 5]);
assert!(right[0..right.len()] == [3, 4, 5][]);
}
for p in right.iter_mut() {
*p += 2;
Expand Down
8 changes: 4 additions & 4 deletions src/libcollections/vec.rs
Expand Up @@ -919,7 +919,7 @@ impl<T> Vec<T> {
///
/// ```
/// let mut vec = vec![1i, 2, 3, 4];
/// vec.retain(|x| x%2 == 0);
/// vec.retain(|&x| x%2 == 0);
/// assert_eq!(vec, vec![2, 4]);
/// ```
#[unstable = "the closure argument may become an unboxed closure"]
Expand Down Expand Up @@ -1800,15 +1800,15 @@ mod tests {
let (left, right) = values.split_at_mut(2);
{
let left: &[_] = left;
assert!(left[0..left.len()] == [1, 2]);
assert!(left[0..left.len()] == [1, 2][]);
}
for p in left.iter_mut() {
*p += 1;
}

{
let right: &[_] = right;
assert!(right[0..right.len()] == [3, 4, 5]);
assert!(right[0..right.len()] == [3, 4, 5][]);
}
for p in right.iter_mut() {
*p += 2;
Expand Down Expand Up @@ -1863,7 +1863,7 @@ mod tests {
#[test]
fn test_retain() {
let mut vec = vec![1u, 2, 3, 4];
vec.retain(|x| x%2 == 0);
vec.retain(|&x| x % 2 == 0);
assert!(vec == vec![2u, 4]);
}

Expand Down
83 changes: 83 additions & 0 deletions src/libcore/array.rs
@@ -0,0 +1,83 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/*!
* Implementations of things like `Eq` for fixed-length arrays
* up to a certain length. Eventually we should able to generalize
* to all lengths.
*/

#![stable]
#![experimental] // not yet reviewed

use cmp::*;
use option::{Option};

// macro for implementing n-ary tuple functions and operations
macro_rules! array_impls {
($($N:expr)+) => {
$(
#[unstable = "waiting for PartialEq to stabilize"]
impl<T:PartialEq> PartialEq for [T, ..$N] {
#[inline]
fn eq(&self, other: &[T, ..$N]) -> bool {
self[] == other[]
}
#[inline]
fn ne(&self, other: &[T, ..$N]) -> bool {
self[] != other[]
}
}

#[unstable = "waiting for Eq to stabilize"]
impl<T:Eq> Eq for [T, ..$N] { }

#[unstable = "waiting for PartialOrd to stabilize"]
impl<T:PartialOrd> PartialOrd for [T, ..$N] {
#[inline]
fn partial_cmp(&self, other: &[T, ..$N]) -> Option<Ordering> {
PartialOrd::partial_cmp(&self[], &other[])
}
#[inline]
fn lt(&self, other: &[T, ..$N]) -> bool {
PartialOrd::lt(&self[], &other[])
}
#[inline]
fn le(&self, other: &[T, ..$N]) -> bool {
PartialOrd::le(&self[], &other[])
}
#[inline]
fn ge(&self, other: &[T, ..$N]) -> bool {
PartialOrd::ge(&self[], &other[])
}
#[inline]
fn gt(&self, other: &[T, ..$N]) -> bool {
PartialOrd::gt(&self[], &other[])
}
}

#[unstable = "waiting for Ord to stabilize"]
impl<T:Ord> Ord for [T, ..$N] {
#[inline]
fn cmp(&self, other: &[T, ..$N]) -> Ordering {
Ord::cmp(&self[], &other[])
}
}
)+
}
}

array_impls! {
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32
}

4 changes: 4 additions & 0 deletions src/libcore/lib.rs
Expand Up @@ -126,6 +126,10 @@ pub mod tuple;
pub mod unit;
pub mod fmt;

// note: does not need to be public
#[cfg(not(stage0))]
mod array;

#[doc(hidden)]
mod core {
pub use panicking;
Expand Down
4 changes: 2 additions & 2 deletions src/libcore/option.rs
Expand Up @@ -787,8 +787,8 @@ impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
/// use std::uint;
///
/// let v = vec!(1u, 2u);
/// let res: Option<Vec<uint>> = v.iter().map(|x: &uint|
/// if *x == uint::MAX { None }
/// let res: Option<Vec<uint>> = v.iter().map(|&x: &uint|
/// if x == uint::MAX { None }
/// else { Some(x + 1) }
/// ).collect();
/// assert!(res == Some(vec!(2u, 3u)));
Expand Down
4 changes: 2 additions & 2 deletions src/libcore/result.rs
Expand Up @@ -894,8 +894,8 @@ impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
/// use std::uint;
///
/// let v = vec!(1u, 2u);
/// let res: Result<Vec<uint>, &'static str> = v.iter().map(|x: &uint|
/// if *x == uint::MAX { Err("Overflow!") }
/// let res: Result<Vec<uint>, &'static str> = v.iter().map(|&x: &uint|
/// if x == uint::MAX { Err("Overflow!") }
/// else { Ok(x + 1) }
/// ).collect();
/// assert!(res == Ok(vec!(2u, 3u)));
Expand Down
8 changes: 4 additions & 4 deletions src/libcoretest/iter.rs
Expand Up @@ -356,7 +356,7 @@ fn test_iterator_size_hint() {
assert_eq!(vi.zip(v2.iter()).size_hint(), (3, Some(3)));
assert_eq!(vi.scan(0i, |_,_| Some(0i)).size_hint(), (0, Some(10)));
assert_eq!(vi.filter(|_| false).size_hint(), (0, Some(10)));
assert_eq!(vi.map(|i| i+1).size_hint(), (10, Some(10)));
assert_eq!(vi.map(|&i| i+1).size_hint(), (10, Some(10)));
assert_eq!(vi.filter_map(|_| Some(0i)).size_hint(), (0, Some(10)));
}

Expand Down Expand Up @@ -388,9 +388,9 @@ fn test_any() {
#[test]
fn test_find() {
let v: &[int] = &[1i, 3, 9, 27, 103, 14, 11];
assert_eq!(*v.iter().find(|x| *x & 1 == 0).unwrap(), 14);
assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3);
assert!(v.iter().find(|x| *x % 12 == 0).is_none());
assert_eq!(*v.iter().find(|&&x| x & 1 == 0).unwrap(), 14);
assert_eq!(*v.iter().find(|&&x| x % 3 == 0).unwrap(), 3);
assert!(v.iter().find(|&&x| x % 12 == 0).is_none());
}

#[test]
Expand Down
23 changes: 19 additions & 4 deletions src/librustc/middle/ty.rs
Expand Up @@ -1167,25 +1167,25 @@ impl cmp::PartialEq for InferRegion {

impl fmt::Show for TyVid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
write!(f, "<generic #{}>", self.index)
write!(f, "_#{}t", self.index)
}
}

impl fmt::Show for IntVid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<generic integer #{}>", self.index)
write!(f, "_#{}i", self.index)
}
}

impl fmt::Show for FloatVid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<generic float #{}>", self.index)
write!(f, "_#{}f", self.index)
}
}

impl fmt::Show for RegionVid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "'<generic lifetime #{}>", self.index)
write!(f, "'_#{}r", self.index)
}
}

Expand Down Expand Up @@ -5566,3 +5566,18 @@ pub fn with_freevars<T>(tcx: &ty::ctxt, fid: ast::NodeId, f: |&[Freevar]| -> T)
Some(d) => f(d.as_slice())
}
}

impl AutoAdjustment {
pub fn is_identity(&self) -> bool {
match *self {
AdjustAddEnv(..) => false,
AdjustDerefRef(ref r) => r.is_identity(),
}
}
}

impl AutoDerefRef {
pub fn is_identity(&self) -> bool {
self.autoderefs == 0 && self.autoref.is_none()
}
}

0 comments on commit 63c4f22

Please sign in to comment.