This handles the ranges contained in UnicodeData.txt.
Counterintuitively this actually makes the tables shorter.
tmp/install-debugger-scripts$(1)_H_$(2)-gdb.done: \
$$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_GDB_ABS) \
$$(DEBUGGER_BIN_SCRIPTS_GDB_ABS)
+ $(Q)touch $$@.start_time
$(Q)mkdir -p $$(HBIN$(1)_H_$(2))
$(Q)mkdir -p $$(HLIB$(1)_H_$(2))/rustlib/etc
$(Q)install $$(DEBUGGER_BIN_SCRIPTS_GDB_ABS) $$(HBIN$(1)_H_$(2))
$(Q)install $$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_GDB_ABS) $$(HLIB$(1)_H_$(2))/rustlib/etc
- $(Q)touch $$@
+ $(Q)touch -r $$@.start_time $$@ && rm $$@.start_time
tmp/install-debugger-scripts$(1)_H_$(2)-lldb.done: \
$$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_LLDB_ABS) \
$$(DEBUGGER_BIN_SCRIPTS_LLDB_ABS)
+ $(Q)touch $$@.start_time
$(Q)mkdir -p $$(HBIN$(1)_H_$(2))
$(Q)mkdir -p $$(HLIB$(1)_H_$(2))/rustlib/etc
$(Q)install $$(DEBUGGER_BIN_SCRIPTS_LLDB_ABS) $$(HBIN$(1)_H_$(2))
$(Q)install $$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_LLDB_ABS) $$(HLIB$(1)_H_$(2))/rustlib/etc
- $(Q)touch $$@
+ $(Q)touch -r $$@.start_time $$@ && rm $$@.start_time
tmp/install-debugger-scripts$(1)_H_$(2)-all.done: \
$$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_ALL_ABS) \
$$(DEBUGGER_BIN_SCRIPTS_ALL_ABS)
+ $(Q)touch $$@.start_time
$(Q)mkdir -p $$(HBIN$(1)_H_$(2))
$(Q)mkdir -p $$(HLIB$(1)_H_$(2))/rustlib/etc
$(Q)install $$(DEBUGGER_BIN_SCRIPTS_ALL_ABS) $$(HBIN$(1)_H_$(2))
$(Q)install $$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_ALL_ABS) $$(HLIB$(1)_H_$(2))/rustlib/etc
- $(Q)touch $$@
+ $(Q)touch -r $$@.start_time $$@ && rm $$@.start_time
tmp/install-debugger-scripts$(1)_H_$(2)-none.done:
$(Q)touch $$@
tmp/install-debugger-scripts$(1)_T_$(2)_H_$(3)-gdb.done: \
$$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_GDB_ABS) \
$$(DEBUGGER_BIN_SCRIPTS_GDB_ABS)
+ $(Q)touch $$@.start_time
$(Q)mkdir -p $$(TBIN$(1)_T_$(2)_H_$(3))
$(Q)mkdir -p $$(TLIB$(1)_T_$(2)_H_$(3))/rustlib/etc
$(Q)install $(DEBUGGER_BIN_SCRIPTS_GDB_ABS) $$(TBIN$(1)_T_$(2)_H_$(3))
$(Q)install $(DEBUGGER_RUSTLIB_ETC_SCRIPTS_GDB_ABS) $$(TLIB$(1)_T_$(2)_H_$(3))/rustlib/etc
- $(Q)touch $$@
+ $(Q)touch -r $$@.start_time $$@ && rm $$@.start_time
tmp/install-debugger-scripts$(1)_T_$(2)_H_$(3)-lldb.done: \
$$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_LLDB_ABS) \
$$(DEBUGGER_BIN_SCRIPTS_LLDB_ABS)
+ $(Q)touch $$@.start_time
$(Q)mkdir -p $$(TBIN$(1)_T_$(2)_H_$(3))
$(Q)mkdir -p $$(TLIB$(1)_T_$(2)_H_$(3))/rustlib/etc
$(Q)install $(DEBUGGER_BIN_SCRIPTS_LLDB_ABS) $$(TBIN$(1)_T_$(2)_H_$(3))
$(Q)install $(DEBUGGER_RUSTLIB_ETC_SCRIPTS_LLDB_ABS) $$(TLIB$(1)_T_$(2)_H_$(3))/rustlib/etc
- $(Q)touch $$@
+ $(Q)touch -r $$@.start_time $$@ && rm $$@.start_time
tmp/install-debugger-scripts$(1)_T_$(2)_H_$(3)-all.done: \
$$(DEBUGGER_RUSTLIB_ETC_SCRIPTS_ALL_ABS) \
$$(DEBUGGER_BIN_SCRIPTS_ALL_ABS)
+ $(Q)touch $$@.start_time
$(Q)mkdir -p $$(TBIN$(1)_T_$(2)_H_$(3))
$(Q)mkdir -p $$(TLIB$(1)_T_$(2)_H_$(3))/rustlib/etc
$(Q)install $(DEBUGGER_BIN_SCRIPTS_ALL_ABS) $$(TBIN$(1)_T_$(2)_H_$(3))
$(Q)install $(DEBUGGER_RUSTLIB_ETC_SCRIPTS_ALL_ABS) $$(TLIB$(1)_T_$(2)_H_$(3))/rustlib/etc
- $(Q)touch $$@
+ $(Q)touch -r $$@.start_time $$@ && rm $$@.start_time
tmp/install-debugger-scripts$(1)_T_$(2)_H_$(3)-none.done:
$(Q)touch $$@
trpl: doc/book/index.html
doc/book/index.html: $(RUSTBOOK_EXE) $(wildcard $(S)/src/doc/trpl/*.md) | doc/
+ @$(call E, rustbook: $@)
$(Q)rm -rf doc/book
$(Q)$(RUSTBOOK) build $(S)src/doc/trpl doc/book
style: doc/style/index.html
doc/style/index.html: $(RUSTBOOK_EXE) $(wildcard $(S)/src/doc/style/*.md) | doc/
+ @$(call E, rustbook: $@)
$(Q)rm -rf doc/style
$(Q)$(RUSTBOOK) build $(S)src/doc/style doc/style
# the stamp in the source dir.
$$(LLVM_STAMP_$(1)): $(S)src/rustllvm/llvm-auto-clean-trigger
@$$(call E, make: cleaning llvm)
+ $(Q)touch $$@.start_time
$(Q)$(MAKE) clean-llvm$(1)
@$$(call E, make: done cleaning llvm)
- touch $$@
+ touch -r $$@.start_time $$@ && rm $$@.start_time
ifeq ($$(CFG_ENABLE_LLVM_STATIC_STDCPP),1)
LLVM_STDCPP_LOCATION_$(1) = $$(shell $$(CC_$(1)) $$(CFG_GCCISH_CFLAGS_$(1)) \
$$(TSREQ$(1)_T_$(2)_H_$(3)) \
| $$(TLIB$(1)_T_$(2)_H_$(3))/
@$$(call E, rustc: $$(@D)/lib$(4))
+ @touch $$@.start_time
$$(call REMOVE_ALL_OLD_GLOB_MATCHES, \
$$(dir $$@)$$(call CFG_LIB_GLOB_$(2),$(4)))
$$(call REMOVE_ALL_OLD_GLOB_MATCHES, \
--out-dir $$(@D) \
-C extra-filename=-$$(CFG_FILENAME_EXTRA) \
$$<
- @touch $$@
+ @touch -r $$@.start_time $$@ && rm $$@.start_time
$$(call LIST_ALL_OLD_GLOB_MATCHES, \
$$(dir $$@)$$(call CFG_LIB_GLOB_$(2),$(4)))
$$(call LIST_ALL_OLD_GLOB_MATCHES, \
$$(call TEST_OK_FILE,$(1),$(2),$(3),$(4)): \
$(3)/stage$(1)/test/$(4)test-$(2)$$(X_$(2))
@$$(call E, run: $$<)
+ $$(Q)touch $$@.start_time
$$(Q)$$(call CFG_RUN_TEST_$(2),$$<,$(1),$(2),$(3)) $$(TESTARGS) \
--logfile $$(call TEST_LOG_FILE,$(1),$(2),$(3),$(4)) \
$$(call CRATE_TEST_EXTRA_ARGS,$(1),$(2),$(3),$(4)) \
- && touch $$@
+ && touch -r $$@.start_time $$@ && rm $$@.start_time
endef
define DEF_TEST_CRATE_RULES_android
$$(call TEST_OK_FILE,$(1),$(2),$(3),$(4)): \
$(3)/stage$(1)/test/$(4)test-$(2)$$(X_$(2))
@$$(call E, run: $$< via adb)
+ $$(Q)touch $$@.start_time
$$(Q)$(CFG_ADB) push $$< $(CFG_ADB_TEST_DIR)
$$(Q)$(CFG_ADB) shell '(cd $(CFG_ADB_TEST_DIR); LD_LIBRARY_PATH=./$(2) \
./$$(notdir $$<) \
@if grep -q "result: ok" tmp/check-stage$(1)-T-$(2)-H-$(3)-$(4).tmp; \
then \
rm tmp/check-stage$(1)-T-$(2)-H-$(3)-$(4).tmp; \
- touch $$@; \
+ touch -r $$@.start_time $$@ && rm $$@.start_time; \
else \
rm tmp/check-stage$(1)-T-$(2)-H-$(3)-$(4).tmp; \
exit 101; \
$$(TEST_SREQ$(1)_T_$(2)_H_$(3)) \
$$(CTEST_DEPS_$(4)_$(1)-T-$(2)-H-$(3))
@$$(call E, run $(4) [$(2)]: $$<)
+ $$(Q)touch $$@.start_time
$$(Q)$$(call CFG_RUN_CTEST_$(2),$(1),$$<,$(3)) \
$$(CTEST_ARGS$(1)-T-$(2)-H-$(3)-$(4)) \
--logfile $$(call TEST_LOG_FILE,$(1),$(2),$(3),$(4)) \
- && touch $$@
+ && touch -r $$@.start_time $$@ && rm $$@.start_time
else
$$(PRETTY_DEPS_$(4)) \
$$(PRETTY_DEPS$(1)_H_$(3)_$(4))
@$$(call E, run pretty-rpass [$(2)]: $$<)
+ $$(Q)touch $$@.start_time
$$(Q)$$(call CFG_RUN_CTEST_$(2),$(1),$$<,$(3)) \
$$(PRETTY_ARGS$(1)-T-$(2)-H-$(3)-$(4)) \
--logfile $$(call TEST_LOG_FILE,$(1),$(2),$(3),$(4)) \
- && touch $$@
+ && touch -r $$@.start_time $$@ && rm $$@.start_time
endef
ifeq ($(2),$$(CFG_BUILD))
$$(call TEST_OK_FILE,$(1),$(2),$(3),doc-$(4)): $$(DOCTESTDEP_$(1)_$(2)_$(3)_$(4))
@$$(call E, run doc-$(4) [$(2)])
+ $$(Q)touch $$@.start_time
$$(Q)$$(RUSTDOC_$(1)_T_$(2)_H_$(3)) --cfg dox --test $$< \
- --test-args "$$(TESTARGS)" && touch $$@
+ --test-args "$$(TESTARGS)" && \
+ touch -r $$@.start_time $$@ && rm $$@.start_time
else
$$(call TEST_OK_FILE,$(1),$(2),$(3),doc-$(4)):
touch $$@
ifeq ($(2),$$(CFG_BUILD))
$$(call TEST_OK_FILE,$(1),$(2),$(3),doc-crate-$(4)): $$(CRATEDOCTESTDEP_$(1)_$(2)_$(3)_$(4))
@$$(call E, run doc-crate-$(4) [$(2)])
+ $$(Q)touch $$@.start_time
$$(Q)CFG_LLVM_LINKAGE_FILE=$$(LLVM_LINKAGE_PATH_$(3)) \
$$(RUSTDOC_$(1)_T_$(2)_H_$(3)) --test --cfg dox \
- $$(CRATEFILE_$(4)) --test-args "$$(TESTARGS)" && touch $$@
+ $$(CRATEFILE_$(4)) --test-args "$$(TESTARGS)" && \
+ touch -r $$@.start_time $$@ && rm $$@.start_time
else
$$(call TEST_OK_FILE,$(1),$(2),$(3),doc-crate-$(4)):
touch $$@
$$(CSREQ$(1)_T_$(2)_H_$(3))
@rm -rf $(3)/test/run-make/$$*
@mkdir -p $(3)/test/run-make/$$*
+ $$(Q)touch $$@.start_time
$$(Q)$$(CFG_PYTHON) $(S)src/etc/maketest.py $$(dir $$<) \
$$(MAKE) \
$$(HBIN$(1)_H_$(3))/rustc$$(X_$(3)) \
"$$(LD_LIBRARY_PATH_ENV_TARGETDIR$(1)_T_$(2)_H_$(3))" \
$(1) \
$$(S)
- @touch $$@
+ @touch -r $$@.start_time $$@ && rm $$@.start_time
else
# FIXME #11094 - The above rule doesn't work right for multiple targets
check-stage$(1)-T-$(2)-H-$(3)-rmake-exec:
use std::fmt;
use std::str::FromStr;
+use std::path::PathBuf;
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Mode {
pub run_lib_path: String,
// The rustc executable
- pub rustc_path: Path,
+ pub rustc_path: PathBuf,
// The clang executable
- pub clang_path: Option<Path>,
+ pub clang_path: Option<PathBuf>,
// The llvm binaries path
- pub llvm_bin_path: Option<Path>,
+ pub llvm_bin_path: Option<PathBuf>,
// The valgrind path
pub valgrind_path: Option<String>,
pub force_valgrind: bool,
// The directory containing the tests to run
- pub src_base: Path,
+ pub src_base: PathBuf,
// The directory where programs should be built
- pub build_base: Path,
+ pub build_base: PathBuf,
// Directory for auxiliary libraries
- pub aux_base: Path,
+ pub aux_base: PathBuf,
// The name of the stage being built (stage1, etc)
pub stage_id: String,
pub filter: Option<String>,
// Write out a parseable log of tests that were run
- pub logfile: Option<Path>,
+ pub logfile: Option<PathBuf>,
// A command line to prefix program execution with,
// for running under valgrind
pub lldb_version: Option<String>,
// Path to the android tools
- pub android_cross_path: Path,
+ pub android_cross_path: PathBuf,
// Extra parameter to run adb on arm-linux-androideabi
pub adb_path: String,
#![feature(test)]
#![feature(unicode)]
#![feature(core)]
+#![feature(path)]
+#![feature(os)]
+#![feature(io)]
+#![feature(fs)]
+#![feature(net)]
#![deny(warnings)]
extern crate log;
use std::env;
+use std::fs;
use std::old_io;
-use std::old_io::fs;
+use std::path::{Path, PathBuf};
use std::thunk::Thunk;
use getopts::{optopt, optflag, reqopt};
use common::Config;
panic!()
}
- fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
+ fn opt_path(m: &getopts::Matches, nm: &str) -> PathBuf {
match m.opt_str(nm) {
- Some(s) => Path::new(s),
+ Some(s) => PathBuf::new(&s),
None => panic!("no option (=path) found for {}", nm),
}
}
compile_lib_path: matches.opt_str("compile-lib-path").unwrap(),
run_lib_path: matches.opt_str("run-lib-path").unwrap(),
rustc_path: opt_path(matches, "rustc-path"),
- clang_path: matches.opt_str("clang-path").map(|s| Path::new(s)),
+ clang_path: matches.opt_str("clang-path").map(|s| PathBuf::new(&s)),
valgrind_path: matches.opt_str("valgrind-path"),
force_valgrind: matches.opt_present("force-valgrind"),
- llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| Path::new(s)),
+ llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| PathBuf::new(&s)),
src_base: opt_path(matches, "src-base"),
build_base: opt_path(matches, "build-base"),
aux_base: opt_path(matches, "aux-base"),
mode: matches.opt_str("mode").unwrap().parse().ok().expect("invalid mode"),
run_ignored: matches.opt_present("ignored"),
filter: filter,
- logfile: matches.opt_str("logfile").map(|s| Path::new(s)),
+ logfile: matches.opt_str("logfile").map(|s| PathBuf::new(&s)),
runtool: matches.opt_str("runtool"),
host_rustcflags: matches.opt_str("host-rustcflags"),
target_rustcflags: matches.opt_str("target-rustcflags"),
debug!("making tests from {:?}",
config.src_base.display());
let mut tests = Vec::new();
- let dirs = fs::readdir(&config.src_base).unwrap();
- for file in &dirs {
- let file = file.clone();
+ let dirs = fs::read_dir(&config.src_base).unwrap();
+ for file in dirs {
+ let file = file.unwrap().path();
debug!("inspecting file {:?}", file.display());
if is_test(config, &file) {
let t = make_test(config, &file, || {
_ => vec!(".rc".to_string(), ".rs".to_string())
};
let invalid_prefixes = vec!(".".to_string(), "#".to_string(), "~".to_string());
- let name = testfile.filename_str().unwrap();
+ let name = testfile.file_name().unwrap().to_str().unwrap();
let mut valid = false;
// Try to elide redundant long paths
fn shorten(path: &Path) -> String {
- let filename = path.filename_str();
- let p = path.dir_path();
- let dir = p.filename_str();
+ let filename = path.file_name().unwrap().to_str();
+ let p = path.parent().unwrap();
+ let dir = p.file_name().unwrap().to_str();
format!("{}/{}", dir.unwrap_or(""), filename.unwrap_or(""))
}
pub fn make_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
let config = (*config).clone();
- // FIXME (#9639): This needs to handle non-utf8 paths
- let testfile = testfile.as_str().unwrap().to_string();
+ let testfile = testfile.to_path_buf();
test::DynTestFn(Thunk::new(move || {
- runtest::run(config, testfile)
+ runtest::run(config, &testfile)
}))
}
pub fn make_metrics_test_closure(config: &Config, testfile: &Path) -> test::TestFn {
let config = (*config).clone();
- // FIXME (#9639): This needs to handle non-utf8 paths
- let testfile = testfile.as_str().unwrap().to_string();
+ let testfile = testfile.to_path_buf();
test::DynMetricFn(box move |mm: &mut test::MetricMap| {
- runtest::run_metrics(config, testfile, mm)
+ runtest::run_metrics(config, &testfile, mm)
})
}
// except according to those terms.
use self::WhichLine::*;
-use std::old_io::{BufferedReader, File};
+use std::fs::File;
+use std::io::BufReader;
+use std::io::prelude::*;
+use std::path::Path;
pub struct ExpectedError {
pub line: uint,
/// //~| ERROR message two for that same line.
// Load any test directives embedded in the file
pub fn load_errors(testfile: &Path) -> Vec<ExpectedError> {
- let mut rdr = BufferedReader::new(File::open(testfile).unwrap());
+ let rdr = BufReader::new(File::open(testfile).unwrap());
// `last_nonfollow_error` tracks the most recently seen
// line with an error template that did not use the
// except according to those terms.
use std::env;
+use std::fs::File;
+use std::io::BufReader;
+use std::io::prelude::*;
+use std::path::{Path, PathBuf};
use common::Config;
use common;
pub run_flags: Option<String>,
// If present, the name of a file that this test should match when
// pretty-printed
- pub pp_exact: Option<Path>,
+ pub pp_exact: Option<PathBuf>,
// Modules from aux directory that should be compiled
pub aux_builds: Vec<String> ,
// Environment settings to use during execution
let mut pretty_mode = None;
let mut pretty_compare_only = false;
let mut forbid_output = Vec::new();
- iter_header(testfile, |ln| {
+ iter_header(testfile, &mut |ln| {
match parse_error_pattern(ln) {
Some(ep) => error_patterns.push(ep),
None => ()
}
}
- let val = iter_header(testfile, |ln| {
+ 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_stage(config)) &&
!val
}
-fn iter_header<F>(testfile: &Path, mut it: F) -> bool where
- F: FnMut(&str) -> bool,
-{
- use std::old_io::{BufferedReader, File};
-
- let mut rdr = BufferedReader::new(File::open(testfile).unwrap());
+fn iter_header(testfile: &Path, it: &mut FnMut(&str) -> bool) -> bool {
+ let rdr = BufReader::new(File::open(testfile).unwrap());
for ln in rdr.lines() {
// Assume that any directives will be found before the first
// module or function. This doesn't seem to be an optimization
})
}
-fn parse_pp_exact(line: &str, testfile: &Path) -> Option<Path> {
+fn parse_pp_exact(line: &str, testfile: &Path) -> Option<PathBuf> {
match parse_name_value_directive(line, "pp-exact") {
- Some(s) => Some(Path::new(s)),
+ Some(s) => Some(PathBuf::new(&s)),
None => {
if parse_name_directive(line, "pp-exact") {
- testfile.filename().map(|s| Path::new(s))
+ testfile.file_name().map(|s| PathBuf::new(s))
} else {
None
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::old_io::process::{ProcessExit, Command, Process, ProcessOutput};
+use std::process::{ExitStatus, Command, Child, Output, Stdio};
+use std::io::prelude::*;
use std::dynamic_lib::DynamicLibrary;
fn add_target_env(cmd: &mut Command, lib_path: &str, aux_path: Option<&str>) {
let var = DynamicLibrary::envvar();
let newpath = DynamicLibrary::create_path(&path);
let newpath = String::from_utf8(newpath).unwrap();
- cmd.env(var.to_string(), newpath);
+ cmd.env(var, &newpath);
}
-pub struct Result {pub status: ProcessExit, pub out: String, pub err: String}
+pub struct Result {pub status: ExitStatus, pub out: String, pub err: String}
pub fn run(lib_path: &str,
prog: &str,
input: Option<String>) -> Option<Result> {
let mut cmd = Command::new(prog);
- cmd.args(args);
+ cmd.args(args)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
add_target_env(&mut cmd, lib_path, aux_path);
for (key, val) in env {
- cmd.env(key, val);
+ cmd.env(&key, &val);
}
match cmd.spawn() {
if let Some(input) = input {
process.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap();
}
- let ProcessOutput { status, output, error } =
+ let Output { status, stdout, stderr } =
process.wait_with_output().unwrap();
Some(Result {
status: status,
- out: String::from_utf8(output).unwrap(),
- err: String::from_utf8(error).unwrap()
+ out: String::from_utf8(stdout).unwrap(),
+ err: String::from_utf8(stderr).unwrap()
})
},
Err(..) => None
aux_path: Option<&str>,
args: &[String],
env: Vec<(String, String)> ,
- input: Option<String>) -> Option<Process> {
+ input: Option<String>) -> Option<Child> {
let mut cmd = Command::new(prog);
- cmd.args(args);
+ cmd.args(args)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
add_target_env(&mut cmd, lib_path, aux_path);
for (key, val) in env {
- cmd.env(key, val);
+ cmd.env(&key, &val);
}
match cmd.spawn() {
use self::TargetLocation::*;
use common::Config;
-use common::{CompileFail, ParseFail, Pretty, RunFail, RunPass, RunPassValgrind, DebugInfoGdb};
-use common::{Codegen, DebugInfoLldb};
+use common::{CompileFail, ParseFail, Pretty, RunFail, RunPass, RunPassValgrind};
+use common::{Codegen, DebugInfoLldb, DebugInfoGdb};
use errors;
use header::TestProps;
use header;
use procsrv;
use util::logv;
-#[cfg(target_os = "windows")]
-use util;
-
-#[cfg(target_os = "windows")]
-use std::ascii::AsciiExt;
-use std::old_io::File;
-use std::old_io::fs::PathExtensions;
-use std::old_io::fs;
-use std::old_io::net::tcp;
-use std::old_io::process::ProcessExit;
-use std::old_io::process;
-use std::old_io::timer;
-use std::old_io;
+
use std::env;
+use std::ffi::OsStr;
+use std::fmt;
+use std::fs::{self, File};
+use std::io::BufReader;
+use std::io::prelude::*;
use std::iter::repeat;
+use std::net::TcpStream;
+use std::old_io::timer;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output, ExitStatus};
use std::str;
-use std::string::String;
-use std::thread;
use std::time::Duration;
use test::MetricMap;
-pub fn run(config: Config, testfile: String) {
+pub fn run(config: Config, testfile: &Path) {
match &*config.target {
"arm-linux-androideabi" | "aarch64-linux-android" => {
run_metrics(config, testfile, &mut _mm);
}
-pub fn run_metrics(config: Config, testfile: String, mm: &mut MetricMap) {
+pub fn run_metrics(config: Config, testfile: &Path, mm: &mut MetricMap) {
if config.verbose {
// We're going to be dumping a lot of info. Start on a new line.
print!("\n\n");
}
- let testfile = Path::new(testfile);
debug!("running {:?}", testfile.display());
let props = header::load_props(&testfile);
debug!("loaded props");
};
// The value our Makefile configures valgrind to return on failure
- const VALGRIND_ERR: int = 100;
- if proc_res.status.matches_exit_status(VALGRIND_ERR) {
+ const VALGRIND_ERR: i32 = 100;
+ if proc_res.status.code() == Some(VALGRIND_ERR) {
fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res);
}
fn check_correct_failure_status(proc_res: &ProcRes) {
// The value the rust runtime returns on failure
- const RUST_ERR: int = 101;
- if !proc_res.status.matches_exit_status(RUST_ERR) {
+ const RUST_ERR: i32 = 101;
+ if proc_res.status.code() != Some(RUST_ERR) {
fatal_proc_rec(
- &format!("failure produced the wrong error: {:?}",
+ &format!("failure produced the wrong error: {}",
proc_res.status),
proc_res);
}
let rounds =
match props.pp_exact { Some(_) => 1, None => 2 };
- let src = File::open(testfile).read_to_end().unwrap();
- let src = String::from_utf8(src.clone()).unwrap();
+ let mut src = String::new();
+ File::open(testfile).unwrap().read_to_string(&mut src).unwrap();
let mut srcs = vec!(src);
let mut round = 0;
let mut expected = match props.pp_exact {
Some(ref file) => {
- let filepath = testfile.dir_path().join(file);
- let s = File::open(&filepath).read_to_end().unwrap();
- String::from_utf8(s).unwrap()
+ let filepath = testfile.parent().unwrap().join(file);
+ let mut s = String::new();
+ File::open(&filepath).unwrap().read_to_string(&mut s).unwrap();
+ s
}
None => { srcs[srcs.len() - 2].clone() }
};
pretty_type.to_string()),
props.exec_env.clone(),
&config.compile_lib_path,
- Some(aux_dir.as_str().unwrap()),
+ Some(aux_dir.to_str().unwrap()),
Some(src))
}
pretty_type,
format!("--target={}", config.target),
"-L".to_string(),
- aux_dir.as_str().unwrap().to_string());
+ aux_dir.to_str().unwrap().to_string());
args.extend(split_maybe_args(&config.target_rustcflags).into_iter());
args.extend(split_maybe_args(&props.compile_flags).into_iter());
return ProcArgs {
- prog: config.rustc_path.as_str().unwrap().to_string(),
+ prog: config.rustc_path.to_str().unwrap().to_string(),
args: args,
};
}
"--crate-type=lib".to_string(),
format!("--target={}", target),
"-L".to_string(),
- config.build_base.as_str().unwrap().to_string(),
+ config.build_base.to_str().unwrap().to_string(),
"-L".to_string(),
- aux_dir.as_str().unwrap().to_string());
+ aux_dir.to_str().unwrap().to_string());
args.extend(split_maybe_args(&config.target_rustcflags).into_iter());
args.extend(split_maybe_args(&props.compile_flags).into_iter());
// FIXME (#9639): This needs to handle non-utf8 paths
return ProcArgs {
- prog: config.rustc_path.as_str().unwrap().to_string(),
+ prog: config.rustc_path.to_str().unwrap().to_string(),
args: args,
};
}
// write debugger script
let mut script_str = String::with_capacity(2048);
script_str.push_str("set charset UTF-8\n");
- script_str.push_str(&format!("file {}\n", exe_file.as_str().unwrap()));
+ script_str.push_str(&format!("file {}\n", exe_file.to_str().unwrap()));
script_str.push_str("target remote :5039\n");
script_str.push_str(&format!("set solib-search-path \
./{}/stage2/lib/rustlib/{}/lib/\n",
config.host, config.target));
for line in breakpoint_lines.iter() {
script_str.push_str(&format!("break {:?}:{}\n",
- testfile.filename_display(),
+ testfile.file_name().unwrap()
+ .to_string_lossy(),
*line)[..]);
}
script_str.push_str(&cmds);
- script_str.push_str("quit\n");
+ script_str.push_str("\nquit\n");
debug!("script_str = {}", script_str);
dump_output_file(config,
None,
&[
"push".to_string(),
- exe_file.as_str().unwrap().to_string(),
+ exe_file.to_str().unwrap().to_string(),
config.adb_test_dir.clone()
],
vec!(("".to_string(), "".to_string())),
if config.target.contains("aarch64")
{"64"} else {""},
config.adb_test_dir.clone(),
- str::from_utf8(
- exe_file.filename()
- .unwrap()).unwrap());
+ exe_file.file_name().unwrap().to_str()
+ .unwrap());
let mut process = procsrv::run_background("",
&config.adb_path
loop {
//waiting 1 second for gdbserver start
timer::sleep(Duration::milliseconds(1000));
- let result = thread::spawn(move || {
- tcp::TcpStream::connect("127.0.0.1:5039").unwrap();
- }).join();
- if result.is_err() {
- continue;
+ if TcpStream::connect("127.0.0.1:5039").is_ok() {
+ break
}
- break;
}
- let tool_path = match config.android_cross_path.as_str() {
+ let tool_path = match config.android_cross_path.to_str() {
Some(x) => x.to_string(),
None => fatal("cannot find android cross path")
};
vec!("-quiet".to_string(),
"-batch".to_string(),
"-nx".to_string(),
- format!("-command={}", debugger_script.as_str().unwrap()));
+ format!("-command={}", debugger_script.to_str().unwrap()));
let mut gdb_path = tool_path;
gdb_path.push_str(&format!("/bin/{}-gdb", config.target));
};
debugger_run_result = ProcRes {
- status: status,
+ status: Status::Normal(status),
stdout: out,
stderr: err,
cmdline: cmdline
};
- if process.signal_kill().is_err() {
+ if process.kill().is_err() {
println!("Adb process is already finished.");
}
}
.expect("Could not find Rust source root");
let rust_pp_module_rel_path = Path::new("./src/etc");
let rust_pp_module_abs_path = rust_src_root.join(rust_pp_module_rel_path)
- .as_str()
+ .to_str()
.unwrap()
.to_string();
// write debugger script
// GDB's script auto loading safe path
script_str.push_str(
&format!("add-auto-load-safe-path {}\n",
- rust_pp_module_abs_path.replace("\\", "\\\\"))
+ rust_pp_module_abs_path.replace(r"\", r"\\"))
);
}
}
script_str.push_str("set print pretty off\n");
// Add the pretty printer directory to GDB's source-file search path
- script_str.push_str(&format!("directory {}\n", rust_pp_module_abs_path)[..]);
+ script_str.push_str(&format!("directory {}\n",
+ rust_pp_module_abs_path));
// Load the target executable
script_str.push_str(&format!("file {}\n",
- exe_file.as_str().unwrap().replace("\\", "\\\\"))[..]);
+ exe_file.to_str().unwrap()
+ .replace(r"\", r"\\")));
// Add line breakpoints
for line in &breakpoint_lines {
script_str.push_str(&format!("break '{}':{}\n",
- testfile.filename_display(),
- *line)[..]);
+ testfile.file_name().unwrap()
+ .to_string_lossy(),
+ *line));
}
script_str.push_str(&cmds);
- script_str.push_str("quit\n");
+ script_str.push_str("\nquit\n");
debug!("script_str = {}", script_str);
dump_output_file(config,
"debugger.script");
// run debugger script with gdb
- #[cfg(windows)]
- fn debugger() -> String {
- "gdb.exe".to_string()
- }
- #[cfg(unix)]
- fn debugger() -> String {
- "gdb".to_string()
+ fn debugger() -> &'static str {
+ if cfg!(windows) {"gdb.exe"} else {"gdb"}
}
let debugger_script = make_out_name(config, testfile, "debugger.script");
vec!("-quiet".to_string(),
"-batch".to_string(),
"-nx".to_string(),
- format!("-command={}", debugger_script.as_str().unwrap()));
+ format!("-command={}", debugger_script.to_str().unwrap()));
let proc_args = ProcArgs {
- prog: debugger(),
+ prog: debugger().to_string(),
args: debugger_opts,
};
check_debugger_output(&debugger_run_result, &check_lines);
}
-fn find_rust_src_root(config: &Config) -> Option<Path> {
+fn find_rust_src_root(config: &Config) -> Option<PathBuf> {
let mut path = config.src_base.clone();
let path_postfix = Path::new("src/etc/lldb_batchmode.py");
}
fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path) {
- use std::old_io::process::{Command, ProcessOutput};
-
if config.lldb_python_dir.is_none() {
fatal("Can't run LLDB test because LLDB's python path is not set.");
}
.expect("Could not find Rust source root");
let rust_pp_module_rel_path = Path::new("./src/etc/lldb_rust_formatters.py");
let rust_pp_module_abs_path = rust_src_root.join(rust_pp_module_rel_path)
- .as_str()
+ .to_str()
.unwrap()
.to_string();
- script_str.push_str(&format!("command script import {}\n", &rust_pp_module_abs_path[..])[..]);
+ script_str.push_str(&format!("command script import {}\n",
+ &rust_pp_module_abs_path[..])[..]);
script_str.push_str("type summary add --no-value ");
script_str.push_str("--python-function lldb_rust_formatters.print_val ");
script_str.push_str("-x \".*\" --category Rust\n");
}
// Finally, quit the debugger
- script_str.push_str("quit\n");
+ script_str.push_str("\nquit\n");
// Write the script into a file
debug!("script_str = {}", script_str);
rust_src_root: &Path)
-> ProcRes {
// Prepare the lldb_batchmode which executes the debugger script
- let lldb_script_path = rust_src_root.join(Path::new("./src/etc/lldb_batchmode.py"));
+ let lldb_script_path = rust_src_root.join("src/etc/lldb_batchmode.py");
let mut cmd = Command::new("python");
- cmd.arg(lldb_script_path)
+ cmd.arg(&lldb_script_path)
.arg(test_executable)
.arg(debugger_script)
- .env_set_all(&[("PYTHONPATH", config.lldb_python_dir.clone().unwrap())]);
-
- let (status, out, err) = match cmd.spawn() {
- Ok(process) => {
- let ProcessOutput { status, output, error } =
- process.wait_with_output().unwrap();
+ .env("PYTHONPATH", config.lldb_python_dir.as_ref().unwrap());
+ let (status, out, err) = match cmd.output() {
+ Ok(Output { status, stdout, stderr }) => {
(status,
- String::from_utf8(output).unwrap(),
- String::from_utf8(error).unwrap())
+ String::from_utf8(stdout).unwrap(),
+ String::from_utf8(stderr).unwrap())
},
Err(e) => {
fatal(&format!("Failed to setup Python process for \
dump_output(config, test_executable, &out, &err);
return ProcRes {
- status: status,
+ status: Status::Normal(status),
stdout: out,
stderr: err,
cmdline: format!("{:?}", cmd)
fn parse_debugger_commands(file_path: &Path, debugger_prefix: &str)
-> DebuggerCommands {
- use std::old_io::{BufferedReader, File};
-
let command_directive = format!("{}-command", debugger_prefix);
let check_directive = format!("{}-check", debugger_prefix);
let mut commands = vec!();
let mut check_lines = vec!();
let mut counter = 1;
- let mut reader = BufferedReader::new(File::open(file_path).unwrap());
+ let reader = BufReader::new(File::open(file_path).unwrap());
for line in reader.lines() {
match line {
Ok(line) => {
let prefixes = expected_errors.iter().map(|ee| {
format!("{}:{}:", testfile.display(), ee.line)
- }).collect::<Vec<String> >();
-
- #[cfg(windows)]
- fn prefix_matches( line : &str, prefix : &str ) -> bool {
- line.to_ascii_lowercase().starts_with(&prefix.to_ascii_lowercase())
- }
-
- #[cfg(unix)]
- fn prefix_matches( line : &str, prefix : &str ) -> bool {
- line.starts_with( prefix )
+ }).collect::<Vec<String>>();
+
+ fn prefix_matches(line: &str, prefix: &str) -> bool {
+ use std::ascii::AsciiExt;
+ // On windows just translate all '\' path separators to '/'
+ let line = line.replace(r"\", "/");
+ if cfg!(windows) {
+ line.to_ascii_lowercase().starts_with(&prefix.to_ascii_lowercase())
+ } else {
+ line.starts_with(prefix)
+ }
}
// A multi-line error will have followup lines which will always
}
struct ProcRes {
- status: ProcessExit,
+ status: Status,
stdout: String,
stderr: String,
cmdline: String,
}
+enum Status {
+ Parsed(i32),
+ Normal(ExitStatus),
+}
+
+impl Status {
+ fn code(&self) -> Option<i32> {
+ match *self {
+ Status::Parsed(i) => Some(i),
+ Status::Normal(ref e) => e.code(),
+ }
+ }
+
+ fn success(&self) -> bool {
+ match *self {
+ Status::Parsed(i) => i == 0,
+ Status::Normal(ref e) => e.success(),
+ }
+ }
+}
+
+impl fmt::Display for Status {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match *self {
+ Status::Parsed(i) => write!(f, "exit code: {}", i),
+ Status::Normal(ref e) => e.fmt(f),
+ }
+ }
+}
+
fn compile_test(config: &Config, props: &TestProps,
testfile: &Path) -> ProcRes {
compile_test_(config, props, testfile, &[])
let aux_dir = aux_output_dir_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
let mut link_args = vec!("-L".to_string(),
- aux_dir.as_str().unwrap().to_string());
+ aux_dir.to_str().unwrap().to_string());
link_args.extend(extra_args.iter().cloned());
let args = make_compile_args(config,
props,
make_run_args(config, props, testfile),
env,
&config.run_lib_path,
- Some(aux_dir.as_str().unwrap()),
+ Some(aux_dir.to_str().unwrap()),
None)
}
}
let aux_dir = aux_output_dir_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
- let extra_link_args = vec!("-L".to_string(), aux_dir.as_str().unwrap().to_string());
+ let extra_link_args = vec!("-L".to_string(), aux_dir.to_str().unwrap().to_string());
for rel_ab in &props.aux_builds {
let abs_ab = config.aux_base.join(rel_ab);
crate_type,
|a,b| {
let f = make_lib_name(a, b, testfile);
- TargetLocation::ThisDirectory(f.dir_path())
+ let parent = f.parent().unwrap();
+ TargetLocation::ThisDirectory(parent.to_path_buf())
},
&abs_ab);
let auxres = compose_and_run(config,
aux_args,
Vec::new(),
&config.compile_lib_path,
- Some(aux_dir.as_str().unwrap()),
+ Some(aux_dir.to_str().unwrap()),
None);
if !auxres.status.success() {
fatal_proc_rec(
args,
Vec::new(),
&config.compile_lib_path,
- Some(aux_dir.as_str().unwrap()),
+ Some(aux_dir.to_str().unwrap()),
input)
}
fn ensure_dir(path: &Path) {
if path.is_dir() { return; }
- fs::mkdir(path, old_io::USER_RWX).unwrap();
+ fs::create_dir(path).unwrap();
}
fn compose_and_run(config: &Config, testfile: &Path,
}
enum TargetLocation {
- ThisFile(Path),
- ThisDirectory(Path),
+ ThisFile(PathBuf),
+ ThisDirectory(PathBuf),
}
fn make_compile_args<F>(config: &Config,
&*config.target
};
// FIXME (#9639): This needs to handle non-utf8 paths
- let mut args = vec!(testfile.as_str().unwrap().to_string(),
+ let mut args = vec!(testfile.to_str().unwrap().to_string(),
"-L".to_string(),
- config.build_base.as_str().unwrap().to_string(),
+ config.build_base.to_str().unwrap().to_string(),
format!("--target={}", target));
args.push_all(&extras);
if !props.no_prefer_dynamic {
path
}
};
- args.push(path.as_str().unwrap().to_string());
+ args.push(path.to_str().unwrap().to_string());
if props.force_host {
args.extend(split_maybe_args(&config.host_rustcflags).into_iter());
} else {
}
args.extend(split_maybe_args(&props.compile_flags).into_iter());
return ProcArgs {
- prog: config.rustc_path.as_str().unwrap().to_string(),
+ prog: config.rustc_path.to_str().unwrap().to_string(),
args: args,
};
}
-fn make_lib_name(config: &Config, auxfile: &Path, testfile: &Path) -> Path {
+fn make_lib_name(config: &Config, auxfile: &Path, testfile: &Path) -> PathBuf {
// what we return here is not particularly important, as it
// happens; rustc ignores everything except for the directory.
let auxname = output_testname(auxfile);
aux_output_dir_name(config, testfile).join(&auxname)
}
-fn make_exe_name(config: &Config, testfile: &Path) -> Path {
+fn make_exe_name(config: &Config, testfile: &Path) -> PathBuf {
let mut f = output_base_name(config, testfile);
if !env::consts::EXE_SUFFIX.is_empty() {
- let mut fname = f.filename().unwrap().to_vec();
- fname.extend(env::consts::EXE_SUFFIX.bytes());
- f.set_filename(fname);
+ let mut fname = f.file_name().unwrap().to_os_string();
+ fname.push_os_str(OsStr::from_str(env::consts::EXE_SUFFIX));
+ f.set_file_name(&fname);
}
f
}
let exe_file = make_exe_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
- args.push(exe_file.as_str().unwrap().to_string());
+ args.push(exe_file.to_str().unwrap().to_string());
// Add the arguments in the run_flags directive
args.extend(split_maybe_args(&props.run_flags).into_iter());
input).expect(&format!("failed to exec `{}`", prog));
dump_output(config, testfile, &out, &err);
return ProcRes {
- status: status,
+ status: Status::Normal(status),
stdout: out,
stderr: err,
cmdline: cmdline,
};
}
-// Linux and mac don't require adjusting the library search path
-#[cfg(unix)]
-fn make_cmdline(_libpath: &str, prog: &str, args: &[String]) -> String {
- format!("{} {}", prog, args.connect(" "))
-}
-
-#[cfg(windows)]
fn make_cmdline(libpath: &str, prog: &str, args: &[String]) -> String {
+ use util;
- // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
- // for diagnostic purposes
- fn lib_path_cmd_prefix(path: &str) -> String {
- format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
- }
+ // Linux and mac don't require adjusting the library search path
+ if cfg!(unix) {
+ format!("{} {}", prog, args.connect(" "))
+ } else {
+ // Build the LD_LIBRARY_PATH variable as it would be seen on the command line
+ // for diagnostic purposes
+ fn lib_path_cmd_prefix(path: &str) -> String {
+ format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
+ }
- format!("{} {} {}", lib_path_cmd_prefix(libpath), prog, args.connect(" "))
+ format!("{} {} {}", lib_path_cmd_prefix(libpath), prog, args.connect(" "))
+ }
}
fn dump_output(config: &Config, testfile: &Path, out: &str, err: &str) {
fn dump_output_file(config: &Config, testfile: &Path,
out: &str, extension: &str) {
let outfile = make_out_name(config, testfile, extension);
- File::create(&outfile).write_all(out.as_bytes()).unwrap();
+ File::create(&outfile).unwrap().write_all(out.as_bytes()).unwrap();
}
-fn make_out_name(config: &Config, testfile: &Path, extension: &str) -> Path {
+fn make_out_name(config: &Config, testfile: &Path, extension: &str) -> PathBuf {
output_base_name(config, testfile).with_extension(extension)
}
-fn aux_output_dir_name(config: &Config, testfile: &Path) -> Path {
+fn aux_output_dir_name(config: &Config, testfile: &Path) -> PathBuf {
let f = output_base_name(config, testfile);
- let mut fname = f.filename().unwrap().to_vec();
- fname.extend("libaux".bytes());
- f.with_filename(fname)
+ let mut fname = f.file_name().unwrap().to_os_string();
+ fname.push_os_str(OsStr::from_str("libaux"));
+ f.with_file_name(&fname)
}
-fn output_testname(testfile: &Path) -> Path {
- Path::new(testfile.filestem().unwrap())
+fn output_testname(testfile: &Path) -> PathBuf {
+ PathBuf::new(testfile.file_stem().unwrap())
}
-fn output_base_name(config: &Config, testfile: &Path) -> Path {
+fn output_base_name(config: &Config, testfile: &Path) -> PathBuf {
config.build_base
.join(&output_testname(testfile))
.with_extension(&config.stage_id)
Some("".to_string()))
.expect(&format!("failed to exec `{}`", config.adb_path));
- let mut exitcode: int = 0;
+ let mut exitcode: i32 = 0;
for c in exitcode_out.chars() {
if !c.is_numeric() { break; }
exitcode = exitcode * 10 + match c {
- '0' ... '9' => c as int - ('0' as int),
+ '0' ... '9' => c as i32 - ('0' as i32),
_ => 101,
}
}
&stderr_out);
ProcRes {
- status: process::ProcessExit::ExitStatus(exitcode),
+ status: Status::Parsed(exitcode),
stdout: stdout_out,
stderr: stderr_out,
cmdline: cmdline
fn _arm_push_aux_shared_library(config: &Config, testfile: &Path) {
let tdir = aux_output_dir_name(config, testfile);
- let dirs = fs::readdir(&tdir).unwrap();
- for file in &dirs {
- if file.extension_str() == Some("so") {
+ let dirs = fs::read_dir(&tdir).unwrap();
+ for file in dirs {
+ let file = file.unwrap().path();
+ if file.extension().and_then(|s| s.to_str()) == Some("so") {
// FIXME (#9639): This needs to handle non-utf8 paths
let copy_result = procsrv::run("",
&config.adb_path,
None,
&[
"push".to_string(),
- file.as_str()
+ file.to_str()
.unwrap()
.to_string(),
config.adb_test_dir.to_string(),
// codegen tests (vs. clang)
-fn append_suffix_to_stem(p: &Path, suffix: &str) -> Path {
+fn append_suffix_to_stem(p: &Path, suffix: &str) -> PathBuf {
if suffix.len() == 0 {
- (*p).clone()
+ p.to_path_buf()
} else {
- let mut stem = p.filestem().unwrap().to_vec();
- stem.extend("-".bytes());
- stem.extend(suffix.bytes());
- p.with_filename(stem)
+ let mut stem = p.file_stem().unwrap().to_os_string();
+ stem.push_os_str(OsStr::from_str("-"));
+ stem.push_os_str(OsStr::from_str(suffix));
+ p.with_file_name(&stem)
}
}
let aux_dir = aux_output_dir_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
let mut link_args = vec!("-L".to_string(),
- aux_dir.as_str().unwrap().to_string());
+ aux_dir.to_str().unwrap().to_string());
let llvm_args = vec!("--emit=llvm-bc,obj".to_string(),
"--crate-type=lib".to_string());
link_args.extend(llvm_args.into_iter());
props,
link_args,
|a, b| TargetLocation::ThisDirectory(
- output_base_name(a, b).dir_path()),
+ output_base_name(a, b).parent()
+ .unwrap().to_path_buf()),
testfile);
compose_and_run_compiler(config, props, testfile, args, None)
}
let testcc = testfile.with_extension("cc");
let proc_args = ProcArgs {
// FIXME (#9639): This needs to handle non-utf8 paths
- prog: config.clang_path.as_ref().unwrap().as_str().unwrap().to_string(),
+ prog: config.clang_path.as_ref().unwrap().to_str().unwrap().to_string(),
args: vec!("-c".to_string(),
"-emit-llvm".to_string(),
"-o".to_string(),
- bitcodefile.as_str().unwrap().to_string(),
- testcc.as_str().unwrap().to_string())
+ bitcodefile.to_str().unwrap().to_string(),
+ testcc.to_str().unwrap().to_string())
};
compose_and_run(config, testfile, proc_args, Vec::new(), "", None, None)
}
let prog = config.llvm_bin_path.as_ref().unwrap().join("llvm-extract");
let proc_args = ProcArgs {
// FIXME (#9639): This needs to handle non-utf8 paths
- prog: prog.as_str().unwrap().to_string(),
+ prog: prog.to_str().unwrap().to_string(),
args: vec!(format!("-func={}", fname),
- format!("-o={}", extracted_bc.as_str().unwrap()),
- bitcodefile.as_str().unwrap().to_string())
+ format!("-o={}", extracted_bc.to_str().unwrap()),
+ bitcodefile.to_str().unwrap().to_string())
};
compose_and_run(config, testfile, proc_args, Vec::new(), "", None, None)
}
let prog = config.llvm_bin_path.as_ref().unwrap().join("llvm-dis");
let proc_args = ProcArgs {
// FIXME (#9639): This needs to handle non-utf8 paths
- prog: prog.as_str().unwrap().to_string(),
- args: vec!(format!("-o={}", extracted_ll.as_str().unwrap()),
- extracted_bc.as_str().unwrap().to_string())
+ prog: prog.to_str().unwrap().to_string(),
+ args: vec!(format!("-o={}", extracted_ll.to_str().unwrap()),
+ extracted_bc.to_str().unwrap().to_string())
};
compose_and_run(config, testfile, proc_args, Vec::new(), "", None, None)
}
fn count_extracted_lines(p: &Path) -> uint {
- let x = File::open(&p.with_extension("ll")).read_to_end().unwrap();
+ let mut x = Vec::new();
+ File::open(&p.with_extension("ll")).unwrap().read_to_end(&mut x).unwrap();
let x = str::from_utf8(&x).unwrap();
x.lines().count()
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use common::Config;
-
-#[cfg(target_os = "windows")]
use std::env;
+use common::Config;
/// Conversion table from triple OS name to Rust SYSNAME
const OS_TABLE: &'static [(&'static str, &'static str)] = &[
panic!("Cannot determine OS from triple");
}
-#[cfg(target_os = "windows")]
pub fn make_new_path(path: &str) -> String {
-
+ assert!(cfg!(windows));
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
match env::var(lib_path_env_var()) {
- Ok(curr) => {
- format!("{}{}{}", path, path_div(), curr)
- }
- Err(..) => path.to_string()
+ Ok(curr) => {
+ format!("{}{}{}", path, path_div(), curr)
+ }
+ Err(..) => path.to_string()
}
}
-#[cfg(target_os = "windows")]
pub fn lib_path_env_var() -> &'static str { "PATH" }
-
-#[cfg(target_os = "windows")]
-pub fn path_div() -> &'static str { ";" }
+fn path_div() -> &'static str { ";" }
pub fn logv(config: &Config, s: String) {
debug!("{}", s);
* `quote_pat!`
* `quote_stmt!`
* `quote_tokens!`
+* `quote_matcher!`
* `quote_ty!`
+* `quote_attr!`
+
+Keep in mind that when `$name : ident` appears in the input to
+`quote_tokens!`, the result contains unquoted `name` followed by two tokens.
+However, input of the same form passed to `quote_matcher!` becomes a
+quasiquoted MBE-matcher of a nonterminal. No unquotation happens. Otherwise
+the result of `quote_matcher!` is identical to that of `quote_tokens!`.
Documentation is very limited at the moment.
one_hundred: 100,
});
- let y = box foo(x);
+ let y: Box<BigStruct> = box foo(x);
}
```
import subprocess
import re
import os
-from licenseck import *
+from licenseck import check_license
import snapshot
err = 0
tab_flag = "ignore-tidy-tab"
linelength_flag = "ignore-tidy-linelength"
-# Be careful to support Python 2.4, 2.6, and 3.x here!
-config_proc = subprocess.Popen(["git", "config", "core.autocrlf"],
- stdout=subprocess.PIPE)
-result = config_proc.communicate()[0]
-
-true = "true".encode('utf8')
-autocrlf = result.strip() == true if result is not None else False
+interesting_files = ['.rs', '.py', '.js', '.sh', '.c', '.h']
+uninteresting_files = ['miniz.c', 'jquery', 'rust_android_dummy']
def report_error_name_no(name, no, s):
if not check_license(name, contents):
report_error_name_no(name, 1, "incorrect license")
+
+def update_counts(current_name):
+ global file_counts
+ global count_other_linted_files
+
+ _, ext = os.path.splitext(current_name)
+
+ if ext in interesting_files:
+ file_counts[ext] += 1
+ else:
+ count_other_linted_files += 1
+
+
+def interesting_file(f):
+ if any(x in f for x in uninteresting_files):
+ return False
+
+ return any(os.path.splitext(f)[1] == ext for ext in interesting_files)
+
+
+# Be careful to support Python 2.4, 2.6, and 3.x here!
+config_proc = subprocess.Popen(["git", "config", "core.autocrlf"],
+ stdout=subprocess.PIPE)
+result = config_proc.communicate()[0]
+
+true = "true".encode('utf8')
+autocrlf = result.strip() == true if result is not None else False
+
current_name = ""
current_contents = ""
check_tab = True
src_dir = sys.argv[1]
-try:
- count_lines = 0
- count_non_blank_lines = 0
+count_lines = 0
+count_non_blank_lines = 0
+count_other_linted_files = 0
- interesting_files = ['.rs', '.py', '.js', '.sh', '.c', '.h']
+file_counts = {ext: 0 for ext in interesting_files}
- file_counts = {ext: 0 for ext in interesting_files}
- file_counts['other'] = 0
-
- def update_counts(current_name):
- global file_counts
- _, ext = os.path.splitext(current_name)
-
- if ext in file_counts:
- file_counts[ext] += 1
- else:
- file_counts['other'] += 1
-
- all_paths = set()
+all_paths = set()
+try:
for (dirpath, dirnames, filenames) in os.walk(src_dir):
-
# Skip some third-party directories
skippable_dirs = {
'src/jemalloc',
if any(d in dirpath for d in skippable_dirs):
continue
- def interesting_file(f):
- if "miniz.c" in f \
- or "jquery" in f \
- or "rust_android_dummy" in f:
- return False
-
- return any(os.path.splitext(f)[1] == ext for ext in interesting_files)
-
file_names = [os.path.join(dirpath, f) for f in filenames
if interesting_file(f)
and not f.endswith("_gen.rs")
report_err("UTF-8 decoding error " + str(e))
print
-for ext in file_counts:
- print "* linted " + str(file_counts[ext]) + " " + ext + " files"
-print "* total lines of code: " + str(count_lines)
-print "* total non-blank lines of code: " + str(count_non_blank_lines)
+for ext in sorted(file_counts, key=file_counts.get, reverse=True):
+ print "* linted {} {} files".format(file_counts[ext], ext)
+print "* linted {} other files".format(count_other_linted_files)
+print "* total lines of code: {}".format(count_lines)
+print "* total non-blank lines of code: {}".format(count_non_blank_lines)
print
sys.exit(err)
%precedence MOD_SEP
%precedence RARROW ':'
+// In where clauses, "for" should have greater precedence when used as
+// a higher ranked constraint than when used as the beginning of a
+// for_in_type (which is a ty)
+%precedence FORTYPE
+%precedence FOR
+
// Binops & unops, and their precedences
%precedence BOX
%precedence BOXPLACE
{
$$ = mk_node("ItemImplNeg", 7, $1, $3, $5, $7, $8, $10, $11);
}
+| maybe_unsafe IMPL generic_params trait_ref FOR DOTDOT '{' '}'
+{
+ $$ = mk_node("ItemImplDefault", 3, $1, $3, $4);
+}
+| maybe_unsafe IMPL generic_params '!' trait_ref FOR DOTDOT '{' '}'
+{
+ $$ = mk_node("ItemImplDefaultNeg", 3, $1, $3, $4);
+}
;
maybe_impl_items
;
where_predicate
-: lifetime ':' bounds { $$ = mk_node("WherePredicate", 2, $1, $3); }
-| ty ':' ty_param_bounds { $$ = mk_node("WherePredicate", 2, $1, $3); }
+: maybe_for_lifetimes lifetime ':' bounds { $$ = mk_node("WherePredicate", 3, $1, $2, $4); }
+| maybe_for_lifetimes ty ':' ty_param_bounds { $$ = mk_node("WherePredicate", 3, $1, $2, $4); }
;
+maybe_for_lifetimes
+: FOR '<' lifetimes '>' { $$ = mk_none(); }
+| %prec FORTYPE %empty { $$ = mk_none(); }
+
ty_params
: ty_param { $$ = mk_node("TyParams", 1, $1); }
| ty_params ',' ty_param { $$ = ext_node($1, 1, $3); }
}
| ty_qualified_path ',' ty_sums maybe_bindings
{
- $$ = mk_node("GenericValues", 3, mk_none(), ext_node(mk_node("TySums", 1, $1), 1, $3), $4); }
+ $$ = mk_node("GenericValues", 3, mk_none(), mk_node("TySums", 2, $1, $3), $4);
+}
;
ty_qualified_path
;
expr_qualified_path
-: '<' ty_sum AS trait_ref '>' MOD_SEP ident
+: '<' ty_sum maybe_as_trait_ref '>' MOD_SEP ident
{
- $$ = mk_node("ExprQualifiedPath", 3, $2, $4, $7);
+ $$ = mk_node("ExprQualifiedPath", 3, $2, $3, $6);
}
-| '<' ty_sum AS trait_ref '>' MOD_SEP ident generic_args
+| '<' ty_sum maybe_as_trait_ref '>' MOD_SEP ident generic_args
{
- $$ = mk_node("ExprQualifiedPath", 4, $2, $4, $7, $8);
+ $$ = mk_node("ExprQualifiedPath", 4, $2, $3, $6, $7);
}
-| SHL ty_sum AS trait_ref '>' MOD_SEP ident AS trait_ref '>' MOD_SEP ident
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident maybe_as_trait_ref '>' MOD_SEP ident
{
- $$ = mk_node("ExprQualifiedPath", 3, mk_node("ExprQualifiedPath", 3, $2, $4, $7), $9, $12);
+ $$ = mk_node("ExprQualifiedPath", 3, mk_node("ExprQualifiedPath", 3, $2, $3, $6), $7, $10);
}
-| SHL ty_sum AS trait_ref '>' MOD_SEP ident generic_args AS trait_ref '>' MOD_SEP ident
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident generic_args maybe_as_trait_ref '>' MOD_SEP ident
{
- $$ = mk_node("ExprQualifiedPath", 3, mk_node("ExprQualifiedPath", 4, $2, $4, $7, $8), $10, $13);
+ $$ = mk_node("ExprQualifiedPath", 3, mk_node("ExprQualifiedPath", 4, $2, $3, $6, $7), $8, $11);
}
-| SHL ty_sum AS trait_ref '>' MOD_SEP ident AS trait_ref '>' MOD_SEP ident generic_args
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident maybe_as_trait_ref '>' MOD_SEP ident generic_args
{
- $$ = mk_node("ExprQualifiedPath", 4, mk_node("ExprQualifiedPath", 3, $2, $4, $7), $9, $12, $13);
+ $$ = mk_node("ExprQualifiedPath", 4, mk_node("ExprQualifiedPath", 3, $2, $3, $6), $7, $10, $11);
}
-| SHL ty_sum AS trait_ref '>' MOD_SEP ident generic_args AS trait_ref '>' MOD_SEP ident generic_args
+| SHL ty_sum maybe_as_trait_ref '>' MOD_SEP ident generic_args maybe_as_trait_ref '>' MOD_SEP ident generic_args
{
- $$ = mk_node("ExprQualifiedPath", 4, mk_node("ExprQualifiedPath", 4, $2, $4, $7, $8), $10, $13, $14);
+ $$ = mk_node("ExprQualifiedPath", 4, mk_node("ExprQualifiedPath", 4, $2, $3, $6, $7), $8, $11, $12);
}
+maybe_as_trait_ref
+: AS trait_ref { $$ = $2; }
+| %empty { $$ = mk_none(); }
+;
lambda_expr
: %prec LAMBDA
//! }
//! ```
+use boxed::Box;
+
use core::prelude::*;
use core::atomic;
pub fn new(data: T) -> Arc<T> {
// Start the weak pointer count as 1 which is the weak pointer that's
// held by all the strong pointers (kinda), see std/rc.rs for more info
- let x = box ArcInner {
+ let x: Box<_> = box ArcInner {
strong: atomic::AtomicUsize::new(1),
weak: atomic::AtomicUsize::new(1),
data: data,
/// let x = Box::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
+ #[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[stable(feature = "rust1", since = "1.0.0")]
- fn default() -> Box<[T]> { box [] }
+ fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
extern crate test;
use self::test::Bencher;
use core::ptr::PtrExt;
+ use boxed::Box;
use heap;
#[test]
#[bench]
fn alloc_owned_small(b: &mut Bencher) {
b.iter(|| {
- box 10
+ let _: Box<_> = box 10;
})
}
}
// Primitive types using the heaps above
+// Need to conditionally define the mod from `boxed.rs` to avoid
+// duplicating the lang-items when building in test cfg; but also need
+// to allow code to have `use boxed::HEAP;`
+// and `use boxed::Box;` declarations.
#[cfg(not(test))]
pub mod boxed;
#[cfg(test)]
+mod boxed { pub use std::boxed::{Box, HEAP}; }
+#[cfg(test)]
mod boxed_test;
pub mod arc;
pub mod rc;
#[cfg(test)]
mod tests {
use super::{Rc, Weak, weak_count, strong_count};
+ use std::boxed::Box;
use std::cell::RefCell;
use std::option::Option;
use std::option::Option::{Some, None};
#[test]
fn test_destructor() {
- let x = Rc::new(box 5);
+ let x: Rc<Box<_>> = Rc::new(box 5);
assert_eq!(**x, 5);
}
#[bench]
pub fn bench_copy_nonarena(b: &mut Bencher) {
b.iter(|| {
- box Point {
+ let _: Box<_> = box Point {
x: 1,
y: 2,
z: 3,
- }
+ };
})
}
#[bench]
pub fn bench_noncopy_nonarena(b: &mut Bencher) {
b.iter(|| {
- box Noncopy {
+ let _: Box<_> = box Noncopy {
string: "hello world".to_string(),
array: vec!( 1, 2, 3, 4, 5 ),
- }
+ };
})
}
#[test]
fn test_push_unique() {
- let mut heap = BinaryHeap::from_vec(vec![box 2, box 4, box 9]);
+ let mut heap = BinaryHeap::<Box<_>>::from_vec(vec![box 2, box 4, box 9]);
assert_eq!(heap.len(), 3);
assert!(*heap.peek().unwrap() == box 9);
heap.push(box 11);
#[test]
fn test_basic() {
- let mut m = LinkedList::new();
+ let mut m = LinkedList::<Box<_>>::new();
assert_eq!(m.pop_front(), None);
assert_eq!(m.pop_back(), None);
assert_eq!(m.pop_front(), None);
#[cfg(test)]
mod tests {
+ use alloc::boxed::Box;
use core::cmp::Ordering::{Greater, Less, Equal};
use core::prelude::{Some, None, Clone};
use core::prelude::{Iterator, IteratorExt};
#[test]
fn test_swap_remove_noncopyable() {
// Tests that we don't accidentally run destructors twice.
- let mut v = Vec::new();
+ let mut v: Vec<Box<_>> = Vec::new();
v.push(box 0u8);
v.push(box 0u8);
v.push(box 0u8);
#[test]
fn test_truncate() {
- let mut v = vec![box 6,box 5,box 4];
+ let mut v: Vec<Box<_>> = vec![box 6,box 5,box 4];
v.truncate(1);
let v = v;
assert_eq!(v.len(), 1);
#[test]
fn test_clear() {
- let mut v = vec![box 6,box 5,box 4];
+ let mut v: Vec<Box<_>> = vec![box 6,box 5,box 4];
v.clear();
assert_eq!(v.len(), 0);
// If the unsafe block didn't drop things properly, we blow up here.
#[test]
fn test_dedup_unique() {
- let mut v0 = vec![box 1, box 1, box 2, box 3];
+ let mut v0: Vec<Box<_>> = vec![box 1, box 1, box 2, box 3];
v0.dedup();
- let mut v1 = vec![box 1, box 2, box 2, box 3];
+ let mut v1: Vec<Box<_>> = vec![box 1, box 2, box 2, box 3];
v1.dedup();
- let mut v2 = vec![box 1, box 2, box 3, box 3];
+ let mut v2: Vec<Box<_>> = vec![box 1, box 2, box 3, box 3];
v2.dedup();
/*
* If the boxed pointers were leaked or otherwise misused, valgrind
#[test]
fn test_dedup_shared() {
- let mut v0 = vec![box 1, box 1, box 2, box 3];
+ let mut v0: Vec<Box<_>> = vec![box 1, box 1, box 2, box 3];
v0.dedup();
- let mut v1 = vec![box 1, box 2, box 2, box 3];
+ let mut v1: Vec<Box<_>> = vec![box 1, box 2, box 2, box 3];
v1.dedup();
- let mut v2 = vec![box 1, box 2, box 3, box 3];
+ let mut v2: Vec<Box<_>> = vec![box 1, box 2, box 3, box 3];
v2.dedup();
/*
* If the pointers were leaked or otherwise misused, valgrind and/or
fn test_connect() {
let v: [Vec<i32>; 0] = [];
assert_eq!(v.connect(&0), []);
- assert_eq!([vec![1i], vec![2, 3]].connect(&0), [1, 0, 2, 3]);
- assert_eq!([vec![1i], vec![2], vec![3]].connect(&0), [1, 0, 2, 0, 3]);
+ assert_eq!([vec![1], vec![2, 3]].connect(&0), [1, 0, 2, 3]);
+ assert_eq!([vec![1], vec![2], vec![3]].connect(&0), [1, 0, 2, 0, 3]);
let v: [&[_]; 2] = [&[1], &[2, 3]];
assert_eq!(v.connect(&0), [1, 0, 2, 3]);
#[test]
#[should_fail]
fn test_permute_fail() {
- let v = [(box 0, Rc::new(0)), (box 0, Rc::new(0)),
- (box 0, Rc::new(0)), (box 0, Rc::new(0))];
+ let v: [(Box<_>, Rc<_>); 4] =
+ [(box 0, Rc::new(0)), (box 0, Rc::new(0)),
+ (box 0, Rc::new(0)), (box 0, Rc::new(0))];
let mut i = 0;
for _ in v.permutations() {
if i == 2 {
#[test]
fn test_to_vec() {
- let xs = box [1, 2, 3];
+ let xs: Box<_> = box [1, 2, 3];
let ys = xs.to_vec();
assert_eq!(ys, [1, 2, 3]);
}
#[test]
fn test_clone_from() {
let mut v = vec!();
- let three = vec!(box 1, box 2, box 3);
- let two = vec!(box 4, box 5);
+ let three: Vec<Box<_>> = vec!(box 1, box 2, box 3);
+ let two: Vec<Box<_>> = vec!(box 4, box 5);
// zero, long
v.clone_from(&three);
assert_eq!(v, three);
#[test]
fn test_move_iter() {
- let mut m = VecMap::new();
+ let mut m: VecMap<Box<_>> = VecMap::new();
m.insert(1, box 2);
let mut called = false;
for (k, v) in m {
f: F,
}
-impl<I: Iterator, F, B> Map<I, F> where F: FnMut(I::Item) -> B {
- #[inline]
- fn do_map(&mut self, elt: Option<I::Item>) -> Option<B> {
- match elt {
- Some(a) => Some((self.f)(a)),
- _ => None
- }
- }
-}
-
#[stable(feature = "rust1", since = "1.0.0")]
impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
type Item = B;
#[inline]
fn next(&mut self) -> Option<B> {
- let next = self.iter.next();
- self.do_map(next)
+ self.iter.next().map(|a| (self.f)(a))
}
#[inline]
{
#[inline]
fn next_back(&mut self) -> Option<B> {
- let next = self.iter.next_back();
- self.do_map(next)
+ self.iter.next_back().map(|a| (self.f)(a))
}
}
#[inline]
fn idx(&mut self, index: usize) -> Option<B> {
- let elt = self.iter.idx(index);
- self.do_map(elt)
+ self.iter.idx(index).map(|a| (self.f)(a))
}
}
#[test]
fn any_downcast_mut() {
let mut a = 5_usize;
- let mut b = box 7_usize;
+ let mut b: Box<_> = box 7_usize;
let a_r = &mut a as &mut Any;
let tmp: &mut uint = &mut *b;
//assert_eq!(hasher.hash(& s), 97 + 0xFF);
let cs: &[u8] = &[1u8, 2u8, 3u8];
assert_eq!(hash(& cs), 9);
- let cs: Box<[u8]> = box [1u8, 2u8, 3u8];
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let cs: Box<[u8]> = Box::new([1u8, 2u8, 3u8]);
assert_eq!(hash(& cs), 9);
// FIXME (#18248) Add tests for hashing Rc<str> and Rc<[T]>
impl Hasher for CustomHasher {
fn finish(&self) -> u64 { self.output }
- fn write(&mut self, data: &[u8]) { panic!() }
+ fn write(&mut self, _: &[u8]) { panic!() }
fn write_u64(&mut self, data: u64) { self.output = data; }
}
#[test]
fn test_all() {
- let v: Box<[int]> = box [1, 2, 3, 4, 5];
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let v: Box<[int]> = Box::new([1, 2, 3, 4, 5]);
assert!(v.iter().all(|&x| x < 10));
assert!(!v.iter().all(|&x| x % 2 == 0));
assert!(!v.iter().all(|&x| x > 100));
#[test]
fn test_any() {
- let v: Box<[int]> = box [1, 2, 3, 4, 5];
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let v: Box<[int]> = Box::new([1, 2, 3, 4, 5]);
assert!(v.iter().any(|&x| x < 10));
assert!(v.iter().any(|&x| x % 2 == 0));
assert!(!v.iter().any(|&x| x > 100));
#[test]
#[should_fail]
fn test_rposition_panic() {
- let v = [(box 0, box 0), (box 0, box 0),
- (box 0, box 0), (box 0, box 0)];
+ let v: [(Box<_>, Box<_>); 4] =
+ [(box 0, box 0), (box 0, box 0),
+ (box 0, box 0), (box 0, box 0)];
let mut i = 0;
v.iter().rposition(|_elt| {
if i == 2 {
#[test]
fn test_get_ptr() {
unsafe {
- let x = box 0;
+ let x: Box<_> = box 0;
let addr_x: *const int = mem::transmute(&*x);
let opt = Some(x);
let y = opt.unwrap();
mod pattern {
use std::str::Pattern;
- use std::str::{Searcher, ReverseSearcher, DoubleEndedSearcher};
+ use std::str::{Searcher, ReverseSearcher};
use std::str::SearchStep::{self, Match, Reject, Done};
macro_rules! make_test {
($name:ident, $p:expr, $h:expr, [$($e:expr,)*]) => {
mod $name {
- use std::str::Pattern;
- use std::str::{Searcher, ReverseSearcher, DoubleEndedSearcher};
- use std::str::SearchStep::{self, Match, Reject, Done};
+ use std::str::SearchStep::{Match, Reject};
use super::{cmp_search_to_vec};
#[test]
fn fwd() {
#![feature(int_uint)]
#![feature(staged_api)]
#![feature(str_words)]
+#![feature(core)]
#![cfg_attr(test, feature(rustc_private))]
#[cfg(test)] #[macro_use] extern crate log;
#[cfg(test)]
mod tests {
- use std::prelude::v1::*;
use std::rand::{Rng, thread_rng, Open01, Closed01};
struct ConstantRng(u64);
fn test_seekable_mem_writer() {
let mut writer = SeekableMemWriter::new();
assert_eq!(writer.tell(), Ok(0));
- writer.write(&[0]).unwrap();
+ writer.write_all(&[0]).unwrap();
assert_eq!(writer.tell(), Ok(1));
- writer.write(&[1, 2, 3]).unwrap();
- writer.write(&[4, 5, 6, 7]).unwrap();
+ writer.write_all(&[1, 2, 3]).unwrap();
+ writer.write_all(&[4, 5, 6, 7]).unwrap();
assert_eq!(writer.tell(), Ok(8));
let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(0, old_io::SeekSet).unwrap();
assert_eq!(writer.tell(), Ok(0));
- writer.write(&[3, 4]).unwrap();
+ writer.write_all(&[3, 4]).unwrap();
let b: &[_] = &[3, 4, 2, 3, 4, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(1, old_io::SeekCur).unwrap();
- writer.write(&[0, 1]).unwrap();
+ writer.write_all(&[0, 1]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(-1, old_io::SeekEnd).unwrap();
- writer.write(&[1, 2]).unwrap();
+ writer.write_all(&[1, 2]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2];
assert_eq!(writer.get_ref(), b);
writer.seek(1, old_io::SeekEnd).unwrap();
- writer.write(&[1]).unwrap();
+ writer.write_all(&[1]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2, 0, 1];
assert_eq!(writer.get_ref(), b);
}
fn seek_past_end() {
let mut r = SeekableMemWriter::new();
r.seek(10, old_io::SeekSet).unwrap();
- assert!(r.write(&[3]).is_ok());
+ assert!(r.write_all(&[3]).is_ok());
}
#[test]
b.iter(|| {
let mut wr = SeekableMemWriter::new();
for _ in 0..times {
- wr.write(&src).unwrap();
+ wr.write_all(&src).unwrap();
}
let v = wr.unwrap();
#![feature(staged_api)]
#![feature(std_misc)]
#![feature(os)]
+#![feature(path)]
+#![feature(fs)]
+#![feature(io)]
#![cfg_attr(test, feature(test))]
extern crate arena;
pub const tag_macro_def_body: uint = 0x9f;
pub const tag_paren_sugar: uint = 0xa0;
+
+pub const tag_codemap: uint = 0xa1;
+pub const tag_codemap_filemap: uint = 0xa2;
use metadata::loader;
use metadata::loader::CratePaths;
+use std::path::{Path, PathBuf};
use std::rc::Rc;
use syntax::ast;
use syntax::abi;
use syntax::attr;
use syntax::attr::AttrMetaMethods;
-use syntax::codemap::{Span, mk_sp};
+use syntax::codemap::{self, Span, mk_sp, Pos};
use syntax::parse;
use syntax::parse::token::InternedString;
use syntax::parse::token;
// Extra info about a crate loaded for plugins or exported macros.
struct ExtensionCrate {
metadata: PMDSource,
- dylib: Option<Path>,
+ dylib: Option<PathBuf>,
target_only: bool,
}
// Maintain a reference to the top most crate.
let root = if root.is_some() { root } else { &crate_paths };
- let cnum_map = self.resolve_crate_deps(root, lib.metadata.as_slice(), span);
+ let loader::Library { dylib, rlib, metadata } = lib;
- let loader::Library{ dylib, rlib, metadata } = lib;
+ let cnum_map = self.resolve_crate_deps(root, metadata.as_slice(), span);
+ let codemap_import_info = import_codemap(self.sess.codemap(), &metadata);
let cmeta = Rc::new( cstore::crate_metadata {
name: name.to_string(),
data: metadata,
cnum_map: cnum_map,
cnum: cnum,
+ codemap_import_info: codemap_import_info,
span: span,
});
}
/// Look for a plugin registrar. Returns library path and symbol name.
- pub fn find_plugin_registrar(&mut self, span: Span, name: &str) -> Option<(Path, String)> {
+ pub fn find_plugin_registrar(&mut self, span: Span, name: &str)
+ -> Option<(PathBuf, String)> {
let ekrate = self.read_extension_crate(span, &CrateInfo {
name: name.to_string(),
ident: name.to_string(),
.map(|id| decoder::get_symbol(ekrate.metadata.as_slice(), id));
match (ekrate.dylib.as_ref(), registrar) {
- (Some(dylib), Some(reg)) => Some((dylib.clone(), reg)),
+ (Some(dylib), Some(reg)) => Some((dylib.to_path_buf(), reg)),
(None, Some(_)) => {
let message = format!("plugin `{}` only found in rlib format, \
but must be available in dylib format",
}
}
}
+
+/// Imports the codemap from an external crate into the codemap of the crate
+/// currently being compiled (the "local crate").
+///
+/// The import algorithm works analogous to how AST items are inlined from an
+/// external crate's metadata:
+/// For every FileMap in the external codemap an 'inline' copy is created in the
+/// local codemap. The correspondence relation between external and local
+/// FileMaps is recorded in the `ImportedFileMap` objects returned from this
+/// function. When an item from an external crate is later inlined into this
+/// crate, this correspondence information is used to translate the span
+/// information of the inlined item so that it refers the correct positions in
+/// the local codemap (see `astencode::DecodeContext::tr_span()`).
+///
+/// The import algorithm in the function below will reuse FileMaps already
+/// existing in the local codemap. For example, even if the FileMap of some
+/// source file of libstd gets imported many times, there will only ever be
+/// one FileMap object for the corresponding file in the local codemap.
+///
+/// Note that imported FileMaps do not actually contain the source code of the
+/// file they represent, just information about length, line breaks, and
+/// multibyte characters. This information is enough to generate valid debuginfo
+/// for items inlined from other crates.
+fn import_codemap(local_codemap: &codemap::CodeMap,
+ metadata: &MetadataBlob)
+ -> Vec<cstore::ImportedFileMap> {
+ let external_codemap = decoder::get_imported_filemaps(metadata.as_slice());
+
+ let imported_filemaps = external_codemap.into_iter().map(|filemap_to_import| {
+ // Try to find an existing FileMap that can be reused for the filemap to
+ // be imported. A FileMap is reusable if it is exactly the same, just
+ // positioned at a different offset within the codemap.
+ let reusable_filemap = {
+ local_codemap.files
+ .borrow()
+ .iter()
+ .find(|fm| are_equal_modulo_startpos(&fm, &filemap_to_import))
+ .map(|rc| rc.clone())
+ };
+
+ match reusable_filemap {
+ Some(fm) => {
+ cstore::ImportedFileMap {
+ original_start_pos: filemap_to_import.start_pos,
+ original_end_pos: filemap_to_import.end_pos,
+ translated_filemap: fm
+ }
+ }
+ None => {
+ // We can't reuse an existing FileMap, so allocate a new one
+ // containing the information we need.
+ let codemap::FileMap {
+ name,
+ start_pos,
+ end_pos,
+ lines,
+ multibyte_chars,
+ ..
+ } = filemap_to_import;
+
+ let source_length = (end_pos - start_pos).to_usize();
+
+ // Translate line-start positions and multibyte character
+ // position into frame of reference local to file.
+ // `CodeMap::new_imported_filemap()` will then translate those
+ // coordinates to their new global frame of reference when the
+ // offset of the FileMap is known.
+ let lines = lines.into_inner().map_in_place(|pos| pos - start_pos);
+ let multibyte_chars = multibyte_chars
+ .into_inner()
+ .map_in_place(|mbc|
+ codemap::MultiByteChar {
+ pos: mbc.pos + start_pos,
+ bytes: mbc.bytes
+ });
+
+ let local_version = local_codemap.new_imported_filemap(name,
+ source_length,
+ lines,
+ multibyte_chars);
+ cstore::ImportedFileMap {
+ original_start_pos: start_pos,
+ original_end_pos: end_pos,
+ translated_filemap: local_version
+ }
+ }
+ }
+ }).collect();
+
+ return imported_filemaps;
+
+ fn are_equal_modulo_startpos(fm1: &codemap::FileMap,
+ fm2: &codemap::FileMap)
+ -> bool {
+ if fm1.name != fm2.name {
+ return false;
+ }
+
+ let lines1 = fm1.lines.borrow();
+ let lines2 = fm2.lines.borrow();
+
+ if lines1.len() != lines2.len() {
+ return false;
+ }
+
+ for (&line1, &line2) in lines1.iter().zip(lines2.iter()) {
+ if (line1 - fm1.start_pos) != (line2 - fm2.start_pos) {
+ return false;
+ }
+ }
+
+ let multibytes1 = fm1.multibyte_chars.borrow();
+ let multibytes2 = fm2.multibyte_chars.borrow();
+
+ if multibytes1.len() != multibytes2.len() {
+ return false;
+ }
+
+ for (mb1, mb2) in multibytes1.iter().zip(multibytes2.iter()) {
+ if (mb1.bytes != mb2.bytes) ||
+ ((mb1.pos - fm1.start_pos) != (mb2.pos - fm2.start_pos)) {
+ return false;
+ }
+ }
+
+ true
+ }
+}
use std::cell::RefCell;
use std::rc::Rc;
+use std::path::PathBuf;
use flate::Bytes;
use syntax::ast;
-use syntax::codemap::Span;
+use syntax::codemap;
use syntax::parse::token::IdentInterner;
// A map from external crate numbers (as decoded from some crate file) to
MetadataArchive(loader::ArchiveMetadata),
}
+/// Holds information about a codemap::FileMap imported from another crate.
+/// See creader::import_codemap() for more information.
+pub struct ImportedFileMap {
+ /// This FileMap's byte-offset within the codemap of its original crate
+ pub original_start_pos: codemap::BytePos,
+ /// The end of this FileMap within the codemap of its original crate
+ pub original_end_pos: codemap::BytePos,
+ /// The imported FileMap's representation within the local codemap
+ pub translated_filemap: Rc<codemap::FileMap>
+}
+
pub struct crate_metadata {
pub name: String,
pub data: MetadataBlob,
pub cnum_map: cnum_map,
pub cnum: ast::CrateNum,
- pub span: Span,
+ pub codemap_import_info: Vec<ImportedFileMap>,
+ pub span: codemap::Span,
}
#[derive(Copy, Debug, PartialEq, Clone)]
// must be non-None.
#[derive(PartialEq, Clone)]
pub struct CrateSource {
- pub dylib: Option<(Path, PathKind)>,
- pub rlib: Option<(Path, PathKind)>,
+ pub dylib: Option<(PathBuf, PathKind)>,
+ pub rlib: Option<(PathBuf, PathKind)>,
pub cnum: ast::CrateNum,
}
// topological sort of all crates putting the leaves at the right-most
// positions.
pub fn get_used_crates(&self, prefer: LinkagePreference)
- -> Vec<(ast::CrateNum, Option<Path>)> {
+ -> Vec<(ast::CrateNum, Option<PathBuf>)> {
let mut ordering = Vec::new();
fn visit(cstore: &CStore, cnum: ast::CrateNum,
ordering: &mut Vec<ast::CrateNum>) {
use std::collections::HashMap;
use std::hash::{self, Hash, SipHasher};
-use std::num::FromPrimitive;
-use std::num::Int;
-use std::old_io;
+use std::io::prelude::*;
+use std::io;
+use std::num::{FromPrimitive, Int};
use std::rc::Rc;
use std::slice::bytes;
use std::str;
}
fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
- out: &mut old_io::Writer) -> old_io::IoResult<()> {
+ out: &mut io::Write) -> io::Result<()> {
try!(write!(out, "=Crate Attributes ({})=\n", *hash));
let r = get_attributes(md);
return deps;
}
-fn list_crate_deps(data: &[u8], out: &mut old_io::Writer) -> old_io::IoResult<()> {
+fn list_crate_deps(data: &[u8], out: &mut io::Write) -> io::Result<()> {
try!(write!(out, "=External Dependencies=\n"));
for dep in &get_crate_deps(data) {
try!(write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash));
maybe_get_crate_name(data).expect("no crate name in crate")
}
-pub fn list_crate_metadata(bytes: &[u8], out: &mut old_io::Writer) -> old_io::IoResult<()> {
+pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Write) -> io::Result<()> {
let hash = get_crate_hash(bytes);
let md = rbml::Doc::new(bytes);
try!(list_crate_attributes(md, &hash, out));
}
}
-
pub fn is_default_trait<'tcx>(cdata: Cmd, id: ast::NodeId) -> bool {
let item_doc = lookup_item(id, cdata.data());
match item_family(item_doc) {
_ => false
}
}
+
+pub fn get_imported_filemaps(metadata: &[u8]) -> Vec<codemap::FileMap> {
+ let crate_doc = rbml::Doc::new(metadata);
+ let cm_doc = reader::get_doc(crate_doc, tag_codemap);
+
+ let mut filemaps = vec![];
+
+ reader::tagged_docs(cm_doc, tag_codemap_filemap, |filemap_doc| {
+ let mut decoder = reader::Decoder::new(filemap_doc);
+ let filemap: codemap::FileMap = Decodable::decode(&mut decoder).unwrap();
+ filemaps.push(filemap);
+ true
+ });
+
+ return filemaps;
+}
}
}
+fn encode_codemap(ecx: &EncodeContext, rbml_w: &mut Encoder) {
+ rbml_w.start_tag(tag_codemap);
+ let codemap = ecx.tcx.sess.codemap();
+
+ for filemap in &codemap.files.borrow()[..] {
+
+ if filemap.lines.borrow().len() == 0 || filemap.is_imported() {
+ // No need to export empty filemaps, as they can't contain spans
+ // that need translation.
+ // Also no need to re-export imported filemaps, as any downstream
+ // crate will import them from their original source.
+ continue;
+ }
+
+ rbml_w.start_tag(tag_codemap_filemap);
+ filemap.encode(rbml_w);
+ rbml_w.end_tag();
+ }
+
+ rbml_w.end_tag();
+}
+
/// Serialize the text of the exported macros
fn encode_macro_defs(rbml_w: &mut Encoder,
krate: &ast::Crate) {
lang_item_bytes: u64,
native_lib_bytes: u64,
plugin_registrar_fn_bytes: u64,
+ codemap_bytes: u64,
macro_defs_bytes: u64,
impl_bytes: u64,
misc_bytes: u64,
lang_item_bytes: 0,
native_lib_bytes: 0,
plugin_registrar_fn_bytes: 0,
+ codemap_bytes: 0,
macro_defs_bytes: 0,
impl_bytes: 0,
misc_bytes: 0,
encode_plugin_registrar_fn(&ecx, &mut rbml_w);
stats.plugin_registrar_fn_bytes = rbml_w.writer.tell().unwrap() - i;
+ // Encode codemap
+ i = rbml_w.writer.tell().unwrap();
+ encode_codemap(&ecx, &mut rbml_w);
+ stats.codemap_bytes = rbml_w.writer.tell().unwrap() - i;
+
// Encode macro definitions
i = rbml_w.writer.tell().unwrap();
encode_macro_defs(&mut rbml_w, krate);
println!(" lang item bytes: {}", stats.lang_item_bytes);
println!(" native bytes: {}", stats.native_lib_bytes);
println!("plugin registrar bytes: {}", stats.plugin_registrar_fn_bytes);
+ println!(" codemap bytes: {}", stats.codemap_bytes);
println!(" macro def bytes: {}", stats.macro_defs_bytes);
println!(" impl bytes: {}", stats.impl_bytes);
println!(" misc bytes: {}", stats.misc_bytes);
use std::collections::HashSet;
use std::env;
-use std::os;
-use std::old_io::fs::PathExtensions;
-use std::old_io::fs;
+use std::fs;
+use std::io::prelude::*;
+use std::path::{Path, PathBuf};
use util::fs as myfs;
use session::search_paths::{SearchPaths, PathKind};
FileMatches => found = true,
FileDoesntMatch => ()
}
- visited_dirs.insert(path.as_vec().to_vec());
+ visited_dirs.insert(path.to_path_buf());
}
debug!("filesearch: searching lib path");
let tlib_path = make_target_lib_path(self.sysroot,
self.triple);
- if !visited_dirs.contains(tlib_path.as_vec()) {
+ if !visited_dirs.contains(&tlib_path) {
match f(&tlib_path, PathKind::All) {
FileMatches => found = true,
FileDoesntMatch => ()
}
}
- visited_dirs.insert(tlib_path.as_vec().to_vec());
+ visited_dirs.insert(tlib_path);
// Try RUST_PATH
if !found {
let rustpath = rust_path();
let tlib_path = make_rustpkg_lib_path(
self.sysroot, path, self.triple);
debug!("is {} in visited_dirs? {}", tlib_path.display(),
- visited_dirs.contains(&tlib_path.as_vec().to_vec()));
+ visited_dirs.contains(&tlib_path));
- if !visited_dirs.contains(tlib_path.as_vec()) {
- visited_dirs.insert(tlib_path.as_vec().to_vec());
+ if !visited_dirs.contains(&tlib_path) {
+ visited_dirs.insert(tlib_path.clone());
// Don't keep searching the RUST_PATH if one match turns up --
// if we did, we'd get a "multiple matching crates" error
match f(&tlib_path, PathKind::All) {
}
}
- pub fn get_lib_path(&self) -> Path {
+ pub fn get_lib_path(&self) -> PathBuf {
make_target_lib_path(self.sysroot, self.triple)
}
{
self.for_each_lib_search_path(|lib_search_path, kind| {
debug!("searching {}", lib_search_path.display());
- match fs::readdir(lib_search_path) {
+ match fs::read_dir(lib_search_path) {
Ok(files) => {
+ let files = files.filter_map(|p| p.ok().map(|s| s.path()))
+ .collect::<Vec<_>>();
let mut rslt = FileDoesntMatch;
- fn is_rlib(p: & &Path) -> bool {
- p.extension_str() == Some("rlib")
+ fn is_rlib(p: &Path) -> bool {
+ p.extension().and_then(|s| s.to_str()) == Some("rlib")
}
// Reading metadata out of rlibs is faster, and if we find both
// an rlib and a dylib we only read one of the files of
}
// Returns a list of directories where target-specific dylibs might be located.
- pub fn get_dylib_search_paths(&self) -> Vec<Path> {
+ pub fn get_dylib_search_paths(&self) -> Vec<PathBuf> {
let mut paths = Vec::new();
self.for_each_lib_search_path(|lib_search_path, _| {
- paths.push(lib_search_path.clone());
+ paths.push(lib_search_path.to_path_buf());
FileDoesntMatch
});
paths
}
// Returns a list of directories where target-specific tool binaries are located.
- pub fn get_tools_search_paths(&self) -> Vec<Path> {
- let mut p = Path::new(self.sysroot);
- p.push(find_libdir(self.sysroot));
- p.push(rustlibdir());
- p.push(self.triple);
+ pub fn get_tools_search_paths(&self) -> Vec<PathBuf> {
+ let mut p = PathBuf::new(self.sysroot);
+ p.push(&find_libdir(self.sysroot));
+ p.push(&rustlibdir());
+ p.push(&self.triple);
p.push("bin");
vec![p]
}
}
-pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
- let mut p = Path::new(find_libdir(sysroot));
+pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
+ let mut p = PathBuf::new(&find_libdir(sysroot));
assert!(p.is_relative());
- p.push(rustlibdir());
+ p.push(&rustlibdir());
p.push(target_triple);
p.push("lib");
p
}
fn make_target_lib_path(sysroot: &Path,
- target_triple: &str) -> Path {
+ target_triple: &str) -> PathBuf {
sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}
fn make_rustpkg_lib_path(sysroot: &Path,
dir: &Path,
- triple: &str) -> Path {
- let mut p = dir.join(find_libdir(sysroot));
+ triple: &str) -> PathBuf {
+ let mut p = dir.join(&find_libdir(sysroot));
p.push(triple);
p
}
-pub fn get_or_default_sysroot() -> Path {
+pub fn get_or_default_sysroot() -> PathBuf {
// Follow symlinks. If the resolved path is relative, make it absolute.
- fn canonicalize(path: Option<Path>) -> Option<Path> {
- path.and_then(|path|
+ fn canonicalize(path: Option<PathBuf>) -> Option<PathBuf> {
+ path.and_then(|path| {
match myfs::realpath(&path) {
Ok(canon) => Some(canon),
Err(e) => panic!("failed to get realpath: {}", e),
- })
+ }
+ })
}
- match canonicalize(os::self_exe_name()) {
+ match canonicalize(env::current_exe().ok()) {
Some(mut p) => { p.pop(); p.pop(); p }
None => panic!("can't determine value for sysroot")
}
/// $HOME/.rust
/// DIR/.rust for any DIR that's the current working directory
/// or an ancestor of it
-pub fn rust_path() -> Vec<Path> {
- let mut env_rust_path: Vec<Path> = match get_rust_path() {
+pub fn rust_path() -> Vec<PathBuf> {
+ let mut env_rust_path: Vec<PathBuf> = match get_rust_path() {
Some(env_path) => {
let env_path_components =
env_path.split(PATH_ENTRY_SEPARATOR);
- env_path_components.map(|s| Path::new(s)).collect()
+ env_path_components.map(|s| PathBuf::new(s)).collect()
}
None => Vec::new()
};
- let mut cwd = os::getcwd().unwrap();
+ let cwd = env::current_dir().unwrap();
// now add in default entries
let cwd_dot_rust = cwd.join(".rust");
if !env_rust_path.contains(&cwd_dot_rust) {
if !env_rust_path.contains(&cwd) {
env_rust_path.push(cwd.clone());
}
- loop {
- if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } {
- break
- }
- cwd.set_filename(".rust");
- if !env_rust_path.contains(&cwd) && cwd.exists() {
- env_rust_path.push(cwd.clone());
+ let mut cur = &*cwd;
+ while let Some(parent) = cur.parent() {
+ let candidate = parent.join(".rust");
+ if !env_rust_path.contains(&candidate) && candidate.exists() {
+ env_rust_path.push(candidate.clone());
}
- cwd.pop();
+ cur = parent;
}
- if let Some(h) = os::homedir() {
+ if let Some(h) = env::home_dir() {
let p = h.join(".rust");
if !env_rust_path.contains(&p) && p.exists() {
env_rust_path.push(p);
match option_env!("CFG_LIBDIR_RELATIVE") {
Some(libdir) if libdir != "lib" => return libdir.to_string(),
- _ => if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
+ _ => if sysroot.join(&primary_libdir_name()).join(&rustlibdir()).exists() {
return primary_libdir_name();
} else {
return secondary_libdir_name();
use syntax::codemap::Span;
use syntax::diagnostic::SpanHandler;
use util::fs;
+use util::common;
use rustc_back::target::Target;
-use std::ffi::CString;
use std::cmp;
use std::collections::HashMap;
-use std::old_io::fs::PathExtensions;
-use std::old_io;
+use std::io::prelude::*;
+use std::io;
+use std::path::{Path, PathBuf};
use std::ptr;
use std::slice;
use std::time::Duration;
use flate;
pub struct CrateMismatch {
- path: Path,
+ path: PathBuf,
got: String,
}
}
pub struct Library {
- pub dylib: Option<(Path, PathKind)>,
- pub rlib: Option<(Path, PathKind)>,
+ pub dylib: Option<(PathBuf, PathKind)>,
+ pub rlib: Option<(PathBuf, PathKind)>,
pub metadata: MetadataBlob,
}
pub struct CratePaths {
pub ident: String,
- pub dylib: Option<Path>,
- pub rlib: Option<Path>
+ pub dylib: Option<PathBuf>,
+ pub rlib: Option<PathBuf>
}
impl CratePaths {
- fn paths(&self) -> Vec<Path> {
+ fn paths(&self) -> Vec<PathBuf> {
match (&self.dylib, &self.rlib) {
(&None, &None) => vec!(),
(&Some(ref p), &None) |
//
// The goal of this step is to look at as little metadata as possible.
self.filesearch.search(|path, kind| {
- let file = match path.filename_str() {
+ let file = match path.file_name().and_then(|s| s.to_str()) {
None => return FileDoesntMatch,
Some(file) => file,
};
if file.starts_with(&staticlib_prefix[..]) &&
file.ends_with(".a") {
staticlibs.push(CrateMismatch {
- path: path.clone(),
+ path: path.to_path_buf(),
got: "static".to_string()
});
}
// read the metadata from it if `*slot` is `None`. If the metadata couldn't
// be read, it is assumed that the file isn't a valid rust library (no
// errors are emitted).
- fn extract_one(&mut self, m: HashMap<Path, PathKind>, flavor: &str,
- slot: &mut Option<MetadataBlob>) -> Option<(Path, PathKind)> {
- let mut ret = None::<(Path, PathKind)>;
+ fn extract_one(&mut self, m: HashMap<PathBuf, PathKind>, flavor: &str,
+ slot: &mut Option<MetadataBlob>) -> Option<(PathBuf, PathKind)> {
+ let mut ret = None::<(PathBuf, PathKind)>;
let mut error = 0;
if slot.is_some() {
if triple != self.triple {
info!("Rejecting via crate triple: expected {} got {}", self.triple, triple);
self.rejected_via_triple.push(CrateMismatch {
- path: libpath.clone(),
+ path: libpath.to_path_buf(),
got: triple.to_string()
});
return false;
if *myhash != hash {
info!("Rejecting via hash: expected {} got {}", *myhash, hash);
self.rejected_via_hash.push(CrateMismatch {
- path: libpath.clone(),
+ path: libpath.to_path_buf(),
got: myhash.as_str().to_string()
});
false
let mut rlibs = HashMap::new();
let mut dylibs = HashMap::new();
{
- let locs = locs.iter().map(|l| Path::new(&l[..])).filter(|loc| {
+ let locs = locs.iter().map(|l| PathBuf::new(&l[..])).filter(|loc| {
if !loc.exists() {
sess.err(&format!("extern location for {} does not exist: {}",
self.crate_name, loc.display()));
return false;
}
- let file = match loc.filename_str() {
+ let file = match loc.file_name().and_then(|s| s.to_str()) {
Some(file) => file,
None => {
sess.err(&format!("extern location for {} is not a file: {}",
// Now that we have an iterator of good candidates, make sure
// there's at most one rlib and at most one dylib.
for loc in locs {
- if loc.filename_str().unwrap().ends_with(".rlib") {
+ if loc.file_name().unwrap().to_str().unwrap().ends_with(".rlib") {
rlibs.insert(fs::realpath(&loc).unwrap(),
PathKind::ExternFlag);
} else {
let dur = Duration::span(|| {
ret = Some(get_metadata_section_imp(is_osx, filename));
});
- info!("reading {} => {}ms", filename.filename_display(),
+ info!("reading {:?} => {}ms", filename.file_name().unwrap(),
dur.num_milliseconds());
return ret.unwrap();;
}
if !filename.exists() {
return Err(format!("no such file: '{}'", filename.display()));
}
- if filename.filename_str().unwrap().ends_with(".rlib") {
+ if filename.file_name().unwrap().to_str().unwrap().ends_with(".rlib") {
// Use ArchiveRO for speed here, it's backed by LLVM and uses mmap
// internally to read the file. We also avoid even using a memcpy by
// just keeping the archive along while the metadata is in use.
};
}
unsafe {
- let buf = CString::new(filename.as_vec()).unwrap();
+ let buf = common::path2cstr(filename);
let mb = llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf.as_ptr());
if mb as int == 0 {
return Err(format!("error reading library: '{}'",
// A diagnostic function for dumping crate metadata to an output stream
pub fn list_file_metadata(is_osx: bool, path: &Path,
- out: &mut old_io::Writer) -> old_io::IoResult<()> {
+ out: &mut io::Write) -> io::Result<()> {
match get_metadata_section(is_osx, path) {
Ok(bytes) => decoder::list_crate_metadata(bytes.as_slice(), out),
Err(msg) => {
use std::old_io::Seek;
use std::num::FromPrimitive;
use std::rc::Rc;
+use std::cell::Cell;
use rbml::reader;
use rbml::writer::Encoder;
tcx: &'a ty::ctxt<'tcx>,
cdata: &'b cstore::crate_metadata,
from_id_range: ast_util::IdRange,
- to_id_range: ast_util::IdRange
+ to_id_range: ast_util::IdRange,
+ // Cache the last used filemap for translating spans as an optimization.
+ last_filemap_index: Cell<usize>,
}
trait tr {
}
}
+/// Decodes an item from its AST in the cdata's metadata and adds it to the
+/// ast-map.
pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata,
tcx: &ty::ctxt<'tcx>,
path: Vec<ast_map::PathElem>,
cdata: cdata,
tcx: tcx,
from_id_range: from_id_range,
- to_id_range: to_id_range
+ to_id_range: to_id_range,
+ last_filemap_index: Cell::new(0)
};
let raw_ii = decode_ast(ast_doc);
let ii = ast_map::map_decoded_item(&dcx.tcx.map, path, raw_ii, dcx);
assert_eq!(did.krate, ast::LOCAL_CRATE);
ast::DefId { krate: ast::LOCAL_CRATE, node: self.tr_id(did.node) }
}
- pub fn tr_span(&self, _span: Span) -> Span {
- codemap::DUMMY_SP // FIXME (#1972): handle span properly
+
+ /// Translates a `Span` from an extern crate to the corresponding `Span`
+ /// within the local crate's codemap. `creader::import_codemap()` will
+ /// already have allocated any additionally needed FileMaps in the local
+ /// codemap as a side-effect of creating the crate_metadata's
+ /// `codemap_import_info`.
+ pub fn tr_span(&self, span: Span) -> Span {
+ let imported_filemaps = &self.cdata.codemap_import_info[..];
+
+ let filemap_index = {
+ // Optimize for the case that most spans within a translated item
+ // originate from the same filemap.
+ let last_filemap_index = self.last_filemap_index.get();
+
+ if span.lo >= imported_filemaps[last_filemap_index].original_start_pos &&
+ span.hi <= imported_filemaps[last_filemap_index].original_end_pos {
+ last_filemap_index
+ } else {
+ let mut a = 0;
+ let mut b = imported_filemaps.len();
+
+ while b - a > 1 {
+ let m = (a + b) / 2;
+ if imported_filemaps[m].original_start_pos > span.lo {
+ b = m;
+ } else {
+ a = m;
+ }
+ }
+
+ self.last_filemap_index.set(a);
+ a
+ }
+ };
+
+ let lo = (span.lo - imported_filemaps[filemap_index].original_start_pos) +
+ imported_filemaps[filemap_index].translated_filemap.start_pos;
+ let hi = (span.hi - imported_filemaps[filemap_index].original_start_pos) +
+ imported_filemaps[filemap_index].translated_filemap.start_pos;
+
+ codemap::mk_sp(lo, hi)
}
}
None => {}
}
let expr_id = match csearch::maybe_get_item_ast(tcx, enum_def,
- box |a, b, c, d| astencode::decode_inlined_item(a, b, c, d)) {
+ Box::new(|a, b, c, d| astencode::decode_inlined_item(a, b, c, d))) {
csearch::FoundAst::Found(&ast::IIItem(ref item)) => match item.node {
ast::ItemEnum(ast::EnumDef { ref variants }, _) => {
// NOTE this doesn't do the right thing, it compares inlined
None => {}
}
let expr_id = match csearch::maybe_get_item_ast(tcx, def_id,
- box |a, b, c, d| astencode::decode_inlined_item(a, b, c, d)) {
+ Box::new(|a, b, c, d| astencode::decode_inlined_item(a, b, c, d))) {
csearch::FoundAst::Found(&ast::IIItem(ref item)) => match item.node {
ast::ItemConst(_, ref const_expr) => Some(const_expr.id),
_ => None
use middle::cfg;
use middle::cfg::CFGIndex;
use middle::ty;
-use std::old_io;
+use std::io;
use std::usize;
use std::iter::repeat;
use syntax::ast;
impl<'a, 'tcx, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, 'tcx, O> {
fn pre(&self,
ps: &mut pprust::State,
- node: pprust::AnnNode) -> old_io::IoResult<()> {
+ node: pprust::AnnNode) -> io::Result<()> {
let id = match node {
pprust::NodeIdent(_) | pprust::NodeName(_) => 0,
pprust::NodeExpr(expr) => expr.id,
debug!("Dataflow result for {}:", self.analysis_name);
debug!("{}", {
- self.pretty_print_to(box old_io::stderr(), blk).unwrap();
+ let mut v = Vec::new();
+ self.pretty_print_to(box &mut v, blk).unwrap();
+ println!("{}", String::from_utf8(v).unwrap());
""
});
}
- fn pretty_print_to(&self, wr: Box<old_io::Writer+'static>,
- blk: &ast::Block) -> old_io::IoResult<()> {
+ fn pretty_print_to<'b>(&self, wr: Box<io::Write + 'b>,
+ blk: &ast::Block) -> io::Result<()> {
let mut ps = pprust::rust_printer_annotated(wr, self);
try!(ps.cbox(pprust::indent_unit));
try!(ps.ibox(0));
use std::borrow::Cow;
use std::collections::hash_map::Entry::Vacant;
-use std::old_io::{self, File};
use std::env;
+use std::fs::File;
+use std::io;
+use std::io::prelude::*;
use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT};
use syntax::ast;
fn dump_region_constraints_to<'a, 'tcx:'a >(tcx: &'a ty::ctxt<'tcx>,
map: &ConstraintMap<'tcx>,
- path: &str) -> old_io::IoResult<()> {
+ path: &str) -> io::Result<()> {
debug!("dump_region_constraints map (len: {}) path: {}", map.len(), path);
let g = ConstraintGraph::new(tcx, format!("region_constraints"), map);
- let mut f = File::create(&Path::new(path));
debug!("dump_region_constraints calling render");
- dot::render(&g, &mut f)
+ let mut v = Vec::new();
+ dot::render(&g, &mut v).unwrap();
+ File::create(path).and_then(|mut f| f.write_all(&v))
}
use metadata::creader::CrateReader;
use plugin::registry::Registry;
-use std::mem;
-use std::os;
-use std::dynamic_lib::DynamicLibrary;
use std::borrow::ToOwned;
+use std::dynamic_lib::DynamicLibrary;
+use std::env;
+use std::mem;
+use std::old_path;
+use std::path::PathBuf;
use syntax::ast;
use syntax::codemap::{Span, COMMAND_LINE_SP};
use syntax::ptr::P;
// Dynamically link a registrar function into the compiler process.
fn dylink_registrar(&mut self,
span: Span,
- path: Path,
+ path: PathBuf,
symbol: String) -> PluginRegistrarFun {
// Make sure the path contains a / or the linker will search for it.
- let path = os::getcwd().unwrap().join(&path);
+ let path = env::current_dir().unwrap().join(&path);
+ let path = old_path::Path::new(path.to_str().unwrap());
let lib = match DynamicLibrary::open(Some(&path)) {
Ok(lib) => lib,
/// It builds for you a `NormalTT` that calls `expander`,
/// and also takes care of interning the macro's name.
pub fn register_macro(&mut self, name: &str, expander: MacroExpanderFn) {
- self.register_syntax_extension(token::intern(name), NormalTT(box expander, None));
+ self.register_syntax_extension(token::intern(name), NormalTT(Box::new(expander), None));
}
/// Register a compiler lint pass.
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::env;
use std::fmt;
+use std::path::PathBuf;
use llvm;
// this.
pub search_paths: SearchPaths,
pub libs: Vec<(String, cstore::NativeLibraryKind)>,
- pub maybe_sysroot: Option<Path>,
+ pub maybe_sysroot: Option<PathBuf>,
pub target_triple: String,
// User-specified cfg meta items. The compiler itself will add additional
// items to the crate config, and during parsing the entire crate config
pub no_analysis: bool,
pub debugging_opts: DebuggingOptions,
/// Whether to write dependency files. It's (enabled, optional filename).
- pub write_dependency_info: (bool, Option<Path>),
+ pub write_dependency_info: (bool, Option<PathBuf>),
pub prints: Vec<PrintRequest>,
pub cg: CodegenOptions,
pub color: ColorConfig,
pub enum Input {
/// Load source from file
- File(Path),
+ File(PathBuf),
/// The string is the source
Str(String)
}
impl Input {
pub fn filestem(&self) -> String {
match *self {
- Input::File(ref ifile) => ifile.filestem_str().unwrap().to_string(),
+ Input::File(ref ifile) => ifile.file_stem().unwrap()
+ .to_str().unwrap().to_string(),
Input::Str(_) => "rust_out".to_string(),
}
}
#[derive(Clone)]
pub struct OutputFilenames {
- pub out_directory: Path,
+ pub out_directory: PathBuf,
pub out_filestem: String,
- pub single_output_file: Option<Path>,
+ pub single_output_file: Option<PathBuf>,
pub extra: String,
}
impl OutputFilenames {
- pub fn path(&self, flavor: OutputType) -> Path {
+ pub fn path(&self, flavor: OutputType) -> PathBuf {
match self.single_output_file {
Some(ref path) => return path.clone(),
None => {}
self.temp_path(flavor)
}
- pub fn temp_path(&self, flavor: OutputType) -> Path {
- let base = self.out_directory.join(self.filestem());
+ pub fn temp_path(&self, flavor: OutputType) -> PathBuf {
+ let base = self.out_directory.join(&self.filestem());
match flavor {
OutputTypeBitcode => base.with_extension("bc"),
OutputTypeAssembly => base.with_extension("s"),
}
}
- pub fn with_extension(&self, extension: &str) -> Path {
- self.out_directory.join(self.filestem()).with_extension(extension)
+ pub fn with_extension(&self, extension: &str) -> PathBuf {
+ self.out_directory.join(&self.filestem()).with_extension(extension)
}
pub fn filestem(&self) -> String {
let cg = build_codegen_options(matches);
- let sysroot_opt = matches.opt_str("sysroot").map(|m| Path::new(m));
+ let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::new(&m));
let target = matches.opt_str("target").unwrap_or(
host_triple().to_string());
let opt_level = {
use rustc_back::target::Target;
+use std::path::{Path, PathBuf};
use std::cell::{Cell, RefCell};
-use std::os;
+use std::env;
pub mod config;
pub mod search_paths;
pub entry_fn: RefCell<Option<(NodeId, codemap::Span)>>,
pub entry_type: Cell<Option<config::EntryFnType>>,
pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
- pub default_sysroot: Option<Path>,
+ pub default_sysroot: Option<PathBuf>,
// The name of the root source file of the crate, in the local file system. The path is always
// expected to be absolute. `None` means that there is no source file.
- pub local_crate_source_file: Option<Path>,
- pub working_dir: Path,
+ pub local_crate_source_file: Option<PathBuf>,
+ pub working_dir: PathBuf,
pub lint_store: RefCell<lint::LintStore>,
pub lints: RefCell<NodeMap<Vec<(lint::LintId, codemap::Span, String)>>>,
pub crate_types: RefCell<Vec<config::CrateType>>,
}
pub fn build_session(sopts: config::Options,
- local_crate_source_file: Option<Path>,
+ local_crate_source_file: Option<PathBuf>,
registry: diagnostics::registry::Registry)
-> Session {
// FIXME: This is not general enough to make the warning lint completely override
}
pub fn build_session_(sopts: config::Options,
- local_crate_source_file: Option<Path>,
+ local_crate_source_file: Option<PathBuf>,
span_diagnostic: diagnostic::SpanHandler)
-> Session {
let host = match Target::search(config::host_triple()) {
if path.is_absolute() {
path.clone()
} else {
- os::getcwd().unwrap().join(&path)
+ env::current_dir().unwrap().join(&path)
}
);
plugin_registrar_fn: Cell::new(None),
default_sysroot: default_sysroot,
local_crate_source_file: local_crate_source_file,
- working_dir: os::getcwd().unwrap(),
+ working_dir: env::current_dir().unwrap(),
lint_store: RefCell::new(lint::LintStore::new()),
lints: RefCell::new(NodeMap()),
crate_types: RefCell::new(Vec::new()),
// except according to those terms.
use std::slice;
+use std::path::{Path, PathBuf};
#[derive(Clone, Debug)]
pub struct SearchPaths {
- paths: Vec<(PathKind, Path)>,
+ paths: Vec<(PathKind, PathBuf)>,
}
pub struct Iter<'a> {
kind: PathKind,
- iter: slice::Iter<'a, (PathKind, Path)>,
+ iter: slice::Iter<'a, (PathKind, PathBuf)>,
}
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
} else {
(PathKind::All, path)
};
- self.paths.push((kind, Path::new(path)));
+ self.paths.push((kind, PathBuf::new(path)));
}
pub fn iter(&self, kind: PathKind) -> Iter {
use std::cell::{RefCell, Cell};
use std::collections::HashMap;
+use std::collections::hash_state::HashState;
+use std::ffi::CString;
use std::fmt::Debug;
use std::hash::Hash;
use std::iter::repeat;
+use std::path::Path;
use std::time::Duration;
-use std::collections::hash_state::HashState;
use syntax::ast;
use syntax::visit;
}
}
}
+
+#[cfg(unix)]
+pub fn path2cstr(p: &Path) -> CString {
+ use std::os::unix::prelude::*;
+ use std::ffi::AsOsStr;
+ CString::new(p.as_os_str().as_bytes()).unwrap()
+}
+#[cfg(windows)]
+pub fn path2cstr(p: &Path) -> CString {
+ CString::new(p.to_str().unwrap()).unwrap()
+}
//! A helper class for dealing with static archives
-use std::old_io::fs::PathExtensions;
-use std::old_io::process::{Command, ProcessOutput};
-use std::old_io::{fs, TempDir};
-use std::old_io;
-use std::os;
+use std::env;
+use std::fs::{self, TempDir};
+use std::io::prelude::*;
+use std::io;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output, Stdio};
use std::str;
use syntax::diagnostic::Handler as ErrorHandler;
pub struct ArchiveConfig<'a> {
pub handler: &'a ErrorHandler,
- pub dst: Path,
- pub lib_search_paths: Vec<Path>,
+ pub dst: PathBuf,
+ pub lib_search_paths: Vec<PathBuf>,
pub slib_prefix: String,
pub slib_suffix: String,
pub maybe_ar_prog: Option<String>
pub struct Archive<'a> {
handler: &'a ErrorHandler,
- dst: Path,
- lib_search_paths: Vec<Path>,
+ dst: PathBuf,
+ lib_search_paths: Vec<PathBuf>,
slib_prefix: String,
slib_suffix: String,
maybe_ar_prog: Option<String>
archive: Archive<'a>,
work_dir: TempDir,
/// Filename of each member that should be added to the archive.
- members: Vec<Path>,
+ members: Vec<PathBuf>,
should_update_symbols: bool,
}
fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option<String>,
args: &str, cwd: Option<&Path>,
- paths: &[&Path]) -> ProcessOutput {
+ paths: &[&Path]) -> Output {
let ar = match *maybe_ar_prog {
Some(ref ar) => &ar[..],
None => "ar"
};
let mut cmd = Command::new(ar);
- cmd.arg(args).args(paths);
+ cmd.arg(args).args(paths).stdout(Stdio::piped()).stderr(Stdio::piped());
debug!("{:?}", cmd);
match cwd {
Some(p) => {
- cmd.cwd(p);
+ cmd.current_dir(p);
debug!("inside {:?}", p.display());
}
None => {}
if !o.status.success() {
handler.err(&format!("{:?} failed with: {}", cmd, o.status));
handler.note(&format!("stdout ---\n{}",
- str::from_utf8(&o.output).unwrap()));
+ str::from_utf8(&o.stdout).unwrap()));
handler.note(&format!("stderr ---\n{}",
- str::from_utf8(&o.error).unwrap())
+ str::from_utf8(&o.stderr).unwrap())
);
handler.abort_if_errors();
}
}
pub fn find_library(name: &str, osprefix: &str, ossuffix: &str,
- search_paths: &[Path], handler: &ErrorHandler) -> Path {
+ search_paths: &[PathBuf],
+ handler: &ErrorHandler) -> PathBuf {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = format!("{}{}{}", osprefix, name, ossuffix);
let unixlibname = format!("lib{}.a", name);
for path in search_paths {
- debug!("looking for {} inside {:?}", name, path.display());
+ debug!("looking for {} inside {:?}", name, path);
let test = path.join(&oslibname[..]);
if test.exists() { return test }
if oslibname != unixlibname {
/// Lists all files in an archive
pub fn files(&self) -> Vec<String> {
let output = run_ar(self.handler, &self.maybe_ar_prog, "t", None, &[&self.dst]);
- let output = str::from_utf8(&output.output).unwrap();
+ let output = str::from_utf8(&output.stdout).unwrap();
// use lines_any because windows delimits output with `\r\n` instead of
// just `\n`
output.lines_any().map(|s| s.to_string()).collect()
/// Adds all of the contents of a native library to this archive. This will
/// search in the relevant locations for a library named `name`.
- pub fn add_native_library(&mut self, name: &str) -> old_io::IoResult<()> {
+ pub fn add_native_library(&mut self, name: &str) -> io::Result<()> {
let location = find_library(name,
&self.archive.slib_prefix,
&self.archive.slib_suffix,
/// This ignores adding the bytecode from the rlib, and if LTO is enabled
/// then the object file also isn't added.
pub fn add_rlib(&mut self, rlib: &Path, name: &str,
- lto: bool) -> old_io::IoResult<()> {
+ lto: bool) -> io::Result<()> {
// Ignoring obj file starting with the crate name
// as simple comparison is not enough - there
// might be also an extra name suffix
}
/// Adds an arbitrary file to this archive
- pub fn add_file(&mut self, file: &Path) -> old_io::IoResult<()> {
- let filename = Path::new(file.filename().unwrap());
+ pub fn add_file(&mut self, file: &Path) -> io::Result<()> {
+ let filename = Path::new(file.file_name().unwrap());
let new_file = self.work_dir.path().join(&filename);
try!(fs::copy(file, &new_file));
- self.members.push(filename);
+ self.members.push(filename.to_path_buf());
Ok(())
}
pub fn build(self) -> Archive<'a> {
// Get an absolute path to the destination, so `ar` will work even
// though we run it from `self.work_dir`.
- let abs_dst = os::getcwd().unwrap().join(&self.archive.dst);
+ let abs_dst = env::current_dir().unwrap().join(&self.archive.dst);
assert!(!abs_dst.is_relative());
- let mut args = vec![&abs_dst];
- let mut total_len = abs_dst.as_vec().len();
+ let mut args = vec![&*abs_dst];
+ let mut total_len = abs_dst.to_string_lossy().len();
if self.members.is_empty() {
// OSX `ar` does not allow using `r` with no members, but it does
const ARG_LENGTH_LIMIT: uint = 32_000;
for member_name in &self.members {
- let len = member_name.as_vec().len();
+ let len = member_name.to_string_lossy().len();
// `len + 1` to account for the space that's inserted before each
// argument. (Windows passes command-line arguments as a single
args.clear();
args.push(&abs_dst);
- total_len = abs_dst.as_vec().len();
+ total_len = abs_dst.to_string_lossy().len();
}
args.push(member_name);
}
fn add_archive<F>(&mut self, archive: &Path, name: &str,
- mut skip: F) -> old_io::IoResult<()>
+ mut skip: F) -> io::Result<()>
where F: FnMut(&str) -> bool,
{
let loc = TempDir::new("rsar").unwrap();
// First, extract the contents of the archive to a temporary directory.
// We don't unpack directly into `self.work_dir` due to the possibility
// of filename collisions.
- let archive = os::getcwd().unwrap().join(archive);
+ let archive = env::current_dir().unwrap().join(archive);
run_ar(self.archive.handler, &self.archive.maybe_ar_prog,
"x", Some(loc.path()), &[&archive]);
// We skip any files explicitly desired for skipping, and we also skip
// all SYMDEF files as these are just magical placeholders which get
// re-created when we make a new archive anyway.
- let files = try!(fs::readdir(loc.path()));
- for file in &files {
- let filename = file.filename_str().unwrap();
+ let files = try!(fs::read_dir(loc.path()));
+ for file in files {
+ let file = try!(file).path();
+ let filename = file.file_name().unwrap().to_str().unwrap();
if skip(filename) { continue }
if filename.contains(".SYMDEF") { continue }
filename
};
let new_filename = self.work_dir.path().join(&filename[..]);
- try!(fs::rename(file, &new_filename));
- self.members.push(Path::new(filename));
+ try!(fs::rename(&file, &new_filename));
+ self.members.push(PathBuf::new(&filename));
}
Ok(())
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::old_io;
+use std::io;
use std::old_io::fs;
+use std::old_io;
+use std::old_path;
use std::os;
+use std::path::{Path, PathBuf};
/// Returns an absolute path in the filesystem that `path` points to. The
/// returned path does not contain any symlinks in its hierarchy.
-pub fn realpath(original: &Path) -> old_io::IoResult<Path> {
- const MAX_LINKS_FOLLOWED: uint = 256;
+#[allow(deprecated)] // readlink is deprecated
+pub fn realpath(original: &Path) -> io::Result<PathBuf> {
+ let old = old_path::Path::new(original.to_str().unwrap());
+ match old_realpath(&old) {
+ Ok(p) => Ok(PathBuf::new(p.as_str().unwrap())),
+ Err(e) => Err(io::Error::new(io::ErrorKind::Other,
+ "realpath error",
+ Some(e.to_string())))
+ }
+}
+
+#[allow(deprecated)]
+fn old_realpath(original: &old_path::Path) -> old_io::IoResult<old_path::Path> {
+ const MAX_LINKS_FOLLOWED: usize = 256;
let original = try!(os::getcwd()).join(original);
// Right now lstat on windows doesn't work quite well
mod test {
use std::old_io;
use std::old_io::fs::{File, symlink, mkdir, mkdir_recursive};
- use super::realpath;
+ use super::old_realpath as realpath;
use std::old_io::TempDir;
#[test]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
+#![feature(old_fs)]
+#![feature(fs)]
#![feature(hash)]
#![feature(int_uint)]
+#![feature(io)]
#![feature(old_io)]
-#![feature(os)]
#![feature(old_path)]
+#![feature(os)]
+#![feature(path)]
#![feature(rustc_private)]
#![feature(staged_api)]
-#![feature(path)]
+#![feature(tempdir)]
extern crate syntax;
extern crate serialize;
use std::collections::HashSet;
use std::env;
-use std::old_io::IoError;
-use std::os;
+use std::io;
+use std::path::{Path, PathBuf};
use syntax::ast;
-pub struct RPathConfig<F, G> where
- F: FnOnce() -> Path,
- G: FnMut(&Path) -> Result<Path, IoError>,
-{
- pub used_crates: Vec<(ast::CrateNum, Option<Path>)>,
- pub out_filename: Path,
+pub struct RPathConfig<'a> {
+ pub used_crates: Vec<(ast::CrateNum, Option<PathBuf>)>,
+ pub out_filename: PathBuf,
pub is_like_osx: bool,
pub has_rpath: bool,
- pub get_install_prefix_lib_path: F,
- pub realpath: G,
+ pub get_install_prefix_lib_path: &'a mut FnMut() -> PathBuf,
+ pub realpath: &'a mut FnMut(&Path) -> io::Result<PathBuf>,
}
-pub fn get_rpath_flags<F, G>(config: RPathConfig<F, G>) -> Vec<String> where
- F: FnOnce() -> Path,
- G: FnMut(&Path) -> Result<Path, IoError>,
-{
+pub fn get_rpath_flags(config: &mut RPathConfig) -> Vec<String> {
// No rpath on windows
if !config.has_rpath {
return Vec::new();
return ret;
}
-fn get_rpaths<F, G>(mut config: RPathConfig<F, G>, libs: &[Path]) -> Vec<String> where
- F: FnOnce() -> Path,
- G: FnMut(&Path) -> Result<Path, IoError>,
-{
+fn get_rpaths(config: &mut RPathConfig, libs: &[PathBuf]) -> Vec<String> {
debug!("output: {:?}", config.out_filename.display());
debug!("libs:");
for libpath in libs {
// Use relative paths to the libraries. Binaries can be moved
// as long as they maintain the relative relationship to the
// crates they depend on.
- let rel_rpaths = get_rpaths_relative_to_output(&mut config, libs);
+ let rel_rpaths = get_rpaths_relative_to_output(config, libs);
// And a final backup rpath to the global library location.
let fallback_rpaths = vec!(get_install_prefix_rpath(config));
return rpaths;
}
-fn get_rpaths_relative_to_output<F, G>(config: &mut RPathConfig<F, G>,
- libs: &[Path]) -> Vec<String> where
- F: FnOnce() -> Path,
- G: FnMut(&Path) -> Result<Path, IoError>,
-{
+fn get_rpaths_relative_to_output(config: &mut RPathConfig,
+ libs: &[PathBuf]) -> Vec<String> {
libs.iter().map(|a| get_rpath_relative_to_output(config, a)).collect()
}
-fn get_rpath_relative_to_output<F, G>(config: &mut RPathConfig<F, G>, lib: &Path) -> String where
- F: FnOnce() -> Path,
- G: FnMut(&Path) -> Result<Path, IoError>,
-{
+fn get_rpath_relative_to_output(config: &mut RPathConfig, lib: &Path) -> String {
// Mac doesn't appear to support $ORIGIN
let prefix = if config.is_like_osx {
"@loader_path"
"$ORIGIN"
};
- let cwd = os::getcwd().unwrap();
+ let cwd = env::current_dir().unwrap();
let mut lib = (config.realpath)(&cwd.join(lib)).unwrap();
lib.pop();
let mut output = (config.realpath)(&cwd.join(&config.out_filename)).unwrap();
output.pop();
- let relative = lib.path_relative_from(&output);
- let relative = relative.expect("could not create rpath relative to output");
+ let relative = relativize(&lib, &output);
// FIXME (#9639): This needs to handle non-utf8 paths
- format!("{}/{}",
- prefix,
- relative.as_str().expect("non-utf8 component in path"))
+ format!("{}/{}", prefix,
+ relative.to_str().expect("non-utf8 component in path"))
}
-fn get_install_prefix_rpath<F, G>(config: RPathConfig<F, G>) -> String where
- F: FnOnce() -> Path,
- G: FnMut(&Path) -> Result<Path, IoError>,
-{
+fn relativize(path: &Path, rel: &Path) -> PathBuf {
+ let mut res = PathBuf::new("");
+ let mut cur = rel;
+ while !path.starts_with(cur) {
+ res.push("..");
+ match cur.parent() {
+ Some(p) => cur = p,
+ None => panic!("can't create relative paths across filesystems"),
+ }
+ }
+ match path.relative_from(cur) {
+ Some(s) => { res.push(s); res }
+ None => panic!("couldn't create relative path from {:?} to {:?}",
+ rel, path),
+ }
+
+}
+
+fn get_install_prefix_rpath(config: &mut RPathConfig) -> String {
let path = (config.get_install_prefix_lib_path)();
let path = env::current_dir().unwrap().join(&path);
// FIXME (#9639): This needs to handle non-utf8 paths
mod test {
use super::{RPathConfig};
use super::{minimize_rpaths, rpaths_to_flags, get_rpath_relative_to_output};
+ use std::path::{Path, PathBuf};
#[test]
fn test_rpaths_to_flags() {
}
#[test]
- #[cfg(any(target_os = "linux", target_os = "android"))]
fn test_rpath_relative() {
- let config = &mut RPathConfig {
- used_crates: Vec::new(),
- out_filename: Path::new("bin/rustc"),
- get_install_prefix_lib_path: || panic!(),
- has_rpath: true,
- is_like_osx: false,
- realpath: |p| Ok(p.clone())
- };
- let res = get_rpath_relative_to_output(config, &Path::new("lib/libstd.so"));
- assert_eq!(res, "$ORIGIN/../lib");
- }
-
- #[test]
- #[cfg(any(target_os = "freebsd",
- target_os = "dragonfly",
- target_os = "bitrig",
- target_os = "openbsd"))]
- fn test_rpath_relative() {
- let config = &mut RPathConfig {
- used_crates: Vec::new(),
- has_rpath: true,
- is_like_osx: false,
- out_filename: Path::new("bin/rustc"),
- get_install_prefix_lib_path: || panic!(),
- realpath: |p| Ok(p.clone())
- };
- let res = get_rpath_relative_to_output(config, &Path::new("lib/libstd.so"));
- assert_eq!(res, "$ORIGIN/../lib");
- }
-
- #[test]
- #[cfg(target_os = "macos")]
- fn test_rpath_relative() {
- let config = &mut RPathConfig {
- used_crates: Vec::new(),
- has_rpath: true,
- is_like_osx: true,
- out_filename: Path::new("bin/rustc"),
- get_install_prefix_lib_path: || panic!(),
- realpath: |p| Ok(p.clone())
- };
- let res = get_rpath_relative_to_output(config, &Path::new("lib/libstd.so"));
- assert_eq!(res, "@loader_path/../lib");
+ if cfg!(target_os = "macos") {
+ let config = &mut RPathConfig {
+ used_crates: Vec::new(),
+ has_rpath: true,
+ is_like_osx: true,
+ out_filename: PathBuf::new("bin/rustc"),
+ get_install_prefix_lib_path: &mut || panic!(),
+ realpath: &mut |p| Ok(p.to_path_buf()),
+ };
+ let res = get_rpath_relative_to_output(config,
+ Path::new("lib/libstd.so"));
+ assert_eq!(res, "@loader_path/../lib");
+ } else {
+ let config = &mut RPathConfig {
+ used_crates: Vec::new(),
+ out_filename: PathBuf::new("bin/rustc"),
+ get_install_prefix_lib_path: &mut || panic!(),
+ has_rpath: true,
+ is_like_osx: false,
+ realpath: &mut |p| Ok(p.to_path_buf()),
+ };
+ let res = get_rpath_relative_to_output(config,
+ Path::new("lib/libstd.so"));
+ assert_eq!(res, "$ORIGIN/../lib");
+ }
}
}
let tests = wikipedia_tests;
- let mut sh = box Sha256::new();
+ let mut sh: Box<_> = box Sha256::new();
test_hash(&mut *sh, &tests);
}
use serialize::json::Json;
use syntax::{diagnostic, abi};
use std::default::Default;
-use std::old_io::fs::PathExtensions;
+use std::io::prelude::*;
mod windows_base;
mod linux_base;
base
}
- /// Search RUST_TARGET_PATH for a JSON file specifying the given target triple. Note that it
- /// could also just be a bare filename already, so also check for that. If one of the hardcoded
- /// targets we know about, just return it directly.
+ /// Search RUST_TARGET_PATH for a JSON file specifying the given target
+ /// triple. Note that it could also just be a bare filename already, so also
+ /// check for that. If one of the hardcoded targets we know about, just
+ /// return it directly.
///
- /// The error string could come from any of the APIs called, including filesystem access and
- /// JSON decoding.
+ /// The error string could come from any of the APIs called, including
+ /// filesystem access and JSON decoding.
pub fn search(target: &str) -> Result<Target, String> {
use std::env;
- use std::os;
use std::ffi::OsString;
- use std::old_io::File;
- use std::old_path::Path;
+ use std::fs::File;
+ use std::path::{Path, PathBuf};
use serialize::json;
fn load_file(path: &Path) -> Result<Target, String> {
- let mut f = try!(File::open(path).map_err(|e| format!("{:?}", e)));
- let obj = try!(json::from_reader(&mut f).map_err(|e| format!("{:?}", e)));
+ let mut f = try!(File::open(path).map_err(|e| e.to_string()));
+ let mut contents = Vec::new();
+ try!(f.read_to_end(&mut contents).map_err(|e| e.to_string()));
+ let obj = try!(json::from_reader(&mut &contents[..])
+ .map_err(|e| e.to_string()));
Ok(Target::from_json(obj))
}
let path = {
let mut target = target.to_string();
target.push_str(".json");
- Path::new(target)
+ PathBuf::new(&target)
};
- let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or(OsString::from_str(""));
+ let target_path = env::var_os("RUST_TARGET_PATH")
+ .unwrap_or(OsString::from_str(""));
// FIXME 16351: add a sane default search path?
- for dir in os::split_paths(target_path.to_str().unwrap()).iter() {
- let p = dir.join(path.clone());
+ for dir in env::split_paths(&target_path) {
+ let p = dir.join(&path);
if p.is_file() {
return load_file(&p);
}
use serialize::json;
use std::env;
-use std::os;
use std::ffi::OsString;
-use std::old_io::fs;
-use std::old_io;
+use std::fs;
+use std::io::{self, Write};
+use std::path::{Path, PathBuf};
use syntax::ast;
use syntax::ast_map;
use syntax::attr;
pub fn compile_input(sess: Session,
cfg: ast::CrateConfig,
input: &Input,
- outdir: &Option<Path>,
- output: &Option<Path>,
+ outdir: &Option<PathBuf>,
+ output: &Option<PathBuf>,
addl_plugins: Option<Vec<String>>,
control: CompileController) {
macro_rules! controller_entry_point{($point: ident, $make_state: expr) => ({
pub fn source_name(input: &Input) -> String {
match *input {
// FIXME (#9639): This needs to handle non-utf8 paths
- Input::File(ref ifile) => ifile.as_str().unwrap().to_string(),
+ Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
Input::Str(_) => anon_src()
}
}
impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
fn empty(input: &'a Input,
session: &'a Session,
- out_dir: &'a Option<Path>)
+ out_dir: &'a Option<PathBuf>)
-> CompileState<'a, 'ast, 'tcx> {
CompileState {
input: input,
session: session,
- out_dir: out_dir.as_ref(),
+ out_dir: out_dir.as_ref().map(|s| &**s),
cfg: None,
krate: None,
crate_name: None,
fn state_after_parse(input: &'a Input,
session: &'a Session,
- out_dir: &'a Option<Path>,
+ out_dir: &'a Option<PathBuf>,
krate: &'a ast::Crate)
-> CompileState<'a, 'ast, 'tcx> {
CompileState {
fn state_after_expand(input: &'a Input,
session: &'a Session,
- out_dir: &'a Option<Path>,
+ out_dir: &'a Option<PathBuf>,
expanded_crate: &'a ast::Crate,
crate_name: &'a str)
-> CompileState<'a, 'ast, 'tcx> {
fn state_after_write_deps(input: &'a Input,
session: &'a Session,
- out_dir: &'a Option<Path>,
+ out_dir: &'a Option<PathBuf>,
ast_map: &'a ast_map::Map<'ast>,
expanded_crate: &'a ast::Crate,
crate_name: &'a str)
fn state_after_analysis(input: &'a Input,
session: &'a Session,
- out_dir: &'a Option<Path>,
+ out_dir: &'a Option<PathBuf>,
expanded_crate: &'a ast::Crate,
analysis: &'a ty::CrateAnalysis<'tcx>,
tcx: &'a ty::ctxt<'tcx>)
fn state_after_llvm(input: &'a Input,
session: &'a Session,
- out_dir: &'a Option<Path>,
+ out_dir: &'a Option<PathBuf>,
trans: &'a trans::CrateTranslation)
-> CompileState<'a, 'ast, 'tcx> {
CompileState {
if cfg!(windows) {
_old_path = env::var_os("PATH").unwrap_or(_old_path);
let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths();
- new_path.extend(os::split_paths(_old_path.to_str().unwrap()).into_iter());
+ new_path.extend(env::split_paths(&_old_path));
env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
}
let features = sess.features.borrow();
// Remove assembly source, unless --save-temps was specified
if !sess.opts.cg.save_temps {
- fs::unlink(&outputs.temp_path(config::OutputTypeAssembly)).unwrap();
+ fs::remove_file(&outputs.temp_path(config::OutputTypeAssembly)).unwrap();
}
} else {
time(sess.time_passes(), "LLVM passes", (), |_|
outputs: &OutputFilenames) {
let old_path = env::var_os("PATH").unwrap_or(OsString::from_str(""));
let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths();
- new_path.extend(os::split_paths(old_path.to_str().unwrap()).into_iter());
+ new_path.extend(env::split_paths(&old_path));
env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
time(sess.time_passes(), "linking", (), |_|
_ => return,
};
- let result = (|| -> old_io::IoResult<()> {
+ let result = (|| -> io::Result<()> {
// Build a list of files used to compile the output and
// write Makefile-compatible dependency rules
let files: Vec<String> = sess.codemap().files.borrow()
.iter().filter(|fmap| fmap.is_real_file())
.map(|fmap| escape_dep_filename(&fmap.name))
.collect();
- let mut file = try!(old_io::File::create(&deps_filename));
+ let mut file = try!(fs::File::create(&deps_filename));
for path in &out_filenames {
- try!(write!(&mut file as &mut Writer,
- "{}: {}\n\n", path.display(), files.connect(" ")));
+ try!(write!(&mut file,
+ "{}: {}\n\n", path.display(), files.connect(" ")));
}
Ok(())
})();
}
pub fn build_output_filenames(input: &Input,
- odir: &Option<Path>,
- ofile: &Option<Path>,
+ odir: &Option<PathBuf>,
+ ofile: &Option<PathBuf>,
attrs: &[ast::Attribute],
sess: &Session)
-> OutputFilenames {
// We want to toss everything after the final '.'
let dirpath = match *odir {
Some(ref d) => d.clone(),
- None => Path::new(".")
+ None => PathBuf::new(".")
};
// If a crate name is present, we use it as the link name
sess.warn("ignoring --out-dir flag due to -o flag.");
}
OutputFilenames {
- out_directory: out_file.dir_path(),
- out_filestem: out_file.filestem_str().unwrap().to_string(),
+ out_directory: out_file.parent().unwrap().to_path_buf(),
+ out_filestem: out_file.file_stem().unwrap()
+ .to_str().unwrap().to_string(),
single_output_file: ofile,
extra: sess.opts.cg.extra_filename.clone(),
}
#![feature(old_io)]
#![feature(libc)]
#![feature(os)]
-#![feature(old_path)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]
#![feature(unicode)]
#![feature(exit_status)]
+#![feature(path)]
+#![feature(io)]
+#![feature(fs)]
extern crate arena;
extern crate flate;
use rustc::util::common::time;
use std::cmp::Ordering::Equal;
-use std::old_io::{self, stdio};
-use std::iter::repeat;
use std::env;
+use std::iter::repeat;
+use std::old_io::{self, stdio};
+use std::path::PathBuf;
use std::sync::mpsc::channel;
use std::thread;
}
// Extract output directory and file from matches.
-fn make_output(matches: &getopts::Matches) -> (Option<Path>, Option<Path>) {
- let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
- let ofile = matches.opt_str("o").map(|o| Path::new(o));
+fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
+ let odir = matches.opt_str("out-dir").map(|o| PathBuf::new(&o));
+ let ofile = matches.opt_str("o").map(|o| PathBuf::new(&o));
(odir, ofile)
}
// Extract input (string or file and optional path) from matches.
-fn make_input(free_matches: &[String]) -> Option<(Input, Option<Path>)> {
+fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
if free_matches.len() == 1 {
let ifile = &free_matches[0][..];
if ifile == "-" {
let src = String::from_utf8(contents).unwrap();
Some((Input::Str(src), None))
} else {
- Some((Input::File(Path::new(ifile)), Some(Path::new(ifile))))
+ Some((Input::File(PathBuf::new(ifile)), Some(PathBuf::new(ifile))))
}
} else {
None
&getopts::Matches,
&Session,
&Input,
- &Option<Path>,
- &Option<Path>)
+ &Option<PathBuf>,
+ &Option<PathBuf>)
-> Compilation;
// Called after we extract the input from the arguments. Gives the implementer
// an opportunity to change the inputs or to add some custom input handling.
// The default behaviour is to simply pass through the inputs.
- fn some_input(&mut self, input: Input, input_path: Option<Path>) -> (Input, Option<Path>) {
+ fn some_input(&mut self, input: Input, input_path: Option<PathBuf>)
+ -> (Input, Option<PathBuf>) {
(input, input_path)
}
fn no_input(&mut self,
&getopts::Matches,
&config::Options,
- &Option<Path>,
- &Option<Path>,
+ &Option<PathBuf>,
+ &Option<PathBuf>,
&diagnostics::registry::Registry)
- -> Option<(Input, Option<Path>)>;
+ -> Option<(Input, Option<PathBuf>)>;
// Parse pretty printing information from the arguments. The implementer can
// choose to ignore this (the default will return None) which will skip pretty
fn no_input(&mut self,
matches: &getopts::Matches,
sopts: &config::Options,
- odir: &Option<Path>,
- ofile: &Option<Path>,
+ odir: &Option<PathBuf>,
+ ofile: &Option<PathBuf>,
descriptions: &diagnostics::registry::Registry)
- -> Option<(Input, Option<Path>)> {
+ -> Option<(Input, Option<PathBuf>)> {
match matches.free.len() {
0 => {
if sopts.describe_lints {
matches: &getopts::Matches,
sess: &Session,
input: &Input,
- odir: &Option<Path>,
- ofile: &Option<Path>)
+ odir: &Option<PathBuf>,
+ ofile: &Option<PathBuf>)
-> Compilation {
RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile).and_then(
|| RustcDefaultCalls::list_metadata(sess, matches, input))
if r.contains(&("ls".to_string())) {
match input {
&Input::File(ref ifile) => {
- let mut stdout = old_io::stdout();
let path = &(*ifile);
+ let mut v = Vec::new();
metadata::loader::list_file_metadata(sess.target.target.options.is_like_osx,
path,
- &mut stdout).unwrap();
+ &mut v).unwrap();
+ println!("{}", String::from_utf8(v).unwrap());
}
&Input::Str(_) => {
early_error("cannot list metadata for stdin");
fn print_crate_info(sess: &Session,
input: Option<&Input>,
- odir: &Option<Path>,
- ofile: &Option<Path>)
+ odir: &Option<PathBuf>,
+ ofile: &Option<PathBuf>)
-> Compilation {
if sess.opts.prints.len() == 0 {
return Compilation::Continue;
style,
&id,
&t_outputs.with_extension(""));
- println!("{}", fname.filename_display());
+ println!("{}", fname.file_name().unwrap()
+ .to_string_lossy());
}
}
}
use graphviz as dot;
-use std::old_io::{self, MemReader};
+use std::fs::File;
+use std::io::{self, Write};
+use std::old_io;
use std::option;
+use std::path::PathBuf;
use std::str::FromStr;
#[derive(Copy, PartialEq, Debug)]
impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
fn pre(&self,
s: &mut pprust::State,
- node: pprust::AnnNode) -> old_io::IoResult<()> {
+ node: pprust::AnnNode) -> io::Result<()> {
match node {
pprust::NodeExpr(_) => s.popen(),
_ => Ok(())
}
fn post(&self,
s: &mut pprust::State,
- node: pprust::AnnNode) -> old_io::IoResult<()> {
+ node: pprust::AnnNode) -> io::Result<()> {
match node {
pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
fn post(&self,
s: &mut pprust::State,
- node: pprust::AnnNode) -> old_io::IoResult<()> {
+ node: pprust::AnnNode) -> io::Result<()> {
match node {
pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
try!(pp::space(&mut s.s));
impl<'tcx> pprust::PpAnn for TypedAnnotation<'tcx> {
fn pre(&self,
s: &mut pprust::State,
- node: pprust::AnnNode) -> old_io::IoResult<()> {
+ node: pprust::AnnNode) -> io::Result<()> {
match node {
pprust::NodeExpr(_) => s.popen(),
_ => Ok(())
}
fn post(&self,
s: &mut pprust::State,
- node: pprust::AnnNode) -> old_io::IoResult<()> {
+ node: pprust::AnnNode) -> io::Result<()> {
let tcx = &self.analysis.ty_cx;
match node {
pprust::NodeExpr(expr) => {
input: &Input,
ppm: PpMode,
opt_uii: Option<UserIdentifiedItem>,
- ofile: Option<Path>) {
+ ofile: Option<PathBuf>) {
let krate = driver::phase_1_parse_input(&sess, cfg, input);
let krate = if let PpmSource(PpmEveryBodyLoops) = ppm {
let src_name = driver::source_name(input);
let src = sess.codemap().get_filemap(&src_name[..])
- .src.as_bytes().to_vec();
- let mut rdr = MemReader::new(src);
+ .src
+ .as_ref()
+ .unwrap()
+ .as_bytes()
+ .to_vec();
+ let mut rdr = &src[..];
- let out = match ofile {
- None => box old_io::stdout() as Box<Writer+'static>,
- Some(p) => {
- let r = old_io::File::create(&p);
- match r {
- Ok(w) => box w as Box<Writer+'static>,
- Err(e) => panic!("print-print failed to open {} due to {}",
- p.display(), e),
- }
- }
- };
+ let mut out = Vec::new();
match (ppm, opt_uii) {
- (PpmSource(s), None) =>
+ (PpmSource(s), None) => {
+ let out: &mut Write = &mut out;
s.call_with_pp_support(
- sess, ast_map, &arenas, id, out, |annotation, out| {
+ sess, ast_map, &arenas, id, box out, |annotation, out| {
debug!("pretty printing source code {:?}", s);
let sess = annotation.sess();
pprust::print_crate(sess.codemap(),
out,
annotation.pp_ann(),
is_expanded)
- }),
+ })
+ }
- (PpmSource(s), Some(uii)) =>
+ (PpmSource(s), Some(uii)) => {
+ let out: &mut Write = &mut out;
s.call_with_pp_support(
sess, ast_map, &arenas, id, (out,uii), |annotation, (out,uii)| {
debug!("pretty printing source code {:?}", s);
sess.diagnostic(),
src_name.to_string(),
&mut rdr,
- out,
+ box out,
annotation.pp_ann(),
is_expanded);
for node_id in uii.all_matching_node_ids(ast_map) {
try!(pp::hardbreak(&mut pp_state.s));
}
pp::eof(&mut pp_state.s)
- }),
+ })
+ }
(PpmFlowGraph(mode), opt_uii) => {
debug!("pretty printing flow graph for {:?}", opt_uii);
});
let code = blocks::Code::from_node(node);
+ let out: &mut Writer = &mut out;
match code {
Some(code) => {
let variants = gather_flowgraph_variants(&sess);
}
}
}
- }.unwrap()
+ }.unwrap();
+
+ match ofile {
+ None => print!("{}", String::from_utf8(out).unwrap()),
+ Some(p) => {
+ match File::create(&p) {
+ Ok(mut w) => w.write_all(&out).unwrap(),
+ Err(e) => panic!("print-print failed to open {} due to {}",
+ p.display(), e),
+ }
+ }
+ }
}
fn print_flowgraph<W:old_io::Writer>(variants: Vec<borrowck_dot::Variant>,
analysis: ty::CrateAnalysis,
code: blocks::Code,
mode: PpFlowGraphMode,
- mut out: W) -> old_io::IoResult<()> {
+ mut out: W) -> io::Result<()> {
let ty_cx = &analysis.ty_cx;
let cfg = match code {
blocks::BlockCode(block) => cfg::CFG::new(ty_cx, &*block),
}
}
- fn expand_err_details(r: old_io::IoResult<()>) -> old_io::IoResult<()> {
+ fn expand_err_details(r: old_io::IoResult<()>) -> io::Result<()> {
r.map_err(|ioerr| {
- let orig_detail = ioerr.detail.clone();
- let m = "graphviz::render failed";
- old_io::IoError {
- detail: Some(match orig_detail {
- None => m.to_string(),
- Some(d) => format!("{}: {}", m, d)
- }),
- ..ioerr
- }
+ io::Error::new(io::ErrorKind::Other, "graphviz::render failed",
+ Some(ioerr.to_string()))
})
}
}
use std::ffi::CString;
use std::mem;
use std::raw;
+use std::path::Path;
pub struct ArchiveRO {
ptr: ArchiveRef,
/// If this archive is used with a mutable method, then an error will be
/// raised.
pub fn open(dst: &Path) -> Option<ArchiveRO> {
- unsafe {
- let s = CString::new(dst.as_vec()).unwrap();
+ return unsafe {
+ let s = path2cstr(dst);
let ar = ::LLVMRustOpenArchive(s.as_ptr());
if ar.is_null() {
None
} else {
Some(ArchiveRO { ptr: ar })
}
+ };
+
+ #[cfg(unix)]
+ fn path2cstr(p: &Path) -> CString {
+ use std::os::unix::prelude::*;
+ use std::ffi::AsOsStr;
+ CString::new(p.as_os_str().as_bytes()).unwrap()
+ }
+ #[cfg(windows)]
+ fn path2cstr(p: &Path) -> CString {
+ CString::new(p.to_str().unwrap()).unwrap()
}
}
#![feature(int_uint)]
#![feature(libc)]
#![feature(link_args)]
-#![feature(old_path)]
#![feature(staged_api)]
#![feature(std_misc)]
+#![feature(path)]
extern crate libc;
#[macro_use] #[no_link] extern crate rustc_bitflags;
use util::ppaux;
use util::sha2::{Digest, Sha256};
-use std::old_io::fs::PathExtensions;
-use std::old_io::{fs, TempDir, Command};
-use std::old_io;
+use std::ffi::{AsOsStr, OsString};
+use std::fs::{self, TempDir, PathExt};
+use std::io::{self, Read, Write};
use std::mem;
+use std::path::{Path, PathBuf};
+use std::process::Command;
use std::str;
-use std::string::String;
use flate;
use serialize::hex::ToHex;
use syntax::ast;
return validate(s.to_string(), Some(attr.span));
}
if let Input::File(ref path) = *input {
- if let Some(s) = path.filestem_str() {
+ if let Some(s) = path.file_stem().and_then(|s| s.to_str()) {
return validate(s.to_string(), None);
}
}
}
pub fn remove(sess: &Session, path: &Path) {
- match fs::unlink(path) {
+ match fs::remove_file(path) {
Ok(..) => {}
Err(e) => {
sess.err(&format!("failed to remove {}: {}",
pub fn link_binary(sess: &Session,
trans: &CrateTranslation,
outputs: &OutputFilenames,
- crate_name: &str) -> Vec<Path> {
+ crate_name: &str) -> Vec<PathBuf> {
let mut out_filenames = Vec::new();
for &crate_type in &*sess.crate_types.borrow() {
if invalid_output_for_target(sess, crate_type) {
}
fn is_writeable(p: &Path) -> bool {
- match p.stat() {
+ match p.metadata() {
Err(..) => true,
- Ok(m) => m.perm & old_io::USER_WRITE == old_io::USER_WRITE
+ Ok(m) => !m.permissions().readonly()
}
}
pub fn filename_for_input(sess: &Session,
crate_type: config::CrateType,
name: &str,
- out_filename: &Path) -> Path {
+ out_filename: &Path) -> PathBuf {
let libname = format!("{}{}", name, sess.opts.cg.extra_filename);
match crate_type {
config::CrateTypeRlib => {
- out_filename.with_filename(format!("lib{}.rlib", libname))
+ out_filename.with_file_name(&format!("lib{}.rlib", libname))
}
config::CrateTypeDylib => {
let (prefix, suffix) = (&sess.target.target.options.dll_prefix,
&sess.target.target.options.dll_suffix);
- out_filename.with_filename(format!("{}{}{}",
- prefix,
- libname,
- suffix))
+ out_filename.with_file_name(&format!("{}{}{}",
+ prefix,
+ libname,
+ suffix))
}
config::CrateTypeStaticlib => {
- out_filename.with_filename(format!("lib{}.a", libname))
+ out_filename.with_file_name(&format!("lib{}.a", libname))
}
config::CrateTypeExecutable => {
let suffix = &sess.target.target.options.exe_suffix;
- out_filename.with_filename(format!("{}{}", libname, suffix))
+ out_filename.with_file_name(&format!("{}{}", libname, suffix))
}
}
}
trans: &CrateTranslation,
crate_type: config::CrateType,
outputs: &OutputFilenames,
- crate_name: &str) -> Path {
+ crate_name: &str) -> PathBuf {
let obj_filename = outputs.temp_path(OutputTypeObject);
let out_filename = match outputs.single_output_file {
Some(ref file) => file.clone(),
out_filename
}
-fn archive_search_paths(sess: &Session) -> Vec<Path> {
+fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
let mut search = Vec::new();
sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| {
- search.push(path.clone());
+ search.push(path.to_path_buf());
FileDoesntMatch
});
return search;
let handler = &sess.diagnostic().handler;
let config = ArchiveConfig {
handler: handler,
- dst: out_filename.clone(),
+ dst: out_filename.to_path_buf(),
lib_search_paths: archive_search_paths(sess),
slib_prefix: sess.target.target.options.staticlib_prefix.clone(),
slib_suffix: sess.target.target.options.staticlib_suffix.clone(),
// the same filename for metadata (stomping over one another)
let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir");
let metadata = tmpdir.path().join(METADATA_FILENAME);
- match fs::File::create(&metadata).write_all(&trans.metadata) {
+ match fs::File::create(&metadata).and_then(|mut f| {
+ f.write_all(&trans.metadata)
+ }) {
Ok(..) => {}
Err(e) => {
sess.err(&format!("failed to write {}: {}",
let bc_deflated_filename = obj_filename.with_extension(
&format!("{}.bytecode.deflate", i));
- let bc_data = match fs::File::open(&bc_filename).read_to_end() {
- Ok(buffer) => buffer,
+ let mut bc_data = Vec::new();
+ match fs::File::open(&bc_filename).and_then(|mut f| {
+ f.read_to_end(&mut bc_data)
+ }) {
+ Ok(..) => {}
Err(e) => sess.fatal(&format!("failed to read bytecode: {}",
e))
- };
+ }
let bc_data_deflated = match flate::deflate_bytes(&bc_data[..]) {
Some(compressed) => compressed,
- None => sess.fatal(&format!("failed to compress bytecode from {}",
- bc_filename.display()))
+ None => sess.fatal(&format!("failed to compress bytecode \
+ from {}",
+ bc_filename.display()))
};
let mut bc_file_deflated = match fs::File::create(&bc_deflated_filename) {
Ok(file) => file,
Err(e) => {
- sess.fatal(&format!("failed to create compressed bytecode \
- file: {}", e))
+ sess.fatal(&format!("failed to create compressed \
+ bytecode file: {}", e))
}
};
match write_rlib_bytecode_object_v1(&mut bc_file_deflated,
- bc_data_deflated.as_slice()) {
+ &bc_data_deflated) {
Ok(()) => {}
Err(e) => {
sess.err(&format!("failed to write compressed bytecode: \
ab
}
-fn write_rlib_bytecode_object_v1<T: Writer>(writer: &mut T,
- bc_data_deflated: &[u8])
- -> ::std::old_io::IoResult<()> {
+fn write_rlib_bytecode_object_v1(writer: &mut Write,
+ bc_data_deflated: &[u8]) -> io::Result<()> {
let bc_data_deflated_size: u64 = bc_data_deflated.len() as u64;
- try! { writer.write_all(RLIB_BYTECODE_OBJECT_MAGIC) };
- try! { writer.write_le_u32(1) };
- try! { writer.write_le_u64(bc_data_deflated_size) };
- try! { writer.write_all(&bc_data_deflated[..]) };
+ try!(writer.write_all(RLIB_BYTECODE_OBJECT_MAGIC));
+ try!(writer.write_all(&[1, 0, 0, 0]));
+ try!(writer.write_all(&[
+ (bc_data_deflated_size >> 0) as u8,
+ (bc_data_deflated_size >> 8) as u8,
+ (bc_data_deflated_size >> 16) as u8,
+ (bc_data_deflated_size >> 24) as u8,
+ (bc_data_deflated_size >> 32) as u8,
+ (bc_data_deflated_size >> 40) as u8,
+ (bc_data_deflated_size >> 48) as u8,
+ (bc_data_deflated_size >> 56) as u8,
+ ]));
+ try!(writer.write_all(&bc_data_deflated));
let number_of_bytes_written_so_far =
RLIB_BYTECODE_OBJECT_MAGIC.len() + // magic id
// padding byte to make it even. This works around a crash bug in LLDB
// (see issue #15950)
if number_of_bytes_written_so_far % 2 == 1 {
- try! { writer.write_u8(0) };
+ try!(writer.write_all(&[0]));
}
return Ok(());
pname,
prog.status));
sess.note(&format!("{:?}", &cmd));
- let mut output = prog.error.clone();
- output.push_all(&prog.output);
+ let mut output = prog.stderr.clone();
+ output.push_all(&prog.stdout);
sess.note(str::from_utf8(&output[..]).unwrap());
sess.abort_if_errors();
}
- debug!("linker stderr:\n{}", String::from_utf8(prog.error).unwrap());
- debug!("linker stdout:\n{}", String::from_utf8(prog.output).unwrap());
+ debug!("linker stderr:\n{}", String::from_utf8(prog.stderr).unwrap());
+ debug!("linker stdout:\n{}", String::from_utf8(prog.stdout).unwrap());
},
Err(e) => {
sess.err(&format!("could not exec the linker `{}`: {}",
if t.options.is_like_osx {
let morestack = lib_path.join("libmorestack.a");
- let mut v = b"-Wl,-force_load,".to_vec();
- v.push_all(morestack.as_vec());
- cmd.arg(&v[..]);
+ let mut v = OsString::from_str("-Wl,-force_load,");
+ v.push_os_str(morestack.as_os_str());
+ cmd.arg(&v);
} else {
cmd.args(&["-Wl,--whole-archive", "-lmorestack", "-Wl,--no-whole-archive"]);
}
// executable. This metadata is in a separate object file from the main
// object file, so we link that in here.
if dylib {
- cmd.arg(obj_filename.with_extension("metadata.o"));
+ cmd.arg(&obj_filename.with_extension("metadata.o"));
}
if t.options.is_like_osx {
cmd.args(&["-dynamiclib", "-Wl,-dylib"]);
if sess.opts.cg.rpath {
- let mut v = "-Wl,-install_name,@rpath/".as_bytes().to_vec();
- v.push_all(out_filename.filename().unwrap());
- cmd.arg(&v[..]);
+ let mut v = OsString::from_str("-Wl,-install_name,@rpath/");
+ v.push_os_str(out_filename.file_name().unwrap());
+ cmd.arg(&v);
}
} else {
cmd.arg("-shared");
if sess.opts.cg.rpath {
let sysroot = sess.sysroot();
let target_triple = &sess.opts.target_triple;
- let get_install_prefix_lib_path = || {
+ let mut get_install_prefix_lib_path = || {
let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
- let mut path = Path::new(install_prefix);
+ let mut path = PathBuf::new(install_prefix);
path.push(&tlib);
path
};
- let rpath_config = RPathConfig {
+ let mut rpath_config = RPathConfig {
used_crates: sess.cstore.get_used_crates(cstore::RequireDynamic),
- out_filename: out_filename.clone(),
+ out_filename: out_filename.to_path_buf(),
has_rpath: sess.target.target.options.has_rpath,
is_like_osx: sess.target.target.options.is_like_osx,
- get_install_prefix_lib_path: get_install_prefix_lib_path,
- realpath: ::util::fs::realpath
+ get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
+ realpath: &mut ::util::fs::realpath
};
- cmd.args(&rpath::get_rpath_flags(rpath_config));
+ cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
}
// Finally add all the linker arguments provided on the command line along
let search_path = archive_search_paths(sess);
for l in staticlibs {
if takes_hints {
- cmd.arg(format!("-l{}", l));
+ cmd.arg(&format!("-l{}", l));
} else {
// -force_load is the OSX equivalent of --whole-archive, but it
// involves passing the full path to the library to link.
&sess.target.target.options.staticlib_suffix,
&search_path[..],
&sess.diagnostic().handler);
- let mut v = b"-Wl,-force_load,".to_vec();
- v.push_all(lib.as_vec());
- cmd.arg(&v[..]);
+ let mut v = OsString::from_str("-Wl,-force_load,");
+ v.push_os_str(lib.as_os_str());
+ cmd.arg(&v);
}
}
if takes_hints {
for &(ref l, kind) in others {
match kind {
cstore::NativeUnknown => {
- cmd.arg(format!("-l{}", l));
+ cmd.arg(&format!("-l{}", l));
}
cstore::NativeFramework => {
cmd.arg("-framework").arg(&l[..]);
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
match kind {
cstore::RequireDynamic => {
- add_dynamic_crate(cmd, sess, src.dylib.unwrap().0)
+ add_dynamic_crate(cmd, sess, &src.dylib.unwrap().0)
}
cstore::RequireStatic => {
- add_static_crate(cmd, sess, tmpdir, src.rlib.unwrap().0)
+ add_static_crate(cmd, sess, tmpdir, &src.rlib.unwrap().0)
}
}
}
// Converts a library file-stem into a cc -l argument
- fn unlib<'a>(config: &config::Config, stem: &'a [u8]) -> &'a [u8] {
- if stem.starts_with("lib".as_bytes()) && !config.target.options.is_like_windows {
+ fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
+ if stem.starts_with("lib") && !config.target.options.is_like_windows {
&stem[3..]
} else {
stem
// Adds the static "rlib" versions of all crates to the command line.
fn add_static_crate(cmd: &mut Command, sess: &Session, tmpdir: &Path,
- cratepath: Path) {
+ cratepath: &Path) {
// When performing LTO on an executable output, all of the
// bytecode from the upstream libraries has already been
// included in our object file output. We need to modify all of
// If we're not doing LTO, then our job is simply to just link
// against the archive.
if sess.lto() {
- let name = cratepath.filename_str().unwrap();
+ let name = cratepath.file_name().unwrap().to_str().unwrap();
let name = &name[3..name.len() - 5]; // chop off lib/.rlib
time(sess.time_passes(),
&format!("altering {}.rlib", name),
(), |()| {
- let dst = tmpdir.join(cratepath.filename().unwrap());
+ let dst = tmpdir.join(cratepath.file_name().unwrap());
match fs::copy(&cratepath, &dst) {
Ok(..) => {}
Err(e) => {
// Fix up permissions of the copy, as fs::copy() preserves
// permissions, but the original file may have been installed
// by a package manager and may be read-only.
- match fs::chmod(&dst, old_io::USER_READ | old_io::USER_WRITE) {
+ match fs::metadata(&dst).and_then(|m| {
+ let mut perms = m.permissions();
+ perms.set_readonly(false);
+ fs::set_permissions(&dst, perms)
+ }) {
Ok(..) => {}
Err(e) => {
sess.err(&format!("failed to chmod {} when preparing \
archive.remove_file(&format!("{}.o", name));
let files = archive.files();
if files.iter().any(|s| s.ends_with(".o")) {
- cmd.arg(dst);
+ cmd.arg(&dst);
}
});
} else {
}
// Same thing as above, but for dynamic crates instead of static crates.
- fn add_dynamic_crate(cmd: &mut Command, sess: &Session, cratepath: Path) {
+ fn add_dynamic_crate(cmd: &mut Command, sess: &Session, cratepath: &Path) {
// If we're performing LTO, then it should have been previously required
// that all upstream rust dependencies were available in an rlib format.
assert!(!sess.lto());
// Just need to tell the linker about where the library lives and
// what its name is
- let dir = cratepath.dirname();
- if !dir.is_empty() { cmd.arg("-L").arg(dir); }
-
- let mut v = "-l".as_bytes().to_vec();
- v.push_all(unlib(&sess.target, cratepath.filestem().unwrap()));
- cmd.arg(&v[..]);
+ if let Some(dir) = cratepath.parent() {
+ cmd.arg("-L").arg(dir);
+ }
+ let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
+ cmd.arg(&format!("-l{}", unlib(&sess.target, filestem)));
}
}
for &(kind, ref lib) in &libs {
match kind {
cstore::NativeUnknown => {
- cmd.arg(format!("-l{}", *lib));
+ cmd.arg(&format!("-l{}", *lib));
}
cstore::NativeFramework => {
cmd.arg("-framework");
};
let archive = ArchiveRO::open(&path).expect("wanted an rlib");
- let file = path.filename_str().unwrap();
+ let file = path.file_name().unwrap().to_str().unwrap();
let file = &file[3..file.len() - 5]; // chop off lib/.rlib
debug!("reading {}", file);
for i in iter::count(0, 1) {
use llvm::SMDiagnosticRef;
use trans::{CrateTranslation, ModuleTranslation};
use util::common::time;
+use util::common::path2cstr;
use syntax::codemap;
use syntax::diagnostic;
use syntax::diagnostic::{Emitter, Handler, Level, mk_handler};
use std::ffi::{CStr, CString};
-use std::old_io::Command;
-use std::old_io::fs;
+use std::fs;
use std::iter::Unfold;
+use std::mem;
+use std::path::Path;
+use std::process::{Command, Stdio};
use std::ptr;
use std::str;
-use std::mem;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::channel;
use std::thread;
output: &Path,
file_type: llvm::FileType) {
unsafe {
- let output_c = CString::new(output.as_vec()).unwrap();
+ let output_c = path2cstr(output);
let result = llvm::LLVMRustWriteOutputFile(
target, pm, m, output_c.as_ptr(), file_type);
if !result {
if config.emit_no_opt_bc {
let ext = format!("{}.no-opt.bc", name_extra);
let out = output_names.with_extension(&ext);
- let out = CString::new(out.as_vec()).unwrap();
+ let out = path2cstr(&out);
llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
}
if config.emit_lto_bc {
let name = format!("{}.lto.bc", name_extra);
let out = output_names.with_extension(&name);
- let out = CString::new(out.as_vec()).unwrap();
+ let out = path2cstr(&out);
llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
}
},
if config.emit_bc {
let ext = format!("{}.bc", name_extra);
let out = output_names.with_extension(&ext);
- let out = CString::new(out.as_vec()).unwrap();
+ let out = path2cstr(&out);
llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
}
if config.emit_ir {
let ext = format!("{}.ll", name_extra);
let out = output_names.with_extension(&ext);
- let out = CString::new(out.as_vec()).unwrap();
+ let out = path2cstr(&out);
with_codegen(tm, llmod, config.no_builtins, |cpm| {
llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr());
})
cmd.arg("-nostdlib");
for index in 0..trans.modules.len() {
- cmd.arg(crate_output.with_extension(&format!("{}.o", index)));
+ cmd.arg(&crate_output.with_extension(&format!("{}.o", index)));
}
- cmd.arg("-r")
- .arg("-o")
- .arg(windows_output_path.as_ref().unwrap_or(output_path));
+ cmd.arg("-r").arg("-o")
+ .arg(windows_output_path.as_ref().map(|s| &**s).unwrap_or(output_path));
cmd.args(&sess.target.target.options.post_link_args);
println!("{:?}", &cmd);
}
- cmd.stdin(::std::old_io::process::Ignored)
- .stdout(::std::old_io::process::InheritFd(1))
- .stderr(::std::old_io::process::InheritFd(2));
+ cmd.stdin(Stdio::null());
match cmd.status() {
Ok(status) => {
if !status.success() {
let pname = get_cc_prog(sess);
let mut cmd = Command::new(&pname[..]);
- cmd.arg("-c").arg("-o").arg(outputs.path(config::OutputTypeObject))
- .arg(outputs.temp_path(config::OutputTypeAssembly));
- debug!("{:?}", &cmd);
+ cmd.arg("-c").arg("-o").arg(&outputs.path(config::OutputTypeObject))
+ .arg(&outputs.temp_path(config::OutputTypeAssembly));
+ debug!("{:?}", cmd);
match cmd.output() {
Ok(prog) => {
pname,
prog.status));
sess.note(&format!("{:?}", &cmd));
- let mut note = prog.error.clone();
- note.push_all(&prog.output);
+ let mut note = prog.stderr.clone();
+ note.push_all(&prog.stdout);
sess.note(str::from_utf8(¬e[..]).unwrap());
sess.abort_if_errors();
}
#![feature(collections)]
#![feature(core)]
#![feature(int_uint)]
-#![feature(old_io)]
#![feature(libc)]
-#![feature(old_path)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]
#![feature(std_misc)]
#![feature(unicode)]
+#![feature(io)]
+#![feature(fs)]
+#![feature(path)]
+#![feature(os)]
+#![feature(tempdir)]
extern crate arena;
extern crate flate;
use middle::ty::{self, Ty};
use std::cell::Cell;
-use std::old_io::{self, File, fs};
use std::env;
+use std::fs::{self, File};
+use std::path::{Path, PathBuf};
use syntax::ast_util::{self, PostExpansionMethod};
use syntax::ast::{self, NodeId, DefId};
}
}
+#[allow(deprecated)]
pub fn process_crate(sess: &Session,
krate: &ast::Crate,
analysis: &ty::CrateAnalysis,
info!("Dumping crate {}", cratename);
// find a path to dump our data to
- let mut root_path = match env::var("DXR_RUST_TEMP_FOLDER") {
- Ok(val) => Path::new(val),
- Err(..) => match odir {
+ let mut root_path = match env::var_os("DXR_RUST_TEMP_FOLDER") {
+ Some(val) => PathBuf::new(&val),
+ None => match odir {
Some(val) => val.join("dxr"),
- None => Path::new("dxr-temp"),
+ None => PathBuf::new("dxr-temp"),
},
};
- match fs::mkdir_recursive(&root_path, old_io::USER_RWX) {
+ match fs::create_dir_all(&root_path) {
Err(e) => sess.err(&format!("Could not create directory {}: {}",
root_path.display(), e)),
_ => (),
// Create output file.
let mut out_name = cratename.clone();
out_name.push_str(".csv");
- root_path.push(out_name);
+ root_path.push(&out_name);
let output_file = match File::create(&root_path) {
Ok(f) => box f,
Err(e) => {
collected_paths: vec!(),
collecting: false,
fmt: FmtStrs::new(box Recorder {
- out: output_file as Box<Writer+'static>,
+ out: output_file,
dump_spans: false,
},
SpanUtils {
use super::escape;
use super::span_utils::SpanUtils;
-use std::vec::Vec;
+use std::io::Write;
use syntax::ast;
use syntax::ast::{NodeId,DefId};
pub struct Recorder {
// output file
- pub out: Box<Writer+'static>,
+ pub out: Box<Write+'static>,
pub dump_spans: bool,
}
}
let encode_inlined_item: encoder::EncodeInlinedItem =
- box |ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii);
+ Box::new(|ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii));
let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
let metadata = encoder::encode_metadata(encode_parms, krate);
use session::config::{self, FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
use util::nodemap::{DefIdMap, NodeMap, FnvHashMap, FnvHashSet};
use util::ppaux;
+use util::common::path2cstr;
use libc::{c_uint, c_longlong};
-use std::ffi::CString;
use std::cell::{Cell, RefCell};
+use std::ffi::CString;
+use std::path::Path;
use std::ptr;
use std::rc::{Rc, Weak};
use syntax::util::interner::Interner;
cx.sess().warn("debuginfo: Invalid path to crate's local root source file!");
fallback_path(cx)
} else {
- match abs_path.path_relative_from(work_dir) {
+ match abs_path.relative_from(work_dir) {
Some(ref p) if p.is_relative() => {
- // prepend "./" if necessary
- let dotdot = b"..";
- let prefix: &[u8] = &[dotdot[0], ::std::old_path::SEP_BYTE];
- let mut path_bytes = p.as_vec().to_vec();
-
- if &path_bytes[..2] != prefix &&
- &path_bytes[..2] != dotdot {
- path_bytes.insert(0, prefix[0]);
- path_bytes.insert(1, prefix[1]);
+ if p.starts_with(Path::new("./")) {
+ path2cstr(p)
+ } else {
+ path2cstr(&Path::new(".").join(p))
}
-
- CString::new(path_bytes).unwrap()
}
_ => fallback_path(cx)
}
(option_env!("CFG_VERSION")).expect("CFG_VERSION"));
let compile_unit_name = compile_unit_name.as_ptr();
- let work_dir = CString::new(work_dir.as_vec()).unwrap();
+ let work_dir = path2cstr(&work_dir);
let producer = CString::new(producer).unwrap();
let flags = "\0";
let split_name = "\0";
debug!("file_metadata: {}", full_path);
// FIXME (#9639): This needs to handle non-utf8 paths
- let work_dir = cx.sess().working_dir.as_str().unwrap();
+ let work_dir = cx.sess().working_dir.to_str().unwrap();
let file_name =
if full_path.starts_with(work_dir) {
&full_path[work_dir.len() + 1..full_path.len()]
let csearch_result =
csearch::maybe_get_item_ast(
ccx.tcx(), fn_id,
- box |a,b,c,d| astencode::decode_inlined_item(a, b, c, d));
+ Box::new(|a,b,c,d| astencode::decode_inlined_item(a, b, c, d)));
let inline_def = match csearch_result {
csearch::FoundAst::NotFound => {
&closure_ty.sig).0;
fcx.record_deferred_call_resolution(
def_id,
- box CallResolution {call_expr: call_expr,
- callee_expr: callee_expr,
- adjusted_ty: adjusted_ty,
- autoderefref: autoderefref,
- fn_sig: fn_sig.clone(),
- closure_def_id: def_id});
+ Box::new(CallResolution {call_expr: call_expr,
+ callee_expr: callee_expr,
+ adjusted_ty: adjusted_ty,
+ autoderefref: autoderefref,
+ fn_sig: fn_sig.clone(),
+ closure_def_id: def_id}));
return Some(CallStep::DeferredClosure(fn_sig));
}
}
use std::rc::Rc;
use std::u32;
-use std::old_path::Path as FsPath; // Conflicts with Path struct
+use std::path::PathBuf;
use core::DocContext;
use doctree;
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Crate {
pub name: String,
- pub src: FsPath,
+ pub src: PathBuf,
pub module: Option<Item>,
pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
pub primitives: Vec<PrimitiveType>,
let src = match cx.input {
Input::File(ref path) => path.clone(),
- Input::Str(_) => FsPath::new("") // FIXME: this is wrong
+ Input::Str(_) => PathBuf::new("") // FIXME: this is wrong
};
Crate {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::{old_io, str};
+use std::fs::File;
+use std::io::prelude::*;
+use std::io;
+use std::old_io;
+use std::path::{PathBuf, Path};
+use std::str;
#[derive(Clone)]
pub struct ExternalHtml{
}
}
-pub fn load_string(input: &Path) -> old_io::IoResult<Option<String>> {
- let mut f = try!(old_io::File::open(input));
- let d = try!(f.read_to_end());
+pub fn load_string(input: &Path) -> io::Result<Option<String>> {
+ let mut f = try!(File::open(input));
+ let mut d = Vec::new();
+ try!(f.read_to_end(&mut d));
Ok(str::from_utf8(&d).map(|s| s.to_string()).ok())
}
macro_rules! load_or_return {
($input: expr, $cant_read: expr, $not_utf8: expr) => {
{
- let input = Path::new($input);
+ let input = PathBuf::new($input);
match ::externalfiles::load_string(&input) {
Err(e) => {
let _ = writeln!(&mut old_io::stderr(),
#[cfg(unix)]
mod imp {
- use std::ffi::CString;
+ use std::ffi::{AsOsStr, CString};
+ use std::os::unix::prelude::*;
+ use std::path::Path;
use libc;
use std::os as stdos;
impl Lock {
pub fn new(p: &Path) -> Lock {
- let buf = CString::new(p.as_vec()).unwrap();
+ let buf = CString::new(p.as_os_str().as_bytes()).unwrap();
let fd = unsafe {
libc::open(buf.as_ptr(), libc::O_RDWR | libc::O_CREAT,
libc::S_IRWXU)
#[cfg(windows)]
mod imp {
use libc;
+ use std::ffi::AsOsStr;
use std::mem;
+ use std::os::windows::prelude::*;
use std::os;
+ use std::path::Path;
use std::ptr;
const LOCKFILE_EXCLUSIVE_LOCK: libc::DWORD = 0x00000002;
impl Lock {
pub fn new(p: &Path) -> Lock {
- let mut p_16: Vec<u16> = p.as_str().unwrap().utf16_units().collect();
+ let mut p_16: Vec<_> = p.as_os_str().encode_wide().collect();
p_16.push(0);
let handle = unsafe {
libc::CreateFileW(p_16.as_ptr(),
// except according to those terms.
use std::fmt;
-use std::old_io;
+use std::io::prelude::*;
+use std::io;
use externalfiles::ExternalHtml;
}
pub fn render<T: fmt::Display, S: fmt::Display>(
- dst: &mut old_io::Writer, layout: &Layout, page: &Page, sidebar: &S, t: &T)
- -> old_io::IoResult<()>
+ dst: &mut io::Write, layout: &Layout, page: &Page, sidebar: &S, t: &T)
+ -> io::Result<()>
{
write!(dst,
r##"<!DOCTYPE html>
)
}
-pub fn redirect(dst: &mut old_io::Writer, url: &str) -> old_io::IoResult<()> {
+pub fn redirect(dst: &mut io::Write, url: &str) -> io::Result<()> {
// <script> triggers a redirect before refresh, so this is fine.
write!(dst,
r##"<!DOCTYPE html>
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::default::Default;
+use std::ffi::OsStr;
use std::fmt;
-use std::old_io::fs::PathExtensions;
-use std::old_io::{fs, File, BufferedWriter, BufferedReader};
-use std::old_io;
+use std::fs::{self, File};
+use std::io::prelude::*;
+use std::io::{self, BufWriter, BufReader};
use std::iter::repeat;
+use std::path::{PathBuf, Path};
use std::str;
use std::sync::Arc;
pub root_path: String,
/// The path to the crate root source minus the file name.
/// Used for simplifying paths to the highlighted source code files.
- pub src_root: Path,
+ pub src_root: PathBuf,
/// The current destination folder of where HTML artifacts should be placed.
/// This changes as the context descends into the module hierarchy.
- pub dst: Path,
+ pub dst: PathBuf,
/// This describes the layout of each page, and is not modified after
/// creation of the context (contains info like the favicon and added html).
pub layout: layout::Layout,
/// Processed source-file paths
seen: HashSet<String>,
/// Root destination to place all HTML output into
- dst: Path,
+ dst: PathBuf,
}
/// Wrapper struct to render the source code of a file. This will do things like
/// Generates the documentation for `crate` into the directory `dst`
pub fn run(mut krate: clean::Crate,
external_html: &ExternalHtml,
- dst: Path,
- passes: HashSet<String>) -> old_io::IoResult<()> {
+ dst: PathBuf,
+ passes: HashSet<String>) -> io::Result<()> {
+ let src_root = match krate.src.parent() {
+ Some(p) => p.to_path_buf(),
+ None => PathBuf::new(""),
+ };
let mut cx = Context {
dst: dst,
- src_root: krate.src.dir_path(),
+ src_root: src_root,
passes: passes,
current: Vec::new(),
root_path: String::new(),
cx.krate(krate, summary)
}
-fn build_index(krate: &clean::Crate, cache: &mut Cache) -> old_io::IoResult<String> {
+fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::Result<String> {
// Build the search index from the collected metadata
let mut nodeid_to_pathid = HashMap::new();
let mut pathid_to_nodeid = Vec::new();
}
// Collect the index into a string
- let mut w = Vec::new();
+ let mut w = io::Cursor::new(Vec::new());
try!(write!(&mut w, r#"searchIndex['{}'] = {{"items":["#, krate.name));
let mut lastpath = "".to_string();
try!(write!(&mut w, "]}};"));
- Ok(String::from_utf8(w).unwrap())
+ Ok(String::from_utf8(w.into_inner()).unwrap())
}
fn write_shared(cx: &Context,
krate: &clean::Crate,
cache: &Cache,
- search_index: String) -> old_io::IoResult<()> {
+ search_index: String) -> io::Result<()> {
// Write out the shared files. Note that these are shared among all rustdoc
// docs placed in the output directory, so this needs to be a synchronized
// operation with respect to all other rustdocs running around.
include_bytes!("static/SourceCodePro-Semibold.woff")));
fn collect(path: &Path, krate: &str,
- key: &str) -> old_io::IoResult<Vec<String>> {
+ key: &str) -> io::Result<Vec<String>> {
let mut ret = Vec::new();
if path.exists() {
- for line in BufferedReader::new(File::open(path)).lines() {
+ for line in BufReader::new(try!(File::open(path))).lines() {
let line = try!(line);
if !line.starts_with(key) {
continue
mydst.push(part);
try!(mkdir(&mydst));
}
- mydst.push(format!("{}.{}.js",
- remote_item_type.to_static_str(),
- remote_path[remote_path.len() - 1]));
+ mydst.push(&format!("{}.{}.js",
+ remote_item_type.to_static_str(),
+ remote_path[remote_path.len() - 1]));
let all_implementors = try!(collect(&mydst, &krate.name,
"implementors"));
- try!(mkdir(&mydst.dir_path()));
- let mut f = BufferedWriter::new(try!(File::create(&mydst)));
+ try!(mkdir(mydst.parent().unwrap()));
+ let mut f = BufWriter::new(try!(File::create(&mydst)));
try!(writeln!(&mut f, "(function() {{var implementors = {{}};"));
for implementor in &all_implementors {
}
fn render_sources(cx: &mut Context,
- krate: clean::Crate) -> old_io::IoResult<clean::Crate> {
+ krate: clean::Crate) -> io::Result<clean::Crate> {
info!("emitting source files");
let dst = cx.dst.join("src");
try!(mkdir(&dst));
/// Writes the entire contents of a string to a destination, not attempting to
/// catch any errors.
-fn write(dst: Path, contents: &[u8]) -> old_io::IoResult<()> {
- File::create(&dst).write_all(contents)
+fn write(dst: PathBuf, contents: &[u8]) -> io::Result<()> {
+ try!(File::create(&dst)).write_all(contents)
}
/// Makes a directory on the filesystem, failing the task if an error occurs and
/// skipping if the directory already exists.
-fn mkdir(path: &Path) -> old_io::IoResult<()> {
+fn mkdir(path: &Path) -> io::Result<()> {
if !path.exists() {
- fs::mkdir(path, old_io::USER_RWX)
+ fs::create_dir(path)
} else {
Ok(())
}
/// static HTML tree.
// FIXME (#9639): The closure should deal with &[u8] instead of &str
// FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
-fn clean_srcpath<F>(src_root: &Path, src: &[u8], mut f: F) where
+fn clean_srcpath<F>(src_root: &Path, p: &Path, mut f: F) where
F: FnMut(&str),
{
- let p = Path::new(src);
-
// make it relative, if possible
- let p = p.path_relative_from(src_root).unwrap_or(p);
+ let p = p.relative_from(src_root).unwrap_or(p);
- if p.as_vec() != b"." {
- for c in p.str_components().map(|x|x.unwrap()) {
- if ".." == c {
- f("up");
- } else {
- f(c)
- }
+ for c in p.iter().map(|x| x.to_str().unwrap()) {
+ if ".." == c {
+ f("up");
+ } else {
+ f(c)
}
}
}
impl<'a> SourceCollector<'a> {
/// Renders the given filename into its corresponding HTML source file.
- fn emit_source(&mut self, filename: &str) -> old_io::IoResult<()> {
- let p = Path::new(filename);
+ fn emit_source(&mut self, filename: &str) -> io::Result<()> {
+ let p = PathBuf::new(filename);
// If we couldn't open this file, then just returns because it
// probably means that it's some standard library macro thing and we
// can't have the source to it anyway.
- let contents = match File::open(&p).read_to_end() {
+ let mut contents = Vec::new();
+ match File::open(&p).and_then(|mut f| f.read_to_end(&mut contents)) {
Ok(r) => r,
// macros from other libraries get special filenames which we can
// safely ignore
// Create the intermediate directories
let mut cur = self.dst.clone();
let mut root_path = String::from_str("../../");
- clean_srcpath(&self.cx.src_root, p.dirname(), |component| {
+ clean_srcpath(&self.cx.src_root, &p, |component| {
cur.push(component);
mkdir(&cur).unwrap();
root_path.push_str("../");
});
- let mut fname = p.filename().expect("source has no filename").to_vec();
- fname.extend(".html".bytes());
- cur.push(fname);
- let mut w = BufferedWriter::new(try!(File::create(&cur)));
+ let mut fname = p.file_name().expect("source has no filename")
+ .to_os_string();
+ fname.push_os_str(OsStr::from_str(".html"));
+ cur.push(&fname);
+ let mut w = BufWriter::new(try!(File::create(&cur)));
- let title = format!("{} -- source", cur.filename_display());
+ let title = format!("{} -- source", cur.file_name().unwrap()
+ .to_string_lossy());
let desc = format!("Source to the Rust file `{}`.", filename);
let page = layout::Page {
title: &title,
description: &desc,
keywords: get_basic_keywords(),
};
- try!(layout::render(&mut w as &mut Writer, &self.cx.layout,
+ try!(layout::render(&mut w, &self.cx.layout,
&page, &(""), &Source(contents)));
try!(w.flush());
return Ok(());
/// This currently isn't parallelized, but it'd be pretty easy to add
/// parallelization to this function.
fn krate(mut self, mut krate: clean::Crate,
- stability: stability_summary::ModuleSummary) -> old_io::IoResult<()> {
+ stability: stability_summary::ModuleSummary) -> io::Result<()> {
let mut item = match krate.module.take() {
Some(i) => i,
None => return Ok(())
// render stability dashboard
try!(self.recurse(stability.name.clone(), |this| {
let json_dst = &this.dst.join("stability.json");
- let mut json_out = BufferedWriter::new(try!(File::create(json_dst)));
+ let mut json_out = BufWriter::new(try!(File::create(json_dst)));
try!(write!(&mut json_out, "{}", json::as_json(&stability)));
let mut title = stability.name.clone();
keywords: get_basic_keywords(),
};
let html_dst = &this.dst.join("stability.html");
- let mut html_out = BufferedWriter::new(try!(File::create(html_dst)));
+ let mut html_out = BufWriter::new(try!(File::create(html_dst)));
layout::render(&mut html_out, &this.layout, &page,
&Sidebar{ cx: this, item: &item },
&stability)
/// all sub-items which need to be rendered.
///
/// The rendering driver uses this closure to queue up more work.
- fn item<F>(&mut self, item: clean::Item, mut f: F) -> old_io::IoResult<()> where
+ fn item<F>(&mut self, item: clean::Item, mut f: F) -> io::Result<()> where
F: FnMut(&mut Context, clean::Item),
{
- fn render(w: old_io::File, cx: &Context, it: &clean::Item,
- pushname: bool) -> old_io::IoResult<()> {
- info!("Rendering an item to {}", w.path().display());
+ fn render(w: File, cx: &Context, it: &clean::Item,
+ pushname: bool) -> io::Result<()> {
+ info!("Rendering an item to {}", w.path().unwrap().display());
// A little unfortunate that this is done like this, but it sure
// does make formatting *a lot* nicer.
CURRENT_LOCATION_KEY.with(|slot| {
// We have a huge number of calls to write, so try to alleviate some
// of the pain by using a buffered writer instead of invoking the
// write syscall all the time.
- let mut writer = BufferedWriter::new(w);
+ let mut writer = BufWriter::new(w);
if !cx.render_redirect_pages {
try!(layout::render(&mut writer, &cx.layout, &page,
&Sidebar{ cx: cx, item: it },
// Things which don't have names (like impls) don't get special
// pages dedicated to them.
_ if item.name.is_some() => {
- let dst = self.dst.join(item_path(&item));
+ let dst = self.dst.join(&item_path(&item));
let dst = try!(File::create(&dst));
render(dst, self, &item, true)
}
// has anchors for the line numbers that we're linking to.
if ast_util::is_local(self.item.def_id) {
let mut path = Vec::new();
- clean_srcpath(&cx.src_root, self.item.source.filename.as_bytes(),
+ clean_srcpath(&cx.src_root, Path::new(&self.item.source.filename),
|component| {
path.push(component.to_string());
});
#![feature(test)]
#![feature(unicode)]
#![feature(str_words)]
+#![feature(io)]
+#![feature(fs)]
+#![feature(path)]
+#![feature(tempdir)]
extern crate arena;
extern crate getopts;
use std::cell::RefCell;
use std::collections::HashMap;
use std::env;
-use std::old_io::File;
-use std::old_io;
+use std::fs::File;
+use std::io::{self, Read, Write};
+use std::path::PathBuf;
use std::rc::Rc;
use std::sync::mpsc::channel;
+
use externalfiles::ExternalHtml;
use serialize::Decodable;
use serialize::json::{self, Json};
let should_test = matches.opt_present("test");
let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
- let output = matches.opt_str("o").map(|s| Path::new(s));
+ let output = matches.opt_str("o").map(|s| PathBuf::new(&s));
let cfgs = matches.opt_strs("cfg");
let external_html = match ExternalHtml::load(
(true, false) => {
return test::run(input, cfgs, libs, externs, test_args, crate_name)
}
- (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
+ (false, true) => return markdown::render(input,
+ output.unwrap_or(PathBuf::new("doc")),
&matches, &external_html,
!matches.opt_present("markdown-no-toc")),
(false, false) => {}
info!("going to format");
match matches.opt_str("w").as_ref().map(|s| &**s) {
Some("html") | None => {
- match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc")),
+ match html::render::run(krate, &external_html,
+ output.unwrap_or(PathBuf::new("doc")),
passes.into_iter().collect()) {
Ok(()) => {}
Err(e) => panic!("failed to generate documentation: {}", e),
}
Some("json") => {
match json_output(krate, json_plugins,
- output.unwrap_or(Path::new("doc.json"))) {
+ output.unwrap_or(PathBuf::new("doc.json"))) {
Ok(()) => {}
Err(e) => panic!("failed to write json: {}", e),
}
let cfgs = matches.opt_strs("cfg");
let triple = matches.opt_str("target");
- let cr = Path::new(cratefile);
+ let cr = PathBuf::new(cratefile);
info!("starting to run rustc");
let (tx, rx) = channel();
std::thread::spawn(move || {
use rustc::session::config::Input;
- let cr = cr;
- tx.send(core::run_core(paths, cfgs, externs, Input::File(cr), triple)).unwrap();
+ tx.send(core::run_core(paths, cfgs, externs, Input::File(cr),
+ triple)).unwrap();
}).join().map_err(|_| "rustc failed").unwrap();
let (mut krate, analysis) = rx.recv().unwrap();
info!("finished with rustc");
/// This input format purely deserializes the json output file. No passes are
/// run over the deserialized output.
fn json_input(input: &str) -> Result<Output, String> {
- let mut input = match File::open(&Path::new(input)) {
- Ok(f) => f,
- Err(e) => {
- return Err(format!("couldn't open {}: {}", input, e))
- }
+ let mut bytes = Vec::new();
+ match File::open(input).and_then(|mut f| f.read_to_end(&mut bytes)) {
+ Ok(()) => {}
+ Err(e) => return Err(format!("couldn't open {}: {}", input, e)),
};
- match json::from_reader(&mut input) {
+ match json::from_reader(&mut &bytes[..]) {
Err(s) => Err(format!("{:?}", s)),
Ok(Json::Object(obj)) => {
let mut obj = obj;
/// Outputs the crate/plugin json as a giant json blob at the specified
/// destination.
fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
- dst: Path) -> old_io::IoResult<()> {
+ dst: PathBuf) -> io::Result<()> {
// {
// "schema": version,
// "crate": { parsed crate ... },
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+use std::fs::File;
+use std::io::Write;
use std::old_io;
+use std::path::{PathBuf, Path};
use core;
use getopts;
/// Render `input` (e.g. "foo.md") into an HTML file in `output`
/// (e.g. output = "bar" => "bar/foo.html").
-pub fn render(input: &str, mut output: Path, matches: &getopts::Matches,
+pub fn render(input: &str, mut output: PathBuf, matches: &getopts::Matches,
external_html: &ExternalHtml, include_toc: bool) -> int {
let input_p = Path::new(input);
- output.push(input_p.filestem().unwrap());
+ output.push(input_p.file_stem().unwrap());
output.set_extension("html");
let mut css = String::new();
}
let playground = playground.unwrap_or("".to_string());
- let mut out = match old_io::File::create(&output) {
+ let mut out = match File::create(&output) {
Err(e) => {
let _ = writeln!(&mut old_io::stderr(),
"error opening `{}` for writing: {}",
// except according to those terms.
use std::cell::RefCell;
-use std::sync::mpsc::channel;
+use std::collections::{HashSet, HashMap};
use std::dynamic_lib::DynamicLibrary;
-use std::old_io::{Command, TempDir};
+use std::env;
+use std::ffi::OsString;
+use std::fs::TempDir;
use std::old_io;
-use std::os;
+use std::io;
+use std::path::PathBuf;
+use std::process::Command;
use std::str;
+use std::sync::mpsc::channel;
use std::thread;
use std::thunk::Thunk;
-use std::collections::{HashSet, HashMap};
use testing;
use rustc_lint;
use rustc::session::{self, config};
mut test_args: Vec<String>,
crate_name: Option<String>)
-> int {
- let input_path = Path::new(input);
+ let input_path = PathBuf::new(input);
let input = config::Input::File(input_path.clone());
let sessopts = config::Options {
- maybe_sysroot: Some(os::self_exe_name().unwrap().dir_path().dir_path()),
+ maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
+ .parent().unwrap().to_path_buf()),
search_paths: libs.clone(),
crate_types: vec!(config::CrateTypeDylib),
externs: externs.clone(),
let input = config::Input::Str(test.to_string());
let sessopts = config::Options {
- maybe_sysroot: Some(os::self_exe_name().unwrap().dir_path().dir_path()),
+ maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
+ .parent().unwrap().to_path_buf()),
search_paths: libs,
crate_types: vec!(config::CrateTypeExecutable),
output_types: vec!(config::OutputTypeExe),
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
- let out = Some(outdir.path().clone());
+ let out = Some(outdir.path().to_path_buf());
let cfg = config::build_configuration(&sess);
let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
let mut control = driver::CompileController::basic();
// environment to ensure that the target loads the right libraries at
// runtime. It would be a sad day if the *host* libraries were loaded as a
// mistake.
- let mut cmd = Command::new(outdir.path().join("rust-out"));
+ let mut cmd = Command::new(&outdir.path().join("rust-out"));
+ let var = DynamicLibrary::envvar();
let newpath = {
- let mut path = DynamicLibrary::search_path();
+ let path = env::var_os(var).unwrap_or(OsString::new());
+ let mut path = env::split_paths(&path).collect::<Vec<_>>();
path.insert(0, libdir.clone());
- DynamicLibrary::create_path(&path)
+ env::join_paths(path.iter()).unwrap()
};
- cmd.env(DynamicLibrary::envvar(), newpath);
+ cmd.env(var, &newpath);
match cmd.output() {
Err(e) => panic!("couldn't run the test: {}{}", e,
- if e.kind == old_io::PermissionDenied {
+ if e.kind() == io::ErrorKind::PermissionDenied {
" - maybe your tempdir is mounted with noexec?"
} else { "" }),
Ok(out) => {
panic!("test executable succeeded when it should have failed");
} else if !should_fail && !out.status.success() {
panic!("test executable failed:\n{:?}",
- str::from_utf8(&out.error));
+ str::from_utf8(&out.stdout));
}
}
}
#![feature(staged_api)]
#![feature(std_misc)]
#![feature(unicode)]
+#![feature(path)]
#![cfg_attr(test, feature(test))]
// test harness access
*/
use std::old_path;
+use std::path;
use std::rc::Rc;
use std::cell::{Cell, RefCell};
use std::sync::Arc;
}
}
+impl Encodable for path::PathBuf {
+ fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
+ self.to_str().unwrap().encode(e)
+ }
+}
+
+impl Decodable for path::PathBuf {
+ fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
+ let bytes: String = try!(Decodable::decode(d));
+ Ok(path::PathBuf::new(&bytes))
+ }
+}
+
impl<T: Encodable + Copy> Encodable for Cell<T> {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
self.get().encode(s)
use prelude::v1::*;
use super::*;
use libc;
- use mem;
#[test]
fn c_to_rust() {
let data = b"123\0";
let ptr = data.as_ptr() as *const libc::c_char;
unsafe {
- assert_eq!(c_str_to_bytes(&ptr), b"123");
- assert_eq!(c_str_to_bytes_with_nul(&ptr), b"123\0");
+ assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
+ assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
}
}
struct R;
impl Read for R {
- fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+ fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Err(io::Error::new(io::ErrorKind::Other, "", None))
}
}
#![feature(hash)]
#![feature(int_uint)]
#![feature(unique)]
-#![cfg_attr(test, feature(test, rustc_private, env))]
+#![cfg_attr(test, feature(test, rustc_private))]
// Don't link to std. We are std.
#![feature(no_std)]
/// attempted against it for which its underlying file descriptor was not
/// configured at creation time, via the `FileAccess` parameter to
/// `File::open_mode()`.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::File")]
+#[unstable(feature = "old_io")]
pub struct File {
fd: fs_imp::FileDesc,
path: Path,
}
}
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+#[unstable(feature = "old_io")]
impl File {
/// Open a file at `path` in the mode specified by the `mode` and `access`
/// arguments
/// * Attempting to open a file with a `FileAccess` that the user lacks
/// permissions for
/// * Filesystem-level errors (full disk, etc)
+ #[deprecated(since = "1.0.0", reason = "replaced with std::fs::OpenOptions")]
+ #[unstable(feature = "old_io")]
pub fn open_mode(path: &Path,
mode: FileMode,
access: FileAccess) -> IoResult<File> {
///
/// let contents = File::open(&Path::new("foo.txt")).read_to_end();
/// ```
+ #[deprecated(since = "1.0.0", reason = "replaced with std::fs::File::open")]
+ #[unstable(feature = "old_io")]
pub fn open(path: &Path) -> IoResult<File> {
File::open_mode(path, Open, Read)
}
/// # drop(f);
/// # ::std::old_io::fs::unlink(&Path::new("foo.txt"));
/// ```
+ #[deprecated(since = "1.0.0", reason = "replaced with std::fs::File::create")]
+ #[unstable(feature = "old_io")]
pub fn create(path: &Path) -> IoResult<File> {
File::open_mode(path, Truncate, Write)
.update_desc("couldn't create file")
}
/// Returns the original path that was used to open this file.
+ #[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+ #[unstable(feature = "old_io")]
pub fn path<'a>(&'a self) -> &'a Path {
&self.path
}
/// Synchronizes all modifications to this file to its permanent storage
/// device. This will flush any internal buffers necessary to perform this
/// operation.
+ #[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+ #[unstable(feature = "old_io")]
pub fn fsync(&mut self) -> IoResult<()> {
self.fd.fsync()
.update_err("couldn't fsync file",
/// file metadata to the filesystem. This is intended for use cases that
/// must synchronize content, but don't need the metadata on disk. The goal
/// of this method is to reduce disk operations.
+ #[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+ #[unstable(feature = "old_io")]
pub fn datasync(&mut self) -> IoResult<()> {
self.fd.datasync()
.update_err("couldn't datasync file",
/// be shrunk. If it is greater than the current file's size, then the file
/// will be extended to `size` and have all of the intermediate data filled
/// in with 0s.
+ #[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+ #[unstable(feature = "old_io")]
pub fn truncate(&mut self, size: i64) -> IoResult<()> {
self.fd.truncate(size)
.update_err("couldn't truncate file", |e|
/// until you have attempted to read past the end of the file, so if
/// you've read _exactly_ the number of bytes in the file, this will
/// return `false`, not `true`.
+ #[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+ #[unstable(feature = "old_io")]
pub fn eof(&self) -> bool {
self.last_nread == 0
}
/// Queries information about the underlying file.
+ #[deprecated(since = "1.0.0", reason = "replaced with std::fs")]
+ #[unstable(feature = "old_io")]
pub fn stat(&self) -> IoResult<FileStat> {
self.fd.fstat()
.update_err("couldn't fstat file", |e|
/// This function will return an error if `path` points to a directory, if the
/// user lacks permissions to remove the file, or if some other filesystem-level
/// error occurs.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::remove_file")]
+#[unstable(feature = "old_io")]
pub fn unlink(path: &Path) -> IoResult<()> {
fs_imp::unlink(path)
.update_err("couldn't unlink path", |e|
/// This function will return an error if the user lacks the requisite permissions
/// to perform a `stat` call on the given `path` or if there is no entry in the
/// filesystem at the provided path.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::metadata")]
+#[unstable(feature = "old_io")]
pub fn stat(path: &Path) -> IoResult<FileStat> {
fs_imp::stat(path)
.update_err("couldn't stat path", |e|
/// # Error
///
/// See `stat`
+#[unstable(feature = "old_fs")]
pub fn lstat(path: &Path) -> IoResult<FileStat> {
fs_imp::lstat(path)
.update_err("couldn't lstat path", |e|
/// This function will return an error if the provided `from` doesn't exist, if
/// the process lacks permissions to view the contents, or if some other
/// intermittent I/O error occurs.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::rename")]
+#[unstable(feature = "old_io")]
pub fn rename(from: &Path, to: &Path) -> IoResult<()> {
fs_imp::rename(from, to)
.update_err("couldn't rename path", |e|
/// Note that this copy is not atomic in that once the destination is
/// ensured to not exist, there is nothing preventing the destination from
/// being created and then destroyed by this operation.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::copy")]
+#[unstable(feature = "old_io")]
pub fn copy(from: &Path, to: &Path) -> IoResult<()> {
fn update_err<T>(result: IoResult<T>, from: &Path, to: &Path) -> IoResult<T> {
result.update_err("couldn't copy path", |e| {
/// This function will return an error if the provided `path` doesn't exist, if
/// the process lacks permissions to change the attributes of the file, or if
/// some other I/O error is encountered.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::set_permissions")]
+#[unstable(feature = "old_io")]
pub fn chmod(path: &Path, mode: old_io::FilePermission) -> IoResult<()> {
fs_imp::chmod(path, mode.bits() as uint)
.update_err("couldn't chmod path", |e|
}
/// Change the user and group owners of a file at the specified path.
+#[unstable(feature = "old_fs")]
pub fn chown(path: &Path, uid: int, gid: int) -> IoResult<()> {
fs_imp::chown(path, uid, gid)
.update_err("couldn't chown path", |e|
/// Creates a new hard link on the filesystem. The `dst` path will be a
/// link pointing to the `src` path. Note that systems often require these
/// two paths to both be located on the same filesystem.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::hard_link")]
+#[unstable(feature = "old_io")]
pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
fs_imp::link(src, dst)
.update_err("couldn't link path", |e|
/// Creates a new symbolic link on the filesystem. The `dst` path will be a
/// symlink pointing to the `src` path.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::soft_link")]
+#[unstable(feature = "old_io")]
pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
fs_imp::symlink(src, dst)
.update_err("couldn't symlink path", |e|
///
/// This function will return an error on failure. Failure conditions include
/// reading a file that does not exist or reading a file that is not a symlink.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::read_link")]
+#[unstable(feature = "old_io")]
pub fn readlink(path: &Path) -> IoResult<Path> {
fs_imp::readlink(path)
.update_err("couldn't resolve symlink for path", |e|
///
/// This function will return an error if the user lacks permissions to make a
/// new directory at the provided `path`, or if the directory already exists.
+#[unstable(feature = "old_fs")]
pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> {
fs_imp::mkdir(path, mode.bits() as uint)
.update_err("couldn't create directory", |e|
///
/// This function will return an error if the user lacks permissions to remove
/// the directory at the provided `path`, or if the directory isn't empty.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::remove_dir")]
+#[unstable(feature = "old_io")]
pub fn rmdir(path: &Path) -> IoResult<()> {
fs_imp::rmdir(path)
.update_err("couldn't remove directory", |e|
/// This function will return an error if the provided `path` doesn't exist, if
/// the process lacks permissions to view the contents or if the `path` points
/// at a non-directory file
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::read_dir")]
+#[unstable(feature = "old_io")]
pub fn readdir(path: &Path) -> IoResult<Vec<Path>> {
fs_imp::readdir(path)
.update_err("couldn't read directory",
/// rooted at `path`. The path given will not be iterated over, and this will
/// perform iteration in some top-down order. The contents of unreadable
/// subdirectories are ignored.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::walk_dir")]
+#[unstable(feature = "old_io")]
pub fn walk_dir(path: &Path) -> IoResult<Directories> {
Ok(Directories {
stack: try!(readdir(path).update_err("couldn't walk directory",
/// An iterator that walks over a directory
#[derive(Clone)]
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::ReadDir")]
+#[unstable(feature = "old_io")]
pub struct Directories {
stack: Vec<Path>,
}
/// # Error
///
/// See `fs::mkdir`.
+#[unstable(feature = "old_fs")]
pub fn mkdir_recursive(path: &Path, mode: FilePermission) -> IoResult<()> {
// tjc: if directory exists but with different permissions,
// should we return false?
/// # Error
///
/// See `file::unlink` and `fs::readdir`
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::remove_dir_all")]
+#[unstable(feature = "old_io")]
pub fn rmdir_recursive(path: &Path) -> IoResult<()> {
let mut rm_stack = Vec::new();
rm_stack.push(path.clone());
/// `atime` and its modification time set to `mtime`. The times specified should
/// be in milliseconds.
// FIXME(#10301) these arguments should not be u64
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::set_file_times")]
+#[unstable(feature = "old_io")]
pub fn change_file_times(path: &Path, atime: u64, mtime: u64) -> IoResult<()> {
fs_imp::utime(path, atime, mtime)
.update_err("couldn't change_file_times", |e|
}
/// Utility methods for paths.
+#[deprecated(since = "1.0.0", reason = "replaced with std::fs::PathExt")]
+#[unstable(feature = "old_io")]
pub trait PathExtensions {
/// Get information on the file, directory, etc at this path.
///
}
fn read_ip_addr(&mut self) -> Option<IpAddr> {
- let ipv4_addr = |p: &mut Parser| p.read_ipv4_addr();
- let ipv6_addr = |p: &mut Parser| p.read_ipv6_addr();
- self.read_or(&mut [box ipv4_addr, box ipv6_addr])
+ let ipv4_addr: Box<_> = box |p: &mut Parser| p.read_ipv4_addr();
+ let ipv6_addr: Box<_> = box |p: &mut Parser| p.read_ipv6_addr();
+ self.read_or(&mut [ipv4_addr, ipv6_addr])
}
fn read_socket_addr(&mut self) -> Option<SocketAddr> {
let ip_addr = |p: &mut Parser| {
- let ipv4_p = |p: &mut Parser| p.read_ip_addr();
- let ipv6_p = |p: &mut Parser| {
+ let ipv4_p: Box<_> = box |p: &mut Parser| p.read_ip_addr();
+ let ipv6_p: Box<_> = box |p: &mut Parser| {
let open_br = |p: &mut Parser| p.read_given_char('[');
let ip_addr = |p: &mut Parser| p.read_ipv6_addr();
let clos_br = |p: &mut Parser| p.read_given_char(']');
p.read_seq_3::<char, IpAddr, char, _, _, _>(open_br, ip_addr, clos_br)
.map(|t| match t { (_, ip, _) => ip })
};
- p.read_or(&mut [box ipv4_p, box ipv6_p])
+ p.read_or(&mut [ipv4_p, ipv6_p])
};
let colon = |p: &mut Parser| p.read_given_char(':');
let port = |p: &mut Parser| p.read_number(10, 5, 0x10000).map(|n| n as u16);
let (tx, rx) = channel();
let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx));
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let _t = thread::spawn(move|| {
- set_stdout(box w);
+ set_stdout(Box::new(w));
println!("hello!");
});
assert_eq!(r.read_to_string().unwrap(), "hello!\n");
let (tx, rx) = channel();
let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx));
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let _t = thread::spawn(move || -> () {
- set_stderr(box w);
+ set_stderr(Box::new(w));
panic!("my special message");
});
let s = r.read_to_string().unwrap();
// FIXME: These functions take Durations but only pass ms to the backend impls.
+use boxed::Box;
use sync::mpsc::{Receiver, Sender, channel};
use time::Duration;
use old_io::IoResult;
let (tx, rx) = channel();
// Short-circuit the timer backend for 0 duration
if in_ms_u64(duration) != 0 {
- self.inner.oneshot(in_ms_u64(duration), box TimerCallback { tx: tx });
+ self.inner.oneshot(in_ms_u64(duration), Box::new(TimerCallback { tx: tx }));
} else {
tx.send(()).unwrap();
}
// not clear what use a 0ms period is anyway...
let ms = if ms == 0 { 1 } else { ms };
let (tx, rx) = channel();
- self.inner.period(ms, box TimerCallback { tx: tx });
+ self.inner.period(ms, Box::new(TimerCallback { tx: tx }));
return rx
}
}
#[cfg(not(target_os="android"))]
#[test]
fn test_inherit_env() {
- use os;
+ use std::env;
if running_on_valgrind() { return; }
let result = env_cmd().output().unwrap();
let output = String::from_utf8(result.stdout).unwrap();
- let r = os::env();
- for &(ref k, ref v) in &r {
+ for (ref k, ref v) in env::vars() {
// don't check windows magical empty-named variables
assert!(k.is_empty() ||
output.contains(format!("{}={}", *k, *v).as_slice()),
rtdebug!("begin_unwind()");
unsafe {
- let exception = box Exception {
+ let exception: Box<_> = box Exception {
uwe: uw::_Unwind_Exception {
exception_class: rust_exception_class(),
exception_cleanup: exception_cleanup,
let mut s = String::new();
let _ = write!(&mut s, "{}", msg);
- begin_unwind_inner(box s, file_line)
+ begin_unwind_inner(Box::new(s), file_line)
}
/// This is the entry point of unwinding for panic!() and assert!().
// panicking.
// see below for why we do the `Any` coercion here.
- begin_unwind_inner(box msg, file_line)
+ begin_unwind_inner(Box::new(msg), file_line)
}
/// The core of the unwinding.
#[test]
fn drop_full() {
- let (tx, _rx) = channel();
+ let (tx, _rx) = channel::<Box<int>>();
tx.send(box 1).unwrap();
}
#[test]
fn drop_full_shared() {
- let (tx, _rx) = channel();
+ let (tx, _rx) = channel::<Box<int>>();
drop(tx.clone());
drop(tx.clone());
tx.send(box 1).unwrap();
#[test]
fn oneshot_multi_thread_send_recv_stress() {
for _ in 0..stress_factor() {
- let (tx, rx) = channel();
+ let (tx, rx) = channel::<Box<int>>();
let _t = thread::spawn(move|| {
tx.send(box 10).unwrap();
});
#[test]
fn drop_full() {
- let (tx, _rx) = sync_channel(1);
+ let (tx, _rx) = sync_channel::<Box<int>>(1);
tx.send(box 1).unwrap();
}
#[test]
fn test_full() {
- let q = Queue::new();
+ let q: Queue<Box<_>> = Queue::new();
q.push(box 1);
q.push(box 2);
}
#[test]
fn drop_full() {
unsafe {
- let q = Queue::new(0);
+ let q: Queue<Box<_>> = Queue::new(0);
q.push(box 1);
q.push(box 2);
}
fn as_raw_fd(&self) -> Fd;
}
+#[allow(deprecated)]
impl AsRawFd for old_io::fs::File {
fn as_raw_fd(&self) -> Fd {
self.as_inner().fd()
fn as_raw_handle(&self) -> Handle;
}
+#[allow(deprecated)]
impl AsRawHandle for old_io::fs::File {
fn as_raw_handle(&self) -> Handle {
self.as_inner().handle()
use libc::{pid_t, c_void};
use libc;
use mem;
-use old_io::fs::PathExtensions;
+#[allow(deprecated)] use old_io::fs::PathExtensions;
use old_io::process::{ProcessExit, ExitStatus};
use old_io::{IoResult, IoError};
use old_io;
fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Thunk<'static>) {
let (tx, rx) = channel();
- let x = box 1;
+ let x: Box<_> = box 1;
let x_in_parent = (&*x) as *const i32 as usize;
spawnfn(Thunk::new(move|| {
where F : FnOnce(A) -> R, F : Send + 'a
{
Thunk {
- invoke: box func
+ invoke: Box::<F>::new(func)
}
}
use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
use abi::Abi;
use ast_util;
+use ext::base;
+use ext::tt::macro_parser;
use owned_slice::OwnedSlice;
use parse::token::{InternedString, str_to_ident};
use parse::token;
+use parse::lexer;
use ptr::P;
use std::fmt;
TtSequence(span, _) => span,
}
}
+
+ /// Use this token tree as a matcher to parse given tts.
+ pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
+ -> macro_parser::NamedParseResult {
+ // `None` is because we're not interpolating
+ let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
+ None,
+ None,
+ tts.iter().cloned().collect(),
+ true);
+ macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
+ }
}
pub type Mac = Spanned<Mac_>;
use arena::TypedArena;
use std::cell::RefCell;
use std::fmt;
-use std::old_io::IoResult;
+use std::io;
use std::iter::{self, repeat};
use std::mem;
use std::slice;
}
pub trait NodePrinter {
- fn print_node(&mut self, node: &Node) -> IoResult<()>;
+ fn print_node(&mut self, node: &Node) -> io::Result<()>;
}
impl<'a> NodePrinter for pprust::State<'a> {
- fn print_node(&mut self, node: &Node) -> IoResult<()> {
+ fn print_node(&mut self, node: &Node) -> io::Result<()> {
match *node {
NodeItem(a) => self.print_item(&*a),
NodeForeignItem(a) => self.print_foreign_item(&*a),
use libc::c_uint;
use serialize::{Encodable, Decodable, Encoder, Decoder};
+
+// _____________________________________________________________________________
+// Pos, BytePos, CharPos
+//
+
pub trait Pos {
fn from_usize(n: usize) -> Self;
fn to_usize(&self) -> usize;
}
}
+impl Encodable for BytePos {
+ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
+ s.emit_u32(self.0)
+ }
+}
+
+impl Decodable for BytePos {
+ fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
+ Ok(BytePos(try!{ d.read_u32() }))
+ }
+}
+
impl Pos for CharPos {
fn from_usize(n: usize) -> CharPos { CharPos(n) }
fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
}
}
+// _____________________________________________________________________________
+// Span, Spanned
+//
+
/// Spans represent a region of code, used for error reporting. Positions in spans
/// are *absolute* positions from the beginning of the codemap, not positions
/// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
impl Eq for Span {}
impl Encodable for Span {
- /* Note #1972 -- spans are encoded but not decoded */
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
- s.emit_nil()
+ // Encode spans as a single u64 in order to cut down on tagging overhead
+ // added by the RBML metadata encoding. The should be solved differently
+ // altogether some time (FIXME #21482)
+ s.emit_u64( (self.lo.0 as u64) | ((self.hi.0 as u64) << 32) )
}
}
impl Decodable for Span {
- fn decode<D: Decoder>(_d: &mut D) -> Result<Span, D::Error> {
- Ok(DUMMY_SP)
+ fn decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
+ let lo_hi: u64 = try! { d.read_u64() };
+ let lo = BytePos(lo_hi as u32);
+ let hi = BytePos((lo_hi >> 32) as u32);
+ Ok(mk_sp(lo, hi))
}
}
}
}
+// _____________________________________________________________________________
+// Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
+//
+
/// A source code location used for error reporting
pub struct Loc {
/// Information about the original source
pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
+
+// _____________________________________________________________________________
+// MacroFormat, NameAndSpan, ExpnInfo, ExpnId
+//
+
/// The syntax with which a macro was invoked.
#[derive(Clone, Copy, Hash, Debug)]
pub enum MacroFormat {
}
}
+// _____________________________________________________________________________
+// FileMap, MultiByteChar, FileName, FileLines
+//
+
pub type FileName = String;
pub struct FileLines {
}
/// Identifies an offset of a multi-byte character in a FileMap
-#[derive(Copy)]
+#[derive(Copy, RustcEncodable, RustcDecodable, Eq, PartialEq)]
pub struct MultiByteChar {
/// The absolute offset of the character in the CodeMap
pub pos: BytePos,
/// e.g. `<anon>`
pub name: FileName,
/// The complete source code
- pub src: String,
+ pub src: Option<Rc<String>>,
/// The start position of this source in the CodeMap
pub start_pos: BytePos,
+ /// The end position of this source in the CodeMap
+ pub end_pos: BytePos,
/// Locations of lines beginnings in the source code
- pub lines: RefCell<Vec<BytePos> >,
+ pub lines: RefCell<Vec<BytePos>>,
/// Locations of multi-byte characters in the source code
- pub multibyte_chars: RefCell<Vec<MultiByteChar> >,
+ pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
+}
+
+impl Encodable for FileMap {
+ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
+ s.emit_struct("FileMap", 5, |s| {
+ try! { s.emit_struct_field("name", 0, |s| self.name.encode(s)) };
+ try! { s.emit_struct_field("start_pos", 1, |s| self.start_pos.encode(s)) };
+ try! { s.emit_struct_field("end_pos", 2, |s| self.end_pos.encode(s)) };
+ try! { s.emit_struct_field("lines", 3, |s| {
+ let lines = self.lines.borrow();
+ // store the length
+ try! { s.emit_u32(lines.len() as u32) };
+
+ if lines.len() > 0 {
+ // In order to preserve some space, we exploit the fact that
+ // the lines list is sorted and individual lines are
+ // probably not that long. Because of that we can store lines
+ // as a difference list, using as little space as possible
+ // for the differences.
+ let max_line_length = if lines.len() == 1 {
+ 0
+ } else {
+ lines.as_slice()
+ .windows(2)
+ .map(|w| w[1] - w[0])
+ .map(|bp| bp.to_usize())
+ .max()
+ .unwrap()
+ };
+
+ let bytes_per_diff: u8 = match max_line_length {
+ 0 ... 0xFF => 1,
+ 0x100 ... 0xFFFF => 2,
+ _ => 4
+ };
+
+ // Encode the number of bytes used per diff.
+ try! { bytes_per_diff.encode(s) };
+
+ // Encode the first element.
+ try! { lines[0].encode(s) };
+
+ let diff_iter = (&lines[..]).windows(2)
+ .map(|w| (w[1] - w[0]));
+
+ match bytes_per_diff {
+ 1 => for diff in diff_iter { try! { (diff.0 as u8).encode(s) } },
+ 2 => for diff in diff_iter { try! { (diff.0 as u16).encode(s) } },
+ 4 => for diff in diff_iter { try! { (diff.0 as u32).encode(s) } },
+ _ => unreachable!()
+ }
+ }
+
+ Ok(())
+ })
+ };
+ s.emit_struct_field("multibyte_chars", 4, |s| {
+ (*self.multibyte_chars.borrow()).encode(s)
+ })
+ })
+ }
+}
+
+impl Decodable for FileMap {
+ fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
+
+ d.read_struct("FileMap", 5, |d| {
+ let name: String = try! {
+ d.read_struct_field("name", 0, |d| Decodable::decode(d))
+ };
+ let start_pos: BytePos = try! {
+ d.read_struct_field("start_pos", 1, |d| Decodable::decode(d))
+ };
+ let end_pos: BytePos = try! {
+ d.read_struct_field("end_pos", 2, |d| Decodable::decode(d))
+ };
+ let lines: Vec<BytePos> = try! {
+ d.read_struct_field("lines", 3, |d| {
+ let num_lines: u32 = try! { Decodable::decode(d) };
+ let mut lines = Vec::with_capacity(num_lines as usize);
+
+ if num_lines > 0 {
+ // Read the number of bytes used per diff.
+ let bytes_per_diff: u8 = try! { Decodable::decode(d) };
+
+ // Read the first element.
+ let mut line_start: BytePos = try! { Decodable::decode(d) };
+ lines.push(line_start);
+
+ for _ in 1..num_lines {
+ let diff = match bytes_per_diff {
+ 1 => try! { d.read_u8() } as u32,
+ 2 => try! { d.read_u16() } as u32,
+ 4 => try! { d.read_u32() },
+ _ => unreachable!()
+ };
+
+ line_start = line_start + BytePos(diff);
+
+ lines.push(line_start);
+ }
+ }
+
+ Ok(lines)
+ })
+ };
+ let multibyte_chars: Vec<MultiByteChar> = try! {
+ d.read_struct_field("multibyte_chars", 4, |d| Decodable::decode(d))
+ };
+ Ok(FileMap {
+ name: name,
+ start_pos: start_pos,
+ end_pos: end_pos,
+ src: None,
+ lines: RefCell::new(lines),
+ multibyte_chars: RefCell::new(multibyte_chars)
+ })
+ })
+ }
}
impl FileMap {
/// get a line from the list of pre-computed line-beginnings
///
pub fn get_line(&self, line_number: usize) -> Option<String> {
- let lines = self.lines.borrow();
- lines.get(line_number).map(|&line| {
- let begin: BytePos = line - self.start_pos;
- let begin = begin.to_usize();
- let slice = &self.src[begin..];
- match slice.find('\n') {
- Some(e) => &slice[..e],
- None => slice
- }.to_string()
- })
+ match self.src {
+ Some(ref src) => {
+ let lines = self.lines.borrow();
+ lines.get(line_number).map(|&line| {
+ let begin: BytePos = line - self.start_pos;
+ let begin = begin.to_usize();
+ let slice = &src[begin..];
+ match slice.find('\n') {
+ Some(e) => &slice[..e],
+ None => slice
+ }.to_string()
+ })
+ }
+ None => None
+ }
}
pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
!(self.name.starts_with("<") &&
self.name.ends_with(">"))
}
+
+ pub fn is_imported(&self) -> bool {
+ self.src.is_none()
+ }
}
+
+// _____________________________________________________________________________
+// CodeMap
+//
+
pub struct CodeMap {
pub files: RefCell<Vec<Rc<FileMap>>>,
expansions: RefCell<Vec<ExpnInfo>>
let mut files = self.files.borrow_mut();
let start_pos = match files.last() {
None => 0,
- Some(last) => last.start_pos.to_usize() + last.src.len(),
+ Some(last) => last.end_pos.to_usize(),
};
// Remove utf-8 BOM if any.
src.push('\n');
}
+ let end_pos = start_pos + src.len();
+
let filemap = Rc::new(FileMap {
name: filename,
- src: src.to_string(),
+ src: Some(Rc::new(src)),
start_pos: Pos::from_usize(start_pos),
+ end_pos: Pos::from_usize(end_pos),
lines: RefCell::new(Vec::new()),
multibyte_chars: RefCell::new(Vec::new()),
});
filemap
}
+ /// Allocates a new FileMap representing a source file from an external
+ /// crate. The source code of such an "imported filemap" is not available,
+ /// but we still know enough to generate accurate debuginfo location
+ /// information for things inlined from other crates.
+ pub fn new_imported_filemap(&self,
+ filename: FileName,
+ source_len: usize,
+ file_local_lines: Vec<BytePos>,
+ file_local_multibyte_chars: Vec<MultiByteChar>)
+ -> Rc<FileMap> {
+ let mut files = self.files.borrow_mut();
+ let start_pos = match files.last() {
+ None => 0,
+ Some(last) => last.end_pos.to_usize(),
+ };
+
+ let end_pos = Pos::from_usize(start_pos + source_len);
+ let start_pos = Pos::from_usize(start_pos);
+
+ let lines = file_local_lines.map_in_place(|pos| pos + start_pos);
+ let multibyte_chars = file_local_multibyte_chars.map_in_place(|mbc| MultiByteChar {
+ pos: mbc.pos + start_pos,
+ bytes: mbc.bytes
+ });
+
+ let filemap = Rc::new(FileMap {
+ name: filename,
+ src: None,
+ start_pos: start_pos,
+ end_pos: end_pos,
+ lines: RefCell::new(lines),
+ multibyte_chars: RefCell::new(multibyte_chars),
+ });
+
+ files.push(filemap.clone());
+
+ filemap
+ }
+
pub fn mk_substr_filename(&self, sp: Span) -> String {
let pos = self.lookup_char_pos(sp.lo);
(format!("<{}:{}:{}>",
return Err(SpanSnippetError::IllFormedSpan(sp));
}
- let begin = self.lookup_byte_offset(sp.lo);
- let end = self.lookup_byte_offset(sp.hi);
+ let local_begin = self.lookup_byte_offset(sp.lo);
+ let local_end = self.lookup_byte_offset(sp.hi);
- if begin.fm.start_pos != end.fm.start_pos {
+ if local_begin.fm.start_pos != local_end.fm.start_pos {
return Err(SpanSnippetError::DistinctSources(DistinctSources {
- begin: (begin.fm.name.clone(),
- begin.fm.start_pos),
- end: (end.fm.name.clone(),
- end.fm.start_pos)
+ begin: (local_begin.fm.name.clone(),
+ local_begin.fm.start_pos),
+ end: (local_end.fm.name.clone(),
+ local_end.fm.start_pos)
}));
} else {
- let start = begin.pos.to_usize();
- let limit = end.pos.to_usize();
- if start > limit || limit > begin.fm.src.len() {
- return Err(SpanSnippetError::MalformedForCodemap(
- MalformedCodemapPositions {
- name: begin.fm.name.clone(),
- source_len: begin.fm.src.len(),
- begin_pos: begin.pos,
- end_pos: end.pos,
- }));
- }
+ match local_begin.fm.src {
+ Some(ref src) => {
+ let start_index = local_begin.pos.to_usize();
+ let end_index = local_end.pos.to_usize();
+ let source_len = (local_begin.fm.end_pos -
+ local_begin.fm.start_pos).to_usize();
+
+ if start_index > end_index || end_index > source_len {
+ return Err(SpanSnippetError::MalformedForCodemap(
+ MalformedCodemapPositions {
+ name: local_begin.fm.name.clone(),
+ source_len: source_len,
+ begin_pos: local_begin.pos,
+ end_pos: local_end.pos,
+ }));
+ }
- return Ok((&begin.fm.src[start..limit]).to_string())
+ return Ok((&src[start_index..end_index]).to_string())
+ }
+ None => {
+ return Err(SpanSnippetError::SourceNotAvailable {
+ filename: local_begin.fm.name.clone()
+ });
+ }
+ }
}
}
panic!("asking for {} which we don't know about", filename);
}
+ /// For a global BytePos compute the local offset within the containing FileMap
pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
let idx = self.lookup_filemap_idx(bpos);
let fm = (*self.files.borrow())[idx].clone();
}
}
+// _____________________________________________________________________________
+// SpanSnippetError, DistinctSources, MalformedCodemapPositions
+//
+
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SpanSnippetError {
IllFormedSpan(Span),
DistinctSources(DistinctSources),
MalformedForCodemap(MalformedCodemapPositions),
+ SourceNotAvailable { filename: String }
}
#[derive(Clone, PartialEq, Eq, Debug)]
end_pos: BytePos
}
+
+// _____________________________________________________________________________
+// Tests
+//
+
#[cfg(test)]
mod test {
use super::*;
pub fn default_handler(color_config: ColorConfig,
registry: Option<diagnostics::registry::Registry>,
can_emit_warnings: bool) -> Handler {
- mk_handler(can_emit_warnings, box EmitterWriter::stderr(color_config, registry))
+ mk_handler(can_emit_warnings, Box::new(EmitterWriter::stderr(color_config, registry)))
}
pub fn mk_handler(can_emit_warnings: bool, e: Box<Emitter + Send>) -> Handler {
if use_color {
let dst = match term::stderr() {
Some(t) => Terminal(t),
- None => Raw(box stderr),
+ None => Raw(Box::new(stderr)),
};
EmitterWriter { dst: dst, registry: registry }
} else {
- EmitterWriter { dst: Raw(box stderr), registry: registry }
+ EmitterWriter { dst: Raw(Box::new(stderr)), registry: registry }
}
}
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// 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.
//
-> SyntaxEnv {
// utility function to simplify creating NormalTT syntax extensions
fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
- NormalTT(box f, None)
+ NormalTT(Box::new(f), None)
}
let mut syntax_expanders = SyntaxEnv::new();
builtin_normal_expander(
ext::log_syntax::expand_syntax_ext));
syntax_expanders.insert(intern("derive"),
- Decorator(box ext::deriving::expand_meta_derive));
+ Decorator(Box::new(ext::deriving::expand_meta_derive)));
syntax_expanders.insert(intern("deriving"),
- Decorator(box ext::deriving::expand_deprecated_deriving));
+ Decorator(Box::new(ext::deriving::expand_deprecated_deriving)));
if ecfg.enable_quotes() {
// Quasi-quoting expanders
syntax_expanders.insert(intern("quote_stmt"),
builtin_normal_expander(
ext::quote::expand_quote_stmt));
+ syntax_expanders.insert(intern("quote_matcher"),
+ builtin_normal_expander(
+ ext::quote::expand_quote_matcher));
+ syntax_expanders.insert(intern("quote_attr"),
+ builtin_normal_expander(
+ ext::quote::expand_quote_attr));
}
syntax_expanders.insert(intern("line"),
args: Vec::new(),
ret_ty: Self_,
attributes: attrs,
- combine_substructure: combine_substructure(box |c, s, sub| {
+ combine_substructure: combine_substructure(Box::new(|c, s, sub| {
cs_clone("Clone", c, s, sub)
- }),
+ })),
}
),
associated_types: Vec::new(),
cx.expr_binary(span, ast::BiAnd, subexpr, eq)
},
cx.expr_bool(span, true),
- box |cx, span, _, _| cx.expr_bool(span, false),
+ Box::new(|cx, span, _, _| cx.expr_bool(span, false)),
cx, span, substr)
}
fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
cx.expr_binary(span, ast::BiOr, subexpr, eq)
},
cx.expr_bool(span, false),
- box |cx, span, _, _| cx.expr_bool(span, true),
+ Box::new(|cx, span, _, _| cx.expr_bool(span, true)),
cx, span, substr)
}
args: vec!(borrowed_self()),
ret_ty: Literal(path_local!(bool)),
attributes: attrs,
- combine_substructure: combine_substructure(box |a, b, c| {
+ combine_substructure: combine_substructure(Box::new(|a, b, c| {
$f(a, b, c)
- })
+ }))
}
} }
}
args: vec!(borrowed_self()),
ret_ty: Literal(path_local!(bool)),
attributes: attrs,
- combine_substructure: combine_substructure(box |cx, span, substr| {
+ combine_substructure: combine_substructure(Box::new(|cx, span, substr| {
cs_op($op, $equal, cx, span, substr)
- })
+ }))
}
} }
}
args: vec![borrowed_self()],
ret_ty: ret_ty,
attributes: attrs,
- combine_substructure: combine_substructure(box |cx, span, substr| {
+ combine_substructure: combine_substructure(Box::new(|cx, span, substr| {
cs_partial_cmp(cx, span, substr)
- })
+ }))
};
let trait_def = TraitDef {
cx.expr_block(cx.block(span, vec!(assign), Some(if_)))
},
equals_expr.clone(),
- box |cx, span, (self_args, tag_tuple), _non_self_args| {
+ Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| {
if self_args.len() != 2 {
cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
} else {
some_ordering_collapsed(cx, span, PartialCmpOp, tag_tuple)
}
- },
+ }),
cx, span, substr)
}
cx.expr_binary(span, ast::BiOr, cmp, and)
},
cx.expr_bool(span, equal),
- box |cx, span, (self_args, tag_tuple), _non_self_args| {
+ Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| {
if self_args.len() != 2 {
cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
} else {
};
some_ordering_collapsed(cx, span, op, tag_tuple)
}
- },
+ }),
cx, span, substr)
}
let block = cx.block(span, stmts, None);
cx.expr_block(block)
},
- box |cx, sp, _, _| cx.span_bug(sp, "non matching enums in derive(Eq)?"),
+ Box::new(|cx, sp, _, _| {
+ cx.span_bug(sp, "non matching enums in derive(Eq)?") }),
cx,
span,
substr)
args: vec!(),
ret_ty: nil_ty(),
attributes: attrs,
- combine_substructure: combine_substructure(box |a, b, c| {
+ combine_substructure: combine_substructure(Box::new(|a, b, c| {
cs_total_eq_assert(a, b, c)
- })
+ }))
}
),
associated_types: Vec::new(),
args: vec!(borrowed_self()),
ret_ty: Literal(path_std!(cx, core::cmp::Ordering)),
attributes: attrs,
- combine_substructure: combine_substructure(box |a, b, c| {
+ combine_substructure: combine_substructure(Box::new(|a, b, c| {
cs_cmp(a, b, c)
- }),
+ })),
}
),
associated_types: Vec::new(),
cx.expr_block(cx.block(span, vec!(assign), Some(if_)))
},
cx.expr_path(equals_path.clone()),
- box |cx, span, (self_args, tag_tuple), _non_self_args| {
+ Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| {
if self_args.len() != 2 {
cx.span_bug(span, "not exactly 2 arguments in `derives(Ord)`")
} else {
ordering_collapsed(cx, span, tag_tuple)
}
- },
+ }),
cx, span, substr)
}
true
)),
attributes: Vec::new(),
- combine_substructure: combine_substructure(box |a, b, c| {
+ combine_substructure: combine_substructure(Box::new(|a, b, c| {
decodable_substructure(a, b, c, krate)
- }),
+ })),
}
),
associated_types: Vec::new(),
args: Vec::new(),
ret_ty: Self_,
attributes: attrs,
- combine_substructure: combine_substructure(box |a, b, c| {
+ combine_substructure: combine_substructure(Box::new(|a, b, c| {
default_substructure(a, b, c)
- })
+ }))
}
),
associated_types: Vec::new(),
true
)),
attributes: Vec::new(),
- combine_substructure: combine_substructure(box |a, b, c| {
+ combine_substructure: combine_substructure(Box::new(|a, b, c| {
encodable_substructure(a, b, c)
- }),
+ })),
}
),
associated_types: Vec::new(),
args: vec!(Ptr(box Literal(arg), Borrowed(None, MutMutable))),
ret_ty: nil_ty(),
attributes: vec![],
- combine_substructure: combine_substructure(box |a, b, c| {
+ combine_substructure: combine_substructure(Box::new(|a, b, c| {
hash_substructure(a, b, c)
- })
+ }))
}
),
associated_types: Vec::new(),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs.clone(),
- combine_substructure: combine_substructure(box |c, s, sub| {
+ combine_substructure: combine_substructure(Box::new(|c, s, sub| {
cs_from("i64", c, s, sub)
- }),
+ })),
},
MethodDef {
name: "from_u64",
true)),
// #[inline] liable to cause code-bloat
attributes: attrs,
- combine_substructure: combine_substructure(box |c, s, sub| {
+ combine_substructure: combine_substructure(Box::new(|c, s, sub| {
cs_from("u64", c, s, sub)
- }),
+ })),
}
),
associated_types: Vec::new(),
),
ret_ty: Self_,
attributes: Vec::new(),
- combine_substructure: combine_substructure(box |a, b, c| {
+ combine_substructure: combine_substructure(Box::new(|a, b, c| {
rand_substructure(a, b, c)
- })
+ }))
}
),
associated_types: Vec::new(),
args: vec!(fmtr),
ret_ty: Literal(path_std!(cx, core::fmt::Result)),
attributes: Vec::new(),
- combine_substructure: combine_substructure(box |a, b, c| {
+ combine_substructure: combine_substructure(Box::new(|a, b, c| {
show_substructure(a, b, c)
- })
+ }))
}
],
associated_types: Vec::new(),
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// 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.
//
tts: &[ast::TokenTree])
-> Box<base::MacResult+'cx> {
let (cx_expr, expr) = expand_tts(cx, sp, tts);
- let expanded = expand_wrapper(cx, sp, cx_expr, expr);
+ let expanded = expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"]]);
base::MacEager::expr(expanded)
}
base::MacEager::expr(expanded)
}
+pub fn expand_quote_attr(cx: &mut ExtCtxt,
+ sp: Span,
+ tts: &[ast::TokenTree])
+ -> Box<base::MacResult+'static> {
+ let expanded = expand_parse_call(cx, sp, "parse_attribute",
+ vec!(cx.expr_bool(sp, true)), tts);
+
+ base::MacEager::expr(expanded)
+}
+
+pub fn expand_quote_matcher(cx: &mut ExtCtxt,
+ sp: Span,
+ tts: &[ast::TokenTree])
+ -> Box<base::MacResult+'static> {
+ let (cx_expr, tts) = parse_arguments_to_quote(cx, tts);
+ let mut vector = mk_stmts_let(cx, sp);
+ vector.extend(statements_mk_tts(cx, &tts[..], true).into_iter());
+ let block = cx.expr_block(
+ cx.block_all(sp,
+ vector,
+ Some(cx.expr_ident(sp, id_ext("tt")))));
+
+ let expanded = expand_wrapper(cx, sp, cx_expr, block, &[&["syntax", "ext", "quote", "rt"]]);
+ base::MacEager::expr(expanded)
+}
+
fn ids_ext(strs: Vec<String> ) -> Vec<ast::Ident> {
strs.iter().map(|str| str_to_ident(&(*str))).collect()
}
}
#[allow(non_upper_case_globals)]
-fn mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> P<ast::Expr> {
+fn expr_mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> P<ast::Expr> {
macro_rules! mk_lit {
($name: expr, $suffix: expr, $($args: expr),*) => {{
let inner = cx.expr_call(sp, mk_token_path(cx, sp, $name), vec![$($args),*]);
vec!(mk_name(cx, sp, ident.ident())));
}
+ token::MatchNt(name, kind, namep, kindp) => {
+ return cx.expr_call(sp,
+ mk_token_path(cx, sp, "MatchNt"),
+ vec!(mk_ident(cx, sp, name),
+ mk_ident(cx, sp, kind),
+ match namep {
+ ModName => mk_token_path(cx, sp, "ModName"),
+ Plain => mk_token_path(cx, sp, "Plain"),
+ },
+ match kindp {
+ ModName => mk_token_path(cx, sp, "ModName"),
+ Plain => mk_token_path(cx, sp, "Plain"),
+ }));
+ }
+
token::Interpolated(_) => panic!("quote! with interpolated token"),
_ => ()
mk_token_path(cx, sp, name)
}
-fn mk_tt(cx: &ExtCtxt, tt: &ast::TokenTree) -> Vec<P<ast::Stmt>> {
+fn statements_mk_tt(cx: &ExtCtxt, tt: &ast::TokenTree, matcher: bool) -> Vec<P<ast::Stmt>> {
match *tt {
ast::TtToken(sp, SubstNt(ident, _)) => {
// tt.extend($ident.to_tokens(ext_cx).into_iter())
vec!(cx.stmt_expr(e_push))
}
- ref tt @ ast::TtToken(_, MatchNt(..)) => {
+ ref tt @ ast::TtToken(_, MatchNt(..)) if !matcher => {
let mut seq = vec![];
for i in 0..tt.len() {
seq.push(tt.get_tt(i));
}
- mk_tts(cx, &seq[..])
+ statements_mk_tts(cx, &seq[..], matcher)
}
ast::TtToken(sp, ref tok) => {
let e_sp = cx.expr_ident(sp, id_ext("_sp"));
let e_tok = cx.expr_call(sp,
mk_ast_path(cx, sp, "TtToken"),
- vec!(e_sp, mk_token(cx, sp, tok)));
+ vec!(e_sp, expr_mk_token(cx, sp, tok)));
let e_push =
cx.expr_method_call(sp,
cx.expr_ident(sp, id_ext("tt")),
vec!(cx.stmt_expr(e_push))
},
ast::TtDelimited(_, ref delimed) => {
- mk_tt(cx, &delimed.open_tt()).into_iter()
- .chain(delimed.tts.iter().flat_map(|tt| mk_tt(cx, tt).into_iter()))
- .chain(mk_tt(cx, &delimed.close_tt()).into_iter())
+ statements_mk_tt(cx, &delimed.open_tt(), matcher).into_iter()
+ .chain(delimed.tts.iter()
+ .flat_map(|tt| statements_mk_tt(cx, tt, matcher).into_iter()))
+ .chain(statements_mk_tt(cx, &delimed.close_tt(), matcher).into_iter())
.collect()
},
- ast::TtSequence(..) => panic!("TtSequence in quote!"),
- }
-}
+ ast::TtSequence(sp, ref seq) => {
+ if !matcher {
+ panic!("TtSequence in quote!");
+ }
-fn mk_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> Vec<P<ast::Stmt>> {
- let mut ss = Vec::new();
- for tt in tts {
- ss.extend(mk_tt(cx, tt).into_iter());
+ let e_sp = cx.expr_ident(sp, id_ext("_sp"));
+
+ let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp));
+ let mut tts_stmts = vec![stmt_let_tt];
+ tts_stmts.extend(statements_mk_tts(cx, &seq.tts[..], matcher).into_iter());
+ let e_tts = cx.expr_block(cx.block(sp, tts_stmts,
+ Some(cx.expr_ident(sp, id_ext("tt")))));
+ let e_separator = match seq.separator {
+ Some(ref sep) => cx.expr_some(sp, expr_mk_token(cx, sp, sep)),
+ None => cx.expr_none(sp),
+ };
+ let e_op = match seq.op {
+ ast::ZeroOrMore => mk_ast_path(cx, sp, "ZeroOrMore"),
+ ast::OneOrMore => mk_ast_path(cx, sp, "OneOrMore"),
+ };
+ let fields = vec![cx.field_imm(sp, id_ext("tts"), e_tts),
+ cx.field_imm(sp, id_ext("separator"), e_separator),
+ cx.field_imm(sp, id_ext("op"), e_op),
+ cx.field_imm(sp, id_ext("num_captures"),
+ cx.expr_usize(sp, seq.num_captures))];
+ let seq_path = vec![id_ext("syntax"), id_ext("ast"), id_ext("SequenceRepetition")];
+ let e_seq_struct = cx.expr_struct(sp, cx.path_global(sp, seq_path), fields);
+ let e_rc_new = cx.expr_call_global(sp, vec![id_ext("std"),
+ id_ext("rc"),
+ id_ext("Rc"),
+ id_ext("new")],
+ vec![e_seq_struct]);
+ let e_tok = cx.expr_call(sp,
+ mk_ast_path(cx, sp, "TtSequence"),
+ vec!(e_sp, e_rc_new));
+ let e_push =
+ cx.expr_method_call(sp,
+ cx.expr_ident(sp, id_ext("tt")),
+ id_ext("push"),
+ vec!(e_tok));
+ vec!(cx.stmt_expr(e_push))
+ }
}
- ss
}
-fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree])
- -> (P<ast::Expr>, P<ast::Expr>) {
+fn parse_arguments_to_quote(cx: &ExtCtxt, tts: &[ast::TokenTree])
+ -> (P<ast::Expr>, Vec<ast::TokenTree>) {
// NB: It appears that the main parser loses its mind if we consider
- // $foo as a TtNonterminal during the main parse, so we have to re-parse
+ // $foo as a SubstNt during the main parse, so we have to re-parse
// under quote_depth > 0. This is silly and should go away; the _guess_ is
// it has to do with transition away from supporting old-style macros, so
// try removing it when enough of them are gone.
let tts = p.parse_all_token_trees();
p.abort_if_errors();
+ (cx_expr, tts)
+}
+
+fn mk_stmts_let(cx: &ExtCtxt, sp: Span) -> Vec<P<ast::Stmt>> {
// We also bind a single value, sp, to ext_cx.call_site()
//
// This causes every span in a token-tree quote to be attributed to the
let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp));
- let mut vector = vec!(stmt_let_sp, stmt_let_tt);
- vector.extend(mk_tts(cx, &tts[..]).into_iter());
+ vec!(stmt_let_sp, stmt_let_tt)
+}
+
+fn statements_mk_tts(cx: &ExtCtxt, tts: &[ast::TokenTree], matcher: bool) -> Vec<P<ast::Stmt>> {
+ let mut ss = Vec::new();
+ for tt in tts {
+ ss.extend(statements_mk_tt(cx, tt, matcher).into_iter());
+ }
+ ss
+}
+
+fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree])
+ -> (P<ast::Expr>, P<ast::Expr>) {
+ let (cx_expr, tts) = parse_arguments_to_quote(cx, tts);
+
+ let mut vector = mk_stmts_let(cx, sp);
+ vector.extend(statements_mk_tts(cx, &tts[..], false).into_iter());
let block = cx.expr_block(
cx.block_all(sp,
vector,
fn expand_wrapper(cx: &ExtCtxt,
sp: Span,
cx_expr: P<ast::Expr>,
- expr: P<ast::Expr>) -> P<ast::Expr> {
+ expr: P<ast::Expr>,
+ imports: &[&[&str]]) -> P<ast::Expr> {
// Explicitly borrow to avoid moving from the invoker (#16992)
let cx_expr_borrow = cx.expr_addr_of(sp, cx.expr_deref(sp, cx_expr));
let stmt_let_ext_cx = cx.stmt_let(sp, false, id_ext("ext_cx"), cx_expr_borrow);
- let stmts = [
- &["syntax", "ext", "quote", "rt"],
- ].iter().map(|path| {
+ let stmts = imports.iter().map(|path| {
+ // make item: `use ...;`
let path = path.iter().map(|s| s.to_string()).collect();
cx.stmt_item(sp, cx.item_use_glob(sp, ast::Inherited, ids_ext(path)))
}).chain(Some(stmt_let_ext_cx).into_iter()).collect();
let expr = cx.expr_method_call(sp, new_parser_call, id_ext(parse_method),
arg_exprs);
- expand_wrapper(cx, sp, cx_expr, expr)
+ if parse_method == "parse_attribute" {
+ expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"],
+ &["syntax", "parse", "attr"]])
+ } else {
+ expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"]])
+ }
}
use ptr::P;
use util::small_vector::SmallVector;
-use std::old_io::File;
+use std::fs::File;
+use std::io::prelude::*;
+use std::path::{Path, PathBuf};
use std::rc::Rc;
// These macros all relate to the file system; they either return
cx.cfg(),
&res_rel_file(cx,
sp,
- &Path::new(file)),
+ Path::new(&file)),
true,
None,
sp);
Some(f) => f,
None => return DummyResult::expr(sp)
};
- let file = res_rel_file(cx, sp, &Path::new(file));
- let bytes = match File::open(&file).read_to_end() {
+ let file = res_rel_file(cx, sp, Path::new(&file));
+ let mut bytes = Vec::new();
+ match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) {
+ Ok(..) => {}
Err(e) => {
cx.span_err(sp,
&format!("couldn't read {}: {}",
e));
return DummyResult::expr(sp);
}
- Ok(bytes) => bytes,
};
match String::from_utf8(bytes) {
Ok(src) => {
Some(f) => f,
None => return DummyResult::expr(sp)
};
- let file = res_rel_file(cx, sp, &Path::new(file));
- match File::open(&file).read_to_end() {
+ let file = res_rel_file(cx, sp, Path::new(&file));
+ let mut bytes = Vec::new();
+ match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) {
Err(e) => {
cx.span_err(sp,
&format!("couldn't read {}: {}", file.display(), e));
return DummyResult::expr(sp);
}
- Ok(bytes) => {
- let bytes = bytes.iter().cloned().collect();
+ Ok(..) => {
base::MacEager::expr(cx.expr_lit(sp, ast::LitBinary(Rc::new(bytes))))
}
}
// resolve a file-system path to an absolute file-system path (if it
// isn't already)
-fn res_rel_file(cx: &mut ExtCtxt, sp: codemap::Span, arg: &Path) -> Path {
+fn res_rel_file(cx: &mut ExtCtxt, sp: codemap::Span, arg: &Path) -> PathBuf {
// NB: relative paths are resolved relative to the compilation unit
if !arg.is_absolute() {
- let mut cu = Path::new(cx.codemap().span_to_filename(sp));
- cu.pop();
+ let mut cu = PathBuf::new(&cx.codemap().span_to_filename(sp));
+ if cu.parent().is_some() {
+ cu.pop();
+ } else {
+ cu = PathBuf::new("");
+ }
cu.push(arg);
cu
} else {
- arg.clone()
+ arg.to_path_buf()
}
}
ret_val
}
-pub enum ParseResult {
- Success(HashMap<Ident, Rc<NamedMatch>>),
+pub enum ParseResult<T> {
+ Success(T),
Failure(codemap::Span, String),
Error(codemap::Span, String)
}
+pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>;
+pub type PositionalParseResult = ParseResult<Vec<Rc<NamedMatch>>>;
+
pub fn parse_or_else(sess: &ParseSess,
cfg: ast::CrateConfig,
rdr: TtReader,
cfg: ast::CrateConfig,
mut rdr: TtReader,
ms: &[TokenTree])
- -> ParseResult {
+ -> NamedParseResult {
let mut cur_eis = Vec::new();
cur_eis.push(initial_matcher_pos(Rc::new(ms.iter()
.cloned()
}
rdr.next_token();
} else /* bb_eis.len() == 1 */ {
- let mut rust_parser = Parser::new(sess, cfg.clone(), box rdr.clone());
+ let mut rust_parser = Parser::new(sess, cfg.clone(), Box::new(rdr.clone()));
let mut ei = bb_eis.pop().unwrap();
match ei.top_elts.get_tt(ei.idx) {
use ext::tt::macro_parser::{Success, Error, Failure};
use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal};
use ext::tt::macro_parser::{parse, parse_or_else};
-use parse::lexer::{new_tt_reader, new_tt_reader_with_doc_flag};
+use parse::lexer::new_tt_reader;
use parse::parser::Parser;
use parse::attr::ParserAttr;
use parse::token::{self, special_idents, gensym_ident, NtTT, Token};
TtDelimited(_, ref delim) => &delim.tts[..],
_ => cx.span_fatal(sp, "malformed macro lhs")
};
- // `None` is because we're not interpolating
- let arg_rdr = new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
- None,
- None,
- arg.iter()
- .cloned()
- .collect(),
- true);
- match parse(cx.parse_sess(), cx.cfg(), arg_rdr, lhs_tt) {
+
+ match TokenTree::parse(cx, lhs_tt, arg) {
Success(named_matches) => {
let rhs = match *rhses[i] {
// okay, what's your transcriber?
Some(named_matches),
imported_from,
rhs);
- let mut p = Parser::new(cx.parse_sess(), cx.cfg(), box trncbr);
+ let mut p = Parser::new(cx.parse_sess(), cx.cfg(), Box::new(trncbr));
p.check_unknown_macro_variable();
// Let the context choose how to interpret the result.
// Weird, but useful for X-macros.
_ => cx.span_bug(def.span, "wrong-structured rhs")
};
- let exp = box MacroRulesMacroExpander {
+ let exp: Box<_> = box MacroRulesMacroExpander {
name: def.ident,
imported_from: def.imported_from,
lhses: lhses,
#[cfg(test)]
mod test {
- use std::old_io;
+ use std::io;
use ast;
use util::parser_testing::{string_to_crate, matches_codepattern};
use parse::token;
// this version doesn't care about getting comments or docstrings in.
fn fake_print_crate(s: &mut pprust::State,
- krate: &ast::Crate) -> old_io::IoResult<()> {
+ krate: &ast::Crate) -> io::Result<()> {
s.print_mod(&krate.module, &krate.attrs)
}
#![feature(staged_api)]
#![feature(std_misc)]
#![feature(unicode)]
+#![feature(path)]
+#![feature(fs)]
+#![feature(io)]
extern crate arena;
extern crate fmt_macros;
impl<T> OwnedSlice<T> {
pub fn empty() -> OwnedSlice<T> {
- OwnedSlice { data: box [] }
+ OwnedSlice { data: Box::new([]) }
}
#[inline(never)]
use parse::lexer;
use print::pprust;
-use std::old_io;
+use std::io::Read;
use std::str;
-use std::string::String;
use std::usize;
#[derive(Clone, Copy, PartialEq)]
// probably not a good thing.
pub fn gather_comments_and_literals(span_diagnostic: &diagnostic::SpanHandler,
path: String,
- srdr: &mut old_io::Reader)
+ srdr: &mut Read)
-> (Vec<Comment>, Vec<Literal>) {
- let src = srdr.read_to_end().unwrap();
+ let mut src = Vec::new();
+ srdr.read_to_end(&mut src).unwrap();
let src = String::from_utf8(src).unwrap();
let cm = CodeMap::new();
let filemap = cm.new_filemap(path, src);
// are revised to go directly to token-trees.
/// Is \x00<name>,<ctxt>\x00 is interpreted as encoded ast::Ident?
read_embedded_ident: bool,
+
+ // cache a direct reference to the source text, so that we don't have to
+ // retrieve it via `self.filemap.src.as_ref().unwrap()` all the time.
+ source_text: Rc<String>
}
impl<'a> Reader for StringReader<'a> {
impl<'a> StringReader<'a> {
/// For comments.rs, which hackily pokes into pos and curr
pub fn new_raw<'b>(span_diagnostic: &'b SpanHandler,
- filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
+ filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
+ if filemap.src.is_none() {
+ span_diagnostic.handler.bug(&format!("Cannot lex filemap without source: {}",
+ filemap.name)[..]);
+ }
+
+ let source_text = (*filemap.src.as_ref().unwrap()).clone();
+
let mut sr = StringReader {
span_diagnostic: span_diagnostic,
pos: filemap.start_pos,
peek_tok: token::Eof,
peek_span: codemap::DUMMY_SP,
read_embedded_ident: false,
+ source_text: source_text
};
sr.bump();
sr
m.push_str(": ");
let from = self.byte_offset(from_pos).to_usize();
let to = self.byte_offset(to_pos).to_usize();
- m.push_str(&self.filemap.src[from..to]);
+ m.push_str(&self.source_text[from..to]);
self.fatal_span_(from_pos, to_pos, &m[..]);
}
fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T where
F: FnOnce(&str) -> T,
{
- f(&self.filemap.src[
- self.byte_offset(start).to_usize()..
- self.byte_offset(end).to_usize()])
+ f(&self.source_text[self.byte_offset(start).to_usize()..
+ self.byte_offset(end).to_usize()])
}
/// Converts CRLF to LF in the given string, raising an error on bare CR.
pub fn bump(&mut self) {
self.last_pos = self.pos;
let current_byte_offset = self.byte_offset(self.pos).to_usize();
- if current_byte_offset < self.filemap.src.len() {
+ if current_byte_offset < self.source_text.len() {
assert!(self.curr.is_some());
let last_char = self.curr.unwrap();
- let next = self.filemap
- .src
- .char_range_at(current_byte_offset);
+ let next = self.source_text.char_range_at(current_byte_offset);
let byte_offset_diff = next.next - current_byte_offset;
self.pos = self.pos + Pos::from_usize(byte_offset_diff);
self.curr = Some(next.ch);
pub fn nextch(&self) -> Option<char> {
let offset = self.byte_offset(self.pos).to_usize();
- if offset < self.filemap.src.len() {
- Some(self.filemap.src.char_at(offset))
+ if offset < self.source_text.len() {
+ Some(self.source_text.char_at(offset))
} else {
None
}
pub fn nextnextch(&self) -> Option<char> {
let offset = self.byte_offset(self.pos).to_usize();
- let s = &*self.filemap.src;
+ let s = &self.source_text[..];
if offset >= s.len() { return None }
let str::CharRange { next, .. } = s.char_range_at(offset);
if next < s.len() {
use std::old_io::util;
fn mk_sh() -> diagnostic::SpanHandler {
- let emitter = diagnostic::EmitterWriter::new(box util::NullWriter, None);
- let handler = diagnostic::mk_handler(true, box emitter);
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let emitter = diagnostic::EmitterWriter::new(Box::new(util::NullWriter), None);
+ let handler = diagnostic::mk_handler(true, Box::new(emitter));
diagnostic::mk_span_handler(handler, CodeMap::new())
}
use ptr::P;
use std::cell::{Cell, RefCell};
-use std::old_io::File;
-use std::rc::Rc;
+use std::fs::File;
+use std::io::Read;
+use std::iter;
use std::num::Int;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
use std::str;
-use std::iter;
#[macro_use]
pub mod parser;
pub struct ParseSess {
pub span_diagnostic: SpanHandler, // better be the same as the one in the reader!
/// Used to determine and report recursive mod inclusions
- included_mod_stack: RefCell<Vec<Path>>,
+ included_mod_stack: RefCell<Vec<PathBuf>>,
pub node_id: Cell<ast::NodeId>,
}
None => sess.span_diagnostic.handler().fatal(msg),
}
};
- let bytes = match File::open(path).read_to_end() {
- Ok(bytes) => bytes,
+ let mut bytes = Vec::new();
+ match File::open(path).and_then(|mut f| f.read_to_end(&mut bytes)) {
+ Ok(..) => {}
Err(e) => {
- err(&format!("couldn't read {:?}: {}",
- path.display(), e));
- unreachable!()
+ err(&format!("couldn't read {:?}: {}", path.display(), e));
+ unreachable!();
}
};
match str::from_utf8(&bytes[..]).ok() {
Some(s) => {
- return string_to_filemap(sess, s.to_string(),
- path.as_str().unwrap().to_string())
+ string_to_filemap(sess, s.to_string(),
+ path.to_str().unwrap().to_string())
}
None => {
- err(&format!("{:?} is not UTF-8 encoded", path.display()))
+ err(&format!("{:?} is not UTF-8 encoded", path.display()));
+ unreachable!();
}
}
- unreachable!()
}
/// Given a session and a string, add the string to
#[cfg(test)]
mod test {
use super::*;
+ use std::rc::Rc;
use serialize::json;
use codemap::{Span, BytePos, Pos, Spanned, NO_EXPANSION};
use owned_slice::OwnedSlice;
}
#[test]
- fn string_to_tts_1 () {
+ fn string_to_tts_1() {
let tts = string_to_tts("fn a (b : i32) { b; }".to_string());
- assert_eq!(json::encode(&tts).unwrap(),
- "[\
- {\
- \"variant\":\"TtToken\",\
- \"fields\":[\
- null,\
- {\
- \"variant\":\"Ident\",\
- \"fields\":[\
- \"fn\",\
- \"Plain\"\
- ]\
- }\
- ]\
- },\
- {\
- \"variant\":\"TtToken\",\
- \"fields\":[\
- null,\
- {\
- \"variant\":\"Ident\",\
- \"fields\":[\
- \"a\",\
- \"Plain\"\
- ]\
- }\
- ]\
- },\
- {\
- \"variant\":\"TtDelimited\",\
- \"fields\":[\
- null,\
- {\
- \"delim\":\"Paren\",\
- \"open_span\":null,\
- \"tts\":[\
- {\
- \"variant\":\"TtToken\",\
- \"fields\":[\
- null,\
- {\
- \"variant\":\"Ident\",\
- \"fields\":[\
- \"b\",\
- \"Plain\"\
- ]\
- }\
- ]\
- },\
- {\
- \"variant\":\"TtToken\",\
- \"fields\":[\
- null,\
- \"Colon\"\
- ]\
- },\
- {\
- \"variant\":\"TtToken\",\
- \"fields\":[\
- null,\
- {\
- \"variant\":\"Ident\",\
- \"fields\":[\
- \"i32\",\
- \"Plain\"\
- ]\
- }\
- ]\
- }\
- ],\
- \"close_span\":null\
- }\
- ]\
- },\
- {\
- \"variant\":\"TtDelimited\",\
- \"fields\":[\
- null,\
- {\
- \"delim\":\"Brace\",\
- \"open_span\":null,\
- \"tts\":[\
- {\
- \"variant\":\"TtToken\",\
- \"fields\":[\
- null,\
- {\
- \"variant\":\"Ident\",\
- \"fields\":[\
- \"b\",\
- \"Plain\"\
- ]\
- }\
- ]\
- },\
- {\
- \"variant\":\"TtToken\",\
- \"fields\":[\
- null,\
- \"Semi\"\
- ]\
- }\
- ],\
- \"close_span\":null\
- }\
- ]\
- }\
-]"
- );
+
+ let expected = vec![
+ ast::TtToken(sp(0, 2),
+ token::Ident(str_to_ident("fn"),
+ token::IdentStyle::Plain)),
+ ast::TtToken(sp(3, 4),
+ token::Ident(str_to_ident("a"),
+ token::IdentStyle::Plain)),
+ ast::TtDelimited(
+ sp(5, 14),
+ Rc::new(ast::Delimited {
+ delim: token::DelimToken::Paren,
+ open_span: sp(5, 6),
+ tts: vec![
+ ast::TtToken(sp(6, 7),
+ token::Ident(str_to_ident("b"),
+ token::IdentStyle::Plain)),
+ ast::TtToken(sp(8, 9),
+ token::Colon),
+ ast::TtToken(sp(10, 13),
+ token::Ident(str_to_ident("i32"),
+ token::IdentStyle::Plain)),
+ ],
+ close_span: sp(13, 14),
+ })),
+ ast::TtDelimited(
+ sp(15, 21),
+ Rc::new(ast::Delimited {
+ delim: token::DelimToken::Brace,
+ open_span: sp(15, 16),
+ tts: vec![
+ ast::TtToken(sp(17, 18),
+ token::Ident(str_to_ident("b"),
+ token::IdentStyle::Plain)),
+ ast::TtToken(sp(18, 19),
+ token::Semi)
+ ],
+ close_span: sp(20, 21),
+ }))
+ ];
+
+ assert_eq!(tts, expected);
}
#[test] fn ret_expr() {
use owned_slice::OwnedSlice;
use std::collections::HashSet;
-use std::old_io::fs::PathExtensions;
+use std::io::prelude::*;
use std::iter;
use std::mem;
use std::num::Float;
+use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::slice;
outer_attrs: &[ast::Attribute],
id_sp: Span)
-> (ast::Item_, Vec<ast::Attribute> ) {
- let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
- prefix.pop();
- let mod_path = Path::new(".").join_many(&self.mod_path_stack);
- let dir_path = prefix.join(&mod_path);
+ let mut prefix = PathBuf::new(&self.sess.span_diagnostic.cm
+ .span_to_filename(self.span));
+ // FIXME(acrichto): right now "a".pop() == "a", but need to confirm with
+ // aturon whether this is expected or not.
+ if prefix.parent().is_some() {
+ prefix.pop();
+ } else {
+ prefix = PathBuf::new("");
+ }
+ let mut dir_path = prefix;
+ for part in &self.mod_path_stack {
+ dir_path.push(&**part);
+ }
let mod_string = token::get_ident(id);
let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
outer_attrs, "path") {
- Some(d) => (dir_path.join(d), true),
+ Some(d) => (dir_path.join(&*d), true),
None => {
let mod_name = mod_string.to_string();
let default_path_str = format!("{}.rs", mod_name);
}
fn eval_src_mod_from_path(&mut self,
- path: Path,
+ path: PathBuf,
owns_directory: bool,
name: String,
id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
let mut err = String::from_str("circular modules: ");
let len = included_mod_stack.len();
for p in &included_mod_stack[i.. len] {
- err.push_str(&p.display().as_cow());
+ err.push_str(&p.to_string_lossy());
err.push_str(" -> ");
}
- err.push_str(&path.display().as_cow());
+ err.push_str(&path.to_string_lossy());
self.span_fatal(id_sp, &err[..]);
}
None => ()
//! line (which it can't) and so naturally place the content on its own line to
//! avoid combining it with other lines and making matters even worse.
-use std::old_io;
+use std::io;
use std::string;
use std::iter::repeat;
const SIZE_INFINITY: isize = 0xffff;
-pub fn mk_printer(out: Box<old_io::Writer+'static>, linewidth: usize) -> Printer {
+pub fn mk_printer<'a>(out: Box<io::Write+'a>, linewidth: usize) -> Printer<'a> {
// Yes 3, it makes the ring buffers big enough to never
// fall behind.
let n: usize = 3 * linewidth;
/// In this implementation (following the paper, again) the SCAN process is
/// the method called 'pretty_print', and the 'PRINT' process is the method
/// called 'print'.
-pub struct Printer {
- pub out: Box<old_io::Writer+'static>,
+pub struct Printer<'a> {
+ pub out: Box<io::Write+'a>,
buf_len: usize,
/// Width of lines we're constrained to
margin: isize,
pending_indentation: isize,
}
-impl Printer {
+impl<'a> Printer<'a> {
pub fn last_token(&mut self) -> Token {
self.token[self.right].clone()
}
pub fn replace_last_token(&mut self, t: Token) {
self.token[self.right] = t;
}
- pub fn pretty_print(&mut self, token: Token) -> old_io::IoResult<()> {
+ pub fn pretty_print(&mut self, token: Token) -> io::Result<()> {
debug!("pp ~[{},{}]", self.left, self.right);
match token {
Token::Eof => {
}
}
}
- pub fn check_stream(&mut self) -> old_io::IoResult<()> {
+ pub fn check_stream(&mut self) -> io::Result<()> {
debug!("check_stream ~[{}, {}] with left_total={}, right_total={}",
self.left, self.right, self.left_total, self.right_total);
if self.right_total - self.left_total > self.space {
self.right %= self.buf_len;
assert!((self.right != self.left));
}
- pub fn advance_left(&mut self) -> old_io::IoResult<()> {
+ pub fn advance_left(&mut self) -> io::Result<()> {
debug!("advance_left ~[{},{}], sizeof({})={}", self.left, self.right,
self.left, self.size[self.left]);
}
}
}
- pub fn print_newline(&mut self, amount: isize) -> old_io::IoResult<()> {
+ pub fn print_newline(&mut self, amount: isize) -> io::Result<()> {
debug!("NEWLINE {}", amount);
let ret = write!(self.out, "\n");
self.pending_indentation = 0;
}
}
}
- pub fn print_str(&mut self, s: &str) -> old_io::IoResult<()> {
+ pub fn print_str(&mut self, s: &str) -> io::Result<()> {
while self.pending_indentation > 0 {
try!(write!(self.out, " "));
self.pending_indentation -= 1;
}
write!(self.out, "{}", s)
}
- pub fn print(&mut self, token: Token, l: isize) -> old_io::IoResult<()> {
+ pub fn print(&mut self, token: Token, l: isize) -> io::Result<()> {
debug!("print {} {} (remaining line space={})", tok_str(&token), l,
self.space);
debug!("{}", buf_str(&self.token,
// Convenience functions to talk to the printer.
//
// "raw box"
-pub fn rbox(p: &mut Printer, indent: usize, b: Breaks) -> old_io::IoResult<()> {
+pub fn rbox(p: &mut Printer, indent: usize, b: Breaks) -> io::Result<()> {
p.pretty_print(Token::Begin(BeginToken {
offset: indent as isize,
breaks: b
}))
}
-pub fn ibox(p: &mut Printer, indent: usize) -> old_io::IoResult<()> {
+pub fn ibox(p: &mut Printer, indent: usize) -> io::Result<()> {
rbox(p, indent, Breaks::Inconsistent)
}
-pub fn cbox(p: &mut Printer, indent: usize) -> old_io::IoResult<()> {
+pub fn cbox(p: &mut Printer, indent: usize) -> io::Result<()> {
rbox(p, indent, Breaks::Consistent)
}
-pub fn break_offset(p: &mut Printer, n: usize, off: isize) -> old_io::IoResult<()> {
+pub fn break_offset(p: &mut Printer, n: usize, off: isize) -> io::Result<()> {
p.pretty_print(Token::Break(BreakToken {
offset: off,
blank_space: n as isize
}))
}
-pub fn end(p: &mut Printer) -> old_io::IoResult<()> {
+pub fn end(p: &mut Printer) -> io::Result<()> {
p.pretty_print(Token::End)
}
-pub fn eof(p: &mut Printer) -> old_io::IoResult<()> {
+pub fn eof(p: &mut Printer) -> io::Result<()> {
p.pretty_print(Token::Eof)
}
-pub fn word(p: &mut Printer, wrd: &str) -> old_io::IoResult<()> {
+pub fn word(p: &mut Printer, wrd: &str) -> io::Result<()> {
p.pretty_print(Token::String(/* bad */ wrd.to_string(), wrd.len() as isize))
}
-pub fn huge_word(p: &mut Printer, wrd: &str) -> old_io::IoResult<()> {
+pub fn huge_word(p: &mut Printer, wrd: &str) -> io::Result<()> {
p.pretty_print(Token::String(/* bad */ wrd.to_string(), SIZE_INFINITY))
}
-pub fn zero_word(p: &mut Printer, wrd: &str) -> old_io::IoResult<()> {
+pub fn zero_word(p: &mut Printer, wrd: &str) -> io::Result<()> {
p.pretty_print(Token::String(/* bad */ wrd.to_string(), 0))
}
-pub fn spaces(p: &mut Printer, n: usize) -> old_io::IoResult<()> {
+pub fn spaces(p: &mut Printer, n: usize) -> io::Result<()> {
break_offset(p, n, 0)
}
-pub fn zerobreak(p: &mut Printer) -> old_io::IoResult<()> {
+pub fn zerobreak(p: &mut Printer) -> io::Result<()> {
spaces(p, 0)
}
-pub fn space(p: &mut Printer) -> old_io::IoResult<()> {
+pub fn space(p: &mut Printer) -> io::Result<()> {
spaces(p, 1)
}
-pub fn hardbreak(p: &mut Printer) -> old_io::IoResult<()> {
+pub fn hardbreak(p: &mut Printer) -> io::Result<()> {
spaces(p, SIZE_INFINITY as usize)
}
use std_inject;
use std::{ascii, mem};
-use std::old_io::{self, IoResult};
+use std::io::{self, Write, Read};
use std::iter;
pub enum AnnNode<'a> {
}
pub trait PpAnn {
- fn pre(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
- fn post(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
+ fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
+ fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
}
#[derive(Copy)]
}
pub struct State<'a> {
- pub s: pp::Printer,
+ pub s: pp::Printer<'a>,
cm: Option<&'a CodeMap>,
comments: Option<Vec<comments::Comment> >,
literals: Option<Vec<comments::Literal> >,
encode_idents_with_hygiene: bool,
}
-pub fn rust_printer(writer: Box<old_io::Writer+'static>) -> State<'static> {
+pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
static NO_ANN: NoAnn = NoAnn;
rust_printer_annotated(writer, &NO_ANN)
}
-pub fn rust_printer_annotated<'a>(writer: Box<old_io::Writer+'static>,
+pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
ann: &'a PpAnn) -> State<'a> {
State {
s: pp::mk_printer(writer, default_columns),
span_diagnostic: &diagnostic::SpanHandler,
krate: &ast::Crate,
filename: String,
- input: &mut old_io::Reader,
- out: Box<old_io::Writer+'static>,
+ input: &mut Read,
+ out: Box<Write+'a>,
ann: &'a PpAnn,
- is_expanded: bool) -> IoResult<()> {
+ is_expanded: bool) -> io::Result<()> {
let mut s = State::new_from_input(cm,
span_diagnostic,
filename,
pub fn new_from_input(cm: &'a CodeMap,
span_diagnostic: &diagnostic::SpanHandler,
filename: String,
- input: &mut old_io::Reader,
- out: Box<old_io::Writer+'static>,
+ input: &mut Read,
+ out: Box<Write+'a>,
ann: &'a PpAnn,
is_expanded: bool) -> State<'a> {
let (cmnts, lits) = comments::gather_comments_and_literals(
}
pub fn new(cm: &'a CodeMap,
- out: Box<old_io::Writer+'static>,
+ out: Box<Write+'a>,
ann: &'a PpAnn,
comments: Option<Vec<comments::Comment>>,
literals: Option<Vec<comments::Literal>>) -> State<'a> {
}
pub fn to_string<F>(f: F) -> String where
- F: FnOnce(&mut State) -> IoResult<()>,
+ F: FnOnce(&mut State) -> io::Result<()>,
{
use std::raw::TraitObject;
let mut s = rust_printer(box Vec::new());
f(&mut s).unwrap();
eof(&mut s.s).unwrap();
let wr = unsafe {
- // FIXME(pcwalton): A nasty function to extract the string from an `old_io::Writer`
+ // FIXME(pcwalton): A nasty function to extract the string from an `Write`
// that we "know" to be a `Vec<u8>` that works around the lack of checked
// downcasts.
let obj: &TraitObject = mem::transmute(&s.s.out);
pub mod with_hygiene {
use abi;
use ast;
- use std::old_io::IoResult;
+ use std::io;
use super::indent_unit;
// This function is the trick that all the rest of the routines
// hang on.
pub fn to_string_hyg<F>(f: F) -> String where
- F: FnOnce(&mut super::State) -> IoResult<()>,
+ F: FnOnce(&mut super::State) -> io::Result<()>,
{
super::to_string(move |s| {
s.encode_idents_with_hygiene = true;
}
impl<'a> State<'a> {
- pub fn ibox(&mut self, u: usize) -> IoResult<()> {
+ pub fn ibox(&mut self, u: usize) -> io::Result<()> {
self.boxes.push(pp::Breaks::Inconsistent);
pp::ibox(&mut self.s, u)
}
- pub fn end(&mut self) -> IoResult<()> {
+ pub fn end(&mut self) -> io::Result<()> {
self.boxes.pop().unwrap();
pp::end(&mut self.s)
}
- pub fn cbox(&mut self, u: usize) -> IoResult<()> {
+ pub fn cbox(&mut self, u: usize) -> io::Result<()> {
self.boxes.push(pp::Breaks::Consistent);
pp::cbox(&mut self.s, u)
}
// "raw box"
- pub fn rbox(&mut self, u: usize, b: pp::Breaks) -> IoResult<()> {
+ pub fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
self.boxes.push(b);
pp::rbox(&mut self.s, u, b)
}
- pub fn nbsp(&mut self) -> IoResult<()> { word(&mut self.s, " ") }
+ pub fn nbsp(&mut self) -> io::Result<()> { word(&mut self.s, " ") }
- pub fn word_nbsp(&mut self, w: &str) -> IoResult<()> {
+ pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
try!(word(&mut self.s, w));
self.nbsp()
}
- pub fn word_space(&mut self, w: &str) -> IoResult<()> {
+ pub fn word_space(&mut self, w: &str) -> io::Result<()> {
try!(word(&mut self.s, w));
space(&mut self.s)
}
- pub fn popen(&mut self) -> IoResult<()> { word(&mut self.s, "(") }
+ pub fn popen(&mut self) -> io::Result<()> { word(&mut self.s, "(") }
- pub fn pclose(&mut self) -> IoResult<()> { word(&mut self.s, ")") }
+ pub fn pclose(&mut self) -> io::Result<()> { word(&mut self.s, ")") }
- pub fn head(&mut self, w: &str) -> IoResult<()> {
+ pub fn head(&mut self, w: &str) -> io::Result<()> {
// outer-box is consistent
try!(self.cbox(indent_unit));
// head-box is inconsistent
Ok(())
}
- pub fn bopen(&mut self) -> IoResult<()> {
+ pub fn bopen(&mut self) -> io::Result<()> {
try!(word(&mut self.s, "{"));
self.end() // close the head-box
}
pub fn bclose_(&mut self, span: codemap::Span,
- indented: usize) -> IoResult<()> {
+ indented: usize) -> io::Result<()> {
self.bclose_maybe_open(span, indented, true)
}
pub fn bclose_maybe_open (&mut self, span: codemap::Span,
- indented: usize, close_box: bool) -> IoResult<()> {
+ indented: usize, close_box: bool) -> io::Result<()> {
try!(self.maybe_print_comment(span.hi));
try!(self.break_offset_if_not_bol(1, -(indented as isize)));
try!(word(&mut self.s, "}"));
}
Ok(())
}
- pub fn bclose(&mut self, span: codemap::Span) -> IoResult<()> {
+ pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
self.bclose_(span, indent_unit)
}
}
}
- pub fn hardbreak_if_not_bol(&mut self) -> IoResult<()> {
+ pub fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
if !self.is_bol() {
try!(hardbreak(&mut self.s))
}
Ok(())
}
- pub fn space_if_not_bol(&mut self) -> IoResult<()> {
+ pub fn space_if_not_bol(&mut self) -> io::Result<()> {
if !self.is_bol() { try!(space(&mut self.s)); }
Ok(())
}
pub fn break_offset_if_not_bol(&mut self, n: usize,
- off: isize) -> IoResult<()> {
+ off: isize) -> io::Result<()> {
if !self.is_bol() {
break_offset(&mut self.s, n, off)
} else {
// Synthesizes a comment that was not textually present in the original source
// file.
- pub fn synth_comment(&mut self, text: String) -> IoResult<()> {
+ pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
try!(word(&mut self.s, "/*"));
try!(space(&mut self.s));
try!(word(&mut self.s, &text[..]));
word(&mut self.s, "*/")
}
- pub fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> IoResult<()> where
- F: FnMut(&mut State, &T) -> IoResult<()>,
+ pub fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()> where
+ F: FnMut(&mut State, &T) -> io::Result<()>,
{
try!(self.rbox(0, b));
let mut first = true;
b: Breaks,
elts: &[T],
mut op: F,
- mut get_span: G) -> IoResult<()> where
- F: FnMut(&mut State, &T) -> IoResult<()>,
+ mut get_span: G) -> io::Result<()> where
+ F: FnMut(&mut State, &T) -> io::Result<()>,
G: FnMut(&T) -> codemap::Span,
{
try!(self.rbox(0, b));
}
pub fn commasep_exprs(&mut self, b: Breaks,
- exprs: &[P<ast::Expr>]) -> IoResult<()> {
+ exprs: &[P<ast::Expr>]) -> io::Result<()> {
self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
}
pub fn print_mod(&mut self, _mod: &ast::Mod,
- attrs: &[ast::Attribute]) -> IoResult<()> {
+ attrs: &[ast::Attribute]) -> io::Result<()> {
try!(self.print_inner_attributes(attrs));
for item in &_mod.items {
try!(self.print_item(&**item));
}
pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
- attrs: &[ast::Attribute]) -> IoResult<()> {
+ attrs: &[ast::Attribute]) -> io::Result<()> {
try!(self.print_inner_attributes(attrs));
for item in &nmod.items {
try!(self.print_foreign_item(&**item));
}
pub fn print_opt_lifetime(&mut self,
- lifetime: &Option<ast::Lifetime>) -> IoResult<()> {
+ lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
if let Some(l) = *lifetime {
try!(self.print_lifetime(&l));
try!(self.nbsp());
Ok(())
}
- pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
+ pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
try!(self.maybe_print_comment(ty.span.lo));
try!(self.ibox(0));
match ty.node {
}
pub fn print_foreign_item(&mut self,
- item: &ast::ForeignItem) -> IoResult<()> {
+ item: &ast::ForeignItem) -> io::Result<()> {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(item.span.lo));
try!(self.print_outer_attributes(&item.attrs));
}
fn print_associated_type(&mut self, typedef: &ast::AssociatedType)
- -> IoResult<()>
+ -> io::Result<()>
{
try!(self.print_outer_attributes(&typedef.attrs));
try!(self.word_space("type"));
word(&mut self.s, ";")
}
- fn print_typedef(&mut self, typedef: &ast::Typedef) -> IoResult<()> {
+ fn print_typedef(&mut self, typedef: &ast::Typedef) -> io::Result<()> {
try!(self.word_space("type"));
try!(self.print_ident(typedef.ident));
try!(space(&mut self.s));
}
/// Pretty-print an item
- pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
+ pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(item.span.lo));
try!(self.print_outer_attributes(&item.attrs));
self.ann.post(self, NodeItem(item))
}
- fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
+ fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
self.print_path(&t.path, false, 0)
}
- fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> IoResult<()> {
+ fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
if !lifetimes.is_empty() {
try!(word(&mut self.s, "for<"));
let mut comma = false;
Ok(())
}
- fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> IoResult<()> {
+ fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
self.print_trait_ref(&t.trait_ref)
}
pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
generics: &ast::Generics, ident: ast::Ident,
span: codemap::Span,
- visibility: ast::Visibility) -> IoResult<()> {
+ visibility: ast::Visibility) -> io::Result<()> {
try!(self.head(&visibility_qualified(visibility, "enum")));
try!(self.print_ident(ident));
try!(self.print_generics(generics));
pub fn print_variants(&mut self,
variants: &[P<ast::Variant>],
- span: codemap::Span) -> IoResult<()> {
+ span: codemap::Span) -> io::Result<()> {
try!(self.bopen());
for v in variants {
try!(self.space_if_not_bol());
self.bclose(span)
}
- pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
+ pub fn print_visibility(&mut self, vis: ast::Visibility) -> io::Result<()> {
match vis {
ast::Public => self.word_nbsp("pub"),
ast::Inherited => Ok(())
struct_def: &ast::StructDef,
generics: &ast::Generics,
ident: ast::Ident,
- span: codemap::Span) -> IoResult<()> {
+ span: codemap::Span) -> io::Result<()> {
try!(self.print_ident(ident));
try!(self.print_generics(generics));
if ast_util::struct_def_is_tuple_like(struct_def) {
/// appropriate macro, transcribe back into the grammar we just parsed from,
/// and then pretty-print the resulting AST nodes (so, e.g., we print
/// expression arguments as expressions). It can be done! I think.
- pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
+ pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
match *tt {
ast::TtToken(_, ref tk) => {
try!(word(&mut self.s, &token_to_string(tk)));
}
}
- pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
+ pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
try!(self.ibox(0));
let mut suppress_space = false;
for (i, tt) in tts.iter().enumerate() {
self.end()
}
- pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
+ pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
try!(self.print_visibility(v.node.vis));
match v.node.kind {
ast::TupleVariantKind(ref args) => {
}
}
- pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
+ pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> io::Result<()> {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(m.span.lo));
try!(self.print_outer_attributes(&m.attrs));
}
pub fn print_trait_method(&mut self,
- m: &ast::TraitItem) -> IoResult<()> {
+ m: &ast::TraitItem) -> io::Result<()> {
match *m {
RequiredMethod(ref ty_m) => self.print_ty_method(ty_m),
ProvidedMethod(ref m) => self.print_method(&**m),
}
}
- pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> IoResult<()> {
+ pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
match *ii {
MethodImplItem(ref m) => self.print_method(&**m),
TypeImplItem(ref td) => self.print_typedef(&**td),
}
}
- pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
+ pub fn print_method(&mut self, meth: &ast::Method) -> io::Result<()> {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(meth.span.lo));
try!(self.print_outer_attributes(&meth.attrs));
}
pub fn print_outer_attributes(&mut self,
- attrs: &[ast::Attribute]) -> IoResult<()> {
+ attrs: &[ast::Attribute]) -> io::Result<()> {
let mut count = 0;
for attr in attrs {
match attr.node.style {
}
pub fn print_inner_attributes(&mut self,
- attrs: &[ast::Attribute]) -> IoResult<()> {
+ attrs: &[ast::Attribute]) -> io::Result<()> {
let mut count = 0;
for attr in attrs {
match attr.node.style {
Ok(())
}
- pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
+ pub fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(attr.span.lo));
if attr.node.is_sugared_doc {
}
- pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
+ pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
try!(self.maybe_print_comment(st.span.lo));
match st.node {
ast::StmtDecl(ref decl, _) => {
self.maybe_print_trailing_comment(st.span, None)
}
- pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
+ pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
self.print_block_with_attrs(blk, &[])
}
- pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
+ pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
self.print_block_unclosed_indent(blk, indent_unit)
}
pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
- indented: usize) -> IoResult<()> {
+ indented: usize) -> io::Result<()> {
self.print_block_maybe_unclosed(blk, indented, &[], false)
}
pub fn print_block_with_attrs(&mut self,
blk: &ast::Block,
- attrs: &[ast::Attribute]) -> IoResult<()> {
+ attrs: &[ast::Attribute]) -> io::Result<()> {
self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
}
blk: &ast::Block,
indented: usize,
attrs: &[ast::Attribute],
- close_box: bool) -> IoResult<()> {
+ close_box: bool) -> io::Result<()> {
match blk.rules {
ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
ast::DefaultBlock => ()
self.ann.post(self, NodeBlock(blk))
}
- fn print_else(&mut self, els: Option<&ast::Expr>) -> IoResult<()> {
+ fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
match els {
Some(_else) => {
match _else.node {
}
pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
- elseopt: Option<&ast::Expr>) -> IoResult<()> {
+ elseopt: Option<&ast::Expr>) -> io::Result<()> {
try!(self.head("if"));
try!(self.print_expr(test));
try!(space(&mut self.s));
}
pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
- elseopt: Option<&ast::Expr>) -> IoResult<()> {
+ elseopt: Option<&ast::Expr>) -> io::Result<()> {
try!(self.head("if let"));
try!(self.print_pat(pat));
try!(space(&mut self.s));
}
pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
- -> IoResult<()> {
+ -> io::Result<()> {
match m.node {
// I think it's reasonable to hide the ctxt here:
ast::MacInvocTT(ref pth, ref tts, _) => {
}
- fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> IoResult<()> {
+ fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
try!(self.popen());
try!(self.commasep_exprs(Inconsistent, args));
self.pclose()
}
- pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
+ pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
let needs_par = needs_parentheses(expr);
if needs_par {
try!(self.popen());
fn print_expr_box(&mut self,
place: &Option<P<ast::Expr>>,
- expr: &ast::Expr) -> IoResult<()> {
+ expr: &ast::Expr) -> io::Result<()> {
try!(word(&mut self.s, "box"));
try!(word(&mut self.s, "("));
try!(place.as_ref().map_or(Ok(()), |e|self.print_expr(&**e)));
self.print_expr(expr)
}
- fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) -> IoResult<()> {
+ fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
try!(self.ibox(indent_unit));
try!(word(&mut self.s, "["));
try!(self.commasep_exprs(Inconsistent, &exprs[..]));
fn print_expr_repeat(&mut self,
element: &ast::Expr,
- count: &ast::Expr) -> IoResult<()> {
+ count: &ast::Expr) -> io::Result<()> {
try!(self.ibox(indent_unit));
try!(word(&mut self.s, "["));
try!(self.print_expr(element));
fn print_expr_struct(&mut self,
path: &ast::Path,
fields: &[ast::Field],
- wth: &Option<P<ast::Expr>>) -> IoResult<()> {
+ wth: &Option<P<ast::Expr>>) -> io::Result<()> {
try!(self.print_path(path, true, 0));
if !(fields.is_empty() && wth.is_none()) {
try!(word(&mut self.s, "{"));
Ok(())
}
- fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) -> IoResult<()> {
+ fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
try!(self.popen());
try!(self.commasep_exprs(Inconsistent, &exprs[..]));
if exprs.len() == 1 {
fn print_expr_call(&mut self,
func: &ast::Expr,
- args: &[P<ast::Expr>]) -> IoResult<()> {
+ args: &[P<ast::Expr>]) -> io::Result<()> {
try!(self.print_expr_maybe_paren(func));
self.print_call_post(args)
}
fn print_expr_method_call(&mut self,
ident: ast::SpannedIdent,
tys: &[P<ast::Ty>],
- args: &[P<ast::Expr>]) -> IoResult<()> {
+ args: &[P<ast::Expr>]) -> io::Result<()> {
let base_args = &args[1..];
try!(self.print_expr(&*args[0]));
try!(word(&mut self.s, "."));
fn print_expr_binary(&mut self,
op: ast::BinOp,
lhs: &ast::Expr,
- rhs: &ast::Expr) -> IoResult<()> {
+ rhs: &ast::Expr) -> io::Result<()> {
try!(self.print_expr(lhs));
try!(space(&mut self.s));
try!(self.word_space(ast_util::binop_to_string(op.node)));
fn print_expr_unary(&mut self,
op: ast::UnOp,
- expr: &ast::Expr) -> IoResult<()> {
+ expr: &ast::Expr) -> io::Result<()> {
try!(word(&mut self.s, ast_util::unop_to_string(op)));
self.print_expr_maybe_paren(expr)
}
fn print_expr_addr_of(&mut self,
mutability: ast::Mutability,
- expr: &ast::Expr) -> IoResult<()> {
+ expr: &ast::Expr) -> io::Result<()> {
try!(word(&mut self.s, "&"));
try!(self.print_mutability(mutability));
self.print_expr_maybe_paren(expr)
}
- pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
+ pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
try!(self.maybe_print_comment(expr.span.lo));
try!(self.ibox(indent_unit));
try!(self.ann.pre(self, NodeExpr(expr)));
self.end()
}
- pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
+ pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
try!(self.print_pat(&*loc.pat));
if let Some(ref ty) = loc.ty {
try!(self.word_space(":"));
Ok(())
}
- pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
+ pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
try!(self.maybe_print_comment(decl.span.lo));
match decl.node {
ast::DeclLocal(ref loc) => {
}
}
- pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
+ pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
if self.encode_idents_with_hygiene {
let encoded = ident.encode_with_hygiene();
try!(word(&mut self.s, &encoded[..]))
self.ann.post(self, NodeIdent(&ident))
}
- pub fn print_usize(&mut self, i: usize) -> IoResult<()> {
+ pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
word(&mut self.s, &i.to_string())
}
- pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
+ pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
try!(word(&mut self.s, &token::get_name(name)));
self.ann.post(self, NodeName(&name))
}
pub fn print_for_decl(&mut self, loc: &ast::Local,
- coll: &ast::Expr) -> IoResult<()> {
+ coll: &ast::Expr) -> io::Result<()> {
try!(self.print_local_decl(loc));
try!(space(&mut self.s));
try!(self.word_space("in"));
path: &ast::Path,
colons_before_params: bool,
depth: usize)
- -> IoResult<()>
+ -> io::Result<()>
{
try!(self.maybe_print_comment(path.span.lo));
path: &ast::Path,
qself: &ast::QSelf,
colons_before_params: bool)
- -> IoResult<()>
+ -> io::Result<()>
{
try!(word(&mut self.s, "<"));
try!(self.print_type(&qself.ty));
fn print_path_parameters(&mut self,
parameters: &ast::PathParameters,
colons_before_params: bool)
- -> IoResult<()>
+ -> io::Result<()>
{
if parameters.is_empty() {
return Ok(());
Ok(())
}
- pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
+ pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
try!(self.maybe_print_comment(pat.span.lo));
try!(self.ann.pre(self, NodePat(pat)));
/* Pat isn't normalized, but the beauty of it
self.ann.post(self, NodePat(pat))
}
- fn print_arm(&mut self, arm: &ast::Arm) -> IoResult<()> {
+ fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
// I have no idea why this check is necessary, but here it
// is :(
if arm.attrs.is_empty() {
// Returns whether it printed anything
fn print_explicit_self(&mut self,
explicit_self: &ast::ExplicitSelf_,
- mutbl: ast::Mutability) -> IoResult<bool> {
+ mutbl: ast::Mutability) -> io::Result<bool> {
try!(self.print_mutability(mutbl));
match *explicit_self {
ast::SelfStatic => { return Ok(false); }
name: ast::Ident,
generics: &ast::Generics,
opt_explicit_self: Option<&ast::ExplicitSelf_>,
- vis: ast::Visibility) -> IoResult<()> {
+ vis: ast::Visibility) -> io::Result<()> {
try!(self.head(""));
try!(self.print_fn_header_info(unsafety, abi, vis));
try!(self.nbsp());
pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
opt_explicit_self: Option<&ast::ExplicitSelf_>)
- -> IoResult<()> {
+ -> io::Result<()> {
// It is unfortunate to duplicate the commasep logic, but we want the
// self type and the args all in the same box.
try!(self.rbox(0, Inconsistent));
pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
opt_explicit_self: Option<&ast::ExplicitSelf_>)
- -> IoResult<()> {
+ -> io::Result<()> {
try!(self.popen());
try!(self.print_fn_args(decl, opt_explicit_self));
if decl.variadic {
pub fn print_fn_block_args(
&mut self,
decl: &ast::FnDecl)
- -> IoResult<()> {
+ -> io::Result<()> {
try!(word(&mut self.s, "|"));
try!(self.print_fn_args(decl, None));
try!(word(&mut self.s, "|"));
}
pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
- -> IoResult<()> {
+ -> io::Result<()> {
match capture_clause {
ast::CaptureByValue => self.word_space("move"),
ast::CaptureByRef => Ok(()),
pub fn print_bounds(&mut self,
prefix: &str,
bounds: &[ast::TyParamBound])
- -> IoResult<()> {
+ -> io::Result<()> {
if !bounds.is_empty() {
try!(word(&mut self.s, prefix));
let mut first = true;
pub fn print_lifetime(&mut self,
lifetime: &ast::Lifetime)
- -> IoResult<()>
+ -> io::Result<()>
{
self.print_name(lifetime.name)
}
pub fn print_lifetime_def(&mut self,
lifetime: &ast::LifetimeDef)
- -> IoResult<()>
+ -> io::Result<()>
{
try!(self.print_lifetime(&lifetime.lifetime));
let mut sep = ":";
pub fn print_generics(&mut self,
generics: &ast::Generics)
- -> IoResult<()>
+ -> io::Result<()>
{
let total = generics.lifetimes.len() + generics.ty_params.len();
if total == 0 {
Ok(())
}
- pub fn print_ty_param(&mut self, param: &ast::TyParam) -> IoResult<()> {
+ pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
try!(self.print_ident(param.ident));
try!(self.print_bounds(":", ¶m.bounds));
match param.default {
}
pub fn print_where_clause(&mut self, generics: &ast::Generics)
- -> IoResult<()> {
+ -> io::Result<()> {
if generics.where_clause.predicates.len() == 0 {
return Ok(())
}
Ok(())
}
- pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
+ pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
try!(self.ibox(indent_unit));
match item.node {
ast::MetaWord(ref name) => {
self.end()
}
- pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
+ pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
match vp.node {
ast::ViewPathSimple(ident, ref path) => {
try!(self.print_path(path, false, 0));
}
pub fn print_mutability(&mut self,
- mutbl: ast::Mutability) -> IoResult<()> {
+ mutbl: ast::Mutability) -> io::Result<()> {
match mutbl {
ast::MutMutable => self.word_nbsp("mut"),
ast::MutImmutable => Ok(()),
}
}
- pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
+ pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
try!(self.print_mutability(mt.mutbl));
self.print_type(&*mt.ty)
}
- pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
+ pub fn print_arg(&mut self, input: &ast::Arg) -> io::Result<()> {
try!(self.ibox(indent_unit));
match input.ty.node {
ast::TyInfer => try!(self.print_pat(&*input.pat)),
self.end()
}
- pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
+ pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
if let ast::DefaultReturn(..) = decl.output {
return Ok(());
}
id: Option<ast::Ident>,
generics: &ast::Generics,
opt_explicit_self: Option<&ast::ExplicitSelf_>)
- -> IoResult<()> {
+ -> io::Result<()> {
try!(self.ibox(indent_unit));
try!(self.print_fn_header_info(Some(unsafety), abi, ast::Inherited));
pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
next_pos: Option<BytePos>)
- -> IoResult<()> {
+ -> io::Result<()> {
let cm = match self.cm {
Some(cm) => cm,
_ => return Ok(())
Ok(())
}
- pub fn print_remaining_comments(&mut self) -> IoResult<()> {
+ pub fn print_remaining_comments(&mut self) -> io::Result<()> {
// If there aren't any remaining comments, then we need to manually
// make sure there is a line break at the end.
if self.next_comment().is_none() {
Ok(())
}
- pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
+ pub fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
try!(self.maybe_print_comment(lit.span.lo));
match self.next_lit(lit.span.lo) {
Some(ref ltrl) => {
}
}
- pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
+ pub fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
loop {
match self.next_comment() {
Some(ref cmnt) => {
}
pub fn print_comment(&mut self,
- cmnt: &comments::Comment) -> IoResult<()> {
+ cmnt: &comments::Comment) -> io::Result<()> {
match cmnt.style {
comments::Mixed => {
assert_eq!(cmnt.lines.len(), 1);
}
pub fn print_string(&mut self, st: &str,
- style: ast::StrStyle) -> IoResult<()> {
+ style: ast::StrStyle) -> io::Result<()> {
let st = match style {
ast::CookedStr => {
(format!("\"{}\"", st.escape_default()))
}
pub fn print_opt_unsafety(&mut self,
- opt_unsafety: Option<ast::Unsafety>) -> IoResult<()> {
+ opt_unsafety: Option<ast::Unsafety>) -> io::Result<()> {
match opt_unsafety {
Some(unsafety) => self.print_unsafety(unsafety),
None => Ok(())
pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
opt_abi: Option<abi::Abi>)
- -> IoResult<()> {
+ -> io::Result<()> {
match opt_abi {
Some(abi::Rust) => Ok(()),
Some(abi) => {
}
pub fn print_extern_opt_abi(&mut self,
- opt_abi: Option<abi::Abi>) -> IoResult<()> {
+ opt_abi: Option<abi::Abi>) -> io::Result<()> {
match opt_abi {
Some(abi) => {
try!(self.word_nbsp("extern"));
pub fn print_fn_header_info(&mut self,
opt_unsafety: Option<ast::Unsafety>,
abi: abi::Abi,
- vis: ast::Visibility) -> IoResult<()> {
+ vis: ast::Visibility) -> io::Result<()> {
try!(word(&mut self.s, &visibility_qualified(vis, "")));
try!(self.print_opt_unsafety(opt_unsafety));
word(&mut self.s, "fn")
}
- pub fn print_unsafety(&mut self, s: ast::Unsafety) -> IoResult<()> {
+ pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
match s {
ast::Unsafety::Normal => Ok(()),
ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
#![feature(box_syntax)]
#![feature(collections)]
+#![feature(fs)]
#![feature(int_uint)]
+#![feature(io)]
#![feature(old_io)]
-#![feature(old_path)]
+#![feature(path)]
#![feature(rustc_private)]
#![feature(staged_api)]
-#![feature(unicode)]
#![feature(std_misc)]
-#![feature(os)]
+#![feature(unicode)]
#![cfg_attr(windows, feature(libc))]
#[macro_use] extern crate log;
//! ncurses-compatible compiled terminfo format parsing (term(5))
use std::collections::HashMap;
-use std::old_io;
+use std::io::prelude::*;
+use std::io;
use super::super::TermInfo;
// These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable.
"box1"];
/// Parse a compiled terminfo entry, using long capability names if `longnames` is true
-pub fn parse(file: &mut old_io::Reader, longnames: bool)
+pub fn parse(file: &mut Read, longnames: bool)
-> Result<Box<TermInfo>, String> {
macro_rules! try { ($e:expr) => (
match $e {
}
// Check magic number
- let magic = try!(file.read_le_u16());
+ let magic = try!(read_le_u16(file));
if magic != 0x011A {
return Err(format!("invalid magic number: expected {:x}, found {:x}",
0x011A as usize, magic as usize));
}
- let names_bytes = try!(file.read_le_i16()) as int;
- let bools_bytes = try!(file.read_le_i16()) as int;
- let numbers_count = try!(file.read_le_i16()) as int;
- let string_offsets_count = try!(file.read_le_i16()) as int;
- let string_table_bytes = try!(file.read_le_i16()) as int;
+ let names_bytes = try!(read_le_u16(file)) as int;
+ let bools_bytes = try!(read_le_u16(file)) as int;
+ let numbers_count = try!(read_le_u16(file)) as int;
+ let string_offsets_count = try!(read_le_u16(file)) as int;
+ let string_table_bytes = try!(read_le_u16(file)) as int;
assert!(names_bytes > 0);
}
// don't read NUL
- let bytes = try!(file.read_exact(names_bytes as uint - 1));
+ let bytes = try!(read_exact(file, names_bytes as uint - 1));
let names_str = match String::from_utf8(bytes) {
Ok(s) => s,
Err(_) => return Err("input not utf-8".to_string()),
.map(|s| s.to_string())
.collect();
- try!(file.read_byte()); // consume NUL
+ try!(read_byte(file)); // consume NUL
let mut bools_map = HashMap::new();
if bools_bytes != 0 {
for i in 0..bools_bytes {
- let b = try!(file.read_byte());
+ let b = try!(read_byte(file));
if b == 1 {
bools_map.insert(bnames[i as uint].to_string(), true);
}
}
if (bools_bytes + names_bytes) % 2 == 1 {
- try!(file.read_byte()); // compensate for padding
+ try!(read_byte(file)); // compensate for padding
}
let mut numbers_map = HashMap::new();
if numbers_count != 0 {
for i in 0..numbers_count {
- let n = try!(file.read_le_u16());
+ let n = try!(read_le_u16(file));
if n != 0xFFFF {
numbers_map.insert(nnames[i as uint].to_string(), n);
}
if string_offsets_count != 0 {
let mut string_offsets = Vec::with_capacity(10);
for _ in 0..string_offsets_count {
- string_offsets.push(try!(file.read_le_u16()));
+ string_offsets.push(try!(read_le_u16(file)));
}
- let string_table = try!(file.read_exact(string_table_bytes as uint));
+ let string_table = try!(read_exact(file, string_table_bytes as usize));
if string_table.len() != string_table_bytes as uint {
return Err("error: hit EOF before end of string \
})
}
+fn read_le_u16<R: Read + ?Sized>(r: &mut R) -> io::Result<u16> {
+ let mut b = [0; 2];
+ assert_eq!(try!(r.read(&mut b)), 2);
+ Ok((b[0] as u16) | ((b[1] as u16) << 8))
+}
+
+fn read_byte<R: Read + ?Sized>(r: &mut R) -> io::Result<u8> {
+ let mut b = [0; 1];
+ assert_eq!(try!(r.read(&mut b)), 1);
+ Ok(b[0])
+}
+
+fn read_exact<R: Read + ?Sized>(r: &mut R, sz: usize) -> io::Result<Vec<u8>> {
+ let mut v = Vec::with_capacity(sz);
+ try!(r.take(sz as u64).read_to_end(&mut v));
+ assert_eq!(v.len(), sz);
+ Ok(v)
+}
+
/// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> Box<TermInfo> {
let mut strings = HashMap::new();
//!
//! Does not support hashed database, only filesystem!
-use std::old_io::File;
-use std::old_io::fs::PathExtensions;
use std::env;
+use std::fs::File;
+use std::io::prelude::*;
+use std::path::PathBuf;
/// Return path to database entry for `term`
#[allow(deprecated)]
-pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> {
+pub fn get_dbpath_for_term(term: &str) -> Option<Box<PathBuf>> {
if term.len() == 0 {
return None;
}
- let homedir = ::std::os::homedir();
+ let homedir = env::home_dir();
let mut dirs_to_search = Vec::new();
let first_char = term.char_at(0);
// Find search directory
- match env::var("TERMINFO") {
- Ok(dir) => dirs_to_search.push(Path::new(dir)),
- Err(..) => {
+ match env::var_os("TERMINFO") {
+ Some(dir) => dirs_to_search.push(PathBuf::new(&dir)),
+ None => {
if homedir.is_some() {
// ncurses compatibility;
dirs_to_search.push(homedir.unwrap().join(".terminfo"))
match env::var("TERMINFO_DIRS") {
Ok(dirs) => for i in dirs.split(':') {
if i == "" {
- dirs_to_search.push(Path::new("/usr/share/terminfo"));
+ dirs_to_search.push(PathBuf::new("/usr/share/terminfo"));
} else {
- dirs_to_search.push(Path::new(i));
+ dirs_to_search.push(PathBuf::new(i));
}
},
// Found nothing in TERMINFO_DIRS, use the default paths:
// ~/.terminfo, ncurses will search /etc/terminfo, then
// /lib/terminfo, and eventually /usr/share/terminfo.
Err(..) => {
- dirs_to_search.push(Path::new("/etc/terminfo"));
- dirs_to_search.push(Path::new("/lib/terminfo"));
- dirs_to_search.push(Path::new("/usr/share/terminfo"));
+ dirs_to_search.push(PathBuf::new("/etc/terminfo"));
+ dirs_to_search.push(PathBuf::new("/lib/terminfo"));
+ dirs_to_search.push(PathBuf::new("/usr/share/terminfo"));
}
}
}
for p in &dirs_to_search {
if p.exists() {
let f = first_char.to_string();
- let newp = p.join_many(&[&f[..], term]);
+ let newp = p.join(&f).join(term);
if newp.exists() {
return Some(box newp);
}
// on some installations the dir is named after the hex of the char (e.g. OS X)
let f = format!("{:x}", first_char as uint);
- let newp = p.join_many(&[&f[..], term]);
+ let newp = p.join(&f).join(term);
if newp.exists() {
return Some(box newp);
}
fn test_get_dbpath_for_term() {
// woefully inadequate test coverage
// note: current tests won't work with non-standard terminfo hierarchies (e.g. OS X's)
- use std::os::{setenv, unsetenv};
+ use std::env;
// FIXME (#9639): This needs to handle non-utf8 paths
fn x(t: &str) -> String {
let p = get_dbpath_for_term(t).expect("no terminfo entry found");
- p.as_str().unwrap().to_string()
+ p.to_str().unwrap().to_string()
};
assert!(x("screen") == "/usr/share/terminfo/s/screen");
assert!(get_dbpath_for_term("") == None);
- setenv("TERMINFO_DIRS", ":");
+ env::set_var("TERMINFO_DIRS", ":");
assert!(x("screen") == "/usr/share/terminfo/s/screen");
- unsetenv("TERMINFO_DIRS");
+ env::remove_var("TERMINFO_DIRS");
}
#[test]
#![feature(core)]
#![feature(int_uint)]
#![feature(old_io)]
-#![feature(old_path)]
+#![feature(path)]
+#![feature(fs)]
#![feature(rustc_private)]
#![feature(staged_api)]
#![feature(std_misc)]
+#![feature(io)]
extern crate getopts;
extern crate serialize;
use std::any::Any;
use std::cmp;
use std::collections::BTreeMap;
+use std::env;
use std::fmt;
-use std::old_io::stdio::StdWriter;
-use std::old_io::{File, ChanReader, ChanWriter};
-use std::old_io;
+use std::fs::File;
+use std::io::{self, Write};
use std::iter::repeat;
use std::num::{Float, Int};
-use std::env;
+use std::old_io::stdio::StdWriter;
+use std::old_io::{ChanReader, ChanWriter};
+use std::old_io;
+use std::path::{PathBuf};
use std::sync::mpsc::{channel, Sender};
use std::thread;
use std::thunk::{Thunk, Invoke};
pub run_ignored: bool,
pub run_tests: bool,
pub run_benchmarks: bool,
- pub logfile: Option<Path>,
+ pub logfile: Option<PathBuf>,
pub nocapture: bool,
pub color: ColorConfig,
}
let run_ignored = matches.opt_present("ignored");
let logfile = matches.opt_str("logfile");
- let logfile = logfile.map(|s| Path::new(s));
+ let logfile = logfile.map(|s| PathBuf::new(&s));
let run_benchmarks = matches.opt_present("bench");
let run_tests = ! run_benchmarks ||
max_name_len: uint, // number of columns to fill when aligning names
}
+fn new2old(new: io::Error) -> old_io::IoError {
+ old_io::IoError {
+ kind: old_io::OtherIoError,
+ desc: "other error",
+ detail: Some(new.to_string()),
+ }
+}
+
impl<T: Writer> ConsoleTestState<T> {
pub fn new(opts: &TestOpts,
_: Option<T>) -> old_io::IoResult<ConsoleTestState<StdWriter>> {
let log_out = match opts.logfile {
- Some(ref path) => Some(try!(File::create(path))),
+ Some(ref path) => Some(try!(File::create(path).map_err(new2old))),
None => None
};
let out = match term::stdout() {
}
pub fn write_log(&mut self, test: &TestDesc,
- result: &TestResult) -> old_io::IoResult<()> {
+ result: &TestResult) -> io::Result<()> {
match self.log_out {
None => Ok(()),
Some(ref mut o) => {
TeFiltered(ref filtered_tests) => st.write_run_start(filtered_tests.len()),
TeWait(ref test, padding) => st.write_test_start(test, padding),
TeResult(test, result, stdout) => {
- try!(st.write_log(&test, &result));
+ try!(st.write_log(&test, &result).map_err(new2old));
try!(st.write_result(&result));
match result {
TrOk => st.passed += 1,
Pretty(_) => unreachable!()
};
- let apos = s.find_str("a").unwrap();
- let bpos = s.find_str("b").unwrap();
+ let apos = s.find("a").unwrap();
+ let bpos = s.find("b").unwrap();
assert!(apos < bpos);
}
//! Basic data structures for representing a book.
-use std::old_io::BufferedReader;
+use std::io::prelude::*;
+use std::io::BufReader;
use std::iter;
use std::iter::AdditiveIterator;
+use std::path::{Path, PathBuf};
pub struct BookItem {
pub title: String,
- pub path: Path,
- pub path_to_root: Path,
+ pub path: PathBuf,
+ pub path_to_root: PathBuf,
pub children: Vec<BookItem>,
}
}
/// Construct a book by parsing a summary (markdown table of contents).
-pub fn parse_summary<R: Reader>(input: R, src: &Path) -> Result<Book, Vec<String>> {
+pub fn parse_summary(input: &mut Read, src: &Path) -> Result<Book, Vec<String>> {
fn collapse(stack: &mut Vec<BookItem>,
top_items: &mut Vec<BookItem>,
to_level: usize) {
// always include the introduction
top_items.push(BookItem {
title: "Introduction".to_string(),
- path: Path::new("README.md"),
- path_to_root: Path::new("."),
+ path: PathBuf::new("README.md"),
+ path_to_root: PathBuf::new("."),
children: vec!(),
});
- for line_result in BufferedReader::new(input).lines() {
+ for line_result in BufReader::new(input).lines() {
let line = match line_result {
Ok(line) => line,
Err(err) => {
- errors.push(err.desc.to_string()); // FIXME: include detail
+ errors.push(err.to_string());
return Err(errors);
}
};
let title = line[start_bracket + 1..end_bracket].to_string();
let indent = &line[..star_idx];
- let path_from_root = match src.join(given_path).path_relative_from(src) {
- Some(p) => p,
+ let path_from_root = match src.join(given_path).relative_from(src) {
+ Some(p) => p.to_path_buf(),
None => {
errors.push(format!("paths in SUMMARY.md must be relative, \
but path '{}' for section '{}' is not.",
given_path, title));
- Path::new("")
+ PathBuf::new("")
}
};
- let path_to_root = Path::new(iter::repeat("../")
+ let path_to_root = PathBuf::new(&iter::repeat("../")
.take(path_from_root.components().count() - 1)
.collect::<String>());
let item = BookItem {
//! Implementation of the `build` subcommand, used to compile a book.
use std::env;
-use std::os;
-use std::old_io;
-use std::old_io::{fs, File, BufferedWriter, TempDir, IoResult};
+use std::fs::{self, File, TempDir};
+use std::io::prelude::*;
+use std::io::{self, BufWriter};
+use std::path::{Path, PathBuf};
use subcommand::Subcommand;
use term::Term;
-use error::{Error, CliResult, CommandResult};
+use error::{err, CliResult, CommandResult};
use book;
use book::{Book, BookItem};
use css;
pub fn parse_cmd(name: &str) -> Option<Box<Subcommand>> {
if name == "build" {
- Some(box Build as Box<Subcommand>)
+ Some(Box::new(Build))
} else {
None
}
}
-fn write_toc(book: &Book, path_to_root: &Path, out: &mut Writer) -> IoResult<()> {
+fn write_toc(book: &Book, path_to_root: &Path, out: &mut Write) -> io::Result<()> {
fn walk_items(items: &[BookItem],
section: &str,
path_to_root: &Path,
- out: &mut Writer) -> IoResult<()> {
+ out: &mut Write) -> io::Result<()> {
for (i, item) in items.iter().enumerate() {
try!(walk_item(item, &format!("{}{}.", section, i + 1)[..], path_to_root, out));
}
fn walk_item(item: &BookItem,
section: &str,
path_to_root: &Path,
- out: &mut Writer) -> IoResult<()> {
+ out: &mut Write) -> io::Result<()> {
try!(writeln!(out, "<li><a href='{}'><b>{}</b> {}</a>",
- path_to_root.join(item.path.with_extension("html")).display(),
+ path_to_root.join(&item.path.with_extension("html")).display(),
section,
item.title));
if !item.children.is_empty() {
fn render(book: &Book, tgt: &Path) -> CliResult<()> {
let tmp = try!(TempDir::new("rust-book"));
- for (section, item) in book.iter() {
- println!("{} {}", section, item.title);
-
- let out_path = tgt.join(item.path.dirname());
+ for (_section, item) in book.iter() {
+ let out_path = match item.path.parent() {
+ Some(p) => tgt.join(p),
+ None => tgt.to_path_buf(),
+ };
let src;
if env::args().len() < 3 {
- src = os::getcwd().unwrap().clone();
+ src = env::current_dir().unwrap().clone();
} else {
- src = Path::new(env::args().nth(2).unwrap().clone());
+ src = PathBuf::new(&env::args().nth(2).unwrap());
}
// preprocess the markdown, rerouting markdown references to html references
- let markdown_data = try!(File::open(&src.join(&item.path)).read_to_string());
- let preprocessed_path = tmp.path().join(item.path.filename().unwrap());
+ let mut markdown_data = String::new();
+ try!(File::open(&src.join(&item.path)).and_then(|mut f| {
+ f.read_to_string(&mut markdown_data)
+ }));
+ let preprocessed_path = tmp.path().join(item.path.file_name().unwrap());
{
let urls = markdown_data.replace(".md)", ".html)");
- try!(File::create(&preprocessed_path)
- .write_str(&urls[..]));
+ try!(File::create(&preprocessed_path).and_then(|mut f| {
+ f.write_all(urls.as_bytes())
+ }));
}
// write the prelude to a temporary HTML file for rustdoc inclusion
let prelude = tmp.path().join("prelude.html");
{
- let mut toc = BufferedWriter::new(try!(File::create(&prelude)));
+ let mut toc = BufWriter::new(try!(File::create(&prelude)));
try!(writeln!(&mut toc, r#"<div id="nav">
<button id="toggle-nav">
<span class="sr-only">Toggle navigation</span>
// write the postlude to a temporary HTML file for rustdoc inclusion
let postlude = tmp.path().join("postlude.html");
{
- let mut toc = BufferedWriter::new(try!(File::create(&postlude)));
- try!(toc.write_str(javascript::JAVASCRIPT));
+ let mut toc = BufWriter::new(try!(File::create(&postlude)));
+ try!(toc.write_all(javascript::JAVASCRIPT.as_bytes()));
try!(writeln!(&mut toc, "</div></div>"));
}
- try!(fs::mkdir_recursive(&out_path, old_io::USER_DIR));
+ try!(fs::create_dir_all(&out_path));
let rustdoc_args: &[String] = &[
"".to_string(),
if output_result != 0 {
let message = format!("Could not execute `rustdoc` with {:?}: {}",
rustdoc_args, output_result);
- return Err(box message as Box<Error>);
+ return Err(err(&message));
}
}
}
fn usage(&self) {}
fn execute(&mut self, term: &mut Term) -> CommandResult<()> {
- let cwd = os::getcwd().unwrap();
+ let cwd = env::current_dir().unwrap();
let src;
let tgt;
if env::args().len() < 3 {
src = cwd.clone();
} else {
- src = Path::new(env::args().nth(2).unwrap().clone());
+ src = PathBuf::new(&env::args().nth(2).unwrap());
}
if env::args().len() < 4 {
tgt = cwd.join("_book");
} else {
- tgt = Path::new(env::args().nth(3).unwrap().clone());
+ tgt = PathBuf::new(&env::args().nth(3).unwrap());
}
- try!(fs::mkdir(&tgt, old_io::USER_DIR));
+ try!(fs::create_dir(&tgt));
- try!(File::create(&tgt.join("rust-book.css")).write_str(css::STYLE));
+ try!(File::create(&tgt.join("rust-book.css")).and_then(|mut f| {
+ f.write_all(css::STYLE.as_bytes())
+ }));
- let summary = try!(File::open(&src.join("SUMMARY.md")));
- match book::parse_summary(summary, &src) {
+ let mut summary = try!(File::open(&src.join("SUMMARY.md")));
+ match book::parse_summary(&mut summary, &src) {
Ok(book) => {
// execute rustdoc on the whole book
render(&book, &tgt)
term.err(&format!("error: {}", err)[..]);
}
- Err(box format!("{} errors occurred", n) as Box<Error>)
+ Err(err(&format!("{} errors occurred", n)))
}
}
}
//! Error handling utilities. WIP.
+use std::error::Error;
use std::fmt;
-use std::fmt::{Debug, Formatter};
-
-use std::old_io::IoError;
pub type CliError = Box<Error + 'static>;
pub type CliResult<T> = Result<T, CliError>;
pub type CommandError = Box<Error + 'static>;
pub type CommandResult<T> = Result<T, CommandError>;
-pub trait Error {
- fn description(&self) -> &str;
-
- fn detail(&self) -> Option<&str> { None }
- fn cause(&self) -> Option<&Error> { None }
-}
-
-pub trait FromError<E> {
- fn from_err(err: E) -> Self;
-}
-
-impl Debug for Box<Error + 'static> {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- write!(f, "{}", self.description())
- }
-}
-
-impl<E: Error + 'static> FromError<E> for Box<Error + 'static> {
- fn from_err(err: E) -> Box<Error + 'static> {
- box err as Box<Error>
- }
-}
+pub fn err(s: &str) -> CliError {
+ struct E(String);
-impl<'a> Error for &'a str {
- fn description<'b>(&'b self) -> &'b str {
- *self
+ impl Error for E {
+ fn description(&self) -> &str { &self.0 }
}
-}
-
-impl Error for String {
- fn description<'a>(&'a self) -> &'a str {
- &self[..]
+ impl fmt::Display for E {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ self.0.fmt(f)
+ }
}
-}
-
-impl<'a> Error for Box<Error + 'a> {
- fn description(&self) -> &str { (**self).description() }
- fn detail(&self) -> Option<&str> { (**self).detail() }
- fn cause(&self) -> Option<&Error> { (**self).cause() }
-}
-
-impl FromError<()> for () {
- fn from_err(_: ()) -> () { () }
-}
-impl FromError<IoError> for IoError {
- fn from_err(error: IoError) -> IoError { error }
+ Box::new(E(s.to_string()))
}
-
-impl Error for IoError {
- fn description(&self) -> &str {
- self.desc
- }
- fn detail(&self) -> Option<&str> {
- self.detail.as_ref().map(|s| &s[..])
- }
-}
-
-
-//fn iter_map_err<T, U, E, I: Iterator<Result<T,E>>>(iter: I,
pub fn parse_cmd(name: &str) -> Option<Box<Subcommand>> {
match name {
- "help" | "--help" | "-h" | "-?" => Some(box Help as Box<Subcommand>),
+ "help" | "--help" | "-h" | "-?" => Some(Box::new(Help)),
_ => None
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
-#![feature(collections)]
+#![deny(warnings)]
+
#![feature(core)]
+#![feature(exit_status)]
+#![feature(fs)]
+#![feature(io)]
#![feature(old_io)]
-#![feature(env)]
-#![feature(os)]
-#![feature(old_path)]
+#![feature(path)]
#![feature(rustdoc)]
+#![feature(tempdir)]
extern crate rustdoc;
use std::env;
+use std::error::Error;
use subcommand::Subcommand;
use term::Term;
-macro_rules! try (
- ($expr:expr) => ({
- use error;
- match $expr {
- Ok(val) => val,
- Err(err) => return Err(error::FromError::from_err(err))
- }
- })
-);
-
mod term;
mod error;
mod book;
} else {
match subcommand::parse_name(&cmd[1][..]) {
Some(mut subcmd) => {
- match subcmd.parse_args(cmd.tail()) {
+ match subcmd.parse_args(&cmd[..cmd.len()-1]) {
Ok(_) => {
match subcmd.execute(&mut term) {
Ok(_) => (),
Err(err) => {
- term.err(&format!("error: {}", err.description())[..]);
- err.detail().map(|detail| {
- term.err(&format!("detail: {}", detail)[..]);
- });
+ term.err(&format!("error: {}", err));
}
}
}
pub fn parse_cmd(name: &str) -> Option<Box<Subcommand>> {
if name == "serve" {
- Some(box Serve as Box<Subcommand>)
+ Some(Box::new(Serve))
} else {
None
}
impl Term {
pub fn new() -> Term {
Term {
- err: box stdio::stderr() as Box<Writer>,
+ err: Box::new(stdio::stderr())
}
}
//! Implementation of the `test` subcommand. Just a stub for now.
use subcommand::Subcommand;
-use error::CliResult;
-use error::CommandResult;
-use error::Error;
+use error::{err, CliResult, CommandResult};
use term::Term;
use book;
-use std::old_io::{Command, File};
-use std::os;
+
+use std::fs::File;
+use std::env;
+use std::process::Command;
struct Test;
pub fn parse_cmd(name: &str) -> Option<Box<Subcommand>> {
if name == "test" {
- Some(box Test as Box<Subcommand>)
+ Some(Box::new(Test))
} else {
None
}
}
fn usage(&self) {}
fn execute(&mut self, term: &mut Term) -> CommandResult<()> {
- let cwd = os::getcwd().unwrap();
+ let cwd = env::current_dir().unwrap();
let src = cwd.clone();
- let summary = File::open(&src.join("SUMMARY.md"));
- match book::parse_summary(summary, &src) {
+ let mut summary = try!(File::open(&src.join("SUMMARY.md")));
+ match book::parse_summary(&mut summary, &src) {
Ok(book) => {
for (_, item) in book.iter() {
let output_result = Command::new("rustdoc")
Ok(output) => {
if !output.status.success() {
term.err(&format!("{}\n{}",
- String::from_utf8_lossy(&output.output[..]),
- String::from_utf8_lossy(&output.error[..]))[..]);
- return Err(box "Some tests failed." as Box<Error>);
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)));
+ return Err(err("some tests failed"));
}
}
Err(e) => {
- let message = format!("Could not execute `rustdoc`: {}", e);
- return Err(box message as Box<Error>);
+ let message = format!("could not execute `rustdoc`: {}", e);
+ return Err(err(&message))
}
}
}
for err in errors {
term.err(&err[..]);
}
- return Err(box "There was an error." as Box<Error>);
+ return Err(err("there was an error"))
}
}
Ok(()) // lol
--- /dev/null
+// Copyright 2013-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.
+
+#![crate_type = "rlib"]
+#![omit_gdb_pretty_printer_section]
+
+// no-prefer-dynamic
+// compile-flags:-g
+
+pub fn generic_function<T: Clone>(val: T) -> (T, T) {
+ let result = (val.clone(), val.clone());
+ let a_variable: u32 = 123456789;
+ let another_variable: f64 = 123456789.5;
+ zzz();
+ result
+}
+
+#[inline(never)]
+fn zzz() {()}
\ No newline at end of file
reg.register_macro("identity", expand_identity);
reg.register_syntax_extension(
token::intern("into_foo"),
- Modifier(box expand_into_foo));
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ Modifier(Box::new(expand_into_foo)));
reg.register_syntax_extension(
token::intern("into_multi_foo"),
- MultiModifier(box expand_into_foo_multi));
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ MultiModifier(Box::new(expand_into_foo_multi)));
}
fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
pub fn plugin_registrar(reg: &mut Registry) {
let args = reg.args().clone();
reg.register_syntax_extension(token::intern("plugin_args"),
- NormalTT(box Expander { args: args, }, None));
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ NormalTT(Box::new(Expander { args: args, }), None));
}
--- /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.
+
+// force-host
+
+#![crate_type="dylib"]
+#![feature(plugin_registrar, quote)]
+
+extern crate syntax;
+extern crate rustc;
+
+use syntax::codemap::Span;
+use syntax::parse::token::{self, str_to_ident, NtExpr, NtPat};
+use syntax::ast::{TokenTree, TtToken, Pat};
+use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacEager};
+use syntax::ext::build::AstBuilder;
+use syntax::ext::tt::macro_parser::{MatchedSeq, MatchedNonterminal};
+use syntax::ext::tt::macro_parser::{Success, Failure, Error};
+use syntax::ptr::P;
+use rustc::plugin::Registry;
+
+fn expand_mbe_matches(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
+ -> Box<MacResult + 'static> {
+
+ let mbe_matcher = quote_matcher!(cx, $matched:expr, $($pat:pat)|+);
+
+ let mac_expr = match TokenTree::parse(cx, &mbe_matcher[..], args) {
+ Success(map) => {
+ match (&*map[str_to_ident("matched")], &*map[str_to_ident("pat")]) {
+ (&MatchedNonterminal(NtExpr(ref matched_expr)),
+ &MatchedSeq(ref pats, seq_sp)) => {
+ let pats: Vec<P<Pat>> = pats.iter().map(|pat_nt|
+ if let &MatchedNonterminal(NtPat(ref pat)) = &**pat_nt {
+ pat.clone()
+ } else {
+ unreachable!()
+ }
+ ).collect();
+ let arm = cx.arm(seq_sp, pats, cx.expr_bool(seq_sp, true));
+
+ quote_expr!(cx,
+ match $matched_expr {
+ $arm
+ _ => false
+ }
+ )
+ }
+ _ => unreachable!()
+ }
+ }
+ Failure(_, s) | Error(_, s) => {
+ panic!("expected Success, but got Error/Failure: {}", s);
+ }
+ };
+
+ MacEager::expr(mac_expr)
+}
+
+#[plugin_registrar]
+pub fn plugin_registrar(reg: &mut Registry) {
+ reg.register_macro("matches", expand_mbe_matches);
+}
fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
match item.next {
None => {
- let mut entry = box Entry {
+ let mut entry: Box<_> = box Entry {
code: key,
count: 0,
next: None,
{
if self.items[index as usize].is_none() {
- let mut entry = box Entry {
+ let mut entry: Box<_> = box Entry {
code: key,
count: 0,
next: None,
fn next_color(&mut self, row: u8, col: u8, start_color: u8) -> bool {
if start_color < 10u8 {
// colors not yet used
- let mut avail = box Colors::new(start_color);
+ let mut avail: Box<_> = box Colors::new(start_color);
// drop colors already in use in neighbourhood
self.drop_colors(&mut *avail, row, col);
struct Bar(isize, isize);
fn main() {
- let x = (box 1, 2);
+ let x: (Box<_>, _) = (box 1, 2);
let r = &x.0;
let y = x; //~ ERROR cannot move out of `x` because it is borrowed
}
fn implicit() {
- let mut a = box 1;
+ let mut a: Box<_> = box 1;
// Note the danger here:
//
}
fn explicit() {
- let mut a = box 1;
+ let mut a: Box<_> = box 1;
add(
&*a,
rewrite(&mut a)); //~ ERROR cannot borrow
}
fn implicit() {
- let mut a = box 1;
+ let mut a: Box<_> = box 1;
// Note the danger here:
//
}
fn explicit() {
- let mut a = box 1;
+ let mut a: Box<_> = box 1;
add(
&*a,
a); //~ ERROR cannot move
}
pub fn main() {
- let a = box A;
+ let a: Box<_> = box A;
a.foo();
//~^ ERROR cannot borrow immutable `Box` content `*a` as mutable
}
use std::collections::HashMap;
fn main() {
- let tmp;
+ let tmp: Box<_>;
let mut buggy_map: HashMap<usize, &usize> = HashMap::new();
- buggy_map.insert(42, &*box 1); //~ ERROR borrowed value does not live long enough
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ buggy_map.insert(42, &*Box::new(1)); //~ ERROR borrowed value does not live long enough
// but it is ok if we use a temporary
tmp = box 2;
}
fn copy_after_move() {
- let a = box A { x: box 0, y: 1 };
+ let a: Box<_> = box A { x: box 0, y: 1 };
let _x = a.x;
let _y = a.y; //~ ERROR use of moved
//~^^ NOTE `a` moved here (through moving `a.x`)
}
fn move_after_move() {
- let a = box B { x: box 0, y: box 1 };
+ let a: Box<_> = box B { x: box 0, y: box 1 };
let _x = a.x;
let _y = a.y; //~ ERROR use of moved
//~^^ NOTE `a` moved here (through moving `a.x`)
}
fn borrow_after_move() {
- let a = box A { x: box 0, y: 1 };
+ let a: Box<_> = box A { x: box 0, y: 1 };
let _x = a.x;
let _y = &a.y; //~ ERROR use of moved
//~^^ NOTE `a` moved here (through moving `a.x`)
}
fn move_after_borrow() {
- let a = box B { x: box 0, y: box 1 };
+ let a: Box<_> = box B { x: box 0, y: box 1 };
let _x = &a.x;
let _y = a.y; //~ ERROR cannot move
}
fn copy_after_mut_borrow() {
- let mut a = box A { x: box 0, y: 1 };
+ let mut a: Box<_> = box A { x: box 0, y: 1 };
let _x = &mut a.x;
let _y = a.y; //~ ERROR cannot use
}
fn move_after_mut_borrow() {
- let mut a = box B { x: box 0, y: box 1 };
+ let mut a: Box<_> = box B { x: box 0, y: box 1 };
let _x = &mut a.x;
let _y = a.y; //~ ERROR cannot move
}
fn borrow_after_mut_borrow() {
- let mut a = box A { x: box 0, y: 1 };
+ let mut a: Box<_> = box A { x: box 0, y: 1 };
let _x = &mut a.x;
let _y = &a.y; //~ ERROR cannot borrow
}
fn mut_borrow_after_borrow() {
- let mut a = box A { x: box 0, y: 1 };
+ let mut a: Box<_> = box A { x: box 0, y: 1 };
let _x = &a.x;
let _y = &mut a.y; //~ ERROR cannot borrow
}
fn copy_after_move_nested() {
- let a = box C { x: box A { x: box 0, y: 1 }, y: 2 };
+ let a: Box<_> = box C { x: box A { x: box 0, y: 1 }, y: 2 };
let _x = a.x.x;
let _y = a.y; //~ ERROR use of collaterally moved
}
fn move_after_move_nested() {
- let a = box D { x: box A { x: box 0, y: 1 }, y: box 2 };
+ let a: Box<_> = box D { x: box A { x: box 0, y: 1 }, y: box 2 };
let _x = a.x.x;
let _y = a.y; //~ ERROR use of collaterally moved
}
fn borrow_after_move_nested() {
- let a = box C { x: box A { x: box 0, y: 1 }, y: 2 };
+ let a: Box<_> = box C { x: box A { x: box 0, y: 1 }, y: 2 };
let _x = a.x.x;
let _y = &a.y; //~ ERROR use of collaterally moved
}
fn move_after_borrow_nested() {
- let a = box D { x: box A { x: box 0, y: 1 }, y: box 2 };
+ let a: Box<_> = box D { x: box A { x: box 0, y: 1 }, y: box 2 };
let _x = &a.x.x;
let _y = a.y; //~ ERROR cannot move
}
fn copy_after_mut_borrow_nested() {
- let mut a = box C { x: box A { x: box 0, y: 1 }, y: 2 };
+ let mut a: Box<_> = box C { x: box A { x: box 0, y: 1 }, y: 2 };
let _x = &mut a.x.x;
let _y = a.y; //~ ERROR cannot use
}
fn move_after_mut_borrow_nested() {
- let mut a = box D { x: box A { x: box 0, y: 1 }, y: box 2 };
+ let mut a: Box<_> = box D { x: box A { x: box 0, y: 1 }, y: box 2 };
let _x = &mut a.x.x;
let _y = a.y; //~ ERROR cannot move
}
fn borrow_after_mut_borrow_nested() {
- let mut a = box C { x: box A { x: box 0, y: 1 }, y: 2 };
+ let mut a: Box<_> = box C { x: box A { x: box 0, y: 1 }, y: 2 };
let _x = &mut a.x.x;
let _y = &a.y; //~ ERROR cannot borrow
}
fn mut_borrow_after_borrow_nested() {
- let mut a = box C { x: box A { x: box 0, y: 1 }, y: 2 };
+ let mut a: Box<_> = box C { x: box A { x: box 0, y: 1 }, y: 2 };
let _x = &a.x.x;
let _y = &mut a.y; //~ ERROR cannot borrow
}
// Ensure that invoking a closure counts as a unique immutable borrow
#![feature(unboxed_closures)]
-#![feature(box_syntax)]
type Fn<'a> = Box<FnMut() + 'a>;
f: Box<FnMut() + 'a>
}
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
fn call<F>(mut f: F) where F: FnMut(Fn) {
- f(box || {
+ f(Box::new(|| {
//~^ ERROR: cannot borrow `f` as mutable more than once
- f(box || {})
- });
+ f((Box::new(|| {})))
+ }));
}
fn test1() {
fn test7() {
fn foo<F>(_: F) where F: FnMut(Box<FnMut(isize)>, isize) {}
let mut f = |g: Box<FnMut(isize)>, b: isize| {};
- f(box |a| {
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ f(Box::new(|a| {
foo(f);
//~^ ERROR cannot move `f` into closure because it is borrowed
//~| ERROR cannot move out of captured outer variable in an `FnMut` closure
- }, 3);
+ }), 3);
}
fn main() {}
}
fn f() {
- let mut x = box 3;
+ let mut x: Box<_> = box 3;
let c1 = || get(&*x);
*x = 5; //~ ERROR cannot assign
}
f: Box<isize>
}
- let mut x = box Foo { f: box 3 };
+ let mut x: Box<_> = box Foo { f: box 3 };
let c1 = || get(&*x.f);
*x.f = 5; //~ ERROR cannot assign to `*x.f`
}
f: Box<isize>
}
- let mut x = box Foo { f: box 3 };
+ let mut x: Box<_> = box Foo { f: box 3 };
let c1 = || get(&*x.f);
let c2 = || *x.f = 5; //~ ERROR cannot borrow `x` as mutable
}
f: Box<isize>
}
- let mut x = box Foo { f: box 3 };
+ let mut x: Box<_> = box Foo { f: box 3 };
let c1 = to_fn_mut(|| set(&mut *x.f));
let c2 = to_fn_mut(|| set(&mut *x.f));
//~^ ERROR cannot borrow `x` as mutable more than once
}
fn main() {
- let mut ptr = box Foo { x: 0 };
+ let mut ptr: Box<_> = box Foo { x: 0 };
let mut test = |foo: &Foo| {
ptr = box Foo { x: ptr.x + 1 };
};
for &a in &f.a { //~ ERROR cannot move out
}
- let x = Some(box 1);
+ let x: Option<Box<_>> = Some(box 1);
for &a in x.iter() { //~ ERROR cannot move out
}
}
fn borrow_in_var_from_var() {
let mut x: isize = 1;
- let y = box &mut x;
+ let y: Box<_> = box &mut x;
let p = &y;
let q = &***p;
**y = 2; //~ ERROR cannot assign to `**y` because it is borrowed
fn borrow_in_var_from_field() {
let mut x = A { a: 1 };
- let y = box &mut x.a;
+ let y: Box<_> = box &mut x.a;
let p = &y;
let q = &***p;
**y = 2; //~ ERROR cannot assign to `**y` because it is borrowed
#![feature(box_syntax)]
fn main() {
- let x = Some(box 1);
+ let x: Option<Box<_>> = Some(box 1);
match x {
Some(ref _y) => {
let _a = x; //~ ERROR cannot move
#![feature(box_syntax)]
fn main() {
- let x = Some(box 1);
+ let x: Option<Box<_>> = Some(box 1);
match x {
Some(ref y) => {
let _b = *y; //~ ERROR cannot move out
// In this instance, the freeze is conditional and starts before
// the mut borrow.
- let mut v = box 3;
+ let mut v: Box<_> = box 3;
let _w;
if cond() {
_w = &v;
// In this instance, the freeze and mut borrow are on separate sides
// of the if.
- let mut v = box 3;
+ let mut v: Box<_> = box 3;
let _w;
if cond() {
_w = &v;
fn loop_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire loop.
- let mut v = box 3;
+ let mut v: Box<_> = box 3;
let mut x = &mut v;
**x += 1;
loop {
fn block_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire closure call.
- let mut v = box 3;
+ let mut v: Box<_> = box 3;
let mut x = &mut v;
for _ in 0..3 {
borrow(&*v); //~ ERROR cannot borrow
fn loop_aliased_mut() {
// In this instance, the borrow is carried through the loop.
- let mut v = box 3;
- let mut w = box 4;
+ let mut v: Box<_> = box 3;
+ let mut w: Box<_> = box 4;
let mut _x = &w;
loop {
borrow_mut(&mut *v); //~ ERROR cannot borrow
fn while_aliased_mut() {
// In this instance, the borrow is carried through the loop.
- let mut v = box 3;
- let mut w = box 4;
+ let mut v: Box<_> = box 3;
+ let mut w: Box<_> = box 4;
let mut _x = &w;
while cond() {
borrow_mut(&mut *v); //~ ERROR cannot borrow
fn loop_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
- let mut v = box 3;
- let mut w = box 4;
+ let mut v: Box<_> = box 3;
+ let mut w: Box<_> = box 4;
let mut _x = &w;
loop {
borrow_mut(&mut *v);
fn while_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
- let mut v = box 3;
- let mut w = box 4;
+ let mut v: Box<_> = box 3;
+ let mut w: Box<_> = box 4;
let mut _x = &w;
while cond() {
borrow_mut(&mut *v);
}
fn while_aliased_mut_cond(cond: bool, cond2: bool) {
- let mut v = box 3;
- let mut w = box 4;
+ let mut v: Box<_> = box 3;
+ let mut w: Box<_> = box 4;
let mut x = &mut w;
while cond {
**x += 1;
fn pre_freeze() {
// In this instance, the freeze starts before the mut borrow.
- let mut v = box 3;
+ let mut v: Box<_> = box 3;
let _w = &v;
borrow_mut(&mut *v); //~ ERROR cannot borrow
}
fn post_freeze() {
// In this instance, the const alias starts after the borrow.
- let mut v = box 3;
+ let mut v: Box<_> = box 3;
borrow_mut(&mut *v);
let _w = &v;
}
}
fn box_imm() {
- let v = box 3;
+ let v: Box<_> = box 3;
let _w = &v;
thread::spawn(move|| {
println!("v={}", *v);
}
fn box_imm_explicit() {
- let v = box 3;
+ let v: Box<_> = box 3;
let _w = &v;
thread::spawn(move|| {
println!("v={}", *v);
}
fn box_imm() {
- let mut v = box 3;
+ let mut v: Box<_> = box 3;
borrow(&*v,
|w| { //~ ERROR cannot borrow `v` as mutable
v = box 4;
fn to_fn_once<A,F:FnOnce<A>>(f: F) -> F { f }
pub fn main() {
- let bar = box 3;
+ let bar: Box<_> = box 3;
let _g = to_fn_mut(|| {
let _h = to_fn_once(move || -> isize { *bar }); //~ ERROR cannot move out of
});
#![feature(box_syntax)]
fn main() {
- let a = box box 2;
+ let a: Box<Box<_>> = box box 2;
let b = &a;
let z = *a; //~ ERROR: cannot move out of `*a` because it is borrowed
}
fn main() {
- let t = box 3;
+ let t: Box<_> = box 3;
call_f(move|| { *t + 1 });
call_f(move|| { *t + 1 }); //~ ERROR capture of moved value
fn borrow<T>(_: &T) { }
fn different_vars_after_borrows() {
- let x1 = box 1;
+ let x1: Box<_> = box 1;
let p1 = &x1;
- let x2 = box 2;
+ let x2: Box<_> = box 2;
let p2 = &x2;
thread::spawn(move|| {
drop(x1); //~ ERROR cannot move `x1` into closure because it is borrowed
}
fn different_vars_after_moves() {
- let x1 = box 1;
+ let x1: Box<_> = box 1;
drop(x1);
- let x2 = box 2;
+ let x2: Box<_> = box 2;
drop(x2);
thread::spawn(move|| {
drop(x1); //~ ERROR capture of moved value: `x1`
}
fn same_var_after_borrow() {
- let x = box 1;
+ let x: Box<_> = box 1;
let p = &x;
thread::spawn(move|| {
drop(x); //~ ERROR cannot move `x` into closure because it is borrowed
}
fn same_var_after_move() {
- let x = box 1;
+ let x: Box<_> = box 1;
drop(x);
thread::spawn(move|| {
drop(x); //~ ERROR capture of moved value: `x`
empty
}
fn main() {
- let mut x = box cycle::node(node_ {a: box cycle::empty});
+ let mut x: Box<_> = box cycle::node(node_ {a: box cycle::empty});
// Create a cycle!
match *x {
cycle::node(ref mut y) => {
}
fn main() {
- let v = MyVec { data: vec!(box 1, box 2, box 3) };
+ let v = MyVec::<Box<_>> { data: vec!(box 1, box 2, box 3) };
let good = &v[0]; // Shouldn't fail here
let bad = v[0];
//~^ ERROR cannot move out of indexed content
fn borrow(_v: &isize) {}
fn local() {
- let mut v = box 3;
+ let mut v: Box<_> = box 3;
borrow(&*v);
}
}
fn aliased_imm() {
- let mut v = box 3;
+ let mut v: Box<_> = box 3;
let _w = &v;
borrow(&*v);
}
fn aliased_mut() {
- let mut v = box 3;
+ let mut v: Box<_> = box 3;
let _w = &mut v;
borrow(&*v); //~ ERROR cannot borrow `*v`
}
fn aliased_other() {
- let mut v = box 3;
- let mut w = box 4;
+ let mut v: Box<_> = box 3;
+ let mut w: Box<_> = box 4;
let _x = &mut w;
borrow(&*v);
}
fn aliased_other_reassign() {
- let mut v = box 3;
- let mut w = box 4;
+ let mut v: Box<_> = box 3;
+ let mut w: Box<_> = box 4;
let mut _x = &mut w;
_x = &mut v;
borrow(&*v); //~ ERROR cannot borrow `*v`
// Test that cross-borrowing (implicitly converting from `Box<T>` to `&T`) is
// forbidden when `T` is a trait.
-#![feature(box_syntax)]
-
struct Foo;
trait Trait { fn foo(&self) {} }
impl Trait for Foo {}
pub fn main() {
- let x: Box<Trait> = box Foo;
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let x: Box<Trait> = Box::new(Foo);
let _y: &Trait = x; //~ ERROR mismatched types
//~| expected `&Trait`
//~| found `Box<Trait>`
// Forbid assignment into a dynamically sized type.
-#![feature(box_syntax)]
-
struct Fat<T: ?Sized> {
f1: isize,
f2: &'static str,
pub fn main() {
// Assignment.
let f5: &mut Fat<ToBar> = &mut Fat { f1: 5, f2: "some str", ptr: Bar1 {f :42} };
- let z: Box<ToBar> = box Bar1 {f: 36};
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let z: Box<ToBar> = Box::new(Bar1 {f: 36});
f5.ptr = *z;
//~^ ERROR the trait `core::marker::Sized` is not implemented
}
// Forbid assignment into a dynamically sized type.
-#![feature(box_syntax)]
-
struct Fat<T: ?Sized> {
f1: isize,
f2: &'static str,
pub fn main() {
// Assignment.
let f5: &mut Fat<ToBar> = &mut Fat { f1: 5, f2: "some str", ptr: Bar1 {f :42} };
- let z: Box<ToBar> = box Bar1 {f: 36};
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let z: Box<ToBar> = Box::new(Bar1 {f: 36});
f5.ptr = Bar1 {f: 36};
//~^ ERROR mismatched types
//~| expected `ToBar`
// except according to those terms.
// compile-flags: --extern std=
-// error-pattern: is not a file
+// error-pattern: can't find crate for `std`
fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
-
fn test<'x>(x: &'x isize) {
- drop::<Box<for<'z> FnMut(&'z isize) -> &'z isize>>(box |z| {
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ drop::<Box<for<'z> FnMut(&'z isize) -> &'z isize>>(Box::new(|z| {
x
//~^ ERROR cannot infer an appropriate lifetime
- });
+ }));
}
fn main() {}
#![feature(box_syntax)]
fn main() {
- let x = box 1;
+ let x: Box<_> = box 1;
let f = move|| {
let _a = x;
drop(x);
}
fn main() {
- let mut ptr = box Foo { x: 0 };
+ let mut ptr: Box<_> = box Foo { x: 0 };
let mut test = |foo: &Foo| {
println!("access {}", foo.x);
ptr = box Foo { x: ptr.x + 1 };
}
fn main() {
- let closure: Box<Fn()+'static> = box || ();
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let closure: Box<Fn()+'static> = Box::new(|| ());
let test = box Test { func: closure }; //~ ERROR mismatched types
}
fn main() {
let r = {
- let x = box 42;
+ let x: Box<_> = box 42;
let f = to_fn_once(move|| &x); //~ ERROR: `x` does not live long enough
f()
};
fn do_it(x: &isize) { }
fn main() {
- let x = box 22;
+ let x: Box<_> = box 22;
let f = to_fn_once(move|| do_it(&*x));
to_fn_once(move|| {
f();
struct Foo { a: isize, b: isize }
fn main() {
- let mut x = box Foo { a: 1, b: 2 };
+ let mut x: Box<_> = box Foo { a: 1, b: 2 };
let (a, b) = (&mut x.a, &mut x.b);
//~^ ERROR cannot borrow `x` (here through borrowing `x.b`) as mutable more than once at a time
//~^^ NOTE previous borrow of `x` occurs here (through borrowing `x.a`)
- let mut foo = box Foo { a: 1, b: 2 };
+ let mut foo: Box<_> = box Foo { a: 1, b: 2 };
let (c, d) = (&mut foo.a, &foo.b);
//~^ ERROR cannot borrow `foo` (here through borrowing `foo.b`) as immutable
//~^^ NOTE previous borrow of `foo` occurs here (through borrowing `foo.a`)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
-
fn main() {
let _foo = &[1_usize, 2] as [usize];
//~^ ERROR cast to unsized type: `&[usize; 2]` as `[usize]`
//~^^ HELP consider using an implicit coercion to `&[usize]` instead
- let _bar = box 1_usize as std::fmt::Debug;
+
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let _bar = Box::new(1_usize) as std::fmt::Debug;
//~^ ERROR cast to unsized type: `Box<usize>` as `core::fmt::Debug`
//~^^ HELP did you mean `Box<core::fmt::Debug>`?
+
let _baz = 1_usize as std::fmt::Debug;
//~^ ERROR cast to unsized type: `usize` as `core::fmt::Debug`
//~^^ HELP consider using a box or reference as appropriate
+
let _quux = [1_usize, 2] as [usize];
//~^ ERROR cast to unsized type: `[usize; 2]` as `[usize]`
//~^^ HELP consider using a box or reference as appropriate
// Test that moves of unsized values within closures are caught
// and rejected.
-#![feature(box_syntax)]
-
fn main() {
- (|| box *[0_usize].as_slice())();
- //~^ ERROR cannot move out of borrowed content
- //~^^ ERROR cannot move a value of type [usize]
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ (|| Box::new(*[0_usize].as_slice()))();
+ //~^ ERROR the trait `core::marker::Sized` is not implemented for the type `[usize]`
}
#[cfg(target_pointer_width = "64")]
fn main() {
let n = 0_usize;
- let a = box [&n; 0xF000000000000000_usize];
+ let a: Box<_> = box [&n; 0xF000000000000000_usize];
println!("{}", a[0xFFFFFF_usize]);
}
#[cfg(target_pointer_width = "32")]
fn main() {
let n = 0_usize;
- let a = box [&n; 0xFFFFFFFF_usize];
+ let a: Box<_> = box [&n; 0xFFFFFFFF_usize];
println!("{}", a[0xFFFFFF_usize]);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
-
use std::cell::RefCell;
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+
fn main() {
let mut y = 1_usize;
let c = RefCell::new(vec![]);
- c.push(box || y = 0);
- c.push(box || y = 0);
+ c.push(Box::new(|| y = 0));
+ c.push(Box::new(|| y = 0));
//~^ ERROR cannot borrow `y` as mutable more than once at a time
}
let mut y = 1_usize;
let c = RefCell::new(vec![]);
- Push::push(&c, box || y = 0);
- Push::push(&c, box || y = 0);
+ Push::push(&c, Box::new(|| y = 0));
+ Push::push(&c, Box::new(|| y = 0));
//~^ ERROR cannot borrow `y` as mutable more than once at a time
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
-
mod my_mod {
pub struct MyStruct {
priv_field: isize
let my_struct = my_mod::MyStruct();
let _woohoo = (&my_struct).priv_field;
//~^ ERROR field `priv_field` of struct `my_mod::MyStruct` is private
- let _woohoo = (box my_struct).priv_field;
+
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let _woohoo = (Box::new(my_struct)).priv_field;
//~^ ERROR field `priv_field` of struct `my_mod::MyStruct` is private
+
(&my_struct).happyfun(); //~ ERROR method `happyfun` is private
- (box my_struct).happyfun(); //~ ERROR method `happyfun` is private
+
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ (Box::new(my_struct)).happyfun(); //~ ERROR method `happyfun` is private
let nope = my_struct.priv_field;
//~^ ERROR field `priv_field` of struct `my_mod::MyStruct` is private
}
// except according to those terms.
#![feature(unboxed_closures)]
-#![feature(box_syntax)]
fn id<T>(t: T) -> T { t }
fn f<'r, T>(v: &'r T) -> Box<FnMut() -> T + 'r> {
- id(box || *v)
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ id(Box::new(|| *v))
//~^ ERROR `v` does not live long enough
//~| ERROR cannot move out of borrowed content
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
-
trait Foo { fn foo(&self) {} }
impl Foo for u8 {}
fn main() {
- let r: Box<Foo> = box 5;
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let r: Box<Foo> = Box::new(5);
let _m: Box<Foo> = r as Box<Foo>;
//~^ ERROR `core::marker::Sized` is not implemented for the type `Foo`
}
fn take_param<T:Foo>(foo: &T) { }
fn main() {
- let x = box 3;
+ let x: Box<_> = box 3;
take_param(&x);
//~^ ERROR the trait `core::marker::Copy` is not implemented
}
fn take_param<T:Foo>(foo: &T) { }
fn a() {
- let x = box 3;
+ let x: Box<_> = box 3;
take_param(&x); //~ ERROR `core::marker::Copy` is not implemented
}
fn b() {
- let x = box 3;
+ let x: Box<_> = box 3;
let y = &x;
let z = &x as &Foo; //~ ERROR `core::marker::Copy` is not implemented
}
#![feature(box_syntax)]
fn main() {
- let x = box 5;
+ let x: Box<_> = box 5;
let y = x;
println!("{}", *x); //~ ERROR use of moved value: `*x`
y.clone();
fn main() {
let x: Box<HashMap<isize, isize>> = box HashMap::new();
let x: Box<Map<isize, isize>> = x;
- let y: Box<Map<usize, isize>> = box x;
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let y: Box<Map<usize, isize>> = Box::new(x);
//~^ ERROR the trait `Map<usize, isize>` is not implemented
}
#![feature(box_syntax)]
pub fn main() {
- let x = box 1;
+ let x: Box<_> = box 1;
let v = (1, 2);
#![feature(box_syntax)]
pub fn main() {
- let x = box 1;
+ let x: Box<_> = box 1;
let v = (1, 2);
struct Foo(Box<isize>);
fn main() {
- let x = (box 1,);
+ let x: (Box<_>,) = (box 1,);
let y = x.0;
let z = x.0; //~ ERROR use of moved value: `x.0`
// bound must be noncopyable. For details see
// http://smallcultfollowing.com/babysteps/blog/2013/04/30/the-case-of-the-recurring-closure/
-#![feature(box_syntax)]
#![feature(unboxed_closures)]
struct R<'a> {
}
fn conspirator<F>(mut f: F) where F: FnMut(&mut R, bool) {
- let mut r = R {c: box f};
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let mut r = R {c: Box::new(f)};
f(&mut r, false) //~ ERROR use of moved value
}
fn f(_: &mut isize) {}
fn main() {
- let mut x = box 3;
+ let mut x: Box<_> = box 3;
f(x) //~ ERROR mismatched types
}
// Test that attempts to implicitly coerce a value into an
// object respect the lifetime bound on the object type.
-#![feature(box_syntax)]
-
trait Foo : ::std::marker::MarkerTrait {}
impl<'a> Foo for &'a [u8] {}
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+
fn a(v: &[u8]) -> Box<Foo + 'static> {
- let x: Box<Foo + 'static> = box v; //~ ERROR does not fulfill the required lifetime
+ let x: Box<Foo + 'static> = Box::new(v);
+ //~^ ERROR cannot infer an appropriate lifetime due to conflicting
x
}
fn b(v: &[u8]) -> Box<Foo + 'static> {
- box v //~ ERROR does not fulfill the required lifetime
+ Box::new(v)
+ //~^ ERROR cannot infer an appropriate lifetime due to conflicting
}
fn c(v: &[u8]) -> Box<Foo> {
// same as previous case due to RFC 599
- box v //~ ERROR does not fulfill the required lifetime
+ Box::new(v)
+ //~^ ERROR cannot infer an appropriate lifetime due to conflicting
}
fn d<'a,'b>(v: &'a [u8]) -> Box<Foo+'b> {
- box v //~ ERROR does not fulfill the required lifetime
+ Box::new(v)
+ //~^ ERROR cannot infer an appropriate lifetime due to conflicting
}
fn e<'a:'b,'b>(v: &'a [u8]) -> Box<Foo+'b> {
- box v // OK, thanks to 'a:'b
+ Box::new(v) // OK, thanks to 'a:'b
}
fn main() { }
#![feature(box_syntax)]
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+
use std::marker::MarkerTrait;
trait X : MarkerTrait {}
fn bad1<T: Iter>(v: T) -> Box<X+'static>
{
let item = v.into_item();
- box item //~ ERROR associated type `<T as Iter>::Item` may not live long enough
+ Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn bad2<T: Iter>(v: T) -> Box<X+'static>
where Box<T::Item> : X
{
- let item = box v.into_item();
- box item //~ ERROR associated type `<T as Iter>::Item` may not live long enough
+ let item: Box<_> = box v.into_item();
+ Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn bad3<'a, T: Iter>(v: T) -> Box<X+'a>
{
let item = v.into_item();
- box item //~ ERROR associated type `<T as Iter>::Item` may not live long enough
+ Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn bad4<'a, T: Iter>(v: T) -> Box<X+'a>
where Box<T::Item> : X
{
- let item = box v.into_item();
- box item //~ ERROR associated type `<T as Iter>::Item` may not live long enough
+ let item: Box<_> = box v.into_item();
+ Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn ok1<'a, T: Iter>(v: T) -> Box<X+'a>
where T::Item : 'a
{
let item = v.into_item();
- box item // OK, T::Item : 'a is declared
+ Box::new(item) // OK, T::Item : 'a is declared
}
fn ok2<'a, T: Iter>(v: &T, w: &'a T::Item) -> Box<X+'a>
where T::Item : Clone
{
let item = Clone::clone(w);
- box item // OK, T::Item : 'a is implied
+ Box::new(item) // OK, T::Item : 'a is implied
}
fn ok3<'a, T: Iter>(v: &'a T) -> Box<X+'a>
where T::Item : Clone + 'a
{
let item = Clone::clone(v.as_item());
- box item // OK, T::Item : 'a was declared
+ Box::new(item) // OK, T::Item : 'a was declared
}
fn meh1<'a, T: Iter>(v: &'a T) -> Box<X+'a>
// T::Item`. But we're not that smart at present.
let item = Clone::clone(v.as_item());
- box item //~ ERROR associated type `<T as Iter>::Item` may not live
+ Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live
}
fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
trait X { fn foo(&self) {} }
fn p1<T>(v: T) -> Box<X+'static>
where T : X
{
- box v //~ ERROR parameter type `T` may not live long enough
+ Box::new(v) //~ ERROR parameter type `T` may not live long enough
}
fn p2<T>(v: Box<T>) -> Box<X+'static>
where Box<T> : X
{
- box v //~ ERROR parameter type `T` may not live long enough
+ Box::new(v) //~ ERROR parameter type `T` may not live long enough
}
fn p3<'a,T>(v: T) -> Box<X+'a>
where T : X
{
- box v //~ ERROR parameter type `T` may not live long enough
+ Box::new(v) //~ ERROR parameter type `T` may not live long enough
}
fn p4<'a,T>(v: Box<T>) -> Box<X+'a>
where Box<T> : X
{
- box v //~ ERROR parameter type `T` may not live long enough
+ Box::new(v) //~ ERROR parameter type `T` may not live long enough
}
fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
fn ignore<T>(t: T) {}
let y = 3;
let mut ay = &y;
- ignore::<Box<for<'z> FnMut(&'z isize)>>(box |z| {
+ ignore::<Box<for<'z> FnMut(&'z isize)>>(Box::new(|z| {
ay = x; //~ ERROR cannot infer
ay = &y;
ay = z;
- });
+ }));
- ignore::< Box<for<'z> FnMut(&'z isize) -> &'z isize>>(box |z| {
+ ignore::< Box<for<'z> FnMut(&'z isize) -> &'z isize>>(Box::new(|z| {
if false { return x; } //~ ERROR cannot infer an appropriate lifetime for automatic
if false { return ay; }
return z;
- });
+ }));
}
fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
fn borrowed_proc<'a>(x: &'a isize) -> Box<FnMut()->(isize) + 'a> {
// This is legal, because the region bound on `proc`
// states that it captures `x`.
- box move|| { *x }
+ Box::new(move|| { *x })
}
fn static_proc(x: &isize) -> Box<FnMut()->(isize) + 'static> {
// This is illegal, because the region bound on `proc` is 'static.
- box move|| { *x } //~ ERROR captured variable `x` does not outlive the enclosing closure
+ Box::new(move|| { *x }) //~ ERROR captured variable `x` does not outlive the enclosing closure
}
fn main() { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
#![feature(unboxed_closures)]
struct closure_box<'a> {
fn main() {
let mut cl_box = {
let mut i = 3;
- box_it(box || i += 1) //~ ERROR `i` does not live long enough
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ box_it(Box::new(|| i += 1)) //~ ERROR `i` does not live long enough
};
cl_box.cl.call_mut(());
}
fn f<T:'static>(_: T) {}
fn main() {
- let x = box 3;
+ let x: Box<_> = box 3;
f(x);
let x = &3; //~ ERROR borrowed value does not live long enough
f(x);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
-
struct Struct {
person: &'static str
}
}
fn main() {
- let s: Box<Trait<isize>> = box Struct { person: "Fred" };
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let s: Box<Trait<isize>> = Box::new(Struct { person: "Fred" });
//~^ ERROR the trait `Trait<isize>` is not implemented for the type `Struct`
s.f(1);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
-
struct Struct {
person: &'static str
}
fn main() {
let person = "Fred".to_string();
let person: &str = &person; //~ ERROR `person` does not live long enough
- let s: Box<Trait<&'static str>> = box Struct { person: person };
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let s: Box<Trait<&'static str>> = Box::new(Struct { person: person });
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
#![feature(unboxed_closures)]
// Tests that we can't move out of an unboxed closure environment
fn to_fn_mut<A,F:FnMut<A>>(f: F) -> F { f }
fn to_fn_once<A,F:FnOnce<A>>(f: F) -> F { f }
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+
fn main() {
// By-ref cases
{
- let x = box 0_usize;
+ let x = Box::new(0_usize);
let f = to_fn(|| drop(x)); //~ ERROR cannot move
}
{
- let x = box 0_usize;
+ let x = Box::new(0_usize);
let f = to_fn_mut(|| drop(x)); //~ ERROR cannot move
}
{
- let x = box 0_usize;
+ let x = Box::new(0_usize);
let f = to_fn_once(|| drop(x)); // OK -- FnOnce
}
// By-value cases
{
- let x = box 0_usize;
+ let x = Box::new(0_usize);
let f = to_fn(move || drop(x)); //~ ERROR cannot move
}
{
- let x = box 0_usize;
+ let x = Box::new(0_usize);
let f = to_fn_mut(move || drop(x)); //~ ERROR cannot move
}
{
- let x = box 0_usize;
+ let x = Box::new(0_usize);
let f = to_fn_once(move || drop(x)); // this one is ok
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
-
#[derive(Debug)]
struct r {
b: bool,
}
fn main() {
- let i = box r { b: true };
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let i = Box::new(r { b: true });
let _j = i.clone(); //~ ERROR not implement
println!("{:?}", i);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
-
use std::rc::Rc;
fn f<T:Send>(__isize: T) {
}
fn main() {
- let i = box Rc::new(100);
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let i = Box::new(Rc::new(100));
f(i);
//~^ ERROR `core::marker::Send` is not implemented
}
#![feature(unsafe_destructor)]
-#![feature(box_syntax)]
-
use std::cell::Cell;
#[derive(Debug)]
fn main() {
let i1 = &Cell::new(0);
let i2 = &Cell::new(1);
- let r1 = vec!(box r { i: i1 });
- let r2 = vec!(box r { i: i2 });
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let r1 = vec!(Box::new(r { i: i1 }));
+ let r2 = vec!(Box::new(r { i: i2 }));
f(clone(&r1), clone(&r2));
//~^ ERROR the trait `core::clone::Clone` is not implemented for the type
//~^^ ERROR the trait `core::clone::Clone` is not implemented for the type
}
fn main() {
- let n = box Number { n: 42 };
- let mut l = box List { list: Vec::new() };
+ let n: Box<_> = box Number { n: 42 };
+ let mut l: Box<_> = box List { list: Vec::new() };
l.push(n);
let x = n.to_string();
//~^ ERROR: use of moved value: `n`
let stack_val_interior_ref_2: &f64 = &stack_val.y;
let ref_to_unnamed: &SomeStruct = &SomeStruct { x: 11, y: 24.5 };
- let unique_val = box SomeStruct { x: 13, y: 26.5 };
+ let unique_val: Box<_> = box SomeStruct { x: 13, y: 26.5 };
let unique_val_ref: &SomeStruct = &*unique_val;
let unique_val_interior_ref_1: &int = &unique_val.x;
let unique_val_interior_ref_2: &f64 = &unique_val.y;
fn main() {
- let unique = box StructWithSomePadding { x: 99, y: 999, z: 9999, w: 99999 };
+ let unique: Box<_> = box StructWithSomePadding { x: 99, y: 999, z: 9999, w: 99999 };
- let unique_dtor = box StructWithDestructor { x: 77, y: 777, z: 7777, w: 77777 };
+ let unique_dtor: Box<_> = box StructWithDestructor { x: 77, y: 777, z: 7777, w: 77777 };
zzz(); // #break
}
fn main() {
some_generic_fun(0.5f64, 10);
- some_generic_fun(&29, box 110);
+ some_generic_fun(&29, Box::new(110));
}
fn zzz() { () }
--- /dev/null
+// Copyright 2013-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.
+
+#![omit_gdb_pretty_printer_section]
+
+// ignore-android: FIXME(#10381)
+// min-lldb-version: 310
+
+// aux-build:cross_crate_spans.rs
+extern crate cross_crate_spans;
+
+// compile-flags:-g
+
+
+// === GDB TESTS ===================================================================================
+
+// gdb-command:break cross_crate_spans.rs:21
+// gdb-command:run
+
+// gdb-command:print result
+// gdb-check:$1 = {17, 17}
+// gdb-command:print a_variable
+// gdb-check:$2 = 123456789
+// gdb-command:print another_variable
+// gdb-check:$3 = 123456789.5
+// gdb-command:continue
+
+// gdb-command:print result
+// gdb-check:$4 = {1212, 1212}
+// gdb-command:print a_variable
+// gdb-check:$5 = 123456789
+// gdb-command:print another_variable
+// gdb-check:$6 = 123456789.5
+// gdb-command:continue
+
+
+
+// === LLDB TESTS ==================================================================================
+
+// lldb-command:b cross_crate_spans.rs:21
+// lldb-command:run
+
+// lldb-command:print result
+// lldb-check:[...]$0 = (17, 17)
+// lldb-command:print a_variable
+// lldb-check:[...]$1 = 123456789
+// lldb-command:print another_variable
+// lldb-check:[...]$2 = 123456789.5
+// lldb-command:continue
+
+// lldb-command:print result
+// lldb-check:[...]$3 = (1212, 1212)
+// lldb-command:print a_variable
+// lldb-check:[...]$4 = 123456789
+// lldb-command:print another_variable
+// lldb-check:[...]$5 = 123456789.5
+// lldb-command:continue
+
+
+// This test makes sure that we can break in functions inlined from other crates.
+
+fn main() {
+
+ let _ = cross_crate_spans::generic_function(17u32);
+ let _ = cross_crate_spans::generic_function(1212i16);
+
+}
let _ = stack.self_by_ref(-1, 2_u16);
let _ = stack.self_by_val(-3, -4_i16);
- let owned = box Struct { x: 1234.5f64 };
+ let owned: Box<_> = box Struct { x: 1234.5f64 };
let _ = owned.self_by_ref(-5, -6_i32);
let _ = owned.self_by_val(-7, -8_i64);
let _ = owned.self_owned(-9, -10.5_f32);
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
- let owned = box Enum::Variant1{ x: 1799, y: 1799 };
+ let owned: Box<_> = box Enum::Variant1{ x: 1799, y: 1799 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
- let owned = box Struct { x: 1234.5f64 };
+ let owned: Box<_> = box Struct { x: 1234.5f64 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
- let owned = box Struct { x: 200 };
+ let owned: Box<_> = box Struct { x: 200 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
- let owned = box Struct { x: 200 };
+ let owned: Box<_> = box Struct { x: 200 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
- let owned = box TupleStruct(200, -200.5);
+ let owned: Box<_> = box TupleStruct(200, -200.5);
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
- let owned = box Struct { x: 200 };
+ let owned: Box<_> = box Struct { x: 200 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
let _ = stack.self_by_ref(-1, 2_u16);
let _ = stack.self_by_val(-3, -4_i16);
- let owned = box Struct { x: 879 };
+ let owned: Box<_> = box Struct { x: 879 };
let _ = owned.self_by_ref(-5, -6_i32);
let _ = owned.self_by_val(-7, -8_i64);
let _ = owned.self_owned(-9, -10.5_f32);
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
- let the_a = box ABC::TheA { x: 0, y: 8970181431921507452 };
+ let the_a: Box<_> = box ABC::TheA { x: 0, y: 8970181431921507452 };
// 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441
// 0b00010001000100010001000100010001 = 286331153
// 0b0001000100010001 = 4369
// 0b00010001 = 17
- let the_b = box ABC::TheB (0, 286331153, 286331153);
+ let the_b: Box<_> = box ABC::TheB (0, 286331153, 286331153);
- let univariant = box Univariant::TheOnlyCase(123234);
+ let univariant: Box<_> = box Univariant::TheOnlyCase(123234);
zzz(); // #break
}
};
let struct_ref = &a_struct;
- let owned = box 6;
+ let owned: Box<_> = box 6;
let mut closure = || {
let closure_local = 8;
c: 4
};
- let owned = box 5;
+ let owned: Box<_> = box 5;
let closure = move || {
zzz(); // #break
};
let struct_ref = &a_struct;
- let owned = box 6;
+ let owned: Box<_> = box 6;
{
let mut first_closure = || {
// except according to those terms.
#[path = "circular_modules_hello.rs"]
-mod circular_modules_hello; //~ERROR: circular modules
+mod circular_modules_hello; //~ ERROR: circular modules
pub fn hi_str() -> String {
- "Hi!".to_string()
+ "Hi!".to_string()
}
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
+// ignore-windows
+// ignore-freebsd
#[path = "../compile-fail"]
mod foo; //~ ERROR: a directory
// error-pattern:panicked at 'Box<Any>'
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
fn main() {
- panic!(box 612_i64);
+ panic!(Box::new(612_i64));
}
// error-pattern: panic
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
-fn main() { box panic!(); }
+fn main() { Box::new(panic!()); }
// error-pattern:fail
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
fn failfn() {
panic!();
}
fn main() {
- box 0;
+ Box::new(0);
failfn();
}
use rustc_driver::driver::{compile_input, CompileController};
use syntax::diagnostics::registry::Registry;
+use std::path::PathBuf;
+
fn main() {
let src = r#"
fn main() {}
panic!("expected rustc path");
}
- let tmpdir = Path::new(&args[1]);
+ let tmpdir = PathBuf::new(&args[1]);
- let mut sysroot = Path::new(&args[3]);
+ let mut sysroot = PathBuf::new(&args[3]);
sysroot.pop();
sysroot.pop();
compile(src.to_string(), tmpdir.join("out"), sysroot.clone());
}
-fn basic_sess(sysroot: Path) -> Session {
+fn basic_sess(sysroot: PathBuf) -> Session {
let mut opts = basic_options();
opts.output_types = vec![OutputTypeExe];
opts.maybe_sysroot = Some(sysroot);
sess
}
-fn compile(code: String, output: Path, sysroot: Path) {
+fn compile(code: String, output: PathBuf, sysroot: PathBuf) {
let sess = basic_sess(sysroot);
let cfg = build_configuration(&sess);
let control = CompileController::basic();
let x = 32.0f32;
let _ = (x + ((x * x) + 1.0).sqrt()).ln();
- let s: Box<SomeTrait> = box some_fields {field1: 43};
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let s: Box<SomeTrait> = Box::new(some_fields {field1: 43});
let s2: Box<some_fields> = box some_fields {field1: 43};
- let s3 = box nofields;
+ let s3: Box<_> = box nofields;
s.Method(43);
s3.Method(43);
}
fn main() { // foo
- let s = box some_fields {field1: 43};
+ let s: Box<_> = box some_fields {field1: 43};
hello((43, "a".to_string()), *s);
sub::sub2::hello();
sub2::sub3::hello();
use rustc_driver::{driver, CompilerCalls, Compilation};
use syntax::diagnostics;
+use std::path::PathBuf;
struct TestCalls {
count: u32
_: &getopts::Matches,
_: &Session,
_: &Input,
- _: &Option<Path>,
- _: &Option<Path>)
+ _: &Option<PathBuf>,
+ _: &Option<PathBuf>)
-> Compilation {
self.count *= 3;
Compilation::Stop
}
- fn some_input(&mut self, input: Input, input_path: Option<Path>) -> (Input, Option<Path>) {
+ fn some_input(&mut self, input: Input, input_path: Option<PathBuf>)
+ -> (Input, Option<PathBuf>) {
self.count *= 5;
(input, input_path)
}
fn no_input(&mut self,
_: &getopts::Matches,
_: &config::Options,
- _: &Option<Path>,
- _: &Option<Path>,
+ _: &Option<PathBuf>,
+ _: &Option<PathBuf>,
_: &diagnostics::registry::Registry)
- -> Option<(Input, Option<Path>)> {
+ -> Option<(Input, Option<PathBuf>)> {
panic!("This shouldn't happen");
}
--- /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.
+
+// aux-build:procedural_mbe_matching.rs
+// ignore-stage1
+
+#![feature(plugin)]
+#![plugin(procedural_mbe_matching)]
+
+#[no_link]
+extern crate procedural_mbe_matching;
+
+pub fn main() {
+ let abc = 123u32;
+ assert_eq!(matches!(Some(123), None | Some(0)), false);
+ assert_eq!(matches!(Some(123), None | Some(123)), true);
+ assert_eq!(matches!(true, true), true);
+}
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// 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.
//
let arm = quote_arm!(cx, (ref x, ref y) => (x, y));
check_pp(ext_cx, arm, pprust::print_stmt, "(ref x, ref y) = (x, y)".to_string());
+
+ let attr = quote_attr!(cx, #![cfg(foo = "bar")]);
+ check_pp(ext_cx, attr, pprust::print_attribute, "#![cfg(foo = "bar")]".to_string());
}
fn check_pp<T>(cx: fake_ext_ctxt,
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// 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.
//
let _k: P<syntax::ast::Method> = quote_method!(cx, #[doc = "hello"] fn foo(&self) {});
let _l: P<syntax::ast::Ty> = quote_ty!(cx, &int);
+
+ let _m: Vec<syntax::ast::TokenTree> = quote_matcher!(cx, $($foo:tt,)* bar);
+ let _n: syntax::ast::Attribute = quote_attr!(cx, #![cfg(foo, bar = "baz")]);
}
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
-
static mut DROP_RAN: bool = false;
struct Foo;
pub fn main() {
{
- let _x: Box<Fat<Trait>> = box Fat { f: Foo };
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let _x: Box<Fat<Trait>> = Box::<Fat<Foo>>::new(Fat { f: Foo });
}
unsafe {
assert!(DROP_RAN);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
-
static mut DROP_RAN: int = 0;
struct Foo;
pub fn main() {
{
- let _x: Box<Fat<[Foo]>> = box Fat { f: [Foo, Foo, Foo] };
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let _x: Box<Fat<[Foo]>> = Box::<Fat<[Foo; 3]>>::new(Fat { f: [Foo, Foo, Foo] });
}
unsafe {
assert!(DROP_RAN == 3);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
#[derive(PartialEq, Debug)]
struct Point { x : int }
pub fn main() {
assert_eq!(14,14);
assert_eq!("abc".to_string(),"abc".to_string());
- assert_eq!(box Point{x:34},box Point{x:34});
+ assert_eq!(Box::new(Point{x:34}),Box::new(Point{x:34}));
assert_eq!(&Point{x:34},&Point{x:34});
}
fn main() {
let v = vec!(1, 2, 3, 4, 5, 6);
- let r = pairwise_sub(box v.into_iter());
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let r = pairwise_sub(Box::new(v.into_iter()));
assert_eq!(r, 9);
}
}
pub fn main() {
- let x = box() (box 3_usize as Box<double>);
+ let x: Box<_> = box() (box 3_usize as Box<double>);
assert_eq!(x.double(), 6_usize);
}
}
pub fn main() {
- let x = box 3_usize;
+ let x: Box<_> = box 3_usize;
assert_eq!(x.double(), 6_usize);
}
}
pub fn main() {
- let x = box box box box box 3_usize;
+ let x: Box<Box<Box<Box<Box<_>>>>> = box box box box box 3_usize;
assert_eq!(x.double(), 6_usize);
}
}
pub fn main() {
- let x = box box 3_usize;
+ let x: Box<Box<_>> = box box 3_usize;
assert_eq!(x.double(), 6_usize);
}
}
pub fn main() {
- let x = box 3_usize;
+ let x: Box<_> = box 3_usize;
assert_eq!(x.double(), 6_usize);
}
}
pub fn main() {
- let x = box 3_usize;
+ let x: Box<_> = box 3_usize;
assert_eq!(x.foo(), "box 3".to_string());
}
use std::collections::BitVec;
fn bitv_test() {
- let mut v1 = box BitVec::from_elem(31, false);
- let v2 = box BitVec::from_elem(31, true);
+ let mut v1: Box<_> = box BitVec::from_elem(31, false);
+ let v2: Box<_> = box BitVec::from_elem(31, true);
v1.union(&*v2);
}
#![feature(unboxed_closures)]
pub fn main() {
- let bar = box 3;
+ let bar: Box<_> = box 3;
let h = || -> int *bar;
assert_eq!(h(), 3);
}
}
pub fn main() {
- let mut ints = box Ints {sum: box 0, values: Vec::new()};
+ let mut ints: Box<_> = box Ints {sum: box 0, values: Vec::new()};
add_int(&mut *ints, 22);
add_int(&mut *ints, 44);
use cci_borrow_lib::foo;
pub fn main() {
- let p = box 22_usize;
+ let p: Box<_> = box 22_usize;
let r = foo(&*p);
println!("r={}", r);
assert_eq!(r, 22_usize);
pub fn fails() {
let x = 2;
- let mut y = Vec::new();
+ let mut y: Vec<Box<_>> = Vec::new();
y.push(box Conzabble::Bickwick(do_it(&get_bar(x))));
}
}
pub fn main() {
- let z = box Pair { a : 10, b : 12};
+ let z: Box<_> = box Pair { a : 10, b : 12};
let _t = Thread::spawn(move|| {
assert_eq!(z.a, 10);
// rvalue expressions to be unsized. See #20169 for more information.
pub fn main() {
- let _: Box<[int]> = box { [1, 2, 3] };
- let _: Box<[int]> = box if true { [1, 2, 3] } else { [1, 3, 4] };
- let _: Box<[int]> = box match true { true => [1, 2, 3], false => [1, 3, 4] };
- let _: Box<Fn(int) -> _> = box { |x| (x as u8) };
- let _: Box<Debug> = box if true { false } else { true };
- let _: Box<Debug> = box match true { true => 'a', false => 'b' };
+ // FIXME #22405: We cannot infer the type `Box<[int; k]>` for
+ // the r-value expression from the context `Box<[int]>`, and
+ // therefore the `box EXPR` desugaring breaks down.
+ //
+ // One could reasonably claim that the `box EXPR` desugaring is
+ // effectively regressing half of Issue #20169. Hopefully we will
+ // eventually fix that, at which point the `Box::new` calls below
+ // should be replaced wth uses of `box`.
+
+ let _: Box<[int]> = Box::new({ [1, 2, 3] });
+ let _: Box<[int]> = Box::new(if true { [1, 2, 3] } else { [1, 3, 4] });
+ let _: Box<[int]> = Box::new(match true { true => [1, 2, 3], false => [1, 3, 4] });
+ let _: Box<Fn(int) -> _> = Box::new({ |x| (x as u8) });
+ let _: Box<Debug> = Box::new(if true { false } else { true });
+ let _: Box<Debug> = Box::new(match true { true => 'a', false => 'b' });
let _: &[int] = &{ [1, 2, 3] };
let _: &[int] = &if true { [1, 2, 3] } else { [1, 3, 4] };
let _: Vec<Box<Fn(int) -> _>> = vec![
Box::new(|x| (x as u8)),
- box |x| (x as i16 as u8),
+ Box::new(|x| (x as i16 as u8)),
];
}
#![feature(box_syntax)]
pub fn main() {
- let _: Box<[int]> = if true { box [1, 2, 3] } else { box [1] };
+ let _: Box<[int]> =
+ if true { let b: Box<_> = box [1, 2, 3]; b } else { let b: Box<_> = box [1]; b };
- let _: Box<[int]> = match true { true => box [1, 2, 3], false => box [1] };
+ let _: Box<[int]> = match true {
+ true => { let b: Box<_> = box [1, 2, 3]; b }
+ false => { let b: Box<_> = box [1]; b }
+ };
// Check we don't get over-keen at propagating coercions in the case of casts.
let x = if true { 42 } else { 42u8 } as u16;
// Make sure const bounds work on things, and test that a few types
// are const.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
fn foo<T: Sync>(x: T) -> T { x }
struct F { field: int }
foo(F{field: 42});
foo((1, 2_usize));
foo(@1);*/
- foo(box 1);
+ foo(Box::new(1));
}
pub fn main() {
use crate_method_reexport_grrrrrrr2::rust::add;
use crate_method_reexport_grrrrrrr2::rust::cx;
- let x = box() ();
+ let x: Box<_> = box () ();
x.cx();
let y = ();
y.add("hi".to_string());
use std::cell::Cell;
pub fn main() {
- let x = box Cell::new(5);
+ let x: Box<_> = box Cell::new(5);
x.set(1000);
println!("{}", x.get());
}
pub fn main() {
let a: A = Default::default();
- let b: Box<[_]> = box [];
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let b: Box<[_]> = Box::<[bool; 0]>::new([]);
assert_eq!(a.foo, b);
}
}
fn main() {
- let obj = A { foo: box [true, false] };
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let obj = A { foo: Box::new([true, false]) };
let s = json::encode(&obj).unwrap();
let obj2: A = json::decode(&s).unwrap();
assert!(obj.foo == obj2.foo);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
#[derive(PartialEq, PartialOrd, Eq, Ord)]
struct Foo(Box<[u8]>);
pub fn main() {
- let a = Foo(box [0, 1, 2]);
- let b = Foo(box [0, 1, 2]);
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let a = Foo(Box::new([0, 1, 2]));
+ let b = Foo(Box::new([0, 1, 2]));
assert!(a == b);
println!("{}", a != b);
println!("{}", a < b);
// Test that a custom deref with a fat pointer return type does not ICE
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
use std::ops::{Deref, DerefMut};
pub struct Arr {
}
fn main() {
- let mut a = Arr { ptr: box [1, 2, 3] };
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let mut a = Arr { ptr: Box::new([1, 2, 3]) };
foo(&mut a);
}
// Test that a custom deref with a fat pointer return type does not ICE
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
use std::ops::Deref;
pub struct Arr {
}
fn main() {
- let a = Arr { ptr: box [1, 2, 3] };
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let a = Arr { ptr: Box::new([1, 2, 3]) };
foo(&a);
}
foo3(f5);
// Box.
- let f1 = box [1, 2, 3];
+ let f1 = Box::new([1, 2, 3]);
assert!((*f1)[1] == 2);
let f2: Box<[int]> = f1;
assert!((*f2)[1] == 2);
foo(&*f1);
let f2 : Box<Fat<[int]>> = f1;
foo(&*f2);
- let f3 : Box<Fat<[int]>> = box Fat { f1: 5, f2: "some str", ptr: [1, 2, 3] };
+
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let f3 : Box<Fat<[int]>> =
+ Box::<Fat<[_; 3]>>::new(Fat { f1: 5, f2: "some str", ptr: [1, 2, 3] });
foo(&*f3);
}
assert!(f6.ptr.to_bar() == Bar);
// &*
- let f7: Box<ToBar> = box Bar1 {f :42};
+ //
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let f7: Box<ToBar> = Box::new(Bar1 {f :42});
bar(&*f7);
// Deep nesting
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
pub fn main() {
- assert!(Some(box() ()).is_some());
+ assert!(Some(Box::new(())).is_some());
- let xs: Box<[()]> = box [];
+ let xs: Box<[()]> = Box::<[(); 0]>::new([]);
assert!(Some(xs).is_some());
struct Foo;
- assert!(Some(box Foo).is_some());
+ assert!(Some(Box::new(Foo)).is_some());
- let ys: Box<[Foo]> = box [];
+ let ys: Box<[Foo]> = Box::<[Foo; 0]>::new([]);
assert!(Some(ys).is_some());
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
pub fn main() {
- let x = *box() ();
+ let x = *Box::new(());
}
}
pub fn main() {
- let mut m = box linear_map::<(),()>();
+ let mut m: Box<_> = box linear_map::<(),()>();
assert_eq!(m.len(), 0);
}
impl Nus for thing { fn f(&self) {} }
pub fn main() {
- let y = box thing(A {a: 10});
+ let y: Box<_> = box thing(A {a: 10});
assert_eq!(y.clone().bar(), 10);
assert_eq!(y.quux(), 10);
#![allow(unknown_features)]
#![feature(box_syntax)]
-pub fn main() { let x = { box 100 }; assert!((*x == 100)); }
+pub fn main() { let x: Box<_> = { box 100 }; assert!((*x == 100)); }
// Tests for if as expressions returning boxed types
fn test_box() {
- let rs = if true { box 100 } else { box 101 };
+ let rs: Box<_> = if true { box 100 } else { box 101 };
assert_eq!(*rs, 100);
}
// Tests for match as expressions resulting in boxed types
fn test_box() {
- let res = match true { true => { box 100 }, _ => panic!() };
+ let res: Box<_> = match true { true => { box 100 }, _ => panic!() };
assert_eq!(*res, 100);
}
}
pub fn main() {
- let obj = box 1;
+ let obj: Box<_> = box 1;
let objptr: *const uint = &*obj;
let f = Foo {x: obj, y: box 2};
let xptr = foo(f);
}
pub fn main() {
- let obj = box 1;
+ let obj: Box<_> = box 1;
let objptr: *const uint = &*obj;
let xptr = getaddr(obj);
assert_eq!(objptr, xptr);
fn id<T:Send>(t: T) -> T { return t; }
pub fn main() {
- let expected = box 100;
+ let expected: Box<_> = box 100;
let actual = id::<Box<int>>(expected.clone());
println!("{}", *actual);
assert_eq!(*expected, *actual);
// except according to those terms.
#![allow(unknown_features)]
-#![feature(box_syntax)]
#![feature(unboxed_closures)]
/**
}
let ctrl_clone = ctrl.clone();
- ::map(input, box |a,b| emit(&mut intermediates, ctrl.clone(), a, b) );
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ ::map(input, Box::new(|a,b| emit(&mut intermediates, ctrl.clone(), a, b)));
ctrl_clone.send(ctrl_proto::mapper_done).unwrap();
}
// except according to those terms.
#![allow(unknown_features)]
-#![feature(box_syntax)]
#![feature(unboxed_closures)]
// Test that `Fn(int) -> int + 'static` parses as `(Fn(int) -> int) +
// cause a compilation error. Issue #18772.
fn adder(y: int) -> Box<Fn(int) -> int + 'static> {
- box move |x| y + x
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ Box::new(move |x| y + x)
}
fn main() {}
test_order();
// make sure that format! doesn't move out of local variables
- let a = box 3;
+ let a: Box<_> = box 3;
format!("{}", a);
format!("{}", a);
fn test_unique() {
let i = &Cell::new(0);
{
- let _a = box r(i);
+ let _a: Box<_> = box r(i);
}
assert_eq!(i.get(), 1);
}
fn test_unique_rec() {
let i = &Cell::new(0);
{
- let _a = box BoxR {
+ let _a: Box<_> = box BoxR {
x: r(i)
};
}
pub fn main() {
unsafe {
- let mut x = box 1;
+ let mut x: Box<_> = box 1;
assert_eq!(rusti::atomic_load(&*x), 1);
*x = 5;
pub fn main() {
unsafe {
- let x = box 1;
+ let x: Box<_> = box 1;
let mut y = rusti::init();
let mut z: *const uint = transmute(&x);
rusti::move_val_init(&mut y, x);
fn main() {
{
- let f = box DroppableStruct;
+ let f: Box<_> = box DroppableStruct;
let _a = Whatever::new(box f as Box<MyTrait>);
}
assert!(unsafe { DROPPED });
unsafe { DROPPED = false; }
{
- let f = box DroppableEnum::DroppableVariant1;
+ let f: Box<_> = box DroppableEnum::DroppableVariant1;
let _a = Whatever::new(box f as Box<MyTrait>);
}
assert!(unsafe { DROPPED });
// except according to those terms.
#![allow(dead_code)]
-#![allow(unknown_features)]
-#![feature(box_syntax)]
+
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
trait Foo { fn dummy(&self) { } }
impl Foo for int {}
let r = &1;
foog(x, &[r]);
- let x: [Box<Foo>; 2] = [box 1, box 2];
+ let x: [Box<Foo>; 2] = [Box::new(1), Box::new(2)];
bar(x);
- bar([box 1, box 2]);
+ bar([Box::new(1), Box::new(2)]);
- let x: &[Box<Foo>] = &[box 1, box 2];
+ let x: &[Box<Foo>] = &[Box::new(1), Box::new(2)];
bars(x);
- bars(&[box 1, box 2]);
+ bars(&[Box::new(1), Box::new(2)]);
- let x: &[Box<Foo>] = &[box 1, box 2];
- foog(x, &[box 1]);
+ let x: &[Box<Foo>] = &[Box::new(1), Box::new(2)];
+ foog(x, &[Box::new(1)]);
struct T<'a> {
t: [&'a (Foo+'a); 2]
t: &'a [Box<Foo+'static>]
}
let _n = M {
- t: &[box 1, box 2]
+ t: &[Box::new(1), Box::new(2)]
};
- let x: [Box<Foo>; 2] = [box 1, box 2];
+ let x: [Box<Foo>; 2] = [Box::new(1), Box::new(2)];
let _n = M {
t: &x
};
// except according to those terms.
#![allow(dead_code)]
-#![allow(unknown_features)]
-#![feature(box_syntax)]
// this code used to cause an ICE
}
fn main() {
- S {f: box F, g: box F};
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ S {f: Box::new(F), g: Box::new(F) };
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
fn main() {
- fn test() -> Box<std::any::Any + 'static> { box 1 }
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ fn test() -> Box<std::any::Any + 'static> { Box::new(1) }
println!("{:?}", test())
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
struct Foo<'a> {
listener: Box<FnMut() + 'a>,
}
impl<'a> Foo<'a> {
fn new<F>(listener: F) -> Foo<'a> where F: FnMut() + 'a {
- Foo { listener: box listener }
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ Foo { listener: Box::new(listener) }
}
}
impl A for B1 {}
fn main() {
- let v = box B1;
+ let v: Box<_> = box B1;
let _c: Box<A> = v.clone();
}
// All 3 expressions should work in that the argument gets
// coerced to a trait object
-#![allow(unknown_features)]
-#![feature(box_syntax)]
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
fn main() {
- send::<Box<Foo>>(box Output(0));
- Test::<Box<Foo>>::foo(box Output(0));
- Test::<Box<Foo>>::new().send(box Output(0));
+ send::<Box<Foo>>(Box::new(Output(0)));
+ Test::<Box<Foo>>::foo(Box::new(Output(0)));
+ Test::<Box<Foo>>::new().send(Box::new(Output(0)));
}
fn send<T>(_: T) {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
trait Matcher {
fn next_match(&mut self) -> Option<(uint, uint)>;
}
impl<'a, 'b, F> IntoMatcher<'a, CharPredMatcher<'a, 'b>> for F where F: FnMut(char) -> bool + 'b {
fn into_matcher(self, s: &'a str) -> CharPredMatcher<'a, 'b> {
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
CharPredMatcher {
str: s,
- pred: box self,
+ pred: Box::new(self),
}
}
}
#![feature(box_syntax)]
fn match_on_local() {
- let mut foo = Some(box 5);
+ let mut foo: Option<Box<_>> = Some(box 5);
match foo {
None => {},
Some(x) => {
}
fn match_on_binding() {
- match Some(box 7) {
+ match Some(Box::new(7)) {
mut foo => {
match foo {
None => {},
}
fn match_on_upvar() {
- let mut foo = Some(box 8i32);
+ let mut foo: Option<Box<_>> = Some(box 8i32);
let f = move|| {
match foo {
None => {},
// ignore-pretty
#![allow(unknown_features)]
-#![feature(box_syntax)]
#![feature(unboxed_closures)]
struct Parser<'a, I, O> {
impl<'a, I: 'a, O: 'a> Parser<'a, I, O> {
fn compose<K: 'a>(mut self, mut rhs: Parser<'a, O, K>) -> Parser<'a, I, K> {
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
Parser {
- parse: box move |x: I| {
+ parse: Box::new(move |x: I| {
match (self.parse)(x) {
Ok(r) => (rhs.parse)(r),
Err(e) => Err(e)
}
- }
+ })
}
}
}
// Test that generating drop glue for Box<str> doesn't ICE
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
fn f(s: Box<str>) -> Box<str> {
s
}
fn main() {
// There is currently no safe way to construct a `Box<str>`, so improvise
- let box_arr: Box<[u8]> = box ['h' as u8, 'e' as u8, 'l' as u8, 'l' as u8, 'o' as u8];
+ //
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let box_arr: Box<[u8]> = Box::new(['h' as u8, 'e' as u8, 'l' as u8, 'l' as u8, 'o' as u8]);
let box_str: Box<str> = unsafe { std::mem::transmute(box_arr) };
assert_eq!(&*box_str, "hello");
f(box_str);
// Check that trans doesn't ICE when translating an array repeat
// expression with a count of 1 and a non-Copy element type.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
fn main() {
- let _ = [box 1_usize; 1];
+ let _ = [Box::new(1_usize); 1];
}
// Test that overloaded calls work with zero arity closures
-#![feature(box_syntax)]
-
fn main() {
- let functions: [Box<Fn() -> Option<()>>; 1] = [box || None];
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let functions: [Box<Fn() -> Option<()>>; 1] = [Box::new(|| None)];
let _: Option<Vec<()>> = functions.iter().map(|f| (*f)()).collect();
}
}
pub fn main() {
- let z = box 22;
+ let z: Box<_> = box 22;
a_val(z.clone(), z.clone());
}
}
pub fn main() {
- let _f = box Font();
+ let _f: Box<_> = box Font();
}
//
// ignore-lexer-test FIXME #15883
-#![allow(unknown_features)]
-#![feature(box_syntax)]
#![feature(unsafe_destructor)]
pub type Task = int;
pub fn packet<T:Send>() -> *const packet<T> {
unsafe {
- let p: *const packet<T> = mem::transmute(box Stuff{
+ let p: *const packet<T> = mem::transmute(Box::new(Stuff{
state: empty,
blocked_task: None::<Task>,
payload: None::<T>
- });
+ }));
p
}
}
// let y = box ({a: 4});
// let z = box ({a: 4} as it);
// let z = box ({a: true} as it);
- let z = box() (box true as Box<it>);
+ let z: Box<_> = box () (box true as Box<it>);
// x.f();
// y.f();
// (*z).f();
pub fn main() {
let fd: libc::c_int = 1 as libc::c_int;
- let _sock = box socket::socket_handle(fd);
+ let _sock: Box<_> = box socket::socket_handle(fd);
}
use std::collections::HashMap;
pub fn main() {
- let x;
+ let x: Box<_>;
let mut buggy_map: HashMap<uint, &uint> = HashMap::new();
x = box 1;
buggy_map.insert(42, &*x);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
type Connection = Box<FnMut(Vec<u8>) + 'static>;
fn f() -> Option<Connection> {
- let mock_connection: Connection = box |_| {};
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let mock_connection: Connection = Box::new(|_| {});
Some(mock_connection)
}
#![feature(box_syntax)]
pub fn main() {
- let mut x = box 3;
+ let mut x: Box<_> = box 3;
x = x;
assert_eq!(*x, 3);
}
// rustc --test ignores2.rs && ./ignores2
#![allow(unknown_features)]
-#![feature(box_syntax)]
#![feature(unboxed_closures)]
use std::old_path::{Path};
fn tester()
{
- let mut loader: rsrc_loader = box move|_path| {
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let mut loader: rsrc_loader = Box::new(move|_path| {
result::Result::Ok("more blah".to_string())
- };
+ });
let path = old_path::Path::new("blah");
assert!(loader(&path).is_ok());
// except according to those terms.
#![allow(unknown_features)]
-#![feature(box_syntax)]
use std::thread::Thread;
use std::sync::mpsc::Sender;
let _t = Thread::spawn(move|| {
let mut samples_chan = samples_chan;
- // `box() (...)` syntax is needed to make pretty printer converge in one try:
- let callback: SamplesFn = box() (move |buffer| {
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let callback: SamplesFn = Box::new(move |buffer| {
for i in 0_usize..buffer.len() {
println!("{}: {}", i, buffer[i])
}
#![feature(box_syntax)]
pub fn main() {
- let y = box 1;
+ let y: Box<_> = box 1;
y;
}
macro_rules! foo {
($tag: expr, $string: expr) => {
if $tag == $string {
- let element = box Element;
+ let element: Box<_> = box Element;
unsafe {
return std::mem::transmute::<_, uint>(element);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
enum Either<T, U> { Left(T), Right(U) }
pub fn main() {
- match Either::Left(box 17) {
+ match Either::Left(Box::new(17)) {
Either::Right(()) => {}
_ => {}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
pub fn main() {
- match &[(box 5,box 7)] {
+ match &[(Box::new(5),Box::new(7))] {
ps => {
let (ref y, _) = ps[0];
assert!(**y == 5);
}
}
- match Some(&[(box 5,)]) {
+ match Some(&[(Box::new(5),)]) {
Some(ps) => {
let (ref y,) = ps[0];
assert!(**y == 5);
None => ()
}
- match Some(&[(box 5,box 7)]) {
+ match Some(&[(Box::new(5),Box::new(7))]) {
Some(ps) => {
let (ref y, ref z) = ps[0];
assert!(**y == 5);
struct A { a: Box<isize> }
fn foo() -> Box<FnMut() -> isize + 'static> {
- let k = box 22;
+ let k: Box<_> = box 22;
let _u = A {a: k.clone()};
// FIXME(#16640) suffix in `22_isize` suffix shouldn't be necessary
let result = || 22_isize;
- box result
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ Box::new(result)
}
pub fn main() {
pub fn main() {
fn invoke<F>(f: F) where F: FnOnce() { f(); }
- let k = box 22;
+ let k: Box<_> = box 22;
let _u = A {a: k.clone()};
invoke(|| println!("{}", k.clone()) )
}
#![feature(box_syntax)]
fn f() {
- let a = box 1;
+ let a: Box<_> = box 1;
let b: &int = &*a;
println!("{}", b);
}
struct Pair { a: Box<int>, b: Box<int> }
pub fn main() {
- let mut x = box Pair {a: box 10, b: box 20};
+ let mut x: Box<_> = box Pair {a: box 10, b: box 20};
let x_internal = &mut *x;
match *x_internal {
Pair {a: ref mut a, b: ref mut _b} => {
}
fn call_foo_other() -> int {
- let mut x = Vec::new();
+ let mut x: Vec<Box<_>> = Vec::new();
let y = x.foo();
x.push(box 0);
y
}
pub fn main() {
- let x = box Triple{x: 1, y: 2, z: 3};
+ let x: Box<_> = box Triple{x: 1, y: 2, z: 3};
assert_eq!(test(true, x.clone()), 2);
assert_eq!(test(true, x.clone()), 2);
assert_eq!(test(true, x.clone()), 2);
struct X { x: int, y: int, z: int }
pub fn main() {
- let x = box X{x: 1, y: 2, z: 3};
+ let x: Box<_> = box X{x: 1, y: 2, z: 3};
let y = x;
assert!((y.y == 2));
}
struct X { x: int, y: int, z: int }
-pub fn main() { let x = box X {x: 1, y: 2, z: 3}; let y = x; assert!((y.y == 2)); }
+pub fn main() { let x: Box<_> = box X {x: 1, y: 2, z: 3}; let y = x; assert!((y.y == 2)); }
}
pub fn main() {
- let x = box Triple{x: 1, y: 2, z: 3};
+ let x: Box<_> = box Triple{x: 1, y: 2, z: 3};
for _ in 0_usize..10000_usize {
assert_eq!(test(true, x.clone()), 2);
}
#![feature(box_syntax)]
fn main() {
- let x = box 1;
+ let x: Box<_> = box 1;
let v = (1, 2);
// Test that the lambda kind is inferred correctly as a return
// expression
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
-fn unique() -> Box<FnMut()+'static> { return box || (); }
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+fn unique() -> Box<FnMut()+'static> { return Box::new(|| ()); }
pub fn main() {
}
// Test that the lambda kind is inferred correctly as a return
// expression
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
-fn unique() -> Box<FnMut()+'static> { box || () }
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+fn unique() -> Box<FnMut()+'static> { Box::new(|| ()) }
pub fn main() {
}
}
pub fn main() {
- let box_5 = box 5_usize;
+ let box_5: Box<_> = box 5_usize;
assert_eq!(Rc::new(5_usize).to_uint(), Some(5));
- assert_eq!((box &box &Rc::new(box box &box_5)).to_uint(), Some(5));
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ assert_eq!((Box::new(&Box::new(&Rc::new(Box::new(Box::new(&box_5)))))).to_uint(), Some(5));
let point = Rc::new(Point {x: 2, y: 4});
assert_eq!(point.x, 2);
assert_eq!(point.y, 4);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
use std::cell::RefCell;
use std::rc::Rc;
use std::string::String;
pub fn main() {
assert_eq!(*Rc::new(5), 5);
- assert_eq!(***Rc::new(box box 5), 5);
+ assert_eq!(***Rc::new(Box::new(Box::new(5))), 5);
assert_eq!(*Rc::new(Point {x: 2, y: 4}), Point {x: 2, y: 4});
let i = Rc::new(RefCell::new(2));
}
fn main() {
- let mut f = box Foo {
+ let mut f: Box<_> = box Foo {
x: 1,
y: 2,
};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
fn f<T: 'static>(_x: T) {}
pub fn main() {
- f(box 5);
+ f(Box::new(5));
}
fn sums_to_using_uniq(v: Vec<int> , sum: int) -> bool {
let mut i = 0_usize;
- let mut sum0 = box 0;
+ let mut sum0: Box<_> = box 0;
while i < v.len() {
*sum0 += v[i];
i += 1_usize;
fn sums_to_using_uniq_rec(v: Vec<int> , sum: int) -> bool {
let mut i = 0_usize;
- let mut sum0 = F {f: box 0};
+ let mut sum0 = F::<Box<_>> {f: box 0};
while i < v.len() {
*sum0.f += v[i];
i += 1_usize;
}
pub fn main() {
- let x = box 6;
+ let x: Box<_> = box 6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
}
pub fn main() {
- let p = box 22_usize;
+ let p: Box<_> = box 22_usize;
let r = foo(&*p);
println!("r={}", r);
assert_eq!(r, 22_usize);
}
pub fn main() {
- let p = box 3_usize;
+ let p: Box<_> = box 3_usize;
let r = foo(&*p);
assert_eq!(r, 3_usize);
}
// except according to those terms.
#![allow(unknown_features)]
-#![feature(box_syntax)]
#![feature(unboxed_closures)]
struct closure_box<'a> {
assert_eq!(i, 3);
{
let cl = || i += 1;
- let mut cl_box = box_it(box cl);
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let mut cl_box = box_it(Box::new(cl));
cl_box.cl.call_mut(());
}
assert_eq!(i, 4);
fn bar(x: &uint) -> uint { *x }
pub fn main() {
- let p = box 3_usize;
+ let p: Box<_> = box 3_usize;
assert_eq!(bar(foo(&*p)), 3);
}
#![allow(dead_assignment)]
#![allow(unused_variable)]
#![allow(unknown_features)]
-#![feature(box_syntax)]
+
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
// Should pass region checking.
fn ok(f: Box<FnMut(&uint)>) {
// f's type should be a subtype of g's type), because f can be
// used in any context that expects g's type. But this currently
// fails.
- let mut g: Box<for<'r> FnMut(&'r uint)> = box |x| { };
+ let mut g: Box<for<'r> FnMut(&'r uint)> = Box::new(|x| { });
g = f;
}
// This version is the same as above, except that here, g's type is
// inferred.
fn ok_inferred(f: Box<FnMut(&uint)>) {
- let mut g: Box<for<'r> FnMut(&'r uint)> = box |_| {};
+ let mut g: Box<for<'r> FnMut(&'r uint)> = Box::new(|_| {});
g = f;
}
fn borrow<T>(x: &T) -> &T {x}
pub fn main() {
- let x = box 3;
+ let x: Box<_> = box 3;
loop {
let y = borrow(&*x);
assert_eq!(*x, *y);
}
pub fn main() {
- let p = box Point {x: 3, y: 4};
+ let p: Box<_> = box Point {x: 3, y: 4};
let xc = x_coord(&*p);
assert_eq!(*xc, 3);
}
impl<'a,'tcx> Foo<'a,'tcx> {
fn bother(&mut self) -> int {
- self.elaborate_bounds(box |this| {
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ self.elaborate_bounds(Box::new(|this| {
// (*) Here: type of `this` is `&'f0 Foo<&'f1, '_2>`,
// where `'f0` and `'f1` are fresh, free regions that
// result from the bound regions on the closure, and `'2`
// `region_inference.rs` file (and the `givens` field, in
// particular) for more details.
this.foo()
- })
+ }))
}
fn foo(&mut self) -> int {
}
pub fn main() {
- let cl_box = box_it(box || println!("Hello, world!"));
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let cl_box = box_it(Box::new(|| println!("Hello, world!")));
call_static_closure(cl_box);
}
let new_x = x.change();
assert_eq!(new_x.a, 55);
- let x = box new_x;
+ let x: Box<_> = box new_x;
let new_x = x.change_again();
assert_eq!(new_x.a, 45);
}
use std::rc::Rc;
pub fn main() {
- let mut x = box 3;
+ let mut x: Box<_> = box 3;
x = x;
assert!(*x == 3);
}
fn test05() {
- let three = box 3;
+ let three: Box<_> = box 3;
let fn_to_send = move|n:int| {
println!("{}", *three + n); // will copy x into the closure
assert_eq!(*three, 3);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
#[derive(Debug)]
struct Foo(Box<[u8]>);
pub fn main() {
- println!("{:?}", Foo(box [0, 1, 2]));
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ println!("{:?}", Foo(Box::new([0, 1, 2])));
}
pub fn main() {
let (tx, rx) = channel::<uint>();
- let x = box 1;
+ let x: Box<_> = box 1;
let x_in_parent = &(*x) as *const int as uint;
let _t = Thread::spawn(move || {
}
fn check_names(arc: Arc<Vec<Box<Pet+Sync+Send>>>) {
for pet in &*arc {
- pet.name(box |name| {
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ pet.name(Box::new(|name| {
assert!(name.as_bytes()[0] == 'a' as u8 && name.as_bytes()[1] == 'l' as u8);
- })
+ }))
}
}
fn check_pedigree(arc: Arc<Vec<Box<Pet+Sync+Send>>>) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
trait Trait<T> {
fn f(&self, x: T);
}
pub fn main() {
let a = Struct { x: 1, y: 2 };
- let b: Box<Trait<&'static str>> = box a;
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let b: Box<Trait<&'static str>> = Box::new(a);
b.f("Mary");
let c: &Trait<&'static str> = &a;
c.f("Joe");
a.write(b"Hello\n");
}
+// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+
pub fn main() {
let a = Struct { x: 1, y: 2 };
- let b: Box<Trait> = box a;
+ let b: Box<Trait> = Box::new(a);
b.f();
let c: &Trait = &a;
c.f();
let out = old_io::stdout();
- foo(box out);
+ foo(Box::new(out));
}
assert_eq!(get_it(&1_u32), 1_u32);
assert_eq!(get_it(&1_u16), 1_u16);
assert_eq!(get_it(&Some(1_u16)), Some(1_u16));
- assert_eq!(get_it(&box 1), box 1);
+ assert_eq!(get_it(&Box::new(1)), Box::new(1));
}
pub fn main() {
p_foo(r(10));
- p_foo(box r(10));
- p_foo(box 10);
+ p_foo::<Box<_>>(box r(10));
+ p_foo::<Box<_>>(box 10);
p_foo(10);
- s_foo(box 10);
+ s_foo::<Box<_>>(box 10);
s_foo(10);
- u_foo(box 10);
+ u_foo::<Box<_>>(box 10);
u_foo(10);
}
}
fn main() {
- let foo = box Foo {
+ let foo: Box<_> = box Foo {
f: 1,
};
println!("{} {} {}", foo.foo(2), foo.bar(2), foo.baz(2));
- let bar = box Bar {
+ let bar: Box<_> = box Bar {
f: 1,
};
println!("{} {} {}", bar.foo(2), bar.bar(2), bar.baz(2));
// Test that the call operator autoderefs when calling to an object type.
#![allow(unknown_features)]
-#![feature(box_syntax)]
#![feature(unboxed_closures)]
use std::ops::FnMut;
fn make_adder(x: int) -> Box<FnMut(int)->int + 'static> {
- box move |y| { x + y }
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ Box::new(move |y| { x + y })
}
pub fn main() {
// except according to those terms.
#![allow(unknown_features)]
-#![feature(box_syntax)]
#![feature(unboxed_closures)]
use std::ops::FnMut;
fn make_adder(x: int) -> Box<FnMut(int)->int + 'static> {
- box move |y| { x + y }
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ Box::new(move |y| { x + y })
}
pub fn main() {
fn main(){
fn bar<'a, T:Clone+'a> (t: T) -> Box<FnMut()->T + 'a> {
- box move || t.clone()
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ Box::new(move || t.clone())
}
let mut f = bar(42_u32);
#![feature(unboxed_closures)]
fn main() {
- let task: Box<Fn(int) -> int> = box |x| x;
+ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+ let task: Box<Fn(int) -> int> = Box::new(|x| x);
task.call((0, ));
- let mut task: Box<FnMut(int) -> int> = box |x| x;
+ let mut task: Box<FnMut(int) -> int> = Box::new(|x| x);
task(0);
call(|x| x, 22);
}
pub fn main() {
- let x = box X { a: 32 };
+ let x: Box<_> = box X { a: 32 };
let new_x = x.change();
assert_eq!(new_x.a, 55);
}
#![feature(box_syntax)]
pub fn main() {
- let mut i = box 1;
+ let mut i: Box<_> = box 1;
// Should be a copy
let mut j;
j = i.clone();
#![feature(box_syntax)]
pub fn main() {
- let i = box 1;
- let mut j = box 2;
+ let i: Box<_> = box 1;
+ let mut j: Box<_> = box 2;
// Should drop the previous value of j
j = i;
assert_eq!(*j, 1);
}
pub fn main() {
- let t = f(box 100);
+ let t = f::<Box<_>>(box 100);
assert_eq!(t, box 100);
}
#![feature(box_syntax)]
pub fn main() {
- let mut i;
+ let mut i: Box<_>;
i = box 1;
assert_eq!(*i, 1);
}
struct J { j: int }
pub fn main() {
- let i = box J {
+ let i: Box<_> = box J {
j: 100
};
assert_eq!(i.j, 100);
#![feature(box_syntax)]
pub fn main() {
- let i = box vec!(100);
+ let i: Box<_> = box vec!(100);
assert_eq!((*i)[0], 100);
}
#![feature(box_syntax)]
pub fn main() {
- let i = box 100;
+ let i: Box<_> = box 100;
assert!(i == box 100);
assert!(i < box 101);
assert!(i <= box 100);
pub fn main() {
enum t { t1(int), t2(int), }
- let _x = box t::t1(10);
+ let _x: Box<_> = box t::t1(10);
/*alt *x {
t1(a) {
#![feature(box_syntax)]
pub fn main() {
- box 100;
+ let _: Box<_> = box 100;
}
fn vec() {
#![feature(box_syntax)]
pub fn main() {
- let mut i = box 1;
+ let mut i: Box<_> = box 1;
// Should be a copy
let mut j = i.clone();
*i = 2;
#![feature(box_syntax)]
pub fn main() {
- let i = box 1;
+ let i: Box<_> = box 1;
let j = i;
assert_eq!(*j, 1);
}
#![feature(box_syntax)]
pub fn main() {
- let i = box 100;
+ let i: Box<_> = box 100;
let j = i;
assert_eq!(*j, 100);
}
#![feature(box_syntax)]
pub fn main() {
- let i = box 100;
+ let i: Box<_> = box 100;
assert_eq!(*i, 100);
}
#![feature(box_syntax)]
pub fn main() {
- let _x = box vec!(0,0,0,0,0);
+ let _x: Box<_> = box vec!(0,0,0,0,0);
}
#![feature(box_syntax)]
pub fn main() {
- let mut a = vec!(box 10);
+ let mut a: Vec<Box<_>> = vec!(box 10);
let b = a.clone();
assert_eq!(*a[0], 10);
#![feature(box_syntax)]
pub fn main() {
- let vect = vec!(box 100);
+ let vect : Vec<Box<_>> = vec!(box 100);
assert!(vect[0] == box 100);
}
#![feature(box_syntax)]
pub fn main() {
- let _i = box 100;
+ let _i: Box<_> = box 100;
}
assert!(i != j);
}
- let i = box 100;
- let j = box 100;
+ let i: Box<_> = box 100;
+ let j: Box<_> = box 100;
f(i, j);
- let i = box 100;
- let j = box 101;
+ let i: Box<_> = box 100;
+ let j: Box<_> = box 101;
g(i, j);
}
assert!(i != j);
}
- let i = box 100;
- let j = box 100;
+ let i: Box<_> = box 100;
+ let j: Box<_> = box 100;
f(i, j);
- let i = box 100;
- let j = box 101;
+ let i: Box<_> = box 100;
+ let j: Box<_> = box 101;
g(i, j);
}
assert!(i != j);
}
- let i = box 100;
- let j = box 100;
+ let i: Box<_> = box 100;
+ let j: Box<_> = box 100;
f(i, j);
- let i = box 100;
- let j = box 101;
+ let i: Box<_> = box 100;
+ let j: Box<_> = box 101;
g(i, j);
}
#![feature(box_syntax)]
pub fn main() {
- let i = box 100;
+ let i: Box<_> = box 100;
println!("{}", i);
}
// Issue #961
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
fn altsimple() {
- match box true {
+ match Box::new(true) {
_ => { }
}
}
#![feature(box_syntax)]
pub fn main() {
- let i = box 100;
- let j = box 200;
+ let i: Box<_> = box 100;
+ let j: Box<_> = box 200;
let j = i;
assert_eq!(*j, 100);
}
#![feature(box_syntax)]
pub fn main() {
- let mut i;
+ let mut i: Box<_>;
i = box 100;
assert_eq!(*i, 100);
}
#![feature(box_syntax)]
pub fn main() {
- let i = box 100;
+ let i: Box<_> = box 100;
let mut j;
j = i;
assert_eq!(*j, 100);
#![feature(box_syntax)]
pub fn main() {
- let mut i = box 0;
+ let mut i: Box<_> = box 0;
*i = 1;
assert_eq!(*i, 1);
}
struct X { x: int }
pub fn main() {
- let x = box X {x: 1};
+ let x: Box<_> = box X {x: 1};
let bar = x;
assert_eq!(bar.x, 1);
}
use std::sync::mpsc::channel;
pub fn main() {
- let (tx, rx) = channel();
+ let (tx, rx) = channel::<Box<_>>();
tx.send(box 100).unwrap();
let v = rx.recv().unwrap();
assert_eq!(v, box 100);
use std::mem::swap;
pub fn main() {
- let mut i = box 100;
- let mut j = box 200;
+ let mut i: Box<_> = box 100;
+ let mut j: Box<_> = box 200;
swap(&mut i, &mut j);
assert_eq!(i, box 200);
assert_eq!(j, box 100);
f: [T; 3]
}
- let data = box Foo_{f: [1i32, 2, 3] };
+ let data: Box<_> = box Foo_{f: [1i32, 2, 3] };
let x: &Foo<i32> = mem::transmute(raw::Slice { len: 3, data: &*data });
assert!(x.f.len() == 3);
assert!(x.f[0] == 1);
f2: [u8; 5],
}
- let data = box Baz_{ f1: 42, f2: ['a' as u8, 'b' as u8, 'c' as u8, 'd' as u8, 'e' as u8] };
+ let data: Box<_> = box Baz_ {
+ f1: 42, f2: ['a' as u8, 'b' as u8, 'c' as u8, 'd' as u8, 'e' as u8] };
let x: &Baz = mem::transmute( raw::Slice { len: 5, data: &*data } );
assert!(x.f1 == 42);
let chs: Vec<char> = x.f2.chars().collect();
let obj: Box<St> = box St { f: 42 };
let obj: &Tr = &*obj;
let obj: raw::TraitObject = mem::transmute(&*obj);
- let data = box Qux_{ f: St { f: 234 } };
+ let data: Box<_> = box Qux_{ f: St { f: 234 } };
let x: &Qux = mem::transmute(raw::TraitObject { vtable: obj.vtable,
data: mem::transmute(&*data) });
assert!(x.f.foo() == 234);
#![feature(box_syntax)]
pub fn main() {
- let _x = box 1;
+ let _x: Box<_> = box 1;
let lam_move = || {};
lam_move();
}
pub fn main()
{
- let y = box 1;
+ let y: Box<_> = box 1;
y;
}
use std::thread;
fn f() {
- let _a = box 0;
+ let _a: Box<_> = box 0;
panic!();
}