auto merge of #13443 : alexcrichton/rust/rollup, r=alexcrichton

Closes #13441 (debuginfo: Fixes and improvements for #12840, #12886, and #13213)
Closes #13433 (Remove references to @Trait from a compiler error message)
Closes #13430 (Fix outdated lint warning about inner attribute)
Closes #13425 (Remove a pile of (mainly) internal `~[]` uses)
Closes #13419 (Stop using transmute_mut in RefCell)
Closes #13417 (Remove an unnecessary file `src/libnative/io/p`.)
Closes #13409 (Closing assorted resolve bugs)
Closes #13406 (Generalized the pretty-print entry points to support `-o <file>`.)
Closes #13403 (test: Add a test for #7663)
Closes #13402 (rustdoc: Prune the paths that do not appear in the index.)
Closes #13396 (rustc: Remove absolute rpaths)
Closes #13371 (Rename ast::Purity and ast::Impure Function. Closes #7287)
Closes #13350 (collections: replace all ~[T] with Vec<T>.)
This commit is contained in:
bors 2014-04-10 15:31:55 -07:00
commit 0156af156d
107 changed files with 1127 additions and 648 deletions

View File

@ -269,6 +269,7 @@ LIB_DOC_DEP_$(1) = $$(CRATEFILE_$(1)) $$(RSINPUTS_$(1))
endif
$(2) += doc/$(1)/index.html
doc/$(1)/index.html: CFG_COMPILER_HOST_TRIPLE = $(CFG_TARGET)
doc/$(1)/index.html: $$(LIB_DOC_DEP_$(1))
@$$(call E, rustdoc $$@)
$$(Q)$$(RUSTDOC) --cfg dox --cfg stage2 $$<

View File

@ -358,7 +358,6 @@ CFGFLAG$(1)_T_$(2)_H_$(3) = stage1
endif
endif
ifdef CFG_DISABLE_RPATH
ifeq ($$(OSTYPE_$(3)),apple-darwin)
RPATH_VAR$(1)_T_$(2)_H_$(3) := \
DYLD_LIBRARY_PATH="$$$$DYLD_LIBRARY_PATH:$$(CURDIR)/$$(HLIB$(1)_H_$(3))"
@ -366,9 +365,6 @@ else
RPATH_VAR$(1)_T_$(2)_H_$(3) := \
LD_LIBRARY_PATH="$$$$LD_LIBRARY_PATH:$$(CURDIR)/$$(HLIB$(1)_H_$(3))"
endif
else
RPATH_VAR$(1)_T_$(2)_H_$(3) :=
endif
STAGE$(1)_T_$(2)_H_$(3) := \
$$(Q)$$(RPATH_VAR$(1)_T_$(2)_H_$(3)) \

View File

@ -451,7 +451,7 @@ fn run_debuginfo_test(config: &config, props: &TestProps, testfile: &Path) {
let options_to_remove = [~"-O", ~"-g", ~"--debuginfo"];
let new_options = split_maybe_args(options).move_iter()
.filter(|x| !options_to_remove.contains(x))
.collect::<~[~str]>()
.collect::<Vec<~str>>()
.connect(" ");
Some(new_options)
}

View File

@ -117,13 +117,13 @@ mod tests {
words.push(r.gen_vec::<u8>(range));
}
for _ in range(0, 20) {
let mut input = ~[];
let mut input = vec![];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()).as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input).expect("deflation failed");
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),

View File

@ -53,7 +53,7 @@
//!
//! let program = args[0].clone();
//!
//! let opts = ~[
//! let opts = [
//! optopt("o", "", "set output file name", "NAME"),
//! optflag("h", "help", "print this help menu")
//! ];

View File

