Auto merge of #21791 - alexcrichton:rollup, r=alexcrichton

This commit is contained in:
bors 2015-01-31 03:57:01 +00:00
commit 474b324eda
661 changed files with 4551 additions and 7328 deletions

View File

@ -110,12 +110,14 @@ There is a lot more documentation in the [wiki].
The Rust community congregates in a few places:
* [StackOverflow] - Get help here.
* [/r/rust] - General discussion.
* [StackOverflow] - Direct questions about using the language here.
* [users.rust-lang.org] - General discussion, broader questions.
* [internals.rust-lang.org] - For development of the Rust language itself.
* [/r/rust] - News and general discussion.
[StackOverflow]: http://stackoverflow.com/questions/tagged/rust
[/r/rust]: http://reddit.com/r/rust
[users.rust-lang.org]: http://users.rust-lang.org/
[internals.rust-lang.org]: http://internals.rust-lang.org/
## License

View File

@ -25,17 +25,18 @@ pub enum Mode {
}
impl FromStr for Mode {
fn from_str(s: &str) -> Option<Mode> {
type Err = ();
fn from_str(s: &str) -> Result<Mode, ()> {
match s {
"compile-fail" => Some(CompileFail),
"run-fail" => Some(RunFail),
"run-pass" => Some(RunPass),
"run-pass-valgrind" => Some(RunPassValgrind),
"pretty" => Some(Pretty),
"debuginfo-lldb" => Some(DebugInfoLldb),
"debuginfo-gdb" => Some(DebugInfoGdb),
"codegen" => Some(Codegen),
_ => None,
"compile-fail" => Ok(CompileFail),
"run-fail" => Ok(RunFail),
"run-pass" => Ok(RunPass),
"run-pass-valgrind" => Ok(RunPassValgrind),
"pretty" => Ok(Pretty),
"debuginfo-lldb" => Ok(DebugInfoLldb),
"debuginfo-gdb" => Ok(DebugInfoGdb),
"codegen" => Ok(Codegen),
_ => Err(()),
}
}
}

View File

@ -9,21 +9,20 @@
// except according to those terms.
#![crate_type = "bin"]
#![allow(unknown_features)]
#![feature(slicing_syntax, unboxed_closures)]
#![feature(box_syntax)]
#![feature(int_uint)]
#![feature(test)]
#![feature(rustc_private)]
#![feature(std_misc)]
#![feature(path)]
#![feature(io)]
#![feature(core)]
#![feature(collections)]
#![feature(core)]
#![feature(int_uint)]
#![feature(io)]
#![feature(os)]
#![feature(path)]
#![feature(rustc_private)]
#![feature(slicing_syntax, unboxed_closures)]
#![feature(std_misc)]
#![feature(test)]
#![feature(unicode)]
#![allow(unstable)]
#![deny(warnings)]
extern crate test;
@ -35,7 +34,6 @@ extern crate log;
use std::os;
use std::old_io;
use std::old_io::fs;
use std::str::FromStr;
use std::thunk::Thunk;
use getopts::{optopt, optflag, reqopt};
use common::Config;
@ -140,9 +138,7 @@ pub fn parse_config(args: Vec<String> ) -> Config {
build_base: opt_path(matches, "build-base"),
aux_base: opt_path(matches, "aux-base"),
stage_id: matches.opt_str("stage-id").unwrap(),
mode: FromStr::from_str(matches.opt_str("mode")
.unwrap()
.as_slice()).expect("invalid mode"),
mode: matches.opt_str("mode").unwrap().parse().ok().expect("invalid mode"),
run_ignored: matches.opt_present("ignored"),
filter: filter,
logfile: matches.opt_str("logfile").map(|s| Path::new(s)),

View File

@ -352,8 +352,8 @@ pub fn gdb_version_to_int(version_string: &str) -> int {
panic!("{}", error_string);
}
let major: int = components[0].parse().expect(error_string);
let minor: int = components[1].parse().expect(error_string);
let major: int = components[0].parse().ok().expect(error_string);
let minor: int = components[1].parse().ok().expect(error_string);
return major * 1000 + minor;
}
@ -363,6 +363,6 @@ pub fn lldb_version_to_int(version_string: &str) -> int {
"Encountered LLDB version string with unexpected format: {}",
version_string);
let error_string = error_string.as_slice();
let major: int = version_string.parse().expect(error_string);
let major: int = version_string.parse().ok().expect(error_string);
return major;
}

View File

@ -39,10 +39,12 @@ Overflow](http://stackoverflow.com/questions/tagged/rust). Searching for your
problem might reveal someone who has asked it before!
There is an active [subreddit](http://reddit.com/r/rust) with lots of
discussion about Rust.
discussion and news about Rust.
There is also a [developer forum](http://internals.rust-lang.org/), where the
development of Rust itself is discussed.
There is also a [user forum](http://users.rust-lang.org), for all
user-oriented discussion, and a [developer
forum](http://internals.rust-lang.org/), where the development of Rust
itself is discussed.
# Specification

View File

@ -2994,7 +2994,7 @@ Some examples of call expressions:
# fn add(x: i32, y: i32) -> i32 { 0 }
let x: i32 = add(1i32, 2i32);
let pi: Option<f32> = "3.14".parse();
let pi: Option<f32> = "3.14".parse().ok();
```
### Lambda expressions
@ -3518,7 +3518,7 @@ An example of each kind:
```{rust}
let vec: Vec<i32> = vec![1, 2, 3];
let arr: [i32; 3] = [1, 2, 3];
let s: &[i32] = vec.as_slice();
let s: &[i32] = &vec;
```
As you can see, the `vec!` macro allows you to create a `Vec<T>` easily. The

View File

@ -400,7 +400,7 @@ a function for that:
let input = old_io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<u32> = input.parse();
let input_num: Option<u32> = input.parse().ok();
```
The `parse` function takes in a `&str` value and converts it into something.
@ -422,11 +422,13 @@ In this case, we say `x` is a `u32` explicitly, so Rust is able to properly
tell `random()` what to generate. In a similar fashion, both of these work:
```{rust,ignore}
let input_num = "5".parse::<u32>(); // input_num: Option<u32>
let input_num: Option<u32> = "5".parse(); // input_num: Option<u32>
let input_num = "5".parse::<u32>().ok(); // input_num: Option<u32>
let input_num: Option<u32> = "5".parse().ok(); // input_num: Option<u32>
```
Anyway, with us now converting our input to a number, our code looks like this:
Here we're converting the `Result` returned by `parse` to an `Option` by using
the `ok` method as well. Anyway, with us now converting our input to a number,
our code looks like this:
```{rust,ignore}
use std::old_io;
@ -445,7 +447,7 @@ fn main() {
let input = old_io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<u32> = input.parse();
let input_num: Option<u32> = input.parse().ok();
println!("You guessed: {}", input_num);
@ -495,7 +497,7 @@ fn main() {
let input = old_io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<u32> = input.parse();
let input_num: Option<u32> = input.parse().ok();
let num = match input_num {
Some(num) => num,
@ -562,7 +564,7 @@ fn main() {
let input = old_io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<u32> = input.trim().parse();
let input_num: Option<u32> = input.trim().parse().ok();
let num = match input_num {
Some(num) => num,
@ -638,7 +640,7 @@ fn main() {
let input = old_io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<u32> = input.trim().parse();
let input_num: Option<u32> = input.trim().parse().ok();
let num = match input_num {
Some(num) => num,
@ -714,7 +716,7 @@ fn main() {
let input = old_io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<u32> = input.trim().parse();
let input_num: Option<u32> = input.trim().parse().ok();
let num = match input_num {
Some(num) => num,
@ -770,7 +772,7 @@ fn main() {
let input = old_io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<u32> = input.trim().parse();
let input_num: Option<u32> = input.trim().parse().ok();
let num = match input_num {
Some(num) => num,
@ -847,7 +849,7 @@ fn main() {
let input = old_io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<u32> = input.trim().parse();
let input_num: Option<u32> = input.trim().parse().ok();
let num = match input_num {
Some(num) => num,

View File

@ -100,7 +100,7 @@ To write a function that's generic over types of strings, use `&str`.
```
fn some_string_length(x: &str) -> uint {
x.len()
x.len()
}
fn main() {
@ -110,7 +110,7 @@ fn main() {
let s = "Hello, world".to_string();
println!("{}", some_string_length(s.as_slice()));
println!("{}", some_string_length(&s));
}
```

View File

@ -174,13 +174,13 @@ match origin {
}
```
If you want to match against a slice or array, you can use `[]`:
If you want to match against a slice or array, you can use `&`:
```{rust}
fn main() {
let v = vec!["match_this", "1"];
match v.as_slice() {
match &v[] {
["match_this", second] => println!("The second element is {}", second),
_ => {},
}

View File

@ -82,7 +82,7 @@ fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
}
};
let mut text = text.as_slice();
let mut text = &text;
let mut total = 0;
while !text.is_empty() {
match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) {

View File

@ -20,7 +20,7 @@ Let's go over these chunks, one by one:
std::old_io::stdin();
```
This calls a function, `stdin()`, that lives inside the `std::io` module. As
This calls a function, `stdin()`, that lives inside the `std::old_io` module. As
you can imagine, everything in `std` is provided by Rust, the 'standard
library.' We'll talk more about the module system later.

View File

@ -36,36 +36,16 @@ s.push_str(", world.");
println!("{}", s);
```
You can get a `&str` view into a `String` with the `as_slice()` method:
`String`s will coerece into `&str` with an `&`:
```{rust}
```
fn takes_slice(slice: &str) {
println!("Got: {}", slice);
}
fn main() {
let s = "Hello".to_string();
takes_slice(s.as_slice());
}
```
To compare a String to a constant string, prefer `as_slice()`...
```{rust}
fn compare(string: String) {
if string.as_slice() == "Hello" {
println!("yes");
}
}
```
... over `to_string()`:
```{rust}
fn compare(string: String) {
if string == "Hello".to_string() {
println!("yes");
}
takes_slice(&s);
}
```

View File

@ -576,6 +576,10 @@ extern fn panic_fmt(args: &core::fmt::Arguments,
#[lang = "eh_personality"] extern fn eh_personality() {}
# #[start] fn start(argc: isize, argv: *const *const u8) -> isize { 0 }
# fn main() {}
# mod std { // for-loops
# pub use core::iter;
# pub use core::option;
# }
```
Note that there is one extra lang item here which differs from the examples

View File

@ -8,7 +8,6 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unknown_features)]
#![cfg_attr(rustc, feature(rustc_private))]
#![cfg_attr(rustdoc, feature(rustdoc))]

View File

@ -1,79 +0,0 @@
`rust-mode`: A major Emacs mode for editing Rust source code
============================================================
`rust-mode` makes editing [Rust](http://rust-lang.org) code with Emacs
enjoyable.
### Manual Installation
To install manually, check out this repository and add this to your
`.emacs` file:
```lisp
(add-to-list 'load-path "/path/to/rust-mode/")
(autoload 'rust-mode "rust-mode" nil t)
(add-to-list 'auto-mode-alist '("\\.rs\\'" . rust-mode))
```
This associates `rust-mode` with `.rs` files. To enable it explicitly, do
<kbd>M-x rust-mode</kbd>.
### `package.el` installation via Marmalade or MELPA
It can be more convenient to use Emacs's package manager to handle
installation for you if you use many elisp libraries. If you have
`package.el` but haven't added Marmalade or MELPA, the community
package source, yet, add this to `~/.emacs.d/init.el`:
Using Marmalade:
```lisp
(require 'package)
(add-to-list 'package-archives
'("marmalade" . "http://marmalade-repo.org/packages/"))
(package-initialize)
```
Using MELPA:
```lisp
(require 'package)
(add-to-list 'package-archives
'("melpa" . "http://melpa.milkbox.net/packages/") t)
(package-initialize)
```
Then do this to load the package listing:
* <kbd>M-x eval-buffer</kbd>
* <kbd>M-x package-refresh-contents</kbd>
If you use a version of Emacs prior to 24 that doesn't include
`package.el`, you can get it from [here](http://bit.ly/pkg-el23).
If you have an older ELPA `package.el` installed from tromey.com, you
should upgrade in order to support installation from multiple sources.
The ELPA archive is deprecated and no longer accepting new packages,
so the version there (1.7.1) is very outdated.
#### Install `rust-mode`
One you have `package.el`, you can install `rust-mode` or any other
modes by choosing them from a list:
* <kbd>M-x package-list-packages</kbd>
Now, to install packages, move your cursor to them and press
<kbd>i</kbd>. This will mark the packages for installation. When
you're done with marking, press <kbd>x</kbd>, and ELPA will install
the packages for you (under `~/.emacs.d/elpa/`).
* or using <kbd>M-x package-install rust-mode</kbd>
### Tests via ERT
The file `rust-mode-tests.el` contains tests that can be run via
[ERT](http://www.gnu.org/software/emacs/manual/html_node/ert/index.html).
You can use `run_rust_emacs_tests.sh` to run them in batch mode, if
Emacs is somewhere in your `$PATH`.

View File

@ -1,14 +0,0 @@
#!/bin/sh
# 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.
#
# This runs the test for emacs rust-mode.
# It must be possible to find emacs via PATH.
emacs -batch -l rust-mode.el -l rust-mode-tests.el -f ert-run-tests-batch-and-exit

View File

@ -1,896 +0,0 @@
;;; rust-mode-tests.el --- ERT tests for rust-mode.el
(require 'rust-mode)
(require 'ert)
(require 'cl)
(setq rust-test-fill-column 32)
(defun rust-compare-code-after-manip (original point-pos manip-func expected got)
(equal expected got))
(defun rust-test-explain-bad-manip (original point-pos manip-func expected got)
(if (equal expected got)
nil
(list
;; The (goto-char) and (insert) business here is just for
;; convenience--after an error, you can copy-paste that into emacs eval to
;; insert the bare strings into a buffer
"Rust code was manipulated wrong after:"
`(insert ,original)
`(goto-char ,point-pos)
'expected `(insert ,expected)
'got `(insert ,got)
(loop for i from 0 to (max (length original) (length expected))
for oi = (if (< i (length got)) (elt got i))
for ei = (if (< i (length expected)) (elt expected i))
while (equal oi ei)
finally return `(first-difference-at
(goto-char ,(+ 1 i))
expected ,(char-to-string ei)
got ,(char-to-string oi))))))
(put 'rust-compare-code-after-manip 'ert-explainer
'rust-test-explain-bad-manip)
(defun rust-test-manip-code (original point-pos manip-func expected)
(with-temp-buffer
(rust-mode)
(insert original)
(goto-char point-pos)
(funcall manip-func)
(should (rust-compare-code-after-manip
original point-pos manip-func expected (buffer-string)))))
(defun test-fill-paragraph (unfilled expected &optional start-pos end-pos)
"We're going to run through many scenarios here--the point should be able to be anywhere from the start-pos (defaults to 1) through end-pos (defaults to the length of what was passed in) and (fill-paragraph) should return the same result.
Also, the result should be the same regardless of whether the code is at the beginning or end of the file. (If you're not careful, that can make a difference.) So we test each position given above with the passed code at the beginning, the end, neither and both. So we do this a total of (end-pos - start-pos)*4 times. Oy."
(let* ((start-pos (or start-pos 1))
(end-pos (or end-pos (length unfilled)))
(padding "\n \n")
(padding-len (length padding)))
(loop
for pad-at-beginning from 0 to 1
do (loop for pad-at-end from 0 to 1
with padding-beginning = (if (= 0 pad-at-beginning) "" padding)
with padding-end = (if (= 0 pad-at-end) "" padding)
with padding-adjust = (* padding-len pad-at-beginning)
with padding-beginning = (if (= 0 pad-at-beginning) "" padding)
with padding-end = (if (= 0 pad-at-end) "" padding)
;; If we're adding space to the beginning, and our start position
;; is at the very beginning, we want to test within the added space.
;; Otherwise adjust the start and end for the beginning padding.
with start-pos = (if (= 1 start-pos) 1 (+ padding-adjust start-pos))
with end-pos = (+ end-pos padding-adjust)
do (loop for pos from start-pos to end-pos
do (rust-test-manip-code
(concat padding-beginning unfilled padding-end)
pos
(lambda ()
(let ((fill-column rust-test-fill-column))
(fill-paragraph)))
(concat padding-beginning expected padding-end)))))))
(ert-deftest fill-paragraph-top-level-multi-line-style-doc-comment-second-line ()
(test-fill-paragraph
"/**
* This is a very very very very very very very long string
*/"
"/**
* This is a very very very very
* very very very long string
*/"))
(ert-deftest fill-paragraph-top-level-multi-line-style-doc-comment-first-line ()
(test-fill-paragraph
"/** This is a very very very very very very very long string
*/"
"/** This is a very very very
* very very very very long
* string
*/"))
(ert-deftest fill-paragraph-multi-paragraph-multi-line-style-doc-comment ()
(let
((multi-paragraph-unfilled
"/**
* This is the first really really really really really really really long paragraph
*
* This is the second really really really really really really long paragraph
*/"))
(test-fill-paragraph
multi-paragraph-unfilled
"/**
* This is the first really
* really really really really
* really really long paragraph
*
* This is the second really really really really really really long paragraph
*/"
1 89)
(test-fill-paragraph
multi-paragraph-unfilled
"/**
* This is the first really really really really really really really long paragraph
*
* This is the second really
* really really really really
* really long paragraph
*/"
90)))
(ert-deftest fill-paragraph-multi-paragraph-single-line-style-doc-comment ()
(let
((multi-paragraph-unfilled
"/// This is the first really really really really really really really long paragraph
///
/// This is the second really really really really really really long paragraph"))
(test-fill-paragraph
multi-paragraph-unfilled
"/// This is the first really
/// really really really really
/// really really long paragraph
///
/// This is the second really really really really really really long paragraph"
1 86)
(test-fill-paragraph
multi-paragraph-unfilled
"/// This is the first really really really really really really really long paragraph
///
/// This is the second really
/// really really really really
/// really long paragraph"
87)))
(ert-deftest fill-paragraph-multi-paragraph-single-line-style-indented ()
(test-fill-paragraph
" // This is the first really really really really really really really long paragraph
//
// This is the second really really really really really really long paragraph"
" // This is the first really
// really really really
// really really really
// long paragraph
//
// This is the second really really really really really really long paragraph" 1 89))
(ert-deftest fill-paragraph-multi-line-style-inner-doc-comment ()
(test-fill-paragraph
"/*! This is a very very very very very very very long string
*/"
"/*! This is a very very very
* very very very very long
* string
*/"))
(ert-deftest fill-paragraph-single-line-style-inner-doc-comment ()
(test-fill-paragraph
"//! This is a very very very very very very very long string"
"//! This is a very very very
//! very very very very long
//! string"))
(ert-deftest fill-paragraph-prefixless-multi-line-doc-comment ()
(test-fill-paragraph
"/**
This is my summary. Blah blah blah blah blah. Dilly dally dilly dally dilly dally doo.
This is some more text. Fee fie fo fum. Humpty dumpty sat on a wall.
*/"
"/**
This is my summary. Blah blah
blah blah blah. Dilly dally
dilly dally dilly dally doo.
This is some more text. Fee fie fo fum. Humpty dumpty sat on a wall.
*/" 4 90))
(ert-deftest fill-paragraph-with-no-space-after-star-prefix ()
(test-fill-paragraph
"/**
*This is a very very very very very very very long string
*/"
"/**
*This is a very very very very
*very very very long string
*/"))
(ert-deftest fill-paragraph-single-line-style-with-code-before ()
(test-fill-paragraph
"fn foo() { }
/// This is my comment. This is more of my comment. This is even more."
"fn foo() { }
/// This is my comment. This is
/// more of my comment. This is
/// even more." 14))
(ert-deftest fill-paragraph-single-line-style-with-code-after ()
(test-fill-paragraph
"/// This is my comment. This is more of my comment. This is even more.
fn foo() { }"
"/// This is my comment. This is
/// more of my comment. This is
/// even more.
fn foo() { }" 1 73))
(ert-deftest fill-paragraph-single-line-style-code-before-and-after ()
(test-fill-paragraph
"fn foo() { }
/// This is my comment. This is more of my comment. This is even more.
fn bar() { }"
"fn foo() { }
/// This is my comment. This is
/// more of my comment. This is
/// even more.
fn bar() { }" 14 67))
(defun test-auto-fill (initial position inserted expected)
(rust-test-manip-code
initial
position
(lambda ()
(unwind-protect
(progn
(let ((fill-column rust-test-fill-column))
(auto-fill-mode)
(goto-char position)
(insert inserted)
(syntax-ppss-flush-cache 1)
(funcall auto-fill-function)))
(auto-fill-mode t)))
expected))
(ert-deftest auto-fill-multi-line-doc-comment ()
(test-auto-fill
"/**
*
*/"
8
"This is a very very very very very very very long string"
"/**
* This is a very very very very
* very very very long string
*/"))
(ert-deftest auto-fill-single-line-doc-comment ()
(test-auto-fill
"/// This is the first really
/// really really really really
/// really really long paragraph
///
/// "
103
"This is the second really really really really really really long paragraph"
"/// This is the first really
/// really really really really
/// really really long paragraph
///
/// This is the second really
/// really really really really
/// really long paragraph"
))
(ert-deftest auto-fill-multi-line-prefixless ()
(test-auto-fill
"/*
*/"
4
"This is a very very very very very very very long string"
"/*
This is a very very very very
very very very long string
*/"
))
(defun test-indent (indented)
(let ((deindented (replace-regexp-in-string "^[[:blank:]]*" " " indented)))
(rust-test-manip-code
deindented
1
(lambda () (indent-region 1 (buffer-size)))
indented)))
(ert-deftest indent-struct-fields-aligned ()
(test-indent
"
struct Foo { bar: int,
baz: int }
struct Blah {x:int,
y:int,
z:String"))
(ert-deftest indent-doc-comments ()
(test-indent
"
/**
* This is a doc comment
*
*/
/// So is this
fn foo() {
/*!
* this is a nested doc comment
*/
//! And so is this
}"))
(ert-deftest indent-inside-braces ()
(test-indent
"
// struct fields out one level:
struct foo {
a:int,
// comments too
b:char
}
fn bar(x:Box<int>) { // comment here should not affect the next indent
bla();
bla();
}"))
(ert-deftest indent-top-level ()
(test-indent
"
// Everything here is at the top level and should not be indented
#[attrib]
mod foo;
pub static bar = Quux{a: b()}
use foo::bar::baz;
fn foo() { }
"))
(ert-deftest indent-params-no-align ()
(test-indent
"
// Indent out one level because no params appear on the first line
fn xyzzy(
a:int,
b:char) { }
fn abcdef(
a:int,
b:char)
-> char
{ }"))
(ert-deftest indent-params-align ()
(test-indent
"
// Align the second line of params to the first
fn foo(a:int,
b:char) { }
fn bar( a:int,
b:char)
-> int
{ }
fn baz( a:int, // should work with a comment here
b:char)
-> int
{ }
"))
(ert-deftest indent-square-bracket-alignment ()
(test-indent
"
fn args_on_the_next_line( // with a comment
a:int,
b:String) {
let aaaaaa = [
1,
2,
3];
let bbbbbbb = [1, 2, 3,
4, 5, 6];
let ccc = [ 10, 9, 8,
7, 6, 5];
}
"))
(ert-deftest indent-nested-fns ()
(test-indent
"
fn nexted_fns(a: fn(b:int,
c:char)
-> int,
d: int)
-> uint
{
0
}
"
))
(ert-deftest indent-multi-line-expr ()
(test-indent
"
fn foo()
{
x();
let a =
b();
}
"
))
(ert-deftest indent-match ()
(test-indent
"
fn foo() {
match blah {
Pattern => stuff(),
_ => whatever
}
}
"
))
(ert-deftest indent-match-multiline-pattern ()
(test-indent
"
fn foo() {
match blah {
Pattern |
Pattern2 => {
hello()
},
_ => whatever
}
}
"
))
(ert-deftest indent-indented-match ()
(test-indent
"
fn foo() {
let x =
match blah {
Pattern |
Pattern2 => {
hello()
},
_ => whatever
};
y();
}
"
))
(ert-deftest indent-curly-braces-within-parens ()
(test-indent
"
fn foo() {
let x =
foo(bar(|x| {
only_one_indent_here();
}));
y();
}
"
))
(ert-deftest indent-weirdly-indented-block ()
(rust-test-manip-code
"
fn foo() {
{
this_block_is_over_to_the_left_for_some_reason();
}
}
"
16
#'indent-for-tab-command
"
fn foo() {
{
this_block_is_over_to_the_left_for_some_reason();
}
}
"
))
(ert-deftest indent-multi-line-attrib ()
(test-indent
"
#[attrib(
this,
that,
theotherthing)]
fn function_with_multiline_attribute() {}
"
))
;; Make sure that in effort to cover match patterns we don't mistreat || or expressions
(ert-deftest indent-nonmatch-or-expression ()
(test-indent
"
fn foo() {
let x = foo() ||
bar();
}
"
))
(setq rust-test-motion-string
"
fn fn1(arg: int) -> bool {
let x = 5;
let y = b();
true
}
fn fn2(arg: int) -> bool {
let x = 5;
let y = b();
true
}
pub fn fn3(arg: int) -> bool {
let x = 5;
let y = b();
true
}
struct Foo {
x: int
}
"
rust-test-region-string rust-test-motion-string
rust-test-indent-motion-string
"
fn blank_line(arg:int) -> bool {
}
fn indenting_closing_brace() {
if(true) {
}
}
fn indenting_middle_of_line() {
if(true) {
push_me_out();
} else {
pull_me_back_in();
}
}
fn indented_already() {
// The previous line already has its spaces
}
"
;; Symbol -> (line column)
rust-test-positions-alist '((start-of-fn1 (2 0))
(start-of-fn1-middle-of-line (2 15))
(middle-of-fn1 (3 7))
(end-of-fn1 (6 0))
(between-fn1-fn2 (7 0))
(start-of-fn2 (8 0))
(middle-of-fn2 (10 4))
(before-start-of-fn1 (1 0))
(after-end-of-fn2 (13 0))
(beginning-of-fn3 (14 0))
(middle-of-fn3 (16 4))
(middle-of-struct (21 10))
(before-start-of-struct (19 0))
(after-end-of-struct (23 0))
(blank-line-indent-start (3 0))
(blank-line-indent-target (3 4))
(closing-brace-indent-start (8 1))
(closing-brace-indent-target (8 5))
(middle-push-indent-start (13 2))
(middle-push-indent-target (13 9))
(after-whitespace-indent-start (13 1))
(after-whitespace-indent-target (13 8))
(middle-pull-indent-start (15 19))
(middle-pull-indent-target (15 12))
(blank-line-indented-already-bol-start (20 0))
(blank-line-indented-already-bol-target (20 4))
(blank-line-indented-already-middle-start (20 2))
(blank-line-indented-already-middle-target (20 4))
(nonblank-line-indented-already-bol-start (21 0))
(nonblank-line-indented-already-bol-target (21 4))
(nonblank-line-indented-already-middle-start (21 2))
(nonblank-line-indented-already-middle-target (21 4))))
(defun rust-get-buffer-pos (pos-symbol)
"Get buffer position from POS-SYMBOL.
POS-SYMBOL is a symbol found in `rust-test-positions-alist'.
Convert the line-column information from that list into a buffer position value."
(interactive "P")
(pcase-let ((`(,line ,column) (cadr (assoc pos-symbol rust-test-positions-alist))))
(save-excursion
(goto-line line)
(move-to-column column)
(point))))
;;; FIXME: Maybe add an ERT explainer function (something that shows the
;;; surrounding code of the final point, not just the position).
(defun rust-test-motion (source-code init-pos final-pos manip-func &optional &rest args)
"Test that MANIP-FUNC moves point from INIT-POS to FINAL-POS.
If ARGS are provided, send them to MANIP-FUNC.
INIT-POS, FINAL-POS are position symbols found in `rust-test-positions-alist'."
(with-temp-buffer
(rust-mode)
(insert source-code)
(goto-char (rust-get-buffer-pos init-pos))
(apply manip-func args)
(should (equal (point) (rust-get-buffer-pos final-pos)))))
(defun rust-test-region (source-code init-pos reg-beg reg-end manip-func &optional &rest args)
"Test that MANIP-FUNC marks region from REG-BEG to REG-END.
INIT-POS is the initial position of point.
If ARGS are provided, send them to MANIP-FUNC.
All positions are position symbols found in `rust-test-positions-alist'."
(with-temp-buffer
(rust-mode)
(insert source-code)
(goto-char (rust-get-buffer-pos init-pos))
(apply manip-func args)
(should (equal (list (region-beginning) (region-end))
(list (rust-get-buffer-pos reg-beg)
(rust-get-buffer-pos reg-end))))))
(ert-deftest rust-beginning-of-defun-from-middle-of-fn ()
(rust-test-motion
rust-test-motion-string
'middle-of-fn1
'start-of-fn1
#'beginning-of-defun))
(ert-deftest rust-beginning-of-defun-from-end ()
(rust-test-motion
rust-test-motion-string
'end-of-fn1
'start-of-fn1
#'beginning-of-defun))
(ert-deftest rust-beginning-of-defun-before-open-brace ()
(rust-test-motion
rust-test-motion-string
'start-of-fn1-middle-of-line
'start-of-fn1
#'beginning-of-defun))
(ert-deftest rust-beginning-of-defun-between-fns ()
(rust-test-motion
rust-test-motion-string
'between-fn1-fn2
'start-of-fn1
#'beginning-of-defun))
(ert-deftest rust-beginning-of-defun-with-arg ()
(rust-test-motion
rust-test-motion-string
'middle-of-fn2
'start-of-fn1
#'beginning-of-defun 2))
(ert-deftest rust-beginning-of-defun-with-negative-arg ()
(rust-test-motion
rust-test-motion-string
'middle-of-fn1
'beginning-of-fn3
#'beginning-of-defun -2))
(ert-deftest rust-beginning-of-defun-pub-fn ()
(rust-test-motion
rust-test-motion-string
'middle-of-fn3
'beginning-of-fn3
#'beginning-of-defun))
(ert-deftest rust-end-of-defun-from-middle-of-fn ()
(rust-test-motion
rust-test-motion-string
'middle-of-fn1
'between-fn1-fn2
#'end-of-defun))
(ert-deftest rust-end-of-defun-from-beg ()
(rust-test-motion
rust-test-motion-string
'start-of-fn1
'between-fn1-fn2
#'end-of-defun))
(ert-deftest rust-end-of-defun-before-open-brace ()
(rust-test-motion
rust-test-motion-string
'start-of-fn1-middle-of-line
'between-fn1-fn2
#'end-of-defun))
(ert-deftest rust-end-of-defun-between-fns ()
(rust-test-motion
rust-test-motion-string
'between-fn1-fn2
'after-end-of-fn2
#'end-of-defun))
(ert-deftest rust-end-of-defun-with-arg ()
(rust-test-motion
rust-test-motion-string
'middle-of-fn1
'after-end-of-fn2
#'end-of-defun 2))
(ert-deftest rust-end-of-defun-with-negative-arg ()
(rust-test-motion
rust-test-motion-string
'middle-of-fn3
'between-fn1-fn2
#'end-of-defun -2))
(ert-deftest rust-mark-defun-from-middle-of-fn ()
(rust-test-region
rust-test-region-string
'middle-of-fn2
'between-fn1-fn2 'after-end-of-fn2
#'mark-defun))
(ert-deftest rust-mark-defun-from-end ()
(rust-test-region
rust-test-region-string
'end-of-fn1
'before-start-of-fn1 'between-fn1-fn2
#'mark-defun))
(ert-deftest rust-mark-defun-start-of-defun ()
(rust-test-region
rust-test-region-string
'start-of-fn2
'between-fn1-fn2 'after-end-of-fn2
#'mark-defun))
(ert-deftest rust-mark-defun-from-middle-of-struct ()
(rust-test-region
rust-test-region-string
'middle-of-struct
'before-start-of-struct 'after-end-of-struct
#'mark-defun))
(ert-deftest indent-line-blank-line-motion ()
(rust-test-motion
rust-test-indent-motion-string
'blank-line-indent-start
'blank-line-indent-target
#'indent-for-tab-command))
(ert-deftest indent-line-closing-brace-motion ()
(rust-test-motion
rust-test-indent-motion-string
'closing-brace-indent-start
'closing-brace-indent-target
#'indent-for-tab-command))
(ert-deftest indent-line-middle-push-motion ()
(rust-test-motion
rust-test-indent-motion-string
'middle-push-indent-start
'middle-push-indent-target
#'indent-for-tab-command))
(ert-deftest indent-line-after-whitespace-motion ()
(rust-test-motion
rust-test-indent-motion-string
'after-whitespace-indent-start
'after-whitespace-indent-target
#'indent-for-tab-command))
(ert-deftest indent-line-middle-pull-motion ()
(rust-test-motion
rust-test-indent-motion-string
'middle-pull-indent-start
'middle-pull-indent-target
#'indent-for-tab-command))
(ert-deftest indent-line-blank-line-indented-already-bol ()
(rust-test-motion
rust-test-indent-motion-string
'blank-line-indented-already-bol-start
'blank-line-indented-already-bol-target
#'indent-for-tab-command))
(ert-deftest indent-line-blank-line-indented-already-middle ()
(rust-test-motion
rust-test-indent-motion-string
'blank-line-indented-already-middle-start
'blank-line-indented-already-middle-target
#'indent-for-tab-command))
(ert-deftest indent-line-nonblank-line-indented-already-bol ()
(rust-test-motion
rust-test-indent-motion-string
'nonblank-line-indented-already-bol-start
'nonblank-line-indented-already-bol-target
#'indent-for-tab-command))
(ert-deftest indent-line-nonblank-line-indented-already-middle ()
(rust-test-motion
rust-test-indent-motion-string
'nonblank-line-indented-already-middle-start
'nonblank-line-indented-already-middle-target
#'indent-for-tab-command))
(defun rust-test-fontify-string (str)
(with-temp-buffer
(rust-mode)
(insert str)
(font-lock-fontify-buffer)
(buffer-string)))
(defun rust-test-group-str-by-face (str)
"Fontify `STR' in rust-mode and group it by face, returning a
list of substrings of `STR' each followed by its face."
(cl-loop with fontified = (rust-test-fontify-string str)
for start = 0 then end
while start
for end = (next-single-property-change start 'face fontified)
for prop = (get-text-property start 'face fontified)
for text = (substring-no-properties fontified start end)
if prop
append (list text prop)))
(defun rust-test-font-lock (source face-groups)
"Test that `SOURCE' fontifies to the expected `FACE-GROUPS'"
(should (equal (rust-test-group-str-by-face source)
face-groups)))
(ert-deftest font-lock-attribute-simple ()
(rust-test-font-lock
"#[foo]"
'("#[foo]" font-lock-preprocessor-face)))
(ert-deftest font-lock-attribute-inner ()
(rust-test-font-lock
"#![foo]"
'("#![foo]" font-lock-preprocessor-face)))
(ert-deftest font-lock-attribute-key-value ()
(rust-test-font-lock
"#[foo = \"bar\"]"
'("#[foo = " font-lock-preprocessor-face
"\"bar\"" font-lock-string-face
"]" font-lock-preprocessor-face)))
(ert-deftest font-lock-attribute-around-comment ()
(rust-test-font-lock
"#[foo /* bar */]"
'("#[foo " font-lock-preprocessor-face
"/* " font-lock-comment-delimiter-face
"bar */" font-lock-comment-face
"]" font-lock-preprocessor-face)))
(ert-deftest font-lock-attribute-inside-string ()
(rust-test-font-lock
"\"#[foo]\""
'("\"#[foo]\"" font-lock-string-face)))
(ert-deftest font-lock-attribute-inside-comment ()
(rust-test-font-lock
"/* #[foo] */"
'("/* " font-lock-comment-delimiter-face
"#[foo] */" font-lock-comment-face)))

View File

@ -1,520 +0,0 @@
;;; rust-mode.el --- A major emacs mode for editing Rust source code
;; Version: 0.2.0
;; Author: Mozilla
;; Url: https://github.com/rust-lang/rust
;; Keywords: languages
;;; Commentary:
;;
;;; Code:
(eval-when-compile (require 'misc))
;; for GNU Emacs < 24.3
(eval-when-compile
(unless (fboundp 'setq-local)
(defmacro setq-local (var val)
"Set variable VAR to value VAL in current buffer."
(list 'set (list 'make-local-variable (list 'quote var)) val))))
;; Syntax definitions and helpers
(defvar rust-mode-syntax-table
(let ((table (make-syntax-table)))
;; Operators
(dolist (i '(?+ ?- ?* ?/ ?& ?| ?^ ?! ?< ?> ?~ ?@))
(modify-syntax-entry i "." table))
;; Strings
(modify-syntax-entry ?\" "\"" table)
(modify-syntax-entry ?\\ "\\" table)
;; mark _ as a word constituent so that identifiers
;; such as xyz_type don't cause type to be highlighted
;; as a keyword
(modify-syntax-entry ?_ "w" table)
;; Comments
(modify-syntax-entry ?/ ". 124b" table)
(modify-syntax-entry ?* ". 23" table)
(modify-syntax-entry ?\n "> b" table)
(modify-syntax-entry ?\^m "> b" table)
table))
(defgroup rust-mode nil
"Support for Rust code."
:link '(url-link "http://www.rust-lang.org/")
:group 'languages)
(defcustom rust-indent-offset 4
"Indent Rust code by this number of spaces."
: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))))
(defun rust-rewind-irrelevant ()
(let ((starting (point)))
(skip-chars-backward "[:space:]\n")
(if (looking-back "\\*/") (backward-char))
(if (rust-in-str-or-cmnt)
(rust-rewind-past-str-cmnt))
(if (/= starting (point))
(rust-rewind-irrelevant))))
(defun rust-align-to-expr-after-brace ()
(save-excursion
(forward-char)
;; We don't want to indent out to the open bracket if the
;; open bracket ends the line
(when (not (looking-at "[[:blank:]]*\\(?://.*\\)?$"))
(when (looking-at "[[:space:]]")
(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))))
(defun rust-rewind-to-beginning-of-current-level-expr ()
(let ((current-level (rust-paren-level)))
(back-to-indentation)
(while (> (rust-paren-level) current-level)
(backward-up-list)
(back-to-indentation))))
(defun rust-mode-indent-line ()
(interactive)
(let ((indent
(save-excursion
(back-to-indentation)
;; Point is now at beginning of current line
(let* ((level (rust-paren-level))
(baseline
;; Our "baseline" is one level out from the indentation of the expression
;; containing the innermost enclosing opening bracket. That
;; way if we are within a block that has a different
;; indentation than this mode would give it, we still indent
;; 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))))))
(cond
;; A function return type is indented to the corresponding function arguments
((looking-at "->")
(save-excursion
(backward-list)
(or (rust-align-to-expr-after-brace)
(+ baseline rust-indent-offset))))
;; 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))
;; If we're in any other token-tree / sexp, then:
(t
(or
;; If we are inside a pair of braces, with something after the
;; open brace on the same line and ending with a comma, treat
;; it as fields and align them.
(when (> level 0)
(save-excursion
(rust-rewind-irrelevant)
(backward-up-list)
;; Point is now at the beginning of the containing set of braces
(rust-align-to-expr-after-brace)))
(progn
(back-to-indentation)
;; Point is now at the beginning of the current line
(if (or
;; If this line begins with "else" or "{", stay on the
;; baseline as well (we are continuing an expression,
;; but the "else" or "{" should align with the beginning
;; of the expression it's in.)
(looking-at "\\<else\\>\\|{")
(save-excursion
(rust-rewind-irrelevant)
;; Point is now at the end of the previous ine
(or
;; If we are at the first line, no indentation is needed, so stay at baseline...
(= 1 (line-number-at-pos (point)))
;; ..or if the previous line ends with any of these:
;; { ? : ( , ; [ }
;; then we are at the beginning of an expression, so stay on the baseline...
(looking-back "[(,:;?[{}]\\|[^|]|")
;; or if the previous line is the end of an attribute, stay at the baseline...
(progn (rust-rewind-to-beginning-of-current-level-expr) (looking-at "#")))))
baseline
;; Otherwise, we are continuing the same expression from the previous line,
;; so add one additional indent level
(+ baseline rust-indent-offset))))))))))
;; If we're at the beginning of the line (before or at the current
;; indentation), jump with the indentation change. Otherwise, save the
;; excursion so that adding the indentations will leave us at the
;; equivalent position within the line to where we were before.
(if (<= (current-column) (current-indentation))
(indent-line-to indent)
(save-excursion (indent-line-to indent)))))
;; Font-locking definitions and helpers
(defconst rust-mode-keywords
'("as"
"box" "break"
"const" "continue" "crate"
"do"
"else" "enum" "extern"
"false" "fn" "for"
"if" "impl" "in"
"let" "loop"
"match" "mod" "move" "mut"
"priv" "pub"
"ref" "return"
"self" "static" "struct" "super"
"true" "trait" "type"
"unsafe" "use"
"virtual"
"where" "while"))
(defconst rust-special-types
'("u8" "i8"
"u16" "i16"
"u32" "i32"
"u64" "i64"
"f32" "f64"
"float" "int" "uint" "isize" "usize"
"bool"
"str" "char"))
(defconst rust-re-ident "[[:word:][:multibyte:]_][[:word:][:multibyte:]_[:digit:]]*")
(defconst rust-re-CamelCase "[[:upper:]][[:word:][:multibyte:]_[:digit:]]*")
(defun rust-re-word (inner) (concat "\\<" inner "\\>"))
(defun rust-re-grab (inner) (concat "\\(" inner "\\)"))
(defun rust-re-grabword (inner) (rust-re-grab (rust-re-word inner)))
(defun rust-re-item-def (itype)
(concat (rust-re-word itype) "[[:space:]]+" (rust-re-grab rust-re-ident)))
(defvar rust-mode-font-lock-keywords
(append
`(
;; Keywords proper
(,(regexp-opt rust-mode-keywords 'words) . font-lock-keyword-face)
;; Special types
(,(regexp-opt rust-special-types 'words) . font-lock-type-face)
;; Attributes like `#[bar(baz)]` or `#![bar(baz)]` or `#[bar = "baz"]`
(,(rust-re-grab (concat "#\\!?\\[" rust-re-ident "[^]]*\\]"))
1 font-lock-preprocessor-face keep)
;; Syntax extension invocations like `foo!`, highlight including the !
(,(concat (rust-re-grab (concat rust-re-ident "!")) "[({[:space:][]")
1 font-lock-preprocessor-face)
;; Field names like `foo:`, highlight excluding the :
(,(concat (rust-re-grab rust-re-ident) ":[^:]") 1 font-lock-variable-name-face)
;; Module names like `foo::`, highlight including the ::
(,(rust-re-grab (concat rust-re-ident "::")) 1 font-lock-type-face)
;; Lifetimes like `'foo`
(,(concat "'" (rust-re-grab rust-re-ident) "[^']") 1 font-lock-variable-name-face)
;; Character constants, since they're not treated as strings
;; in order to have sufficient leeway to parse 'lifetime above.
(,(rust-re-grab "'[^']'") 1 font-lock-string-face)
(,(rust-re-grab "'\\\\[nrt]'") 1 font-lock-string-face)
(,(rust-re-grab "'\\\\x[[:xdigit:]]\\{2\\}'") 1 font-lock-string-face)
(,(rust-re-grab "'\\\\u[[:xdigit:]]\\{4\\}'") 1 font-lock-string-face)
(,(rust-re-grab "'\\\\U[[:xdigit:]]\\{8\\}'") 1 font-lock-string-face)
;; CamelCase Means Type Or Constructor
(,(rust-re-grabword rust-re-CamelCase) 1 font-lock-type-face)
)
;; Item definitions
(mapcar #'(lambda (x)
(list (rust-re-item-def (car x))
1 (cdr x)))
'(("enum" . font-lock-type-face)
("struct" . font-lock-type-face)
("type" . font-lock-type-face)
("mod" . font-lock-type-face)
("use" . font-lock-type-face)
("fn" . font-lock-function-name-face)
("static" . font-lock-constant-face)))))
(defun rust-fill-prefix-for-comment-start (line-start)
"Determine what to use for `fill-prefix' based on what is at the beginning of a line."
(let ((result
;; Replace /* with same number of spaces
(replace-regexp-in-string
"\\(?:/\\*+\\)[!*]"
(lambda (s)
;; We want the * to line up with the first * of the comment start
(concat (make-string (- (length s) 2) ?\x20) "*"))
line-start)))
;; Make sure we've got at least one space at the end
(if (not (= (aref result (- (length result) 1)) ?\x20))
(setq result (concat result " ")))
result))
(defun rust-in-comment-paragraph (body)
;; We might move the point to fill the next comment, but we don't want it
;; seeming to jump around on the user
(save-excursion
;; If we're outside of a comment, with only whitespace and then a comment
;; in front, jump to the comment and prepare to fill it.
(when (not (nth 4 (syntax-ppss)))
(beginning-of-line)
(when (looking-at (concat "[[:space:]\n]*" comment-start-skip))
(goto-char (match-end 0))))
;; We need this when we're moving the point around and then checking syntax
;; while doing paragraph fills, because the cache it uses isn't always
;; invalidated during this.
(syntax-ppss-flush-cache 1)
;; If we're at the beginning of a comment paragraph with nothing but
;; whitespace til the next line, jump to the next line so that we use the
;; existing prefix to figure out what the new prefix should be, rather than
;; inferring it from the comment start.
(let ((next-bol (line-beginning-position 2)))
(while (save-excursion
(end-of-line)
(syntax-ppss-flush-cache 1)
(and (nth 4 (syntax-ppss))
(save-excursion
(beginning-of-line)
(looking-at paragraph-start))
(looking-at "[[:space:]]*$")
(nth 4 (syntax-ppss next-bol))))
(goto-char next-bol)))
(syntax-ppss-flush-cache 1)
;; If we're on the last line of a multiline-style comment that started
;; above, back up one line so we don't mistake the * of the */ that ends
;; the comment for a prefix.
(when (save-excursion
(and (nth 4 (syntax-ppss (line-beginning-position 1)))
(looking-at "[[:space:]]*\\*/")))
(goto-char (line-end-position 0)))
(funcall body)))
(defun rust-with-comment-fill-prefix (body)
(let*
((line-string (buffer-substring-no-properties
(line-beginning-position) (line-end-position)))
(line-comment-start
(when (nth 4 (syntax-ppss))
(cond
;; If we're inside the comment and see a * prefix, use it
((string-match "^\\([[:space:]]*\\*+[[:space:]]*\\)"
line-string)
(match-string 1 line-string))
;; If we're at the start of a comment, figure out what prefix
;; to use for the subsequent lines after it
((string-match (concat "[[:space:]]*" comment-start-skip) line-string)
(rust-fill-prefix-for-comment-start
(match-string 0 line-string))))))
(fill-prefix
(or line-comment-start
fill-prefix)))
(funcall body)))
(defun rust-find-fill-prefix ()
(rust-with-comment-fill-prefix (lambda () fill-prefix)))
(defun rust-fill-paragraph (&rest args)
"Special wrapping for `fill-paragraph' to handle multi-line comments with a * prefix on each line."
(rust-in-comment-paragraph
(lambda ()
(rust-with-comment-fill-prefix
(lambda ()
(let
((fill-paragraph-function
(if (not (eq fill-paragraph-function 'rust-fill-paragraph))
fill-paragraph-function))
(fill-paragraph-handle-comment t))
(apply 'fill-paragraph args)
t))))))
(defun rust-do-auto-fill (&rest args)
"Special wrapping for `do-auto-fill' to handle multi-line comments with a * prefix on each line."
(rust-with-comment-fill-prefix
(lambda ()
(apply 'do-auto-fill args)
t)))
(defun rust-fill-forward-paragraph (arg)
;; This is to work around some funny behavior when a paragraph separator is
;; at the very top of the file and there is a fill prefix.
(let ((fill-prefix nil)) (forward-paragraph arg)))
(defun rust-comment-indent-new-line (&optional arg)
(rust-with-comment-fill-prefix
(lambda () (comment-indent-new-line arg))))
;;; Imenu support
(defvar rust-imenu-generic-expression
(append (mapcar #'(lambda (x)
(list nil (rust-re-item-def x) 1))
'("enum" "struct" "type" "mod" "fn" "trait"))
`(("Impl" ,(rust-re-item-def "impl") 1)))
"Value for `imenu-generic-expression' in Rust mode.
Create a flat index of the item definitions in a Rust file.
Imenu will show all the enums, structs, etc. at the same level.
Implementations will be shown under the `Impl` subheading. Use
idomenu (imenu with `ido-mode') for best mileage.")
;;; Defun Motions
;;; Start of a Rust item
(defvar rust-top-item-beg-re
(concat "^\\s-*\\(?:priv\\|pub\\)?\\s-*"
(regexp-opt
'("enum" "struct" "type" "mod" "use" "fn" "static" "impl"
"extern" "impl" "static" "trait"))))
(defun rust-beginning-of-defun (&optional arg)
"Move backward to the beginning of the current defun.
With ARG, move backward multiple defuns. Negative ARG means
move forward.
This is written mainly to be used as `beginning-of-defun-function' for Rust.
Don't move to the beginning of the line. `beginning-of-defun',
which calls this, does that afterwards."
(interactive "p")
(re-search-backward (concat "^\\(" rust-top-item-beg-re "\\)\\_>")
nil 'move (or arg 1)))
(defun rust-end-of-defun ()
"Move forward to the next end of defun.
With argument, do it that many times.
Negative argument -N means move back to Nth preceding end of defun.
Assume that this is called after beginning-of-defun. So point is
at the beginning of the defun body.
This is written mainly to be used as `end-of-defun-function' for Rust."
(interactive "p")
;; Find the opening brace
(re-search-forward "[{]" nil t)
(goto-char (match-beginning 0))
;; Go to the closing brace
(forward-sexp))
;; For compatibility with Emacs < 24, derive conditionally
(defalias 'rust-parent-mode
(if (fboundp 'prog-mode) 'prog-mode 'fundamental-mode))
;;;###autoload
(define-derived-mode rust-mode rust-parent-mode "Rust"
"Major mode for Rust code."
:group 'rust-mode
:syntax-table rust-mode-syntax-table
;; Indentation
(setq-local indent-line-function 'rust-mode-indent-line)
;; Fonts
(setq-local font-lock-defaults '(rust-mode-font-lock-keywords nil nil nil nil))
;; Misc
(setq-local comment-start "// ")
(setq-local comment-end "")
(setq-local indent-tabs-mode nil)
;; Allow paragraph fills for comments
(setq-local comment-start-skip "\\(?://[/!]*\\|/\\*[*!]?\\)[[:space:]]*")
(setq-local paragraph-start
(concat "[[:space:]]*\\(?:" comment-start-skip "\\|\\*/?[[:space:]]*\\|\\)$"))
(setq-local paragraph-separate paragraph-start)
(setq-local normal-auto-fill-function 'rust-do-auto-fill)
(setq-local fill-paragraph-function 'rust-fill-paragraph)
(setq-local fill-forward-paragraph-function 'rust-fill-forward-paragraph)
(setq-local adaptive-fill-function 'rust-find-fill-prefix)
(setq-local comment-multi-line t)
(setq-local comment-line-break-function 'rust-comment-indent-new-line)
(setq-local imenu-generic-expression rust-imenu-generic-expression)
(setq-local beginning-of-defun-function 'rust-beginning-of-defun)
(setq-local end-of-defun-function 'rust-end-of-defun))
;;;###autoload
(add-to-list 'auto-mode-alist '("\\.rs\\'" . rust-mode))
(defun rust-mode-reload ()
(interactive)
(unload-feature 'rust-mode)
(require 'rust-mode)
(rust-mode))
;; Issue #6887: Rather than inheriting the 'gnu compilation error
;; regexp (which is broken on a few edge cases), add our own 'rust
;; compilation error regexp and use it instead.
(defvar rustc-compilation-regexps
(let ((file "\\([^\n]+\\)")
(start-line "\\([0-9]+\\)")
(start-col "\\([0-9]+\\)")
(end-line "\\([0-9]+\\)")
(end-col "\\([0-9]+\\)")
(error-or-warning "\\(?:[Ee]rror\\|\\([Ww]arning\\)\\)"))
(let ((re (concat "^" file ":" start-line ":" start-col
": " end-line ":" end-col
" \\(?:[Ee]rror\\|\\([Ww]arning\\)\\):")))
(cons re '(1 (2 . 4) (3 . 5) (6)))))
"Specifications for matching errors in rustc invocations.
See `compilation-error-regexp-alist for help on their format.")
(eval-after-load 'compile
'(progn
(add-to-list 'compilation-error-regexp-alist-alist
(cons 'rustc rustc-compilation-regexps))
(add-to-list 'compilation-error-regexp-alist 'rustc)))
(provide 'rust-mode)
;;; rust-mode.el ends here

View File

@ -1,10 +0,0 @@
Add syntax highlighting for Mozilla Rust in GtkSourceView (used by GEdit).
Instructions for Ubuntu Linux 12.04+
1) Close all instances of GEdit
2) Copy the included "share" folder into "~/.local/"
3) Open a shell in "~/.local/share/" and run "update-mime-database mime"

View File

@ -1,340 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Syntax highlighting for the under-development Mozilla Rust language -->
<language id="rust" _name="Rust" version="2.0" _section="Sources">
<metadata>
<property name="mimetypes">text/x-rust</property>
<property name="globs">*.rs</property>
<property name="line-comment-start">//</property>
<property name="block-comment-start">/*</property>
<property name="block-comment-end">*/</property>
</metadata>
<styles>
<style id="comment" _name="Comment" map-to="def:comment"/>
<style id="string" _name="String" map-to="def:string"/>
<style id="char" _name="Character" map-to="def:character"/>
<style id="keyword" _name="Keyword" map-to="def:keyword"/>
<style id="type" _name="Data Type" map-to="def:type"/>
<style id="constant" _name="Constant" map-to="def:constant"/>
<style id="identifier" _name="Identifier" map-to="def:identifier"/>
<style id="number" _name="Number" map-to="def:number"/>
<style id="scope" _name="Scope" map-to="def:preprocessor"/>
<style id="attribute" _name="Attribute" map-to="def:preprocessor"/>
<style id="macro" _name="Macro" map-to="def:preprocessor"/>
</styles>
<definitions>
<context id="function" style-ref="keyword">
<keyword>fn</keyword>
</context>
<context id="type" style-ref="keyword">
<keyword>type</keyword>
</context>
<context id="keywords" style-ref="keyword">
<keyword>as</keyword>
<keyword>assert</keyword>
<keyword>break</keyword>
<keyword>box</keyword>
<keyword>const</keyword>
<keyword>continue</keyword>
<keyword>crate</keyword>
<keyword>do</keyword>
<keyword>drop</keyword>
<keyword>else</keyword>
<keyword>enum</keyword>
<keyword>export</keyword>
<keyword>extern</keyword>
<keyword>fail</keyword>
<keyword>for</keyword>
<keyword>if</keyword>
<keyword>impl</keyword>
<keyword>in</keyword>
<keyword>let</keyword>
<keyword>log</keyword>
<keyword>loop</keyword>
<keyword>match</keyword>
<keyword>mod</keyword>
<keyword>move</keyword>
<keyword>mut</keyword>
<keyword>priv</keyword>
<keyword>pub</keyword>
<keyword>pure</keyword>
<keyword>ref</keyword>
<keyword>return</keyword>
<keyword>static</keyword>
<keyword>struct</keyword>
<keyword>trait</keyword>
<keyword>unsafe</keyword>
<keyword>use</keyword>
<keyword>virtual</keyword>
<keyword>where</keyword>
<keyword>while</keyword>
</context>
<context id="types" style-ref="type">
<keyword>bool</keyword>
<keyword>int</keyword>
<keyword>isize</keyword>
<keyword>uint</keyword>
<keyword>usize</keyword>
<keyword>i8</keyword>
<keyword>i16</keyword>
<keyword>i32</keyword>
<keyword>i64</keyword>
<keyword>u8</keyword>
<keyword>u16</keyword>
<keyword>u32</keyword>
<keyword>u64</keyword>
<keyword>f32</keyword>
<keyword>f64</keyword>
<keyword>char</keyword>
<keyword>str</keyword>
<keyword>Option</keyword>
<keyword>Result</keyword>
</context>
<context id="ctypes" style-ref="type">
<keyword>c_float</keyword>
<keyword>c_double</keyword>
<keyword>c_void</keyword>
<keyword>FILE</keyword>
<keyword>fpos_t</keyword>
<keyword>DIR</keyword>
<keyword>dirent</keyword>
<keyword>c_char</keyword>
<keyword>c_schar</keyword>
<keyword>c_uchar</keyword>
<keyword>c_short</keyword>
<keyword>c_ushort</keyword>
<keyword>c_int</keyword>
<keyword>c_uint</keyword>
<keyword>c_long</keyword>
<keyword>c_ulong</keyword>
<keyword>size_t</keyword>
<keyword>ptrdiff_t</keyword>
<keyword>clock_t</keyword>
<keyword>time_t</keyword>
<keyword>c_longlong</keyword>
<keyword>c_ulonglong</keyword>
<keyword>intptr_t</keyword>
<keyword>uintptr_t</keyword>
<keyword>off_t</keyword>
<keyword>dev_t</keyword>
<keyword>ino_t</keyword>
<keyword>pid_t</keyword>
<keyword>mode_t</keyword>
<keyword>ssize_t</keyword>
</context>
<context id="self" style-ref="identifier">
<keyword>self</keyword>
</context>
<context id="constants" style-ref="constant">
<keyword>true</keyword>
<keyword>false</keyword>
<keyword>Some</keyword>
<keyword>None</keyword>
<keyword>Ok</keyword>
<keyword>Err</keyword>
<keyword>Success</keyword>
<keyword>Failure</keyword>
<keyword>Cons</keyword>
<keyword>Nil</keyword>
</context>
<context id="cconstants" style-ref="constant">
<keyword>EXIT_FAILURE</keyword>
<keyword>EXIT_SUCCESS</keyword>
<keyword>RAND_MAX</keyword>
<keyword>EOF</keyword>
<keyword>SEEK_SET</keyword>
<keyword>SEEK_CUR</keyword>
<keyword>SEEK_END</keyword>
<keyword>_IOFBF</keyword>
<keyword>_IONBF</keyword>
<keyword>_IOLBF</keyword>
<keyword>BUFSIZ</keyword>
<keyword>FOPEN_MAX</keyword>
<keyword>FILENAME_MAX</keyword>
<keyword>L_tmpnam</keyword>
<keyword>TMP_MAX</keyword>
<keyword>O_RDONLY</keyword>
<keyword>O_WRONLY</keyword>
<keyword>O_RDWR</keyword>
<keyword>O_APPEND</keyword>
<keyword>O_CREAT</keyword>
<keyword>O_EXCL</keyword>
<keyword>O_TRUNC</keyword>
<keyword>S_IFIFO</keyword>
<keyword>S_IFCHR</keyword>
<keyword>S_IFBLK</keyword>
<keyword>S_IFDIR</keyword>
<keyword>S_IFREG</keyword>
<keyword>S_IFMT</keyword>
<keyword>S_IEXEC</keyword>
<keyword>S_IWRITE</keyword>
<keyword>S_IREAD</keyword>
<keyword>S_IRWXU</keyword>
<keyword>S_IXUSR</keyword>
<keyword>S_IWUSR</keyword>
<keyword>S_IRUSR</keyword>
<keyword>F_OK</keyword>
<keyword>R_OK</keyword>
<keyword>W_OK</keyword>
<keyword>X_OK</keyword>
<keyword>STDIN_FILENO</keyword>
<keyword>STDOUT_FILENO</keyword>
<keyword>STDERR_FILENO</keyword>
</context>
<context id="line-comment" style-ref="comment" end-at-line-end="true" class="comment" class-disabled="no-spell-check">
<start>//</start>
<include>
<context ref="def:in-line-comment"/>
</include>
</context>
<context id="block-comment" style-ref="comment" class="comment" class-disabled="no-spell-check">
<start>/\*</start>
<end>\*/</end>
<include>
<context ref="def:in-comment"/>
</include>
</context>
<define-regex id="int_suffix" extended="true">
(i8|i16|i32|i64|i|u8|u16|u32|u64|u)
</define-regex>
<define-regex id="exponent" extended="true">
([eE][+-]?[0-9_]+)
</define-regex>
<define-regex id="float_suffix" extended="true">
(\%{exponent}?(f32|f64)?)|(\.[0-9][0-9_]*\%{exponent}?)?(f32|f64)?|\.
</define-regex>
<define-regex id="num_suffix" extended="true">
\%{int_suffix}|\%{float_suffix}
</define-regex>
<define-regex id="hex_digit" extended="true">
[0-9a-fA-F]
</define-regex>
<define-regex id="oct_digit" extended="true">
[0-7]
</define-regex>
<context id="number" style-ref="number">
<match extended="true">
((?&lt;=\.\.)|(?&lt;![\w\.]))
(
[1-9][0-9_]*\%{num_suffix}?|
0[0-9_]*\%{num_suffix}?|
0b[01_]+\%{int_suffix}?|
0o(\%{oct_digit}|_)+\%{int_suffix}?|
0x(\%{hex_digit}|_)+\%{int_suffix}?
)
((?![\w\.].)|(?=\.\.))
</match>
</context>
<define-regex id="ident" extended="true">
([^[:cntrl:][:space:][:punct:][:digit:]]|_)([^[:cntrl:][:punct:][:space:]]|_)*
</define-regex>
<context id="scope" style-ref="scope">
<match extended="true">
\%{ident}::
</match>
</context>
<context id="macro" style-ref="macro">
<match extended="true">
\%{ident}!
</match>
</context>
<context id="lifetime" style-ref="keyword">
<match extended="true">
'\%{ident}
</match>
</context>
<define-regex id="common_escape" extended="true">
'|"|
\\|n|r|t|0|
x\%{hex_digit}{2}|
u{\%{hex_digit}{1,6}}|
u\%{hex_digit}{4}|
U\%{hex_digit}{8}
</define-regex>
<context id="string_escape" style-ref="def:special-char">
<match>\\\%{common_escape}</match>
</context>
<context id="raw-string" style-ref="string" class="string" class-disabled="no-spell-check">
<start>r(#*)"</start>
<end>"\%{1@start}</end>
<include>
<context ref="def:line-continue"/>
</include>
</context>
<context id="string" style-ref="string" class="string" class-disabled="no-spell-check">
<start>"</start>
<end>"</end>
<include>
<context ref="string_escape"/>
<context ref="def:line-continue"/>
</include>
</context>
<context id="char" style-ref="char">
<match extended="true">'([^\\']|\\\%{common_escape})'</match>
</context>
<context id="attribute" style-ref="attribute" class="attribute">
<start extended="true">\#!?\[</start>
<end>\]</end>
<include>
<context ref="def:in-comment"/>
<context ref="string"/>
<context ref="raw-string"/>
</include>
</context>
<context id="rust" class="no-spell-check">
<include>
<context ref="function"/>
<context ref="type"/>
<context ref="keywords"/>
<context ref="types"/>
<context ref="ctypes"/>
<context ref="self"/>
<context ref="macro"/>
<context ref="constants"/>
<context ref="cconstants"/>
<context ref="line-comment"/>
<context ref="block-comment"/>
<context ref="number"/>
<context ref="scope"/>
<context ref="string"/>
<context ref="raw-string"/>
<context ref="char"/>
<context ref="lifetime"/>
<context ref="attribute"/>
</include>
</context>
</definitions>
</language>

View File

@ -1,6 +0,0 @@
<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>
<mime-type type="text/x-rust">
<comment>Rust Source</comment>
<glob pattern="*.rs"/>
</mime-type>
</mime-info>

View File

@ -1,304 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE language SYSTEM "language.dtd"
[
<!-- FIXME: Kate's regex engine has very limited support for
predefined char classes, so making rustIdent consistent with actual
Rust identifiers will be a bit difficult -->
<!ENTITY rustIdent "[a-zA-Z_][a-zA-Z_0-9]*">
<!ENTITY rustIntSuf "([iu](8|16|32|64)?)?">
]>
<language name="Rust" version="1.0.0" kateversion="2.4" section="Sources" extensions="*.rs" mimetype="text/x-rust" priority="15">
<highlighting>
<list name="fn">
<item> fn </item>
</list>
<list name="type">
<item> type </item>
</list>
<list name="reserved">
<item> abstract </item>
<item> alignof </item>
<item> be </item>
<item> do </item>
<item> final </item>
<item> offsetof </item>
<item> override </item>
<item> priv </item>
<item> pure </item>
<item> sizeof </item>
<item> typeof </item>
<item> unsized </item>
<item> yield </item>
</list>
<list name="keywords">
<item> as </item>
<item> box </item>
<item> break </item>
<item> const </item>
<item> continue </item>
<item> crate </item>
<item> else </item>
<item> enum </item>
<item> extern </item>
<item> for </item>
<item> if </item>
<item> impl </item>
<item> in </item>
<item> let </item>
<item> loop </item>
<item> match </item>
<item> mod </item>
<item> move </item>
<item> mut </item>
<item> pub </item>
<item> ref </item>
<item> return </item>
<item> static </item>
<item> struct </item>
<item> super </item>
<item> trait </item>
<item> unsafe </item>
<item> use </item>
<item> virtual </item>
<item> where </item>
<item> while </item>
</list>
<list name="traits">
<item> Const </item>
<item> Copy </item>
<item> Send </item>
<item> Owned </item>
<item> Sized </item>
<item> Eq </item>
<item> Ord </item>
<item> Num </item>
<item> Ptr </item>
<item> Drop </item>
<item> Add </item>
<item> Sub </item>
<item> Mul </item>
<item> Quot </item>
<item> Rem </item>
<item> Neg </item>
<item> BitAnd </item>
<item> BitOr </item>
<item> BitXor </item>
<item> Shl </item>
<item> Shr </item>
<item> Index </item>
<item> Not </item>
</list>
<list name="types">
<item> bool </item>
<item> int </item>
<item> isize </item>
<item> uint </item>
<item> usize </item>
<item> i8 </item>
<item> i16 </item>
<item> i32 </item>
<item> i64 </item>
<item> u8 </item>
<item> u16 </item>
<item> u32 </item>
<item> u64 </item>
<item> f32 </item>
<item> f64 </item>
<item> float </item>
<item> char </item>
<item> str </item>
<item> Option </item>
<item> Result </item>
<item> Self </item>
</list>
<list name="ctypes">
<item> c_float </item>
<item> c_double </item>
<item> c_void </item>
<item> FILE </item>
<item> fpos_t </item>
<item> DIR </item>
<item> dirent </item>
<item> c_char </item>
<item> c_schar </item>
<item> c_uchar </item>
<item> c_short </item>
<item> c_ushort </item>
<item> c_int </item>
<item> c_uint </item>
<item> c_long </item>
<item> c_ulong </item>
<item> size_t </item>
<item> ptrdiff_t </item>
<item> clock_t </item>
<item> time_t </item>
<item> c_longlong </item>
<item> c_ulonglong </item>
<item> intptr_t </item>
<item> uintptr_t </item>
<item> off_t </item>
<item> dev_t </item>
<item> ino_t </item>
<item> pid_t </item>
<item> mode_t </item>
<item> ssize_t </item>
</list>
<list name="self">
<item> self </item>
</list>
<list name="constants">
<item> true </item>
<item> false </item>
<item> Some </item>
<item> None </item>
<item> Ok </item>
<item> Err </item>
<item> Success </item>
<item> Failure </item>
<item> Cons </item>
<item> Nil </item>
</list>
<list name="cconstants">
<item> EXIT_FAILURE </item>
<item> EXIT_SUCCESS </item>
<item> RAND_MAX </item>
<item> EOF </item>
<item> SEEK_SET </item>
<item> SEEK_CUR </item>
<item> SEEK_END </item>
<item> _IOFBF </item>
<item> _IONBF </item>
<item> _IOLBF </item>
<item> BUFSIZ </item>
<item> FOPEN_MAX </item>
<item> FILENAME_MAX </item>
<item> L_tmpnam </item>
<item> TMP_MAX </item>
<item> O_RDONLY </item>
<item> O_WRONLY </item>
<item> O_RDWR </item>
<item> O_APPEND </item>
<item> O_CREAT </item>
<item> O_EXCL </item>
<item> O_TRUNC </item>
<item> S_IFIFO </item>
<item> S_IFCHR </item>
<item> S_IFBLK </item>
<item> S_IFDIR </item>
<item> S_IFREG </item>
<item> S_IFMT </item>
<item> S_IEXEC </item>
<item> S_IWRITE </item>
<item> S_IREAD </item>
<item> S_IRWXU </item>
<item> S_IXUSR </item>
<item> S_IWUSR </item>
<item> S_IRUSR </item>
<item> F_OK </item>
<item> R_OK </item>
<item> W_OK </item>
<item> X_OK </item>
<item> STDIN_FILENO </item>
<item> STDOUT_FILENO </item>
<item> STDERR_FILENO </item>
</list>
<contexts>
<context attribute="Normal Text" lineEndContext="#stay" name="Normal">
<DetectSpaces/>
<keyword String="fn" attribute="Keyword" context="Function"/>
<keyword String="type" attribute="Keyword" context="Type"/>
<keyword String="reserved" attribute="Keyword" context="#stay"/>
<keyword String="keywords" attribute="Keyword" context="#stay"/>
<keyword String="types" attribute="Type" context="#stay"/>
<keyword String="traits" attribute="Trait" context="#stay"/>
<keyword String="ctypes" attribute="CType" context="#stay"/>
<keyword String="self" attribute="Self" context="#stay"/>
<keyword String="constants" attribute="Constant" context="#stay"/>
<keyword String="cconstants" attribute="CConstant" context="#stay"/>
<Detect2Chars char="/" char1="/" attribute="Comment" context="Commentar 1"/>
<Detect2Chars char="/" char1="*" attribute="Comment" context="Commentar 2" beginRegion="Comment"/>
<RegExpr String="0x[0-9a-fA-F_]+&rustIntSuf;" attribute="Number" context="#stay"/>
<RegExpr String="0o[0-7_]+&rustIntSuf;" attribute="Number" context="#stay"/>
<RegExpr String="0b[0-1_]+&rustIntSuf;" attribute="Number" context="#stay"/>
<RegExpr String="[0-9][0-9_]*\.[0-9_]*([eE][+-]?[0-9_]+)?(f32|f64|f)?" attribute="Number" context="#stay"/>
<RegExpr String="[0-9][0-9_]*&rustIntSuf;" attribute="Number" context="#stay"/>
<Detect2Chars char="#" char1="[" attribute="Attribute" context="Attribute" beginRegion="Attribute"/>
<StringDetect String="#![" attribute="Attribute" context="Attribute" beginRegion="Attribute"/>
<RegExpr String="&rustIdent;::" attribute="Scope"/>
<RegExpr String="&rustIdent;!" attribute="Macro"/>
<RegExpr String="&apos;&rustIdent;(?!&apos;)" attribute="Lifetime"/>
<DetectChar char="{" attribute="Symbol" context="#stay" beginRegion="Brace" />
<DetectChar char="}" attribute="Symbol" context="#stay" endRegion="Brace" />
<DetectChar char="&quot;" attribute="String" context="String"/>
<DetectChar char="&apos;" attribute="Character" context="Character"/>
<DetectChar char="[" attribute="Symbol" context="#stay" beginRegion="Bracket" />
<DetectChar char="]" attribute="Symbol" context="#stay" endRegion="Bracket" />
<DetectIdentifier/>
</context>
<context attribute="Attribute" lineEndContext="#stay" name="Attribute">
<DetectChar char="]" attribute="Attribute" context="#pop" endRegion="Attribute"/>
<IncludeRules context="Normal"/>
</context>
<context attribute="Definition" lineEndContext="#stay" name="Function">
<DetectSpaces/>
<DetectChar char="(" attribute="Normal Text" context="#pop"/>
<DetectChar char="&lt;" attribute="Normal Text" context="#pop"/>
</context>
<context attribute="Definition" lineEndContext="#stay" name="Type">
<DetectSpaces/>
<DetectChar char="=" attribute="Normal Text" context="#pop"/>
<DetectChar char="&lt;" attribute="Normal Text" context="#pop"/>
</context>
<context attribute="String" lineEndContext="#pop" name="String">
<LineContinue attribute="String" context="#stay"/>
<DetectChar char="\" attribute="CharEscape" context="CharEscape"/>
<DetectChar attribute="String" context="#pop" char="&quot;"/>
</context>
<context attribute="Character" lineEndContext="#pop" name="Character">
<DetectChar char="\" attribute="CharEscape" context="CharEscape"/>
<DetectChar attribute="Character" context="#pop" char="&apos;"/>
</context>
<context attribute="CharEscape" lineEndContext="#pop" name="CharEscape">
<AnyChar String="nrt\&apos;&quot;" attribute="CharEscape" context="#pop"/>
<RegExpr String="x[0-9a-fA-F]{2}" attribute="CharEscape" context="#pop"/>
<RegExpr String="u\{[0-9a-fA-F]{1,6}\}" attribute="CharEscape" context="#pop"/>
<RegExpr String="u[0-9a-fA-F]{4}" attribute="CharEscape" context="#pop"/>
<RegExpr String="U[0-9a-fA-F]{8}" attribute="CharEscape" context="#pop"/>
<RegExpr String="." attribute="Error" context="#pop"/>
</context>
<context attribute="Comment" lineEndContext="#pop" name="Commentar 1"/>
<context attribute="Comment" lineEndContext="#stay" name="Commentar 2">
<DetectSpaces/>
<Detect2Chars char="*" char1="/" attribute="Comment" context="#pop" endRegion="Comment"/>
</context>
</contexts>
<itemDatas>
<itemData name="Normal Text" defStyleNum="dsNormal"/>
<itemData name="Keyword" defStyleNum="dsKeyword" color="#770088" bold="1"/>
<itemData name="Self" defStyleNum="dsKeyword" color="#FF0000" bold="1"/>
<itemData name="Type" defStyleNum="dsKeyword" color="#4e9a06" bold="1"/>
<itemData name="Trait" defStyleNum="dsKeyword" color="#4e9a06" bold="1"/>
<itemData name="CType" defStyleNum="dsNormal" color="#4e9a06"/>
<itemData name="Constant" defStyleNum="dsKeyword" color="#116644"/>
<itemData name="CConstant" defStyleNum="dsNormal" color="#116644"/>
<itemData name="Definition" defStyleNum="dsNormal" color="#0000FF"/>
<itemData name="Comment" defStyleNum="dsComment" color="#AA5500"/>
<itemData name="Scope" defStyleNum="dsNormal" color="#0055AA"/>
<itemData name="Number" defStyleNum="dsDecVal" color="#116644"/>
<itemData name="String" defStyleNum="dsString" color="#FF0000"/>
<itemData name="CharEscape" defStyleNum="dsChar" color="#FF0000" bold="1"/>
<itemData name="Character" defStyleNum="dsChar" color="#FF0000"/>
<itemData name="Macro" defStyleNum="dsOthers"/>
<itemData name="Attribute" defStyleNum="dsOthers"/>
<itemData name="Lifetime" defStyleNum="dsOthers" bold="1"/>
<itemData name="Error" defStyleNum="dsError"/>
</itemDatas>
</highlighting>
<general>
<comments>
<comment name="singleLine" start="//" />
<comment name="multiLine" start="/*" end="*/" region="Comment"/>
</comments>
<keywords casesensitive="1" />
</general>
</language>

View File

@ -1,35 +0,0 @@
# Nano configuration for Rust
# Copyright 2015 The Rust Project Developers.
#
# NOTE: Rules are applied in order: later rules re-colorize matching text.
syntax "rust" "\.rs"
# function definition
color magenta "fn [a-z0-9_]+"
# Reserved words
color yellow "\<(abstract|alignof|as|be|box|break|const|continue|crate|do|else|enum|extern|false|final|fn|for|if|impl|in|let|loop|macro|match|mod|move|mut|offsetof|override|priv|pub|pure|ref|return|sizeof|static|self|struct|super|true|trait|type|typeof|unsafe|unsized|use|virtual|where|while|yield)\>"
# macros
color red "[a-z_]+!"
# Constants
color magenta "[A-Z][A-Z_]+"
# Traits/Enums/Structs/Types/etc.
color magenta "[A-Z][a-z]+"
# Strings
color green "\".*\""
color green start="\".*\\$" end=".*\""
# NOTE: This isn't accurate but matching "#{0,} for the end of the string is too liberal
color green start="r#+\"" end="\"#+"
# Comments
color blue "//.*"
# Attributes
color magenta start="#!\[" end="\]"
# Some common markers
color brightcyan "(XXX|TODO|FIXME|\?\?\?)"

View File

@ -1,31 +0,0 @@
if !exists('g:rust_conceal') || !has('conceal') || &enc != 'utf-8'
finish
endif
" For those who don't want to see `::`...
if exists('g:rust_conceal_mod_path')
syn match rustNiceOperator "::" conceal cchar=
endif
syn match rustRightArrowHead contained ">" conceal cchar= 
syn match rustRightArrowTail contained "-" conceal cchar=
syn match rustNiceOperator "->" contains=rustRightArrowHead,rustRightArrowTail
syn match rustFatRightArrowHead contained ">" conceal cchar= 
syn match rustFatRightArrowTail contained "=" conceal cchar=
syn match rustNiceOperator "=>" contains=rustFatRightArrowHead,rustFatRightArrowTail
syn match rustNiceOperator /\<\@!_\(_*\>\)\@=/ conceal cchar=
" For those who don't want to see `pub`...
if exists('g:rust_conceal_pub')
syn match rustPublicSigil contained "pu" conceal cchar=
syn match rustPublicRest contained "b" conceal cchar= 
syn match rustNiceOperator "pub " contains=rustPublicSigil,rustPublicRest
endif
hi link rustNiceOperator Operator
if !exists('g:rust_conceal_mod_path')
hi! link Conceal Operator
endif

View File

@ -1,225 +0,0 @@
" Author: Kevin Ballard
" Description: Helper functions for Rust commands/mappings
" Last Modified: May 27, 2014
" Jump {{{1
function! rust#Jump(mode, function) range
let cnt = v:count1
normal! m'
if a:mode ==# 'v'
norm! gv
endif
let foldenable = &foldenable
set nofoldenable
while cnt > 0
execute "call <SID>Jump_" . a:function . "()"
let cnt = cnt - 1
endwhile
let &foldenable = foldenable
endfunction
function! s:Jump_Back()
call search('{', 'b')
keepjumps normal! w99[{
endfunction
function! s:Jump_Forward()
normal! j0
call search('{', 'b')
keepjumps normal! w99[{%
call search('{')
endfunction
" Run {{{1
function! rust#Run(bang, args)
if a:bang
let idx = index(a:args, '--')
if idx != -1
let rustc_args = idx == 0 ? [] : a:args[:idx-1]
let args = a:args[idx+1:]
else
let rustc_args = a:args
let args = []
endif
else
let rustc_args = []
let args = a:args
endif
let b:rust_last_rustc_args = rustc_args
let b:rust_last_args = args
call s:WithPath(function("s:Run"), rustc_args, args)
endfunction
function! s:Run(path, rustc_args, args)
try
let exepath = tempname()
if has('win32')
let exepath .= '.exe'
endif
let rustc_args = [a:path, '-o', exepath] + a:rustc_args
let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc"
let output = system(shellescape(rustc) . " " . join(map(rustc_args, 'shellescape(v:val)')))
if output != ''
echohl WarningMsg
echo output
echohl None
endif
if !v:shell_error
exe '!' . shellescape(exepath) . " " . join(map(a:args, 'shellescape(v:val)'))
endif
finally
if exists("exepath")
silent! call delete(exepath)
endif
endtry
endfunction
" Expand {{{1
function! rust#Expand(bang, args)
if a:bang && !empty(a:args)
let pretty = a:args[0]
let args = a:args[1:]
else
let pretty = "expanded"
let args = a:args
endif
call s:WithPath(function("s:Expand"), pretty, args)
endfunction
function! s:Expand(path, pretty, args)
try
let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc"
let args = [a:path, '--pretty', a:pretty] + a:args
let output = system(shellescape(rustc) . " " . join(map(args, "shellescape(v:val)")))
if v:shell_error
echohl WarningMsg
echo output
echohl None
else
new
silent put =output
1
d
setl filetype=rust
setl buftype=nofile
setl bufhidden=hide
setl noswapfile
endif
endtry
endfunction
function! rust#CompleteExpand(lead, line, pos)
if a:line[: a:pos-1] =~ '^RustExpand!\s*\S*$'
" first argument and it has a !
let list = ["normal", "expanded", "typed", "expanded,identified", "flowgraph="]
if !empty(a:lead)
call filter(list, "v:val[:len(a:lead)-1] == a:lead")
endif
return list
endif
return glob(escape(a:lead, "*?[") . '*', 0, 1)
endfunction
" Emit {{{1
function! rust#Emit(type, args)
call s:WithPath(function("s:Emit"), a:type, a:args)
endfunction
function! s:Emit(path, type, args)
try
let rustc = exists("g:rustc_path") ? g:rustc_path : "rustc"
let args = [a:path, '--emit', a:type, '-o', '-'] + a:args
let output = system(shellescape(rustc) . " " . join(map(args, "shellescape(v:val)")))
if v:shell_error
echohl WarningMsg
echo output
echohl None
else
new
silent put =output
1
d
if a:type == "ir"
setl filetype=llvm
elseif a:type == "asm"
setl filetype=asm
endif
setl buftype=nofile
setl bufhidden=hide
setl noswapfile
endif
endtry
endfunction
" Utility functions {{{1
function! s:WithPath(func, ...)
try
let save_write = &write
set write
let path = expand('%')
let pathisempty = empty(path)
if pathisempty || !save_write
" use a temporary file named 'unnamed.rs' inside a temporary
" directory. This produces better error messages
let tmpdir = tempname()
call mkdir(tmpdir)
let save_cwd = getcwd()
silent exe 'lcd' fnameescape(tmpdir)
let path = 'unnamed.rs'
let save_mod = &mod
set nomod
silent exe 'keepalt write! ' . fnameescape(path)
if pathisempty
silent keepalt 0file
endif
else
update
endif
call call(a:func, [path] + a:000)
finally
if exists("save_mod") | let &mod = save_mod | endif
if exists("save_write") | let &write = save_write | endif
if exists("save_cwd") | silent exe 'lcd' fnameescape(save_cwd) | endif
if exists("tmpdir") | silent call s:RmDir(tmpdir) | endif
endtry
endfunction
function! rust#AppendCmdLine(text)
call setcmdpos(getcmdpos())
let cmd = getcmdline() . a:text
return cmd
endfunction
function! s:RmDir(path)
" sanity check; make sure it's not empty, /, or $HOME
if empty(a:path)
echoerr 'Attempted to delete empty path'
return 0
elseif a:path == '/' || a:path == $HOME
echoerr 'Attempted to delete protected path: ' . a:path
return 0
endif
silent exe "!rm -rf " . shellescape(a:path)
endfunction
" }}}1
" vim: set noet sw=4 ts=4:

View File

@ -1,65 +0,0 @@
" Vim compiler file
" Compiler: Cargo Compiler
" Maintainer: Damien Radtke <damienradtke@gmail.com>
" Latest Revision: 2014 Sep 24
if exists('current_compiler')
finish
endif
runtime compiler/rustc.vim
let current_compiler = "cargo"
if exists(':CompilerSet') != 2
command -nargs=* CompilerSet setlocal <args>
endif
if exists('g:cargo_makeprg_params')
execute 'CompilerSet makeprg=cargo\ '.escape(g:cargo_makeprg_params, ' \|"').'\ $*'
else
CompilerSet makeprg=cargo\ $*
endif
" Allow a configurable global Cargo.toml name. This makes it easy to
" support variations like 'cargo.toml'.
let s:cargo_manifest_name = get(g:, 'cargo_manifest_name', 'Cargo.toml')
function! s:is_absolute(path)
return a:path[0] == '/' || a:path =~ '[A-Z]\+:'
endfunction
let s:local_manifest = findfile(s:cargo_manifest_name, '.;')
if s:local_manifest != ''
let s:local_manifest = fnamemodify(s:local_manifest, ':p:h').'/'
augroup cargo
au!
au QuickfixCmdPost make call s:FixPaths()
augroup END
" FixPaths() is run after Cargo, and is used to change the file paths
" to be relative to the current directory instead of Cargo.toml.
function! s:FixPaths()
let qflist = getqflist()
let manifest = s:local_manifest
for qf in qflist
if !qf.valid
let m = matchlist(qf.text, '(file://\(.*\))$')
if !empty(m)
let manifest = m[1].'/'
" Manually strip another slash if needed; usually just an
" issue on Windows.
if manifest =~ '^/[A-Z]\+:/'
let manifest = manifest[1:]
endif
endif
continue
endif
let filename = bufname(qf.bufnr)
if s:is_absolute(filename)
continue
endif
let qf.filename = simplify(manifest.filename)
call remove(qf, 'bufnr')
endfor
call setqflist(qflist, 'r')
endfunction
endif

View File

@ -1,33 +0,0 @@
" Vim compiler file
" Compiler: Rust Compiler
" Maintainer: Chris Morgan <me@chrismorgan.info>
" Latest Revision: 2013 Jul 12
if exists("current_compiler")
finish
endif
let current_compiler = "rustc"
let s:cpo_save = &cpo
set cpo&vim
if exists(":CompilerSet") != 2
command -nargs=* CompilerSet setlocal <args>
endif
if exists("g:rustc_makeprg_no_percent") && g:rustc_makeprg_no_percent == 1
CompilerSet makeprg=rustc
else
CompilerSet makeprg=rustc\ \%
endif
CompilerSet errorformat=
\%f:%l:%c:\ %t%*[^:]:\ %m,
\%f:%l:%c:\ %*\\d:%*\\d\ %t%*[^:]:\ %m,
\%-G%f:%l\ %s,
\%-G%*[\ ]^,
\%-G%*[\ ]^%*[~],
\%-G%*[\ ]...
let &cpo = s:cpo_save
unlet s:cpo_save

View File

@ -1,178 +0,0 @@
*rust.txt* Filetype plugin for Rust
==============================================================================
CONTENTS *rust* *ft-rust*
1. Introduction |rust-intro|
2. Settings |rust-settings|
3. Commands |rust-commands|
4. Mappings |rust-mappings|
==============================================================================
INTRODUCTION *rust-intro*
This plugin provides syntax and supporting functionality for the Rust
filetype.
==============================================================================
SETTINGS *rust-settings*
This plugin has a few variables you can define in your vimrc that change the
behavior of the plugin.
*g:rustc_path*
g:rustc_path~
Set this option to the path to rustc for use in the |:RustRun| and
|:RustExpand| commands. If unset, "rustc" will be located in $PATH: >
let g:rustc_path = $HOME."/bin/rustc"
<
*g:rustc_makeprg_no_percent*
g:rustc_makeprg_no_percent~
Set this option to 1 to have 'makeprg' default to "rustc" instead of
"rustc %": >
let g:rustc_makeprg_no_percent = 1
<
*g:rust_conceal*
g:rust_conceal~
Set this option to turn on the basic |conceal| support: >
let g:rust_conceal = 1
<
*g:rust_conceal_mod_path*
g:rust_conceal_mod_path~
Set this option to turn on |conceal| for the path connecting token
"::": >
let g:rust_conceal_mod_path = 1
<
*g:rust_conceal_pub*
g:rust_conceal_pub~
Set this option to turn on |conceal| for the "pub" token: >
let g:rust_conceal_pub = 1
<
*g:rust_recommended_style*
g:rust_recommended_style~
Set this option to enable vim indentation and textwidth settings to
conform to style conventions of the rust standard library (i.e. use 4
spaces for indents and sets 'textwidth' to 99). This option is enabled
by default. To disable it: >
let g:rust_recommended_style = 0
<
*g:rust_fold*
g:rust_fold~
Set this option to turn on |folding|: >
let g:rust_fold = 1
<
Value Effect ~
0 No folding
1 Braced blocks are folded. All folds are open by
default.
2 Braced blocks are folded. 'foldlevel' is left at the
global value (all folds are closed by default).
*g:rust_bang_comment_leader*
g:rust_bang_comment_leader~
Set this option to 1 to preserve the leader on multi-line doc comments
using the /*! syntax: >
let g:rust_bang_comment_leader = 1
<
*g:ftplugin_rust_source_path*
g:ftplugin_rust_source_path~
Set this option to a path that should be prepended to 'path' for Rust
source files: >
let g:ftplugin_rust_source_path = $HOME.'/dev/rust'
<
*g:cargo_manifest_name*
g:cargo_manifest_name~
Set this option to the name of the manifest file for your projects. If
not specified it defaults to 'Cargo.toml' : >
let g:cargo_manifest_name = 'Cargo.toml'
<
==============================================================================
COMMANDS *rust-commands*
:RustRun [args] *:RustRun*
:RustRun! [rustc-args] [--] [args]
Compiles and runs the current file. If it has unsaved changes,
it will be saved first using |:update|. If the current file is
an unnamed buffer, it will be written to a temporary file
first. The compiled binary is always placed in a temporary
directory, but is run from the current directory.
The arguments given to |:RustRun| will be passed to the
compiled binary.
If ! is specified, the arguments are passed to rustc instead.
A "--" argument will separate the rustc arguments from the
arguments passed to the binary.
If |g:rustc_path| is defined, it is used as the path to rustc.
Otherwise it is assumed rustc can be found in $PATH.
:RustExpand [args] *:RustExpand*
:RustExpand! [TYPE] [args]
Expands the current file using --pretty and displays the
results in a new split. If the current file has unsaved
changes, it will be saved first using |:update|. If the
current file is an unnamed buffer, it will be written to a
temporary file first.
The arguments given to |:RustExpand| will be passed to rustc.
This is largely intended for specifying various --cfg
configurations.
If ! is specified, the first argument is the expansion type to
pass to rustc --pretty. Otherwise it will default to
"expanded".
If |g:rustc_path| is defined, it is used as the path to rustc.
Otherwise it is assumed rustc can be found in $PATH.
:RustEmitIr [args] *:RustEmitIr*
Compiles the current file to LLVM IR and displays the results
in a new split. If the current file has unsaved changes, it
will be saved first using |:update|. If the current file is an
unnamed buffer, it will be written to a temporary file first.
The arguments given to |:RustEmitIr| will be passed to rustc.
If |g:rustc_path| is defined, it is used as the path to rustc.
Otherwise it is assumed rustc can be found in $PATH.
:RustEmitAsm [args] *:RustEmitAsm*
Compiles the current file to assembly and displays the results
in a new split. If the current file has unsaved changes, it
will be saved first using |:update|. If the current file is an
unnamed buffer, it will be written to a temporary file first.
The arguments given to |:RustEmitAsm| will be passed to rustc.
If |g:rustc_path| is defined, it is used as the path to rustc.
Otherwise it is assumed rustc can be found in $PATH.
==============================================================================
MAPPINGS *rust-mappings*
This plugin defines mappings for |[[| and |]]| to support hanging indents.
It also has a few other mappings:
*rust_<D-r>*
<D-r> Executes |:RustRun| with no arguments.
Note: This binding is only available in MacVim.
*rust_<D-R>*
<D-R> Populates the command line with |:RustRun|! using the
arguments given to the last invocation, but does not
execute it.
Note: This binding is only available in MacVim.
==============================================================================
vim:tw=78:sw=4:noet:ts=8:ft=help:norl:

View File

@ -1 +0,0 @@
au BufRead,BufNewFile *.rs set filetype=rust

View File

@ -1,150 +0,0 @@
" Language: Rust
" Description: Vim syntax file for Rust
" Maintainer: Chris Morgan <me@chrismorgan.info>
" Maintainer: Kevin Ballard <kevin@sb.org>
" Last Change: Jul 07, 2014
if exists("b:did_ftplugin")
finish
endif
let b:did_ftplugin = 1
let s:save_cpo = &cpo
set cpo&vim
" Variables {{{1
" The rust source code at present seems to typically omit a leader on /*!
" comments, so we'll use that as our default, but make it easy to switch.
" This does not affect indentation at all (I tested it with and without
" leader), merely whether a leader is inserted by default or not.
if exists("g:rust_bang_comment_leader") && g:rust_bang_comment_leader == 1
" Why is the `,s0:/*,mb:\ ,ex:*/` there, you ask? I don't understand why,
" but without it, */ gets indented one space even if there were no
" leaders. I'm fairly sure that's a Vim bug.
setlocal comments=s1:/*,mb:*,ex:*/,s0:/*,mb:\ ,ex:*/,:///,://!,://
else
setlocal comments=s0:/*!,m:\ ,ex:*/,s1:/*,mb:*,ex:*/,:///,://!,://
endif
setlocal commentstring=//%s
setlocal formatoptions-=t formatoptions+=croqnl
" j was only added in 7.3.541, so stop complaints about its nonexistence
silent! setlocal formatoptions+=j
" smartindent will be overridden by indentexpr if filetype indent is on, but
" otherwise it's better than nothing.
setlocal smartindent nocindent
if !exists("g:rust_recommended_style") || g:rust_recommended_style == 1
setlocal tabstop=4 shiftwidth=4 softtabstop=4 expandtab
setlocal textwidth=99
endif
" This includeexpr isn't perfect, but it's a good start
setlocal includeexpr=substitute(v:fname,'::','/','g')
" NOT adding .rc as it's being phased out (0.7)
setlocal suffixesadd=.rs
if exists("g:ftplugin_rust_source_path")
let &l:path=g:ftplugin_rust_source_path . ',' . &l:path
endif
if exists("g:loaded_delimitMate")
if exists("b:delimitMate_excluded_regions")
let b:rust_original_delimitMate_excluded_regions = b:delimitMate_excluded_regions
endif
let b:delimitMate_excluded_regions = delimitMate#Get("excluded_regions") . ',rustLifetimeCandidate,rustGenericLifetimeCandidate'
endif
if has("folding") && exists('g:rust_fold') && g:rust_fold != 0
let b:rust_set_foldmethod=1
setlocal foldmethod=syntax
if g:rust_fold == 2
setlocal foldlevel<
else
setlocal foldlevel=99
endif
endif
if has('conceal') && exists('g:rust_conceal')
let b:rust_set_conceallevel=1
setlocal conceallevel=2
endif
" Motion Commands {{{1
" Bind motion commands to support hanging indents
nnoremap <silent> <buffer> [[ :call rust#Jump('n', 'Back')<CR>
nnoremap <silent> <buffer> ]] :call rust#Jump('n', 'Forward')<CR>
xnoremap <silent> <buffer> [[ :call rust#Jump('v', 'Back')<CR>
xnoremap <silent> <buffer> ]] :call rust#Jump('v', 'Forward')<CR>
onoremap <silent> <buffer> [[ :call rust#Jump('o', 'Back')<CR>
onoremap <silent> <buffer> ]] :call rust#Jump('o', 'Forward')<CR>
" Commands {{{1
" See |:RustRun| for docs
command! -nargs=* -complete=file -bang -bar -buffer RustRun call rust#Run(<bang>0, [<f-args>])
" See |:RustExpand| for docs
command! -nargs=* -complete=customlist,rust#CompleteExpand -bang -bar -buffer RustExpand call rust#Expand(<bang>0, [<f-args>])
" See |:RustEmitIr| for docs
command! -nargs=* -bar -buffer RustEmitIr call rust#Emit("ir", [<f-args>])
" See |:RustEmitAsm| for docs
command! -nargs=* -bar -buffer RustEmitAsm call rust#Emit("asm", [<f-args>])
" Mappings {{{1
" Bind ⌘R in MacVim to :RustRun
nnoremap <silent> <buffer> <D-r> :RustRun<CR>
" Bind ⌘⇧R in MacVim to :RustRun! pre-filled with the last args
nnoremap <buffer> <D-R> :RustRun! <C-r>=join(b:rust_last_rustc_args)<CR><C-\>erust#AppendCmdLine(' -- ' . join(b:rust_last_args))<CR>
if !exists("b:rust_last_rustc_args") || !exists("b:rust_last_args")
let b:rust_last_rustc_args = []
let b:rust_last_args = []
endif
" Cleanup {{{1
let b:undo_ftplugin = "
\ setlocal formatoptions< comments< commentstring< includeexpr< suffixesadd<
\|setlocal tabstop< shiftwidth< softtabstop< expandtab< textwidth<
\|if exists('b:rust_original_delimitMate_excluded_regions')
\|let b:delimitMate_excluded_regions = b:rust_original_delimitMate_excluded_regions
\|unlet b:rust_original_delimitMate_excluded_regions
\|else
\|unlet! b:delimitMate_excluded_regions
\|endif
\|if exists('b:rust_set_foldmethod')
\|setlocal foldmethod< foldlevel<
\|unlet b:rust_set_foldmethod
\|endif
\|if exists('b:rust_set_conceallevel')
\|setlocal conceallevel<
\|unlet b:rust_set_conceallevel
\|endif
\|unlet! b:rust_last_rustc_args b:rust_last_args
\|delcommand RustRun
\|delcommand RustExpand
\|delcommand RustEmitIr
\|delcommand RustEmitAsm
\|nunmap <buffer> <D-r>
\|nunmap <buffer> <D-R>
\|nunmap <buffer> [[
\|nunmap <buffer> ]]
\|xunmap <buffer> [[
\|xunmap <buffer> ]]
\|ounmap <buffer> [[
\|ounmap <buffer> ]]
\"
" }}}1
let &cpo = s:save_cpo
unlet s:save_cpo
" vim: set noet sw=4 ts=4:

View File

@ -1,196 +0,0 @@
" Vim indent file
" Language: Rust
" Author: Chris Morgan <me@chrismorgan.info>
" Last Change: 2014 Sep 13
" Only load this indent file when no other was loaded.
if exists("b:did_indent")
finish
endif
let b:did_indent = 1
setlocal cindent
setlocal cinoptions=L0,(0,Ws,J1,j1
setlocal cinkeys=0{,0},!^F,o,O,0[,0]
" Don't think cinwords will actually do anything at all... never mind
setlocal cinwords=for,if,else,while,loop,impl,mod,unsafe,trait,struct,enum,fn,extern
" Some preliminary settings
setlocal nolisp " Make sure lisp indenting doesn't supersede us
setlocal autoindent " indentexpr isn't much help otherwise
" Also do indentkeys, otherwise # gets shoved to column 0 :-/
setlocal indentkeys=0{,0},!^F,o,O,0[,0]
setlocal indentexpr=GetRustIndent(v:lnum)
" Only define the function once.
if exists("*GetRustIndent")
finish
endif
" Come here when loading the script the first time.
function! s:get_line_trimmed(lnum)
" Get the line and remove a trailing comment.
" Use syntax highlighting attributes when possible.
" NOTE: this is not accurate; /* */ or a line continuation could trick it
let line = getline(a:lnum)
let line_len = strlen(line)
if has('syntax_items')
" If the last character in the line is a comment, do a binary search for
" the start of the comment. synID() is slow, a linear search would take
" too long on a long line.
if synIDattr(synID(a:lnum, line_len, 1), "name") =~ 'Comment\|Todo'
let min = 1
let max = line_len
while min < max
let col = (min + max) / 2
if synIDattr(synID(a:lnum, col, 1), "name") =~ 'Comment\|Todo'
let max = col
else
let min = col + 1
endif
endwhile
let line = strpart(line, 0, min - 1)
endif
return substitute(line, "\s*$", "", "")
else
" Sorry, this is not complete, nor fully correct (e.g. string "//").
" Such is life.
return substitute(line, "\s*//.*$", "", "")
endif
endfunction
function! s:is_string_comment(lnum, col)
if has('syntax_items')
for id in synstack(a:lnum, a:col)
let synname = synIDattr(id, "name")
if synname == "rustString" || synname =~ "^rustComment"
return 1
endif
endfor
else
" without syntax, let's not even try
return 0
endif
endfunction
function GetRustIndent(lnum)
" Starting assumption: cindent (called at the end) will do it right
" normally. We just want to fix up a few cases.
let line = getline(a:lnum)
if has('syntax_items')
let synname = synIDattr(synID(a:lnum, 1, 1), "name")
if synname == "rustString"
" If the start of the line is in a string, don't change the indent
return -1
elseif synname =~ '\(Comment\|Todo\)'
\ && line !~ '^\s*/\*' " not /* opening line
if synname =~ "CommentML" " multi-line
if line !~ '^\s*\*' && getline(a:lnum - 1) =~ '^\s*/\*'
" This is (hopefully) the line after a /*, and it has no
" leader, so the correct indentation is that of the
" previous line.
return GetRustIndent(a:lnum - 1)
endif
endif
" If it's in a comment, let cindent take care of it now. This is
" for cases like "/*" where the next line should start " * ", not
" "* " as the code below would otherwise cause for module scope
" Fun fact: " /*\n*\n*/" takes two calls to get right!
return cindent(a:lnum)
endif
endif
" cindent gets second and subsequent match patterns/struct members wrong,
" as it treats the comma as indicating an unfinished statement::
"
" match a {
" b => c,
" d => e,
" f => g,
" };
" Search backwards for the previous non-empty line.
let prevlinenum = prevnonblank(a:lnum - 1)
let prevline = s:get_line_trimmed(prevlinenum)
while prevlinenum > 1 && prevline !~ '[^[:blank:]]'
let prevlinenum = prevnonblank(prevlinenum - 1)
let prevline = s:get_line_trimmed(prevlinenum)
endwhile
if prevline[len(prevline) - 1] == ","
\ && s:get_line_trimmed(a:lnum) !~ '^\s*[\[\]{}]'
\ && prevline !~ '^\s*fn\s'
\ && prevline !~ '([^()]\+,$'
" Oh ho! The previous line ended in a comma! I bet cindent will try to
" take this too far... For now, let's normally use the previous line's
" indent.
" One case where this doesn't work out is where *this* line contains
" square or curly brackets; then we normally *do* want to be indenting
" further.
"
" Another case where we don't want to is one like a function
" definition with arguments spread over multiple lines:
"
" fn foo(baz: Baz,
" baz: Baz) // <-- cindent gets this right by itself
"
" Another case is similar to the previous, except calling a function
" instead of defining it, or any conditional expression that leaves
" an open paren:
"
" foo(baz,
" baz);
"
" if baz && (foo ||
" bar) {
"
" There are probably other cases where we don't want to do this as
" well. Add them as needed.
return indent(prevlinenum)
endif
if !has("patch-7.4.355")
" cindent before 7.4.355 doesn't do the module scope well at all; e.g.::
"
" static FOO : &'static [bool] = [
" true,
" false,
" false,
" true,
" ];
"
" uh oh, next statement is indented further!
" Note that this does *not* apply the line continuation pattern properly;
" that's too hard to do correctly for my liking at present, so I'll just
" start with these two main cases (square brackets and not returning to
" column zero)
call cursor(a:lnum, 1)
if searchpair('{\|(', '', '}\|)', 'nbW',
\ 's:is_string_comment(line("."), col("."))') == 0
if searchpair('\[', '', '\]', 'nbW',
\ 's:is_string_comment(line("."), col("."))') == 0
" Global scope, should be zero
return 0
else
" At the module scope, inside square brackets only
"if getline(a:lnum)[0] == ']' || search('\[', '', '\]', 'nW') == a:lnum
if line =~ "^\\s*]"
" It's the closing line, dedent it
return 0
else
return &shiftwidth
endif
endif
endif
endif
" Fall back on cindent, which does it mostly right
return cindent(a:lnum)
endfunction

View File

@ -1,22 +0,0 @@
" Vim syntastic plugin helper
" Language: Rust
" Maintainer: Andrew Gallant <jamslam@gmail.com>
if exists("g:loaded_syntastic_rust_filetype")
finish
endif
let g:loaded_syntastic_rust_filetype = 1
let s:save_cpo = &cpo
set cpo&vim
" This is to let Syntastic know about the Rust filetype.
" It enables tab completion for the 'SyntasticInfo' command.
" (This does not actually register the syntax checker.)
if exists('g:syntastic_extra_filetypes')
call add(g:syntastic_extra_filetypes, 'rust')
else
let g:syntastic_extra_filetypes = ['rust']
endif
let &cpo = s:save_cpo
unlet s:save_cpo

View File

@ -1,262 +0,0 @@
" Vim syntax file
" Language: Rust
" Maintainer: Patrick Walton <pcwalton@mozilla.com>
" Maintainer: Ben Blum <bblum@cs.cmu.edu>
" Maintainer: Chris Morgan <me@chrismorgan.info>
" Last Change: January 5, 2015
if version < 600
syntax clear
elseif exists("b:current_syntax")
finish
endif
" Syntax definitions {{{1
" Basic keywords {{{2
syn keyword rustConditional match if else
syn keyword rustOperator as
syn match rustAssert "\<assert\(\w\)*!" contained
syn match rustPanic "\<panic\(\w\)*!" contained
syn keyword rustKeyword break
syn keyword rustKeyword box nextgroup=rustBoxPlacement skipwhite skipempty
syn keyword rustKeyword continue
syn keyword rustKeyword extern nextgroup=rustExternCrate,rustObsoleteExternMod skipwhite skipempty
syn keyword rustKeyword fn nextgroup=rustFuncName skipwhite skipempty
syn keyword rustKeyword for in if impl let
syn keyword rustKeyword loop once pub
syn keyword rustKeyword return super
syn keyword rustKeyword unsafe virtual where while
syn keyword rustKeyword use nextgroup=rustModPath skipwhite skipempty
" FIXME: Scoped impl's name is also fallen in this category
syn keyword rustKeyword mod trait struct enum type nextgroup=rustIdentifier skipwhite skipempty
syn keyword rustStorage move mut ref static const
syn keyword rustInvalidBareKeyword crate
syn keyword rustExternCrate crate contained nextgroup=rustIdentifier,rustExternCrateString skipwhite skipempty
" This is to get the `bar` part of `extern crate "foo" as bar;` highlighting.
syn match rustExternCrateString /".*"\_s*as/ contained nextgroup=rustIdentifier skipwhite transparent skipempty contains=rustString,rustOperator
syn keyword rustObsoleteExternMod mod contained nextgroup=rustIdentifier skipwhite skipempty
syn match rustIdentifier contains=rustIdentifierPrime "\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*" display contained
syn match rustFuncName "\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*" display contained
syn region rustBoxPlacement matchgroup=rustBoxPlacementParens start="(" end=")" contains=TOP contained
syn keyword rustBoxPlacementExpr GC containedin=rustBoxPlacement
" Ideally we'd have syntax rules set up to match arbitrary expressions. Since
" we don't, we'll just define temporary contained rules to handle balancing
" delimiters.
syn region rustBoxPlacementBalance start="(" end=")" containedin=rustBoxPlacement transparent
syn region rustBoxPlacementBalance start="\[" end="\]" containedin=rustBoxPlacement transparent
" {} are handled by rustFoldBraces
syn region rustMacroRepeat matchgroup=rustMacroRepeatDelimiters start="$(" end=")" contains=TOP nextgroup=rustMacroRepeatCount
syn match rustMacroRepeatCount ".\?[*+]" contained
syn match rustMacroVariable "$\w\+"
" Reserved (but not yet used) keywords {{{2
syn keyword rustReservedKeyword alignof be do offsetof priv pure sizeof typeof unsized yield abstract final override macro
" Built-in types {{{2
syn keyword rustType isize usize float char bool u8 u16 u32 u64 f32
syn keyword rustType f64 i8 i16 i32 i64 str Self
" Things from the prelude (src/libstd/prelude.rs) {{{2
" This section is just straight transformation of the contents of the prelude,
" to make it easy to update.
" Reexported core operators {{{3
syn keyword rustTrait Copy Send Sized Sync
syn keyword rustTrait Drop Fn FnMut FnOnce
" Reexported functions {{{3
syn keyword rustFunction drop
" Reexported types and traits {{{3
syn keyword rustTrait Box
syn keyword rustTrait CharExt
syn keyword rustTrait Clone
syn keyword rustTrait PartialEq PartialOrd Eq Ord
syn keyword rustTrait DoubleEndedIterator
syn keyword rustTrait ExactSizeIterator
syn keyword rustTrait Iterator IteratorExt Extend
syn keyword rustEnum Option
syn keyword rustEnumVariant Some None
syn keyword rustTrait PtrExt MutPtrExt
syn keyword rustEnum Result
syn keyword rustEnumVariant Ok Err
syn keyword rustTrait AsSlice
syn keyword rustTrait SliceExt SliceConcatExt
syn keyword rustTrait Str StrExt
syn keyword rustTrait String ToString
syn keyword rustTrait Vec
" FIXME: remove when path reform lands
syn keyword rustTrait Path GenericPath
" FIXME: remove when I/O reform lands
syn keyword rustTrait Buffer Writer Reader Seek BufferPrelude
" Other syntax {{{2
syn keyword rustSelf self
syn keyword rustBoolean true false
" If foo::bar changes to foo.bar, change this ("::" to "\.").
" If foo::bar changes to Foo::bar, change this (first "\w" to "\u").
syn match rustModPath "\w\(\w\)*::[^<]"he=e-3,me=e-3
syn match rustModPathSep "::"
syn match rustFuncCall "\w\(\w\)*("he=e-1,me=e-1
syn match rustFuncCall "\w\(\w\)*::<"he=e-3,me=e-3 " foo::<T>();
" This is merely a convention; note also the use of [A-Z], restricting it to
" latin identifiers rather than the full Unicode uppercase. I have not used
" [:upper:] as it depends upon 'noignorecase'
"syn match rustCapsIdent display "[A-Z]\w\(\w\)*"
syn match rustOperator display "\%(+\|-\|/\|*\|=\|\^\|&\||\|!\|>\|<\|%\)=\?"
" This one isn't *quite* right, as we could have binary-& with a reference
syn match rustSigil display /&\s\+[&~@*][^)= \t\r\n]/he=e-1,me=e-1
syn match rustSigil display /[&~@*][^)= \t\r\n]/he=e-1,me=e-1
" This isn't actually correct; a closure with no arguments can be `|| { }`.
" Last, because the & in && isn't a sigil
syn match rustOperator display "&&\|||"
syn match rustMacro '\w\(\w\)*!' contains=rustAssert,rustPanic
syn match rustMacro '#\w\(\w\)*' contains=rustAssert,rustPanic
syn match rustEscapeError display contained /\\./
syn match rustEscape display contained /\\\([nrt0\\'"]\|x\x\{2}\)/
syn match rustEscapeUnicode display contained /\\\(u\x\{4}\|U\x\{8}\)/
syn match rustEscapeUnicode display contained /\\u{\x\{1,6}}/
syn match rustStringContinuation display contained /\\\n\s*/
syn region rustString start=+b"+ skip=+\\\\\|\\"+ end=+"+ contains=rustEscape,rustEscapeError,rustStringContinuation
syn region rustString start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=rustEscape,rustEscapeUnicode,rustEscapeError,rustStringContinuation,@Spell
syn region rustString start='b\?r\z(#*\)"' end='"\z1' contains=@Spell
syn region rustAttribute start="#!\?\[" end="\]" contains=rustString,rustDerive
syn region rustDerive start="derive(" end=")" contained contains=rustTrait
" Number literals
syn match rustDecNumber display "\<[0-9][0-9_]*\%([iu]\%(s\|8\|16\|32\|64\)\)\="
syn match rustHexNumber display "\<0x[a-fA-F0-9_]\+\%([iu]\%(s\|8\|16\|32\|64\)\)\="
syn match rustOctNumber display "\<0o[0-7_]\+\%([iu]\%(s\|8\|16\|32\|64\)\)\="
syn match rustBinNumber display "\<0b[01_]\+\%([iu]\%(s\|8\|16\|32\|64\)\)\="
" Special case for numbers of the form "1." which are float literals, unless followed by
" an identifier, which makes them integer literals with a method call or field access,
" or by another ".", which makes them integer literals followed by the ".." token.
" (This must go first so the others take precedence.)
syn match rustFloat display "\<[0-9][0-9_]*\.\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\|\.\)\@!"
" To mark a number as a normal float, it must have at least one of the three things integral values don't have:
" a decimal point and more numbers; an exponent; and a type suffix.
syn match rustFloat display "\<[0-9][0-9_]*\%(\.[0-9][0-9_]*\)\%([eE][+-]\=[0-9_]\+\)\=\(f32\|f64\)\="
syn match rustFloat display "\<[0-9][0-9_]*\%(\.[0-9][0-9_]*\)\=\%([eE][+-]\=[0-9_]\+\)\(f32\|f64\)\="
syn match rustFloat display "\<[0-9][0-9_]*\%(\.[0-9][0-9_]*\)\=\%([eE][+-]\=[0-9_]\+\)\=\(f32\|f64\)"
" For the benefit of delimitMate
syn region rustLifetimeCandidate display start=/&'\%(\([^'\\]\|\\\(['nrt0\\\"]\|x\x\{2}\|u\x\{4}\|U\x\{8}\)\)'\)\@!/ end=/[[:cntrl:][:space:][:punct:]]\@=\|$/ contains=rustSigil,rustLifetime
syn region rustGenericRegion display start=/<\%('\|[^[cntrl:][:space:][:punct:]]\)\@=')\S\@=/ end=/>/ contains=rustGenericLifetimeCandidate
syn region rustGenericLifetimeCandidate display start=/\%(<\|,\s*\)\@<='/ end=/[[:cntrl:][:space:][:punct:]]\@=\|$/ contains=rustSigil,rustLifetime
"rustLifetime must appear before rustCharacter, or chars will get the lifetime highlighting
syn match rustLifetime display "\'\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*"
syn match rustCharacterInvalid display contained /b\?'\zs[\n\r\t']\ze'/
" The groups negated here add up to 0-255 but nothing else (they do not seem to go beyond ASCII).
syn match rustCharacterInvalidUnicode display contained /b'\zs[^[:cntrl:][:graph:][:alnum:][:space:]]\ze'/
syn match rustCharacter /b'\([^\\]\|\\\(.\|x\x\{2}\)\)'/ contains=rustEscape,rustEscapeError,rustCharacterInvalid,rustCharacterInvalidUnicode
syn match rustCharacter /'\([^\\]\|\\\(.\|x\x\{2}\|u\x\{4}\|U\x\{8}\|u{\x\{1,6}}\)\)'/ contains=rustEscape,rustEscapeUnicode,rustEscapeError,rustCharacterInvalid
syn region rustCommentLine start="//" end="$" contains=rustTodo,@Spell
syn region rustCommentLineDoc start="//\%(//\@!\|!\)" end="$" contains=rustTodo,@Spell
syn region rustCommentBlock matchgroup=rustCommentBlock start="/\*\%(!\|\*[*/]\@!\)\@!" end="\*/" contains=rustTodo,rustCommentBlockNest,@Spell
syn region rustCommentBlockDoc matchgroup=rustCommentBlockDoc start="/\*\%(!\|\*[*/]\@!\)" end="\*/" contains=rustTodo,rustCommentBlockDocNest,@Spell
syn region rustCommentBlockNest matchgroup=rustCommentBlock start="/\*" end="\*/" contains=rustTodo,rustCommentBlockNest,@Spell contained transparent
syn region rustCommentBlockDocNest matchgroup=rustCommentBlockDoc start="/\*" end="\*/" contains=rustTodo,rustCommentBlockDocNest,@Spell contained transparent
" FIXME: this is a really ugly and not fully correct implementation. Most
" importantly, a case like ``/* */*`` should have the final ``*`` not being in
" a comment, but in practice at present it leaves comments open two levels
" deep. But as long as you stay away from that particular case, I *believe*
" the highlighting is correct. Due to the way Vim's syntax engine works
" (greedy for start matches, unlike Rust's tokeniser which is searching for
" the earliest-starting match, start or end), I believe this cannot be solved.
" Oh you who would fix it, don't bother with things like duplicating the Block
" rules and putting ``\*\@<!`` at the start of them; it makes it worse, as
" then you must deal with cases like ``/*/**/*/``. And don't try making it
" worse with ``\%(/\@<!\*\)\@<!``, either...
syn keyword rustTodo contained TODO FIXME XXX NB NOTE
" Folding rules {{{2
" Trivial folding rules to begin with.
" FIXME: use the AST to make really good folding
syn region rustFoldBraces start="{" end="}" transparent fold
" Default highlighting {{{1
hi def link rustDecNumber rustNumber
hi def link rustHexNumber rustNumber
hi def link rustOctNumber rustNumber
hi def link rustBinNumber rustNumber
hi def link rustIdentifierPrime rustIdentifier
hi def link rustTrait rustType
hi def link rustMacroRepeatCount rustMacroRepeatDelimiters
hi def link rustMacroRepeatDelimiters Macro
hi def link rustMacroVariable Define
hi def link rustSigil StorageClass
hi def link rustEscape Special
hi def link rustEscapeUnicode rustEscape
hi def link rustEscapeError Error
hi def link rustStringContinuation Special
hi def link rustString String
hi def link rustCharacterInvalid Error
hi def link rustCharacterInvalidUnicode rustCharacterInvalid
hi def link rustCharacter Character
hi def link rustNumber Number
hi def link rustBoolean Boolean
hi def link rustEnum rustType
hi def link rustEnumVariant rustConstant
hi def link rustConstant Constant
hi def link rustSelf Constant
hi def link rustFloat Float
hi def link rustOperator Operator
hi def link rustKeyword Keyword
hi def link rustReservedKeyword Error
hi def link rustConditional Conditional
hi def link rustIdentifier Identifier
hi def link rustCapsIdent rustIdentifier
hi def link rustModPath Include
hi def link rustModPathSep Delimiter
hi def link rustFunction Function
hi def link rustFuncName Function
hi def link rustFuncCall Function
hi def link rustCommentLine Comment
hi def link rustCommentLineDoc SpecialComment
hi def link rustCommentBlock rustCommentLine
hi def link rustCommentBlockDoc rustCommentLineDoc
hi def link rustAssert PreCondit
hi def link rustPanic PreCondit
hi def link rustMacro Macro
hi def link rustType Type
hi def link rustTodo Todo
hi def link rustAttribute PreProc
hi def link rustDerive PreProc
hi def link rustStorage StorageClass
hi def link rustObsoleteStorage Error
hi def link rustLifetime Special
hi def link rustInvalidBareKeyword Error
hi def link rustExternCrate rustKeyword
hi def link rustObsoleteExternMod Error
hi def link rustBoxPlacementParens Delimiter
hi def link rustBoxPlacementExpr rustKeyword
" Other Suggestions:
" hi rustAttribute ctermfg=cyan
" hi rustDerive ctermfg=cyan
" hi rustAssert ctermfg=yellow
" hi rustPanic ctermfg=red
" hi rustMacro ctermfg=magenta
syn sync minlines=200
syn sync maxlines=500
let b:current_syntax = "rust"

View File

@ -1,35 +0,0 @@
" Vim syntastic plugin
" Language: Rust
" Maintainer: Andrew Gallant <jamslam@gmail.com>
"
" See for details on how to add an external Syntastic checker:
" https://github.com/scrooloose/syntastic/wiki/Syntax-Checker-Guide#external
if exists("g:loaded_syntastic_rust_rustc_checker")
finish
endif
let g:loaded_syntastic_rust_rustc_checker = 1
let s:save_cpo = &cpo
set cpo&vim
function! SyntaxCheckers_rust_rustc_GetLocList() dict
let makeprg = self.makeprgBuild({ 'args': '-Zparse-only' })
let errorformat =
\ '%E%f:%l:%c: %\d%#:%\d%# %.%\{-}error:%.%\{-} %m,' .
\ '%W%f:%l:%c: %\d%#:%\d%# %.%\{-}warning:%.%\{-} %m,' .
\ '%C%f:%l %m,' .
\ '%-Z%.%#'
return SyntasticMake({
\ 'makeprg': makeprg,
\ 'errorformat': errorformat })
endfunction
call g:SyntasticRegistry.CreateAndRegisterChecker({
\ 'filetype': 'rust',
\ 'name': 'rustc'})
let &cpo = s:save_cpo
unlet s:save_cpo

View File

@ -1,215 +0,0 @@
#compdef rustc
local -a _rustc_opts_switches _rustc_opts_lint _rustc_opts_debug
typeset -A opt_args
_rustc_debuginfo_levels=(
"0[no debug info]"
"1[line-tables only (for stacktraces and breakpoints)]"
"2[full debug info with variable and type information (same as -g)]"
)
_rustc_crate_types=(
'bin'
'lib'
'rlib'
'dylib'
'staticlib'
)
_rustc_emit_types=(
'asm'
'llvm-bc'
'llvm-ir'
'obj'
'link'
'dep-info'
)
_rustc_pretty_types=(
'normal[un-annotated source]'
'expanded[crates expanded]'
'typed[crates expanded, with type annotations]'
'identified[fully parenthesized, AST nodes and blocks with IDs]'
'flowgraph[graphviz formatted flowgraph for node]:NODEID:'
)
_rustc_color_types=(
'auto[colorize, if output goes to a tty (default)]'
'always[always colorize output]'
'never[never colorize output]'
)
_rustc_info_types=(
'crate-name[Output the crate name and exit]'
'file-names[Output the file(s) that would be written if compilation continued and exited]'
'sysroot[Output the sysroot and exit]'
)
_rustc_opts_vals=(
--crate-name='[Specify the name of the crate being built]'
--crate-type='[Comma separated list of types of crates for the compiler to emit]:TYPES:_values -s "," "Crate types" "$_rustc_crate_types[@]"'
--emit='[Comma separated list of types of output for the compiler to emit]:TYPES:_values -s "," "Emit Targets" "$_rustc_emit_types[@]"'
--cfg='[Configure the compilation environment]:SPEC:'
--out-dir='[Write output to compiler-chosen filename in <dir>. Ignored if -o is specified. (default the current directory)]:DIR:_files -/'
-o'[Write output to <filename>. Ignored if more than one --emit is specified.]:FILENAME:_files'
--pretty='[Pretty-print the input instead of compiling]::TYPE:_values "TYPES" "$_rustc_pretty_types[@]"'
-L'[Add a directory to the library search path]:DIR:_files -/'
--target='[Target triple cpu-manufacturer-kernel\[-os\] to compile]:TRIPLE:'
--color='[Configure coloring of output]:CONF:_values "COLORS" "$_rustc_color_types[@]"'
{-v,--version}'[Print version info and exit]::VERBOSE:(verbose)'
--explain='[Provide a detailed explanation of an error message]:OPT:'
--extern'[Specify where an external rust library is located]:ARG:'
--print='[Comma separated list of compiler information to print on stdout]:TYPES:_values -s "," "Compiler Information" "$_rustc_info_types[@]"'
)
_rustc_opts_switches=(
-g'[Equivalent to -C debuginfo=2]'
{-h,--help}'[Display the help message]'
{-V,--verbose}'[use verbose output]'
-O'[Equivalent to -C opt-level=2]'
--test'[Build a test harness]'
)
_rustc_opts_link=(
'static[Path to the library to link statically]:PATH:_files -/'
'dylib[Path to the library to link dynamically]:PATH:_files -/'
'framework[Path to the library to link as a framework]:PATH:_files -/'
)
_rustc_opts_codegen=(
'ar[Path to the archive utility to use when assembling archives.]:BIN:_path_files'
'linker[Path to the linker utility to use when linking libraries, executables, and objects.]:BIN:_path_files'
'link-args[A space-separated list of extra arguments to pass to the linker when the linker is invoked.]:ARGS:'
'lto[Perform LLVM link-time optimizations]'
'target-cpu[Selects a target processor. If the value is "help", then a list of available CPUs is printed.]:CPU:'
'target-feature[A space-separated list of features to enable or disable for the target. A preceding "+" enables a feature while a preceding "-" disables it. Available features can be discovered through target-cpu=help.]:FEATURE:'
'passes[A space-separated list of extra LLVM passes to run. A value of "list" will cause rustc to print all known passes and exit. The passes specified are appended at the end of the normal pass manager.]:LIST:'
'llvm-args[A space-separated list of arguments to pass through to LLVM.]:ARGS:'
'save-temps[If specified, the compiler will save more files (.bc, .o, .no-opt.bc) generated throughout compilation in the output directory.]'
'rpath[If specified, then the rpath value for dynamic libraries will be set in either dynamic library or executable outputs.]'
'no-prepopulate-passes[Suppresses pre-population of the LLVM pass manager that is run over the module.]'
'no-vectorize-loops[Suppresses running the loop vectorization LLVM pass, regardless of optimization level.]'
'no-vectorize-slp[Suppresses running the LLVM SLP vectorization pass, regardless of optimization level.]'
'soft-float[Generates software floating point library calls instead of hardware instructions.]'
'prefer-dynamic[Prefers dynamic linking to static linking.]'
"no-integrated-as[Force usage of an external assembler rather than LLVM's integrated one.]"
'no-redzone[disable the use of the redzone]'
'relocation-model[The relocation model to use. (default: pic)]:MODEL:(pic static dynamic-no-pic)'
'code-model[choose the code model to use (llc -code-model for details)]:MODEL:'
'metadata[metadata to mangle symbol names with]:VAL:'
'extra-filenames[extra data to put in each output filename]:VAL:'
'codegen-units[divide crate into N units to optimize in parallel]:N:'
'remark[print remarks for these optimization passes (space separated, or "all")]:TYPE:'
'debuginfo[debug info emission level, 0 = no debug info, 1 = line tables only, 2 = full debug info with variable and type information]:LEVEL:_values "Debug Levels" "$_rustc_debuginfo_levels[@]"'
'opt-level[Optimize with possible levels 0-3]:LEVEL:(0 1 2 3)'
'help[Show all codegen options]'
)
_rustc_opts_lint=(
'help[Show a list of all lints]'
'box-pointers[(default: allow) use of owned (Box type) heap memory]'
'experimental[(default: allow) detects use of #\[experimental\] items]'
'fat-ptr-transmutes[(default: allow) detects transmutes of fat pointers]'
'missing-docs[(default: allow) detects missing documentation for public members]'
'unsafe-blocks[(default: allow) usage of an "unsafe" block]'
'unstable[(default: allow) detects use of #\[unstable\] items (incl. items with no stability attribute)]'
'unused-extern-crates[(default: allow) extern crates that are never used]'
'unused-import-braces[(default: allow) unnecessary braces around an imported item]'
'unused-qualifications[(default: allow) detects unnecessarily qualified names]'
'unused-results[(default: allow) unused result of an expression in a statement]'
'unused-typecasts[(default: allow) detects unnecessary type casts that can be removed]'
'variant-size-differences[(default: allow) detects enums with widely varying variant sizes]'
'dead-code[(default: warn) detect unused, unexported items]'
'deprecated[(default: warn) detects use of #\[deprecated\] items]'
'improper-ctypes[(default: warn) proper use of libc types in foreign modules]'
'missing-copy-implementations[(default: warn) detects potentially-forgotten implementations of "Copy"]'
'non-camel-case-types[(default: warn) types, variants, traits and type parameters should have camel case names]'
'non-shorthand-field-patterns[(default: warn) using "Struct { x: x }" instead of "Struct { x }"]'
'non-snake-case[(default: warn) methods, functions, lifetime parameters and modules should have snake case names]'
'non-upper-case-globals[(default: warn) static constants should have uppercase identifiers]'
'overflowing-literals[(default: warn) literal out of range for its type]'
'path-statements[(default: warn) path statements with no effect]'
'raw-pointer-deriving[(default: warn) uses of #\[derive\] with raw pointers are rarely correct]'
'unknown-lints[(default: warn) unrecognized lint attribute]'
'unreachable-code[(default: warn) detects unreachable code paths]'
'unsigned-negation[(default: warn) using an unary minus operator on unsigned type]'
'unused-allocation[(default: warn) detects unnecessary allocations that can be eliminated]'
'unused-assignments[(default: warn) detect assignments that will never be read]'
'unused-attributes[(default: warn) detects attributes that were not used by the compiler]'
'unused-comparisons[(default: warn) comparisons made useless by limits of the types involved]'
'unused-imports[(default: warn) imports that are never used]'
'unused-must-use[(default: warn) unused result of a type flagged as must_use]'
"unused-mut[(default: warn) detect mut variables which don't need to be mutable]"
'unused-parens[(default: warn) "if", "match", "while" and "return" do not need parentheses]'
'unused-unsafe[(default: warn) unnecessary use of an "unsafe" block]'
'unused-variables[(default: warn) detect variables which are not used in any way]'
'warnings[(default: warn) mass-change the level for lints which produce warnings]'
'while-true[(default: warn) suggest using "loop { }" instead of "while true { }"]'
"exceeding-bitshifts[(default: deny) shift exceeds the type's number of bits]"
'unknown-crate-types[(default: deny) unknown crate type found in #\[crate_type\] directive]'
'unknown-features[(default: deny) unknown features found in crate-level #\[feature\] directives]'
'bad-style[non-camel-case-types, non-snake-case, non-upper-case-globals]'
'unused[unused-imports, unused-variables, unused-assignments, dead-code, unused-mut, unreachable-code, unused-must-use, unused-unsafe, path-statements]'
)
_rustc_opts_debug=(
'verbose[in general, enable more debug printouts]'
'time-passes[measure time of each rustc pass]'
'count-llvm-insns[count where LLVM instrs originate]'
'time-llvm-passes[measure time of each LLVM pass]'
'trans-stats[gather trans statistics]'
'asm-comments[generate comments into the assembly (may change behavior)]'
'no-verify[skip LLVM verification]'
'borrowck-stats[gather borrowck statistics]'
'no-landing-pads[omit landing pads for unwinding]'
'debug-llvm[enable debug output from LLVM]'
'show-span[show spans for compiler debugging]'
'count-type-sizes[count the sizes of aggregate types]'
'meta-stats[gather metadata statistics]'
'print-link-args[Print the arguments passed to the linker]'
'gc[Garbage collect shared data (experimental)]'
'print-llvm-passes[Prints the llvm optimization passes being run]'
'ast-json[Print the AST as JSON and halt]'
'ast-json-noexpand[Print the pre-expansion AST as JSON and halt]'
'ls[List the symbols defined by a library crate]'
'save-analysis[Write syntax and type analysis information in addition to normal output]'
'flowgraph-print-loans[Include loan analysis data in --pretty flowgraph output]'
'flowgraph-print-moves[Include move analysis data in --pretty flowgraph output]'
'flowgraph-print-assigns[Include assignment analysis data in --pretty flowgraph output]'
'flowgraph-print-all[Include all dataflow analysis data in --pretty flowgraph output]'
'print-regiion-graph[Prints region inference graph. Use with RUST_REGION_GRAPH=help for more info]'
'parse-only[Parse only; do not compile, assemble, or link]'
'no-trans[Run all passes except translation; no output]'
'no-analysis[Parse and expand the source, but run no analysis]'
'unstable-options[Adds unstable command line options to rustc interface]'
'print-enum-sizes[Print the size of enums and their variants]'
)
_rustc_opts_fun_lint(){
_values -s , 'options' \
"$_rustc_opts_lint[@]"
}
_rustc_opts_fun_debug(){
_values 'options' "$_rustc_opts_debug[@]"
}
_rustc_opts_fun_codegen(){
_values 'options' "$_rustc_opts_codegen[@]"
}
_rustc_opts_fun_link(){
_values 'options' "$_rustc_opts_link[@]"
}
_arguments -s : \
'(-W --warn)'{-W,--warn=}'[Set lint warnings]:lint options:_rustc_opts_fun_lint' \
'(-A --allow)'{-A,--allow=}'[Set lint allowed]:lint options:_rustc_opts_fun_lint' \
'(-D --deny)'{-D,--deny=}'[Set lint denied]:lint options:_rustc_opts_fun_lint' \
'(-F --forbid)'{-F,--forbid=}'[Set lint forbidden]:lint options:_rustc_opts_fun_lint' \
'*-Z[Set internal debugging options]:debug options:_rustc_opts_fun_debug' \
'(-C --codegen)'{-C,--codegen}'[Set internal Codegen options]:codegen options:_rustc_opts_fun_codegen' \
'*-l[Link the generated crates to the specified native library NAME. the optional KIND can be one of, static, dylib, or framework. If omitted, dylib is assumed.]:ARG:_rustc_opts_fun_link' \
"$_rustc_opts_switches[@]" \
"$_rustc_opts_vals[@]" \
'::files:_files -g "*.rs"'

View File

@ -12,20 +12,22 @@
//! Threadsafe reference-counted boxes (the `Arc<T>` type).
//!
//! The `Arc<T>` type provides shared ownership of an immutable value. Destruction is
//! deterministic, and will occur as soon as the last owner is gone. It is marked as `Send` because
//! it uses atomic reference counting.
//! The `Arc<T>` type provides shared ownership of an immutable value.
//! Destruction is deterministic, and will occur as soon as the last owner is
//! gone. It is marked as `Send` because it uses atomic reference counting.
//!
//! If you do not need thread-safety, and just need shared ownership, consider the [`Rc<T>`
//! type](../rc/struct.Rc.html). It is the same as `Arc<T>`, but does not use atomics, making it
//! both thread-unsafe as well as significantly faster when updating the reference count.
//! If you do not need thread-safety, and just need shared ownership, consider
//! the [`Rc<T>` type](../rc/struct.Rc.html). It is the same as `Arc<T>`, but
//! does not use atomics, making it both thread-unsafe as well as significantly
//! faster when updating the reference count.
//!
//! The `downgrade` method can be used to create a non-owning `Weak<T>` pointer to the box. A
//! `Weak<T>` pointer can be upgraded to an `Arc<T>` pointer, but will return `None` if the value
//! has already been dropped.
//! The `downgrade` method can be used to create a non-owning `Weak<T>` pointer
//! to the box. A `Weak<T>` pointer can be upgraded to an `Arc<T>` pointer, but
//! will return `None` if the value has already been dropped.
//!
//! For example, a tree with parent pointers can be represented by putting the nodes behind strong
//! `Arc<T>` pointers, and then storing the parent pointers as `Weak<T>` pointers.
//! For example, a tree with parent pointers can be represented by putting the
//! nodes behind strong `Arc<T>` pointers, and then storing the parent pointers
//! as `Weak<T>` pointers.
//!
//! # Examples
//!
@ -35,7 +37,7 @@
//! use std::sync::Arc;
//! use std::thread::Thread;
//!
//! let five = Arc::new(5i);
//! let five = Arc::new(5);
//!
//! for _ in 0u..10 {
//! let five = five.clone();
@ -52,7 +54,7 @@
//! use std::sync::{Arc, Mutex};
//! use std::thread::Thread;
//!
//! let five = Arc::new(Mutex::new(5i));
//! let five = Arc::new(Mutex::new(5));
//!
//! for _ in 0u..10 {
//! let five = five.clone();
@ -87,8 +89,9 @@ use heap::deallocate;
///
/// # Example
///
/// In this example, a large vector of floats is shared between several tasks. With simple pipes,
/// without `Arc`, a copy would have to be made for each task.
/// In this example, a large vector of floats is shared between several tasks.
/// With simple pipes, without `Arc`, a copy would have to be made for each
/// task.
///
/// ```rust
/// use std::sync::Arc;
@ -154,7 +157,7 @@ impl<T> Arc<T> {
/// ```
/// use std::sync::Arc;
///
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
@ -176,7 +179,7 @@ impl<T> Arc<T> {
/// ```
/// use std::sync::Arc;
///
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
///
/// let weak_five = five.downgrade();
/// ```
@ -221,7 +224,7 @@ impl<T> Clone for Arc<T> {
/// ```
/// use std::sync::Arc;
///
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
///
/// five.clone();
/// ```
@ -268,7 +271,7 @@ impl<T: Send + Sync + Clone> Arc<T> {
/// ```
/// use std::sync::Arc;
///
/// let mut five = Arc::new(5i);
/// let mut five = Arc::new(5);
///
/// let mut_five = five.make_unique();
/// ```
@ -304,14 +307,14 @@ impl<T: Sync + Send> Drop for Arc<T> {
/// use std::sync::Arc;
///
/// {
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
///
/// // stuff
///
/// drop(five); // explict drop
/// }
/// {
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
///
/// // stuff
///
@ -371,7 +374,7 @@ impl<T: Sync + Send> Weak<T> {
/// ```
/// use std::sync::Arc;
///
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
///
/// let weak_five = five.downgrade();
///
@ -408,7 +411,7 @@ impl<T: Sync + Send> Clone for Weak<T> {
/// ```
/// use std::sync::Arc;
///
/// let weak_five = Arc::new(5i).downgrade();
/// let weak_five = Arc::new(5).downgrade();
///
/// weak_five.clone();
/// ```
@ -433,7 +436,7 @@ impl<T: Sync + Send> Drop for Weak<T> {
/// use std::sync::Arc;
///
/// {
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
/// let weak_five = five.downgrade();
///
/// // stuff
@ -441,7 +444,7 @@ impl<T: Sync + Send> Drop for Weak<T> {
/// drop(weak_five); // explict drop
/// }
/// {
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
/// let weak_five = five.downgrade();
///
/// // stuff
@ -475,9 +478,9 @@ impl<T: PartialEq> PartialEq for Arc<T> {
/// ```
/// use std::sync::Arc;
///
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
///
/// five == Arc::new(5i);
/// five == Arc::new(5);
/// ```
fn eq(&self, other: &Arc<T>) -> bool { *(*self) == *(*other) }
@ -490,9 +493,9 @@ impl<T: PartialEq> PartialEq for Arc<T> {
/// ```
/// use std::sync::Arc;
///
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
///
/// five != Arc::new(5i);
/// five != Arc::new(5);
/// ```
fn ne(&self, other: &Arc<T>) -> bool { *(*self) != *(*other) }
}
@ -507,9 +510,9 @@ impl<T: PartialOrd> PartialOrd for Arc<T> {
/// ```
/// use std::sync::Arc;
///
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
///
/// five.partial_cmp(&Arc::new(5i));
/// five.partial_cmp(&Arc::new(5));
/// ```
fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
(**self).partial_cmp(&**other)
@ -524,9 +527,9 @@ impl<T: PartialOrd> PartialOrd for Arc<T> {
/// ```
/// use std::sync::Arc;
///
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
///
/// five < Arc::new(5i);
/// five < Arc::new(5);
/// ```
fn lt(&self, other: &Arc<T>) -> bool { *(*self) < *(*other) }
@ -539,9 +542,9 @@ impl<T: PartialOrd> PartialOrd for Arc<T> {
/// ```
/// use std::sync::Arc;
///
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
///
/// five <= Arc::new(5i);
/// five <= Arc::new(5);
/// ```
fn le(&self, other: &Arc<T>) -> bool { *(*self) <= *(*other) }
@ -554,9 +557,9 @@ impl<T: PartialOrd> PartialOrd for Arc<T> {
/// ```
/// use std::sync::Arc;
///
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
///
/// five > Arc::new(5i);
/// five > Arc::new(5);
/// ```
fn gt(&self, other: &Arc<T>) -> bool { *(*self) > *(*other) }
@ -569,9 +572,9 @@ impl<T: PartialOrd> PartialOrd for Arc<T> {
/// ```
/// use std::sync::Arc;
///
/// let five = Arc::new(5i);
/// let five = Arc::new(5);
///
/// five >= Arc::new(5i);
/// five >= Arc::new(5);
/// ```
fn ge(&self, other: &Arc<T>) -> bool { *(*self) >= *(*other) }
}
@ -719,14 +722,14 @@ mod tests {
#[test]
fn test_live() {
let x = Arc::new(5i);
let x = Arc::new(5);
let y = x.downgrade();
assert!(y.upgrade().is_some());
}
#[test]
fn test_dead() {
let x = Arc::new(5i);
let x = Arc::new(5);
let y = x.downgrade();
drop(x);
assert!(y.upgrade().is_none());

View File

@ -20,7 +20,7 @@ use std::boxed::BoxAny;
#[test]
fn test_owned_clone() {
let a = Box::new(5i);
let a = Box::new(5);
let b: Box<int> = a.clone();
assert!(a == b);
}

View File

@ -403,7 +403,7 @@ mod test {
#[bench]
fn alloc_owned_small(b: &mut Bencher) {
b.iter(|| {
box 10i
box 10
})
}
}

View File

@ -66,12 +66,11 @@
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![no_std]
#![allow(unknown_features)]
#![feature(lang_items, unsafe_destructor)]
#![feature(box_syntax)]
#![feature(optin_builtin_traits)]
#![feature(int_uint)]
#![feature(unboxed_closures)]
#![allow(unknown_features)] #![feature(int_uint)]
#![feature(core)]
#![feature(hash)]
#![feature(libc)]

View File

@ -192,7 +192,7 @@ impl<T> Rc<T> {
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new(value: T) -> Rc<T> {
@ -217,7 +217,7 @@ impl<T> Rc<T> {
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// let weak_five = five.downgrade();
/// ```
@ -247,7 +247,7 @@ pub fn strong_count<T>(this: &Rc<T>) -> uint { this.strong() }
/// use std::rc;
/// use std::rc::Rc;
///
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// rc::is_unique(&five);
/// ```
@ -329,7 +329,7 @@ impl<T: Clone> Rc<T> {
/// ```
/// use std::rc::Rc;
///
/// let mut five = Rc::new(5i);
/// let mut five = Rc::new(5);
///
/// let mut_five = five.make_unique();
/// ```
@ -378,14 +378,14 @@ impl<T> Drop for Rc<T> {
/// use std::rc::Rc;
///
/// {
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// // stuff
///
/// drop(five); // explict drop
/// }
/// {
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// // stuff
///
@ -425,7 +425,7 @@ impl<T> Clone for Rc<T> {
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// five.clone();
/// ```
@ -466,9 +466,9 @@ impl<T: PartialEq> PartialEq for Rc<T> {
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// five == Rc::new(5i);
/// five == Rc::new(5);
/// ```
#[inline(always)]
fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
@ -482,9 +482,9 @@ impl<T: PartialEq> PartialEq for Rc<T> {
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// five != Rc::new(5i);
/// five != Rc::new(5);
/// ```
#[inline(always)]
fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
@ -504,9 +504,9 @@ impl<T: PartialOrd> PartialOrd for Rc<T> {
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// five.partial_cmp(&Rc::new(5i));
/// five.partial_cmp(&Rc::new(5));
/// ```
#[inline(always)]
fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
@ -522,9 +522,9 @@ impl<T: PartialOrd> PartialOrd for Rc<T> {
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// five < Rc::new(5i);
/// five < Rc::new(5);
/// ```
#[inline(always)]
fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
@ -538,9 +538,9 @@ impl<T: PartialOrd> PartialOrd for Rc<T> {
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// five <= Rc::new(5i);
/// five <= Rc::new(5);
/// ```
#[inline(always)]
fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
@ -554,9 +554,9 @@ impl<T: PartialOrd> PartialOrd for Rc<T> {
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// five > Rc::new(5i);
/// five > Rc::new(5);
/// ```
#[inline(always)]
fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
@ -570,9 +570,9 @@ impl<T: PartialOrd> PartialOrd for Rc<T> {
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// five >= Rc::new(5i);
/// five >= Rc::new(5);
/// ```
#[inline(always)]
fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
@ -589,9 +589,9 @@ impl<T: Ord> Ord for Rc<T> {
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// five.partial_cmp(&Rc::new(5i));
/// five.partial_cmp(&Rc::new(5));
/// ```
#[inline]
fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
@ -653,7 +653,7 @@ impl<T> Weak<T> {
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
///
/// let weak_five = five.downgrade();
///
@ -682,7 +682,7 @@ impl<T> Drop for Weak<T> {
/// use std::rc::Rc;
///
/// {
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
/// let weak_five = five.downgrade();
///
/// // stuff
@ -690,7 +690,7 @@ impl<T> Drop for Weak<T> {
/// drop(weak_five); // explict drop
/// }
/// {
/// let five = Rc::new(5i);
/// let five = Rc::new(5);
/// let weak_five = five.downgrade();
///
/// // stuff
@ -726,7 +726,7 @@ impl<T> Clone for Weak<T> {
/// ```
/// use std::rc::Rc;
///
/// let weak_five = Rc::new(5i).downgrade();
/// let weak_five = Rc::new(5).downgrade();
///
/// weak_five.clone();
/// ```
@ -789,7 +789,7 @@ mod tests {
#[test]
fn test_clone() {
let x = Rc::new(RefCell::new(5i));
let x = Rc::new(RefCell::new(5));
let y = x.clone();
*x.borrow_mut() = 20;
assert_eq!(*y.borrow(), 20);
@ -797,13 +797,13 @@ mod tests {
#[test]
fn test_simple() {
let x = Rc::new(5i);
let x = Rc::new(5);
assert_eq!(*x, 5);
}
#[test]
fn test_simple_clone() {
let x = Rc::new(5i);
let x = Rc::new(5);
let y = x.clone();
assert_eq!(*x, 5);
assert_eq!(*y, 5);
@ -811,20 +811,20 @@ mod tests {
#[test]
fn test_destructor() {
let x = Rc::new(box 5i);
let x = Rc::new(box 5);
assert_eq!(**x, 5);
}
#[test]
fn test_live() {
let x = Rc::new(5i);
let x = Rc::new(5);
let y = x.downgrade();
assert!(y.upgrade().is_some());
}
#[test]
fn test_dead() {
let x = Rc::new(5i);
let x = Rc::new(5);
let y = x.downgrade();
drop(x);
assert!(y.upgrade().is_none());

View File

@ -21,7 +21,6 @@
#![crate_name = "arena"]
#![unstable(feature = "rustc_private")]
#![feature(staged_api)]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
@ -29,16 +28,14 @@
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![allow(unknown_features)]
#![feature(unsafe_destructor)]
#![feature(unboxed_closures)]
#![feature(box_syntax)]
#![allow(unknown_features)] #![feature(int_uint)]
#![allow(missing_docs)]
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(core)]
#![feature(int_uint)]
#![feature(staged_api)]
#![feature(unboxed_closures)]
#![feature(unsafe_destructor)]
#![cfg_attr(test, feature(test))]
#![cfg_attr(test, feature(collections))]
extern crate alloc;

View File

@ -153,7 +153,7 @@
use core::prelude::*;
use core::default::Default;
use core::iter::FromIterator;
use core::iter::{FromIterator, IntoIterator};
use core::mem::{zeroed, replace, swap};
use core::ptr;
@ -212,7 +212,7 @@ impl<T: Ord> BinaryHeap<T> {
///
/// ```
/// use std::collections::BinaryHeap;
/// let heap = BinaryHeap::from_vec(vec![9i, 1, 2, 7, 3, 2]);
/// let heap = BinaryHeap::from_vec(vec![9, 1, 2, 7, 3, 2]);
/// ```
pub fn from_vec(vec: Vec<T>) -> BinaryHeap<T> {
let mut heap = BinaryHeap { data: vec };
@ -231,7 +231,7 @@ impl<T: Ord> BinaryHeap<T> {
///
/// ```
/// use std::collections::BinaryHeap;
/// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4]);
/// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
///
/// // Print 1, 2, 3, 4 in arbitrary order
/// for x in heap.iter() {
@ -251,7 +251,7 @@ impl<T: Ord> BinaryHeap<T> {
///
/// ```
/// use std::collections::BinaryHeap;
/// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4]);
/// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
///
/// // Print 1, 2, 3, 4 in arbitrary order
/// for x in heap.into_iter() {
@ -273,7 +273,7 @@ impl<T: Ord> BinaryHeap<T> {
/// let mut heap = BinaryHeap::new();
/// assert_eq!(heap.peek(), None);
///
/// heap.push(1i);
/// heap.push(1);
/// heap.push(5);
/// heap.push(2);
/// assert_eq!(heap.peek(), Some(&5));
@ -356,7 +356,7 @@ impl<T: Ord> BinaryHeap<T> {
///
/// ```
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::from_vec(vec![1i, 3]);
/// let mut heap = BinaryHeap::from_vec(vec![1, 3]);
///
/// assert_eq!(heap.pop(), Some(3));
/// assert_eq!(heap.pop(), Some(1));
@ -380,7 +380,7 @@ impl<T: Ord> BinaryHeap<T> {
/// ```
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
/// heap.push(3i);
/// heap.push(3);
/// heap.push(5);
/// heap.push(1);
///
@ -402,7 +402,7 @@ impl<T: Ord> BinaryHeap<T> {
/// ```
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
/// heap.push(1i);
/// heap.push(1);
/// heap.push(5);
///
/// assert_eq!(heap.push_pop(3), 5);
@ -434,7 +434,7 @@ impl<T: Ord> BinaryHeap<T> {
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
///
/// assert_eq!(heap.replace(1i), None);
/// assert_eq!(heap.replace(1), None);
/// assert_eq!(heap.replace(3), Some(1));
/// assert_eq!(heap.len(), 1);
/// assert_eq!(heap.peek(), Some(&3));
@ -457,7 +457,7 @@ impl<T: Ord> BinaryHeap<T> {
///
/// ```
/// use std::collections::BinaryHeap;
/// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4, 5, 6, 7]);
/// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4, 5, 6, 7]);
/// let vec = heap.into_vec();
///
/// // Will print in some order
@ -475,12 +475,12 @@ impl<T: Ord> BinaryHeap<T> {
/// ```
/// use std::collections::BinaryHeap;
///
/// let mut heap = BinaryHeap::from_vec(vec![1i, 2, 4, 5, 7]);
/// let mut heap = BinaryHeap::from_vec(vec![1, 2, 4, 5, 7]);
/// heap.push(6);
/// heap.push(3);
///
/// let vec = heap.into_sorted_vec();
/// assert_eq!(vec, vec![1i, 2, 3, 4, 5, 6, 7]);
/// assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7]);
/// ```
pub fn into_sorted_vec(mut self) -> Vec<T> {
let mut end = self.len();
@ -655,6 +655,22 @@ impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
}
}
impl<T: Ord> IntoIterator for BinaryHeap<T> {
type Iter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
self.into_iter()
}
}
impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord {
type Iter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> Extend<T> for BinaryHeap<T> {
fn extend<Iter: Iterator<Item=T>>(&mut self, mut iter: Iter) {
@ -676,8 +692,8 @@ mod tests {
#[test]
fn test_iterator() {
let data = vec!(5i, 9, 3);
let iterout = [9i, 5, 3];
let data = vec!(5, 9, 3);
let iterout = [9, 5, 3];
let heap = BinaryHeap::from_vec(data);
let mut i = 0;
for el in heap.iter() {
@ -688,8 +704,8 @@ mod tests {
#[test]
fn test_iterator_reverse() {
let data = vec!(5i, 9, 3);
let iterout = vec!(3i, 5, 9);
let data = vec!(5, 9, 3);
let iterout = vec!(3, 5, 9);
let pq = BinaryHeap::from_vec(data);
let v: Vec<int> = pq.iter().rev().map(|&x| x).collect();
@ -698,8 +714,8 @@ mod tests {
#[test]
fn test_move_iter() {
let data = vec!(5i, 9, 3);
let iterout = vec!(9i, 5, 3);
let data = vec!(5, 9, 3);
let iterout = vec!(9, 5, 3);
let pq = BinaryHeap::from_vec(data);
let v: Vec<int> = pq.into_iter().collect();
@ -708,16 +724,16 @@ mod tests {
#[test]
fn test_move_iter_size_hint() {
let data = vec!(5i, 9);
let data = vec!(5, 9);
let pq = BinaryHeap::from_vec(data);
let mut it = pq.into_iter();
assert_eq!(it.size_hint(), (2, Some(2)));
assert_eq!(it.next(), Some(9i));
assert_eq!(it.next(), Some(9));
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next(), Some(5i));
assert_eq!(it.next(), Some(5));
assert_eq!(it.size_hint(), (0, Some(0)));
assert_eq!(it.next(), None);
@ -725,8 +741,8 @@ mod tests {
#[test]
fn test_move_iter_reverse() {
let data = vec!(5i, 9, 3);
let iterout = vec!(3i, 5, 9);
let data = vec!(5, 9, 3);
let iterout = vec!(3, 5, 9);
let pq = BinaryHeap::from_vec(data);
let v: Vec<int> = pq.into_iter().rev().collect();
@ -747,7 +763,7 @@ mod tests {
#[test]
fn test_push() {
let mut heap = BinaryHeap::from_vec(vec!(2i, 4, 9));
let mut heap = BinaryHeap::from_vec(vec!(2, 4, 9));
assert_eq!(heap.len(), 3);
assert!(*heap.peek().unwrap() == 9);
heap.push(11);
@ -769,7 +785,7 @@ mod tests {
#[test]
fn test_push_unique() {
let mut heap = BinaryHeap::from_vec(vec!(box 2i, box 4, box 9));
let mut heap = BinaryHeap::from_vec(vec!(box 2, box 4, box 9));
assert_eq!(heap.len(), 3);
assert!(*heap.peek().unwrap() == box 9);
heap.push(box 11);
@ -791,7 +807,7 @@ mod tests {
#[test]
fn test_push_pop() {
let mut heap = BinaryHeap::from_vec(vec!(5i, 5, 2, 1, 3));
let mut heap = BinaryHeap::from_vec(vec!(5, 5, 2, 1, 3));
assert_eq!(heap.len(), 5);
assert_eq!(heap.push_pop(6), 6);
assert_eq!(heap.len(), 5);
@ -805,7 +821,7 @@ mod tests {
#[test]
fn test_replace() {
let mut heap = BinaryHeap::from_vec(vec!(5i, 5, 2, 1, 3));
let mut heap = BinaryHeap::from_vec(vec!(5, 5, 2, 1, 3));
assert_eq!(heap.len(), 5);
assert_eq!(heap.replace(6).unwrap(), 5);
assert_eq!(heap.len(), 5);
@ -830,18 +846,18 @@ mod tests {
#[test]
fn test_to_vec() {
check_to_vec(vec!());
check_to_vec(vec!(5i));
check_to_vec(vec!(3i, 2));
check_to_vec(vec!(2i, 3));
check_to_vec(vec!(5i, 1, 2));
check_to_vec(vec!(1i, 100, 2, 3));
check_to_vec(vec!(1i, 3, 5, 7, 9, 2, 4, 6, 8, 0));
check_to_vec(vec!(2i, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
check_to_vec(vec!(9i, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
check_to_vec(vec!(10i, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
check_to_vec(vec!(5i, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
check_to_vec(vec!(5));
check_to_vec(vec!(3, 2));
check_to_vec(vec!(2, 3));
check_to_vec(vec!(5, 1, 2));
check_to_vec(vec!(1, 100, 2, 3));
check_to_vec(vec!(1, 3, 5, 7, 9, 2, 4, 6, 8, 0));
check_to_vec(vec!(2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
check_to_vec(vec!(9, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
check_to_vec(vec!(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
check_to_vec(vec!(5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
}
#[test]

View File

@ -89,7 +89,7 @@ use core::fmt;
use core::hash;
use core::iter::RandomAccessIterator;
use core::iter::{Chain, Enumerate, Repeat, Skip, Take, repeat, Cloned};
use core::iter::{self, FromIterator};
use core::iter::{self, FromIterator, IntoIterator};
use core::num::Int;
use core::ops::Index;
use core::slice;
@ -1070,6 +1070,14 @@ impl<'a> RandomAccessIterator for Iter<'a> {
}
}
impl<'a> IntoIterator for &'a Bitv {
type Iter = Iter<'a>;
fn into_iter(self) -> Iter<'a> {
self.iter()
}
}
/// An implementation of a set using a bit vector as an underlying
/// representation for holding unsigned numerical elements.
///
@ -1730,6 +1738,7 @@ impl BitvSet {
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for BitvSet {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "BitvSet {{"));
@ -1873,6 +1882,13 @@ impl<'a> Iterator for SymmetricDifference<'a> {
#[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.0.size_hint() }
}
impl<'a> IntoIterator for &'a BitvSet {
type Iter = SetIter<'a>;
fn into_iter(self) -> SetIter<'a> {
self.iter()
}
}
#[cfg(test)]
mod tests {

View File

@ -24,7 +24,7 @@ use core::cmp::Ordering;
use core::default::Default;
use core::fmt::Debug;
use core::hash::{Hash, Hasher};
use core::iter::{Map, FromIterator};
use core::iter::{Map, FromIterator, IntoIterator};
use core::ops::{Index, IndexMut};
use core::{iter, fmt, mem};
use Bound::{self, Included, Excluded, Unbounded};
@ -478,6 +478,30 @@ impl<K: Ord, V> BTreeMap<K, V> {
}
}
impl<K, V> IntoIterator for BTreeMap<K, V> {
type Iter = IntoIter<K, V>;
fn into_iter(self) -> IntoIter<K, V> {
self.into_iter()
}
}
impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> {
type Iter = Iter<'a, K, V>;
fn into_iter(self) -> Iter<'a, K, V> {
self.iter()
}
}
impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
type Iter = IterMut<'a, K, V>;
fn into_iter(mut self) -> IterMut<'a, K, V> {
self.iter_mut()
}
}
/// A helper enum useful for deciding whether to continue a loop since we can't
/// return from a closure
enum Continuation<A, B> {
@ -1782,7 +1806,7 @@ mod test {
#[test]
fn test_entry(){
let xs = [(1i, 10i), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
let mut map: BTreeMap<int, int> = xs.iter().map(|&x| x).collect();

View File

@ -271,7 +271,7 @@ impl<T> DoubleEndedIterator for RawItems<T> {
#[unsafe_destructor]
impl<T> Drop for RawItems<T> {
fn drop(&mut self) {
for _ in *self {}
for _ in self.by_ref() {}
}
}
@ -1374,9 +1374,9 @@ impl<K, V> Drop for MoveTraversalImpl<K, V> {
fn drop(&mut self) {
// We need to cleanup the stored values manually, as the RawItems destructor would run
// after our deallocation.
for _ in self.keys {}
for _ in self.vals {}
for _ in self.edges {}
for _ in self.keys.by_ref() {}
for _ in self.vals.by_ref() {}
for _ in self.edges.by_ref() {}
let (alignment, size) =
calculate_allocation_generic::<K, V>(self.capacity, self.is_leaf);

View File

@ -18,7 +18,7 @@ use core::cmp::Ordering::{self, Less, Greater, Equal};
use core::default::Default;
use core::fmt::Debug;
use core::fmt;
use core::iter::{Peekable, Map, FromIterator};
use core::iter::{Peekable, Map, FromIterator, IntoIterator};
use core::ops::{BitOr, BitAnd, BitXor, Sub};
use btree_map::{BTreeMap, Keys};
@ -282,7 +282,7 @@ impl<T: Ord> BTreeSet<T> {
///
/// let mut v = BTreeSet::new();
/// assert_eq!(v.len(), 0);
/// v.insert(1i);
/// v.insert(1);
/// assert_eq!(v.len(), 1);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -297,7 +297,7 @@ impl<T: Ord> BTreeSet<T> {
///
/// let mut v = BTreeSet::new();
/// assert!(v.is_empty());
/// v.insert(1i);
/// v.insert(1);
/// assert!(!v.is_empty());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -311,7 +311,7 @@ impl<T: Ord> BTreeSet<T> {
/// use std::collections::BTreeSet;
///
/// let mut v = BTreeSet::new();
/// v.insert(1i);
/// v.insert(1);
/// v.clear();
/// assert!(v.is_empty());
/// ```
@ -331,7 +331,7 @@ impl<T: Ord> BTreeSet<T> {
/// ```
/// use std::collections::BTreeSet;
///
/// let set: BTreeSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
/// let set: BTreeSet<int> = [1, 2, 3].iter().map(|&x| x).collect();
/// assert_eq!(set.contains(&1), true);
/// assert_eq!(set.contains(&4), false);
/// ```
@ -348,7 +348,7 @@ impl<T: Ord> BTreeSet<T> {
/// ```
/// use std::collections::BTreeSet;
///
/// let a: BTreeSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
/// let a: BTreeSet<int> = [1, 2, 3].iter().map(|&x| x).collect();
/// let mut b: BTreeSet<int> = BTreeSet::new();
///
/// assert_eq!(a.is_disjoint(&b), true);
@ -369,7 +369,7 @@ impl<T: Ord> BTreeSet<T> {
/// ```
/// use std::collections::BTreeSet;
///
/// let sup: BTreeSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
/// let sup: BTreeSet<int> = [1, 2, 3].iter().map(|&x| x).collect();
/// let mut set: BTreeSet<int> = BTreeSet::new();
///
/// assert_eq!(set.is_subset(&sup), true);
@ -411,7 +411,7 @@ impl<T: Ord> BTreeSet<T> {
/// ```
/// use std::collections::BTreeSet;
///
/// let sub: BTreeSet<int> = [1i, 2].iter().map(|&x| x).collect();
/// let sub: BTreeSet<int> = [1, 2].iter().map(|&x| x).collect();
/// let mut set: BTreeSet<int> = BTreeSet::new();
///
/// assert_eq!(set.is_superset(&sub), false);
@ -438,8 +438,8 @@ impl<T: Ord> BTreeSet<T> {
///
/// let mut set = BTreeSet::new();
///
/// assert_eq!(set.insert(2i), true);
/// assert_eq!(set.insert(2i), false);
/// assert_eq!(set.insert(2), true);
/// assert_eq!(set.insert(2), false);
/// assert_eq!(set.len(), 1);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -461,7 +461,7 @@ impl<T: Ord> BTreeSet<T> {
///
/// let mut set = BTreeSet::new();
///
/// set.insert(2i);
/// set.insert(2);
/// assert_eq!(set.remove(&2), true);
/// assert_eq!(set.remove(&2), false);
/// ```
@ -480,6 +480,22 @@ impl<T: Ord> FromIterator<T> for BTreeSet<T> {
}
}
impl<T> IntoIterator for BTreeSet<T> {
type Iter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
self.into_iter()
}
}
impl<'a, T> IntoIterator for &'a BTreeSet<T> {
type Iter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> Extend<T> for BTreeSet<T> {
#[inline]
@ -731,7 +747,7 @@ mod test {
fn test_clone_eq() {
let mut m = BTreeSet::new();
m.insert(1i);
m.insert(1);
m.insert(2);
assert!(m.clone() == m);
@ -742,11 +758,11 @@ mod test {
let mut x = BTreeSet::new();
let mut y = BTreeSet::new();
x.insert(1i);
x.insert(1);
x.insert(2);
x.insert(3);
y.insert(3i);
y.insert(3);
y.insert(2);
y.insert(1);
@ -874,7 +890,7 @@ mod test {
#[test]
fn test_from_iter() {
let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let set: BTreeSet<int> = xs.iter().map(|&x| x).collect();

View File

@ -28,7 +28,7 @@ use core::cmp::Ordering;
use core::default::Default;
use core::fmt;
use core::hash::{Writer, Hasher, Hash};
use core::iter::{self, FromIterator};
use core::iter::{self, FromIterator, IntoIterator};
use core::mem;
use core::ptr;
@ -235,9 +235,9 @@ impl<T> DList<T> {
///
/// let mut a = DList::new();
/// let mut b = DList::new();
/// a.push_back(1i);
/// a.push_back(1);
/// a.push_back(2);
/// b.push_back(3i);
/// b.push_back(3);
/// b.push_back(4);
///
/// a.append(&mut b);
@ -529,7 +529,7 @@ impl<T> DList<T> {
/// use std::collections::DList;
///
/// let mut d = DList::new();
/// d.push_back(1i);
/// d.push_back(1);
/// d.push_back(3);
/// assert_eq!(3, *d.back().unwrap());
/// ```
@ -548,7 +548,7 @@ impl<T> DList<T> {
///
/// let mut d = DList::new();
/// assert_eq!(d.pop_back(), None);
/// d.push_back(1i);
/// d.push_back(1);
/// d.push_back(3);
/// assert_eq!(d.pop_back(), Some(3));
/// ```
@ -766,7 +766,7 @@ impl<'a, A> IterMut<'a, A> {
/// }
/// {
/// let vec: Vec<int> = list.into_iter().collect();
/// assert_eq!(vec, vec![1i, 2, 3, 4]);
/// assert_eq!(vec, vec![1, 2, 3, 4]);
/// }
/// ```
#[inline]
@ -830,6 +830,30 @@ impl<A> FromIterator<A> for DList<A> {
}
}
impl<T> IntoIterator for DList<T> {
type Iter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
self.into_iter()
}
}
impl<'a, T> IntoIterator for &'a DList<T> {
type Iter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut DList<T> {
type Iter = IterMut<'a, T>;
fn into_iter(mut self) -> IterMut<'a, T> {
self.iter_mut()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<A> Extend<A> for DList<A> {
fn extend<T: Iterator<Item=A>>(&mut self, mut iterator: T) {
@ -964,7 +988,7 @@ mod tests {
assert_eq!(m.pop_front(), Some(box 1));
let mut n = DList::new();
n.push_front(2i);
n.push_front(2);
n.push_front(3);
{
assert_eq!(n.front().unwrap(), &3);
@ -984,7 +1008,7 @@ mod tests {
#[cfg(test)]
fn generate_test() -> DList<int> {
list_from(&[0i,1,2,3,4,5,6])
list_from(&[0,1,2,3,4,5,6])
}
#[cfg(test)]
@ -1007,7 +1031,7 @@ mod tests {
{
let mut m = DList::new();
let mut n = DList::new();
n.push_back(2i);
n.push_back(2);
m.append(&mut n);
check_links(&m);
assert_eq!(m.len(), 1);
@ -1019,7 +1043,7 @@ mod tests {
{
let mut m = DList::new();
let mut n = DList::new();
m.push_back(2i);
m.push_back(2);
m.append(&mut n);
check_links(&m);
assert_eq!(m.len(), 1);
@ -1028,8 +1052,8 @@ mod tests {
}
// Non-empty to non-empty
let v = vec![1i,2,3,4,5];
let u = vec![9i,8,1,2,3,4,5];
let v = vec![1,2,3,4,5];
let u = vec![9,8,1,2,3,4,5];
let mut m = list_from(v.as_slice());
let mut n = list_from(u.as_slice());
m.append(&mut n);
@ -1054,7 +1078,7 @@ mod tests {
// singleton
{
let mut m = DList::new();
m.push_back(1i);
m.push_back(1);
let p = m.split_off(0);
assert_eq!(m.len(), 0);
@ -1065,29 +1089,29 @@ mod tests {
// not singleton, forwards
{
let u = vec![1i,2,3,4,5];
let u = vec![1,2,3,4,5];
let mut m = list_from(u.as_slice());
let mut n = m.split_off(2);
assert_eq!(m.len(), 2);
assert_eq!(n.len(), 3);
for elt in 1i..3 {
for elt in 1..3 {
assert_eq!(m.pop_front(), Some(elt));
}
for elt in 3i..6 {
for elt in 3..6 {
assert_eq!(n.pop_front(), Some(elt));
}
}
// not singleton, backwards
{
let u = vec![1i,2,3,4,5];
let u = vec![1,2,3,4,5];
let mut m = list_from(u.as_slice());
let mut n = m.split_off(4);
assert_eq!(m.len(), 4);
assert_eq!(n.len(), 1);
for elt in 1i..5 {
for elt in 1..5 {
assert_eq!(m.pop_front(), Some(elt));
}
for elt in 5i..6 {
for elt in 5..6 {
assert_eq!(n.pop_front(), Some(elt));
}
}
@ -1102,7 +1126,7 @@ mod tests {
}
let mut n = DList::new();
assert_eq!(n.iter().next(), None);
n.push_front(4i);
n.push_front(4);
let mut it = n.iter();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next().unwrap(), &4);
@ -1113,7 +1137,7 @@ mod tests {
#[test]
fn test_iterator_clone() {
let mut n = DList::new();
n.push_back(2i);
n.push_back(2);
n.push_back(3);
n.push_back(4);
let mut it = n.iter();
@ -1128,7 +1152,7 @@ mod tests {
fn test_iterator_double_end() {
let mut n = DList::new();
assert_eq!(n.iter().next(), None);
n.push_front(4i);
n.push_front(4);
n.push_front(5);
n.push_front(6);
let mut it = n.iter();
@ -1150,7 +1174,7 @@ mod tests {
}
let mut n = DList::new();
assert_eq!(n.iter().rev().next(), None);
n.push_front(4i);
n.push_front(4);
let mut it = n.iter().rev();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next().unwrap(), &4);
@ -1169,7 +1193,7 @@ mod tests {
assert_eq!(len, 0);
let mut n = DList::new();
assert!(n.iter_mut().next().is_none());
n.push_front(4i);
n.push_front(4);
n.push_back(5);
let mut it = n.iter_mut();
assert_eq!(it.size_hint(), (2, Some(2)));
@ -1183,7 +1207,7 @@ mod tests {
fn test_iterator_mut_double_end() {
let mut n = DList::new();
assert!(n.iter_mut().next_back().is_none());
n.push_front(4i);
n.push_front(4);
n.push_front(5);
n.push_front(6);
let mut it = n.iter_mut();
@ -1199,7 +1223,7 @@ mod tests {
#[test]
fn test_insert_prev() {
let mut m = list_from(&[0i,2,4,6,8]);
let mut m = list_from(&[0,2,4,6,8]);
let len = m.len();
{
let mut it = m.iter_mut();
@ -1232,7 +1256,7 @@ mod tests {
}
let mut n = DList::new();
assert!(n.iter_mut().rev().next().is_none());
n.push_front(4i);
n.push_front(4);
let mut it = n.iter_mut().rev();
assert!(it.next().is_some());
assert!(it.next().is_none());
@ -1240,7 +1264,7 @@ mod tests {
#[test]
fn test_send() {
let n = list_from(&[1i,2,3]);
let n = list_from(&[1,2,3]);
Thread::scoped(move || {
check_links(&n);
let a: &[_] = &[&1,&2,&3];
@ -1258,8 +1282,8 @@ mod tests {
m.push_back(1);
assert!(n == m);
let n = list_from(&[2i,3,4]);
let m = list_from(&[1i,2,3]);
let n = list_from(&[2,3,4]);
let m = list_from(&[1,2,3]);
assert!(n != m);
}
@ -1270,11 +1294,11 @@ mod tests {
assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y));
x.push_back(1i);
x.push_back(1);
x.push_back(2);
x.push_back(3);
y.push_front(3i);
y.push_front(3);
y.push_front(2);
y.push_front(1);
@ -1284,7 +1308,7 @@ mod tests {
#[test]
fn test_ord() {
let n: DList<int> = list_from(&[]);
let m = list_from(&[1i,2,3]);
let m = list_from(&[1,2,3]);
assert!(n < m);
assert!(m > n);
assert!(n <= n);
@ -1334,7 +1358,7 @@ mod tests {
#[test]
fn test_show() {
let list: DList<int> = (0i..10).collect();
let list: DList<i32> = (0..10).collect();
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()
@ -1384,7 +1408,7 @@ mod tests {
#[bench]
fn bench_collect_into(b: &mut test::Bencher) {
let v = &[0i; 64];
let v = &[0; 64];
b.iter(|| {
let _: DList<int> = v.iter().map(|x| *x).collect();
})
@ -1426,7 +1450,7 @@ mod tests {
#[bench]
fn bench_iter(b: &mut test::Bencher) {
let v = &[0i; 128];
let v = &[0; 128];
let m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.iter().count() == 128);
@ -1434,7 +1458,7 @@ mod tests {
}
#[bench]
fn bench_iter_mut(b: &mut test::Bencher) {
let v = &[0i; 128];
let v = &[0; 128];
let mut m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.iter_mut().count() == 128);
@ -1442,7 +1466,7 @@ mod tests {
}
#[bench]
fn bench_iter_rev(b: &mut test::Bencher) {
let v = &[0i; 128];
let v = &[0; 128];
let m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.iter().rev().count() == 128);
@ -1450,7 +1474,7 @@ mod tests {
}
#[bench]
fn bench_iter_mut_rev(b: &mut test::Bencher) {
let v = &[0i; 128];
let v = &[0; 128];
let mut m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.iter_mut().rev().count() == 128);

View File

@ -16,7 +16,7 @@
use core::prelude::*;
use core::fmt;
use core::num::Int;
use core::iter::FromIterator;
use core::iter::{FromIterator, IntoIterator};
use core::ops::{Sub, BitOr, BitAnd, BitXor};
// FIXME(contentions): implement union family of methods? (general design may be wrong here)
@ -31,6 +31,7 @@ pub struct EnumSet<E> {
impl<E> Copy for EnumSet<E> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<E:CLike + fmt::Debug> fmt::Debug for EnumSet<E> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "EnumSet {{"));
@ -256,6 +257,14 @@ impl<E:CLike> FromIterator<E> for EnumSet<E> {
}
}
impl<'a, E> IntoIterator for &'a EnumSet<E> where E: CLike {
type Iter = Iter<E>;
fn into_iter(self) -> Iter<E> {
self.iter()
}
}
impl<E:CLike> Extend<E> for EnumSet<E> {
fn extend<I: Iterator<Item=E>>(&mut self, mut iterator: I) {
for element in iterator {

View File

@ -15,7 +15,6 @@
#![crate_name = "collections"]
#![unstable(feature = "collections")]
#![feature(staged_api)]
#![staged_api]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
@ -23,18 +22,21 @@
html_root_url = "http://doc.rust-lang.org/nightly/",
html_playground_url = "http://play.rust-lang.org/")]
#![allow(unknown_features)]
#![feature(unsafe_destructor, slicing_syntax)]
#![feature(box_syntax)]
#![feature(unboxed_closures)]
#![allow(unknown_features)] #![feature(int_uint)]
#![no_std]
#![feature(core)]
#![cfg_attr(not(stage0), allow(unused_mut))] // NOTE: remove after stage0 snap
#![feature(alloc)]
#![feature(unicode)]
#![feature(box_syntax)]
#![feature(core)]
#![feature(hash)]
#![feature(int_uint)]
#![feature(staged_api)]
#![feature(unboxed_closures)]
#![feature(unicode)]
#![feature(unsafe_destructor, slicing_syntax)]
#![cfg_attr(test, feature(test))]
#![no_std]
#[macro_use]
extern crate core;
@ -114,6 +116,8 @@ mod std {
pub use core::marker; // derive(Copy)
pub use core::hash; // derive(Hash)
pub use core::ops; // RangeFull
// for-loops
pub use core::iter;
}
#[cfg(test)]

View File

@ -19,7 +19,7 @@ use core::prelude::*;
use core::cmp::Ordering;
use core::default::Default;
use core::fmt;
use core::iter::{self, repeat, FromIterator, RandomAccessIterator};
use core::iter::{self, repeat, FromIterator, IntoIterator, RandomAccessIterator};
use core::marker;
use core::mem;
use core::num::{Int, UnsignedInt};
@ -186,7 +186,7 @@ impl<T> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut buf = RingBuf::new();
/// buf.push_back(3i);
/// buf.push_back(3);
/// buf.push_back(4);
/// buf.push_back(5);
/// assert_eq!(buf.get(1).unwrap(), &4);
@ -209,7 +209,7 @@ impl<T> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut buf = RingBuf::new();
/// buf.push_back(3i);
/// buf.push_back(3);
/// buf.push_back(4);
/// buf.push_back(5);
/// match buf.get_mut(1) {
@ -243,7 +243,7 @@ impl<T> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut buf = RingBuf::new();
/// buf.push_back(3i);
/// buf.push_back(3);
/// buf.push_back(4);
/// buf.push_back(5);
/// buf.swap(0, 2);
@ -269,7 +269,7 @@ impl<T> RingBuf<T> {
/// ```
/// use std::collections::RingBuf;
///
/// let buf: RingBuf<int> = RingBuf::with_capacity(10);
/// let buf: RingBuf<i32> = RingBuf::with_capacity(10);
/// assert!(buf.capacity() >= 10);
/// ```
#[inline]
@ -292,7 +292,7 @@ impl<T> RingBuf<T> {
/// ```
/// use std::collections::RingBuf;
///
/// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
/// let mut buf: RingBuf<i32> = vec![1].into_iter().collect();
/// buf.reserve_exact(10);
/// assert!(buf.capacity() >= 11);
/// ```
@ -313,7 +313,7 @@ impl<T> RingBuf<T> {
/// ```
/// use std::collections::RingBuf;
///
/// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
/// let mut buf: RingBuf<i32> = vec![1].into_iter().collect();
/// buf.reserve(10);
/// assert!(buf.capacity() >= 11);
/// ```
@ -473,8 +473,8 @@ impl<T> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut buf = RingBuf::new();
/// buf.push_back(5i);
/// buf.push_back(10i);
/// buf.push_back(5);
/// buf.push_back(10);
/// buf.push_back(15);
/// buf.truncate(1);
/// assert_eq!(buf.len(), 1);
@ -496,11 +496,11 @@ impl<T> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut buf = RingBuf::new();
/// buf.push_back(5i);
/// buf.push_back(5);
/// buf.push_back(3);
/// buf.push_back(4);
/// let b: &[_] = &[&5, &3, &4];
/// assert_eq!(buf.iter().collect::<Vec<&int>>().as_slice(), b);
/// assert_eq!(buf.iter().collect::<Vec<&i32>>().as_slice(), b);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn iter(&self) -> Iter<T> {
@ -519,14 +519,14 @@ impl<T> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut buf = RingBuf::new();
/// buf.push_back(5i);
/// buf.push_back(5);
/// buf.push_back(3);
/// buf.push_back(4);
/// for num in buf.iter_mut() {
/// *num = *num - 2;
/// }
/// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
/// assert_eq!(&buf.iter_mut().collect::<Vec<&mut int>>()[], b);
/// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[], b);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
@ -600,7 +600,7 @@ impl<T> RingBuf<T> {
///
/// let mut v = RingBuf::new();
/// assert_eq!(v.len(), 0);
/// v.push_back(1i);
/// v.push_back(1);
/// assert_eq!(v.len(), 1);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -615,7 +615,7 @@ impl<T> RingBuf<T> {
///
/// let mut v = RingBuf::new();
/// assert!(v.is_empty());
/// v.push_front(1i);
/// v.push_front(1);
/// assert!(!v.is_empty());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -630,7 +630,7 @@ impl<T> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut v = RingBuf::new();
/// v.push_back(1i);
/// v.push_back(1);
/// assert_eq!(v.drain().next(), Some(1));
/// assert!(v.is_empty());
/// ```
@ -651,7 +651,7 @@ impl<T> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut v = RingBuf::new();
/// v.push_back(1i);
/// v.push_back(1);
/// v.clear();
/// assert!(v.is_empty());
/// ```
@ -672,9 +672,9 @@ impl<T> RingBuf<T> {
/// let mut d = RingBuf::new();
/// assert_eq!(d.front(), None);
///
/// d.push_back(1i);
/// d.push_back(2i);
/// assert_eq!(d.front(), Some(&1i));
/// d.push_back(1);
/// d.push_back(2);
/// assert_eq!(d.front(), Some(&1));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn front(&self) -> Option<&T> {
@ -692,13 +692,13 @@ impl<T> RingBuf<T> {
/// let mut d = RingBuf::new();
/// assert_eq!(d.front_mut(), None);
///
/// d.push_back(1i);
/// d.push_back(2i);
/// d.push_back(1);
/// d.push_back(2);
/// match d.front_mut() {
/// Some(x) => *x = 9i,
/// Some(x) => *x = 9,
/// None => (),
/// }
/// assert_eq!(d.front(), Some(&9i));
/// assert_eq!(d.front(), Some(&9));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn front_mut(&mut self) -> Option<&mut T> {
@ -716,9 +716,9 @@ impl<T> RingBuf<T> {
/// let mut d = RingBuf::new();
/// assert_eq!(d.back(), None);
///
/// d.push_back(1i);
/// d.push_back(2i);
/// assert_eq!(d.back(), Some(&2i));
/// d.push_back(1);
/// d.push_back(2);
/// assert_eq!(d.back(), Some(&2));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn back(&self) -> Option<&T> {
@ -736,13 +736,13 @@ impl<T> RingBuf<T> {
/// let mut d = RingBuf::new();
/// assert_eq!(d.back(), None);
///
/// d.push_back(1i);
/// d.push_back(2i);
/// d.push_back(1);
/// d.push_back(2);
/// match d.back_mut() {
/// Some(x) => *x = 9i,
/// Some(x) => *x = 9,
/// None => (),
/// }
/// assert_eq!(d.back(), Some(&9i));
/// assert_eq!(d.back(), Some(&9));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn back_mut(&mut self) -> Option<&mut T> {
@ -759,11 +759,11 @@ impl<T> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut d = RingBuf::new();
/// d.push_back(1i);
/// d.push_back(2i);
/// d.push_back(1);
/// d.push_back(2);
///
/// assert_eq!(d.pop_front(), Some(1i));
/// assert_eq!(d.pop_front(), Some(2i));
/// assert_eq!(d.pop_front(), Some(1));
/// assert_eq!(d.pop_front(), Some(2));
/// assert_eq!(d.pop_front(), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -785,9 +785,9 @@ impl<T> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut d = RingBuf::new();
/// d.push_front(1i);
/// d.push_front(2i);
/// assert_eq!(d.front(), Some(&2i));
/// d.push_front(1);
/// d.push_front(2);
/// assert_eq!(d.front(), Some(&2));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push_front(&mut self, t: T) {
@ -809,7 +809,7 @@ impl<T> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut buf = RingBuf::new();
/// buf.push_back(1i);
/// buf.push_back(1);
/// buf.push_back(3);
/// assert_eq!(3, *buf.back().unwrap());
/// ```
@ -835,7 +835,7 @@ impl<T> RingBuf<T> {
///
/// let mut buf = RingBuf::new();
/// assert_eq!(buf.pop_back(), None);
/// buf.push_back(1i);
/// buf.push_back(1);
/// buf.push_back(3);
/// assert_eq!(buf.pop_back(), Some(3));
/// ```
@ -869,7 +869,7 @@ impl<T> RingBuf<T> {
///
/// let mut buf = RingBuf::new();
/// assert_eq!(buf.swap_back_remove(0), None);
/// buf.push_back(5i);
/// buf.push_back(5);
/// buf.push_back(99);
/// buf.push_back(15);
/// buf.push_back(20);
@ -902,11 +902,11 @@ impl<T> RingBuf<T> {
///
/// let mut buf = RingBuf::new();
/// assert_eq!(buf.swap_front_remove(0), None);
/// buf.push_back(15i);
/// buf.push_back(15);
/// buf.push_back(5);
/// buf.push_back(10);
/// buf.push_back(99);
/// buf.push_back(20i);
/// buf.push_back(20);
/// assert_eq!(buf.swap_front_remove(3), Some(99));
/// ```
#[unstable(feature = "collections",
@ -934,7 +934,7 @@ impl<T> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut buf = RingBuf::new();
/// buf.push_back(10i);
/// buf.push_back(10);
/// buf.push_back(12);
/// buf.insert(1,11);
/// assert_eq!(Some(&11), buf.get(1));
@ -1136,9 +1136,9 @@ impl<T> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut buf = RingBuf::new();
/// buf.push_back(5i);
/// buf.push_back(10i);
/// buf.push_back(12i);
/// buf.push_back(5);
/// buf.push_back(10);
/// buf.push_back(12);
/// buf.push_back(15);
/// buf.remove(2);
/// assert_eq!(Some(&15), buf.get(2));
@ -1301,8 +1301,8 @@ impl<T: Clone> RingBuf<T> {
/// use std::collections::RingBuf;
///
/// let mut buf = RingBuf::new();
/// buf.push_back(5i);
/// buf.push_back(10i);
/// buf.push_back(5);
/// buf.push_back(10);
/// buf.push_back(15);
/// buf.resize(2, 0);
/// buf.resize(6, 20);
@ -1510,7 +1510,7 @@ pub struct Drain<'a, T: 'a> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: 'a> Drop for Drain<'a, T> {
fn drop(&mut self) {
for _ in *self {}
for _ in self.by_ref() {}
self.inner.head = 0;
self.inner.tail = 0;
}
@ -1609,6 +1609,30 @@ impl<A> FromIterator<A> for RingBuf<A> {
}
}
impl<T> IntoIterator for RingBuf<T> {
type Iter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
self.into_iter()
}
}
impl<'a, T> IntoIterator for &'a RingBuf<T> {
type Iter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut RingBuf<T> {
type Iter = IterMut<'a, T>;
fn into_iter(mut self) -> IterMut<'a, T> {
self.iter_mut()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<A> Extend<A> for RingBuf<A> {
fn extend<T: Iterator<Item=A>>(&mut self, mut iterator: T) {
@ -1650,8 +1674,8 @@ mod tests {
fn test_simple() {
let mut d = RingBuf::new();
assert_eq!(d.len(), 0u);
d.push_front(17i);
d.push_front(42i);
d.push_front(17);
d.push_front(42);
d.push_back(137);
assert_eq!(d.len(), 3u);
d.push_back(137);
@ -1769,7 +1793,7 @@ mod tests {
fn bench_push_back_100(b: &mut test::Bencher) {
let mut deq = RingBuf::with_capacity(101);
b.iter(|| {
for i in 0i..100 {
for i in 0..100 {
deq.push_back(i);
}
deq.head = 0;
@ -1781,7 +1805,7 @@ mod tests {
fn bench_push_front_100(b: &mut test::Bencher) {
let mut deq = RingBuf::with_capacity(101);
b.iter(|| {
for i in 0i..100 {
for i in 0..100 {
deq.push_front(i);
}
deq.head = 0;
@ -1791,7 +1815,7 @@ mod tests {
#[bench]
fn bench_pop_back_100(b: &mut test::Bencher) {
let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
let mut deq: RingBuf<i32> = RingBuf::with_capacity(101);
b.iter(|| {
deq.head = 100;
@ -1804,7 +1828,7 @@ mod tests {
#[bench]
fn bench_pop_front_100(b: &mut test::Bencher) {
let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
let mut deq: RingBuf<i32> = RingBuf::with_capacity(101);
b.iter(|| {
deq.head = 100;
@ -1819,7 +1843,7 @@ mod tests {
fn bench_grow_1025(b: &mut test::Bencher) {
b.iter(|| {
let mut deq = RingBuf::new();
for i in 0i..1025 {
for i in 0..1025 {
deq.push_front(i);
}
test::black_box(deq);
@ -1828,7 +1852,7 @@ mod tests {
#[bench]
fn bench_iter_1000(b: &mut test::Bencher) {
let ring: RingBuf<int> = (0i..1000).collect();
let ring: RingBuf<i32> = (0..1000).collect();
b.iter(|| {
let mut sum = 0;
@ -1841,7 +1865,7 @@ mod tests {
#[bench]
fn bench_mut_iter_1000(b: &mut test::Bencher) {
let mut ring: RingBuf<int> = (0i..1000).collect();
let mut ring: RingBuf<i32> = (0..1000).collect();
b.iter(|| {
let mut sum = 0;
@ -1854,28 +1878,28 @@ mod tests {
#[derive(Clone, PartialEq, Debug)]
enum Taggy {
One(int),
Two(int, int),
Three(int, int, int),
One(i32),
Two(i32, i32),
Three(i32, i32, i32),
}
#[derive(Clone, PartialEq, Debug)]
enum Taggypar<T> {
Onepar(int),
Twopar(int, int),
Threepar(int, int, int),
Onepar(i32),
Twopar(i32, i32),
Threepar(i32, i32, i32),
}
#[derive(Clone, PartialEq, Debug)]
struct RecCy {
x: int,
y: int,
x: i32,
y: i32,
t: Taggy
}
#[test]
fn test_param_int() {
test_parameterized::<int>(5, 72, 64, 175);
test_parameterized::<i32>(5, 72, 64, 175);
}
#[test]
@ -1885,10 +1909,10 @@ mod tests {
#[test]
fn test_param_taggypar() {
test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
Twopar::<int>(1, 2),
Threepar::<int>(1, 2, 3),
Twopar::<int>(17, 42));
test_parameterized::<Taggypar<i32>>(Onepar::<i32>(1),
Twopar::<i32>(1, 2),
Threepar::<i32>(1, 2, 3),
Twopar::<i32>(17, 42));
}
#[test]
@ -1903,17 +1927,17 @@ mod tests {
#[test]
fn test_with_capacity() {
let mut d = RingBuf::with_capacity(0);
d.push_back(1i);
d.push_back(1);
assert_eq!(d.len(), 1);
let mut d = RingBuf::with_capacity(50);
d.push_back(1i);
d.push_back(1);
assert_eq!(d.len(), 1);
}
#[test]
fn test_with_capacity_non_power_two() {
let mut d3 = RingBuf::with_capacity(3);
d3.push_back(1i);
d3.push_back(1);
// X = None, | = lo
// [|1, X, X]
@ -1977,10 +2001,10 @@ mod tests {
#[test]
fn test_swap() {
let mut d: RingBuf<int> = (0i..5).collect();
let mut d: RingBuf<i32> = (0..5).collect();
d.pop_front();
d.swap(0, 3);
assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
assert_eq!(d.iter().map(|&x|x).collect::<Vec<i32>>(), vec!(4, 2, 3, 1));
}
#[test]
@ -1989,20 +2013,20 @@ mod tests {
assert_eq!(d.iter().next(), None);
assert_eq!(d.iter().size_hint(), (0, Some(0)));
for i in 0i..5 {
for i in 0..5 {
d.push_back(i);
}
{
let b: &[_] = &[&0,&1,&2,&3,&4];
assert_eq!(d.iter().collect::<Vec<&int>>(), b);
assert_eq!(d.iter().collect::<Vec<&i32>>(), b);
}
for i in 6i..9 {
for i in 6..9 {
d.push_front(i);
}
{
let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
assert_eq!(d.iter().collect::<Vec<&int>>(), b);
assert_eq!(d.iter().collect::<Vec<&i32>>(), b);
}
let mut it = d.iter();
@ -2020,19 +2044,19 @@ mod tests {
let mut d = RingBuf::new();
assert_eq!(d.iter().rev().next(), None);
for i in 0i..5 {
for i in 0..5 {
d.push_back(i);
}
{
let b: &[_] = &[&4,&3,&2,&1,&0];
assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
assert_eq!(d.iter().rev().collect::<Vec<&i32>>(), b);
}
for i in 6i..9 {
for i in 6..9 {
d.push_front(i);
}
let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
assert_eq!(d.iter().rev().collect::<Vec<&i32>>(), b);
}
#[test]
@ -2040,13 +2064,13 @@ mod tests {
let mut d = RingBuf::with_capacity(3);
assert!(d.iter_mut().rev().next().is_none());
d.push_back(1i);
d.push_back(1);
d.push_back(2);
d.push_back(3);
assert_eq!(d.pop_front(), Some(1));
d.push_back(4);
assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<int>>(),
assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<i32>>(),
vec!(4, 3, 2));
}
@ -2101,7 +2125,7 @@ mod tests {
// Empty iter
{
let d: RingBuf<int> = RingBuf::new();
let d: RingBuf<i32> = RingBuf::new();
let mut iter = d.into_iter();
assert_eq!(iter.size_hint(), (0, Some(0)));
@ -2112,35 +2136,35 @@ mod tests {
// simple iter
{
let mut d = RingBuf::new();
for i in 0i..5 {
for i in 0..5 {
d.push_back(i);
}
let b = vec![0,1,2,3,4];
assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
assert_eq!(d.into_iter().collect::<Vec<i32>>(), b);
}
// wrapped iter
{
let mut d = RingBuf::new();
for i in 0i..5 {
for i in 0..5 {
d.push_back(i);
}
for i in 6i..9 {
for i in 6..9 {
d.push_front(i);
}
let b = vec![8,7,6,0,1,2,3,4];
assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
assert_eq!(d.into_iter().collect::<Vec<i32>>(), b);
}
// partially used
{
let mut d = RingBuf::new();
for i in 0i..5 {
for i in 0..5 {
d.push_back(i);
}
for i in 6i..9 {
for i in 6..9 {
d.push_front(i);
}
@ -2160,7 +2184,7 @@ mod tests {
// Empty iter
{
let mut d: RingBuf<int> = RingBuf::new();
let mut d: RingBuf<i32> = RingBuf::new();
{
let mut iter = d.drain();
@ -2176,35 +2200,35 @@ mod tests {
// simple iter
{
let mut d = RingBuf::new();
for i in 0i..5 {
for i in 0..5 {
d.push_back(i);
}
assert_eq!(d.drain().collect::<Vec<int>>(), [0, 1, 2, 3, 4]);
assert_eq!(d.drain().collect::<Vec<_>>(), [0, 1, 2, 3, 4]);
assert!(d.is_empty());
}
// wrapped iter
{
let mut d = RingBuf::new();
for i in 0i..5 {
for i in 0..5 {
d.push_back(i);
}
for i in 6i..9 {
for i in 6..9 {
d.push_front(i);
}
assert_eq!(d.drain().collect::<Vec<int>>(), [8,7,6,0,1,2,3,4]);
assert_eq!(d.drain().collect::<Vec<_>>(), [8,7,6,0,1,2,3,4]);
assert!(d.is_empty());
}
// partially used
{
let mut d = RingBuf::new();
for i in 0i..5 {
let mut d: RingBuf<i32> = RingBuf::new();
for i in 0..5 {
d.push_back(i);
}
for i in 6i..9 {
for i in 6..9 {
d.push_front(i);
}
@ -2225,9 +2249,9 @@ mod tests {
#[test]
fn test_from_iter() {
use core::iter;
let v = vec!(1i,2,3,4,5,6,7);
let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
let u: Vec<int> = deq.iter().map(|&x| x).collect();
let v = vec!(1,2,3,4,5,6,7);
let deq: RingBuf<i32> = v.iter().map(|&x| x).collect();
let u: Vec<i32> = deq.iter().map(|&x| x).collect();
assert_eq!(u, v);
let seq = iter::count(0u, 2).take(256);
@ -2241,7 +2265,7 @@ mod tests {
#[test]
fn test_clone() {
let mut d = RingBuf::new();
d.push_front(17i);
d.push_front(17);
d.push_front(42);
d.push_back(137);
d.push_back(137);
@ -2259,7 +2283,7 @@ mod tests {
fn test_eq() {
let mut d = RingBuf::new();
assert!(d == RingBuf::with_capacity(0));
d.push_front(137i);
d.push_front(137);
d.push_front(17);
d.push_front(42);
d.push_back(137);
@ -2281,12 +2305,12 @@ mod tests {
let mut x = RingBuf::new();
let mut y = RingBuf::new();
x.push_back(1i);
x.push_back(1);
x.push_back(2);
x.push_back(3);
y.push_back(0i);
y.push_back(1i);
y.push_back(0);
y.push_back(1);
y.pop_front();
y.push_back(2);
y.push_back(3);
@ -2298,7 +2322,7 @@ mod tests {
fn test_ord() {
let x = RingBuf::new();
let mut y = RingBuf::new();
y.push_back(1i);
y.push_back(1);
y.push_back(2);
y.push_back(3);
assert!(x < y);
@ -2309,7 +2333,7 @@ mod tests {
#[test]
fn test_show() {
let ringbuf: RingBuf<int> = (0i..10).collect();
let ringbuf: RingBuf<i32> = (0..10).collect();
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()
@ -2389,41 +2413,41 @@ mod tests {
// test growth path A
// [T o o H] -> [T o o H . . . . ]
let mut ring = RingBuf::with_capacity(4);
for i in 0i..3 {
for i in 0..3 {
ring.push_back(i);
}
ring.reserve(7);
for i in 0i..3 {
for i in 0..3 {
assert_eq!(ring.pop_front(), Some(i));
}
// test growth path B
// [H T o o] -> [. T o o H . . . ]
let mut ring = RingBuf::with_capacity(4);
for i in 0i..1 {
for i in 0..1 {
ring.push_back(i);
assert_eq!(ring.pop_front(), Some(i));
}
for i in 0i..3 {
for i in 0..3 {
ring.push_back(i);
}
ring.reserve(7);
for i in 0i..3 {
for i in 0..3 {
assert_eq!(ring.pop_front(), Some(i));
}
// test growth path C
// [o o H T] -> [o o H . . . . T ]
let mut ring = RingBuf::with_capacity(4);
for i in 0i..3 {
for i in 0..3 {
ring.push_back(i);
assert_eq!(ring.pop_front(), Some(i));
}
for i in 0i..3 {
for i in 0..3 {
ring.push_back(i);
}
ring.reserve(7);
for i in 0i..3 {
for i in 0..3 {
assert_eq!(ring.pop_front(), Some(i));
}
}
@ -2431,7 +2455,7 @@ mod tests {
#[test]
fn test_get() {
let mut ring = RingBuf::new();
ring.push_back(0i);
ring.push_back(0);
assert_eq!(ring.get(0), Some(&0));
assert_eq!(ring.get(1), None);
@ -2463,7 +2487,7 @@ mod tests {
#[test]
fn test_get_mut() {
let mut ring = RingBuf::new();
for i in 0i..3 {
for i in 0..3 {
ring.push_back(i);
}
@ -2633,8 +2657,8 @@ mod tests {
#[test]
fn test_front() {
let mut ring = RingBuf::new();
ring.push_back(10i);
ring.push_back(20i);
ring.push_back(10);
ring.push_back(20);
assert_eq!(ring.front(), Some(&10));
ring.pop_front();
assert_eq!(ring.front(), Some(&20));
@ -2644,8 +2668,8 @@ mod tests {
#[test]
fn test_as_slices() {
let mut ring: RingBuf<int> = RingBuf::with_capacity(127);
let cap = ring.capacity() as int;
let mut ring: RingBuf<i32> = RingBuf::with_capacity(127);
let cap = ring.capacity() as i32;
let first = cap/2;
let last = cap - first;
for i in 0..first {
@ -2666,14 +2690,14 @@ mod tests {
assert_eq!(right, expected_right);
}
assert_eq!(ring.len() as int, cap);
assert_eq!(ring.capacity() as int, cap);
assert_eq!(ring.len() as i32, cap);
assert_eq!(ring.capacity() as i32, cap);
}
#[test]
fn test_as_mut_slices() {
let mut ring: RingBuf<int> = RingBuf::with_capacity(127);
let cap = ring.capacity() as int;
let mut ring: RingBuf<i32> = RingBuf::with_capacity(127);
let cap = ring.capacity() as i32;
let first = cap/2;
let last = cap - first;
for i in 0..first {
@ -2694,7 +2718,7 @@ mod tests {
assert_eq!(right, expected_right);
}
assert_eq!(ring.len() as int, cap);
assert_eq!(ring.capacity() as int, cap);
assert_eq!(ring.len() as i32, cap);
assert_eq!(ring.capacity() as i32, cap);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -68,6 +68,7 @@ use core::ops::FullRange;
#[cfg(not(stage0))]
use core::ops::RangeFull;
use core::option::Option::{self, Some, None};
use core::result::Result;
use core::slice::AsSlice;
use core::str as core_str;
use unicode::str::{UnicodeStr, Utf16Encoder};
@ -199,7 +200,7 @@ impl<'a> Iterator for Decompositions<'a> {
}
if !self.sorted {
for ch in self.iter {
for ch in self.iter.by_ref() {
let buffer = &mut self.buffer;
let sorted = &mut self.sorted;
{
@ -279,7 +280,7 @@ impl<'a> Iterator for Recompositions<'a> {
loop {
match self.state {
Composing => {
for ch in self.iter {
for ch in self.iter.by_ref() {
let ch_class = unicode::char::canonical_combining_class(ch);
if self.composee.is_none() {
if ch_class != 0 {
@ -443,12 +444,9 @@ pub trait StrExt: Index<RangeFull, Output = str> {
/// # Examples
///
/// ```rust
/// let s = "Do you know the muffin man,
/// The muffin man, the muffin man, ...".to_string();
/// let s = "this is old";
///
/// assert_eq!(s.replace("muffin man", "little lamb"),
/// "Do you know the little lamb,
/// The little lamb, the little lamb, ...".to_string());
/// assert_eq!(s.replace("old", "new"), "this is new");
///
/// // not found, so no change.
/// assert_eq!(s.replace("cookie monster", "little lamb"), s);
@ -1231,13 +1229,12 @@ pub trait StrExt: Index<RangeFull, Output = str> {
/// # Example
///
/// ```
/// assert_eq!("4".parse::<u32>(), Some(4));
/// assert_eq!("j".parse::<u32>(), None);
/// assert_eq!("4".parse::<u32>(), Ok(4));
/// assert!("j".parse::<u32>().is_err());
/// ```
#[inline]
#[unstable(feature = "collections",
reason = "this method was just created")]
fn parse<F: FromStr>(&self) -> Option<F> {
#[stable(feature = "rust1", since = "1.0.0")]
fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
core_str::StrExt::parse(&self[])
}
@ -2154,7 +2151,7 @@ mod tests {
let s = "ศไทย中华Việt Nam";
let mut it = s.chars();
it.next();
assert!(it.zip(it.clone()).all(|(x,y)| x == y));
assert!(it.clone().zip(it).all(|(x,y)| x == y));
}
#[test]

View File

@ -940,19 +940,24 @@ pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
DerefString { x: as_vec(x.as_bytes()) }
}
#[unstable(feature = "collections", reason = "associated error type may change")]
impl FromStr for String {
type Err = ();
#[inline]
fn from_str(s: &str) -> Option<String> {
Some(String::from_str(s))
fn from_str(s: &str) -> Result<String, ()> {
Ok(String::from_str(s))
}
}
/// A generic trait for converting a value to a string
#[stable(feature = "rust1", since = "1.0.0")]
pub trait ToString {
/// Converts the value of `self` to an owned string
#[stable(feature = "rust1", since = "1.0.0")]
fn to_string(&self) -> String;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display + ?Sized> ToString for T {
#[inline]
fn to_string(&self) -> String {
@ -989,6 +994,7 @@ impl<'a> Str for CowString<'a> {
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Writer for String {
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
@ -1016,7 +1022,7 @@ mod tests {
#[test]
fn test_from_str() {
let owned: Option<::std::string::String> = "string".parse();
let owned: Option<::std::string::String> = "string".parse().ok();
assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
}
@ -1302,8 +1308,8 @@ mod tests {
#[test]
fn test_simple_types() {
assert_eq!(1i.to_string(), "1");
assert_eq!((-1i).to_string(), "-1");
assert_eq!(1.to_string(), "1");
assert_eq!((-1).to_string(), "-1");
assert_eq!(200u.to_string(), "200");
assert_eq!(2u8.to_string(), "2");
assert_eq!(true.to_string(), "true");
@ -1315,9 +1321,9 @@ mod tests {
fn test_vectors() {
let x: Vec<int> = vec![];
assert_eq!(format!("{:?}", x), "[]");
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]]) ==
assert_eq!(format!("{:?}", vec![1]), "[1]");
assert_eq!(format!("{:?}", vec![1, 2, 3]), "[1, 2, 3]");
assert!(format!("{:?}", vec![vec![], vec![1], vec![1, 1]]) ==
"[[], [1], [1, 1]]");
}

View File

@ -56,7 +56,7 @@ use core::cmp::{Ordering};
use core::default::Default;
use core::fmt;
use core::hash::{self, Hash};
use core::iter::{repeat, FromIterator};
use core::iter::{repeat, FromIterator, IntoIterator};
use core::marker::{ContravariantLifetime, InvariantType};
use core::mem;
use core::nonzero::NonZero;
@ -65,6 +65,7 @@ use core::ops::{Index, IndexMut, Deref, Add};
use core::ops;
use core::ptr;
use core::raw::Slice as RawSlice;
use core::slice;
use core::uint;
/// A growable list type, written `Vec<T>` but pronounced 'vector.'
@ -73,8 +74,8 @@ use core::uint;
///
/// ```
/// let mut vec = Vec::new();
/// vec.push(1i);
/// vec.push(2i);
/// vec.push(1);
/// vec.push(2);
///
/// assert_eq!(vec.len(), 2);
/// assert_eq!(vec[0], 1);
@ -82,7 +83,7 @@ use core::uint;
/// assert_eq!(vec.pop(), Some(2));
/// assert_eq!(vec.len(), 1);
///
/// vec[0] = 7i;
/// vec[0] = 7;
/// assert_eq!(vec[0], 7);
///
/// vec.push_all(&[1, 2, 3]);
@ -90,13 +91,13 @@ use core::uint;
/// for x in vec.iter() {
/// println!("{}", x);
/// }
/// assert_eq!(vec, vec![7i, 1, 2, 3]);
/// assert_eq!(vec, vec![7, 1, 2, 3]);
/// ```
///
/// The `vec!` macro is provided to make initialization more convenient:
///
/// ```
/// let mut vec = vec![1i, 2i, 3i];
/// let mut vec = vec![1, 2, 3];
/// vec.push(4);
/// assert_eq!(vec, vec![1, 2, 3, 4]);
/// ```
@ -106,9 +107,9 @@ use core::uint;
/// ```
/// let mut stack = Vec::new();
///
/// stack.push(1i);
/// stack.push(2i);
/// stack.push(3i);
/// stack.push(1);
/// stack.push(2);
/// stack.push(3);
///
/// loop {
/// let top = match stack.pop() {
@ -180,13 +181,13 @@ impl<T> Vec<T> {
/// # Examples
///
/// ```
/// let mut vec: Vec<int> = Vec::with_capacity(10);
/// let mut vec: Vec<_> = Vec::with_capacity(10);
///
/// // The vector contains no items, even though it has capacity for more
/// assert_eq!(vec.len(), 0);
///
/// // These are all done without reallocating...
/// for i in 0i..10 {
/// for i in 0..10 {
/// vec.push(i);
/// }
///
@ -220,7 +221,7 @@ impl<T> Vec<T> {
/// use std::mem;
///
/// fn main() {
/// let mut v = vec![1i, 2, 3];
/// let mut v = vec![1, 2, 3];
///
/// // Pull out the various important pieces of information about `v`
/// let p = v.as_mut_ptr();
@ -239,7 +240,7 @@ impl<T> Vec<T> {
///
/// // Put everything back together into a Vec
/// let rebuilt = Vec::from_raw_parts(p, len, cap);
/// assert_eq!(rebuilt, vec![4i, 5i, 6i]);
/// assert_eq!(rebuilt, vec![4, 5, 6]);
/// }
/// }
/// ```
@ -395,7 +396,7 @@ impl<T> Vec<T> {
/// # Examples
///
/// ```
/// let mut vec = vec![1i, 2, 3, 4];
/// let mut vec = vec![1, 2, 3, 4];
/// vec.truncate(2);
/// assert_eq!(vec, vec![1, 2]);
/// ```
@ -419,7 +420,7 @@ impl<T> Vec<T> {
/// ```
/// fn foo(slice: &mut [int]) {}
///
/// let mut vec = vec![1i, 2];
/// let mut vec = vec![1, 2];
/// foo(vec.as_mut_slice());
/// ```
#[inline]
@ -522,7 +523,7 @@ impl<T> Vec<T> {
/// # Examples
///
/// ```
/// let mut vec = vec![1i, 2, 3];
/// let mut vec = vec![1, 2, 3];
/// vec.insert(1, 4);
/// assert_eq!(vec, vec![1, 4, 2, 3]);
/// vec.insert(4, 5);
@ -560,7 +561,7 @@ impl<T> Vec<T> {
/// # Examples
///
/// ```
/// let mut v = vec![1i, 2, 3];
/// let mut v = vec![1, 2, 3];
/// assert_eq!(v.remove(1), 2);
/// assert_eq!(v, vec![1, 3]);
/// ```
@ -594,7 +595,7 @@ impl<T> Vec<T> {
/// # Examples
///
/// ```
/// let mut vec = vec![1i, 2, 3, 4];
/// let mut vec = vec![1, 2, 3, 4];
/// vec.retain(|&x| x%2 == 0);
/// assert_eq!(vec, vec![2, 4]);
/// ```
@ -627,7 +628,7 @@ impl<T> Vec<T> {
/// # Examples
///
/// ```rust
/// let mut vec = vec!(1i, 2);
/// let mut vec = vec!(1, 2);
/// vec.push(3);
/// assert_eq!(vec, vec!(1, 2, 3));
/// ```
@ -665,7 +666,7 @@ impl<T> Vec<T> {
/// # Examples
///
/// ```rust
/// let mut vec = vec![1i, 2, 3];
/// let mut vec = vec![1, 2, 3];
/// assert_eq!(vec.pop(), Some(3));
/// assert_eq!(vec, vec![1, 2]);
/// ```
@ -758,7 +759,7 @@ impl<T> Vec<T> {
/// # Examples
///
/// ```
/// let mut v = vec![1i, 2, 3];
/// let mut v = vec![1, 2, 3];
///
/// v.clear();
///
@ -775,7 +776,7 @@ impl<T> Vec<T> {
/// # Examples
///
/// ```
/// let a = vec![1i, 2, 3];
/// let a = vec![1, 2, 3];
/// assert_eq!(a.len(), 3);
/// ```
#[inline]
@ -790,7 +791,7 @@ impl<T> Vec<T> {
/// let mut v = Vec::new();
/// assert!(v.is_empty());
///
/// v.push(1i);
/// v.push(1);
/// assert!(!v.is_empty());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -1045,7 +1046,7 @@ impl<T: Clone> Vec<T> {
/// vec.resize(3, "world");
/// assert_eq!(vec, vec!["hello", "world", "world"]);
///
/// let mut vec = vec![1i, 2, 3, 4];
/// let mut vec = vec![1, 2, 3, 4];
/// vec.resize(2, 0);
/// assert_eq!(vec, vec![1, 2]);
/// ```
@ -1069,8 +1070,8 @@ impl<T: Clone> Vec<T> {
/// # Examples
///
/// ```
/// let mut vec = vec![1i];
/// vec.push_all(&[2i, 3, 4]);
/// let mut vec = vec![1];
/// vec.push_all(&[2, 3, 4]);
/// assert_eq!(vec, vec![1, 2, 3, 4]);
/// ```
#[inline]
@ -1103,11 +1104,11 @@ impl<T: PartialEq> Vec<T> {
/// # Examples
///
/// ```
/// let mut vec = vec![1i, 2, 2, 3, 2];
/// let mut vec = vec![1, 2, 2, 3, 2];
///
/// vec.dedup();
///
/// assert_eq!(vec, vec![1i, 2, 3, 2]);
/// assert_eq!(vec, vec![1, 2, 3, 2]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn dedup(&mut self) {
@ -1404,6 +1405,30 @@ impl<T> FromIterator<T> for Vec<T> {
}
}
impl<T> IntoIterator for Vec<T> {
type Iter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
self.into_iter()
}
}
impl<'a, T> IntoIterator for &'a Vec<T> {
type Iter = slice::Iter<'a, T>;
fn into_iter(self) -> slice::Iter<'a, T> {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut Vec<T> {
type Iter = slice::IterMut<'a, T>;
fn into_iter(mut self) -> slice::IterMut<'a, T> {
self.iter_mut()
}
}
#[unstable(feature = "collections", reason = "waiting on Extend stability")]
impl<T> Extend<T> for Vec<T> {
#[inline]
@ -1507,7 +1532,7 @@ impl<T> AsSlice<T> for Vec<T> {
/// ```
/// fn foo(slice: &[int]) {}
///
/// let vec = vec![1i, 2];
/// let vec = vec![1, 2];
/// foo(vec.as_slice());
/// ```
#[inline]
@ -1566,13 +1591,6 @@ impl<T: fmt::Debug> fmt::Debug for Vec<T> {
}
}
impl<'a> fmt::Writer for Vec<u8> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.push_all(s.as_bytes());
Ok(())
}
}
////////////////////////////////////////////////////////////////////////////////
// Clone-on-write
////////////////////////////////////////////////////////////////////////////////
@ -1623,7 +1641,7 @@ impl<T> IntoIter<T> {
#[unstable(feature = "collections")]
pub fn into_inner(mut self) -> Vec<T> {
unsafe {
for _x in self { }
for _x in self.by_ref() { }
let IntoIter { allocation, cap, ptr: _ptr, end: _end } = self;
mem::forget(self);
Vec { ptr: NonZero::new(allocation), cap: cap, len: 0 }
@ -1701,7 +1719,7 @@ impl<T> Drop for IntoIter<T> {
fn drop(&mut self) {
// destroy the remaining elements
if self.cap != 0 {
for _x in *self {}
for _x in self.by_ref() {}
unsafe {
dealloc(self.allocation, self.cap);
}
@ -1791,7 +1809,7 @@ impl<'a, T> Drop for Drain<'a, T> {
// so we can use #[unsafe_no_drop_flag].
// destroy the remaining elements
for _x in *self {}
for _x in self.by_ref() {}
}
}
@ -1990,7 +2008,7 @@ mod tests {
v.reserve(2);
assert!(v.capacity() >= 2);
for i in 0i..16 {
for i in 0..16 {
v.push(i);
}
@ -2009,13 +2027,13 @@ mod tests {
let mut v = Vec::new();
let mut w = Vec::new();
v.extend(0i..3);
for i in 0i..3 { w.push(i) }
v.extend(0..3);
for i in 0..3 { w.push(i) }
assert_eq!(v, w);
v.extend(3i..10);
for i in 3i..10 { w.push(i) }
v.extend(3..10);
for i in 3..10 { w.push(i) }
assert_eq!(v, w);
}
@ -2076,7 +2094,7 @@ mod tests {
#[test]
fn test_clone() {
let v: Vec<int> = vec!();
let w = vec!(1i, 2, 3);
let w = vec!(1, 2, 3);
assert_eq!(v, v.clone());
@ -2089,8 +2107,8 @@ mod tests {
#[test]
fn test_clone_from() {
let mut v = vec!();
let three = vec!(box 1i, box 2, box 3);
let two = vec!(box 4i, box 5);
let three = vec!(box 1, box 2, box 3);
let two = vec!(box 4, box 5);
// zero, long
v.clone_from(&three);
assert_eq!(v, three);
@ -2149,14 +2167,14 @@ mod tests {
#[test]
fn test_partition() {
assert_eq!(vec![].into_iter().partition(|x: &int| *x < 3), (vec![], vec![]));
assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
assert_eq!(vec![1, 2, 3].into_iter().partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
assert_eq!(vec![1, 2, 3].into_iter().partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
assert_eq!(vec![1, 2, 3].into_iter().partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
}
#[test]
fn test_zip_unzip() {
let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
let z1 = vec![(1, 4), (2, 5), (3, 6)];
let (left, right): (Vec<_>, Vec<_>) = z1.iter().map(|&x| x).unzip();
@ -2169,13 +2187,13 @@ mod tests {
fn test_unsafe_ptrs() {
unsafe {
// Test on-stack copy-from-buf.
let a = [1i, 2, 3];
let a = [1, 2, 3];
let ptr = a.as_ptr();
let b = Vec::from_raw_buf(ptr, 3u);
assert_eq!(b, vec![1, 2, 3]);
// Test on-heap copy-from-buf.
let c = vec![1i, 2, 3, 4, 5];
let c = vec![1, 2, 3, 4, 5];
let ptr = c.as_ptr();
let d = Vec::from_raw_buf(ptr, 5u);
assert_eq!(d, vec![1, 2, 3, 4, 5]);
@ -2219,14 +2237,14 @@ mod tests {
#[test]
fn test_index() {
let vec = vec!(1i, 2, 3);
let vec = vec!(1, 2, 3);
assert!(vec[1] == 2);
}
#[test]
#[should_fail]
fn test_index_out_of_bounds() {
let vec = vec!(1i, 2, 3);
let vec = vec!(1, 2, 3);
let _ = vec[3];
}
@ -2294,7 +2312,7 @@ mod tests {
#[test]
fn test_map_in_place() {
let v = vec![0u, 1, 2];
assert_eq!(v.map_in_place(|i: uint| i as int - 1), [-1i, 0, 1]);
assert_eq!(v.map_in_place(|i: uint| i as int - 1), [-1, 0, 1]);
}
#[test]

View File

@ -19,7 +19,7 @@ use core::cmp::Ordering;
use core::default::Default;
use core::fmt;
use core::hash::{Hash, Writer, Hasher};
use core::iter::{Enumerate, FilterMap, Map, FromIterator};
use core::iter::{Enumerate, FilterMap, Map, FromIterator, IntoIterator};
use core::iter;
use core::mem::replace;
use core::ops::{Index, IndexMut};
@ -536,6 +536,30 @@ impl<V> FromIterator<(uint, V)> for VecMap<V> {
}
}
impl<T> IntoIterator for VecMap<T> {
type Iter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
self.into_iter()
}
}
impl<'a, T> IntoIterator for &'a VecMap<T> {
type Iter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut VecMap<T> {
type Iter = IterMut<'a, T>;
fn into_iter(mut self) -> IterMut<'a, T> {
self.iter_mut()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<V> Extend<(uint, V)> for VecMap<V> {
fn extend<Iter: Iterator<Item=(uint, V)>>(&mut self, mut iter: Iter) {
@ -768,7 +792,7 @@ mod test_map {
#[test]
fn test_get_mut() {
let mut m = VecMap::new();
assert!(m.insert(1, 12i).is_none());
assert!(m.insert(1, 12).is_none());
assert!(m.insert(2, 8).is_none());
assert!(m.insert(5, 14).is_none());
let new = 100;
@ -783,7 +807,7 @@ mod test_map {
let mut map = VecMap::new();
assert_eq!(map.len(), 0);
assert!(map.is_empty());
assert!(map.insert(5, 20i).is_none());
assert!(map.insert(5, 20).is_none());
assert_eq!(map.len(), 1);
assert!(!map.is_empty());
assert!(map.insert(11, 12).is_none());
@ -797,7 +821,7 @@ mod test_map {
#[test]
fn test_clear() {
let mut map = VecMap::new();
assert!(map.insert(5, 20i).is_none());
assert!(map.insert(5, 20).is_none());
assert!(map.insert(11, 12).is_none());
assert!(map.insert(14, 22).is_none());
map.clear();
@ -810,15 +834,15 @@ mod test_map {
#[test]
fn test_insert() {
let mut m = VecMap::new();
assert_eq!(m.insert(1, 2i), None);
assert_eq!(m.insert(1, 3i), Some(2));
assert_eq!(m.insert(1, 4i), Some(3));
assert_eq!(m.insert(1, 2), None);
assert_eq!(m.insert(1, 3), Some(2));
assert_eq!(m.insert(1, 4), Some(3));
}
#[test]
fn test_remove() {
let mut m = VecMap::new();
m.insert(1, 2i);
m.insert(1, 2);
assert_eq!(m.remove(&1), Some(2));
assert_eq!(m.remove(&1), None);
}
@ -853,7 +877,7 @@ mod test_map {
fn test_iterator() {
let mut m = VecMap::new();
assert!(m.insert(0, 1i).is_none());
assert!(m.insert(0, 1).is_none());
assert!(m.insert(1, 2).is_none());
assert!(m.insert(3, 5).is_none());
assert!(m.insert(6, 10).is_none());
@ -878,7 +902,7 @@ mod test_map {
fn test_iterator_size_hints() {
let mut m = VecMap::new();
assert!(m.insert(0, 1i).is_none());
assert!(m.insert(0, 1).is_none());
assert!(m.insert(1, 2).is_none());
assert!(m.insert(3, 5).is_none());
assert!(m.insert(6, 10).is_none());
@ -894,7 +918,7 @@ mod test_map {
fn test_mut_iterator() {
let mut m = VecMap::new();
assert!(m.insert(0, 1i).is_none());
assert!(m.insert(0, 1).is_none());
assert!(m.insert(1, 2).is_none());
assert!(m.insert(3, 5).is_none());
assert!(m.insert(6, 10).is_none());
@ -917,7 +941,7 @@ mod test_map {
fn test_rev_iterator() {
let mut m = VecMap::new();
assert!(m.insert(0, 1i).is_none());
assert!(m.insert(0, 1).is_none());
assert!(m.insert(1, 2).is_none());
assert!(m.insert(3, 5).is_none());
assert!(m.insert(6, 10).is_none());
@ -936,7 +960,7 @@ mod test_map {
fn test_mut_rev_iterator() {
let mut m = VecMap::new();
assert!(m.insert(0, 1i).is_none());
assert!(m.insert(0, 1).is_none());
assert!(m.insert(1, 2).is_none());
assert!(m.insert(3, 5).is_none());
assert!(m.insert(6, 10).is_none());
@ -958,13 +982,13 @@ mod test_map {
#[test]
fn test_move_iter() {
let mut m = VecMap::new();
m.insert(1, box 2i);
m.insert(1, box 2);
let mut called = false;
for (k, v) in m.into_iter() {
assert!(!called);
called = true;
assert_eq!(k, 1);
assert_eq!(v, box 2i);
assert_eq!(v, box 2);
}
assert!(called);
}
@ -987,8 +1011,8 @@ mod test_map {
let mut map = VecMap::new();
let empty = VecMap::<int>::new();
map.insert(1, 2i);
map.insert(3, 4i);
map.insert(1, 2);
map.insert(3, 4);
let map_str = format!("{:?}", map);
assert!(map_str == "VecMap {1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
@ -1012,9 +1036,9 @@ mod test_map {
let mut b = VecMap::new();
assert!(a == b);
assert!(a.insert(0, 5i).is_none());
assert!(a.insert(0, 5).is_none());
assert!(a != b);
assert!(b.insert(0, 4i).is_none());
assert!(b.insert(0, 4).is_none());
assert!(a != b);
assert!(a.insert(5, 19).is_none());
assert!(a != b);
@ -1034,7 +1058,7 @@ mod test_map {
let mut b = VecMap::new();
assert!(!(a < b) && !(b < a));
assert!(b.insert(2u, 5i).is_none());
assert!(b.insert(2u, 5).is_none());
assert!(a < b);
assert!(a.insert(2, 7).is_none());
assert!(!(a < b) && b < a);
@ -1052,7 +1076,7 @@ mod test_map {
let mut b = VecMap::new();
assert!(a <= b && a >= b);
assert!(a.insert(1u, 1i).is_none());
assert!(a.insert(1u, 1).is_none());
assert!(a > b && a >= b);
assert!(b < a && b <= a);
assert!(b.insert(2, 2).is_none());

View File

@ -18,12 +18,14 @@ use clone::Clone;
use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
use fmt;
use hash::{Hash, Hasher, self};
use iter::IntoIterator;
use marker::Copy;
#[cfg(stage0)]
use ops::{Deref, FullRange};
#[cfg(not(stage0))]
use ops::Deref;
use option::Option;
use slice::{Iter, IterMut, SliceExt};
// macro for implementing n-ary tuple functions and operations
macro_rules! array_impls {
@ -49,6 +51,22 @@ macro_rules! array_impls {
}
}
impl<'a, T> IntoIterator for &'a [T; $N] {
type Iter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut [T; $N] {
type Iter = IterMut<'a, T>;
fn into_iter(self) -> IterMut<'a, T> {
self.iter_mut()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<A, B> PartialEq<[B; $N]> for [A; $N] where A: PartialEq<B> {
#[inline]

View File

@ -10,7 +10,6 @@
//! Utilities for formatting and printing strings
#![allow(unused_variables)]
#![stable(feature = "rust1", since = "1.0.0")]
use any;
@ -27,6 +26,7 @@ use result;
use slice::SliceExt;
use slice;
use str::{self, StrExt};
use self::rt::v1::Alignment;
pub use self::num::radix;
pub use self::num::Radix;
@ -34,10 +34,15 @@ pub use self::num::RadixFmt;
mod num;
mod float;
pub mod rt;
#[unstable(feature = "core",
reason = "core and I/O reconciliation may alter this definition")]
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(hidden)]
pub mod rt {
#[cfg(stage0)] pub use self::v1::*;
pub mod v1;
}
#[stable(feature = "rust1", since = "1.0.0")]
/// The type returned by formatter methods.
pub type Result = result::Result<(), Error>;
@ -46,8 +51,7 @@ pub type Result = result::Result<(), Error>;
/// This type does not support transmission of an error other than that an error
/// occurred. Any extra information must be arranged to be transmitted through
/// some other means.
#[unstable(feature = "core",
reason = "core and I/O reconciliation may alter this definition")]
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Copy, Debug)]
pub struct Error;
@ -60,8 +64,7 @@ pub struct Error;
/// This trait should generally not be implemented by consumers of the standard
/// library. The `write!` macro accepts an instance of `io::Writer`, and the
/// `io::Writer` trait is favored over implementing this trait.
#[unstable(feature = "core",
reason = "waiting for core and I/O reconciliation")]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Writer {
/// Writes a slice of bytes into this writer, returning whether the write
/// succeeded.
@ -73,12 +76,14 @@ pub trait Writer {
/// # Errors
///
/// This function will return an instance of `FormatError` on error.
#[stable(feature = "rust1", since = "1.0.0")]
fn write_str(&mut self, s: &str) -> Result;
/// Glue for usage of the `write!` macro with implementers of this trait.
///
/// This method should generally not be invoked manually, but rather through
/// the `write!` macro itself.
#[stable(feature = "rust1", since = "1.0.0")]
fn write_fmt(&mut self, args: Arguments) -> Result {
// This Adapter is needed to allow `self` (of type `&mut
// Self`) to be cast to a FormatWriter (below) without
@ -104,18 +109,17 @@ pub trait Writer {
/// A struct to represent both where to emit formatting strings to and how they
/// should be formatted. A mutable version of this is passed to all formatting
/// traits.
#[unstable(feature = "core",
reason = "name may change and implemented traits are also unstable")]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Formatter<'a> {
flags: uint,
fill: char,
align: rt::Alignment,
align: rt::v1::Alignment,
width: Option<uint>,
precision: Option<uint>,
buf: &'a mut (Writer+'a),
curarg: slice::Iter<'a, Argument<'a>>,
args: &'a [Argument<'a>],
curarg: slice::Iter<'a, ArgumentV1<'a>>,
args: &'a [ArgumentV1<'a>],
}
// NB. Argument is essentially an optimized partially applied formatting function,
@ -127,35 +131,40 @@ enum Void {}
/// family of functions. It contains a function to format the given value. At
/// compile time it is ensured that the function and the value have the correct
/// types, and then this struct is used to canonicalize arguments to one type.
#[unstable(feature = "core",
reason = "implementation detail of the `format_args!` macro")]
#[derive(Copy)]
pub struct Argument<'a> {
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(hidden)]
pub struct ArgumentV1<'a> {
value: &'a Void,
formatter: fn(&Void, &mut Formatter) -> Result,
}
impl<'a> Argument<'a> {
impl<'a> ArgumentV1<'a> {
#[inline(never)]
fn show_uint(x: &uint, f: &mut Formatter) -> Result {
Display::fmt(x, f)
}
fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter) -> Result) -> Argument<'b> {
#[doc(hidden)]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new<'b, T>(x: &'b T,
f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
unsafe {
Argument {
ArgumentV1 {
formatter: mem::transmute(f),
value: mem::transmute(x)
}
}
}
fn from_uint(x: &uint) -> Argument {
Argument::new(x, Argument::show_uint)
#[doc(hidden)]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_uint(x: &uint) -> ArgumentV1 {
ArgumentV1::new(x, ArgumentV1::show_uint)
}
fn as_uint(&self) -> Option<uint> {
if self.formatter as uint == Argument::show_uint as uint {
if self.formatter as uint == ArgumentV1::show_uint as uint {
Some(unsafe { *(self.value as *const _ as *const uint) })
} else {
None
@ -163,14 +172,32 @@ impl<'a> Argument<'a> {
}
}
// flags available in the v1 format of format_args
#[derive(Copy)]
#[allow(dead_code)] // SignMinus isn't currently used
enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
impl<'a> Arguments<'a> {
/// When using the format_args!() macro, this function is used to generate the
/// Arguments structure.
#[doc(hidden)] #[inline]
#[unstable(feature = "core",
reason = "implementation detail of the `format_args!` macro")]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new_v1(pieces: &'a [&'a str],
args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
Arguments {
pieces: pieces,
fmt: None,
args: args
}
}
/// When using the format_args!() macro, this function is used to generate the
/// Arguments structure.
#[doc(hidden)] #[inline]
#[cfg(stage0)]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new(pieces: &'a [&'a str],
args: &'a [Argument<'a>]) -> Arguments<'a> {
args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
Arguments {
pieces: pieces,
fmt: None,
@ -185,11 +212,28 @@ impl<'a> Arguments<'a> {
/// created with `argumentuint`. However, failing to do so doesn't cause
/// unsafety, but will ignore invalid .
#[doc(hidden)] #[inline]
#[unstable(feature = "core",
reason = "implementation detail of the `format_args!` macro")]
#[cfg(stage0)]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn with_placeholders(pieces: &'a [&'a str],
fmt: &'a [rt::Argument],
args: &'a [Argument<'a>]) -> Arguments<'a> {
fmt: &'a [rt::v1::Argument],
args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
Arguments {
pieces: pieces,
fmt: Some(fmt),
args: args
}
}
/// This function is used to specify nonstandard formatting parameters.
/// The `pieces` array must be at least as long as `fmt` to construct
/// a valid Arguments structure. Also, any `Count` within `fmt` that is
/// `CountIsParam` or `CountIsNextParam` has to point to an argument
/// created with `argumentuint`. However, failing to do so doesn't cause
/// unsafety, but will ignore invalid .
#[doc(hidden)] #[inline]
#[cfg(not(stage0))]
pub fn new_v1_formatted(pieces: &'a [&'a str],
args: &'a [ArgumentV1<'a>],
fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
Arguments {
pieces: pieces,
fmt: Some(fmt),
@ -214,11 +258,11 @@ pub struct Arguments<'a> {
pieces: &'a [&'a str],
// Placeholder specs, or `None` if all specs are default (as in "{}{}").
fmt: Option<&'a [rt::Argument]>,
fmt: Option<&'a [rt::v1::Argument]>,
// Dynamic arguments for interpolation, to be interleaved with string
// pieces. (Every argument is preceded by a string piece.)
args: &'a [Argument<'a>],
args: &'a [ArgumentV1<'a>],
}
#[stable(feature = "rust1", since = "1.0.0")]
@ -237,20 +281,20 @@ impl<'a> Display for Arguments<'a> {
/// Format trait for the `:?` format. Useful for debugging, all types
/// should implement this.
#[unstable(feature = "core",
reason = "I/O and core have yet to be reconciled")]
#[deprecated(since = "1.0.0", reason = "renamed to Debug")]
#[unstable(feature = "old_fmt")]
pub trait Show {
/// Formats the value using the given formatter.
#[stable(feature = "rust1", since = "1.0.0")]
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `:?` format. Useful for debugging, all types
/// should implement this.
#[unstable(feature = "core",
reason = "I/O and core have yet to be reconciled")]
#[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is defined in your \
crate, add `#[derive(Debug)]` or manually implement it"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
defined in your crate, add `#[derive(Debug)]` or \
manually implement it"]
#[lang = "debug_trait"]
pub trait Debug {
/// Formats the value using the given formatter.
@ -264,19 +308,20 @@ impl<T: Show + ?Sized> Debug for T {
/// When a value can be semantically expressed as a String, this trait may be
/// used. It corresponds to the default format, `{}`.
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0", reason = "renamed to Display")]
#[unstable(feature = "old_fmt")]
pub trait String {
/// Formats the value using the given formatter.
#[stable(feature = "rust1", since = "1.0.0")]
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(feature = "core",
reason = "I/O and core have yet to be reconciled")]
#[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default formatter; try using \
`:?` instead if you are using a format string"]
#[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
formatter; try using `:?` instead if you are using \
a format string"]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Display {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
@ -288,58 +333,58 @@ impl<T: String + ?Sized> Display for T {
}
/// Format trait for the `o` character
#[unstable(feature = "core",
reason = "I/O and core have yet to be reconciled")]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Octal {
/// Formats the value using the given formatter.
#[stable(feature = "rust1", since = "1.0.0")]
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `b` character
#[unstable(feature = "core",
reason = "I/O and core have yet to be reconciled")]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Binary {
/// Formats the value using the given formatter.
#[stable(feature = "rust1", since = "1.0.0")]
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `x` character
#[unstable(feature = "core",
reason = "I/O and core have yet to be reconciled")]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait LowerHex {
/// Formats the value using the given formatter.
#[stable(feature = "rust1", since = "1.0.0")]
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `X` character
#[unstable(feature = "core",
reason = "I/O and core have yet to be reconciled")]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait UpperHex {
/// Formats the value using the given formatter.
#[stable(feature = "rust1", since = "1.0.0")]
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `p` character
#[unstable(feature = "core",
reason = "I/O and core have yet to be reconciled")]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Pointer {
/// Formats the value using the given formatter.
#[stable(feature = "rust1", since = "1.0.0")]
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `e` character
#[unstable(feature = "core",
reason = "I/O and core have yet to be reconciled")]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait LowerExp {
/// Formats the value using the given formatter.
#[stable(feature = "rust1", since = "1.0.0")]
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `E` character
#[unstable(feature = "core",
reason = "I/O and core have yet to be reconciled")]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait UpperExp {
/// Formats the value using the given formatter.
#[stable(feature = "rust1", since = "1.0.0")]
fn fmt(&self, &mut Formatter) -> Result;
}
@ -351,16 +396,14 @@ pub trait UpperExp {
///
/// * output - the buffer to write output to
/// * args - the precompiled arguments generated by `format_args!`
#[unstable(feature = "core",
reason = "libcore and I/O have yet to be reconciled, and this is an \
implementation detail which should not otherwise be exported")]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn write(output: &mut Writer, args: Arguments) -> Result {
let mut formatter = Formatter {
flags: 0,
width: None,
precision: None,
buf: output,
align: rt::AlignUnknown,
align: Alignment::Unknown,
fill: ' ',
args: args.args,
curarg: args.args.iter(),
@ -402,7 +445,7 @@ impl<'a> Formatter<'a> {
// First up is the collection of functions used to execute a format string
// at runtime. This consumes all of the compile-time statics generated by
// the format! syntax extension.
fn run(&mut self, arg: &rt::Argument) -> Result {
fn run(&mut self, arg: &rt::v1::Argument) -> Result {
// Fill in the format parameters into the formatter
self.fill = arg.format.fill;
self.align = arg.format.align;
@ -412,22 +455,22 @@ impl<'a> Formatter<'a> {
// Extract the correct argument
let value = match arg.position {
rt::ArgumentNext => { *self.curarg.next().unwrap() }
rt::ArgumentIs(i) => self.args[i],
rt::v1::Position::Next => { *self.curarg.next().unwrap() }
rt::v1::Position::At(i) => self.args[i],
};
// Then actually do some printing
(value.formatter)(value.value, self)
}
fn getcount(&mut self, cnt: &rt::Count) -> Option<uint> {
fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<uint> {
match *cnt {
rt::CountIs(n) => Some(n),
rt::CountImplied => None,
rt::CountIsParam(i) => {
rt::v1::Count::Is(n) => Some(n),
rt::v1::Count::Implied => None,
rt::v1::Count::Param(i) => {
self.args[i].as_uint()
}
rt::CountIsNextParam => {
rt::v1::Count::NextParam => {
self.curarg.next().and_then(|arg| arg.as_uint())
}
}
@ -437,8 +480,8 @@ impl<'a> Formatter<'a> {
// all formatting traits can use.
/// Performs the correct padding for an integer which has already been
/// emitted into a byte-array. The byte-array should *not* contain the sign
/// for the integer, that will be added by this method.
/// emitted into a str. The str should *not* contain the sign for the
/// integer, that will be added by this method.
///
/// # Arguments
///
@ -449,27 +492,25 @@ impl<'a> Formatter<'a> {
///
/// This function will correctly account for the flags provided as well as
/// the minimum width. It will not take precision into account.
#[unstable(feature = "core",
reason = "definition may change slightly over time")]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pad_integral(&mut self,
is_positive: bool,
prefix: &str,
buf: &str)
-> Result {
use char::CharExt;
use fmt::rt::{FlagAlternate, FlagSignPlus, FlagSignAwareZeroPad};
let mut width = buf.len();
let mut sign = None;
if !is_positive {
sign = Some('-'); width += 1;
} else if self.flags & (1 << (FlagSignPlus as uint)) != 0 {
} else if self.flags & (1 << (FlagV1::SignPlus as uint)) != 0 {
sign = Some('+'); width += 1;
}
let mut prefixed = false;
if self.flags & (1 << (FlagAlternate as uint)) != 0 {
if self.flags & (1 << (FlagV1::Alternate as uint)) != 0 {
prefixed = true; width += prefix.char_len();
}
@ -499,16 +540,16 @@ impl<'a> Formatter<'a> {
}
// The sign and prefix goes before the padding if the fill character
// is zero
Some(min) if self.flags & (1 << (FlagSignAwareZeroPad as uint)) != 0 => {
Some(min) if self.flags & (1 << (FlagV1::SignAwareZeroPad as uint)) != 0 => {
self.fill = '0';
try!(write_prefix(self));
self.with_padding(min - width, rt::AlignRight, |f| {
self.with_padding(min - width, Alignment::Right, |f| {
f.buf.write_str(buf)
})
}
// Otherwise, the sign and prefix goes after the padding
Some(min) => {
self.with_padding(min - width, rt::AlignRight, |f| {
self.with_padding(min - width, Alignment::Right, |f| {
try!(write_prefix(f)); f.buf.write_str(buf)
})
}
@ -526,8 +567,7 @@ impl<'a> Formatter<'a> {
/// is longer than this length
///
/// Notably this function ignored the `flag` parameters
#[unstable(feature = "core",
reason = "definition may change slightly over time")]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pad(&mut self, s: &str) -> Result {
// Make sure there's a fast path up front
if self.width.is_none() && self.precision.is_none() {
@ -561,7 +601,7 @@ impl<'a> Formatter<'a> {
// If we're under both the maximum and the minimum width, then fill
// up the minimum width with the specified string + some alignment.
Some(width) => {
self.with_padding(width - s.char_len(), rt::AlignLeft, |me| {
self.with_padding(width - s.char_len(), Alignment::Left, |me| {
me.buf.write_str(s)
})
}
@ -570,19 +610,20 @@ impl<'a> Formatter<'a> {
/// Runs a callback, emitting the correct padding either before or
/// afterwards depending on whether right or left alignment is requested.
fn with_padding<F>(&mut self, padding: uint, default: rt::Alignment, f: F) -> Result where
F: FnOnce(&mut Formatter) -> Result,
fn with_padding<F>(&mut self, padding: uint, default: Alignment,
f: F) -> Result
where F: FnOnce(&mut Formatter) -> Result,
{
use char::CharExt;
let align = match self.align {
rt::AlignUnknown => default,
Alignment::Unknown => default,
_ => self.align
};
let (pre_pad, post_pad) = match align {
rt::AlignLeft => (0, padding),
rt::AlignRight | rt::AlignUnknown => (padding, 0),
rt::AlignCenter => (padding / 2, (padding + 1) / 2),
Alignment::Left => (0, padding),
Alignment::Right | Alignment::Unknown => (padding, 0),
Alignment::Center => (padding / 2, (padding + 1) / 2),
};
let mut fill = [0u8; 4];
@ -604,23 +645,20 @@ impl<'a> Formatter<'a> {
/// Writes some data to the underlying buffer contained within this
/// formatter.
#[unstable(feature = "core",
reason = "reconciling core and I/O may alter this definition")]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn write_str(&mut self, data: &str) -> Result {
self.buf.write_str(data)
}
/// Writes some formatted information into this instance
#[unstable(feature = "core",
reason = "reconciling core and I/O may alter this definition")]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
write(self.buf, fmt)
}
/// Flags for formatting (packed version of rt::Flag)
#[unstable(feature = "core",
reason = "return type may change and method was just created")]
pub fn flags(&self) -> uint { self.flags }
#[stable(feature = "rust1", since = "1.0.0")]
pub fn flags(&self) -> usize { self.flags }
/// Character used as 'fill' whenever there is alignment
#[unstable(feature = "core", reason = "method was just created")]
@ -628,7 +666,7 @@ impl<'a> Formatter<'a> {
/// Flag indicating what form of alignment was requested
#[unstable(feature = "core", reason = "method was just created")]
pub fn align(&self) -> rt::Alignment { self.align }
pub fn align(&self) -> Alignment { self.align }
/// Optionally specified integer width that the output should be
#[unstable(feature = "core", reason = "method was just created")]
@ -649,20 +687,20 @@ impl Display for Error {
/// This is a function which calls are emitted to by the compiler itself to
/// create the Argument structures that are passed into the `format` function.
#[doc(hidden)] #[inline]
#[unstable(feature = "core",
reason = "implementation detail of the `format_args!` macro")]
#[cfg(stage0)]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn argument<'a, T>(f: fn(&T, &mut Formatter) -> Result,
t: &'a T) -> Argument<'a> {
Argument::new(t, f)
t: &'a T) -> ArgumentV1<'a> {
ArgumentV1::new(t, f)
}
/// When the compiler determines that the type of an argument *must* be a uint
/// (such as for width and precision), then it invokes this method.
#[doc(hidden)] #[inline]
#[unstable(feature = "core",
reason = "implementation detail of the `format_args!` macro")]
pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> {
Argument::from_uint(s)
#[cfg(stage0)]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn argumentuint<'a>(s: &'a uint) -> ArgumentV1<'a> {
ArgumentV1::from_uint(s)
}
// Implementations of the core formatting traits
@ -741,9 +779,9 @@ impl Display for char {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Pointer for *const T {
fn fmt(&self, f: &mut Formatter) -> Result {
f.flags |= 1 << (rt::FlagAlternate as uint);
f.flags |= 1 << (FlagV1::Alternate as uint);
let ret = LowerHex::fmt(&(*self as uint), f);
f.flags &= !(1 << (rt::FlagAlternate as uint));
f.flags &= !(1 << (FlagV1::Alternate as uint));
ret
}
}
@ -899,7 +937,7 @@ impl<'a> Debug for &'a (any::Any+'a) {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Debug> Debug for [T] {
fn fmt(&self, f: &mut Formatter) -> Result {
if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
if f.flags & (1 << (FlagV1::Alternate as uint)) == 0 {
try!(write!(f, "["));
}
let mut is_first = true;
@ -911,7 +949,7 @@ impl<T: Debug> Debug for [T] {
}
try!(write!(f, "{:?}", *x))
}
if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
if f.flags & (1 << (FlagV1::Alternate as uint)) == 0 {
try!(write!(f, "]"));
}
Ok(())

View File

@ -1,86 +0,0 @@
// Copyright 2013 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.
//! This is an internal module used by the ifmt! runtime. These structures are
//! emitted to static arrays to precompile format strings ahead of time.
//!
//! These definitions are similar to their `ct` equivalents, but differ in that
//! these can be statically allocated and are slightly optimized for the runtime
#![unstable(feature = "core",
reason = "implementation detail of the `format_args!` macro")]
pub use self::Alignment::*;
pub use self::Count::*;
pub use self::Position::*;
pub use self::Flag::*;
#[doc(hidden)]
#[derive(Copy)]
pub struct Argument {
pub position: Position,
pub format: FormatSpec,
}
#[doc(hidden)]
#[derive(Copy)]
pub struct FormatSpec {
pub fill: char,
pub align: Alignment,
pub flags: uint,
pub precision: Count,
pub width: Count,
}
/// Possible alignments that can be requested as part of a formatting directive.
#[derive(Copy, PartialEq)]
pub enum Alignment {
/// Indication that contents should be left-aligned.
AlignLeft,
/// Indication that contents should be right-aligned.
AlignRight,
/// Indication that contents should be center-aligned.
AlignCenter,
/// No alignment was requested.
AlignUnknown,
}
#[doc(hidden)]
#[derive(Copy)]
pub enum Count {
CountIs(uint), CountIsParam(uint), CountIsNextParam, CountImplied,
}
#[doc(hidden)]
#[derive(Copy)]
pub enum Position {
ArgumentNext, ArgumentIs(uint)
}
/// Flags which can be passed to formatting via a directive.
///
/// These flags are discovered through the `flags` field of the `Formatter`
/// structure. The flag in that structure is a union of these flags into a
/// `uint` where each flag's discriminant is the corresponding bit.
#[derive(Copy)]
pub enum Flag {
/// A flag which enables number formatting to always print the sign of a
/// number.
FlagSignPlus,
/// Currently not a used flag
FlagSignMinus,
/// Indicates that the "alternate formatting" for a type should be used.
///
/// The meaning of this flag is type-specific.
FlagAlternate,
/// Indicates that padding should be done with a `0` character as well as
/// being aware of the sign to be printed.
FlagSignAwareZeroPad,
}

94
src/libcore/fmt/rt/v1.rs Normal file
View File

@ -0,0 +1,94 @@
// Copyright 2013 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.
//! This is an internal module used by the ifmt! runtime. These structures are
//! emitted to static arrays to precompile format strings ahead of time.
//!
//! These definitions are similar to their `ct` equivalents, but differ in that
//! these can be statically allocated and are slightly optimized for the runtime
#![stable(feature = "rust1", since = "1.0.0")]
#[cfg(stage0)] pub use self::Position::*;
#[cfg(stage0)] pub use self::Alignment::Left as AlignLeft;
#[cfg(stage0)] pub use self::Alignment::Right as AlignRight;
#[cfg(stage0)] pub use self::Alignment::Center as AlignCenter;
#[cfg(stage0)] pub use self::Alignment::Unknown as AlignUnknown;
#[cfg(stage0)] pub use self::Count::Is as CountIs;
#[cfg(stage0)] pub use self::Count::Implied as CountImplied;
#[cfg(stage0)] pub use self::Count::Param as CountIsParam;
#[cfg(stage0)] pub use self::Count::NextParam as CountIsNextParam;
#[cfg(stage0)] pub use self::Position::Next as ArgumentNext;
#[cfg(stage0)] pub use self::Position::At as ArgumentIs;
#[derive(Copy)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Argument {
#[stable(feature = "rust1", since = "1.0.0")]
pub position: Position,
#[stable(feature = "rust1", since = "1.0.0")]
pub format: FormatSpec,
}
#[derive(Copy)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct FormatSpec {
#[stable(feature = "rust1", since = "1.0.0")]
pub fill: char,
#[stable(feature = "rust1", since = "1.0.0")]
pub align: Alignment,
#[stable(feature = "rust1", since = "1.0.0")]
pub flags: uint,
#[stable(feature = "rust1", since = "1.0.0")]
pub precision: Count,
#[stable(feature = "rust1", since = "1.0.0")]
pub width: Count,
}
/// Possible alignments that can be requested as part of a formatting directive.
#[derive(Copy, PartialEq)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Alignment {
/// Indication that contents should be left-aligned.
#[stable(feature = "rust1", since = "1.0.0")]
Left,
/// Indication that contents should be right-aligned.
#[stable(feature = "rust1", since = "1.0.0")]
Right,
/// Indication that contents should be center-aligned.
#[stable(feature = "rust1", since = "1.0.0")]
Center,
/// No alignment was requested.
#[stable(feature = "rust1", since = "1.0.0")]
Unknown,
}
#[derive(Copy)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Count {
#[stable(feature = "rust1", since = "1.0.0")]
Is(usize),
#[stable(feature = "rust1", since = "1.0.0")]
Param(usize),
#[stable(feature = "rust1", since = "1.0.0")]
NextParam,
#[stable(feature = "rust1", since = "1.0.0")]
Implied,
}
#[derive(Copy)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Position {
#[stable(feature = "rust1", since = "1.0.0")]
Next,
#[stable(feature = "rust1", since = "1.0.0")]
At(usize)
}

View File

@ -122,6 +122,22 @@ pub trait FromIterator<A> {
fn from_iter<T: Iterator<Item=A>>(iterator: T) -> Self;
}
/// Conversion into an `Iterator`
pub trait IntoIterator {
type Iter: Iterator;
/// Consumes `Self` and returns an iterator over it
fn into_iter(self) -> Self::Iter;
}
impl<I> IntoIterator for I where I: Iterator {
type Iter = I;
fn into_iter(self) -> I {
self
}
}
/// A type growable from an `Iterator` implementation
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Extend<A> {
@ -178,7 +194,7 @@ pub trait IteratorExt: Iterator + Sized {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
for x in *self {
for x in self.by_ref() {
if n == 0 { return Some(x) }
n -= 1;
}
@ -475,7 +491,7 @@ pub trait IteratorExt: Iterator + Sized {
/// fn process<U: Iterator<Item=isize>>(it: U) -> isize {
/// let mut it = it.fuse();
/// let mut sum = 0;
/// for x in it {
/// for x in it.by_ref() {
/// if x > 5 {
/// break;
/// }
@ -643,7 +659,7 @@ pub trait IteratorExt: Iterator + Sized {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn any<F>(&mut self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool {
for x in *self { if f(x) { return true; } }
for x in self.by_ref() { if f(x) { return true; } }
false
}
@ -663,7 +679,7 @@ pub trait IteratorExt: Iterator + Sized {
fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
P: FnMut(&Self::Item) -> bool,
{
for x in *self {
for x in self.by_ref() {
if predicate(&x) { return Some(x) }
}
None
@ -686,7 +702,7 @@ pub trait IteratorExt: Iterator + Sized {
P: FnMut(Self::Item) -> bool,
{
let mut i = 0;
for x in *self {
for x in self.by_ref() {
if predicate(x) {
return Some(i);
}
@ -1312,7 +1328,7 @@ impl<T, D, I> ExactSizeIterator for Cloned<I> where
{}
/// An iterator that repeats endlessly
#[derive(Clone, Copy)]
#[derive(Clone)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Cycle<I> {
@ -1647,7 +1663,7 @@ impl<A, I, P> Iterator for Filter<A, I, P> where I: Iterator<Item=A>, P: FnMut(&
#[inline]
fn next(&mut self) -> Option<A> {
for x in self.iter {
for x in self.iter.by_ref() {
if (self.predicate)(&x) {
return Some(x);
} else {
@ -1711,7 +1727,7 @@ impl<A, B, I, F> Iterator for FilterMap<A, B, I, F> where
#[inline]
fn next(&mut self) -> Option<B> {
for x in self.iter {
for x in self.iter.by_ref() {
match (self.f)(x) {
Some(y) => return Some(y),
None => ()
@ -1810,7 +1826,6 @@ impl<I> RandomAccessIterator for Enumerate<I> where I: RandomAccessIterator {
/// An iterator with a `peek()` that returns an optional reference to the next element.
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Copy)]
pub struct Peekable<T, I> where I: Iterator<Item=T> {
iter: I,
peeked: Option<T>,
@ -1897,7 +1912,7 @@ impl<A, I, P> Iterator for SkipWhile<A, I, P> where I: Iterator<Item=A>, P: FnMu
#[inline]
fn next(&mut self) -> Option<A> {
for x in self.iter {
for x in self.iter.by_ref() {
if self.flag || !(self.predicate)(&x) {
self.flag = true;
return Some(x);
@ -2190,7 +2205,7 @@ impl<A, B, I, U, F> Iterator for FlatMap<A, B, I, U, F> where
fn next(&mut self) -> Option<B> {
loop {
for inner in self.frontiter.iter_mut() {
for x in *inner {
for x in inner.by_ref() {
return Some(x)
}
}
@ -2484,7 +2499,7 @@ impl<A, St, F> Iterator for Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A
/// An infinite iterator starting at `start` and advancing by `step` with each
/// iteration
#[derive(Clone, Copy)]
#[derive(Clone)]
#[unstable(feature = "core",
reason = "may be renamed or replaced by range notation adapaters")]
pub struct Counter<A> {
@ -2520,7 +2535,7 @@ impl<A: Add<Output=A> + Clone> Iterator for Counter<A> {
}
/// An iterator over the range [start, stop)
#[derive(Clone, Copy)]
#[derive(Clone)]
#[unstable(feature = "core",
reason = "will be replaced by range notation")]
pub struct Range<A> {

View File

@ -49,7 +49,6 @@
#![crate_name = "core"]
#![unstable(feature = "core")]
#![feature(staged_api)]
#![staged_api]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
@ -58,13 +57,16 @@
html_playground_url = "http://play.rust-lang.org/")]
#![no_std]
#![allow(unknown_features, raw_pointer_derive)]
#![allow(unknown_features)] #![feature(intrinsics, lang_items)]
#![feature(simd, unsafe_destructor, slicing_syntax)]
#![feature(unboxed_closures)]
#![allow(unknown_features)] #![feature(int_uint)]
#![feature(on_unimplemented)]
#![allow(raw_pointer_derive)]
#![deny(missing_docs)]
#![cfg_attr(not(stage0), allow(unused_mut))] // NOTE: remove after stage0 snap
#![feature(int_uint)]
#![feature(intrinsics, lang_items)]
#![feature(on_unimplemented)]
#![feature(simd, unsafe_destructor, slicing_syntax)]
#![feature(staged_api)]
#![feature(unboxed_closures)]
#[macro_use]
mod macros;
@ -158,4 +160,6 @@ mod std {
pub use marker;
pub use ops;
pub use option;
// for-loops
pub use iter;
}

View File

@ -11,12 +11,14 @@
//! Exposes the NonZero lang item which provides optimization hints.
use ops::Deref;
use ptr::Unique;
/// Unsafe trait to indicate what types are usable with the NonZero struct
pub unsafe trait Zeroable {}
unsafe impl<T> Zeroable for *const T {}
unsafe impl<T> Zeroable for *mut T {}
unsafe impl<T> Zeroable for Unique<T> { }
unsafe impl Zeroable for int {}
unsafe impl Zeroable for uint {}
unsafe impl Zeroable for i8 {}

View File

@ -17,16 +17,17 @@
use char::CharExt;
use clone::Clone;
use cmp::{PartialEq, Eq};
use cmp::{PartialOrd, Ord};
use cmp::{PartialEq, Eq, PartialOrd, Ord};
use error::Error;
use fmt;
use intrinsics;
use iter::IteratorExt;
use marker::Copy;
use mem::size_of;
use ops::{Add, Sub, Mul, Div, Rem, Neg};
use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
use option::Option;
use option::Option::{Some, None};
use option::Option::{self, Some, None};
use result::Result::{self, Ok, Err};
use str::{FromStr, StrExt};
/// A built-in signed or unsigned integer.
@ -1428,22 +1429,25 @@ pub trait Float
}
/// A generic trait for converting a string with a radix (base) to a value
#[unstable(feature = "core", reason = "might need to return Result")]
#[unstable(feature = "core", reason = "needs reevaluation")]
pub trait FromStrRadix {
fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
type Err;
fn from_str_radix(str: &str, radix: uint) -> Result<Self, Self::Err>;
}
/// A utility function that just calls FromStrRadix::from_str_radix.
#[unstable(feature = "core", reason = "might need to return Result")]
pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint) -> Option<T> {
#[unstable(feature = "core", reason = "needs reevaluation")]
pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint)
-> Result<T, T::Err> {
FromStrRadix::from_str_radix(str, radix)
}
macro_rules! from_str_radix_float_impl {
($T:ty) => {
#[unstable(feature = "core",
reason = "might need to return Result")]
#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for $T {
type Err = ParseFloatError;
/// Convert a string in base 10 to a float.
/// Accepts an optional decimal exponent.
///
@ -1470,14 +1474,15 @@ macro_rules! from_str_radix_float_impl {
/// `None` if the string did not represent a valid number. Otherwise,
/// `Some(n)` where `n` is the floating-point number represented by `src`.
#[inline]
fn from_str(src: &str) -> Option<$T> {
fn from_str(src: &str) -> Result<$T, ParseFloatError> {
from_str_radix(src, 10)
}
}
#[unstable(feature = "core",
reason = "might need to return Result")]
#[stable(feature = "rust1", since = "1.0.0")]
impl FromStrRadix for $T {
type Err = ParseFloatError;
/// Convert a string in a given base to a float.
///
/// Due to possible conflicts, this function does **not** accept
@ -1493,24 +1498,28 @@ macro_rules! from_str_radix_float_impl {
///
/// # Return value
///
/// `None` if the string did not represent a valid number. Otherwise,
/// `Some(n)` where `n` is the floating-point number represented by `src`.
fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
assert!(radix >= 2 && radix <= 36,
/// `None` if the string did not represent a valid number.
/// Otherwise, `Some(n)` where `n` is the floating-point number
/// represented by `src`.
fn from_str_radix(src: &str, radix: uint)
-> Result<$T, ParseFloatError> {
use self::FloatErrorKind::*;
use self::ParseFloatError as PFE;
assert!(radix >= 2 && radix <= 36,
"from_str_radix_float: must lie in the range `[2, 36]` - found {}",
radix);
// Special values
match src {
"inf" => return Some(Float::infinity()),
"-inf" => return Some(Float::neg_infinity()),
"NaN" => return Some(Float::nan()),
"inf" => return Ok(Float::infinity()),
"-inf" => return Ok(Float::neg_infinity()),
"NaN" => return Ok(Float::nan()),
_ => {},
}
let (is_positive, src) = match src.slice_shift_char() {
None => return None,
Some(('-', "")) => return None,
None => return Err(PFE { kind: Empty }),
Some(('-', "")) => return Err(PFE { kind: Empty }),
Some(('-', src)) => (false, src),
Some((_, _)) => (true, src),
};
@ -1524,7 +1533,7 @@ macro_rules! from_str_radix_float_impl {
let mut exp_info = None::<(char, uint)>;
// Parse the integer part of the significand
for (i, c) in cs {
for (i, c) in cs.by_ref() {
match c.to_digit(radix) {
Some(digit) => {
// shift significand one digit left
@ -1541,15 +1550,15 @@ macro_rules! from_str_radix_float_impl {
// if we've not seen any non-zero digits.
if prev_sig != 0.0 {
if is_positive && sig <= prev_sig
{ return Some(Float::infinity()); }
{ return Ok(Float::infinity()); }
if !is_positive && sig >= prev_sig
{ return Some(Float::neg_infinity()); }
{ return Ok(Float::neg_infinity()); }
// Detect overflow by reversing the shift-and-add process
if is_positive && (prev_sig != (sig - digit as $T) / radix as $T)
{ return Some(Float::infinity()); }
{ return Ok(Float::infinity()); }
if !is_positive && (prev_sig != (sig + digit as $T) / radix as $T)
{ return Some(Float::neg_infinity()); }
{ return Ok(Float::neg_infinity()); }
}
prev_sig = sig;
},
@ -1562,7 +1571,7 @@ macro_rules! from_str_radix_float_impl {
break; // start of fractional part
},
_ => {
return None;
return Err(PFE { kind: Invalid });
},
},
}
@ -1572,7 +1581,7 @@ macro_rules! from_str_radix_float_impl {
// part of the significand
if exp_info.is_none() {
let mut power = 1.0;
for (i, c) in cs {
for (i, c) in cs.by_ref() {
match c.to_digit(radix) {
Some(digit) => {
// Decrease power one order of magnitude
@ -1585,9 +1594,9 @@ macro_rules! from_str_radix_float_impl {
};
// Detect overflow by comparing to last value
if is_positive && sig < prev_sig
{ return Some(Float::infinity()); }
{ return Ok(Float::infinity()); }
if !is_positive && sig > prev_sig
{ return Some(Float::neg_infinity()); }
{ return Ok(Float::neg_infinity()); }
prev_sig = sig;
},
None => match c {
@ -1596,7 +1605,7 @@ macro_rules! from_str_radix_float_impl {
break; // start of exponent
},
_ => {
return None; // invalid number
return Err(PFE { kind: Invalid });
},
},
}
@ -1609,7 +1618,7 @@ macro_rules! from_str_radix_float_impl {
let base = match c {
'E' | 'e' if radix == 10 => 10.0,
'P' | 'p' if radix == 16 => 2.0,
_ => return None,
_ => return Err(PFE { kind: Invalid }),
};
// Parse the exponent as decimal integer
@ -1618,19 +1627,19 @@ macro_rules! from_str_radix_float_impl {
Some(('-', src)) => (false, src.parse::<uint>()),
Some(('+', src)) => (true, src.parse::<uint>()),
Some((_, _)) => (true, src.parse::<uint>()),
None => return None,
None => return Err(PFE { kind: Invalid }),
};
match (is_positive, exp) {
(true, Some(exp)) => base.powi(exp as i32),
(false, Some(exp)) => 1.0 / base.powi(exp as i32),
(_, None) => return None,
(true, Ok(exp)) => base.powi(exp as i32),
(false, Ok(exp)) => 1.0 / base.powi(exp as i32),
(_, Err(_)) => return Err(PFE { kind: Invalid }),
}
},
None => 1.0, // no exponent
};
Some(sig * exp)
Ok(sig * exp)
}
}
}
@ -1640,19 +1649,22 @@ from_str_radix_float_impl! { f64 }
macro_rules! from_str_radix_int_impl {
($T:ty) => {
#[unstable(feature = "core",
reason = "might need to return Result")]
#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for $T {
type Err = ParseIntError;
#[inline]
fn from_str(src: &str) -> Option<$T> {
fn from_str(src: &str) -> Result<$T, ParseIntError> {
from_str_radix(src, 10)
}
}
#[unstable(feature = "core",
reason = "might need to return Result")]
#[stable(feature = "rust1", since = "1.0.0")]
impl FromStrRadix for $T {
fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
type Err = ParseIntError;
fn from_str_radix(src: &str, radix: uint)
-> Result<$T, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
assert!(radix >= 2 && radix <= 36,
"from_str_radix_int: must lie in the range `[2, 36]` - found {}",
radix);
@ -1666,18 +1678,18 @@ macro_rules! from_str_radix_int_impl {
for c in src.chars() {
let x = match c.to_digit(radix) {
Some(x) => x,
None => return None,
None => return Err(PIE { kind: InvalidDigit }),
};
result = match result.checked_mul(radix as $T) {
Some(result) => result,
None => return None,
None => return Err(PIE { kind: Underflow }),
};
result = match result.checked_sub(x as $T) {
Some(result) => result,
None => return None,
None => return Err(PIE { kind: Underflow }),
};
}
Some(result)
Ok(result)
},
Some((_, _)) => {
// The number is signed
@ -1685,20 +1697,20 @@ macro_rules! from_str_radix_int_impl {
for c in src.chars() {
let x = match c.to_digit(radix) {
Some(x) => x,
None => return None,
None => return Err(PIE { kind: InvalidDigit }),
};
result = match result.checked_mul(radix as $T) {
Some(result) => result,
None => return None,
None => return Err(PIE { kind: Overflow }),
};
result = match result.checked_add(x as $T) {
Some(result) => result,
None => return None,
None => return Err(PIE { kind: Overflow }),
};
}
Some(result)
Ok(result)
},
None => None,
None => Err(ParseIntError { kind: Empty }),
}
}
}
@ -1714,3 +1726,63 @@ from_str_radix_int_impl! { u8 }
from_str_radix_int_impl! { u16 }
from_str_radix_int_impl! { u32 }
from_str_radix_int_impl! { u64 }
/// An error which can be returned when parsing an integer.
#[derive(Debug, Clone, PartialEq)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct ParseIntError { kind: IntErrorKind }
#[derive(Debug, Clone, PartialEq)]
enum IntErrorKind {
Empty,
InvalidDigit,
Overflow,
Underflow,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for ParseIntError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Error for ParseIntError {
fn description(&self) -> &str {
match self.kind {
IntErrorKind::Empty => "cannot parse integer from empty string",
IntErrorKind::InvalidDigit => "invalid digit found in string",
IntErrorKind::Overflow => "number too large to fit in target type",
IntErrorKind::Underflow => "number too small to fit in target type",
}
}
}
/// An error which can be returned when parsing a float.
#[derive(Debug, Clone, PartialEq)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct ParseFloatError { kind: FloatErrorKind }
#[derive(Debug, Clone, PartialEq)]
enum FloatErrorKind {
Empty,
Invalid,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for ParseFloatError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Error for ParseFloatError {
fn description(&self) -> &str {
match self.kind {
FloatErrorKind::Empty => "cannot parse float from empty string",
FloatErrorKind::Invalid => "invalid float literal",
}
}
}

View File

@ -1134,55 +1134,6 @@ impl<'a, T: ?Sized> DerefMut for &'a mut T {
#[lang="fn"]
#[unstable(feature = "core",
reason = "uncertain about variadic generics, input versus associated types")]
#[cfg(stage0)]
pub trait Fn<Args,Output> {
/// This is called when the call operator is used.
extern "rust-call" fn call(&self, args: Args) -> Output;
}
/// A version of the call operator that takes a mutable receiver.
#[lang="fn_mut"]
#[unstable(feature = "core",
reason = "uncertain about variadic generics, input versus associated types")]
#[cfg(stage0)]
pub trait FnMut<Args,Output> {
/// This is called when the call operator is used.
extern "rust-call" fn call_mut(&mut self, args: Args) -> Output;
}
/// A version of the call operator that takes a by-value receiver.
#[lang="fn_once"]
#[unstable(feature = "core",
reason = "uncertain about variadic generics, input versus associated types")]
#[cfg(stage0)]
pub trait FnOnce<Args,Output> {
/// This is called when the call operator is used.
extern "rust-call" fn call_once(self, args: Args) -> Output;
}
#[cfg(stage0)]
impl<F: ?Sized, A, R> FnMut<A, R> for F
where F : Fn<A, R>
{
extern "rust-call" fn call_mut(&mut self, args: A) -> R {
self.call(args)
}
}
#[cfg(stage0)]
impl<F,A,R> FnOnce<A,R> for F
where F : FnMut<A,R>
{
extern "rust-call" fn call_once(mut self, args: A) -> R {
self.call_mut(args)
}
}
/// A version of the call operator that takes an immutable receiver.
#[lang="fn"]
#[unstable(feature = "core",
reason = "uncertain about variadic generics, input versus associated types")]
#[cfg(not(stage0))]
#[rustc_paren_sugar]
pub trait Fn<Args> {
type Output;
@ -1195,7 +1146,6 @@ pub trait Fn<Args> {
#[lang="fn_mut"]
#[unstable(feature = "core",
reason = "uncertain about variadic generics, input versus associated types")]
#[cfg(not(stage0))]
#[rustc_paren_sugar]
pub trait FnMut<Args> {
type Output;
@ -1208,7 +1158,6 @@ pub trait FnMut<Args> {
#[lang="fn_once"]
#[unstable(feature = "core",
reason = "uncertain about variadic generics, input versus associated types")]
#[cfg(not(stage0))]
#[rustc_paren_sugar]
pub trait FnOnce<Args> {
type Output;
@ -1217,7 +1166,6 @@ pub trait FnOnce<Args> {
extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
}
#[cfg(not(stage0))]
impl<F: ?Sized, A> FnMut<A> for F
where F : Fn<A>
{
@ -1228,7 +1176,6 @@ impl<F: ?Sized, A> FnMut<A> for F
}
}
#[cfg(not(stage0))]
impl<F,A> FnOnce<A> for F
where F : FnMut<A>
{

View File

@ -728,8 +728,8 @@ impl<T: Default> Option<T> {
/// ```
/// let good_year_from_input = "1909";
/// let bad_year_from_input = "190blarg";
/// let good_year = good_year_from_input.parse().unwrap_or_default();
/// let bad_year = bad_year_from_input.parse().unwrap_or_default();
/// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
/// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
///
/// assert_eq!(1909, good_year);
/// assert_eq!(0, bad_year);

View File

@ -229,7 +229,7 @@
use self::Result::{Ok, Err};
use clone::Clone;
use fmt::Debug;
use fmt;
use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, ExactSizeIterator};
use ops::{FnMut, FnOnce};
use option::Option::{self, None, Some};
@ -715,7 +715,7 @@ impl<T, E> Result<T, E> {
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, E: Debug> Result<T, E> {
impl<T, E: fmt::Debug> Result<T, E> {
/// Unwraps a result, yielding the content of an `Ok`.
///
/// # Panics
@ -746,7 +746,7 @@ impl<T, E: Debug> Result<T, E> {
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Debug, E> Result<T, E> {
impl<T: fmt::Debug, E> Result<T, E> {
/// Unwraps a result, yielding the content of an `Err`.
///
/// # Panics

View File

@ -41,7 +41,6 @@ use cmp::Ordering::{Less, Equal, Greater};
use cmp;
use default::Default;
use iter::*;
use marker::Copy;
use num::Int;
use ops::{FnMut, self, Index};
#[cfg(stage0)]
@ -637,6 +636,22 @@ impl<'a, T> Default for &'a [T] {
// Iterators
//
impl<'a, T> IntoIterator for &'a [T] {
type Iter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut [T] {
type Iter = IterMut<'a, T>;
fn into_iter(self) -> IterMut<'a, T> {
self.iter_mut()
}
}
// The shared definition of the `Iter` and `IterMut` iterators
macro_rules! iterator {
(struct $name:ident -> $ptr:ty, $elem:ty) => {
@ -784,8 +799,6 @@ impl<'a, T> Iter<'a, T> {
}
}
impl<'a,T> Copy for Iter<'a,T> {}
iterator!{struct Iter -> *const T, &'a T}
#[stable(feature = "rust1", since = "1.0.0")]
@ -793,7 +806,7 @@ impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> Clone for Iter<'a, T> {
fn clone(&self) -> Iter<'a, T> { *self }
fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, marker: self.marker } }
}
#[unstable(feature = "core", reason = "trait is experimental")]

View File

@ -18,6 +18,7 @@
use self::Searcher::{Naive, TwoWay, TwoWayLong};
use clone::Clone;
use cmp::{self, Eq};
use default::Default;
use error::Error;
@ -108,37 +109,62 @@ macro_rules! delegate_iter {
/// A trait to abstract the idea of creating a new instance of a type from a
/// string.
// FIXME(#17307): there should be an `E` associated type for a `Result` return
#[unstable(feature = "core",
reason = "will return a Result once associated types are working")]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait FromStr {
/// The associated error which can be returned from parsing.
#[stable(feature = "rust1", since = "1.0.0")]
type Err;
/// Parses a string `s` to return an optional value of this type. If the
/// string is ill-formatted, the None is returned.
fn from_str(s: &str) -> Option<Self>;
#[stable(feature = "rust1", since = "1.0.0")]
fn from_str(s: &str) -> Result<Self, Self::Err>;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for bool {
type Err = ParseBoolError;
/// Parse a `bool` from a string.
///
/// Yields an `Option<bool>`, because `s` may or may not actually be parseable.
/// Yields an `Option<bool>`, because `s` may or may not actually be
/// parseable.
///
/// # Examples
///
/// ```rust
/// assert_eq!("true".parse(), Some(true));
/// assert_eq!("false".parse(), Some(false));
/// assert_eq!("not even a boolean".parse::<bool>(), None);
/// assert_eq!("true".parse(), Ok(true));
/// assert_eq!("false".parse(), Ok(false));
/// assert!("not even a boolean".parse::<bool>().is_err());
/// ```
#[inline]
fn from_str(s: &str) -> Option<bool> {
fn from_str(s: &str) -> Result<bool, ParseBoolError> {
match s {
"true" => Some(true),
"false" => Some(false),
_ => None,
"true" => Ok(true),
"false" => Ok(false),
_ => Err(ParseBoolError { _priv: () }),
}
}
}
/// An error returned when parsing a `bool` from a string fails.
#[derive(Debug, Clone, PartialEq)]
#[allow(missing_copy_implementations)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct ParseBoolError { _priv: () }
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for ParseBoolError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"provided string was not `true` or `false`".fmt(f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Error for ParseBoolError {
fn description(&self) -> &str { "failed to parse bool" }
}
/*
Section: Creating a string
*/
@ -279,7 +305,7 @@ Section: Iterators
/// Iterator for the char (representing *Unicode Scalar Values*) of a string
///
/// Created with the method `.chars()`.
#[derive(Clone, Copy)]
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Chars<'a> {
iter: slice::Iter<'a, u8>
@ -460,15 +486,6 @@ delegate_iter!{exact u8 : Bytes<'a>}
#[derive(Copy, Clone)]
struct BytesDeref;
#[cfg(stage0)]
impl<'a> Fn(&'a u8) -> u8 for BytesDeref {
#[inline]
extern "rust-call" fn call(&self, (ptr,): (&'a u8,)) -> u8 {
*ptr
}
}
#[cfg(not(stage0))]
impl<'a> Fn<(&'a u8,)> for BytesDeref {
type Output = u8;
@ -1007,11 +1024,11 @@ fn run_utf8_validation_iterator(iter: &mut slice::Iter<u8>)
let whole = iter.as_slice();
loop {
// save the current thing we're pointing at.
let old = *iter;
let old = iter.clone();
// restore the iterator we had at the start of this codepoint.
macro_rules! err { () => {{
*iter = old;
*iter = old.clone();
return Err(Utf8Error::InvalidByte(whole.len() - iter.as_slice().len()))
}}}
@ -1355,7 +1372,7 @@ pub trait StrExt {
fn as_ptr(&self) -> *const u8;
fn len(&self) -> uint;
fn is_empty(&self) -> bool;
fn parse<T: FromStr>(&self) -> Option<T>;
fn parse<T: FromStr>(&self) -> Result<T, T::Err>;
}
#[inline(never)]
@ -1670,7 +1687,7 @@ impl StrExt for str {
fn is_empty(&self) -> bool { self.len() == 0 }
#[inline]
fn parse<T: FromStr>(&self) -> Option<T> { FromStr::from_str(self) }
fn parse<T: FromStr>(&self) -> Result<T, T::Err> { FromStr::from_str(self) }
}
/// Pluck a code point out of a UTF-8-like byte slice and return the

View File

@ -123,7 +123,7 @@ fn any_fixed_vec() {
#[bench]
fn bench_downcast_ref(b: &mut Bencher) {
b.iter(|| {
let mut x = 0i;
let mut x = 0;
let mut y = &mut x as &mut Any;
test::black_box(&mut y);
test::black_box(y.downcast_ref::<int>() == Some(&0));

View File

@ -14,14 +14,14 @@ use std::mem::drop;
#[test]
fn smoketest_cell() {
let x = Cell::new(10i);
let x = Cell::new(10);
assert!(x == Cell::new(10));
assert!(x.get() == 10);
x.set(20);
assert!(x == Cell::new(20));
assert!(x.get() == 20);
let y = Cell::new((30i, 40i));
let y = Cell::new((30, 40));
assert!(y == Cell::new((30, 40)));
assert!(y.get() == (30, 40));
}
@ -50,35 +50,35 @@ fn ref_and_refmut_have_sensible_show() {
#[test]
fn double_imm_borrow() {
let x = RefCell::new(0i);
let x = RefCell::new(0);
let _b1 = x.borrow();
x.borrow();
}
#[test]
fn no_mut_then_imm_borrow() {
let x = RefCell::new(0i);
let x = RefCell::new(0);
let _b1 = x.borrow_mut();
assert!(x.try_borrow().is_none());
}
#[test]
fn no_imm_then_borrow_mut() {
let x = RefCell::new(0i);
let x = RefCell::new(0);
let _b1 = x.borrow();
assert!(x.try_borrow_mut().is_none());
}
#[test]
fn no_double_borrow_mut() {
let x = RefCell::new(0i);
let x = RefCell::new(0);
let _b1 = x.borrow_mut();
assert!(x.try_borrow_mut().is_none());
}
#[test]
fn imm_release_borrow_mut() {
let x = RefCell::new(0i);
let x = RefCell::new(0);
{
let _b1 = x.borrow();
}
@ -87,7 +87,7 @@ fn imm_release_borrow_mut() {
#[test]
fn mut_release_borrow_mut() {
let x = RefCell::new(0i);
let x = RefCell::new(0);
{
let _b1 = x.borrow_mut();
}
@ -96,7 +96,7 @@ fn mut_release_borrow_mut() {
#[test]
fn double_borrow_single_release_no_borrow_mut() {
let x = RefCell::new(0i);
let x = RefCell::new(0);
let _b1 = x.borrow();
{
let _b2 = x.borrow();
@ -107,7 +107,7 @@ fn double_borrow_single_release_no_borrow_mut() {
#[test]
#[should_fail]
fn discard_doesnt_unborrow() {
let x = RefCell::new(0i);
let x = RefCell::new(0);
let _b = x.borrow();
let _ = _b;
let _b = x.borrow_mut();
@ -115,7 +115,7 @@ fn discard_doesnt_unborrow() {
#[test]
fn clone_ref_updates_flag() {
let x = RefCell::new(0i);
let x = RefCell::new(0);
{
let b1 = x.borrow();
assert!(x.try_borrow_mut().is_none());

View File

@ -10,7 +10,7 @@
#[test]
fn test_borrowed_clone() {
let x = 5i;
let x = 5;
let y: &int = &x;
let z: &int = (&y).clone();
assert_eq!(*z, 5);
@ -18,8 +18,8 @@ fn test_borrowed_clone() {
#[test]
fn test_clone_from() {
let a = box 5i;
let mut b = box 10i;
let a = box 5;
let mut b = box 10;
b.clone_from(&a);
assert_eq!(*b, 5);
}

View File

@ -13,20 +13,20 @@ use core::cmp::Ordering::{Less, Greater, Equal};
#[test]
fn test_int_totalord() {
assert_eq!(5i.cmp(&10), Less);
assert_eq!(10i.cmp(&5), Greater);
assert_eq!(5i.cmp(&5), Equal);
assert_eq!((-5i).cmp(&12), Less);
assert_eq!(12i.cmp(&-5), Greater);
assert_eq!(5.cmp(&10), Less);
assert_eq!(10.cmp(&5), Greater);
assert_eq!(5.cmp(&5), Equal);
assert_eq!((-5).cmp(&12), Less);
assert_eq!(12.cmp(&-5), Greater);
}
#[test]
fn test_mut_int_totalord() {
assert_eq!((&mut 5i).cmp(&&mut 10), Less);
assert_eq!((&mut 10i).cmp(&&mut 5), Greater);
assert_eq!((&mut 5i).cmp(&&mut 5), Equal);
assert_eq!((&mut -5i).cmp(&&mut 12), Less);
assert_eq!((&mut 12i).cmp(&&mut -5), Greater);
assert_eq!((&mut 5).cmp(&&mut 10), Less);
assert_eq!((&mut 10).cmp(&&mut 5), Greater);
assert_eq!((&mut 5).cmp(&&mut 5), Equal);
assert_eq!((&mut -5).cmp(&&mut 12), Less);
assert_eq!((&mut 12).cmp(&&mut -5), Greater);
}
#[test]
@ -47,11 +47,11 @@ fn test_partial_min() {
use core::f64::NAN;
let data_integer = [
// a, b, result
(0i, 0i, Some(0i)),
(1i, 0i, Some(0i)),
(0i, 1i, Some(0i)),
(-1i, 0i, Some(-1i)),
(0i, -1i, Some(-1i))
(0, 0, Some(0)),
(1, 0, Some(0)),
(0, 1, Some(0)),
(-1, 0, Some(-1)),
(0, -1, Some(-1))
];
let data_float = [
@ -80,11 +80,11 @@ fn test_partial_max() {
use core::f64::NAN;
let data_integer = [
// a, b, result
(0i, 0i, Some(0i)),
(1i, 0i, Some(1i)),
(0i, 1i, Some(1i)),
(-1i, 0i, Some(0i)),
(0i, -1i, Some(0i))
(0, 0, Some(0)),
(1, 0, Some(1)),
(0, 1, Some(1)),
(-1, 0, Some(0)),
(0, -1, Some(0))
];
let data_float = [

View File

@ -15,7 +15,7 @@ use std::thread::Thread;
#[test]
fn test_success() {
let mut i = 0i;
let mut i = 0;
try_finally(
&mut i, (),
|i, ()| {
@ -32,7 +32,7 @@ fn test_success() {
#[test]
#[should_fail]
fn test_fail() {
let mut i = 0i;
let mut i = 0;
try_finally(
&mut i, (),
|i, ()| {
@ -47,7 +47,7 @@ fn test_fail() {
#[test]
fn test_retval() {
let mut closure = |&mut:| 10i;
let mut closure = |&mut:| 10;
let i = closure.finally(|| { });
assert_eq!(i, 10);
}

View File

@ -56,7 +56,7 @@ fn test_writer_hasher() {
assert_eq!(hash(&5i16), 5);
assert_eq!(hash(&5i32), 5);
assert_eq!(hash(&5i64), 5);
assert_eq!(hash(&5i), 5);
assert_eq!(hash(&5), 5);
assert_eq!(hash(&false), 0);
assert_eq!(hash(&true), 1);
@ -76,12 +76,12 @@ fn test_writer_hasher() {
// FIXME (#18248) Add tests for hashing Rc<str> and Rc<[T]>
unsafe {
let ptr: *const int = mem::transmute(5i);
let ptr: *const i32 = mem::transmute(5is);
assert_eq!(hash(&ptr), 5);
}
unsafe {
let ptr: *mut int = mem::transmute(5i);
let ptr: *mut i32 = mem::transmute(5is);
assert_eq!(hash(&ptr), 5);
}
}

View File

@ -20,8 +20,8 @@ use test::Bencher;
#[test]
fn test_lt() {
let empty: [int; 0] = [];
let xs = [1i,2,3];
let ys = [1i,2,0];
let xs = [1,2,3];
let ys = [1,2,0];
assert!(!lt(xs.iter(), ys.iter()));
assert!(!le(xs.iter(), ys.iter()));
@ -64,15 +64,15 @@ fn test_lt() {
#[test]
fn test_multi_iter() {
let xs = [1i,2,3,4];
let ys = [4i,3,2,1];
let xs = [1,2,3,4];
let ys = [4,3,2,1];
assert!(eq(xs.iter(), ys.iter().rev()));
assert!(lt(xs.iter(), xs.iter().skip(2)));
}
#[test]
fn test_counter_from_iter() {
let it = count(0i, 5).take(10);
let it = count(0, 5).take(10);
let xs: Vec<int> = FromIterator::from_iter(it);
assert!(xs == vec![0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
}
@ -304,7 +304,7 @@ fn test_cycle() {
#[test]
fn test_iterator_nth() {
let v: &[_] = &[0i, 1, 2, 3, 4];
let v: &[_] = &[0, 1, 2, 3, 4];
for i in 0u..v.len() {
assert_eq!(v.iter().nth(i).unwrap(), &v[i]);
}
@ -313,14 +313,14 @@ fn test_iterator_nth() {
#[test]
fn test_iterator_last() {
let v: &[_] = &[0i, 1, 2, 3, 4];
let v: &[_] = &[0, 1, 2, 3, 4];
assert_eq!(v.iter().last().unwrap(), &4);
assert_eq!(v[..1].iter().last().unwrap(), &0);
}
#[test]
fn test_iterator_len() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let v: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v[..4].iter().count(), 4);
assert_eq!(v[..10].iter().count(), 10);
assert_eq!(v[..0].iter().count(), 0);
@ -328,7 +328,7 @@ fn test_iterator_len() {
#[test]
fn test_iterator_sum() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let v: &[i32] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v[..4].iter().map(|&x| x).sum(), 6);
assert_eq!(v.iter().map(|&x| x).sum(), 55);
assert_eq!(v[..0].iter().map(|&x| x).sum(), 0);
@ -336,7 +336,7 @@ fn test_iterator_sum() {
#[test]
fn test_iterator_product() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let v: &[i32] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v[..4].iter().map(|&x| x).product(), 0);
assert_eq!(v[1..5].iter().map(|&x| x).product(), 24);
assert_eq!(v[..0].iter().map(|&x| x).product(), 1);
@ -344,7 +344,7 @@ fn test_iterator_product() {
#[test]
fn test_iterator_max() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let v: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v[..4].iter().map(|&x| x).max(), Some(3));
assert_eq!(v.iter().map(|&x| x).max(), Some(10));
assert_eq!(v[..0].iter().map(|&x| x).max(), None);
@ -352,7 +352,7 @@ fn test_iterator_max() {
#[test]
fn test_iterator_min() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let v: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v[..4].iter().map(|&x| x).min(), Some(0));
assert_eq!(v.iter().map(|&x| x).min(), Some(0));
assert_eq!(v[..0].iter().map(|&x| x).min(), None);
@ -360,51 +360,51 @@ fn test_iterator_min() {
#[test]
fn test_iterator_size_hint() {
let c = count(0i, 1);
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let v2 = &[10i, 11, 12];
let c = count(0, 1);
let v: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let v2 = &[10, 11, 12];
let vi = v.iter();
assert_eq!(c.size_hint(), (uint::MAX, None));
assert_eq!(vi.size_hint(), (10, Some(10)));
assert_eq!(vi.clone().size_hint(), (10, Some(10)));
assert_eq!(c.take(5).size_hint(), (5, Some(5)));
assert_eq!(c.skip(5).size_hint().1, None);
assert_eq!(c.take_while(|_| false).size_hint(), (0, None));
assert_eq!(c.skip_while(|_| false).size_hint(), (0, None));
assert_eq!(c.enumerate().size_hint(), (uint::MAX, None));
assert_eq!(c.chain(vi.map(|&i| i)).size_hint(), (uint::MAX, None));
assert_eq!(c.zip(vi).size_hint(), (10, Some(10)));
assert_eq!(c.scan(0i, |_,_| Some(0i)).size_hint(), (0, None));
assert_eq!(c.filter(|_| false).size_hint(), (0, None));
assert_eq!(c.map(|_| 0i).size_hint(), (uint::MAX, None));
assert_eq!(c.filter_map(|_| Some(0i)).size_hint(), (0, None));
assert_eq!(c.clone().take(5).size_hint(), (5, Some(5)));
assert_eq!(c.clone().skip(5).size_hint().1, None);
assert_eq!(c.clone().take_while(|_| false).size_hint(), (0, None));
assert_eq!(c.clone().skip_while(|_| false).size_hint(), (0, None));
assert_eq!(c.clone().enumerate().size_hint(), (uint::MAX, None));
assert_eq!(c.clone().chain(vi.clone().map(|&i| i)).size_hint(), (uint::MAX, None));
assert_eq!(c.clone().zip(vi.clone()).size_hint(), (10, Some(10)));
assert_eq!(c.clone().scan(0i, |_,_| Some(0)).size_hint(), (0, None));
assert_eq!(c.clone().filter(|_| false).size_hint(), (0, None));
assert_eq!(c.clone().map(|_| 0).size_hint(), (uint::MAX, None));
assert_eq!(c.filter_map(|_| Some(0)).size_hint(), (0, None));
assert_eq!(vi.take(5).size_hint(), (5, Some(5)));
assert_eq!(vi.take(12).size_hint(), (10, Some(10)));
assert_eq!(vi.skip(3).size_hint(), (7, Some(7)));
assert_eq!(vi.skip(12).size_hint(), (0, Some(0)));
assert_eq!(vi.take_while(|_| false).size_hint(), (0, Some(10)));
assert_eq!(vi.skip_while(|_| false).size_hint(), (0, Some(10)));
assert_eq!(vi.enumerate().size_hint(), (10, Some(10)));
assert_eq!(vi.chain(v2.iter()).size_hint(), (13, Some(13)));
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.filter_map(|_| Some(0i)).size_hint(), (0, Some(10)));
assert_eq!(vi.clone().take(5).size_hint(), (5, Some(5)));
assert_eq!(vi.clone().take(12).size_hint(), (10, Some(10)));
assert_eq!(vi.clone().skip(3).size_hint(), (7, Some(7)));
assert_eq!(vi.clone().skip(12).size_hint(), (0, Some(0)));
assert_eq!(vi.clone().take_while(|_| false).size_hint(), (0, Some(10)));
assert_eq!(vi.clone().skip_while(|_| false).size_hint(), (0, Some(10)));
assert_eq!(vi.clone().enumerate().size_hint(), (10, Some(10)));
assert_eq!(vi.clone().chain(v2.iter()).size_hint(), (13, Some(13)));
assert_eq!(vi.clone().zip(v2.iter()).size_hint(), (3, Some(3)));
assert_eq!(vi.clone().scan(0i, |_,_| Some(0)).size_hint(), (0, Some(10)));
assert_eq!(vi.clone().filter(|_| false).size_hint(), (0, Some(10)));
assert_eq!(vi.clone().map(|&i| i+1).size_hint(), (10, Some(10)));
assert_eq!(vi.filter_map(|_| Some(0)).size_hint(), (0, Some(10)));
}
#[test]
fn test_collect() {
let a = vec![1i, 2, 3, 4, 5];
let a = vec![1, 2, 3, 4, 5];
let b: Vec<int> = a.iter().map(|&x| x).collect();
assert!(a == b);
}
#[test]
fn test_all() {
let v: Box<[int]> = box [1i, 2, 3, 4, 5];
let v: Box<[int]> = box [1, 2, 3, 4, 5];
assert!(v.iter().all(|&x| x < 10));
assert!(!v.iter().all(|&x| x % 2 == 0));
assert!(!v.iter().all(|&x| x > 100));
@ -413,7 +413,7 @@ fn test_all() {
#[test]
fn test_any() {
let v: Box<[int]> = box [1i, 2, 3, 4, 5];
let v: Box<[int]> = box [1, 2, 3, 4, 5];
assert!(v.iter().any(|&x| x < 10));
assert!(v.iter().any(|&x| x % 2 == 0));
assert!(!v.iter().any(|&x| x > 100));
@ -422,7 +422,7 @@ fn test_any() {
#[test]
fn test_find() {
let v: &[int] = &[1i, 3, 9, 27, 103, 14, 11];
let v: &[int] = &[1, 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());
@ -430,7 +430,7 @@ fn test_find() {
#[test]
fn test_position() {
let v = &[1i, 3, 9, 27, 103, 14, 11];
let v = &[1, 3, 9, 27, 103, 14, 11];
assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5);
assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1);
assert!(v.iter().position(|x| *x % 12 == 0).is_none());
@ -438,7 +438,7 @@ fn test_position() {
#[test]
fn test_count() {
let xs = &[1i, 2, 2, 1, 5, 9, 0, 2];
let xs = &[1, 2, 2, 1, 5, 9, 0, 2];
assert_eq!(xs.iter().filter(|x| **x == 2).count(), 3);
assert_eq!(xs.iter().filter(|x| **x == 5).count(), 1);
assert_eq!(xs.iter().filter(|x| **x == 95).count(), 0);
@ -446,19 +446,19 @@ fn test_count() {
#[test]
fn test_max_by() {
let xs: &[int] = &[-3i, 0, 1, 5, -10];
let xs: &[int] = &[-3, 0, 1, 5, -10];
assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
}
#[test]
fn test_min_by() {
let xs: &[int] = &[-3i, 0, 1, 5, -10];
let xs: &[int] = &[-3, 0, 1, 5, -10];
assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
}
#[test]
fn test_by_ref() {
let mut xs = 0i..10;
let mut xs = 0..10;
// sum the first five values
let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
assert_eq!(partial_sum, 10);
@ -467,7 +467,7 @@ fn test_by_ref() {
#[test]
fn test_rev() {
let xs = [2i, 4, 6, 8, 10, 12, 14, 16];
let xs = [2, 4, 6, 8, 10, 12, 14, 16];
let mut it = xs.iter();
it.next();
it.next();
@ -494,7 +494,7 @@ fn test_cloned() {
#[test]
fn test_double_ended_map() {
let xs = [1i, 2, 3, 4, 5, 6];
let xs = [1, 2, 3, 4, 5, 6];
let mut it = xs.iter().map(|&x| x * -1);
assert_eq!(it.next(), Some(-1));
assert_eq!(it.next(), Some(-2));
@ -507,7 +507,7 @@ fn test_double_ended_map() {
#[test]
fn test_double_ended_enumerate() {
let xs = [1i, 2, 3, 4, 5, 6];
let xs = [1, 2, 3, 4, 5, 6];
let mut it = xs.iter().map(|&x| x).enumerate();
assert_eq!(it.next(), Some((0, 1)));
assert_eq!(it.next(), Some((1, 2)));
@ -520,8 +520,8 @@ fn test_double_ended_enumerate() {
#[test]
fn test_double_ended_zip() {
let xs = [1i, 2, 3, 4, 5, 6];
let ys = [1i, 2, 3, 7];
let xs = [1, 2, 3, 4, 5, 6];
let ys = [1, 2, 3, 7];
let a = xs.iter().map(|&x| x);
let b = ys.iter().map(|&x| x);
let mut it = a.zip(b);
@ -534,7 +534,7 @@ fn test_double_ended_zip() {
#[test]
fn test_double_ended_filter() {
let xs = [1i, 2, 3, 4, 5, 6];
let xs = [1, 2, 3, 4, 5, 6];
let mut it = xs.iter().filter(|&x| *x & 1 == 0);
assert_eq!(it.next_back().unwrap(), &6);
assert_eq!(it.next_back().unwrap(), &4);
@ -544,7 +544,7 @@ fn test_double_ended_filter() {
#[test]
fn test_double_ended_filter_map() {
let xs = [1i, 2, 3, 4, 5, 6];
let xs = [1, 2, 3, 4, 5, 6];
let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None });
assert_eq!(it.next_back().unwrap(), 12);
assert_eq!(it.next_back().unwrap(), 8);
@ -554,8 +554,8 @@ fn test_double_ended_filter_map() {
#[test]
fn test_double_ended_chain() {
let xs = [1i, 2, 3, 4, 5];
let ys = [7i, 9, 11];
let xs = [1, 2, 3, 4, 5];
let ys = [7, 9, 11];
let mut it = xs.iter().chain(ys.iter()).rev();
assert_eq!(it.next().unwrap(), &11);
assert_eq!(it.next().unwrap(), &9);
@ -572,7 +572,7 @@ fn test_double_ended_chain() {
fn test_rposition() {
fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
let v = [(0i, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
let v = [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
assert_eq!(v.iter().rposition(f), Some(3u));
assert!(v.iter().rposition(g).is_none());
@ -581,9 +581,9 @@ fn test_rposition() {
#[test]
#[should_fail]
fn test_rposition_panic() {
let v = [(box 0i, box 0i), (box 0i, box 0i),
(box 0i, box 0i), (box 0i, box 0i)];
let mut i = 0i;
let v = [(box 0, box 0), (box 0, box 0),
(box 0, box 0), (box 0, box 0)];
let mut i = 0;
v.iter().rposition(|_elt| {
if i == 2 {
panic!()
@ -635,8 +635,8 @@ fn test_double_ended_flat_map() {
#[test]
fn test_random_access_chain() {
let xs = [1i, 2, 3, 4, 5];
let ys = [7i, 9, 11];
let xs = [1, 2, 3, 4, 5];
let ys = [7, 9, 11];
let mut it = xs.iter().chain(ys.iter());
assert_eq!(it.idx(0).unwrap(), &1);
assert_eq!(it.idx(5).unwrap(), &7);
@ -656,13 +656,13 @@ fn test_random_access_chain() {
#[test]
fn test_random_access_enumerate() {
let xs = [1i, 2, 3, 4, 5];
let xs = [1, 2, 3, 4, 5];
check_randacc_iter(xs.iter().enumerate(), xs.len());
}
#[test]
fn test_random_access_rev() {
let xs = [1i, 2, 3, 4, 5];
let xs = [1, 2, 3, 4, 5];
check_randacc_iter(xs.iter().rev(), xs.len());
let mut it = xs.iter().rev();
it.next();
@ -673,14 +673,14 @@ fn test_random_access_rev() {
#[test]
fn test_random_access_zip() {
let xs = [1i, 2, 3, 4, 5];
let ys = [7i, 9, 11];
let xs = [1, 2, 3, 4, 5];
let ys = [7, 9, 11];
check_randacc_iter(xs.iter().zip(ys.iter()), cmp::min(xs.len(), ys.len()));
}
#[test]
fn test_random_access_take() {
let xs = [1i, 2, 3, 4, 5];
let xs = [1, 2, 3, 4, 5];
let empty: &[int] = &[];
check_randacc_iter(xs.iter().take(3), 3);
check_randacc_iter(xs.iter().take(20), xs.len());
@ -690,7 +690,7 @@ fn test_random_access_take() {
#[test]
fn test_random_access_skip() {
let xs = [1i, 2, 3, 4, 5];
let xs = [1, 2, 3, 4, 5];
let empty: &[int] = &[];
check_randacc_iter(xs.iter().skip(2), xs.len() - 2);
check_randacc_iter(empty.iter().skip(2), 0);
@ -698,7 +698,7 @@ fn test_random_access_skip() {
#[test]
fn test_random_access_inspect() {
let xs = [1i, 2, 3, 4, 5];
let xs = [1, 2, 3, 4, 5];
// test .map and .inspect that don't implement Clone
let mut it = xs.iter().inspect(|_| {});
@ -711,7 +711,7 @@ fn test_random_access_inspect() {
#[test]
fn test_random_access_map() {
let xs = [1i, 2, 3, 4, 5];
let xs = [1, 2, 3, 4, 5];
let mut it = xs.iter().map(|x| *x);
assert_eq!(xs.len(), it.indexable());
@ -722,7 +722,7 @@ fn test_random_access_map() {
#[test]
fn test_random_access_cycle() {
let xs = [1i, 2, 3, 4, 5];
let xs = [1, 2, 3, 4, 5];
let empty: &[int] = &[];
check_randacc_iter(xs.iter().cycle().take(27), 27);
check_randacc_iter(empty.iter().cycle(), 0);
@ -730,86 +730,86 @@ fn test_random_access_cycle() {
#[test]
fn test_double_ended_range() {
assert!((11i..14).rev().collect::<Vec<int>>() == vec![13i, 12, 11]);
for _ in (10i..0).rev() {
assert!((11..14).rev().collect::<Vec<_>>() == vec![13, 12, 11]);
for _ in (10..0).rev() {
panic!("unreachable");
}
assert!((11u..14).rev().collect::<Vec<uint>>() == vec![13u, 12, 11]);
for _ in (10u..0).rev() {
assert!((11..14).rev().collect::<Vec<_>>() == vec![13, 12, 11]);
for _ in (10..0).rev() {
panic!("unreachable");
}
}
#[test]
fn test_range() {
assert!((0i..5).collect::<Vec<int>>() == vec![0i, 1, 2, 3, 4]);
assert!((-10i..-1).collect::<Vec<int>>() ==
assert!((0..5).collect::<Vec<_>>() == vec![0, 1, 2, 3, 4]);
assert!((-10..-1).collect::<Vec<_>>() ==
vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]);
assert!((0i..5).rev().collect::<Vec<int>>() == vec![4, 3, 2, 1, 0]);
assert_eq!((200i..-5).count(), 0);
assert_eq!((200i..-5).rev().count(), 0);
assert_eq!((200i..200).count(), 0);
assert_eq!((200i..200).rev().count(), 0);
assert!((0..5).rev().collect::<Vec<_>>() == vec![4, 3, 2, 1, 0]);
assert_eq!((200..-5).count(), 0);
assert_eq!((200..-5).rev().count(), 0);
assert_eq!((200..200).count(), 0);
assert_eq!((200..200).rev().count(), 0);
assert_eq!((0i..100).size_hint(), (100, Some(100)));
assert_eq!((0..100).size_hint(), (100, Some(100)));
// this test is only meaningful when sizeof uint < sizeof u64
assert_eq!((uint::MAX - 1..uint::MAX).size_hint(), (1, Some(1)));
assert_eq!((-10i..-1).size_hint(), (9, Some(9)));
assert_eq!((-10..-1).size_hint(), (9, Some(9)));
}
#[test]
fn test_range_inclusive() {
assert!(range_inclusive(0i, 5).collect::<Vec<int>>() ==
vec![0i, 1, 2, 3, 4, 5]);
assert!(range_inclusive(0i, 5).rev().collect::<Vec<int>>() ==
vec![5i, 4, 3, 2, 1, 0]);
assert_eq!(range_inclusive(200i, -5).count(), 0);
assert_eq!(range_inclusive(200i, -5).rev().count(), 0);
assert!(range_inclusive(200i, 200).collect::<Vec<int>>() == vec![200]);
assert!(range_inclusive(200i, 200).rev().collect::<Vec<int>>() == vec![200]);
assert!(range_inclusive(0, 5).collect::<Vec<int>>() ==
vec![0, 1, 2, 3, 4, 5]);
assert!(range_inclusive(0, 5).rev().collect::<Vec<int>>() ==
vec![5, 4, 3, 2, 1, 0]);
assert_eq!(range_inclusive(200, -5).count(), 0);
assert_eq!(range_inclusive(200, -5).rev().count(), 0);
assert!(range_inclusive(200, 200).collect::<Vec<int>>() == vec![200]);
assert!(range_inclusive(200, 200).rev().collect::<Vec<int>>() == vec![200]);
}
#[test]
fn test_range_step() {
assert!(range_step(0i, 20, 5).collect::<Vec<int>>() ==
assert!(range_step(0, 20, 5).collect::<Vec<int>>() ==
vec![0, 5, 10, 15]);
assert!(range_step(20i, 0, -5).collect::<Vec<int>>() ==
assert!(range_step(20, 0, -5).collect::<Vec<int>>() ==
vec![20, 15, 10, 5]);
assert!(range_step(20i, 0, -6).collect::<Vec<int>>() ==
assert!(range_step(20, 0, -6).collect::<Vec<int>>() ==
vec![20, 14, 8, 2]);
assert!(range_step(200u8, 255, 50).collect::<Vec<u8>>() ==
vec![200u8, 250]);
assert!(range_step(200i, -5, 1).collect::<Vec<int>>() == vec![]);
assert!(range_step(200i, 200, 1).collect::<Vec<int>>() == vec![]);
assert!(range_step(200, -5, 1).collect::<Vec<int>>() == vec![]);
assert!(range_step(200, 200, 1).collect::<Vec<int>>() == vec![]);
}
#[test]
fn test_range_step_inclusive() {
assert!(range_step_inclusive(0i, 20, 5).collect::<Vec<int>>() ==
assert!(range_step_inclusive(0, 20, 5).collect::<Vec<int>>() ==
vec![0, 5, 10, 15, 20]);
assert!(range_step_inclusive(20i, 0, -5).collect::<Vec<int>>() ==
assert!(range_step_inclusive(20, 0, -5).collect::<Vec<int>>() ==
vec![20, 15, 10, 5, 0]);
assert!(range_step_inclusive(20i, 0, -6).collect::<Vec<int>>() ==
assert!(range_step_inclusive(20, 0, -6).collect::<Vec<int>>() ==
vec![20, 14, 8, 2]);
assert!(range_step_inclusive(200u8, 255, 50).collect::<Vec<u8>>() ==
vec![200u8, 250]);
assert!(range_step_inclusive(200i, -5, 1).collect::<Vec<int>>() ==
assert!(range_step_inclusive(200, -5, 1).collect::<Vec<int>>() ==
vec![]);
assert!(range_step_inclusive(200i, 200, 1).collect::<Vec<int>>() ==
assert!(range_step_inclusive(200, 200, 1).collect::<Vec<int>>() ==
vec![200]);
}
#[test]
fn test_reverse() {
let mut ys = [1i, 2, 3, 4, 5];
let mut ys = [1, 2, 3, 4, 5];
ys.iter_mut().reverse_in_place();
assert!(ys == [5, 4, 3, 2, 1]);
}
#[test]
fn test_peekable_is_empty() {
let a = [1i];
let a = [1];
let mut it = a.iter().peekable();
assert!( !it.is_empty() );
it.next();
@ -821,16 +821,16 @@ fn test_min_max() {
let v: [int; 0] = [];
assert_eq!(v.iter().min_max(), NoElements);
let v = [1i];
let v = [1];
assert!(v.iter().min_max() == OneElement(&1));
let v = [1i, 2, 3, 4, 5];
let v = [1, 2, 3, 4, 5];
assert!(v.iter().min_max() == MinMax(&1, &5));
let v = [1i, 2, 3, 4, 5, 6];
let v = [1, 2, 3, 4, 5, 6];
assert!(v.iter().min_max() == MinMax(&1, &6));
let v = [1i, 1, 1, 1];
let v = [1, 1, 1, 1];
assert!(v.iter().min_max() == MinMax(&1, &1));
}
@ -839,10 +839,10 @@ fn test_min_max_result() {
let r: MinMaxResult<int> = NoElements;
assert_eq!(r.into_option(), None);
let r = OneElement(1i);
let r = OneElement(1);
assert_eq!(r.into_option(), Some((1,1)));
let r = MinMax(1i,2);
let r = MinMax(1,2);
assert_eq!(r.into_option(), Some((1,2)));
}
@ -904,7 +904,7 @@ fn bench_multiple_take(b: &mut Bencher) {
b.iter(|| {
let n = it.next().unwrap();
for _ in 0u..n {
it.take(it.next().unwrap()).all(|_| true);
it.clone().take(it.next().unwrap()).all(|_| true);
}
});
}

View File

@ -8,10 +8,10 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(unsafe_destructor, slicing_syntax)]
#![feature(unboxed_closures)]
#![feature(box_syntax)]
#![allow(unknown_features)] #![feature(int_uint)]
#![feature(int_uint)]
#![feature(unboxed_closures)]
#![feature(unsafe_destructor, slicing_syntax)]
extern crate core;
extern crate test;

View File

@ -70,8 +70,8 @@ fn align_of_val_basic() {
#[test]
fn test_swap() {
let mut x = 31337i;
let mut y = 42i;
let mut x = 31337;
let mut y = 42;
swap(&mut x, &mut y);
assert_eq!(x, 42);
assert_eq!(y, 31337);
@ -87,7 +87,7 @@ fn test_replace() {
#[test]
fn test_transmute_copy() {
assert_eq!(1u, unsafe { transmute_copy(&1i) });
assert_eq!(1u, unsafe { transmute_copy(&1) });
}
#[test]
@ -95,7 +95,7 @@ fn test_transmute() {
trait Foo {}
impl Foo for int {}
let a = box 100i as Box<Foo>;
let a = box 100 as Box<Foo>;
unsafe {
let x: ::core::raw::TraitObject = transmute(a);
assert!(*(x.data as *const int) == 100);
@ -146,7 +146,7 @@ fn trait_static_method_call(b: &mut Bencher) {
#[bench]
fn match_option_some(b: &mut Bencher) {
let x = Some(10i);
let x = Some(10);
b.iter(|| {
match x {
Some(y) => y,
@ -157,11 +157,11 @@ fn match_option_some(b: &mut Bencher) {
#[bench]
fn match_vec_pattern(b: &mut Bencher) {
let x = [1i,2,3,4,5,6];
let x = [1,2,3,4,5,6];
b.iter(|| {
match x {
[1,2,3,..] => 10i,
_ => 11i,
[1,2,3,..] => 10,
_ => 11,
}
});
}

View File

@ -16,7 +16,7 @@ use std::mem::size_of;
#[test]
fn test_create_nonzero_instance() {
let _a = unsafe {
NonZero::new(21i)
NonZero::new(21)
};
}
@ -28,14 +28,14 @@ fn test_size_nonzero_in_option() {
#[test]
fn test_match_on_nonzero_option() {
let a = Some(unsafe {
NonZero::new(42i)
NonZero::new(42)
});
match a {
Some(val) => assert_eq!(*val, 42),
None => panic!("unexpected None while matching on Some(NonZero(_))")
}
match unsafe { Some(NonZero::new(43i)) } {
match unsafe { Some(NonZero::new(43)) } {
Some(val) => assert_eq!(*val, 43),
None => panic!("unexpected None while matching on Some(NonZero(_))")
}
@ -52,9 +52,9 @@ fn test_match_option_empty_vec() {
#[test]
fn test_match_option_vec() {
let a = Some(vec![1i, 2, 3, 4]);
let a = Some(vec![1, 2, 3, 4]);
match a {
Some(v) => assert_eq!(v, vec![1i, 2, 3, 4]),
Some(v) => assert_eq!(v, vec![1, 2, 3, 4]),
None => panic!("unexpected None while matching on Some(vec![1, 2, 3, 4])")
}
}
@ -63,9 +63,9 @@ fn test_match_option_vec() {
fn test_match_option_rc() {
use std::rc::Rc;
let five = Rc::new(5i);
let five = Rc::new(5);
match Some(five) {
Some(r) => assert_eq!(*r, 5i),
Some(r) => assert_eq!(*r, 5),
None => panic!("unexpected None while matching on Some(Rc::new(5))")
}
}
@ -74,9 +74,9 @@ fn test_match_option_rc() {
fn test_match_option_arc() {
use std::sync::Arc;
let five = Arc::new(5i);
let five = Arc::new(5);
match Some(five) {
Some(a) => assert_eq!(*a, 5i),
Some(a) => assert_eq!(*a, 5),
None => panic!("unexpected None while matching on Some(Arc::new(5))")
}
}

View File

@ -151,15 +151,15 @@ mod tests {
#[test]
fn test_signed_checked_div() {
assert!(10i.checked_div(2) == Some(5));
assert!(5i.checked_div(0) == None);
assert!(10.checked_div(2) == Some(5));
assert!(5.checked_div(0) == None);
assert!(int::MIN.checked_div(-1) == None);
}
#[test]
fn test_from_str() {
fn from_str<T: ::std::str::FromStr>(t: &str) -> Option<T> {
::std::str::FromStr::from_str(t)
::std::str::FromStr::from_str(t).ok()
}
assert_eq!(from_str::<$T>("0"), Some(0 as $T));
assert_eq!(from_str::<$T>("3"), Some(3 as $T));
@ -180,26 +180,26 @@ mod tests {
#[test]
fn test_from_str_radix() {
assert_eq!(FromStrRadix::from_str_radix("123", 10), Some(123 as $T));
assert_eq!(FromStrRadix::from_str_radix("1001", 2), Some(9 as $T));
assert_eq!(FromStrRadix::from_str_radix("123", 8), Some(83 as $T));
assert_eq!(FromStrRadix::from_str_radix("123", 16), Some(291 as i32));
assert_eq!(FromStrRadix::from_str_radix("ffff", 16), Some(65535 as i32));
assert_eq!(FromStrRadix::from_str_radix("FFFF", 16), Some(65535 as i32));
assert_eq!(FromStrRadix::from_str_radix("z", 36), Some(35 as $T));
assert_eq!(FromStrRadix::from_str_radix("Z", 36), Some(35 as $T));
assert_eq!(FromStrRadix::from_str_radix("123", 10), Ok(123 as $T));
assert_eq!(FromStrRadix::from_str_radix("1001", 2), Ok(9 as $T));
assert_eq!(FromStrRadix::from_str_radix("123", 8), Ok(83 as $T));
assert_eq!(FromStrRadix::from_str_radix("123", 16), Ok(291 as i32));
assert_eq!(FromStrRadix::from_str_radix("ffff", 16), Ok(65535 as i32));
assert_eq!(FromStrRadix::from_str_radix("FFFF", 16), Ok(65535 as i32));
assert_eq!(FromStrRadix::from_str_radix("z", 36), Ok(35 as $T));
assert_eq!(FromStrRadix::from_str_radix("Z", 36), Ok(35 as $T));
assert_eq!(FromStrRadix::from_str_radix("-123", 10), Some(-123 as $T));
assert_eq!(FromStrRadix::from_str_radix("-1001", 2), Some(-9 as $T));
assert_eq!(FromStrRadix::from_str_radix("-123", 8), Some(-83 as $T));
assert_eq!(FromStrRadix::from_str_radix("-123", 16), Some(-291 as i32));
assert_eq!(FromStrRadix::from_str_radix("-ffff", 16), Some(-65535 as i32));
assert_eq!(FromStrRadix::from_str_radix("-FFFF", 16), Some(-65535 as i32));
assert_eq!(FromStrRadix::from_str_radix("-z", 36), Some(-35 as $T));
assert_eq!(FromStrRadix::from_str_radix("-Z", 36), Some(-35 as $T));
assert_eq!(FromStrRadix::from_str_radix("-123", 10), Ok(-123 as $T));
assert_eq!(FromStrRadix::from_str_radix("-1001", 2), Ok(-9 as $T));
assert_eq!(FromStrRadix::from_str_radix("-123", 8), Ok(-83 as $T));
assert_eq!(FromStrRadix::from_str_radix("-123", 16), Ok(-291 as i32));
assert_eq!(FromStrRadix::from_str_radix("-ffff", 16), Ok(-65535 as i32));
assert_eq!(FromStrRadix::from_str_radix("-FFFF", 16), Ok(-65535 as i32));
assert_eq!(FromStrRadix::from_str_radix("-z", 36), Ok(-35 as $T));
assert_eq!(FromStrRadix::from_str_radix("-Z", 36), Ok(-35 as $T));
assert_eq!(FromStrRadix::from_str_radix("Z", 35), None::<$T>);
assert_eq!(FromStrRadix::from_str_radix("-9", 2), None::<$T>);
assert_eq!(FromStrRadix::from_str_radix("Z", 35).ok(), None::<$T>);
assert_eq!(FromStrRadix::from_str_radix("-9", 2).ok(), None::<$T>);
}
}

View File

@ -40,11 +40,11 @@ pub fn test_num<T>(ten: T, two: T) where
+ Rem<Output=T> + Debug
+ Copy
{
assert_eq!(ten.add(two), cast(12i).unwrap());
assert_eq!(ten.sub(two), cast(8i).unwrap());
assert_eq!(ten.mul(two), cast(20i).unwrap());
assert_eq!(ten.div(two), cast(5i).unwrap());
assert_eq!(ten.rem(two), cast(0i).unwrap());
assert_eq!(ten.add(two), cast(12).unwrap());
assert_eq!(ten.sub(two), cast(8).unwrap());
assert_eq!(ten.mul(two), cast(20).unwrap());
assert_eq!(ten.div(two), cast(5).unwrap());
assert_eq!(ten.rem(two), cast(0).unwrap());
assert_eq!(ten.add(two), ten + two);
assert_eq!(ten.sub(two), ten - two);
@ -62,64 +62,64 @@ mod test {
#[test]
fn from_str_issue7588() {
let u : Option<u8> = from_str_radix("1000", 10);
let u : Option<u8> = from_str_radix("1000", 10).ok();
assert_eq!(u, None);
let s : Option<i16> = from_str_radix("80000", 10);
let s : Option<i16> = from_str_radix("80000", 10).ok();
assert_eq!(s, None);
let f : Option<f32> = from_str_radix("10000000000000000000000000000000000000000", 10);
let f : Option<f32> = from_str_radix("10000000000000000000000000000000000000000", 10).ok();
assert_eq!(f, Some(Float::infinity()));
let fe : Option<f32> = from_str_radix("1e40", 10);
let fe : Option<f32> = from_str_radix("1e40", 10).ok();
assert_eq!(fe, Some(Float::infinity()));
}
#[test]
fn test_from_str_radix_float() {
let x1 : Option<f64> = from_str_radix("-123.456", 10);
let x1 : Option<f64> = from_str_radix("-123.456", 10).ok();
assert_eq!(x1, Some(-123.456));
let x2 : Option<f32> = from_str_radix("123.456", 10);
let x2 : Option<f32> = from_str_radix("123.456", 10).ok();
assert_eq!(x2, Some(123.456));
let x3 : Option<f32> = from_str_radix("-0.0", 10);
let x3 : Option<f32> = from_str_radix("-0.0", 10).ok();
assert_eq!(x3, Some(-0.0));
let x4 : Option<f32> = from_str_radix("0.0", 10);
let x4 : Option<f32> = from_str_radix("0.0", 10).ok();
assert_eq!(x4, Some(0.0));
let x4 : Option<f32> = from_str_radix("1.0", 10);
let x4 : Option<f32> = from_str_radix("1.0", 10).ok();
assert_eq!(x4, Some(1.0));
let x5 : Option<f32> = from_str_radix("-1.0", 10);
let x5 : Option<f32> = from_str_radix("-1.0", 10).ok();
assert_eq!(x5, Some(-1.0));
}
#[test]
fn test_int_from_str_overflow() {
let mut i8_val: i8 = 127_i8;
assert_eq!("127".parse::<i8>(), Some(i8_val));
assert_eq!("128".parse::<i8>(), None);
assert_eq!("127".parse::<i8>().ok(), Some(i8_val));
assert_eq!("128".parse::<i8>().ok(), None);
i8_val += 1 as i8;
assert_eq!("-128".parse::<i8>(), Some(i8_val));
assert_eq!("-129".parse::<i8>(), None);
assert_eq!("-128".parse::<i8>().ok(), Some(i8_val));
assert_eq!("-129".parse::<i8>().ok(), None);
let mut i16_val: i16 = 32_767_i16;
assert_eq!("32767".parse::<i16>(), Some(i16_val));
assert_eq!("32768".parse::<i16>(), None);
assert_eq!("32767".parse::<i16>().ok(), Some(i16_val));
assert_eq!("32768".parse::<i16>().ok(), None);
i16_val += 1 as i16;
assert_eq!("-32768".parse::<i16>(), Some(i16_val));
assert_eq!("-32769".parse::<i16>(), None);
assert_eq!("-32768".parse::<i16>().ok(), Some(i16_val));
assert_eq!("-32769".parse::<i16>().ok(), None);
let mut i32_val: i32 = 2_147_483_647_i32;
assert_eq!("2147483647".parse::<i32>(), Some(i32_val));
assert_eq!("2147483648".parse::<i32>(), None);
assert_eq!("2147483647".parse::<i32>().ok(), Some(i32_val));
assert_eq!("2147483648".parse::<i32>().ok(), None);
i32_val += 1 as i32;
assert_eq!("-2147483648".parse::<i32>(), Some(i32_val));
assert_eq!("-2147483649".parse::<i32>(), None);
assert_eq!("-2147483648".parse::<i32>().ok(), Some(i32_val));
assert_eq!("-2147483649".parse::<i32>().ok(), None);
let mut i64_val: i64 = 9_223_372_036_854_775_807_i64;
assert_eq!("9223372036854775807".parse::<i64>(), Some(i64_val));
assert_eq!("9223372036854775808".parse::<i64>(), None);
assert_eq!("9223372036854775807".parse::<i64>().ok(), Some(i64_val));
assert_eq!("9223372036854775808".parse::<i64>().ok(), None);
i64_val += 1 as i64;
assert_eq!("-9223372036854775808".parse::<i64>(), Some(i64_val));
assert_eq!("-9223372036854775809".parse::<i64>(), None);
assert_eq!("-9223372036854775808".parse::<i64>().ok(), Some(i64_val));
assert_eq!("-9223372036854775809".parse::<i64>().ok(), None);
}
}

View File

@ -16,7 +16,7 @@ use core::clone::Clone;
#[test]
fn test_get_ptr() {
unsafe {
let x = box 0i;
let x = box 0;
let addr_x: *const int = mem::transmute(&*x);
let opt = Some(x);
let y = opt.unwrap();
@ -59,7 +59,7 @@ fn test_get_resource() {
}
}
let i = Rc::new(RefCell::new(0i));
let i = Rc::new(RefCell::new(0));
{
let x = r(i.clone());
let opt = Some(x);
@ -71,7 +71,7 @@ fn test_get_resource() {
#[test]
fn test_option_dance() {
let x = Some(());
let mut y = Some(5i);
let mut y = Some(5);
let mut y2 = 0;
for _x in x.iter() {
y2 = y.take().unwrap();
@ -89,12 +89,12 @@ fn test_option_too_much_dance() {
#[test]
fn test_and() {
let x: Option<int> = Some(1i);
assert_eq!(x.and(Some(2i)), Some(2));
let x: Option<int> = Some(1);
assert_eq!(x.and(Some(2)), Some(2));
assert_eq!(x.and(None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and(Some(2i)), None);
assert_eq!(x.and(Some(2)), None);
assert_eq!(x.and(None::<int>), None);
}
@ -133,7 +133,7 @@ fn test_or_else() {
#[test]
fn test_unwrap() {
assert_eq!(Some(1i).unwrap(), 1);
assert_eq!(Some(1).unwrap(), 1);
let s = Some("hello".to_string()).unwrap();
assert_eq!(s, "hello");
}
@ -172,7 +172,7 @@ fn test_unwrap_or_else() {
#[test]
fn test_iter() {
let val = 5i;
let val = 5;
let x = Some(val);
let mut it = x.iter();
@ -185,8 +185,8 @@ fn test_iter() {
#[test]
fn test_mut_iter() {
let val = 5i;
let new_val = 11i;
let val = 5;
let new_val = 11;
let mut x = Some(val);
{
@ -223,13 +223,13 @@ fn test_ord() {
/* FIXME(#20575)
#[test]
fn test_collect() {
let v: Option<Vec<int>> = (0i..0).map(|_| Some(0i)).collect();
let v: Option<Vec<int>> = (0..0).map(|_| Some(0i)).collect();
assert!(v == Some(vec![]));
let v: Option<Vec<int>> = (0i..3).map(|x| Some(x)).collect();
let v: Option<Vec<int>> = (0..3).map(|x| Some(x)).collect();
assert!(v == Some(vec![0, 1, 2]));
let v: Option<Vec<int>> = (0i..3).map(|x| {
let v: Option<Vec<int>> = (0..3).map(|x| {
if x > 1 { None } else { Some(x) }
}).collect();
assert!(v == None);

View File

@ -84,7 +84,7 @@ fn test_as_ref() {
assert_eq!(q.as_ref().unwrap(), &2);
// Lifetime inference
let u = 2i;
let u = 2;
{
let p: *const int = &u as *const _;
assert_eq!(p.as_ref().unwrap(), &2);
@ -102,7 +102,7 @@ fn test_as_mut() {
assert!(q.as_mut().unwrap() == &mut 2);
// Lifetime inference
let mut u = 2i;
let mut u = 2;
{
let p: *mut int = &mut u as *mut _;
assert!(p.as_mut().unwrap() == &mut 2);
@ -113,7 +113,7 @@ fn test_as_mut() {
#[test]
fn test_ptr_addition() {
unsafe {
let xs = repeat(5i).take(16).collect::<Vec<_>>();
let xs = repeat(5).take(16).collect::<Vec<_>>();
let mut ptr = xs.as_ptr();
let end = ptr.offset(16);
@ -131,7 +131,7 @@ fn test_ptr_addition() {
m_ptr = m_ptr.offset(1);
}
assert!(xs_mut == repeat(10i).take(16).collect::<Vec<_>>());
assert!(xs_mut == repeat(10).take(16).collect::<Vec<_>>());
}
}

View File

@ -13,11 +13,11 @@ pub fn op2() -> Result<int, &'static str> { Err("sadface") }
#[test]
pub fn test_and() {
assert_eq!(op1().and(Ok(667i)).unwrap(), 667);
assert_eq!(op1().and(Ok(667)).unwrap(), 667);
assert_eq!(op1().and(Err::<i32, &'static str>("bad")).unwrap_err(),
"bad");
assert_eq!(op2().and(Ok(667i)).unwrap_err(), "sadface");
assert_eq!(op2().and(Ok(667)).unwrap_err(), "sadface");
assert_eq!(op2().and(Err::<i32,&'static str>("bad")).unwrap_err(),
"sadface");
}
@ -68,20 +68,20 @@ pub fn test_impl_map_err() {
/* FIXME(#20575)
#[test]
fn test_collect() {
let v: Result<Vec<int>, ()> = (0i..0).map(|_| Ok::<int, ()>(0)).collect();
let v: Result<Vec<int>, ()> = (0..0).map(|_| Ok::<int, ()>(0)).collect();
assert!(v == Ok(vec![]));
let v: Result<Vec<int>, ()> = (0i..3).map(|x| Ok::<int, ()>(x)).collect();
let v: Result<Vec<int>, ()> = (0..3).map(|x| Ok::<int, ()>(x)).collect();
assert!(v == Ok(vec![0, 1, 2]));
let v: Result<Vec<int>, int> = (0i..3).map(|x| {
let v: Result<Vec<int>, int> = (0..3).map(|x| {
if x > 1 { Err(x) } else { Ok(x) }
}).collect();
assert!(v == Err(2));
// test that it does not take more elements than it needs
let mut functions: [Box<Fn() -> Result<(), int>>; 3] =
[box || Ok(()), box || Err(1i), box || panic!()];
[box || Ok(()), box || Err(1), box || panic!()];
let v: Result<Vec<()>, int> = functions.iter_mut().map(|f| (*f)()).collect();
assert!(v == Err(1));
@ -101,7 +101,7 @@ pub fn test_fmt_default() {
#[test]
pub fn test_unwrap_or() {
let ok: Result<int, &'static str> = Ok(100i);
let ok: Result<int, &'static str> = Ok(100);
let ok_err: Result<int, &'static str> = Err("Err");
assert_eq!(ok.unwrap_or(50), 100);
@ -112,7 +112,7 @@ pub fn test_unwrap_or() {
pub fn test_unwrap_or_else() {
fn handler(msg: &'static str) -> int {
if msg == "I got this." {
50i
50
} else {
panic!("BadBad")
}
@ -130,7 +130,7 @@ pub fn test_unwrap_or_else() {
pub fn test_unwrap_or_else_panic() {
fn handler(msg: &'static str) -> int {
if msg == "I got this." {
50i
50
} else {
panic!("BadBad")
}

View File

@ -12,25 +12,25 @@ use core::result::Result::{Ok, Err};
#[test]
fn binary_search_not_found() {
let b = [1i, 2, 4, 6, 8, 9];
let b = [1, 2, 4, 6, 8, 9];
assert!(b.binary_search_by(|v| v.cmp(&6)) == Ok(3));
let b = [1i, 2, 4, 6, 8, 9];
let b = [1, 2, 4, 6, 8, 9];
assert!(b.binary_search_by(|v| v.cmp(&5)) == Err(3));
let b = [1i, 2, 4, 6, 7, 8, 9];
let b = [1, 2, 4, 6, 7, 8, 9];
assert!(b.binary_search_by(|v| v.cmp(&6)) == Ok(3));
let b = [1i, 2, 4, 6, 7, 8, 9];
let b = [1, 2, 4, 6, 7, 8, 9];
assert!(b.binary_search_by(|v| v.cmp(&5)) == Err(3));
let b = [1i, 2, 4, 6, 8, 9];
let b = [1, 2, 4, 6, 8, 9];
assert!(b.binary_search_by(|v| v.cmp(&8)) == Ok(4));
let b = [1i, 2, 4, 6, 8, 9];
let b = [1, 2, 4, 6, 8, 9];
assert!(b.binary_search_by(|v| v.cmp(&7)) == Err(4));
let b = [1i, 2, 4, 6, 7, 8, 9];
let b = [1, 2, 4, 6, 7, 8, 9];
assert!(b.binary_search_by(|v| v.cmp(&8)) == Ok(5));
let b = [1i, 2, 4, 5, 6, 8, 9];
let b = [1, 2, 4, 5, 6, 8, 9];
assert!(b.binary_search_by(|v| v.cmp(&7)) == Err(5));
let b = [1i, 2, 4, 5, 6, 8, 9];
let b = [1, 2, 4, 5, 6, 8, 9];
assert!(b.binary_search_by(|v| v.cmp(&0)) == Err(0));
let b = [1i, 2, 4, 5, 6, 8];
let b = [1, 2, 4, 5, 6, 8];
assert!(b.binary_search_by(|v| v.cmp(&9)) == Err(6));
}

View File

@ -10,9 +10,9 @@
#[test]
fn test_bool_from_str() {
assert_eq!("true".parse(), Some(true));
assert_eq!("false".parse(), Some(false));
assert_eq!("not even a boolean".parse::<bool>(), None);
assert_eq!("true".parse().ok(), Some(true));
assert_eq!("false".parse().ok(), Some(false));
assert_eq!("not even a boolean".parse::<bool>().ok(), None);
}
fn check_contains_all_substrings(s: &str) {

View File

@ -12,7 +12,7 @@ use std::cmp::Ordering::{Equal, Less, Greater};
#[test]
fn test_clone() {
let a = (1i, "2");
let a = (1, "2");
let b = a.clone();
assert_eq!(a, b);
}
@ -59,10 +59,10 @@ fn test_tuple_cmp() {
#[test]
fn test_show() {
let s = format!("{:?}", (1i,));
let s = format!("{:?}", (1,));
assert_eq!(s, "(1,)");
let s = format!("{:?}", (1i, true));
let s = format!("{:?}", (1, true));
assert_eq!(s, "(1, true)");
let s = format!("{:?}", (1i, "hi", true));
let s = format!("{:?}", (1, "hi", true));
assert_eq!(s, "(1, \"hi\", true)");
}

View File

@ -16,17 +16,17 @@
#![crate_name = "flate"]
#![unstable(feature = "rustc_private")]
#![feature(staged_api)]
#![staged_api]
#![allow(unknown_features)] #![feature(int_uint)]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(hash)]
#![feature(core)]
#![feature(int_uint)]
#![feature(libc)]
#![feature(staged_api)]
#[cfg(test)] #[macro_use] extern crate log;

View File

@ -16,7 +16,6 @@
#![crate_name = "fmt_macros"]
#![unstable(feature = "rustc_private")]
#![feature(staged_api)]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
@ -25,10 +24,10 @@
html_root_url = "http://doc.rust-lang.org/nightly/",
html_playground_url = "http://play.rust-lang.org/")]
#![cfg_attr(stage0, feature(core))]
#![feature(int_uint)]
#![feature(slicing_syntax)]
#![allow(unknown_features)] #![feature(int_uint)]
#![feature(collections)]
#![feature(core)]
#![feature(staged_api)]
#![feature(unicode)]
pub use self::Piece::*;

View File

@ -80,7 +80,6 @@
#![crate_name = "getopts"]
#![unstable(feature = "rustc_private",
reason = "use the crates.io `getopts` library instead")]
#![feature(staged_api)]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
@ -88,11 +87,13 @@
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/",
html_playground_url = "http://play.rust-lang.org/")]
#![feature(slicing_syntax)]
#![allow(unknown_features)] #![feature(int_uint)]
#![deny(missing_docs)]
#![feature(collections)]
#![feature(core)]
#![feature(int_uint)]
#![feature(slicing_syntax)]
#![feature(staged_api)]
#![cfg_attr(test, feature(rustc_private))]
#[cfg(test)] #[macro_use] extern crate log;

View File

@ -274,7 +274,7 @@
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(slicing_syntax)]
#![allow(unknown_features)] #![feature(int_uint)]
#![feature(int_uint)]
#![feature(collections)]
#![feature(core)]
#![feature(io)]
@ -362,19 +362,19 @@ impl<'a> Id<'a> {
///
/// Passing an invalid string (containing spaces, brackets,
/// quotes, ...) will return an empty `Err` value.
pub fn new<Name: IntoCow<'a, String, str>>(name: Name) -> Option<Id<'a>> {
pub fn new<Name: IntoCow<'a, String, str>>(name: Name) -> Result<Id<'a>, ()> {
let name = name.into_cow();
{
let mut chars = name.chars();
match chars.next() {
Some(c) if is_letter_or_underscore(c) => { ; },
_ => return None
_ => return Err(())
}
if !chars.all(is_constituent) {
return None
return Err(())
}
}
return Some(Id{ name: name });
return Ok(Id{ name: name });
fn is_letter_or_underscore(c: char) -> bool {
in_range('a', c, 'z') || in_range('A', c, 'Z') || c == '_'
@ -878,8 +878,8 @@ r#"digraph syntax_tree {
fn simple_id_construction() {
let id1 = Id::new("hello");
match id1 {
Some(_) => {;},
None => panic!("'hello' is not a valid value for id anymore")
Ok(_) => {;},
Err(..) => panic!("'hello' is not a valid value for id anymore")
}
}
@ -887,8 +887,8 @@ r#"digraph syntax_tree {
fn badly_formatted_id() {
let id2 = Id::new("Weird { struct : ure } !!!");
match id2 {
Some(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"),
None => {;}
Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"),
Err(..) => {;}
}
}
}

View File

@ -15,7 +15,7 @@
#![cfg_attr(not(feature = "cargo-build"), feature(staged_api))]
#![cfg_attr(not(feature = "cargo-build"), staged_api)]
#![cfg_attr(not(feature = "cargo-build"), feature(core))]
#![allow(unknown_features)] #![feature(int_uint)]
#![feature(int_uint)]
#![no_std]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",

View File

@ -22,7 +22,7 @@ pub static LOG_LEVEL_NAMES: [&'static str; 4] = ["ERROR", "WARN", "INFO",
/// Parse an individual log level that is either a number or a symbolic log level
fn parse_log_level(level: &str) -> Option<u32> {
level.parse::<u32>().or_else(|| {
level.parse::<u32>().ok().or_else(|| {
let pos = LOG_LEVEL_NAMES.iter().position(|&name| name.eq_ignore_ascii_case(level));
pos.map(|p| p as u32 + 1)
}).map(|p| cmp::min(p, ::MAX_LOG_LEVEL))

View File

@ -20,7 +20,7 @@
//! error!("this is printed by default");
//!
//! if log_enabled!(log::INFO) {
//! let x = 3i * 4i; // expensive computation
//! let x = 3 * 4; // expensive computation
//! info!("the answer was: {:?}", x);
//! }
//! }
@ -158,7 +158,6 @@
#![crate_name = "log"]
#![unstable(feature = "rustc_private",
reason = "use the crates.io `log` library instead")]
#![feature(staged_api)]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
@ -166,17 +165,15 @@
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/",
html_playground_url = "http://play.rust-lang.org/")]
#![deny(missing_docs)]
#![allow(unknown_features)]
#![feature(staged_api)]
#![feature(slicing_syntax)]
#![feature(box_syntax)]
#![allow(unknown_features)] #![feature(int_uint)]
#![deny(missing_docs)]
#![feature(collections)]
#![feature(int_uint)]
#![feature(core)]
#![feature(io)]
#![feature(os)]
#![feature(rustc_private)]
#![feature(std_misc)]
use std::cell::RefCell;

View File

@ -119,7 +119,7 @@ macro_rules! warn {
/// #[macro_use] extern crate log;
///
/// fn main() {
/// let ret = 3i;
/// let ret = 3;
/// info!("this function is about to return: {}", ret);
/// }
/// ```
@ -145,7 +145,7 @@ macro_rules! info {
/// #[macro_use] extern crate log;
///
/// fn main() {
/// debug!("x = {x}, y = {y}", x=10i, y=20i);
/// debug!("x = {x}, y = {y}", x=10, y=20);
/// }
/// ```
///

View File

@ -311,36 +311,36 @@ mod tests {
}}
}
t!(vec!(Weighted { weight: 1, item: 10i}), [10]);
t!(vec!(Weighted { weight: 1, item: 10}), [10]);
// skip some
t!(vec!(Weighted { weight: 0, item: 20i},
Weighted { weight: 2, item: 21i},
Weighted { weight: 0, item: 22i},
Weighted { weight: 1, item: 23i}),
t!(vec!(Weighted { weight: 0, item: 20},
Weighted { weight: 2, item: 21},
Weighted { weight: 0, item: 22},
Weighted { weight: 1, item: 23}),
[21,21, 23]);
// different weights
t!(vec!(Weighted { weight: 4, item: 30i},
Weighted { weight: 3, item: 31i}),
t!(vec!(Weighted { weight: 4, item: 30},
Weighted { weight: 3, item: 31}),
[30,30,30,30, 31,31,31]);
// check that we're binary searching
// correctly with some vectors of odd
// length.
t!(vec!(Weighted { weight: 1, item: 40i},
Weighted { weight: 1, item: 41i},
Weighted { weight: 1, item: 42i},
Weighted { weight: 1, item: 43i},
Weighted { weight: 1, item: 44i}),
t!(vec!(Weighted { weight: 1, item: 40},
Weighted { weight: 1, item: 41},
Weighted { weight: 1, item: 42},
Weighted { weight: 1, item: 43},
Weighted { weight: 1, item: 44}),
[40, 41, 42, 43, 44]);
t!(vec!(Weighted { weight: 1, item: 50i},
Weighted { weight: 1, item: 51i},
Weighted { weight: 1, item: 52i},
Weighted { weight: 1, item: 53i},
Weighted { weight: 1, item: 54i},
Weighted { weight: 1, item: 55i},
Weighted { weight: 1, item: 56i}),
t!(vec!(Weighted { weight: 1, item: 50},
Weighted { weight: 1, item: 51},
Weighted { weight: 1, item: 52},
Weighted { weight: 1, item: 53},
Weighted { weight: 1, item: 54},
Weighted { weight: 1, item: 55},
Weighted { weight: 1, item: 56}),
[50, 51, 52, 53, 54, 55, 56]);
}
@ -350,15 +350,15 @@ mod tests {
}
#[test] #[should_fail]
fn test_weighted_choice_zero_weight() {
WeightedChoice::new(&mut [Weighted { weight: 0, item: 0i},
Weighted { weight: 0, item: 1i}]);
WeightedChoice::new(&mut [Weighted { weight: 0, item: 0},
Weighted { weight: 0, item: 1}]);
}
#[test] #[should_fail]
fn test_weighted_choice_weight_overflows() {
let x = (-1) as uint / 2; // x + x + 2 is the overflow
WeightedChoice::new(&mut [Weighted { weight: x, item: 0i },
Weighted { weight: 1, item: 1i },
Weighted { weight: x, item: 2i },
Weighted { weight: 1, item: 3i }]);
WeightedChoice::new(&mut [Weighted { weight: x, item: 0 },
Weighted { weight: 1, item: 1 },
Weighted { weight: x, item: 2 },
Weighted { weight: 1, item: 3 }]);
}
}

View File

@ -171,12 +171,12 @@ mod tests {
#[should_fail]
#[test]
fn test_range_bad_limits_equal() {
Range::new(10i, 10i);
Range::new(10, 10);
}
#[should_fail]
#[test]
fn test_range_bad_limits_flipped() {
Range::new(10i, 5i);
Range::new(10, 5);
}
#[test]

View File

@ -22,7 +22,7 @@
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/",
html_playground_url = "http://play.rust-lang.org/")]
#![allow(unknown_features)] #![feature(int_uint)]
#![feature(int_uint)]
#![no_std]
#![unstable(feature = "rand")]
#![feature(staged_api)]
@ -152,7 +152,7 @@ pub trait Rng : Sized {
// (3) adds more `unsafe` that needs to be checked, (4)
// probably doesn't give much performance gain if
// optimisations are on.
let mut count = 0i;
let mut count = 0;
let mut num = 0;
for byte in dest.iter_mut() {
if count == 0 {
@ -269,7 +269,7 @@ pub trait Rng : Sized {
/// ```
/// use std::rand::{thread_rng, Rng};
///
/// let choices = [1i, 2, 4, 8, 16, 32];
/// let choices = [1, 2, 4, 8, 16, 32];
/// let mut rng = thread_rng();
/// println!("{:?}", rng.choose(&choices));
/// assert_eq!(rng.choose(&choices[..0]), None);
@ -290,7 +290,7 @@ pub trait Rng : Sized {
/// use std::rand::{thread_rng, Rng};
///
/// let mut rng = thread_rng();
/// let mut y = [1i, 2, 3];
/// let mut y = [1, 2, 3];
/// rng.shuffle(&mut y);
/// println!("{:?}", y.as_slice());
/// rng.shuffle(&mut y);
@ -498,6 +498,8 @@ mod std {
pub use core::{option, fmt}; // panic!()
pub use core::clone; // derive Clone
pub use core::marker;
// for-loops
pub use core::iter;
}
#[cfg(test)]

View File

@ -17,7 +17,6 @@
#![crate_name = "rbml"]
#![unstable(feature = "rustc_private")]
#![feature(staged_api)]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
@ -25,13 +24,14 @@
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/",
html_playground_url = "http://play.rust-lang.org/")]
#![allow(unknown_features)]
#![feature(slicing_syntax)]
#![allow(unknown_features)] #![feature(int_uint)]
#![feature(collections)]
#![feature(core)]
#![feature(int_uint)]
#![feature(io)]
#![feature(rustc_private)]
#![feature(slicing_syntax)]
#![feature(staged_api)]
extern crate serialize;
#[macro_use] extern crate log;

View File

@ -16,7 +16,6 @@
#![crate_name = "rustc"]
#![unstable(feature = "rustc_private")]
#![feature(staged_api)]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
@ -24,22 +23,24 @@
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![allow(unknown_features)]
#![feature(quote)]
#![feature(slicing_syntax, unsafe_destructor)]
#![cfg_attr(not(stage0), allow(unused_mut))] // NOTE: remove after stage0 snap
#![feature(box_syntax)]
#![allow(unknown_features)] #![feature(int_uint)]
#![feature(rustc_diagnostic_macros)]
#![feature(collections)]
#![feature(core)]
#![feature(hash)]
#![feature(int_uint)]
#![feature(io)]
#![feature(libc)]
#![feature(os)]
#![feature(path)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(slicing_syntax, unsafe_destructor)]
#![feature(staged_api)]
#![feature(std_misc)]
#![feature(unicode)]
#![feature(hash)]
#![cfg_attr(test, feature(test))]
extern crate arena;

View File

@ -254,7 +254,7 @@ impl LintPass for TypeLimits {
let lit_val: f64 = match lit.node {
ast::LitFloat(ref v, _) |
ast::LitFloatUnsuffixed(ref v) => {
match v.parse() {
match v.parse().ok() {
Some(f) => f,
None => return
}
@ -493,7 +493,7 @@ pub struct BoxPointers;
impl BoxPointers {
fn check_heap_type<'a, 'tcx>(&self, cx: &Context<'a, 'tcx>,
span: Span, ty: Ty<'tcx>) {
let mut n_uniq = 0i;
let mut n_uniq = 0u;
ty::fold_ty(cx.tcx, ty, |t| {
match t.sty {
ty::ty_uniq(_) => {
@ -938,6 +938,34 @@ declare_lint! {
pub struct NonSnakeCase;
impl NonSnakeCase {
fn to_snake_case(mut str: &str) -> String {
let mut words = vec![];
// Preserve leading underscores
str = str.trim_left_matches(|&mut: c: char| {
if c == '_' {
words.push(String::new());
true
} else { false }
});
for s in str.split('_') {
let mut last_upper = false;
let mut buf = String::new();
if s.is_empty() { continue; }
for ch in s.chars() {
if !buf.is_empty() && buf != "'"
&& ch.is_uppercase()
&& !last_upper {
words.push(buf);
buf = String::new();
}
last_upper = ch.is_uppercase();
buf.push(ch.to_lowercase());
}
words.push(buf);
}
words.connect("_")
}
fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
fn is_snake_case(ident: ast::Ident) -> bool {
let ident = token::get_ident(ident);
@ -948,41 +976,28 @@ impl NonSnakeCase {
let mut allow_underscore = true;
ident.chars().all(|c| {
allow_underscore = match c {
c if c.is_lowercase() || c.is_numeric() => true,
'_' if allow_underscore => false,
'_' if !allow_underscore => return false,
'_' => false,
c if !c.is_uppercase() => true,
_ => return false,
};
true
})
}
fn to_snake_case(str: &str) -> String {
let mut words = vec![];
for s in str.split('_') {
let mut last_upper = false;
let mut buf = String::new();
if s.is_empty() { continue; }
for ch in s.chars() {
if !buf.is_empty() && buf != "'"
&& ch.is_uppercase()
&& !last_upper {
words.push(buf);
buf = String::new();
}
last_upper = ch.is_uppercase();
buf.push(ch.to_lowercase());
}
words.push(buf);
}
words.connect("_")
}
let s = token::get_ident(ident);
if !is_snake_case(ident) {
cx.span_lint(NON_SNAKE_CASE, span,
&format!("{} `{}` should have a snake case name such as `{}`",
sort, s, to_snake_case(s.get()))[]);
let sc = NonSnakeCase::to_snake_case(s.get());
if sc != s.get() {
cx.span_lint(NON_SNAKE_CASE, span,
&*format!("{} `{}` should have a snake case name such as `{}`",
sort, s, sc));
} else {
cx.span_lint(NON_SNAKE_CASE, span,
&*format!("{} `{}` should have a snake case name",
sort, s));
}
}
}
}
@ -1050,6 +1065,26 @@ declare_lint! {
#[derive(Copy)]
pub struct NonUpperCaseGlobals;
impl NonUpperCaseGlobals {
fn check_upper_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
let s = token::get_ident(ident);
if s.get().chars().any(|c| c.is_lowercase()) {
let uc: String = NonSnakeCase::to_snake_case(s.get()).chars()
.map(|c| c.to_uppercase()).collect();
if uc != s.get() {
cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
format!("{} `{}` should have an upper case name such as `{}`",
sort, s, uc).as_slice());
} else {
cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
format!("{} `{}` should have an upper case name",
sort, s).as_slice());
}
}
}
}
impl LintPass for NonUpperCaseGlobals {
fn get_lints(&self) -> LintArray {
lint_array!(NON_UPPER_CASE_GLOBALS)
@ -1058,19 +1093,11 @@ impl LintPass for NonUpperCaseGlobals {
fn check_item(&mut self, cx: &Context, it: &ast::Item) {
match it.node {
// only check static constants
ast::ItemStatic(_, ast::MutImmutable, _) |
ast::ItemStatic(_, ast::MutImmutable, _) => {
NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span);
}
ast::ItemConst(..) => {
let s = token::get_ident(it.ident);
// check for lowercase letters rather than non-uppercase
// ones (some scripts don't have a concept of
// upper/lowercase)
if s.get().chars().any(|c| c.is_lowercase()) {
cx.span_lint(NON_UPPER_CASE_GLOBALS, it.span,
&format!("static constant `{}` should have an uppercase name \
such as `{}`",
s.get(), &s.get().chars().map(|c| c.to_uppercase())
.collect::<String>()[])[]);
}
NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span);
}
_ => {}
}
@ -1080,14 +1107,8 @@ impl LintPass for NonUpperCaseGlobals {
// Lint for constants that look like binding identifiers (#7526)
match (&p.node, cx.tcx.def_map.borrow().get(&p.id)) {
(&ast::PatIdent(_, ref path1, _), Some(&def::DefConst(..))) => {
let s = token::get_ident(path1.node);
if s.get().chars().any(|c| c.is_lowercase()) {
cx.span_lint(NON_UPPER_CASE_GLOBALS, path1.span,
&format!("static constant in pattern `{}` should have an uppercase \
name such as `{}`",
s.get(), &s.get().chars().map(|c| c.to_uppercase())
.collect::<String>()[])[]);
}
NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern",
path1.node, p.span);
}
_ => {}
}
@ -1164,6 +1185,7 @@ impl LintPass for UnusedParens {
ast::MatchSource::Normal => (head, "`match` head expression", true),
ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
ast::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
},
ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
ast::ExprAssign(_, ref value) => (value, "assigned value", false),

Some files were not shown because too many files have changed in this diff Show More