提交 b495933a 编写于 作者: B bors

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

......@@ -51,7 +51,7 @@
TARGET_CRATES := libc std green rustuv native flate arena glob term semver \
uuid serialize sync getopts collections num test time rand \
url log regex graphviz core rlibc alloc debug rustrt \
url log regex graphviz core rbml rlibc alloc debug rustrt \
unicode
HOST_CRATES := syntax rustc rustdoc fourcc hexfloat regex_macros fmt_macros \
rustc_llvm rustc_back
......@@ -71,7 +71,7 @@ DEPS_green := std native:context_switch
DEPS_rustuv := std native:uv native:uv_support
DEPS_native := std
DEPS_syntax := std term serialize log fmt_macros debug
DEPS_rustc := syntax flate arena serialize getopts \
DEPS_rustc := syntax flate arena serialize getopts rbml \
time log graphviz debug rustc_llvm rustc_back
DEPS_rustc_llvm := native:rustllvm libc std
DEPS_rustc_back := std syntax rustc_llvm flate log libc
......@@ -82,6 +82,7 @@ DEPS_arena := std
DEPS_graphviz := std
DEPS_glob := std
DEPS_serialize := std log
DEPS_rbml := std log serialize
DEPS_term := std log
DEPS_semver := std
DEPS_uuid := std serialize
......@@ -91,7 +92,7 @@ DEPS_collections := core alloc unicode
DEPS_fourcc := rustc syntax std
DEPS_hexfloat := rustc syntax std
DEPS_num := std
DEPS_test := std getopts serialize term time regex native:rust_test_helpers
DEPS_test := std getopts serialize rbml term time regex native:rust_test_helpers
DEPS_time := std serialize
DEPS_rand := core
DEPS_url := std
......
% Language FAQ
## Are there any big programs written in it yet? I want to read big samples.
There aren't many large programs yet. The Rust [compiler][rustc], 60,000+ lines at the time of writing, is written in Rust. As the oldest body of Rust code it has gone through many iterations of the language, and some parts are nicer to look at than others. It may not be the best code to learn from, but [borrowck] and [resolve] were written recently.
......@@ -29,6 +28,18 @@ You may also be interested in browsing [GitHub's Rust][github-rust] page.
[github-rust]: https://github.com/trending?l=rust
## Is anyone using Rust in production?
Currently, Rust is still pre-1.0, and so we don't recommend that you use Rust
in production unless you know exactly what you're getting into.
That said, there are two production deployments of Rust that we're aware of:
* [OpenDNS](http://labs.opendns.com/2013/10/04/zeromq-helping-us-block-malicious-domains/)
* [Skylight](http://skylight.io)
Let the fact that this is an easily countable number be a warning.
## Does it run on Windows?
Yes. All development happens in lock-step on all 3 target platforms. Using MinGW, not Cygwin. Note that the windows implementation currently has some limitations: in particular 64-bit build is [not fully supported yet][win64], and all executables created by rustc [depend on libgcc DLL at runtime][libgcc].
......
......@@ -431,36 +431,6 @@ In any case, whatever the lifetime of `r` is, the pointer produced by
field of a struct is valid as long as the struct is valid. Therefore,
the compiler accepts the function `get_x()`.
To emphasize this point, let’s look at a variation on the example, this
time one that does not compile:
~~~ {.ignore}
struct Point {x: f64, y: f64}
fn get_x_sh(p: &Point) -> &f64 {
&p.x // Error reported here
}
~~~
Here, the function `get_x_sh()` takes a reference as input and
returns a reference. As before, the lifetime of the reference
that will be returned is a parameter (specified by the
caller). That means that `get_x_sh()` promises to return a reference
that is valid for as long as the caller would like: this is
subtly different from the first example, which promised to return a
pointer that was valid for as long as its pointer argument was valid.
Within `get_x_sh()`, we see the expression `&p.x` which takes the
address of a field of a Point. The presence of this expression
implies that the compiler must guarantee that , so long as the
resulting pointer is valid, the original Point won't be moved or changed.
But recall that `get_x_sh()` also promised to
return a pointer that was valid for as long as the caller wanted it to
be. Clearly, `get_x_sh()` is not in a position to make both of these
guarantees; in fact, it cannot guarantee that the pointer will remain
valid at all once it returns, as the parameter `p` may or may not be
live in the caller. Therefore, the compiler will report an error here.
In general, if you borrow a struct or box to create a
reference, it will only be valid within the function
and cannot be returned. This is why the typical way to return references
......
......@@ -578,12 +578,12 @@ fn main() {
Notice we changed the signature of `add_one()` to request a mutable reference.
# Best practices
## Best practices
Boxes are appropriate to use in two situations: Recursive data structures,
and occasionally, when returning data.
## Recursive data structures
### Recursive data structures
Sometimes, you need a recursive data structure. The simplest is known as a
'cons list':
......@@ -615,7 +615,7 @@ we don't know the size, and therefore, we need to heap allocate our list.
Working with recursive or other unknown-sized data structures is the primary
use-case for boxes.
## Returning data
### Returning data
This is important enough to have its own section entirely. The TL;DR is this:
you don't generally want to return pointers, even when you might in a language
......@@ -733,18 +733,15 @@ This part is coming soon.
Here's a quick rundown of Rust's pointer types:
| Type | Name | Summary |
|--------------|---------------------|-------------------------------------------|
| `&T` | Reference | Allows one or more references to read `T` |
| `&mut T` | Mutable Reference | Allows a single reference to |
| | | read and write `T` |
| `Box<T>` | Box | Heap allocated `T` with a single owner |
| | | that may read and write `T`. |
| `Rc<T>` | "arr cee" pointer | Heap allocated `T` with many readers |
| `Arc<T>` | Arc pointer | Same as above, but safe sharing across |
| | | threads |
| `*const T` | Raw pointer | Unsafe read access to `T` |
| `*mut T` | Mutable raw pointer | Unsafe read and write access to `T` |
| Type | Name | Summary |
|--------------|---------------------|---------------------------------------------------------------------|
| `&T` | Reference | Allows one or more references to read `T` |
| `&mut T` | Mutable Reference | Allows a single reference to read and write `T` |
| `Box<T>` | Box | Heap allocated `T` with a single owner that may read and write `T`. |
| `Rc<T>` | "arr cee" pointer | Heap allocated `T` with many readers |
| `Arc<T>` | Arc pointer | Same as above, but safe sharing across threads |
| `*const T` | Raw pointer | Unsafe read access to `T` |
| `*mut T` | Mutable raw pointer | Unsafe read and write access to `T` |
# Related resources
......
......@@ -1503,7 +1503,7 @@ reference. We also call this _borrowing_ the local variable
`on_the_stack`, because we are creating an alias: that is, another
route to the same data.
Likewise, in the case of `owned_box`,
Likewise, in the case of `on_the_heap`,
the `&` operator is used in conjunction with the `*` operator
to take a reference to the contents of the box.
......
......@@ -226,7 +226,7 @@ impl<T: Clone> Rc<T> {
/// data is cloned if the reference count is greater than one.
#[inline]
#[experimental]
pub fn make_unique<'a>(&'a mut self) -> &'a mut T {
pub fn make_unique(&mut self) -> &mut T {
// Note that we hold a strong reference, which also counts as
// a weak reference, so we only clone if there is an
// additional reference of either kind.
......@@ -247,7 +247,7 @@ pub fn make_unique<'a>(&'a mut self) -> &'a mut T {
impl<T> Deref<T> for Rc<T> {
/// Borrow the value contained in the reference-counted box
#[inline(always)]
fn deref<'a>(&'a self) -> &'a T {
fn deref(&self) -> &T {
&self.inner().value
}
}
......@@ -390,7 +390,7 @@ fn clone(&self) -> Weak<T> {
#[doc(hidden)]
trait RcBoxPtr<T> {
fn inner<'a>(&'a self) -> &'a RcBox<T>;
fn inner(&self) -> &RcBox<T>;
#[inline]
fn strong(&self) -> uint { self.inner().strong.get() }
......@@ -413,12 +413,12 @@ fn weak(&self) -> uint { self.inner().weak.get() }
impl<T> RcBoxPtr<T> for Rc<T> {
#[inline(always)]
fn inner<'a>(&'a self) -> &'a RcBox<T> { unsafe { &(*self._ptr) } }
fn inner(&self) -> &RcBox<T> { unsafe { &(*self._ptr) } }
}
impl<T> RcBoxPtr<T> for Weak<T> {
#[inline(always)]
fn inner<'a>(&'a self) -> &'a RcBox<T> { unsafe { &(*self._ptr) } }
fn inner(&self) -> &RcBox<T> { unsafe { &(*self._ptr) } }
}
#[cfg(test)]
......
......@@ -207,7 +207,7 @@ fn alloc_copy_inner(&self, n_bytes: uint, align: uint) -> *const u8 {
}
#[inline]
fn alloc_copy<'a, T>(&'a self, op: || -> T) -> &'a T {
fn alloc_copy<T>(&self, op: || -> T) -> &T {
unsafe {
let ptr = self.alloc_copy_inner(mem::size_of::<T>(),
mem::min_align_of::<T>());
......@@ -261,7 +261,7 @@ fn alloc_noncopy_inner(&self, n_bytes: uint,
}
#[inline]
fn alloc_noncopy<'a, T>(&'a self, op: || -> T) -> &'a T {
fn alloc_noncopy<T>(&self, op: || -> T) -> &T {
unsafe {
let tydesc = get_tydesc::<T>();
let (ty_ptr, ptr) =
......@@ -285,7 +285,7 @@ fn alloc_noncopy<'a, T>(&'a self, op: || -> T) -> &'a T {
/// Allocate a new item in the arena, using `op` to initialize the value
/// and returning a reference to it.
#[inline]
pub fn alloc<'a, T>(&'a self, op: || -> T) -> &'a T {
pub fn alloc<T>(&self, op: || -> T) -> &T {
unsafe {
if intrinsics::needs_drop::<T>() {
self.alloc_noncopy(op)
......@@ -458,13 +458,13 @@ pub fn with_capacity(capacity: uint) -> TypedArena<T> {
/// Allocates an object in the TypedArena, returning a reference to it.
#[inline]
pub fn alloc<'a>(&'a self, object: T) -> &'a T {
pub fn alloc(&self, object: T) -> &T {
if self.ptr == self.end {
self.grow()
}
let ptr: &'a T = unsafe {
let ptr: &'a mut T = mem::transmute(self.ptr);
let ptr: &T = unsafe {
let ptr: &mut T = mem::transmute(self.ptr);
ptr::write(ptr, object);
self.ptr.set(self.ptr.get().offset(1));
ptr
......
......@@ -149,7 +149,7 @@ fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
/// If the first ordering is different, the first ordering is all that must be returned.
/// If the first ordering is equal, then second ordering is returned.
#[inline]
#[deprecated = "Just call .cmp() on an Ordering"]
#[deprecated = "Just call .cmp() on a tuple"]
pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering {
match o1 {
Equal => o2,
......
......@@ -16,7 +16,7 @@
//! interface for failure is:
//!
//! ```ignore
//! fn begin_unwind(fmt: &fmt::Arguments, file: &str, line: uint) -> !;
//! fn begin_unwind(fmt: &fmt::Arguments, &(&'static str, uint)) -> !;
//! ```
//!
//! This definition allows for failing with any general message, but it does not
......@@ -33,6 +33,7 @@
use fmt;
use intrinsics;
#[cfg(stage0)]
#[cold] #[inline(never)] // this is the slow path, always
#[lang="fail_"]
fn fail_(expr: &'static str, file: &'static str, line: uint) -> ! {
......@@ -43,6 +44,7 @@ fn fail_(expr: &'static str, file: &'static str, line: uint) -> ! {
unsafe { intrinsics::abort() }
}
#[cfg(stage0)]
#[cold]
#[lang="fail_bounds_check"]
fn fail_bounds_check(file: &'static str, line: uint,
......@@ -53,7 +55,31 @@ fn fail_bounds_check(file: &'static str, line: uint,
unsafe { intrinsics::abort() }
}
#[cold]
#[cfg(not(stage0))]
#[cold] #[inline(never)] // this is the slow path, always
#[lang="fail_"]
fn fail_(expr_file_line: &(&'static str, &'static str, uint)) -> ! {
let (expr, file, line) = *expr_file_line;
let ref file_line = (file, line);
format_args!(|args| -> () {
begin_unwind(args, file_line);
}, "{}", expr);
unsafe { intrinsics::abort() }
}
#[cfg(not(stage0))]
#[cold] #[inline(never)]
#[lang="fail_bounds_check"]
fn fail_bounds_check(file_line: &(&'static str, uint),
index: uint, len: uint) -> ! {
format_args!(|args| -> () {
begin_unwind(args, file_line);
}, "index out of bounds: the len is {} but the index is {}", len, index);
unsafe { intrinsics::abort() }
}
#[cold] #[inline(never)]
pub fn begin_unwind(fmt: &fmt::Arguments, file_line: &(&'static str, uint)) -> ! {
#[allow(ctypes)]
extern {
......
......@@ -143,6 +143,7 @@
use cmp::{PartialEq, Eq, Ord};
use default::Default;
use slice::Vector;
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
use mem;
use slice;
......@@ -216,15 +217,6 @@ pub fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> {
match *self { Some(ref mut x) => Some(x), None => None }
}
/// Convert from `Option<T>` to `&[T]` (without copying)
#[inline]
pub fn as_slice<'r>(&'r self) -> &'r [T] {
match *self {
Some(ref x) => slice::ref_slice(x),
None => &[]
}
}
/// Convert from `Option<T>` to `&mut [T]` (without copying)
#[inline]
pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
......@@ -526,6 +518,17 @@ pub fn unwrap_or_default(self) -> T {
// Trait implementations
/////////////////////////////////////////////////////////////////////////////
impl<T> Vector<T> for Option<T> {
/// Convert from `Option<T>` to `&[T]` (without copying)
#[inline]
fn as_slice<'a>(&'a self) -> &'a [T] {
match *self {
Some(ref x) => slice::ref_slice(x),
None => &[]
}
}
}
impl<T> Default for Option<T> {
#[inline]
fn default() -> Option<T> { None }
......
......@@ -40,7 +40,8 @@ fn main() {
*/
#![crate_name = "fourcc"]
#![experimental]
#![deprecated = "This is now a cargo package located at: \
https://github.com/rust-lang/fourcc"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
......
......@@ -37,7 +37,8 @@ fn main() {
*/
#![crate_name = "hexfloat"]
#![experimental]
#![deprecated = "This is now a cargo package located at: \
https://github.com/rust-lang/hexfloat"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
......
......@@ -39,7 +39,7 @@ fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64>
///
/// ```rust
/// # #![allow(unused_must_use)]
/// use std::io::SeekableMemWriter;
/// use rbml::io::SeekableMemWriter;
///
/// let mut w = SeekableMemWriter::new();
/// w.write([0, 1, 2]);
......@@ -128,6 +128,7 @@ fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> {
#[cfg(test)]
mod tests {
extern crate test;
use super::SeekableMemWriter;
use std::io;
use test::Bencher;
......
......@@ -8,16 +8,35 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Really Bad Markup Language (rbml) is a temporary measure until we migrate
//! the rust object metadata to a better serialization format. It is not
//! intended to be used by users.
//!
//! It is loosely based on the Extensible Binary Markup Language (ebml):
//! http://www.matroska.org/technical/specs/rfc/index.html
#![crate_name = "rbml"]
#![experimental]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")]
#![feature(macro_rules, phase)]
#![allow(missing_doc)]
use std::io;
extern crate serialize;
#[phase(plugin, link)] extern crate log;
#[cfg(test)] extern crate test;
use std::str;
// Simple Extensible Binary Markup Language (ebml) reader and writer on a
// cursor model. See the specification here:
// http://www.matroska.org/technical/specs/rfc/index.html
pub mod io;
// Common data structures
/// Common data structures
#[deriving(Clone)]
pub struct Doc<'a> {
pub data: &'a [u8],
......@@ -86,7 +105,7 @@ pub enum EbmlEncoderTag {
pub enum Error {
IntTooBig(uint),
Expected(String),
IoError(io::IoError)
IoError(std::io::IoError)
}
// --------------------------------------
......@@ -107,7 +126,7 @@ pub mod reader {
Expected };
pub type DecodeResult<T> = Result<T, Error>;
// ebml reading
// rbml reading
macro_rules! try_or(
($e:expr, $r:expr) => (
......@@ -637,7 +656,7 @@ pub mod writer {
pub type EncodeResult = io::IoResult<()>;
// ebml writing
// rbml writing
pub struct Encoder<'a, W> {
pub writer: &'a mut W,
size_positions: Vec<uint>,
......@@ -671,7 +690,7 @@ fn write_vuint<W: Writer>(w: &mut W, n: uint) -> EncodeResult {
})
}
// FIXME (#2741): Provide a function to write the standard ebml header.
// FIXME (#2741): Provide a function to write the standard rbml header.
impl<'a, W: Writer + Seek> Encoder<'a, W> {
pub fn new(w: &'a mut W) -> Encoder<'a, W> {
Encoder {
......@@ -1018,130 +1037,16 @@ fn emit_map_elt_val(&mut self,
#[cfg(test)]
mod tests {
use super::Doc;
use ebml::reader;
use ebml::writer;
use {Encodable, Decodable};
use super::{Doc, reader, writer};
use super::io::SeekableMemWriter;
use serialize::{Encodable, Decodable};
use std::io::{IoError, IoResult, SeekStyle};
use std::io;
use std::option::{None, Option, Some};
use std::slice;
static BUF_CAPACITY: uint = 128;
fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> {
// compute offset as signed and clamp to prevent overflow
let pos = match seek {
io::SeekSet => 0,
io::SeekEnd => end,
io::SeekCur => cur,
} as i64;
if offset + pos < 0 {
Err(IoError {
kind: io::InvalidInput,
desc: "invalid seek to a negative offset",
detail: None
})
} else {
Ok((offset + pos) as u64)
}
}
/// Writes to an owned, growable byte vector that supports seeking.
///
/// # Example
///
/// ```rust
/// # #![allow(unused_must_use)]
/// use std::io::SeekableMemWriter;
///
/// let mut w = SeekableMemWriter::new();
/// w.write([0, 1, 2]);
///
/// assert_eq!(w.unwrap(), vec!(0, 1, 2));
/// ```
pub struct SeekableMemWriter {
buf: Vec<u8>,
pos: uint,
}
impl SeekableMemWriter {
/// Create a new `SeekableMemWriter`.
#[inline]
pub fn new() -> SeekableMemWriter {
SeekableMemWriter::with_capacity(BUF_CAPACITY)
}
/// Create a new `SeekableMemWriter`, allocating at least `n` bytes for
/// the internal buffer.
#[inline]
pub fn with_capacity(n: uint) -> SeekableMemWriter {
SeekableMemWriter { buf: Vec::with_capacity(n), pos: 0 }
}
/// Acquires an immutable reference to the underlying buffer of this
/// `SeekableMemWriter`.
///
/// No method is exposed for acquiring a mutable reference to the buffer
/// because it could corrupt the state of this `MemWriter`.
#[inline]
pub fn get_ref<'a>(&'a self) -> &'a [u8] { self.buf.as_slice() }
/// Unwraps this `SeekableMemWriter`, returning the underlying buffer
#[inline]
pub fn unwrap(self) -> Vec<u8> { self.buf }
}
impl Writer for SeekableMemWriter {
#[inline]
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
if self.pos == self.buf.len() {
self.buf.push_all(buf)
} else {
// Make sure the internal buffer is as least as big as where we
// currently are
let difference = self.pos as i64 - self.buf.len() as i64;
if difference > 0 {
self.buf.grow(difference as uint, &0);
}
// Figure out what bytes will be used to overwrite what's currently
// there (left), and what will be appended on the end (right)
let cap = self.buf.len() - self.pos;
let (left, right) = if cap <= buf.len() {
(buf.slice_to(cap), buf.slice_from(cap))
} else {
(buf, &[])
};
// Do the necessary writes
if left.len() > 0 {
slice::bytes::copy_memory(self.buf.mut_slice_from(self.pos), left);
}
if right.len() > 0 {
self.buf.push_all(right);
}
}
// Bump us forward
self.pos += buf.len();
Ok(())
}
}
impl Seek for SeekableMemWriter {
#[inline]
fn tell(&self) -> IoResult<u64> { Ok(self.pos as u64) }
#[inline]
fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> {
let new = try!(combine(style, self.pos, self.buf.len(), pos));
self.pos = new as uint;
Ok(())
}
}
#[test]
fn test_vuint_at() {
let data = [
......@@ -1196,11 +1101,11 @@ fn test_v(v: Option<int>) {
debug!("v == {}", v);
let mut wr = SeekableMemWriter::new();
{
let mut ebml_w = writer::Encoder::new(&mut wr);
let _ = v.encode(&mut ebml_w);
let mut rbml_w = writer::Encoder::new(&mut wr);
let _ = v.encode(&mut rbml_w);
}
let ebml_doc = Doc::new(wr.get_ref());
let mut deser = reader::Decoder::new(ebml_doc);
let rbml_doc = Doc::new(wr.get_ref());
let mut deser = reader::Decoder::new(rbml_doc);
let v1 = Decodable::decode(&mut deser).unwrap();
debug!("v1 == {}", v1);
assert_eq!(v, v1);
......@@ -1215,9 +1120,8 @@ fn test_v(v: Option<int>) {
#[cfg(test)]
mod bench {
#![allow(non_snake_case_functions)]
extern crate test;
use self::test::Bencher;
use ebml::reader;
use test::Bencher;
use super::reader;
#[bench]
pub fn vuint_at_A_aligned(b: &mut Bencher) {
......
......@@ -44,6 +44,7 @@
extern crate llvm = "rustc_llvm";
extern crate rustc_back = "rustc_back";
extern crate serialize;
extern crate rbml;
extern crate time;
#[phase(plugin, link)] extern crate log;
#[phase(plugin, link)] extern crate syntax;
......@@ -132,7 +133,6 @@ pub mod util {
pub mod common;
pub mod ppaux;
pub mod io;
pub mod nodemap;
}
......
......@@ -20,8 +20,8 @@
use middle::typeck;
use middle::subst::VecPerParamSpace;
use serialize::ebml;
use serialize::ebml::reader;
use rbml;
use rbml::reader;
use std::rc::Rc;
use syntax::ast;
use syntax::ast_map;
......@@ -218,7 +218,7 @@ pub fn get_field_type(tcx: &ty::ctxt, class_id: ast::DefId,
def: ast::DefId) -> ty::Polytype {
let cstore = &tcx.sess.cstore;
let cdata = cstore.get_crate_data(class_id.krate);
let all_items = reader::get_doc(ebml::Doc::new(cdata.data()), tag_items);
let all_items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_items);
let class_doc = expect(tcx.sess.diagnostic(),
decoder::maybe_find_item(class_id.node, all_items),
|| {
......
......@@ -37,8 +37,8 @@
use std::collections::hashmap::HashMap;
use std::rc::Rc;
use std::u64;
use serialize::ebml::reader;
use serialize::ebml;
use rbml::reader;
use rbml;
use serialize::Decodable;
use syntax::ast_map;
use syntax::attr;
......@@ -56,8 +56,8 @@
// what crate that's in and give us a def_id that makes sense for the current
// build.
fn lookup_hash<'a>(d: ebml::Doc<'a>, eq_fn: |&[u8]| -> bool,
hash: u64) -> Option<ebml::Doc<'a>> {
fn lookup_hash<'a>(d: rbml::Doc<'a>, eq_fn: |&[u8]| -> bool,
hash: u64) -> Option<rbml::Doc<'a>> {
let index = reader::get_doc(d, tag_index);
let table = reader::get_doc(index, tag_index_table);
let hash_pos = table.start + (hash % 256 * 4) as uint;
......@@ -80,7 +80,7 @@ fn lookup_hash<'a>(d: ebml::Doc<'a>, eq_fn: |&[u8]| -> bool,
}
pub fn maybe_find_item<'a>(item_id: ast::NodeId,
items: ebml::Doc<'a>) -> Option<ebml::Doc<'a>> {
items: rbml::Doc<'a>) -> Option<rbml::Doc<'a>> {
fn eq_item(bytes: &[u8], item_id: ast::NodeId) -> bool {
return u64_from_be_bytes(
bytes.slice(0u, 4u), 0u, 4u) as ast::NodeId
......@@ -91,17 +91,17 @@ fn eq_item(bytes: &[u8], item_id: ast::NodeId) -> bool {
hash::hash(&(item_id as i64)))
}
fn find_item<'a>(item_id: ast::NodeId, items: ebml::Doc<'a>) -> ebml::Doc<'a> {
fn find_item<'a>(item_id: ast::NodeId, items: rbml::Doc<'a>) -> rbml::Doc<'a> {
match maybe_find_item(item_id, items) {
None => fail!("lookup_item: id not found: {}", item_id),
Some(d) => d
}
}
// Looks up an item in the given metadata and returns an ebml doc pointing
// Looks up an item in the given metadata and returns an rbml doc pointing
// to the item data.
fn lookup_item<'a>(item_id: ast::NodeId, data: &'a [u8]) -> ebml::Doc<'a> {
let items = reader::get_doc(ebml::Doc::new(data), tag_items);
fn lookup_item<'a>(item_id: ast::NodeId, data: &'a [u8]) -> rbml::Doc<'a> {
let items = reader::get_doc(rbml::Doc::new(data), tag_items);
find_item(item_id, items)
}
......@@ -127,7 +127,7 @@ enum Family {
InheritedField // N
}
fn item_family(item: ebml::Doc) -> Family {
fn item_family(item: rbml::Doc) -> Family {
let fam = reader::get_doc(item, tag_items_data_item_family);
match reader::doc_as_u8(fam) as char {
'c' => ImmStatic,
......@@ -152,7 +152,7 @@ fn item_family(item: ebml::Doc) -> Family {
}
}
fn item_visibility(item: ebml::Doc) -> ast::Visibility {
fn item_visibility(item: rbml::Doc) -> ast::Visibility {
match reader::maybe_get_doc(item, tag_items_data_item_visibility) {
None => ast::Public,
Some(visibility_doc) => {
......@@ -165,7 +165,7 @@ fn item_visibility(item: ebml::Doc) -> ast::Visibility {
}
}
fn item_method_sort(item: ebml::Doc) -> char {
fn item_method_sort(item: rbml::Doc) -> char {
let mut ret = 'r';
reader::tagged_docs(item, tag_item_trait_method_sort, |doc| {
ret = doc.as_str_slice().as_bytes()[0] as char;
......@@ -174,11 +174,11 @@ fn item_method_sort(item: ebml::Doc) -> char {
ret
}
fn item_symbol(item: ebml::Doc) -> String {
fn item_symbol(item: rbml::Doc) -> String {
reader::get_doc(item, tag_items_data_item_symbol).as_str().to_string()
}
fn item_parent_item(d: ebml::Doc) -> Option<ast::DefId> {
fn item_parent_item(d: rbml::Doc) -> Option<ast::DefId> {
let mut ret = None;
reader::tagged_docs(d, tag_items_data_parent_item, |did| {
ret = Some(reader::with_doc_data(did, parse_def_id));
......@@ -188,60 +188,60 @@ fn item_parent_item(d: ebml::Doc) -> Option<ast::DefId> {
}
fn item_reqd_and_translated_parent_item(cnum: ast::CrateNum,
d: ebml::Doc) -> ast::DefId {
d: rbml::Doc) -> ast::DefId {
let trait_did = item_parent_item(d).expect("item without parent");
ast::DefId { krate: cnum, node: trait_did.node }
}
fn item_def_id(d: ebml::Doc, cdata: Cmd) -> ast::DefId {
fn item_def_id(d: rbml::Doc, cdata: Cmd) -> ast::DefId {
let tagdoc = reader::get_doc(d, tag_def_id);
return translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
}
fn get_provided_source(d: ebml::Doc, cdata: Cmd) -> Option<ast::DefId> {
fn get_provided_source(d: rbml::Doc, cdata: Cmd) -> Option<ast::DefId> {
reader::maybe_get_doc(d, tag_item_method_provided_source).map(|doc| {
translate_def_id(cdata, reader::with_doc_data(doc, parse_def_id))
})
}
fn each_reexport(d: ebml::Doc, f: |ebml::Doc| -> bool) -> bool {
fn each_reexport(d: rbml::Doc, f: |rbml::Doc| -> bool) -> bool {
reader::tagged_docs(d, tag_items_data_item_reexport, f)
}
fn variant_disr_val(d: ebml::Doc) -> Option<ty::Disr> {
fn variant_disr_val(d: rbml::Doc) -> Option<ty::Disr> {
reader::maybe_get_doc(d, tag_disr_val).and_then(|val_doc| {
reader::with_doc_data(val_doc, |data| u64::parse_bytes(data, 10u))
})
}
fn doc_type(doc: ebml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::t {
fn doc_type(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::t {
let tp = reader::get_doc(doc, tag_items_data_item_type);
parse_ty_data(tp.data, cdata.cnum, tp.start, tcx,
|_, did| translate_def_id(cdata, did))
}
fn doc_method_fty(doc: ebml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::BareFnTy {
fn doc_method_fty(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::BareFnTy {
let tp = reader::get_doc(doc, tag_item_method_fty);
parse_bare_fn_ty_data(tp.data, cdata.cnum, tp.start, tcx,
|_, did| translate_def_id(cdata, did))
}
pub fn item_type(_item_id: ast::DefId, item: ebml::Doc,
pub fn item_type(_item_id: ast::DefId, item: rbml::Doc,
tcx: &ty::ctxt, cdata: Cmd) -> ty::t {
doc_type(item, tcx, cdata)
}
fn doc_trait_ref(doc: ebml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
fn doc_trait_ref(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
parse_trait_ref_data(doc.data, cdata.cnum, doc.start, tcx,
|_, did| translate_def_id(cdata, did))
}
fn item_trait_ref(doc: ebml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
fn item_trait_ref(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
let tp = reader::get_doc(doc, tag_item_trait_ref);
doc_trait_ref(tp, tcx, cdata)
}
fn item_ty_param_defs(item: ebml::Doc,
fn item_ty_param_defs(item: rbml::Doc,
tcx: &ty::ctxt,
cdata: Cmd,
tag: uint)
......@@ -257,7 +257,7 @@ fn item_ty_param_defs(item: ebml::Doc,
bounds
}
fn item_region_param_defs(item_doc: ebml::Doc, cdata: Cmd)
fn item_region_param_defs(item_doc: rbml::Doc, cdata: Cmd)
-> subst::VecPerParamSpace<ty::RegionParameterDef>
{
let mut v = subst::VecPerParamSpace::empty();
......@@ -285,7 +285,7 @@ fn item_region_param_defs(item_doc: ebml::Doc, cdata: Cmd)
v
}
fn enum_variant_ids(item: ebml::Doc, cdata: Cmd) -> Vec<ast::DefId> {
fn enum_variant_ids(item: rbml::Doc, cdata: Cmd) -> Vec<ast::DefId> {
let mut ids: Vec<ast::DefId> = Vec::new();
let v = tag_items_data_item_variant;
reader::tagged_docs(item, v, |p| {
......@@ -296,7 +296,7 @@ fn enum_variant_ids(item: ebml::Doc, cdata: Cmd) -> Vec<ast::DefId> {
return ids;
}
fn item_path(item_doc: ebml::Doc) -> Vec<ast_map::PathElem> {
fn item_path(item_doc: rbml::Doc) -> Vec<ast_map::PathElem> {
let path_doc = reader::get_doc(item_doc, tag_path);
let len_doc = reader::get_doc(path_doc, tag_path_len);
......@@ -319,7 +319,7 @@ fn item_path(item_doc: ebml::Doc) -> Vec<ast_map::PathElem> {
result
}
fn item_name(intr: &IdentInterner, item: ebml::Doc) -> ast::Ident {
fn item_name(intr: &IdentInterner, item: rbml::Doc) -> ast::Ident {
let name = reader::get_doc(item, tag_paths_data_name);
let string = name.as_str_slice();
match intr.find_equiv(&string) {
......@@ -328,7 +328,7 @@ fn item_name(intr: &IdentInterner, item: ebml::Doc) -> ast::Ident {
}
}
fn item_to_def_like(item: ebml::Doc, did: ast::DefId, cnum: ast::CrateNum)
fn item_to_def_like(item: rbml::Doc, did: ast::DefId, cnum: ast::CrateNum)
-> DefLike {
let fam = item_family(item);
match fam {
......@@ -463,7 +463,7 @@ pub enum DefLike {
/// Iterates over the language items in the given crate.
pub fn each_lang_item(cdata: Cmd, f: |ast::NodeId, uint| -> bool) -> bool {
let root = ebml::Doc::new(cdata.data());
let root = rbml::Doc::new(cdata.data());
let lang_items = reader::get_doc(root, tag_lang_items);
reader::tagged_docs(lang_items, tag_lang_items_item, |item_doc| {
let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id);
......@@ -480,7 +480,7 @@ pub fn each_lang_item(cdata: Cmd, f: |ast::NodeId, uint| -> bool) -> bool {
fn each_child_of_item_or_crate(intr: Rc<IdentInterner>,
cdata: Cmd,
item_doc: ebml::Doc,
item_doc: rbml::Doc,
get_crate_data: GetCrateDataCb,
callback: |DefLike,
ast::Ident,
......@@ -503,7 +503,7 @@ fn each_child_of_item_or_crate(intr: Rc<IdentInterner>,
None => cdata
};
let other_crates_items = reader::get_doc(ebml::Doc::new(crate_data.data()), tag_items);
let other_crates_items = reader::get_doc(rbml::Doc::new(crate_data.data()), tag_items);
// Get the item.
match maybe_find_item(child_def_id.node, other_crates_items) {
......@@ -531,7 +531,7 @@ fn each_child_of_item_or_crate(intr: Rc<IdentInterner>,
|inherent_impl_def_id_doc| {
let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc,
cdata);
let items = reader::get_doc(ebml::Doc::new(cdata.data()), tag_items);
let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_items);
match maybe_find_item(inherent_impl_def_id.node, items) {
None => {}
Some(inherent_impl_doc) => {
......@@ -596,7 +596,7 @@ fn each_child_of_item_or_crate(intr: Rc<IdentInterner>,
None => cdata
};
let other_crates_items = reader::get_doc(ebml::Doc::new(crate_data.data()), tag_items);
let other_crates_items = reader::get_doc(rbml::Doc::new(crate_data.data()), tag_items);
// Get the item.
match maybe_find_item(child_def_id.node, other_crates_items) {
......@@ -623,7 +623,7 @@ pub fn each_child_of_item(intr: Rc<IdentInterner>,
get_crate_data: GetCrateDataCb,
callback: |DefLike, ast::Ident, ast::Visibility|) {
// Find the item.
let root_doc = ebml::Doc::new(cdata.data());
let root_doc = rbml::Doc::new(cdata.data());
let items = reader::get_doc(root_doc, tag_items);
let item_doc = match maybe_find_item(id, items) {
None => return,
......@@ -644,7 +644,7 @@ pub fn each_top_level_item_of_crate(intr: Rc<IdentInterner>,
callback: |DefLike,
ast::Ident,
ast::Visibility|) {
let root_doc = ebml::Doc::new(cdata.data());
let root_doc = rbml::Doc::new(cdata.data());
let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
let crate_items_doc = reader::get_doc(misc_info_doc,
tag_misc_info_crate_items);
......@@ -663,7 +663,7 @@ pub fn get_item_path(cdata: Cmd, id: ast::NodeId) -> Vec<ast_map::PathElem> {
pub type DecodeInlinedItem<'a> = |cdata: Cmd,
tcx: &ty::ctxt,
path: Vec<ast_map::PathElem>,
par_doc: ebml::Doc|: 'a
par_doc: rbml::Doc|: 'a
-> Result<ast::InlinedItem, Vec<ast_map::PathElem> >;
pub fn maybe_get_item_ast(cdata: Cmd, tcx: &ty::ctxt, id: ast::NodeId,
......@@ -693,7 +693,7 @@ pub fn maybe_get_item_ast(cdata: Cmd, tcx: &ty::ctxt, id: ast::NodeId,
pub fn get_enum_variants(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId,
tcx: &ty::ctxt) -> Vec<Rc<ty::VariantInfo>> {
let data = cdata.data();
let items = reader::get_doc(ebml::Doc::new(data), tag_items);
let items = reader::get_doc(rbml::Doc::new(data), tag_items);
let item = find_item(id, items);
let mut disr_val = 0;
enum_variant_ids(item, cdata).iter().map(|did| {
......@@ -725,7 +725,7 @@ pub fn get_enum_variants(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId,
}).collect()
}
fn get_explicit_self(item: ebml::Doc) -> ty::ExplicitSelfCategory {
fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
fn get_mutability(ch: u8) -> ast::Mutability {
match ch as char {
'i' => ast::MutImmutable,
......@@ -965,7 +965,7 @@ pub fn get_item_attrs(cdata: Cmd,
}
pub fn get_struct_field_attrs(cdata: Cmd) -> HashMap<ast::NodeId, Vec<ast::Attribute>> {
let data = ebml::Doc::new(cdata.data());
let data = rbml::Doc::new(cdata.data());
let fields = reader::get_doc(data, tag_struct_fields);
let mut map = HashMap::new();
reader::tagged_docs(fields, tag_struct_field, |field| {
......@@ -1023,7 +1023,7 @@ pub fn get_struct_fields(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId)
result
}
fn get_meta_items(md: ebml::Doc) -> Vec<Gc<ast::MetaItem>> {
fn get_meta_items(md: rbml::Doc) -> Vec<Gc<ast::MetaItem>> {
let mut items: Vec<Gc<ast::MetaItem>> = Vec::new();
reader::tagged_docs(md, tag_meta_item_word, |meta_item_doc| {
let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
......@@ -1051,7 +1051,7 @@ fn get_meta_items(md: ebml::Doc) -> Vec<Gc<ast::MetaItem>> {
return items;
}
fn get_attributes(md: ebml::Doc) -> Vec<ast::Attribute> {
fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
let mut attrs: Vec<ast::Attribute> = Vec::new();
match reader::maybe_get_doc(md, tag_attributes) {
Some(attrs_d) => {
......@@ -1082,7 +1082,7 @@ fn get_attributes(md: ebml::Doc) -> Vec<ast::Attribute> {
return attrs;
}
fn list_crate_attributes(md: ebml::Doc, hash: &Svh,
fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
out: &mut io::Writer) -> io::IoResult<()> {
try!(write!(out, "=Crate Attributes ({})=\n", *hash));
......@@ -1095,7 +1095,7 @@ fn list_crate_attributes(md: ebml::Doc, hash: &Svh,
}
pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
get_attributes(ebml::Doc::new(data))
get_attributes(rbml::Doc::new(data))
}
#[deriving(Clone)]
......@@ -1107,10 +1107,10 @@ pub struct CrateDep {
pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
let mut deps: Vec<CrateDep> = Vec::new();
let cratedoc = ebml::Doc::new(data);
let cratedoc = rbml::Doc::new(data);
let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
let mut crate_num = 1;
fn docstr(doc: ebml::Doc, tag_: uint) -> String {
fn docstr(doc: rbml::Doc, tag_: uint) -> String {
let d = reader::get_doc(doc, tag_);
d.as_str_slice().to_string()
}
......@@ -1138,27 +1138,27 @@ fn list_crate_deps(data: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
}
pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
let cratedoc = ebml::Doc::new(data);
let cratedoc = rbml::Doc::new(data);
reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
Svh::new(doc.as_str_slice())
})
}
pub fn get_crate_hash(data: &[u8]) -> Svh {
let cratedoc = ebml::Doc::new(data);
let cratedoc = rbml::Doc::new(data);
let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
Svh::new(hashdoc.as_str_slice())
}
pub fn maybe_get_crate_name(data: &[u8]) -> Option<String> {
let cratedoc = ebml::Doc::new(data);
let cratedoc = rbml::Doc::new(data);
reader::maybe_get_doc(cratedoc, tag_crate_crate_name).map(|doc| {
doc.as_str_slice().to_string()
})
}
pub fn get_crate_triple(data: &[u8]) -> Option<String> {
let cratedoc = ebml::Doc::new(data);
let cratedoc = rbml::Doc::new(data);
let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
triple_doc.map(|s| s.as_str().to_string())
}
......@@ -1169,7 +1169,7 @@ pub fn get_crate_name(data: &[u8]) -> String {
pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
let hash = get_crate_hash(bytes);
let md = ebml::Doc::new(bytes);
let md = rbml::Doc::new(bytes);
try!(list_crate_attributes(md, &hash, out));
list_crate_deps(bytes, out)
}
......@@ -1196,7 +1196,7 @@ pub fn translate_def_id(cdata: Cmd, did: ast::DefId) -> ast::DefId {
}
pub fn each_impl(cdata: Cmd, callback: |ast::DefId|) {
let impls_doc = reader::get_doc(ebml::Doc::new(cdata.data()), tag_impls);
let impls_doc = reader::get_doc(rbml::Doc::new(cdata.data()), tag_impls);
let _ = reader::tagged_docs(impls_doc, tag_impls_impl, |impl_doc| {
callback(item_def_id(impl_doc, cdata));
true
......@@ -1252,7 +1252,7 @@ pub fn get_trait_of_method(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
pub fn get_native_libraries(cdata: Cmd)
-> Vec<(cstore::NativeLibaryKind, String)> {
let libraries = reader::get_doc(ebml::Doc::new(cdata.data()),
let libraries = reader::get_doc(rbml::Doc::new(cdata.data()),
tag_native_libraries);
let mut result = Vec::new();
reader::tagged_docs(libraries, tag_native_libraries_lib, |lib_doc| {
......@@ -1268,12 +1268,12 @@ pub fn get_native_libraries(cdata: Cmd)
}
pub fn get_plugin_registrar_fn(data: &[u8]) -> Option<ast::NodeId> {
reader::maybe_get_doc(ebml::Doc::new(data), tag_plugin_registrar_fn)
reader::maybe_get_doc(rbml::Doc::new(data), tag_plugin_registrar_fn)
.map(|doc| FromPrimitive::from_u32(reader::doc_as_u32(doc)).unwrap())
}
pub fn get_exported_macros(data: &[u8]) -> Vec<String> {
let macros = reader::get_doc(ebml::Doc::new(data),
let macros = reader::get_doc(rbml::Doc::new(data),
tag_exported_macros);
let mut result = Vec::new();
reader::tagged_docs(macros, tag_macro_def, |macro_doc| {
......@@ -1286,7 +1286,7 @@ pub fn get_exported_macros(data: &[u8]) -> Vec<String> {
pub fn get_dylib_dependency_formats(cdata: Cmd)
-> Vec<(ast::CrateNum, cstore::LinkagePreference)>
{
let formats = reader::get_doc(ebml::Doc::new(cdata.data()),
let formats = reader::get_doc(rbml::Doc::new(cdata.data()),
tag_dylib_dependency_formats);
let mut result = Vec::new();
......@@ -1312,7 +1312,7 @@ pub fn get_dylib_dependency_formats(cdata: Cmd)
pub fn get_missing_lang_items(cdata: Cmd)
-> Vec<lang_items::LangItem>
{
let items = reader::get_doc(ebml::Doc::new(cdata.data()), tag_lang_items);
let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_lang_items);
let mut result = Vec::new();
reader::tagged_docs(items, tag_lang_items_missing, |missing_doc| {
let item: lang_items::LangItem =
......@@ -1340,7 +1340,7 @@ pub fn get_method_arg_names(cdata: Cmd, id: ast::NodeId) -> Vec<String> {
pub fn get_reachable_extern_fns(cdata: Cmd) -> Vec<ast::DefId> {
let mut ret = Vec::new();
let items = reader::get_doc(ebml::Doc::new(cdata.data()),
let items = reader::get_doc(rbml::Doc::new(cdata.data()),
tag_reachable_extern_fns);
reader::tagged_docs(items, tag_reachable_extern_fn_id, |doc| {
ret.push(ast::DefId {
......
此差异已折叠。
......@@ -27,7 +27,7 @@
use syntax::diagnostic::SpanHandler;
use syntax::parse::token;
use util::io::SeekableMemWriter;
use rbml::io::SeekableMemWriter;
macro_rules! mywrite( ($($arg:tt)*) => ({ write!($($arg)*); }) )
......
此差异已折叠。
......@@ -584,9 +584,11 @@ fn fold_region(&mut self, r: ty::Region) -> ty::Region {
self.tcx().sess.span_bug(
span,
format!("Type parameter out of range \
when substituting in region {} (root type={})",
when substituting in region {} (root type={}) \
(space={}, index={})",
region_name.as_str(),
self.root_ty.repr(self.tcx())).as_slice());
self.root_ty.repr(self.tcx()),
space, i).as_slice());
}
}
}
......
......@@ -485,6 +485,9 @@ pub fn get_res_dtor(ccx: &CrateContext,
if !substs.types.is_empty() {
assert_eq!(did.krate, ast::LOCAL_CRATE);
// Since we're in trans we don't care for any region parameters
let ref substs = subst::Substs::erased(substs.types.clone());
let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, substs);
let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, vtables, None);
......@@ -2593,7 +2596,7 @@ pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
}
let encode_inlined_item: encoder::EncodeInlinedItem =
|ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii);
|ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii);
let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
let metadata = encoder::encode_metadata(encode_parms, krate);
......
......@@ -109,7 +109,7 @@ fn const_vec(cx: &CrateContext, e: &ast::Expr,
(v, llunitty, inlineable.iter().fold(true, |a, &b| a && b))
}
fn const_addr_of(cx: &CrateContext, cv: ValueRef) -> ValueRef {
pub fn const_addr_of(cx: &CrateContext, cv: ValueRef) -> ValueRef {
unsafe {
let gv = "const".with_c_str(|name| {
llvm::LLVMAddGlobal(cx.llmod, val_ty(cv).to_ref(), name)
......
......@@ -20,6 +20,7 @@
use middle::trans::cleanup::CleanupMethods;
use middle::trans::cleanup;
use middle::trans::common::*;
use middle::trans::consts;
use middle::trans::datum;
use middle::trans::debuginfo;
use middle::trans::expr;
......@@ -477,14 +478,6 @@ pub fn trans_ret<'a>(bcx: &'a Block<'a>,
return bcx;
}
fn str_slice_arg<'a>(bcx: &'a Block<'a>, s: InternedString) -> ValueRef {
let ccx = bcx.ccx();
let s = C_str_slice(ccx, s);
let slot = alloca(bcx, val_ty(s), "__temp");
Store(bcx, s, slot);
slot
}
pub fn trans_fail<'a>(
bcx: &'a Block<'a>,
sp: Span,
......@@ -493,12 +486,14 @@ pub fn trans_fail<'a>(
let ccx = bcx.ccx();
let _icx = push_ctxt("trans_fail_value");
let v_str = str_slice_arg(bcx, fail_str);
let v_str = C_str_slice(ccx, fail_str);
let loc = bcx.sess().codemap().lookup_char_pos(sp.lo);
let filename = token::intern_and_get_ident(loc.file.name.as_slice());
let v_filename = str_slice_arg(bcx, filename);
let v_line = loc.line as int;
let args = vec!(v_str, v_filename, C_int(ccx, v_line));
let filename = C_str_slice(ccx, filename);
let line = C_int(ccx, loc.line as int);
let expr_file_line_const = C_struct(ccx, &[v_str, filename, line], false);
let expr_file_line = consts::const_addr_of(ccx, expr_file_line_const);
let args = vec!(expr_file_line);
let did = langcall(bcx, Some(sp), "", FailFnLangItem);
let bcx = callee::trans_lang_call(bcx,
did,
......@@ -514,6 +509,7 @@ pub fn trans_fail_bounds_check<'a>(
index: ValueRef,
len: ValueRef)
-> &'a Block<'a> {
let ccx = bcx.ccx();
let _icx = push_ctxt("trans_fail_bounds_check");
// Extract the file/line from the span
......@@ -521,9 +517,11 @@ pub fn trans_fail_bounds_check<'a>(
let filename = token::intern_and_get_ident(loc.file.name.as_slice());
// Invoke the lang item
let filename = str_slice_arg(bcx, filename);
let line = C_int(bcx.ccx(), loc.line as int);
let args = vec!(filename, line, index, len);
let filename = C_str_slice(ccx, filename);
let line = C_int(ccx, loc.line as int);
let file_line_const = C_struct(ccx, &[filename, line], false);
let file_line = consts::const_addr_of(ccx, file_line_const);
let args = vec!(file_line, index, len);
let did = langcall(bcx, Some(sp), "", FailBoundsCheckFnLangItem);
let bcx = callee::trans_lang_call(bcx,
did,
......
......@@ -3547,6 +3547,17 @@ fn check_fn_for_vec_elements_expected(fcx: &FnCtxt,
span_err!(tcx.sess, path.span, E0071,
"`{}` does not name a structure",
pprust::path_to_string(path));
// Make sure to still write the types
// otherwise we might ICE
fcx.write_error(id);
for field in fields.iter() {
check_expr(fcx, &*field.expr);
}
match base_expr {
Some(ref base) => check_expr(fcx, &**base),
None => {}
}
}
}
......
......@@ -31,7 +31,7 @@ pub fn init() {
let state: Box<Queue> = box Exclusive::new(Vec::new());
unsafe {
rtassert!(!RUNNING.load(atomics::SeqCst));
rtassert!(QUEUE.swap(mem::transmute(state), atomics::SeqCst) == 0);
assert!(QUEUE.swap(mem::transmute(state), atomics::SeqCst) == 0);
}
}
......
......@@ -649,7 +649,7 @@ struct List {
#[should_fail]
fn test_begin_unwind() {
use std::rt::unwind::begin_unwind;
begin_unwind("cause", file!(), line!())
begin_unwind("cause", &(file!(), line!()))
}
#[test]
......
......@@ -417,8 +417,8 @@ fn write(&mut self, buf: &[u8]) -> fmt::Result {
begin_unwind_inner(box String::from_utf8(v).unwrap(), file_line)
}
// FIXME: Need to change expr_fail in AstBuilder to change this to &(str, uint)
/// This is the entry point of unwinding for fail!() and assert!().
#[cfg(stage0)]
#[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
pub fn begin_unwind<M: Any + Send>(msg: M, file: &'static str, line: uint) -> ! {
// Note that this should be the only allocation performed in this code path.
......@@ -432,6 +432,21 @@ pub fn begin_unwind<M: Any + Send>(msg: M, file: &'static str, line: uint) -> !
begin_unwind_inner(box msg, &(file, line))
}
/// This is the entry point of unwinding for fail!() and assert!().
#[cfg(not(stage0))]
#[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
pub fn begin_unwind<M: Any + Send>(msg: M, file_line: &(&'static str, uint)) -> ! {
// Note that this should be the only allocation performed in this code path.
// Currently this means that fail!() on OOM will invoke this code path,
// but then again we're not really ready for failing on OOM anyway. If
// we do start doing this, then we should propagate this allocation to
// be performed in the parent of this task instead of the task that's
// failing.
// see below for why we do the `Any` coercion here.
begin_unwind_inner(box msg, file_line)
}
/// The core of the unwinding.
///
/// This is non-generic to avoid instantiation bloat in other crates
......
......@@ -29,7 +29,8 @@
//! `0.8.1-rc.3.0+20130922.linux`.
#![crate_name = "semver"]
#![experimental]
#![deprecated = "This is now a cargo package located at: \
https://github.com/rust-lang/semver"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
......
......@@ -39,6 +39,5 @@
mod collection_impls;
pub mod base64;
pub mod ebml;
pub mod hex;
pub mod json;
......@@ -43,6 +43,7 @@
use ptr::RawPtr;
use ptr;
use raw;
use slice::Vector;
/// The type representing a foreign chunk of memory
pub struct CVec<T> {
......@@ -101,13 +102,6 @@ pub unsafe fn new_with_dtor(base: *mut T, len: uint,
}
}
/// View the stored data as a slice.
pub fn as_slice<'a>(&'a self) -> &'a [T] {
unsafe {
mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
}
}
/// View the stored data as a mutable slice.
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
unsafe {
......@@ -151,6 +145,15 @@ pub unsafe fn unwrap(mut self) -> *mut T {
}
}
impl<T> Vector<T> for CVec<T> {
/// View the stored data as a slice.
fn as_slice<'a>(&'a self) -> &'a [T] {
unsafe {
mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
}
}
}
impl<T> Collection for CVec<T> {
fn len(&self) -> uint { self.len }
}
......
......@@ -37,6 +37,39 @@
/// fail!("this is a {} {message}", "fancy", message = "message");
/// ```
#[macro_export]
#[cfg(not(stage0))]
macro_rules! fail(
() => ({
fail!("explicit failure")
});
($msg:expr) => ({
// static requires less code at runtime, more constant data
static FILE_LINE: (&'static str, uint) = (file!(), line!());
::std::rt::begin_unwind($msg, &FILE_LINE)
});
($fmt:expr, $($arg:tt)*) => ({
// a closure can't have return type !, so we need a full
// function to pass to format_args!, *and* we need the
// file and line numbers right here; so an inner bare fn
// is our only choice.
//
// LLVM doesn't tend to inline this, presumably because begin_unwind_fmt
// is #[cold] and #[inline(never)] and because this is flagged as cold
// as returning !. We really do want this to be inlined, however,
// because it's just a tiny wrapper. Small wins (156K to 149K in size)
// were seen when forcing this to be inlined, and that number just goes
// up with the number of calls to fail!()
#[inline(always)]
fn run_fmt(fmt: &::std::fmt::Arguments) -> ! {
static FILE_LINE: (&'static str, uint) = (file!(), line!());
::std::rt::begin_unwind_fmt(fmt, &FILE_LINE)
}
format_args!(run_fmt, $fmt, $($arg)*)
});
)
#[macro_export]
#[cfg(stage0)]
macro_rules! fail(
() => ({
fail!("explicit failure")
......
......@@ -142,6 +142,16 @@ pub trait GenericPath: Clone + GenericPathUnsafe {
/// Creates a new Path from a byte vector or string.
/// The resulting Path will always be normalized.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let path = Path::new("foo/bar");
/// # }
/// ```
///
/// # Failure
///
/// Fails the task if the path contains a NUL.
......@@ -155,6 +165,17 @@ fn new<T: BytesContainer>(path: T) -> Self {
/// Creates a new Path from a byte vector or string, if possible.
/// The resulting Path will always be normalized.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let x: &[u8] = b"foo\0";
/// assert!(Path::new_opt(x).is_none());
/// # }
/// ```
#[inline]
fn new_opt<T: BytesContainer>(path: T) -> Option<Self> {
if contains_nul(&path) {
......@@ -166,18 +187,63 @@ fn new_opt<T: BytesContainer>(path: T) -> Option<Self> {
/// Returns the path as a string, if possible.
/// If the path is not representable in utf-8, this returns None.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("/abc/def");
/// assert_eq!(p.as_str(), Some("/abc/def"));
/// # }
/// ```
#[inline]
fn as_str<'a>(&'a self) -> Option<&'a str> {
str::from_utf8(self.as_vec())
}
/// Returns the path as a byte vector
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("abc/def");
/// assert_eq!(p.as_vec(), b"abc/def");
/// # }
/// ```
fn as_vec<'a>(&'a self) -> &'a [u8];
/// Converts the Path into an owned byte vector
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("abc/def");
/// assert_eq!(p.into_vec(), b"abc/def".to_vec());
/// // attempting to use p now results in "error: use of moved value"
/// # }
/// ```
fn into_vec(self) -> Vec<u8>;
/// Returns an object that implements `Show` for printing paths
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("abc/def");
/// println!("{}", p.display()); // prints "abc/def"
/// # }
/// ```
fn display<'a>(&'a self) -> Display<'a, Self> {
Display{ path: self, filename: false }
}
......@@ -185,32 +251,102 @@ fn display<'a>(&'a self) -> Display<'a, Self> {
/// Returns an object that implements `Show` for printing filenames
///
/// If there is no filename, nothing will be printed.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("abc/def");
/// println!("{}", p.filename_display()); // prints "def"
/// # }
/// ```
fn filename_display<'a>(&'a self) -> Display<'a, Self> {
Display{ path: self, filename: true }
}
/// Returns the directory component of `self`, as a byte vector (with no trailing separator).
/// If `self` has no directory component, returns ['.'].
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("abc/def/ghi");
/// assert_eq!(p.dirname(), b"abc/def");
/// # }
/// ```
fn dirname<'a>(&'a self) -> &'a [u8];
/// Returns the directory component of `self`, as a string, if possible.
/// See `dirname` for details.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("abc/def/ghi");
/// assert_eq!(p.dirname_str(), Some("abc/def"));
/// # }
/// ```
#[inline]
fn dirname_str<'a>(&'a self) -> Option<&'a str> {
str::from_utf8(self.dirname())
}
/// Returns the file component of `self`, as a byte vector.
/// If `self` represents the root of the file hierarchy, returns None.
/// If `self` is "." or "..", returns None.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("abc/def/ghi");
/// assert_eq!(p.filename(), Some(b"ghi"));
/// # }
/// ```
fn filename<'a>(&'a self) -> Option<&'a [u8]>;
/// Returns the file component of `self`, as a string, if possible.
/// See `filename` for details.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("abc/def/ghi");
/// assert_eq!(p.filename_str(), Some("ghi"));
/// # }
/// ```
#[inline]
fn filename_str<'a>(&'a self) -> Option<&'a str> {
self.filename().and_then(str::from_utf8)
}
/// Returns the stem of the filename of `self`, as a byte vector.
/// The stem is the portion of the filename just before the last '.'.
/// If there is no '.', the entire filename is returned.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("/abc/def.txt");
/// assert_eq!(p.filestem(), Some(b"def"));
/// # }
/// ```
fn filestem<'a>(&'a self) -> Option<&'a [u8]> {
match self.filename() {
None => None,
......@@ -224,16 +360,40 @@ fn filestem<'a>(&'a self) -> Option<&'a [u8]> {
})
}
}
/// Returns the stem of the filename of `self`, as a string, if possible.
/// See `filestem` for details.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("/abc/def.txt");
/// assert_eq!(p.filestem_str(), Some("def"));
/// # }
/// ```
#[inline]
fn filestem_str<'a>(&'a self) -> Option<&'a str> {
self.filestem().and_then(str::from_utf8)
}
/// Returns the extension of the filename of `self`, as an optional byte vector.
/// The extension is the portion of the filename just after the last '.'.
/// If there is no extension, None is returned.
/// If the filename ends in '.', the empty vector is returned.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("abc/def.txt");
/// assert_eq!(p.extension(), Some(b"txt"));
/// # }
/// ```
fn extension<'a>(&'a self) -> Option<&'a [u8]> {
match self.filename() {
None => None,
......@@ -247,8 +407,20 @@ fn extension<'a>(&'a self) -> Option<&'a [u8]> {
}
}
}
/// Returns the extension of the filename of `self`, as a string, if possible.
/// See `extension` for details.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("abc/def.txt");
/// assert_eq!(p.extension_str(), Some("txt"));
/// # }
/// ```
#[inline]
fn extension_str<'a>(&'a self) -> Option<&'a str> {
self.extension().and_then(str::from_utf8)
......@@ -257,6 +429,18 @@ fn extension_str<'a>(&'a self) -> Option<&'a str> {
/// Replaces the filename portion of the path with the given byte vector or string.
/// If the replacement name is [], this is equivalent to popping the path.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let mut p = Path::new("abc/def.txt");
/// p.set_filename("foo.dat");
/// assert!(p == Path::new("abc/foo.dat"));
/// # }
/// ```
///
/// # Failure
///
/// Fails the task if the filename contains a NUL.
......@@ -265,11 +449,24 @@ fn set_filename<T: BytesContainer>(&mut self, filename: T) {
assert!(!contains_nul(&filename));
unsafe { self.set_filename_unchecked(filename) }
}
/// Replaces the extension with the given byte vector or string.
/// If there is no extension in `self`, this adds one.
/// If the argument is [] or "", this removes the extension.
/// If `self` has no filename, this is a no-op.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let mut p = Path::new("abc/def.txt");
/// p.set_extension("csv");
/// assert!(p == Path::new("abc/def.csv"));
/// # }
/// ```
///
/// # Failure
///
/// Fails the task if the extension contains a NUL.
......@@ -308,6 +505,17 @@ fn set_extension<T: BytesContainer>(&mut self, extension: T) {
/// byte vector or string.
/// See `set_filename` for details.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let mut p = Path::new("abc/def.txt");
/// assert!(p.with_filename("foo.dat") == Path::new("abc/foo.dat"));
/// # }
/// ```
///
/// # Failure
///
/// Fails the task if the filename contains a NUL.
......@@ -317,10 +525,22 @@ fn with_filename<T: BytesContainer>(&self, filename: T) -> Self {
p.set_filename(filename);
p
}
/// Returns a new Path constructed by setting the extension to the given
/// byte vector or string.
/// See `set_extension` for details.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let mut p = Path::new("abc/def.txt");
/// assert!(p.with_extension("csv") == Path::new("abc/def.csv"));
/// # }
/// ```
///
/// # Failure
///
/// Fails the task if the extension contains a NUL.
......@@ -333,6 +553,17 @@ fn with_extension<T: BytesContainer>(&self, extension: T) -> Self {
/// Returns the directory component of `self`, as a Path.
/// If `self` represents the root of the filesystem hierarchy, returns `self`.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("abc/def/ghi");
/// assert!(p.dir_path() == Path::new("abc/def"));
/// # }
/// ```
fn dir_path(&self) -> Self {
// self.dirname() returns a NUL-free vector
unsafe { GenericPathUnsafe::new_unchecked(self.dirname()) }
......@@ -341,11 +572,34 @@ fn dir_path(&self) -> Self {
/// Returns a Path that represents the filesystem root that `self` is rooted in.
///
/// If `self` is not absolute, or vol/cwd-relative in the case of Windows, this returns None.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// assert!(Path::new("abc/def").root_path() == None);
/// assert!(Path::new("/abc/def").root_path() == Some(Path::new("/")));
/// # }
/// ```
fn root_path(&self) -> Option<Self>;
/// Pushes a path (as a byte vector or string) onto `self`.
/// If the argument represents an absolute path, it replaces `self`.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let mut p = Path::new("foo/bar");
/// p.push("baz.txt");
/// assert!(p == Path::new("foo/bar/baz.txt"));
/// # }
/// ```
///
/// # Failure
///
/// Fails the task if the path contains a NUL.
......@@ -354,8 +608,21 @@ fn push<T: BytesContainer>(&mut self, path: T) {
assert!(!contains_nul(&path));
unsafe { self.push_unchecked(path) }
}
/// Pushes multiple paths (as byte vectors or strings) onto `self`.
/// See `push` for details.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let mut p = Path::new("foo");
/// p.push_many(&["bar", "baz.txt"]);
/// assert!(p == Path::new("foo/bar/baz.txt"));
/// # }
/// ```
#[inline]
fn push_many<T: BytesContainer>(&mut self, paths: &[T]) {
let t: Option<T> = None;
......@@ -369,15 +636,39 @@ fn push_many<T: BytesContainer>(&mut self, paths: &[T]) {
}
}
}
/// Removes the last path component from the receiver.
/// Returns `true` if the receiver was modified, or `false` if it already
/// represented the root of the file hierarchy.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let mut p = Path::new("foo/bar/baz.txt");
/// p.pop();
/// assert!(p == Path::new("foo/bar"));
/// # }
/// ```
fn pop(&mut self) -> bool;
/// Returns a new Path constructed by joining `self` with the given path
/// (as a byte vector or string).
/// If the given path is absolute, the new Path will represent just that.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("/foo");
/// assert!(p.join("bar.txt") == Path::new("/foo/bar.txt"));
/// # }
/// ```
///
/// # Failure
///
/// Fails the task if the path contains a NUL.
......@@ -387,9 +678,22 @@ fn join<T: BytesContainer>(&self, path: T) -> Self {
p.push(path);
p
}
/// Returns a new Path constructed by joining `self` with the given paths
/// (as byte vectors or strings).
/// See `join` for details.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("foo");
/// let fbbq = Path::new("foo/bar/baz/quux.txt");
/// assert!(p.join_many(&["bar", "baz", "quux.txt"]) == fbbq);
/// # }
/// ```
#[inline]
fn join_many<T: BytesContainer>(&self, paths: &[T]) -> Self {
let mut p = self.clone();
......@@ -400,12 +704,34 @@ fn join_many<T: BytesContainer>(&self, paths: &[T]) -> Self {
/// Returns whether `self` represents an absolute path.
/// An absolute path is defined as one that, when joined to another path, will
/// yield back the same absolute path.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("/abc/def");
/// assert!(p.is_absolute());
/// # }
/// ```
fn is_absolute(&self) -> bool;
/// Returns whether `self` represents a relative path.
/// Typically this is the inverse of `is_absolute`.
/// But for Windows paths, it also means the path is not volume-relative or
/// relative to the current working directory.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("abc/def");
/// assert!(p.is_relative());
/// # }
/// ```
fn is_relative(&self) -> bool {
!self.is_absolute()
}
......@@ -413,15 +739,53 @@ fn is_relative(&self) -> bool {
/// Returns whether `self` is equal to, or is an ancestor of, the given path.
/// If both paths are relative, they are compared as though they are relative
/// to the same parent path.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("foo/bar/baz/quux.txt");
/// let fb = Path::new("foo/bar");
/// let bq = Path::new("baz/quux.txt");
/// assert!(fb.is_ancestor_of(&p));
/// # }
/// ```
fn is_ancestor_of(&self, other: &Self) -> bool;
/// Returns the Path that, were it joined to `base`, would yield `self`.
/// If no such path exists, None is returned.
/// If `self` is absolute and `base` is relative, or on Windows if both
/// paths refer to separate drives, an absolute path is returned.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("foo/bar/baz/quux.txt");
/// let fb = Path::new("foo/bar");
/// let bq = Path::new("baz/quux.txt");
/// assert!(p.path_relative_from(&fb) == Some(bq));
/// # }
/// ```
fn path_relative_from(&self, base: &Self) -> Option<Self>;
/// Returns whether the relative path `child` is a suffix of `self`.
///
/// # Example
///
/// ```
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// let p = Path::new("foo/bar/baz/quux.txt");
/// let bq = Path::new("baz/quux.txt");
/// assert!(p.ends_with_path(&bq));
/// # }
/// ```
fn ends_with_path(&self, child: &Self) -> bool;
}
......
......@@ -690,6 +690,13 @@ fn expr_tuple(&self, sp: Span, exprs: Vec<Gc<ast::Expr>>) -> Gc<ast::Expr> {
fn expr_fail(&self, span: Span, msg: InternedString) -> Gc<ast::Expr> {
let loc = self.codemap().lookup_char_pos(span.lo);
let expr_file = self.expr_str(span,
token::intern_and_get_ident(loc.file
.name
.as_slice()));
let expr_line = self.expr_uint(span, loc.line);
let expr_file_line_tuple = self.expr_tuple(span, vec!(expr_file, expr_line));
let expr_file_line_ptr = self.expr_addr_of(span, expr_file_line_tuple);
self.expr_call_global(
span,
vec!(
......@@ -698,11 +705,7 @@ fn expr_fail(&self, span: Span, msg: InternedString) -> Gc<ast::Expr> {
self.ident_of("begin_unwind")),
vec!(
self.expr_str(span, msg),
self.expr_str(span,
token::intern_and_get_ident(loc.file
.name
.as_slice())),
self.expr_uint(span, loc.line)))
expr_file_line_ptr))
}
fn expr_unreachable(&self, span: Span) -> Gc<ast::Expr> {
......
......@@ -164,7 +164,7 @@ pub fn new(samples: &[T]) -> Summary<T> {
}
}
impl<'a,T: FloatMath + FromPrimitive> Stats<T> for &'a [T] {
impl<'a, T: FloatMath + FromPrimitive> Stats<T> for &'a [T] {
// FIXME #11059 handle NaN, inf and overflow
fn sum(self) -> T {
......
......@@ -394,7 +394,7 @@ fn maybe_push_value(map: &mut HashMap<String, Vec<String>>,
}
}
fn split_char_first<'a>(s: &'a str, c: char) -> (&'a str, &'a str) {
fn split_char_first(s: &str, c: char) -> (&str, &str) {
let mut iter = s.splitn(c, 1);
match (iter.next(), iter.next()) {
......@@ -466,7 +466,7 @@ pub fn query_to_str(query: &Query) -> String {
/// };
/// println!("Scheme in use: {}.", scheme); // Scheme in use: https.
/// ```
pub fn get_scheme<'a>(rawurl: &'a str) -> DecodeResult<(&'a str, &'a str)> {
pub fn get_scheme(rawurl: &str) -> DecodeResult<(&str, &str)> {
for (i,c) in rawurl.chars().enumerate() {
let result = match c {
'A' .. 'Z'
......@@ -493,8 +493,8 @@ pub fn get_scheme<'a>(rawurl: &'a str) -> DecodeResult<(&'a str, &'a str)> {
}
// returns userinfo, host, port, and unparsed part, or an error
fn get_authority<'a>(rawurl: &'a str) ->
DecodeResult<(Option<UserInfo>, &'a str, Option<u16>, &'a str)> {
fn get_authority(rawurl: &str) ->
DecodeResult<(Option<UserInfo>, &str, Option<u16>, &str)> {
enum State {
Start, // starting state
PassHostPort, // could be in user or port
......@@ -662,8 +662,7 @@ enum Input {
// returns the path and unparsed part of url, or an error
fn get_path<'a>(rawurl: &'a str, is_authority: bool)
-> DecodeResult<(String, &'a str)> {
fn get_path(rawurl: &str, is_authority: bool) -> DecodeResult<(String, &str)> {
let len = rawurl.len();
let mut end = len;
for (i,c) in rawurl.chars().enumerate() {
......
......@@ -29,6 +29,8 @@
To create a new random (V4) UUID and print it out in hexadecimal form:
```rust
# #![allow(deprecated)]
# extern crate uuid;
use uuid::Uuid;
fn main() {
......@@ -55,7 +57,8 @@ fn main() {
*/
#![crate_name = "uuid"]
#![experimental]
#![deprecated = "This is now a cargo package located at: \
https://github.com/rust-lang/uuid"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
......@@ -312,7 +315,7 @@ pub fn get_version(&self) -> Option<UuidVersion> {
}
/// Return an array of 16 octets containing the UUID data
pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
pub fn as_bytes(&self) -> &[u8] {
self.bytes.as_slice()
}
......
......@@ -12,7 +12,7 @@
#![feature(lang_items)]
#[lang="fail_"]
fn fail(_: &'static str, _: &'static str, _: uint) -> ! { loop {} }
fn fail(_: &(&'static str, &'static str, uint)) -> ! { loop {} }
#[lang = "stack_exhausted"]
extern fn stack_exhausted() {}
......
// Copyright 2012-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 struct GslResult {
pub val: f64,
pub err: f64
}
impl GslResult {
pub fn new() -> GslResult {
Result { //~ ERROR: `Result` does not name a structure
val: 0f64,
err: 0f64
}
}
}
fn main() {}
......@@ -10,33 +10,33 @@
// ignore-test FIXME(#5121)
extern crate time;
extern crate rbml;
extern crate serialize;
extern crate time;
// These tests used to be separate files, but I wanted to refactor all
// the common code.
use std::hashmap::{HashMap, HashSet};
use EBReader = serialize::ebml::reader;
use EBWriter = serialize::ebml::writer;
use EBReader = rbml::reader;
use EBWriter = rbml::writer;
use std::cmp::Eq;
use std::cmp;
use std::io;
use serialize::{Decodable, Encodable};
fn test_ebml<'a, 'b, A:
fn test_rbml<'a, 'b, A:
Eq +
Encodable<EBWriter::Encoder<'a>> +
Decodable<EBReader::Decoder<'b>>
>(a1: &A) {
let mut wr = std::io::MemWriter::new();
let mut ebml_w = EBwriter::Encoder::new(&mut wr);
a1.encode(&mut ebml_w);
let mut rbml_w = EBwriter::Encoder::new(&mut wr);
a1.encode(&mut rbml_w);
let bytes = wr.get_ref();
let d: serialize::ebml::Doc<'a> = EBDoc::new(bytes);
let d: serialize::rbml::Doc<'a> = EBDoc::new(bytes);
let mut decoder: EBReader::Decoder<'a> = EBreader::Decoder::new(d);
let a2: A = Decodable::decode(&mut decoder);
assert!(*a1 == a2);
......@@ -133,40 +133,40 @@ enum CLike { A, B, C }
pub fn main() {
let a = &Plus(@Minus(@Val(3u), @Val(10u)), @Plus(@Val(22u), @Val(5u)));
test_ebml(a);
test_rbml(a);
let a = &Spanned {lo: 0u, hi: 5u, node: 22u};
test_ebml(a);
test_rbml(a);
let a = &Point {x: 3u, y: 5u};
test_ebml(a);
test_rbml(a);
let a = &Top(22u);
test_ebml(a);
test_rbml(a);
let a = &Bottom(222u);
test_ebml(a);
test_rbml(a);
let a = &A;
test_ebml(a);
test_rbml(a);
let a = &B;
test_ebml(a);
test_rbml(a);
let a = &time::now();
test_ebml(a);
test_rbml(a);
test_ebml(&1.0f32);
test_ebml(&1.0f64);
test_ebml(&'a');
test_rbml(&1.0f32);
test_rbml(&1.0f64);
test_rbml(&'a');
let mut a = HashMap::new();
test_ebml(&a);
test_rbml(&a);
a.insert(1, 2);
test_ebml(&a);
test_rbml(&a);
let mut a = HashSet::new();
test_ebml(&a);
test_rbml(&a);
a.insert(1);
test_ebml(&a);
test_rbml(&a);
}
......@@ -24,7 +24,10 @@ fn start(argc: int, argv: *const *const u8) -> int {
#[inline(never)]
fn foo() {
fail!()
let _v = vec![1i, 2, 3];
if os::getenv("IS_TEST").is_some() {
fail!()
}
}
#[inline(never)]
......@@ -37,8 +40,11 @@ fn double() {
}
fn runtest(me: &str) {
let mut template = Command::new(me);
template.env("IS_TEST", "1");
// Make sure that the stack trace is printed
let mut p = Command::new(me).arg("fail").env("RUST_BACKTRACE", "1").spawn().unwrap();
let p = template.clone().arg("fail").env("RUST_BACKTRACE", "1").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
......@@ -46,7 +52,7 @@ fn runtest(me: &str) {
"bad output: {}", s);
// Make sure the stack trace is *not* printed
let mut p = Command::new(me).arg("fail").spawn().unwrap();
let p = template.clone().arg("fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
......@@ -54,7 +60,7 @@ fn runtest(me: &str) {
"bad output2: {}", s);
// Make sure a stack trace is printed
let mut p = Command::new(me).arg("double-fail").spawn().unwrap();
let p = template.clone().arg("double-fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
......@@ -62,7 +68,7 @@ fn runtest(me: &str) {
"bad output3: {}", s);
// Make sure a stack trace isn't printed too many times
let mut p = Command::new(me).arg("double-fail")
let p = template.clone().arg("double-fail")
.env("RUST_BACKTRACE", "1").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
......
......@@ -16,15 +16,16 @@
#![feature(struct_variant)]
extern crate rand;
extern crate rbml;
extern crate serialize;
use std::io::MemWriter;
use rand::{random, Rand};
use rbml;
use rbml::Doc;
use rbml::writer::Encoder;
use rbml::reader::Decoder;
use serialize::{Encodable, Decodable};
use serialize::ebml;
use serialize::ebml::Doc;
use serialize::ebml::writer::Encoder;
use serialize::ebml::reader::Decoder;
#[deriving(Encodable, Decodable, Eq, Rand)]
struct A;
......@@ -61,7 +62,7 @@ fn roundtrip<'a, T: Rand + Eq + Encodable<Encoder<'a>> +
let mut w = MemWriter::new();
let mut e = Encoder::new(&mut w);
obj.encode(&mut e);
let doc = ebml::Doc::new(@w.get_ref());
let doc = rbml::Doc::new(@w.get_ref());
let mut dec = Decoder::new(doc);
let obj2 = Decodable::decode(&mut dec);
assert!(obj == obj2);
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册