@ -31,6 +31,8 @@
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://static.rust-lang.org/doc/master")]
#![deny(deprecated_owned_vector)]
use std::cell::Cell;
use std::{cmp, os, path};
use std::io::fs;
@ -245,26 +247,26 @@ impl Pattern {
*/
pub fn new(pattern: &str) -> Pattern {
let chars = pattern.chars().collect::<~[_]>();
let chars = pattern.chars().collect::<Vec<_>>();
let mut tokens = Vec::new();
let mut i = 0;
while i < chars.len() {
match chars[i] {
match *chars.get(i) {
'?' => {
tokens.push(AnyChar);
i += 1;
}
'*' => {
// *, **, ***, ****, ... are all equivalent
while i < chars.len() && chars[i] == '*' {
while i < chars.len() && *chars.get(i) == '*' {
i += 1;
}
tokens.push(AnySequence);
}
'[' => {
if i <= chars.len() - 4 && chars[i + 1] == '!' {
if i <= chars.len() - 4 && *chars.get(i + 1) == '!' {
match chars.slice_from(i + 3).position_elem(&']') {
None => (),
Some(j) => {
@ -276,7 +278,7 @@ impl Pattern {
}
}
}
else if i <= chars.len() - 3 && chars[i + 1] != '!' {
else if i <= chars.len() - 3 && *chars.get(i + 1) != '!' {
match chars.slice_from(i + 2).position_elem(&']') {
None => (),
Some(j) => {

View File

@ -27,11 +27,11 @@ pub fn event_loop() -> ~EventLoop:Send {
}
struct BasicLoop {
work: ~[proc():Send], // pending work
work: Vec<proc():Send>, // pending work
idle: Option<*mut BasicPausable>, // only one is allowed
remotes: ~[(uint, ~Callback:Send)],
remotes: Vec<(uint, ~Callback:Send)>,
next_remote: uint,
messages: Exclusive<~[Message]>,
messages: Exclusive<Vec<Message>>,
}
enum Message { RunRemote(uint), RemoveRemote(uint) }
@ -39,18 +39,18 @@ enum Message { RunRemote(uint), RemoveRemote(uint) }
impl BasicLoop {
fn new() -> BasicLoop {
BasicLoop {
work: ~[],
work: vec![],
idle: None,
next_remote: 0,
remotes: ~[],
messages: Exclusive::new(~[]),
remotes: vec![],
messages: Exclusive::new(vec![]),
}
}
/// Process everything in the work queue (continually)
fn work(&mut self) {
while self.work.len() > 0 {
for work in replace(&mut self.work, ~[]).move_iter() {
for work in replace(&mut self.work, vec![]).move_iter() {
work();
}
}
@ -60,7 +60,7 @@ impl BasicLoop {
let messages = unsafe {
self.messages.with(|messages| {
if messages.len() > 0 {
Some(replace(messages, ~[]))
Some(replace(messages, vec![]))
} else {
None
}
@ -165,12 +165,12 @@ impl EventLoop for BasicLoop {
}
struct BasicRemote {
queue: Exclusive<~[Message]>,
queue: Exclusive<Vec<Message>>,
id: uint,
}
impl BasicRemote {
fn new(queue: Exclusive<~[Message]>, id: uint) -> BasicRemote {
fn new(queue: Exclusive<Vec<Message>>, id: uint) -> BasicRemote {
BasicRemote { queue: queue, id: id }
}
}

View File

@ -195,6 +195,7 @@
// NB this does *not* include globs, please keep it that way.
#![feature(macro_rules, phase)]
#![allow(visible_private_types)]
#![deny(deprecated_owned_vector)]
#[cfg(test)] #[phase(syntax, link)] extern crate log;
#[cfg(test)] extern crate rustuv;
@ -209,7 +210,6 @@ use std::rt;
use std::sync::atomics::{SeqCst, AtomicUint, INIT_ATOMIC_UINT};
use std::sync::deque;
use std::task::TaskOpts;
use std::slice;
use std::sync::arc::UnsafeArc;
use sched::{Shutdown, Scheduler, SchedHandle, TaskFromFriend, NewNeighbor};
@ -318,9 +318,9 @@ impl PoolConfig {
/// used to keep the pool alive and also reap the status from the pool.
pub struct SchedPool {
id: uint,
threads: ~[Thread<()>],
handles: ~[SchedHandle],
stealers: ~[deque::Stealer<~task::GreenTask>],
threads: Vec<Thread<()>>,
handles: Vec<SchedHandle>,
stealers: Vec<deque::Stealer<~task::GreenTask>>,
next_friend: uint,
stack_pool: StackPool,
deque_pool: deque::BufferPool<~task::GreenTask>,
@ -356,9 +356,9 @@ impl SchedPool {
// The pool of schedulers that will be returned from this function
let (p, state) = TaskState::new();
let mut pool = SchedPool {
threads: ~[],
handles: ~[],
stealers: ~[],
threads: vec![],
handles: vec![],
stealers: vec![],
id: unsafe { POOL_ID.fetch_add(1, SeqCst) },
sleepers: SleeperList::new(),
stack_pool: StackPool::new(),
@ -371,8 +371,14 @@ impl SchedPool {
// Create a work queue for each scheduler, ntimes. Create an extra
// for the main thread if that flag is set. We won't steal from it.
let arr = slice::from_fn(nscheds, |_| pool.deque_pool.deque());
let (workers, stealers) = slice::unzip(arr.move_iter());
let mut workers = Vec::with_capacity(nscheds);
let mut stealers = Vec::with_capacity(nscheds);
for _ in range(0, nscheds) {
let (w, s) = pool.deque_pool.deque();
workers.push(w);
stealers.push(s);
}
pool.stealers = stealers;
// Now that we've got all our work queues, create one scheduler per
@ -420,7 +426,7 @@ impl SchedPool {
}
// Jettison the task away!
self.handles[idx].send(TaskFromFriend(task));
self.handles.get_mut(idx).send(TaskFromFriend(task));
}
/// Spawns a new scheduler into this M:N pool. A handle is returned to the
@ -466,7 +472,7 @@ impl SchedPool {
/// This only waits for all tasks in *this pool* of schedulers to exit, any
/// native tasks or extern pools will not be waited on
pub fn shutdown(mut self) {
self.stealers = ~[];
self.stealers = vec![];
// Wait for everyone to exit. We may have reached a 0-task count
// multiple times in the past, meaning there could be several buffered
@ -478,10 +484,10 @@ impl SchedPool {
}
// Now that everyone's gone, tell everything to shut down.
for mut handle in replace(&mut self.handles, ~[]).move_iter() {
for mut handle in replace(&mut self.handles, vec![]).move_iter() {
handle.send(Shutdown);
}
for thread in replace(&mut self.threads, ~[]).move_iter() {
for thread in replace(&mut self.threads, vec![]).move_iter() {
thread.join();
}
}

View File

@ -49,7 +49,7 @@ pub struct Scheduler {
work_queue: deque::Worker<~GreenTask>,
/// Work queues for the other schedulers. These are created by
/// cloning the core work queues.
work_queues: ~[deque::Stealer<~GreenTask>],
work_queues: Vec<deque::Stealer<~GreenTask>>,
/// The queue of incoming messages from other schedulers.
/// These are enqueued by SchedHandles after which a remote callback
/// is triggered to handle the message.
@ -125,7 +125,7 @@ impl Scheduler {
pub fn new(pool_id: uint,
event_loop: ~EventLoop:Send,
work_queue: deque::Worker<~GreenTask>,
work_queues: ~[deque::Stealer<~GreenTask>],
work_queues: Vec<deque::Stealer<~GreenTask>>,
sleeper_list: SleeperList,
state: TaskState)
-> Scheduler {
@ -138,7 +138,7 @@ impl Scheduler {
pub fn new_special(pool_id: uint,
event_loop: ~EventLoop:Send,
work_queue: deque::Worker<~GreenTask>,
work_queues: ~[deque::Stealer<~GreenTask>],
work_queues: Vec<deque::Stealer<~GreenTask>>,
sleeper_list: SleeperList,
run_anything: bool,
friend: Option<SchedHandle>,
@ -502,7 +502,7 @@ impl Scheduler {
let len = work_queues.len();
let start_index = self.rng.gen_range(0, len);
for index in range(0, len).map(|i| (i + start_index) % len) {
match work_queues[index].steal() {
match work_queues.get_mut(index).steal() {
deque::Data(task) => {
rtdebug!("found task by stealing");
return Some(task)
@ -1137,7 +1137,7 @@ mod test {
let mut pool = BufferPool::new();
let (normal_worker, normal_stealer) = pool.deque();
let (special_worker, special_stealer) = pool.deque();
let queues = ~[normal_stealer, special_stealer];
let queues = vec![normal_stealer, special_stealer];
let (_p, state) = TaskState::new();
// Our normal scheduler
@ -1326,7 +1326,7 @@ mod test {
#[test]
fn multithreading() {
run(proc() {
let mut rxs = ~[];
let mut rxs = vec![];
for _ in range(0, 10) {
let (tx, rx) = channel();
spawn(proc() {

View File

@ -126,13 +126,13 @@ impl Drop for Stack {
pub struct StackPool {
// Ideally this would be some datastructure that preserved ordering on
// Stack.min_size.
stacks: ~[Stack],
stacks: Vec<Stack>,
}
impl StackPool {
pub fn new() -> StackPool {
StackPool {
stacks: ~[],
stacks: vec![],
}
}

View File

@ -146,7 +146,7 @@ pub use types::os::arch::c95::{c_ushort, clock_t, ptrdiff_t};
pub use types::os::arch::c95::{size_t, time_t};
pub use types::os::arch::c99::{c_longlong, c_ulonglong, intptr_t};
pub use types::os::arch::c99::{uintptr_t};
pub use types::os::arch::posix88::{dev_t, dirent_t, ino_t, mode_t};
pub use types::os::arch::posix88::{dev_t, ino_t, mode_t};
pub use types::os::arch::posix88::{off_t, pid_t, ssize_t};
pub use consts::os::c95::{_IOFBF, _IOLBF, _IONBF, BUFSIZ, EOF};

View File

@ -340,11 +340,11 @@ pub fn mkdir(p: &CString, mode: io::FilePermission) -> IoResult<()> {
}))
}
pub fn readdir(p: &CString) -> IoResult<~[Path]> {
pub fn readdir(p: &CString) -> IoResult<Vec<Path>> {
use libc::{dirent_t};
use libc::{opendir, readdir_r, closedir};
fn prune(root: &CString, dirs: ~[Path]) -> ~[Path] {
fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> {
let root = unsafe { CString::new(root.with_ref(|p| p), false) };
let root = Path::new(root);
@ -365,7 +365,7 @@ pub fn readdir(p: &CString) -> IoResult<~[Path]> {
let dir_ptr = p.with_ref(|buf| unsafe { opendir(buf) });
if dir_ptr as uint != 0 {
let mut paths = ~[];
let mut paths = vec!();
let mut entry_ptr = 0 as *mut dirent_t;
while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
if entry_ptr.is_null() { break }
@ -571,4 +571,3 @@ mod tests {
}
}
}

View File

@ -323,10 +323,10 @@ pub fn mkdir(p: &CString, _mode: io::FilePermission) -> IoResult<()> {
})
}
pub fn readdir(p: &CString) -> IoResult<~[Path]> {
use rt::global_heap::malloc_raw;
pub fn readdir(p: &CString) -> IoResult<Vec<Path>> {
use std::rt::global_heap::malloc_raw;
fn prune(root: &CString, dirs: ~[Path]) -> ~[Path] {
fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> {
let root = unsafe { CString::new(root.with_ref(|p| p), false) };
let root = Path::new(root);
@ -346,7 +346,7 @@ pub fn readdir(p: &CString) -> IoResult<~[Path]> {
let wfd_ptr = malloc_raw(rust_list_dir_wfd_size() as uint);
let find_handle = libc::FindFirstFileW(path_ptr, wfd_ptr as libc::HANDLE);
if find_handle as libc::c_int != libc::INVALID_HANDLE_VALUE {
let mut paths = ~[];
let mut paths = vec!();
let mut more_files = 1 as libc::c_int;
while more_files != 0 {
let fp_buf = rust_list_dir_wfd_fp_buf(wfd_ptr as *c_void);

View File

@ -217,7 +217,7 @@ impl rtio::IoFactory for IoFactory {
fn fs_rename(&mut self, path: &CString, to: &CString) -> IoResult<()> {
file::rename(path, to)
}
fn fs_readdir(&mut self, path: &CString, _flags: c_int) -> IoResult<~[Path]> {
fn fs_readdir(&mut self, path: &CString, _flags: c_int) -> IoResult<Vec<Path>> {
file::readdir(path)
}
fn fs_lstat(&mut self, path: &CString) -> IoResult<io::FileStat> {

View File

View File

@ -102,11 +102,11 @@ fn helper(input: libc::c_int, messages: Receiver<Req>) {
// active timers are those which are able to be selected upon (and it's a
// sorted list, and dead timers are those which have expired, but ownership
// hasn't yet been transferred back to the timer itself.
let mut active: ~[~Inner] = ~[];
let mut dead = ~[];
let mut active: Vec<~Inner> = vec![];
let mut dead = vec![];
// inserts a timer into an array of timers (sorted by firing time)
fn insert(t: ~Inner, active: &mut ~[~Inner]) {
fn insert(t: ~Inner, active: &mut Vec<~Inner>) {
match active.iter().position(|tm| tm.target > t.target) {
Some(pos) => { active.insert(pos, t); }
None => { active.push(t); }
@ -114,7 +114,7 @@ fn helper(input: libc::c_int, messages: Receiver<Req>) {
}
// signals the first requests in the queue, possible re-enqueueing it.
fn signal(active: &mut ~[~Inner], dead: &mut ~[(uint, ~Inner)]) {
fn signal(active: &mut Vec<~Inner>, dead: &mut Vec<(uint, ~Inner)>) {
let mut timer = match active.shift() {
Some(timer) => timer, None => return
};
@ -137,7 +137,7 @@ fn helper(input: libc::c_int, messages: Receiver<Req>) {
let now = now();
// If this request has already expired, then signal it and go
// through another iteration
if active[0].target <= now {
if active.get(0).target <= now {
signal(&mut active, &mut dead);
continue;
}
@ -145,7 +145,7 @@ fn helper(input: libc::c_int, messages: Receiver<Req>) {
// The actual timeout listed in the requests array is an
// absolute date, so here we translate the absolute time to a
// relative time.
let tm = active[0].target - now;
let tm = active.get(0).target - now;
timeout.tv_sec = (tm / 1000) as libc::time_t;
timeout.tv_usec = ((tm % 1000) * 1000) as libc::suseconds_t;
&timeout as *libc::timeval

View File

@ -76,7 +76,7 @@ fn helper(input: libc::c_int, messages: Receiver<Req>) {
add(efd, input);
let events: [imp::epoll_event, ..16] = unsafe { mem::init() };
let mut list: ~[(libc::c_int, Sender<()>, bool)] = ~[];
let mut list: Vec<(libc::c_int, Sender<()>, bool)> = vec![];
'outer: loop {
let n = match unsafe {
imp::epoll_wait(efd, events.as_ptr(),
@ -104,9 +104,9 @@ fn helper(input: libc::c_int, messages: Receiver<Req>) {
// times?
let _ = FileDesc::new(fd, false).inner_read(bits).unwrap();
let (remove, i) = {
match list.bsearch(|&(f, _, _)| f.cmp(&fd)) {
match list.as_slice().bsearch(|&(f, _, _)| f.cmp(&fd)) {
Some(i) => {
let (_, ref c, oneshot) = list[i];
let (_, ref c, oneshot) = *list.get(i);
(!c.try_send(()) || oneshot, i)
}
None => fail!("fd not active: {}", fd),
@ -128,9 +128,9 @@ fn helper(input: libc::c_int, messages: Receiver<Req>) {
// If we haven't previously seen the file descriptor, then
// we need to add it to the epoll set.
match list.bsearch(|&(f, _, _)| f.cmp(&fd)) {
match list.as_slice().bsearch(|&(f, _, _)| f.cmp(&fd)) {
Some(i) => {
drop(mem::replace(&mut list[i], (fd, chan, one)));
drop(mem::replace(list.get_mut(i), (fd, chan, one)));
}
None => {
match list.iter().position(|&(f, _, _)| f >= fd) {
@ -150,7 +150,7 @@ fn helper(input: libc::c_int, messages: Receiver<Req>) {
}
Data(RemoveTimer(fd, chan)) => {
match list.bsearch(|&(f, _, _)| f.cmp(&fd)) {
match list.as_slice().bsearch(|&(f, _, _)| f.cmp(&fd)) {
Some(i) => {
drop(list.remove(i));
del(efd, fd);

View File

@ -40,8 +40,8 @@ pub enum Req {
}
fn helper(input: libc::HANDLE, messages: Receiver<Req>) {
let mut objs = ~[input];
let mut chans = ~[];
let mut objs = vec![input];
let mut chans = vec![];
'outer: loop {
let idx = unsafe {
@ -78,7 +78,7 @@ fn helper(input: libc::HANDLE, messages: Receiver<Req>) {
}
} else {
let remove = {
match &chans[idx as uint - 1] {
match chans.get(idx as uint - 1) {
&(ref c, oneshot) => !c.try_send(()) || oneshot
}
};

View File

@ -12,9 +12,10 @@
use driver::session::Session;
use metadata::cstore;
use metadata::filesearch;
use util::fs;
use collections::HashSet;
use std::{os, slice};
use std::os;
use syntax::abi;
fn not_win32(os: abi::Os) -> bool {
@ -42,10 +43,9 @@ pub fn get_rpath_flags(sess: &Session, out_filename: &Path) -> Vec<~str> {
let sysroot = sess.filesearch().sysroot;
let output = out_filename;
let libs = sess.cstore.get_used_crates(cstore::RequireDynamic);
let libs = libs.move_iter().filter_map(|(_, l)| l.map(|p| p.clone())).collect();
// We don't currently rpath extern libraries, but we know
// where rustrt is and we know every rust program needs it
let libs = slice::append_one(libs, get_sysroot_absolute_rt_lib(sess));
let libs = libs.move_iter().filter_map(|(_, l)| {
l.map(|p| p.clone())
}).collect::<~[_]>();
let rpaths = get_rpaths(os, sysroot, output, libs,
sess.opts.target_triple);
@ -53,14 +53,6 @@ pub fn get_rpath_flags(sess: &Session, out_filename: &Path) -> Vec<~str> {
flags
}
fn get_sysroot_absolute_rt_lib(sess: &Session) -> Path {
let sysroot = sess.filesearch().sysroot;
let r = filesearch::relative_target_lib_path(sysroot, sess.opts.target_triple);
let mut p = sysroot.join(&r);
p.push(os::dll_filename("rustrt"));
p
}
pub fn rpaths_to_flags(rpaths: &[~str]) -> Vec<~str> {
let mut ret = Vec::new();
for rpath in rpaths.iter() {
@ -87,10 +79,6 @@ fn get_rpaths(os: abi::Os,
// crates they depend on.
let rel_rpaths = get_rpaths_relative_to_output(os, output, libs);
// Make backup absolute paths to the libraries. Binaries can
// be moved as long as the crates they link against don't move.
let abs_rpaths = get_absolute_rpaths(libs);
// And a final backup rpath to the global library location.
let fallback_rpaths = vec!(get_install_prefix_rpath(sysroot, target_triple));
@ -102,11 +90,9 @@ fn get_rpaths(os: abi::Os,
}
log_rpaths("relative", rel_rpaths.as_slice());
log_rpaths("absolute", abs_rpaths.as_slice());
log_rpaths("fallback", fallback_rpaths.as_slice());
let mut rpaths = rel_rpaths;
rpaths.push_all(abs_rpaths.as_slice());
rpaths.push_all(fallback_rpaths.as_slice());
// Remove duplicates
@ -136,9 +122,9 @@ pub fn get_rpath_relative_to_output(os: abi::Os,
abi::OsWin32 => unreachable!()
};
let mut lib = os::make_absolute(lib);
let mut lib = fs::realpath(&os::make_absolute(lib)).unwrap();
lib.pop();
let mut output = os::make_absolute(output);
let mut output = fs::realpath(&os::make_absolute(output)).unwrap();
output.pop();
let relative = lib.path_relative_from(&output);
let relative = relative.expect("could not create rpath relative to output");
@ -146,17 +132,6 @@ pub fn get_rpath_relative_to_output(os: abi::Os,
prefix+"/"+relative.as_str().expect("non-utf8 component in path")
}
fn get_absolute_rpaths(libs: &[Path]) -> Vec<~str> {
libs.iter().map(|a| get_absolute_rpath(a)).collect()
}
pub fn get_absolute_rpath(lib: &Path) -> ~str {
let mut p = os::make_absolute(lib);
p.pop();
// FIXME (#9639): This needs to handle non-utf8 paths
p.as_str().expect("non-utf8 component in rpath").to_owned()
}
pub fn get_install_prefix_rpath(sysroot: &Path, target_triple: &str) -> ~str {
let install_prefix = env!("CFG_PREFIX");
@ -183,7 +158,7 @@ pub fn minimize_rpaths(rpaths: &[~str]) -> Vec<~str> {
mod test {
use std::os;
use back::rpath::{get_absolute_rpath, get_install_prefix_rpath};
use back::rpath::get_install_prefix_rpath;
use back::rpath::{minimize_rpaths, rpaths_to_flags, get_rpath_relative_to_output};
use syntax::abi;
use metadata::filesearch;
@ -258,15 +233,4 @@ mod test {
&Path::new("lib/libstd.so"));
assert_eq!(res.as_slice(), "@loader_path/../lib");
}
#[test]
fn test_get_absolute_rpath() {
let res = get_absolute_rpath(&Path::new("lib/libstd.so"));
let lib = os::make_absolute(&Path::new("lib"));
debug!("test_get_absolute_rpath: {} vs. {}",
res.to_str(), lib.display());
// FIXME (#9639): This needs to handle non-utf8 paths
assert_eq!(res.as_slice(), lib.as_str().expect("non-utf8 component in path"));
}
}

View File

@ -664,7 +664,8 @@ impl pprust::PpAnn for TypedAnnotation {
pub fn pretty_print_input(sess: Session,
cfg: ast::CrateConfig,
input: &Input,
ppm: PpMode) {
ppm: PpMode,
ofile: Option<Path>) {
let krate = phase_1_parse_input(&sess, cfg, input);
let id = link::find_crate_id(krate.attrs.as_slice(), input.filestem());
@ -682,6 +683,17 @@ pub fn pretty_print_input(sess: Session,
let src = Vec::from_slice(sess.codemap().get_filemap(src_name).src.as_bytes());
let mut rdr = MemReader::new(src);
let out = match ofile {
None => ~io::stdout() as ~Writer,
Some(p) => {
let r = io::File::create(&p);
match r {
Ok(w) => ~w as ~Writer,
Err(e) => fail!("print-print failed to open {} due to {}",
p.display(), e),
}
}
};
match ppm {
PpmIdentified | PpmExpandedIdentified => {
pprust::print_crate(sess.codemap(),
@ -689,7 +701,7 @@ pub fn pretty_print_input(sess: Session,
&krate,
src_name,
&mut rdr,
~io::stdout(),
out,
&IdentifiedAnnotation,
is_expanded)
}
@ -704,7 +716,7 @@ pub fn pretty_print_input(sess: Session,
&krate,
src_name,
&mut rdr,
~io::stdout(),
out,
&annotation,
is_expanded)
}
@ -714,7 +726,7 @@ pub fn pretty_print_input(sess: Session,
&krate,
src_name,
&mut rdr,
~io::stdout(),
out,
&pprust::NoAnn,
is_expanded)
}

View File

@ -297,20 +297,22 @@ mod __test {
fn mk_std(cx: &TestCtxt) -> ast::ViewItem {
let id_test = token::str_to_ident("test");
let vi = if cx.is_test_crate {
ast::ViewItemUse(
let (vi, vis) = if cx.is_test_crate {
(ast::ViewItemUse(
vec!(@nospan(ast::ViewPathSimple(id_test,
path_node(vec!(id_test)),
ast::DUMMY_NODE_ID))))
ast::DUMMY_NODE_ID)))),
ast::Public)
} else {
ast::ViewItemExternCrate(id_test,
(ast::ViewItemExternCrate(id_test,
with_version("test"),
ast::DUMMY_NODE_ID)
ast::DUMMY_NODE_ID),
ast::Inherited)
};
ast::ViewItem {
node: vi,
attrs: Vec::new(),
vis: ast::Inherited,
vis: vis,
span: DUMMY_SP
}
}

View File

@ -127,6 +127,7 @@ pub mod util {
pub mod ppaux;
pub mod sha2;
pub mod nodemap;
pub mod fs;
}
pub mod lib {
@ -293,7 +294,7 @@ pub fn run_compiler(args: &[~str]) {
});
match pretty {
Some::<d::PpMode>(ppm) => {
d::pretty_print_input(sess, cfg, &input, ppm);
d::pretty_print_input(sess, cfg, &input, ppm, ofile);
return;
}
None::<d::PpMode> => {/* continue */ }

View File

@ -190,7 +190,7 @@ fn visit_item(e: &Env, i: &ast::Item) {
} else {
None
})
.collect::<~[&ast::Attribute]>();
.collect::<Vec<&ast::Attribute>>();
for m in link_args.iter() {
match m.value_str() {
Some(linkarg) => e.sess.cstore.add_used_link_args(linkarg.get()),
@ -205,7 +205,7 @@ fn visit_item(e: &Env, i: &ast::Item) {
} else {
None
})
.collect::<~[&ast::Attribute]>();
.collect::<Vec<&ast::Attribute>>();
for m in link_args.iter() {
match m.meta_item_list() {
Some(items) => {

View File

@ -28,7 +28,7 @@ use syntax::parse::token;
pub struct StaticMethodInfo {
pub ident: ast::Ident,
pub def_id: ast::DefId,
pub purity: ast::Purity,
pub fn_style: ast::FnStyle,
pub vis: ast::Visibility,
}

View File

@ -330,11 +330,11 @@ fn item_to_def_like(item: ebml::Doc, did: ast::DefId, cnum: ast::CrateNum)
MutStatic => DlDef(ast::DefStatic(did, true)),
Struct => DlDef(ast::DefStruct(did)),
UnsafeFn => DlDef(ast::DefFn(did, ast::UnsafeFn)),
Fn => DlDef(ast::DefFn(did, ast::ImpureFn)),
Fn => DlDef(ast::DefFn(did, ast::NormalFn)),
ForeignFn => DlDef(ast::DefFn(did, ast::ExternFn)),
StaticMethod | UnsafeStaticMethod => {
let purity = if fam == UnsafeStaticMethod { ast::UnsafeFn } else
{ ast::ImpureFn };
let fn_style = if fam == UnsafeStaticMethod { ast::UnsafeFn } else
{ ast::NormalFn };
// def_static_method carries an optional field of its enclosing
// trait or enclosing impl (if this is an inherent static method).
// So we need to detect whether this is in a trait or not, which
@ -348,7 +348,7 @@ fn item_to_def_like(item: ebml::Doc, did: ast::DefId, cnum: ast::CrateNum)
ast::FromImpl(item_reqd_and_translated_parent_item(cnum,
item))
};
DlDef(ast::DefStaticMethod(did, provenance, purity))
DlDef(ast::DefStaticMethod(did, provenance, fn_style))
}
Type | ForeignType => DlDef(ast::DefTy(did)),
Mod => DlDef(ast::DefMod(did)),
@ -905,17 +905,17 @@ pub fn get_static_methods_if_impl(intr: Rc<IdentInterner>,
let family = item_family(impl_method_doc);
match family {
StaticMethod | UnsafeStaticMethod => {
let purity;
let fn_style;
match item_family(impl_method_doc) {
StaticMethod => purity = ast::ImpureFn,
UnsafeStaticMethod => purity = ast::UnsafeFn,
StaticMethod => fn_style = ast::NormalFn,
UnsafeStaticMethod => fn_style = ast::UnsafeFn,
_ => fail!()
}
static_impl_methods.push(StaticMethodInfo {
ident: item_name(&*intr, impl_method_doc),
def_id: item_def_id(impl_method_doc, cdata),
purity: purity,
fn_style: fn_style,
vis: item_visibility(impl_method_doc),
});
}

View File

@ -758,12 +758,12 @@ fn encode_method_ty_fields(ecx: &EncodeContext,
encode_method_fty(ecx, ebml_w, &method_ty.fty);
encode_visibility(ebml_w, method_ty.vis);
encode_explicit_self(ebml_w, method_ty.explicit_self);
let purity = method_ty.fty.purity;
let fn_style = method_ty.fty.fn_style;
match method_ty.explicit_self {
ast::SelfStatic => {
encode_family(ebml_w, purity_static_method_family(purity));
encode_family(ebml_w, fn_style_static_method_family(fn_style));
}
_ => encode_family(ebml_w, purity_fn_family(purity))
_ => encode_family(ebml_w, style_fn_family(fn_style))
}
encode_provided_source(ebml_w, method_ty.provided_source);
}
@ -811,18 +811,18 @@ fn encode_info_for_method(ecx: &EncodeContext,
ebml_w.end_tag();
}
fn purity_fn_family(p: Purity) -> char {
match p {
fn style_fn_family(s: FnStyle) -> char {
match s {
UnsafeFn => 'u',
ImpureFn => 'f',
NormalFn => 'f',
ExternFn => 'e'
}
}
fn purity_static_method_family(p: Purity) -> char {
match p {
fn fn_style_static_method_family(s: FnStyle) -> char {
match s {
UnsafeFn => 'U',
ImpureFn => 'F',
NormalFn => 'F',
_ => fail!("extern fn can't be static")
}
}
@ -911,11 +911,11 @@ fn encode_info_for_item(ecx: &EncodeContext,
encode_visibility(ebml_w, vis);
ebml_w.end_tag();
}
ItemFn(_, purity, _, ref generics, _) => {
ItemFn(_, fn_style, _, ref generics, _) => {
add_to_index(item, ebml_w, index);
ebml_w.start_tag(tag_items_data_item);
encode_def_id(ebml_w, def_id);
encode_family(ebml_w, purity_fn_family(purity));
encode_family(ebml_w, style_fn_family(fn_style));
let tps_len = generics.ty_params.len();
encode_bounds_and_type(ebml_w, ecx, &lookup_item_type(tcx, def_id));
encode_name(ebml_w, item.ident.name);
@ -1165,8 +1165,8 @@ fn encode_info_for_item(ecx: &EncodeContext,
match method_ty.explicit_self {
SelfStatic => {
encode_family(ebml_w,
purity_static_method_family(
method_ty.fty.purity));
fn_style_static_method_family(
method_ty.fty.fn_style));
let tpt = ty::lookup_item_type(tcx, method_def_id);
encode_bounds_and_type(ebml_w, ecx, &tpt);
@ -1174,8 +1174,8 @@ fn encode_info_for_item(ecx: &EncodeContext,
_ => {
encode_family(ebml_w,
purity_fn_family(
method_ty.fty.purity));
style_fn_family(
method_ty.fty.fn_style));
}
}
@ -1227,7 +1227,7 @@ fn encode_info_for_foreign_item(ecx: &EncodeContext,
encode_def_id(ebml_w, local_def(nitem.id));
match nitem.node {
ForeignItemFn(..) => {
encode_family(ebml_w, purity_fn_family(ImpureFn));
encode_family(ebml_w, style_fn_family(NormalFn));
encode_bounds_and_type(ebml_w, ecx,
&lookup_item_type(ecx.tcx,local_def(nitem.id)));
encode_name(ebml_w, nitem.ident.name);

View File

@ -15,6 +15,8 @@ use std::os;
use std::io::fs;
use collections::HashSet;
use myfs = util::fs;
pub enum FileMatch { FileMatches, FileDoesntMatch }
// A module for searching for libraries
@ -156,17 +158,10 @@ fn make_rustpkg_target_lib_path(sysroot: &Path,
pub fn get_or_default_sysroot() -> Path {
// Follow symlinks. If the resolved path is relative, make it absolute.
fn canonicalize(path: Option<Path>) -> Option<Path> {
path.and_then(|mut path|
match fs::readlink(&path) {
Ok(canon) => {
if canon.is_absolute() {
Some(canon)
} else {
path.pop();
Some(path.join(canon))
}
},
Err(..) => Some(path),
path.and_then(|path|
match myfs::realpath(&path) {
Ok(canon) => Some(canon),
Err(e) => fail!("failed to get realpath: {}", e),
})
}

View File

@ -449,12 +449,12 @@ fn parse_hex(st: &mut PState) -> uint {
};
}
fn parse_purity(c: char) -> Purity {
fn parse_fn_style(c: char) -> FnStyle {
match c {
'u' => UnsafeFn,
'i' => ImpureFn,
'n' => NormalFn,
'c' => ExternFn,
_ => fail!("parse_purity: bad purity {}", c)
_ => fail!("parse_fn_style: bad fn_style {}", c)
}
}
@ -476,13 +476,13 @@ fn parse_onceness(c: char) -> ast::Onceness {
fn parse_closure_ty(st: &mut PState, conv: conv_did) -> ty::ClosureTy {
let sigil = parse_sigil(st);
let purity = parse_purity(next(st));
let fn_style = parse_fn_style(next(st));
let onceness = parse_onceness(next(st));
let region = parse_region(st, |x,y| conv(x,y));
let bounds = parse_bounds(st, |x,y| conv(x,y));
let sig = parse_sig(st, |x,y| conv(x,y));
ty::ClosureTy {
purity: purity,
fn_style: fn_style,
sigil: sigil,
onceness: onceness,
region: region,
@ -492,11 +492,11 @@ fn parse_closure_ty(st: &mut PState, conv: conv_did) -> ty::ClosureTy {
}
fn parse_bare_fn_ty(st: &mut PState, conv: conv_did) -> ty::BareFnTy {
let purity = parse_purity(next(st));
let fn_style = parse_fn_style(next(st));
let abi = parse_abi_set(st);
let sig = parse_sig(st, |x,y| conv(x,y));
ty::BareFnTy {
purity: purity,
fn_style: fn_style,
abi: abi,
sig: sig
}

View File

@ -332,9 +332,9 @@ fn enc_sigil(w: &mut MemWriter, sigil: Sigil) {
}
}
fn enc_purity(w: &mut MemWriter, p: Purity) {
fn enc_fn_style(w: &mut MemWriter, p: FnStyle) {
match p {
ImpureFn => mywrite!(w, "i"),
NormalFn => mywrite!(w, "n"),
UnsafeFn => mywrite!(w, "u"),
ExternFn => mywrite!(w, "c")
}
@ -354,14 +354,14 @@ fn enc_onceness(w: &mut MemWriter, o: Onceness) {
}
pub fn enc_bare_fn_ty(w: &mut MemWriter, cx: &ctxt, ft: &ty::BareFnTy) {
enc_purity(w, ft.purity);
enc_fn_style(w, ft.fn_style);
enc_abi(w, ft.abi);
enc_fn_sig(w, cx, &ft.sig);
}
fn enc_closure_ty(w: &mut MemWriter, cx: &ctxt, ft: &ty::ClosureTy) {
enc_sigil(w, ft.sigil);
enc_purity(w, ft.purity);
enc_fn_style(w, ft.fn_style);
enc_onceness(w, ft.onceness);
enc_region(w, cx, ft.region);
let bounds = ty::ParamBounds {builtin_bounds: ft.bounds,

View File

@ -29,8 +29,8 @@ enum UnsafeContext {
fn type_is_unsafe_function(ty: ty::t) -> bool {
match ty::get(ty).sty {
ty::ty_bare_fn(ref f) => f.purity == ast::UnsafeFn,
ty::ty_closure(ref f) => f.purity == ast::UnsafeFn,
ty::ty_bare_fn(ref f) => f.fn_style == ast::UnsafeFn,
ty::ty_closure(ref f) => f.fn_style == ast::UnsafeFn,
_ => false,
}
}
@ -84,10 +84,10 @@ impl<'a> Visitor<()> for EffectCheckVisitor<'a> {
block: &ast::Block, span: Span, node_id: ast::NodeId, _:()) {
let (is_item_fn, is_unsafe_fn) = match *fn_kind {
visit::FkItemFn(_, _, purity, _) =>
(true, purity == ast::UnsafeFn),
visit::FkItemFn(_, _, fn_style, _) =>
(true, fn_style == ast::UnsafeFn),
visit::FkMethod(_, _, method) =>
(true, method.purity == ast::UnsafeFn),
(true, method.fn_style == ast::UnsafeFn),
_ => (false, false),
};

View File

@ -1063,7 +1063,7 @@ fn check_attrs_usage(cx: &Context, attrs: &[ast::Attribute]) {
if name.equiv(crate_attr) {
let msg = match attr.node.style {
ast::AttrOuter => "crate-level attribute should be an inner attribute: \
add semicolon at end",
add an exclamation mark: #![foo]",
ast::AttrInner => "crate-level attribute should be in the root module",
};
cx.span_lint(AttributeUsage, attr.span, msg);

View File

@ -144,6 +144,12 @@ impl NamespaceResult {
_ => false
}
}
fn is_unbound(&self) -> bool {
match *self {
UnboundResult => true,
_ => false
}
}
}
enum NameDefinition {
@ -1182,11 +1188,11 @@ impl<'a> Resolver<'a> {
(DefStatic(local_def(item.id), mutbl), sp, is_public);
parent
}
ItemFn(_, purity, _, _, _) => {
ItemFn(_, fn_style, _, _, _) => {
let (name_bindings, new_parent) =
self.add_child(ident, parent, ForbidDuplicateValues, sp);
let def = DefFn(local_def(item.id), purity);
let def = DefFn(local_def(item.id), fn_style);
name_bindings.define_value(def, sp, is_public);
new_parent
}
@ -1313,7 +1319,7 @@ impl<'a> Resolver<'a> {
DefStaticMethod(local_def(method.id),
FromImpl(local_def(
item.id)),
method.purity)
method.fn_style)
}
_ => {
// Non-static methods become
@ -1364,7 +1370,7 @@ impl<'a> Resolver<'a> {
// Static methods become `def_static_method`s.
DefStaticMethod(local_def(ty_m.id),
FromTrait(local_def(item.id)),
ty_m.purity)
ty_m.fn_style)
}
_ => {
// Non-static methods become `def_method`s.
@ -1869,7 +1875,7 @@ impl<'a> Resolver<'a> {
DUMMY_SP);
let def = DefFn(
static_method_info.def_id,
static_method_info.purity);
static_method_info.fn_style);
method_name_bindings.define_value(
def, DUMMY_SP,
@ -1976,6 +1982,7 @@ impl<'a> Resolver<'a> {
// the source of this name is different now
resolution.type_id.set(id);
resolution.value_id.set(id);
resolution.is_public.set(is_public);
}
None => {
debug!("(building import directive) creating new");
@ -2286,10 +2293,12 @@ impl<'a> Resolver<'a> {
}
Some(child_name_bindings) => {
if child_name_bindings.defined_in_namespace(ValueNS) {
debug!("(resolving single import) found value binding");
value_result = BoundResult(containing_module,
*child_name_bindings);
}
if child_name_bindings.defined_in_namespace(TypeNS) {
debug!("(resolving single import) found type binding");
type_result = BoundResult(containing_module,
*child_name_bindings);
}
@ -2320,6 +2329,7 @@ impl<'a> Resolver<'a> {
.borrow();
match import_resolutions.find(&source.name) {
None => {
debug!("(resolving single import) no import");
// The containing module definitely doesn't have an
// exported import with the name in question. We can
// therefore accurately report that the names are
@ -2353,6 +2363,8 @@ impl<'a> Resolver<'a> {
return UnboundResult;
}
Some(target) => {
debug!("(resolving single import) found \
import in ns {:?}", namespace);
let id = import_resolution.id(namespace);
this.used_imports.insert((id, namespace));
return BoundResult(target.target_module,
@ -2396,6 +2408,8 @@ impl<'a> Resolver<'a> {
.find_copy(&source.name) {
None => {} // Continue.
Some(module) => {
debug!("(resolving single import) found external \
module");
let name_bindings =
@Resolver::create_name_bindings_from_module(
module);
@ -2442,8 +2456,7 @@ impl<'a> Resolver<'a> {
}
}
if import_resolution.value_target.borrow().is_none() &&
import_resolution.type_target.borrow().is_none() {
if value_result.is_unbound() && type_result.is_unbound() {
let msg = format!("unresolved import: there is no \
`{}` in `{}`",
token::get_ident(source),
@ -2669,7 +2682,8 @@ impl<'a> Resolver<'a> {
match self.resolve_name_in_module(search_module,
name,
TypeNS,
name_search_type) {
name_search_type,
false) {
Failed => {
let segment_name = token::get_ident(name);
let module_name = self.module_to_str(search_module);
@ -2977,7 +2991,8 @@ impl<'a> Resolver<'a> {
match self.resolve_name_in_module(search_module,
name,
namespace,
PathSearch) {
PathSearch,
true) {
Failed => {
// Continue up the search chain.
}
@ -3141,7 +3156,8 @@ impl<'a> Resolver<'a> {
module_: @Module,
name: Ident,
namespace: Namespace,
name_search_type: NameSearchType)
name_search_type: NameSearchType,
allow_private_imports: bool)
-> ResolveResult<(Target, bool)> {
debug!("(resolving name in module) resolving `{}` in `{}`",
token::get_ident(name),
@ -3172,7 +3188,9 @@ impl<'a> Resolver<'a> {
// Check the list of resolved imports.
match module_.import_resolutions.borrow().find(&name.name) {
Some(import_resolution) => {
Some(import_resolution) if allow_private_imports ||
import_resolution.is_public.get() => {
if import_resolution.is_public.get() &&
import_resolution.outstanding_references.get() != 0 {
debug!("(resolving name in module) import \
@ -3193,7 +3211,7 @@ impl<'a> Resolver<'a> {
}
}
}
None => {} // Continue.
Some(..) | None => {} // Continue.
}
// Finally, search through external children.

View File

@ -1554,8 +1554,8 @@ impl<'a> Visitor<()> for TransItemVisitor<'a> {
pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
let _icx = push_ctxt("trans_item");
match item.node {
ast::ItemFn(decl, purity, _abi, ref generics, body) => {
if purity == ast::ExternFn {
ast::ItemFn(decl, fn_style, _abi, ref generics, body) => {
if fn_style == ast::ExternFn {
let llfndecl = get_item_val(ccx, item.id);
foreign::trans_rust_fn_with_foreign_abi(
ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id);
@ -1899,8 +1899,8 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
}
}
ast::ItemFn(_, purity, _, _, _) => {
let llfn = if purity != ast::ExternFn {
ast::ItemFn(_, fn_style, _, _, _) => {
let llfn = if fn_style != ast::ExternFn {
register_fn(ccx, i.span, sym, i.id, ty)
} else {
foreign::register_rust_fn_with_foreign_abi(ccx,

View File

@ -615,7 +615,7 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr,
let opt_def = cx.tcx().def_map.borrow().find_copy(&e.id);
match opt_def {
Some(ast::DefFn(def_id, _purity)) => {
Some(ast::DefFn(def_id, _fn_style)) => {
if !ast_util::is_local(def_id) {
let ty = csearch::get_type(cx.tcx(), def_id).ty;
(base::trans_external_path(cx, def_id, ty), true)

View File

@ -130,6 +130,7 @@ use driver::session::{FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
use lib::llvm::llvm;
use lib::llvm::{ModuleRef, ContextRef, ValueRef};
use lib::llvm::debuginfo::*;
use metadata::csearch;
use middle::trans::adt;
use middle::trans::common::*;
use middle::trans::datum::{Datum, Lvalue};
@ -178,6 +179,7 @@ pub struct CrateDebugContext {
current_debug_location: Cell<DebugLocation>,
created_files: RefCell<HashMap<~str, DIFile>>,
created_types: RefCell<HashMap<uint, DIType>>,
created_enum_disr_types: RefCell<HashMap<ast::DefId, DIType>>,
namespace_map: RefCell<HashMap<Vec<ast::Name> , @NamespaceTreeNode>>,
// This collection is used to assert that composite types (structs, enums, ...) have their
// members only set once:
@ -196,6 +198,7 @@ impl CrateDebugContext {
current_debug_location: Cell::new(UnknownLocation),
created_files: RefCell::new(HashMap::new()),
created_types: RefCell::new(HashMap::new()),
created_enum_disr_types: RefCell::new(HashMap::new()),
namespace_map: RefCell::new(HashMap::new()),
composite_types_completed: RefCell::new(HashSet::new()),
};
@ -290,6 +293,13 @@ pub fn create_global_var_metadata(cx: &CrateContext,
return;
}
// Don't create debuginfo for globals inlined from other crates. The other crate should already
// contain debuginfo for it. More importantly, the global might not even exist in un-inlined
// form anywhere which would lead to a linker errors.
if cx.external_srcs.borrow().contains_key(&node_id) {
return;
}
let var_item = cx.tcx.map.get(node_id);
let (ident, span) = match var_item {
@ -533,21 +543,26 @@ pub fn create_argument_metadata(bcx: &Block, arg: &ast::Arg) {
pub fn set_source_location(fcx: &FunctionContext,
node_id: ast::NodeId,
span: Span) {
if fn_should_be_ignored(fcx) {
return;
}
match fcx.debug_context {
DebugInfoDisabled => return,
FunctionWithoutDebugInfo => {
set_debug_location(fcx.ccx, UnknownLocation);
return;
}
FunctionDebugContext(~ref function_debug_context) => {
let cx = fcx.ccx;
let cx = fcx.ccx;
debug!("set_source_location: {}", cx.sess().codemap().span_to_str(span));
debug!("set_source_location: {}", cx.sess().codemap().span_to_str(span));
if function_debug_context.source_locations_enabled.get() {
let loc = span_start(cx, span);
let scope = scope_metadata(fcx, node_id, span);
if fcx.debug_context.get_ref(cx, span).source_locations_enabled.get() {
let loc = span_start(cx, span);
let scope = scope_metadata(fcx, node_id, span);
set_debug_location(cx, DebugLocation::new(scope, loc.line, loc.col.to_uint()));
} else {
set_debug_location(cx, UnknownLocation);
set_debug_location(cx, DebugLocation::new(scope, loc.line, loc.col.to_uint()));
} else {
set_debug_location(cx, UnknownLocation);
}
}
}
}
@ -590,6 +605,10 @@ pub fn create_function_debug_context(cx: &CrateContext,
return DebugInfoDisabled;
}
// Clear the debug location so we don't assign them in the function prelude. Do this here
// already, in case we do an early exit from this function.
set_debug_location(cx, UnknownLocation);
if fn_ast_id == -1 {
return FunctionWithoutDebugInfo;
}
@ -740,9 +759,6 @@ pub fn create_function_debug_context(cx: &CrateContext,
fn_metadata,
&mut *fn_debug_context.scope_map.borrow_mut());
// Clear the debug location so we don't assign them in the function prelude
set_debug_location(cx, UnknownLocation);
return FunctionDebugContext(fn_debug_context);
fn get_function_signature(cx: &CrateContext,
@ -1536,24 +1552,45 @@ fn prepare_enum_metadata(cx: &CrateContext,
.collect();
let discriminant_type_metadata = |inttype| {
let discriminant_llvm_type = adt::ll_inttype(cx, inttype);
let (discriminant_size, discriminant_align) = size_and_align_of(cx, discriminant_llvm_type);
let discriminant_base_type_metadata = type_metadata(cx, adt::ty_of_inttype(inttype),
codemap::DUMMY_SP);
enum_name.with_c_str(|enum_name| {
unsafe {
llvm::LLVMDIBuilderCreateEnumerationType(
DIB(cx),
containing_scope,
enum_name,
file_metadata,
loc.line as c_uint,
bytes_to_bits(discriminant_size),
bytes_to_bits(discriminant_align),
create_DIArray(DIB(cx), enumerators_metadata.as_slice()),
discriminant_base_type_metadata)
// We can reuse the type of the discriminant for all monomorphized instances of an enum
// because it doesn't depend on any type parameters. The def_id, uniquely identifying the
// enum's polytype acts as key in this cache.
let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
.borrow()
.find_copy(&enum_def_id);
match cached_discriminant_type_metadata {
Some(discriminant_type_metadata) => discriminant_type_metadata,
None => {
let discriminant_llvm_type = adt::ll_inttype(cx, inttype);
let (discriminant_size, discriminant_align) =
size_and_align_of(cx, discriminant_llvm_type);
let discriminant_base_type_metadata = type_metadata(cx,
adt::ty_of_inttype(inttype),
codemap::DUMMY_SP);
let discriminant_name = get_enum_discriminant_name(cx, enum_def_id);
let discriminant_type_metadata = discriminant_name.get().with_c_str(|name| {
unsafe {
llvm::LLVMDIBuilderCreateEnumerationType(
DIB(cx),
containing_scope,
name,
file_metadata,
loc.line as c_uint,
bytes_to_bits(discriminant_size),
bytes_to_bits(discriminant_align),
create_DIArray(DIB(cx), enumerators_metadata.as_slice()),
discriminant_base_type_metadata)
}
});
debug_context(cx).created_enum_disr_types
.borrow_mut()
.insert(enum_def_id, discriminant_type_metadata);
discriminant_type_metadata
}
})
}
};
let type_rep = adt::represent_type(cx, enum_type);
@ -1642,6 +1679,16 @@ fn prepare_enum_metadata(cx: &CrateContext,
}
}
};
fn get_enum_discriminant_name(cx: &CrateContext, def_id: ast::DefId) -> token::InternedString {
let name = if def_id.krate == ast::LOCAL_CRATE {
cx.tcx.map.get_path_elem(def_id.node).name()
} else {
csearch::get_item_path(&cx.tcx, def_id).last().unwrap().name()
};
token::get_name(name)
}
}
enum MemberOffset {

View File

@ -211,7 +211,7 @@ impl<'a> Reflector<'a> {
// FIXME (#2594): fetch constants out of intrinsic
// FIXME (#4809): visitor should break out bare fns from other fns
ty::ty_closure(ref fty) => {
let pureval = ast_purity_constant(fty.purity);
let pureval = ast_fn_style_constant(fty.fn_style);
let sigilval = ast_sigil_constant(fty.sigil);
let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
let extra = vec!(self.c_uint(pureval),
@ -226,7 +226,7 @@ impl<'a> Reflector<'a> {
// FIXME (#2594): fetch constants out of intrinsic:: for the
// numbers.
ty::ty_bare_fn(ref fty) => {
let pureval = ast_purity_constant(fty.purity);
let pureval = ast_fn_style_constant(fty.fn_style);
let sigilval = 0u;
let retval = if ty::type_is_bot(fty.sig.output) {0u} else {1u};
let extra = vec!(self.c_uint(pureval),
@ -399,10 +399,10 @@ pub fn ast_sigil_constant(sigil: ast::Sigil) -> uint {
}
}
pub fn ast_purity_constant(purity: ast::Purity) -> uint {
match purity {
pub fn ast_fn_style_constant(fn_style: ast::FnStyle) -> uint {
match fn_style {
ast::UnsafeFn => 1u,
ast::ImpureFn => 2u,
ast::NormalFn => 2u,
ast::ExternFn => 3u
}
}

View File

@ -415,14 +415,14 @@ pub fn type_id(t: t) -> uint { get(t).id }
#[deriving(Clone, Eq, TotalEq, Hash)]
pub struct BareFnTy {
pub purity: ast::Purity,
pub fn_style: ast::FnStyle,
pub abi: abi::Abi,
pub sig: FnSig,
}
#[deriving(Clone, Eq, TotalEq, Hash)]
pub struct ClosureTy {
pub purity: ast::Purity,
pub fn_style: ast::FnStyle,
pub sigil: ast::Sigil,
pub onceness: ast::Onceness,
pub region: Region,
@ -791,7 +791,7 @@ pub struct expected_found<T> {
#[deriving(Clone, Show)]
pub enum type_err {
terr_mismatch,
terr_purity_mismatch(expected_found<Purity>),
terr_fn_style_mismatch(expected_found<FnStyle>),
terr_onceness_mismatch(expected_found<Onceness>),
terr_abi_mismatch(expected_found<abi::Abi>),
terr_mutability,
@ -1397,7 +1397,7 @@ pub fn mk_ctor_fn(cx: &ctxt,
let input_args = input_tys.iter().map(|t| *t).collect();
mk_bare_fn(cx,
BareFnTy {
purity: ast::ImpureFn,
fn_style: ast::NormalFn,
abi: abi::Rust,
sig: FnSig {
binder_id: binder_id,
@ -2843,7 +2843,7 @@ pub fn adjust_ty(cx: &ctxt,
ty::ty_bare_fn(ref b) => {
ty::mk_closure(
cx,
ty::ClosureTy {purity: b.purity,
ty::ClosureTy {fn_style: b.fn_style,
sigil: s,
onceness: ast::Many,
region: r,
@ -3340,7 +3340,7 @@ pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> ~str {
match *err {
terr_mismatch => ~"types differ",
terr_purity_mismatch(values) => {
terr_fn_style_mismatch(values) => {
format!("expected {} fn but found {} fn",
values.expected.to_str(), values.found.to_str())
}
@ -4297,16 +4297,16 @@ pub fn eval_repeat_count<T: ExprTyProvider>(tcx: &T, count_expr: &ast::Expr) ->
}
}
// Determine what purity to check a nested function under
pub fn determine_inherited_purity(parent: (ast::Purity, ast::NodeId),
child: (ast::Purity, ast::NodeId),
// Determine what the style to check a nested function under
pub fn determine_inherited_style(parent: (ast::FnStyle, ast::NodeId),
child: (ast::FnStyle, ast::NodeId),
child_sigil: ast::Sigil)
-> (ast::Purity, ast::NodeId) {
-> (ast::FnStyle, ast::NodeId) {
// If the closure is a stack closure and hasn't had some non-standard
// purity inferred for it, then check it under its parent's purity.
// style inferred for it, then check it under its parent's style.
// Otherwise, use its own
match child_sigil {
ast::BorrowedSigil if child.val0() == ast::ImpureFn => parent,
ast::BorrowedSigil if child.val0() == ast::NormalFn => parent,
_ => child
}
}
@ -4665,12 +4665,12 @@ pub fn hash_crate_independent(tcx: &ctxt, t: t, svh: &Svh) -> u64 {
}
ty_bare_fn(ref b) => {
byte!(14);
hash!(b.purity);
hash!(b.fn_style);
hash!(b.abi);
}
ty_closure(ref c) => {
byte!(15);
hash!(c.purity);
hash!(c.fn_style);
hash!(c.sigil);
hash!(c.onceness);
hash!(c.bounds);

View File

@ -49,7 +49,7 @@ pub trait TypeFolder {
-> ty::BareFnTy {
ty::BareFnTy { sig: self.fold_sig(&fty.sig),
abi: fty.abi,
purity: fty.purity }
fn_style: fty.fn_style }
}
fn fold_closure_ty(&mut self,
@ -58,7 +58,7 @@ pub trait TypeFolder {
ty::ClosureTy {
region: self.fold_region(fty.region),
sig: self.fold_sig(&fty.sig),
purity: fty.purity,
fn_style: fty.fn_style,
sigil: fty.sigil,
onceness: fty.onceness,
bounds: fty.bounds,

View File

@ -523,7 +523,7 @@ pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>(
tcx.sess.span_err(ast_ty.span,
"variadic function must have C calling convention");
}
ty::mk_bare_fn(tcx, ty_of_bare_fn(this, ast_ty.id, bf.purity,
ty::mk_bare_fn(tcx, ty_of_bare_fn(this, ast_ty.id, bf.fn_style,
bf.abi, bf.decl))
}
ast::TyClosure(ref f) => {
@ -543,7 +543,7 @@ pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>(
rscope,
ast_ty.id,
f.sigil,
f.purity,
f.fn_style,
f.onceness,
bounds,
&f.region,
@ -572,9 +572,8 @@ pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>(
let path_str = path_to_str(path);
tcx.sess.span_err(
ast_ty.span,
format!("reference to trait `{}` where a type is expected; \
try `@{}`, `~{}`, or `&{}`",
path_str, path_str, path_str, path_str));
format!("reference to trait `{name}` where a type is expected; \
try `~{name}` or `&{name}`", name=path_str));
ty::mk_err()
}
ast::DefTy(did) | ast::DefStruct(did) => {
@ -662,24 +661,24 @@ struct SelfInfo {
pub fn ty_of_method<AC:AstConv>(
this: &AC,
id: ast::NodeId,
purity: ast::Purity,
fn_style: ast::FnStyle,
untransformed_self_ty: ty::t,
explicit_self: ast::ExplicitSelf,
decl: &ast::FnDecl) -> ty::BareFnTy {
ty_of_method_or_bare_fn(this, id, purity, abi::Rust, Some(SelfInfo {
ty_of_method_or_bare_fn(this, id, fn_style, abi::Rust, Some(SelfInfo {
untransformed_self_ty: untransformed_self_ty,
explicit_self: explicit_self
}), decl)
}
pub fn ty_of_bare_fn<AC:AstConv>(this: &AC, id: ast::NodeId,
purity: ast::Purity, abi: abi::Abi,
fn_style: ast::FnStyle, abi: abi::Abi,
decl: &ast::FnDecl) -> ty::BareFnTy {
ty_of_method_or_bare_fn(this, id, purity, abi, None, decl)
ty_of_method_or_bare_fn(this, id, fn_style, abi, None, decl)
}
fn ty_of_method_or_bare_fn<AC:AstConv>(this: &AC, id: ast::NodeId,
purity: ast::Purity, abi: abi::Abi,
fn_style: ast::FnStyle, abi: abi::Abi,
opt_self_info: Option<SelfInfo>,
decl: &ast::FnDecl) -> ty::BareFnTy {
debug!("ty_of_method_or_bare_fn");
@ -725,7 +724,7 @@ fn ty_of_method_or_bare_fn<AC:AstConv>(this: &AC, id: ast::NodeId,
};
return ty::BareFnTy {
purity: purity,
fn_style: fn_style,
abi: abi,
sig: ty::FnSig {
binder_id: id,
@ -741,7 +740,7 @@ pub fn ty_of_closure<AC:AstConv,RS:RegionScope>(
rscope: &RS,
id: ast::NodeId,
sigil: ast::Sigil,
purity: ast::Purity,
fn_style: ast::FnStyle,
onceness: ast::Onceness,
bounds: ty::BuiltinBounds,
opt_lifetime: &Option<ast::Lifetime>,
@ -798,7 +797,7 @@ pub fn ty_of_closure<AC:AstConv,RS:RegionScope>(
};
ty::ClosureTy {
purity: purity,
fn_style: fn_style,
sigil: sigil,
onceness: onceness,
region: bound_region,

View File

@ -1163,7 +1163,7 @@ impl<'a> LookupContext<'a> {
let transformed_self_ty = *fn_sig.inputs.get(0);
let fty = ty::mk_bare_fn(tcx, ty::BareFnTy {
sig: fn_sig,
purity: bare_fn_ty.purity,
fn_style: bare_fn_ty.fn_style,
abi: bare_fn_ty.abi.clone(),
});
debug!("after replacing bound regions, fty={}", self.ty_to_str(fty));

View File

@ -177,32 +177,32 @@ pub enum FnKind {
}
#[deriving(Clone)]
pub struct PurityState {
pub struct FnStyleState {
pub def: ast::NodeId,
pub purity: ast::Purity,
pub fn_style: ast::FnStyle,
from_fn: bool
}
impl PurityState {
pub fn function(purity: ast::Purity, def: ast::NodeId) -> PurityState {
PurityState { def: def, purity: purity, from_fn: true }
impl FnStyleState {
pub fn function(fn_style: ast::FnStyle, def: ast::NodeId) -> FnStyleState {
FnStyleState { def: def, fn_style: fn_style, from_fn: true }
}
pub fn recurse(&mut self, blk: &ast::Block) -> PurityState {
match self.purity {
pub fn recurse(&mut self, blk: &ast::Block) -> FnStyleState {
match self.fn_style {
// If this unsafe, then if the outer function was already marked as
// unsafe we shouldn't attribute the unsafe'ness to the block. This
// way the block can be warned about instead of ignoring this
// extraneous block (functions are never warned about).
ast::UnsafeFn if self.from_fn => *self,
purity => {
let (purity, def) = match blk.rules {
fn_style => {
let (fn_style, def) = match blk.rules {
ast::UnsafeBlock(..) => (ast::UnsafeFn, blk.id),
ast::DefaultBlock => (purity, self.def),
ast::DefaultBlock => (fn_style, self.def),
};
PurityState{ def: def,
purity: purity,
FnStyleState{ def: def,
fn_style: fn_style,
from_fn: false }
}
}
@ -227,7 +227,7 @@ pub struct FnCtxt<'a> {
err_count_on_creation: uint,
ret_ty: ty::t,
ps: RefCell<PurityState>,
ps: RefCell<FnStyleState>,
// Sometimes we generate region pointers where the precise region
// to use is not known. For example, an expression like `&x.f`
@ -281,7 +281,7 @@ fn blank_fn_ctxt<'a>(ccx: &'a CrateCtxt<'a>,
FnCtxt {
err_count_on_creation: ccx.tcx.sess.err_count(),
ret_ty: rty,
ps: RefCell::new(PurityState::function(ast::ImpureFn, 0)),
ps: RefCell::new(FnStyleState::function(ast::NormalFn, 0)),
region_lb: Cell::new(region_bnd),
fn_kind: Vanilla,
inh: inh,
@ -335,7 +335,7 @@ fn check_bare_fn(ccx: &CrateCtxt,
match ty::get(fty).sty {
ty::ty_bare_fn(ref fn_ty) => {
let inh = Inherited::new(ccx.tcx, param_env);
let fcx = check_fn(ccx, fn_ty.purity, &fn_ty.sig,
let fcx = check_fn(ccx, fn_ty.fn_style, &fn_ty.sig,
decl, id, body, Vanilla, &inh);
vtable::resolve_in_block(&fcx, body);
@ -415,7 +415,7 @@ impl<'a> Visitor<()> for GatherLocalsVisitor<'a> {
}
fn check_fn<'a>(ccx: &'a CrateCtxt<'a>,
purity: ast::Purity,
fn_style: ast::FnStyle,
fn_sig: &ty::FnSig,
decl: &ast::FnDecl,
id: ast::NodeId,
@ -456,7 +456,7 @@ fn check_fn<'a>(ccx: &'a CrateCtxt<'a>,
let fcx = FnCtxt {
err_count_on_creation: err_count_on_creation,
ret_ty: ret_ty,
ps: RefCell::new(PurityState::function(purity, id)),
ps: RefCell::new(FnStyleState::function(fn_style, id)),
region_lb: Cell::new(body.id),
fn_kind: fn_kind,
inh: inherited,
@ -2127,7 +2127,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
// fresh bound regions for any bound regions we find in the
// expected types so as to avoid capture.
//
// Also try to pick up inferred purity and sigil, defaulting
// Also try to pick up inferred style and sigil, defaulting
// to impure and block. Note that we only will use those for
// block syntax lambdas; that is, lambdas without explicit
// sigils.
@ -2136,7 +2136,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
|x| Some((*x).clone()));
let error_happened = false;
let (expected_sig,
expected_purity,
expected_style,
expected_sigil,
expected_onceness,
expected_bounds) = {
@ -2146,7 +2146,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
replace_late_bound_regions_in_fn_sig(
tcx, &cenv.sig,
|_| fcx.inh.infcx.fresh_bound_region(expr.id));
(Some(sig), cenv.purity, cenv.sigil,
(Some(sig), cenv.fn_style, cenv.sigil,
cenv.onceness, cenv.bounds)
}
_ => {
@ -2162,7 +2162,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
}
_ => ()
}
(None, ast::ImpureFn, sigil,
(None, ast::NormalFn, sigil,
onceness, bounds)
}
}
@ -2170,9 +2170,9 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
// If the proto is specified, use that, otherwise select a
// proto based on inference.
let (sigil, purity) = match ast_sigil_opt {
Some(p) => (p, ast::ImpureFn),
None => (expected_sigil, expected_purity)
let (sigil, fn_style) = match ast_sigil_opt {
Some(p) => (p, ast::NormalFn),
None => (expected_sigil, expected_style)
};
// construct the function type
@ -2180,7 +2180,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
fcx.infcx(),
expr.id,
sigil,
purity,
fn_style,
expected_onceness,
expected_bounds,
&None,
@ -2208,13 +2208,13 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
fcx.write_ty(expr.id, fty);
let (inherited_purity, id) =
ty::determine_inherited_purity((fcx.ps.borrow().purity,
let (inherited_style, id) =
ty::determine_inherited_style((fcx.ps.borrow().fn_style,
fcx.ps.borrow().def),
(purity, expr.id),
(fn_style, expr.id),
sigil);
check_fn(fcx.ccx, inherited_purity, &fty_sig,
check_fn(fcx.ccx, inherited_style, &fty_sig,
decl, id, body, fn_kind, fcx.inh);
}
@ -3272,8 +3272,8 @@ pub fn check_block_with_expected(fcx: &FnCtxt,
expected: Option<ty::t>) {
let prev = {
let mut fcx_ps = fcx.ps.borrow_mut();
let purity_state = fcx_ps.recurse(blk);
replace(&mut *fcx_ps, purity_state)
let fn_style_state = fcx_ps.recurse(blk);
replace(&mut *fcx_ps, fn_style_state)
};
fcx.with_region_lb(blk.id, || {
@ -4223,7 +4223,7 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &ast::ForeignItem) {
}
};
let fty = ty::mk_bare_fn(tcx, ty::BareFnTy {
purity: ast::UnsafeFn,
fn_style: ast::UnsafeFn,
abi: abi::RustIntrinsic,
sig: FnSig {binder_id: it.id,
inputs: inputs,

View File

@ -200,14 +200,14 @@ pub fn ensure_trait_methods(ccx: &CrateCtxt, trait_id: ast::NodeId) {
ty_method_of_trait_method(
ccx, trait_id, &trait_ty_generics,
&m.id, &m.ident, &m.explicit_self,
&m.generics, &m.purity, m.decl)
&m.generics, &m.fn_style, m.decl)
}
&ast::Provided(ref m) => {
ty_method_of_trait_method(
ccx, trait_id, &trait_ty_generics,
&m.id, &m.ident, &m.explicit_self,
&m.generics, &m.purity, m.decl)
&m.generics, &m.fn_style, m.decl)
}
};
@ -376,11 +376,11 @@ pub fn ensure_trait_methods(ccx: &CrateCtxt, trait_id: ast::NodeId) {
m_ident: &ast::Ident,
m_explicit_self: &ast::ExplicitSelf,
m_generics: &ast::Generics,
m_purity: &ast::Purity,
m_fn_style: &ast::FnStyle,
m_decl: &ast::FnDecl) -> ty::Method
{
let trait_self_ty = ty::mk_self(this.tcx, local_def(trait_id));
let fty = astconv::ty_of_method(this, *m_id, *m_purity, trait_self_ty,
let fty = astconv::ty_of_method(this, *m_id, *m_fn_style, trait_self_ty,
*m_explicit_self, m_decl);
let num_trait_type_params = trait_generics.type_param_defs().len();
let ty_generics = ty_generics_for_fn_or_method(this, m_generics,
@ -508,7 +508,7 @@ fn convert_methods(ccx: &CrateCtxt,
rcvr_generics: &ast::Generics,
rcvr_visibility: ast::Visibility) -> ty::Method
{
let fty = astconv::ty_of_method(ccx, m.id, m.purity,
let fty = astconv::ty_of_method(ccx, m.id, m.fn_style,
untransformed_rcvr_ty,
m.explicit_self, m.decl);
@ -818,11 +818,11 @@ pub fn ty_of_item(ccx: &CrateCtxt, it: &ast::Item)
tcx.tcache.borrow_mut().insert(local_def(it.id), tpt.clone());
return tpt;
}
ast::ItemFn(decl, purity, abi, ref generics, _) => {
ast::ItemFn(decl, fn_style, abi, ref generics, _) => {
let ty_generics = ty_generics_for_fn_or_method(ccx, generics, 0);
let tofd = astconv::ty_of_bare_fn(ccx,
it.id,
purity,
fn_style,
abi,
decl);
let tpt = ty_param_bounds_and_ty {
@ -1029,7 +1029,7 @@ pub fn ty_of_foreign_fn_decl(ccx: &CrateCtxt,
ccx.tcx,
ty::BareFnTy {
abi: abi,
purity: ast::UnsafeFn,
fn_style: ast::UnsafeFn,
sig: ty::FnSig {binder_id: def_id.node,
inputs: input_tys,
output: output_ty,

View File

@ -385,7 +385,7 @@ impl<'f> Coerce<'f> {
debug!("coerce_from_bare_fn(a={}, b={})",
a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx));
if fn_ty_a.abi != abi::Rust || fn_ty_a.purity != ast::ImpureFn {
if fn_ty_a.abi != abi::Rust || fn_ty_a.fn_style != ast::NormalFn {
return self.subtype(a, b);
}

View File

@ -64,7 +64,7 @@ use util::ppaux::Repr;
use std::result;
use syntax::ast::{Onceness, Purity};
use syntax::ast::{Onceness, FnStyle};
use syntax::ast;
use syntax::owned_slice::OwnedSlice;
use syntax::abi;
@ -194,10 +194,10 @@ pub trait Combine {
fn bare_fn_tys(&self, a: &ty::BareFnTy,
b: &ty::BareFnTy) -> cres<ty::BareFnTy> {
let purity = if_ok!(self.purities(a.purity, b.purity));
let fn_style = if_ok!(self.fn_styles(a.fn_style, b.fn_style));
let abi = if_ok!(self.abi(a.abi, b.abi));
let sig = if_ok!(self.fn_sigs(&a.sig, &b.sig));
Ok(ty::BareFnTy {purity: purity,
Ok(ty::BareFnTy {fn_style: fn_style,
abi: abi,
sig: sig})
}
@ -207,11 +207,11 @@ pub trait Combine {
let p = if_ok!(self.sigils(a.sigil, b.sigil));
let r = if_ok!(self.contraregions(a.region, b.region));
let purity = if_ok!(self.purities(a.purity, b.purity));
let fn_style = if_ok!(self.fn_styles(a.fn_style, b.fn_style));
let onceness = if_ok!(self.oncenesses(a.onceness, b.onceness));
let bounds = if_ok!(self.bounds(a.bounds, b.bounds));
let sig = if_ok!(self.fn_sigs(&a.sig, &b.sig));
Ok(ty::ClosureTy {purity: purity,
Ok(ty::ClosureTy {fn_style: fn_style,
sigil: p,
onceness: onceness,
region: r,
@ -246,7 +246,7 @@ pub trait Combine {
}
}
fn purities(&self, a: Purity, b: Purity) -> cres<Purity>;
fn fn_styles(&self, a: FnStyle, b: FnStyle) -> cres<FnStyle>;
fn abi(&self, a: abi::Abi, b: abi::Abi) -> cres<abi::Abi> {
if a == b {

View File

@ -1102,10 +1102,10 @@ impl<'a> ErrorReportingHelpers for InferCtxt<'a> {
output: ast::P<ast::Ty>,
item: ast::P<ast::Item>,
generics: ast::Generics) {
let (fn_decl, purity, ident) = match item.node {
let (fn_decl, fn_style, ident) = match item.node {
// FIXME: handling method
ast::ItemFn(ref fn_decl, ref purity, _, _, _) => {
(fn_decl, purity, item.ident)
ast::ItemFn(ref fn_decl, ref fn_style, _, _, _) => {
(fn_decl, fn_style, item.ident)
},
_ => fail!("Expect function or method")
@ -1117,7 +1117,7 @@ impl<'a> ErrorReportingHelpers for InferCtxt<'a> {
variadic: fn_decl.variadic
};
let suggested_fn =
pprust::fun_to_str(&fd, *purity, ident, None, &generics);
pprust::fun_to_str(&fd, *fn_style, ident, None, &generics);
let msg = format!("consider using an explicit lifetime \
parameter as shown: {}", suggested_fn);
self.tcx.sess.span_note(item.span, msg);

View File

@ -22,8 +22,8 @@ use middle::typeck::infer::{cres, InferCtxt};
use middle::typeck::infer::{TypeTrace, Subtype};
use middle::typeck::infer::fold_regions_in_sig;
use syntax::ast::{Many, Once, MutImmutable, MutMutable};
use syntax::ast::{ExternFn, ImpureFn, UnsafeFn, NodeId};
use syntax::ast::{Onceness, Purity};
use syntax::ast::{ExternFn, NormalFn, UnsafeFn, NodeId};
use syntax::ast::{Onceness, FnStyle};
use collections::HashMap;
use util::common::{indenter};
use util::ppaux::mt_to_str;
@ -81,10 +81,10 @@ impl<'f> Combine for Glb<'f> {
Lub(*self.get_ref()).tys(a, b)
}
fn purities(&self, a: Purity, b: Purity) -> cres<Purity> {
fn fn_styles(&self, a: FnStyle, b: FnStyle) -> cres<FnStyle> {
match (a, b) {
(ExternFn, _) | (_, ExternFn) => Ok(ExternFn),
(ImpureFn, _) | (_, ImpureFn) => Ok(ImpureFn),
(NormalFn, _) | (_, NormalFn) => Ok(NormalFn),
(UnsafeFn, UnsafeFn) => Ok(UnsafeFn)
}
}

View File

@ -23,8 +23,8 @@ use middle::typeck::infer::fold_regions_in_sig;
use middle::typeck::infer::{TypeTrace, Subtype};
use collections::HashMap;
use syntax::ast::{Many, Once, NodeId};
use syntax::ast::{ExternFn, ImpureFn, UnsafeFn};
use syntax::ast::{Onceness, Purity};
use syntax::ast::{ExternFn, NormalFn, UnsafeFn};
use syntax::ast::{Onceness, FnStyle};
use util::ppaux::mt_to_str;
pub struct Lub<'f>(pub CombineFields<'f>); // least-upper-bound: common supertype
@ -75,10 +75,10 @@ impl<'f> Combine for Lub<'f> {
Glb(*self.get_ref()).tys(a, b)
}
fn purities(&self, a: Purity, b: Purity) -> cres<Purity> {
fn fn_styles(&self, a: FnStyle, b: FnStyle) -> cres<FnStyle> {
match (a, b) {
(UnsafeFn, _) | (_, UnsafeFn) => Ok(UnsafeFn),
(ImpureFn, _) | (_, ImpureFn) => Ok(ImpureFn),
(NormalFn, _) | (_, NormalFn) => Ok(NormalFn),
(ExternFn, ExternFn) => Ok(ExternFn),
}
}

View File

@ -25,7 +25,7 @@ use middle::typeck::infer::{TypeTrace, Subtype};
use util::common::{indenter};
use util::ppaux::bound_region_to_str;
use syntax::ast::{Onceness, Purity};
use syntax::ast::{Onceness, FnStyle};
pub struct Sub<'f>(pub CombineFields<'f>); // "subtype", "subregion" etc
@ -87,9 +87,9 @@ impl<'f> Combine for Sub<'f> {
}
}
fn purities(&self, a: Purity, b: Purity) -> cres<Purity> {
self.lub().purities(a, b).compare(b, || {
ty::terr_purity_mismatch(expected_found(self, a, b))
fn fn_styles(&self, a: FnStyle, b: FnStyle) -> cres<FnStyle> {
self.lub().fn_styles(a, b).compare(b, || {
ty::terr_fn_style_mismatch(expected_found(self, a, b))
})
}

View File

@ -182,7 +182,7 @@ impl Env {
let inputs = input_tys.map(|t| {mode: ast::expl(ast::by_copy),
ty: *t});
ty::mk_fn(self.tcx, FnTyBase {
meta: FnMeta {purity: ast::ImpureFn,
meta: FnMeta {fn_style: ast::NormalFn,
proto: ast::ProtoBare,
onceness: ast::Many,
region: ty::ReStatic,

View File

@ -357,7 +357,7 @@ fn check_main_fn_ty(ccx: &CrateCtxt,
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, ty::BareFnTy {
purity: ast::ImpureFn,
fn_style: ast::NormalFn,
abi: abi::Rust,
sig: ty::FnSig {
binder_id: main_id,
@ -403,7 +403,7 @@ fn check_start_fn_ty(ccx: &CrateCtxt,
}
let se_ty = ty::mk_bare_fn(tcx, ty::BareFnTy {
purity: ast::ImpureFn,
fn_style: ast::NormalFn,
abi: abi::Rust,
sig: ty::FnSig {
binder_id: start_id,

103
src/librustc/util/fs.rs Normal file
View File

@ -0,0 +1,103 @@
// 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.
use std::io;
use std::io::fs;
use std::os;
/// Returns an absolute path in the filesystem that `path` points to. The
/// returned path does not contain any symlinks in its hierarchy.
pub fn realpath(original: &Path) -> io::IoResult<Path> {
static MAX_LINKS_FOLLOWED: uint = 256;
let original = os::make_absolute(original);
// Right now lstat on windows doesn't work quite well
if cfg!(windows) {
return Ok(original)
}
let result = original.root_path();
let mut result = result.expect("make_absolute has no root_path");
let mut followed = 0;
for part in original.components() {
result.push(part);
loop {
if followed == MAX_LINKS_FOLLOWED {
return Err(io::standard_error(io::InvalidInput))
}
match fs::lstat(&result) {
Err(..) => break,
Ok(ref stat) if stat.kind != io::TypeSymlink => break,
Ok(..) => {
followed += 1;
let path = try!(fs::readlink(&result));
result.pop();
result.push(path);
}
}
}
}
return Ok(result);
}
#[cfg(not(windows), test)]
mod test {
use std::io;
use std::io::fs::{File, symlink, mkdir, mkdir_recursive};
use super::realpath;
use std::io::TempDir;
#[test]
fn realpath_works() {
let tmpdir = TempDir::new("rustc-fs").unwrap();
let tmpdir = realpath(tmpdir.path()).unwrap();
let file = tmpdir.join("test");
let dir = tmpdir.join("test2");
let link = dir.join("link");
let linkdir = tmpdir.join("test3");
File::create(&file).unwrap();
mkdir(&dir, io::UserRWX).unwrap();
symlink(&file, &link).unwrap();
symlink(&dir, &linkdir).unwrap();
assert!(realpath(&tmpdir).unwrap() == tmpdir);
assert!(realpath(&file).unwrap() == file);
assert!(realpath(&link).unwrap() == file);
assert!(realpath(&linkdir).unwrap() == dir);
assert!(realpath(&linkdir.join("link")).unwrap() == file);
}
#[test]
fn realpath_works_tricky() {
let tmpdir = TempDir::new("rustc-fs").unwrap();
let tmpdir = realpath(tmpdir.path()).unwrap();
let a = tmpdir.join("a");
let b = a.join("b");
let c = b.join("c");
let d = a.join("d");
let e = d.join("e");
let f = a.join("f");
mkdir_recursive(&b, io::UserRWX).unwrap();
mkdir_recursive(&d, io::UserRWX).unwrap();
File::create(&f).unwrap();
symlink(&Path::new("../d/e"), &c).unwrap();
symlink(&Path::new("../f"), &e).unwrap();
assert!(realpath(&c).unwrap() == f);
assert!(realpath(&e).unwrap() == f);
}
}

View File

@ -252,7 +252,7 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> ~str {
ty_to_str(cx, input)
}
fn bare_fn_to_str(cx: &ctxt,
purity: ast::Purity,
fn_style: ast::FnStyle,
abi: abi::Abi,
ident: Option<ast::Ident>,
sig: &ty::FnSig)
@ -263,10 +263,10 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> ~str {
format!("extern {} ", abi.to_str())
};
match purity {
ast::ImpureFn => {}
match fn_style {
ast::NormalFn => {}
_ => {
s.push_str(purity.to_str());
s.push_str(fn_style.to_str());
s.push_char(' ');
}
};
@ -305,10 +305,10 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> ~str {
}
}
match cty.purity {
ast::ImpureFn => {}
match cty.fn_style {
ast::NormalFn => {}
_ => {
s.push_str(cty.purity.to_str());
s.push_str(cty.fn_style.to_str());
s.push_char(' ');
}
};
@ -405,7 +405,7 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> ~str {
closure_to_str(cx, *f)
}
ty_bare_fn(ref f) => {
bare_fn_to_str(cx, f.purity, f.abi, None, &f.sig)
bare_fn_to_str(cx, f.fn_style, f.abi, None, &f.sig)
}
ty_infer(infer_ty) => infer_ty.to_str(),
ty_err => ~"[type error]",
@ -812,8 +812,8 @@ impl Repr for ast::Visibility {
impl Repr for ty::BareFnTy {
fn repr(&self, tcx: &ctxt) -> ~str {
format!("BareFnTy \\{purity: {:?}, abi: {}, sig: {}\\}",
self.purity,
format!("BareFnTy \\{fn_style: {:?}, abi: {}, sig: {}\\}",
self.fn_style,
self.abi.to_str(),
self.sig.repr(tcx))
}

View File

@ -356,7 +356,7 @@ impl Clean<Generics> for ast::Generics {
pub struct Method {
pub generics: Generics,
pub self_: SelfTy,
pub purity: ast::Purity,
pub fn_style: ast::FnStyle,
pub decl: FnDecl,
}
@ -383,7 +383,7 @@ impl Clean<Item> for ast::Method {
inner: MethodItem(Method {
generics: self.generics.clean(),
self_: self.explicit_self.clean(),
purity: self.purity.clone(),
fn_style: self.fn_style.clone(),
decl: decl,
}),
}
@ -392,7 +392,7 @@ impl Clean<Item> for ast::Method {
#[deriving(Clone, Encodable, Decodable)]
pub struct TyMethod {
pub purity: ast::Purity,
pub fn_style: ast::FnStyle,
pub decl: FnDecl,
pub generics: Generics,
pub self_: SelfTy,
@ -419,7 +419,7 @@ impl Clean<Item> for ast::TypeMethod {
id: self.id,
visibility: None,
inner: TyMethodItem(TyMethod {
purity: self.purity.clone(),
fn_style: self.fn_style.clone(),
decl: decl,
self_: self.explicit_self.clean(),
generics: self.generics.clean(),
@ -451,7 +451,7 @@ impl Clean<SelfTy> for ast::ExplicitSelf {
pub struct Function {
pub decl: FnDecl,
pub generics: Generics,
pub purity: ast::Purity,
pub fn_style: ast::FnStyle,
}
impl Clean<Item> for doctree::Function {
@ -465,7 +465,7 @@ impl Clean<Item> for doctree::Function {
inner: FunctionItem(Function {
decl: self.decl.clean(),
generics: self.generics.clean(),
purity: self.purity,
fn_style: self.fn_style,
}),
}
}
@ -478,7 +478,7 @@ pub struct ClosureDecl {
pub lifetimes: Vec<Lifetime>,
pub decl: FnDecl,
pub onceness: ast::Onceness,
pub purity: ast::Purity,
pub fn_style: ast::FnStyle,
pub bounds: Vec<TyParamBound>,
}
@ -490,7 +490,7 @@ impl Clean<ClosureDecl> for ast::ClosureTy {
lifetimes: self.lifetimes.clean().move_iter().collect(),
decl: self.decl.clean(),
onceness: self.onceness,
purity: self.purity,
fn_style: self.fn_style,
bounds: match self.bounds {
Some(ref x) => x.clean().move_iter().collect(),
None => Vec::new()
@ -960,7 +960,7 @@ impl Clean<Item> for doctree::Typedef {
#[deriving(Clone, Encodable, Decodable)]
pub struct BareFunctionDecl {
pub purity: ast::Purity,
pub fn_style: ast::FnStyle,
pub generics: Generics,
pub decl: FnDecl,
pub abi: ~str,
@ -969,7 +969,7 @@ pub struct BareFunctionDecl {
impl Clean<BareFunctionDecl> for ast::BareFnTy {
fn clean(&self) -> BareFunctionDecl {
BareFunctionDecl {
purity: self.purity,
fn_style: self.fn_style,
generics: Generics {
lifetimes: self.lifetimes.clean().move_iter().collect(),
type_params: Vec::new(),
@ -1164,7 +1164,7 @@ impl Clean<Item> for ast::ForeignItem {
ForeignFunctionItem(Function {
decl: decl.clean(),
generics: generics.clean(),
purity: ast::ExternFn,
fn_style: ast::ExternFn,
})
}
ast::ForeignItemStatic(ref ty, mutbl) => {

View File

@ -113,7 +113,7 @@ pub struct Function {
pub id: NodeId,
pub name: Ident,
pub vis: ast::Visibility,
pub purity: ast::Purity,
pub fn_style: ast::FnStyle,
pub where: Span,
pub generics: ast::Generics,
}

View File

@ -29,9 +29,9 @@ use html::render::{cache_key, current_location_key};
/// Helper to render an optional visibility with a space after it (if the
/// visibility is preset)
pub struct VisSpace(pub Option<ast::Visibility>);
/// Similarly to VisSpace, this structure is used to render a purity with a
/// Similarly to VisSpace, this structure is used to render a function style with a
/// space after it.
pub struct PuritySpace(pub ast::Purity);
pub struct FnStyleSpace(pub ast::FnStyle);
/// Wrapper struct for properly emitting a method declaration.
pub struct Method<'a>(pub &'a clean::SelfTy, pub &'a clean::FnDecl);
@ -41,9 +41,9 @@ impl VisSpace {
}
}
impl PuritySpace {
pub fn get(&self) -> ast::Purity {
let PuritySpace(v) = *self; v
impl FnStyleSpace {
pub fn get(&self) -> ast::FnStyle {
let FnStyleSpace(v) = *self; v
}
}
@ -343,7 +343,7 @@ impl fmt::Show for clean::Type {
};
write!(f.buf, "{}{}{arrow, select, yes{ -&gt; {ret}} other{}}",
PuritySpace(decl.purity),
FnStyleSpace(decl.fn_style),
match decl.sigil {
ast::OwnedSigil => format!("proc({})", decl.decl.inputs),
ast::BorrowedSigil => format!("{}|{}|", region, decl.decl.inputs),
@ -355,7 +355,7 @@ impl fmt::Show for clean::Type {
}
clean::BareFunction(ref decl) => {
write!(f.buf, "{}{}fn{}{}",
PuritySpace(decl.purity),
FnStyleSpace(decl.fn_style),
match decl.abi {
ref x if "" == *x => ~"",
ref x if "\"Rust\"" == *x => ~"",
@ -472,12 +472,12 @@ impl fmt::Show for VisSpace {
}
}
impl fmt::Show for PuritySpace {
impl fmt::Show for FnStyleSpace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.get() {
ast::UnsafeFn => write!(f.buf, "unsafe "),
ast::ExternFn => write!(f.buf, "extern "),
ast::ImpureFn => Ok(())
ast::NormalFn => Ok(())
}
}
}

View File

@ -133,7 +133,7 @@ pub fn render(w: &mut io::Writer, s: &str, print_toc: bool) -> fmt::Result {
slice::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
let text = str::from_utf8(text).unwrap();
let mut lines = text.lines().filter(|l| stripped_filtered_line(*l).is_none());
let text = lines.collect::<~[&str]>().connect("\n");
let text = lines.collect::<Vec<&str>>().connect("\n");
let buf = buf {
data: text.as_bytes().as_ptr(),
@ -186,7 +186,7 @@ pub fn render(w: &mut io::Writer, s: &str, print_toc: bool) -> fmt::Result {
Some(s) => s.to_lower().into_str(),
None => s.to_owned()
}
}).collect::<~[~str]>().connect("-");
}).collect::<Vec<~str>>().connect("-");
let opaque = unsafe {&mut *(opaque as *mut my_opaque)};
@ -285,7 +285,7 @@ pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
let tests = &mut *(opaque as *mut ::test::Collector);
let text = str::from_utf8(text).unwrap();
let mut lines = text.lines().map(|l| stripped_filtered_line(l).unwrap_or(l));
let text = lines.collect::<~[&str]>().connect("\n");
let text = lines.collect::<Vec<&str>>().connect("\n");
tests.add_test(text, should_fail, no_run, ignore);
})
}

View File

@ -51,7 +51,7 @@ use rustc::util::nodemap::NodeSet;
use clean;
use doctree;
use fold::DocFolder;
use html::format::{VisSpace, Method, PuritySpace};
use html::format::{VisSpace, Method, FnStyleSpace};
use html::layout;
use html::markdown;
use html::markdown::Markdown;
@ -262,10 +262,11 @@ pub fn run(mut krate: clean::Crate, dst: Path) -> io::IoResult<()> {
cache.stack.push(krate.name.clone());
krate = cache.fold_crate(krate);
{
let Cache { search_index: ref mut index,
orphan_methods: ref meths, paths: ref mut paths, ..} = cache;
// Attach all orphan methods to the type's definition if the type
// has since been learned.
let Cache { search_index: ref mut index,
orphan_methods: ref meths, paths: ref paths, ..} = cache;
for &(ref pid, ref item) in meths.iter() {
match paths.find(pid) {
Some(&(ref fqp, _)) => {
@ -280,6 +281,18 @@ pub fn run(mut krate: clean::Crate, dst: Path) -> io::IoResult<()> {
None => {}
}
};
// Prune the paths that do not appear in the index.
let mut unseen: HashSet<ast::NodeId> = paths.keys().map(|&id| id).collect();
for item in index.iter() {
match item.parent {
Some(ref pid) => { unseen.remove(pid); }
None => {}
}
}
for pid in unseen.iter() {
paths.remove(pid);
}
}
// Publish the search index
@ -1178,10 +1191,10 @@ fn item_module(w: &mut Writer, cx: &Context,
fn item_function(w: &mut Writer, it: &clean::Item,
f: &clean::Function) -> fmt::Result {
try!(write!(w, "<pre class='rust fn'>{vis}{purity}fn \
try!(write!(w, "<pre class='rust fn'>{vis}{fn_style}fn \
{name}{generics}{decl}</pre>",
vis = VisSpace(it.visibility),
purity = PuritySpace(f.purity),
fn_style = FnStyleSpace(f.fn_style),
name = it.name.get_ref().as_slice(),
generics = f.generics,
decl = f.decl));
@ -1205,8 +1218,8 @@ fn item_trait(w: &mut Writer, it: &clean::Item,
it.name.get_ref().as_slice(),
t.generics,
parents));
let required = t.methods.iter().filter(|m| m.is_req()).collect::<~[&clean::TraitMethod]>();
let provided = t.methods.iter().filter(|m| !m.is_req()).collect::<~[&clean::TraitMethod]>();
let required = t.methods.iter().filter(|m| m.is_req()).collect::<Vec<&clean::TraitMethod>>();
let provided = t.methods.iter().filter(|m| !m.is_req()).collect::<Vec<&clean::TraitMethod>>();
if t.methods.len() == 0 {
try!(write!(w, "\\{ \\}"));
@ -1292,12 +1305,12 @@ fn item_trait(w: &mut Writer, it: &clean::Item,
}
fn render_method(w: &mut Writer, meth: &clean::Item) -> fmt::Result {
fn fun(w: &mut Writer, it: &clean::Item, purity: ast::Purity,
fn fun(w: &mut Writer, it: &clean::Item, fn_style: ast::FnStyle,
g: &clean::Generics, selfty: &clean::SelfTy,
d: &clean::FnDecl) -> fmt::Result {
write!(w, "{}fn <a href='\\#{ty}.{name}' class='fnname'>{name}</a>\
{generics}{decl}",
match purity {
match fn_style {
ast::UnsafeFn => "unsafe ",
_ => "",
},
@ -1308,10 +1321,10 @@ fn render_method(w: &mut Writer, meth: &clean::Item) -> fmt::Result {
}
match meth.inner {
clean::TyMethodItem(ref m) => {
fun(w, meth, m.purity, &m.generics, &m.self_, &m.decl)
fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl)
}
clean::MethodItem(ref m) => {
fun(w, meth, m.purity, &m.generics, &m.self_, &m.decl)
fun(w, meth, m.fn_style, &m.generics, &m.self_, &m.decl)
}
_ => unreachable!()
}
@ -1502,11 +1515,11 @@ fn render_methods(w: &mut Writer, it: &clean::Item) -> fmt::Result {
let mut non_trait = v.iter().filter(|p| {
p.ref0().trait_.is_none()
});
let non_trait = non_trait.collect::<~[&(clean::Impl, Option<~str>)]>();
let non_trait = non_trait.collect::<Vec<&(clean::Impl, Option<~str>)>>();
let mut traits = v.iter().filter(|p| {
p.ref0().trait_.is_some()
});
let traits = traits.collect::<~[&(clean::Impl, Option<~str>)]>();
let traits = traits.collect::<Vec<&(clean::Impl, Option<~str>)>>();
if non_trait.len() > 0 {
try!(write!(w, "<h2 id='methods'>Methods</h2>"));

View File

@ -137,8 +137,6 @@
val = valLower,
typeFilter = query.type,
results = [],
aa = 0,
bb = 0,
split = valLower.split("::");
//remove empty keywords
@ -150,16 +148,16 @@
}
// quoted values mean literal search
bb = searchWords.length;
var nSearchWords = searchWords.length;
if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
val.charAt(val.length - 1) === val.charAt(0))
{
val = val.substr(1, val.length - 2);
for (aa = 0; aa < bb; aa += 1) {
if (searchWords[aa] === val) {
for (var i = 0; i < nSearchWords; i += 1) {
if (searchWords[i] === val) {
// filter type: ... queries
if (!typeFilter || typeFilter === searchIndex[aa].ty) {
results.push([aa, -1]);
if (!typeFilter || typeFilter === searchIndex[i].ty) {
results.push({id: i, index: -1});
}
}
if (results.length === max) {
@ -170,14 +168,14 @@
// gather matching search results up to a certain maximum
val = val.replace(/\_/g, "");
for (var i = 0; i < split.length; i++) {
for (aa = 0; aa < bb; aa += 1) {
if (searchWords[aa].indexOf(split[i]) > -1 ||
searchWords[aa].indexOf(val) > -1 ||
searchWords[aa].replace(/_/g, "").indexOf(val) > -1)
for (var j = 0; j < nSearchWords; j += 1) {
if (searchWords[j].indexOf(split[i]) > -1 ||
searchWords[j].indexOf(val) > -1 ||
searchWords[j].replace(/_/g, "").indexOf(val) > -1)
{
// filter type: ... queries
if (!typeFilter || typeFilter === searchIndex[aa].ty) {
results.push([aa, searchWords[aa].replace(/_/g, "").indexOf(val)]);
if (!typeFilter || typeFilter === searchIndex[j].ty) {
results.push({id: j, index: searchWords[j].replace(/_/g, "").indexOf(val)});
}
}
if (results.length === max) {
@ -187,13 +185,12 @@
}
}
bb = results.length;
for (aa = 0; aa < bb; aa += 1) {
results[aa].push(searchIndex[results[aa][0]].ty);
results[aa].push(searchIndex[results[aa][0]].path);
results[aa].push(searchIndex[results[aa][0]].name);
results[aa].push(searchIndex[results[aa][0]].parent);
results[aa].push(searchIndex[results[aa][0]].crate);
var nresults = results.length;
for (var i = 0; i < nresults; i += 1) {
results[i].word = searchWords[results[i].id];
results[i].item = searchIndex[results[i].id] || {};
results[i].ty = results[i].item.ty;
results[i].path = results[i].item.path;
}
// if there are no results then return to default and fail
if (results.length === 0) {
@ -202,31 +199,31 @@
// sort by exact match
results.sort(function search_complete_sort0(aaa, bbb) {
if (searchWords[aaa[0]] === valLower &&
searchWords[bbb[0]] !== valLower) {
if (aaa.word === valLower &&
bbb.word !== valLower) {
return 1;
}
});
// first sorting attempt
// sort by item name length
results.sort(function search_complete_sort1(aaa, bbb) {
if (searchWords[aaa[0]].length > searchWords[bbb[0]].length) {
if (aaa.word.length > bbb.word.length) {
return 1;
}
});
// second sorting attempt
// sort by item name
results.sort(function search_complete_sort1(aaa, bbb) {
if (searchWords[aaa[0]].length === searchWords[bbb[0]].length &&
searchWords[aaa[0]] > searchWords[bbb[0]]) {
if (aaa.word.length === bbb.word.length &&
aaa.word > bbb.word) {
return 1;
}
});
// third sorting attempt
// sort by index of keyword in item name
if (results[0][1] !== -1) {
if (results[0].index !== -1) {
results.sort(function search_complete_sort1(aaa, bbb) {
if (aaa[1] > bbb[1] && bbb[1] === 0) {
if (aaa.index > bbb.index && bbb.index === 0) {
return 1;
}
});
@ -234,38 +231,38 @@
// fourth sorting attempt
// sort by type
results.sort(function search_complete_sort3(aaa, bbb) {
if (searchWords[aaa[0]] === searchWords[bbb[0]] &&
aaa[2] > bbb[2]) {
if (aaa.word === bbb.word &&
aaa.ty > bbb.ty) {
return 1;
}
});
// fifth sorting attempt
// sort by path
results.sort(function search_complete_sort4(aaa, bbb) {
if (searchWords[aaa[0]] === searchWords[bbb[0]] &&
aaa[2] === bbb[2] && aaa[3] > bbb[3]) {
if (aaa.word === bbb.word &&
aaa.ty === bbb.ty && aaa.path > bbb.path) {
return 1;
}
});
// sixth sorting attempt
// remove duplicates, according to the data provided
for (aa = results.length - 1; aa > 0; aa -= 1) {
if (searchWords[results[aa][0]] === searchWords[results[aa - 1][0]] &&
results[aa][2] === results[aa - 1][2] &&
results[aa][3] === results[aa - 1][3])
for (var i = results.length - 1; i > 0; i -= 1) {
if (results[i].word === results[i - 1].word &&
results[i].ty === results[i - 1].ty &&
results[i].path === results[i - 1].path)
{
results[aa][0] = -1;
results[i].id = -1;
}
}
for (var i = 0; i < results.length; i++) {
var result = results[i],
name = result[4].toLowerCase(),
path = result[3].toLowerCase(),
parent = allPaths[result[6]][result[5]];
name = result.item.name.toLowerCase(),
path = result.item.path.toLowerCase(),
parent = allPaths[result.item.crate][result.item.parent];
var valid = validateResult(name, path, split, parent);
if (!valid) {
result[0] = -1;
result.id = -1;
}
}
return results;
@ -495,8 +492,8 @@
resultIndex = execQuery(query, 20000, index);
len = resultIndex.length;
for (i = 0; i < len; i += 1) {
if (resultIndex[i][0] > -1) {
obj = searchIndex[resultIndex[i][0]];
if (resultIndex[i].id > -1) {
obj = searchIndex[resultIndex[i].id];
filterdata.push([obj.name, obj.ty, obj.path, obj.desc]);
results.push(obj);
}
@ -580,7 +577,6 @@
// Draw a convenient sidebar of known crates if we have a listing
if (rootPath == '../') {
console.log('here');
var sidebar = $('.sidebar');
var div = $('<div>').attr('class', 'block crate');
div.append($('<h2>').text('Crates'));

View File

@ -161,12 +161,12 @@ pub fn render(input: &str, mut output: Path, matches: &getopts::Matches) -> int
}
/// Run any tests/code examples in the markdown file `input`.
pub fn test(input: &str, libs: HashSet<Path>, mut test_args: ~[~str]) -> int {
pub fn test(input: &str, libs: HashSet<Path>, mut test_args: Vec<~str>) -> int {
let input_str = load_or_return!(input, 1, 2);
let mut collector = Collector::new(input.to_owned(), libs, true, true);
find_testable_code(input_str, &mut collector);
test_args.unshift(~"rustdoctest");
testing::test_main(test_args, collector.tests);
testing::test_main(test_args.as_slice(), collector.tests);
0
}

View File

@ -95,7 +95,7 @@ impl<'a> RustdocVisitor<'a> {
}
pub fn visit_fn(&mut self, item: &ast::Item, fd: &ast::FnDecl,
purity: &ast::Purity, _abi: &abi::Abi,
fn_style: &ast::FnStyle, _abi: &abi::Abi,
gen: &ast::Generics) -> Function {
debug!("Visiting fn");
Function {
@ -106,7 +106,7 @@ impl<'a> RustdocVisitor<'a> {
name: item.ident,
where: item.span,
generics: gen.clone(),
purity: *purity,
fn_style: *fn_style,
}
}

View File

@ -31,7 +31,7 @@ pub struct Guard<'a> {
}
struct Inner {
queue: ~[BlockedTask],
queue: Vec<BlockedTask>,
held: bool,
}
@ -39,7 +39,7 @@ impl Access {
pub fn new() -> Access {
Access {
inner: UnsafeArc::new(Inner {
queue: ~[],
queue: vec![],
held: false,
})
}

View File

@ -152,13 +152,13 @@ impl FsRequest {
}
pub fn readdir(loop_: &Loop, path: &CString, flags: c_int)
-> Result<~[Path], UvError>
-> Result<Vec<Path>, UvError>
{
execute(|req, cb| unsafe {
uvll::uv_fs_readdir(loop_.handle,
req, path.with_ref(|p| p), flags, cb)
}).map(|req| unsafe {
let mut paths = ~[];
let mut paths = vec!();
let path = CString::new(path.with_ref(|p| p), false);
let parent = Path::new(path);
let _ = c_str::from_c_multistring(req.get_ptr() as *libc::c_char,

View File

@ -234,7 +234,7 @@ impl IoFactory for UvIoFactory {
r.map_err(uv_error_to_io_error)
}
fn fs_readdir(&mut self, path: &CString, flags: c_int)
-> Result<~[Path], IoError>
-> Result<Vec<Path>, IoError>
{
let r = FsRequest::readdir(&self.loop_, path, flags);
r.map_err(uv_error_to_io_error)

View File

@ -636,7 +636,7 @@ pub mod writer {
// ebml writing
pub struct Encoder<'a, W> {
pub writer: &'a mut W,
size_positions: ~[uint],
size_positions: Vec<uint>,
}
fn write_sized_vuint<W: Writer>(w: &mut W, n: uint, size: uint) -> EncodeResult {
@ -668,10 +668,9 @@ pub mod writer {
}
pub fn Encoder<'a, W: Writer + Seek>(w: &'a mut W) -> Encoder<'a, W> {
let size_positions: ~[uint] = ~[];
Encoder {
writer: w,
size_positions: size_positions,
size_positions: vec!(),
}
}

View File

@ -10,7 +10,6 @@
//! Types dealing with dynamic mutability
use cast;
use clone::Clone;
use cmp::Eq;
use fmt;
@ -70,7 +69,7 @@ impl<T: Copy + fmt::Show> fmt::Show for Cell<T> {
/// A mutable memory location with dynamically checked borrow rules
pub struct RefCell<T> {
value: Unsafe<T>,
borrow: BorrowFlag,
borrow: Cell<BorrowFlag>,
nocopy: marker::NoCopy,
noshare: marker::NoShare,
}
@ -86,22 +85,18 @@ impl<T> RefCell<T> {
pub fn new(value: T) -> RefCell<T> {
RefCell {
value: Unsafe::new(value),
borrow: Cell::new(UNUSED),
nocopy: marker::NoCopy,
noshare: marker::NoShare,
borrow: UNUSED,
}
}
/// Consumes the `RefCell`, returning the wrapped value.
pub fn unwrap(self) -> T {
assert!(self.borrow == UNUSED);
assert!(self.borrow.get() == UNUSED);
unsafe{self.value.unwrap()}
}
unsafe fn as_mut<'a>(&'a self) -> &'a mut RefCell<T> {
cast::transmute_mut(self)
}
/// Attempts to immutably borrow the wrapped value.
///
/// The borrow lasts until the returned `Ref` exits scope. Multiple
@ -109,10 +104,10 @@ impl<T> RefCell<T> {
///
/// Returns `None` if the value is currently mutably borrowed.
pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> {
match self.borrow {
match self.borrow.get() {
WRITING => None,
_ => {
unsafe { self.as_mut().borrow += 1; }
borrow => {
self.borrow.set(borrow + 1);
Some(Ref { parent: self })
}
}
@ -140,11 +135,10 @@ impl<T> RefCell<T> {
///
/// Returns `None` if the value is currently borrowed.
pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> {
match self.borrow {
UNUSED => unsafe {
let mut_self = self.as_mut();
mut_self.borrow = WRITING;
Some(RefMut { parent: mut_self })
match self.borrow.get() {
UNUSED => {
self.borrow.set(WRITING);
Some(RefMut { parent: self })
},
_ => None
}
@ -186,8 +180,9 @@ pub struct Ref<'b, T> {
#[unsafe_destructor]
impl<'b, T> Drop for Ref<'b, T> {
fn drop(&mut self) {
assert!(self.parent.borrow != WRITING && self.parent.borrow != UNUSED);
unsafe { self.parent.as_mut().borrow -= 1; }
let borrow = self.parent.borrow.get();
assert!(borrow != WRITING && borrow != UNUSED);
self.parent.borrow.set(borrow - 1);
}
}
@ -200,14 +195,15 @@ impl<'b, T> Deref<T> for Ref<'b, T> {
/// Wraps a mutable borrowed reference to a value in a `RefCell` box.
pub struct RefMut<'b, T> {
parent: &'b mut RefCell<T>
parent: &'b RefCell<T>
}
#[unsafe_destructor]
impl<'b, T> Drop for RefMut<'b, T> {
fn drop(&mut self) {
assert!(self.parent.borrow == WRITING);
self.parent.borrow = UNUSED;
let borrow = self.parent.borrow.get();
assert!(borrow == WRITING);
self.parent.borrow.set(UNUSED);
}
}

View File

@ -131,13 +131,13 @@ pub enum Method<'a> {
///
/// The final element of this enum is the default "other" case which is
/// always required to be specified.
Plural(Option<uint>, ~[PluralArm<'a>], ~[Piece<'a>]),
Plural(Option<uint>, Vec<PluralArm<'a>>, Vec<Piece<'a>>),
/// A select method selects over a string. Each arm is a different string
/// which can be selected for.
///
/// As with `Plural`, a default "other" case is required as well.
Select(~[SelectArm<'a>], ~[Piece<'a>]),
Select(Vec<SelectArm<'a>>, Vec<Piece<'a>>),
}
/// A selector for what pluralization a plural method should take
@ -156,7 +156,7 @@ pub struct PluralArm<'a> {
/// literal.
pub selector: PluralSelector,
/// Array of pieces which are the format of this arm
pub result: ~[Piece<'a>],
pub result: Vec<Piece<'a>>,
}
/// Enum of the 5 CLDR plural keywords. There is one more, "other", but that
@ -184,7 +184,7 @@ pub struct SelectArm<'a> {
/// String selector which guards this arm
pub selector: &'a str,
/// Array of pieces which are the format of this arm
pub result: ~[Piece<'a>],
pub result: Vec<Piece<'a>>,
}
/// The parser structure for interpreting the input format string. This is
@ -198,7 +198,7 @@ pub struct Parser<'a> {
cur: str::CharOffsets<'a>,
depth: uint,
/// Error messages accumulated during parsing
pub errors: ~[~str],
pub errors: Vec<~str>,
}
impl<'a> Iterator<Piece<'a>> for Parser<'a> {
@ -236,7 +236,7 @@ impl<'a> Parser<'a> {
input: s,
cur: s.char_indices(),
depth: 0,
errors: ~[],
errors: vec!(),
}
}
@ -463,7 +463,7 @@ impl<'a> Parser<'a> {
/// Parses a 'select' statement (after the initial 'select' word)
fn select(&mut self) -> ~Method<'a> {
let mut other = None;
let mut arms = ~[];
let mut arms = vec!();
// Consume arms one at a time
loop {
self.ws();
@ -496,7 +496,7 @@ impl<'a> Parser<'a> {
Some(arm) => { arm }
None => {
self.err("`select` statement must provide an `other` case");
~[]
vec!()
}
};
~Select(arms, other)
@ -506,7 +506,7 @@ impl<'a> Parser<'a> {
fn plural(&mut self) -> ~Method<'a> {
let mut offset = None;
let mut other = None;
let mut arms = ~[];
let mut arms = vec!();
// First, attempt to parse the 'offset:' field. We know the set of
// selector words which can appear in plural arms, and the only ones
@ -594,7 +594,7 @@ impl<'a> Parser<'a> {
Some(arm) => { arm }
None => {
self.err("`plural` statement must provide an `other` case");
~[]
vec!()
}
};
~Plural(offset, arms, other)
@ -684,9 +684,9 @@ mod tests {
use super::*;
use prelude::*;
fn same(fmt: &'static str, p: ~[Piece<'static>]) {
fn same(fmt: &'static str, p: &[Piece<'static>]) {
let mut parser = Parser::new(fmt);
assert!(p == parser.collect());
assert!(p == parser.collect::<Vec<Piece<'static>>>().as_slice());
}
fn fmtdflt() -> FormatSpec<'static> {
@ -708,12 +708,12 @@ mod tests {
#[test]
fn simple() {
same("asdf", ~[String("asdf")]);
same("a\\{b", ~[String("a"), String("{b")]);
same("a\\#b", ~[String("a"), String("#b")]);
same("a\\}b", ~[String("a"), String("}b")]);
same("a\\}", ~[String("a"), String("}")]);
same("\\}", ~[String("}")]);
same("asdf", [String("asdf")]);
same("a\\{b", [String("a"), String("{b")]);
same("a\\#b", [String("a"), String("#b")]);
same("a\\}b", [String("a"), String("}b")]);
same("a\\}", [String("a"), String("}")]);
same("\\}", [String("}")]);
}
#[test] fn invalid01() { musterr("{") }
@ -725,7 +725,7 @@ mod tests {
#[test]
fn format_nothing() {
same("{}", ~[Argument(Argument {
same("{}", [Argument(Argument {
position: ArgumentNext,
format: fmtdflt(),
method: None,
@ -733,7 +733,7 @@ mod tests {
}
#[test]
fn format_position() {
same("{3}", ~[Argument(Argument {
same("{3}", [Argument(Argument {
position: ArgumentIs(3),
format: fmtdflt(),
method: None,
@ -741,7 +741,7 @@ mod tests {
}
#[test]
fn format_position_nothing_else() {
same("{3:}", ~[Argument(Argument {
same("{3:}", [Argument(Argument {
position: ArgumentIs(3),
format: fmtdflt(),
method: None,
@ -749,7 +749,7 @@ mod tests {
}
#[test]
fn format_type() {
same("{3:a}", ~[Argument(Argument {
same("{3:a}", [Argument(Argument {
position: ArgumentIs(3),
format: FormatSpec {
fill: None,
@ -764,7 +764,7 @@ mod tests {
}
#[test]
fn format_align_fill() {
same("{3:>}", ~[Argument(Argument {
same("{3:>}", [Argument(Argument {
position: ArgumentIs(3),
format: FormatSpec {
fill: None,
@ -776,7 +776,7 @@ mod tests {
},
method: None,
})]);
same("{3:0<}", ~[Argument(Argument {
same("{3:0<}", [Argument(Argument {
position: ArgumentIs(3),
format: FormatSpec {
fill: Some('0'),
@ -788,7 +788,7 @@ mod tests {
},
method: None,
})]);
same("{3:*<abcd}", ~[Argument(Argument {
same("{3:*<abcd}", [Argument(Argument {
position: ArgumentIs(3),
format: FormatSpec {
fill: Some('*'),
@ -803,7 +803,7 @@ mod tests {
}
#[test]
fn format_counts() {
same("{:10s}", ~[Argument(Argument {
same("{:10s}", [Argument(Argument {
position: ArgumentNext,
format: FormatSpec {
fill: None,
@ -815,7 +815,7 @@ mod tests {
},
method: None,
})]);
same("{:10$.10s}", ~[Argument(Argument {
same("{:10$.10s}", [Argument(Argument {
position: ArgumentNext,
format: FormatSpec {
fill: None,
@ -827,7 +827,7 @@ mod tests {
},
method: None,
})]);
same("{:.*s}", ~[Argument(Argument {
same("{:.*s}", [Argument(Argument {
position: ArgumentNext,
format: FormatSpec {
fill: None,
@ -839,7 +839,7 @@ mod tests {
},
method: None,
})]);
same("{:.10$s}", ~[Argument(Argument {
same("{:.10$s}", [Argument(Argument {
position: ArgumentNext,
format: FormatSpec {
fill: None,
@ -851,7 +851,7 @@ mod tests {
},
method: None,
})]);
same("{:a$.b$s}", ~[Argument(Argument {
same("{:a$.b$s}", [Argument(Argument {
position: ArgumentNext,
format: FormatSpec {
fill: None,
@ -866,7 +866,7 @@ mod tests {
}
#[test]
fn format_flags() {
same("{:-}", ~[Argument(Argument {
same("{:-}", [Argument(Argument {
position: ArgumentNext,
format: FormatSpec {
fill: None,
@ -878,7 +878,7 @@ mod tests {
},
method: None,
})]);
same("{:+#}", ~[Argument(Argument {
same("{:+#}", [Argument(Argument {
position: ArgumentNext,
format: FormatSpec {
fill: None,
@ -893,7 +893,7 @@ mod tests {
}
#[test]
fn format_mixture() {
same("abcd {3:a} efg", ~[String("abcd "), Argument(Argument {
same("abcd {3:a} efg", [String("abcd "), Argument(Argument {
position: ArgumentIs(3),
format: FormatSpec {
fill: None,
@ -909,42 +909,42 @@ mod tests {
#[test]
fn select_simple() {
same("{, select, other { haha } }", ~[Argument(Argument{
same("{, select, other { haha } }", [Argument(Argument{
position: ArgumentNext,
format: fmtdflt(),
method: Some(~Select(~[], ~[String(" haha ")]))
method: Some(~Select(vec![], vec![String(" haha ")]))
})]);
same("{1, select, other { haha } }", ~[Argument(Argument{
same("{1, select, other { haha } }", [Argument(Argument{
position: ArgumentIs(1),
format: fmtdflt(),
method: Some(~Select(~[], ~[String(" haha ")]))
method: Some(~Select(vec![], vec![String(" haha ")]))
})]);
same("{1, select, other {#} }", ~[Argument(Argument{
same("{1, select, other {#} }", [Argument(Argument{
position: ArgumentIs(1),
format: fmtdflt(),
method: Some(~Select(~[], ~[CurrentArgument]))
method: Some(~Select(vec![], vec![CurrentArgument]))
})]);
same("{1, select, other {{2, select, other {lol}}} }", ~[Argument(Argument{
same("{1, select, other {{2, select, other {lol}}} }", [Argument(Argument{
position: ArgumentIs(1),
format: fmtdflt(),
method: Some(~Select(~[], ~[Argument(Argument{
method: Some(~Select(vec![], vec![Argument(Argument{
position: ArgumentIs(2),
format: fmtdflt(),
method: Some(~Select(~[], ~[String("lol")]))
method: Some(~Select(vec![], vec![String("lol")]))
})])) // wat
})]);
}
#[test]
fn select_cases() {
same("{1, select, a{1} b{2} c{3} other{4} }", ~[Argument(Argument{
same("{1, select, a{1} b{2} c{3} other{4} }", [Argument(Argument{
position: ArgumentIs(1),
format: fmtdflt(),
method: Some(~Select(~[
SelectArm{ selector: "a", result: ~[String("1")] },
SelectArm{ selector: "b", result: ~[String("2")] },
SelectArm{ selector: "c", result: ~[String("3")] },
], ~[String("4")]))
method: Some(~Select(vec![
SelectArm{ selector: "a", result: vec![String("1")] },
SelectArm{ selector: "b", result: vec![String("2")] },
SelectArm{ selector: "c", result: vec![String("3")] },
], vec![String("4")]))
})]);
}
@ -961,25 +961,25 @@ mod tests {
#[test]
fn plural_simple() {
same("{, plural, other { haha } }", ~[Argument(Argument{
same("{, plural, other { haha } }", [Argument(Argument{
position: ArgumentNext,
format: fmtdflt(),
method: Some(~Plural(None, ~[], ~[String(" haha ")]))
method: Some(~Plural(None, vec![], vec![String(" haha ")]))
})]);
same("{:, plural, other { haha } }", ~[Argument(Argument{
same("{:, plural, other { haha } }", [Argument(Argument{
position: ArgumentNext,
format: fmtdflt(),
method: Some(~Plural(None, ~[], ~[String(" haha ")]))
method: Some(~Plural(None, vec![], vec![String(" haha ")]))
})]);
same("{, plural, offset:1 =2{2} =3{3} many{yes} other{haha} }",
~[Argument(Argument{
[Argument(Argument{
position: ArgumentNext,
format: fmtdflt(),
method: Some(~Plural(Some(1), ~[
PluralArm{ selector: Literal(2), result: ~[String("2")] },
PluralArm{ selector: Literal(3), result: ~[String("3")] },
PluralArm{ selector: Keyword(Many), result: ~[String("yes")] }
], ~[String("haha")]))
method: Some(~Plural(Some(1), vec![
PluralArm{ selector: Literal(2), result: vec![String("2")] },
PluralArm{ selector: Literal(3), result: vec![String("3")] },
PluralArm{ selector: Keyword(Many), result: vec![String("yes")] }
], vec![String("haha")]))
})]);
}
}

View File

@ -21,7 +21,7 @@ use option::{Option, Some, None};
use result::{Ok, Err};
use io;
use io::{IoError, IoResult, Reader};
use slice::{OwnedVector, ImmutableVector};
use slice::{OwnedVector, ImmutableVector, Vector};
use ptr::RawPtr;
/// An iterator that reads a single byte on each iteration,
@ -88,7 +88,7 @@ pub fn u64_to_le_bytes<T>(n: u64, size: uint, f: |v: &[u8]| -> T) -> T {
8u => f(unsafe { transmute::<i64, [u8, ..8]>(to_le64(n as i64)) }),
_ => {
let mut bytes: ~[u8] = ~[];
let mut bytes = vec!();
let mut i = size;
let mut n = n;
while i > 0u {
@ -96,7 +96,7 @@ pub fn u64_to_le_bytes<T>(n: u64, size: uint, f: |v: &[u8]| -> T) -> T {
n >>= 8_u64;
i -= 1u;
}
f(bytes)
f(bytes.as_slice())
}
}
}
@ -127,14 +127,14 @@ pub fn u64_to_be_bytes<T>(n: u64, size: uint, f: |v: &[u8]| -> T) -> T {
4u => f(unsafe { transmute::<i32, [u8, ..4]>(to_be32(n as i32)) }),
8u => f(unsafe { transmute::<i64, [u8, ..8]>(to_be64(n as i64)) }),
_ => {
let mut bytes: ~[u8] = ~[];
let mut bytes = vec!();
let mut i = size;
while i > 0u {
let shift = ((i - 1u) * 8u) as u64;
bytes.push((n >> shift) as u8);
i -= 1u;
}
f(bytes)
f(bytes.as_slice())
}
}
}

View File

@ -483,7 +483,7 @@ pub fn rmdir(path: &Path) -> IoResult<()> {
/// Will return an error if the provided `from` doesn't exist, the process lacks
/// permissions to view the contents or if the `path` points at a non-directory
/// file
pub fn readdir(path: &Path) -> IoResult<~[Path]> {
pub fn readdir(path: &Path) -> IoResult<Vec<Path>> {
LocalIo::maybe_raise(|io| {
io.fs_readdir(&path.to_c_str(), 0)
})
@ -498,7 +498,7 @@ pub fn walk_dir(path: &Path) -> IoResult<Directories> {
/// An iterator which walks over a directory
pub struct Directories {
stack: ~[Path],
stack: Vec<Path>,
}
impl Iterator<Path> for Directories {

View File

@ -29,6 +29,7 @@ use option::{Some, None};
use result::{Ok, Err};
use rt::rtio::{IoFactory, LocalIo, RtioSignal};
use slice::{ImmutableVector, OwnedVector};
use vec::Vec;
/// Signals that can be sent and received
#[repr(int)]
@ -80,7 +81,7 @@ pub enum Signum {
/// ```
pub struct Listener {
/// A map from signums to handles to keep the handles in memory
handles: ~[(Signum, ~RtioSignal:Send)],
handles: Vec<(Signum, ~RtioSignal:Send)>,
/// This is where all the handles send signums, which are received by
/// the clients from the receiver.
tx: Sender<Signum>,
@ -99,7 +100,7 @@ impl Listener {
Listener {
tx: tx,
rx: rx,
handles: ~[],
handles: vec!(),
}
}

View File

@ -39,7 +39,6 @@ macro_rules! iotest (
use io::process::*;
use unstable::running_on_valgrind;
use str;
use util;
fn f() $b

View File

@ -47,6 +47,7 @@ use mem::replace;
use option::{None, Option, Some};
use rt::task::{Task, LocalStorage};
use slice::{ImmutableVector, MutableVector, OwnedVector};
use vec::Vec;
/**
* Indexes a task-local data slot. This pointer is used for comparison to
@ -89,7 +90,7 @@ impl<T: 'static> LocalData for T {}
// n.b. If TLS is used heavily in future, this could be made more efficient with
// a proper map.
#[doc(hidden)]
pub type Map = ~[Option<(*u8, TLSValue, LoanState)>];
pub type Map = Vec<Option<(*u8, TLSValue, LoanState)>>;
type TLSValue = ~LocalData:Send;
// Gets the map from the runtime. Lazily initialises if not done so already.
@ -106,7 +107,7 @@ unsafe fn get_local_map() -> &mut Map {
// If this is the first time we've accessed TLS, perform similar
// actions to the oldsched way of doing things.
&LocalStorage(ref mut slot) => {
*slot = Some(~[]);
*slot = Some(vec!());
match *slot {
Some(ref mut map_ptr) => { return map_ptr }
None => abort()
@ -237,7 +238,7 @@ fn get_with<T:'static,
Some(i) => {
let ret;
let mut return_loan = false;
match map[i] {
match *map.get_mut(i) {
Some((_, ref data, ref mut loan)) => {
match (state, *loan) {
(_, NoLoan) => {
@ -271,7 +272,7 @@ fn get_with<T:'static,
// in turn relocated the vector. Hence we do another lookup here to
// fixup the loans.
if return_loan {
match map[i] {
match *map.get_mut(i) {
Some((_, _, ref mut loan)) => { *loan = NoLoan; }
None => abort()
}
@ -331,7 +332,7 @@ pub fn set<T: 'static>(key: Key<T>, data: T) {
// we're not actually sending it to other schedulers or anything.
let data: ~LocalData:Send = unsafe { cast::transmute(data) };
match insertion_position(map, keyval) {
Some(i) => { map[i] = Some((keyval, data, NoLoan)); }
Some(i) => { *map.get_mut(i) = Some((keyval, data, NoLoan)); }
None => { map.push(Some((keyval, data, NoLoan))); }
}
}

View File

@ -31,6 +31,7 @@ use to_str::ToStr;
use slice::{Vector, OwnedVector};
use intrinsics::{Disr, Opaque, TyDesc, TyVisitor, get_tydesc, visit_tydesc};
use raw;
use vec::Vec;
macro_rules! try( ($me:expr, $e:expr) => (
match $e {
@ -102,8 +103,8 @@ enum VariantState {
pub struct ReprVisitor<'a> {
ptr: *u8,
ptr_stk: ~[*u8],
var_stk: ~[VariantState],
ptr_stk: Vec<*u8>,
var_stk: Vec<VariantState>,
writer: &'a mut io::Writer,
last_err: Option<io::IoError>,
}
@ -112,8 +113,8 @@ pub fn ReprVisitor<'a>(ptr: *u8,
writer: &'a mut io::Writer) -> ReprVisitor<'a> {
ReprVisitor {
ptr: ptr,
ptr_stk: ~[],
var_stk: ~[],
ptr_stk: vec!(),
var_stk: vec!(),
writer: writer,
last_err: None,
}
@ -154,8 +155,8 @@ impl<'a> ReprVisitor<'a> {
// issues we have to recreate it here.
let u = ReprVisitor {
ptr: ptr,
ptr_stk: ~[],
var_stk: ~[],
ptr_stk: vec!(),
var_stk: vec!(),
writer: ::cast::transmute_copy(&self.writer),
last_err: None,
};
@ -505,7 +506,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> {
_offset: uint,
inner: *TyDesc)
-> bool {
match self.var_stk[self.var_stk.len() - 1] {
match *self.var_stk.get(self.var_stk.len() - 1) {
Matched => {
if i != 0 {
try!(self, self.writer.write(", ".as_bytes()));
@ -523,7 +524,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> {
_disr_val: Disr,
n_fields: uint,
_name: &str) -> bool {
match self.var_stk[self.var_stk.len() - 1] {
match *self.var_stk.get(self.var_stk.len() - 1) {
Matched => {
if n_fields > 0 {
try!(self, self.writer.write([')' as u8]));

View File

@ -20,8 +20,9 @@ use option::{Some, None};
use ptr::RawPtr;
use unstable::sync::Exclusive;
use slice::OwnedVector;
use vec::Vec;
type Queue = Exclusive<~[proc():Send]>;
type Queue = Exclusive<Vec<proc():Send>>;
// You'll note that these variables are *not* atomic, and this is done on
// purpose. This module is designed to have init() called *once* in a
@ -35,7 +36,7 @@ pub fn init() {
unsafe {
rtassert!(!RUNNING);
rtassert!(QUEUE.is_null());
let state: ~Queue = ~Exclusive::new(~[]);
let state: ~Queue = ~Exclusive::new(vec!());
QUEUE = cast::transmute(state);
}
}
@ -61,7 +62,7 @@ pub fn run() {
QUEUE = 0 as *mut Queue;
let mut vec = None;
state.with(|arr| {
vec = Some(mem::replace(arr, ~[]));
vec = Some(mem::replace(arr, vec!()));
});
vec.take_unwrap()
};

View File

@ -20,6 +20,7 @@ use path::Path;
use result::Err;
use rt::local::Local;
use rt::task::Task;
use vec::Vec;
use ai = io::net::addrinfo;
use io;
@ -168,7 +169,7 @@ pub trait IoFactory {
fn fs_rmdir(&mut self, path: &CString) -> IoResult<()>;
fn fs_rename(&mut self, path: &CString, to: &CString) -> IoResult<()>;
fn fs_readdir(&mut self, path: &CString, flags: c_int) ->
IoResult<~[Path]>;
IoResult<Vec<Path>>;
fn fs_lstat(&mut self, path: &CString) -> IoResult<FileStat>;
fn fs_chown(&mut self, path: &CString, uid: int, gid: int) ->
IoResult<()>;

View File

@ -62,6 +62,7 @@ use sync::arc::UnsafeArc;
use sync::atomics::{AtomicInt, AtomicPtr, SeqCst};
use unstable::sync::Exclusive;
use slice::{OwnedVector, ImmutableVector};
use vec::Vec;
// Once the queue is less than 1/K full, then it will be downsized. Note that
// the deque requires that this number be less than 2.
@ -116,14 +117,14 @@ pub enum Stolen<T> {
/// will only use this structure when allocating a new buffer or deallocating a
/// previous one.
pub struct BufferPool<T> {
pool: Exclusive<~[~Buffer<T>]>,
pool: Exclusive<Vec<~Buffer<T>>>,
}
/// An internal buffer used by the chase-lev deque. This structure is actually
/// implemented as a circular buffer, and is used as the intermediate storage of
/// the data in the deque.
///
/// This type is implemented with *T instead of ~[T] for two reasons:
/// This type is implemented with *T instead of Vec<T> for two reasons:
///
/// 1. There is nothing safe about using this buffer. This easily allows the
/// same value to be read twice in to rust, and there is nothing to
@ -132,7 +133,7 @@ pub struct BufferPool<T> {
/// destructors for values in this buffer (on drop) because the bounds
/// are defined by the deque it's owned by.
///
/// 2. We can certainly avoid bounds checks using *T instead of ~[T], although
/// 2. We can certainly avoid bounds checks using *T instead of Vec<T>, although
/// LLVM is probably pretty good at doing this already.
struct Buffer<T> {
storage: *T,
@ -143,7 +144,7 @@ impl<T: Send> BufferPool<T> {
/// Allocates a new buffer pool which in turn can be used to allocate new
/// deques.
pub fn new() -> BufferPool<T> {
BufferPool { pool: Exclusive::new(~[]) }
BufferPool { pool: Exclusive::new(vec!()) }
}
/// Allocates a new work-stealing deque which will send/receiving memory to
@ -494,7 +495,7 @@ mod tests {
}
}
})
}).collect::<~[Thread<()>]>();
}).collect::<Vec<Thread<()>>>();
while remaining.load(SeqCst) > 0 {
match w.pop() {
@ -525,7 +526,7 @@ mod tests {
Thread::start(proc() {
stampede(w, s, 4, 10000);
})
}).collect::<~[Thread<()>]>();
}).collect::<Vec<Thread<()>>>();
for thread in threads.move_iter() {
thread.join();
@ -556,7 +557,7 @@ mod tests {
}
}
})
}).collect::<~[Thread<()>]>();
}).collect::<Vec<Thread<()>>>();
let mut rng = rand::task_rng();
let mut expected = 0;
@ -658,4 +659,3 @@ mod tests {
}
}
}

View File

@ -35,7 +35,7 @@ use num::next_power_of_two;
use option::{Option, Some, None};
use sync::arc::UnsafeArc;
use sync::atomics::{AtomicUint,Relaxed,Release,Acquire};
use slice;
use vec::Vec;
struct Node<T> {
sequence: AtomicUint,
@ -44,7 +44,7 @@ struct Node<T> {
struct State<T> {
pad0: [u8, ..64],
buffer: ~[Node<T>],
buffer: Vec<Node<T>>,
mask: uint,
pad1: [u8, ..64],
enqueue_pos: AtomicUint,
@ -69,7 +69,7 @@ impl<T: Send> State<T> {
} else {
capacity
};
let buffer = slice::from_fn(capacity, |i| {
let buffer = Vec::from_fn(capacity, |i| {
Node { sequence:AtomicUint::new(i), value: None }
});
State{
@ -88,7 +88,7 @@ impl<T: Send> State<T> {
let mask = self.mask;
let mut pos = self.enqueue_pos.load(Relaxed);
loop {
let node = &mut self.buffer[pos & mask];
let node = self.buffer.get_mut(pos & mask);
let seq = node.sequence.load(Acquire);
let diff: int = seq as int - pos as int;
@ -114,7 +114,7 @@ impl<T: Send> State<T> {
let mask = self.mask;
let mut pos = self.dequeue_pos.load(Relaxed);
loop {
let node = &mut self.buffer[pos & mask];
let node = self.buffer.get_mut(pos & mask);
let seq = node.sequence.load(Acquire);
let diff: int = seq as int - (pos + 1) as int;
if diff == 0 {
@ -186,7 +186,7 @@ mod tests {
});
}
let mut completion_rxs = ~[];
let mut completion_rxs = vec![];
for _ in range(0, nthreads) {
let (tx, rx) = channel();
completion_rxs.push(rx);

View File

@ -210,8 +210,8 @@ pub enum MethodProvenance {
#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum Def {
DefFn(DefId, Purity),
DefStaticMethod(/* method */ DefId, MethodProvenance, Purity),
DefFn(DefId, FnStyle),
DefStaticMethod(/* method */ DefId, MethodProvenance, FnStyle),
DefSelfTy(/* trait id */ NodeId),
DefMod(DefId),
DefForeignMod(DefId),
@ -696,7 +696,7 @@ pub struct TypeField {
pub struct TypeMethod {
pub ident: Ident,
pub attrs: Vec<Attribute>,
pub purity: Purity,
pub fn_style: FnStyle,
pub decl: P<FnDecl>,
pub generics: Generics,
pub explicit_self: ExplicitSelf,
@ -794,7 +794,7 @@ pub struct ClosureTy {
pub sigil: Sigil,
pub region: Option<Lifetime>,
pub lifetimes: Vec<Lifetime>,
pub purity: Purity,
pub fn_style: FnStyle,
pub onceness: Onceness,
pub decl: P<FnDecl>,
// Optional optvec distinguishes between "fn()" and "fn:()" so we can
@ -806,7 +806,7 @@ pub struct ClosureTy {
#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct BareFnTy {
pub purity: Purity,
pub fn_style: FnStyle,
pub abi: Abi,
pub lifetimes: Vec<Lifetime>,
pub decl: P<FnDecl>
@ -886,16 +886,16 @@ pub struct FnDecl {
}
#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum Purity {
pub enum FnStyle {
UnsafeFn, // declared with "unsafe fn"
ImpureFn, // declared with "fn"
NormalFn, // declared with "fn"
ExternFn, // declared with "extern fn"
}
impl fmt::Show for Purity {
impl fmt::Show for FnStyle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ImpureFn => "impure".fmt(f),
NormalFn => "normal".fmt(f),
UnsafeFn => "unsafe".fmt(f),
ExternFn => "extern".fmt(f),
}
@ -925,7 +925,7 @@ pub struct Method {
pub attrs: Vec<Attribute>,
pub generics: Generics,
pub explicit_self: ExplicitSelf,
pub purity: Purity,
pub fn_style: FnStyle,
pub decl: P<FnDecl>,
pub body: P<Block>,
pub id: NodeId,
@ -1119,7 +1119,7 @@ pub struct Item {
#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum Item_ {
ItemStatic(P<Ty>, Mutability, @Expr),
ItemFn(P<FnDecl>, Purity, Abi, Generics, P<Block>),
ItemFn(P<FnDecl>, FnStyle, Abi, Generics, P<Block>),
ItemMod(Mod),
ItemForeignMod(ForeignMod),
ItemTy(P<Ty>, Generics),

View File

@ -264,7 +264,7 @@ pub fn trait_method_to_ty_method(method: &TraitMethod) -> TypeMethod {
TypeMethod {
ident: m.ident,
attrs: m.attrs.clone(),
purity: m.purity,
fn_style: m.fn_style,
decl: m.decl,
generics: m.generics.clone(),
explicit_self: m.explicit_self,

View File

@ -825,7 +825,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> {
name,
Vec::new(),
ast::ItemFn(self.fn_decl(inputs, output),
ast::ImpureFn,
ast::NormalFn,
abi::Rust,
generics,
body))

View File

@ -619,7 +619,7 @@ impl<'a> MethodDef<'a> {
attrs: attrs,
generics: fn_generics,
explicit_self: explicit_self,
purity: ast::ImpureFn,
fn_style: ast::NormalFn,
decl: fn_decl,
body: body_block,
id: ast::DUMMY_NODE_ID,

View File

@ -242,9 +242,9 @@ impl<'a, 'b> Context<'a, 'b> {
}
}
}
self.verify_pieces(arm.result);
self.verify_pieces(arm.result.as_slice());
}
self.verify_pieces(*default);
self.verify_pieces(default.as_slice());
}
parse::Select(ref arms, ref default) => {
self.verify_arg_type(pos, String);
@ -258,9 +258,9 @@ impl<'a, 'b> Context<'a, 'b> {
self.ecx.span_err(self.fmtsp,
"empty selector in `select`");
}
self.verify_pieces(arm.result);
self.verify_pieces(arm.result.as_slice());
}
self.verify_pieces(*default);
self.verify_pieces(default.as_slice());
}
}
self.nest_level -= 1;

View File

@ -158,7 +158,7 @@ pub trait Folder {
TyClosure(ref f) => {
TyClosure(@ClosureTy {
sigil: f.sigil,
purity: f.purity,
fn_style: f.fn_style,
region: fold_opt_lifetime(&f.region, self),
onceness: f.onceness,
bounds: fold_opt_bounds(&f.bounds, self),
@ -169,7 +169,7 @@ pub trait Folder {
TyBareFn(ref f) => {
TyBareFn(@BareFnTy {
lifetimes: f.lifetimes.iter().map(|l| fold_lifetime(l, self)).collect(),
purity: f.purity,
fn_style: f.fn_style,
abi: f.abi,
decl: self.fold_fn_decl(f.decl)
})
@ -549,10 +549,10 @@ pub fn noop_fold_item_underscore<T: Folder>(i: &Item_, folder: &mut T) -> Item_
ItemStatic(t, m, e) => {
ItemStatic(folder.fold_ty(t), m, folder.fold_expr(e))
}
ItemFn(decl, purity, abi, ref generics, body) => {
ItemFn(decl, fn_style, abi, ref generics, body) => {
ItemFn(
folder.fold_fn_decl(decl),
purity,
fn_style,
abi,
fold_generics(generics, folder),
folder.fold_block(body)
@ -603,7 +603,7 @@ pub fn noop_fold_type_method<T: Folder>(m: &TypeMethod, fld: &mut T) -> TypeMeth
id: fld.new_id(m.id), // Needs to be first, for ast_map.
ident: fld.fold_ident(m.ident),
attrs: m.attrs.iter().map(|a| fold_attribute_(*a, fld)).collect(),
purity: m.purity,
fn_style: m.fn_style,
decl: fld.fold_fn_decl(m.decl),
generics: fold_generics(&m.generics, fld),
explicit_self: fld.fold_explicit_self(&m.explicit_self),
@ -680,7 +680,7 @@ pub fn noop_fold_method<T: Folder>(m: &Method, folder: &mut T) -> @Method {
attrs: m.attrs.iter().map(|a| fold_attribute_(*a, folder)).collect(),
generics: fold_generics(&m.generics, folder),
explicit_self: folder.fold_explicit_self(&m.explicit_self),
purity: m.purity,
fn_style: m.fn_style,
decl: folder.fold_fn_decl(m.decl),
body: folder.fold_block(m.body),
span: folder.new_span(m.span),

View File

@ -657,7 +657,7 @@ mod test {
cf: ast::Return,
variadic: false
}),
ast::ImpureFn,
ast::NormalFn,
abi::Rust,
ast::Generics{ // no idea on either of these:
lifetimes: Vec::new(),

View File

@ -14,7 +14,7 @@ use abi;
use ast::{Sigil, BorrowedSigil, ManagedSigil, OwnedSigil};
use ast::{BareFnTy, ClosureTy};
use ast::{RegionTyParamBound, TraitTyParamBound};
use ast::{Provided, Public, Purity};
use ast::{Provided, Public, FnStyle};
use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
use ast::{BiBitAnd, BiBitOr, BiBitXor, Block};
use ast::{BlockCheckMode, UnBox};
@ -31,7 +31,7 @@ use ast::{ExprVec, ExprVstore, ExprVstoreSlice};
use ast::{ExprVstoreMutSlice, ExprWhile, ExprForLoop, ExternFn, Field, FnDecl};
use ast::{ExprVstoreUniq, Once, Many};
use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod};
use ast::{Ident, ImpureFn, Inherited, Item, Item_, ItemStatic};
use ast::{Ident, NormalFn, Inherited, Item, Item_, ItemStatic};
use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl};
use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, Lit, Lit_};
use ast::{LitBool, LitFloat, LitFloatUnsuffixed, LitInt, LitChar};
@ -867,7 +867,7 @@ impl<'a> Parser<'a> {
| | | Argument types
| | Lifetimes
| |
| Purity
| Function Style
ABI
*/
@ -878,12 +878,12 @@ impl<'a> Parser<'a> {
abi::Rust
};
let purity = self.parse_unsafety();
let fn_style = self.parse_unsafety();
self.expect_keyword(keywords::Fn);
let (decl, lifetimes) = self.parse_ty_fn_decl(true);
return TyBareFn(@BareFnTy {
abi: abi,
purity: purity,
fn_style: fn_style,
lifetimes: lifetimes,
decl: decl
});
@ -925,7 +925,7 @@ impl<'a> Parser<'a> {
TyClosure(@ClosureTy {
sigil: OwnedSigil,
region: None,
purity: ImpureFn,
fn_style: NormalFn,
onceness: Once,
bounds: bounds,
decl: decl,
@ -945,11 +945,11 @@ impl<'a> Parser<'a> {
| | | Argument types
| | Lifetimes
| Once-ness (a.k.a., affine)
Purity
Function Style
*/
let purity = self.parse_unsafety();
let fn_style = self.parse_unsafety();
let onceness = if self.eat_keyword(keywords::Once) {Once} else {Many};
let lifetimes = if self.eat(&token::LT) {
@ -985,7 +985,7 @@ impl<'a> Parser<'a> {
TyClosure(@ClosureTy {
sigil: BorrowedSigil,
region: region,
purity: purity,
fn_style: fn_style,
onceness: onceness,
bounds: bounds,
decl: decl,
@ -993,11 +993,11 @@ impl<'a> Parser<'a> {
})
}
pub fn parse_unsafety(&mut self) -> Purity {
pub fn parse_unsafety(&mut self) -> FnStyle {
if self.eat_keyword(keywords::Unsafe) {
return UnsafeFn;
} else {
return ImpureFn;
return NormalFn;
}
}
@ -1045,7 +1045,7 @@ impl<'a> Parser<'a> {
let vis_span = p.span;
let vis = p.parse_visibility();
let pur = p.parse_fn_purity();
let style = p.parse_fn_style();
// NB: at the moment, trait methods are public by default; this
// could change.
let ident = p.parse_ident();
@ -1071,7 +1071,7 @@ impl<'a> Parser<'a> {
Required(TypeMethod {
ident: ident,
attrs: attrs,
purity: pur,
fn_style: style,
decl: d,
generics: generics,
explicit_self: explicit_self,
@ -1089,7 +1089,7 @@ impl<'a> Parser<'a> {
attrs: attrs,
generics: generics,
explicit_self: explicit_self,
purity: pur,
fn_style: style,
decl: d,
body: body,
id: ast::DUMMY_NODE_ID,
@ -3754,11 +3754,11 @@ impl<'a> Parser<'a> {
}
// parse an item-position function declaration.
fn parse_item_fn(&mut self, purity: Purity, abi: abi::Abi) -> ItemInfo {
fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
let (ident, generics) = self.parse_fn_header();
let decl = self.parse_fn_decl(false);
let (inner_attrs, body) = self.parse_inner_attrs_and_block();
(ident, ItemFn(decl, purity, abi, generics, body), Some(inner_attrs))
(ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
}
// parse a method in a trait impl, starting with `attrs` attributes.
@ -3772,7 +3772,7 @@ impl<'a> Parser<'a> {
let lo = self.span.lo;
let visa = self.parse_visibility();
let pur = self.parse_fn_purity();
let fn_style = self.parse_fn_style();
let ident = self.parse_ident();
let generics = self.parse_generics();
let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
@ -3787,7 +3787,7 @@ impl<'a> Parser<'a> {
attrs: attrs,
generics: generics,
explicit_self: explicit_self,
purity: pur,
fn_style: fn_style,
decl: decl,
body: body,
id: ast::DUMMY_NODE_ID,
@ -4169,8 +4169,8 @@ impl<'a> Parser<'a> {
let lo = self.span.lo;
// Parse obsolete purity.
let purity = self.parse_fn_purity();
if purity != ImpureFn {
let fn_style = self.parse_fn_style();
if fn_style != NormalFn {
self.obsolete(self.last_span, ObsoleteUnsafeExternFn);
}
@ -4208,8 +4208,8 @@ impl<'a> Parser<'a> {
}
// parse safe/unsafe and fn
fn parse_fn_purity(&mut self) -> Purity {
if self.eat_keyword(keywords::Fn) { ImpureFn }
fn parse_fn_style(&mut self) -> FnStyle {
if self.eat_keyword(keywords::Fn) { NormalFn }
else if self.eat_keyword(keywords::Unsafe) {
self.expect_keyword(keywords::Fn);
UnsafeFn
@ -4540,7 +4540,7 @@ impl<'a> Parser<'a> {
// FUNCTION ITEM
self.bump();
let (ident, item_, extra_attrs) =
self.parse_item_fn(ImpureFn, abi::Rust);
self.parse_item_fn(NormalFn, abi::Rust);
let item = self.mk_item(lo,
self.last_span.hi,
ident,

View File

@ -186,11 +186,11 @@ pub fn path_to_str(p: &ast::Path) -> ~str {
to_str(|s| s.print_path(p, false))
}
pub fn fun_to_str(decl: &ast::FnDecl, purity: ast::Purity, name: ast::Ident,
pub fn fun_to_str(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident,
opt_explicit_self: Option<ast::ExplicitSelf_>,
generics: &ast::Generics) -> ~str {
to_str(|s| {
try!(s.print_fn(decl, Some(purity), abi::Rust,
try!(s.print_fn(decl, Some(fn_style), abi::Rust,
name, generics, opt_explicit_self, ast::Inherited));
try!(s.end()); // Close the head box
s.end() // Close the outer box
@ -479,7 +479,7 @@ impl<'a> State<'a> {
ty_params: OwnedSlice::empty()
};
try!(self.print_ty_fn(Some(f.abi), None, &None,
f.purity, ast::Many, f.decl, None, &None,
f.fn_style, ast::Many, f.decl, None, &None,
Some(&generics), None));
}
ast::TyClosure(f) => {
@ -488,7 +488,7 @@ impl<'a> State<'a> {
ty_params: OwnedSlice::empty()
};
try!(self.print_ty_fn(None, Some(f.sigil), &f.region,
f.purity, f.onceness, f.decl, None, &f.bounds,
f.fn_style, f.onceness, f.decl, None, &f.bounds,
Some(&generics), None));
}
ast::TyPath(ref path, ref bounds, _) => {
@ -567,10 +567,10 @@ impl<'a> State<'a> {
try!(word(&mut self.s, ";"));
try!(self.end()); // end the outer cbox
}
ast::ItemFn(decl, purity, abi, ref typarams, body) => {
ast::ItemFn(decl, fn_style, abi, ref typarams, body) => {
try!(self.print_fn(
decl,
Some(purity),
Some(fn_style),
abi,
item.ident,
typarams,
@ -861,7 +861,7 @@ impl<'a> State<'a> {
try!(self.print_ty_fn(None,
None,
&None,
m.purity,
m.fn_style,
ast::Many,
m.decl,
Some(m.ident),
@ -883,7 +883,7 @@ impl<'a> State<'a> {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(meth.span.lo));
try!(self.print_outer_attributes(meth.attrs.as_slice()));
try!(self.print_fn(meth.decl, Some(meth.purity), abi::Rust,
try!(self.print_fn(meth.decl, Some(meth.fn_style), abi::Rust,
meth.ident, &meth.generics, Some(meth.explicit_self.node),
meth.vis));
try!(word(&mut self.s, " "));
@ -1708,14 +1708,14 @@ impl<'a> State<'a> {
pub fn print_fn(&mut self,
decl: &ast::FnDecl,
purity: Option<ast::Purity>,
fn_style: Option<ast::FnStyle>,
abi: abi::Abi,
name: ast::Ident,
generics: &ast::Generics,
opt_explicit_self: Option<ast::ExplicitSelf_>,
vis: ast::Visibility) -> IoResult<()> {
try!(self.head(""));
try!(self.print_fn_header_info(opt_explicit_self, purity, abi,
try!(self.print_fn_header_info(opt_explicit_self, fn_style, abi,
ast::Many, None, vis));
try!(self.nbsp());
try!(self.print_ident(name));
@ -2024,7 +2024,7 @@ impl<'a> State<'a> {
opt_abi: Option<abi::Abi>,
opt_sigil: Option<ast::Sigil>,
opt_region: &Option<ast::Lifetime>,
purity: ast::Purity,
fn_style: ast::FnStyle,
onceness: ast::Onceness,
decl: &ast::FnDecl,
id: Option<ast::Ident>,
@ -2040,12 +2040,12 @@ impl<'a> State<'a> {
try!(word(&mut self.s, "proc"));
} else if opt_sigil == Some(ast::BorrowedSigil) {
try!(self.print_extern_opt_abi(opt_abi));
try!(self.print_purity(purity));
try!(self.print_fn_style(fn_style));
try!(self.print_onceness(onceness));
} else {
try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
try!(self.print_opt_sigil(opt_sigil));
try!(self.print_purity(purity));
try!(self.print_fn_style(fn_style));
try!(self.print_onceness(onceness));
try!(word(&mut self.s, "fn"));
}
@ -2294,10 +2294,10 @@ impl<'a> State<'a> {
}
}
pub fn print_opt_purity(&mut self,
opt_purity: Option<ast::Purity>) -> IoResult<()> {
match opt_purity {
Some(purity) => self.print_purity(purity),
pub fn print_opt_fn_style(&mut self,
opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
match opt_fn_style {
Some(fn_style) => self.print_fn_style(fn_style),
None => Ok(())
}
}
@ -2338,7 +2338,7 @@ impl<'a> State<'a> {
pub fn print_fn_header_info(&mut self,
_opt_explicit_self: Option<ast::ExplicitSelf_>,
opt_purity: Option<ast::Purity>,
opt_fn_style: Option<ast::FnStyle>,
abi: abi::Abi,
onceness: ast::Onceness,
opt_sigil: Option<ast::Sigil>,
@ -2349,11 +2349,11 @@ impl<'a> State<'a> {
try!(self.word_nbsp("extern"));
try!(self.word_nbsp(abi.to_str()));
if opt_purity != Some(ast::ExternFn) {
try!(self.print_opt_purity(opt_purity));
if opt_fn_style != Some(ast::ExternFn) {
try!(self.print_opt_fn_style(opt_fn_style));
}
} else {
try!(self.print_opt_purity(opt_purity));
try!(self.print_opt_fn_style(opt_fn_style));
}
try!(self.print_onceness(onceness));
@ -2361,9 +2361,9 @@ impl<'a> State<'a> {
self.print_opt_sigil(opt_sigil)
}
pub fn print_purity(&mut self, p: ast::Purity) -> IoResult<()> {
match p {
ast::ImpureFn => Ok(()),
pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
match s {
ast::NormalFn => Ok(()),
ast::UnsafeFn => self.word_nbsp("unsafe"),
ast::ExternFn => self.word_nbsp("extern")
}
@ -2399,7 +2399,7 @@ mod test {
variadic: false
};
let generics = ast_util::empty_generics();
assert_eq!(&fun_to_str(&decl, ast::ImpureFn, abba_ident,
assert_eq!(&fun_to_str(&decl, ast::NormalFn, abba_ident,
None, &generics),
&~"fn abba()");
}

View File

@ -29,7 +29,7 @@ use owned_slice::OwnedSlice;
pub enum FnKind<'a> {
// fn foo() or extern "Abi" fn foo()
FkItemFn(Ident, &'a Generics, Purity, Abi),
FkItemFn(Ident, &'a Generics, FnStyle, Abi),
// fn foo(&self)
FkMethod(Ident, &'a Generics, &'a Method),
@ -207,8 +207,8 @@ pub fn walk_item<E: Clone, V: Visitor<E>>(visitor: &mut V, item: &Item, env: E)
visitor.visit_ty(typ, env.clone());
visitor.visit_expr(expr, env);
}
ItemFn(declaration, purity, abi, ref generics, body) => {
visitor.visit_fn(&FkItemFn(item.ident, generics, purity, abi),
ItemFn(declaration, fn_style, abi, ref generics, body) => {
visitor.visit_fn(&FkItemFn(item.ident, generics, fn_style, abi),
declaration,
body,
item.span,

View File

@ -170,14 +170,14 @@ impl<'a> Stats for &'a [f64] {
// FIXME #11059 handle NaN, inf and overflow
#[allow(deprecated_owned_vector)]
fn sum(self) -> f64 {
let mut partials : ~[f64] = ~[];
let mut partials = vec![];
for &mut x in self.iter() {
let mut j = 0;
// This inner loop applies `hi`/`lo` summation to each
// partial so that the list of partial sums remains exact.
for i in range(0, partials.len()) {
let mut y = partials[i];
let mut y = *partials.get(i);
if num::abs(x) < num::abs(y) {
mem::swap(&mut x, &mut y);
}
@ -186,7 +186,7 @@ impl<'a> Stats for &'a [f64] {
let hi = x + y;
let lo = y - (hi - x);
if lo != 0f64 {
partials[j] = lo;
*partials.get_mut(j) = lo;
j += 1;
}
x = hi;
@ -194,7 +194,7 @@ impl<'a> Stats for &'a [f64] {
if j >= partials.len() {
partials.push(x);
} else {
partials[j] = x;
*partials.get_mut(j) = x;
partials.truncate(j+1);
}
}

View File

@ -17,6 +17,7 @@
html_root_url = "http://static.rust-lang.org/doc/master")]
#![feature(phase)]
#![allow(visible_private_types)]
#![deny(deprecated_owned_vector)]
#[phase(syntax, link)] extern crate log;
extern crate serialize;
@ -319,8 +320,8 @@ impl Exec {
}
// returns pairs of (kind, name)
pub fn lookup_discovered_inputs(&self) -> ~[(~str, ~str)] {
let mut rs = ~[];
pub fn lookup_discovered_inputs(&self) -> Vec<(~str, ~str)> {
let mut rs = vec![];
let WorkMap(ref discovered_inputs) = self.discovered_inputs;
for (k, v) in discovered_inputs.iter() {
let KindMap(ref vmap) = *v;
@ -341,8 +342,8 @@ impl<'a> Prep<'a> {
}
}
pub fn lookup_declared_inputs(&self) -> ~[~str] {
let mut rs = ~[];
pub fn lookup_declared_inputs(&self) -> Vec<~str> {
let mut rs = vec![];
let WorkMap(ref declared_inputs) = self.declared_inputs;
for (_, v) in declared_inputs.iter() {
let KindMap(ref vmap) = *v;

View File

@ -0,0 +1,13 @@
// 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.
pub mod bar {
pub fn foo() {}
}

View File

@ -0,0 +1,11 @@
// 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.
pub fn baz() {}

View File

@ -0,0 +1,27 @@
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_type = "lib"]
// compile-flags:-g
pub use private::P;
pub struct S {
p: P,
}
mod private {
pub struct P {
p: i32,
}
pub static THREE: P = P { p: 3 };
}
pub static A: S = S { p: private::THREE };

View File

@ -76,7 +76,7 @@ fn main() {
format!("{}\t trees of depth {}\t check: {}",
iterations * 2, depth, chk)
})
}).collect::<~[Future<~str>]>();
}).collect::<Vec<Future<~str>>>();
for message in messages.mut_iter() {
println!("{}", *message.get_ref());

View File

@ -0,0 +1,24 @@
// 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.
// aux-build:issue-12612-1.rs
extern crate foo = "issue-12612-1";
use foo::bar;
mod test {
use bar::foo;
//~^ ERROR: unresolved import
//~^^ ERROR: failed to resolve import
}
fn main() {}

View File

@ -0,0 +1,21 @@
// 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.
use a::f;
use b::f;
//~^ ERROR: unresolved import
//~^^ ERROR: failed to resolve import
mod a { pub fn f() {} }
mod b { }
fn main() {
f();
}

View File

@ -11,13 +11,15 @@
trait A {}
struct Struct {
r: A //~ ERROR reference to trait `A` where a type is expected
r: A //~ ERROR reference to trait `A` where a type is expected; try `~A` or `&A`
}
fn new_struct(r: A) -> Struct { //~ ERROR reference to trait `A` where a type is expected
fn new_struct(r: A) -> Struct {
//~^ ERROR reference to trait `A` where a type is expected; try `~A` or `&A`
Struct { r: r }
}
trait Curve {}
enum E {X(Curve)} //~ ERROR reference to trait `Curve` where a type is expected
enum E {X(Curve)}
//~^ ERROR reference to trait `Curve` where a type is expected; try `~Curve` or `&Curve`
fn main() {}

View File

@ -0,0 +1,56 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(globs)]
#![deny(unused_imports)]
#![allow(dead_code)]
mod test1 {
mod foo { pub fn p() -> int { 1 } }
mod bar { pub fn p() -> int { 2 } }
pub mod baz {
use test1::foo::*; //~ ERROR: unused import
use test1::bar::*;
pub fn my_main() { assert!(p() == 2); }
}
}
mod test2 {
mod foo { pub fn p() -> int { 1 } }
mod bar { pub fn p() -> int { 2 } }
pub mod baz {
use test2::foo::p; //~ ERROR: unused import
use test2::bar::p;
pub fn my_main() { assert!(p() == 2); }
}
}
mod test3 {
mod foo { pub fn p() -> int { 1 } }
mod bar { pub fn p() -> int { 2 } }
pub mod baz {
use test3::foo::*; //~ ERROR: unused import
use test3::bar::p;
pub fn my_main() { assert!(p() == 2); }
}
}
fn main() {
}

View File

@ -29,7 +29,7 @@ fn make_gc() -> @get_ctxt {
let ctxt = ctxt { v: 22u };
let hc = has_ctxt { c: &ctxt };
return @hc as @get_ctxt;
//^~ ERROR source contains reference
//~^ ERROR source contains reference
}
fn main() {

View File

@ -0,0 +1,33 @@
// 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.
mod a {
pub fn foobar() -> int { 1 }
}
mod b {
pub fn foobar() -> int { 2 }
}
mod c {
// Technically the second use shadows the first, but in theory it should
// only be shadowed for this module. The implementation of resolve currently
// doesn't implement this, so this test is ensuring that using "c::foobar"
// is *not* getting b::foobar. Today it's an error, but perhaps one day it
// can correctly get a::foobar instead.
pub use a::foobar;
use b::foobar;
}
fn main() {
assert_eq!(c::foobar(), 1);
//~^ ERROR: unresolved name `c::foobar`
}

View File

@ -13,7 +13,8 @@ trait Foo {
// This should emit the less confusing error, not the more confusing one.
fn foo(_x: Foo:Send) { //~ERROR reference to trait `Foo` where a type is expected
fn foo(_x: Foo:Send) {
//~^ERROR reference to trait `Foo` where a type is expected; try `~Foo` or `&Foo`
}
fn main() { }

View File

@ -17,7 +17,7 @@ trait Mumbo {
impl Mumbo for uint {
// Cannot have a larger effect than the trait:
unsafe fn jumbo(&self, x: @uint) { *self + *x; }
//~^ ERROR expected impure fn but found unsafe fn
//~^ ERROR expected normal fn but found unsafe fn
}
fn main() {}

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