Rustbook already does this.
\fBopt\-level\fR=\fIVAL\fR
Optimize with possible levels 0\[en]3
-.SH ENVIRONMENT VARIABLES
+.SH ENVIRONMENT
Some of these affect the output of the compiler, while others affect programs
which link to the standard library.
fn ignore_target(config: &Config) -> String {
format!("ignore-{}", util::get_os(&config.target))
}
+ fn ignore_architecture(config: &Config) -> String {
+ format!("ignore-{}", util::get_arch(&config.target))
+ }
fn ignore_stage(config: &Config) -> String {
format!("ignore-{}",
config.stage_id.split('-').next().unwrap())
let val = iter_header(testfile, &mut |ln| {
!parse_name_directive(ln, "ignore-test") &&
!parse_name_directive(ln, &ignore_target(config)) &&
+ !parse_name_directive(ln, &ignore_architecture(config)) &&
!parse_name_directive(ln, &ignore_stage(config)) &&
!(config.mode == common::Pretty && parse_name_directive(ln, "ignore-pretty")) &&
!(config.target != config.host && parse_name_directive(ln, "ignore-cross-compile")) &&
#![allow(deprecated)] // for old path, for dynamic_lib
-use std::process::{ExitStatus, Command, Child, Output, Stdio};
-use std::io::prelude::*;
use std::dynamic_lib::DynamicLibrary;
+use std::io::prelude::*;
+use std::old_path::Path;
+use std::process::{ExitStatus, Command, Child, Output, Stdio};
fn add_target_env(cmd: &mut Command, lib_path: &str, aux_path: Option<&str>) {
// Need to be sure to put both the lib_path and the aux path in the dylib
("openbsd", "openbsd"),
];
+const ARCH_TABLE: &'static [(&'static str, &'static str)] = &[
+ ("i386", "x86"),
+ ("i686", "x86"),
+ ("amd64", "x86_64"),
+ ("x86_64", "x86_64"),
+ ("sparc", "sparc"),
+ ("powerpc", "powerpc"),
+ ("arm64", "aarch64"),
+ ("arm", "arm"),
+ ("aarch64", "aarch64"),
+ ("mips", "mips"),
+ ("xcore", "xcore"),
+ ("msp430", "msp430"),
+ ("hexagon", "hexagon"),
+ ("s390x", "systemz"),
+];
+
pub fn get_os(triple: &str) -> &'static str {
for &(triple_os, os) in OS_TABLE {
if triple.contains(triple_os) {
}
panic!("Cannot determine OS from triple");
}
+pub fn get_arch(triple: &str) -> &'static str {
+ for &(triple_arch, arch) in ARCH_TABLE {
+ if triple.contains(triple_arch) {
+ return arch
+ }
+ }
+ panic!("Cannot determine Architecture from triple");
+}
pub fn make_new_path(path: &str) -> String {
assert!(cfg!(windows));
use core::fmt::Debug;
use core::hash::{Hash, Hasher};
use core::iter::{Map, FromIterator, IntoIterator};
-use core::ops::{Index, IndexMut};
+use core::ops::{Index};
use core::{iter, fmt, mem, usize};
use Bound::{self, Included, Excluded, Unbounded};
}
}
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<K: Ord, Q: ?Sized, V> IndexMut<Q> for BTreeMap<K, V>
- where K: Borrow<Q>, Q: Ord
-{
- fn index_mut(&mut self, key: &Q) -> &mut V {
- self.get_mut(key).expect("no entry found for key")
- }
-}
-
/// Genericises over how to get the correct type of iterator from the correct type
/// of Node ownership.
trait Traverse<N> {
//!
//! ```
//! # #![allow(unused_must_use)]
+//! use std::io::Write;
//! let mut w = Vec::new();
//! write!(&mut w, "Hello {}!", "world");
//! ```
//!
//! ```
//! use std::fmt;
-//! use std::old_io;
+//! use std::io::{self, Write};
//!
//! fmt::format(format_args!("this returns {}", "String"));
//!
-//! let mut some_writer = old_io::stdout();
+//! let mut some_writer = io::stdout();
//! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro"));
//!
//! fn my_fmt_fn(args: fmt::Arguments) {
-//! write!(&mut old_io::stdout(), "{}", args);
+//! write!(&mut io::stdout(), "{}", args);
//! }
//! my_fmt_fn(format_args!("or a {} too", "function"));
//! ```
///
/// ```
/// # #![allow(unused_must_use)]
+/// use std::io::Write;
///
/// let mut w = Vec::new();
/// write!(&mut w, "test");
pub use ops::{Drop, Fn, FnMut, FnOnce};
// Reexported functions
-#[allow(deprecated)]
-pub use iter::range;
pub use mem::drop;
// Reexported types and traits
//! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11));
//!
//! // Consume the result and return the contents with `unwrap`.
-//! let final_awesome_result = good_result.ok().unwrap();
+//! let final_awesome_result = good_result.unwrap();
//! ```
//!
//! # Results must be used
//! something like this:
//!
//! ```{.ignore}
-//! use std::old_io::{File, Open, Write};
+//! use std::old_io::*;
+//! use std::old_path::Path;
//!
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! // If `write_line` errors, then we'll never know, because the return
//! a marginally useful message indicating why:
//!
//! ```{.no_run}
-//! use std::old_io::{File, Open, Write};
+//! use std::old_io::*;
+//! use std::old_path::Path;
//!
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! file.write_line("important message").ok().expect("failed to write message");
//! You might also simply assert success:
//!
//! ```{.no_run}
-//! # use std::old_io::{File, Open, Write};
+//! # use std::old_io::*;
+//! # use std::old_path::Path;
//!
//! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! assert!(file.write_line("important message").is_ok());
//! Or propagate the error up the call stack with `try!`:
//!
//! ```
-//! # use std::old_io::{File, Open, Write, IoError};
+//! # use std::old_io::*;
+//! # use std::old_path::Path;
//! fn write_message() -> Result<(), IoError> {
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! try!(file.write_line("important message"));
//! It replaces this:
//!
//! ```
-//! use std::old_io::{File, Open, Write, IoError};
+//! use std::old_io::*;
+//! use std::old_path::Path;
//!
//! struct Info {
//! name: String,
//! With this:
//!
//! ```
-//! use std::old_io::{File, Open, Write, IoError};
+//! use std::old_io::*;
+//! use std::old_path::Path;
//!
//! struct Info {
//! name: String,
/// ignoring I/O and parse errors:
///
/// ```
- /// use std::old_io::IoResult;
+ /// use std::old_io::*;
///
/// let mut buffer: &[u8] = b"1\n2\n3\n4\n";
/// let mut buffer = &mut buffer;
/// line.trim_right().parse::<int>().unwrap_or(0)
/// });
/// // Add the value if there were no errors, otherwise add 0
- /// sum += val.ok().unwrap_or(0);
+ /// sum += val.unwrap_or(0);
/// }
///
/// assert!(sum == 10);
fn check_contains_all_substrings(s: &str) {
assert!(s.contains(""));
for i in 0..s.len() {
- for j in range(i+1, s.len() + 1) {
+ for j in i+1..s.len() + 1 {
assert!(s.contains(&s[i..j]));
}
}
use std::io::prelude::*;
use std::mem;
use std::env;
-use std::ptr;
use std::rt;
use std::slice;
-use std::sync::{Once, ONCE_INIT};
+use std::sync::{Once, ONCE_INIT, StaticMutex, MUTEX_INIT};
use directive::LOG_LEVEL_NAMES;
/// The default logging level of a crate if no other is specified.
const DEFAULT_LOG_LEVEL: u32 = 1;
+static LOCK: StaticMutex = MUTEX_INIT;
+
/// An unsafe constant that is the maximum logging level of any module
/// specified. This is the first line of defense to determining whether a
/// logging statement should be run.
pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) {
// Test the literal string from args against the current filter, if there
// is one.
- match unsafe { FILTER.as_ref() } {
- Some(filter) if !args.to_string().contains(&filter[..]) => return,
- _ => {}
+ unsafe {
+ let _g = LOCK.lock();
+ match FILTER as uint {
+ 0 => {}
+ 1 => panic!("cannot log after main thread has exited"),
+ n => {
+ let filter = mem::transmute::<_, &String>(n);
+ if !args.to_string().contains(&filter[..]) {
+ return
+ }
+ }
+ }
}
// Completely remove the local logger from TLS in case anyone attempts to
// This assertion should never get tripped unless we're in an at_exit
// handler after logging has been torn down and a logging attempt was made.
- assert!(unsafe { !DIRECTIVES.is_null() });
- enabled(level, module, unsafe { (*DIRECTIVES).iter() })
+ let _g = LOCK.lock();
+ unsafe {
+ assert!(DIRECTIVES as uint != 0);
+ assert!(DIRECTIVES as uint != 1,
+ "cannot log after the main thread has exited");
+
+ enabled(level, module, (*DIRECTIVES).iter())
+ }
}
fn enabled(level: u32,
// Schedule the cleanup for the globals for when the runtime exits.
rt::at_exit(move || {
+ let _g = LOCK.lock();
assert!(!DIRECTIVES.is_null());
- let _directives: Box<Vec<directive::LogDirective>> =
- Box::from_raw(DIRECTIVES);
- DIRECTIVES = ptr::null_mut();
+ let _directives = Box::from_raw(DIRECTIVES);
+ DIRECTIVES = 1 as *mut _;
if !FILTER.is_null() {
- let _filter: Box<String> = Box::from_raw(FILTER);
- FILTER = 0 as *mut _;
+ let _filter = Box::from_raw(FILTER);
+ FILTER = 1 as *mut _;
}
});
}
--- /dev/null
+An informal guide to reading and working on the rustc compiler.
+==================================================================
+
+If you wish to expand on this document, or have a more experienced
+Rust contributor add anything else to it, please get in touch:
+
+* http://internals.rust-lang.org/
+* https://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust
+
+or file a bug:
+
+https://github.com/rust-lang/rust/issues
+
+Your concerns are probably the same as someone else's.
+
+The crates of rustc
+===================
+
+Rustc consists of a number of crates, including `libsyntax`,
+`librustc`, `librustc_back`, `librustc_trans`, and `librustc_driver`
+(the names and divisions are not set in stone and may change;
+in general, a finer-grained division of crates is preferable):
+
+- `libsyntax` contains those things concerned purely with syntax –
+ that is, the AST, parser, pretty-printer, lexer, macro expander, and
+ utilities for traversing ASTs – are in a separate crate called
+ "syntax", whose files are in `./../libsyntax`, where `.` is the
+ current directory (that is, the parent directory of front/, middle/,
+ back/, and so on).
+
+- `librustc` (the current directory) contains the high-level analysis
+ passes, such as the type checker, borrow checker, and so forth.
+ It is the heart of the compiler.
+
+- `librustc_back` contains some very low-level details that are
+ specific to different LLVM targets and so forth.
+
+- `librustc_trans` contains the code to convert from Rust IR into LLVM
+ IR, and then from LLVM IR into machine code, as well as the main
+ driver that orchestrates all the other passes and various other bits
+ of miscellany. In general it contains code that runs towards the
+ end of the compilation process.
+
+- `librustc_driver` invokes the compiler from `libsyntax`, then the
+ analysis phases from `librustc`, and finally the lowering and
+ codegen passes from `librustc_trans`.
+
+Roughly speaking the "order" of the three crates is as follows:
+
+ libsyntax -> librustc -> librustc_trans
+ | |
+ +-----------------+-------------------+
+ |
+ librustc_driver
+
+
+Modules in the rustc crate
+==========================
+
+The rustc crate itself consists of the following submodules
+(mostly, but not entirely, in their own directories):
+
+- session: options and data that pertain to the compilation session as
+ a whole
+- middle: middle-end: name resolution, typechecking, LLVM code
+ generation
+- metadata: encoder and decoder for data required by separate
+ compilation
+- plugin: infrastructure for compiler plugins
+- lint: infrastructure for compiler warnings
+- util: ubiquitous types and helper functions
+- lib: bindings to LLVM
+
+The entry-point for the compiler is main() in the librustc_trans
+crate.
+
+The 3 central data structures:
+------------------------------
+
+1. `./../libsyntax/ast.rs` defines the AST. The AST is treated as
+ immutable after parsing, but it depends on mutable context data
+ structures (mainly hash maps) to give it meaning.
+
+ - Many – though not all – nodes within this data structure are
+ wrapped in the type `spanned<T>`, meaning that the front-end has
+ marked the input coordinates of that node. The member `node` is
+ the data itself, the member `span` is the input location (file,
+ line, column; both low and high).
+
+ - Many other nodes within this data structure carry a
+ `def_id`. These nodes represent the 'target' of some name
+ reference elsewhere in the tree. When the AST is resolved, by
+ `middle/resolve.rs`, all names wind up acquiring a def that they
+ point to. So anything that can be pointed-to by a name winds
+ up with a `def_id`.
+
+2. `middle/ty.rs` defines the datatype `sty`. This is the type that
+ represents types after they have been resolved and normalized by
+ the middle-end. The typeck phase converts every ast type to a
+ `ty::sty`, and the latter is used to drive later phases of
+ compilation. Most variants in the `ast::ty` tag have a
+ corresponding variant in the `ty::sty` tag.
+
+3. `./../librustc_llvm/lib.rs` defines the exported types
+ `ValueRef`, `TypeRef`, `BasicBlockRef`, and several others.
+ Each of these is an opaque pointer to an LLVM type,
+ manipulated through the `lib::llvm` interface.
+
+
+Control and information flow within the compiler:
+-------------------------------------------------
+
+- main() in lib.rs assumes control on startup. Options are
+ parsed, platform is detected, etc.
+
+- `./../libsyntax/parse/parser.rs` parses the input files and produces
+ an AST that represents the input crate.
+
+- Multiple middle-end passes (`middle/resolve.rs`, `middle/typeck.rs`)
+ analyze the semantics of the resulting AST. Each pass generates new
+ information about the AST and stores it in various environment data
+ structures. The driver passes environments to each compiler pass
+ that needs to refer to them.
+
+- Finally, the `trans` module in `librustc_trans` translates the Rust
+ AST to LLVM bitcode in a type-directed way. When it's finished
+ synthesizing LLVM values, rustc asks LLVM to write them out in some
+ form (`.bc`, `.o`) and possibly run the system linker.
+++ /dev/null
-An informal guide to reading and working on the rustc compiler.
-==================================================================
-
-If you wish to expand on this document, or have a more experienced
-Rust contributor add anything else to it, please get in touch:
-
-* http://internals.rust-lang.org/
-* https://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust
-
-or file a bug:
-
-https://github.com/rust-lang/rust/issues
-
-Your concerns are probably the same as someone else's.
-
-The crates of rustc
-===================
-
-Rustc consists of four crates altogether: `libsyntax`, `librustc`,
-`librustc_back`, and `librustc_trans` (the names and divisions are not
-set in stone and may change; in general, a finer-grained division of
-crates is preferable):
-
-- `libsyntax` contains those things concerned purely with syntax --
- that is, the AST, parser, pretty-printer, lexer, macro expander, and
- utilities for traversing ASTs -- are in a separate crate called
- "syntax", whose files are in ./../libsyntax, where . is the current
- directory (that is, the parent directory of front/, middle/, back/,
- and so on).
-
-- `librustc` (the current directory) contains the high-level analysis
- passes, such as the type checker, borrow checker, and so forth.
- It is the heart of the compiler.
-
-- `librustc_back` contains some very low-level details that are
- specific to different LLVM targets and so forth.
-
-- `librustc_trans` contains the code to convert from Rust IR into LLVM
- IR, and then from LLVM IR into machine code, as well as the main
- driver that orchestrates all the other passes and various other bits
- of miscellany. In general it contains code that runs towards the
- end of the compilation process.
-
-Roughly speaking the "order" of the three crates is as follows:
-
- libsyntax -> librustc -> librustc_trans
- | |
- +-----------------+-------------------+
- |
- librustc_trans/driver
-
-Here the role of `librustc_trans/driver` is to invoke the compiler
-from libsyntax, then the analysis phases from librustc, and finally
-the lowering and codegen passes from librustc_trans.
-
-Modules in the rustc crate
-==========================
-
-The rustc crate itself consists of the following subdirectories
-(mostly, but not entirely, in their own directories):
-
-session - options and data that pertain to the compilation session as a whole
-middle - middle-end: name resolution, typechecking, LLVM code
- generation
-metadata - encoder and decoder for data required by
- separate compilation
-util - ubiquitous types and helper functions
-lib - bindings to LLVM
-
-The entry-point for the compiler is main() in the librustc_trans
-crate.
-
-The 3 central data structures:
-------------------------------
-
-#1: ./../libsyntax/ast.rs defines the AST. The AST is treated as immutable
- after parsing, but it depends on mutable context data structures
- (mainly hash maps) to give it meaning.
-
- - Many -- though not all -- nodes within this data structure are
- wrapped in the type `spanned<T>`, meaning that the front-end has
- marked the input coordinates of that node. The member .node is
- the data itself, the member .span is the input location (file,
- line, column; both low and high).
-
- - Many other nodes within this data structure carry a
- def_id. These nodes represent the 'target' of some name
- reference elsewhere in the tree. When the AST is resolved, by
- middle/resolve.rs, all names wind up acquiring a def that they
- point to. So anything that can be pointed-to by a name winds
- up with a def_id.
-
-#2: middle/ty.rs defines the datatype sty. This is the type that
- represents types after they have been resolved and normalized by
- the middle-end. The typeck phase converts every ast type to a
- ty::sty, and the latter is used to drive later phases of
- compilation. Most variants in the ast::ty tag have a
- corresponding variant in the ty::sty tag.
-
-#3: lib/llvm.rs (in librustc_trans) defines the exported types
- ValueRef, TypeRef, BasicBlockRef, and several others. Each of
- these is an opaque pointer to an LLVM type, manipulated through
- the lib::llvm interface.
-
-
-Control and information flow within the compiler:
--------------------------------------------------
-
-- main() in lib.rs assumes control on startup. Options are
- parsed, platform is detected, etc.
-
-- ./../libsyntax/parse/parser.rs parses the input files and produces an AST
- that represents the input crate.
-
-- Multiple middle-end passes (middle/resolve.rs, middle/typeck.rs)
- analyze the semantics of the resulting AST. Each pass generates new
- information about the AST and stores it in various environment data
- structures. The driver passes environments to each compiler pass
- that needs to refer to them.
-
-- Finally, the `trans` module in `librustc_trans` translates the Rust
- AST to LLVM bitcode in a type-directed way. When it's finished
- synthesizing LLVM values, rustc asks LLVM to write them out in some
- form (.bc, .o) and possibly run the system linker.
use std::io::prelude::*;
use std::num::FromPrimitive;
use std::rc::Rc;
+use std::fmt::Debug;
use rbml::reader;
use rbml::writer::Encoder;
fn emit_def_id(&mut self, did: ast::DefId);
}
-impl<S:serialize::Encoder> def_id_encoder_helpers for S {
+impl<S:serialize::Encoder> def_id_encoder_helpers for S
+ where <S as serialize::serialize::Encoder>::Error: Debug
+{
fn emit_def_id(&mut self, did: ast::DefId) {
- did.encode(self).ok().unwrap()
+ did.encode(self).unwrap()
}
}
cdata: &cstore::crate_metadata) -> ast::DefId;
}
-impl<D:serialize::Decoder> def_id_decoder_helpers for D {
+impl<D:serialize::Decoder> def_id_decoder_helpers for D
+ where <D as serialize::serialize::Decoder>::Error: Debug
+{
fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId {
- let did: ast::DefId = Decodable::decode(self).ok().unwrap();
+ let did: ast::DefId = Decodable::decode(self).unwrap();
did.tr(dcx)
}
fn read_def_id_nodcx(&mut self,
- cdata: &cstore::crate_metadata) -> ast::DefId {
- let did: ast::DefId = Decodable::decode(self).ok().unwrap();
+ cdata: &cstore::crate_metadata)
+ -> ast::DefId {
+ let did: ast::DefId = Decodable::decode(self).unwrap();
decoder::translate_def_id(cdata, did)
}
}
fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
-> ty::ClosureKind
{
- Decodable::decode(self).ok().unwrap()
+ Decodable::decode(self).unwrap()
}
fn read_closure_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)
}
impl<'a, 'ast> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a, 'ast> {
- fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(&self.name[..]).ok().unwrap() }
+ fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(&self.name[..]).unwrap() }
fn node_id(&'a self, &(i,_): &Node<'a>) -> dot::Id<'a> {
- dot::Id::new(format!("N{}", i.node_id())).ok().unwrap()
+ dot::Id::new(format!("N{}", i.node_id())).unwrap()
}
fn node_label(&'a self, &(i, n): &Node<'a>) -> dot::LabelText<'a> {
return;
}
- let requested_output = env::var("RUST_REGION_GRAPH").ok();
+ let requested_output = env::var("RUST_REGION_GRAPH");
debug!("requested_output: {:?} requested_node: {:?}",
requested_output, requested_node);
let output_path = {
let output_template = match requested_output {
- Some(ref s) if &**s == "help" => {
+ Ok(ref s) if &**s == "help" => {
static PRINTED_YET: AtomicBool = ATOMIC_BOOL_INIT;
if !PRINTED_YET.load(Ordering::SeqCst) {
print_help_message();
return;
}
- Some(other_path) => other_path,
- None => "/tmp/constraints.node%.dot".to_string(),
+ Ok(other_path) => other_path,
+ Err(_) => "/tmp/constraints.node%.dot".to_string(),
};
if output_template.len() == 0 {
impl<'a, 'tcx> dot::Labeller<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> {
fn graph_id(&self) -> dot::Id {
- dot::Id::new(&*self.graph_name).ok().unwrap()
+ dot::Id::new(&*self.graph_name).unwrap()
}
fn node_id(&self, n: &Node) -> dot::Id {
let node_id = match self.node_ids.get(n) {
// except according to those terms.
use std::io;
-#[allow(deprecated)] use std::old_path;
+#[allow(deprecated)] use std::old_path::{self, GenericPath};
#[allow(deprecated)] use std::old_io;
use std::path::{Path, PathBuf};
use std::old_io::fs::{File, symlink, mkdir, mkdir_recursive};
use super::old_realpath as realpath;
use std::old_io::TempDir;
+ use std::old_path::{Path, GenericPath};
#[test]
fn realpath_works() {
if let ast::ExprAddrOf(mutbl, ref base) = ex.node {
let param_env = ty::empty_parameter_environment(self.bccx.tcx);
let mc = mc::MemCategorizationContext::new(¶m_env);
- let base_cmt = mc.cat_expr(&**base).ok().unwrap();
+ let base_cmt = mc.cat_expr(&**base).unwrap();
let borrow_kind = ty::BorrowKind::from_mutbl(mutbl);
// Check that we don't allow borrows of unsafe static items.
if check_aliasability(self.bccx, ex.span, euv::AddrOf,
return;
}
if self.glob_map.contains_key(&import_id) {
- self.glob_map[import_id].insert(name);
+ self.glob_map.get_mut(&import_id).unwrap().insert(name);
return;
}
// We've successfully resolved the import. Write the results in.
let mut import_resolutions = module_.import_resolutions.borrow_mut();
- let import_resolution = &mut (*import_resolutions)[target];
+ let import_resolution = import_resolutions.get_mut(&target).unwrap();
{
let mut check_and_write_import = |namespace, result: &_, used_public: &mut bool| {
-See the README.txt in ../librustc.
+See the README.md in ../librustc.
LowerBound(Result<'blk, 'tcx>)
}
-#[derive(Clone, Copy)]
+#[derive(Clone, Copy, PartialEq)]
pub enum TransBindingMode {
TrByCopy(/* llbinding */ ValueRef),
TrByMove,
None => {
let data = &m[0].data;
for &(ref ident, ref value_ptr) in &m[0].bound_ptrs {
- let llmatch = data.bindings_map[*ident].llmatch;
- call_lifetime_start(bcx, llmatch);
- Store(bcx, *value_ptr, llmatch);
+ let binfo = data.bindings_map[*ident];
+ call_lifetime_start(bcx, binfo.llmatch);
+ if binfo.trmode == TrByRef && type_is_fat_ptr(bcx.tcx(), binfo.ty) {
+ expr::copy_fat_ptr(bcx, *value_ptr, binfo.llmatch);
+ }
+ else {
+ Store(bcx, *value_ptr, binfo.llmatch);
+ }
}
match data.arm.guard {
Some(ref guard_expr) => {
_ => None
}
};
-
match adt_vals {
Some(field_vals) => {
let pats = enter_match(bcx, dm, m, col, val, |pats|
ast::BindByRef(_) => {
// By ref binding: the value of the variable
- // is the pointer `val` itself.
- Store(bcx, val, llval);
+ // is the pointer `val` itself or fat pointer referenced by `val`
+ if type_is_fat_ptr(bcx.tcx(), ty) {
+ expr::copy_fat_ptr(bcx, val, llval);
+ }
+ else {
+ Store(bcx, val, llval);
+ }
+
bcx
}
}
/// gives us better information about what we are loading.
pub fn load_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
- if type_is_zero_size(cx.ccx(), t) {
- C_undef(type_of::type_of(cx.ccx(), t))
- } else if type_is_immediate(cx.ccx(), t) && type_of::type_of(cx.ccx(), t).is_aggregate() {
- // We want to pass small aggregates as immediate values, but using an aggregate LLVM type
- // for this leads to bad optimizations, so its arg type is an appropriately sized integer
- // and we have to convert it
- Load(cx, BitCast(cx, ptr, type_of::arg_type_of(cx.ccx(), t).ptr_to()))
- } else {
- unsafe {
- let global = llvm::LLVMIsAGlobalVariable(ptr);
- if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
- let val = llvm::LLVMGetInitializer(global);
- if !val.is_null() {
- // This could go into its own function, for DRY.
- // (something like "pre-store packing/post-load unpacking")
- if ty::type_is_bool(t) {
- return Trunc(cx, val, Type::i1(cx.ccx()));
- } else {
- return val;
- }
- }
+ if cx.unreachable.get() || type_is_zero_size(cx.ccx(), t) {
+ return C_undef(type_of::type_of(cx.ccx(), t));
+ }
+
+ let ptr = to_arg_ty_ptr(cx, ptr, t);
+
+ if type_is_immediate(cx.ccx(), t) && type_of::type_of(cx.ccx(), t).is_aggregate() {
+ return Load(cx, ptr);
+ }
+
+ unsafe {
+ let global = llvm::LLVMIsAGlobalVariable(ptr);
+ if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
+ let val = llvm::LLVMGetInitializer(global);
+ if !val.is_null() {
+ return from_arg_ty(cx, val, t);
}
}
- if ty::type_is_bool(t) {
- Trunc(cx, LoadRangeAssert(cx, ptr, 0, 2, llvm::False), Type::i1(cx.ccx()))
- } else if ty::type_is_char(t) {
- // a char is a Unicode codepoint, and so takes values from 0
- // to 0x10FFFF inclusive only.
- LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
- } else if (ty::type_is_region_ptr(t) || ty::type_is_unique(t))
- && !common::type_is_fat_ptr(cx.tcx(), t) {
- LoadNonNull(cx, ptr)
- } else {
- Load(cx, ptr)
- }
}
+
+ let val = if ty::type_is_bool(t) {
+ LoadRangeAssert(cx, ptr, 0, 2, llvm::False)
+ } else if ty::type_is_char(t) {
+ // a char is a Unicode codepoint, and so takes values from 0
+ // to 0x10FFFF inclusive only.
+ LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
+ } else if (ty::type_is_region_ptr(t) || ty::type_is_unique(t))
+ && !common::type_is_fat_ptr(cx.tcx(), t) {
+ LoadNonNull(cx, ptr)
+ } else {
+ Load(cx, ptr)
+ };
+
+ from_arg_ty(cx, val, t)
}
/// Helper for storing values in memory. Does the necessary conversion if the in-memory type
/// differs from the type used for SSA values.
pub fn store_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
- if ty::type_is_bool(t) {
- Store(cx, ZExt(cx, v, Type::i8(cx.ccx())), dst);
- } else if type_is_immediate(cx.ccx(), t) && type_of::type_of(cx.ccx(), t).is_aggregate() {
+ Store(cx, to_arg_ty(cx, v, t), to_arg_ty_ptr(cx, dst, t));
+}
+
+pub fn to_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
+ if ty::type_is_bool(ty) {
+ ZExt(bcx, val, Type::i8(bcx.ccx()))
+ } else {
+ val
+ }
+}
+
+pub fn from_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
+ if ty::type_is_bool(ty) {
+ Trunc(bcx, val, Type::i1(bcx.ccx()))
+ } else {
+ val
+ }
+}
+
+pub fn to_arg_ty_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ptr: ValueRef, ty: Ty<'tcx>) -> ValueRef {
+ if type_is_immediate(bcx.ccx(), ty) && type_of::type_of(bcx.ccx(), ty).is_aggregate() {
// We want to pass small aggregates as immediate values, but using an aggregate LLVM type
// for this leads to bad optimizations, so its arg type is an appropriately sized integer
// and we have to convert it
- Store(cx, v, BitCast(cx, dst, type_of::arg_type_of(cx.ccx(), t).ptr_to()));
+ BitCast(bcx, ptr, type_of::arg_type_of(bcx.ccx(), ty).ptr_to())
} else {
- Store(cx, v, dst);
+ ptr
}
}
GEPi(bcx, fat_ptr, &[0, abi::FAT_PTR_ADDR])
}
+pub fn copy_fat_ptr(bcx: Block, src_ptr: ValueRef, dst_ptr: ValueRef) {
+ Store(bcx, Load(bcx, get_dataptr(bcx, src_ptr)), get_dataptr(bcx, dst_ptr));
+ Store(bcx, Load(bcx, get_len(bcx, src_ptr)), get_len(bcx, dst_ptr));
+}
+
// Retrieve the information we are losing (making dynamic) in an unsizing
// adjustment.
//
call_debug_location)
}
(_, "volatile_load") => {
- VolatileLoad(bcx, llargs[0])
+ let tp_ty = *substs.types.get(FnSpace, 0);
+ let ptr = to_arg_ty_ptr(bcx, llargs[0], tp_ty);
+ from_arg_ty(bcx, VolatileLoad(bcx, ptr), tp_ty)
},
(_, "volatile_store") => {
- VolatileStore(bcx, llargs[1], llargs[0]);
+ let tp_ty = *substs.types.get(FnSpace, 0);
+ let ptr = to_arg_ty_ptr(bcx, llargs[0], tp_ty);
+ let val = to_arg_ty(bcx, llargs[1], tp_ty);
+ VolatileStore(bcx, val, ptr);
C_nil(ccx)
},
llvm::SequentiallyConsistent
};
- let res = AtomicCmpXchg(bcx, llargs[0], llargs[1],
- llargs[2], order,
+ let tp_ty = *substs.types.get(FnSpace, 0);
+ let ptr = to_arg_ty_ptr(bcx, llargs[0], tp_ty);
+ let cmp = to_arg_ty(bcx, llargs[1], tp_ty);
+ let src = to_arg_ty(bcx, llargs[2], tp_ty);
+ let res = AtomicCmpXchg(bcx, ptr, cmp, src, order,
strongest_failure_ordering);
if unsafe { llvm::LLVMVersionMinor() >= 5 } {
ExtractValue(bcx, res, 0)
}
"load" => {
- AtomicLoad(bcx, llargs[0], order)
+ let tp_ty = *substs.types.get(FnSpace, 0);
+ let ptr = to_arg_ty_ptr(bcx, llargs[0], tp_ty);
+ from_arg_ty(bcx, AtomicLoad(bcx, ptr, order), tp_ty)
}
"store" => {
- AtomicStore(bcx, llargs[1], llargs[0], order);
+ let tp_ty = *substs.types.get(FnSpace, 0);
+ let ptr = to_arg_ty_ptr(bcx, llargs[0], tp_ty);
+ let val = to_arg_ty(bcx, llargs[1], tp_ty);
+ AtomicStore(bcx, val, ptr, order);
C_nil(ccx)
}
_ => ccx.sess().fatal("unknown atomic operation")
};
- AtomicRMW(bcx, atom_op, llargs[0], llargs[1], order)
+ let tp_ty = *substs.types.get(FnSpace, 0);
+ let ptr = to_arg_ty_ptr(bcx, llargs[0], tp_ty);
+ let val = to_arg_ty(bcx, llargs[1], tp_ty);
+ AtomicRMW(bcx, atom_op, ptr, val, order)
}
}
// borrow_kind of the upvar to make sure it
// is inferred to mutable if necessary
let mut upvar_capture_map = self.fcx.inh.upvar_capture_map.borrow_mut();
- let ub = &mut upvar_capture_map[upvar_id];
+ let ub = upvar_capture_map.get_mut(&upvar_id).unwrap();
self.adjust_upvar_borrow_kind(upvar_id, ub, borrow_kind);
// also need to be in an FnMut closure since this is not an ImmBorrow
use std::rc::Rc;
use std::sync::mpsc::channel;
+#[allow(deprecated)] use std::old_path::Path;
+
use externalfiles::ExternalHtml;
use serialize::Decodable;
use serialize::json::{self, Json};
use serialize::json;
use std::mem;
use std::string::String;
+use std::old_path::{Path, GenericPath};
pub type PluginJson = Option<(String, json::Json)>;
pub type PluginResult = (clean::Crate, PluginJson);
use std::{i64, u64, f32, f64};
use std::collections::BTreeMap;
use std::string;
+ use std::old_io::Writer;
#[derive(RustcDecodable, Eq, PartialEq, Debug)]
struct OptionData {
*/
#[allow(deprecated)]
-use std::old_path;
+use std::old_path::{self, GenericPath};
use std::path;
use std::rc::Rc;
use std::cell::{Cell, RefCell};
use iter::{self, Iterator, ExactSizeIterator, IntoIterator, IteratorExt, FromIterator, Extend, Map};
use marker::Sized;
use mem::{self, replace};
-use ops::{Deref, FnMut, Index, IndexMut};
+use ops::{Deref, FnMut, Index};
use option::Option::{self, Some, None};
use rand::{self, Rng};
use result::Result::{self, Ok, Err};
}
}
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<K, V, S, Q: ?Sized> IndexMut<Q> for HashMap<K, V, S>
- where K: Eq + Hash + Borrow<Q>,
- Q: Eq + Hash,
- S: HashState,
-{
- #[inline]
- fn index_mut<'a>(&'a mut self, index: &Q) -> &'a mut V {
- self.get_mut(index).expect("no entry found for key")
- }
-}
-
/// HashMap iterator.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Iter<'a, K: 'a, V: 'a> {
use prelude::v1::*;
+use env;
use ffi::CString;
use mem;
-use env;
-use str;
+use old_path::{Path, GenericPath};
use os;
+use str;
pub struct DynamicLibrary {
handle: *mut u8
use super::*;
use prelude::v1::*;
use libc;
+ use old_path::Path;
use mem;
#[test]
fn test_loading_cosine() {
// The math library does not need to be loaded since it is already
// statically linked in
- let none: Option<&Path> = None; // appease the typechecker
- let libm = match DynamicLibrary::open(none) {
+ let libm = match DynamicLibrary::open(None) {
Err(error) => panic!("Could not load self as module: {}", error),
Ok(libm) => libm
};
mod tests {
use prelude::v1::*;
use super::*;
+
use iter::repeat;
use rand::{self, Rng};
use ffi::{OsString, OsStr};
- use path::PathBuf;
+ use path::{Path, PathBuf};
fn make_rand_name() -> OsString {
let mut rng = rand::thread_rng();
use prelude::v1::*;
use io::prelude::*;
+ use env;
use fs::{self, File, OpenOptions};
use io::{ErrorKind, SeekFrom};
use path::PathBuf;
}
pub fn tmpdir() -> TempDir {
- let s = os::tmpdir();
- let p = Path2::new(s.as_str().unwrap());
+ let p = env::temp_dir();
let ret = p.join(&format!("rust-{}", rand::random::<u32>()));
check!(fs::create_dir(&ret));
TempDir(ret)
let dir = &tmpdir.join("di_readdir");
check!(fs::create_dir(dir));
let prefix = "foo";
- for n in range(0, 3) {
+ for n in 0..3 {
let f = dir.join(&format!("{}.txt", n));
let mut w = check!(File::create(&f));
let msg_str = format!("{}{}", prefix, n.to_string());
#[test]
fn binary_file() {
let mut bytes = [0; 1024];
- StdRng::new().ok().unwrap().fill_bytes(&mut bytes);
+ StdRng::new().unwrap().fill_bytes(&mut bytes);
let tmpdir = tmpdir();
fn read_to_end() {
let mut reader = Cursor::new(vec!(0, 1, 2, 3, 4, 5, 6, 7));
let mut v = Vec::new();
- reader.read_to_end(&mut v).ok().unwrap();
+ reader.read_to_end(&mut v).unwrap();
assert_eq!(v, [0, 1, 2, 3, 4, 5, 6, 7]);
}
#![stable(feature = "rust1", since = "1.0.0")]
-pub use super::{Read, Write, BufRead};
+pub use super::{Read, Write, BufRead, Seek};
pub use fs::PathExt;
-
-// FIXME: pub use as `Seek` when the name isn't in the actual prelude any more
-pub use super::Seek as NewSeek;
unique_local: bool, global: bool,
u_link_local: bool, u_site_local: bool, u_global: bool,
m_scope: Option<Ipv6MulticastScope>) {
- let ip: Ipv6Addr = str_addr.parse().ok().unwrap();
+ let ip: Ipv6Addr = str_addr.parse().unwrap();
assert_eq!(str_addr, ip.to_string());
assert_eq!(ip.is_unspecified(), unspec);
#![test]
assert_eq!((0 as $T).next_power_of_two(), 1);
let mut next_power = 1;
- for i in range::<$T>(1, 40) {
+ for i in 1 as $T..40 {
assert_eq!(i.next_power_of_two(), next_power);
if i == next_power { next_power *= 2 }
}
assert_eq!(($T::MAX - 1).checked_next_power_of_two(), None);
assert_eq!($T::MAX.checked_next_power_of_two(), None);
let mut next_power = 1;
- for i in range::<$T>(1, 40) {
+ for i in 1 as $T..40 {
assert_eq!(i.checked_next_power_of_two(), Some(next_power));
if i == next_power { next_power *= 2 }
}
/// # Examples
///
/// ```
-/// use std::old_io::{BufferedReader, File};
+/// use std::old_io::*;
+/// use std::old_path::Path;
///
/// let file = File::open(&Path::new("message.txt"));
/// let mut reader = BufferedReader::new(file);
/// # Examples
///
/// ```
-/// use std::old_io::{BufferedWriter, File};
+/// use std::old_io::*;
+/// use std::old_path::Path;
///
/// let file = File::create(&Path::new("message.txt")).unwrap();
/// let mut writer = BufferedWriter::new(file);
///
/// ```
/// # #![allow(unused_must_use)]
-/// use std::old_io::{BufferedStream, File};
+/// use std::old_io::*;
+/// use std::old_path::Path;
///
/// let file = File::open(&Path::new("message.txt"));
/// let mut stream = BufferedStream::new(file);
#[cfg(test)]
mod test {
extern crate test;
- use old_io;
+ use old_io::{self, Reader, Writer, Buffer, BufferPrelude};
use prelude::v1::*;
use super::*;
use super::super::{IoResult, EndOfFile};
///
/// ```
/// use std::sync::mpsc::channel;
-/// use std::old_io::ChanReader;
+/// use std::old_io::*;
///
/// let (tx, rx) = channel();
/// # drop(tx);
/// ```
/// # #![allow(unused_must_use)]
/// use std::sync::mpsc::channel;
-/// use std::old_io::ChanWriter;
+/// use std::old_io::*;
///
/// let (tx, rx) = channel();
/// # drop(rx);
use sync::mpsc::channel;
use super::*;
- use old_io;
+ use old_io::{self, Reader, Writer, Buffer};
use thread;
#[test]
#[cfg(test)]
mod test {
use prelude::v1::*;
- use old_io;
+ use old_io::{self, Reader, Writer};
use old_io::{MemReader, BytesReader};
struct InitialZeroByteReader {
//! ```rust
//! # #![allow(unused_must_use)]
//! use std::old_io::fs::PathExtensions;
-//! use std::old_io::{File, fs};
+//! use std::old_io::*;
+//! use std::old_path::Path;
//!
//! let path = Path::new("foo.txt");
//!
/// # Examples
///
/// ```rust,should_fail
- /// use std::old_io::{File, Open, ReadWrite};
+ /// use std::old_io::*;
+ /// use std::old_path::Path;
///
/// let p = Path::new("/some/file/path.txt");
///
/// # Examples
///
/// ```
- /// use std::old_io::File;
+ /// use std::old_io::*;
+ /// use std::old_path::Path;
///
/// let contents = File::open(&Path::new("foo.txt")).read_to_end();
/// ```
///
/// ```
/// # #![allow(unused_must_use)]
- /// use std::old_io::File;
+ /// use std::old_io::*;
+ /// use std::old_path::Path;
///
/// let mut f = File::create(&Path::new("foo.txt"));
/// f.write(b"This is a sample file");
///
/// ```
/// # #![allow(unused_must_use)]
-/// use std::old_io::fs;
+/// use std::old_io::*;
+/// use std::old_path::Path;
///
/// let p = Path::new("/some/file/path.txt");
/// fs::unlink(&p);
/// # Examples
///
/// ```
-/// use std::old_io::fs;
+/// use std::old_io::*;
+/// use std::old_path::Path;
///
/// let p = Path::new("/some/file/path.txt");
/// match fs::stat(&p) {
///
/// ```
/// # #![allow(unused_must_use)]
-/// use std::old_io::fs;
+/// use std::old_io::*;
+/// use std::old_path::Path;
///
/// fs::rename(&Path::new("foo"), &Path::new("bar"));
/// ```
///
/// ```
/// # #![allow(unused_must_use)]
-/// use std::old_io::fs;
+/// use std::old_io::*;
+/// use std::old_path::Path;
///
/// fs::copy(&Path::new("foo.txt"), &Path::new("bar.txt"));
/// ```
/// ```
/// # #![allow(unused_must_use)]
/// use std::old_io;
-/// use std::old_io::fs;
+/// use std::old_io::*;
+/// use std::old_path::Path;
///
/// fs::chmod(&Path::new("file.txt"), old_io::USER_FILE);
/// fs::chmod(&Path::new("file.txt"), old_io::USER_READ | old_io::USER_WRITE);
/// ```
/// # #![allow(unused_must_use)]
/// use std::old_io;
-/// use std::old_io::fs;
+/// use std::old_io::*;
+/// use std::old_path::Path;
///
/// let p = Path::new("/some/dir");
/// fs::mkdir(&p, old_io::USER_RWX);
///
/// ```
/// # #![allow(unused_must_use)]
-/// use std::old_io::fs;
+/// use std::old_io::*;
+/// use std::old_path::Path;
///
/// let p = Path::new("/some/dir");
/// fs::rmdir(&p);
///
/// ```
/// use std::old_io::fs::PathExtensions;
-/// use std::old_io::fs;
/// use std::old_io;
+/// use std::old_io::*;
+/// use std::old_path::Path;
///
/// // one possible implementation of fs::walk_dir only visiting files
/// fn visit_dirs<F>(dir: &Path, cb: &mut F) -> old_io::IoResult<()> where
mod test {
use prelude::v1::*;
use old_io::{SeekSet, SeekCur, SeekEnd, Read, Open, ReadWrite, FileType};
- use old_io;
+ use old_io::{self, Reader, Writer, Seek};
+ use old_path::{Path, GenericPath};
use str;
use old_io::fs::*;
use rand::{StdRng, Rng};
let mut bytes = [0; 1024];
- StdRng::new().ok().unwrap().fill_bytes(&mut bytes);
+ StdRng::new().unwrap().fill_bytes(&mut bytes);
let tmpdir = tmpdir();
///
/// ```
/// # #![allow(unused_must_use)]
-/// use std::old_io::MemWriter;
+/// use std::old_io::*;
///
/// let mut w = MemWriter::new();
/// w.write(&[0, 1, 2]);
///
/// ```
/// # #![allow(unused_must_use)]
-/// use std::old_io::MemReader;
+/// use std::old_io::*;
///
/// let mut r = MemReader::new(vec!(0, 1, 2));
///
///
/// ```
/// # #![allow(unused_must_use)]
-/// use std::old_io::BufWriter;
+/// use std::old_io::*;
///
/// let mut buf = [0; 4];
/// {
///
/// ```
/// # #![allow(unused_must_use)]
-/// use std::old_io::BufReader;
+/// use std::old_io::*;
///
/// let buf = [0, 1, 2, 3];
/// let mut r = BufReader::new(&buf);
#[cfg(test)]
mod test {
extern crate "test" as test_crate;
- use old_io::{SeekSet, SeekCur, SeekEnd, Reader, Writer, Seek};
- use prelude::v1::{Ok, Err, range, Vec, Buffer, AsSlice};
+ use old_io::{SeekSet, SeekCur, SeekEnd, Reader, Writer, Seek, Buffer};
+ use prelude::v1::{Ok, Err, Vec, AsSlice};
use prelude::v1::IteratorExt;
use old_io;
use iter::repeat;
//!
//! ```rust
//! use std::old_io as io;
+//! use std::old_io::*;
//!
//! let mut stdin = io::stdin();
//! for line in stdin.lock().lines() {
//! * Read a complete file
//!
//! ```rust
-//! use std::old_io::File;
+//! use std::old_io::*;
+//! use std::old_path::Path;
//!
//! let contents = File::open(&Path::new("message.txt")).read_to_end();
//! ```
//!
//! ```rust
//! # #![allow(unused_must_use)]
-//! use std::old_io::File;
+//! use std::old_io::*;
+//! use std::old_path::Path;
//!
//! let mut file = File::create(&Path::new("message.txt"));
//! file.write_all(b"hello, file!\n");
//! * Iterate over the lines of a file
//!
//! ```rust,no_run
-//! use std::old_io::BufferedReader;
-//! use std::old_io::File;
+//! use std::old_io::*;
+//! use std::old_path::Path;
//!
//! let path = Path::new("message.txt");
//! let mut file = BufferedReader::new(File::open(&path));
//! * Pull the lines of a file into a vector of strings
//!
//! ```rust,no_run
-//! use std::old_io::BufferedReader;
-//! use std::old_io::File;
+//! use std::old_io::*;
+//! use std::old_path::Path;
//!
//! let path = Path::new("message.txt");
//! let mut file = BufferedReader::new(File::open(&path));
//!
//! ```rust
//! # #![allow(unused_must_use)]
-//! use std::old_io::TcpStream;
+//! use std::old_io::*;
//!
//! # // connection doesn't fail if a server is running on 8080
//! # // locally, we still want to be type checking this code, so lets
//! # fn main() { }
//! # fn foo() {
//! # #![allow(dead_code)]
-//! use std::old_io::{TcpListener, TcpStream};
-//! use std::old_io::{Acceptor, Listener};
+//! use std::old_io::*;
//! use std::thread;
//!
//! let listener = TcpListener::bind("127.0.0.1:80");
//!
//! ```rust
//! # #![allow(unused_must_use)]
-//! use std::old_io::File;
+//! use std::old_io::*;
+//! use std::old_path::Path;
//!
//! match File::create(&Path::new("diary.txt")).write_all(b"Met a girl.\n") {
//! Ok(()) => (), // succeeded
//! If you wanted to read several `u32`s from a file and return their product:
//!
//! ```rust
-//! use std::old_io::{File, IoResult};
+//! use std::old_io::*;
+//! use std::old_path::Path;
//!
//! fn file_product(p: &Path) -> IoResult<u32> {
//! let mut f = File::open(p);
///
/// ```
/// use std::old_io as io;
-/// use std::old_io::ByRefReader;
+/// use std::old_io::*;
/// use std::old_io::util::LimitReader;
///
/// fn process_input<R: Reader>(r: R) {}
///
/// ```
/// use std::old_io::util::TeeReader;
-/// use std::old_io::{stdin, ByRefWriter};
+/// use std::old_io::*;
///
/// fn process_input<R: Reader>(r: R) {}
///
/// # Examples
///
/// ```
- /// use std::old_io::BufReader;
+ /// use std::old_io::*;
///
/// let mut reader = BufReader::new(b"hello\nworld");
/// assert_eq!("hello\n", &*reader.read_line().unwrap());
/// ```no_run
///
/// use std::old_io::fs::PathExtensions;
+/// use std::old_path::Path;
///
/// let info = match Path::new("foo.txt").stat() {
/// Ok(stat) => stat,
mod tests {
use self::BadReaderBehavior::*;
use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput, Writer};
- use prelude::v1::{Ok, Vec, Buffer};
+ use super::Buffer;
+ use prelude::v1::{Ok, Vec};
use usize;
#[derive(Clone, PartialEq, Debug)]
use ffi::CString;
use old_path::BytesContainer;
use old_io::{Listener, Acceptor, IoResult, TimedOut, standard_error};
+use old_io::{Reader, Writer};
use sys::pipe::UnixAcceptor as UnixAcceptorImp;
use sys::pipe::UnixListener as UnixListenerImp;
use sys::pipe::UnixStream as UnixStreamImp;
/// ```
/// # #![allow(unused_must_use)]
/// use std::old_io::net::pipe::UnixStream;
+ /// use std::old_io::*;
+ /// use std::old_path::Path;
///
/// let server = Path::new("path/to/my/socket");
/// let mut stream = UnixStream::connect(&server);
/// ```
/// # fn foo() {
/// use std::old_io::net::pipe::UnixListener;
- /// use std::old_io::{Listener, Acceptor};
+ /// use std::old_io::*;
+ /// use std::old_path::Path;
///
/// let server = Path::new("/path/to/my/socket");
/// let stream = UnixListener::bind(&server);
use old_io::{EndOfFile, TimedOut, ShortWrite, IoError, ConnectionReset};
use old_io::{NotConnected, BrokenPipe, FileNotFound, InvalidInput, OtherIoError};
use old_io::{PermissionDenied, Acceptor, Listener};
+ use old_io::{Reader, Writer};
use old_io::test::*;
use super::*;
use sync::mpsc::channel;
/// # Examples
///
/// ```no_run
-/// use std::old_io::TcpStream;
+/// use std::old_io::*;
///
/// {
/// let mut stream = TcpStream::connect("127.0.0.1:34254");
///
/// ```no_run
/// # #![allow(unused_must_use)]
- /// use std::old_io::timer;
- /// use std::old_io::TcpStream;
+ /// use std::old_io::*;
/// use std::time::Duration;
/// use std::thread;
///
///
/// ```
/// # fn foo() {
-/// use std::old_io::{TcpListener, TcpStream};
-/// use std::old_io::{Acceptor, Listener};
+/// use std::old_io::*;
/// use std::thread;
///
/// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
/// # Examples
///
/// ```no_run
- /// use std::old_io::TcpListener;
- /// use std::old_io::{Listener, Acceptor, TimedOut};
+ /// use std::old_io::*;
///
/// let mut a = TcpListener::bind("127.0.0.1:8482").listen().unwrap();
///
/// # Examples
///
/// ```
- /// use std::old_io::{TcpListener, Listener, Acceptor, EndOfFile};
+ /// use std::old_io::*;
/// use std::thread;
///
/// let mut a = TcpListener::bind("127.0.0.1:8482").listen().unwrap();
use old_io::{ConnectionReset, NotConnected, PermissionDenied, OtherIoError};
use old_io::{InvalidInput};
use old_io::{Acceptor, Listener};
+ use old_io::{Reader, Writer};
// FIXME #11530 this fails on android because tests are run as root
#[cfg_attr(any(windows, target_os = "android"), ignore)]
use prelude::v1::*;
-use old_io::IoResult;
+use old_io::{IoResult, Reader, Writer};
use libc;
use sync::Arc;
/// # #![allow(unused_must_use)]
/// extern crate libc;
///
- /// use std::old_io::pipe::PipeStream;
+ /// use std::old_io::*;
///
/// fn main() {
/// let mut pipe = PipeStream::open(libc::STDERR_FILENO);
mod test {
use prelude::v1::*;
+ use old_io::{Writer, Reader};
use sync::mpsc::channel;
use thread;
use ffi::CString;
use fmt;
use old_io::pipe::{PipeStream, PipePair};
-use old_io::{IoResult, IoError};
+use old_io::{IoResult, IoError, Reader, Writer};
use old_io;
+use old_path::{Path, GenericPath};
use libc;
use os;
use old_path::BytesContainer;
/// # Examples
///
/// ```should_fail
-/// use std::old_io::Command;
+/// use std::old_io::*;
///
/// let mut child = match Command::new("/bin/cat").arg("file.txt").spawn() {
/// Ok(child) => child,
/// to be changed (for example, by adding arguments) prior to spawning:
///
/// ```
-/// use std::old_io::Command;
+/// use std::old_io::*;
///
/// let mut process = match Command::new("sh").arg("-c").arg("echo hello").spawn() {
/// Ok(p) => p,
#[cfg(test)]
mod tests {
use old_io::{Truncate, Write, TimedOut, timer, process, FileNotFound};
- use prelude::v1::{Ok, Err, range, drop, Some, None, Vec};
- use prelude::v1::{Path, String, Reader, Writer, Clone};
- use prelude::v1::{Str, AsSlice, ToString, GenericPath};
+ use old_io::{Reader, Writer};
+ use prelude::v1::{Ok, Err, drop, Some, None, Vec};
+ use prelude::v1::{String, Clone};
+ use prelude::v1::{Str, AsSlice, ToString};
+ use old_path::{GenericPath, Path};
use old_io::fs::PathExtensions;
use old_io::timer::*;
use rt::running_on_valgrind;
mod test {
use prelude::v1::*;
use super::super::mem::*;
- use old_io;
+ use old_io::{self, Reader, Writer};
#[test]
fn test_option_writer() {
//! ```rust
//! # #![allow(unused_must_use)]
//! use std::old_io;
+//! use std::old_io::*;
//!
//! let mut out = old_io::stdout();
//! out.write_all(b"Hello, world!");
///
/// ```
/// use std::old_io;
+ /// use std::old_io::*;
///
/// let mut stdin = old_io::stdin();
/// for line in stdin.lock().lines() {
/// # Examples
///
/// ```no_run
-/// use std::old_io::TempDir;
+/// use std::old_io::*;
+/// use std::old_path::{Path, GenericPath};
///
/// {
/// // create a temporary directory
use env;
use libc;
-use std::old_io::net::ip::*;
+use old_io::net::ip::*;
+use old_path::{Path, GenericPath};
use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
/// Get a port number, starting at 9600, for use in tests
use prelude::v1::*;
use cmp;
-use old_io;
+use old_io::{self, Reader, Writer, Buffer};
use slice::bytes::MutableByteVector;
/// Wraps a `Reader`, limiting the number of bytes that can be read from it.
mod test {
use prelude::v1::*;
- use old_io::{MemReader, ByRefReader};
+ use old_io::{MemReader, ByRefReader, Reader, Writer, Buffer};
use old_io;
use super::*;
//!
//! ```rust
//! use std::old_io::fs::PathExtensions;
+//! use std::old_path::{Path, GenericPath};
//!
//! let mut path = Path::new("/tmp/path");
//! println!("path: {}", path.display());
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # #[cfg(unix)] fn foo() {
extern crate test;
use self::test::Bencher;
use super::*;
- use prelude::v1::{Clone, GenericPath};
+ use old_path::GenericPath;
+ use prelude::v1::Clone;
#[bench]
fn join_home_dir(b: &mut Bencher) {
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// println!("{}", Path::new(r"C:\some\path").display());
/// ```
#[inline]
/// # Examples
///
/// ```
+ /// use std::old_path::{Path, GenericPath};
/// let path = Path::new_opt(r"C:\some\path");
///
/// match path {
///
/// ```
/// use std::os;
+/// use std::old_path::{Path, GenericPath};
///
/// // We assume that we are in a valid directory.
/// let current_working_directory = os::getcwd().unwrap();
///
/// ```
/// use std::os;
+/// use std::old_path::{Path, GenericPath};
///
/// let key = "PATH";
/// match os::getenv_as_bytes(key) {
///
/// ```
/// use std::os;
+/// use std::old_path::{Path, GenericPath};
///
/// match os::self_exe_name() {
/// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
///
/// ```
/// use std::os;
+/// use std::old_path::{Path, GenericPath};
///
/// match os::self_exe_path() {
/// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
///
/// ```
/// use std::os;
+/// use std::old_path::{Path, GenericPath};
///
/// match os::homedir() {
/// Some(ref p) => println!("{}", p.display()),
///
/// ```
/// use std::os;
-/// use std::old_path::Path;
+/// use std::old_path::{Path, GenericPath};
///
/// // Assume we're in a path like /home/someuser
/// let rel_path = Path::new("..");
///
/// ```
/// use std::os;
-/// use std::old_path::Path;
+/// use std::old_path::{Path, GenericPath};
///
/// let root = Path::new("/");
/// assert!(os::change_dir(&root).is_ok());
use os;
use rand::Rng;
use rand;
+ use old_path::{Path, GenericPath};
+ use old_io::{Reader, Writer, Seek};
#[test]
pub fn last_os_error() {
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use vec::Vec;
-// NB: remove when path reform lands
-#[doc(no_inline)] pub use old_path::{Path, GenericPath};
-// NB: remove when I/O reform lands
-#[doc(no_inline)] pub use old_io::{Buffer, Writer, Reader, Seek, BufferPrelude};
-// NB: remove when range syntax lands
-#[allow(deprecated)]
-#[doc(no_inline)] pub use iter::range;
-
+// FIXME(#23454) should these be here?
#[doc(no_inline)] pub use num::wrapping::{Wrapping, WrappingOps};
use io::prelude::*;
use prelude::v1::{Ok, Err, drop, Some, Vec};
use prelude::v1::{String, Clone};
- use prelude::v1::{Str, AsSlice, ToString, GenericPath};
- use old_path;
+ use prelude::v1::{Str, AsSlice, ToString};
+ use old_path::{self, GenericPath};
use old_io::fs::PathExtensions;
use rt::running_on_valgrind;
use str;
}
}
-/// Enqueues a procedure to run when the runtime is cleaned up
-///
-/// The procedure passed to this function will be executed as part of the
-/// runtime cleanup phase. For normal rust programs, this means that it will run
-/// after all other threads have exited.
-///
-/// The procedure is *not* executed with a local `Thread` available to it, so
-/// primitives like logging, I/O, channels, spawning, etc, are *not* available.
-/// This is meant for "bare bones" usage to clean up runtime details, this is
-/// not meant as a general-purpose "let's clean everything up" function.
+/// Enqueues a procedure to run when the main thread exits.
///
/// It is forbidden for procedures to register more `at_exit` handlers when they
/// are running, and doing so will lead to a process abort.
-pub fn at_exit<F:FnOnce()+Send+'static>(f: F) {
+///
+/// Note that other threads may still be running when `at_exit` routines start
+/// running.
+pub fn at_exit<F: FnOnce() + Send + 'static>(f: F) {
at_exit_imp::push(Thunk::new(f));
}
pub unsafe fn cleanup() {
args::cleanup();
sys::stack_overflow::cleanup();
- // FIXME: (#20012): the resources being cleaned up by at_exit
- // currently are not prepared for cleanup to happen asynchronously
- // with detached threads using the resources; for now, we leak.
- // at_exit_imp::cleanup();
+ at_exit_imp::cleanup();
}
use libc::c_void;
use mem;
use sync::atomic::{self, Ordering};
-use sync::{Once, ONCE_INIT};
+use sys_common::mutex::{Mutex, MUTEX_INIT};
use rt::libunwind as uw;
/// Doing this split took the LLVM IR line counts of `fn main() { panic!()
/// }` from ~1900/3700 (-O/no opts) to 180/590.
#[inline(never)] #[cold] // this is the slow path, please never inline this
-fn begin_unwind_inner(msg: Box<Any + Send>, file_line: &(&'static str, uint)) -> ! {
- // Make sure the default panic handler is registered before we look at the
- // callbacks.
- static INIT: Once = ONCE_INIT;
- INIT.call_once(|| unsafe { register(panicking::on_panic); });
+fn begin_unwind_inner(msg: Box<Any + Send>,
+ file_line: &(&'static str, uint)) -> ! {
+ // Make sure the default failure handler is registered before we look at the
+ // callbacks. We also use a raw sys-based mutex here instead of a
+ // `std::sync` one as accessing TLS can cause weird recursive problems (and
+ // we don't need poison checking).
+ unsafe {
+ static LOCK: Mutex = MUTEX_INIT;
+ static mut INIT: bool = false;
+ LOCK.lock();
+ if !INIT {
+ register(panicking::on_panic);
+ INIT = true;
+ }
+ LOCK.unlock();
+ }
// First, invoke call the user-defined callbacks triggered on thread panic.
//
//
// ignore-lexer-test FIXME #15677
-use prelude::v1::*;
use io::prelude::*;
use env;
// asleep (we're looking at it), so the receiver
// can't go away.
(*a.get()).send(t).ok().unwrap();
- token.signal();
+ token.signal();
(a, Ok(()))
}
}
use boxed;
use cell::UnsafeCell;
-use ptr;
use rt;
use sync::{StaticMutex, StaticCondvar};
use sync::mpsc::{channel, Sender, Receiver};
{
unsafe {
let _guard = self.lock.lock().unwrap();
- if !*self.initialized.get() {
+ if *self.chan.get() as uint == 0 {
let (tx, rx) = channel();
*self.chan.get() = boxed::into_raw(box tx);
let (receive, send) = helper_signal::new();
self.cond.notify_one()
});
- rt::at_exit(move|| { self.shutdown() });
+ rt::at_exit(move || { self.shutdown() });
*self.initialized.get() = true;
+ } else if *self.chan.get() as uint == 1 {
+ panic!("cannot continue usage after shutdown");
}
}
}
// Must send and *then* signal to ensure that the child receives the
// message. Otherwise it could wake up and go to sleep before we
// send the message.
- assert!(!self.chan.get().is_null());
+ assert!(*self.chan.get() as uint != 0);
+ assert!(*self.chan.get() as uint != 1,
+ "cannot continue usage after shutdown");
(**self.chan.get()).send(msg).unwrap();
helper_signal::signal(*self.signal.get() as helper_signal::signal);
}
// returns.
let mut guard = self.lock.lock().unwrap();
+ let ptr = *self.chan.get();
+ if ptr as uint == 1 {
+ panic!("cannot continue usage after shutdown");
+ }
// Close the channel by destroying it
- let chan: Box<Sender<M>> = Box::from_raw(*self.chan.get());
- *self.chan.get() = ptr::null_mut();
+ let chan = Box::from_raw(*self.chan.get());
+ *self.chan.get() = 1 as *mut Sender<M>;
drop(chan);
helper_signal::signal(*self.signal.get() as helper_signal::signal);
use prelude::v1::*;
use sync::atomic::{self, AtomicUsize, Ordering};
-use sync::{Mutex, Once, ONCE_INIT};
use sys::thread_local as imp;
key: atomic::ATOMIC_USIZE_INIT,
};
-static INIT_KEYS: Once = ONCE_INIT;
-static mut KEYS: *mut Mutex<Vec<imp::Key>> = 0 as *mut _;
-
impl StaticKey {
/// Gets the value associated with this TLS key
///
#[allow(dead_code)]
fn output_fileline(w: &mut Write, file: &[u8], line: libc::c_int,
more: bool) -> io::Result<()> {
- let file = str::from_utf8(file).ok().unwrap_or("<unknown>");
+ let file = str::from_utf8(file).unwrap_or("<unknown>");
// prior line: " ##: {:2$} - func"
try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH));
if more {
use old_io::{IoResult, FileStat, SeekStyle};
use old_io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append};
use old_io;
+use old_path::{Path, GenericPath};
use libc::{self, c_int, c_void};
use mem;
use ptr;
let mut reader = FileDesc::new(reader, true);
let mut writer = FileDesc::new(writer, true);
- writer.write(b"test").ok().unwrap();
+ writer.write(b"test").unwrap();
let mut buf = [0; 4];
match reader.read(&mut buf) {
Ok(4) => {
}
pub fn signal(fd: libc::c_int) {
- FileDesc::new(fd, false).write(&[0]).ok().unwrap();
+ FileDesc::new(fd, false).write(&[0]).unwrap();
}
pub fn close(fd: libc::c_int) {
1 => {
loop {
match messages.try_recv() {
+ // Once we've been disconnected it means the main thread
+ // is exiting (at_exit has run). We could still have
+ // active timers for other threads, so we're just going
+ // to drop them all on the floor. This is all we can
+ // really do, however, to prevent resource leakage. The
+ // remaining timers will likely start panicking quickly
+ // as they attempt to re-use this thread but are
+ // disallowed to do so.
Err(TryRecvError::Disconnected) => {
- assert!(active.len() == 0);
break 'outer;
}
// drain the file descriptor
let mut buf = [0];
- assert_eq!(fd.read(&mut buf).ok().unwrap(), 1);
+ assert_eq!(fd.read(&mut buf).unwrap(), 1);
}
-1 if os::errno() == libc::EINTR as i32 => {}
#![allow(deprecated)] // for old path for dynamic lib
use prelude::v1::*;
+use io::prelude::*;
use dynamic_lib::DynamicLibrary;
-use io;
-use io::prelude::*;
use ffi::CStr;
use intrinsics;
+use io;
use libc;
use mem;
+use old_path::Path;
use ptr;
use str;
use sync::{StaticMutex, MUTEX_INIT};
use sys;
use sys_common::{self, mkerr_libc};
+use old_path::{Path, GenericPath};
use old_io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode};
use old_io::{IoResult, IoError, FileStat, SeekStyle};
use old_io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append};
impl Clone for UnixAcceptor {
fn clone(&self) -> UnixAcceptor {
- let name = to_utf16(&self.listener.name).ok().unwrap();
+ let name = to_utf16(&self.listener.name).unwrap();
UnixAcceptor {
inner: self.inner.clone(),
- event: Event::new(true, false).ok().unwrap(),
+ event: Event::new(true, false).unwrap(),
deadline: 0,
listener: UnixListener {
name: self.listener.name.clone(),
use old_io::{IoResult, IoError};
use old_io;
use os;
-use old_path::BytesContainer;
+use old_path::{BytesContainer, GenericPath};
use ptr;
use str;
use sync::{StaticMutex, MUTEX_INIT};
rt::at_exit(move|| {
DTOR_LOCK.lock();
let dtors = DTORS;
- DTORS = ptr::null_mut();
+ DTORS = 1 as *mut _;
Box::from_raw(dtors);
- assert!(DTORS.is_null()); // can't re-init after destructing
+ assert!(DTORS as uint == 1); // can't re-init after destructing
DTOR_LOCK.unlock();
});
}
unsafe fn register_dtor(key: Key, dtor: Dtor) {
DTOR_LOCK.lock();
init_dtors();
+ assert!(DTORS as uint != 0);
+ assert!(DTORS as uint != 1,
+ "cannot create new TLS keys after the main thread has exited");
(*DTORS).push((key, dtor));
DTOR_LOCK.unlock();
}
unsafe fn unregister_dtor(key: Key) -> bool {
DTOR_LOCK.lock();
init_dtors();
+ assert!(DTORS as uint != 0);
+ assert!(DTORS as uint != 1,
+ "cannot unregister destructors after the main thread has exited");
let ret = {
let dtors = &mut *DTORS;
let before = dtors.len();
any_run = false;
let dtors = {
DTOR_LOCK.lock();
- let ret = if DTORS.is_null() {
+ let ret = if DTORS as usize <= 1 {
Vec::new()
} else {
(*DTORS).iter().map(|s| *s).collect()
None => {}
}
}
+ // See the comment in unix::timer for why we don't have any
+ // asserts here and why we're likely just leaving timers on
+ // the floor as we exit.
Err(TryRecvError::Disconnected) => {
- assert_eq!(objs.len(), 1);
- assert_eq!(chans.len(), 0);
break 'outer;
}
Err(..) => break
use prelude::v1::*;
-use old_io::{self, IoError, IoResult, MemReader};
+use old_io::{self, IoError, IoResult, MemReader, Reader};
use iter::repeat;
use libc::types::os::arch::extra::LPCVOID;
use libc::{c_int, HANDLE, LPDWORD, DWORD, LPVOID};
use marker::PhantomData;
use rt::{self, unwind};
use sync::{Mutex, Condvar, Arc};
+use sys::thread as imp;
+use sys_common::{stack, thread_info};
use thunk::Thunk;
use time::Duration;
-use sys::thread as imp;
-use sys_common::{stack, thread_info};
+#[allow(deprecated)] use old_io::Writer;
/// Thread configuration. Provides detailed control over the properties
/// and behavior of new threads.
Err(e) => {
type T = &'static str;
assert!(e.is::<T>());
- assert_eq!(*e.downcast::<T>().ok().unwrap(), "static string");
+ assert_eq!(*e.downcast::<T>().unwrap(), "static string");
}
Ok(()) => panic!()
}
Err(e) => {
type T = String;
assert!(e.is::<T>());
- assert_eq!(*e.downcast::<T>().ok().unwrap(), "owned string".to_string());
+ assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
}
Ok(()) => panic!()
}
Err(e) => {
type T = Box<Any + Send>;
assert!(e.is::<T>());
- let any = e.downcast::<T>().ok().unwrap();
+ let any = e.downcast::<T>().unwrap();
assert!(any.is::<u16>());
- assert_eq!(*any.downcast::<u16>().ok().unwrap(), 413);
+ assert_eq!(*any.downcast::<u16>().unwrap(), 413);
}
Ok(()) => panic!()
}
//! fn encode(&self, s: &mut S) -> Result<(), E> {
//! s.emit_struct("Spanned", 2, |this| {
//! this.emit_struct_field("node", 0, |this| self.node.encode(this))
-//! .ok().unwrap();
+//! .unwrap();
//! this.emit_struct_field("span", 1, |this| self.span.encode(this))
//! })
//! }
//! d.read_struct("Spanned", 2, |this| {
//! Ok(Spanned {
//! node: this.read_struct_field("node", 0, |this| Decodable::decode(this))
-//! .ok().unwrap(),
+//! .unwrap(),
//! span: this.read_struct_field("span", 1, |this| Decodable::decode(this))
-//! .ok().unwrap(),
+//! .unwrap(),
//! })
//! })
//! }
// find the integer representing the name
self.scan_digits(base);
let encoded_name : u32 = self.with_str_from(start_bpos, |s| {
- num::from_str_radix(s, 10).ok().unwrap_or_else(|| {
+ num::from_str_radix(s, 10).unwrap_or_else(|_| {
panic!("expected digits representing a name, got {:?}, {}, range [{:?},{:?}]",
s, whence, start_bpos, self.last_pos);
})
let start_bpos = self.last_pos;
self.scan_digits(base);
let encoded_ctxt : ast::SyntaxContext = self.with_str_from(start_bpos, |s| {
- num::from_str_radix(s, 10).ok().unwrap_or_else(|| {
+ num::from_str_radix(s, 10).unwrap_or_else(|_| {
panic!("expected digits representing a ctxt, got {:?}, {}", s, whence);
})
});
}
};
- let entry = open(&term[..]);
- if entry.is_err() {
- if env::var("MSYSCON").ok().map_or(false, |s| {
- "mintty.exe" == s
- }) {
- // msys terminal
- return Some(box TerminfoTerminal {out: out,
- ti: msys_terminfo(),
- num_colors: 8} as Box<Terminal<T>+Send>);
- }
- debug!("error finding terminfo entry: {:?}", entry.err().unwrap());
- return None;
- }
+ let mut file = match open(&term[..]) {
+ Ok(f) => f,
+ Err(err) => return match env::var("MSYSCON") {
+ Ok(ref val) if &val[..] == "mintty.exe" => {
+ // msys terminal
+ Some(box TerminfoTerminal{
+ out: out,
+ ti: msys_terminfo(),
+ num_colors: 8,
+ } as Box<Terminal<T>+Send>)
+ },
+ _ => {
+ debug!("error finding terminfo entry: {:?}", err);
+ None
+ },
+ },
+ };
- let mut file = entry.unwrap();
let ti = parse(&mut file, false);
if ti.is_err() {
debug!("error parsing terminfo entry: {:?}", ti.err().unwrap());
mod tests {
use stats::Stats;
use stats::Summary;
- use std::old_io;
+ use std::old_io::{self, Writer};
use std::f64;
macro_rules! assert_approx_eq {
fn baz() { }
pub fn test() {
- let none: Option<&Path> = None; // appease the typechecker
- let lib = DynamicLibrary::open(none).unwrap();
+ let lib = DynamicLibrary::open(None).unwrap();
unsafe {
assert!(lib.symbol::<int>("foo").is_ok());
assert!(lib.symbol::<int>("baz").is_err());
#![feature(unboxed_closures)]
-use std::old_io::File;
+use std::old_io::*;
+use std::old_path::{Path, GenericPath};
use std::iter::repeat;
use std::mem::swap;
use std::env;
// OF THE POSSIBILITY OF SUCH DAMAGE.
use std::cmp::min;
-use std::old_io::{stdout, IoResult};
+use std::old_io::*;
use std::iter::repeat;
use std::env;
use std::slice::bytes::copy_memory;
// OF THE POSSIBILITY OF SUCH DAMAGE.
use std::cmp::min;
-use std::old_io::{BufferedWriter, File};
+use std::old_io::*;
use std::old_io;
+use std::old_path::Path;
use std::num::Float;
use std::env;
// given a FASTA file on stdin, process sequence THREE
fn main() {
- use std::old_io::{stdio, MemReader, BufferedReader};
+ use std::old_io::*;
let rdr = if env::var_os("RUST_BENCH").is_some() {
let foo = include_bytes!("shootout-k-nucleotide.data");
// ignore-pretty very bad with line comments
use std::old_io;
+use std::old_io::*;
use std::env;
use std::simd::f64x2;
use std::sync::Arc;
extern crate libc;
use std::old_io::stdio::{stdin_raw, stdout_raw};
-use std::old_io::{IoResult, EndOfFile};
+use std::old_io::*;
use std::ptr::{copy_memory, Unique};
use std::thread;
--- /dev/null
+// 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.
+
+// Test that macro reexports item are gated by `macro_reexport` feature gate.
+
+// aux-build:macro_reexport_1.rs
+// ignore-stage1
+
+#![crate_type = "dylib"]
+
+#[macro_reexport(reexported)]
+#[macro_use] #[no_link]
+extern crate macro_reexport_1;
+//~^ ERROR macros reexports are experimental and possibly buggy
+//~| HELP add #![feature(macro_reexport)] to the crate attributes to enable
#![feature(unboxed_closures)]
+use std::io::Read;
+
fn to_fn_once<A,F:FnOnce<A>>(f: F) -> F { f }
fn main() {
to_fn_once(move|| { x = 2; });
//~^ ERROR: cannot assign to immutable captured outer variable
- let s = std::old_io::stdin();
- to_fn_once(move|| { s.read_to_end(); });
+ let s = std::io::stdin();
+ to_fn_once(move|| { s.read_to_end(&mut Vec::new()); });
//~^ ERROR: cannot borrow immutable captured outer variable
}
--- /dev/null
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <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.
+
+// Test that patterns including the box syntax are gated by `box_patterns` feature gate.
+
+fn main() {
+ let x = Box::new(1);
+
+ match x {
+ box 1 => (),
+ //~^ box pattern syntax is experimental
+ //~| add #![feature(box_patterns)] to the crate attributes to enable
+ _ => ()
+ };
+}
--- /dev/null
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <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.
+
+// Test that the use of the box syntax is gated by `box_syntax` feature gate.
+
+fn main() {
+ let x = box 3;
+ //~^ ERROR box expression syntax is experimental; you can call `Box::new` instead.
+ //~| HELP add #![feature(box_syntax)] to the crate attributes to enable
+}
--- /dev/null
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <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.
+
+// Test that the use of smid types in the ffi is gated by `smid_ffi` feature gate.
+
+#![feature(simd)]
+
+#[repr(C)]
+#[derive(Copy)]
+#[simd]
+pub struct f32x4(f32, f32, f32, f32);
+
+#[allow(dead_code)]
+extern {
+ fn foo(x: f32x4);
+ //~^ ERROR use of SIMD type `f32x4` in FFI is highly experimental and may result in invalid code
+ //~| HELP add #![feature(simd_ffi)] to the crate attributes to enable
+}
+
+fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::old_io;
+use std::io::{self, Read};
use std::vec;
pub struct Container<'a> {
- reader: &'a mut Reader
+ reader: &'a mut Read
}
impl<'a> Container<'a> {
- pub fn wrap<'s>(reader: &'s mut Reader) -> Container<'s> {
+ pub fn wrap<'s>(reader: &'s mut io::Read) -> Container<'s> {
Container { reader: reader }
}
}
pub fn for_stdin<'a>() -> Container<'a> {
- let mut r = old_io::stdin();
- Container::wrap(&mut r as &mut Reader)
+ let mut r = io::stdin();
+ Container::wrap(&mut r as &mut io::Read)
}
fn main() {
fn main() {
error!("whatever");
- let _t = thread::spawn(move|| {
+ let _t = thread::scoped(move|| {
let _i = r(5);
});
panic!();
// except according to those terms.
use std::env;
-use std::old_io::{File, Command};
+use std::fs::File;
+use std::process::Command;
+use std::io::Write;
+use std::path::Path;
// creates broken.rs, which has the Ident \x00name_0,ctxt_0\x00
// embedded within it, and then attempts to compile broken.rs with the
let main_file = tmpdir.join("broken.rs");
let _ = File::create(&main_file).unwrap()
- .write_str("pub fn main() {
+ .write_all(b"pub fn main() {
let \x00name_0,ctxt_0\x00 = 3;
println!(\"{}\", \x00name_0,ctxt_0\x00);
- }");
+ }").unwrap();
// rustc is passed to us with --out-dir and -L etc., so we
// can't exec it directly
let result = Command::new("sh")
.arg("-c")
- .arg(&format!("{} {}",
- rustc,
- main_file.as_str()
- .unwrap()))
+ .arg(&format!("{} {}", rustc, main_file.display()))
.output().unwrap();
- let err = String::from_utf8_lossy(&result.error);
+ let err = String::from_utf8_lossy(&result.stderr);
// positive test so that this test will be updated when the
// compiler changes.
use std::dynamic_lib::DynamicLibrary;
use std::os;
+use std::old_path::Path;
pub fn main() {
unsafe {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::{char, env};
-use std::old_io::{File, Command};
+use std::fs::File;
+use std::io::prelude::*;
+use std::path::Path;
+use std::process::Command;
use std::rand::{thread_rng, Rng};
+use std::{char, env};
// creates unicode_input_multiple_files_{main,chars}.rs, where the
// former imports the latter. `_chars` just contains an identifier
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
{
let _ = File::create(&main_file).unwrap()
- .write_str("mod unicode_input_multiple_files_chars;");
+ .write_all(b"mod unicode_input_multiple_files_chars;").unwrap();
}
for _ in 0..100 {
let randoms = tmpdir.join("unicode_input_multiple_files_chars.rs");
let mut w = File::create(&randoms).unwrap();
for _ in 0..30 {
- let _ = w.write_char(random_char());
+ write!(&mut w, "{}", random_char()).unwrap();
}
}
.arg("-c")
.arg(&format!("{} {}",
rustc,
- main_file.as_str()
- .unwrap()))
+ main_file.display()))
.output().unwrap();
- let err = String::from_utf8_lossy(&result.error);
+ let err = String::from_utf8_lossy(&result.stderr);
// positive test so that this test will be updated when the
// compiler changes.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::old_io::{File, Command};
+use std::fs::File;
+use std::io::prelude::*;
use std::iter::repeat;
+use std::path::Path;
+use std::process::Command;
use std::rand::{thread_rng, Rng};
use std::{char, env};
.arg("-c")
.arg(&format!("{} {}",
rustc,
- main_file.as_str()
+ main_file.to_str()
.unwrap()))
.output().unwrap();
- let err = String::from_utf8_lossy(&result.error);
+ let err = String::from_utf8_lossy(&result.stderr);
// the span should end the line (e.g no extra ~'s)
let expected_span = format!("^{}\n", repeat("~").take(n - 1)
}
// Extra characters. Every line is preceded by `filename:lineno <actual code>`
- let offset = main_file.as_str().unwrap().len() + 3;
+ let offset = main_file.to_str().unwrap().len() + 3;
let result = Command::new("sh")
.arg("-c")
.arg(format!("{} {}",
rustc,
- main_file.as_str()
- .unwrap()))
+ main_file.display()))
.output().unwrap();
- let err = String::from_utf8_lossy(result.error.as_slice());
+ let err = String::from_utf8_lossy(&result.stderr);
// Test both the length of the snake and the leading spaces up to it
// compile-flags:-g
// ignore-pretty as this critically relies on line numbers
-use std::old_io::stderr;
+use std::io;
+use std::io::prelude::*;
use std::env;
#[path = "backtrace-debuginfo-aux.rs"] mod aux;
fn run_test(me: &str) {
use std::str;
- use std::old_io::process::Command;
+ use std::process::Command;
let mut template = Command::new(me);
template.env("RUST_BACKTRACE", "1");
let mut i = 0;
loop {
- let p = template.clone().arg(i.to_string()).spawn().unwrap();
- let out = p.wait_with_output().unwrap();
- let output = str::from_utf8(&out.output).unwrap();
- let error = str::from_utf8(&out.error).unwrap();
+ let out = Command::new(me)
+ .env("RUST_BACKTRACE", "1")
+ .arg(i.to_string()).output().unwrap();
+ let output = str::from_utf8(&out.stdout).unwrap();
+ let error = str::from_utf8(&out.stderr).unwrap();
if out.status.success() {
assert!(output.contains("done."), "bad output for successful run: {}", output);
break;
let args: Vec<String> = env::args().collect();
if args.len() >= 2 {
let case = args[1].parse().unwrap();
- writeln!(&mut stderr(), "test case {}", case).unwrap();
+ writeln!(&mut io::stderr(), "test case {}", case).unwrap();
outer(case, pos!());
println!("done.");
} else {
use log::{set_logger, Logger, LogRecord};
use std::sync::mpsc::channel;
use std::fmt;
-use std::old_io::{ChanReader, ChanWriter};
+use std::old_io::{ChanReader, ChanWriter, Reader, Writer};
use std::thread::Thread;
struct MyWriter(ChanWriter);
// no-pretty-expanded
-#![allow(unused_must_use, dead_code, deprecated)]
-use std::old_io::MemWriter;
+use std::io::Write;
use std::fmt;
struct Foo<'a> {
- writer: &'a mut (Writer+'a),
+ writer: &'a mut (Write+'a),
other: &'a str,
}
}
fn main() {
- let mut w = MemWriter::new();
- write!(&mut w as &mut Writer, "");
+ let mut w = Vec::new();
+ write!(&mut w as &mut Write, "");
write!(&mut w, ""); // should coerce
println!("ok");
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// ignore-aarch64
+
extern crate libc;
use std::mem;
fn desugared_for_loop_bad(byte: u8) -> u8 {
let mut result = 0;
- let mut x = IntoIterator::into_iter(range(0, u8::BITS));
+ let mut x = IntoIterator::into_iter(0..u8::BITS);
let mut y = Iterator::next(&mut x);
let mut z = y.unwrap();
byte >> z;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// ignore-aarch64
+
use std::env;
use std::io::prelude::*;
use std::io;
// except according to those terms.
use std::env;
-use std::old_io::{stdio, Command};
+use std::process::Command;
+use std::io::{self, Write};
fn main() {
let mut args = env::args();
if args.len() > 1 {
- let mut out = stdio::stdout();
+ let mut out = io::stdout();
out.write(&['a' as u8; 128 * 1024]).unwrap();
} else {
let out = Command::new(&args.next().unwrap()).arg("child").output();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// ignore-aarch64
+
use std::process::Command;
use std::env;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::old_io::BufReader;
-use std::old_io::BufferedReader;
-use std::old_io::File;
-use std::old_io::IoResult;
+use std::fs::File;
+use std::io::{self, BufReader, Read};
-struct Lexer<R: Reader>
+struct Lexer<R: Read>
{
- reader: BufferedReader<R>,
+ reader: BufReader<R>,
}
-impl<R: Reader> Lexer<R>
+impl<R: Read> Lexer<R>
{
pub fn new_from_reader(r: R) -> Lexer<R>
{
- Lexer{reader: BufferedReader::new(r)}
+ Lexer{reader: BufReader::new(r)}
}
- pub fn new_from_file(p: Path) -> IoResult<Lexer<File>>
+ pub fn new_from_file(p: &str) -> io::Result<Lexer<File>>
{
- Ok(Lexer::new_from_reader(try!(File::open(&p))))
+ Ok(Lexer::new_from_reader(try!(File::open(p))))
}
- pub fn new_from_str<'a>(s: &'a str) -> Lexer<BufReader<'a>>
+ pub fn new_from_str<'a>(s: &'a str) -> Lexer<&'a [u8]>
{
- Lexer::new_from_reader(BufReader::new(s.as_bytes()))
+ Lexer::new_from_reader(s.as_bytes())
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// ignore-aarch64
+
#[cfg(unix)]
fn main() {
use std::process::Command;
// A reduced version of the rustbook ice. The problem this encountered
// had to do with trans ignoring binders.
-#![feature(associated_types)]
-#![feature(macro_rules)]
-
use std::iter;
use std::os;
-use std::old_io::File;
+use std::fs::File;
+use std::io::prelude::*;
+use std::env;
+use std::path::Path;
-#[allow(unused)]
-pub fn parse_summary<R: Reader>(_: R, _: &Path) {
+pub fn parse_summary<R: Read>(_: R, _: &Path) {
let path_from_root = Path::new("");
- Path::new(iter::repeat("../")
+ Path::new(&iter::repeat("../")
.take(path_from_root.components().count() - 1)
.collect::<String>());
}
-fn main() {
- let cwd = os::getcwd().unwrap();
+fn foo() {
+ let cwd = env::current_dir().unwrap();
let src = cwd.clone();
- let summary = File::open(&src.join("SUMMARY.md"));
+ let summary = File::open(&src.join("SUMMARY.md")).unwrap();
let _ = parse_summary(summary, &src);
}
+
+fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// ignore-android
-// ignore-windows
-
// Regression test for #20797.
use std::default::Default;
-use std::old_io::IoResult;
-use std::old_io::fs;
-use std::old_io::fs::PathExtensions;
+use std::io;
+use std::fs;
+use std::path::{PathBuf, Path};
+
+pub trait PathExtensions {
+ fn is_dir(&self) -> bool { false }
+}
+
+impl PathExtensions for PathBuf {}
/// A strategy for acquiring more subpaths to walk.
pub trait Strategy {
- type P: PathExtensions;
- /// Get additional subpaths from a given path.
- fn get_more(&self, item: &Self::P) -> IoResult<Vec<Self::P>>;
- /// Determine whether a path should be walked further.
- /// This is run against each item from `get_more()`.
- fn prune(&self, p: &Self::P) -> bool;
+ type P: PathExtensions;
+ /// Get additional subpaths from a given path.
+ fn get_more(&self, item: &Self::P) -> io::Result<Vec<Self::P>>;
+ /// Determine whether a path should be walked further.
+ /// This is run against each item from `get_more()`.
+ fn prune(&self, p: &Self::P) -> bool;
}
/// The basic fully-recursive strategy. Nothing is pruned.
pub struct Recursive;
impl Strategy for Recursive {
- type P = Path;
- fn get_more(&self, p: &Path) -> IoResult<Vec<Path>> { fs::readdir(p) }
+ type P = PathBuf;
+ fn get_more(&self, p: &PathBuf) -> io::Result<Vec<PathBuf>> {
+ Ok(fs::read_dir(p).unwrap().map(|s| s.unwrap().path()).collect())
+ }
- fn prune(&self, _: &Path) -> bool { false }
+ fn prune(&self, _: &PathBuf) -> bool { false }
}
/// A directory walker of `P` using strategy `S`.
}
impl<S: Strategy> Subpaths<S> {
- /// Create a directory walker with a root path and strategy.
- pub fn new(p: &S::P, strategy: S) -> IoResult<Subpaths<S>> {
- let stack = try!(strategy.get_more(p));
- Ok(Subpaths { stack: stack, strategy: strategy })
- }
+ /// Create a directory walker with a root path and strategy.
+ pub fn new(p: &S::P, strategy: S) -> io::Result<Subpaths<S>> {
+ let stack = try!(strategy.get_more(p));
+ Ok(Subpaths { stack: stack, strategy: strategy })
+ }
}
impl<S: Default + Strategy> Subpaths<S> {
- /// Create a directory walker with a root path and a default strategy.
- pub fn walk(p: &S::P) -> IoResult<Subpaths<S>> {
- Subpaths::new(p, Default::default())
- }
+ /// Create a directory walker with a root path and a default strategy.
+ pub fn walk(p: &S::P) -> io::Result<Subpaths<S>> {
+ Subpaths::new(p, Default::default())
+ }
}
impl<S: Default + Strategy> Default for Subpaths<S> {
- fn default() -> Subpaths<S> {
- Subpaths { stack: Vec::new(), strategy: Default::default() }
- }
+ fn default() -> Subpaths<S> {
+ Subpaths { stack: Vec::new(), strategy: Default::default() }
+ }
}
impl<S: Strategy> Iterator for Subpaths<S> {
- type Item = S::P;
- fn next (&mut self) -> Option<S::P> {
- let mut opt_path = self.stack.pop();
- while opt_path.is_some() && self.strategy.prune(opt_path.as_ref().unwrap()) {
- opt_path = self.stack.pop();
- }
- match opt_path {
- Some(path) => {
- if PathExtensions::is_dir(&path) {
- let result = self.strategy.get_more(&path);
- match result {
- Ok(dirs) => { self.stack.extend(dirs.into_iter()); },
- Err(..) => { }
- }
+ type Item = S::P;
+ fn next (&mut self) -> Option<S::P> {
+ let mut opt_path = self.stack.pop();
+ while opt_path.is_some() && self.strategy.prune(opt_path.as_ref().unwrap()) {
+ opt_path = self.stack.pop();
+ }
+ match opt_path {
+ Some(path) => {
+ if path.is_dir() {
+ let result = self.strategy.get_more(&path);
+ match result {
+ Ok(dirs) => { self.stack.extend(dirs.into_iter()); },
+ Err(..) => { }
+ }
+ }
+ Some(path)
+ }
+ None => None,
}
- Some(path)
- }
- None => None,
}
- }
}
-fn main() {
- let mut walker: Subpaths<Recursive> = Subpaths::walk(&Path::new("/home")).unwrap();
+fn foo() {
+ let mut walker: Subpaths<Recursive> = Subpaths::walk(&PathBuf::new("/home")).unwrap();
}
+
+fn main() {}
--- /dev/null
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <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(core)]
+#![allow(warnings)]
+
+use std::intrinsics;
+
+#[derive(Copy)]
+struct Wrap(i64);
+
+// These volatile and atomic intrinsics used to cause an ICE
+
+unsafe fn test_bool(p: &mut bool, v: bool) {
+ intrinsics::volatile_load(p);
+ intrinsics::volatile_store(p, v);
+ intrinsics::atomic_load(p);
+ intrinsics::atomic_cxchg(p, v, v);
+ intrinsics::atomic_store(p, v);
+ intrinsics::atomic_xchg(p, v);
+}
+
+unsafe fn test_immediate_fca(p: &mut Wrap, v: Wrap) {
+ intrinsics::volatile_load(p);
+ intrinsics::volatile_store(p, v);
+ intrinsics::atomic_load(p);
+ intrinsics::atomic_cxchg(p, v, v);
+ intrinsics::atomic_store(p, v);
+ intrinsics::atomic_xchg(p, v);
+}
+
+fn main() {}
// This used to cause an ICE because the retslot for the "return" had the wrong type
fn testcase<'a>() -> Box<Iterator<Item=usize> + 'a> {
- return Box::new(range(0, 3).map(|i| { return i; }));
+ return Box::new((0..3).map(|i| { return i; }));
}
fn main() {
--- /dev/null
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <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.
+
+// Binding unsized expressions to ref patterns
+
+pub fn main() {
+ let ref a = *"abcdef";
+ assert_eq!(a, "abcdef");
+
+ match *"12345" {
+ ref b => { assert_eq!(b, "12345") }
+ }
+}
// non-ASCII characters. The child process ensures all the strings are
// intact.
+// ignore-aarch64
+
use std::io::prelude::*;
use std::io;
use std::fs;
fn main() {
let my_args = env::args().collect::<Vec<_>>();
- let my_cwd = PathBuf::new(os::getcwd().unwrap().as_str().unwrap());
+ let my_cwd = env::current_dir().unwrap();
let my_env = env::vars().collect::<Vec<_>>();
- let my_path = PathBuf::new(os::self_exe_name().unwrap().as_str().unwrap());
+ let my_path = env::current_exe().unwrap();
let my_dir = my_path.parent().unwrap();
let my_ext = my_path.extension().and_then(|s| s.to_str()).unwrap_or("");
// This test can't be a unit test in std,
// because it needs TempDir, which is in extra
-extern crate libc;
-
use std::ffi::CString;
-use std::old_io::TempDir;
-use std::old_io::fs::PathExtensions;
-use std::old_io::fs;
-use std::old_io;
-use std::os;
+use std::fs::{self, TempDir, File, PathExt};
fn rename_directory() {
- unsafe {
- static U_RWX: i32 = (libc::S_IRUSR | libc::S_IWUSR | libc::S_IXUSR) as i32;
-
- let tmpdir = TempDir::new("rename_directory").ok().expect("rename_directory failed");
- let tmpdir = tmpdir.path();
- let old_path = tmpdir.join_many(&["foo", "bar", "baz"]);
- fs::mkdir_recursive(&old_path, old_io::USER_RWX);
- let test_file = &old_path.join("temp.txt");
-
- /* Write the temp input file */
- let fromp = CString::new(test_file.as_vec()).unwrap();
- let modebuf = CString::new(&b"w+b"[..]).unwrap();
- let ostream = libc::fopen(fromp.as_ptr(), modebuf.as_ptr());
- assert!((ostream as uint != 0));
- let s = "hello".to_string();
- let buf = CString::new(&b"hello"[..]).unwrap();
- let write_len = libc::fwrite(buf.as_ptr() as *mut _,
- 1_usize as libc::size_t,
- (s.len() + 1_usize) as libc::size_t,
- ostream);
- assert_eq!(write_len, (s.len() + 1) as libc::size_t);
- assert_eq!(libc::fclose(ostream), (0_usize as libc::c_int));
-
- let new_path = tmpdir.join_many(&["quux", "blat"]);
- fs::mkdir_recursive(&new_path, old_io::USER_RWX);
- fs::rename(&old_path, &new_path.join("newdir"));
- assert!(new_path.join("newdir").is_dir());
- assert!(new_path.join_many(&["newdir", "temp.txt"]).exists());
- }
+ let tmpdir = TempDir::new("rename_directory").ok().expect("rename_directory failed");
+ let tmpdir = tmpdir.path();
+ let old_path = tmpdir.join("foo/bar/baz");
+ fs::create_dir_all(&old_path).unwrap();
+ let test_file = &old_path.join("temp.txt");
+
+ File::create(test_file).unwrap();
+
+ let new_path = tmpdir.join("quux/blat");
+ fs::create_dir_all(&new_path).unwrap();
+ fs::rename(&old_path, &new_path.join("newdir"));
+ assert!(new_path.join("newdir").is_dir());
+ assert!(new_path.join("newdir/temp.txt").exists());
}
pub fn main() { rename_directory() }
// Be sure that when a SIGPIPE would have been received that the entire process
// doesn't die in a ball of fire, but rather it's gracefully handled.
-use std::os;
use std::env;
-use std::old_io::PipeStream;
-use std::old_io::Command;
+use std::io::prelude::*;
+use std::io;
+use std::process::{Command, Stdio};
fn test() {
- let os::Pipe { reader, writer } = unsafe { os::pipe().unwrap() };
- let reader = PipeStream::open(reader);
- let mut writer = PipeStream::open(writer);
- drop(reader);
-
- let _ = writer.write(&[1]);
+ let _ = io::stdin().read_line(&mut String::new());
+ io::stdout().write(&[1]);
+ assert!(io::stdout().flush().is_err());
}
fn main() {
}
let mut p = Command::new(&args[0])
+ .stdout(Stdio::piped())
+ .stdin(Stdio::piped())
.arg("test").spawn().unwrap();
+ drop(p.stdout.take());
assert!(p.wait().unwrap().success());
}
pub fn main() {
let t = thread::spawn(move|| child((10, 20, 30, 40, 50, 60, 70, 80, 90)) );
- t.join().ok().unwrap();
+ t.join().ok().unwrap(); // forget Err value, since it doesn't implement Debug
}
fn child(args: (int, int, int, int, int, int, int, int, int)) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::old_io::fs::PathExtensions;
-use std::old_io::{File, TempDir};
+use std::fs::{File, TempDir};
+use std::io::prelude::*;
pub fn main() {
- let dir = TempDir::new_in(&Path::new("."), "").unwrap();
+ let dir = TempDir::new_in(".", "").unwrap();
let path = dir.path().join("file");
{
Err(..) => unreachable!(),
Ok(f) => {
let mut f = f;
- for _ in 0_usize..1000 {
+ for _ in 0..1000 {
f.write(&[0]);
}
}
}
assert!(path.exists());
- assert_eq!(path.stat().unwrap().size, 1000);
+ assert_eq!(path.metadata().unwrap().len(), 1000);
}
use std::sync::mpsc::channel;
use std::old_io::net::tcp::{TcpListener, TcpStream};
-use std::old_io::{Acceptor, Listener};
+use std::old_io::{Acceptor, Listener, Reader, Writer};
use std::thread::{Builder, Thread};
use std::time::Duration;
// they're in a different location than before. Hence, these tests are all run
// serially here.
+use std::old_path::{Path, GenericPath};
use std::old_io::fs::PathExtensions;
use std::old_io::{fs, TempDir};
use std::old_io;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
#![feature(box_syntax)]
-use std::old_io;
+use std::io::{self, Write};
trait Trait {
fn f(&self);
}
}
-fn foo(mut a: Box<Writer>) {
- a.write(b"Hello\n");
-}
+fn foo(mut a: Box<Write>) {}
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let c: &Trait = &a;
c.f();
- let out = old_io::stdout();
+ let out = io::stdout();
foo(Box::new(out));
}
let _t = (0..n).map(|i| {
expected += i;
let tx = tx.clone();
- thread::spawn(move|| {
+ thread::scoped(move|| {
child(&tx, i)
})
}).collect::<Vec<_>>();
let _b = Foo;
}).join();
- let s = x.err().unwrap().downcast::<&'static str>().ok().unwrap();
+ let s = x.err().unwrap().downcast::<&'static str>().unwrap();
assert_eq!(&**s, "This panic should happen.");
}