False);
if threshold != 0u {
- llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(MPMB,
- threshold);
+ llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(
+ MPMB, threshold);
}
-
llvm::LLVMPassManagerBuilderPopulateModulePassManager(MPMB,
pm.llpm);
provided_metas {
let name: option::t<str> = none;
let vers: option::t<str> = none;
- let cmh_items: [@ast::meta_item] = ~[];
+ let cmh_items: [@ast::meta_item] = [];
let linkage_metas = attr::find_linkage_metas(c.node.attrs);
attr::require_unique_names(sess, linkage_metas);
for meta: @ast::meta_item in linkage_metas {
if attr::get_meta_item_name(meta) == "name" {
alt attr::get_meta_item_value_str(meta) {
some(v) { name = some(v); }
- none. { cmh_items += ~[meta]; }
+ none. { cmh_items += [meta]; }
}
- } else if (attr::get_meta_item_name(meta) == "vers") {
+ } else if attr::get_meta_item_name(meta) == "vers" {
alt attr::get_meta_item_value_str(meta) {
some(v) { vers = some(v); }
- none. { cmh_items += ~[meta]; }
+ none. { cmh_items += [meta]; }
}
- } else { cmh_items += ~[meta]; }
+ } else { cmh_items += [meta]; }
}
ret {name: name, vers: vers, cmh_items: cmh_items};
}
fn crate_meta_extras_hash(sha: sha1, _crate: &ast::crate,
metas: &provided_metas) -> str {
fn len_and_str(s: &str) -> str {
- ret #fmt("%u_%s", str::byte_len(s), s);
+ ret #fmt["%u_%s", str::byte_len(s), s];
}
fn len_and_str_lit(l: &ast::lit) -> str {
fn warn_missing(sess: &session::session, name: str, default: str) {
if !sess.get_opts().library { ret; }
- sess.warn(#fmt("missing crate link meta '%s', using '%s' as default",
- name, default));
+ sess.warn(#fmt["missing crate link meta '%s', using '%s' as default",
+ name, default]);
}
fn crate_meta_name(sess: &session::session, _crate: &ast::crate,
none. {
let name =
{
- let os =
- str::split(fs::basename(output), '.' as u8);
+ let os = str::split(fs::basename(output), '.' as u8);
assert (vec::len(os) >= 2u);
vec::pop(os);
str::connect(os, ".")
let n = "_ZN"; // Begin name-sequence.
- for s: str in ss { n += #fmt("%u%s", str::byte_len(s), s); }
+ for s: str in ss { n += #fmt["%u%s", str::byte_len(s), s]; }
n += "E"; // End name-sequence.
ret n;
fn exported_name(path: &[str], hash: &str, _vers: &str) -> str {
// FIXME: versioning isn't working yet
- ret mangle(path + ~[hash]); // + "@" + vers;
+ ret mangle(path + [hash]); // + "@" + vers;
}
-> str {
let s = util::ppaux::ty_to_short_str(ccx.tcx, t);
let hash = get_symbol_hash(ccx, t);
- ret mangle(~[name, s, hash]);
+ ret mangle([name, s, hash]);
}
fn mangle_internal_name_by_path_and_seq(ccx: &@crate_ctxt, path: &[str],
flav: &str) -> str {
- ret mangle(path + ~[ccx.names.next(flav)]);
+ ret mangle(path + [ccx.names.next(flav)]);
}
fn mangle_internal_name_by_path(_ccx: &@crate_ctxt, path: &[str]) -> str {
fn declare_upcalls(_tn: type_names, tydesc_type: TypeRef,
taskptr_type: TypeRef, llmod: ModuleRef) -> @upcalls {
- fn decl(llmod: ModuleRef, name: str, tys: [TypeRef],
- rv: TypeRef) -> ValueRef {
- let arg_tys: [TypeRef] = ~[];
- for t: TypeRef in tys { arg_tys += ~[t]; }
+ fn decl(llmod: ModuleRef, name: str, tys: [TypeRef], rv: TypeRef) ->
+ ValueRef {
+ let arg_tys: [TypeRef] = [];
+ for t: TypeRef in tys { arg_tys += [t]; }
let fn_ty = T_fn(arg_tys, rv);
ret trans::decl_cdecl_fn(llmod, "upcall_" + name, fn_ty);
}
- fn decl_with_taskptr(taskptr_type: TypeRef,
- llmod: ModuleRef, name: str, tys: [TypeRef],
- rv: TypeRef) -> ValueRef {
- ret decl(llmod, name, ~[taskptr_type] + tys, rv);
+ fn decl_with_taskptr(taskptr_type: TypeRef, llmod: ModuleRef, name: str,
+ tys: [TypeRef], rv: TypeRef) -> ValueRef {
+ ret decl(llmod, name, [taskptr_type] + tys, rv);
}
let dv = bind decl_with_taskptr(taskptr_type, llmod, _, _, T_void());
let d = bind decl_with_taskptr(taskptr_type, llmod, _, _, _);
let dr = bind decl(llmod, _, _, _);
- let empty_vec: [TypeRef] = ~[];
- ret @{grow_task: dv("grow_task", ~[T_size_t()]),
+ let empty_vec: [TypeRef] = [];
+ ret @{grow_task: dv("grow_task", [T_size_t()]),
_yield: dv("yield", empty_vec),
- sleep: dv("sleep", ~[T_size_t()]),
- _fail: dv("fail", ~[T_ptr(T_i8()), T_ptr(T_i8()), T_size_t()]),
- kill: dv("kill", ~[taskptr_type]),
+ sleep: dv("sleep", [T_size_t()]),
+ _fail: dv("fail", [T_ptr(T_i8()), T_ptr(T_i8()), T_size_t()]),
+ kill: dv("kill", [taskptr_type]),
exit: dv("exit", empty_vec),
malloc:
- d("malloc", ~[T_size_t(), T_ptr(tydesc_type)], T_ptr(T_i8())),
- free: dv("free", ~[T_ptr(T_i8()), T_int()]),
+ d("malloc", [T_size_t(), T_ptr(tydesc_type)], T_ptr(T_i8())),
+ free: dv("free", [T_ptr(T_i8()), T_int()]),
shared_malloc:
- d("shared_malloc", ~[T_size_t(), T_ptr(tydesc_type)],
+ d("shared_malloc", [T_size_t(), T_ptr(tydesc_type)],
T_ptr(T_i8())),
- shared_free: dv("shared_free", ~[T_ptr(T_i8())]),
- mark: d("mark", ~[T_ptr(T_i8())], T_int()),
- new_str: d("new_str", ~[T_ptr(T_i8()), T_size_t()], T_ptr(T_str())),
+ shared_free: dv("shared_free", [T_ptr(T_i8())]),
+ mark: d("mark", [T_ptr(T_i8())], T_int()),
+ new_str: d("new_str", [T_ptr(T_i8()), T_size_t()], T_ptr(T_str())),
evec_append:
d("evec_append",
- ~[T_ptr(tydesc_type), T_ptr(tydesc_type),
- T_ptr(T_opaque_vec_ptr()), T_opaque_vec_ptr(), T_bool()],
+ [T_ptr(tydesc_type), T_ptr(tydesc_type),
+ T_ptr(T_opaque_vec_ptr()), T_opaque_vec_ptr(), T_bool()],
T_void()),
get_type_desc:
d("get_type_desc",
- ~[T_ptr(T_nil()), T_size_t(), T_size_t(), T_size_t(),
- T_ptr(T_ptr(tydesc_type))], T_ptr(tydesc_type)),
+ [T_ptr(T_nil()), T_size_t(), T_size_t(), T_size_t(),
+ T_ptr(T_ptr(tydesc_type))], T_ptr(tydesc_type)),
ivec_resize:
- d("ivec_resize", ~[T_ptr(T_opaque_ivec()), T_int()], T_void()),
+ d("ivec_resize", [T_ptr(T_opaque_ivec()), T_int()], T_void()),
ivec_spill:
- d("ivec_spill", ~[T_ptr(T_opaque_ivec()), T_int()], T_void()),
+ d("ivec_spill", [T_ptr(T_opaque_ivec()), T_int()], T_void()),
ivec_resize_shared:
- d("ivec_resize_shared", ~[T_ptr(T_opaque_ivec()), T_int()],
+ d("ivec_resize_shared", [T_ptr(T_opaque_ivec()), T_int()],
T_void()),
ivec_spill_shared:
- d("ivec_spill_shared", ~[T_ptr(T_opaque_ivec()), T_int()],
+ d("ivec_spill_shared", [T_ptr(T_opaque_ivec()), T_int()],
T_void()),
cmp_type:
- dr("cmp_type", ~[T_ptr(T_i1()), taskptr_type,
- T_ptr(tydesc_type), T_ptr(T_ptr(tydesc_type)),
- T_ptr(T_i8()), T_ptr(T_i8()), T_i8()],
- T_void()),
+ dr("cmp_type",
+ [T_ptr(T_i1()), taskptr_type, T_ptr(tydesc_type),
+ T_ptr(T_ptr(tydesc_type)), T_ptr(T_i8()), T_ptr(T_i8()),
+ T_i8()], T_void()),
log_type:
- dr("log_type", ~[taskptr_type, T_ptr(tydesc_type),
- T_ptr(T_i8()), T_i32()],
+ dr("log_type",
+ [taskptr_type, T_ptr(tydesc_type), T_ptr(T_i8()), T_i32()],
T_void()),
- dynastack_mark:
- d("dynastack_mark", ~[], T_ptr(T_i8())),
- dynastack_alloc:
- d("dynastack_alloc", ~[T_size_t()], T_ptr(T_i8())),
- dynastack_free:
- d("dynastack_free", ~[T_ptr(T_i8())], T_void())};
+ dynastack_mark: d("dynastack_mark", [], T_ptr(T_i8())),
+ dynastack_alloc: d("dynastack_alloc", [T_size_t()], T_ptr(T_i8())),
+ dynastack_free: d("dynastack_free", [T_ptr(T_i8())], T_void())};
}
//
// Local Variables:
let mk = attr::mk_name_value_item_str;
- ret ~[ // Target bindings.
- mk("target_os", std::os::target_os()), mk("target_arch", "x86"),
- mk("target_libc", libc),
- // Build bindings.
- mk("build_compiler", argv0), mk("build_input", input)];
+ ret [ // Target bindings.
+ mk("target_os", std::os::target_os()), mk("target_arch", "x86"),
+ mk("target_libc", libc),
+ // Build bindings.
+ mk("build_compiler", argv0), mk("build_input", input)];
}
fn build_configuration(sess: session::session, argv0: str, input: str) ->
{
if sess.get_opts().test && !attr::contains_name(user_cfg, "test")
{
- ~[attr::mk_word_item("test")]
- } else { ~[] }
+ [attr::mk_word_item("test")]
+ } else { [] }
};
ret user_cfg + gen_cfg + default_cfg;
}
fn parse_cfgspecs(cfgspecs: &[str]) -> ast::crate_cfg {
// FIXME: It would be nice to use the parser to parse all varieties of
// meta_item here. At the moment we just support the meta_word variant.
- let words = ~[];
- for s: str in cfgspecs { words += ~[attr::mk_word_item(s)]; }
+ let words = [];
+ for s: str in cfgspecs { words += [attr::mk_word_item(s)]; }
ret words;
}
@ast::crate {
if !input_is_stdin(input) {
parser::parse_crate_from_file(input, cfg, sess.get_parse_sess())
- } else {
- parse_input_src(sess, cfg, input).crate
- }
+ } else { parse_input_src(sess, cfg, input).crate }
}
-fn parse_input_src(sess: session::session, cfg: &ast::crate_cfg,
- infile: str) -> {crate: @ast::crate, src: str} {
- let srcbytes = if infile != "-" {
- io::file_reader(infile)
- } else {
- io::stdin()
- }.read_whole_stream();
+fn parse_input_src(sess: session::session, cfg: &ast::crate_cfg, infile: str)
+ -> {crate: @ast::crate, src: str} {
+ let srcbytes =
+ if infile != "-" {
+ io::file_reader(infile)
+ } else { io::stdin() }.read_whole_stream();
let src = str::unsafe_from_bytes(srcbytes);
- let crate = parser::parse_crate_from_source_str(infile, src, cfg,
- sess.get_parse_sess());
+ let crate =
+ parser::parse_crate_from_source_str(infile, src, cfg,
+ sess.get_parse_sess());
ret {crate: crate, src: src};
}
-fn time<T>(do_it: bool, what: str, thunk: fn() -> T ) -> T {
+fn time<T>(do_it: bool, what: str, thunk: fn() -> T) -> T {
if !do_it { ret thunk(); }
let start = std::time::precise_time_s();
let rv = thunk();
let end = std::time::precise_time_s();
- log_err #fmt("time: %s took %s s", what,
- common::float_to_str(end - start, 3u));
+ log_err #fmt["time: %s took %s s", what,
+ common::float_to_str(end - start, 3u)];
ret rv;
}
bind middle::ast_map::map_crate(*crate));
time(time_passes, "external crate/lib resolution",
bind creader::read_crates(sess, *crate));
- let {def_map, ext_map} =
+ let {def_map: def_map, ext_map: ext_map} =
time(time_passes, "resolution",
bind resolve::resolve_crate(sess, ast_map, crate));
let freevars =
bind freevars::annotate_freevars(sess, def_map, crate));
let ty_cx = ty::mk_ctxt(sess, def_map, ext_map, ast_map, freevars);
time::<()>(time_passes, "typechecking",
- bind typeck::check_crate(ty_cx, crate));
+ bind typeck::check_crate(ty_cx, crate));
time::<()>(time_passes, "alt checking",
- bind middle::check_alt::check_crate(ty_cx, crate));
+ bind middle::check_alt::check_crate(ty_cx, crate));
if sess.get_opts().run_typestate {
time(time_passes, "typestate checking",
bind middle::tstate::ck::check_crate(ty_cx, crate));
time(time_passes, "alias checking",
bind middle::alias::check_crate(ty_cx, crate));
time::<()>(time_passes, "kind checking",
- bind kind::check_crate(ty_cx, crate));
+ bind kind::check_crate(ty_cx, crate));
if sess.get_opts().no_trans { ret; }
let llmod =
time::<llvm::llvm::ModuleRef>(time_passes, "translation",
- bind trans::trans_crate(sess, crate,
- ty_cx, output,
- ast_map));
+ bind trans::trans_crate(sess, crate,
+ ty_cx, output,
+ ast_map));
time::<()>(time_passes, "LLVM passes",
- bind link::write::run_passes(sess, llmod, output));
+ bind link::write::run_passes(sess, llmod, output));
}
fn pretty_print_input(sess: session::session, cfg: ast::crate_cfg, input: str,
alt ppm {
ppm_typed. {
let amap = middle::ast_map::map_crate(*crate);
- let {def_map, ext_map} = resolve::resolve_crate(sess, amap, crate);
+ let {def_map: def_map, ext_map: ext_map} =
+ resolve::resolve_crate(sess, amap, crate);
let freevars = freevars::annotate_freevars(sess, def_map, crate);
let ty_cx = ty::mk_ctxt(sess, def_map, ext_map, amap, freevars);
typeck::check_crate(ty_cx, crate);
fn version(argv0: str) {
let vers = "unknown version";
- let env_vers = #env("CFG_VERSION");
+ let env_vers = #env["CFG_VERSION"];
if str::byte_len(env_vers) != 0u { vers = env_vers; }
- io::stdout().write_str(#fmt("%s %s\n", argv0, vers));
+ io::stdout().write_str(#fmt["%s %s\n", argv0, vers]);
}
fn usage(argv0: str) {
- io::stdout().write_str(#fmt("usage: %s [options] <input>\n", argv0) +
- "
+ io::stdout().write_str(#fmt["usage: %s [options] <input>\n", argv0] +
+ "
options:
-h --help display this message
ret if str::find(triple, "win32") >= 0 ||
str::find(triple, "mingw32") >= 0 {
session::os_win32
- } else if (str::find(triple, "darwin") >= 0) {
+ } else if str::find(triple, "darwin") >= 0 {
session::os_macos
- } else if (str::find(triple, "linux") >= 0) {
+ } else if str::find(triple, "linux") >= 0 {
session::os_linux
} else { log_err "Unknown operating system!"; fail };
}
str::find(triple, "i686") >= 0 ||
str::find(triple, "i786") >= 0 {
session::arch_x86
- } else if (str::find(triple, "x86_64") >= 0) {
+ } else if str::find(triple, "x86_64") >= 0 {
session::arch_x64
- } else if (str::find(triple, "arm") >= 0 ||
- str::find(triple, "xscale") >= 0) {
+ } else if str::find(triple, "arm") >= 0 ||
+ str::find(triple, "xscale") >= 0 {
session::arch_arm
} else { log_err "Unknown architecture! " + triple; fail };
}
let library = opt_present(match, "lib");
let static = opt_present(match, "static");
- let library_search_paths = ~[binary_dir + "/lib"];
+ let library_search_paths = [binary_dir + "/lib"];
let lsp_vec = getopts::opt_strs(match, "L");
- for lsp: str in lsp_vec { library_search_paths += ~[lsp]; }
+ for lsp: str in lsp_vec { library_search_paths += [lsp]; }
let parse_only = opt_present(match, "parse-only");
let no_trans = opt_present(match, "no-trans");
let output_type =
if parse_only || no_trans {
link::output_type_none
- } else if (opt_present(match, "S")) {
+ } else if opt_present(match, "S") {
link::output_type_assembly
- } else if (opt_present(match, "c")) {
+ } else if opt_present(match, "c") {
link::output_type_object
- } else if (opt_present(match, "emit-llvm")) {
+ } else if opt_present(match, "emit-llvm") {
link::output_type_bitcode
} else { link::output_type_exe };
let verify = !opt_present(match, "noverify");
fail;
}
2u
- } else if (opt_present(match, "OptLevel")) {
+ } else if opt_present(match, "OptLevel") {
alt getopts::opt_str(match, "OptLevel") {
"0" { 0u }
"1" { 1u }
fn parse_pretty(sess: session::session, name: &str) -> pp_mode {
if str::eq(name, "normal") {
ret ppm_normal;
- } else if (str::eq(name, "typed")) {
+ } else if str::eq(name, "typed") {
ret ppm_typed;
- } else if (str::eq(name, "identified")) { ret ppm_identified; }
+ } else if str::eq(name, "identified") { ret ppm_identified; }
sess.fatal("argument to `pretty` or `expand` must be one of `normal`, " +
"`typed`, or `identified`");
}
fn opts() -> [getopts::opt] {
- ret ~[optflag("h"), optflag("help"), optflag("v"), optflag("version"),
- optflag("glue"), optflag("emit-llvm"), optflagopt("pretty"),
- optflagopt("expand"), optflag("ls"), optflag("parse-only"),
- optflag("no-trans"),
- optflag("O"), optopt("OptLevel"), optmulti("L"), optflag("S"),
- optflag("c"), optopt("o"), optflag("g"), optflag("save-temps"),
- optopt("sysroot"), optflag("stats"), optflag("time-passes"),
- optflag("time-llvm-passes"), optflag("no-typestate"),
- optflag("noverify"), optmulti("cfg"), optflag("test"),
- optflag("lib"), optflag("static"), optflag("gc")];
+ ret [optflag("h"), optflag("help"), optflag("v"), optflag("version"),
+ optflag("glue"), optflag("emit-llvm"), optflagopt("pretty"),
+ optflagopt("expand"), optflag("ls"), optflag("parse-only"),
+ optflag("no-trans"), optflag("O"), optopt("OptLevel"), optmulti("L"),
+ optflag("S"), optflag("c"), optopt("o"), optflag("g"),
+ optflag("save-temps"), optopt("sysroot"), optflag("stats"),
+ optflag("time-passes"), optflag("time-llvm-passes"),
+ optflag("no-typestate"), optflag("noverify"), optmulti("cfg"),
+ optflag("test"), optflag("lib"), optflag("static"), optflag("gc")];
}
fn main(args: [str]) {
alt getopts::getopts(args, opts()) {
getopts::success(m) { m }
getopts::failure(f) {
- log_err #fmt("error: %s", getopts::fail_str(f));
+ log_err #fmt["error: %s", getopts::fail_str(f)];
fail
}
};
}
if n_inputs == 0u {
sess.fatal("No input filename given.");
- } else if (n_inputs > 1u) {
+ } else if n_inputs > 1u {
sess.fatal("Multiple input filenames provided.");
}
- let ifile = match.free.(0);
+ let ifile = match.free[0];
let saved_out_filename: str = "";
let cfg = build_configuration(sess, binary, ifile);
let expand =
none::<pp_mode>. {/* continue */ }
}
let ls = opt_present(match, "ls");
- if ls {
- metadata::creader::list_file_metadata(ifile, io::stdout());
- ret;
- }
+ if ls { metadata::creader::list_file_metadata(ifile, io::stdout()); ret; }
let stop_after_codegen =
sopts.output_type != link::output_type_exe ||
// "-" as input file will cause the parser to read from stdin so we
// have to make up a name
// We want to toss everything after the final '.'
- let parts = if !input_is_stdin(ifile) {
- str::split(ifile, '.' as u8)
- } else {
- ~["default", "rs"]
- };
+ let parts =
+ if !input_is_stdin(ifile) {
+ str::split(ifile, '.' as u8)
+ } else { ["default", "rs"] };
vec::pop(parts);
saved_out_filename = str::connect(parts, ".");
- let suffix = alt sopts.output_type {
- link::output_type_none. { "none" }
- link::output_type_bitcode. { "bc" }
- link::output_type_assembly. { "s" }
- // Object and exe output both use the '.o' extension here
- link::output_type_object. | link::output_type_exe. { "o" }
- };
+ let suffix =
+ alt sopts.output_type {
+ link::output_type_none. { "none" }
+ link::output_type_bitcode. { "bc" }
+ link::output_type_assembly. { "s" }
+
+ // Object and exe output both use the '.o' extension here
+ link::output_type_object. | link::output_type_exe. {
+ "o"
+ }
+ };
let ofile = saved_out_filename + "." + suffix;
compile_input(sess, cfg, ifile, ofile);
}
some(ofile) {
// FIXME: what about windows? This will create a foo.exe.o.
saved_out_filename = ofile;
- let temp_filename = if !stop_after_codegen {
- ofile + ".o"
- } else { ofile };
+ let temp_filename =
+ if !stop_after_codegen { ofile + ".o" } else { ofile };
compile_input(sess, cfg, ifile, temp_filename);
}
}
// The invocations of gcc share some flags across platforms
let gcc_args =
- ~[stage, "-Lrt", "-lrustrt", glu, "-m32", "-o", saved_out_filename,
- saved_out_filename + ".o"];
+ [stage, "-Lrt", "-lrustrt", glu, "-m32", "-o", saved_out_filename,
+ saved_out_filename + ".o"];
let lib_cmd;
let os = sess.get_targ_cfg().os;
let cstore = sess.get_cstore();
for cratepath: str in cstore::get_used_crate_files(cstore) {
if str::ends_with(cratepath, ".rlib") {
- gcc_args += ~[cratepath];
+ gcc_args += [cratepath];
cont;
}
let dir = fs::dirname(cratepath);
- if dir != "" { gcc_args += ~["-L" + dir]; }
+ if dir != "" { gcc_args += ["-L" + dir]; }
let libarg = unlib(sess.get_targ_cfg(), fs::basename(cratepath));
- gcc_args += ~["-l" + libarg];
+ gcc_args += ["-l" + libarg];
}
let ula = cstore::get_used_link_args(cstore);
- for arg: str in ula { gcc_args += ~[arg]; }
+ for arg: str in ula { gcc_args += [arg]; }
let used_libs = cstore::get_used_libraries(cstore);
- for l: str in used_libs { gcc_args += ~["-l" + l]; }
+ for l: str in used_libs { gcc_args += ["-l" + l]; }
if sopts.library {
- gcc_args += ~[lib_cmd];
+ gcc_args += [lib_cmd];
} else {
// FIXME: why do we hardcode -lm?
- gcc_args += ~["-lm", main];
+ gcc_args += ["-lm", main];
}
// We run 'gcc' here
let err_code = run::run_program(prog, gcc_args);
if 0 != err_code {
- sess.err(#fmt("linking with gcc failed with code %d", err_code));
- sess.note(#fmt("gcc arguments: %s",
- str::connect(gcc_args, " ")));
+ sess.err(#fmt["linking with gcc failed with code %d", err_code]);
+ sess.note(#fmt["gcc arguments: %s", str::connect(gcc_args, " ")]);
sess.abort_if_errors();
}
// Clean up on Darwin
if sess.get_targ_cfg().os == session::os_macos {
- run::run_program("dsymutil", ~[saved_out_filename]);
+ run::run_program("dsymutil", [saved_out_filename]);
}
// Remove the temporary object file if we aren't saving temps
if !sopts.save_temps {
- run::run_program("rm", ~[saved_out_filename + ".o"]);
+ run::run_program("rm", [saved_out_filename + ".o"]);
}
}
#[test]
fn test_switch_implies_cfg_test() {
let match =
- alt getopts::getopts(~["--test"], opts()) {
+ alt getopts::getopts(["--test"], opts()) {
getopts::success(m) { m }
};
let sessopts = build_session_options("whatever", match, "whatever");
#[test]
fn test_switch_implies_cfg_test_unless_cfg_test() {
let match =
- alt getopts::getopts(~["--test", "--cfg=test"], opts()) {
+ alt getopts::getopts(["--test", "--cfg=test"], opts()) {
getopts::success(m) { m }
};
let sessopts = build_session_options("whatever", match, "whatever");
test: bool,
parse_only: bool,
no_trans: bool,
- do_gc: bool
- };
+ do_gc: bool};
type crate_metadata = {name: str, data: [u8]};
}
fn note(msg: str) { codemap::emit_note(none, msg, parse_sess.cm); }
fn span_bug(sp: span, msg: str) -> ! {
- self.span_fatal(sp, #fmt("internal compiler error %s", msg));
+ self.span_fatal(sp, #fmt["internal compiler error %s", msg]);
}
fn bug(msg: str) -> ! {
- self.fatal(#fmt("internal compiler error %s", msg));
+ self.fatal(#fmt["internal compiler error %s", msg]);
}
fn span_unimpl(sp: span, msg: str) -> ! {
self.span_bug(sp, "unimplemented " + msg);
// From a list of crate attributes get only the meta_items that impact crate
// linkage
fn find_linkage_metas(attrs: &[ast::attribute]) -> [@ast::meta_item] {
- let metas: [@ast::meta_item] = ~[];
+ let metas: [@ast::meta_item] = [];
for attr: ast::attribute in find_attrs_by_name(attrs, "link") {
alt attr.node.value.node {
ast::meta_list(_, items) { metas += items; }
// Get the meta_items from inside a vector of attributes
fn attr_metas(attrs: &[ast::attribute]) -> [@ast::meta_item] {
- let mitems = ~[];
- for a: ast::attribute in attrs { mitems += ~[attr_meta(a)]; }
+ let mitems = [];
+ for a: ast::attribute in attrs { mitems += [attr_meta(a)]; }
ret mitems;
}
}
fn contains(haystack: &[@ast::meta_item], needle: @ast::meta_item) -> bool {
- log #fmt("looking for %s",
- syntax::print::pprust::meta_item_to_str(*needle));
+ log #fmt["looking for %s",
+ syntax::print::pprust::meta_item_to_str(*needle)];
for item: @ast::meta_item in haystack {
- log #fmt("looking in %s",
- syntax::print::pprust::meta_item_to_str(*item));
+ log #fmt["looking in %s",
+ syntax::print::pprust::meta_item_to_str(*item)];
if eq(item, needle) { log "found it!"; ret true; }
}
log "found it not :(";
}
// This is sort of stupid here, converting to a vec of mutables and back
- let v: [mutable @ast::meta_item] = ~[mutable];
- for mi: @ast::meta_item in items { v += ~[mutable mi]; }
+ let v: [mutable @ast::meta_item] = [mutable];
+ for mi: @ast::meta_item in items { v += [mutable mi]; }
std::sort::quick_sort(lteq, v);
- let v2: [@ast::meta_item] = ~[];
- for mi: @ast::meta_item in v { v2 += ~[mi]; }
+ let v2: [@ast::meta_item] = [];
+ for mi: @ast::meta_item in v { v2 += [mi]; }
ret v2;
}
ret vec::filter_map(filter, items);
}
-fn require_unique_names(sess: &session::session,
- metas: &[@ast::meta_item]) {
+fn require_unique_names(sess: &session::session, metas: &[@ast::meta_item]) {
let map = map::mk_hashmap::<str, ()>(str::hash, str::eq);
for meta: @ast::meta_item in metas {
let name = get_meta_item_name(meta);
if map.contains_key(name) {
sess.span_fatal(meta.span,
- #fmt("duplicate meta item `%s`", name));
+ #fmt["duplicate meta item `%s`", name]);
}
map.insert(name, ());
}
}
}
let cfg_metas = attr::attr_metas(item_cfg_attrs);
- vec::foldl(extract_metas, ~[], cfg_metas)
+ vec::foldl(extract_metas, [], cfg_metas)
};
for cfg_mi: @ast::meta_item in item_cfg_metas {
export modify_for_testing;
-type node_id_gen = @fn() -> ast::node_id ;
+type node_id_gen = @fn() -> ast::node_id;
type test = {path: [ast::ident], ignore: bool};
let cx: test_ctxt =
@{next_node_id: next_node_id_fn,
- mutable path: ~[],
- mutable testfns: ~[]};
+ mutable path: [],
+ mutable testfns: []};
let precursor =
{fold_crate: bind fold_crate(cx, _, _),
ret res;
}
-fn fold_mod(_cx: &test_ctxt, m: &ast::_mod, fld: fold::ast_fold)
- -> ast::_mod {
+fn fold_mod(_cx: &test_ctxt, m: &ast::_mod, fld: fold::ast_fold) ->
+ ast::_mod {
// Remove any defined main function from the AST so it doesn't clash with
// the one we're going to add. FIXME: This is sloppy. Instead we should
fn fold_item(cx: &test_ctxt, i: &@ast::item, fld: fold::ast_fold) ->
@ast::item {
- cx.path += ~[i.ident];
- log #fmt("current path: %s", ast::path_name_i(cx.path));
+ cx.path += [i.ident];
+ log #fmt["current path: %s", ast::path_name_i(cx.path)];
if is_test_fn(i) {
log "this is a test function";
let test = {path: cx.path, ignore: is_ignored(i)};
- cx.testfns += ~[test];
- log #fmt("have %u test functions", vec::len(cx.testfns));
+ cx.testfns += [test];
+ log #fmt["have %u test functions", vec::len(cx.testfns)];
}
let res = fold::noop_fold_item(i, fld);
fn add_test_module(cx: &test_ctxt, m: &ast::_mod) -> ast::_mod {
let testmod = mk_test_module(cx);
- ret {items: m.items + ~[testmod] with m};
+ ret {items: m.items + [testmod] with m};
}
/*
// The synthesized main function which will call the console test runner
// with our list of tests
let mainfn = mk_main(cx);
- let testmod: ast::_mod = {view_items: ~[], items: ~[mainfn, testsfn]};
+ let testmod: ast::_mod = {view_items: [], items: [mainfn, testsfn]};
let item_ = ast::item_mod(testmod);
let item: ast::item =
{ident: "__test",
- attrs: ~[],
+ attrs: [],
id: cx.next_node_id(),
node: item_,
span: ast::dummy_sp()};
- log #fmt("Synthetic test module:\n%s\n", pprust::item_to_str(@item));
+ log #fmt["Synthetic test module:\n%s\n", pprust::item_to_str(@item)];
ret @item;
}
let ret_ty = mk_test_desc_vec_ty(cx);
let decl: ast::fn_decl =
- {inputs: ~[],
+ {inputs: [],
output: ret_ty,
purity: ast::impure_fn,
il: ast::il_normal,
cf: ast::return,
- constraints: ~[]};
+ constraints: []};
let proto = ast::proto_fn;
// The vector of test_descs for this crate
let test_descs = mk_test_desc_vec(cx);
let body_: ast::blk_ =
- {stmts: ~[], expr: option::some(test_descs), id: cx.next_node_id()};
+ {stmts: [], expr: option::some(test_descs), id: cx.next_node_id()};
let body = nospan(body_);
let fn_ = {decl: decl, proto: proto, body: body};
- let item_ = ast::item_fn(fn_, ~[]);
+ let item_ = ast::item_fn(fn_, []);
let item: ast::item =
{ident: "tests",
- attrs: ~[],
+ attrs: [],
id: cx.next_node_id(),
node: item_,
span: ast::dummy_sp()};
fn empty_fn_ty() -> ast::ty {
let proto = ast::proto_fn;
- let input_ty = ~[];
+ let input_ty = [];
let ret_ty = @nospan(ast::ty_nil);
let cf = ast::return;
- let constrs = ~[];
+ let constrs = [];
ret nospan(ast::ty_fn(proto, input_ty, ret_ty, cf, constrs));
}
fn mk_test_desc_vec_ty(cx: &test_ctxt) -> @ast::ty {
let test_desc_ty_path: ast::path =
nospan({global: false,
- idents: ~["std", "test", "test_desc"],
- types: ~[]});
+ idents: ["std", "test", "test_desc"],
+ types: []});
let test_desc_ty: ast::ty =
nospan(ast::ty_path(test_desc_ty_path, cx.next_node_id()));
}
fn mk_test_desc_vec(cx: &test_ctxt) -> @ast::expr {
- log #fmt("building test vector from %u tests", vec::len(cx.testfns));
- let descs = ~[];
+ log #fmt["building test vector from %u tests", vec::len(cx.testfns)];
+ let descs = [];
for test: test in cx.testfns {
let test_ = test; // Satisfy alias analysis
- descs += ~[mk_test_desc_rec(cx, test_)];
+ descs += [mk_test_desc_rec(cx, test_)];
}
ret @{id: cx.next_node_id(),
fn mk_test_desc_rec(cx: &test_ctxt, test: test) -> @ast::expr {
let path = test.path;
- log #fmt("encoding %s", ast::path_name_i(path));
+ log #fmt["encoding %s", ast::path_name_i(path)];
let name_lit: ast::lit =
nospan(ast::lit_str(ast::path_name_i(path), ast::sk_rc));
let name_field: ast::field =
nospan({mut: ast::imm, ident: "name", expr: @name_expr});
- let fn_path: ast::path =
- nospan({global: false, idents: path, types: ~[]});
+ let fn_path: ast::path = nospan({global: false, idents: path, types: []});
let fn_expr: ast::expr =
{id: cx.next_node_id(),
nospan({mut: ast::imm, ident: "ignore", expr: @ignore_expr});
let desc_rec_: ast::expr_ =
- ast::expr_rec(~[name_field, fn_field, ignore_field], option::none);
+ ast::expr_rec([name_field, fn_field, ignore_field], option::none);
let desc_rec: ast::expr =
{id: cx.next_node_id(), node: desc_rec_, span: ast::dummy_sp()};
ret @desc_rec;
let ret_ty = nospan(ast::ty_nil);
let decl: ast::fn_decl =
- {inputs: ~[args_arg],
+ {inputs: [args_arg],
output: @ret_ty,
purity: ast::impure_fn,
il: ast::il_normal,
cf: ast::return,
- constraints: ~[]};
+ constraints: []};
let proto = ast::proto_fn;
let test_main_call_expr = mk_test_main_call(cx);
let body_: ast::blk_ =
- {stmts: ~[],
+ {stmts: [],
expr: option::some(test_main_call_expr),
id: cx.next_node_id()};
let body = {node: body_, span: ast::dummy_sp()};
let fn_ = {decl: decl, proto: proto, body: body};
- let item_ = ast::item_fn(fn_, ~[]);
+ let item_ = ast::item_fn(fn_, []);
let item: ast::item =
{ident: "main",
- attrs: ~[],
+ attrs: [],
id: cx.next_node_id(),
node: item_,
span: ast::dummy_sp()};
// Get the args passed to main so we can pass the to test_main
let args_path: ast::path =
- nospan({global: false, idents: ~["args"], types: ~[]});
+ nospan({global: false, idents: ["args"], types: []});
let args_path_expr_: ast::expr_ = ast::expr_path(args_path);
let args_path_expr: ast::expr =
- {id: cx.next_node_id(),
- node: args_path_expr_,
- span: ast::dummy_sp()};
+ {id: cx.next_node_id(), node: args_path_expr_, span: ast::dummy_sp()};
// Call __test::test to generate the vector of test_descs
let test_path: ast::path =
- nospan({global: false, idents: ~["tests"], types: ~[]});
+ nospan({global: false, idents: ["tests"], types: []});
let test_path_expr_: ast::expr_ = ast::expr_path(test_path);
let test_path_expr: ast::expr =
- {id: cx.next_node_id(),
- node: test_path_expr_,
- span: ast::dummy_sp()};
+ {id: cx.next_node_id(), node: test_path_expr_, span: ast::dummy_sp()};
- let test_call_expr_: ast::expr_ = ast::expr_call(@test_path_expr, ~[]);
+ let test_call_expr_: ast::expr_ = ast::expr_call(@test_path_expr, []);
let test_call_expr: ast::expr =
- {id: cx.next_node_id(),
- node: test_call_expr_,
- span: ast::dummy_sp()};
+ {id: cx.next_node_id(), node: test_call_expr_, span: ast::dummy_sp()};
// Call std::test::test_main
let test_main_path: ast::path =
nospan({global: false,
- idents: ~["std", "test", "test_main"],
- types: ~[]});
+ idents: ["std", "test", "test_main"],
+ types: []});
let test_main_path_expr_: ast::expr_ = ast::expr_path(test_main_path);
let test_main_call_expr_: ast::expr_ =
ast::expr_call(@test_main_path_expr,
- ~[@args_path_expr, @test_call_expr]);
+ [@args_path_expr, @test_call_expr]);
let test_main_call_expr: ast::expr =
{id: cx.next_node_id(),
const LLVMStackProtectAttribute: uint = 16384u;
const LLVMStackProtectReqAttribute: uint = 32768u;
const LLVMAlignmentAttribute: uint = 2031616u;
- // 31 << 16
+// 31 << 16
const LLVMNoCaptureAttribute: uint = 2097152u;
const LLVMNoRedZoneAttribute: uint = 4194304u;
const LLVMNoImplicitFloatAttribute: uint = 8388608u;
const LLVMNakedAttribute: uint = 16777216u;
const LLVMInlineHintAttribute: uint = 33554432u;
const LLVMStackAttribute: uint = 469762048u;
- // 7 << 26
+// 7 << 26
const LLVMUWTableAttribute: uint = 1073741824u;
- // 1 << 30
+// 1 << 30
- // Consts for the LLVM IntPredicate type, pre-cast to uint.
- // FIXME: as above.
+// Consts for the LLVM IntPredicate type, pre-cast to uint.
+// FIXME: as above.
const LLVMIntEQ: uint = 32u;
/* Operations on constants of any type */
fn LLVMConstNull(Ty: TypeRef) -> ValueRef;
- /* all zeroes */
+ /* all zeroes */
fn LLVMConstAllOnes(Ty: TypeRef) -> ValueRef;
- /* only for int/vector */
+ /* only for int/vector */
fn LLVMGetUndef(Ty: TypeRef) -> ValueRef;
fn LLVMIsConstant(Val: ValueRef) -> Bool;
fn LLVMIsNull(Val: ValueRef) -> Bool;
Value: Bool);
fn LLVMPassManagerBuilderSetDisableUnrollLoops(PMB: PassManagerBuilderRef,
Value: Bool);
- fn LLVMPassManagerBuilderSetDisableSimplifyLibCalls(PMB:
- PassManagerBuilderRef,
- Value: Bool);
- fn LLVMPassManagerBuilderUseInlinerWithThreshold(PMB:
- PassManagerBuilderRef,
- threshold: uint);
- fn LLVMPassManagerBuilderPopulateModulePassManager(PMB:
- PassManagerBuilderRef,
- PM: PassManagerRef);
-
- fn LLVMPassManagerBuilderPopulateFunctionPassManager(PMB:
- PassManagerBuilderRef,
- PM: PassManagerRef);
+ fn LLVMPassManagerBuilderSetDisableSimplifyLibCalls(
+ PMB: PassManagerBuilderRef,
+ Value: Bool);
+ fn LLVMPassManagerBuilderUseInlinerWithThreshold(
+ PMB: PassManagerBuilderRef,
+ threshold: uint);
+ fn LLVMPassManagerBuilderPopulateModulePassManager(
+ PMB: PassManagerBuilderRef,
+ PM: PassManagerRef);
+
+ fn LLVMPassManagerBuilderPopulateFunctionPassManager(
+ PMB: PassManagerBuilderRef,
+ PM: PassManagerRef);
/** Destroys a memory buffer. */
fn LLVMDisposeMemoryBuffer(MemBuf: MemoryBufferRef);
* it's attached to.
*/
-resource BuilderRef_res(B: BuilderRef) {
- llvm::LLVMDisposeBuilder(B);
-}
+resource BuilderRef_res(B: BuilderRef) { llvm::LLVMDisposeBuilder(B); }
+
+obj builder(B: BuilderRef,
+ terminated: @mutable bool,
-obj builder(B: BuilderRef, terminated: @mutable bool,
// Stored twice so that we don't have to constantly deref
res: @BuilderRef_res) {
/* Terminators */
fn RetVoid() -> ValueRef {
- assert (!*terminated);
+ assert (!*terminated);;
*terminated = true;
ret llvm::LLVMBuildRetVoid(B);
}
fn Ret(V: ValueRef) -> ValueRef {
- assert (!*terminated);
+ assert (!*terminated);;
*terminated = true;
ret llvm::LLVMBuildRet(B, V);
}
fn AggregateRet(RetVals: &[ValueRef]) -> ValueRef {
- assert (!*terminated);
+ assert (!*terminated);;
*terminated = true;
ret llvm::LLVMBuildAggregateRet(B, vec::to_ptr(RetVals),
vec::len(RetVals));
}
fn Br(Dest: BasicBlockRef) -> ValueRef {
- assert (!*terminated);
+ assert (!*terminated);;
*terminated = true;
ret llvm::LLVMBuildBr(B, Dest);
}
fn CondBr(If: ValueRef, Then: BasicBlockRef, Else: BasicBlockRef) ->
ValueRef {
- assert (!*terminated);
+ assert (!*terminated);;
*terminated = true;
ret llvm::LLVMBuildCondBr(B, If, Then, Else);
}
fn Switch(V: ValueRef, Else: BasicBlockRef, NumCases: uint) -> ValueRef {
- assert (!*terminated);
+ assert (!*terminated);;
*terminated = true;
ret llvm::LLVMBuildSwitch(B, V, Else, NumCases);
}
fn IndirectBr(Addr: ValueRef, NumDests: uint) -> ValueRef {
- assert (!*terminated);
+ assert (!*terminated);;
*terminated = true;
ret llvm::LLVMBuildIndirectBr(B, Addr, NumDests);
}
fn Invoke(Fn: ValueRef, Args: &[ValueRef], Then: BasicBlockRef,
Catch: BasicBlockRef) -> ValueRef {
- assert (!*terminated);
+ assert (!*terminated);;
*terminated = true;
ret llvm::LLVMBuildInvoke(B, Fn, vec::to_ptr(Args), vec::len(Args),
Then, Catch, str::buf(""));
}
fn Unreachable() -> ValueRef {
- assert (!*terminated);
+ assert (!*terminated);;
*terminated = true;
ret llvm::LLVMBuildUnreachable(B);
}
let T: ValueRef =
llvm::LLVMGetNamedFunction(M, str::buf("llvm.trap"));
assert (T as int != 0);
- let Args: [ValueRef] = ~[];
+ let Args: [ValueRef] = [];
ret llvm::LLVMBuildCall(B, T, vec::to_ptr(Args), vec::len(Args),
str::buf(""));
}
- fn is_terminated() -> bool {
- ret *terminated;
- }
+ fn is_terminated() -> bool { ret *terminated; }
}
fn new_builder(llbb: BasicBlockRef) -> builder {
}
fn type_to_str(names: type_names, ty: TypeRef) -> str {
- ret type_to_str_inner(names, ~[], ty);
+ ret type_to_str_inner(names, [], ty);
}
fn type_to_str_inner(names: type_names, outer0: &[TypeRef], ty: TypeRef) ->
if names.type_has_name(ty) { ret names.get_name(ty); }
- let outer = outer0 + ~[ty];
+ let outer = outer0 + [ty];
let kind: int = llvm::LLVMGetTypeKind(ty);
alt kind {
+
// FIXME: more enum-as-int constants determined from Core::h;
// horrible, horrible. Complete as needed.
6 { ret "Label"; }
+
7 {
ret "i" + std::int::str(llvm::LLVMGetIntTypeWidth(ty) as int);
}
+
8 {
let s = "fn(";
let out_ty: TypeRef = llvm::LLVMGetReturnType(ty);
}
+
9 {
let s: str = "{";
let n_elts: uint = llvm::LLVMCountStructElementTypes(ty);
}
+
10 {
let el_ty = llvm::LLVMGetElementType(ty);
ret "[" + type_to_str_inner(names, outer, el_ty) + "]";
}
+
11 {
let i: uint = 0u;
for tout: TypeRef in outer0 {
}
+
12 {
ret "Opaque";
}
13 { ret "Vector"; }
14 { ret "Metadata"; }
- _ { log_err #fmt("unknown TypeKind %d", kind as int); fail; }
+ _ { log_err #fmt["unknown TypeKind %d", kind as int]; fail; }
}
}
}
let cstore = e.sess.get_cstore();
if !cstore::add_used_library(cstore, m.native_name) { ret; }
- for a: ast::attribute in
+ for a: ast::attribute in
attr::find_attrs_by_name(i.attrs, "link_args") {
alt attr::get_meta_item_value_str(attr::attr_meta(a)) {
some(linkarg) { cstore::add_used_link_args(cstore, linkarg); }
let attrs = decoder::get_crate_attributes(crate_data);
let linkage_metas = attr::find_linkage_metas(attrs);
- log #fmt("matching %u metadata requirements against %u items",
- vec::len(metas), vec::len(linkage_metas));
+ log #fmt["matching %u metadata requirements against %u items",
+ vec::len(metas), vec::len(linkage_metas)];
for needed: @ast::meta_item in metas {
if !attr::contains(linkage_metas, needed) {
- log #fmt("missing %s", pprust::meta_item_to_str(*needed));
+ log #fmt["missing %s", pprust::meta_item_to_str(*needed)];
ret false;
}
}
}
fn find_library_crate(sess: &session::session, ident: &ast::ident,
- metas: &[@ast::meta_item],
- library_search_paths: &[str]) ->
- option::t<{ident: str, data: @[u8]}> {
+ metas: &[@ast::meta_item], library_search_paths: &[str])
+ -> option::t<{ident: str, data: @[u8]}> {
attr::require_unique_names(sess, metas);
// FIXME: Probably want a warning here since the user
// is using the wrong type of meta item
- let crate_name = {
- let name_items = attr::find_meta_items_by_name(metas, "name");
- alt vec::last(name_items) {
- some(i) {
- alt attr::get_meta_item_value_str(i) {
- some(n) { n }
- _ { ident }
+ let crate_name =
+ {
+ let name_items = attr::find_meta_items_by_name(metas, "name");
+ alt vec::last(name_items) {
+ some(i) {
+ alt attr::get_meta_item_value_str(i) {
+ some(n) { n }
+ _ { ident }
+ }
+ }
+ none. { ident }
}
- }
- none. { ident }
- }
- };
+ };
let nn = default_native_lib_naming(sess, sess.get_opts().static);
let x =
// manually filtering fs::list_dir here.
for library_search_path: str in library_search_paths {
- log #fmt("searching %s", library_search_path);
+ log #fmt["searching %s", library_search_path];
for path: str in fs::list_dir(library_search_path) {
- log #fmt("searching %s", path);
+ log #fmt["searching %s", path];
let f: str = fs::basename(path);
if !(str::starts_with(f, prefix) && str::ends_with(f, nn.suffix))
{
- log #fmt("skipping %s, doesn't look like %s*%s", path, prefix,
- nn.suffix);
+ log #fmt["skipping %s, doesn't look like %s*%s", path, prefix,
+ nn.suffix];
cont;
}
alt get_metadata_section(path) {
option::some(cvec) {
if !metadata_matches(cvec, metas) {
- log #fmt("skipping %s, metadata doesn't match", path);
+ log #fmt["skipping %s, metadata doesn't match", path];
cont;
}
- log #fmt("found %s with matching metadata", path);
+ log #fmt["found %s with matching metadata", path];
ret some({ident: path, data: cvec});
}
_ { }
}
fn load_library_crate(sess: &session::session, span: span, ident: &ast::ident,
- metas: &[@ast::meta_item],
- library_search_paths: &[str]) ->
- {ident: str, data: @[u8]} {
+ metas: &[@ast::meta_item], library_search_paths: &[str])
+ -> {ident: str, data: @[u8]} {
alt find_library_crate(sess, ident, metas, library_search_paths) {
some(t) { ret t; }
none. {
- sess.span_fatal(span, #fmt("can't find crate for '%s'", ident));
+ sess.span_fatal(span, #fmt["can't find crate for '%s'", ident]);
}
}
}
for dep: decoder::crate_dep in decoder::get_crate_deps(cdata) {
let extrn_cnum = dep.cnum;
let cname = dep.ident;
- log #fmt("resolving dep %s", cname);
+ log #fmt["resolving dep %s", cname];
if e.crate_cache.contains_key(cname) {
log "already have it";
// We've already seen this crate
// This is a new one so we've got to load it
// FIXME: Need better error reporting than just a bogus span
let fake_span = ast::dummy_sp();
- let local_cnum = resolve_crate(e, cname, ~[], fake_span);
+ let local_cnum = resolve_crate(e, cname, [], fake_span);
cnum_map.insert(extrn_cnum, local_cnum);
}
}
let crate_map = map::new_int_hash::<ast::crate_num>();
ret private(@{metas: meta_cache,
use_crate_map: crate_map,
- mutable used_crate_files: ~[],
- mutable used_libraries: ~[],
- mutable used_link_args: ~[]});
+ mutable used_crate_files: [],
+ mutable used_libraries: [],
+ mutable used_link_args: []});
}
fn get_crate_data(cstore: &cstore, cnum: ast::crate_num) -> crate_metadata {
iter iter_crate_data(cstore: &cstore) ->
@{key: ast::crate_num, val: crate_metadata} {
- for each kv: @{key: ast::crate_num, val: crate_metadata} in
+ for each kv: @{key: ast::crate_num, val: crate_metadata} in
p(cstore).metas.items() {
put kv;
}
fn add_used_crate_file(cstore: &cstore, lib: &str) {
if !vec::member(lib, p(cstore).used_crate_files) {
- p(cstore).used_crate_files += ~[lib];
+ p(cstore).used_crate_files += [lib];
}
}
if vec::member(lib, p(cstore).used_libraries) { ret false; }
- p(cstore).used_libraries += ~[lib];
+ p(cstore).used_libraries += [lib];
ret true;
}
// def_id for an item defined in another crate, somebody needs to figure out
// what crate that's in and give us a def_id that makes sense for the current
// build.
-type external_resolver = fn(&ast::def_id) -> ast::def_id ;
+type external_resolver = fn(&ast::def_id) -> ast::def_id;
-fn lookup_hash(d: &ebml::doc, eq_fn: fn(&[u8]) -> bool , hash: uint) ->
+fn lookup_hash(d: &ebml::doc, eq_fn: fn(&[u8]) -> bool, hash: uint) ->
[ebml::doc] {
let index = ebml::get_doc(d, tag_index);
let table = ebml::get_doc(index, tag_index_table);
let bucket = ebml::doc_at(d.data, pos);
// Awkward logic because we can't ret from foreach yet
- let result: [ebml::doc] = ~[];
+ let result: [ebml::doc] = [];
let belt = tag_index_buckets_bucket_elt;
for each elt: ebml::doc in ebml::tagged_docs(bucket, belt) {
let pos = ebml::be_uint_from_bytes(elt.data, elt.start, 4u);
if eq_fn(vec::slice::<u8>(*elt.data, elt.start + 4u, elt.end)) {
- result += ~[ebml::doc_at(d.data, pos)];
+ result += [ebml::doc_at(d.data, pos)];
}
}
ret result;
}
-fn maybe_find_item(item_id: int, items: &ebml::doc) ->
- option::t<ebml::doc> {
+fn maybe_find_item(item_id: int, items: &ebml::doc) -> option::t<ebml::doc> {
fn eq_item(bytes: &[u8], item_id: int) -> bool {
ret ebml::be_uint_from_bytes(@bytes, 0u, 4u) as int == item_id;
}
let found = lookup_hash(items, eqer, hash_node_id(item_id));
if vec::len(found) == 0u {
ret option::none::<ebml::doc>;
- } else { ret option::some::<ebml::doc>(found.(0)); }
+ } else { ret option::some::<ebml::doc>(found[0]); }
}
fn find_item(item_id: int, items: &ebml::doc) -> ebml::doc {
}
fn item_ty_param_kinds(item: &ebml::doc) -> [ast::kind] {
- let ks: [ast::kind] = ~[];
+ let ks: [ast::kind] = [];
let tp = tag_items_data_item_ty_param_kinds;
for each p: ebml::doc in ebml::tagged_docs(item, tp) {
- let dat : [u8] = ebml::doc_data(p);
+ let dat: [u8] = ebml::doc_data(p);
let vi = ebml::vint_at(dat, 0u);
let i = 0u;
while i < vi.val {
- let k = alt dat.(vi.next + i) as char {
- 'u' { ast::kind_unique }
- 's' { ast::kind_shared }
- 'p' { ast::kind_pinned }
- };
- ks += ~[k];
+ let k =
+ alt dat[vi.next + i] as char {
+ 'u' { ast::kind_unique }
+ 's' { ast::kind_shared }
+ 'p' { ast::kind_pinned }
+ };
+ ks += [k];
i += 1u;
}
}
fn tag_variant_ids(item: &ebml::doc, this_cnum: ast::crate_num) ->
[ast::def_id] {
- let ids: [ast::def_id] = ~[];
+ let ids: [ast::def_id] = [];
let v = tag_items_data_item_variant;
for each p: ebml::doc in ebml::tagged_docs(item, v) {
let ext = parse_def_id(ebml::doc_data(p));
- ids += ~[{crate: this_cnum, node: ext.node}];
+ ids += [{crate: this_cnum, node: ext.node}];
}
ret ids;
}
let md = ebml::new_doc(data);
let paths = ebml::get_doc(md, tag_paths);
let eqer = bind eq_item(_, s);
- let result: [ast::def_id] = ~[];
+ let result: [ast::def_id] = [];
for doc: ebml::doc in lookup_hash(paths, eqer, hash_path(s)) {
let did_doc = ebml::get_doc(doc, tag_def_id);
- result += ~[parse_def_id(ebml::doc_data(did_doc))];
+ result += [parse_def_id(ebml::doc_data(did_doc))];
}
ret result;
}
let node_id = def.node;
let item = lookup_item(node_id, data);
let t = item_type(item, this_cnum, tcx, extres);
- let tp_kinds : [ast::kind];
+ let tp_kinds: [ast::kind];
let fam_ch = item_family(item);
let has_ty_params = family_has_type_params(fam_ch);
if has_ty_params {
tp_kinds = item_ty_param_kinds(item);
- } else { tp_kinds = ~[]; }
+ } else { tp_kinds = []; }
ret {kinds: tp_kinds, ty: t};
}
cstore::get_crate_data(tcx.sess.get_cstore(), external_crate_id).data;
let items = ebml::get_doc(ebml::new_doc(data), tag_items);
let item = find_item(def.node, items);
- let infos: [ty::variant_info] = ~[];
+ let infos: [ty::variant_info] = [];
let variant_ids = tag_variant_ids(item, external_crate_id);
for did: ast::def_id in variant_ids {
let item = find_item(did.node, items);
let ctor_ty = item_type(item, external_crate_id, tcx, extres);
- let arg_tys: [ty::t] = ~[];
+ let arg_tys: [ty::t] = [];
alt ty::struct(tcx, ctor_ty) {
ty::ty_fn(_, args, _, _, _) {
- for a: ty::arg in args { arg_tys += ~[a.ty]; }
+ for a: ty::arg in args { arg_tys += [a.ty]; }
}
_ {
// Nullary tag variant.
}
}
- infos += ~[{args: arg_tys, ctor_ty: ctor_ty, id: did}];
+ infos += [{args: arg_tys, ctor_ty: ctor_ty, id: did}];
}
ret infos;
}
}
fn get_meta_items(md: &ebml::doc) -> [@ast::meta_item] {
- let items: [@ast::meta_item] = ~[];
- for each meta_item_doc: ebml::doc in
+ let items: [@ast::meta_item] = [];
+ for each meta_item_doc: ebml::doc in
ebml::tagged_docs(md, tag_meta_item_word) {
let nd = ebml::get_doc(meta_item_doc, tag_meta_item_name);
let n = str::unsafe_from_bytes(ebml::doc_data(nd));
- items += ~[attr::mk_word_item(n)];
+ items += [attr::mk_word_item(n)];
}
- for each meta_item_doc: ebml::doc in
+ for each meta_item_doc: ebml::doc in
ebml::tagged_docs(md, tag_meta_item_name_value) {
let nd = ebml::get_doc(meta_item_doc, tag_meta_item_name);
let vd = ebml::get_doc(meta_item_doc, tag_meta_item_value);
let v = str::unsafe_from_bytes(ebml::doc_data(vd));
// FIXME (#611): Should be able to decode meta_name_value variants,
// but currently they can't be encoded
- items += ~[attr::mk_name_value_item_str(n, v)];
+ items += [attr::mk_name_value_item_str(n, v)];
}
- for each meta_item_doc: ebml::doc in
+ for each meta_item_doc: ebml::doc in
ebml::tagged_docs(md, tag_meta_item_list) {
let nd = ebml::get_doc(meta_item_doc, tag_meta_item_name);
let n = str::unsafe_from_bytes(ebml::doc_data(nd));
let subitems = get_meta_items(meta_item_doc);
- items += ~[attr::mk_list_item(n, subitems)];
+ items += [attr::mk_list_item(n, subitems)];
}
ret items;
}
fn get_attributes(md: &ebml::doc) -> [ast::attribute] {
- let attrs: [ast::attribute] = ~[];
+ let attrs: [ast::attribute] = [];
alt ebml::maybe_get_doc(md, tag_attributes) {
option::some(attrs_d) {
- for each attr_doc: ebml::doc in
+ for each attr_doc: ebml::doc in
ebml::tagged_docs(attrs_d, tag_attribute) {
let meta_items = get_meta_items(attr_doc);
// Currently it's only possible to have a single meta item on
// an attribute
assert (vec::len(meta_items) == 1u);
- let meta_item = meta_items.(0);
+ let meta_item = meta_items[0];
attrs +=
- ~[{node: {style: ast::attr_outer, value: *meta_item},
- span: ast::dummy_sp()}];
+ [{node: {style: ast::attr_outer, value: *meta_item},
+ span: ast::dummy_sp()}];
}
}
option::none. { }
fn list_meta_items(meta_items: &ebml::doc, out: io::writer) {
for mi: @ast::meta_item in get_meta_items(meta_items) {
- out.write_str(#fmt("%s\n", pprust::meta_item_to_str(*mi)));
+ out.write_str(#fmt["%s\n", pprust::meta_item_to_str(*mi)]);
}
}
out.write_str("=Crate Attributes=\n");
for attr: ast::attribute in get_attributes(md) {
- out.write_str(#fmt("%s\n", pprust::attribute_to_str(attr)));
+ out.write_str(#fmt["%s\n", pprust::attribute_to_str(attr)]);
}
out.write_str("\n\n");
type crate_dep = {cnum: ast::crate_num, ident: str};
fn get_crate_deps(data: @[u8]) -> [crate_dep] {
- let deps: [crate_dep] = ~[];
+ let deps: [crate_dep] = [];
let cratedoc = ebml::new_doc(data);
let depsdoc = ebml::get_doc(cratedoc, tag_crate_deps);
let crate_num = 1;
- for each depdoc: ebml::doc in
- ebml::tagged_docs(depsdoc, tag_crate_dep) {
+ for each depdoc: ebml::doc in ebml::tagged_docs(depsdoc, tag_crate_dep) {
let depname = str::unsafe_from_bytes(ebml::doc_data(depdoc));
- deps += ~[{cnum: crate_num, ident: depname}];
+ deps += [{cnum: crate_num, ident: depname}];
crate_num += 1;
}
ret deps;
out.write_str("=External Dependencies=\n");
for dep: crate_dep in get_crate_deps(data) {
- out.write_str(#fmt("%d %s\n", dep.cnum, dep.ident));
+ out.write_str(#fmt["%d %s\n", dep.cnum, dep.ident]);
}
out.write_str("\n");
let items = ebml::get_doc(md, tag_items);
let index = ebml::get_doc(paths, tag_index);
let bs = ebml::get_doc(index, tag_index_buckets);
- for each bucket: ebml::doc in
+ for each bucket: ebml::doc in
ebml::tagged_docs(bs, tag_index_buckets_bucket) {
let et = tag_index_buckets_bucket_elt;
for each elt: ebml::doc in ebml::tagged_docs(bucket, et) {
let def = ebml::doc_at(bytes, data.pos);
let did_doc = ebml::get_doc(def, tag_def_id);
let did = parse_def_id(ebml::doc_data(did_doc));
- out.write_str(#fmt("%s (%s)\n", data.path,
- describe_def(items, did)));
+ out.write_str(#fmt["%s (%s)\n", data.path,
+ describe_def(items, did)]);
}
}
out.write_str("\n");
fn add_to_index(ebml_w: &ebml::writer, path: &[str],
index: &mutable [entry<str>], name: &str) {
- let full_path = path + ~[name];
+ let full_path = path + [name];
index +=
- ~[{val: str::connect(full_path, "::"),
- pos: ebml_w.writer.tell()}];
+ [{val: str::connect(full_path, "::"), pos: ebml_w.writer.tell()}];
}
-fn encode_native_module_item_paths(ebml_w: &ebml::writer,
- nmod: &native_mod, path: &[str],
+fn encode_native_module_item_paths(ebml_w: &ebml::writer, nmod: &native_mod,
+ path: &[str],
index: &mutable [entry<str>]) {
for nitem: @native_item in nmod.items {
add_to_index(ebml_w, path, index, nitem.ident);
ebml::start_tag(ebml_w, tag_paths_data_mod);
encode_name(ebml_w, it.ident);
encode_def_id(ebml_w, local_def(it.id));
- encode_module_item_paths(ebml_w, _mod, path + ~[it.ident], index);
+ encode_module_item_paths(ebml_w, _mod, path + [it.ident], index);
ebml::end_tag(ebml_w);
}
item_native_mod(nmod) {
ebml::start_tag(ebml_w, tag_paths_data_mod);
encode_name(ebml_w, it.ident);
encode_def_id(ebml_w, local_def(it.id));
- encode_native_module_item_paths(ebml_w, nmod, path + ~[it.ident],
+ encode_native_module_item_paths(ebml_w, nmod, path + [it.ident],
index);
ebml::end_tag(ebml_w);
}
}
}
-fn encode_item_paths(ebml_w: &ebml::writer, crate: &@crate) ->
- [entry<str>] {
- let index: [entry<str>] = ~[];
- let path: [str] = ~[];
+fn encode_item_paths(ebml_w: &ebml::writer, crate: &@crate) -> [entry<str>] {
+ let index: [entry<str>] = [];
+ let path: [str] = [];
ebml::start_tag(ebml_w, tag_paths);
encode_module_item_paths(ebml_w, crate.node.module, path, index);
ebml::end_tag(ebml_w);
// Item info table encoding
fn encode_family(ebml_w: &ebml::writer, c: u8) {
ebml::start_tag(ebml_w, tag_items_data_item_family);
- ebml_w.writer.write(~[c]);
+ ebml_w.writer.write([c]);
ebml::end_tag(ebml_w);
}
fn encode_inlineness(ebml_w: &ebml::writer, c: u8) {
ebml::start_tag(ebml_w, tag_items_data_item_inlineness);
- ebml_w.writer.write(~[c]);
+ ebml_w.writer.write([c]);
ebml::end_tag(ebml_w);
}
-fn def_to_str(did: &def_id) -> str { ret #fmt("%d:%d", did.crate, did.node); }
+fn def_to_str(did: &def_id) -> str { ret #fmt["%d:%d", did.crate, did.node]; }
fn encode_type_param_kinds(ebml_w: &ebml::writer, tps: &[ty_param]) {
ebml::start_tag(ebml_w, tag_items_data_item_ty_param_kinds);
ebml::write_vint(ebml_w.writer, vec::len::<ty_param>(tps));
for tp: ty_param in tps {
- let c = alt tp.kind {
- kind_unique. { 'u' }
- kind_shared. { 's' }
- kind_pinned. { 'p' }
- };
- ebml_w.writer.write(~[c as u8]);
+ let c =
+ alt tp.kind {
+ kind_unique. { 'u' }
+ kind_shared. { 's' }
+ kind_pinned. { 'p' }
+ };
+ ebml_w.writer.write([c as u8]);
}
ebml::end_tag(ebml_w);
}
index: &mutable [entry<int>],
ty_params: &[ty_param]) {
for variant: variant in variants {
- index += ~[{val: variant.node.id, pos: ebml_w.writer.tell()}];
+ index += [{val: variant.node.id, pos: ebml_w.writer.tell()}];
ebml::start_tag(ebml_w, tag_items_data_item);
encode_def_id(ebml_w, local_def(variant.node.id));
encode_family(ebml_w, 'v' as u8);
}
}
-fn encode_info_for_item(ecx: @encode_ctxt, ebml_w: &ebml::writer,
- item: @item, index: &mutable [entry<int>]) {
+fn encode_info_for_item(ecx: @encode_ctxt, ebml_w: &ebml::writer, item: @item,
+ index: &mutable [entry<int>]) {
alt item.node {
item_const(_, _) {
ebml::start_tag(ebml_w, tag_items_data_item);
ebml::start_tag(ebml_w, tag_items_data_item);
encode_def_id(ebml_w, local_def(item.id));
encode_family(ebml_w,
- alt fd.decl.purity { pure_fn. { 'p' } impure_fn. { 'f' } }
- as u8);
+ alt fd.decl.purity {
+ pure_fn. { 'p' }
+ impure_fn. { 'f' }
+ } as u8);
encode_inlineness(ebml_w,
alt fd.decl.il {
il_normal. { 'n' }
encode_symbol(ecx, ebml_w, item.id);
ebml::end_tag(ebml_w);
- index += ~[{val: ctor_id, pos: ebml_w.writer.tell()}];
+ index += [{val: ctor_id, pos: ebml_w.writer.tell()}];
ebml::start_tag(ebml_w, tag_items_data_item);
encode_def_id(ebml_w, local_def(ctor_id));
encode_family(ebml_w, 'f' as u8);
encode_type(ecx, ebml_w, ty::ty_fn_ret(ecx.ccx.tcx, fn_ty));
ebml::end_tag(ebml_w);
- index += ~[{val: ctor_id, pos: ebml_w.writer.tell()}];
+ index += [{val: ctor_id, pos: ebml_w.writer.tell()}];
ebml::start_tag(ebml_w, tag_items_data_item);
encode_def_id(ebml_w, local_def(ctor_id));
encode_family(ebml_w, 'f' as u8);
fn encode_info_for_items(ecx: &@encode_ctxt, ebml_w: &ebml::writer) ->
[entry<int>] {
- let index: [entry<int>] = ~[];
+ let index: [entry<int>] = [];
ebml::start_tag(ebml_w, tag_items_data);
- for each kvp: @{key: node_id, val: middle::ast_map::ast_node} in
+ for each kvp: @{key: node_id, val: middle::ast_map::ast_node} in
ecx.ccx.ast_map.items() {
alt kvp.val {
middle::ast_map::node_item(i) {
- index += ~[{val: kvp.key, pos: ebml_w.writer.tell()}];
+ index += [{val: kvp.key, pos: ebml_w.writer.tell()}];
encode_info_for_item(ecx, ebml_w, i, index);
}
middle::ast_map::node_native_item(i) {
- index += ~[{val: kvp.key, pos: ebml_w.writer.tell()}];
+ index += [{val: kvp.key, pos: ebml_w.writer.tell()}];
encode_info_for_native_item(ecx, ebml_w, i);
}
_ { }
// Path and definition ID indexing
-fn create_index<T>(index: &[entry<T>], hash_fn: fn(&T) -> uint ) ->
+fn create_index<T>(index: &[entry<T>], hash_fn: fn(&T) -> uint) ->
[@[entry<T>]] {
- let buckets: [@mutable [entry<T>]] = ~[];
- for each i: uint in uint::range(0u, 256u) { buckets += ~[@mutable ~[]]; }
+ let buckets: [@mutable [entry<T>]] = [];
+ for each i: uint in uint::range(0u, 256u) { buckets += [@mutable []]; }
for elt: entry<T> in index {
let h = hash_fn(elt.val);
- *buckets.(h % 256u) += ~[elt];
+ *buckets[h % 256u] += [elt];
}
- let buckets_frozen = ~[];
+ let buckets_frozen = [];
for bucket: @mutable [entry<T>] in buckets {
- buckets_frozen += ~[@*bucket];
+ buckets_frozen += [@*bucket];
}
ret buckets_frozen;
}
fn encode_index<T>(ebml_w: &ebml::writer, buckets: &[@[entry<T>]],
- write_fn: fn(&io::writer, &T) ) {
+ write_fn: fn(&io::writer, &T)) {
let writer = io::new_writer_(ebml_w.writer);
ebml::start_tag(ebml_w, tag_index);
- let bucket_locs: [uint] = ~[];
+ let bucket_locs: [uint] = [];
ebml::start_tag(ebml_w, tag_index_buckets);
for bucket: @[entry<T>] in buckets {
- bucket_locs += ~[ebml_w.writer.tell()];
+ bucket_locs += [ebml_w.writer.tell()];
ebml::start_tag(ebml_w, tag_index_buckets_bucket);
for elt: entry<T> in *bucket {
ebml::start_tag(ebml_w, tag_index_buckets_bucket_elt);
attr::remove_meta_items_by_name(tmp, "vers")
};
- let meta_items = ~[name_item, vers_item] + other_items;
+ let meta_items = [name_item, vers_item] + other_items;
let link_item = attr::mk_list_item("link", meta_items);
ret attr::mk_attr(link_item);
}
- let attrs: [attribute] = ~[];
+ let attrs: [attribute] = [];
let found_link_attr = false;
for attr: attribute in crate.node.attrs {
attrs +=
if attr::get_attr_name(attr) != "link" {
- ~[attr]
+ [attr]
} else {
alt attr.node.value.node {
meta_list(n, l) {
found_link_attr = true;
- ~[synthesize_link_attr(ecx, l)]
+ [synthesize_link_attr(ecx, l)]
}
- _ { ~[attr] }
+ _ { [attr] }
}
}
}
- if !found_link_attr { attrs += ~[synthesize_link_attr(ecx, ~[])]; }
+ if !found_link_attr { attrs += [synthesize_link_attr(ecx, [])]; }
ret attrs;
}
type numname = {crate: crate_num, ident: str};
// Pull the cnums and names out of cstore
- let pairs: [mutable numname] = ~[mutable];
+ let pairs: [mutable numname] = [mutable];
for each hashkv: hashkv in cstore::iter_crate_data(cstore) {
- pairs += ~[mutable {crate: hashkv.key, ident: hashkv.val.name}];
+ pairs += [mutable {crate: hashkv.key, ident: hashkv.val.name}];
}
// Sort by cnum
// Pad this, since something (LLVM, presumably) is cutting off the
// remaining % 4 bytes.
- buf_w.write(~[0u8, 0u8, 0u8, 0u8]);
+ buf_w.write([0u8, 0u8, 0u8, 0u8]);
ret string_w.get_str();
}
// data buffer. Whatever format you choose should not contain pipe characters.
// Callback to translate defs to strs or back:
-type str_def = fn(str) -> ast::def_id ;
+type str_def = fn(str) -> ast::def_id;
type pstate =
{data: @[u8], crate: int, mutable pos: uint, len: uint, tcx: ty::ctxt};
tag ty_or_bang { a_ty(ty::t); a_bang; }
-fn peek(st: @pstate) -> u8 { ret st.data.(st.pos); }
+fn peek(st: @pstate) -> u8 { ret st.data[st.pos]; }
fn next(st: @pstate) -> u8 {
- let ch = st.data.(st.pos);
+ let ch = st.data[st.pos];
st.pos = st.pos + 1u;
ret ch;
}
ret parse_ident_(st, sd, bind is_last(last, _));
}
-fn parse_ident_(st: @pstate, _sd: str_def, is_last: fn(char) -> bool ) ->
+fn parse_ident_(st: @pstate, _sd: str_def, is_last: fn(char) -> bool) ->
ast::ident {
let rslt = "";
while !is_last(peek(st) as char) {
}
fn parse_constrs(st: @pstate, sd: str_def) -> [@ty::constr] {
- let rslt: [@ty::constr] = ~[];
+ let rslt: [@ty::constr] = [];
alt peek(st) as char {
':' {
do {
next(st);
let one: @ty::constr =
parse_constr::<uint>(st, sd, parse_constr_arg);
- rslt += ~[one];
+ rslt += [one];
} while peek(st) as char == ';'
}
_ { }
// FIXME less copy-and-paste
fn parse_ty_constrs(st: @pstate, sd: str_def) -> [@ty::type_constr] {
- let rslt: [@ty::type_constr] = ~[];
+ let rslt: [@ty::type_constr] = [];
alt peek(st) as char {
':' {
do {
next(st);
let one: @ty::type_constr =
parse_constr::<path>(st, sd, parse_ty_constr_arg);
- rslt += ~[one];
+ rslt += [one];
} while peek(st) as char == ';'
}
_ { }
}
fn parse_path(st: @pstate, sd: str_def) -> ast::path {
- let idents: [ast::ident] = ~[];
+ let idents: [ast::ident] = [];
fn is_last(c: char) -> bool { ret c == '(' || c == ':'; }
- idents += ~[parse_ident_(st, sd, is_last)];
+ idents += [parse_ident_(st, sd, is_last)];
while true {
alt peek(st) as char {
':' { next(st); next(st); }
c {
if c == '(' {
ret respan(ast::dummy_sp(),
- {global: false, idents: idents, types: ~[]});
- } else { idents += ~[parse_ident_(st, sd, is_last)]; }
+ {global: false, idents: idents, types: []});
+ } else { idents += [parse_ident_(st, sd, is_last)]; }
}
}
}
fail "parse_path: ill-formed path";
}
-type arg_parser<T> = fn(@pstate, str_def) -> ast::constr_arg_general_<T> ;
+type arg_parser<T> = fn(@pstate, str_def) -> ast::constr_arg_general_<T>;
fn parse_constr_arg(st: @pstate, _sd: str_def) -> ast::fn_constr_arg {
alt peek(st) as char {
fn parse_constr<@T>(st: @pstate, sd: str_def, pser: arg_parser<T>) ->
@ty::constr_general<T> {
let sp = ast::dummy_sp(); // FIXME: use a real span
- let args: [@sp_constr_arg<T>] = ~[];
+ let args: [@sp_constr_arg<T>] = [];
let pth: path = parse_path(st, sd);
let ignore: char = next(st) as char;
assert (ignore as char == '(');
do {
an_arg = pser(st, sd);
// FIXME use a real span
- args += ~[@respan(sp, an_arg)];
+ args += [@respan(sp, an_arg)];
ignore = next(st) as char;
} while ignore == ';'
assert (ignore == ')');
't' {
assert (next(st) as char == '[');
let def = parse_def(st, sd);
- let params: [ty::t] = ~[];
- while peek(st) as char != ']' { params += ~[parse_ty(st, sd)]; }
+ let params: [ty::t] = [];
+ while peek(st) as char != ']' { params += [parse_ty(st, sd)]; }
st.pos = st.pos + 1u;
ret ty::mk_tag(st.tcx, def, params);
}
'p' {
- let k = alt next(st) as char {
- 'u' { kind_unique }
- 's' { kind_shared }
- 'p' { kind_pinned }
- c {
- log_err "unexpected char in encoded type param: ";
- log_err c; fail
- }
- };
+ let k =
+ alt next(st) as char {
+ 'u' { kind_unique }
+ 's' { kind_shared }
+ 'p' { kind_pinned }
+ c {
+ log_err "unexpected char in encoded type param: ";
+ log_err c;
+ fail
+ }
+ };
ret ty::mk_param(st.tcx, parse_int(st) as uint, k);
}
'@' { ret ty::mk_box(st.tcx, parse_mt(st, sd)); }
'I' { ret ty::mk_vec(st.tcx, parse_mt(st, sd)); }
'R' {
assert (next(st) as char == '[');
- let fields: [ty::field] = ~[];
+ let fields: [ty::field] = [];
while peek(st) as char != ']' {
let name = "";
while peek(st) as char != '=' {
name += str::unsafe_from_byte(next(st));
}
st.pos = st.pos + 1u;
- fields += ~[{ident: name, mt: parse_mt(st, sd)}];
+ fields += [{ident: name, mt: parse_mt(st, sd)}];
}
st.pos = st.pos + 1u;
ret ty::mk_rec(st.tcx, fields);
}
'T' {
assert (next(st) as char == '[');
- let params = ~[];
- while peek(st) as char != ']' { params += ~[parse_ty(st, sd)]; }
+ let params = [];
+ while peek(st) as char != ']' { params += [parse_ty(st, sd)]; }
st.pos = st.pos + 1u;
ret ty::mk_tup(st.tcx, params);
}
}
'O' {
assert (next(st) as char == '[');
- let methods: [ty::method] = ~[];
+ let methods: [ty::method] = [];
while peek(st) as char != ']' {
let proto;
alt next(st) as char {
}
let func = parse_ty_fn(st, sd);
methods +=
- ~[{proto: proto,
- ident: name,
- inputs: func.args,
- output: func.ty,
- cf: func.cf,
- constrs: func.cs}];
+ [{proto: proto,
+ ident: name,
+ inputs: func.args,
+ output: func.ty,
+ cf: func.cf,
+ constrs: func.cs}];
}
st.pos += 1u;
ret ty::mk_obj(st.tcx, methods);
assert (next(st) as char == '[');
let def = parse_def(st, sd);
let inner = parse_ty(st, sd);
- let params: [ty::t] = ~[];
- while peek(st) as char != ']' { params += ~[parse_ty(st, sd)]; }
+ let params: [ty::t] = [];
+ while peek(st) as char != ']' { params += [parse_ty(st, sd)]; }
st.pos = st.pos + 1u;
ret ty::mk_res(st.tcx, def, inner, params);
}
fn parse_ty_fn(st: @pstate, sd: str_def) ->
{args: [ty::arg], ty: ty::t, cf: ast::controlflow, cs: [@ty::constr]} {
assert (next(st) as char == '[');
- let inputs: [ty::arg] = ~[];
+ let inputs: [ty::arg] = [];
while peek(st) as char != ']' {
let mode = ty::mo_val;
if peek(st) as char == '&' {
mode = ty::mo_move;
st.pos += 1u;
}
- inputs += ~[{mode: mode, ty: parse_ty(st, sd)}];
+ inputs += [{mode: mode, ty: parse_ty(st, sd)}];
}
st.pos += 1u; // eat the ']'
let cs = parse_constrs(st, sd);
fn parse_def_id(buf: &[u8]) -> ast::def_id {
let colon_idx = 0u;
let len = vec::len::<u8>(buf);
- while colon_idx < len && buf.(colon_idx) != ':' as u8 { colon_idx += 1u; }
+ while colon_idx < len && buf[colon_idx] != ':' as u8 { colon_idx += 1u; }
if colon_idx == len {
log_err "didn't find ':' when parsing def id";
fail;
let crate_part = vec::slice::<u8>(buf, 0u, colon_idx);
let def_part = vec::slice::<u8>(buf, colon_idx + 1u, len);
- let crate_part_vec = ~[];
- let def_part_vec = ~[];
- for b: u8 in crate_part { crate_part_vec += ~[b]; }
- for b: u8 in def_part { def_part_vec += ~[b]; }
+ let crate_part_vec = [];
+ let def_part_vec = [];
+ for b: u8 in crate_part { crate_part_vec += [b]; }
+ for b: u8 in def_part { def_part_vec += [b]; }
let crate_num = uint::parse_buf(crate_part_vec, 10u) as int;
let def_num = uint::parse_buf(def_part_vec, 10u) as int;
export ac_use_abbrevs;
export enc_ty;
-type ctxt = // Def -> str Callback:
+type ctxt =
+ // Def -> str Callback:
// The type context.
- {ds: fn(&def_id) -> str , tcx: ty::ctxt, abbrevs: abbrev_ctxt};
+ {ds: fn(&def_id) -> str, tcx: ty::ctxt, abbrevs: abbrev_ctxt};
// Compact string representation for ty.t values. API ty_str & parse_from_str.
// Extra parameters are for converting to/from def_ids in the string rep.
native_abi_llvm. { w.write_char('l'); }
native_abi_x86stdcall. { w.write_char('s'); }
}
- enc_ty_fn(w, cx, args, out, return, ~[]);
+ enc_ty_fn(w, cx, args, out, return, []);
}
ty::ty_obj(methods) {
w.write_str("O[");
w.write_str(cx.ds(def));
w.write_char('|');
}
- ty::ty_param(id,k) {
+ ty::ty_param(id, k) {
alt k {
kind_unique. { w.write_str("pu"); }
kind_shared. { w.write_str("ps"); }
w.write_char('&');
if mut { w.write_char('m'); }
}
- ty::mo_move. {
- w.write_char('-');
- }
+ ty::mo_move. { w.write_char('-'); }
ty::mo_val. { }
}
enc_ty(w, cx, arg.ty);
// Stores information about object fields and function
// arguments that's otherwise not easily available.
let cx = @{tcx: tcx, local_map: std::map::new_int_hash()};
- let v = @{visit_fn: bind visit_fn(cx, _, _, _, _, _, _, _),
- visit_item: bind visit_item(cx, _, _, _),
- visit_expr: bind visit_expr(cx, _, _, _),
- visit_decl: bind visit_decl(cx, _, _, _)
- with *visit::default_visitor::<scope>()};
- visit::visit_crate(*crate, @~[], visit::mk_vt(v));
+ let v =
+ @{visit_fn: bind visit_fn(cx, _, _, _, _, _, _, _),
+ visit_item: bind visit_item(cx, _, _, _),
+ visit_expr: bind visit_expr(cx, _, _, _),
+ visit_decl: bind visit_decl(cx, _, _, _)
+ with *visit::default_visitor::<scope>()};
+ visit::visit_crate(*crate, @[], visit::mk_vt(v));
tcx.sess.abort_if_errors();
}
for arg_: ast::arg in f.decl.inputs {
cx.local_map.insert(arg_.id, arg(arg_.mode));
}
- let scope = alt (f.proto) {
- // Blocks need to obey any restrictions from the enclosing scope.
- ast::proto_block. { sc }
- // Closures need to prohibit writing to any of the upvars.
- // This doesn't seem like a particularly clean way to do this.
- ast::proto_closure. {
- let dnums = ~[];
- for each nid in freevars::get_freevar_defs(cx.tcx, id).keys() {
- dnums += ~[nid];
- }
- @~[@{root_vars: ~[],
- // I'm not sure if there is anything sensical to put here
- block_defnum: 0,
- bindings: dnums,
- tys: ~[],
- depends_on: ~[],
- mutable ok: valid}]
- }
- // Non capturing functions start out fresh.
- _ { @~[] }
- };
+ let scope =
+ alt f.proto {
+
+ // Blocks need to obey any restrictions from the enclosing scope.
+ ast::proto_block. {
+ sc
+ }
+
+ // Closures need to prohibit writing to any of the upvars.
+ // This doesn't seem like a particularly clean way to do this.
+ ast::proto_closure. {
+ let dnums = [];
+ for each nid in freevars::get_freevar_defs(cx.tcx, id).keys() {
+ dnums += [nid];
+ };
+ @[
+ // I'm not sure if there is anything sensical to put here
+ @{root_vars: [],
+ block_defnum: 0,
+ bindings: dnums,
+ tys: [],
+ depends_on: [],
+ mutable ok: valid}]
+ }
+
+ // Non capturing functions start out fresh.
+ _ {
+ @[]
+ }
+ };
v.visit_block(f.body, scope, v);
}
{root_vars: [node_id], unsafe_ts: [ty::t]} {
let fty = ty::expr_ty(cx.tcx, f);
let arg_ts = fty_args(cx, fty);
- let roots: [node_id] = ~[];
- let mut_roots: [{arg: uint, node: node_id}] = ~[];
- let unsafe_ts: [ty::t] = ~[];
- let unsafe_t_offsets: [uint] = ~[];
+ let roots: [node_id] = [];
+ let mut_roots: [{arg: uint, node: node_id}] = [];
+ let unsafe_ts: [ty::t] = [];
+ let unsafe_t_offsets: [uint] = [];
let i = 0u;
for arg_t: ty::arg in arg_ts {
if arg_t.mode != ty::mo_val {
- let arg = args.(i);
+ let arg = args[i];
let root = expr_root(cx, arg, false);
if arg_t.mode == ty::mo_alias(true) {
alt path_def(cx, arg) {
let dnum = ast::def_id_of_def(def).node;
if def_is_local(def, true) {
if is_immutable_alias(cx, sc, dnum) {
- cx.tcx.sess.span_err
- (arg.span, "passing an immutable alias \
- by mutable alias");
+ cx.tcx.sess.span_err(
+ arg.span,
+ "passing an immutable alias \
+ by mutable alias");
} else if is_immutable_objfield(cx, dnum) {
- cx.tcx.sess.span_err
- (arg.span, "passing an immutable object \
- field by mutable alias");
+ cx.tcx.sess.span_err(
+ arg.span,
+ "passing an immutable object \
+ field by mutable alias");
}
} else {
- cx.tcx.sess.span_err
- (arg.span,
- "passing a static item by mutable alias");
+ cx.tcx.sess.span_err(
+ arg.span,
+ "passing a static item by mutable alias");
}
- mut_roots += ~[{arg: i, node: dnum}];
+ mut_roots += [{arg: i, node: dnum}];
}
_ {
if !mut_field(root.ds) {
- let m = "passing a temporary value or \
+ let m =
+ "passing a temporary value or \
immutable field by mutable alias";
cx.tcx.sess.span_err(arg.span, m);
}
}
}
alt path_def_id(cx, root.ex) {
- some(did) { roots += ~[did.node]; }
+ some(did) { roots += [did.node]; }
_ { }
}
alt inner_mut(root.ds) {
- some(t) { unsafe_ts += ~[t]; unsafe_t_offsets += ~[i]; }
+ some(t) { unsafe_ts += [t]; unsafe_t_offsets += [i]; }
_ { }
}
}
ast::expr_path(_) {
if def_is_local(cx.tcx.def_map.get(f.id), true) {
cx.tcx.sess.span_err(f.span,
- #fmt("function may alias with \
+ #fmt["function may alias with \
argument %u, which is not immutably rooted",
- unsafe_t_offsets.(0)));
+ unsafe_t_offsets[0]]);
}
}
_ { }
}
let j = 0u;
for unsafe: ty::t in unsafe_ts {
- let offset = unsafe_t_offsets.(j);
+ let offset = unsafe_t_offsets[j];
j += 1u;
let i = 0u;
for arg_t: ty::arg in arg_ts {
let mut_alias = arg_t.mode == ty::mo_alias(true);
if i != offset &&
ty_can_unsafely_include(cx, unsafe, arg_t.ty, mut_alias) {
- cx.tcx.sess.span_err(args.(i).span,
- #fmt("argument %u may alias with \
+ cx.tcx.sess.span_err(args[i].span,
+ #fmt["argument %u may alias with \
argument %u, which is not immutably rooted",
- i, offset));
+ i, offset]);
}
i += 1u;
}
if mut_alias_to_root {
- cx.tcx.sess.span_err(args.(root.arg).span,
+ cx.tcx.sess.span_err(args[root.arg].span,
"passing a mutable alias to a \
variable that roots another alias");
}
if arg_t.mode != ty::mo_val {
let mut_a = arg_t.mode == ty::mo_alias(true);
let ok = true;
- alt args.(i).node {
+ alt args[i].node {
ast::expr_path(_) {
- let def = cx.tcx.def_map.get(args.(i).id);
+ let def = cx.tcx.def_map.get(args[i].id);
let dnum = ast::def_id_of_def(def).node;
alt cx.local_map.find(dnum) {
some(arg(ast::alias(mut))) {
if mut_a && !mut {
- cx.tcx.sess.span_err(args.(i).span,
+ cx.tcx.sess.span_err(args[i].span,
"passing an immutable \
alias by mutable alias");
}
_ { ok = false; }
}
if !ok {
- cx.tcx.sess.span_err(args.(i).span,
+ cx.tcx.sess.span_err(args[i].span,
"can not pass a local value by \
alias to a tail call");
}
visit::visit_expr(input, sc, v);
let root = expr_root(cx, input, true);
let roots =
- alt path_def_id(cx, root.ex) { some(did) { ~[did.node] } _ { ~[] } };
+ alt path_def_id(cx, root.ex) { some(did) { [did.node] } _ { [] } };
let forbidden_tp: [ty::t] =
- alt inner_mut(root.ds) { some(t) { ~[t] } _ { ~[] } };
+ alt inner_mut(root.ds) { some(t) { [t] } _ { [] } };
for a: ast::arm in arms {
let dnums = arm_defnums(a);
let new_sc = sc;
if vec::len(dnums) > 0u {
- new_sc = @(*sc + ~[@{root_vars: roots,
- block_defnum: dnums.(vec::len(dnums) - 1u),
- bindings: dnums,
- tys: forbidden_tp,
- depends_on: deps(sc, roots),
- mutable ok: valid}]);
+ new_sc =
+ @(*sc +
+ [@{root_vars: roots,
+ block_defnum: dnums[vec::len(dnums) - 1u],
+ bindings: dnums,
+ tys: forbidden_tp,
+ depends_on: deps(sc, roots),
+ mutable ok: valid}]);
}
visit::visit_arm(a, new_sc, v);
}
}
fn arm_defnums(arm: &ast::arm) -> [node_id] {
- ret ast::pat_binding_ids(arm.pats.(0));
+ ret ast::pat_binding_ids(arm.pats[0]);
}
fn check_for_each(cx: &ctx, local: &@ast::local, call: &@ast::expr,
ast::expr_call(f, args) {
let data = check_call(cx, f, args, sc);
let bindings = ast::pat_binding_ids(local.node.pat);
- let new_sc = @{root_vars: data.root_vars,
- block_defnum: bindings.(vec::len(bindings) - 1u),
- bindings: bindings,
- tys: data.unsafe_ts,
- depends_on: deps(sc, data.root_vars),
- mutable ok: valid};
- visit::visit_block(blk, @(*sc + ~[new_sc]), v);
+ let new_sc =
+ @{root_vars: data.root_vars,
+ block_defnum: bindings[vec::len(bindings) - 1u],
+ bindings: bindings,
+ tys: data.unsafe_ts,
+ depends_on: deps(sc, data.root_vars),
+ mutable ok: valid};
+ visit::visit_block(blk, @(*sc + [new_sc]), v);
}
}
}
visit::visit_expr(seq, sc, v);
let root = expr_root(cx, seq, false);
let root_def =
- alt path_def_id(cx, root.ex) { some(did) { ~[did.node] } _ { ~[] } };
- let unsafe = alt inner_mut(root.ds) { some(t) { ~[t] } _ { ~[] } };
+ alt path_def_id(cx, root.ex) { some(did) { [did.node] } _ { [] } };
+ let unsafe = alt inner_mut(root.ds) { some(t) { [t] } _ { [] } };
// If this is a mutable vector, don't allow it to be touched.
let seq_t = ty::expr_ty(cx.tcx, seq);
alt ty::struct(cx.tcx, seq_t) {
- ty::ty_vec(mt) {
- if mt.mut != ast::imm { unsafe = ~[seq_t]; }
- }
+ ty::ty_vec(mt) { if mt.mut != ast::imm { unsafe = [seq_t]; } }
ty::ty_str. | ty::ty_istr. {/* no-op */ }
_ {
cx.tcx.sess.span_unimpl(seq.span,
}
}
let bindings = ast::pat_binding_ids(local.node.pat);
- let new_sc = @{root_vars: root_def,
- block_defnum: bindings.(vec::len(bindings) - 1u),
- bindings: bindings,
- tys: unsafe,
- depends_on: deps(sc, root_def),
- mutable ok: valid};
- visit::visit_block(blk, @(*sc + ~[new_sc]), v);
+ let new_sc =
+ @{root_vars: root_def,
+ block_defnum: bindings[vec::len(bindings) - 1u],
+ bindings: bindings,
+ tys: unsafe,
+ depends_on: deps(sc, root_def),
+ mutable ok: valid};
+ visit::visit_block(blk, @(*sc + [new_sc]), v);
}
fn check_var(cx: &ctx, ex: &@ast::expr, p: &ast::path, id: ast::node_id,
let my_defnum = ast::def_id_of_def(def).node;
let var_t = ty::expr_ty(cx.tcx, ex);
for r: restrict in *sc {
+
// excludes variables introduced since the alias was made
// FIXME This does not work anymore, now that we have macros.
if my_defnum < r.block_defnum {
r.ok = val_taken(ex.span, p);
}
}
- } else if (vec::member(my_defnum, r.bindings)) {
+ } else if vec::member(my_defnum, r.bindings) {
test_scope(cx, sc, r, p);
}
}
let dnum = ast::def_id_of_def(cx.tcx.def_map.get(dest.id)).node;
if is_immutable_alias(*cx, sc, dnum) {
cx.tcx.sess.span_err(dest.span, "assigning to immutable alias");
- } else if (is_immutable_objfield(*cx, dnum)) {
+ } else if is_immutable_objfield(*cx, dnum) {
cx.tcx.sess.span_err(dest.span,
"assigning to immutable obj field");
}
let root = expr_root(*cx, dest, false);
if vec::len(*root.ds) == 0u {
cx.tcx.sess.span_err(dest.span, "assignment to non-lvalue");
- } else if (!root.ds.(0).mut) {
+ } else if !root.ds[0].mut {
let name =
- alt root.ds.(0).kind {
+ alt root.ds[0].kind {
unbox. { "box" }
field. { "field" }
index. { "vec content" }
some(arg(ast::alias(false))) { ret true; }
_ { }
}
- for r: restrict in *sc {
- if vec::member(dnum, r.bindings) { ret true; }
- }
+ for r: restrict in *sc { if vec::member(dnum, r.bindings) { ret true; } }
ret false;
}
let prob = r.ok;
for dep: uint in r.depends_on {
if prob != valid { break; }
- prob = sc.(dep).ok;
+ prob = sc[dep].ok;
}
if prob != valid {
- let msg = alt prob {
- overwritten(sp, wpt) {
- {span: sp, msg: "overwriting " + ast::path_name(wpt)}
- }
- val_taken(sp, vpt) {
- {span: sp, msg: "taking the value of " + ast::path_name(vpt)}
- }
- };
+ let msg =
+ alt prob {
+ overwritten(sp, wpt) {
+ {span: sp, msg: "overwriting " + ast::path_name(wpt)}
+ }
+ val_taken(sp, vpt) {
+ {span: sp, msg: "taking the value of " + ast::path_name(vpt)}
+ }
+ };
cx.tcx.sess.span_err(msg.span,
msg.msg + " will invalidate alias " +
ast::path_name(p) + ", which is still used");
fn deps(sc: &scope, roots: &[node_id]) -> [uint] {
let i = 0u;
- let result = ~[];
+ let result = [];
for r: restrict in *sc {
for dn: node_id in roots {
- if vec::member(dn, r.bindings) { result += ~[i]; }
+ if vec::member(dn, r.bindings) { result += [i]; }
}
i += 1u;
}
fn expr_root(cx: &ctx, ex: @ast::expr, autoderef: bool) ->
{ex: @ast::expr, ds: @[deref]} {
fn maybe_auto_unbox(cx: &ctx, t: ty::t) -> {t: ty::t, ds: [deref]} {
- let ds = ~[];
+ let ds = [];
while true {
alt ty::struct(cx.tcx, t) {
ty::ty_box(mt) {
- ds += ~[@{mut: mt.mut != ast::imm, kind: unbox, outer_t: t}];
+ ds += [@{mut: mt.mut != ast::imm, kind: unbox, outer_t: t}];
t = mt.ty;
}
ty::ty_uniq(mt) {
- ds += ~[@{mut: false, kind: unbox, outer_t: t}];
+ ds += [@{mut: false, kind: unbox, outer_t: t}];
}
ty::ty_res(_, inner, tps) {
- ds += ~[@{mut: false, kind: unbox, outer_t: t}];
+ ds += [@{mut: false, kind: unbox, outer_t: t}];
t = ty::substitute_type_params(cx.tcx, tps, inner);
}
ty::ty_tag(did, tps) {
let variants = ty::tag_variants(cx.tcx, did);
if vec::len(variants) != 1u ||
- vec::len(variants.(0).args) != 1u {
+ vec::len(variants[0].args) != 1u {
break;
}
- ds += ~[@{mut: false, kind: unbox, outer_t: t}];
+ ds += [@{mut: false, kind: unbox, outer_t: t}];
t =
ty::substitute_type_params(cx.tcx, tps,
- variants.(0).args.(0));
+ variants[0].args[0]);
}
_ { break; }
}
}
ret {t: t, ds: ds};
}
- let ds: [deref] = ~[];
+ let ds: [deref] = [];
while true {
alt { ex.node } {
ast::expr_field(base, ident) {
}
ty::ty_obj(_) { }
}
- ds += ~[@{mut: mut, kind: field, outer_t: auto_unbox.t}];
+ ds += [@{mut: mut, kind: field, outer_t: auto_unbox.t}];
ds += auto_unbox.ds;
ex = base;
}
alt ty::struct(cx.tcx, auto_unbox.t) {
ty::ty_vec(mt) {
ds +=
- ~[@{mut: mt.mut != ast::imm,
- kind: index,
- outer_t: auto_unbox.t}];
+ [@{mut: mt.mut != ast::imm,
+ kind: index,
+ outer_t: auto_unbox.t}];
}
}
ds += auto_unbox.ds;
ty::ty_tag(_, _) { }
ty::ty_ptr(mt) { mut = mt.mut != ast::imm; }
}
- ds += ~[@{mut: mut, kind: unbox, outer_t: base_t}];
+ ds += [@{mut: mut, kind: unbox, outer_t: base_t}];
ex = base;
} else { break; }
}
fn path_def(cx: &ctx, ex: &@ast::expr) -> option::t<ast::def> {
ret alt ex.node {
- ast::expr_path(_) { some(cx.tcx.def_map.get(ex.id)) }
- _ { none }
- }
+ ast::expr_path(_) { some(cx.tcx.def_map.get(ex.id)) }
+ _ { none }
+ }
}
fn path_def_id(cx: &ctx, ex: &@ast::expr) -> option::t<ast::def_id> {
ret false;
}
ty::ty_tup(ts) {
- for t in ts {
- if helper(tcx, needle, t, mut) {
- ret true;
- }
- }
+ for t in ts { if helper(tcx, needle, t, mut) { ret true; } }
ret false;
}
+
// These may contain anything.
ty::ty_fn(_, _, _, _, _) {
ret true;
}
ty::ty_obj(_) { ret true; }
+
// A type param may include everything, but can only be
// treated as opaque downstream, and is thus safe unless we
// saw mutable fields, in which case the whole thing can be
// overwritten.
- ty::ty_param(_,_) {
+ ty::ty_param(_, _) {
ret mut;
}
_ { ret false; }
// interface.
// FIXME: hashmap and smallintmap should support the same interface.
fn new_smallintmap_adapter<@K,
- @V>(key_idx: fn(&K) -> uint ,
- idx_key: fn(&uint) -> K ) ->
+ @V>(key_idx: fn(&K) -> uint,
+ idx_key: fn(&uint) -> K) ->
std::map::hashmap<K, V> {
obj adapter<@K,
@V>(map: smallintmap::smallintmap<V>,
- key_idx: fn(&K) -> uint ,
- idx_key: fn(&uint) -> K ) {
+ key_idx: fn(&K) -> uint,
+ idx_key: fn(&uint) -> K) {
fn size() -> uint { fail }
#[test]
fn test_node_span_item() {
let expected: codemap::span = mk_sp(20u, 30u);
- let node = node_item(@{ident: "test",
- attrs: ~[],
- id: 0,
- node: item_mod({view_items: ~[],
- items: ~[]}),
- span: expected});
- assert node_span(node) == expected;
+ let node =
+ node_item(@{ident: "test",
+ attrs: [],
+ id: 0,
+ node: item_mod({view_items: [], items: []}),
+ span: expected});
+ assert (node_span(node) == expected);
}
#[test]
fn test_node_span_obj_ctor() {
let expected: codemap::span = mk_sp(20u, 30u);
- let node = node_obj_ctor(@{ident: "test",
- attrs: ~[],
- id: 0,
- node: item_mod({view_items: ~[],
- items: ~[]}),
- span: expected});
- assert node_span(node) == expected;
+ let node =
+ node_obj_ctor(@{ident: "test",
+ attrs: [],
+ id: 0,
+ node: item_mod({view_items: [], items: []}),
+ span: expected});
+ assert (node_span(node) == expected);
}
#[test]
fn test_node_span_native_item() {
let expected: codemap::span = mk_sp(20u, 30u);
- let node = node_native_item(@{ident: "test",
- attrs: ~[],
- node: native_item_ty,
- id: 0,
- span: expected});
- assert node_span(node) == expected;
+ let node =
+ node_native_item(@{ident: "test",
+ attrs: [],
+ node: native_item_ty,
+ id: 0,
+ span: expected});
+ assert (node_span(node) == expected);
}
#[test]
fn test_node_span_expr() {
let expected: codemap::span = mk_sp(20u, 30u);
- let node = node_expr(@{id: 0,
- node: expr_break,
- span: expected});
- assert node_span(node) == expected;
+ let node = node_expr(@{id: 0, node: expr_break, span: expected});
+ assert (node_span(node) == expected);
}
}
let v =
@{visit_expr: bind check_expr(tcx, _, _, _),
visit_local: bind check_local(tcx, _, _, _)
- with *visit::default_visitor::<()>()};
+ with *visit::default_visitor::<()>()};
visit::visit_crate(*crate, (), visit::mk_vt(v));
tcx.sess.abort_if_errors();
}
let reachable = true;
let j = 0;
while j < i {
- for prev_pat: @pat in arms.(j).pats {
+ for prev_pat: @pat in arms[j].pats {
if pattern_supersedes(tcx, prev_pat, arm_pat) {
reachable = false;
}
}
fn pattern_supersedes(tcx: &ty::ctxt, a: &@pat, b: &@pat) -> bool {
- fn patterns_supersede(tcx: &ty::ctxt, as: &[@pat], bs: &[@pat]) ->
- bool {
+ fn patterns_supersede(tcx: &ty::ctxt, as: &[@pat], bs: &[@pat]) -> bool {
let i = 0;
for a: @pat in as {
- if !pattern_supersedes(tcx, a, bs.(i)) { ret false; }
+ if !pattern_supersedes(tcx, a, bs[i]) { ret false; }
i += 1;
}
ret true;
ret false;
}
pat_tup(elts) {
- for elt in elts {
- if is_refutable(tcx, elt) { ret true; }
- }
+ for elt in elts { if is_refutable(tcx, elt) { ret true; } }
ret false;
}
pat_tag(_, args) {
let vdef = variant_def_ids(tcx.def_map.get(pat.id));
- if std::vec::len(ty::tag_variants(tcx, vdef.tg)) != 1u {
- ret true;
- }
- for p: @pat in args {
- if is_refutable(tcx, p) { ret true; }
- }
+ if std::vec::len(ty::tag_variants(tcx, vdef.tg)) != 1u { ret true; }
+ for p: @pat in args { if is_refutable(tcx, p) { ret true; } }
ret false;
}
}
// of the AST, we take a walker function that we invoke with a visitor
// in order to start the search.
fn collect_freevars(def_map: &resolve::def_map, sess: &session::session,
- walker: &fn(&visit::vt<()>) ,
+ walker: &fn(&visit::vt<()>),
initial_decls: [ast::node_id]) -> freevar_info {
let decls = new_int_hash();
for decl: ast::node_id in initial_decls { set_add(decls, decl); }
- let refs = @mutable ~[];
+ let refs = @mutable [];
- let walk_fn = lambda(f: &ast::_fn, _tps: &[ast::ty_param], _sp: &span,
- _i: &ast::fn_ident, _nid: ast::node_id) {
- for a: ast::arg in f.decl.inputs { set_add(decls, a.id); }
- };
- let walk_expr = lambda(expr: &@ast::expr) {
- alt expr.node {
- ast::expr_path(path) {
- if !def_map.contains_key(expr.id) {
- sess.span_fatal(expr.span,
- "internal error in collect_freevars");
+ let walk_fn =
+ lambda (f: &ast::_fn, _tps: &[ast::ty_param], _sp: &span,
+ _i: &ast::fn_ident, _nid: ast::node_id) {
+ for a: ast::arg in f.decl.inputs { set_add(decls, a.id); }
+ };
+ let walk_expr =
+ lambda (expr: &@ast::expr) {
+ alt expr.node {
+ ast::expr_path(path) {
+ if !def_map.contains_key(expr.id) {
+ sess.span_fatal(expr.span,
+ "internal error in collect_freevars");
+ }
+ alt def_map.get(expr.id) {
+ ast::def_arg(did) { *refs += [expr.id]; }
+ ast::def_local(did) { *refs += [expr.id]; }
+ ast::def_binding(did) { *refs += [expr.id]; }
+ _ {/* no-op */ }
+ }
+ }
+ _ { }
}
- alt def_map.get(expr.id) {
- ast::def_arg(did) { *refs += ~[expr.id]; }
- ast::def_local(did) { *refs += ~[expr.id]; }
- ast::def_binding(did) { *refs += ~[expr.id]; }
- _ {/* no-op */ }
+ };
+ let walk_local =
+ lambda (local: &@ast::local) {
+ for each b: @ast::pat in ast::pat_bindings(local.node.pat) {
+ set_add(decls, b.id);
}
- }
- _ { }
- }
- };
- let walk_local = lambda(local: &@ast::local) {
- for each b: @ast::pat in ast::pat_bindings(local.node.pat) {
- set_add(decls, b.id);
- }
- };
- let walk_pat = lambda(p: &@ast::pat) {
- alt p.node { ast::pat_bind(_) { set_add(decls, p.id); } _ { } }
- };
-
- walker(visit::mk_simple_visitor
- (@{visit_local: walk_local,
- visit_pat: walk_pat,
- visit_expr: walk_expr,
- visit_fn: walk_fn
- with *visit::default_simple_visitor()}));
+ };
+ let walk_pat =
+ lambda (p: &@ast::pat) {
+ alt p.node { ast::pat_bind(_) { set_add(decls, p.id); } _ { } }
+ };
+ walker(visit::mk_simple_visitor(@{visit_local: walk_local,
+ visit_pat: walk_pat,
+ visit_expr: walk_expr,
+ visit_fn: walk_fn
+ with
+ *visit::default_simple_visitor()}));
// Calculate (refs - decls). This is the set of captured upvars.
// We build a vec of the node ids of the uses and a set of the
// node ids of the definitions.
- let canonical_refs = ~[];
+ let canonical_refs = [];
let defs = new_int_hash();
for ref_id_: ast::node_id in *refs {
let ref_id = ref_id_;
let def_id = ast::def_id_of_def(def_map.get(ref_id)).node;
if !decls.contains_key(def_id) && !defs.contains_key(def_id) {
- canonical_refs += ~[ref_id];
+ canonical_refs += [ref_id];
set_add(defs, def_id);
}
}
crate: &@ast::crate) -> freevar_map {
let freevars = new_int_hash();
- let walk_fn = lambda(f: &ast::_fn, tps: &[ast::ty_param], sp: &span,
- i: &ast::fn_ident, nid: ast::node_id) {
- let start_walk = lambda(v: &visit::vt<()>) {
- v.visit_fn(f, tps, sp, i, nid, (), v);
+ let walk_fn =
+ lambda (f: &ast::_fn, tps: &[ast::ty_param], sp: &span,
+ i: &ast::fn_ident, nid: ast::node_id) {
+ let start_walk =
+ lambda (v: &visit::vt<()>) {
+ v.visit_fn(f, tps, sp, i, nid, (), v);
+ };
+ let vars = collect_freevars(def_map, sess, start_walk, []);
+ freevars.insert(nid, vars);
+ };
+ let walk_expr =
+ lambda (expr: &@ast::expr) {
+ alt expr.node {
+ ast::expr_for_each(local, _, body) {
+ let start_walk =
+ lambda (v: &visit::vt<()>) {
+ v.visit_block(body, (), v);
+ };
+ let bound = ast::pat_binding_ids(local.node.pat);
+ let vars = collect_freevars(def_map, sess, start_walk, bound);
+ freevars.insert(body.node.id, vars);
+ }
+ _ { }
+ }
};
- let vars = collect_freevars(def_map, sess, start_walk, ~[]);
- freevars.insert(nid, vars);
- };
- let walk_expr = lambda(expr: &@ast::expr) {
- alt expr.node {
- ast::expr_for_each(local, _, body) {
- let start_walk = lambda(v: &visit::vt<()>) {
- v.visit_block(body, (), v);
- };
- let bound = ast::pat_binding_ids(local.node.pat);
- let vars =
- collect_freevars(def_map, sess, start_walk, bound);
- freevars.insert(body.node.id, vars);
- }
- _ { }
- }
- };
let visitor =
- visit::mk_simple_visitor(@{visit_fn: walk_fn,
- visit_expr: walk_expr
+ visit::mk_simple_visitor(@{visit_fn: walk_fn, visit_expr: walk_expr
with *visit::default_simple_visitor()});
visit::visit_crate(*crate, (), visitor);
import lll = lib::llvm::llvm;
-type ctxt = @{ mutable next_tydesc_num: uint };
+type ctxt = @{mutable next_tydesc_num: uint};
-fn mk_ctxt() -> ctxt {
- ret @{ mutable next_tydesc_num: 0u };
-}
+fn mk_ctxt() -> ctxt { ret @{mutable next_tydesc_num: 0u}; }
fn add_global(ccx: &@crate_ctxt, llval: ValueRef, name: str) -> ValueRef {
- let llglobal = lll::LLVMAddGlobal(ccx.llmod, val_ty(llval),
- str::buf(name));
+ let llglobal =
+ lll::LLVMAddGlobal(ccx.llmod, val_ty(llval), str::buf(name));
lll::LLVMSetInitializer(llglobal, llval);
lll::LLVMSetGlobalConstant(llglobal, True);
ret llglobal;
fn add_gc_root(cx: &@block_ctxt, llval: ValueRef, ty: ty::t) -> @block_ctxt {
let bcx = cx;
if !type_is_gc_relevant(bcx_tcx(cx), ty) ||
- ty::type_has_dynamic_size(bcx_tcx(cx), ty) {
+ ty::type_has_dynamic_size(bcx_tcx(cx), ty) {
ret bcx;
}
let llvalptr = bcx.build.PointerCast(llval, T_ptr(T_ptr(T_i8())));
alt td_r.kind {
- tk_derived. {
- // It's a derived type descriptor. First, spill it.
- let lltydescptr = trans::alloca(bcx, val_ty(lltydesc));
- bcx.build.Store(lltydesc, lltydescptr);
-
- let number = gc_cx.next_tydesc_num;
- gc_cx.next_tydesc_num += 1u;
-
- let lldestindex = add_global(bcx_ccx(bcx),
- C_struct(~[C_int(0),
- C_uint(number)]),
- "rust_gc_tydesc_dest_index");
- let llsrcindex = add_global(bcx_ccx(bcx),
- C_struct(~[C_int(1), C_uint(number)]),
- "rust_gc_tydesc_src_index");
-
- lldestindex = lll::LLVMConstPointerCast(lldestindex,
- T_ptr(T_i8()));
- llsrcindex = lll::LLVMConstPointerCast(llsrcindex,
- T_ptr(T_i8()));
-
- lltydescptr = bcx.build.PointerCast(lltydescptr,
- T_ptr(T_ptr(T_i8())));
-
- bcx.build.Call(gcroot, ~[ lltydescptr, lldestindex ]);
- bcx.build.Call(gcroot, ~[ llvalptr, llsrcindex ]);
- }
- tk_param. {
- bcx_tcx(cx).sess.bug("we should never be trying to root values " +
- "of a type parameter");
- }
- tk_static. {
- // Static type descriptor.
-
- let llstaticgcmeta = add_global(bcx_ccx(bcx),
- C_struct(~[C_int(2), lltydesc]),
- "rust_gc_tydesc_static_gc_meta");
- let llstaticgcmetaptr = lll::LLVMConstPointerCast(llstaticgcmeta,
- T_ptr(T_i8()));
-
- bcx.build.Call(gcroot, ~[ llvalptr, llstaticgcmetaptr ]);
- }
+ tk_derived. {
+ // It's a derived type descriptor. First, spill it.
+ let lltydescptr = trans::alloca(bcx, val_ty(lltydesc));
+ bcx.build.Store(lltydesc, lltydescptr);
+
+ let number = gc_cx.next_tydesc_num;
+ gc_cx.next_tydesc_num += 1u;
+
+ let lldestindex =
+ add_global(bcx_ccx(bcx), C_struct([C_int(0), C_uint(number)]),
+ "rust_gc_tydesc_dest_index");
+ let llsrcindex =
+ add_global(bcx_ccx(bcx), C_struct([C_int(1), C_uint(number)]),
+ "rust_gc_tydesc_src_index");
+
+ lldestindex = lll::LLVMConstPointerCast(lldestindex, T_ptr(T_i8()));
+ llsrcindex = lll::LLVMConstPointerCast(llsrcindex, T_ptr(T_i8()));
+
+ lltydescptr =
+ bcx.build.PointerCast(lltydescptr, T_ptr(T_ptr(T_i8())));
+
+ bcx.build.Call(gcroot, [lltydescptr, lldestindex]);
+ bcx.build.Call(gcroot, [llvalptr, llsrcindex]);
+ }
+ tk_param. {
+ bcx_tcx(cx).sess.bug("we should never be trying to root values " +
+ "of a type parameter");
+ }
+ tk_static. {
+ // Static type descriptor.
+
+ let llstaticgcmeta =
+ add_global(bcx_ccx(bcx), C_struct([C_int(2), lltydesc]),
+ "rust_gc_tydesc_static_gc_meta");
+ let llstaticgcmetaptr =
+ lll::LLVMConstPointerCast(llstaticgcmeta, T_ptr(T_i8()));
+
+ bcx.build.Call(gcroot, [llvalptr, llstaticgcmetaptr]);
+ }
}
ret bcx;
fn type_is_gc_relevant(cx: &ty::ctxt, ty: &ty::t) -> bool {
alt ty::struct(cx, ty) {
- ty::ty_nil. | ty::ty_bot. | ty::ty_bool. | ty::ty_int. |
- ty::ty_float. | ty::ty_uint. | ty::ty_machine(_) | ty::ty_char. |
- ty::ty_istr. | ty::ty_type. | ty::ty_native(_) | ty::ty_ptr(_) |
- ty::ty_type. | ty::ty_native(_) {
- ret false;
- }
-
- ty::ty_rec(fields) {
- for f in fields {
- if type_is_gc_relevant(cx, f.mt.ty) { ret true; }
- }
- ret false;
- }
- ty::ty_tup(elts) {
- for elt in elts {
- if type_is_gc_relevant(cx, elt) { ret true; }
+ ty::ty_nil. | ty::ty_bot. | ty::ty_bool. | ty::ty_int. | ty::ty_float. |
+ ty::ty_uint. | ty::ty_machine(_) | ty::ty_char. | ty::ty_istr. |
+ ty::ty_type. | ty::ty_native(_) | ty::ty_ptr(_) | ty::ty_type. |
+ ty::ty_native(_) {
+ ret false;
+ }
+
+
+ ty::ty_rec(fields) {
+ for f in fields { if type_is_gc_relevant(cx, f.mt.ty) { ret true; } }
+ ret false;
+ }
+ ty::ty_tup(elts) {
+ for elt in elts { if type_is_gc_relevant(cx, elt) { ret true; } }
+ ret false;
+ }
+
+
+ ty::ty_tag(did, tps) {
+ let variants = ty::tag_variants(cx, did);
+ for variant in variants {
+ for aty in variant.args {
+ let arg_ty = ty::substitute_type_params(cx, tps, aty);
+ if type_is_gc_relevant(cx, arg_ty) { ret true; }
}
- ret false;
}
+ ret false;
+ }
+
+
+ ty::ty_vec(tm) {
+ ret type_is_gc_relevant(cx, tm.ty);
+ }
+ ty::ty_constr(sub, _) { ret type_is_gc_relevant(cx, sub); }
- ty::ty_tag(did, tps) {
- let variants = ty::tag_variants(cx, did);
- for variant in variants {
- for aty in variant.args {
- let arg_ty = ty::substitute_type_params(cx, tps, aty);
- if type_is_gc_relevant(cx, arg_ty) { ret true; }
- }
- }
- ret false;
- }
- ty::ty_vec(tm) { ret type_is_gc_relevant(cx, tm.ty); }
- ty::ty_constr(sub, _) { ret type_is_gc_relevant(cx, sub); }
+ ty::ty_str. | ty::ty_box(_) | ty::ty_uniq(_) | ty::ty_fn(_, _, _, _, _)
+ | ty::ty_native_fn(_, _, _) | ty::ty_obj(_) | ty::ty_param(_, _) |
+ ty::ty_res(_, _, _) {
+ ret true;
+ }
- ty::ty_str. | ty::ty_box(_) | ty::ty_uniq(_) |
- ty::ty_fn(_,_,_,_,_) | ty::ty_native_fn(_,_,_) | ty::ty_obj(_) |
- ty::ty_param(_,_) | ty::ty_res(_,_,_) { ret true; }
- ty::ty_var(_) { fail "ty_var in type_is_gc_relevant"; }
+ ty::ty_var(_) {
+ fail "ty_var in type_is_gc_relevant";
+ }
}
}
}
}
-fn type_and_kind(tcx: &ty::ctxt, e: &@ast::expr)
- -> {ty: ty::t, kind: ast::kind} {
+fn type_and_kind(tcx: &ty::ctxt, e: &@ast::expr) ->
+ {ty: ty::t, kind: ast::kind} {
let t = ty::expr_ty(tcx, e);
let k = ty::type_kind(tcx, t);
{ty: t, kind: k}
}
-fn need_expr_kind(tcx: &ty::ctxt, e: &@ast::expr,
- k_need: ast::kind, descr: &str) {
+fn need_expr_kind(tcx: &ty::ctxt, e: &@ast::expr, k_need: ast::kind,
+ descr: &str) {
let tk = type_and_kind(tcx, e);
- log #fmt("for %s: want %s type, got %s type %s",
- descr,
- kind_to_str(k_need),
- kind_to_str(tk.kind),
- util::ppaux::ty_to_str(tcx, tk.ty));
+ log #fmt["for %s: want %s type, got %s type %s", descr,
+ kind_to_str(k_need), kind_to_str(tk.kind),
+ util::ppaux::ty_to_str(tcx, tk.ty)];
- if ! kind_lteq(k_need, tk.kind) {
+ if !kind_lteq(k_need, tk.kind) {
let s =
- #fmt("mismatched kinds for %s: needed %s type, got %s type %s",
- descr,
- kind_to_str(k_need),
- kind_to_str(tk.kind),
- util::ppaux::ty_to_str(tcx, tk.ty));
+ #fmt["mismatched kinds for %s: needed %s type, got %s type %s",
+ descr, kind_to_str(k_need), kind_to_str(tk.kind),
+ util::ppaux::ty_to_str(tcx, tk.ty)];
tcx.sess.span_err(e.span, s);
}
}
-fn need_shared_lhs_rhs(tcx: &ty::ctxt,
- a: &@ast::expr, b: &@ast::expr,
+fn need_shared_lhs_rhs(tcx: &ty::ctxt, a: &@ast::expr, b: &@ast::expr,
op: &str) {
need_expr_kind(tcx, a, ast::kind_shared, op + " lhs");
need_expr_kind(tcx, b, ast::kind_shared, op + " rhs");
ast::expr_swap(a, b) { need_shared_lhs_rhs(tcx, a, b, "<->"); }
ast::expr_call(callee, _) {
let tpt = ty::expr_ty_params_and_ty(tcx, callee);
+
// If we have typarams, we're calling an item; we need to check
// that all the types we're supplying as typarams conform to the
// typaram kind constraints on that item.
let callee_def = ast::def_id_of_def(tcx.def_map.get(callee.id));
let item_tk = ty::lookup_item_type(tcx, callee_def);
let i = 0;
- assert vec::len(item_tk.kinds) == vec::len(tpt.params);
+ assert (vec::len(item_tk.kinds) == vec::len(tpt.params));
for k_need: ast::kind in item_tk.kinds {
- let t = tpt.params.(i);
+ let t = tpt.params[i];
let k = ty::type_kind(tcx, t);
- if ! kind_lteq(k_need, k) {
- let s = #fmt("mismatched kinds for typaram %d: \
+ if !kind_lteq(k_need, k) {
+ let s =
+ #fmt["mismatched kinds for typaram %d: \
needed %s type, got %s type %s",
- i,
- kind_to_str(k_need),
- kind_to_str(k),
- util::ppaux::ty_to_str(tcx, t));
+ i, kind_to_str(k_need), kind_to_str(k),
+ util::ppaux::ty_to_str(tcx, t)];
tcx.sess.span_err(e.span, s);
}
i += 1;
}
fn check_crate(tcx: &ty::ctxt, crate: &@ast::crate) {
- let visit = visit::mk_simple_visitor
- (@{visit_expr: bind check_expr(tcx, _)
- with *visit::default_simple_visitor()});
+ let visit =
+ visit::mk_simple_visitor(@{visit_expr: bind check_expr(tcx, _)
+ with *visit::default_simple_visitor()});
visit::visit_crate(*crate, (), visit);
tcx.sess.abort_if_errors();
}
todo(ast::node_id, ast::ident, [ast::ident], codemap::span, scopes);
resolving(span);
resolved(option::t<def>,
- /* value */
+
+ /* value */
option::t<def>,
- /* type */
+
+ /* type */
option::t<def>); /* module */
}
tag namespace { ns_value; ns_type; ns_module; }
fn resolve_crate(sess: session, amap: &ast_map::map, crate: @ast::crate) ->
- {def_map: def_map, ext_map: ext_map} {
+ {def_map: def_map, ext_map: ext_map} {
let e =
@{cstore: sess.get_cstore(),
def_map: new_int_hash::<def>(),
mod_map: new_int_hash::<@indexed_mod>(),
ext_map: new_def_hash::<[ident]>(),
ext_cache: new_ext_hash(),
- mutable reported: ~[],
+ mutable reported: [],
sess: sess};
map_crate(e, crate);
resolve_imports(*e);
e.mod_map.insert(-1,
@{m: some(c.node.module),
index: index_mod(c.node.module),
- mutable glob_imports: ~[],
+ mutable glob_imports: [],
glob_imported_names: new_str_hash::<import_state>()});
fn index_vi(e: @env, i: &@ast::view_item, sc: &scopes, _v: &vt<scopes>) {
alt i.node {
for ident in idents {
e.imports.insert(ident.node.id,
todo(ident.node.id, ident.node.name,
- mod_path + ~[ident.node.name],
- ident.span, sc));
+ mod_path + [ident.node.name],
+ ident.span, sc));
}
}
_ { }
e.mod_map.insert(i.id,
@{m: some(md),
index: index_mod(md),
- mutable glob_imports: ~[],
+ mutable glob_imports: [],
glob_imported_names: s});
}
ast::item_native_mod(nmd) {
e.mod_map.insert(i.id,
@{m: none::<ast::_mod>,
index: index_nmod(nmd),
- mutable glob_imports: ~[],
+ mutable glob_imports: [],
glob_imported_names: s});
}
_ { }
}
alt vi.node {
+
//if it really is a glob import, that is
ast::view_item_import_glob(path, _) {
let imp = follow_import(*e, sc, path, vi.span);
if option::is_some(imp) {
find_mod(e, sc).glob_imports +=
- ~[{def: option::get(imp), item: vi}];
+ [{def: option::get(imp), item: vi}];
}
}
_ { }
{
alt it.val {
todo(node_id, name, path, span, scopes) {
- resolve_import(e, local_def(node_id),
- name, path, span, scopes);
+ resolve_import(e, local_def(node_id), name, path, span, scopes);
}
resolved(_, _, _) { }
}
e.def_map.insert(pat.id, option::get(fnd));
}
_ {
- e.sess.span_err
- (p.span, "not a tag variant: " + ast::path_name(p));
+ e.sess.span_err(p.span,
+ "not a tag variant: " + ast::path_name(p));
}
}
}
// is this a main fn declaration?
alt name {
some(nm) {
- if is_main_name(~[nm]) && !e.sess.get_opts().library {
+ if is_main_name([nm]) && !e.sess.get_opts().library {
// This is a main function -- set it in the session
// as the main ID
e.sess.set_main_id(id);
// here's where we need to set up the mapping
// for f's constrs in the table.
- for c: @ast::constr in f.decl.constraints {
- resolve_constr(e, c, sc, v);
- }
+ for c: @ast::constr in f.decl.constraints { resolve_constr(e, c, sc, v); }
visit::visit_fn(f, tp, sp, name, id,
cons(scope_fn(f.decl, f.proto, tp), @sc), v);
}
let pos = @mutable 0u, loc = @mutable 0u;
let block_sc = cons(scope_block(b, pos, loc), @sc);
for stmt in b.node.stmts {
- v.visit_stmt(stmt, block_sc, v);
- *pos += 1u;
+ v.visit_stmt(stmt, block_sc, v);;
+ *pos += 1u;;
*loc = 0u;
}
visit::visit_expr_opt(b.node.expr, block_sc, v);
}
fn visit_decl_with_scope(d: &@decl, sc: &scopes, v: &vt<scopes>) {
- let loc_pos = alt list::car(sc) {
- scope_block(_, _, pos) { pos }
- _ { @mutable 0u }
- };
+ let loc_pos =
+ alt list::car(sc) {
+ scope_block(_, _, pos) { pos }
+ _ { @mutable 0u }
+ };
alt d.node {
decl_local(locs) {
- for loc in locs {
- v.visit_local(loc, sc, v);
- *loc_pos += 1u;
- }
+ for loc in locs { v.visit_local(loc, sc, v);; *loc_pos += 1u; }
}
decl_item(it) { v.visit_item(it, sc, v); }
}
v.visit_block(blk, new_sc, v);
}
ast::expr_fn(f) {
- visit::visit_expr(x, cons(scope_fn(f.decl, f.proto, ~[]), @sc), v);
+ visit::visit_expr(x, cons(scope_fn(f.decl, f.proto, []), @sc), v);
}
_ { visit::visit_expr(x, sc, v); }
}
fn follow_import(e: &env, sc: &scopes, path: &[ident], sp: &span) ->
option::t<def> {
let path_len = vec::len(path);
- let dcur = lookup_in_scope_strict(e, sc, sp, path.(0), ns_module);
+ let dcur = lookup_in_scope_strict(e, sc, sp, path[0], ns_module);
let i = 1u;
while true && option::is_some(dcur) {
if i == path_len { break; }
dcur =
- lookup_in_mod_strict(e, sc, option::get(dcur), sp, path.(i),
+ lookup_in_mod_strict(e, sc, option::get(dcur), sp, path[i],
ns_module, outside);
i += 1u;
}
ids: &[ast::ident], sp: &codemap::span, sc_in: &scopes) {
e.imports.insert(defid.node, resolving(sp));
let n_idents = vec::len(ids);
- let end_id = ids.(n_idents - 1u);
+ let end_id = ids[n_idents - 1u];
// Ignore the current scope if this import would shadow itself.
let sc =
- if str::eq(name, ids.(0)) { std::list::cdr(sc_in) } else { sc_in };
+ if str::eq(name, ids[0]) { std::list::cdr(sc_in) } else { sc_in };
if n_idents == 1u {
register(e, defid, sp, end_id, sc_in,
lookup_in_scope(e, sc, sp, end_id, ns_value),
lookup_in_scope(e, sc, sp, end_id, ns_type),
lookup_in_scope(e, sc, sp, end_id, ns_module));
remove_if_unresolved(e.imports, defid.node);
- } else {
- let // FIXME (issue #521)
- dcur =
- alt lookup_in_scope(e, sc, sp, ids.(0), ns_module) {
+ } else { // FIXME (issue #521)
+ let dcur =
+ alt lookup_in_scope(e, sc, sp, ids[0], ns_module) {
some(dcur) { dcur }
none. {
- unresolved_err(e, sc, sp, ids.(0), ns_name(ns_module));
+ unresolved_err(e, sc, sp, ids[0], ns_name(ns_module));
remove_if_unresolved(e.imports, defid.node);
ret ()
}
register(e, defid, sp, end_id, sc_in,
lookup_in_mod(e, dcur, sp, end_id, ns_value,
outside),
- lookup_in_mod(e, dcur, sp, end_id, ns_type,
- outside),
+ lookup_in_mod(e, dcur, sp, end_id, ns_type, outside),
lookup_in_mod(e, dcur, sp, end_id, ns_module,
outside));
remove_if_unresolved(e.imports, defid.node);
break;
} else {
dcur =
- alt lookup_in_mod(e, dcur, sp, ids.(i), ns_module,
- outside) {
+ alt lookup_in_mod(e, dcur, sp, ids[i], ns_module, outside)
+ {
some(dcur) { dcur }
none. {
- unresolved_err(e, sc, sp, ids.(i),
- ns_name(ns_module));
+ unresolved_err(e, sc, sp, ids[i], ns_name(ns_module));
remove_if_unresolved(e.imports, defid.node);
ret () // FIXME (issue #521)
}
for rs: {ident: str, sc: scope} in e.reported {
if str::eq(rs.ident, name) && err_scope == rs.sc { ret; }
}
- e.reported += ~[{ident: name, sc: err_scope}];
+ e.reported += [{ident: name, sc: err_scope}];
e.sess.span_err(sp, mk_unresolved_msg(name, kind));
}
}
fn mk_unresolved_msg(id: &ident, kind: &str) -> str {
- ret #fmt("unresolved %s: %s", kind, id);
+ ret #fmt["unresolved %s: %s", kind, id];
}
// Lookup helpers
} else { first_scope = sc; }
let dcur =
- lookup_in_scope_strict(e, first_scope, sp, pth.idents.(0), headns);
+ lookup_in_scope_strict(e, first_scope, sp, pth.idents[0], headns);
let i = 1u;
while i < n_idents && option::is_some(dcur) {
let curns = if n_idents == i + 1u { ns } else { ns_module };
dcur =
- lookup_in_mod_strict(e, sc, option::get(dcur), sp, pth.idents.(i),
+ lookup_in_mod_strict(e, sc, option::get(dcur), sp, pth.idents[i],
curns, outside);
i += 1u;
}
}
fn def_is_ty_arg(d: &def) -> bool {
- ret alt d { ast::def_ty_arg(_,_) { true } _ { false } };
+ ret alt d { ast::def_ty_arg(_, _) { true } _ { false } };
}
fn lookup_in_scope(e: &env, sc: scopes, sp: &span, name: &ident,
if ns == ns_value {
alt lookup_in_pat(name, local.node.pat) {
some(did) { ret some(ast::def_local(did)); }
- _ {}
+ _ { }
}
}
}
scope_arm(a) {
if ns == ns_value {
ret option::map(ast::def_binding,
- lookup_in_pat(name, a.pats.(0)));
+ lookup_in_pat(name, a.pats[0]));
}
}
}
option::t<def> {
let i = 0u;
for tp: ast::ty_param in ty_params {
- if str::eq(tp.ident, name) { ret some(ast::def_ty_arg(i,tp.kind)); }
+ if str::eq(tp.ident, name) { ret some(ast::def_ty_arg(i, tp.kind)); }
i += 1u;
}
ret none::<def>;
let found = none;
for each bound in ast::pat_bindings(pat) {
let p_name = alt bound.node { ast::pat_bind(n) { n } };
- if str::eq(p_name, name) {
- found = some(local_def(bound.id));
- }
+ if str::eq(p_name, name) { found = some(local_def(bound.id)); }
}
ret found;
}
let i = vec::len(b.stmts);
while i > 0u {
i -= 1u;
- let st = b.stmts.(i);
+ let st = b.stmts[i];
alt st.node {
ast::stmt_decl(d, _) {
alt d.node {
let j = vec::len(locs);
while j > 0u {
j -= 1u;
- let loc = locs.(j);
+ let loc = locs[j];
if ns == ns_value && (i < pos || j < loc_pos) {
alt lookup_in_pat(name, loc.node.pat) {
some(did) { ret some(ast::def_local(did)); }
- _ {}
+ _ { }
}
}
}
if str::eq(it.ident, name) {
ret some(ast::def_ty(local_def(it.id)));
}
- } else if (ns == ns_value) {
+ } else if ns == ns_value {
for v: ast::variant in variants {
if str::eq(v.node.name, name) {
let i = v.node.id;
let cached = e.ext_cache.find({did: defid, ident: name, ns: ns});
if !is_none(cached) { ret cached; }
- let path = ~[name];
+ let path = [name];
if defid.node != -1 { path = e.ext_map.get(defid) + path; }
let fnd = lookup_external(e, defid.crate, path, ns);
if !is_none(fnd) {
}
}
-fn found_view_item(e: &env, vi: @ast::view_item) ->
- option::t<def> {
+fn found_view_item(e: &env, vi: @ast::view_item) -> option::t<def> {
alt vi.node {
ast::view_item_use(_, _, id) {
let cnum = cstore::get_use_stmt_cnum(e.cstore, id);
fn lookup_import(e: &env, defid: def_id, ns: namespace) -> option::t<def> {
alt e.imports.get(defid.node) {
todo(node_id, name, path, span, scopes) {
- resolve_import(e, local_def(node_id),
- name, path, span, scopes);
+ resolve_import(e, local_def(node_id), name, path, span, scopes);
ret lookup_import(e, defid, ns);
}
resolving(sp) { e.sess.span_err(sp, "cyclic import"); ret none; }
let matches =
vec::filter_map(bind lookup_in_mod_(e, _, sp, id, ns, dr),
- { info.glob_imports });
+ { info.glob_imports });
if vec::len(matches) == 0u {
ret none;
- } else if (vec::len(matches) == 1u) {
- ret some(matches.(0).def);
+ } else if vec::len(matches) == 1u {
+ ret some(matches[0].def);
} else {
for match: glob_imp_def in matches {
let sp = match.item.span;
- e.sess.span_note(sp, #fmt("'%s' is imported here", id));
+ e.sess.span_note(sp, #fmt["'%s' is imported here", id]);
}
e.sess.span_fatal(sp,
"'" + id + "' is glob-imported from" +
alt item.node {
ast::item_tag(variants, _) {
if ns == ns_value {
- let vid = variants.(variant_idx).node.id;
+ let vid = variants[variant_idx].node.id;
ret some(ast::def_variant(local_def(item.id),
local_def(vid)));
} else { ret none::<def>; }
let index = new_str_hash::<list<mod_index_entry>>();
for it: @ast::view_item in md.view_items {
alt it.node {
- ast::view_item_use(ident, _, _)
- {
+ ast::view_item_use(ident, _, _) {
add_to_index(index, ident, mie_view_item(it));
}
+
ast::view_item_import(ident, _, id) {
add_to_index(index, ident, mie_import_ident(id, it.span));
}
+
ast::view_item_import_from(_, idents, _) {
for ident in idents {
add_to_index(index, ident.node.name,
}
}
+
//globbed imports have to be resolved lazily.
ast::view_item_import_glob(_, _) | ast::view_item_export(_, _) {
}
fn check_for_collisions(e: &@env, c: &ast::crate) {
// Module indices make checking those relatively simple -- just check each
// name for multiple entities in the same namespace.
- for each m: @{key: ast::node_id, val: @indexed_mod}
- in e.mod_map.items() {
- for each name: @{key: ident, val: list<mod_index_entry>}
- in m.val.index.items() {
+ for each m: @{key: ast::node_id, val: @indexed_mod} in e.mod_map.items() {
+ for each name: @{key: ident, val: list<mod_index_entry>} in
+ m.val.index.items() {
check_mod_name(*e, name.key, name.val);
}
}
// Other scopes have to be checked the hard way.
- let v = @{visit_item: bind check_item(e, _, _, _),
- visit_block: bind check_block(e, _, _, _),
- visit_arm: bind check_arm(e, _, _, _),
- visit_expr: bind check_expr(e, _, _, _),
- visit_ty: bind check_ty(e, _, _, _)
- with *visit::default_visitor()};
+ let v =
+ @{visit_item: bind check_item(e, _, _, _),
+ visit_block: bind check_block(e, _, _, _),
+ visit_arm: bind check_arm(e, _, _, _),
+ visit_expr: bind check_expr(e, _, _, _),
+ visit_ty: bind check_ty(e, _, _, _) with *visit::default_visitor()};
visit::visit_crate(c, (), visit::mk_vt(v));
}
fn check_item(e: &@env, i: &@ast::item, x: &(), v: &vt<()>) {
fn typaram_names(tps: &[ast::ty_param]) -> [ident] {
- let x: [ast::ident] = ~[];
- for tp: ast::ty_param in tps { x += ~[tp.ident] }
+ let x: [ast::ident] = [];
+ for tp: ast::ty_param in tps { x += [tp.ident] }
ret x;
}
visit::visit_item(i, x, v);
alt i.node {
ast::item_fn(f, ty_params) {
check_fn(*e, i.span, f);
- ensure_unique(*e, i.span, typaram_names(ty_params),
- ident_id, "type parameter");
+ ensure_unique(*e, i.span, typaram_names(ty_params), ident_id,
+ "type parameter");
}
ast::item_obj(ob, ty_params, _) {
fn field_name(field: &ast::obj_field) -> ident { ret field.ident; }
for m: @ast::method in ob.methods {
check_fn(*e, m.span, m.node.meth);
}
- ensure_unique(*e, i.span, typaram_names(ty_params),
- ident_id, "type parameter");
+ ensure_unique(*e, i.span, typaram_names(ty_params), ident_id,
+ "type parameter");
}
ast::item_tag(_, ty_params) {
- ensure_unique(*e, i.span, typaram_names(ty_params),
- ident_id, "type parameter");
+ ensure_unique(*e, i.span, typaram_names(ty_params), ident_id,
+ "type parameter");
}
_ { }
}
fn check_arm(e: &@env, a: &ast::arm, x: &(), v: &vt<()>) {
visit::visit_arm(a, x, v);
let ch0 = checker(*e, "binding");
- check_pat(ch0, a.pats.(0));
+ check_pat(ch0, a.pats[0]);
let seen0 = ch0.seen;
let i = vec::len(a.pats);
while i > 1u {
i -= 1u;
let ch = checker(*e, "binding");
- check_pat(ch, a.pats.(i));
+ check_pat(ch, a.pats[i]);
// Ensure the bindings introduced in this pattern are the same as in
// the first pattern.
if vec::len(ch.seen) != vec::len(seen0) {
- e.sess.span_err(a.pats.(i).span,
+ e.sess.span_err(a.pats[i].span,
"inconsistent number of bindings");
} else {
for name: ident in ch.seen {
if is_none(vec::find(bind str::eq(name, _), seen0)) {
// Fight the alias checker
let name_ = name;
- e.sess.span_err(a.pats.(i).span,
+ e.sess.span_err(a.pats[i].span,
"binding " + name_ +
" does not occur in first pattern");
}
type checker = @{mutable seen: [ident], kind: str, sess: session};
fn checker(e: &env, kind: str) -> checker {
- let seen: [ident] = ~[];
+ let seen: [ident] = [];
ret @{mutable seen: seen, kind: kind, sess: e.sess};
}
}
fn add_name(ch: &checker, sp: &span, name: &ident) {
check_name(ch, sp, name);
- ch.seen += ~[name];
+ ch.seen += [name];
}
fn ident_id(i: &ident) -> ident { ret i; }
-fn ensure_unique<T>(e: &env, sp: &span, elts: &[T], id: fn(&T) -> ident ,
+fn ensure_unique<T>(e: &env, sp: &span, elts: &[T], id: fn(&T) -> ident,
kind: &str) {
let ch = checker(e, kind);
for elt: T in elts { add_name(ch, sp, id(elt)); }
import ty_ctxt = middle::ty::ctxt;
-type res_info = { did: ast::def_id, t: ty::t };
-
-type ctxt = {
- mutable next_tag_id: u16,
- pad: u16,
- tag_id_to_index: hashmap<ast::def_id,u16>,
- mutable tag_order: [ast::def_id],
- resources: interner::interner<res_info>,
- llshapetablesty: TypeRef,
- llshapetables: ValueRef
-};
-
-const shape_u8 : u8 = 0u8;
-const shape_u16 : u8 = 1u8;
-const shape_u32 : u8 = 2u8;
-const shape_u64 : u8 = 3u8;
-const shape_i8 : u8 = 4u8;
-const shape_i16 : u8 = 5u8;
-const shape_i32 : u8 = 6u8;
-const shape_i64 : u8 = 7u8;
-const shape_f32 : u8 = 8u8;
-const shape_f64 : u8 = 9u8;
-const shape_evec : u8 = 10u8;
-const shape_ivec : u8 = 11u8;
-const shape_tag : u8 = 12u8;
-const shape_box : u8 = 13u8;
-const shape_struct : u8 = 17u8;
-const shape_fn : u8 = 18u8;
-const shape_obj : u8 = 19u8;
-const shape_res : u8 = 20u8;
-const shape_var : u8 = 21u8;
-const shape_uniq : u8 = 22u8;
+type res_info = {did: ast::def_id, t: ty::t};
+
+type ctxt =
+ {mutable next_tag_id: u16,
+ pad: u16,
+ tag_id_to_index: hashmap<ast::def_id, u16>,
+ mutable tag_order: [ast::def_id],
+ resources: interner::interner<res_info>,
+ llshapetablesty: TypeRef,
+ llshapetables: ValueRef};
+
+const shape_u8: u8 = 0u8;
+const shape_u16: u8 = 1u8;
+const shape_u32: u8 = 2u8;
+const shape_u64: u8 = 3u8;
+const shape_i8: u8 = 4u8;
+const shape_i16: u8 = 5u8;
+const shape_i32: u8 = 6u8;
+const shape_i64: u8 = 7u8;
+const shape_f32: u8 = 8u8;
+const shape_f64: u8 = 9u8;
+const shape_evec: u8 = 10u8;
+const shape_ivec: u8 = 11u8;
+const shape_tag: u8 = 12u8;
+const shape_box: u8 = 13u8;
+const shape_struct: u8 = 17u8;
+const shape_fn: u8 = 18u8;
+const shape_obj: u8 = 19u8;
+const shape_res: u8 = 20u8;
+const shape_var: u8 = 21u8;
+const shape_uniq: u8 = 22u8;
// FIXME: This is a bad API in trans_common.
-fn C_u8(n : u8) -> ValueRef { ret trans_common::C_u8(n as uint); }
+fn C_u8(n: u8) -> ValueRef { ret trans_common::C_u8(n as uint); }
-fn hash_res_info(ri : &res_info) -> uint {
+fn hash_res_info(ri: &res_info) -> uint {
let h = 5381u;
- h *= 33u; h += (ri.did.crate as uint);
- h *= 33u; h += (ri.did.node as uint);
- h *= 33u; h += (ri.t as uint);
+ h *= 33u;
+ h += ri.did.crate as uint;
+ h *= 33u;
+ h += ri.did.node as uint;
+ h *= 33u;
+ h += ri.t as uint;
ret h;
}
-fn eq_res_info(a : &res_info, b : &res_info) -> bool {
+fn eq_res_info(a: &res_info, b: &res_info) -> bool {
ret a.did.crate == b.did.crate && a.did.node == b.did.node && a.t == b.t;
}
-fn mk_global(ccx : &@crate_ctxt, name : &str, llval : ValueRef) -> ValueRef {
- let llglobal = lib::llvm::llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval),
- str::buf(name));
+fn mk_global(ccx: &@crate_ctxt, name: &str, llval: ValueRef) -> ValueRef {
+ let llglobal =
+ lib::llvm::llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval),
+ str::buf(name));
lib::llvm::llvm::LLVMSetInitializer(llglobal, llval);
lib::llvm::llvm::LLVMSetGlobalConstant(llglobal, True);
- lib::llvm::llvm::LLVMSetLinkage(llglobal, lib::llvm::LLVMInternalLinkage
- as lib::llvm::llvm::Linkage);
+ lib::llvm::llvm::LLVMSetLinkage(llglobal,
+ lib::llvm::LLVMInternalLinkage as
+ lib::llvm::llvm::Linkage);
ret llglobal;
}
//
// TODO: Use this in dynamic_size_of() as well.
-fn largest_variants(ccx : &@crate_ctxt, tag_id : &ast::def_id) -> [uint] {
+fn largest_variants(ccx: &@crate_ctxt, tag_id: &ast::def_id) -> [uint] {
// Compute the minimum and maximum size and alignment for each variant.
//
// TODO: We could do better here; e.g. we know that any variant that
// contains (T,T) must be as least as large as any variant that contains
// just T.
- let ranges = ~[];
+ let ranges = [];
let variants = ty::tag_variants(ccx.tcx, tag_id);
- for variant : ty::variant_info in variants {
+ for variant: ty::variant_info in variants {
let bounded = true;
- let { a: min_size, b: min_align } = { a: 0u, b: 0u };
- for elem_t : ty::t in variant.args {
+ let {a: min_size, b: min_align} = {a: 0u, b: 0u};
+ for elem_t: ty::t in variant.args {
if ty::type_contains_params(ccx.tcx, elem_t) {
// TODO: We could do better here; this causes us to
// conservatively assume that (int, T) has minimum size 0,
}
}
- ranges += ~[{ size: { min: min_size, bounded: bounded },
- align: { min: min_align, bounded: bounded } }];
+ ranges +=
+ [{size: {min: min_size, bounded: bounded},
+ align: {min: min_align, bounded: bounded}}];
}
// Initialize the candidate set to contain all variants.
- let candidates = ~[mutable];
- for variant in variants { candidates += ~[mutable true]; }
+ let candidates = [mutable];
+ for variant in variants { candidates += [mutable true]; }
// Do a pairwise comparison among all variants still in the candidate set.
// Throw out any variant that we know has size and alignment at least as
// small as some other variant.
let i = 0u;
while i < vec::len(ranges) - 1u {
- if candidates.(i) {
+ if candidates[i] {
let j = i + 1u;
- while (j < vec::len(ranges)) {
- if candidates.(j) {
- if ranges.(i).size.bounded && ranges.(i).align.bounded &&
- ranges.(j).size.bounded &&
- ranges.(j).align.bounded {
- if ranges.(i).size >= ranges.(j).size &&
- ranges.(i).align >= ranges.(j).align {
+ while j < vec::len(ranges) {
+ if candidates[j] {
+ if ranges[i].size.bounded && ranges[i].align.bounded &&
+ ranges[j].size.bounded && ranges[j].align.bounded {
+ if ranges[i].size >= ranges[j].size &&
+ ranges[i].align >= ranges[j].align {
// Throw out j.
- candidates.(j) = false;
- } else if ranges.(j).size >= ranges.(i).size &&
- ranges.(j).align >= ranges.(j).align {
+ candidates[j] = false;
+ } else if ranges[j].size >= ranges[i].size &&
+ ranges[j].align >= ranges[j].align {
// Throw out i.
- candidates.(i) = false;
+ candidates[i] = false;
}
}
}
}
// Return the resulting set.
- let result = ~[];
+ let result = [];
i = 0u;
while i < vec::len(candidates) {
- if candidates.(i) { result += ~[i]; }
+ if candidates[i] { result += [i]; }
i += 1u;
}
ret result;
//
// TODO: Migrate trans over to use this.
-fn round_up(size : u16, align : u8) -> u16 {
- assert align >= 1u8;
+fn round_up(size: u16, align: u8) -> u16 {
+ assert (align >= 1u8);
let alignment = align as u16;
- ret ((size-1u16) + alignment) & !(alignment-1u16);
+ ret size - 1u16 + alignment & !(alignment - 1u16);
}
-type size_align = { size: u16, align: u8 };
+type size_align = {size: u16, align: u8};
-fn compute_static_tag_size(ccx : &@crate_ctxt, largest_variants : &[uint],
- did : &ast::def_id) -> size_align {
- let max_size = 0u16; let max_align = 1u8;
+fn compute_static_tag_size(ccx: &@crate_ctxt, largest_variants: &[uint],
+ did: &ast::def_id) -> size_align {
+ let max_size = 0u16;
+ let max_align = 1u8;
let variants = ty::tag_variants(ccx.tcx, did);
- for vid : uint in largest_variants {
+ for vid: uint in largest_variants {
// We increment a "virtual data pointer" to compute the size.
- let lltys = ~[];
- for typ : ty::t in variants.(vid).args {
- lltys += ~[trans::type_of(ccx, dummy_sp(), typ)];
+ let lltys = [];
+ for typ: ty::t in variants[vid].args {
+ lltys += [trans::type_of(ccx, dummy_sp(), typ)];
}
let llty = trans_common::T_struct(lltys);
// Add space for the tag if applicable.
// FIXME (issue #792): This is wrong. If the tag starts with an 8 byte
// aligned quantity, we don't align it.
- if vec::len(variants) > 1u {
- max_size += 4u16;
- max_align = 4u8;
- }
+ if vec::len(variants) > 1u { max_size += 4u16; max_align = 4u8; }
- ret { size: max_size, align: max_align };
+ ret {size: max_size, align: max_align};
}
-tag tag_kind {
- tk_unit;
- tk_enum;
- tk_complex;
-}
+tag tag_kind { tk_unit; tk_enum; tk_complex; }
-fn tag_kind(ccx : &@crate_ctxt, did : &ast::def_id) -> tag_kind {
+fn tag_kind(ccx: &@crate_ctxt, did: &ast::def_id) -> tag_kind {
let variants = ty::tag_variants(ccx.tcx, did);
if vec::len(variants) == 0u { ret tk_complex; }
- for v : ty::variant_info in variants {
+ for v: ty::variant_info in variants {
if vec::len(v.args) > 0u { ret tk_complex; }
}
if vec::len(variants) == 1u { ret tk_unit; }
// Returns the code corresponding to the pointer size on this architecture.
-fn s_int(_tcx : &ty_ctxt) -> u8 {
- ret shape_i32; // TODO: x86-64
+fn s_int(_tcx: &ty_ctxt) -> u8 {
+ ret shape_i32; // TODO: x86-64
}
-fn s_uint(_tcx : &ty_ctxt) -> u8 {
- ret shape_u32; // TODO: x86-64
+fn s_uint(_tcx: &ty_ctxt) -> u8 {
+ ret shape_u32; // TODO: x86-64
}
-fn s_float(_tcx : &ty_ctxt) -> u8 {
- ret shape_f64; // TODO: x86-64
+fn s_float(_tcx: &ty_ctxt) -> u8 {
+ ret shape_f64; // TODO: x86-64
}
-fn mk_ctxt(llmod : ModuleRef) -> ctxt {
+fn mk_ctxt(llmod: ModuleRef) -> ctxt {
let llshapetablesty = trans_common::T_named_struct("shapes");
let llshapetables =
lib::llvm::llvm::LLVMAddGlobal(llmod, llshapetablesty,
str::buf("shapes"));
- ret {
- mutable next_tag_id: 0u16,
- pad: 0u16,
- tag_id_to_index: common::new_def_hash(),
- mutable tag_order: ~[],
- resources: interner::mk(hash_res_info, eq_res_info),
- llshapetablesty: llshapetablesty,
- llshapetables: llshapetables
- };
+ ret {mutable next_tag_id: 0u16,
+ pad: 0u16,
+ tag_id_to_index: common::new_def_hash(),
+ mutable tag_order: [],
+ resources: interner::mk(hash_res_info, eq_res_info),
+ llshapetablesty: llshapetablesty,
+ llshapetables: llshapetables};
}
-fn add_bool(dest : &mutable [u8], val : bool) {
- dest += ~[if val { 1u8 } else { 0u8 }];
+fn add_bool(dest: &mutable [u8], val: bool) {
+ dest += [if val { 1u8 } else { 0u8 }];
}
-fn add_u16(dest : &mutable [u8], val : u16) {
- dest += ~[(val & 0xffu16) as u8, (val >> 8u16) as u8];
+fn add_u16(dest: &mutable [u8], val: u16) {
+ dest += [val & 0xffu16 as u8, val >> 8u16 as u8];
}
-fn add_substr(dest : &mutable [u8], src : &[u8]) {
+fn add_substr(dest: &mutable [u8], src: &[u8]) {
add_u16(dest, vec::len(src) as u16);
dest += src;
}
-fn shape_of(ccx : &@crate_ctxt, t : ty::t) -> [u8] {
- let s = ~[];
+fn shape_of(ccx: &@crate_ctxt, t: ty::t) -> [u8] {
+ let s = [];
alt ty::struct(ccx.tcx, t) {
ty::ty_nil. | ty::ty_bool. | ty::ty_machine(ast::ty_u8.) | ty::ty_bot. {
- s += ~[shape_u8];
+ s += [shape_u8];
+ }
+
+
+ ty::ty_int. {
+ s += [s_int(ccx.tcx)];
}
+ ty::ty_float. { s += [s_float(ccx.tcx)]; }
- ty::ty_int. { s += ~[s_int(ccx.tcx)]; }
- ty::ty_float. { s += ~[s_float(ccx.tcx)]; }
ty::ty_uint. | ty::ty_ptr(_) | ty::ty_type. | ty::ty_native(_) {
- s += ~[s_uint(ccx.tcx)];
+ s += [s_uint(ccx.tcx)];
}
- ty::ty_machine(ast::ty_i8.) { s += ~[shape_i8]; }
- ty::ty_machine(ast::ty_u16.) { s += ~[shape_u16]; }
- ty::ty_machine(ast::ty_i16.) { s += ~[shape_i16]; }
- ty::ty_machine(ast::ty_u32.) | ty::ty_char. { s += ~[shape_u32]; }
- ty::ty_machine(ast::ty_i32.) { s += ~[shape_i32]; }
- ty::ty_machine(ast::ty_u64.) { s += ~[shape_u64]; }
- ty::ty_machine(ast::ty_i64.) { s += ~[shape_i64]; }
- ty::ty_str. { s += ~[shape_evec, 1u8, 1u8, 0u8, shape_u8]; }
- ty::ty_istr. { s += ~[shape_ivec, 1u8, 1u8, 0u8, shape_u8]; }
+ ty::ty_machine(ast::ty_i8.) {
+ s += [shape_i8];
+ }
+ ty::ty_machine(ast::ty_u16.) { s += [shape_u16]; }
+ ty::ty_machine(ast::ty_i16.) { s += [shape_i16]; }
+ ty::ty_machine(ast::ty_u32.) | ty::ty_char. { s += [shape_u32]; }
+ ty::ty_machine(ast::ty_i32.) { s += [shape_i32]; }
+ ty::ty_machine(ast::ty_u64.) { s += [shape_u64]; }
+ ty::ty_machine(ast::ty_i64.) { s += [shape_i64]; }
+
+
+ ty::ty_str. {
+ s += [shape_evec, 1u8, 1u8, 0u8, shape_u8];
+ }
+ ty::ty_istr. { s += [shape_ivec, 1u8, 1u8, 0u8, shape_u8]; }
+
ty::ty_tag(did, tps) {
alt tag_kind(ccx, did) {
tk_unit. {
// FIXME: For now we do this.
- s += ~[shape_u32];
+ s += [shape_u32];
}
- tk_enum. { s += ~[shape_u32]; }
+ tk_enum. { s += [shape_u32]; }
tk_complex. {
- s += ~[shape_tag];
+ s += [shape_tag];
- let sub = ~[];
+ let sub = [];
let id;
alt ccx.shape_cx.tag_id_to_index.find(did) {
none. {
id = ccx.shape_cx.next_tag_id;
ccx.shape_cx.tag_id_to_index.insert(did, id);
- ccx.shape_cx.tag_order += ~[did];
+ ccx.shape_cx.tag_order += [did];
ccx.shape_cx.next_tag_id += 1u16;
}
some(existing_id) { id = existing_id; }
add_u16(sub, id as u16);
add_u16(sub, vec::len(tps) as u16);
- for tp : ty::t in tps {
+ for tp: ty::t in tps {
let subshape = shape_of(ccx, tp);
add_u16(sub, vec::len(subshape) as u16);
sub += subshape;
}
}
+
ty::ty_box(mt) {
- s += ~[shape_box];
+ s += [shape_box];
add_substr(s, shape_of(ccx, mt.ty));
}
ty::ty_uniq(subt) {
- s += ~[shape_uniq];
+ s += [shape_uniq];
add_substr(s, shape_of(ccx, subt));
}
ty::ty_vec(mt) {
- s += ~[shape_ivec];
+ s += [shape_ivec];
add_bool(s, ty::type_is_pod(ccx.tcx, mt.ty));
add_size_hint(ccx, s, mt.ty);
add_substr(s, shape_of(ccx, mt.ty));
}
ty::ty_rec(fields) {
- s += ~[shape_struct];
- let sub = ~[];
- for f : field in fields { sub += shape_of(ccx, f.mt.ty); }
+ s += [shape_struct];
+ let sub = [];
+ for f: field in fields { sub += shape_of(ccx, f.mt.ty); }
add_substr(s, sub);
}
ty::ty_tup(elts) {
- s += ~[shape_struct];
- let sub = ~[];
+ s += [shape_struct];
+ let sub = [];
for elt in elts { sub += shape_of(ccx, elt); }
add_substr(s, sub);
}
- ty::ty_fn(_,_,_,_,_) { s += ~[shape_fn]; }
- ty::ty_native_fn(_,_,_) { s += ~[shape_u32]; }
- ty::ty_obj(_) { s += ~[shape_obj]; }
+
+ ty::ty_fn(_, _, _, _, _) {
+ s += [shape_fn];
+ }
+ ty::ty_native_fn(_, _, _) { s += [shape_u32]; }
+ ty::ty_obj(_) { s += [shape_obj]; }
+
ty::ty_res(did, raw_subt, tps) {
let subt = ty::substitute_type_params(ccx.tcx, tps, raw_subt);
- let ri = { did: did, t: subt };
+ let ri = {did: did, t: subt};
let id = interner::intern(ccx.shape_cx.resources, ri);
- s += ~[shape_res];
+ s += [shape_res];
add_u16(s, id as u16);
add_u16(s, vec::len(tps) as u16);
- let sub = ~[];
- for tp : ty::t in tps { add_substr(s, sub); }
+ let sub = [];
+ for tp: ty::t in tps { add_substr(s, sub); }
add_substr(s, sub);
add_substr(s, shape_of(ccx, subt));
}
- ty::ty_var(n) { fail "shape_of ty_var"; }
- ty::ty_param(n,_) { s += ~[shape_var, n as u8]; }
+
+ ty::ty_var(n) {
+ fail "shape_of ty_var";
+ }
+ ty::ty_param(n, _) { s += [shape_var, n as u8]; }
}
ret s;
}
-fn add_size_hint(ccx : &@crate_ctxt, s : &mutable [u8], typ : ty::t) {
- if (ty::type_has_dynamic_size(ccx.tcx, typ)) {
- s += ~[ 0u8, 0u8, 0u8 ];
- ret;
- }
+fn add_size_hint(ccx: &@crate_ctxt, s: &mutable [u8], typ: ty::t) {
+ if ty::type_has_dynamic_size(ccx.tcx, typ) { s += [0u8, 0u8, 0u8]; ret; }
let llty = trans::type_of(ccx, dummy_sp(), typ);
add_u16(s, trans::llsize_of_real(ccx, llty) as u16);
- s += ~[ trans::llalign_of_real(ccx, llty) as u8 ];
+ s += [trans::llalign_of_real(ccx, llty) as u8];
}
// FIXME: We might discover other variants as we traverse these. Handle this.
-fn shape_of_variant(ccx : &@crate_ctxt, v : &ty::variant_info) -> [u8] {
- let s = ~[];
- for t : ty::t in v.args { s += shape_of(ccx, t); }
+fn shape_of_variant(ccx: &@crate_ctxt, v: &ty::variant_info) -> [u8] {
+ let s = [];
+ for t: ty::t in v.args { s += shape_of(ccx, t); }
ret s;
}
-fn gen_tag_shapes(ccx : &@crate_ctxt) -> ValueRef {
+fn gen_tag_shapes(ccx: &@crate_ctxt) -> ValueRef {
// Loop over all the tag variants and write their shapes into a data
// buffer. As we do this, it's possible for us to discover new tags, so we
// must do this first.
let i = 0u;
- let data = ~[]; let offsets = ~[];
- while (i < vec::len(ccx.shape_cx.tag_order)) {
- let did = ccx.shape_cx.tag_order.(i);
+ let data = [];
+ let offsets = [];
+ while i < vec::len(ccx.shape_cx.tag_order) {
+ let did = ccx.shape_cx.tag_order[i];
let variants = ty::tag_variants(ccx.tcx, did);
- for v : ty::variant_info in variants {
- offsets += ~[vec::len(data) as u16];
+ for v: ty::variant_info in variants {
+ offsets += [vec::len(data) as u16];
let variant_shape = shape_of_variant(ccx, v);
add_substr(data, variant_shape);
// info records for each tag) and the info space (which contains offsets
// to each variant shape). As we do so, build up the header.
- let header = ~[]; let info = ~[];
+ let header = [];
+ let info = [];
let header_sz = 2u16 * ccx.shape_cx.next_tag_id;
let data_sz = vec::len(data) as u16;
let info_sz = 0u16;
- for did_ : ast::def_id in ccx.shape_cx.tag_order {
- let did = did_; // Satisfy alias checker.
+ for did_: ast::def_id in ccx.shape_cx.tag_order {
+ let did = did_; // Satisfy alias checker.
let variants = ty::tag_variants(ccx.tcx, did);
add_u16(header, header_sz + info_sz);
info_sz += 2u16 * ((vec::len(variants) as u16) + 2u16) + 3u16;
// variant. Also construct the largest-variant table for each tag, which
// contains the variants that the size-of operation needs to look at.
- let lv_table = ~[];
+ let lv_table = [];
i = 0u;
- for did_ : ast::def_id in ccx.shape_cx.tag_order {
- let did = did_; // Satisfy alias checker.
+ for did_: ast::def_id in ccx.shape_cx.tag_order {
+ let did = did_; // Satisfy alias checker.
let variants = ty::tag_variants(ccx.tcx, did);
add_u16(info, vec::len(variants) as u16);
// Construct the largest-variants table.
- add_u16(info, header_sz + info_sz + data_sz +
- (vec::len(lv_table) as u16));
+ add_u16(info,
+ header_sz + info_sz + data_sz + (vec::len(lv_table) as u16));
let lv = largest_variants(ccx, did);
add_u16(lv_table, vec::len(lv) as u16);
- for v : uint in lv { add_u16(lv_table, v as u16); }
+ for v: uint in lv { add_u16(lv_table, v as u16); }
// Determine whether the tag has dynamic size.
let dynamic = false;
- for variant : ty::variant_info in variants {
- for typ : ty::t in variant.args {
+ for variant: ty::variant_info in variants {
+ for typ: ty::t in variant.args {
if ty::type_has_dynamic_size(ccx.tcx, typ) { dynamic = true; }
}
}
// Otherwise, write a placeholder.
let size_align;
if dynamic {
- size_align = { size: 0u16, align: 0u8 };
- } else {
- size_align = compute_static_tag_size(ccx, lv, did);
- }
+ size_align = {size: 0u16, align: 0u8};
+ } else { size_align = compute_static_tag_size(ccx, lv, did); }
add_u16(info, size_align.size);
- info += ~[size_align.align];
+ info += [size_align.align];
// Now write in the offset of each variant.
- for v : ty::variant_info in variants {
- add_u16(info, header_sz + info_sz + offsets.(i));
+ for v: ty::variant_info in variants {
+ add_u16(info, header_sz + info_sz + offsets[i]);
i += 1u;
}
}
assert (i == vec::len(offsets));
- assert (header_sz == (vec::len(header) as u16));
- assert (info_sz == (vec::len(info) as u16));
- assert (data_sz == (vec::len(data) as u16));
+ assert (header_sz == vec::len(header) as u16);
+ assert (info_sz == vec::len(info) as u16);
+ assert (data_sz == vec::len(data) as u16);
header += info;
header += data;
ret mk_global(ccx, "tag_shapes", C_bytes(header));
}
-fn gen_resource_shapes(ccx : &@crate_ctxt) -> ValueRef {
- let dtors = ~[];
+fn gen_resource_shapes(ccx: &@crate_ctxt) -> ValueRef {
+ let dtors = [];
let i = 0u;
let len = interner::len(ccx.shape_cx.resources);
while i < len {
let ri = interner::get(ccx.shape_cx.resources, i);
- dtors += ~[trans_common::get_res_dtor(ccx, dummy_sp(), ri.did, ri.t)];
+ dtors += [trans_common::get_res_dtor(ccx, dummy_sp(), ri.did, ri.t)];
i += 1u;
}
ret mk_global(ccx, "resource_shapes", C_struct(dtors));
}
-fn gen_shape_tables(ccx : &@crate_ctxt) {
+fn gen_shape_tables(ccx: &@crate_ctxt) {
let lltagstable = gen_tag_shapes(ccx);
let llresourcestable = gen_resource_shapes(ccx);
trans_common::set_struct_body(ccx.shape_cx.llshapetablesty,
- ~[val_ty(lltagstable),
- val_ty(llresourcestable)]);
+ [val_ty(lltagstable),
+ val_ty(llresourcestable)]);
- let lltables = C_named_struct(ccx.shape_cx.llshapetablesty,
- ~[lltagstable, llresourcestable]);
+ let lltables =
+ C_named_struct(ccx.shape_cx.llshapetablesty,
+ [lltagstable, llresourcestable]);
lib::llvm::llvm::LLVMSetInitializer(ccx.shape_cx.llshapetables, lltables);
lib::llvm::llvm::LLVMSetGlobalConstant(ccx.shape_cx.llshapetables, True);
lib::llvm::llvm::LLVMSetLinkage(ccx.shape_cx.llshapetables,
lib::llvm::LLVMInternalLinkage as
- lib::llvm::llvm::Linkage);
+ lib::llvm::llvm::Linkage);
}
fn type_of_explicit_args(cx: &@crate_ctxt, sp: &span, inputs: &[ty::arg]) ->
[TypeRef] {
- let atys: [TypeRef] = ~[];
+ let atys: [TypeRef] = [];
for arg: ty::arg in inputs {
let t: TypeRef = type_of_inner(cx, sp, arg.ty);
- t = alt arg.mode {
- ty::mo_alias(_) { T_ptr(t) }
- ty::mo_move. { T_ptr(t) }
- _ { t }
- };
- atys += ~[t];
+ t =
+ alt arg.mode {
+ ty::mo_alias(_) { T_ptr(t) }
+ ty::mo_move. { T_ptr(t) }
+ _ { t }
+ };
+ atys += [t];
}
ret atys;
}
fn type_of_fn_full(cx: &@crate_ctxt, sp: &span, proto: ast::proto,
is_method: bool, inputs: &[ty::arg], output: &ty::t,
ty_param_count: uint) -> TypeRef {
- let atys: [TypeRef] = ~[];
+ let atys: [TypeRef] = [];
// Arg 0: Output pointer.
- atys += ~[T_ptr(type_of_inner(cx, sp, output))];
+ atys += [T_ptr(type_of_inner(cx, sp, output))];
// Arg 1: task pointer.
- atys += ~[T_taskptr(*cx)];
+ atys += [T_taskptr(*cx)];
// Arg 2: Env (closure-bindings / self-obj)
if is_method {
- atys += ~[T_ptr(cx.rust_object_type)];
- } else { atys += ~[T_opaque_closure_ptr(*cx)]; }
+ atys += [T_ptr(cx.rust_object_type)];
+ } else { atys += [T_opaque_closure_ptr(*cx)]; }
// Args >3: ty params, if not acquired via capture...
if !is_method {
let i = 0u;
- while i < ty_param_count {
- atys += ~[T_ptr(cx.tydesc_type)];
- i += 1u;
- }
+ while i < ty_param_count { atys += [T_ptr(cx.tydesc_type)]; i += 1u; }
}
if proto == ast::proto_iter {
// If it's an iter, the 'output' type of the iter is actually the
// *input* type of the function we're given as our iter-block
// argument.
- atys +=
- ~[type_of_inner(cx, sp, ty::mk_iter_body_fn(cx.tcx, output))];
+ atys += [type_of_inner(cx, sp, ty::mk_iter_body_fn(cx.tcx, output))];
}
-
// ... then explicit args.
atys += type_of_explicit_args(cx, sp, inputs);
ret T_fn(atys, llvm::LLVMVoidType());
}
// Given a function type and a count of ty params, construct an llvm type
-fn type_of_fn_from_ty(cx: &@crate_ctxt, sp: &span,
- fty: &ty::t, ty_param_count: uint) -> TypeRef {
- ret type_of_fn(cx, sp,
- ty::ty_fn_proto(cx.tcx, fty),
- ty::ty_fn_args(cx.tcx, fty),
- ty::ty_fn_ret(cx.tcx, fty),
+fn type_of_fn_from_ty(cx: &@crate_ctxt, sp: &span, fty: &ty::t,
+ ty_param_count: uint) -> TypeRef {
+ ret type_of_fn(cx, sp, ty::ty_fn_proto(cx.tcx, fty),
+ ty::ty_fn_args(cx.tcx, fty), ty::ty_fn_ret(cx.tcx, fty),
ty_param_count);
}
fn type_of_native_fn(cx: &@crate_ctxt, sp: &span, abi: ast::native_abi,
inputs: &[ty::arg], output: &ty::t, ty_param_count: uint)
-> TypeRef {
- let atys: [TypeRef] = ~[];
+ let atys: [TypeRef] = [];
if abi == ast::native_abi_rust {
- atys += ~[T_taskptr(*cx)];
+ atys += [T_taskptr(*cx)];
let i = 0u;
- while i < ty_param_count {
- atys += ~[T_ptr(cx.tydesc_type)];
- i += 1u;
- }
+ while i < ty_param_count { atys += [T_ptr(cx.tydesc_type)]; i += 1u; }
}
atys += type_of_explicit_args(cx, sp, inputs);
ret T_fn(atys, type_of_inner(cx, sp, output));
}
ty::ty_ptr(mt) { llty = T_ptr(type_of_inner(cx, sp, mt.ty)); }
ty::ty_rec(fields) {
- let tys: [TypeRef] = ~[];
+ let tys: [TypeRef] = [];
for f: ty::field in fields {
- tys += ~[type_of_inner(cx, sp, f.mt.ty)];
+ tys += [type_of_inner(cx, sp, f.mt.ty)];
}
llty = T_struct(tys);
}
ty::ty_obj(meths) { llty = cx.rust_object_type; }
ty::ty_res(_, sub, tps) {
let sub1 = ty::substitute_type_params(cx.tcx, tps, sub);
- ret T_struct(~[T_i32(), type_of_inner(cx, sp, sub1)]);
+ ret T_struct([T_i32(), type_of_inner(cx, sp, sub1)]);
}
ty::ty_var(_) {
cx.tcx.sess.span_fatal(sp, "trans::type_of called on ty_var");
ty::ty_param(_, _) { llty = T_typaram(cx.tn); }
ty::ty_type. { llty = T_ptr(cx.tydesc_type); }
ty::ty_tup(elts) {
- let tys = ~[];
- for elt in elts {
- tys += ~[type_of_inner(cx, sp, elt)];
- }
+ let tys = [];
+ for elt in elts { tys += [type_of_inner(cx, sp, elt)]; }
llty = T_struct(tys);
}
}
tpt: &ty::ty_param_kinds_and_ty) -> TypeRef {
alt ty::struct(lcx.ccx.tcx, tpt.ty) {
ty::ty_fn(_, _, _, _, _) {
- let llfnty = type_of_fn_from_ty(lcx.ccx, sp, tpt.ty,
- std::vec::len(tpt.kinds));
+ let llfnty =
+ type_of_fn_from_ty(lcx.ccx, sp, tpt.ty, std::vec::len(tpt.kinds));
ret T_fn_pair(*lcx.ccx, llfnty);
}
_ {
if c != 10u8 && c != '}' as u8 && c != ')' as u8 &&
c != ' ' as u8 && c != '\t' as u8 && c != ';' as u8
{
- let v = ~[c];
+ let v = [c];
result += str::unsafe_from_bytes(v);
}
}
let elapsed =
1000 * (end.sec - start.sec as int) +
((end.usec as int) - (start.usec as int)) / 1000;
- *ccx.stats.fn_times += ~[{ident: name, time: elapsed}];
+ *ccx.stats.fn_times += [{ident: name, time: elapsed}];
}
}
fn decl_glue(llmod: ModuleRef, cx: &crate_ctxt, s: &str) -> ValueRef {
- ret decl_cdecl_fn(llmod, s, T_fn(~[T_taskptr(cx)], T_void()));
+ ret decl_cdecl_fn(llmod, s, T_fn([T_taskptr(cx)], T_void()));
}
fn get_extern_fn(externs: &hashmap<str, ValueRef>, llmod: ModuleRef,
}
fn trans_native_call(b: &builder, externs: &hashmap<str, ValueRef>,
- llmod: ModuleRef, name: &str,
- args: &[ValueRef]) -> ValueRef {
+ llmod: ModuleRef, name: &str, args: &[ValueRef]) ->
+ ValueRef {
let n: int = std::vec::len::<ValueRef>(args) as int;
let llnative: ValueRef = get_simple_extern_fn(externs, llmod, name, n);
- let call_args: [ValueRef] = ~[];
- for a: ValueRef in args { call_args += ~[b.ZExtOrBitCast(a, T_int())]; }
+ let call_args: [ValueRef] = [];
+ for a: ValueRef in args { call_args += [b.ZExtOrBitCast(a, T_int())]; }
ret b.Call(llnative, call_args);
}
fn trans_non_gc_free(cx: &@block_ctxt, v: ValueRef) -> result {
cx.build.Call(bcx_ccx(cx).upcalls.free,
- ~[cx.fcx.lltaskptr, cx.build.PointerCast(v, T_ptr(T_i8())),
- C_int(0)]);
+ [cx.fcx.lltaskptr, cx.build.PointerCast(v, T_ptr(T_i8())),
+ C_int(0)]);
ret rslt(cx, C_int(0));
}
fn trans_shared_free(cx: &@block_ctxt, v: ValueRef) -> result {
cx.build.Call(bcx_ccx(cx).upcalls.shared_free,
- ~[cx.fcx.lltaskptr,
- cx.build.PointerCast(v, T_ptr(T_i8()))]);
+ [cx.fcx.lltaskptr, cx.build.PointerCast(v, T_ptr(T_i8()))]);
ret rslt(cx, C_int(0));
}
let builder = new_builder(cx.fcx.lldynamicallocas);
let lltaskptr = bcx_fcx(bcx).lltaskptr;
alt bcx_fcx(cx).llobstacktoken {
- none. {
- bcx_fcx(cx).llobstacktoken =
- some(mk_obstack_token(bcx_ccx(cx), cx.fcx.lldynamicallocas,
- lltaskptr));
- }
- some(_) { /* no-op */ }
+ none. {
+ bcx_fcx(cx).llobstacktoken =
+ some(mk_obstack_token(bcx_ccx(cx), cx.fcx.lldynamicallocas,
+ lltaskptr));
+ }
+ some(_) {/* no-op */ }
}
let dynastack_alloc = bcx_ccx(bcx).upcalls.dynastack_alloc;
let llsz = builder.Mul(C_uint(llsize_of_real(bcx_ccx(bcx), t)), n);
- let llresult = builder.Call(dynastack_alloc, ~[lltaskptr, llsz]);
+ let llresult = builder.Call(dynastack_alloc, [lltaskptr, llsz]);
ret builder.PointerCast(llresult, T_ptr(t));
}
fn mk_obstack_token(ccx: &@crate_ctxt, lldynamicallocas: BasicBlockRef,
lltaskptr: ValueRef) -> ValueRef {
let builder = new_builder(lldynamicallocas);
- ret builder.Call(ccx.upcalls.dynastack_mark, ~[lltaskptr]);
+ ret builder.Call(ccx.upcalls.dynastack_mark, [lltaskptr]);
}
ty::ty_uniq(_) { ret ty::mk_uniq(ccx.tcx, ty::mk_nil(ccx.tcx)); }
ty::ty_fn(_, _, _, _, _) {
ret ty::mk_tup(ccx.tcx,
- ~[ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx)),
- ty::mk_imm_box(ccx.tcx,
- ty::mk_nil(ccx.tcx))]);
+ [ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx)),
+ ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx))]);
}
ty::ty_obj(_) {
ret ty::mk_tup(ccx.tcx,
- ~[ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx)),
- ty::mk_imm_box(ccx.tcx,
- ty::mk_nil(ccx.tcx))]);
+ [ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx)),
+ ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx))]);
}
ty::ty_res(_, sub, tps) {
let sub1 = ty::substitute_type_params(ccx.tcx, tps, sub);
ret ty::mk_tup(ccx.tcx,
- ~[ty::mk_int(ccx.tcx),
- simplify_type(ccx, sub1)]);
+ [ty::mk_int(ccx.tcx), simplify_type(ccx, sub1)]);
}
_ { ret typ; }
}
let max_size = 0u;
let variants = ty::tag_variants(cx.tcx, tid);
for variant: ty::variant_info in variants {
- let tup_ty =
- simplify_type(cx, ty::mk_tup(cx.tcx, variant.args));
+ let tup_ty = simplify_type(cx, ty::mk_tup(cx.tcx, variant.args));
// Perform any type parameter substitutions.
tup_ty = ty::substitute_type_params(cx.tcx, subtys, tup_ty);
ret rslt(bcx, off);
}
alt ty::struct(bcx_tcx(cx), t) {
- ty::ty_param(p,_) {
+ ty::ty_param(p, _) {
let szptr = field_of_tydesc(cx, t, false, abi::tydesc_field_size);
ret rslt(szptr.bcx, szptr.bcx.build.Load(szptr.val));
}
ty::ty_rec(flds) {
- let tys: [ty::t] = ~[];
- for f: ty::field in flds { tys += ~[f.mt.ty]; }
+ let tys: [ty::t] = [];
+ for f: ty::field in flds { tys += [f.mt.ty]; }
ret align_elements(cx, tys);
}
ty::ty_tup(elts) {
- let tys = ~[];
- for tp in elts { tys += ~[tp]; }
+ let tys = [];
+ for tp in elts { tys += [tp]; }
ret align_elements(cx, tys);
}
ty::ty_tag(tid, tps) {
// Perform type substitution on the raw argument types.
let raw_tys: [ty::t] = variant.args;
- let tys: [ty::t] = ~[];
+ let tys: [ty::t] = [];
for raw_ty: ty::t in raw_tys {
let t = ty::substitute_type_params(bcx_tcx(cx), tps, raw_ty);
- tys += ~[t];
+ tys += [t];
}
let rslt = align_elements(bcx, tys);
bcx = rslt.bcx;
fn dynamic_align_of(cx: &@block_ctxt, t: &ty::t) -> result {
alt ty::struct(bcx_tcx(cx), t) {
- ty::ty_param(p,_) {
+ ty::ty_param(p, _) {
let aptr = field_of_tydesc(cx, t, false, abi::tydesc_field_align);
ret rslt(aptr.bcx, aptr.bcx.build.Load(aptr.val));
}
// Simple wrapper around GEP that takes an array of ints and wraps them
// in C_int()
fn GEPi(cx: &@block_ctxt, base: ValueRef, ixs: &[int]) -> ValueRef {
- let v: [ValueRef] = ~[];
- for i: int in ixs { v += ~[C_int(i)]; }
+ let v: [ValueRef] = [];
+ for i: int in ixs { v += [C_int(i)]; }
ret cx.build.InBoundsGEP(base, v);
}
// Increment a pointer by a given amount and then cast it to be a pointer
// to a given type.
-fn bump_ptr(bcx: &@block_ctxt, t: &ty::t, base: ValueRef, sz: ValueRef)
- -> ValueRef {
+fn bump_ptr(bcx: &@block_ctxt, t: &ty::t, base: ValueRef, sz: ValueRef) ->
+ ValueRef {
let raw = bcx.build.PointerCast(base, T_ptr(T_i8()));
- let bumped = bcx.build.GEP(raw, ~[sz]);
- if ty::type_has_dynamic_size(bcx_tcx(bcx), t) {
- ret bumped;
- }
+ let bumped = bcx.build.GEP(raw, [sz]);
+ if ty::type_has_dynamic_size(bcx_tcx(bcx), t) { ret bumped; }
let typ = T_ptr(type_of(bcx_ccx(bcx), bcx.sp, t));
ret bcx.build.PointerCast(bumped, typ);
}
// *single* structure, the first index (in GEP-ese) should just be
// 0, to yield the pointee.
- assert (ixs.(n) == 0);
+ assert (ixs[n] == 0);
ret split_type(ccx, t, ixs, n + 1u);
}
assert (n < len);
- let ix: int = ixs.(n);
- let prefix: [ty::t] = ~[];
+ let ix: int = ixs[n];
+ let prefix: [ty::t] = [];
let i: int = 0;
while i < ix {
- prefix += ~[ty::get_element_type(ccx.tcx, t, i as uint)];
+ prefix += [ty::get_element_type(ccx.tcx, t, i as uint)];
i += 1;
}
let selected = ty::get_element_type(ccx.tcx, t, i as uint);
let s = split_type(bcx_ccx(cx), t, ixs, 0u);
- let args = ~[];
- for typ: ty::t in s.prefix { args += ~[typ]; }
+ let args = [];
+ for typ: ty::t in s.prefix { args += [typ]; }
let prefix_ty = ty::mk_tup(bcx_tcx(cx), args);
let bcx = cx;
let elem_ty = ty::mk_nil(bcx_tcx(cx)); // typestate infelicity
let i = 0;
- let true_arg_tys: [ty::t] = ~[];
+ let true_arg_tys: [ty::t] = [];
for aty: ty::t in arg_tys {
let arg_ty = ty::substitute_type_params(bcx_tcx(cx), ty_substs, aty);
- true_arg_tys += ~[arg_ty];
+ true_arg_tys += [arg_ty];
if i == ix { elem_ty = arg_ty; }
i += 1;
}
} else { llunionptr = llblobptr; }
// Do the GEP_tup_like().
- let rs = GEP_tup_like(cx, tup_ty, llunionptr, ~[0, ix]);
+ let rs = GEP_tup_like(cx, tup_ty, llunionptr, [0, ix]);
// Cast the result to the appropriate type, if necessary.
let val;
let tydesc = C_null(T_ptr(bcx_ccx(cx).tydesc_type));
let rval =
cx.build.Call(bcx_ccx(cx).upcalls.malloc,
- ~[cx.fcx.lltaskptr, llsize, tydesc]);
+ [cx.fcx.lltaskptr, llsize, tydesc]);
ret rslt(cx, cx.build.PointerCast(rval, llptr_ty));
}
let tydesc = C_null(T_ptr(bcx_ccx(cx).tydesc_type));
let rval =
cx.build.Call(bcx_ccx(cx).upcalls.shared_malloc,
- ~[cx.fcx.lltaskptr, llsize, tydesc]);
+ [cx.fcx.lltaskptr, llsize, tydesc]);
ret rslt(cx, cx.build.PointerCast(rval, llptr_ty));
}
// The mk_int here is the space being
// reserved for the refcount.
- let boxed_body =
- ty::mk_tup(bcx_tcx(cx), ~[ty::mk_int(bcx_tcx(cx)), t]);
+ let boxed_body = ty::mk_tup(bcx_tcx(cx), [ty::mk_int(bcx_tcx(cx)), t]);
let box_ptr = ty::mk_imm_box(bcx_tcx(cx), t);
let sz = size_of(cx, boxed_body);
// trans_malloc_boxed: usefully wraps trans_malloc_box_raw; allocates a box,
// initializes the reference count to 1, and pulls out the body and rc
fn trans_malloc_boxed(cx: &@block_ctxt, t: ty::t) ->
- {bcx: @block_ctxt, box: ValueRef, body: ValueRef} {
+ {bcx: @block_ctxt, box: ValueRef, body: ValueRef} {
let res = trans_malloc_boxed_raw(cx, t);
let box = res.val;
- let rc = GEPi(res.bcx, box, ~[0, abi::box_rc_field_refcnt]);
+ let rc = GEPi(res.bcx, box, [0, abi::box_rc_field_refcnt]);
res.bcx.build.Store(C_int(1), rc);
- let body = GEPi(res.bcx, box, ~[0, abi::box_rc_field_body]);
+ let body = GEPi(res.bcx, box, [0, abi::box_rc_field_body]);
ret {bcx: res.bcx, box: res.val, body: body};
}
let ti = none::<@tydesc_info>;
let tydesc = get_tydesc(cx, t, escapes, ti).result;
ret rslt(tydesc.bcx,
- tydesc.bcx.build.GEP(tydesc.val, ~[C_int(0), C_int(field)]));
+ tydesc.bcx.build.GEP(tydesc.val, [C_int(0), C_int(field)]));
}
// constructing derived tydescs.
fn linearize_ty_params(cx: &@block_ctxt, t: &ty::t) ->
{params: [uint], descs: [ValueRef]} {
- let param_vals: [ValueRef] = ~[];
- let param_defs: [uint] = ~[];
+ let param_vals: [ValueRef] = [];
+ let param_defs: [uint] = [];
type rr =
{cx: @block_ctxt, mutable vals: [ValueRef], mutable defs: [uint]};
fn linearizer(r: @rr, t: ty::t) {
alt ty::struct(bcx_tcx(r.cx), t) {
- ty::ty_param(pid,_) {
+ ty::ty_param(pid, _) {
let seen: bool = false;
for d: uint in r.defs { if d == pid { seen = true; } }
- if !seen {
- r.vals += ~[r.cx.fcx.lltydescs.(pid)];
- r.defs += ~[pid];
- }
+ if !seen { r.vals += [r.cx.fcx.lltydescs[pid]]; r.defs += [pid]; }
}
_ { }
}
fn trans_stack_local_derived_tydesc(cx: &@block_ctxt, llsz: ValueRef,
llalign: ValueRef, llroottydesc: ValueRef,
- llparamtydescs: ValueRef,
- n_params: uint) -> ValueRef {
+ llparamtydescs: ValueRef, n_params: uint)
+ -> ValueRef {
let llmyroottydesc = alloca(cx, bcx_ccx(cx).tydesc_type);
// By convention, desc 0 is the root descriptor.
cx.build.Store(llroottydesc, llmyroottydesc);
// Store a pointer to the rest of the descriptors.
- let llfirstparam = cx.build.GEP(llparamtydescs, ~[C_int(0), C_int(0)]);
+ let llfirstparam = cx.build.GEP(llparamtydescs, [C_int(0), C_int(0)]);
store_inbounds(cx, llfirstparam, llmyroottydesc,
- ~[C_int(0), C_int(abi::tydesc_field_first_param)]);
+ [C_int(0), C_int(abi::tydesc_field_first_param)]);
store_inbounds(cx, C_uint(n_params), llmyroottydesc,
- ~[C_int(0), C_int(abi::tydesc_field_n_params)]);
+ [C_int(0), C_int(abi::tydesc_field_n_params)]);
store_inbounds(cx, llsz, llmyroottydesc,
- ~[C_int(0), C_int(abi::tydesc_field_size)]);
+ [C_int(0), C_int(abi::tydesc_field_size)]);
store_inbounds(cx, llalign, llmyroottydesc,
- ~[C_int(0), C_int(abi::tydesc_field_align)]);
+ [C_int(0), C_int(abi::tydesc_field_align)]);
ret llmyroottydesc;
}
alloca(bcx,
T_array(T_ptr(bcx_ccx(bcx).tydesc_type), 1u + n_params));
let i = 0;
- let tdp = bcx.build.GEP(tydescs, ~[C_int(0), C_int(i)]);
+ let tdp = bcx.build.GEP(tydescs, [C_int(0), C_int(i)]);
bcx.build.Store(root, tdp);
i += 1;
for td: ValueRef in tys.descs {
- let tdp = bcx.build.GEP(tydescs, ~[C_int(0), C_int(i)]);
+ let tdp = bcx.build.GEP(tydescs, [C_int(0), C_int(i)]);
bcx.build.Store(td, tdp);
i += 1;
}
T_ptr(T_ptr(bcx_ccx(bcx).tydesc_type)));
let td_val =
bcx.build.Call(bcx_ccx(bcx).upcalls.get_type_desc,
- ~[bcx.fcx.lltaskptr, C_null(T_ptr(T_nil())),
- sz.val, align.val, C_int(1u + n_params as int),
- lltydescsptr]);
+ [bcx.fcx.lltaskptr, C_null(T_ptr(T_nil())), sz.val,
+ align.val, C_int(1u + n_params as int),
+ lltydescsptr]);
v = td_val;
} else {
let llparamtydescs =
- alloca(bcx, T_array(T_ptr(bcx_ccx(bcx).tydesc_type),
- n_params + 1u));
+ alloca(bcx,
+ T_array(T_ptr(bcx_ccx(bcx).tydesc_type), n_params + 1u));
let i = 0;
for td: ValueRef in tys.descs {
- let tdp = bcx.build.GEP(llparamtydescs, ~[C_int(0), C_int(i)]);
+ let tdp = bcx.build.GEP(llparamtydescs, [C_int(0), C_int(i)]);
bcx.build.Store(td, tdp);
i += 1;
}
ret rslt(cx, v);
}
-type get_tydesc_result = { kind: tydesc_kind, result: result };
+type get_tydesc_result = {kind: tydesc_kind, result: result};
fn get_tydesc(cx: &@block_ctxt, orig_t: &ty::t, escapes: bool,
- static_ti: &mutable option::t<@tydesc_info>)
- -> get_tydesc_result {
+ static_ti: &mutable option::t<@tydesc_info>) ->
+ get_tydesc_result {
let t = ty::strip_cname(bcx_tcx(cx), orig_t);
alt ty::type_param(bcx_tcx(cx), t) {
some(id) {
if id < vec::len(cx.fcx.lltydescs) {
- ret { kind: tk_param, result: rslt(cx, cx.fcx.lltydescs.(id)) };
- }
- else {
- bcx_tcx(cx).sess.span_bug(cx.sp, "Unbound typaram in get_tydesc: "
- + "orig_t = " + ty_to_str(bcx_tcx(cx), orig_t)
- + " ty_param = " + std::uint::str(id));
+ ret {kind: tk_param, result: rslt(cx, cx.fcx.lltydescs[id])};
+ } else {
+ bcx_tcx(cx).sess.span_bug(cx.sp,
+ "Unbound typaram in get_tydesc: " +
+ "orig_t = " +
+ ty_to_str(bcx_tcx(cx), orig_t) +
+ " ty_param = " +
+ std::uint::str(id));
}
}
none. {/* fall through */ }
// Does it contain a type param? If so, generate a derived tydesc.
if ty::type_contains_params(bcx_tcx(cx), t) {
- ret {
- kind: tk_derived,
- result: get_derived_tydesc(cx, t, escapes, static_ti)
- };
+ ret {kind: tk_derived,
+ result: get_derived_tydesc(cx, t, escapes, static_ti)};
}
// Otherwise, generate a tydesc if necessary, and return it.
- let info = get_static_tydesc(cx, t, ~[]);
+ let info = get_static_tydesc(cx, t, []);
static_ti = some::<@tydesc_info>(info);
- ret { kind: tk_static, result: rslt(cx, info.tydesc) };
+ ret {kind: tk_static, result: rslt(cx, info.tydesc)};
}
fn get_static_tydesc(cx: &@block_ctxt, orig_t: &ty::t, ty_params: &[uint]) ->
let ty_param_count = std::vec::len::<uint>(ty_params);
let lltyparams = llvm::LLVMGetParam(llfn, 3u);
let copy_args_bcx = new_raw_block_ctxt(fcx, fcx.llcopyargs);
- let lltydescs = ~[mutable];
+ let lltydescs = [mutable];
let p = 0u;
while p < ty_param_count {
- let llparam = copy_args_bcx.build.GEP(lltyparams, ~[C_int(p as int)]);
+ let llparam = copy_args_bcx.build.GEP(lltyparams, [C_int(p as int)]);
llparam = copy_args_bcx.build.Load(llparam);
- std::vec::grow_set(lltydescs, ty_params.(p), 0 as ValueRef, llparam);
+ std::vec::grow_set(lltydescs, ty_params[p], 0 as ValueRef, llparam);
p += 1u;
}
// TODO: Implement some kind of freeze operation in the standard library.
- let lltydescs_frozen = ~[];
- for lltydesc: ValueRef in lltydescs { lltydescs_frozen += ~[lltydesc]; }
+ let lltydescs_frozen = [];
+ for lltydesc: ValueRef in lltydescs { lltydescs_frozen += [lltydesc]; }
fcx.lltydescs = lltydescs_frozen;
let bcx = new_top_block_ctxt(fcx);
let tydesc =
C_named_struct(ccx.tydesc_type,
- ~[C_null(T_ptr(T_ptr(ccx.tydesc_type))),
- ti.size, // size
- ti.align, // align
- copy_glue, // copy_glue
- drop_glue, // drop_glue
- free_glue, // free_glue
- C_null(glue_fn_ty), // sever_glue
- C_null(glue_fn_ty), // mark_glue
- C_null(glue_fn_ty), // obj_drop_glue
- C_null(glue_fn_ty), // is_stateful
- cmp_glue, // cmp_glue
- C_shape(ccx, shape), // shape
- shape_tables, // shape_tables
- C_int(0)]); // n_params
+ [C_null(T_ptr(T_ptr(ccx.tydesc_type))),
+ ti.size, // size
+ ti.align, // align
+ copy_glue, // copy_glue
+ drop_glue, // drop_glue
+ free_glue, // free_glue
+ C_null(glue_fn_ty), // sever_glue
+ C_null(glue_fn_ty), // mark_glue
+ C_null(glue_fn_ty), // obj_drop_glue
+ C_null(glue_fn_ty), // is_stateful
+ cmp_glue, // cmp_glue
+ C_shape(ccx, shape), // shape
+ shape_tables, // shape_tables
+ C_int(0)]); // n_params
let gvar = ti.tydesc;
llvm::LLVMSetInitializer(gvar, tydesc);
if ty::type_is_boxed(bcx_tcx(cx), t) {
bcx = incr_refcnt_of_boxed(cx, cx.build.Load(v)).bcx;
- } else if (ty::type_is_structural(bcx_tcx(cx), t)) {
+ } else if ty::type_is_structural(bcx_tcx(cx), t) {
bcx = duplicate_heap_parts_if_necessary(cx, v, t).bcx;
bcx = iter_structural_ty(bcx, v, t, bind copy_ty(_, _, _)).bcx;
} else { bcx = cx; }
fn incr_refcnt_of_boxed(cx: &@block_ctxt, box_ptr: ValueRef) -> result {
let rc_ptr =
- cx.build.GEP(box_ptr, ~[C_int(0), C_int(abi::box_rc_field_refcnt)]);
+ cx.build.GEP(box_ptr, [C_int(0), C_int(abi::box_rc_field_refcnt)]);
let rc = cx.build.Load(rc_ptr);
let rc_adj_cx = new_sub_block_ctxt(cx, "rc++");
let next_cx = new_sub_block_ctxt(cx, "next");
let v = cx.build.Load(v0);
if !bcx_ccx(cx).sess.get_opts().do_gc {
trans_non_gc_free(cx, v)
- } else {
- rslt(cx, C_nil())
- }
+ } else { rslt(cx, C_nil()) }
}
ty::ty_box(body_mt) {
let v = cx.build.Load(v0);
let body =
- cx.build.GEP(v, ~[C_int(0), C_int(abi::box_rc_field_body)]);
+ cx.build.GEP(v, [C_int(0), C_int(abi::box_rc_field_body)]);
let body_ty = body_mt.ty;
let body_val = load_if_immediate(cx, body, body_ty);
let rs = drop_ty(cx, body_val, body_ty);
if !bcx_ccx(cx).sess.get_opts().do_gc {
trans_non_gc_free(rs.bcx, v)
- } else {
- rslt(cx, C_nil())
- }
- }
- ty::ty_uniq(_) {
- fail "free uniq unimplemented";
+ } else { rslt(cx, C_nil()) }
}
+ ty::ty_uniq(_) { fail "free uniq unimplemented"; }
ty::ty_obj(_) {
// Call through the obj's own fields-drop glue first.
// Then free the body.
let box_cell =
- cx.build.GEP(v0, ~[C_int(0), C_int(abi::obj_field_box)]);
+ cx.build.GEP(v0, [C_int(0), C_int(abi::obj_field_box)]);
let b = cx.build.Load(box_cell);
let ccx = bcx_ccx(cx);
let llbox_ty = T_opaque_obj_ptr(*ccx);
b = cx.build.PointerCast(b, llbox_ty);
let body =
- cx.build.GEP(b, ~[C_int(0), C_int(abi::box_rc_field_body)]);
+ cx.build.GEP(b, [C_int(0), C_int(abi::box_rc_field_body)]);
let tydescptr =
cx.build.GEP(body,
- ~[C_int(0), C_int(abi::obj_body_elt_tydesc)]);
+ [C_int(0), C_int(abi::obj_body_elt_tydesc)]);
let tydesc = cx.build.Load(tydescptr);
let ti = none::<@tydesc_info>;
call_tydesc_glue_full(cx, body, tydesc,
abi::tydesc_field_drop_glue, ti);
- if (!bcx_ccx(cx).sess.get_opts().do_gc) {
+ if !bcx_ccx(cx).sess.get_opts().do_gc {
trans_non_gc_free(cx, b)
- } else {
- rslt(cx, C_nil())
- }
+ } else { rslt(cx, C_nil()) }
}
ty::ty_fn(_, _, _, _, _) {
// Call through the closure's own fields-drop glue first.
// Then free the body.
let box_cell =
- cx.build.GEP(v0, ~[C_int(0), C_int(abi::fn_field_box)]);
+ cx.build.GEP(v0, [C_int(0), C_int(abi::fn_field_box)]);
let v = cx.build.Load(box_cell);
let body =
- cx.build.GEP(v, ~[C_int(0), C_int(abi::box_rc_field_body)]);
+ cx.build.GEP(v, [C_int(0), C_int(abi::box_rc_field_body)]);
let bindings =
cx.build.GEP(body,
- ~[C_int(0), C_int(abi::closure_elt_bindings)]);
+ [C_int(0), C_int(abi::closure_elt_bindings)]);
let tydescptr =
cx.build.GEP(body,
- ~[C_int(0), C_int(abi::closure_elt_tydesc)]);
+ [C_int(0), C_int(abi::closure_elt_tydesc)]);
let ti = none::<@tydesc_info>;
call_tydesc_glue_full(cx, bindings, cx.build.Load(tydescptr),
abi::tydesc_field_drop_glue, ti);
- if (!bcx_ccx(cx).sess.get_opts().do_gc) {
+ if !bcx_ccx(cx).sess.get_opts().do_gc {
trans_non_gc_free(cx, v)
- } else {
- rslt(cx, C_nil())
- }
+ } else { rslt(cx, C_nil()) }
}
_ { rslt(cx, C_nil()) }
};
let llunitty = type_of_or_i8(cx, unit_ty);
let stack_len =
cx.build.Load(cx.build.InBoundsGEP(v0,
- ~[C_int(0),
- C_uint(abi::ivec_elt_len)]));
+ [C_int(0),
+ C_uint(abi::ivec_elt_len)]));
let maybe_on_heap_cx = new_sub_block_ctxt(cx, "maybe_on_heap");
let next_cx = new_sub_block_ctxt(cx, "next");
let maybe_on_heap =
maybe_on_heap_cx.build.PointerCast(v0, T_ptr(T_ivec_heap(llunitty)));
let heap_ptr =
{
- let v = ~[C_int(0), C_uint(abi::ivec_heap_stub_elt_ptr)];
+ let v = [C_int(0), C_uint(abi::ivec_heap_stub_elt_ptr)];
let m = maybe_on_heap_cx.build.InBoundsGEP(stub_ptr, v);
maybe_on_heap_cx.build.Load(m)
};
ty::ty_uniq(_) { trans_shared_free(cx, cx.build.Load(v0)) }
ty::ty_obj(_) {
let box_cell =
- cx.build.GEP(v0, ~[C_int(0), C_int(abi::obj_field_box)]);
+ cx.build.GEP(v0, [C_int(0), C_int(abi::obj_field_box)]);
decr_refcnt_maybe_free(cx, box_cell, v0, t)
}
ty::ty_res(did, inner, tps) {
}
ty::ty_fn(_, _, _, _, _) {
let box_cell =
- cx.build.GEP(v0, ~[C_int(0), C_int(abi::fn_field_box)]);
+ cx.build.GEP(v0, [C_int(0), C_int(abi::fn_field_box)]);
decr_refcnt_maybe_free(cx, box_cell, v0, t)
}
_ {
inner_t: ty::t, tps: &[ty::t]) -> result {
let ccx = bcx_ccx(cx);
let inner_t_s = ty::substitute_type_params(ccx.tcx, tps, inner_t);
- let tup_ty = ty::mk_tup(ccx.tcx, ~[ty::mk_int(ccx.tcx), inner_t_s]);
+ let tup_ty = ty::mk_tup(ccx.tcx, [ty::mk_int(ccx.tcx), inner_t_s]);
let drop_cx = new_sub_block_ctxt(cx, "drop res");
let next_cx = new_sub_block_ctxt(cx, "next");
- let drop_flag = GEP_tup_like(cx, tup_ty, rs, ~[0, 0]);
+ let drop_flag = GEP_tup_like(cx, tup_ty, rs, [0, 0]);
cx = drop_flag.bcx;
let null_test = cx.build.IsNull(cx.build.Load(drop_flag.val));
cx.build.CondBr(null_test, next_cx.llbb, drop_cx.llbb);
cx = drop_cx;
- let val = GEP_tup_like(cx, tup_ty, rs, ~[0, 1]);
+ let val = GEP_tup_like(cx, tup_ty, rs, [0, 1]);
cx = val.bcx;
// Find and call the actual destructor.
let dtor_pair = trans_common::get_res_dtor(ccx, cx.sp, did, inner_t);
let dtor_addr =
cx.build.Load(cx.build.GEP(dtor_pair,
- ~[C_int(0), C_int(abi::fn_field_code)]));
+ [C_int(0), C_int(abi::fn_field_code)]));
let dtor_env =
cx.build.Load(cx.build.GEP(dtor_pair,
- ~[C_int(0), C_int(abi::fn_field_box)]));
- let args = ~[cx.fcx.llretptr, cx.fcx.lltaskptr, dtor_env];
- for tp: ty::t in tps {
+ [C_int(0), C_int(abi::fn_field_box)]));
+ let args = [cx.fcx.llretptr, cx.fcx.lltaskptr, dtor_env];
+ for tp: ty::t in tps {
let ti: option::t<@tydesc_info> = none;
let td = get_tydesc(cx, tp, false, ti).result;
- args += ~[td.val];
+ args += [td.val];
cx = td.bcx;
}
// Kludge to work around the fact that we know the precise type of the
// value here, but the dtor expects a type that still has opaque pointers
// for type variables.
let val_llty =
- lib::llvm::fn_ty_param_tys(llvm::LLVMGetElementType
- (llvm::LLVMTypeOf(dtor_addr)))
- .(std::vec::len(args));
+ lib::llvm::fn_ty_param_tys(
+ llvm::LLVMGetElementType(
+ llvm::LLVMTypeOf(dtor_addr)))[std::vec::len(args)];
let val_cast = cx.build.BitCast(val.val, val_llty);
- cx.build.FastCall(dtor_addr, args + ~[val_cast]);
+ cx.build.FastCall(dtor_addr, args + [val_cast]);
cx = drop_slot(cx, val.val, inner_t_s).bcx;
cx.build.Store(C_int(0), drop_flag.val);
cx.build.CondBr(null_test, next_cx.llbb, load_rc_cx.llbb);
let rc_ptr =
load_rc_cx.build.GEP(box_ptr,
- ~[C_int(0), C_int(abi::box_rc_field_refcnt)]);
+ [C_int(0), C_int(abi::box_rc_field_refcnt)]);
let rc = load_rc_cx.build.Load(rc_ptr);
let const_test =
load_rc_cx.build.ICmp(lib::llvm::LLVMIntEQ,
let t_else = T_nil();
let v_else = C_nil();
let phi =
- next_cx.build.Phi(t_else, ~[v_else, v_else, v_else, free_res.val],
- ~[cx.llbb, load_rc_cx.llbb, rc_adj_cx.llbb,
- free_res.bcx.llbb]);
+ next_cx.build.Phi(t_else, [v_else, v_else, v_else, free_res.val],
+ [cx.llbb, load_rc_cx.llbb, rc_adj_cx.llbb,
+ free_res.bcx.llbb]);
ret rslt(next_cx, phi);
}
alt ty::struct(bcx_tcx(cx), t) {
ty::ty_nil. { ret f(nil_type); }
- ty::ty_bool. | ty::ty_uint. | ty::ty_ptr(_) |
- ty::ty_char. { ret f(unsigned_int); }
+ ty::ty_bool. | ty::ty_uint. | ty::ty_ptr(_) | ty::ty_char. {
+ ret f(unsigned_int);
+ }
ty::ty_int. { ret f(signed_int); }
ty::ty_float. { ret f(floating_point); }
ty::ty_machine(_) {
if ty::type_is_fp(bcx_tcx(cx), t) {
// Floating point machine types
ret f(floating_point);
- } else if (ty::type_is_signed(bcx_tcx(cx), t)) {
+ } else if ty::type_is_signed(bcx_tcx(cx), t) {
// Signed, integral machine types
ret f(signed_int);
} else {
let r: ValueRef;
if nt == nil_type {
r = C_bool(op != 0u);
- } else if (nt == floating_point) {
+ } else if nt == floating_point {
r = cx.build.FCmp(op, lhs, rhs);
} else { r = cx.build.ICmp(op, lhs, rhs); }
ret r;
llvm::LLVMAddCase(llswitch, C_u8(abi::cmp_glue_op_lt), lt_cx.llbb);
llvm::LLVMAddCase(llswitch, C_u8(abi::cmp_glue_op_le), le_cx.llbb);
let last_result =
- last_cx.build.Phi(T_i1(), ~[eq_result, lt_result, le_result],
- ~[eq_cx.llbb, lt_cx.llbb, le_cx.llbb]);
+ last_cx.build.Phi(T_i1(), [eq_result, lt_result, le_result],
+ [eq_cx.llbb, lt_cx.llbb, le_cx.llbb]);
ret rslt(last_cx, last_result);
}
-type val_pair_fn = fn(&@block_ctxt, ValueRef, ValueRef) -> result ;
-type val_fn = fn(&@block_ctxt, ValueRef) -> result ;
-type val_and_ty_fn = fn(&@block_ctxt, ValueRef, ty::t) -> result ;
+type val_pair_fn = fn(&@block_ctxt, ValueRef, ValueRef) -> result;
+type val_fn = fn(&@block_ctxt, ValueRef) -> result;
+type val_and_ty_fn = fn(&@block_ctxt, ValueRef, ty::t) -> result;
// Iterates through the elements of a structural type.
fn iter_structural_ty(cx: &@block_ctxt, v: ValueRef, t: &ty::t,
f: val_and_ty_fn) -> result {
- fn adaptor_fn(f: val_and_ty_fn, cx: &@block_ctxt, av: ValueRef,
- t: ty::t) -> result {
+ fn adaptor_fn(f: val_and_ty_fn, cx: &@block_ctxt, av: ValueRef, t: ty::t)
+ -> result {
ret f(cx, av, t);
}
ret iter_structural_ty_full(cx, v, t, bind adaptor_fn(f, _, _, _));
// This uses store and inboundsGEP, but it only doing so superficially; it's
// really storing an incremented pointer to another pointer.
fn incr_ptr(cx: &@block_ctxt, p: ValueRef, incr: ValueRef, pp: ValueRef) {
- cx.build.Store(cx.build.InBoundsGEP(p, ~[incr]), pp);
+ cx.build.Store(cx.build.InBoundsGEP(p, [incr]), pp);
}
fn iter_structural_ty_full(cx: &@block_ctxt, av: ValueRef, t: &ty::t,
f: &val_and_ty_fn) -> result {
- fn iter_boxpp(cx: @block_ctxt, box_cell: ValueRef, f: &val_and_ty_fn)
- -> result {
+ fn iter_boxpp(cx: @block_ctxt, box_cell: ValueRef, f: &val_and_ty_fn) ->
+ result {
let box_ptr = cx.build.Load(box_cell);
let tnil = ty::mk_nil(bcx_tcx(cx));
let tbox = ty::mk_imm_box(bcx_tcx(cx), tnil);
// known to not use pointer casts, which tend to confuse LLVM.
let a_elem_i8 = bcx.build.PointerCast(a_elem, T_ptr(T_i8()));
- let a_end_i8 = bcx.build.GEP(a_elem_i8, ~[len]);
+ let a_end_i8 = bcx.build.GEP(a_elem_i8, [len]);
let a_end = bcx.build.PointerCast(a_end_i8, T_ptr(llunitty));
let dest_elem_ptr = alloca(bcx, T_ptr(llunitty));
loop_header_cx.build.CondBr(not_yet_at_end, loop_body_cx.llbb,
next_cx.llbb);
- rs = f(loop_body_cx,
- load_if_immediate(loop_body_cx, dest_elem, unit_ty), unit_ty);
+ rs =
+ f(loop_body_cx,
+ load_if_immediate(loop_body_cx, dest_elem, unit_ty), unit_ty);
loop_body_cx = rs.bcx;
ty::ty_rec(fields) {
let i: int = 0;
for fld: ty::field in fields {
- r = GEP_tup_like(r.bcx, t, av, ~[0, i]);
+ r = GEP_tup_like(r.bcx, t, av, [0, i]);
let llfld_a = r.val;
- r = f(r.bcx, load_if_immediate(r.bcx, llfld_a, fld.mt.ty),
+ r =
+ f(r.bcx, load_if_immediate(r.bcx, llfld_a, fld.mt.ty),
fld.mt.ty);
i += 1;
}
ty::ty_tup(args) {
let i = 0;
for arg in args {
- r = GEP_tup_like(r.bcx, t, av, ~[0, i]);
+ r = GEP_tup_like(r.bcx, t, av, [0, i]);
let llfld_a = r.val;
r = f(r.bcx, load_if_immediate(r.bcx, llfld_a, arg), arg);
i += 1;
let tcx = bcx_tcx(cx);
let inner1 = ty::substitute_type_params(tcx, tps, inner);
let inner_t_s = ty::substitute_type_params(tcx, tps, inner);
- let tup_t = ty::mk_tup(tcx, ~[ty::mk_int(tcx), inner_t_s]);
- r = GEP_tup_like(r.bcx, tup_t, av, ~[0, 1]);
+ let tup_t = ty::mk_tup(tcx, [ty::mk_int(tcx), inner_t_s]);
+ r = GEP_tup_like(r.bcx, tup_t, av, [0, 1]);
let llfld_a = r.val;
r = f(r.bcx, load_if_immediate(r.bcx, llfld_a, inner1), inner1);
}
// Cast the tags to types we can GEP into.
if n_variants == 1u {
- ret iter_variant(cx, av, variants.(0), tps, tid, f);
+ ret iter_variant(cx, av, variants[0], tps, tid, f);
}
let lltagty = T_opaque_tag_ptr(bcx_ccx(cx).tn);
let av_tag = cx.build.PointerCast(av, lltagty);
- let lldiscrim_a_ptr = cx.build.GEP(av_tag, ~[C_int(0), C_int(0)]);
- let llunion_a_ptr = cx.build.GEP(av_tag, ~[C_int(0), C_int(1)]);
+ let lldiscrim_a_ptr = cx.build.GEP(av_tag, [C_int(0), C_int(0)]);
+ let llunion_a_ptr = cx.build.GEP(av_tag, [C_int(0), C_int(1)]);
let lldiscrim_a = cx.build.Load(lldiscrim_a_ptr);
// NB: we must hit the discriminant first so that structural
"tag-iter-variant-" +
uint::to_str(i, 10u));
llvm::LLVMAddCase(llswitch, C_int(i as int), variant_cx.llbb);
- variant_cx = iter_variant(variant_cx, llunion_a_ptr, variant, tps,
- tid, f).bcx;
+ variant_cx =
+ iter_variant(variant_cx, llunion_a_ptr, variant, tps, tid,
+ f).bcx;
variant_cx.build.Br(next_cx.llbb);
i += 1u;
}
}
ty::ty_fn(_, _, _, _, _) {
let box_cell_a =
- cx.build.GEP(av, ~[C_int(0), C_int(abi::fn_field_box)]);
+ cx.build.GEP(av, [C_int(0), C_int(abi::fn_field_box)]);
ret iter_boxpp(cx, box_cell_a, f);
}
ty::ty_obj(_) {
let box_cell_a =
- cx.build.GEP(av, ~[C_int(0), C_int(abi::obj_field_box)]);
+ cx.build.GEP(av, [C_int(0), C_int(abi::obj_field_box)]);
ret iter_boxpp(cx, box_cell_a, f);
}
ty::ty_vec(unit_tm) { ret iter_ivec(cx, av, unit_tm.ty, f); }
// Iterates through a pointer range, until the src* hits the src_lim*.
fn iter_sequence_raw(cx: @block_ctxt, dst: ValueRef,
- // elt*
- src: ValueRef,
- // elt*
- src_lim: ValueRef,
- // elt*
- elt_sz: ValueRef, f: &val_pair_fn) -> result {
+ src:
+ // elt*
+ ValueRef,
+ src_lim:
+ // elt*
+ ValueRef,
+ elt_sz:
+ // elt*
+ ValueRef, f: &val_pair_fn) -> result {
let bcx = cx;
let dst_int: ValueRef = vp2i(bcx, dst);
let src_int: ValueRef = vp2i(bcx, src);
let next_cx = new_sub_block_ctxt(cx, "next");
bcx.build.Br(cond_cx.llbb);
let dst_curr: ValueRef =
- cond_cx.build.Phi(T_int(), ~[dst_int], ~[bcx.llbb]);
+ cond_cx.build.Phi(T_int(), [dst_int], [bcx.llbb]);
let src_curr: ValueRef =
- cond_cx.build.Phi(T_int(), ~[src_int], ~[bcx.llbb]);
+ cond_cx.build.Phi(T_int(), [src_int], [bcx.llbb]);
let end_test =
cond_cx.build.ICmp(lib::llvm::LLVMIntULT, src_curr, src_lim_int);
cond_cx.build.CondBr(end_test, body_cx.llbb, next_cx.llbb);
let dst_next = body_cx.build.Add(dst_curr, elt_sz);
let src_next = body_cx.build.Add(src_curr, elt_sz);
body_cx.build.Br(cond_cx.llbb);
- cond_cx.build.AddIncomingToPhi(dst_curr, ~[dst_next], ~[body_cx.llbb]);
- cond_cx.build.AddIncomingToPhi(src_curr, ~[src_next], ~[body_cx.llbb]);
+ cond_cx.build.AddIncomingToPhi(dst_curr, [dst_next], [body_cx.llbb]);
+ cond_cx.build.AddIncomingToPhi(src_curr, [src_next], [body_cx.llbb]);
ret rslt(next_cx, C_nil());
}
fn iter_sequence_inner(cx: &@block_ctxt, src: ValueRef,
src_lim:
-
// elt*
ValueRef,
elt_ty: & // elt*
let len;
let bcx;
if !interior {
- p0 = cx.build.GEP(v, ~[C_int(0), C_int(abi::vec_elt_data)]);
- let lp = cx.build.GEP(v, ~[C_int(0), C_int(abi::vec_elt_fill)]);
+ p0 = cx.build.GEP(v, [C_int(0), C_int(abi::vec_elt_data)]);
+ let lp = cx.build.GEP(v, [C_int(0), C_int(abi::vec_elt_fill)]);
len = cx.build.Load(lp);
bcx = cx;
} else {
alt { ti.copy_glue } {
some(_) { }
none. {
- log #fmt("+++ lazily_emit_tydesc_glue TAKE %s",
- ty_to_str(bcx_tcx(cx), ti.ty));
+ log #fmt["+++ lazily_emit_tydesc_glue TAKE %s",
+ ty_to_str(bcx_tcx(cx), ti.ty)];
let lcx = cx.fcx.lcx;
let glue_fn =
declare_generic_glue(lcx, ti.ty, T_glue_fn(*lcx.ccx),
"copy");
ti.copy_glue = some::<ValueRef>(glue_fn);
- make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
- make_copy_glue, ti.ty_params,
- "take");
- log #fmt("--- lazily_emit_tydesc_glue TAKE %s",
- ty_to_str(bcx_tcx(cx), ti.ty));
+ make_generic_glue(lcx, cx.sp, ti.ty, glue_fn, make_copy_glue,
+ ti.ty_params, "take");
+ log #fmt["--- lazily_emit_tydesc_glue TAKE %s",
+ ty_to_str(bcx_tcx(cx), ti.ty)];
}
}
- } else if (field == abi::tydesc_field_drop_glue) {
+ } else if field == abi::tydesc_field_drop_glue {
alt { ti.drop_glue } {
some(_) { }
none. {
- log #fmt("+++ lazily_emit_tydesc_glue DROP %s",
- ty_to_str(bcx_tcx(cx), ti.ty));
+ log #fmt["+++ lazily_emit_tydesc_glue DROP %s",
+ ty_to_str(bcx_tcx(cx), ti.ty)];
let lcx = cx.fcx.lcx;
let glue_fn =
declare_generic_glue(lcx, ti.ty, T_glue_fn(*lcx.ccx),
"drop");
ti.drop_glue = some::<ValueRef>(glue_fn);
- make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
- make_drop_glue, ti.ty_params,
- "drop");
- log #fmt("--- lazily_emit_tydesc_glue DROP %s",
- ty_to_str(bcx_tcx(cx), ti.ty));
+ make_generic_glue(lcx, cx.sp, ti.ty, glue_fn, make_drop_glue,
+ ti.ty_params, "drop");
+ log #fmt["--- lazily_emit_tydesc_glue DROP %s",
+ ty_to_str(bcx_tcx(cx), ti.ty)];
}
}
- } else if (field == abi::tydesc_field_free_glue) {
+ } else if field == abi::tydesc_field_free_glue {
alt { ti.free_glue } {
some(_) { }
none. {
- log #fmt("+++ lazily_emit_tydesc_glue FREE %s",
- ty_to_str(bcx_tcx(cx), ti.ty));
+ log #fmt["+++ lazily_emit_tydesc_glue FREE %s",
+ ty_to_str(bcx_tcx(cx), ti.ty)];
let lcx = cx.fcx.lcx;
let glue_fn =
declare_generic_glue(lcx, ti.ty, T_glue_fn(*lcx.ccx),
"free");
ti.free_glue = some::<ValueRef>(glue_fn);
- make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
- make_free_glue, ti.ty_params,
- "free");
- log #fmt("--- lazily_emit_tydesc_glue FREE %s",
- ty_to_str(bcx_tcx(cx), ti.ty));
+ make_generic_glue(lcx, cx.sp, ti.ty, glue_fn, make_free_glue,
+ ti.ty_params, "free");
+ log #fmt["--- lazily_emit_tydesc_glue FREE %s",
+ ty_to_str(bcx_tcx(cx), ti.ty)];
}
}
- } else if (field == abi::tydesc_field_cmp_glue) {
+ } else if field == abi::tydesc_field_cmp_glue {
alt { ti.cmp_glue } {
some(_) { }
none. {
- log #fmt("+++ lazily_emit_tydesc_glue CMP %s",
- ty_to_str(bcx_tcx(cx), ti.ty));
+ log #fmt["+++ lazily_emit_tydesc_glue CMP %s",
+ ty_to_str(bcx_tcx(cx), ti.ty)];
ti.cmp_glue = some(bcx_ccx(cx).upcalls.cmp_type);
- log #fmt("--- lazily_emit_tydesc_glue CMP %s",
- ty_to_str(bcx_tcx(cx), ti.ty));
+ log #fmt["--- lazily_emit_tydesc_glue CMP %s",
+ ty_to_str(bcx_tcx(cx), ti.ty)];
}
}
}
some(sti) {
if field == abi::tydesc_field_copy_glue {
static_glue_fn = sti.copy_glue;
- } else if (field == abi::tydesc_field_drop_glue) {
+ } else if field == abi::tydesc_field_drop_glue {
static_glue_fn = sti.drop_glue;
- } else if (field == abi::tydesc_field_free_glue) {
+ } else if field == abi::tydesc_field_free_glue {
static_glue_fn = sti.free_glue;
- } else if (field == abi::tydesc_field_cmp_glue) {
+ } else if field == abi::tydesc_field_cmp_glue {
static_glue_fn = sti.cmp_glue;
}
}
let llrawptr = cx.build.BitCast(v, T_ptr(T_i8()));
let lltydescs =
cx.build.GEP(tydesc,
- ~[C_int(0), C_int(abi::tydesc_field_first_param)]);
+ [C_int(0), C_int(abi::tydesc_field_first_param)]);
lltydescs = cx.build.Load(lltydescs);
let llfn;
alt static_glue_fn {
none. {
- let llfnptr = cx.build.GEP(tydesc, ~[C_int(0), C_int(field)]);
+ let llfnptr = cx.build.GEP(tydesc, [C_int(0), C_int(field)]);
llfn = cx.build.Load(llfnptr);
}
some(sgf) { llfn = sgf; }
}
cx.build.Call(llfn,
- ~[C_null(T_ptr(T_nil())), cx.fcx.lltaskptr,
- C_null(T_ptr(T_nil())), lltydescs, llrawptr]);
+ [C_null(T_ptr(T_nil())), cx.fcx.lltaskptr,
+ C_null(T_ptr(T_nil())), lltydescs, llrawptr]);
}
fn call_tydesc_glue(cx: &@block_ctxt, v: ValueRef, t: &ty::t, field: int) ->
let lltydesc = r.val;
let lltydescs =
r.bcx.build.GEP(lltydesc,
- ~[C_int(0), C_int(abi::tydesc_field_first_param)]);
+ [C_int(0), C_int(abi::tydesc_field_first_param)]);
lltydescs = r.bcx.build.Load(lltydescs);
let llfn;
none. {
let llfnptr =
r.bcx.build.GEP(lltydesc,
- ~[C_int(0), C_int(abi::tydesc_field_cmp_glue)]);
+ [C_int(0), C_int(abi::tydesc_field_cmp_glue)]);
llfn = r.bcx.build.Load(llfnptr);
}
some(sti) { llfn = option::get(sti.cmp_glue); }
let llcmpresultptr = alloca(r.bcx, T_i1());
let llargs: [ValueRef] =
- ~[llcmpresultptr, r.bcx.fcx.lltaskptr, lltydesc,
- lltydescs, llrawlhsptr, llrawrhsptr, llop];
+ [llcmpresultptr, r.bcx.fcx.lltaskptr, lltydesc, lltydescs,
+ llrawlhsptr, llrawrhsptr, llop];
r.bcx.build.Call(llfn, llargs);
ret rslt(r.bcx, r.bcx.build.Load(llcmpresultptr));
}
let volatile = C_bool(false);
ret rslt(cx,
cx.build.Call(memmove,
- ~[dst_ptr, src_ptr, size, align, volatile]));
+ [dst_ptr, src_ptr, size, align, volatile]));
}
fn call_bzero(cx: &@block_ctxt, dst: ValueRef, n_bytes: ValueRef,
let volatile = C_bool(false);
ret rslt(cx,
cx.build.Call(memset,
- ~[dst_ptr, C_u8(0u), size, align, volatile]));
+ [dst_ptr, C_u8(0u), size, align, volatile]));
}
fn memmove_ty(cx: &@block_ctxt, dst: ValueRef, src: ValueRef, t: &ty::t) ->
} else if ty::type_is_structural(bcx_tcx(cx), t) {
let llsz = llsize_of(type_of(bcx_ccx(cx), cx.sp, t));
ret call_memmove(cx, dst, src, llsz);
- } else {
- ret rslt(cx, cx.build.Store(cx.build.Load(src), dst));
- }
+ } else { ret rslt(cx, cx.build.Store(cx.build.Load(src), dst)); }
}
// Duplicates any heap-owned memory owned by a value of the given type.
if ty::type_is_scalar(ccx.tcx, t) || ty::type_is_native(ccx.tcx, t) {
ret rslt(cx, cx.build.Store(src, dst));
- } else if (ty::type_is_nil(ccx.tcx, t) || ty::type_is_bot(ccx.tcx, t)) {
+ } else if ty::type_is_nil(ccx.tcx, t) || ty::type_is_bot(ccx.tcx, t) {
ret rslt(cx, C_nil());
- } else if (ty::type_is_boxed(ccx.tcx, t)) {
+ } else if ty::type_is_boxed(ccx.tcx, t) {
let bcx;
if action == DROP_EXISTING {
bcx = drop_ty(cx, cx.build.Load(dst), t).bcx;
} else { bcx = cx; }
bcx = copy_ty(bcx, src, t).bcx;
ret rslt(bcx, bcx.build.Store(src, dst));
- } else if (ty::type_is_structural(ccx.tcx, t) ||
- ty::type_has_dynamic_size(ccx.tcx, t)) {
+ } else if ty::type_is_structural(ccx.tcx, t) ||
+ ty::type_has_dynamic_size(ccx.tcx, t) {
// Check for self-assignment.
let do_copy_cx = new_sub_block_ctxt(cx, "do_copy");
let next_cx = new_sub_block_ctxt(cx, "next");
if src.is_mem { src_val = cx.build.Load(src_val); }
cx.build.Store(src_val, dst);
ret rslt(cx, C_nil());
- } else if (ty::type_is_nil(bcx_tcx(cx), t) ||
- ty::type_is_bot(bcx_tcx(cx), t)) {
+ } else if ty::type_is_nil(bcx_tcx(cx), t) ||
+ ty::type_is_bot(bcx_tcx(cx), t) {
ret rslt(cx, C_nil());
- } else if (ty::type_is_unique(bcx_tcx(cx), t) ||
- ty::type_is_boxed(bcx_tcx(cx), t)) {
+ } else if ty::type_is_unique(bcx_tcx(cx), t) ||
+ ty::type_is_boxed(bcx_tcx(cx), t) {
if src.is_mem { src_val = cx.build.Load(src_val); }
if action == DROP_EXISTING {
cx = drop_ty(cx, cx.build.Load(dst), t).bcx;
// If we're here, it must be a temporary.
revoke_clean(cx, src_val);
ret rslt(cx, C_nil());
- } else if (ty::type_is_structural(bcx_tcx(cx), t) ||
- ty::type_has_dynamic_size(bcx_tcx(cx), t)) {
+ } else if ty::type_is_structural(bcx_tcx(cx), t) ||
+ ty::type_has_dynamic_size(bcx_tcx(cx), t) {
if action == DROP_EXISTING { cx = drop_ty(cx, dst, t).bcx; }
cx = memmove_ty(cx, dst, src_val, t).bcx;
if src.is_mem {
if len < 3u { // 3 because of the \0
cx.build.Store(C_uint(len + 1u),
cx.build.InBoundsGEP(llstackpart,
- ~[C_int(0), C_int(0)]));
+ [C_int(0), C_int(0)]));
cx.build.Store(C_int(4),
cx.build.InBoundsGEP(llstackpart,
- ~[C_int(0), C_int(1)]));
+ [C_int(0), C_int(1)]));
let i = 0u;
while i < len {
- cx.build.Store(C_u8(s.(i) as uint),
+ cx.build.Store(C_u8(s[i] as uint),
cx.build.InBoundsGEP(llstackpart,
- ~[C_int(0), C_int(2),
- C_uint(i)]));
+ [C_int(0), C_int(2),
+ C_uint(i)]));
i += 1u;
}
cx.build.Store(C_u8(0u),
cx.build.InBoundsGEP(llstackpart,
- ~[C_int(0), C_int(2),
- C_uint(len)]));
+ [C_int(0), C_int(2),
+ C_uint(len)]));
bcx = cx;
} else {
let r =
trans_shared_malloc(cx, T_ptr(T_ivec_heap_part(T_i8())),
- llsize_of(T_struct(~[T_int(),
- T_array(T_i8(),
- len + 1u)])));
+ llsize_of(T_struct([T_int(),
+ T_array(T_i8(),
+ len + 1u)])));
bcx = r.bcx;
let llheappart = r.val;
bcx.build.Store(C_uint(len + 1u),
bcx.build.InBoundsGEP(llheappart,
- ~[C_int(0), C_int(0)]));
+ [C_int(0), C_int(0)]));
bcx.build.Store(llvm::LLVMConstString(str::buf(s), len, False),
bcx.build.InBoundsGEP(llheappart,
- ~[C_int(0), C_int(1)]));
+ [C_int(0), C_int(1)]));
let llspilledstackpart =
bcx.build.PointerCast(llstackpart, T_ptr(T_ivec_heap(T_i8())));
bcx.build.Store(C_int(0),
bcx.build.InBoundsGEP(llspilledstackpart,
- ~[C_int(0), C_int(0)]));
+ [C_int(0), C_int(0)]));
bcx.build.Store(C_uint(len + 1u),
bcx.build.InBoundsGEP(llspilledstackpart,
- ~[C_int(0), C_int(1)]));
+ [C_int(0), C_int(1)]));
bcx.build.Store(llheappart,
bcx.build.InBoundsGEP(llspilledstackpart,
- ~[C_int(0), C_int(2)]));
+ [C_int(0), C_int(2)]));
}
ret rslt(bcx, llstackpart);
}
}
-fn trans_compare(cx: &@block_ctxt, op: ast::binop,
- lhs: ValueRef, _lhs_t: ty::t, rhs: ValueRef,
- rhs_t: ty::t) -> result {
+fn trans_compare(cx: &@block_ctxt, op: ast::binop, lhs: ValueRef,
+ _lhs_t: ty::t, rhs: ValueRef, rhs_t: ty::t) -> result {
// Determine the operation we need.
let llop;
alt op {
}
}
-fn trans_evec_append(cx: &@block_ctxt, t: &ty::t,
- lhs: ValueRef, rhs: ValueRef)
- -> result {
+fn trans_evec_append(cx: &@block_ctxt, t: &ty::t, lhs: ValueRef,
+ rhs: ValueRef) -> result {
let elt_ty = ty::sequence_element_type(bcx_tcx(cx), t);
let skip_null = C_bool(false);
alt ty::struct(bcx_tcx(cx), t) {
let src = bcx.build.PointerCast(rhs, T_opaque_vec_ptr());
ret rslt(bcx,
bcx.build.Call(bcx_ccx(cx).upcalls.evec_append,
- ~[cx.fcx.lltaskptr, llvec_tydesc.val,
- llelt_tydesc.val, dst, src, skip_null]));
+ [cx.fcx.lltaskptr, llvec_tydesc.val,
+ llelt_tydesc.val, dst, src, skip_null]));
}
mod ivec {
let llunitty = type_of_or_i8(bcx, unit_ty);
let stack_len =
- load_inbounds(bcx, v, ~[C_int(0), C_uint(abi::ivec_elt_len)]);
+ load_inbounds(bcx, v, [C_int(0), C_uint(abi::ivec_elt_len)]);
let stack_elem =
bcx.build.InBoundsGEP(v,
- ~[C_int(0), C_uint(abi::ivec_elt_elems),
- C_int(0)]);
+ [C_int(0), C_uint(abi::ivec_elt_elems),
+ C_int(0)]);
let on_heap =
bcx.build.ICmp(lib::llvm::LLVMIntEQ, stack_len, C_int(0));
let on_heap_cx = new_sub_block_ctxt(bcx, "on_heap");
on_heap_cx.build.PointerCast(v, T_ptr(T_ivec_heap(llunitty)));
let heap_ptr =
load_inbounds(on_heap_cx, heap_stub,
- ~[C_int(0), C_uint(abi::ivec_heap_stub_elt_ptr)]);
+ [C_int(0), C_uint(abi::ivec_heap_stub_elt_ptr)]);
// Check whether the heap pointer is null. If it is, the vector length
// is truly zero.
let heap_len =
load_inbounds(nonzero_len_cx, heap_ptr,
- ~[C_int(0), C_uint(abi::ivec_heap_elt_len)]);
+ [C_int(0), C_uint(abi::ivec_heap_elt_len)]);
let heap_elem =
{
let v =
- ~[C_int(0), C_uint(abi::ivec_heap_elt_elems), C_int(0)];
+ [C_int(0), C_uint(abi::ivec_heap_elt_elems), C_int(0)];
nonzero_len_cx.build.InBoundsGEP(heap_ptr, v)
};
// first element.
let len =
- next_cx.build.Phi(T_int(), ~[stack_len, zero_len, heap_len],
- ~[bcx.llbb, zero_len_cx.llbb,
- nonzero_len_cx.llbb]);
+ next_cx.build.Phi(T_int(), [stack_len, zero_len, heap_len],
+ [bcx.llbb, zero_len_cx.llbb,
+ nonzero_len_cx.llbb]);
let elem =
next_cx.build.Phi(T_ptr(llunitty),
- ~[stack_elem, zero_elem, heap_elem],
- ~[bcx.llbb, zero_len_cx.llbb,
- nonzero_len_cx.llbb]);
+ [stack_elem, zero_elem, heap_elem],
+ [bcx.llbb, zero_len_cx.llbb,
+ nonzero_len_cx.llbb]);
ret {len: len, data: elem, bcx: next_cx};
}
fn reserve_space(cx: &@block_ctxt, llunitty: TypeRef, v: ValueRef,
len_needed: ValueRef) -> result {
let stack_len_ptr =
- cx.build.InBoundsGEP(v, ~[C_int(0), C_uint(abi::ivec_elt_len)]);
+ cx.build.InBoundsGEP(v, [C_int(0), C_uint(abi::ivec_elt_len)]);
let stack_len = cx.build.Load(stack_len_ptr);
let alen =
- load_inbounds(cx, v, ~[C_int(0), C_uint(abi::ivec_elt_alen)]);
+ load_inbounds(cx, v, [C_int(0), C_uint(abi::ivec_elt_alen)]);
// There are four cases we have to consider:
// (1) On heap, no resize necessary.
// (2) On heap, need to resize.
let next_cx = new_sub_block_ctxt(cx, "next");
// We're possibly on the heap, unless the vector is zero-length.
- let stub_p = ~[C_int(0), C_uint(abi::ivec_heap_stub_elt_ptr)];
+ let stub_p = [C_int(0), C_uint(abi::ivec_heap_stub_elt_ptr)];
let stub_ptr =
maybe_on_heap_cx.build.PointerCast(v,
T_ptr(T_ivec_heap(llunitty)));
let heap_len_ptr =
on_heap_cx.build.InBoundsGEP(heap_ptr,
- ~[C_int(0),
- C_uint(abi::ivec_heap_elt_len)]);
+ [C_int(0),
+ C_uint(abi::ivec_heap_elt_len)]);
let heap_len = on_heap_cx.build.Load(heap_len_ptr);
let new_heap_len = on_heap_cx.build.Add(heap_len, len_needed);
let heap_len_unscaled =
let heap_data_no_resize =
{
let v =
- ~[C_int(0), C_uint(abi::ivec_heap_elt_elems),
- heap_len_unscaled];
+ [C_int(0), C_uint(abi::ivec_heap_elt_elems),
+ heap_len_unscaled];
heap_no_resize_cx.build.InBoundsGEP(heap_ptr, v)
};
heap_no_resize_cx.build.Store(new_heap_len, heap_len_ptr);
heap_resize_cx.build.PointerCast(v, T_ptr(T_opaque_ivec()));
let upcall = bcx_ccx(cx).upcalls.ivec_resize_shared;
heap_resize_cx.build.Call(upcall,
- ~[cx.fcx.lltaskptr, p, new_heap_len]);
+ [cx.fcx.lltaskptr, p, new_heap_len]);
}
let heap_ptr_resize = load_inbounds(heap_resize_cx, stub_ptr, stub_p);
let heap_data_resize =
{
let v =
- ~[C_int(0), C_uint(abi::ivec_heap_elt_elems),
- heap_len_unscaled];
+ [C_int(0), C_uint(abi::ivec_heap_elt_elems),
+ heap_len_unscaled];
heap_resize_cx.build.InBoundsGEP(heap_ptr_resize, v)
};
heap_resize_cx.build.Br(next_cx.llbb);
let stack_data_no_spill =
stack_no_spill_cx.build.InBoundsGEP(v,
- ~[C_int(0),
- C_uint(abi::ivec_elt_elems),
- stack_len_unscaled]);
+ [C_int(0),
+ C_uint(abi::ivec_elt_elems),
+ stack_len_unscaled]);
stack_no_spill_cx.build.Store(new_stack_len, stack_len_ptr);
stack_no_spill_cx.build.Br(next_cx.llbb);
// Case (4): We're on the stack and need to spill. Like case (2), this
stack_spill_cx.build.PointerCast(v, T_ptr(T_opaque_ivec()));
let upcall = bcx_ccx(cx).upcalls.ivec_spill_shared;
stack_spill_cx.build.Call(upcall,
- ~[cx.fcx.lltaskptr, p, new_stack_len]);
+ [cx.fcx.lltaskptr, p, new_stack_len]);
}
let spill_stub =
stack_spill_cx.build.PointerCast(v, T_ptr(T_ivec_heap(llunitty)));
let heap_data_spill =
{
let v =
- ~[C_int(0), C_uint(abi::ivec_heap_elt_elems),
- stack_len_unscaled];
+ [C_int(0), C_uint(abi::ivec_heap_elt_elems),
+ stack_len_unscaled];
stack_spill_cx.build.InBoundsGEP(heap_ptr_spill, v)
};
stack_spill_cx.build.Br(next_cx.llbb);
let data_ptr =
next_cx.build.Phi(T_ptr(llunitty),
- ~[heap_data_no_resize, heap_data_resize,
- stack_data_no_spill, heap_data_spill],
- ~[heap_no_resize_cx.llbb, heap_resize_cx.llbb,
- stack_no_spill_cx.llbb, stack_spill_cx.llbb]);
+ [heap_data_no_resize, heap_data_resize,
+ stack_data_no_spill, heap_data_spill],
+ [heap_no_resize_cx.llbb, heap_resize_cx.llbb,
+ stack_no_spill_cx.llbb, stack_spill_cx.llbb]);
ret rslt(next_cx, data_ptr);
}
fn trans_append(cx: &@block_ctxt, t: &ty::t, orig_lhs: ValueRef,
// Work out the end pointer.
let lhs_unscaled_idx = bcx.build.UDiv(rhs_len, llsize_of(llunitty));
- let lhs_end = bcx.build.InBoundsGEP(lhs_data, ~[lhs_unscaled_idx]);
+ let lhs_end = bcx.build.InBoundsGEP(lhs_data, [lhs_unscaled_idx]);
// Now emit the copy loop.
let dest_ptr = alloca(bcx, T_ptr(llunitty));
bcx.build.CondBr(len_is_zero, zero_len_cx.llbb, nonzero_len_cx.llbb);
// Case (1): Length is zero.
- let stub_z = ~[C_int(0), C_uint(abi::ivec_heap_stub_elt_zero)];
- let stub_a = ~[C_int(0), C_uint(abi::ivec_heap_stub_elt_alen)];
- let stub_p = ~[C_int(0), C_uint(abi::ivec_heap_stub_elt_ptr)];
+ let stub_z = [C_int(0), C_uint(abi::ivec_heap_stub_elt_zero)];
+ let stub_a = [C_int(0), C_uint(abi::ivec_heap_stub_elt_alen)];
+ let stub_p = [C_int(0), C_uint(abi::ivec_heap_stub_elt_ptr)];
- let vec_l = ~[C_int(0), C_uint(abi::ivec_elt_len)];
- let vec_a = ~[C_int(0), C_uint(abi::ivec_elt_alen)];
+ let vec_l = [C_int(0), C_uint(abi::ivec_elt_len)];
+ let vec_a = [C_int(0), C_uint(abi::ivec_elt_alen)];
let stub_ptr_zero =
zero_len_cx.build.PointerCast(llvecptr,
stack_cx.build.InBoundsGEP(llvecptr, vec_a));
let dest_ptr_stack =
stack_cx.build.InBoundsGEP(llvecptr,
- ~[C_int(0),
- C_uint(abi::ivec_elt_elems),
- C_int(0)]);
+ [C_int(0), C_uint(abi::ivec_elt_elems),
+ C_int(0)]);
let copy_cx = new_sub_block_ctxt(bcx, "copy");
stack_cx.build.Br(copy_cx.llbb);
// Case (3): Allocate on heap and copy there.
heap_cx.build.Store(heap_part,
heap_cx.build.InBoundsGEP(stub_ptr_heap, stub_p));
{
- let v = ~[C_int(0), C_uint(abi::ivec_heap_elt_len)];
+ let v = [C_int(0), C_uint(abi::ivec_heap_elt_len)];
heap_cx.build.Store(lllen,
heap_cx.build.InBoundsGEP(heap_part, v));
}
let dest_ptr_heap =
heap_cx.build.InBoundsGEP(heap_part,
- ~[C_int(0),
- C_uint(abi::ivec_heap_elt_elems),
- C_int(0)]);
+ [C_int(0),
+ C_uint(abi::ivec_heap_elt_elems),
+ C_int(0)]);
heap_cx.build.Br(copy_cx.llbb);
// Emit the copy loop.
let first_dest_ptr =
copy_cx.build.Phi(T_ptr(llunitty),
- ~[dest_ptr_stack, dest_ptr_heap],
- ~[stack_cx.llbb, heap_cx.llbb]);
+ [dest_ptr_stack, dest_ptr_heap],
+ [stack_cx.llbb, heap_cx.llbb]);
let lhs_end_ptr;
let rhs_end_ptr;
if ty::type_has_dynamic_size(bcx_tcx(cx), unit_ty) {
- lhs_end_ptr = copy_cx.build.InBoundsGEP(lhs_data, ~[lhs_len]);
- rhs_end_ptr = copy_cx.build.InBoundsGEP(rhs_data, ~[rhs_len]);
+ lhs_end_ptr = copy_cx.build.InBoundsGEP(lhs_data, [lhs_len]);
+ rhs_end_ptr = copy_cx.build.InBoundsGEP(rhs_data, [rhs_len]);
} else {
let lhs_len_unscaled = copy_cx.build.UDiv(lhs_len, unit_sz);
lhs_end_ptr =
- copy_cx.build.InBoundsGEP(lhs_data, ~[lhs_len_unscaled]);
+ copy_cx.build.InBoundsGEP(lhs_data, [lhs_len_unscaled]);
let rhs_len_unscaled = copy_cx.build.UDiv(rhs_len, unit_sz);
rhs_end_ptr =
- copy_cx.build.InBoundsGEP(rhs_data, ~[rhs_len_unscaled]);
+ copy_cx.build.InBoundsGEP(rhs_data, [rhs_len_unscaled]);
}
let dest_ptr_ptr = alloca(copy_cx, T_ptr(llunitty));
// Check to see if the vector is heapified.
let stack_len_ptr =
- cx.build.InBoundsGEP(vptr,
- ~[C_int(0), C_uint(abi::ivec_elt_len)]);
+ cx.build.InBoundsGEP(vptr, [C_int(0), C_uint(abi::ivec_elt_len)]);
let stack_len = cx.build.Load(stack_len_ptr);
let stack_len_is_zero =
cx.build.ICmp(lib::llvm::LLVMIntEQ, stack_len, C_int(0));
maybe_on_heap_cx.build.PointerCast(vptr,
T_ptr(T_ivec_heap(llunitty)));
let heap_ptr_ptr =
- maybe_on_heap_cx.build.InBoundsGEP
- (stub_ptr, ~[C_int(0), C_uint(abi::ivec_heap_stub_elt_ptr)]);
+ maybe_on_heap_cx.build.InBoundsGEP(
+ stub_ptr,
+ [C_int(0),
+ C_uint(abi::ivec_heap_stub_elt_ptr)]);
let heap_ptr = maybe_on_heap_cx.build.Load(heap_ptr_ptr);
let heap_ptr_is_nonnull =
maybe_on_heap_cx.build.ICmp(lib::llvm::LLVMIntNE, heap_ptr,
// Ok, the vector is on the heap. Copy the heap part.
let alen_ptr =
- on_heap_cx.build.InBoundsGEP
- (stub_ptr, ~[C_int(0), C_uint(abi::ivec_heap_stub_elt_alen)]);
+ on_heap_cx.build.InBoundsGEP(
+ stub_ptr,
+ [C_int(0),
+ C_uint(abi::ivec_heap_stub_elt_alen)]);
let alen = on_heap_cx.build.Load(alen_ptr);
let heap_part_sz =
}
}
-fn trans_evec_add(cx: &@block_ctxt, t: &ty::t,
- lhs: ValueRef, rhs: ValueRef) ->
- result {
+fn trans_evec_add(cx: &@block_ctxt, t: &ty::t, lhs: ValueRef, rhs: ValueRef)
+ -> result {
let r = alloc_ty(cx, t);
let tmp = r.val;
r = copy_val(r.bcx, INIT, tmp, lhs, t);
// If either is bottom, it diverges. So no need to do the
// operation.
- if (ty::type_is_bot(bcx_tcx(cx), lhs_t) ||
- ty::type_is_bot(bcx_tcx(cx), rhs_t)) {
+ if ty::type_is_bot(bcx_tcx(cx), lhs_t) ||
+ ty::type_is_bot(bcx_tcx(cx), rhs_t) {
ret rslt(cx, cx.build.Unreachable());
}
let is_float = false;
let intype = lhs_t;
- if ty::type_is_bot(bcx_tcx(cx), intype) {
- intype = rhs_t;
- }
+ if ty::type_is_bot(bcx_tcx(cx), intype) { intype = rhs_t; }
alt ty::struct(bcx_tcx(cx), intype) {
ty::ty_float. { is_float = true; }
alt ty::struct(ccx.tcx, t1) {
ty::ty_box(mt) {
let body =
- cx.build.GEP(v1, ~[C_int(0), C_int(abi::box_rc_field_body)]);
+ cx.build.GEP(v1, [C_int(0), C_int(abi::box_rc_field_body)]);
t1 = mt.ty;
// Since we're changing levels of box indirection, we may have
ty::ty_uniq(t) { fail "autoderef uniq unimplemented"; }
ty::ty_res(did, inner, tps) {
t1 = ty::substitute_type_params(ccx.tcx, tps, inner);
- v1 = cx.build.GEP(v1, ~[C_int(0), C_int(1)]);
+ v1 = cx.build.GEP(v1, [C_int(0), C_int(1)]);
}
ty::ty_tag(did, tps) {
let variants = ty::tag_variants(ccx.tcx, did);
if std::vec::len(variants) != 1u ||
- std::vec::len(variants.(0).args) != 1u {
+ std::vec::len(variants[0].args) != 1u {
break;
}
t1 =
- ty::substitute_type_params(ccx.tcx, tps,
- variants.(0).args.(0));
+ ty::substitute_type_params(ccx.tcx, tps, variants[0].args[0]);
if !ty::type_has_dynamic_size(ccx.tcx, t1) {
v1 = cx.build.PointerCast(v1, T_ptr(type_of(ccx, cx.sp, t1)));
}
fn trans_binary(cx: &@block_ctxt, op: ast::binop, a: &@ast::expr,
b: &@ast::expr) -> result {
+
// First couple cases are lazy:
alt op {
ast::and. {
let rhs_bcx = trans_block_cleanups(rhs_res.bcx, rhs_cx);
lhs_res.bcx.build.CondBr(lhs_res.val, rhs_cx.llbb, lhs_false_cx.llbb);
ret join_results(cx, T_bool(),
- ~[lhs_false_res, {bcx: rhs_bcx, val: rhs_res.val}]);
+ [lhs_false_res, {bcx: rhs_bcx, val: rhs_res.val}]);
}
ast::or. {
// Lazy-eval or
let rhs_bcx = trans_block_cleanups(rhs_res.bcx, rhs_cx);
lhs_res.bcx.build.CondBr(lhs_res.val, lhs_true_cx.llbb, rhs_cx.llbb);
ret join_results(cx, T_bool(),
- ~[lhs_true_res, {bcx: rhs_bcx, val: rhs_res.val}]);
+ [lhs_true_res, {bcx: rhs_bcx, val: rhs_res.val}]);
}
_ {
// Remaining cases are eager:
let lhs = trans_expr(cx, a);
let rhs = trans_expr(lhs.bcx, b);
- ret trans_eager_binop(rhs.bcx, op,
- lhs.val, ty::expr_ty(bcx_tcx(cx), a),
- rhs.val, ty::expr_ty(bcx_tcx(cx), b));
+ ret trans_eager_binop(rhs.bcx, op, lhs.val,
+ ty::expr_ty(bcx_tcx(cx), a), rhs.val,
+ ty::expr_ty(bcx_tcx(cx), b));
}
}
}
fn join_results(parent_cx: &@block_ctxt, t: TypeRef, ins: &[result]) ->
result {
- let live: [result] = ~[];
- let vals: [ValueRef] = ~[];
- let bbs: [BasicBlockRef] = ~[];
+ let live: [result] = [];
+ let vals: [ValueRef] = [];
+ let bbs: [BasicBlockRef] = [];
for r: result in ins {
if !is_terminated(r.bcx) {
- live += ~[r];
- vals += ~[r.val];
- bbs += ~[r.bcx.llbb];
+ live += [r];
+ vals += [r.val];
+ bbs += [r.bcx.llbb];
}
}
alt std::vec::len::<result>(live) {
// is just going to propagate it outward.
assert (std::vec::len::<result>(ins) >= 1u);
- ret ins.(0);
+ ret ins[0];
}
_ {/* fall through */ }
}
tag out_method { return; save_in(ValueRef); }
fn trans_if(cx: &@block_ctxt, cond: &@ast::expr, thn: &ast::blk,
- els: &option::t<@ast::expr>, output: &out_method)
- -> result {
+ els: &option::t<@ast::expr>, output: &out_method) -> result {
let cond_res = trans_expr(cx, cond);
- if (ty::type_is_bot(bcx_tcx(cx), ty::expr_ty(bcx_tcx(cx), cond))) {
+ if ty::type_is_bot(bcx_tcx(cx), ty::expr_ty(bcx_tcx(cx), cond)) {
+
// No need to generate code for comparison,
// since the cond diverges.
- if (!cx.build.is_terminated()) {
+ if !cx.build.is_terminated() {
ret rslt(cx, cx.build.Unreachable());
- }
- else {
- ret cond_res;
- }
+ } else { ret cond_res; }
}
let then_cx = new_scope_block_ctxt(cx, "then");
_ { rslt(else_cx, C_nil()) }
};
cond_res.bcx.build.CondBr(cond_res.val, then_cx.llbb, else_cx.llbb);
- ret rslt(join_branches(cx, ~[then_res, else_res]), C_nil());
+ ret rslt(join_branches(cx, [then_res, else_res]), C_nil());
}
fn trans_for(cx: &@block_ctxt, local: &@ast::local, seq: &@ast::expr,
let local_res = alloc_local(scope_cx, local);
let loc_r = copy_val(local_res.bcx, INIT, local_res.val, curr, t);
add_clean(scope_cx, local_res.val, t);
- let bcx = trans_alt::bind_irrefutable_pat
- (loc_r.bcx, local.node.pat, local_res.val, cx.fcx.lllocals, false);
+ let bcx =
+ trans_alt::bind_irrefutable_pat(loc_r.bcx, local.node.pat,
+ local_res.val, cx.fcx.lllocals,
+ false);
bcx = trans_block(bcx, body, return).bcx;
if !bcx.build.is_terminated() {
bcx.build.Br(next_cx.llbb);
// Otherwise, it is stack allocated and copies pointers to the upvars.
fn build_environment(bcx: @block_ctxt, lltydescs: [ValueRef],
bound_tys: [ty::t], bound_vals: [lval_result],
- copying: bool)
- -> {ptr: ValueRef, ptrty: ty::t, bcx: @block_ctxt} {
+ copying: bool) ->
+ {ptr: ValueRef, ptrty: ty::t, bcx: @block_ctxt} {
// Synthesize a closure type.
// First, synthesize a tuple type containing the types of all the
// (We'll need room for that many tydescs in the closure.)
let ty_param_count = std::vec::len(lltydescs);
let tydesc_ty: ty::t = ty::mk_type(bcx_tcx(bcx));
- let captured_tys: [ty::t] =
- std::vec::init_elt(tydesc_ty, ty_param_count);
+ let captured_tys: [ty::t] = std::vec::init_elt(tydesc_ty, ty_param_count);
// Get all the types we've got (some of which we synthesized
// ourselves) into a vector. The whole things ends up looking
// closure_tys = [tydesc_ty, [bound_ty1, bound_ty2, ...], [tydesc_ty,
// tydesc_ty, ...]]
let closure_tys: [ty::t] =
- ~[tydesc_ty, bindings_ty, ty::mk_tup(bcx_tcx(bcx), captured_tys)];
+ [tydesc_ty, bindings_ty, ty::mk_tup(bcx_tcx(bcx), captured_tys)];
// Finally, synthesize a type for that whole vector.
let closure_ty: ty::t = ty::mk_tup(bcx_tcx(bcx), closure_tys);
// Allocate a box that can hold something closure-sized.
- let r = if copying {
- trans_malloc_boxed(bcx, closure_ty)
- } else {
- // We need to dummy up a box on the stack
- let ty = ty::mk_tup(bcx_tcx(bcx),
- ~[ty::mk_int(bcx_tcx(bcx)), closure_ty]);
- let r = alloc_ty(bcx, ty);
- let body = GEPi(bcx, r.val, ~[0, abi::box_rc_field_body]);
- {bcx: r.bcx, box: r.val, body: body}
- };
+ let r =
+ if copying {
+ trans_malloc_boxed(bcx, closure_ty)
+ } else {
+ // We need to dummy up a box on the stack
+ let ty =
+ ty::mk_tup(bcx_tcx(bcx),
+ [ty::mk_int(bcx_tcx(bcx)), closure_ty]);
+ let r = alloc_ty(bcx, ty);
+ let body = GEPi(bcx, r.val, [0, abi::box_rc_field_body]);
+ {bcx: r.bcx, box: r.val, body: body}
+ };
bcx = r.bcx;
let closure = r.body;
// Store bindings tydesc.
if copying {
- let bound_tydesc = GEPi(bcx, closure, ~[0, abi::closure_elt_tydesc]);
+ let bound_tydesc = GEPi(bcx, closure, [0, abi::closure_elt_tydesc]);
let ti = none;
let bindings_tydesc = get_tydesc(bcx, bindings_ty, true, ti).result;
lazily_emit_tydesc_glue(bcx, abi::tydesc_field_drop_glue, ti);
let i = 0u;
let bindings =
GEP_tup_like(bcx, closure_ty, closure,
- ~[0, abi::closure_elt_bindings]);
+ [0, abi::closure_elt_bindings]);
bcx = bindings.bcx;
for lv: lval_result in bound_vals {
- let bound = GEP_tup_like(bcx, bindings_ty, bindings.val,
- ~[0, i as int]);
+ let bound =
+ GEP_tup_like(bcx, bindings_ty, bindings.val, [0, i as int]);
bcx = bound.bcx;
if copying {
- bcx = move_val_if_temp(bcx, INIT,
- bound.val, lv, bound_tys.(i)).bcx;
- } else {
- bcx.build.Store(lv.res.val, bound.val);
- }
+ bcx =
+ move_val_if_temp(bcx, INIT, bound.val, lv, bound_tys[i]).bcx;
+ } else { bcx.build.Store(lv.res.val, bound.val); }
i += 1u;
}
// appropriate slot in the closure.
let ty_params_slot =
GEP_tup_like(bcx, closure_ty, closure,
- ~[0, abi::closure_elt_ty_params]);
+ [0, abi::closure_elt_ty_params]);
bcx = ty_params_slot.bcx;
i = 0u;
for td: ValueRef in lltydescs {
- let ty_param_slot = GEPi(bcx, ty_params_slot.val, ~[0, i as int]);
+ let ty_param_slot = GEPi(bcx, ty_params_slot.val, [0, i as int]);
bcx.build.Store(td, ty_param_slot);
i += 1u;
}
// Given a context and a list of upvars, build a closure. This just
// collects the upvars and packages them up for build_environment.
-fn build_closure(cx: &@block_ctxt, upvars: &@[ast::node_id], copying: bool)
- -> {ptr: ValueRef, ptrty: ty::t, bcx: @block_ctxt} {
- let closure_vals: [lval_result] = ~[];
- let closure_tys: [ty::t] = ~[];
- // If we need to, package up the iterator body to call
- if !copying && !option::is_none(cx.fcx.lliterbody) {
- closure_vals += ~[lval_mem(cx, option::get(cx.fcx.lliterbody))];
- closure_tys += ~[option::get(cx.fcx.iterbodyty)];
- }
- // Package up the upvars
- for nid: ast::node_id in *upvars {
- closure_vals += ~[trans_var(cx, cx.sp, nid)];
- let ty = ty::node_id_to_monotype(bcx_tcx(cx), nid);
- if !copying { ty = ty::mk_mut_ptr(bcx_tcx(cx), ty); }
- closure_tys += ~[ty];
- }
+fn build_closure(cx: &@block_ctxt, upvars: &@[ast::node_id], copying: bool) ->
+ {ptr: ValueRef, ptrty: ty::t, bcx: @block_ctxt} {
+ let closure_vals: [lval_result] = [];
+ let closure_tys: [ty::t] = [];
+ // If we need to, package up the iterator body to call
+ if !copying && !option::is_none(cx.fcx.lliterbody) {
+ closure_vals += [lval_mem(cx, option::get(cx.fcx.lliterbody))];
+ closure_tys += [option::get(cx.fcx.iterbodyty)];
+ }
+ // Package up the upvars
+ for nid: ast::node_id in *upvars {
+ closure_vals += [trans_var(cx, cx.sp, nid)];
+ let ty = ty::node_id_to_monotype(bcx_tcx(cx), nid);
+ if !copying { ty = ty::mk_mut_ptr(bcx_tcx(cx), ty); }
+ closure_tys += [ty];
+ }
- ret build_environment(cx, cx.fcx.lltydescs,
- closure_tys, closure_vals, copying);
+ ret build_environment(cx, cx.fcx.lltydescs, closure_tys, closure_vals,
+ copying);
}
// Return a pointer to the stored typarams in a closure.
fn find_environment_tydescs(bcx: &@block_ctxt, envty: &ty::t,
closure: ValueRef) -> ValueRef {
ret if !ty::type_has_dynamic_size(bcx_tcx(bcx), envty) {
- // If we can find the typarams statically, do it
- GEPi(bcx, closure,
- ~[0, abi::box_rc_field_body, abi::closure_elt_ty_params])
- } else {
- // Ugh. We need to load the size of the bindings out of the
- // closure's tydesc and use that to skip over the bindings.
- let descsty =
- ty::get_element_type(bcx_tcx(bcx), envty,
- abi::closure_elt_ty_params as uint);
- let llenv = GEPi(bcx, closure, ~[0, abi::box_rc_field_body]);
- // Load the tydesc and find the size of the body
- let lldesc =
- bcx.build.Load(GEPi(bcx, llenv, ~[0, abi::closure_elt_tydesc]));
- let llsz = bcx.build.Load(
- GEPi(bcx, lldesc, ~[0, abi::tydesc_field_size]));
- // Get the bindings pointer and add the size to it
- let llbinds = GEPi(bcx, llenv, ~[0, abi::closure_elt_bindings]);
- bump_ptr(bcx, descsty, llbinds, llsz)
- }
+ // If we can find the typarams statically, do it
+ GEPi(bcx, closure,
+ [0, abi::box_rc_field_body, abi::closure_elt_ty_params])
+ } else {
+ // Ugh. We need to load the size of the bindings out of the
+ // closure's tydesc and use that to skip over the bindings.
+ let descsty =
+ ty::get_element_type(bcx_tcx(bcx), envty,
+ abi::closure_elt_ty_params as uint);
+ let llenv = GEPi(bcx, closure, [0, abi::box_rc_field_body]);
+ // Load the tydesc and find the size of the body
+ let lldesc =
+ bcx.build.Load(GEPi(bcx, llenv,
+ [0, abi::closure_elt_tydesc]));
+ let llsz =
+ bcx.build.Load(GEPi(bcx, lldesc,
+ [0, abi::tydesc_field_size]));
+
+ // Get the bindings pointer and add the size to it
+ let llbinds = GEPi(bcx, llenv, [0, abi::closure_elt_bindings]);
+ bump_ptr(bcx, descsty, llbinds, llsz)
+ }
}
// Given an enclosing block context, a new function context, a closure type,
// and a list of upvars, generate code to load and populate the environment
// with the upvars and type descriptors.
-fn load_environment(enclosing_cx: &@block_ctxt, fcx: &@fn_ctxt,
- envty: &ty::t, upvars: &@[ast::node_id],
- copying: bool) {
+fn load_environment(enclosing_cx: &@block_ctxt, fcx: &@fn_ctxt, envty: &ty::t,
+ upvars: &@[ast::node_id], copying: bool) {
let bcx = new_raw_block_ctxt(fcx, fcx.llcopyargs);
let ty = ty::mk_imm_box(bcx_tcx(bcx), envty);
let lltydescs = find_environment_tydescs(bcx, envty, llclosure);
let i = 0u;
while i < tydesc_count {
- let lltydescptr = GEPi(bcx, lltydescs, ~[0, i as int]);
- fcx.lltydescs += ~[bcx.build.Load(lltydescptr)];
+ let lltydescptr = GEPi(bcx, lltydescs, [0, i as int]);
+ fcx.lltydescs += [bcx.build.Load(lltydescptr)];
i += 1u;
}
// Populate the upvars from the environment.
- let path = ~[0, abi::box_rc_field_body, abi::closure_elt_bindings];
+ let path = [0, abi::box_rc_field_body, abi::closure_elt_bindings];
i = 0u;
// If this is an aliasing closure/for-each body, we need to load
// the iterbody.
if !copying && !option::is_none(enclosing_cx.fcx.lliterbody) {
- let iterbodyptr = GEP_tup_like(bcx, ty, llclosure, path + ~[0]);
+ let iterbodyptr = GEP_tup_like(bcx, ty, llclosure, path + [0]);
fcx.lliterbody = some(bcx.build.Load(iterbodyptr.val));
bcx = iterbodyptr.bcx;
i += 1u;
}
+
// Load the acutal upvars.
for upvar_id: ast::node_id in *upvars {
- let upvarptr =
- GEP_tup_like(bcx, ty, llclosure, path + ~[i as int]);
+ let upvarptr = GEP_tup_like(bcx, ty, llclosure, path + [i as int]);
bcx = upvarptr.bcx;
let llupvarptr = upvarptr.val;
if !copying { llupvarptr = bcx.build.Load(llupvarptr); }
let bcx = new_top_block_ctxt(fcx);
// Add bindings for the loop variable alias.
- bcx = trans_alt::bind_irrefutable_pat
- (bcx, local.node.pat, llvm::LLVMGetParam(fcx.llfn, 3u),
- bcx.fcx.lllocals, false);
+ bcx =
+ trans_alt::bind_irrefutable_pat(bcx, local.node.pat,
+ llvm::LLVMGetParam(fcx.llfn, 3u),
+ bcx.fcx.lllocals, false);
let lltop = bcx.llbb;
let r = trans_block(bcx, body, return);
finish_fn(fcx, lltop);
// This is kind of ridiculous, but no permutations
// involving body_res or body_cx.val worked.
let rs = trans_block(cx, body, return);
- if ! is_terminated (next_cx) {
- next_cx.build.Unreachable();
- }
- if ! is_terminated (body_cx) {
- body_cx.build.Unreachable();
- }
+ if !is_terminated(next_cx) { next_cx.build.Unreachable(); }
+ if !is_terminated(body_cx) { body_cx.build.Unreachable(); }
ret rs;
}
let cond_res = trans_expr(body_res.bcx, cond);
let tys = ty::node_id_to_type_params(bcx_tcx(cx), id);
if std::vec::len::<ty::t>(tys) != 0u {
let bcx = lv.res.bcx;
- let tydescs: [ValueRef] = ~[];
- let tis: [option::t<@tydesc_info>] = ~[];
+ let tydescs: [ValueRef] = [];
+ let tis: [option::t<@tydesc_info>] = [];
for t: ty::t in tys {
// TODO: Doesn't always escape.
let ti = none::<@tydesc_info>;
let td = get_tydesc(bcx, t, true, ti).result;
- tis += ~[ti];
+ tis += [ti];
bcx = td.bcx;
- tydescs += ~[td.val];
+ tydescs += [td.val];
}
let gen = {item_type: tpt.ty, static_tis: tis, tydescs: tydescs};
lv = {res: rslt(bcx, lv.res.val), generic: some(gen) with lv};
}
}
-fn trans_var(cx: &@block_ctxt, sp: &span, id: ast::node_id) ->
- lval_result {
+fn trans_var(cx: &@block_ctxt, sp: &span, id: ast::node_id) -> lval_result {
let ccx = bcx_ccx(cx);
alt freevars::def_lookup(bcx_tcx(cx), cx.fcx.id, id) {
some(ast::def_upvar(did, _)) {
let lldiscrim_gv = lookup_discriminant(bcx.fcx.lcx, vid);
let lldiscrim = bcx.build.Load(lldiscrim_gv);
let lldiscrimptr =
- bcx.build.GEP(lltagptr, ~[C_int(0), C_int(0)]);
+ bcx.build.GEP(lltagptr, [C_int(0), C_int(0)]);
bcx.build.Store(lldiscrim, lldiscrimptr);
}
ret lval_val(bcx, lltagptr);
ret lval_mem(cx, ccx.consts.get(did.node));
} else {
let tp = ty::node_id_to_monotype(ccx.tcx, id);
- let k: [ast::kind] = ~[];
+ let k: [ast::kind] = [];
ret lval_val(cx,
load_if_immediate(cx,
trans_external_path(cx, did,
alt ty::struct(bcx_tcx(cx), t) {
ty::ty_rec(fields) {
let ix: uint = ty::field_idx(bcx_ccx(cx).sess, sp, field, fields);
- let v = GEP_tup_like(r.bcx, t, r.val, ~[0, ix as int]);
+ let v = GEP_tup_like(r.bcx, t, r.val, [0, ix as int]);
ret lval_mem(v.bcx, v.val);
}
ty::ty_obj(methods) {
let ix: uint = ty::method_idx(bcx_ccx(cx).sess, sp, field, methods);
let vtbl =
- r.bcx.build.GEP(r.val, ~[C_int(0), C_int(abi::obj_field_vtbl)]);
+ r.bcx.build.GEP(r.val, [C_int(0), C_int(abi::obj_field_vtbl)]);
vtbl = r.bcx.build.Load(vtbl);
let vtbl_type = T_ptr(T_array(T_ptr(T_nil()), ix + 1u));
vtbl = cx.build.PointerCast(vtbl, vtbl_type);
- let v = r.bcx.build.GEP(vtbl, ~[C_int(0), C_int(ix as int)]);
- let fn_ty: ty::t = ty::method_ty_to_fn_ty(bcx_tcx(cx), methods.(ix));
+ let v = r.bcx.build.GEP(vtbl, [C_int(0), C_int(ix as int)]);
+ let fn_ty: ty::t = ty::method_ty_to_fn_ty(bcx_tcx(cx), methods[ix]);
let tcx = bcx_tcx(cx);
let ll_fn_ty =
type_of_fn_full(bcx_ccx(cx), sp, ty::ty_fn_proto(tcx, fn_ty),
let int_size = llsize_of_real(bcx_ccx(cx), T_int());
if ix_size < int_size {
ix_val = bcx.build.ZExt(ix.val, T_int());
- } else if (ix_size > int_size) {
+ } else if ix_size > int_size {
ix_val = bcx.build.Trunc(ix.val, T_int());
} else { ix_val = ix.val; }
let unit_ty = node_id_type(bcx_ccx(cx), id);
alt interior_len_and_data {
some(lad) { lim = lad.len; }
none. {
- lim = bcx.build.GEP(v, ~[C_int(0), C_int(abi::vec_elt_fill)]);
+ lim = bcx.build.GEP(v, [C_int(0), C_int(abi::vec_elt_fill)]);
lim = bcx.build.Load(lim);
}
}
none. {
body =
next_cx.build.GEP(v,
- ~[C_int(0), C_int(abi::vec_elt_data),
- C_int(0)]);
+ [C_int(0), C_int(abi::vec_elt_data), C_int(0)]);
}
}
let elt;
if ty::type_has_dynamic_size(bcx_tcx(cx), unit_ty) {
body = next_cx.build.PointerCast(body, T_ptr(T_i8()));
- elt = next_cx.build.GEP(body, ~[scaled_ix]);
+ elt = next_cx.build.GEP(body, [scaled_ix]);
} else {
- elt = next_cx.build.GEP(body, ~[ix_val]);
+ elt = next_cx.build.GEP(body, [ix_val]);
// We're crossing a box boundary here, so we may need to pointer cast.
let llunitty = type_of(bcx_ccx(next_cx), sp, unit_ty);
alt ty::struct(ccx.tcx, t) {
ty::ty_box(_) {
sub.bcx.build.InBoundsGEP(sub.val,
- ~[C_int(0),
- C_int(abi::box_rc_field_body)])
+ [C_int(0),
+ C_int(abi::box_rc_field_body)])
}
ty::ty_uniq(_) { fail "uniq lval translation unimplemented" }
ty::ty_res(_, _, _) {
- sub.bcx.build.InBoundsGEP(sub.val, ~[C_int(0), C_int(1)])
+ sub.bcx.build.InBoundsGEP(sub.val, [C_int(0), C_int(1)])
}
ty::ty_tag(_, _) {
let ety = ty::expr_ty(ccx.tcx, e);
let dstsz = llvm::LLVMGetIntTypeWidth(lldsttype);
ret if dstsz == srcsz {
bcx.build.BitCast(llsrc, lldsttype)
- } else if (srcsz > dstsz) {
+ } else if srcsz > dstsz {
bcx.build.TruncOrBitCast(llsrc, lldsttype)
- } else if (signed) {
+ } else if signed {
bcx.build.SExtOrBitCast(llsrc, lldsttype)
} else { bcx.build.ZExtOrBitCast(llsrc, lldsttype) };
}
let dstsz = lib::llvm::float_width(lldsttype);
ret if dstsz > srcsz {
bcx.build.FPExt(llsrc, lldsttype)
- } else if (srcsz > dstsz) {
+ } else if srcsz > dstsz {
bcx.build.FPTrunc(llsrc, lldsttype)
} else { llsrc };
}
fn t_kind(tcx: &ty::ctxt, t: ty::t) -> kind {
ret if ty::type_is_fp(tcx, t) {
float
- } else if (ty::type_is_native(tcx, t)) {
+ } else if ty::type_is_native(tcx, t) {
native_
- } else if (ty::type_is_integral(tcx, t)) {
+ } else if ty::type_is_integral(tcx, t) {
integral
} else { other };
}
outgoing_fty: &ty::t, args: &[option::t<@ast::expr>],
env_ty: &ty::t, ty_param_count: uint,
target_fn: &option::t<ValueRef>) ->
- {val: ValueRef, ty: TypeRef} {
+ {val: ValueRef, ty: TypeRef} {
// Here we're not necessarily constructing a thunk in the sense of
// "function with no arguments". The result of compiling 'bind f(foo,
// creating. (In our running example, target is the function f.) Pick
// out the pointer to the target function from the environment. The
// target function lives in the first binding spot.
- let (lltarget, starting_idx) = alt target_fn {
- some(lltarget) { (lltarget, 0) }
- none. {
- let lltarget =
- GEP_tup_like(bcx, closure_ty, llclosure,
- ~[0, abi::box_rc_field_body,
- abi::closure_elt_bindings, 0]);
- bcx = lltarget.bcx;
- (lltarget.val, 1)
- }
- };
+ let (lltarget, starting_idx) =
+ alt target_fn {
+ some(lltarget) { (lltarget, 0) }
+ none. {
+ let lltarget =
+ GEP_tup_like(bcx, closure_ty, llclosure,
+ [0, abi::box_rc_field_body,
+ abi::closure_elt_bindings, 0]);
+ bcx = lltarget.bcx;;
+ (lltarget.val, 1)
+ }
+ };
// And then, pick out the target function's own environment. That's what
// we'll use as the environment the thunk gets.
let lltargetclosure =
- bcx.build.GEP(lltarget, ~[C_int(0), C_int(abi::fn_field_box)]);
+ bcx.build.GEP(lltarget, [C_int(0), C_int(abi::fn_field_box)]);
lltargetclosure = bcx.build.Load(lltargetclosure);
// Get f's return type, which will also be the return type of the entire
}
// Set up the three implicit arguments to the thunk.
- let llargs: [ValueRef] = ~[llretptr, fcx.lltaskptr, lltargetclosure];
+ let llargs: [ValueRef] = [llretptr, fcx.lltaskptr, lltargetclosure];
// Copy in the type parameters.
let i: uint = 0u;
while i < ty_param_count {
let lltyparam_ptr =
GEP_tup_like(copy_args_bcx, closure_ty, llclosure,
- ~[0, abi::box_rc_field_body,
- abi::closure_elt_ty_params, i as int]);
+ [0, abi::box_rc_field_body,
+ abi::closure_elt_ty_params, i as int]);
copy_args_bcx = lltyparam_ptr.bcx;
let td = copy_args_bcx.build.Load(lltyparam_ptr.val);
- llargs += ~[td];
- fcx.lltydescs += ~[td];
+ llargs += [td];
+ fcx.lltydescs += [td];
i += 1u;
}
let llout_arg_tys: [TypeRef] =
type_of_explicit_args(cx.ccx, sp, outgoing_args);
for arg: option::t<@ast::expr> in args {
- let out_arg = outgoing_args.(outgoing_arg_index);
- let llout_arg_ty = llout_arg_tys.(outgoing_arg_index);
+ let out_arg = outgoing_args[outgoing_arg_index];
+ let llout_arg_ty = llout_arg_tys[outgoing_arg_index];
let is_val = out_arg.mode == ty::mo_val;
alt arg {
+
// Arg provided at binding time; thunk copies it from
// closure.
some(e) {
let e_ty = ty::expr_ty(cx.ccx.tcx, e);
let bound_arg =
GEP_tup_like(bcx, closure_ty, llclosure,
- ~[0, abi::box_rc_field_body,
- abi::closure_elt_bindings, b]);
+ [0, abi::box_rc_field_body,
+ abi::closure_elt_bindings, b]);
bcx = bound_arg.bcx;
let val = bound_arg.val;
// If the type is parameterized, then we need to cast the
// type we actually have to the parameterized out type.
if ty::type_contains_params(cx.ccx.tcx, out_arg.ty) {
- let ty = if is_val
- { T_ptr(llout_arg_ty) } else { llout_arg_ty };
+ let ty =
+ if is_val { T_ptr(llout_arg_ty) } else { llout_arg_ty };
val = bcx.build.PointerCast(val, ty);
}
if is_val {
val = bcx.build.Load(val);
}
}
- llargs += ~[val];
+ llargs += [val];
b += 1;
}
+
// Arg will be provided when the thunk is invoked.
none. {
let arg: ValueRef = llvm::LLVMGetParam(llthunk, a);
if ty::type_contains_params(cx.ccx.tcx, out_arg.ty) {
+
// If the argument was passed by value and isn't a
// pointer type, we need to spill it to an alloca in
// order to do a pointer cast. Argh.
let argp = do_spill(bcx, arg);
argp = bcx.build.PointerCast(argp, T_ptr(llout_arg_ty));
arg = bcx.build.Load(argp);
- } else {
- arg = bcx.build.PointerCast(arg, llout_arg_ty);
- }
+ } else { arg = bcx.build.PointerCast(arg, llout_arg_ty); }
}
- llargs += ~[arg];
+ llargs += [arg];
a += 1u;
}
}
}
let lltargetfn =
- bcx.build.GEP(lltarget, ~[C_int(0), C_int(abi::fn_field_code)]);
+ bcx.build.GEP(lltarget, [C_int(0), C_int(abi::fn_field_code)]);
// Cast the outgoing function to the appropriate type.
// This is necessary because the type of the function that we have
}
fn trans_bind_1(cx: &@block_ctxt, f: &@ast::expr, f_res: &lval_result,
- args: &[option::t<@ast::expr>], id: ast::node_id) ->
- result {
- let bound: [@ast::expr] = ~[];
+ args: &[option::t<@ast::expr>], id: ast::node_id) -> result {
+ let bound: [@ast::expr] = [];
for argopt: option::t<@ast::expr> in args {
- alt argopt { none. { } some(e) { bound += ~[e]; } }
+ alt argopt { none. { } some(e) { bound += [e]; } }
}
// Figure out which tydescs we need to pass, if any.
let outgoing_fty_real; // the type with typarams still in it
let lltydescs: [ValueRef];
alt f_res.generic {
- none. { outgoing_fty_real = outgoing_fty; lltydescs = ~[]; }
+ none. { outgoing_fty_real = outgoing_fty; lltydescs = []; }
some(ginfo) {
lazily_emit_all_generic_info_tydesc_glues(cx, ginfo);
outgoing_fty_real = ginfo.item_type;
// Arrange for the bound function to live in the first binding spot
// if the function is not statically known.
- let (bound_tys, bound_vals, target_res) = if f_res.is_mem {
- // Cast the function we are binding to be the type that the closure
- // will expect it to have. The type the closure knows about has the
- // type parameters substituted with the real types.
- let llclosurety = T_ptr(type_of(bcx_ccx(cx), cx.sp, outgoing_fty));
- let src_loc = bcx.build.PointerCast(f_res.res.val, llclosurety);
- let bound_f = {res: {bcx: bcx, val: src_loc} with f_res};
- (~[outgoing_fty], ~[bound_f], none)
- } else {
- (~[], ~[], some(f_res.res.val))
- };
+ let (bound_tys, bound_vals, target_res) =
+ if f_res.is_mem {
+ // Cast the function we are binding to be the type that the
+ // closure will expect it to have. The type the closure knows
+ // about has the type parameters substituted with the real types.
+ let llclosurety =
+ T_ptr(type_of(bcx_ccx(cx), cx.sp, outgoing_fty));
+ let src_loc = bcx.build.PointerCast(f_res.res.val, llclosurety);
+ let bound_f = {res: {bcx: bcx, val: src_loc} with f_res};
+ ([outgoing_fty], [bound_f], none)
+ } else { ([], [], some(f_res.res.val)) };
// Translate the bound expressions.
for e: @ast::expr in bound {
let lv = trans_lval(bcx, e);
bcx = lv.res.bcx;
- bound_vals += ~[lv];
- bound_tys += ~[ty::expr_ty(bcx_tcx(cx), e)];
+ bound_vals += [lv];
+ bound_tys += [ty::expr_ty(bcx_tcx(cx), e)];
}
// Actually construct the closure
- let closure = build_environment(bcx, lltydescs,
- bound_tys, bound_vals, true);
+ let closure =
+ build_environment(bcx, lltydescs, bound_tys, bound_vals, true);
bcx = closure.bcx;
// Make thunk
// The type of the entire bind expression.
let pair_ty = node_id_type(bcx_ccx(cx), id);
let llthunk =
- trans_bind_thunk(cx.fcx.lcx, cx.sp, pair_ty, outgoing_fty_real,
- args, closure.ptrty, ty_param_count,
- target_res);
+ trans_bind_thunk(cx.fcx.lcx, cx.sp, pair_ty, outgoing_fty_real, args,
+ closure.ptrty, ty_param_count, target_res);
// Construct the function pair
- let pair_v = create_real_fn_pair(bcx, llthunk.ty, llthunk.val,
- closure.ptr);
+ let pair_v =
+ create_real_fn_pair(bcx, llthunk.ty, llthunk.val, closure.ptr);
add_clean_temp(cx, pair_v, pair_ty);
ret rslt(bcx, pair_v);
}
-fn trans_arg_expr(cx: &@block_ctxt, arg: &ty::arg,
- lldestty0: TypeRef,
- to_zero: &mutable[{v:ValueRef, t: ty::t}],
- to_revoke: &mutable[ValueRef],
- e: &@ast::expr) -> result {
+fn trans_arg_expr(cx: &@block_ctxt, arg: &ty::arg, lldestty0: TypeRef,
+ to_zero: &mutable [{v: ValueRef, t: ty::t}],
+ to_revoke: &mutable [ValueRef], e: &@ast::expr) -> result {
let ccx = bcx_ccx(cx);
let e_ty = ty::expr_ty(ccx.tcx, e);
let is_bot = ty::type_is_bot(ccx.tcx, e_ty);
// be inspected. It's important for the value
// to have type lldestty0 (the callee's expected type).
val = llvm::LLVMGetUndef(lldestty0);
- } else if (arg.mode == ty::mo_val) {
+ } else if arg.mode == ty::mo_val {
if ty::type_owns_heap_mem(ccx.tcx, e_ty) {
let dst = alloc_ty(bcx, e_ty);
val = dst.val;
bcx = move_val_if_temp(dst.bcx, INIT, val, lv, e_ty).bcx;
- } else if (lv.is_mem) {
+ } else if lv.is_mem {
val = load_if_immediate(bcx, val, e_ty);
bcx = copy_ty(bcx, val, e_ty).bcx;
} else {
bcx = copy_ty(bcx, val, e_ty).bcx;
} else { revoke_clean(bcx, val); }
}
- } else if (type_is_immediate(ccx, e_ty) && !lv.is_mem) {
+ } else if type_is_immediate(ccx, e_ty) && !lv.is_mem {
val = do_spill(bcx, val);
}
// Collect arg for later if it happens to be one we've moving out.
if arg.mode == ty::mo_move {
if lv.is_mem {
- // Use actual ty, not declared ty -- anything else doesn't make sense
- // if declared ty is a ty param
- to_zero += ~[{v: lv.res.val, t: e_ty}];
- } else {
- to_revoke += ~[lv.res.val];
- }
+ // Use actual ty, not declared ty -- anything else doesn't make
+ // sense if declared ty is a ty param
+ to_zero += [{v: lv.res.val, t: e_ty}];
+ } else { to_revoke += [lv.res.val]; }
}
ret rslt(bcx, val);
}
{bcx: @block_ctxt,
args: [ValueRef],
retslot: ValueRef,
- to_zero: [{v:ValueRef, t: ty::t}],
- to_revoke: [ValueRef] } {
+ to_zero: [{v: ValueRef, t: ty::t}],
+ to_revoke: [ValueRef]} {
let args: [ty::arg] = ty::ty_fn_args(bcx_tcx(cx), fn_ty);
- let llargs: [ValueRef] = ~[];
- let lltydescs: [ValueRef] = ~[];
- let to_zero = ~[];
- let to_revoke = ~[];
+ let llargs: [ValueRef] = [];
+ let lltydescs: [ValueRef] = [];
+ let to_zero = [];
+ let to_revoke = [];
let bcx: @block_ctxt = cx;
// Arg 0: Output pointer.
if bcx.build.is_terminated() {
// This means an earlier arg was divergent.
// So this arg can't be evaluated.
- ret {bcx: bcx, args: ~[], retslot: C_nil(),
- to_zero: to_zero, to_revoke: to_revoke};
+ ret {bcx: bcx,
+ args: [],
+ retslot: C_nil(),
+ to_zero: to_zero,
+ to_revoke: to_revoke};
}
let retty = ty::ty_fn_ret(bcx_tcx(cx), fn_ty);
let llretslot_res = alloc_ty(bcx, retty);
}
_ { }
}
- if (ty::type_contains_params(bcx_tcx(cx), retty)) {
+ if ty::type_contains_params(bcx_tcx(cx), retty) {
// It's possible that the callee has some generic-ness somewhere in
// its return value -- say a method signature within an obj or a fn
// type deep in a structure -- which the caller has a concrete view
// of. If so, cast the caller's view of the restlot to the callee's
// view, for the sake of making a type-compatible call.
let llretty = T_ptr(type_of_inner(bcx_ccx(bcx), bcx.sp, retty));
- llargs += ~[cx.build.PointerCast(llretslot, llretty)];
- } else { llargs += ~[llretslot]; }
+ llargs += [cx.build.PointerCast(llretslot, llretty)];
+ } else { llargs += [llretslot]; }
// Arg 1: task pointer.
- llargs += ~[bcx.fcx.lltaskptr];
+ llargs += [bcx.fcx.lltaskptr];
// Arg 2: Env (closure-bindings / self-obj)
- llargs += ~[llenv];
+ llargs += [llenv];
// Args >3: ty_params ...
llargs += lltydescs;
alt lliterbody {
none. { }
some(lli) {
- let lli = if (ty::type_contains_params(bcx_tcx(cx), retty)) {
- let body_ty = ty::mk_iter_body_fn(bcx_tcx(cx), retty);
- let body_llty = type_of_inner(bcx_ccx(cx), cx.sp, body_ty);
- bcx.build.PointerCast(lli, T_ptr(body_llty))
- } else { lli };
- llargs += ~[cx.build.Load(lli)];
+ let lli =
+ if ty::type_contains_params(bcx_tcx(cx), retty) {
+ let body_ty = ty::mk_iter_body_fn(bcx_tcx(cx), retty);
+ let body_llty = type_of_inner(bcx_ccx(cx), cx.sp, body_ty);
+ bcx.build.PointerCast(lli, T_ptr(body_llty))
+ } else { lli };
+ llargs += [cx.build.Load(lli)];
}
}
// So this arg can't be evaluated.
break;
}
- let r = trans_arg_expr(bcx, args.(i), arg_tys.(i),
- to_zero, to_revoke, e);
+ let r =
+ trans_arg_expr(bcx, args[i], arg_tys[i], to_zero, to_revoke, e);
bcx = r.bcx;
- llargs += ~[r.val];
+ llargs += [r.val];
i += 1u;
}
- ret {bcx: bcx, args: llargs, retslot: llretslot,
- to_zero: to_zero, to_revoke: to_revoke};
+ ret {bcx: bcx,
+ args: llargs,
+ retslot: llretslot,
+ to_zero: to_zero,
+ to_revoke: to_revoke};
}
fn trans_call(cx: &@block_ctxt, f: &@ast::expr,
fn_ty = res.ty;
let pair = res.val;
- faddr = bcx.build.GEP(pair, ~[C_int(0), C_int(abi::fn_field_code)]);
+ faddr = bcx.build.GEP(pair, [C_int(0), C_int(abi::fn_field_code)]);
faddr = bcx.build.Load(faddr);
let llclosure =
- bcx.build.GEP(pair, ~[C_int(0), C_int(abi::fn_field_box)]);
+ bcx.build.GEP(pair, [C_int(0), C_int(abi::fn_field_box)]);
llenv = bcx.build.Load(llclosure);
}
}
}
// Forget about anything we moved out.
- for {v,t}: {v: ValueRef, t: ty::t} in args_res.to_zero {
+ for {v: v, t: t}: {v: ValueRef, t: ty::t} in args_res.to_zero {
zero_alloca(bcx, v, t)
}
- for v: ValueRef in args_res.to_revoke {
- revoke_clean(bcx, v)
- }
+ for v: ValueRef in args_res.to_revoke { revoke_clean(bcx, v) }
}
ret rslt(bcx, retval);
}
-fn trans_tup(cx: &@block_ctxt, elts: &[@ast::expr], id: ast::node_id)
- -> result {
+fn trans_tup(cx: &@block_ctxt, elts: &[@ast::expr], id: ast::node_id) ->
+ result {
let bcx = cx;
let t = node_id_type(bcx.fcx.lcx.ccx, id);
let tup_res = alloc_ty(bcx, t);
let e_ty = ty::expr_ty(cx.fcx.lcx.ccx.tcx, e);
let src = trans_lval(bcx, e);
bcx = src.res.bcx;
- let dst_res = GEP_tup_like(bcx, t, tup_val, ~[0, i]);
+ let dst_res = GEP_tup_like(bcx, t, tup_val, [0, i]);
bcx = move_val_if_temp(dst_res.bcx, INIT, dst_res.val, src, e_ty).bcx;
i += 1;
}
bcx.build.Store(lllen,
bcx.build.InBoundsGEP(llvecptr,
- ~[C_int(0),
- C_uint(abi::ivec_elt_len)]));
+ [C_int(0),
+ C_uint(abi::ivec_elt_len)]));
bcx.build.Store(llalen,
bcx.build.InBoundsGEP(llvecptr,
- ~[C_int(0),
- C_uint(abi::ivec_elt_alen)]));
+ [C_int(0),
+ C_uint(abi::ivec_elt_alen)]));
llfirsteltptr =
bcx.build.InBoundsGEP(llvecptr,
- ~[C_int(0), C_uint(abi::ivec_elt_elems),
- C_int(0)]);
+ [C_int(0), C_uint(abi::ivec_elt_elems),
+ C_int(0)]);
} else {
// Heap case.
- let stub_z = ~[C_int(0), C_uint(abi::ivec_heap_stub_elt_zero)];
- let stub_a = ~[C_int(0), C_uint(abi::ivec_heap_stub_elt_alen)];
- let stub_p = ~[C_int(0), C_uint(abi::ivec_heap_stub_elt_ptr)];
+ let stub_z = [C_int(0), C_uint(abi::ivec_heap_stub_elt_zero)];
+ let stub_a = [C_int(0), C_uint(abi::ivec_heap_stub_elt_alen)];
+ let stub_p = [C_int(0), C_uint(abi::ivec_heap_stub_elt_ptr)];
let llstubty = T_ivec_heap(llunitty);
let llstubptr = bcx.build.PointerCast(llvecptr, T_ptr(llstubty));
bcx.build.Store(C_int(0), bcx.build.InBoundsGEP(llstubptr, stub_z));
let llheapptr = rslt.val;
bcx.build.Store(llheapptr,
bcx.build.InBoundsGEP(llstubptr, stub_p));
- let heap_l = ~[C_int(0), C_uint(abi::ivec_heap_elt_len)];
+ let heap_l = [C_int(0), C_uint(abi::ivec_heap_elt_len)];
bcx.build.Store(lllen, bcx.build.InBoundsGEP(llheapptr, heap_l));
llfirsteltptr =
bcx.build.InBoundsGEP(llheapptr,
- ~[C_int(0),
- C_uint(abi::ivec_heap_elt_elems),
- C_int(0)]);
+ [C_int(0),
+ C_uint(abi::ivec_heap_elt_elems),
+ C_int(0)]);
}
}
// Store the individual elements.
if ty::type_has_dynamic_size(bcx_tcx(bcx), unit_ty) {
lleltptr =
bcx.build.InBoundsGEP(llfirsteltptr,
- ~[bcx.build.Mul(C_uint(i), unit_sz)]);
+ [bcx.build.Mul(C_uint(i), unit_sz)]);
} else {
- lleltptr = bcx.build.InBoundsGEP(llfirsteltptr, ~[C_uint(i)]);
+ lleltptr = bcx.build.InBoundsGEP(llfirsteltptr, [C_uint(i)]);
}
bcx = move_val_if_temp(bcx, INIT, lleltptr, lv, unit_ty).bcx;
i += 1u;
base_val = base_res.val;
}
}
- let ty_fields: [ty::field] = ~[];
+ let ty_fields: [ty::field] = [];
alt ty::struct(bcx_tcx(cx), t) { ty::ty_rec(flds) { ty_fields = flds; } }
for tf: ty::field in ty_fields {
let e_ty = tf.mt.ty;
- let dst_res = GEP_tup_like(bcx, t, rec_val, ~[0, i]);
+ let dst_res = GEP_tup_like(bcx, t, rec_val, [0, i]);
bcx = dst_res.bcx;
let expr_provided = false;
for f: ast::field in fields {
}
}
if !expr_provided {
- let src_res = GEP_tup_like(bcx, t, base_val, ~[0, i]);
+ let src_res = GEP_tup_like(bcx, t, base_val, [0, i]);
src_res =
rslt(src_res.bcx, load_if_immediate(bcx, src_res.val, e_ty));
bcx =
}
ast::expr_binary(op, x, y) { ret trans_binary(cx, op, x, y); }
ast::expr_if(cond, thn, els) {
- ret with_out_method(bind trans_if(cx, cond, thn, els, _), cx,
- e.id, output);
+ ret with_out_method(bind trans_if(cx, cond, thn, els, _), cx, e.id,
+ output);
}
ast::expr_if_check(cond, thn, els) {
- ret with_out_method(bind trans_if(cx, cond, thn, els, _), cx,
- e.id, output);
+ ret with_out_method(bind trans_if(cx, cond, thn, els, _), cx, e.id,
+ output);
}
ast::expr_ternary(_, _, _) {
ret trans_expr_out(cx, ast::ternary_to_if(e), output);
ast::expr_while(cond, body) { ret trans_while(cx, cond, body); }
ast::expr_do_while(body, cond) { ret trans_do_while(cx, body, cond); }
ast::expr_alt(expr, arms) {
- ret with_out_method(bind trans_alt::trans_alt(cx, expr, arms, _),
- cx, e.id, output);
+ ret with_out_method(bind trans_alt::trans_alt(cx, expr, arms, _), cx,
+ e.id, output);
}
ast::expr_fn(f) {
let ccx = bcx_ccx(cx);
let fn_res =
trans_closure(some(cx), some(llfnty), sub_cx, e.span, f, llfn,
- none, ~[], e.id);
+ none, [], e.id);
let fn_pair =
alt fn_res {
some(fn_pair) { fn_pair }
- none. { {fn_pair: create_fn_pair(ccx, s, llfnty, llfn, false),
- bcx: cx} }
+ none. {
+ {fn_pair: create_fn_pair(ccx, s, llfnty, llfn, false),
+ bcx: cx}
+ }
};
ret rslt(fn_pair.bcx, fn_pair.fn_pair);
}
rhs_res.val);
}
ret trans_evec_append(rhs_res.bcx, t, lhs_res.res.val,
- rhs_res.val);
+ rhs_res.val);
}
_ { }
}
}
let lhs_val = load_if_immediate(rhs_res.bcx, lhs_res.res.val, t);
- let v = trans_eager_binop(rhs_res.bcx, op, lhs_val, t,
- rhs_res.val, t);
+ let v =
+ trans_eager_binop(rhs_res.bcx, op, lhs_val, t, rhs_res.val, t);
// FIXME: calculate copy init-ness in typestate.
// This is always a temporary, so can always be safely moved
let move_res =
ret trans_call(cx, f, none::<ValueRef>, args, e.id);
}
ast::expr_cast(val, _) { ret trans_cast(cx, val, e.id); }
- ast::expr_vec(args, _) {
- ret trans_ivec(cx, args, e.id);
- }
+ ast::expr_vec(args, _) { ret trans_ivec(cx, args, e.id); }
ast::expr_rec(args, base) { ret trans_rec(cx, args, base, e.id); }
ast::expr_tup(args) { ret trans_tup(cx, args, e.id); }
ast::expr_mac(_) { ret bcx_ccx(cx).sess.bug("unexpanded macro"); }
let els = rslt(else_cx, C_nil());
cx.build.CondBr(cond, then_cx.llbb, else_cx.llbb);
- ret rslt(join_branches(cx, ~[check_res, els]), C_nil());
+ ret rslt(join_branches(cx, [check_res, els]), C_nil());
}
ast::expr_break. { ret trans_break(e.span, cx); }
ast::expr_cont. { ret trans_cont(e.span, cx); }
ret rslt(sub.res.bcx, v);
}
-fn with_out_method(work: fn(&out_method) -> result , cx: @block_ctxt,
+fn with_out_method(work: fn(&out_method) -> result, cx: @block_ctxt,
id: ast::node_id, outer_output: &out_method) -> result {
let ccx = bcx_ccx(cx);
if outer_output != return {
let llval_i8 = log_bcx.build.PointerCast(llvalptr, T_ptr(T_i8()));
log_bcx.build.Call(bcx_ccx(log_bcx).upcalls.log_type,
- ~[log_bcx.fcx.lltaskptr, r.val, llval_i8, C_int(lvl)]);
+ [log_bcx.fcx.lltaskptr, r.val, llval_i8, C_int(lvl)]);
log_bcx = trans_block_cleanups(log_bcx, log_cx);
log_bcx.build.Br(after_cx.llbb);
if ty::type_is_str(tcx, e_ty) {
let elt =
bcx.build.GEP(expr_res.val,
- ~[C_int(0), C_int(abi::vec_elt_data)]);
+ [C_int(0), C_int(abi::vec_elt_data)]);
ret trans_fail_value(bcx, sp_opt, elt);
} else {
bcx_ccx(cx).sess.span_bug(expr.span,
}
let V_str = cx.build.PointerCast(V_fail_str, T_ptr(T_i8()));
V_filename = cx.build.PointerCast(V_filename, T_ptr(T_i8()));
- let args = ~[cx.fcx.lltaskptr, V_str, V_filename, C_int(V_line)];
+ let args = [cx.fcx.lltaskptr, V_str, V_filename, C_int(V_line)];
cx.build.Call(bcx_ccx(cx).upcalls._fail, args);
cx.build.Unreachable();
ret rslt(cx, C_nil());
some(lli) {
let slot = alloca(cx, val_ty(lli));
cx.build.Store(lli, slot);
- llcallee = cx.build.GEP(slot, ~[C_int(0), C_int(abi::fn_field_code)]);
+ llcallee = cx.build.GEP(slot, [C_int(0), C_int(abi::fn_field_code)]);
llcallee = cx.build.Load(llcallee);
- llenv = cx.build.GEP(slot, ~[C_int(0), C_int(abi::fn_field_box)]);
+ llenv = cx.build.GEP(slot, [C_int(0), C_int(abi::fn_field_box)]);
llenv = cx.build.Load(llenv);
}
}
let bcx = cx;
let dummy_retslot = alloca(bcx, T_nil());
- let llargs: [ValueRef] = ~[dummy_retslot, cx.fcx.lltaskptr, llenv];
+ let llargs: [ValueRef] = [dummy_retslot, cx.fcx.lltaskptr, llenv];
alt e {
none. { }
some(x) {
let e_ty = ty::expr_ty(bcx_tcx(cx), x);
let arg = {mode: ty::mo_alias(false), ty: e_ty};
- let arg_tys = type_of_explicit_args(bcx_ccx(cx), x.span, ~[arg]);
- let z = ~[];
- let k = ~[];
- let r = trans_arg_expr(bcx, arg, arg_tys.(0), z, k, x);
+ let arg_tys = type_of_explicit_args(bcx_ccx(cx), x.span, [arg]);
+ let z = [];
+ let k = [];
+ let r = trans_arg_expr(bcx, arg, arg_tys[0], z, k, x);
bcx = r.bcx;
- llargs += ~[r.val];
+ llargs += [r.val];
}
}
bcx.build.FastCall(llcallee, llargs);
let t = ty::expr_ty(bcx_tcx(cx), x);
let lv = trans_lval(cx, x);
bcx = lv.res.bcx;
- let is_local = alt x.node {
- ast::expr_path(p) {
- alt bcx_tcx(bcx).def_map.get(x.id) {
- ast::def_local(_) { true } _ { false }
- }
- }
- _ { false }
- };
+ let is_local =
+ alt x.node {
+ ast::expr_path(p) {
+ alt bcx_tcx(bcx).def_map.get(x.id) {
+ ast::def_local(_) { true }
+ _ { false }
+ }
+ }
+ _ { false }
+ };
if is_local {
bcx = move_val(bcx, INIT, cx.fcx.llretptr, lv, t).bcx;
} else {
ret rslt(new_sub_block_ctxt(bcx, "ret.unreachable"), C_nil());
}
-fn build_return(bcx: &@block_ctxt) {
- bcx.build.Br(bcx_fcx(bcx).llreturn);
-}
+fn build_return(bcx: &@block_ctxt) { bcx.build.Br(bcx_fcx(bcx).llreturn); }
fn trans_be(cx: &@block_ctxt, e: &@ast::expr) -> result {
// FIXME: This should be a typestate precondition
}
_ { bcx = zero_alloca(bcx, llptr, ty).bcx; }
}
- bcx = trans_alt::bind_irrefutable_pat(bcx, local.node.pat, llptr,
- bcx.fcx.lllocals, false);
+ bcx =
+ trans_alt::bind_irrefutable_pat(bcx, local.node.pat, llptr,
+ bcx.fcx.lllocals, false);
ret rslt(bcx, llptr);
}
// next three functions instead.
fn new_block_ctxt(cx: &@fn_ctxt, parent: &block_parent, kind: block_kind,
name: &str) -> @block_ctxt {
- let cleanups: [cleanup] = ~[];
+ let cleanups: [cleanup] = [];
let s = str::buf("");
let held_name; //HACK for str::buf, which doesn't keep its value alive
if cx.lcx.ccx.sess.get_opts().save_temps ||
}
fn new_raw_block_ctxt(fcx: &@fn_ctxt, llbb: BasicBlockRef) -> @block_ctxt {
- let cleanups: [cleanup] = ~[];
+ let cleanups: [cleanup] = [];
ret @{llbb: llbb,
build: new_builder(llbb),
parent: parent_none,
let i = std::vec::len::<cleanup>(cleanup_cx.cleanups);
while i > 0u {
i -= 1u;
- let c = cleanup_cx.cleanups.(i);
+ let c = cleanup_cx.cleanups[i];
alt c {
clean(cfn) { bcx = cfn(bcx).bcx; }
clean_temp(_, cfn) { bcx = cfn(bcx).bcx; }
fn trans_fn_cleanups(fcx: &@fn_ctxt, build: &lib::llvm::builder) {
alt fcx.llobstacktoken {
- some(lltoken_) {
- let lltoken = lltoken_; // satisfy alias checker
- build.Call(fcx_ccx(fcx).upcalls.dynastack_free, ~[fcx.lltaskptr,
- lltoken]);
- }
- none. { /* nothing to do */ }
+ some(lltoken_) {
+ let lltoken = lltoken_; // satisfy alias checker
+ build.Call(fcx_ccx(fcx).upcalls.dynastack_free,
+ [fcx.lltaskptr, lltoken]);
+ }
+ none. {/* nothing to do */ }
}
}
iter block_locals(b: &ast::blk) -> @ast::local {
+
// FIXME: putting from inside an iter block doesn't work, so we can't
// use the index here.
for s: @ast::stmt in b.node.stmts {
}
fn llstaticallocas_block_ctxt(fcx: &@fn_ctxt) -> @block_ctxt {
- let cleanups: [cleanup] = ~[];
+ let cleanups: [cleanup] = [];
ret @{llbb: fcx.llstaticallocas,
build: new_builder(fcx.llstaticallocas),
parent: parent_none,
}
fn llderivedtydescs_block_ctxt(fcx: &@fn_ctxt) -> @block_ctxt {
- let cleanups: [cleanup] = ~[];
+ let cleanups: [cleanup] = [];
ret @{llbb: fcx.llderivedtydescs,
build: new_builder(fcx.llderivedtydescs),
parent: parent_none,
let n = size_of(llderivedtydescs_block_ctxt(bcx.fcx), t);
bcx.fcx.llderivedtydescs = n.bcx.llbb;
val = array_alloca(bcx, T_i8(), n.val);
- } else {
- val = alloca(bcx, type_of(bcx_ccx(cx), cx.sp, t));
- }
+ } else { val = alloca(bcx, type_of(bcx_ccx(cx), cx.sp, t)); }
// NB: since we've pushed all size calculations in this
// function up to the alloca block, we actually return the
// block passed into us unmodified; it doesn't really
// past caller conventions and may well make sense again,
// so we leave it as-is.
- if (bcx_tcx(cx).sess.get_opts().do_gc) {
+ if bcx_tcx(cx).sess.get_opts().do_gc {
bcx = gc::add_gc_root(bcx, val, t);
}
llvm::LLVMSetValueName(r.val, str::buf(ident));
}
}
- _ {}
+ _ { }
}
ret r;
}
}
fn new_local_ctxt(ccx: &@crate_ctxt) -> @local_ctxt {
- let pth: [str] = ~[];
+ let pth: [str] = [];
ret @{path: pth,
- module_path: ~[ccx.link_meta.name],
- obj_typarams: ~[],
- obj_fields: ~[],
+ module_path: [ccx.link_meta.name],
+ obj_typarams: [],
+ obj_fields: [],
ccx: ccx};
}
llobjfields: llobjfields,
lllocals: lllocals,
llupvars: llupvars,
- mutable lltydescs: ~[],
+ mutable lltydescs: [],
derived_tydescs: derived_tydescs,
id: id,
sp: sp,
for tp: ast::ty_param in ty_params {
let llarg = llvm::LLVMGetParam(cx.llfn, arg_n);
assert (llarg as int != 0);
- cx.lltydescs += ~[llarg];
+ cx.lltydescs += [llarg];
arg_n += 1u;
i += 1u;
}
alt bcx.fcx.llargs.find(aarg.id) {
some(x) { argval = x; }
_ {
- bcx_ccx(bcx).sess.span_fatal
- (aarg.ty.span, "unbound arg ID in copy_args_to_allocas");
+ bcx_ccx(bcx).sess.span_fatal(
+ aarg.ty.span,
+ "unbound arg ID in copy_args_to_allocas");
}
}
let a = do_spill(bcx, argval);
alt bcx.fcx.llargs.find(aarg.id) {
some(x) { argval = x; }
_ {
- bcx_ccx(bcx).sess.span_fatal
- (aarg.ty.span, "unbound arg ID in add_cleanups_for_args");
+ bcx_ccx(bcx).sess.span_fatal(
+ aarg.ty.span,
+ "unbound arg ID in add_cleanups_for_args");
}
}
- add_clean(bcx, argval, arg_tys.(arg_n).ty);
+ add_clean(bcx, argval, arg_tys[arg_n].ty);
}
arg_n += 1u;
}
fn populate_fn_ctxt_from_llself(fcx: @fn_ctxt, llself: val_self_pair) {
let bcx = llstaticallocas_block_ctxt(fcx);
- let field_tys: [ty::t] = ~[];
+ let field_tys: [ty::t] = [];
for f: ast::obj_field in bcx.fcx.lcx.obj_fields {
- field_tys += ~[node_id_type(bcx_ccx(bcx), f.id)];
+ field_tys += [node_id_type(bcx_ccx(bcx), f.id)];
}
// Synthesize a tuple type for the fields so that GEP_tup_like() can work
// its magic.
let n_typarams = std::vec::len::<ast::ty_param>(bcx.fcx.lcx.obj_typarams);
let llobj_box_ty: TypeRef = T_obj_ptr(*bcx_ccx(bcx), n_typarams);
let box_cell =
- bcx.build.GEP(llself.v, ~[C_int(0), C_int(abi::obj_field_box)]);
+ bcx.build.GEP(llself.v, [C_int(0), C_int(abi::obj_field_box)]);
let box_ptr = bcx.build.Load(box_cell);
box_ptr = bcx.build.PointerCast(box_ptr, llobj_box_ty);
let obj_typarams =
bcx.build.GEP(box_ptr,
- ~[C_int(0), C_int(abi::box_rc_field_body),
- C_int(abi::obj_body_elt_typarams)]);
+ [C_int(0), C_int(abi::box_rc_field_body),
+ C_int(abi::obj_body_elt_typarams)]);
// The object fields immediately follow the type parameters, so we skip
// over them to get the pointer.
let i: int = 0;
for p: ast::ty_param in fcx.lcx.obj_typarams {
let lltyparam: ValueRef =
- bcx.build.GEP(obj_typarams, ~[C_int(0), C_int(i)]);
+ bcx.build.GEP(obj_typarams, [C_int(0), C_int(i)]);
lltyparam = bcx.build.Load(lltyparam);
- fcx.lltydescs += ~[lltyparam];
+ fcx.lltydescs += [lltyparam];
i += 1;
}
i = 0;
for f: ast::obj_field in fcx.lcx.obj_fields {
- let rslt = GEP_tup_like(bcx, fields_tup_ty, obj_fields, ~[0, i]);
+ let rslt = GEP_tup_like(bcx, fields_tup_ty, obj_fields, [0, i]);
bcx = llstaticallocas_block_ctxt(fcx);
let llfield = rslt.val;
fcx.llobjfields.insert(f.id, llfield);
fn trans_closure(bcx_maybe: &option::t<@block_ctxt>,
llfnty: &option::t<TypeRef>, cx: @local_ctxt, sp: &span,
f: &ast::_fn, llfndecl: ValueRef, ty_self: option::t<ty::t>,
- ty_params: &[ast::ty_param], id: ast::node_id)
- -> option::t<{fn_pair: ValueRef, bcx: @block_ctxt}> {
+ ty_params: &[ast::ty_param], id: ast::node_id) ->
+ option::t<{fn_pair: ValueRef, bcx: @block_ctxt}> {
set_uwtable(llfndecl);
// Set up arguments to the function.
copy_args_to_allocas(fcx, f.decl.inputs);
// Figure out if we need to build a closure and act accordingly
- let res = alt f.proto {
- ast::proto_block. | ast::proto_closure. {
- let bcx = option::get(bcx_maybe);
- let upvars = get_freevars(cx.ccx.tcx, id);
-
- let copying = f.proto == ast::proto_closure;
- let env = build_closure(bcx, upvars, copying);
- load_environment(bcx, fcx, env.ptrty, upvars, copying);
-
- let closure = create_real_fn_pair(env.bcx, option::get(llfnty),
- llfndecl, env.ptr);
- if copying {
- add_clean_temp(bcx, closure, node_id_type(cx.ccx, id))
- }
- some({fn_pair: closure, bcx: env.bcx})
- }
- _ { none }
- };
+ let res =
+ alt f.proto {
+ ast::proto_block. | ast::proto_closure. {
+ let bcx = option::get(bcx_maybe);
+ let upvars = get_freevars(cx.ccx.tcx, id);
+
+ let copying = f.proto == ast::proto_closure;
+ let env = build_closure(bcx, upvars, copying);
+ load_environment(bcx, fcx, env.ptrty, upvars, copying);
+
+ let closure =
+ create_real_fn_pair(env.bcx, option::get(llfnty), llfndecl,
+ env.ptr);
+ if copying {
+ add_clean_temp(bcx, closure, node_id_type(cx.ccx, id))
+ }
+ some({fn_pair: closure, bcx: env.bcx})
+ }
+ _ { none }
+ };
// Create the first basic block in the function and keep a handle on it to
// pass to finish_fn later.
// (trans_block, trans_expr, et cetera).
let rslt =
if !ty::type_is_nil(cx.ccx.tcx, block_ty) &&
- !ty::type_is_bot(cx.ccx.tcx, block_ty) &&
- f.proto != ast::proto_iter {
- trans_block(bcx, f.body, save_in(fcx.llretptr))
- } else { trans_block(bcx, f.body, return) };
+ !ty::type_is_bot(cx.ccx.tcx, block_ty) &&
+ f.proto != ast::proto_iter {
+ trans_block(bcx, f.body, save_in(fcx.llretptr))
+ } else { trans_block(bcx, f.body, return) };
bcx = rslt.bcx;
if !is_terminated(bcx) {
dtor.decl.inputs, ty_params);
let bcx = new_top_block_ctxt(fcx);
let lltop = bcx.llbb;
- let arg_t = arg_tys_of_fn(cx.ccx, ctor_id).(0).ty;
- let tup_t = ty::mk_tup(cx.ccx.tcx, ~[ty::mk_int(cx.ccx.tcx), arg_t]);
+ let arg_t = arg_tys_of_fn(cx.ccx, ctor_id)[0].ty;
+ let tup_t = ty::mk_tup(cx.ccx.tcx, [ty::mk_int(cx.ccx.tcx), arg_t]);
let arg;
- alt fcx.llargs.find(dtor.decl.inputs.(0).id) {
+ alt fcx.llargs.find(dtor.decl.inputs[0].id) {
some(x) { arg = load_if_immediate(bcx, x, arg_t); }
_ { cx.ccx.sess.span_fatal(sp, "unbound dtor decl in trans_res_ctor"); }
}
-
let llretptr = fcx.llretptr;
if ty::type_has_dynamic_size(cx.ccx.tcx, ret_t) {
- let llret_t = T_ptr(T_struct(~[T_i32(), llvm::LLVMTypeOf(arg)]));
+ let llret_t = T_ptr(T_struct([T_i32(), llvm::LLVMTypeOf(arg)]));
llretptr = bcx.build.BitCast(llretptr, llret_t);
}
- let dst = GEP_tup_like(bcx, tup_t, llretptr, ~[0, 1]);
+ let dst = GEP_tup_like(bcx, tup_t, llretptr, [0, 1]);
bcx = dst.bcx;
bcx = copy_val(bcx, INIT, dst.val, arg, arg_t).bcx;
- let flag = GEP_tup_like(bcx, tup_t, llretptr, ~[0, 0]);
+ let flag = GEP_tup_like(bcx, tup_t, llretptr, [0, 0]);
bcx = flag.bcx;
bcx.build.Store(C_int(1), flag.val);
build_return(bcx);
}
// Translate variant arguments to function arguments.
- let fn_args: [ast::arg] = ~[];
+ let fn_args: [ast::arg] = [];
let i = 0u;
for varg: ast::variant_arg in variant.node.args {
fn_args +=
- ~[{mode: ast::alias(false),
- ty: varg.ty,
- ident: "arg" + uint::to_str(i, 10u),
- id: varg.id}];
+ [{mode: ast::alias(false),
+ ty: varg.ty,
+ ident: "arg" + uint::to_str(i, 10u),
+ id: varg.id}];
}
assert (cx.ccx.item_ids.contains_key(variant.node.id));
let llfndecl: ValueRef;
create_llargs_for_fn_args(fcx, ast::proto_fn, none::<ty::t>,
ty::ret_ty_of_fn(cx.ccx.tcx, variant.node.id),
fn_args, ty_params);
- let ty_param_substs: [ty::t] = ~[];
+ let ty_param_substs: [ty::t] = [];
i = 0u;
for tp: ast::ty_param in ty_params {
- ty_param_substs += ~[ty::mk_param(cx.ccx.tcx, i, tp.kind)];
+ ty_param_substs += [ty::mk_param(cx.ccx.tcx, i, tp.kind)];
i += 1u;
}
let arg_tys = arg_tys_of_fn(cx.ccx, variant.node.id);
let lltagptr =
bcx.build.PointerCast(fcx.llretptr,
T_opaque_tag_ptr(fcx.lcx.ccx.tn));
- let lldiscrimptr = bcx.build.GEP(lltagptr, ~[C_int(0), C_int(0)]);
+ let lldiscrimptr = bcx.build.GEP(lltagptr, [C_int(0), C_int(0)]);
bcx.build.Store(C_int(index), lldiscrimptr);
- bcx.build.GEP(lltagptr, ~[C_int(0), C_int(1)])
+ bcx.build.GEP(lltagptr, [C_int(0), C_int(1)])
};
i = 0u;
for va: ast::variant_arg in variant.node.args {
trans_tag_variant");
}
}
- let arg_ty = arg_tys.(i).ty;
+ let arg_ty = arg_tys[i].ty;
let llargval;
if ty::type_is_structural(cx.ccx.tcx, arg_ty) ||
ty::type_has_dynamic_size(cx.ccx.tcx, arg_ty) {
}
ast::item_mod(m) {
let sub_cx =
- @{path: cx.path + ~[item.ident],
- module_path: cx.module_path + ~[item.ident] with *cx};
+ @{path: cx.path + [item.ident],
+ module_path: cx.module_path + [item.ident] with *cx};
trans_mod(sub_cx, m);
}
ast::item_tag(variants, tps) {
fn decl_fn_and_pair_full(ccx: &@crate_ctxt, sp: &span, path: &[str],
_flav: str, ty_params: &[ast::ty_param],
node_id: ast::node_id, node_type: ty::t) {
- let llfty = type_of_fn_from_ty(ccx, sp, node_type,
- std::vec::len(ty_params));
+ let llfty =
+ type_of_fn_from_ty(ccx, sp, node_type, std::vec::len(ty_params));
alt ty::struct(ccx.tcx, node_type) {
ty::ty_fn(proto, inputs, output, _, _) {
llfty =
}
_ { ccx.sess.bug("decl_fn_and_pair(): fn item doesn't have fn type!"); }
}
-
- let s: str = mangle_internal_name_by_path(ccx, path);
+ let s: str = mangle_internal_name_by_path(ccx, path);
let llfn: ValueRef = decl_internal_fastcall_fn(ccx.llmod, s, llfty);
// Declare the global constant pair that points to it.
register_fn_pair(ccx, ps, llfty, llfn, node_id);
let is_main: bool = is_main_name(path) && !ccx.sess.get_opts().library;
- if is_main {
- create_main_wrapper(ccx, sp, llfn, node_type);
- }
+ if is_main { create_main_wrapper(ccx, sp, llfn, node_type); }
}
// Create a _rust_main(args: [str]) function which will be called from the
// runtime rust_start function
-fn create_main_wrapper(ccx: &@crate_ctxt, sp: &span,
- main_llfn: ValueRef, main_node_type: ty::t) {
+fn create_main_wrapper(ccx: &@crate_ctxt, sp: &span, main_llfn: ValueRef,
+ main_node_type: ty::t) {
if ccx.main_fn != none::<ValueRef> {
ccx.sess.span_fatal(sp, "multiple 'main' functions");
}
- let main_takes_ivec = alt ty::struct(ccx.tcx, main_node_type) {
- ty::ty_fn(_, args, _ ,_ ,_) {
- std::vec::len(args) != 0u
- }
- };
+ let main_takes_ivec =
+ alt ty::struct(ccx.tcx, main_node_type) {
+ ty::ty_fn(_, args, _, _, _) { std::vec::len(args) != 0u }
+ };
let llfn = create_main(ccx, sp, main_llfn, main_takes_ivec);
ccx.main_fn = some(llfn);
- fn create_main(ccx: &@crate_ctxt,
- sp: &span,
- main_llfn: ValueRef,
+ fn create_main(ccx: &@crate_ctxt, sp: &span, main_llfn: ValueRef,
takes_ivec: bool) -> ValueRef {
- let ivecarg_ty: ty::arg = {
- mode: ty::mo_val,
- ty: ty::mk_vec(ccx.tcx, {
- ty: ty::mk_str(ccx.tcx),
- mut: ast::imm
- })
- };
- let llfty = type_of_fn(ccx, sp,
- ast::proto_fn,
- ~[ivecarg_ty],
- ty::mk_nil(ccx.tcx),
- 0u);
+ let ivecarg_ty: ty::arg =
+ {mode: ty::mo_val,
+ ty:
+ ty::mk_vec(ccx.tcx,
+ {ty: ty::mk_str(ccx.tcx), mut: ast::imm})};
+ let llfty =
+ type_of_fn(ccx, sp, ast::proto_fn, [ivecarg_ty],
+ ty::mk_nil(ccx.tcx), 0u);
let llfdecl = decl_fastcall_fn(ccx.llmod, "_rust_main", llfty);
let fcx = new_fn_ctxt(new_local_ctxt(ccx), sp, llfdecl);
let lltaskarg = llvm::LLVMGetParam(llfdecl, 1u);
let llenvarg = llvm::LLVMGetParam(llfdecl, 2u);
let llargvarg = llvm::LLVMGetParam(llfdecl, 3u);
- let args = ~[lloutputarg,
- lltaskarg,
- llenvarg,
- llargvarg];
+ let args = [lloutputarg, lltaskarg, llenvarg, llargvarg];
bcx.build.FastCall(main_llfn, args);
} else {
let lloutputarg = llvm::LLVMGetParam(llfdecl, 0u);
// we're responsible for freeing it
let llivecptr = alloca(bcx, val_ty(llargvarg));
bcx.build.Store(llargvarg, llivecptr);
- bcx = maybe_free_ivec_heap_part(bcx, llivecptr,
- ty::mk_str(ccx.tcx)).bcx;
+ bcx =
+ maybe_free_ivec_heap_part(bcx, llivecptr,
+ ty::mk_str(ccx.tcx)).bcx;
- let args = ~[lloutputarg,
- lltaskarg,
- llenvarg];
+ let args = [lloutputarg, lltaskarg, llenvarg];
bcx.build.FastCall(main_llfn, args);
}
build_return(bcx);
external: bool) -> ValueRef {
let gvar =
llvm::LLVMAddGlobal(cx.llmod, T_fn_pair(*cx, llfnty), str::buf(ps));
- let pair = C_struct(~[llfn, C_null(T_opaque_closure_ptr(*cx))]);
+ let pair = C_struct([llfn, C_null(T_opaque_closure_ptr(*cx))]);
llvm::LLVMSetInitializer(gvar, pair);
llvm::LLVMSetGlobalConstant(gvar, True);
if !external {
let lcx = cx.fcx.lcx;
let pair = alloca(cx, T_fn_pair(*lcx.ccx, llfnty));
- let code_cell =
- cx.build.GEP(pair, ~[C_int(0), C_int(abi::fn_field_code)]);
+ let code_cell = cx.build.GEP(pair, [C_int(0), C_int(abi::fn_field_code)]);
cx.build.Store(llfn, code_cell);
- let env_cell = cx.build.GEP(pair, ~[C_int(0), C_int(abi::fn_field_box)]);
+ let env_cell = cx.build.GEP(pair, [C_int(0), C_int(abi::fn_field_box)]);
let llenvblobptr =
cx.build.PointerCast(llenvptr, T_opaque_closure_ptr(*lcx.ccx));
cx.build.Store(llenvblobptr, env_cell);
lltaskptr = vp2i(bcx, fcx.lltaskptr);
} else { lltaskptr = fcx.lltaskptr; }
- let call_args: [ValueRef] = ~[];
- if pass_task { call_args += ~[lltaskptr]; }
- if uses_retptr { call_args += ~[bcx.fcx.llretptr]; }
+ let call_args: [ValueRef] = [];
+ if pass_task { call_args += [lltaskptr]; }
+ if uses_retptr { call_args += [bcx.fcx.llretptr]; }
let arg_n = 3u;
for each i: uint in uint::range(0u, num_ty_param) {
let llarg = llvm::LLVMGetParam(fcx.llfn, arg_n);
- fcx.lltydescs += ~[llarg];
+ fcx.lltydescs += [llarg];
assert (llarg as int != 0);
if cast_to_i32 {
- call_args += ~[vp2i(bcx, llarg)];
- } else { call_args += ~[llarg]; }
+ call_args += [vp2i(bcx, llarg)];
+ } else { call_args += [llarg]; }
arg_n += 1u;
}
fn convert_arg_to_i32(cx: &@block_ctxt, v: ValueRef, t: ty::t,
fn trans_simple_native_abi(bcx: &@block_ctxt, name: str,
call_args: &mutable [ValueRef], fn_type: ty::t,
- uses_retptr: bool, cc: uint)
- -> {val: ValueRef, rptr: ValueRef} {
- let call_arg_tys: [TypeRef] = ~[];
- for arg: ValueRef in call_args { call_arg_tys += ~[val_ty(arg)]; }
+ uses_retptr: bool, cc: uint) ->
+ {val: ValueRef, rptr: ValueRef} {
+ let call_arg_tys: [TypeRef] = [];
+ for arg: ValueRef in call_args { call_arg_tys += [val_ty(arg)]; }
let llnativefnty;
if uses_retptr {
let args = ty::ty_fn_args(ccx.tcx, fn_type);
// Build up the list of arguments.
- let drop_args: [{val: ValueRef, ty: ty::t}] = ~[];
+ let drop_args: [{val: ValueRef, ty: ty::t}] = [];
let i = arg_n;
for arg: ty::arg in args {
let llarg = llvm::LLVMGetParam(fcx.llfn, i);
assert (llarg as int != 0);
if cast_to_i32 {
let llarg_i32 = convert_arg_to_i32(bcx, llarg, arg.ty, arg.mode);
- call_args += ~[llarg_i32];
- } else { call_args += ~[llarg]; }
- if arg.mode == ty::mo_val {
- drop_args += ~[{val: llarg, ty: arg.ty}];
- }
+ call_args += [llarg_i32];
+ } else { call_args += [llarg]; }
+ if arg.mode == ty::mo_val { drop_args += [{val: llarg, ty: arg.ty}]; }
i += 1u;
}
let r;
}
_ {
r =
- trans_native_call(bcx.build, ccx.externs,
- ccx.llmod, name, call_args);
+ trans_native_call(bcx.build, ccx.externs, ccx.llmod, name,
+ call_args);
rptr = bcx.build.BitCast(fcx.llretptr, T_ptr(T_i32()));
}
}
finish_fn(fcx, lltop);
}
-fn item_path(item: &@ast::item) -> [str] { ret ~[item.ident]; }
+fn item_path(item: &@ast::item) -> [str] { ret [item.ident]; }
fn collect_native_item(ccx: @crate_ctxt, i: &@ast::native_item, pt: &[str],
_v: &vt<[str]>) {
ast::item_const(_, _) {
let typ = node_id_type(ccx, i.id);
let s =
- mangle_exported_name(ccx, pt + ~[i.ident],
+ mangle_exported_name(ccx, pt + [i.ident],
node_id_type(ccx, i.id));
let g =
llvm::LLVMAddGlobal(ccx.llmod, type_of(ccx, i.span, typ),
visit_item: bind collect_item_1(ccx, _, _, _) with *visitor0};
let visitor2 =
@{visit_item: bind collect_item_2(ccx, _, _, _) with *visitor0};
- visit::visit_crate(*crate, ~[], visit::mk_vt(visitor1));
- visit::visit_crate(*crate, ~[], visit::mk_vt(visitor2));
+ visit::visit_crate(*crate, [], visit::mk_vt(visitor1));
+ visit::visit_crate(*crate, [], visit::mk_vt(visitor2));
}
fn collect_tag_ctor(ccx: @crate_ctxt, i: &@ast::item, pt: &[str],
ast::item_tag(variants, tps) {
for variant: ast::variant in variants {
if std::vec::len(variant.node.args) != 0u {
- decl_fn_and_pair(ccx, i.span, new_pt + ~[variant.node.name],
+ decl_fn_and_pair(ccx, i.span, new_pt + [variant.node.name],
"tag", tps, variant.node.id);
}
}
let visitor =
@{visit_item: bind collect_tag_ctor(ccx, _, _, _)
with *visit::default_visitor()};
- visit::visit_crate(*crate, ~[], visit::mk_vt(visitor));
+ visit::visit_crate(*crate, [], visit::mk_vt(visitor));
}
let i = 0u;
let n_variants = std::vec::len::<ast::variant>(variants);
while i < n_variants {
- let variant = variants.(i);
- let p = new_pt + ~[it.ident, variant.node.name, "discrim"];
+ let variant = variants[i];
+ let p = new_pt + [it.ident, variant.node.name, "discrim"];
let s = mangle_exported_name(ccx, p, ty::mk_int(ccx.tcx));
let discrim_gvar =
llvm::LLVMAddGlobal(ccx.llmod, T_int(), str::buf(s));
let visitor =
@{visit_item: bind trans_constant(ccx, _, _, _)
with *visit::default_visitor()};
- visit::visit_crate(*crate, ~[], visit::mk_vt(visitor));
+ visit::visit_crate(*crate, [], visit::mk_vt(visitor));
}
fn vp2i(cx: &@block_ctxt, v: ValueRef) -> ValueRef {
fn declare_intrinsics(llmod: ModuleRef) -> hashmap<str, ValueRef> {
let T_memmove32_args: [TypeRef] =
- ~[T_ptr(T_i8()), T_ptr(T_i8()), T_i32(), T_i32(), T_i1()];
+ [T_ptr(T_i8()), T_ptr(T_i8()), T_i32(), T_i32(), T_i1()];
let T_memmove64_args: [TypeRef] =
- ~[T_ptr(T_i8()), T_ptr(T_i8()), T_i64(), T_i32(), T_i1()];
+ [T_ptr(T_i8()), T_ptr(T_i8()), T_i64(), T_i32(), T_i1()];
let T_memset32_args: [TypeRef] =
- ~[T_ptr(T_i8()), T_i8(), T_i32(), T_i32(), T_i1()];
+ [T_ptr(T_i8()), T_i8(), T_i32(), T_i32(), T_i1()];
let T_memset64_args: [TypeRef] =
- ~[T_ptr(T_i8()), T_i8(), T_i64(), T_i32(), T_i1()];
- let T_trap_args: [TypeRef] = ~[];
+ [T_ptr(T_i8()), T_i8(), T_i64(), T_i32(), T_i1()];
+ let T_trap_args: [TypeRef] = [];
let gcroot =
decl_cdecl_fn(llmod, "llvm.gcroot",
- T_fn(~[T_ptr(T_ptr(T_i8())), T_ptr(T_i8())], T_void()));
+ T_fn([T_ptr(T_ptr(T_i8())), T_ptr(T_i8())], T_void()));
let gcread =
decl_cdecl_fn(llmod, "llvm.gcread",
- T_fn(~[T_ptr(T_i8()), T_ptr(T_ptr(T_i8()))], T_void()));
+ T_fn([T_ptr(T_i8()), T_ptr(T_ptr(T_i8()))], T_void()));
let memmove32 =
decl_cdecl_fn(llmod, "llvm.memmove.p0i8.p0i8.i32",
T_fn(T_memmove32_args, T_void()));
}
fn trap(bcx: &@block_ctxt) {
- let v: [ValueRef] = ~[];
+ let v: [ValueRef] = [];
alt bcx_ccx(bcx).intrinsics.find("llvm.trap") {
some(x) { bcx.build.Call(x, v); }
_ { bcx_ccx(bcx).sess.bug("unbound llvm.trap in trap"); }
}
fn decl_no_op_type_glue(llmod: ModuleRef, taskptr_type: TypeRef) -> ValueRef {
- let ty = T_fn(~[taskptr_type, T_ptr(T_i8())], T_void());
+ let ty = T_fn([taskptr_type, T_ptr(T_i8())], T_void());
ret decl_fastcall_fn(llmod, abi::no_op_type_glue_name(), ty);
}
fn vec_fill(bcx: &@block_ctxt, v: ValueRef) -> ValueRef {
ret bcx.build.Load(bcx.build.GEP(v,
- ~[C_int(0), C_int(abi::vec_elt_fill)]));
+ [C_int(0), C_int(abi::vec_elt_fill)]));
}
fn vec_p0(bcx: &@block_ctxt, v: ValueRef) -> ValueRef {
- let p = bcx.build.GEP(v, ~[C_int(0), C_int(abi::vec_elt_data)]);
+ let p = bcx.build.GEP(v, [C_int(0), C_int(abi::vec_elt_data)]);
ret bcx.build.PointerCast(p, T_ptr(T_i8()));
}
}
fn create_module_map(ccx: &@crate_ctxt) -> ValueRef {
- let elttype = T_struct(~[T_int(), T_int()]);
+ let elttype = T_struct([T_int(), T_int()]);
let maptype = T_array(elttype, ccx.module_data.size() + 1u);
let map =
llvm::LLVMAddGlobal(ccx.llmod, maptype, str::buf("_rust_mod_map"));
llvm::LLVMSetLinkage(map,
lib::llvm::LLVMInternalLinkage as llvm::Linkage);
- let elts: [ValueRef] = ~[];
+ let elts: [ValueRef] = [];
for each item: @{key: str, val: ValueRef} in ccx.module_data.items() {
- let elt = C_struct(~[p2i(C_cstr(ccx, item.key)), p2i(item.val)]);
- elts += ~[elt];
+ let elt = C_struct([p2i(C_cstr(ccx, item.key)), p2i(item.val)]);
+ elts += [elt];
}
- let term = C_struct(~[C_int(0), C_int(0)]);
- elts += ~[term];
+ let term = C_struct([C_int(0), C_int(0)]);
+ elts += [term];
llvm::LLVMSetInitializer(map, C_array(elttype, elts));
ret map;
}
// FIXME use hashed metadata instead of crate names once we have that
fn create_crate_map(ccx: &@crate_ctxt) -> ValueRef {
- let subcrates: [ValueRef] = ~[];
+ let subcrates: [ValueRef] = [];
let i = 1;
let cstore = ccx.sess.get_cstore();
while cstore::have_crate_data(cstore, i) {
let nm = "_rust_crate_map_" + cstore::get_crate_data(cstore, i).name;
- let cr =
- llvm::LLVMAddGlobal(ccx.llmod, T_int(), str::buf(nm));
- subcrates += ~[p2i(cr)];
+ let cr = llvm::LLVMAddGlobal(ccx.llmod, T_int(), str::buf(nm));
+ subcrates += [p2i(cr)];
i += 1;
}
- subcrates += ~[C_int(0)];
+ subcrates += [C_int(0)];
let mapname;
if ccx.sess.get_opts().library {
mapname = ccx.link_meta.name;
} else { mapname = "toplevel"; }
let sym_name = "_rust_crate_map_" + mapname;
let arrtype = T_array(T_int(), std::vec::len::<ValueRef>(subcrates));
- let maptype = T_struct(~[T_int(), arrtype]);
+ let maptype = T_struct([T_int(), arrtype]);
let map = llvm::LLVMAddGlobal(ccx.llmod, maptype, str::buf(sym_name));
llvm::LLVMSetLinkage(map,
lib::llvm::LLVMExternalLinkage as llvm::Linkage);
llvm::LLVMSetInitializer(map,
- C_struct(~[p2i(create_module_map(ccx)),
- C_array(T_int(), subcrates)]));
+ C_struct([p2i(create_module_map(ccx)),
+ C_array(T_int(), subcrates)]));
ret map;
}
fn write_metadata(cx: &@crate_ctxt, crate: &@ast::crate) {
if !cx.sess.get_opts().library { ret; }
let llmeta = C_postr(metadata::encoder::encode_metadata(cx, crate));
- let llconst = trans_common::C_struct(~[llmeta]);
+ let llconst = trans_common::C_struct([llmeta]);
let llglobal =
llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst),
str::buf("rust_metadata"));
str::buf("llvm.used"));
llvm::LLVMSetLinkage(llvm_used,
lib::llvm::LLVMAppendingLinkage as llvm::Linkage);
- llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, ~[llglobal]));
+ llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
}
fn trans_crate(sess: &session::session, crate: &@ast::crate, tcx: &ty::ctxt,
mutable n_glues_created: 0u,
mutable n_null_glues: 0u,
mutable n_real_glues: 0u,
- fn_times: @mutable ~[]},
+ fn_times: @mutable []},
upcalls:
upcall::declare_upcalls(tn, tydesc_type, taskptr_type, llmod),
rust_object_type: T_rust_object(),
write_metadata(cx.ccx, crate);
if ccx.sess.get_opts().stats {
log_err "--- trans stats ---";
- log_err #fmt("n_static_tydescs: %u", ccx.stats.n_static_tydescs);
- log_err #fmt("n_derived_tydescs: %u", ccx.stats.n_derived_tydescs);
- log_err #fmt("n_glues_created: %u", ccx.stats.n_glues_created);
- log_err #fmt("n_null_glues: %u", ccx.stats.n_null_glues);
- log_err #fmt("n_real_glues: %u", ccx.stats.n_real_glues);
+ log_err #fmt["n_static_tydescs: %u", ccx.stats.n_static_tydescs];
+ log_err #fmt["n_derived_tydescs: %u", ccx.stats.n_derived_tydescs];
+ log_err #fmt["n_glues_created: %u", ccx.stats.n_glues_created];
+ log_err #fmt["n_null_glues: %u", ccx.stats.n_null_glues];
+ log_err #fmt["n_real_glues: %u", ccx.stats.n_real_glues];
for timing: {ident: str, time: int} in *ccx.stats.fn_times {
- log_err #fmt("time: %s took %d ms", timing.ident, timing.time);
+ log_err #fmt["time: %s took %d ms", timing.ident, timing.time];
}
}
ret llmod;
fn bind_for_pat(p: &@ast::pat, br: &match_branch, val: ValueRef) {
alt p.node {
- ast::pat_bind(name) { br.bound += ~[{ident: name, val: val}]; }
+ ast::pat_bind(name) { br.bound += [{ident: name, val: val}]; }
_ { }
}
}
-type enter_pat = fn(&@ast::pat) -> option::t<[@ast::pat]> ;
+type enter_pat = fn(&@ast::pat) -> option::t<[@ast::pat]>;
fn enter_match(m: &match, col: uint, val: ValueRef, e: &enter_pat) -> match {
- let result = ~[];
+ let result = [];
for br: match_branch in m {
- alt e(br.pats.(col)) {
+ alt e(br.pats[col]) {
some(sub) {
let pats =
vec::slice(br.pats, 0u, col) + sub +
vec::slice(br.pats, col + 1u, vec::len(br.pats));
let new_br = @{pats: pats with *br};
- result += ~[new_br];
- bind_for_pat(br.pats.(col), new_br, val);
+ result += [new_br];
+ bind_for_pat(br.pats[col], new_br, val);
}
none. { }
}
fn enter_default(m: &match, col: uint, val: ValueRef) -> match {
fn e(p: &@ast::pat) -> option::t<[@ast::pat]> {
- ret if matches_always(p) { some(~[]) } else { none };
+ ret if matches_always(p) { some([]) } else { none };
}
ret enter_match(m, col, val, e);
}
} else { none };
}
ast::pat_lit(l) {
- ret if opt_eq(lit(l), opt) { some(~[]) } else { none };
+ ret if opt_eq(lit(l), opt) { some([]) } else { none };
}
_ { ret some(vec::init_elt(dummy, size)); }
}
option::t<[@ast::pat]> {
alt p.node {
ast::pat_rec(fpats, _) {
- let pats = ~[];
+ let pats = [];
for fname: ast::ident in fields {
let pat = dummy;
for fpat: ast::field_pat in fpats {
if str::eq(fpat.ident, fname) { pat = fpat.pat; break; }
}
- pats += ~[pat];
+ pats += [pat];
}
ret some(pats);
}
fn enter_tup(m: &match, col: uint, val: ValueRef, n_elts: uint) -> match {
let dummy = @{id: 0, node: ast::pat_wild, span: dummy_sp()};
- fn e(dummy: &@ast::pat, n_elts: uint, p: &@ast::pat)
- -> option::t<[@ast::pat]> {
+ fn e(dummy: &@ast::pat, n_elts: uint, p: &@ast::pat) ->
+ option::t<[@ast::pat]> {
alt p.node {
ast::pat_tup(elts) { ret some(elts); }
_ { ret some(vec::init_elt(dummy, n_elts)); }
let dummy = @{id: 0, node: ast::pat_wild, span: dummy_sp()};
fn e(dummy: &@ast::pat, p: &@ast::pat) -> option::t<[@ast::pat]> {
alt p.node {
- ast::pat_box(sub) { ret some(~[sub]); }
- _ { ret some(~[dummy]); }
+ ast::pat_box(sub) { ret some([sub]); }
+ _ { ret some([dummy]); }
}
}
ret enter_match(m, col, val, bind e(dummy, _));
fn get_options(ccx: &@crate_ctxt, m: &match, col: uint) -> [opt] {
fn add_to_set(set: &mutable [opt], val: &opt) {
for l: opt in set { if opt_eq(l, val) { ret; } }
- set += ~[val];
+ set += [val];
}
- let found = ~[];
+ let found = [];
for br: match_branch in m {
- alt br.pats.(col).node {
+ alt br.pats[col].node {
ast::pat_lit(l) { add_to_set(found, lit(l)); }
ast::pat_tag(_, _) {
- add_to_set(found, variant_opt(ccx, br.pats.(col).id));
+ add_to_set(found, variant_opt(ccx, br.pats[col].id));
}
_ { }
}
}
fn extract_variant_args(bcx: @block_ctxt, pat_id: ast::node_id,
- vdefs: &{tg: def_id, var: def_id}, val: ValueRef)
- -> {vals: [ValueRef], bcx: @block_ctxt} {
+ vdefs: &{tg: def_id, var: def_id}, val: ValueRef) ->
+ {vals: [ValueRef], bcx: @block_ctxt} {
let ccx = bcx.fcx.lcx.ccx;
let ty_param_substs = ty::node_id_to_type_params(ccx.tcx, pat_id);
let blobptr = val;
let variants = ty::tag_variants(ccx.tcx, vdefs.tg);
- let args = ~[];
+ let args = [];
let size =
vec::len(ty::tag_variant_with_id(ccx.tcx, vdefs.tg, vdefs.var).args);
if size > 0u && vec::len(variants) != 1u {
let tagptr =
bcx.build.PointerCast(val,
trans_common::T_opaque_tag_ptr(ccx.tn));
- blobptr = bcx.build.GEP(tagptr, ~[C_int(0), C_int(1)]);
+ blobptr = bcx.build.GEP(tagptr, [C_int(0), C_int(1)]);
}
let i = 0u;
while i < size {
trans::GEP_tag(bcx, blobptr, vdefs.tg, vdefs.var, ty_param_substs,
i as int);
bcx = r.bcx;
- args += ~[r.val];
+ args += [r.val];
i += 1u;
}
ret {vals: args, bcx: bcx};
}
fn collect_record_fields(m: &match, col: uint) -> [ast::ident] {
- let fields = ~[];
+ let fields = [];
for br: match_branch in m {
- alt br.pats.(col).node {
+ alt br.pats[col].node {
ast::pat_rec(fs, _) {
for f: ast::field_pat in fs {
if !vec::any(bind str::eq(f.ident, _), fields) {
- fields += ~[f.ident];
+ fields += [f.ident];
}
}
}
fn any_box_pat(m: &match, col: uint) -> bool {
for br: match_branch in m {
- alt br.pats.(col).node { ast::pat_box(_) { ret true; } _ { } }
+ alt br.pats[col].node { ast::pat_box(_) { ret true; } _ { } }
}
ret false;
}
fn any_tup_pat(m: &match, col: uint) -> bool {
for br: match_branch in m {
- alt br.pats.(col).node { ast::pat_tup(_) { ret true; } _ { } }
+ alt br.pats[col].node { ast::pat_tup(_) { ret true; } _ { } }
}
ret false;
}
type mk_fail = fn() -> BasicBlockRef;
fn pick_col(m: &match) -> uint {
- let scores = vec::init_elt_mut(0u, vec::len(m.(0).pats));
+ let scores = vec::init_elt_mut(0u, vec::len(m[0].pats));
for br: match_branch in m {
let i = 0u;
for p: @ast::pat in br.pats {
alt p.node {
- ast::pat_lit(_) | ast::pat_tag(_, _) { scores.(i) += 1u; }
- _ {}
+ ast::pat_lit(_) | ast::pat_tag(_, _) { scores[i] += 1u; }
+ _ { }
}
i += 1u;
}
if score == 0u { ret i; }
// If no irrefutable ones are found, we pick the one with the biggest
// branching factor.
- if score > max_score {
- max_score = score;
- best_col = i;
- }
+ if score > max_score { max_score = score; best_col = i; }
i += 1u;
}
ret best_col;
fn compile_submatch(bcx: @block_ctxt, m: &match, vals: [ValueRef],
f: &mk_fail, exits: &mutable [exit_node]) {
if vec::len(m) == 0u { bcx.build.Br(f()); ret; }
- if vec::len(m.(0).pats) == 0u {
- exits += ~[{bound: m.(0).bound, from: bcx.llbb, to: m.(0).body}];
- bcx.build.Br(m.(0).body);
+ if vec::len(m[0].pats) == 0u {
+ exits += [{bound: m[0].bound, from: bcx.llbb, to: m[0].body}];
+ bcx.build.Br(m[0].body);
ret;
}
let col = pick_col(m);
- let val = vals.(col);
- let vals_left = vec::slice(vals, 0u, col) +
- vec::slice(vals, col + 1u, vec::len(vals));
+ let val = vals[col];
+ let vals_left =
+ vec::slice(vals, 0u, col) +
+ vec::slice(vals, col + 1u, vec::len(vals));
let ccx = bcx.fcx.lcx.ccx;
let pat_id = 0;
for br: match_branch in m {
+
// Find a real id (we're adding placeholder wildcard patterns, but
// each column is guaranteed to have at least one real pattern)
- if pat_id == 0 { pat_id = br.pats.(col).id; }
+ if pat_id == 0 { pat_id = br.pats[col].id; }
}
let rec_fields = collect_record_fields(m, col);
let rec_ty = ty::node_id_to_monotype(ccx.tcx, pat_id);
let fields =
alt ty::struct(ccx.tcx, rec_ty) { ty::ty_rec(fields) { fields } };
- let rec_vals = ~[];
+ let rec_vals = [];
for field_name: ast::ident in rec_fields {
let ix: uint =
ty::field_idx(ccx.sess, dummy_sp(), field_name, fields);
- let r = trans::GEP_tup_like(bcx, rec_ty, val, ~[0, ix as int]);
- rec_vals += ~[r.val];
+ let r = trans::GEP_tup_like(bcx, rec_ty, val, [0, ix as int]);
+ rec_vals += [r.val];
bcx = r.bcx;
}
compile_submatch(bcx, enter_rec(m, col, rec_fields, val),
if any_tup_pat(m, col) {
let tup_ty = ty::node_id_to_monotype(ccx.tcx, pat_id);
- let n_tup_elts = alt ty::struct(ccx.tcx, tup_ty) {
- ty::ty_tup(elts) { vec::len(elts) }
- };
- let tup_vals = ~[], i = 0u;
+ let n_tup_elts =
+ alt ty::struct(ccx.tcx, tup_ty) {
+ ty::ty_tup(elts) { vec::len(elts) }
+ };
+ let tup_vals = [], i = 0u;
while i < n_tup_elts {
- let r = trans::GEP_tup_like(bcx, tup_ty, val, ~[0, i as int]);
- tup_vals += ~[r.val];
+ let r = trans::GEP_tup_like(bcx, tup_ty, val, [0, i as int]);
+ tup_vals += [r.val];
bcx = r.bcx;
i += 1u;
}
let box = bcx.build.Load(val);
let unboxed =
bcx.build.InBoundsGEP(box,
- ~[C_int(0),
- C_int(back::abi::box_rc_field_body)]);
- compile_submatch(bcx, enter_box(m, col, val), ~[unboxed] + vals_left,
+ [C_int(0),
+ C_int(back::abi::box_rc_field_body)]);
+ compile_submatch(bcx, enter_box(m, col, val), [unboxed] + vals_left,
f, exits);
ret;
}
let kind = no_branch;
let test_val = val;
if vec::len(opts) > 0u {
- alt opts.(0) {
+ alt opts[0] {
var(_, vdef) {
if vec::len(ty::tag_variants(ccx.tcx, vdef.tg)) == 1u {
kind = single;
} else {
- let tagptr = bcx.build.PointerCast
- (val, trans_common::T_opaque_tag_ptr(ccx.tn));
- let discrimptr = bcx.build.GEP(tagptr, ~[C_int(0), C_int(0)]);
+ let tagptr =
+ bcx.build.PointerCast(
+ val,
+ trans_common::T_opaque_tag_ptr(ccx.tn));
+ let discrimptr = bcx.build.GEP(tagptr, [C_int(0), C_int(0)]);
test_val = bcx.build.Load(discrimptr);
kind = switch;
}
let r = trans_opt(bcx, opt);
bcx = r.bcx;
let t = ty::node_id_to_type(ccx.tcx, pat_id);
- let eq = trans::trans_compare(bcx, ast::eq, test_val, t,
- r.val, t);
+ let eq =
+ trans::trans_compare(bcx, ast::eq, test_val, t, r.val, t);
bcx = new_sub_block_ctxt(bcx, "next");
eq.bcx.build.CondBr(eq.val, opt_cx.llbb, bcx.llbb);
}
_ { }
}
let size = 0u;
- let unpacked = ~[];
+ let unpacked = [];
alt opt {
var(_, vdef) {
let args = extract_variant_args(opt_cx, pat_id, vdef, val);
let our_block = bcx.llbb as uint;
let success = true;
for each item: @{key: ast::ident, val: ast::node_id} in ids.items() {
- let llbbs = ~[];
- let vals = ~[];
+ let llbbs = [];
+ let vals = [];
for ex: exit_node in map {
if ex.to as uint == our_block {
alt assoc(item.key, ex.bound) {
- some(val) { llbbs += ~[ex.from]; vals += ~[val]; }
+ some(val) { llbbs += [ex.from]; vals += [val]; }
none. { }
}
}
}
if vec::len(vals) > 0u {
- let phi = bcx.build.Phi(val_ty(vals.(0)), vals, llbbs);
+ let phi = bcx.build.Phi(val_ty(vals[0]), vals, llbbs);
bcx.fcx.lllocals.insert(item.val, phi);
} else { success = false; }
}
fn trans_alt(cx: &@block_ctxt, expr: &@ast::expr, arms: &[ast::arm],
output: &trans::out_method) -> result {
- let bodies = ~[];
- let match: match = ~[];
+ let bodies = [];
+ let match: match = [];
let er = trans::trans_expr(cx, expr);
- if (ty::type_is_bot(bcx_tcx(cx), ty::expr_ty(bcx_tcx(cx), expr))) {
+ if ty::type_is_bot(bcx_tcx(cx), ty::expr_ty(bcx_tcx(cx), expr)) {
+
// No need to generate code for alt,
// since the disc diverges.
- if (!cx.build.is_terminated()) {
+ if !cx.build.is_terminated() {
ret rslt(cx, cx.build.Unreachable());
- }
- else {
- ret er;
- }
+ } else { ret er; }
}
for a: ast::arm in arms {
let body = new_scope_block_ctxt(cx, "case_body");
- bodies += ~[body];
+ bodies += [body];
for p: @ast::pat in a.pats {
- match += ~[@{pats: ~[p], body: body.llbb, mutable bound: ~[]}];
+ match += [@{pats: [p], body: body.llbb, mutable bound: []}];
}
}
done: @mutable option::t<BasicBlockRef>) -> BasicBlockRef {
alt *done { some(bb) { ret bb; } _ { } }
let fail_cx = new_sub_block_ctxt(cx, "case_fallthrough");
- trans::trans_fail(fail_cx, some(sp), "non-exhaustive match failure");
+ trans::trans_fail(fail_cx, some(sp), "non-exhaustive match failure");;
*done = some(fail_cx.llbb);
ret fail_cx.llbb;
}
- let exit_map = ~[];
+ let exit_map = [];
let t = trans::node_id_type(cx.fcx.lcx.ccx, expr.id);
let v = trans::spill_if_immediate(er.bcx, er.val, t);
- compile_submatch(er.bcx, match, ~[v],
- bind mk_fail(cx, expr.span, fail_cx), exit_map);
+ compile_submatch(er.bcx, match, [v], bind mk_fail(cx, expr.span, fail_cx),
+ exit_map);
let i = 0u;
- let arm_results = ~[];
+ let arm_results = [];
for a: ast::arm in arms {
- let body_cx = bodies.(i);
- if make_phi_bindings(body_cx, exit_map, ast::pat_id_map(a.pats.(0))) {
+ let body_cx = bodies[i];
+ if make_phi_bindings(body_cx, exit_map, ast::pat_id_map(a.pats[0])) {
let block_res = trans::trans_block(body_cx, a.body, output);
- arm_results += ~[block_res];
+ arm_results += [block_res];
} else { // Unreachable
- arm_results += ~[rslt(body_cx, C_nil())];
+ arm_results += [rslt(body_cx, C_nil())];
}
i += 1u;
}
// Not alt-related, but similar to the pattern-munging code above
fn bind_irrefutable_pat(bcx: @block_ctxt, pat: &@ast::pat, val: ValueRef,
table: hashmap<ast::node_id, ValueRef>,
- make_copy: bool)
- -> @block_ctxt {
+ make_copy: bool) -> @block_ctxt {
let ccx = bcx.fcx.lcx.ccx;
alt pat.node {
ast::pat_bind(_) {
bcx = trans::copy_ty(bcx, loaded, ty).bcx;
table.insert(pat.id, alloc);
trans_common::add_clean(bcx, alloc, ty);
- } else {
- table.insert(pat.id, val);
- }
+ } else { table.insert(pat.id, val); }
}
ast::pat_tag(_, sub) {
if vec::len(sub) == 0u { ret bcx; }
let args = extract_variant_args(bcx, pat.id, vdefs, val);
let i = 0;
for argval: ValueRef in args.vals {
- bcx = bind_irrefutable_pat(bcx, sub.(i), argval, table,
- make_copy);
+ bcx = bind_irrefutable_pat(bcx, sub[i], argval, table, make_copy);
i += 1;
}
}
for f: ast::field_pat in fields {
let ix: uint =
ty::field_idx(ccx.sess, pat.span, f.ident, rec_fields);
- let r = trans::GEP_tup_like(bcx, rec_ty, val, ~[0, ix as int]);
+ let r = trans::GEP_tup_like(bcx, rec_ty, val, [0, ix as int]);
bcx = bind_irrefutable_pat(r.bcx, f.pat, r.val, table, make_copy);
}
}
let tup_ty = ty::node_id_to_monotype(ccx.tcx, pat.id);
let i = 0u;
for elem in elems {
- let r = trans::GEP_tup_like(bcx, tup_ty, val, ~[0, i as int]);
+ let r = trans::GEP_tup_like(bcx, tup_ty, val, [0, i as int]);
bcx = bind_irrefutable_pat(r.bcx, elem, r.val, table, make_copy);
i += 1u;
}
}
ast::pat_box(inner) {
let box = bcx.build.Load(val);
- let unboxed = bcx.build.InBoundsGEP
- (box, ~[C_int(0), C_int(back::abi::box_rc_field_body)]);
+ let unboxed =
+ bcx.build.InBoundsGEP(box,
+ [C_int(0),
+ C_int(back::abi::box_rc_field_body)]);
bcx = bind_irrefutable_pat(bcx, inner, unboxed, table, true);
}
- ast::pat_wild. | ast::pat_lit(_) {}
+ ast::pat_wild. | ast::pat_lit(_) { }
}
ret bcx;
}
type glue_fns = {no_op_type_glue: ValueRef};
tag tydesc_kind {
- tk_static; // Static (monomorphic) type descriptor.
- tk_param; // Type parameter.
- tk_derived; // Derived from a typaram or another derived tydesc.
+ tk_static; // Static (monomorphic) type descriptor.
+ tk_param; // Type parameter.
+ tk_derived; // Derived from a typaram or another derived tydesc.
}
type tydesc_info =
fn_times: @mutable [{ident: str, time: int}]};
// Crate context. Every crate we compile has one of these.
-type crate_ctxt = {
- sess: session::session,
- llmod: ModuleRef,
- td: target_data,
- tn: type_names,
- externs: hashmap<str, ValueRef>,
- intrinsics: hashmap<str, ValueRef>,
-
+type crate_ctxt =
// A mapping from the def_id of each item in this crate to the address
// of the first instruction of the item's definition in the executable
// we're generating.
- item_ids: hashmap<ast::node_id, ValueRef>,
- ast_map: ast_map::map,
- item_symbols: hashmap<ast::node_id, str>,
- mutable main_fn: option::t<ValueRef>,
- link_meta: link::link_meta,
// TODO: hashmap<tup(tag_id,subtys), @tag_info>
- tag_sizes: hashmap<ty::t, uint>,
- discrims: hashmap<ast::node_id, ValueRef>,
- discrim_symbols: hashmap<ast::node_id, str>,
- fn_pairs: hashmap<ast::node_id, ValueRef>,
- consts: hashmap<ast::node_id, ValueRef>,
- obj_methods: hashmap<ast::node_id, ()>,
- tydescs: hashmap<ty::t, @tydesc_info>,
- module_data: hashmap<str, ValueRef>,
- lltypes: hashmap<ty::t, TypeRef>,
- glues: @glue_fns,
- names: namegen,
- sha: std::sha1::sha1,
- type_sha1s: hashmap<ty::t, str>,
- type_short_names: hashmap<ty::t, str>,
- tcx: ty::ctxt,
- stats: stats,
- upcalls: @upcall::upcalls,
- rust_object_type: TypeRef,
- tydesc_type: TypeRef,
- task_type: TypeRef,
- shape_cx: shape::ctxt,
- gc_cx: gc::ctxt
-};
+ {sess: session::session,
+ llmod: ModuleRef,
+ td: target_data,
+ tn: type_names,
+ externs: hashmap<str, ValueRef>,
+ intrinsics: hashmap<str, ValueRef>,
+ item_ids: hashmap<ast::node_id, ValueRef>,
+ ast_map: ast_map::map,
+ item_symbols: hashmap<ast::node_id, str>,
+ mutable main_fn: option::t<ValueRef>,
+ link_meta: link::link_meta,
+ tag_sizes: hashmap<ty::t, uint>,
+ discrims: hashmap<ast::node_id, ValueRef>,
+ discrim_symbols: hashmap<ast::node_id, str>,
+ fn_pairs: hashmap<ast::node_id, ValueRef>,
+ consts: hashmap<ast::node_id, ValueRef>,
+ obj_methods: hashmap<ast::node_id, ()>,
+ tydescs: hashmap<ty::t, @tydesc_info>,
+ module_data: hashmap<str, ValueRef>,
+ lltypes: hashmap<ty::t, TypeRef>,
+ glues: @glue_fns,
+ names: namegen,
+ sha: std::sha1::sha1,
+ type_sha1s: hashmap<ty::t, str>,
+ type_short_names: hashmap<ty::t, str>,
+ tcx: ty::ctxt,
+ stats: stats,
+ upcalls: @upcall::upcalls,
+ rust_object_type: TypeRef,
+ tydesc_type: TypeRef,
+ task_type: TypeRef,
+ shape_cx: shape::ctxt,
+ gc_cx: gc::ctxt};
type local_ctxt =
{path: [str],
// Function context. Every LLVM function we create will have one of
// these.
-type fn_ctxt = {
+type fn_ctxt =
// The ValueRef returned from a call to llvm::LLVMAddFunction; the
// address of the first instruction in the sequence of
// instructions for this function that will go in the .text
// section of the executable we're generating.
- llfn: ValueRef,
// The three implicit arguments that arrive in the function we're
// creating. For instance, foo(int, int) is really foo(ret*,
// convenience.
// Points to the current task.
- lltaskptr: ValueRef,
// Points to the current environment (bindings of variables to
// values), if this is a regular function; points to the current
// object, if this is a method.
- llenv: ValueRef,
// Points to where the return value of this function should end
// up.
- llretptr: ValueRef,
// The next three elements: "hoisted basic blocks" containing
// administrative activities that have to happen in only one place in
// A block for all the function's static allocas, so that LLVM
// will coalesce them into a single alloca call.
- mutable llstaticallocas: BasicBlockRef,
// A block containing code that copies incoming arguments to space
// already allocated by code in one of the llallocas blocks.
// (LLVM requires that arguments be copied to local allocas before
// allowing most any operation to be performed on them.)
- mutable llcopyargs: BasicBlockRef,
// The first block containing derived tydescs received from the
// runtime. See description of derived_tydescs, below.
- mutable llderivedtydescs_first: BasicBlockRef,
// The last block of the llderivedtydescs group.
- mutable llderivedtydescs: BasicBlockRef,
// A block for all of the dynamically sized allocas. This must be
// after llderivedtydescs, because these sometimes depend on
// for incoming function arguments? Or is it merely the block
// containing code that copies incoming args to space already
// alloca'd by code in llallocas?
- mutable lldynamicallocas: BasicBlockRef,
- mutable llreturn: BasicBlockRef,
// The token used to clear the dynamic allocas at the end of this frame.
- mutable llobstacktoken: option::t<ValueRef>,
// The 'self' object currently in use in this function, if there
// is one.
- mutable llself: option::t<val_self_pair>,
// If this function is actually a iter, a block containing the
// code called whenever the iter calls 'put'.
- mutable lliterbody: option::t<ValueRef>,
// If this function is actually a iter, the type of the function
// that that we call when we call 'put'. Having to track this is
// pretty irritating. We have to do it because we need the type if
// we are going to put the iterbody into a closure (if it appears
// in a for-each inside of an iter).
- mutable iterbodyty: option::t<ty::t>,
// The next four items: hash tables mapping from AST def_ids to
// LLVM-stuff-in-the-frame.
// Maps arguments to allocas created for them in llallocas.
- llargs: hashmap<ast::node_id, ValueRef>,
// Maps fields in objects to pointers into the interior of
// llself's body.
- llobjfields: hashmap<ast::node_id, ValueRef>,
// Maps the def_ids for local variables to the allocas created for
// them in llallocas.
- lllocals: hashmap<ast::node_id, ValueRef>,
// The same as above, but for variables accessed via the frame
// pointer we pass into an iter, for access to the static
// environment of the iter-calling frame.
- llupvars: hashmap<ast::node_id, ValueRef>,
// For convenience, a vector of the incoming tydescs for each of
// this functions type parameters, fetched via llvm::LLVMGetParam.
// For example, for a function foo::<A, B, C>(), lltydescs contains
// the ValueRefs for the tydescs for A, B, and C.
- mutable lltydescs: [ValueRef],
// Derived tydescs are tydescs created at runtime, for types that
// involve type parameters inside type constructors. For example,
// when information about both "[T]" and "T" are available. When
// such a tydesc is created, we cache it in the derived_tydescs
// table for the next time that such a tydesc is needed.
- derived_tydescs: hashmap<ty::t, derived_tydesc_info>,
// The node_id of the function, or -1 if it doesn't correspond to
// a user-defined function.
- id: ast::node_id,
// The source span where this function comes from, for error
// reporting.
- sp: span,
// This function's enclosing local context.
- lcx: @local_ctxt
-};
+ {llfn: ValueRef,
+ lltaskptr: ValueRef,
+ llenv: ValueRef,
+ llretptr: ValueRef,
+ mutable llstaticallocas: BasicBlockRef,
+ mutable llcopyargs: BasicBlockRef,
+ mutable llderivedtydescs_first: BasicBlockRef,
+ mutable llderivedtydescs: BasicBlockRef,
+ mutable lldynamicallocas: BasicBlockRef,
+ mutable llreturn: BasicBlockRef,
+ mutable llobstacktoken: option::t<ValueRef>,
+ mutable llself: option::t<val_self_pair>,
+ mutable lliterbody: option::t<ValueRef>,
+ mutable iterbodyty: option::t<ty::t>,
+ llargs: hashmap<ast::node_id, ValueRef>,
+ llobjfields: hashmap<ast::node_id, ValueRef>,
+ lllocals: hashmap<ast::node_id, ValueRef>,
+ llupvars: hashmap<ast::node_id, ValueRef>,
+ mutable lltydescs: [ValueRef],
+ derived_tydescs: hashmap<ty::t, derived_tydesc_info>,
+ id: ast::node_id,
+ sp: span,
+ lcx: @local_ctxt};
tag cleanup {
- clean(fn(&@block_ctxt) -> result );
- clean_temp(ValueRef, fn(&@block_ctxt) -> result );
+ clean(fn(&@block_ctxt) -> result);
+ clean_temp(ValueRef, fn(&@block_ctxt) -> result);
}
fn add_clean(cx: &@block_ctxt, val: ValueRef, ty: ty::t) {
- find_scope_cx(cx).cleanups += ~[clean(bind drop_slot(_, val, ty))];
+ find_scope_cx(cx).cleanups += [clean(bind drop_slot(_, val, ty))];
}
fn add_clean_temp(cx: &@block_ctxt, val: ValueRef, ty: ty::t) {
- find_scope_cx(cx).cleanups +=
- ~[clean_temp(val, bind drop_ty(_, val, ty))];
+ find_scope_cx(cx).cleanups += [clean_temp(val, bind drop_ty(_, val, ty))];
}
// Note that this only works for temporaries. We should, at some point, move
sc_cx.cleanups =
std::vec::slice(sc_cx.cleanups, 0u, found as uint) +
std::vec::slice(sc_cx.cleanups, (found as uint) + 1u,
- std::vec::len(sc_cx.cleanups));
+ std::vec::len(sc_cx.cleanups));
}
-fn get_res_dtor(ccx : &@crate_ctxt, sp : &span, did : &ast::def_id,
- inner_t : ty::t) -> ValueRef {
+fn get_res_dtor(ccx: &@crate_ctxt, sp: &span, did: &ast::def_id,
+ inner_t: ty::t) -> ValueRef {
if did.crate == ast::local_crate {
alt ccx.fn_pairs.find(did.node) {
- some(x) { ret x; }
- _ { ccx.tcx.sess.bug("get_res_dtor: can't find resource dtor!"); }
+ some(x) { ret x; }
+ _ { ccx.tcx.sess.bug("get_res_dtor: can't find resource dtor!"); }
}
}
let params = csearch::get_type_param_count(ccx.sess.get_cstore(), did);
- let f_t = trans::type_of_fn(ccx, sp, ast::proto_fn,
- ~[{ mode: ty::mo_alias(false), ty: inner_t }],
- ty::mk_nil(ccx.tcx), params);
+ let f_t =
+ trans::type_of_fn(ccx, sp, ast::proto_fn,
+ [{mode: ty::mo_alias(false), ty: inner_t}],
+ ty::mk_nil(ccx.tcx), params);
ret trans::get_extern_const(ccx.externs, ccx.llmod,
csearch::get_symbol(ccx.sess.get_cstore(),
did),
// code. Each basic block we generate is attached to a function, typically
// with many basic blocks per function. All the basic blocks attached to a
// function are organized as a directed graph.
-type block_ctxt = {
+type block_ctxt =
// The BasicBlockRef returned from a call to
// llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
// block to the function pointed to by llfn. We insert
// instructions into that block by way of this block context.
- llbb: BasicBlockRef,
// The llvm::builder object serving as an interface to LLVM's
// LLVMBuild* functions.
- build: builder,
// The block pointing to this one in the function's digraph.
- parent: block_parent,
// The 'kind' of basic block this is.
- kind: block_kind,
// A list of functions that run at the end of translating this
// block, cleaning up any variables that were introduced in the
// block and need to go out of scope at the end of it.
- mutable cleanups: [cleanup],
// The source span where this block comes from, for error
// reporting.
- sp: span,
// The function context for the function to which this block is
// attached.
- fcx: @fn_ctxt
-};
+ {llbb: BasicBlockRef,
+ build: builder,
+ parent: block_parent,
+ kind: block_kind,
+ mutable cleanups: [cleanup],
+ sp: span,
+ fcx: @fn_ctxt};
// FIXME: we should be able to use option::t<@block_parent> here but
// the infinite-tag check in rustboot gets upset.
type result_t = {bcx: @block_ctxt, val: ValueRef, ty: ty::t};
fn extend_path(cx: @local_ctxt, name: &str) -> @local_ctxt {
- ret @{path: cx.path + ~[name] with *cx};
+ ret @{path: cx.path + [name] with *cx};
}
fn rslt(bcx: @block_ctxt, val: ValueRef) -> result {
assert (n < elt_count);
let elt_tys = std::vec::init_elt(T_nil(), elt_count);
llvm::LLVMGetStructElementTypes(llstructty, std::vec::to_ptr(elt_tys));
- ret llvm::LLVMGetElementType(elt_tys.(n));
+ ret llvm::LLVMGetElementType(elt_tys[n]);
}
fn find_scope_cx(cx: &@block_ctxt) -> @block_ctxt {
fn bcx_ccx(bcx: &@block_ctxt) -> @crate_ctxt { ret bcx.fcx.lcx.ccx; }
fn bcx_lcx(bcx: &@block_ctxt) -> @local_ctxt { ret bcx.fcx.lcx; }
fn bcx_fcx(bcx: &@block_ctxt) -> @fn_ctxt { ret bcx.fcx; }
-fn fcx_ccx(fcx: &@fn_ctxt) -> @crate_ctxt { ret fcx.lcx.ccx; }
-fn fcx_tcx(fcx: &@fn_ctxt) -> ty::ctxt { ret fcx.lcx.ccx.tcx; }
+fn fcx_ccx(fcx: &@fn_ctxt) -> @crate_ctxt { ret fcx.lcx.ccx; }
+fn fcx_tcx(fcx: &@fn_ctxt) -> ty::ctxt { ret fcx.lcx.ccx.tcx; }
fn lcx_ccx(lcx: &@local_ctxt) -> @crate_ctxt { ret lcx.ccx; }
fn ccx_tcx(ccx: &@crate_ctxt) -> ty::ctxt { ret ccx.tcx; }
}
fn T_fn_pair(cx: &crate_ctxt, tfn: TypeRef) -> TypeRef {
- ret T_struct(~[T_ptr(tfn), T_opaque_closure_ptr(cx)]);
+ ret T_struct([T_ptr(tfn), T_opaque_closure_ptr(cx)]);
}
fn T_ptr(t: TypeRef) -> TypeRef { ret llvm::LLVMPointerType(t, 0u); }
False);
}
-fn T_empty_struct() -> TypeRef { ret T_struct(~[]); }
+fn T_empty_struct() -> TypeRef { ret T_struct([]); }
// NB: This will return something different every time it's called. If
// you need a generic object type that matches the type of your
fn T_rust_object() -> TypeRef {
let t = T_named_struct("rust_object");
let e = T_ptr(T_empty_struct());
- set_struct_body(t, ~[e, e]);
+ set_struct_body(t, [e, e]);
ret t;
}
fn T_task() -> TypeRef {
let t = T_named_struct("task");
- let // Refcount
- // Delegate pointer
- // Stack segment pointer
- // Runtime SP
- // Rust SP
- // GC chain
-
- // Domain pointer
- // Crate cache pointer
- elems =
- ~[T_int(), T_int(), T_int(), T_int(), T_int(), T_int(), T_int(),
- T_int()];
+ // Refcount
+ // Delegate pointer
+ // Stack segment pointer
+ // Runtime SP
+ // Rust SP
+ // GC chain
+
+
+ // Domain pointer
+ // Crate cache pointer
+
+ let elems =
+ [T_int(), T_int(), T_int(), T_int(), T_int(), T_int(), T_int(),
+ T_int()];
set_struct_body(t, elems);
ret t;
}
std::vec::init_elt::<TypeRef>(T_nil(), abi::n_tydesc_fields as uint);
llvm::LLVMGetStructElementTypes(cx.tydesc_type,
std::vec::to_ptr::<TypeRef>(tydesc_elts));
- let t = llvm::LLVMGetElementType(tydesc_elts.(field));
+ let t = llvm::LLVMGetElementType(tydesc_elts[field]);
ret t;
}
let tydescpp = T_ptr(T_ptr(tydesc));
let pvoid = T_ptr(T_i8());
let glue_fn_ty =
- T_ptr(T_fn(~[T_ptr(T_nil()), taskptr_type, T_ptr(T_nil()), tydescpp,
- pvoid], T_void()));
+ T_ptr(T_fn([T_ptr(T_nil()), taskptr_type, T_ptr(T_nil()), tydescpp,
+ pvoid], T_void()));
let cmp_glue_fn_ty =
- T_ptr(T_fn(~[T_ptr(T_i1()), taskptr_type, T_ptr(tydesc), tydescpp,
- pvoid, pvoid, T_i8()], T_void()));
+ T_ptr(T_fn([T_ptr(T_i1()), taskptr_type, T_ptr(tydesc), tydescpp,
+ pvoid, pvoid, T_i8()], T_void()));
let elems =
- ~[tydescpp, T_int(), T_int(), glue_fn_ty, glue_fn_ty, glue_fn_ty,
- glue_fn_ty, glue_fn_ty, glue_fn_ty, glue_fn_ty, cmp_glue_fn_ty,
- T_ptr(T_i8()), T_ptr(T_i8()), T_int()];
+ [tydescpp, T_int(), T_int(), glue_fn_ty, glue_fn_ty, glue_fn_ty,
+ glue_fn_ty, glue_fn_ty, glue_fn_ty, glue_fn_ty, cmp_glue_fn_ty,
+ T_ptr(T_i8()), T_ptr(T_i8()), T_int()];
set_struct_body(tydesc, elems);
ret tydesc;
}
fn T_array(t: TypeRef, n: uint) -> TypeRef { ret llvm::LLVMArrayType(t, n); }
fn T_evec(t: TypeRef) -> TypeRef {
- ret T_struct(~[T_int(), // Refcount
- T_int(), // Alloc
- T_int(), // Fill
+ ret T_struct([T_int(), // Refcount
+ T_int(), // Alloc
+ T_int(), // Fill
- T_int(), // Pad
- // Body elements
- T_array(t, 0u)]);
+ T_int(), // Pad
+ // Body elements
+ T_array(t, 0u)]);
}
fn T_opaque_vec_ptr() -> TypeRef { ret T_ptr(T_evec(T_int())); }
//
// TODO: Support user-defined vector sizes.
fn T_ivec(t: TypeRef) -> TypeRef {
- ret T_struct(~[T_int(), // Length ("fill"; if zero, heapified)
- T_int(), // Alloc
- T_array(t, abi::ivec_default_length)]); // Body elements
+ ret T_struct([T_int(), // Length ("fill"; if zero, heapified)
+ T_int(), // Alloc
+ T_array(t, abi::ivec_default_length)]); // Body elements
}
// Note that the size of this one is in bytes.
fn T_opaque_ivec() -> TypeRef {
- ret T_struct(~[T_int(), // Length ("fill"; if zero, heapified)
- T_int(), // Alloc
- T_array(T_i8(), 0u)]); // Body elements
+ ret T_struct([T_int(), // Length ("fill"; if zero, heapified)
+ T_int(), // Alloc
+ T_array(T_i8(), 0u)]); // Body elements
}
fn T_ivec_heap_part(t: TypeRef) -> TypeRef {
- ret T_struct(~[T_int(), // Real length
- T_array(t, 0u)]); // Body elements
+ ret T_struct([T_int(), // Real length
+ T_array(t, 0u)]); // Body elements
}
// Interior vector on the heap, also known as the "stub". Cast to this when
// the allocated length (second element of T_ivec above) is zero.
fn T_ivec_heap(t: TypeRef) -> TypeRef {
- ret T_struct(~[T_int(), // Length (zero)
- T_int(), // Alloc
- T_ptr(T_ivec_heap_part(t))]); // Pointer
+ ret T_struct([T_int(), // Length (zero)
+ T_int(), // Alloc
+ T_ptr(T_ivec_heap_part(t))]); // Pointer
}
fn T_opaque_ivec_heap_part() -> TypeRef {
- ret T_struct(~[T_int(), // Real length
- T_array(T_i8(), 0u)]); // Body elements
+ ret T_struct([T_int(), // Real length
+ T_array(T_i8(), 0u)]); // Body elements
}
fn T_opaque_ivec_heap() -> TypeRef {
- ret T_struct(~[T_int(), // Length (zero)
- T_int(), // Alloc
- T_ptr(T_opaque_ivec_heap_part())]); // Pointer
+ ret T_struct([T_int(), // Length (zero)
+ T_int(), // Alloc
+ T_ptr(T_opaque_ivec_heap_part())]); // Pointer
}
fn T_str() -> TypeRef { ret T_evec(T_i8()); }
-fn T_box(t: TypeRef) -> TypeRef { ret T_struct(~[T_int(), t]); }
+fn T_box(t: TypeRef) -> TypeRef { ret T_struct([T_int(), t]); }
fn T_port(_t: TypeRef) -> TypeRef {
- ret T_struct(~[T_int()]); // Refcount
+ ret T_struct([T_int()]); // Refcount
}
fn T_chan(_t: TypeRef) -> TypeRef {
- ret T_struct(~[T_int()]); // Refcount
+ ret T_struct([T_int()]); // Refcount
}
fn T_typaram_ptr(tn: &type_names) -> TypeRef { ret T_ptr(T_typaram(tn)); }
-fn T_closure_ptr(cx: &crate_ctxt, llbindings_ty: TypeRef,
- n_ty_params: uint) -> TypeRef {
+fn T_closure_ptr(cx: &crate_ctxt, llbindings_ty: TypeRef, n_ty_params: uint)
+ -> TypeRef {
// NB: keep this in sync with code in trans_bind; we're making
// an LLVM typeref structure that has the same "shape" as the ty::t
// it constructs.
- ret T_ptr(T_box(T_struct(~[T_ptr(cx.tydesc_type),
- llbindings_ty,
- T_captured_tydescs(cx, n_ty_params)])));
+ ret T_ptr(T_box(T_struct([T_ptr(cx.tydesc_type), llbindings_ty,
+ T_captured_tydescs(cx, n_ty_params)])));
}
fn T_opaque_closure_ptr(cx: &crate_ctxt) -> TypeRef {
fn T_tag(tn: &type_names, size: uint) -> TypeRef {
let s = "tag_" + uint::to_str(size, 10u);
if tn.name_has_type(s) { ret tn.get_type(s); }
- let t = T_struct(~[T_int(), T_array(T_i8(), size)]);
+ let t = T_struct([T_int(), T_array(T_i8(), size)]);
tn.associate(s, t);
ret t;
}
fn T_opaque_tag(tn: &type_names) -> TypeRef {
let s = "opaque_tag";
if tn.name_has_type(s) { ret tn.get_type(s); }
- let t = T_struct(~[T_int(), T_i8()]);
+ let t = T_struct([T_int(), T_i8()]);
tn.associate(s, t);
ret t;
}
// type. The dynamically-sized fields follow the captured tydescs.
fn T_obj(cx: &crate_ctxt, n_captured_tydescs: uint) -> TypeRef {
- ret T_struct(~[T_ptr(cx.tydesc_type),
- T_captured_tydescs(cx, n_captured_tydescs)]);
+ ret T_struct([T_ptr(cx.tydesc_type),
+ T_captured_tydescs(cx, n_captured_tydescs)]);
}
ret T_ptr(T_box(T_obj(cx, n_captured_tydescs)));
}
// A rust boxed-and-length-annotated string.
fn C_str(cx: &@crate_ctxt, s: &str) -> ValueRef {
- let len = str::byte_len(s);
- let // 'alloc'
- // 'fill'
- // 'pad'
- box =
- C_struct(~[C_int(abi::const_refcount as int), C_int(len + 1u as int),
- C_int(len + 1u as int), C_int(0),
- llvm::LLVMConstString(str::buf(s), len, False)]);
+ let len =
+ str::byte_len(s); // 'alloc'
+ // 'fill'
+ // 'pad'
+
+ let box =
+ C_struct([C_int(abi::const_refcount as int), C_int(len + 1u as int),
+ C_int(len + 1u as int), C_int(0),
+ llvm::LLVMConstString(str::buf(s), len, False)]);
let g =
llvm::LLVMAddGlobal(cx.llmod, val_ty(box),
str::buf(cx.names.next("str")));
fn C_zero_byte_arr(size: uint) -> ValueRef {
let i = 0u;
- let elts: [ValueRef] = ~[];
- while i < size { elts += ~[C_u8(0u)]; i += 1u; }
+ let elts: [ValueRef] = [];
+ while i < size { elts += [C_u8(0u)]; i += 1u; }
ret llvm::LLVMConstArray(T_i8(), std::vec::to_ptr(elts),
std::vec::len(elts));
}
}
fn C_array(ty: TypeRef, elts: &[ValueRef]) -> ValueRef {
- ret llvm::LLVMConstArray(ty, std::vec::to_ptr(elts),
- std::vec::len(elts));
+ ret llvm::LLVMConstArray(ty, std::vec::to_ptr(elts), std::vec::len(elts));
}
-fn C_bytes(bytes : &[u8]) -> ValueRef {
+fn C_bytes(bytes: &[u8]) -> ValueRef {
ret llvm::LLVMConstString(unsafe::reinterpret_cast(vec::to_ptr(bytes)),
vec::len(bytes), False);
}
-fn C_shape(ccx : &@crate_ctxt, bytes : &[u8]) -> ValueRef {
+fn C_shape(ccx: &@crate_ctxt, bytes: &[u8]) -> ValueRef {
let llshape = C_bytes(bytes);
- let llglobal = llvm::LLVMAddGlobal(ccx.llmod, val_ty(llshape),
- str::buf(ccx.names.next("shape")));
+ let llglobal =
+ llvm::LLVMAddGlobal(ccx.llmod, val_ty(llshape),
+ str::buf(ccx.names.next("shape")));
llvm::LLVMSetInitializer(llglobal, llshape);
llvm::LLVMSetGlobalConstant(llglobal, True);
llvm::LLVMSetLinkage(llglobal,
// The fields of our object will become the arguments to the function
// we're creating.
- let fn_args: [ast::arg] = ~[];
+ let fn_args: [ast::arg] = [];
for f: ast::obj_field in ob.fields {
fn_args +=
- ~[{mode: ast::alias(false), ty: f.ty, ident: f.ident, id: f.id}];
+ [{mode: ast::alias(false), ty: f.ty, ident: f.ident, id: f.id}];
}
let fcx = new_fn_ctxt(cx, sp, llctor_decl);
// abi::obj_field_vtbl and abi::obj_field_box simply specify words 0 and 1
// of 'pair'.
let pair_vtbl =
- bcx.build.GEP(pair, ~[C_int(0), C_int(abi::obj_field_vtbl)]);
- let pair_box =
- bcx.build.GEP(pair, ~[C_int(0), C_int(abi::obj_field_box)]);
+ bcx.build.GEP(pair, [C_int(0), C_int(abi::obj_field_vtbl)]);
+ let pair_box = bcx.build.GEP(pair, [C_int(0), C_int(abi::obj_field_box)]);
// Make a vtable for this object: a static array of pointers to functions.
// It will be located in the read-only memory of the executable we're
// creating and will contain ValueRefs for all of this object's methods.
// create_vtbl returns a pointer to the vtable, which we store.
- let vtbl = create_vtbl(cx, sp, self_ty, ob, ty_params, none, ~[]);
+ let vtbl = create_vtbl(cx, sp, self_ty, ob, ty_params, none, []);
vtbl = bcx.build.PointerCast(vtbl, T_ptr(T_empty_struct()));
bcx.build.Store(vtbl, pair_vtbl);
// Store null into pair, if no args or typarams.
bcx.build.Store(C_null(llbox_ty), pair_box);
} else {
- let obj_fields: [ty::t] = ~[];
- for a: ty::arg in arg_tys { obj_fields += ~[a.ty]; }
+ let obj_fields: [ty::t] = [];
+ for a: ty::arg in arg_tys { obj_fields += [a.ty]; }
- let tps: [ty::t] = ~[];
+ let tps: [ty::t] = [];
let tydesc_ty = ty::mk_type(ccx.tcx);
- for tp: ast::ty_param in ty_params { tps += ~[tydesc_ty]; }
+ for tp: ast::ty_param in ty_params { tps += [tydesc_ty]; }
// Synthesize an object body type and hand it off to
// trans_malloc_boxed, which allocates a box, including space for a
// refcount.
- let body_ty: ty::t = create_object_body_type(ccx.tcx, obj_fields, tps,
- none);
+ let body_ty: ty::t =
+ create_object_body_type(ccx.tcx, obj_fields, tps, none);
let box = trans_malloc_boxed(bcx, body_ty);
bcx = box.bcx;
let body = box.body;
// later.
let body_tydesc =
- GEP_tup_like(bcx, body_ty, body,
- ~[0, abi::obj_body_elt_tydesc]);
+ GEP_tup_like(bcx, body_ty, body, [0, abi::obj_body_elt_tydesc]);
bcx = body_tydesc.bcx;
let ti = none::<@tydesc_info>;
let body_td = get_tydesc(bcx, body_ty, true, ti).result;
// Copy typarams into captured typarams.
let body_typarams =
- GEP_tup_like(bcx, body_ty, body,
- ~[0, abi::obj_body_elt_typarams]);
+ GEP_tup_like(bcx, body_ty, body, [0, abi::obj_body_elt_typarams]);
bcx = body_typarams.bcx;
// TODO: can we just get typarams_ty out of body_ty instead?
let typarams_ty: ty::t = ty::mk_tup(ccx.tcx, tps);
let i: int = 0;
for tp: ast::ty_param in ty_params {
- let typaram = bcx.fcx.lltydescs.(i);
+ let typaram = bcx.fcx.lltydescs[i];
let capture =
- GEP_tup_like(bcx, typarams_ty, body_typarams.val, ~[0, i]);
+ GEP_tup_like(bcx, typarams_ty, body_typarams.val, [0, i]);
bcx = capture.bcx;
bcx = copy_val(bcx, INIT, capture.val, typaram, tydesc_ty).bcx;
i += 1;
// Copy args into body fields.
let body_fields =
- GEP_tup_like(bcx, body_ty, body,
- ~[0, abi::obj_body_elt_fields]);
+ GEP_tup_like(bcx, body_ty, body, [0, abi::obj_body_elt_fields]);
bcx = body_fields.bcx;
i = 0;
for f: ast::obj_field in ob.fields {
alt bcx.fcx.llargs.find(f.id) {
some(arg1) {
- let arg = load_if_immediate(bcx, arg1, arg_tys.(i).ty);
+ let arg = load_if_immediate(bcx, arg1, arg_tys[i].ty);
// TODO: can we just get fields_ty out of body_ty instead?
let fields_ty: ty::t = ty::mk_tup(ccx.tcx, obj_fields);
let field =
- GEP_tup_like(bcx, fields_ty, body_fields.val, ~[0, i]);
+ GEP_tup_like(bcx, fields_ty, body_fields.val, [0, i]);
bcx = field.bcx;
- bcx = copy_val(bcx, INIT, field.val, arg, arg_tys.(i).ty).bcx;
+ bcx = copy_val(bcx, INIT, field.val, arg, arg_tys[i].ty).bcx;
i += 1;
}
none. {
// Fields. FIXME (part of issue #538): Where do we fill in the field
// *values* from the outer object?
- let additional_fields: [ast::anon_obj_field] = ~[];
- let additional_field_vals: [result] = ~[];
- let additional_field_tys: [ty::t] = ~[];
+ let additional_fields: [ast::anon_obj_field] = [];
+ let additional_field_vals: [result] = [];
+ let additional_field_tys: [ty::t] = [];
alt anon_obj.fields {
none. { }
some(fields) {
additional_fields = fields;
for f: ast::anon_obj_field in fields {
- additional_field_tys += ~[node_id_type(ccx, f.id)];
- additional_field_vals += ~[trans_expr(bcx, f.expr)];
+ additional_field_tys += [node_id_type(ccx, f.id)];
+ additional_field_vals += [trans_expr(bcx, f.expr)];
}
}
}
let wrapper_obj: ast::_obj =
{fields:
std::vec::map(ast::obj_field_from_anon_obj_field,
- additional_fields),
+ additional_fields),
methods: anon_obj.methods};
let inner_obj_ty: ty::t;
// just pass the outer object to create_vtbl(). Our vtable won't need
// to have any forwarding slots.
vtbl =
- create_vtbl(bcx.fcx.lcx, sp, outer_obj_ty, wrapper_obj, ~[], none,
+ create_vtbl(bcx.fcx.lcx, sp, outer_obj_ty, wrapper_obj, [], none,
additional_field_tys);
}
some(e) {
// forwarding slot. And, of course, we need to create a normal vtable
// entry for every method being added.
vtbl =
- create_vtbl(bcx.fcx.lcx, sp, outer_obj_ty, wrapper_obj, ~[],
+ create_vtbl(bcx.fcx.lcx, sp, outer_obj_ty, wrapper_obj, [],
some(inner_obj_ty), additional_field_tys);
}
}
// Grab onto the first and second elements of the pair.
let pair_vtbl =
- bcx.build.GEP(pair, ~[C_int(0), C_int(abi::obj_field_vtbl)]);
- let pair_box =
- bcx.build.GEP(pair, ~[C_int(0), C_int(abi::obj_field_box)]);
+ bcx.build.GEP(pair, [C_int(0), C_int(abi::obj_field_vtbl)]);
+ let pair_box = bcx.build.GEP(pair, [C_int(0), C_int(abi::obj_field_box)]);
vtbl = bcx.build.PointerCast(vtbl, T_ptr(T_empty_struct()));
bcx.build.Store(vtbl, pair_vtbl);
// Synthesize a type for the object body and hand it off to
// trans_malloc_boxed, which allocates a box, including space for a
// refcount.
- let body_ty: ty::t = create_object_body_type(ccx.tcx,
- additional_field_tys,
- ~[], some(inner_obj_ty));
+ let body_ty: ty::t =
+ create_object_body_type(ccx.tcx, additional_field_tys, [],
+ some(inner_obj_ty));
let box = trans_malloc_boxed(bcx, body_ty);
bcx = box.bcx;
let body = box.body;
// the types of the object's fields, so that the fields can be freed
// later.
let body_tydesc =
- GEP_tup_like(bcx, body_ty, body,
- ~[0, abi::obj_body_elt_tydesc]);
+ GEP_tup_like(bcx, body_ty, body, [0, abi::obj_body_elt_tydesc]);
bcx = body_tydesc.bcx;
let ti = none::<@tydesc_info>;
let body_td = get_tydesc(bcx, body_ty, true, ti).result;
// function in its closure: the fields were passed to the object
// constructor and are now available to the object's methods.
let body_fields =
- GEP_tup_like(bcx, body_ty, body,
- ~[0, abi::obj_body_elt_fields]);
+ GEP_tup_like(bcx, body_ty, body, [0, abi::obj_body_elt_fields]);
bcx = body_fields.bcx;
let i: int = 0;
for f: ast::anon_obj_field in additional_fields {
// FIXME (part of issue #538): make this work eventually, when we
// have additional field exprs in the AST.
- load_if_immediate(bcx, additional_field_vals.(i).val,
- additional_field_tys.(i));
- let fields_ty: ty::t = ty::mk_tup(ccx.tcx,
- additional_field_tys);
- let field =
- GEP_tup_like(bcx, fields_ty, body_fields.val, ~[0, i]);
+ load_if_immediate(bcx, additional_field_vals[i].val,
+ additional_field_tys[i]);
+ let fields_ty: ty::t = ty::mk_tup(ccx.tcx, additional_field_tys);
+ let field = GEP_tup_like(bcx, fields_ty, body_fields.val, [0, i]);
bcx = field.bcx;
bcx =
- copy_val(bcx, INIT, field.val, additional_field_vals.(i).val,
- additional_field_tys.(i)).bcx;
+ copy_val(bcx, INIT, field.val, additional_field_vals[i].val,
+ additional_field_tys[i]).bcx;
i += 1;
}
let body_inner_obj =
GEP_tup_like(bcx, body_ty, body,
- ~[0, abi::obj_body_elt_inner_obj]);
+ [0, abi::obj_body_elt_inner_obj]);
bcx = body_inner_obj.bcx;
bcx =
copy_val(bcx, INIT, body_inner_obj.val, inner_obj_val.val,
// Used only inside create_vtbl and create_backwarding_vtbl to distinguish
// different kinds of slots we'll have to create.
tag vtbl_mthd {
+
// Normal methods are complete AST nodes, but for forwarding methods, the
// only information we'll have about them is their type.
normal_mthd(@ast::method);
// filtering_fn: Used by create_vtbl to filter a list of methods to remove the
// ones that we don't need forwarding slots for.
-fn filtering_fn(cx: @local_ctxt, m: &vtbl_mthd,
- addtl_meths: [@ast::method]) ->
- option::t<vtbl_mthd> {
+fn filtering_fn(cx: @local_ctxt, m: &vtbl_mthd, addtl_meths: [@ast::method])
+ -> option::t<vtbl_mthd> {
// Since m is a fwding_mthd, and we're checking to see if it's in
// addtl_meths (which only contains normal_mthds), we can't just check if
// object, and return a pointer to it.
fn create_vtbl(cx: @local_ctxt, sp: &span, outer_obj_ty: ty::t,
ob: &ast::_obj, ty_params: &[ast::ty_param],
- inner_obj_ty: option::t<ty::t>,
- additional_field_tys: &[ty::t]) -> ValueRef {
+ inner_obj_ty: option::t<ty::t>, additional_field_tys: &[ty::t])
+ -> ValueRef {
- let llmethods: [ValueRef] = ~[];
+ let llmethods: [ValueRef] = [];
alt inner_obj_ty {
none. {
// Sort and process all the methods.
let meths =
- std::sort::merge_sort::<@ast::method>
- (bind ast_mthd_lteq(_, _), ob.methods);
+ std::sort::merge_sort::<@ast::method>(bind ast_mthd_lteq(_, _),
+ ob.methods);
for m: @ast::method in meths {
- llmethods += ~[process_normal_mthd(cx, m, outer_obj_ty,
- ty_params)];
+ llmethods +=
+ [process_normal_mthd(cx, m, outer_obj_ty, ty_params)];
}
}
some(inner_obj_ty) {
// we take the set difference of { methods on the original object }
// and { methods being added, whether entirely new or overriding }.
- let meths: [vtbl_mthd] = ~[];
+ let meths: [vtbl_mthd] = [];
// Gather up methods on the inner object.
alt ty::struct(cx.ccx.tcx, inner_obj_ty) {
ty::ty_obj(inner_obj_methods) {
for m: ty::method in inner_obj_methods {
- meths += ~[fwding_mthd(@m)];
+ meths += [fwding_mthd(@m)];
}
}
_ {
// And now add the additional ones, both overriding ones and entirely
// new ones. These will just be normal methods.
- for m: @ast::method in ob.methods { meths += ~[normal_mthd(m)]; }
+ for m: @ast::method in ob.methods { meths += [normal_mthd(m)]; }
// Sort all the methods and process them.
meths =
- std::sort::merge_sort::<vtbl_mthd>
- (bind vtbl_mthd_lteq(_, _), meths);
+ std::sort::merge_sort::<vtbl_mthd>(bind vtbl_mthd_lteq(_, _),
+ meths);
// To create forwarding methods, we'll need a "backwarding" vtbl. See
// create_backwarding_vtbl and process_bkwding_method for details.
alt m {
normal_mthd(nm) {
llmethods +=
- ~[process_normal_mthd(cx, nm, outer_obj_ty, ty_params)];
+ [process_normal_mthd(cx, nm, outer_obj_ty, ty_params)];
}
fwding_mthd(fm) {
llmethods +=
- ~[process_fwding_mthd(cx, sp, fm, ty_params, inner_obj_ty,
- backwarding_vtbl,
- additional_field_tys)];
+ [process_fwding_mthd(cx, sp, fm, ty_params, inner_obj_ty,
+ backwarding_vtbl,
+ additional_field_tys)];
}
}
}
// object, and it needs to forward them to the corresponding slots on the
// outer object. All we know about either one are their types.
- let llmethods: [ValueRef] = ~[];
- let meths: [ty::method]= ~[];
+ let llmethods: [ValueRef] = [];
+ let meths: [ty::method] = [];
// Gather up methods on the inner object.
alt ty::struct(cx.ccx.tcx, inner_obj_ty) {
- ty::ty_obj(inner_obj_methods) {
- for m: ty::method in inner_obj_methods {
- meths += ~[m];
- }
- }
- _ {
- // Shouldn't happen.
- cx.ccx.sess.bug("create_backwarding_vtbl(): trying to extend a \
+ ty::ty_obj(inner_obj_methods) {
+ for m: ty::method in inner_obj_methods { meths += [m]; }
+ }
+ _ {
+ // Shouldn't happen.
+ cx.ccx.sess.bug("create_backwarding_vtbl(): trying to extend a \
non-object");
- }
+ }
}
// Methods should have already been sorted, so no need to do so again.
for m: ty::method in meths {
// We pass outer_obj_ty to process_fwding_mthd() because it's the one
// being forwarded to.
- llmethods += ~[process_bkwding_mthd(
- cx, sp, @m, ~[], outer_obj_ty, ~[])];
+ llmethods += [process_bkwding_mthd(cx, sp, @m, [], outer_obj_ty, [])];
}
-
ret finish_vtbl(cx, llmethods, "backwarding_vtbl");
}
// finish_vtbl: Given a vector of vtable entries, create the table in
// read-only memory and return a pointer to it.
-fn finish_vtbl(cx: @local_ctxt, llmethods: [ValueRef], name: str)
- -> ValueRef {
+fn finish_vtbl(cx: @local_ctxt, llmethods: [ValueRef], name: str) ->
+ ValueRef {
let vtbl = C_struct(llmethods);
- let vtbl_name = mangle_internal_name_by_path(cx.ccx, cx.path + ~[name]);
+ let vtbl_name = mangle_internal_name_by_path(cx.ccx, cx.path + [name]);
let gvar =
llvm::LLVMAddGlobal(cx.ccx.llmod, val_ty(vtbl), str::buf(vtbl_name));
llvm::LLVMSetInitializer(gvar, vtbl);
// the corresponding method on inner does, calls that method on outer, and
// returns the value returned from that call.
fn process_bkwding_mthd(cx: @local_ctxt, sp: &span, m: @ty::method,
- ty_params: &[ast::ty_param], outer_obj_ty: ty::t,
- _additional_field_tys: &[ty::t]) -> ValueRef {
+ ty_params: &[ast::ty_param], outer_obj_ty: ty::t,
+ _additional_field_tys: &[ty::t]) -> ValueRef {
// Create a local context that's aware of the name of the method we're
// creating.
- let mcx: @local_ctxt = @{path: cx.path + ~["method", m.ident] with *cx};
+ let mcx: @local_ctxt = @{path: cx.path + ["method", m.ident] with *cx};
// Make up a name for the backwarding function.
let fn_name: str = "backwarding_fn";
- let s: str = mangle_internal_name_by_path_and_seq(mcx.ccx, mcx.path,
- fn_name);
+ let s: str =
+ mangle_internal_name_by_path_and_seq(mcx.ccx, mcx.path, fn_name);
// Get the backwarding function's type and declare it.
let llbackwarding_fn_ty: TypeRef =
// self-stack to get to the one we really want.
// Cast to self-stack's type.
- let llenv = bcx.build.PointerCast(
- fcx.llenv,
- T_ptr(T_struct(~[cx.ccx.rust_object_type,
- T_ptr(cx.ccx.rust_object_type)])));
-
- let llself_obj_ptr = bcx.build.GEP(llenv,
- ~[C_int(0),
- C_int(1)]);
+ let llenv =
+ bcx.build.PointerCast(
+ fcx.llenv,
+ T_ptr(T_struct([cx.ccx.rust_object_type,
+ T_ptr(cx.ccx.rust_object_type)])));
+ let llself_obj_ptr = bcx.build.GEP(llenv, [C_int(0), C_int(1)]);
llself_obj_ptr = bcx.build.Load(llself_obj_ptr);
// Cast it back to pointer-to-object-type, so LLVM won't complain.
- llself_obj_ptr = bcx.build.PointerCast(llself_obj_ptr,
- T_ptr(cx.ccx.rust_object_type));
+ llself_obj_ptr =
+ bcx.build.PointerCast(llself_obj_ptr, T_ptr(cx.ccx.rust_object_type));
// The 'llretptr' that will arrive in the backwarding function we're
// creating also needs to be the correct type. Cast it to the method's
let vtbl_type = T_ptr(T_array(T_ptr(T_nil()), ix + 1u));
let llouter_obj_vtbl =
- bcx.build.GEP(llself_obj_ptr,
- ~[C_int(0), C_int(abi::obj_field_vtbl)]);
+ bcx.build.GEP(llself_obj_ptr, [C_int(0), C_int(abi::obj_field_vtbl)]);
llouter_obj_vtbl = bcx.build.Load(llouter_obj_vtbl);
llouter_obj_vtbl = bcx.build.PointerCast(llouter_obj_vtbl, vtbl_type);
let llouter_mthd =
- bcx.build.GEP(llouter_obj_vtbl, ~[C_int(0), C_int(ix as int)]);
+ bcx.build.GEP(llouter_obj_vtbl, [C_int(0), C_int(ix as int)]);
// Set up the outer method to be called.
let outer_mthd_ty = ty::method_ty_to_fn_ty(cx.ccx.tcx, *m);
// Set up the three implicit arguments to the outer method we'll need to
// call.
let self_arg = llself_obj_ptr;
- let llouter_mthd_args: [ValueRef] = ~[llretptr, fcx.lltaskptr, self_arg];
+ let llouter_mthd_args: [ValueRef] = [llretptr, fcx.lltaskptr, self_arg];
// Copy the explicit arguments that are being passed into the forwarding
// function (they're in fcx.llargs) to llouter_mthd_args.
if arg.mode == ty::mo_val {
passed_arg = load_if_immediate(bcx, passed_arg, arg.ty);
}
- llouter_mthd_args += ~[passed_arg];
+ llouter_mthd_args += [passed_arg];
a += 1u;
}
// Create a local context that's aware of the name of the method we're
// creating.
- let mcx: @local_ctxt = @{path: cx.path + ~["method", m.ident] with *cx};
+ let mcx: @local_ctxt = @{path: cx.path + ["method", m.ident] with *cx};
// Make up a name for the forwarding function.
let fn_name: str = "forwarding_fn";
- let s: str = mangle_internal_name_by_path_and_seq(mcx.ccx, mcx.path,
- fn_name);
+ let s: str =
+ mangle_internal_name_by_path_and_seq(mcx.ccx, mcx.path, fn_name);
// Get the forwarding function's type and declare it.
let llforwarding_fn_ty: TypeRef =
// First, grab the box out of the self_obj. It contains a refcount and a
// body.
let llself_obj_box =
- bcx.build.GEP(llself_obj_ptr, ~[C_int(0), C_int(abi::obj_field_box)]);
+ bcx.build.GEP(llself_obj_ptr, [C_int(0), C_int(abi::obj_field_box)]);
llself_obj_box = bcx.build.Load(llself_obj_box);
let ccx = bcx_ccx(bcx);
// Now, reach into the box and grab the body.
let llself_obj_body =
bcx.build.GEP(llself_obj_box,
- ~[C_int(0), C_int(abi::box_rc_field_body)]);
+ [C_int(0), C_int(abi::box_rc_field_body)]);
// Now, we need to figure out exactly what type the body is supposed to be
// cast to.
- let body_ty: ty::t = create_object_body_type(cx.ccx.tcx,
- additional_field_tys, ~[],
- some(inner_obj_ty));
+ let body_ty: ty::t =
+ create_object_body_type(cx.ccx.tcx, additional_field_tys, [],
+ some(inner_obj_ty));
// And cast to that type.
llself_obj_body =
bcx.build.PointerCast(llself_obj_body,
// Now, reach into the body and grab the inner_obj.
let llinner_obj =
GEP_tup_like(bcx, body_ty, llself_obj_body,
- ~[0, abi::obj_body_elt_inner_obj]);
+ [0, abi::obj_body_elt_inner_obj]);
bcx = llinner_obj.bcx;
// And, now, somewhere in inner_obj is a vtable with an entry for the
// call it.
let llinner_obj_vtbl =
bcx.build.GEP(llinner_obj.val,
- ~[C_int(0), C_int(abi::obj_field_vtbl)]);
+ [C_int(0), C_int(abi::obj_field_vtbl)]);
llinner_obj_vtbl = bcx.build.Load(llinner_obj_vtbl);
let llinner_obj_body =
- bcx.build.GEP(llinner_obj.val,
- ~[C_int(0), C_int(abi::obj_field_box)]);
+ bcx.build.GEP(llinner_obj.val, [C_int(0), C_int(abi::obj_field_box)]);
llinner_obj_body = bcx.build.Load(llinner_obj_body);
// Get the index of the method we want.
llinner_obj_vtbl = bcx.build.PointerCast(llinner_obj_vtbl, vtbl_type);
let llorig_mthd =
- bcx.build.GEP(llinner_obj_vtbl, ~[C_int(0), C_int(ix as int)]);
+ bcx.build.GEP(llinner_obj_vtbl, [C_int(0), C_int(ix as int)]);
// Set up the original method to be called.
let orig_mthd_ty = ty::method_ty_to_fn_ty(cx.ccx.tcx, *m);
llorig_mthd = bcx.build.Load(llorig_mthd);
// Set up the self-stack.
- let self_stack = alloca(bcx, T_struct(~[cx.ccx.rust_object_type,
- T_ptr(cx.ccx.rust_object_type)]));
- self_stack = populate_self_stack(bcx,
- self_stack,
- llself_obj_ptr,
- backwarding_vtbl,
- llinner_obj_body);
+ let self_stack =
+ alloca(bcx,
+ T_struct([cx.ccx.rust_object_type,
+ T_ptr(cx.ccx.rust_object_type)]));
+ self_stack =
+ populate_self_stack(bcx, self_stack, llself_obj_ptr, backwarding_vtbl,
+ llinner_obj_body);
// Cast self_stack back to pointer-to-object-type to make LLVM happy.
- self_stack = bcx.build.PointerCast(self_stack,
- T_ptr(cx.ccx.rust_object_type));
+ self_stack =
+ bcx.build.PointerCast(self_stack, T_ptr(cx.ccx.rust_object_type));
// Set up the three implicit arguments to the original method we'll need
// to call.
- let llorig_mthd_args: [ValueRef] = ~[llretptr, fcx.lltaskptr, self_stack];
+ let llorig_mthd_args: [ValueRef] = [llretptr, fcx.lltaskptr, self_stack];
// Copy the explicit arguments that are being passed into the forwarding
// function (they're in fcx.llargs) to llorig_mthd_args.
if arg.mode == ty::mo_val {
passed_arg = load_if_immediate(bcx, passed_arg, arg.ty);
}
- llorig_mthd_args += ~[passed_arg];
+ llorig_mthd_args += [passed_arg];
a += 1u;
}
let body_ty: ty::t;
alt maybe_inner_obj_ty {
some(inner_obj_ty) {
- body_ty = ty::mk_tup(tcx, ~[tydesc_ty, typarams_ty_tup,
- fields_ty_tup, inner_obj_ty]);
+ body_ty =
+ ty::mk_tup(tcx,
+ [tydesc_ty, typarams_ty_tup, fields_ty_tup,
+ inner_obj_ty]);
}
none {
- body_ty = ty::mk_tup(tcx, ~[tydesc_ty, typarams_ty_tup,
- fields_ty_tup]);
+ body_ty =
+ ty::mk_tup(tcx, [tydesc_ty, typarams_ty_tup, fields_ty_tup]);
}
}
}
}
let mcx: @local_ctxt =
- @{path: cx.path + ~["method", m.node.ident] with *cx};
+ @{path: cx.path + ["method", m.node.ident] with *cx};
let s: str = mangle_internal_name_by_path(mcx.ccx, mcx.path);
let llfn: ValueRef = decl_internal_fastcall_fn(cx.ccx.llmod, s, llfnty);
// via the llenv argument, and we want the forwarding function to call a
// method on a "self" that's inner-obj-shaped, but we also want to hold onto
// the outer obj for potential use later by backwarding functions.
-fn populate_self_stack(bcx: @block_ctxt,
- self_stack: ValueRef, outer_obj: ValueRef,
- backwarding_vtbl: ValueRef, inner_obj_body: ValueRef)
- -> ValueRef {
+fn populate_self_stack(bcx: @block_ctxt, self_stack: ValueRef,
+ outer_obj: ValueRef, backwarding_vtbl: ValueRef,
+ inner_obj_body: ValueRef) -> ValueRef {
// Drop the outer obj into the second slot.
- let self_pair_ptr = bcx.build.GEP(self_stack,
- ~[C_int(0),
- C_int(1)]);
+ let self_pair_ptr = bcx.build.GEP(self_stack, [C_int(0), C_int(1)]);
bcx.build.Store(outer_obj, self_pair_ptr);
// Drop in the backwarding vtbl.
- let wrapper_pair = bcx.build.GEP(self_stack,
- ~[C_int(0),
- C_int(0)]);
- let wrapper_vtbl_ptr = bcx.build.GEP(wrapper_pair,
- ~[C_int(0),
- C_int(0)]);
+ let wrapper_pair = bcx.build.GEP(self_stack, [C_int(0), C_int(0)]);
+ let wrapper_vtbl_ptr = bcx.build.GEP(wrapper_pair, [C_int(0), C_int(0)]);
let backwarding_vtbl_cast =
bcx.build.PointerCast(backwarding_vtbl, T_ptr(T_empty_struct()));
bcx.build.Store(backwarding_vtbl_cast, wrapper_vtbl_ptr);
// Drop in the inner obj body.
- let wrapper_body_ptr = bcx.build.GEP(wrapper_pair,
- ~[C_int(0),
- C_int(1)]);
+ let wrapper_body_ptr = bcx.build.GEP(wrapper_pair, [C_int(0), C_int(1)]);
bcx.build.Store(inner_obj_body, wrapper_body_ptr);
ret self_stack;
import aux::add_node;
import middle::tstate::ann::empty_ann;
-fn collect_ids_expr(e: &@expr, rs: @mutable [node_id]) { *rs += ~[e.id]; }
+fn collect_ids_expr(e: &@expr, rs: @mutable [node_id]) { *rs += [e.id]; }
-fn collect_ids_block(b: &blk, rs: @mutable [node_id]) { *rs += ~[b.node.id]; }
+fn collect_ids_block(b: &blk, rs: @mutable [node_id]) { *rs += [b.node.id]; }
fn collect_ids_stmt(s: &@stmt, rs: @mutable [node_id]) {
alt s.node {
stmt_decl(_, id) {
log "node_id " + int::str(id);
- log_stmt(*s);
- *rs += ~[id];
+ log_stmt(*s);;
+ *rs += [id];
}
stmt_expr(_, id) {
log "node_id " + int::str(id);
- log_stmt(*s);
- *rs += ~[id];
+ log_stmt(*s);;
+ *rs += [id];
}
_ { }
}
fn visit_fn(ccx: &crate_ctxt, num_constraints: uint, f: &_fn,
tps: &[ty_param], sp: &span, i: &fn_ident, id: node_id) {
- let node_ids: @mutable [node_id] = @mutable ~[];
+ let node_ids: @mutable [node_id] = @mutable [];
node_ids_in_fn(f, tps, sp, i, id, node_ids);
let node_id_vec = *node_ids;
init_vecs(ccx, node_id_vec, num_constraints);
for i: uint in v {
if i == 0u {
rslt += "0";
- } else if (i == 1u) { rslt += "1"; } else { rslt += "?"; }
+ } else if i == 1u { rslt += "1"; } else { rslt += "?"; }
}
ret rslt;
}
type constr_map = @std::map::hashmap<def_id, constraint>;
/* Contains stuff that has to be computed up front */
+/* For easy access, the fn_info stores two special constraints for each
+function. i_return holds if all control paths in this function terminate
+in either a return expression, or an appropriate tail expression.
+i_diverge holds if all control paths in this function terminate in a fail
+or diverging call.
+
+It might be tempting to use a single constraint C for both properties,
+where C represents i_return and !C represents i_diverge. This is
+inadvisable, because then the sense of the bit depends on context. If we're
+inside a ! function, that reverses the sense of the bit: C would be
+i_diverge and !C would be i_return. That's awkward, because we have to
+pass extra context around to functions that shouldn't care.
+
+Okay, suppose C represents i_return and !C represents i_diverge, regardless
+of context. Consider this code:
+
+if (foo) { ret; } else { fail; }
+
+C is true in the consequent and false in the alternative. What's T `join`
+F, then? ? doesn't work, because this code should definitely-return if the
+context is a returning function (and be definitely-rejected if the context
+is a ! function). F doesn't work, because then the code gets incorrectly
+rejected if the context is a returning function. T would work, but it
+doesn't make sense for T `join` F to be T (consider init constraints, for
+example).;
+
+So we need context. And so it seems clearer to just have separate
+constraints.
+*/
type fn_info =
{constrs: constr_map,
num_constraints: uint,
cf: controlflow,
-/* For easy access, the fn_info stores two special constraints for each
- function. i_return holds if all control paths in this function terminate
- in either a return expression, or an appropriate tail expression.
- i_diverge holds if all control paths in this function terminate in a fail
- or diverging call.
-
- It might be tempting to use a single constraint C for both properties,
- where C represents i_return and !C represents i_diverge. This is
- inadvisable, because then the sense of the bit depends on context. If we're
- inside a ! function, that reverses the sense of the bit: C would be
- i_diverge and !C would be i_return. That's awkward, because we have to
- pass extra context around to functions that shouldn't care.
-
- Okay, suppose C represents i_return and !C represents i_diverge, regardless
- of context. Consider this code:
-
- if (foo) { ret; } else { fail; }
-
- C is true in the consequent and false in the alternative. What's T `join`
- F, then? ? doesn't work, because this code should definitely-return if the
- context is a returning function (and be definitely-rejected if the context
- is a ! function). F doesn't work, because then the code gets incorrectly
- rejected if the context is a returning function. T would work, but it
- doesn't make sense for T `join` F to be T (consider init constraints, for
- example).;
-
- So we need context. And so it seems clearer to just have separate
- constraints.
-*/
i_return: tsconstr,
i_diverge: tsconstr,
- /* list, accumulated during pre/postcondition
+ /* list, accumulated during pre/postcondition
computation, of all local variables that may be
used */
-// Doesn't seem to work without the @ -- bug
+ // Doesn't seem to work without the @ -- bug
used_vars: @mutable [node_id]};
fn tsconstr_to_def_id(t: &tsconstr) -> def_id {
}
fn tsconstr_to_node_id(t: &tsconstr) -> node_id {
- alt t { ninit(id, _) { id }
- npred(_, id, _) {
- fail "tsconstr_to_node_id called on pred constraint" } }
+ alt t {
+ ninit(id, _) { id }
+ npred(_, id, _) { fail "tsconstr_to_node_id called on pred constraint" }
+ }
}
/* mapping from node ID to typestate annotation */
type fn_info_map = @std::map::hashmap<node_id, fn_info>;
type fn_ctxt =
- {enclosing: fn_info,
- id: node_id,
- name: ident,
- ccx: crate_ctxt};
+ {enclosing: fn_info, id: node_id, name: ident, ccx: crate_ctxt};
type crate_ctxt = {tcx: ty::ctxt, node_anns: node_ann_table, fm: fn_info_map};
if sz <= i as uint {
vec::grow_mut(*ccx.node_anns, (i as uint) - sz + 1u, empty_ann(0u));
}
- ccx.node_anns.(i) = a;
+ ccx.node_anns[i] = a;
}
fn get_ts_ann(ccx: &crate_ctxt, i: node_id) -> option::t<ts_ann> {
if i as uint < vec::len(*ccx.node_anns) {
- ret some::<ts_ann>(ccx.node_anns.(i));
+ ret some::<ts_ann>(ccx.node_anns[i]);
} else { ret none::<ts_ann>; }
}
fn num_constraints(m: fn_info) -> uint { ret m.num_constraints; }
fn new_crate_ctxt(cx: ty::ctxt) -> crate_ctxt {
- let na: [mutable ts_ann] = ~[mutable];
+ let na: [mutable ts_ann] = [mutable];
ret {tcx: cx, node_anns: @mutable na, fm: @new_int_hash::<fn_info>()};
}
fn constraints_expr(cx: &ty::ctxt, e: @expr) -> [@ty::constr] {
alt ty::struct(cx, ty::node_id_to_type(cx, e.id)) {
ty::ty_fn(_, _, _, _, cs) { ret cs; }
- _ { ret ~[]; }
+ _ { ret []; }
}
}
fn norm_a_constraint(id: def_id, c: &constraint) -> [norm_constraint] {
alt c {
cinit(n, sp, i) {
- ret ~[{bit_num: n, c: respan(sp, ninit(id.node, i))}];
+ ret [{bit_num: n, c: respan(sp, ninit(id.node, i))}];
}
cpred(p, descs) {
- let rslt: [norm_constraint] = ~[];
+ let rslt: [norm_constraint] = [];
for pd: pred_args in *descs {
rslt +=
- ~[{bit_num: pd.node.bit_num,
- c: respan(pd.span, npred(p, id, pd.node.args))}];
+ [{bit_num: pd.node.bit_num,
+ c: respan(pd.span, npred(p, id, pd.node.args))}];
}
ret rslt;
}
// Tried to write this as an iterator, but I got a
// non-exhaustive match in trans.
fn constraints(fcx: &fn_ctxt) -> [norm_constraint] {
- let rslt: [norm_constraint] = ~[];
- for each p: @{key: def_id, val: constraint} in
+ let rslt: [norm_constraint] = [];
+ for each p: @{key: def_id, val: constraint} in
fcx.enclosing.constrs.items() {
rslt += norm_a_constraint(p.key, p.val);
}
alt tcx.def_map.find(e.id) {
some(def_local(l_id)) {
ret @respan(p.span,
- carg_ident({ident: p.node.idents.(0),
+ carg_ident({ident: p.node.idents[0],
node: l_id.node}));
}
some(def_arg(a_id)) {
ret @respan(p.span,
- carg_ident({ident: p.node.idents.(0),
+ carg_ident({ident: p.node.idents[0],
node: a_id.node}));
}
_ {
}
}
-fn exprs_to_constr_args(tcx: ty::ctxt, args: &[@expr]) ->
- [@constr_arg_use] {
+fn exprs_to_constr_args(tcx: ty::ctxt, args: &[@expr]) -> [@constr_arg_use] {
let f = bind expr_to_constr_arg(tcx, _);
- let rslt: [@constr_arg_use] = ~[];
- for e: @expr in args { rslt += ~[f(e)]; }
+ let rslt: [@constr_arg_use] = [];
+ for e: @expr in args { rslt += [f(e)]; }
rslt
}
fn expr_to_constr(tcx: ty::ctxt, e: &@expr) -> sp_constr {
alt e.node {
+
// FIXME change the first pattern to expr_path to test a
// typechecker bug
expr_call(operator, args) {
fn substitute_constr_args(cx: &ty::ctxt, actuals: &[@expr], c: &@ty::constr)
-> tsconstr {
- let rslt: [@constr_arg_use] = ~[];
+ let rslt: [@constr_arg_use] = [];
for a: @constr_arg in c.node.args {
- rslt += ~[substitute_arg(cx, actuals, a)];
+ rslt += [substitute_arg(cx, actuals, a)];
}
ret npred(c.node.path, c.node.id, rslt);
}
alt a.node {
carg_ident(i) {
if i < num_actuals {
- ret expr_to_constr_arg(cx, actuals.(i));
+ ret expr_to_constr_arg(cx, actuals[i]);
} else {
cx.sess.span_fatal(a.span, "Constraint argument out of bounds");
}
}
}
-fn pred_args_matches(pattern: &[constr_arg_general_<inst>],
- desc: &pred_args) -> bool {
+fn pred_args_matches(pattern: &[constr_arg_general_<inst>], desc: &pred_args)
+ -> bool {
let i = 0u;
for c: @constr_arg_use in desc.node.args {
- let n = pattern.(i);
+ let n = pattern[i];
alt c.node {
carg_ident(p) {
alt n {
ret true;
}
-fn find_instance_(pattern: &[constr_arg_general_<inst>],
- descs: &[pred_args]) -> option::t<uint> {
+fn find_instance_(pattern: &[constr_arg_general_<inst>], descs: &[pred_args])
+ -> option::t<uint> {
for d: pred_args in descs {
if pred_args_matches(pattern, d) { ret some(d.node.bit_num); }
}
fn find_instances(_fcx: &fn_ctxt, subst: &subst, c: &constraint) ->
[{from: uint, to: uint}] {
- let rslt = ~[];
+ let rslt = [];
if vec::len(subst) == 0u { ret rslt; }
alt c {
let old_bit_num = d.node.bit_num;
let new = replace(subst, d);
alt find_instance_(new, *descs) {
- some(d1) { rslt += ~[{from: old_bit_num, to: d1}]; }
+ some(d1) { rslt += [{from: old_bit_num, to: d1}]; }
_ { }
}
}
}
fn replace(subst: subst, d: pred_args) -> [constr_arg_general_<inst>] {
- let rslt: [constr_arg_general_<inst>] = ~[];
+ let rslt: [constr_arg_general_<inst>] = [];
for c: @constr_arg_use in d.node.args {
alt c.node {
carg_ident(p) {
alt find_in_subst(p.node, subst) {
- some(new) { rslt += ~[carg_ident(new)]; }
- _ { rslt += ~[c.node]; }
+ some(new) { rslt += [carg_ident(new)]; }
+ _ { rslt += [c.node]; }
}
}
_ {
// log_err "##";
- rslt += ~[c.node];
+ rslt += [c.node];
}
}
}
ty: oper_type) {
let subst;
alt ty {
- oper_swap. { subst = ~[{from: dest, to: src}, {from: src, to: dest}]; }
+ oper_swap. { subst = [{from: dest, to: src}, {from: src, to: dest}]; }
oper_assign_op. {
ret; // Don't do any propagation
}
- _ { subst = ~[{from: src, to: dest}]; }
+ _ { subst = [{from: src, to: dest}]; }
}
- for each p: @{key: def_id, val: constraint} in
+ for each p: @{key: def_id, val: constraint} in
fcx.enclosing.constrs.items() {
// replace any occurrences of the src def_id with the
// dest def_id
bool {
ret alt c.c.node {
ninit(id, _) { v == id }
- npred(_, _, args) { args_mention(args, any_eq, ~[v]) }
+ npred(_, _, args) { args_mention(args, any_eq, [v]) }
};
}
v: &node_id) -> bool {
ret alt c.c.node {
ninit(_, _) { false }
- npred(_, _, args) { args_mention(args, any_eq, ~[v]) }
+ npred(_, _, args) { args_mention(args, any_eq, [v]) }
};
}
-fn args_mention<T>(args: &[@constr_arg_use], q: fn(&[T], node_id) -> bool ,
+fn args_mention<T>(args: &[@constr_arg_use], q: fn(&[T], node_id) -> bool,
s: &[T]) -> bool {
/*
FIXME
ret false;
}
-fn use_var(fcx: &fn_ctxt, v: &node_id) { *fcx.enclosing.used_vars += ~[v]; }
+fn use_var(fcx: &fn_ctxt, v: &node_id) { *fcx.enclosing.used_vars += [v]; }
// FIXME: This should be a function in std::vec::.
fn vec_contains(v: &@mutable [node_id], i: &node_id) -> bool {
fn args_to_constr_args(sp: &span, args: &[arg]) -> [@constr_arg_use] {
- let actuals: [@constr_arg_use] = ~[];
+ let actuals: [@constr_arg_use] = [];
for a: arg in args {
- actuals += ~[@respan(sp, carg_ident({ident: a.ident, node: a.id}))];
+ actuals += [@respan(sp, carg_ident({ident: a.ident, node: a.id}))];
}
ret actuals;
}
type binding = {lhs: [inst], rhs: option::t<initializer>};
-fn local_to_bindings(loc : &@local) -> binding {
- let lhs = ~[];
+fn local_to_bindings(loc: &@local) -> binding {
+ let lhs = [];
for each p: @pat in pat_bindings(loc.node.pat) {
let ident = alt p.node { pat_bind(name) { name } };
- lhs += ~[{ident: ident, node: p.id}];
+ lhs += [{ident: ident, node: p.id}];
}
- {lhs: lhs,
- rhs: loc.node.init}
+ {lhs: lhs, rhs: loc.node.init}
}
-fn locals_to_bindings(locals : &[@local]) -> [binding] {
+fn locals_to_bindings(locals: &[@local]) -> [binding] {
vec::map(local_to_bindings, locals)
}
fn callee_modes(fcx: &fn_ctxt, callee: node_id) -> [ty::mode] {
- let ty = ty::type_autoderef(fcx.ccx.tcx,
- ty::node_id_to_type(fcx.ccx.tcx, callee));
+ let ty =
+ ty::type_autoderef(fcx.ccx.tcx,
+ ty::node_id_to_type(fcx.ccx.tcx, callee));
alt ty::struct(fcx.ccx.tcx, ty) {
- ty::ty_fn(_, args, _, _, _)
- | ty::ty_native_fn(_, args, _) {
- let modes = ~[];
- for arg: ty::arg in args {
- modes += ~[arg.mode];
- }
+ ty::ty_fn(_, args, _, _, _) | ty::ty_native_fn(_, args, _) {
+ let modes = [];
+ for arg: ty::arg in args { modes += [arg.mode]; }
ret modes;
}
_ {
// Shouldn't happen; callee should be ty_fn.
- fcx.ccx.tcx.sess.bug("non-fn callee type in callee_modes: "
- + util::ppaux::ty_to_str(fcx.ccx.tcx, ty));
+ fcx.ccx.tcx.sess.bug("non-fn callee type in callee_modes: " +
+ util::ppaux::ty_to_str(fcx.ccx.tcx, ty));
}
- }
+ }
}
fn callee_arg_init_ops(fcx: &fn_ctxt, callee: node_id) -> [init_op] {
fn mode_to_op(m: &ty::mode) -> init_op {
- alt m {
- ty::mo_move. { init_move }
- _ { init_assign }
- }
+ alt m { ty::mo_move. { init_move } _ { init_assign } }
}
vec::map(mode_to_op, callee_modes(fcx, callee))
}
-fn anon_bindings(ops: &[init_op], es : &[@expr]) -> [binding] {
- let bindings: [binding] = ~[];
+fn anon_bindings(ops: &[init_op], es: &[@expr]) -> [binding] {
+ let bindings: [binding] = [];
let i = 0;
for op: init_op in ops {
- bindings += ~[{lhs: ~[],
- rhs: some({op:op, expr: es.(i)})}];
+ bindings += [{lhs: [], rhs: some({op: op, expr: es[i]})}];
i += 1;
}
ret bindings;
fn seq_postconds(fcx: &fn_ctxt, ps: &[postcond]) -> postcond {
let sz = vec::len(ps);
if sz >= 1u {
- let prev = tritv_clone(ps.(0));
+ let prev = tritv_clone(ps[0]);
for p: postcond in vec::slice(ps, 1u, sz) { seq_tritv(prev, p); }
ret prev;
} else { ret ann::empty_poststate(num_constraints(fcx.enclosing)); }
first: &pre_and_post) -> precond {
let sz: uint = vec::len(pps);
if sz >= 1u {
- let second = pps.(0);
+ let second = pps[0];
assert (pps_len(second) == num_constraints(fcx.enclosing));
let second_pre = clone(second.precondition);
difference(second_pre, first.postcondition);
if sz >= 1u {
- let first = pps.(0);
+ let first = pps[0];
assert (pps_len(first) == num_vars);
ret seq_preconds_go(fcx, vec::slice(pps, 1u, sz), first);
} else { ret true_precond(num_vars); }
visit::visit_stmt(s, cx, vt);
}
-type relax_ctxt = {fcx:fn_ctxt, i:node_id};
+type relax_ctxt = {fcx: fn_ctxt, i: node_id};
fn relax_precond_block_inner(b: &blk, cx: &relax_ctxt,
vt: &visit::vt<relax_ctxt>) {
visit::visit_block(b, cx, vt);
}
-fn relax_precond_block(fcx: &fn_ctxt, i: node_id, b:&blk) {
+fn relax_precond_block(fcx: &fn_ctxt, i: node_id, b: &blk) {
let cx = {fcx: fcx, i: i};
let visitor = visit::default_visitor::<relax_ctxt>();
visitor =
@{visit_block: relax_precond_block_inner,
visit_expr: relax_precond_expr,
visit_stmt: relax_precond_stmt,
- visit_item: (fn (_i: &@item, _cx: &relax_ctxt,
- _vt: &visit::vt<relax_ctxt>) {})
- with *visitor};
+ visit_item:
+ fn (_i: &@item, _cx: &relax_ctxt, _vt: &visit::vt<relax_ctxt>) {
+ } with *visitor};
let v1 = visit::mk_vt(visitor);
v1.visit_block(b, cx, v1);
}
}
}
-fn kill_poststate_(fcx : &fn_ctxt, c : &tsconstr, post : &poststate) -> bool {
+fn kill_poststate_(fcx: &fn_ctxt, c: &tsconstr, post: &poststate) -> bool {
log "kill_poststate_";
ret clear_in_poststate_(bit_num(fcx, c), post);
}
ret kill_prestate(fcx, parent, ninit(id, ident));
}
-fn clear_in_poststate_ident_(fcx : &fn_ctxt, id : &node_id, ident : &ident,
- post : &poststate) -> bool {
+fn clear_in_poststate_ident_(fcx: &fn_ctxt, id: &node_id, ident: &ident,
+ post: &poststate) -> bool {
ret kill_poststate_(fcx, ninit(id, ident), post);
}
for c: norm_constraint in constraints(fcx) {
alt c.c.node {
ninit(id, v) {
- if !vec_contains(fcx.enclosing.used_vars, id) &&
- v.(0) != ('_' as u8) {
+ if !vec_contains(fcx.enclosing.used_vars, id) && v[0] != '_' as u8
+ {
fcx.ccx.tcx.sess.span_warn(c.c.span, "unused variable " + v);
}
}
/* Check that the return value is initialized */
let post = aux::block_poststate(fcx.ccx, f.body);
if f.proto == ast::proto_fn &&
- !promises(fcx, post, fcx.enclosing.i_return) &&
- !type_is_nil(fcx.ccx.tcx, ret_ty_of_fn(fcx.ccx.tcx, id)) &&
- f.decl.cf == return {
+ !promises(fcx, post, fcx.enclosing.i_return) &&
+ !type_is_nil(fcx.ccx.tcx, ret_ty_of_fn(fcx.ccx.tcx, id)) &&
+ f.decl.cf == return {
fcx.ccx.tcx.sess.span_err(f.body.span,
- "In function " + fcx.name +
- ", not all control paths \
+ "In function " + fcx.name +
+ ", not all control paths \
return a value");
fcx.ccx.tcx.sess.span_fatal(f.decl.output.span,
"see declared return type of '" +
ty_to_str(f.decl.output) + "'");
- } else if (f.decl.cf == noreturn) {
+ } else if f.decl.cf == noreturn {
+
// check that this really always fails
// Note that it's ok for i_diverge and i_return to both be true.
// In fact, i_diverge implies i_return. (But not vice versa!)
fn collect_local(loc: &@local, cx: &ctxt, v: &visit::vt<ctxt>) {
for each p: @pat in pat_bindings(loc.node.pat) {
let ident = alt p.node { pat_bind(id) { id } };
- log "collect_local: pushing " + ident;
- *cx.cs += ~[respan(loc.span, ninit(p.id, ident))];
+ log "collect_local: pushing " + ident;;
+ *cx.cs += [respan(loc.span, ninit(p.id, ident))];
}
visit::visit_local(loc, cx, v);
}
fn collect_pred(e: &@expr, cx: &ctxt, v: &visit::vt<ctxt>) {
alt e.node {
- expr_check(_, ch) { *cx.cs += ~[expr_to_constr(cx.tcx, ch)]; }
- expr_if_check(ex, _, _) { *cx.cs += ~[expr_to_constr(cx.tcx, ex)]; }
+ expr_check(_, ch) { *cx.cs += [expr_to_constr(cx.tcx, ch)]; }
+ expr_if_check(ex, _, _) { *cx.cs += [expr_to_constr(cx.tcx, ex)]; }
+
// If it's a call, generate appropriate instances of the
// call's constraints.
let ct: sp_constr =
respan(c.span,
aux::substitute_constr_args(cx.tcx, operands, c));
- *cx.cs += ~[ct];
+ *cx.cs += [ct];
}
}
_ { }
fn find_locals(tcx: &ty::ctxt, f: &_fn, tps: &[ty_param], sp: &span,
i: &fn_ident, id: node_id) -> ctxt {
- let cx: ctxt = {cs: @mutable ~[], tcx: tcx};
+ let cx: ctxt = {cs: @mutable [], tcx: tcx};
let visitor = visit::default_visitor::<ctxt>();
visitor =
" as a variable and a pred");
}
cpred(_, pds) {
- *pds += ~[respan(c.span, {args: args, bit_num: next})];
+ *pds += [respan(c.span, {args: args, bit_num: next})];
}
}
}
none. {
let rslt: @mutable [pred_args] =
- @mutable ~[respan(c.span, {args: args, bit_num: next})];
+ @mutable [respan(c.span, {args: args, bit_num: next})];
tbl.insert(d_id, cpred(p, rslt));
}
}
/* Need to add constraints for args too, b/c they
can be deinitialized */
- for a:arg in f.decl.inputs {
- next = add_constraint(cx.tcx, respan(f_sp,
- ninit(a.id, a.ident)),
- next, res_map);
+ for a: arg in f.decl.inputs {
+ next =
+ add_constraint(cx.tcx, respan(f_sp, ninit(a.id, a.ident)), next,
+ res_map);
}
/* add the special i_diverge and i_return constraints
(see the type definition for auxiliary::fn_info for an explanation) */
// use the name of the function for the "return" constraint
- next = add_constraint(cx.tcx, respan(f_sp, ninit(id, name)), next,
- res_map);
+ next =
+ add_constraint(cx.tcx, respan(f_sp, ninit(id, name)), next, res_map);
// and the name of the function, with a '!' appended to it, for the
// "diverges" constraint
let diverges_id = ccx.tcx.sess.next_node_id();
add_constraint(cx.tcx, respan(f_sp, ninit(diverges_id, diverges_name)),
next, res_map);
- let v: @mutable [node_id] = @mutable ~[];
+ let v: @mutable [node_id] = @mutable [];
let rslt =
{constrs: res_map,
- num_constraints:
+
// add 2 to account for the i_return and i_diverge constraints
- vec::len(*cx.cs) + vec::len(f.decl.constraints)
- + vec::len(f.decl.inputs) + 2u,
+ num_constraints:
+ vec::len(*cx.cs) + vec::len(f.decl.constraints) +
+ vec::len(f.decl.inputs) + 2u,
cf: f.decl.cf,
i_return: ninit(id, name),
i_diverge: ninit(diverges_id, diverges_name),
alt i.node {
item_const(_, e) {
// make a fake fcx
- let v: @mutable [node_id] = @mutable ~[];
+ let v: @mutable [node_id] = @mutable [];
let fake_fcx =
- {enclosing:
+ {
+ // just bogus
+ enclosing:
{constrs: @new_def_hash::<constraint>(),
num_constraints: 0u,
cf: return,
- // just bogus
i_return: ninit(0, ""),
i_diverge: ninit(0, ""),
used_vars: v},
fn find_pre_post_exprs(fcx: &fn_ctxt, args: &[@expr], id: node_id) {
if vec::len::<@expr>(args) > 0u {
log "find_pre_post_exprs: oper =";
- log_expr(*args.(0));
+ log_expr(*args[0]);
}
fn do_one(fcx: fn_ctxt, e: &@expr) { find_pre_post_expr(fcx, e); }
for e: @expr in args { do_one(fcx, e); }
}
let loop_precond =
- seq_preconds(fcx,
- ~[expr_pp(fcx.ccx, index), block_pp(fcx.ccx, body)]);
+ seq_preconds(fcx, [expr_pp(fcx.ccx, index), block_pp(fcx.ccx, body)]);
let loop_postcond =
intersect_states(expr_postcond(fcx.ccx, index),
block_postcond(fcx.ccx, body));
let precond_res =
seq_preconds(fcx,
- ~[expr_pp(fcx.ccx, antec),
- block_pp(fcx.ccx, conseq)]);
+ [expr_pp(fcx.ccx, antec),
+ block_pp(fcx.ccx, conseq)]);
set_pre_and_post(fcx.ccx, id, precond_res,
expr_poststate(fcx.ccx, antec));
}
find_pre_post_expr(fcx, altern);
let precond_false_case =
seq_preconds(fcx,
- ~[expr_pp(fcx.ccx, antec),
- expr_pp(fcx.ccx, altern)]);
+ [expr_pp(fcx.ccx, antec), expr_pp(fcx.ccx, altern)]);
let postcond_false_case =
seq_postconds(fcx,
- ~[expr_postcond(fcx.ccx, antec),
- expr_postcond(fcx.ccx, altern)]);
+ [expr_postcond(fcx.ccx, antec),
+ expr_postcond(fcx.ccx, altern)]);
/* Be sure to set the bit for the check condition here,
so that it's *not* set in the alternative. */
}
let precond_true_case =
seq_preconds(fcx,
- ~[expr_pp(fcx.ccx, antec),
- block_pp(fcx.ccx, conseq)]);
+ [expr_pp(fcx.ccx, antec),
+ block_pp(fcx.ccx, conseq)]);
let postcond_true_case =
seq_postconds(fcx,
- ~[expr_postcond(fcx.ccx, antec),
- block_postcond(fcx.ccx, conseq)]);
+ [expr_postcond(fcx.ccx, antec),
+ block_postcond(fcx.ccx, conseq)]);
let precond_res =
- seq_postconds(fcx, ~[precond_true_case, precond_false_case]);
+ seq_postconds(fcx, [precond_true_case, precond_false_case]);
let postcond_res =
intersect_states(postcond_true_case, postcond_false_case);
set_pre_and_post(fcx.ccx, id, precond_res, postcond_res);
gen(fcx, larger_id,
ninit(d_id.node, path_to_ident(fcx.ccx.tcx, pth)));
}
- _ { find_pre_post_exprs(fcx, ~[lhs, rhs], larger_id); }
+ _ { find_pre_post_exprs(fcx, [lhs, rhs], larger_id); }
}
}
- _ { find_pre_post_exprs(fcx, ~[lhs, rhs], larger_id); }
+ _ { find_pre_post_exprs(fcx, [lhs, rhs], larger_id); }
}
}
}
}
-fn forget_args_moved_in(fcx: &fn_ctxt, parent: &@expr,
- modes: &[ty::mode],
+fn forget_args_moved_in(fcx: &fn_ctxt, parent: &@expr, modes: &[ty::mode],
operands: &[@expr]) {
let i = 0u;
for mode: ty::mode in modes {
if mode == ty::mo_move {
- forget_in_postcond(fcx, parent.id, operands.(i).id);
+ forget_in_postcond(fcx, parent.id, operands[i].id);
}
i += 1u;
}
alt e.node {
expr_call(operator, operands) {
- let /* copy */args = operands;
- args += ~[operator];
+ /* copy */
+
+ let args = operands;
+ args += [operator];
find_pre_post_exprs(fcx, args, e.id);
/* see if the call has any constraints on its type */
}
expr_rec(fields, maybe_base) {
let es = field_exprs(fields);
- alt maybe_base { none. {/* no-op */ } some(b) { es += ~[b]; } }
+ alt maybe_base { none. {/* no-op */ } some(b) { es += [b]; } }
find_pre_post_exprs(fcx, es, e.id);
}
- expr_tup(elts) {
- find_pre_post_exprs(fcx, elts, e.id);
- }
+ expr_tup(elts) { find_pre_post_exprs(fcx, elts, e.id); }
expr_copy(a) {
find_pre_post_expr(fcx, a);
copy_pre_post(fcx.ccx, e.id, a);
/* Different from expr_assign in that the lhs *must*
already be initialized */
- find_pre_post_exprs(fcx, ~[lhs, rhs], e.id);
+ find_pre_post_exprs(fcx, [lhs, rhs], e.id);
forget_in_postcond_still_init(fcx, e.id, lhs.id);
}
expr_lit(_) { clear_pp(expr_pp(fcx.ccx, e)); }
find_pre_post_expr(fcx, l);
find_pre_post_expr(fcx, r);
let overall_pre =
- seq_preconds(fcx,
- ~[expr_pp(fcx.ccx, l), expr_pp(fcx.ccx, r)]);
+ seq_preconds(fcx, [expr_pp(fcx.ccx, l), expr_pp(fcx.ccx, r)]);
set_precondition(node_id_to_ts_ann(fcx.ccx, e.id), overall_pre);
set_postcondition(node_id_to_ts_ann(fcx.ccx, e.id),
expr_postcond(fcx.ccx, l));
- } else { find_pre_post_exprs(fcx, ~[l, r], e.id); }
+ } else { find_pre_post_exprs(fcx, [l, r], e.id); }
}
expr_unary(_, operand) {
find_pre_post_expr(fcx, operand);
find_pre_post_block(fcx, body);
set_pre_and_post(fcx.ccx, e.id,
seq_preconds(fcx,
- ~[expr_pp(fcx.ccx, test),
- block_pp(fcx.ccx, body)]),
+ [expr_pp(fcx.ccx, test),
+ block_pp(fcx.ccx, body)]),
intersect_states(expr_postcond(fcx.ccx, test),
block_postcond(fcx.ccx, body)));
}
find_pre_post_expr(fcx, test);
let loop_postcond =
seq_postconds(fcx,
- ~[block_postcond(fcx.ccx, body),
- expr_postcond(fcx.ccx, test)]);
+ [block_postcond(fcx.ccx, body),
+ expr_postcond(fcx.ccx, test)]);
/* conservative approximation: if the body
could break or cont, the test may never be executed */
}
set_pre_and_post(fcx.ccx, e.id,
seq_preconds(fcx,
- ~[block_pp(fcx.ccx, body),
- expr_pp(fcx.ccx, test)]),
+ [block_pp(fcx.ccx, body),
+ expr_pp(fcx.ccx, test)]),
loop_postcond);
}
expr_for(d, index, body) {
expr_for_each(d, index, body) {
find_pre_post_loop(fcx, d, index, body, e.id);
}
- expr_index(val, sub) { find_pre_post_exprs(fcx, ~[val, sub], e.id); }
+ expr_index(val, sub) { find_pre_post_exprs(fcx, [val, sub], e.id); }
expr_alt(ex, alts) {
find_pre_post_expr(fcx, ex);
fn do_an_alt(fcx: &fn_ctxt, an_alt: &arm) -> pre_and_post {
find_pre_post_block(fcx, an_alt.body);
ret block_pp(fcx.ccx, an_alt.body);
}
- let alt_pps = ~[];
- for a: arm in alts { alt_pps += ~[do_an_alt(fcx, a)]; }
+ let alt_pps = [];
+ for a: arm in alts { alt_pps += [do_an_alt(fcx, a)]; }
fn combine_pp(antec: pre_and_post, fcx: fn_ctxt, pp: &pre_and_post,
next: &pre_and_post) -> pre_and_post {
- union(pp.precondition, seq_preconds(fcx, ~[antec, next]));
+ union(pp.precondition, seq_preconds(fcx, [antec, next]));
intersect(pp.postcondition, next.postcondition);
ret pp;
}
}
+
expr_bind(operator, maybe_args) {
- let args = ~[];
+ let args = [];
let cmodes = callee_modes(fcx, operator.id);
- let modes = ~[];
+ let modes = [];
let i = 0;
for expr_opt: option::t<@expr> in maybe_args {
alt expr_opt {
none. {/* no-op */ }
- some(expr) {
- modes += ~[cmodes.(i)];
- args += ~[expr];
- }
+ some(expr) { modes += [cmodes[i]]; args += [expr]; }
}
i += 1;
}
- args += ~[operator]; /* ??? order of eval? */
+ args += [operator]; /* ??? order of eval? */
forget_args_moved_in(fcx, e, modes, args);
find_pre_post_exprs(fcx, args, e.id);
}
none. { clear_pp(expr_pp(fcx.ccx, e)); }
}
}
- expr_uniq(sub) { find_pre_post_exprs(fcx, ~[sub], e.id); }
+ expr_uniq(sub) { find_pre_post_exprs(fcx, [sub], e.id); }
}
}
/* FIXME: This won't be necessary when typestate
works well enough for pat_bindings to return a
refinement-typed thing. */
- let ident = alt pat.node {
- pat_bind(n) { n }
- _ {
- fcx.ccx.tcx.sess.span_bug(pat.span,
- "Impossible LHS");
- }
- };
+ let ident =
+ alt pat.node {
+ pat_bind(n) { n }
+ _ {
+ fcx.ccx.tcx.sess.span_bug(pat.span,
+ "Impossible LHS");
+ }
+ };
alt p {
some(p) {
copy_in_postcond(fcx, id,
{ident: ident, node: pat.id},
{ident:
- path_to_ident(fcx.ccx.tcx, p),
+ path_to_ident(fcx.ccx.tcx,
+ p),
node: an_init.expr.id},
op_to_oper_ty(an_init.op));
}
- none. {}
+ none. { }
}
gen(fcx, id, ninit(pat.id, ident));
}
fcx.ccx.tcx.sess.span_bug(pat.span,
"Impossible LHS");
}
- };
+ }
}
- copy_pre_post_(fcx.ccx, id,
- prev_pp.precondition,
+ copy_pre_post_(fcx.ccx, id, prev_pp.precondition,
prev_pp.postcondition);
}
none. {
let nv = num_constraints(fcx.enclosing);
fn do_one_(fcx: fn_ctxt, s: &@stmt) {
find_pre_post_stmt(fcx, *s);
-/*
- log_err "pre_post for stmt:";
- log_stmt_err(*s);
- log_err "is:";
- log_pp_err(stmt_pp(fcx.ccx, *s));
-*/
+ /*
+ log_err "pre_post for stmt:";
+ log_stmt_err(*s);
+ log_err "is:";
+ log_pp_err(stmt_pp(fcx.ccx, *s));
+ */
}
for s: @stmt in b.node.stmts { do_one_(fcx, s); }
fn do_inner_(fcx: fn_ctxt, e: &@expr) { find_pre_post_expr(fcx, e); }
let do_inner = bind do_inner_(fcx, _);
option::map::<@expr, ()>(do_inner, b.node.expr);
- let pps: [pre_and_post] = ~[];
- for s: @stmt in b.node.stmts { pps += ~[stmt_pp(fcx.ccx, *s)]; }
+ let pps: [pre_and_post] = [];
+ for s: @stmt in b.node.stmts { pps += [stmt_pp(fcx.ccx, *s)]; }
alt b.node.expr {
none. {/* no-op */ }
- some(e) { pps += ~[expr_pp(fcx.ccx, e)]; }
+ some(e) { pps += [expr_pp(fcx.ccx, e)]; }
}
let block_precond = seq_preconds(fcx, pps);
- let postconds = ~[];
- for pp: pre_and_post in pps { postconds += ~[get_post(pp)]; }
+ let postconds = [];
+ for pp: pre_and_post in pps { postconds += [get_post(pp)]; }
/* A block may be empty, so this next line ensures that the postconds
vector is non-empty. */
- postconds += ~[block_precond];
+ postconds += [block_precond];
let block_postcond = empty_poststate(nv);
/* conservative approximation */
import util::common::log_expr_err;
fn handle_move_or_copy(fcx: &fn_ctxt, post: &poststate, rhs_path: &path,
- rhs_id: &node_id, instlhs: &inst, init_op: &init_op) {
+ rhs_id: &node_id, instlhs: &inst, init_op: &init_op) {
let rhs_d = local_node_id_to_def_id(fcx, rhs_id);
- alt (rhs_d) {
+ alt rhs_d {
some(rhsid) {
// RHS is a local var
let instrhs =
}
}
-fn seq_states(fcx: &fn_ctxt, pres: &prestate, bindings: &[binding])
- -> {changed: bool, post: poststate} {
+fn seq_states(fcx: &fn_ctxt, pres: &prestate, bindings: &[binding]) ->
+ {changed: bool, post: poststate} {
let changed = false;
let post = tritv_clone(pres);
- for b:binding in bindings {
- alt (b.rhs) {
+ for b: binding in bindings {
+ alt b.rhs {
some(an_init) {
// an expression, with or without a destination
- changed |= find_pre_post_state_expr(fcx, post, an_init.expr)
- || changed;
+ changed |=
+ find_pre_post_state_expr(fcx, post, an_init.expr) || changed;
post = tritv_clone(expr_poststate(fcx.ccx, an_init.expr));
for i: inst in b.lhs {
- alt (an_init.expr.node) {
+ alt an_init.expr.node {
expr_path(p) {
handle_move_or_copy(fcx, post, p, an_init.expr.id, i,
an_init.op);
}
set_in_poststate_ident(fcx, i.node, i.ident, post);
}
+
// Forget the RHS if we just moved it.
if an_init.op == init_move {
forget_in_poststate(fcx, post, an_init.expr.id);
// FIXME: This could be a typestate constraint
if vec::len(bs) != vec::len(ops) {
fcx.ccx.tcx.sess.span_bug(a.span,
- #fmt("mismatched arg lengths: \
+ #fmt["mismatched arg lengths: \
%u exprs vs. %u ops",
- vec::len(bs), vec::len(ops)));
+ vec::len(bs), vec::len(ops)]);
}
- ret find_pre_post_state_exprs(fcx, expr_poststate(fcx.ccx, a), id,
- ops, bs, cf)
- || changed;
+ ret find_pre_post_state_exprs(fcx, expr_poststate(fcx.ccx, a), id, ops,
+ bs, cf) || changed;
}
fn find_pre_post_state_exprs(fcx: &fn_ctxt, pres: &prestate, id: node_id,
- ops: &[init_op], es: &[@expr],
- cf: controlflow) -> bool {
+ ops: &[init_op], es: &[@expr], cf: controlflow)
+ -> bool {
let rs = seq_states(fcx, pres, anon_bindings(ops, es));
let changed = rs.changed | set_prestate_ann(fcx.ccx, id, pres);
/* if this is a failing call, it sets everything as initialized */
expr_vec(elts, _) {
ret find_pre_post_state_exprs(fcx, pres, e.id,
vec::init_elt(init_assign,
- vec::len(elts)),
- elts, return);
+ vec::len(elts)), elts,
+ return);
}
expr_call(operator, operands) {
ret find_pre_post_state_call(fcx, pres, operator, e.id,
controlflow_expr(fcx.ccx, operator));
}
expr_bind(operator, maybe_args) {
- let args = ~[];
+ let args = [];
let callee_ops = callee_arg_init_ops(fcx, operator.id);
- let ops = ~[];
+ let ops = [];
let i = 0;
for a_opt: option::t<@expr> in maybe_args {
alt a_opt {
none. {/* no-op */ }
- some(a) {
- ops += ~[callee_ops.(i)];
- args += ~[a];
- }
+ some(a) { ops += [callee_ops[i]]; args += [a]; }
}
i += 1;
}
let changed =
find_pre_post_state_exprs(fcx, pres, e.id,
vec::init_elt(init_assign,
- vec::len(fields)),
- field_exprs(fields),
- return);
+ vec::len(fields)),
+ field_exprs(fields), return);
alt maybe_base {
none. {/* do nothing */ }
some(base) {
expr_tup(elts) {
ret find_pre_post_state_exprs(fcx, pres, e.id,
vec::init_elt(init_assign,
- vec::len(elts)),
- elts, return);
- }
- expr_copy(a) {
- ret find_pre_post_state_sub(fcx, pres, a, e.id, none);
+ vec::len(elts)), elts,
+ return);
}
+ expr_copy(a) { ret find_pre_post_state_sub(fcx, pres, a, e.id, none); }
expr_move(lhs, rhs) {
ret find_pre_post_state_two(fcx, pres, lhs, rhs, e.id, oper_move);
}
/* normally, everything is true if execution continues after
a ret expression (since execution never continues locally
after a ret expression */
-// FIXME should factor this out
+ // FIXME should factor this out
let post = false_postcond(num_constrs);
// except for the "diverges" bit...
kill_poststate_(fcx, fcx.enclosing.i_diverge, post);
set_poststate_ann(fcx.ccx, e.id, post);
- alt maybe_ret_val {
+ alt maybe_ret_val {
none. {/* do nothing */ }
some(ret_val) {
changed |= find_pre_post_state_expr(fcx, pres, ret_val);
woo! */
let post = false_postcond(num_constrs);
alt fcx.enclosing.cf {
- noreturn. {
- kill_poststate_(fcx, ninit(fcx.id, fcx.name), post);
- }
- _ {}
+ noreturn. { kill_poststate_(fcx, ninit(fcx.id, fcx.name), post); }
+ _ { }
}
ret set_prestate_ann(fcx.ccx, e.id, pres) |
- set_poststate_ann(fcx.ccx, e.id, post)
- | alt maybe_fail_val {
+ set_poststate_ann(fcx.ccx, e.id, post) |
+ alt maybe_fail_val {
none. { false }
some(fail_val) {
find_pre_post_state_expr(fcx, pres, fail_val)
}
}
-fn find_pre_post_state_stmt(fcx: &fn_ctxt, pres: &prestate, s: @stmt)
- -> bool {
+fn find_pre_post_state_stmt(fcx: &fn_ctxt, pres: &prestate, s: @stmt) ->
+ bool {
let stmt_ann = stmt_to_ann(fcx.ccx, *s);
-/*
- log_err ("[" + fcx.name + "]");
- log_err "*At beginning: stmt = ";
- log_stmt_err(*s);
- log_err "*prestate = ";
- log_tritv_err(fcx, stmt_ann.states.prestate);
- log_err "*poststate =";
- log_tritv_err(fcx, stmt_ann.states.poststate);
- log_err "pres = ";
- log_tritv_err(fcx, pres);
-*/
-
- alt (s.node) {
+ /*
+ log_err ("[" + fcx.name + "]");
+ log_err "*At beginning: stmt = ";
+ log_stmt_err(*s);
+ log_err "*prestate = ";
+ log_tritv_err(fcx, stmt_ann.states.prestate);
+ log_err "*poststate =";
+ log_tritv_err(fcx, stmt_ann.states.poststate);
+ log_err "pres = ";
+ log_tritv_err(fcx, pres);
+ */
+
+ alt s.node {
stmt_decl(adecl, id) {
- alt (adecl.node) {
+ alt adecl.node {
decl_local(alocals) {
set_prestate(stmt_ann, pres);
- let c_and_p = seq_states(fcx, pres,
- locals_to_bindings(alocals));
+ let c_and_p = seq_states(fcx, pres, locals_to_bindings(alocals));
/* important to do this in one step to ensure
termination (don't want to set changed to true
for intermediate changes) */
- let changed = (set_poststate(stmt_ann, c_and_p.post)
- | c_and_p.changed);
+ let changed =
+ set_poststate(stmt_ann, c_and_p.post) | c_and_p.changed;
-/*
- log_err "Summary: stmt = ";
- log_stmt_err(*s);
- log_err "prestate = ";
- log_tritv_err(fcx, stmt_ann.states.prestate);
- log_err "poststate =";
- log_tritv_err(fcx, stmt_ann.states.poststate);
- log_err "changed =";
- log_err changed;
-*/
+ /*
+ log_err "Summary: stmt = ";
+ log_stmt_err(*s);
+ log_err "prestate = ";
+ log_tritv_err(fcx, stmt_ann.states.prestate);
+ log_err "poststate =";
+ log_tritv_err(fcx, stmt_ann.states.poststate);
+ log_err "changed =";
+ log_err changed;
+ */
ret changed;
}
decl_item(an_item) {
- ret set_prestate(stmt_ann, pres) |
- set_poststate(stmt_ann, pres);
+ ret set_prestate(stmt_ann, pres) | set_poststate(stmt_ann, pres);
/* the outer visitor will recurse into the item */
}
}
}
stmt_expr(ex, _) {
- let changed = find_pre_post_state_expr(fcx, pres, ex) |
+ let changed =
+ find_pre_post_state_expr(fcx, pres, ex) |
set_prestate(stmt_ann, expr_prestate(fcx.ccx, ex)) |
set_poststate(stmt_ann, expr_poststate(fcx.ccx, ex));
-/*
- log_err "Finally:";
- log_stmt_err(*s);
- log_err("prestate = ");
- // log_err(bitv::to_str(stmt_ann.states.prestate));
- log_tritv_err(fcx, stmt_ann.states.prestate);
- log_err("poststate =");
- // log_err(bitv::to_str(stmt_ann.states.poststate));
- log_tritv_err(fcx, stmt_ann.states.poststate);
- log_err("changed =");
-*/
+ /*
+ log_err "Finally:";
+ log_stmt_err(*s);
+ log_err("prestate = ");
+ log_err(bitv::to_str(stmt_ann.states.prestate));
+ log_tritv_err(fcx, stmt_ann.states.prestate);
+ log_err("poststate =");
+ log_err(bitv::to_str(stmt_ann.states.poststate));
+ log_tritv_err(fcx, stmt_ann.states.poststate);
+ log_err("changed =");
+ */
- ret changed;
+ ret changed;
}
_ { ret false; }
}
set_poststate_ann(fcx.ccx, b.node.id, post);
-/*
- log_err "For block:";
- log_block_err(b);
- log_err "poststate = ";
- log_states_err(block_states(fcx.ccx, b));
- log_err "pres0:";
- log_tritv_err(fcx, pres0);
- log_err "post:";
- log_tritv_err(fcx, post);
- log_err "changed = ";
- log_err changed;
-*/
+ /*
+ log_err "For block:";
+ log_block_err(b);
+ log_err "poststate = ";
+ log_states_err(block_states(fcx.ccx, b));
+ log_err "pres0:";
+ log_tritv_err(fcx, pres0);
+ log_err "post:";
+ log_tritv_err(fcx, post);
+ log_err "changed = ";
+ log_err changed;
+ */
ret changed;
}
// Arguments start out initialized
let block_pre = block_prestate(fcx.ccx, f.body);
- for a:arg in f.decl.inputs {
+ for a: arg in f.decl.inputs {
set_in_prestate_constr(fcx, ninit(a.id, a.ident), block_pre);
}
alt b {
ttrue. { dont_care }
tfalse. { ttrue }
- /* internally contradictory, but
- I guess it'll get flagged? */
- dont_care. {
+
+ /* internally contradictory, but
+ I guess it'll get flagged? */
+ dont_care. {
ttrue
}
}
tfalse. {
alt b {
ttrue. { tfalse }
- /* see above comment */
+
+ /* see above comment */
_ {
tfalse
}
tfalse. {
alt b {
ttrue. { dont_care }
- /* FIXME: ?????? */
+
+ /* FIXME: ?????? */
_ {
tfalse
}
fn trit_and(a: trit, b: trit) -> trit {
alt a {
dont_care. { b }
- // also seems wrong for case b = ttrue
+
+ // also seems wrong for case b = ttrue
ttrue. {
alt b {
dont_care. { ttrue }
- // ??? Seems wrong
+
+ // ??? Seems wrong
ttrue. {
ttrue
}
+
// false wins, since if something is uninit
// on one path, we care
// (Rationale: it's always safe to assume that
}
}
+
// Rationale: if it's uninit on one path,
// we can consider it as uninit on all paths
tfalse. {
let b1 = bitv::get(v.uncertain, i);
let b2 = bitv::get(v.val, i);
assert (!(b1 && b2));
- if b1 { dont_care } else if (b2) { ttrue } else { tfalse }
+ if b1 { dont_care } else if b2 { ttrue } else { tfalse }
}
fn tritv_set(i: uint, v: &t, t: trit) -> bool {
fn to_vec(v: &t) -> [uint] {
let i: uint = 0u;
- let rslt: [uint] = ~[];
+ let rslt: [uint] = [];
while i < v.nbits {
rslt +=
- ~[alt tritv_get(v, i) {
- dont_care. { 2u }
- ttrue. { 1u }
- tfalse. { 0u }
- }];
+ [alt tritv_get(v, i) {
+ dont_care. { 2u }
+ ttrue. { 1u }
+ tfalse. { 0u }
+ }];
i += 1u;
}
ret rslt;
type creader_cache = hashmap<{cnum: int, pos: uint, len: uint}, ty::t>;
type ctxt =
-
// constr_table fn_constrs,
+ // We need the ext_map just for printing the types of tags defined in
+ // other crates. Once we get cnames back it should go.
@{ts: @type_store,
sess: session::session,
def_map: resolve::def_map,
- // We need the ext_map just for printing the types of tags defined in
- // other crates. Once we get cnames back it should go.
ext_map: resolve::ext_map,
node_types: node_type_table,
items: ast_map::map,
ty_istr. {/* no-op */ }
ty_type. {/* no-op */ }
ty_native(_) {/* no-op */ }
- ty_param(_,_) { has_params = true; }
+ ty_param(_, _) { has_params = true; }
ty_var(_) { has_vars = true; }
ty_tag(_, tys) {
for tt: t in tys { derive_flags_t(cx, has_params, has_vars, tt); }
}
}
ty_tup(ts) {
- for tt in ts {
- derive_flags_t(cx, has_params, has_vars, tt);
- }
+ for tt in ts { derive_flags_t(cx, has_params, has_vars, tt); }
}
ty_fn(_, args, tt, _, _) {
derive_flags_sig(cx, has_params, has_vars, args, tt);
fn mk_native(cx: &ctxt, did: &def_id) -> t { ret gen_ty(cx, ty_native(did)); }
fn mk_iter_body_fn(cx: &ctxt, output: &t) -> t {
- ret mk_fn(cx, ast::proto_block,
- ~[{mode: ty::mo_alias(false), ty: output}],
- ty::mk_nil(cx), ast::return, ~[]);
+ ret mk_fn(cx, ast::proto_block, [{mode: ty::mo_alias(false), ty: output}],
+ ty::mk_nil(cx), ast::return, []);
}
// Returns the one-level-deep type structure of the given type.
// Type folds
-type ty_walk = fn(t) ;
+type ty_walk = fn(t);
fn walk_ty(cx: &ctxt, walker: ty_walk, ty: t) {
alt struct(cx, ty) {
ty_rec(fields) {
for fl: field in fields { walk_ty(cx, walker, fl.mt.ty); }
}
- ty_tup(ts) {
- for tt in ts { walk_ty(cx, walker, tt); }
- }
+ ty_tup(ts) { for tt in ts { walk_ty(cx, walker, tt); } }
ty_fn(proto, args, ret_ty, _, _) {
for a: arg in args { walk_ty(cx, walker, a.ty); }
walk_ty(cx, walker, ret_ty);
walk_ty(cx, walker, sub);
for tp: t in tps { walk_ty(cx, walker, tp); }
}
- ty_constr(sub, _) {
- walk_ty(cx, walker, sub);
- }
+ ty_constr(sub, _) { walk_ty(cx, walker, sub); }
ty_var(_) {/* no-op */ }
- ty_param(_,_) {/* no-op */ }
+ ty_param(_, _) {/* no-op */ }
ty_uniq(sub) { walk_ty(cx, walker, sub); }
}
walker(ty);
}
tag fold_mode {
- fm_var(fn(int) -> t );
- fm_param(fn(uint,ast::kind) -> t );
- fm_general(fn(t) -> t );
+ fm_var(fn(int) -> t);
+ fm_param(fn(uint, ast::kind) -> t);
+ fm_general(fn(t) -> t);
}
fn fold_ty(cx: &ctxt, fld: fold_mode, ty_0: t) -> t {
ty = mk_vec(cx, {ty: fold_ty(cx, fld, tm.ty), mut: tm.mut});
}
ty_tag(tid, subtys) {
- let new_subtys: [t] = ~[];
- for subty: t in subtys { new_subtys += ~[fold_ty(cx, fld, subty)]; }
+ let new_subtys: [t] = [];
+ for subty: t in subtys { new_subtys += [fold_ty(cx, fld, subty)]; }
ty = copy_cname(cx, mk_tag(cx, tid, new_subtys), ty);
}
ty_rec(fields) {
- let new_fields: [field] = ~[];
+ let new_fields: [field] = [];
for fl: field in fields {
let new_ty = fold_ty(cx, fld, fl.mt.ty);
let new_mt = {ty: new_ty, mut: fl.mt.mut};
- new_fields += ~[{ident: fl.ident, mt: new_mt}];
+ new_fields += [{ident: fl.ident, mt: new_mt}];
}
ty = copy_cname(cx, mk_rec(cx, new_fields), ty);
}
ty_tup(ts) {
- let new_ts = ~[];
- for tt in ts {
- new_ts += ~[fold_ty(cx, fld, tt)];
- }
+ let new_ts = [];
+ for tt in ts { new_ts += [fold_ty(cx, fld, tt)]; }
ty = copy_cname(cx, mk_tup(cx, new_ts), ty);
}
ty_fn(proto, args, ret_ty, cf, constrs) {
- let new_args: [arg] = ~[];
+ let new_args: [arg] = [];
for a: arg in args {
let new_ty = fold_ty(cx, fld, a.ty);
- new_args += ~[{mode: a.mode, ty: new_ty}];
+ new_args += [{mode: a.mode, ty: new_ty}];
}
ty =
copy_cname(cx,
cf, constrs), ty);
}
ty_native_fn(abi, args, ret_ty) {
- let new_args: [arg] = ~[];
+ let new_args: [arg] = [];
for a: arg in args {
let new_ty = fold_ty(cx, fld, a.ty);
- new_args += ~[{mode: a.mode, ty: new_ty}];
+ new_args += [{mode: a.mode, ty: new_ty}];
}
ty =
copy_cname(cx,
fold_ty(cx, fld, ret_ty)), ty);
}
ty_obj(methods) {
- let new_methods: [method] = ~[];
+ let new_methods: [method] = [];
for m: method in methods {
- let new_args: [arg] = ~[];
+ let new_args: [arg] = [];
for a: arg in m.inputs {
- new_args += ~[{mode: a.mode, ty: fold_ty(cx, fld, a.ty)}];
+ new_args += [{mode: a.mode, ty: fold_ty(cx, fld, a.ty)}];
}
new_methods +=
- ~[{proto: m.proto,
- ident: m.ident,
- inputs: new_args,
- output: fold_ty(cx, fld, m.output),
- cf: m.cf,
- constrs: m.constrs}];
+ [{proto: m.proto,
+ ident: m.ident,
+ inputs: new_args,
+ output: fold_ty(cx, fld, m.output),
+ cf: m.cf,
+ constrs: m.constrs}];
}
ty = copy_cname(cx, mk_obj(cx, new_methods), ty);
}
ty_res(did, subty, tps) {
- let new_tps = ~[];
- for tp: t in tps { new_tps += ~[fold_ty(cx, fld, tp)]; }
+ let new_tps = [];
+ for tp: t in tps { new_tps += [fold_ty(cx, fld, tp)]; }
ty =
copy_cname(cx, mk_res(cx, did, fold_ty(cx, fld, subty), new_tps),
ty);
ty_var(id) {
alt fld { fm_var(folder) { ty = folder(id); } _ {/* no-op */ } }
}
- ty_param(id,k) {
- alt fld { fm_param(folder) { ty = folder(id,k); } _ {/* no-op */ } }
+ ty_param(id, k) {
+ alt fld { fm_param(folder) { ty = folder(id, k); } _ {/* no-op */ } }
}
}
fn sequence_is_interior(cx: &ctxt, ty: &t) -> bool {
alt struct(cx, ty) {
- ty::ty_str. { ret false; }
+
+ ty::ty_str. {
+ ret false;
+ }
ty::ty_vec(_) { ret true; }
ty::ty_istr. { ret true; }
_ { cx.sess.bug("sequence_is_interior called on non-sequence type"); }
fn get_element_type(cx: &ctxt, ty: &t, i: uint) -> t {
alt struct(cx, ty) {
- ty_rec(flds) { ret flds.(i).mt.ty; }
- ty_tup(ts) { ret ts.(i); }
+ ty_rec(flds) { ret flds[i].mt.ty; }
+ ty_tup(ts) { ret ts[i]; }
_ {
cx.sess.bug("get_element_type called on type " + ty_to_str(cx, ty) +
" - expected a \
let result = false;
alt struct(cx, ty) {
+
// scalar types
ty_nil. {
/* no-op */
ty_native(_) {/* no-op */ }
ty_rec(flds) {
for f: field in flds {
- if type_has_pointers(cx, f.mt.ty) {
- result = true;
- break;
- }
+ if type_has_pointers(cx, f.mt.ty) { result = true; break; }
}
}
ty_tup(elts) {
- for m in elts {
- if type_has_pointers(cx, m) { result = true; }
- }
+ for m in elts { if type_has_pointers(cx, m) { result = true; } }
}
ty_tag(did, tps) {
let variants = tag_variants(cx, did);
for aty: t in variant.args {
// Perform any type parameter substitutions.
let arg_ty = substitute_type_params(cx, tps, aty);
- if type_has_pointers(cx, arg_ty) {
- result = true;
- break;
- }
+ if type_has_pointers(cx, arg_ty) { result = true; break; }
}
if result { break; }
}
fn type_needs_drop(cx: &ctxt, ty: &t) -> bool {
ret alt struct(cx, ty) {
- ty_res(_, _, _) { true }
- _ { type_has_pointers(cx, ty) }
- };
+ ty_res(_, _, _) { true }
+ _ { type_has_pointers(cx, ty) }
+ };
}
fn type_kind(cx: &ctxt, ty: &t) -> ast::kind {
alt struct(cx, ty) {
+
// Scalar types are unique-kind, no substructure.
- ty_nil. | ty_bot. | ty_bool. | ty_int. | ty_uint. | ty_float.
- | ty_machine(_) | ty_char. | ty_native(_) {
+ ty_nil. | ty_bot. | ty_bool. | ty_int. | ty_uint. | ty_float. |
+ ty_machine(_) | ty_char. | ty_native(_) {
// no-op
}
+
// A handful of other built-in are unique too.
ty_type. | ty_istr. | ty_native_fn(_, _, _) {
// no-op
}
+
// Those things with refcounts-to-interior are just shared.
ty_str. {
result = kind_shared;
}
+
// FIXME: obj is broken for now, since we aren't asserting
// anything about its fields.
- ty_obj(_) { result = kind_shared; }
+ ty_obj(_) {
+ result = kind_shared;
+ }
+
// FIXME: the environment capture mode is not fully encoded
// here yet, leading to weirdness around closure.
ty_fn(proto, _, _, _, _) {
- result = alt proto {
- ast::proto_block. { ast::kind_pinned }
- ast::proto_closure. { ast::kind_shared }
- _ { ast::kind_unique }
- }
+ result =
+ alt proto {
+ ast::proto_block. { ast::kind_pinned }
+ ast::proto_closure. { ast::kind_shared }
+ _ { ast::kind_unique }
+ }
}
+
// Those with refcounts-to-inner raise pinned to shared,
// lower unique to shared. Therefore just set result to shared.
ty_box(mt) {
result = ast::kind_shared;
}
+
// Pointers and unique boxes / vecs raise pinned to shared,
// otherwise pass through their pointee kind.
ty_ptr(tm) | ty_vec(tm) {
result = kind::lower_kind(result, k);
}
+
// Records lower to the lowest of their members.
ty_rec(flds) {
for f: field in flds {
if result == ast::kind_pinned { break; }
}
}
+
// Tuples lower to the lowest of their members.
ty_tup(tys) {
for ty: t in tys {
}
}
+
// Tags lower to the lowest of their variants.
ty_tag(did, tps) {
let variants = tag_variants(cx, did);
}
}
+
// Resources are always pinned.
ty_res(did, inner, tps) {
result = ast::kind_pinned;
}
- ty_var(_) { fail; }
- ty_param(_,k) {
+ ty_var(_) {
+ fail;
+ }
+
+
+ ty_param(_, k) {
result = kind::lower_kind(result, k);
}
+
ty_constr(t, _) {
result = type_kind(cx, t);
}
- _ {
- cx.sess.bug("missed case: " + ty_to_str(cx, ty));
- }
+ _ {
+ cx.sess.bug("missed case: " + ty_to_str(cx, ty));
+ }
}
+
cx.kind_cache.insert(ty, result);
ret result;
}
ty_tag(_, subtys) {
let i = 0u;
while i < vec::len::<t>(subtys) {
- if type_has_dynamic_size(cx, subtys.(i)) { ret true; }
+ if type_has_dynamic_size(cx, subtys[i]) { ret true; }
i += 1u;
}
ret false;
ty_rec(fields) {
let i = 0u;
while i < vec::len::<field>(fields) {
- if type_has_dynamic_size(cx, fields.(i).mt.ty) { ret true; }
+ if type_has_dynamic_size(cx, fields[i].mt.ty) { ret true; }
i += 1u;
}
ret false;
}
ty_tup(ts) {
- for tt in ts {
- if type_has_dynamic_size(cx, tt) { ret true; }
- }
+ for tt in ts { if type_has_dynamic_size(cx, tt) { ret true; } }
ret false;
}
ty_fn(_, _, _, _, _) { ret false; }
ret type_has_dynamic_size(cx, sub);
}
ty_var(_) { fail "ty_var in type_has_dynamic_size()"; }
- ty_param(_,_) { ret true; }
+ ty_param(_, _) { ret true; }
ty_type. { ret false; }
ty_native(_) { ret false; }
ty_uniq(_) { ret false; }
ty_istr. { result = true; }
+
// scalar types
ty_nil. {
result = false;
ty_native(_) { result = false; }
+
// boxed types
ty_str. {
result = false;
ty_obj(_) { result = false; }
+
// structural types
ty_tag(did, tps) {
let variants = tag_variants(cx, did);
}
}
ty_tup(elts) {
- for m in elts {
- if type_owns_heap_mem(cx, m) { result = true; }
- }
+ for m in elts { if type_owns_heap_mem(cx, m) { result = true; } }
}
ty_res(_, inner, tps) {
result =
type_owns_heap_mem(cx, substitute_type_params(cx, tps, inner));
}
+
ty_ptr(_) {
result = false;
}
ty_var(_) { fail "ty_var in type_owns_heap_mem"; }
- ty_param(_,_) { result = false; }
+ ty_param(_, _) { result = false; }
}
cx.owns_heap_mem_cache.insert(ty, result);
}
// Whether a type is Plain Old Data (i.e. can be safely memmoved).
-fn type_is_pod(cx : &ctxt, ty : &t) -> bool {
+fn type_is_pod(cx: &ctxt, ty: &t) -> bool {
let result = true;
alt struct(cx, ty) {
- // Scalar types
- ty_nil. | ty_bot. | ty_bool. | ty_int. | ty_float. | ty_uint. |
- ty_machine(_) | ty_char. | ty_type. | ty_native(_) | ty_ptr(_) {
- result = true;
- }
- // Boxed types
- ty_str. | ty_istr. | ty_box(_) | ty_vec(_) |
- ty_fn(_,_,_,_,_) | ty_native_fn(_,_,_) | ty_obj(_) { result = false; }
+ // Scalar types
+ ty_nil. | ty_bot. | ty_bool. | ty_int. | ty_float. | ty_uint. |
+ ty_machine(_) | ty_char. | ty_type. | ty_native(_) | ty_ptr(_) {
+ result = true;
+ }
- // Structural types
- ty_tag(did, tps) {
- let variants = tag_variants(cx, did);
- for variant : variant_info in variants {
- let tup_ty = mk_tup(cx, variant.args);
- // Perform any type parameter substitutions.
- tup_ty = substitute_type_params(cx, tps, tup_ty);
- if !type_is_pod(cx, tup_ty) { result = false; }
- }
- }
- ty_rec(flds) {
- for f : field in flds {
- if !type_is_pod(cx, f.mt.ty) { result = false; }
- }
- }
- ty_tup(elts) {
- for elt in elts {
- if !type_is_pod(cx, elt) { result = false; }
- }
+ // Boxed types
+ ty_str. | ty_istr. | ty_box(_) | ty_vec(_) | ty_fn(_, _, _, _, _) |
+ ty_native_fn(_, _, _) | ty_obj(_) {
+ result = false;
+ }
+
+
+ // Structural types
+ ty_tag(did, tps) {
+ let variants = tag_variants(cx, did);
+ for variant: variant_info in variants {
+ let tup_ty = mk_tup(cx, variant.args);
+
+ // Perform any type parameter substitutions.
+ tup_ty = substitute_type_params(cx, tps, tup_ty);
+ if !type_is_pod(cx, tup_ty) { result = false; }
}
- ty_res(_, inner, tps) {
- result = type_is_pod(cx,
- substitute_type_params(cx, tps, inner));
+ }
+ ty_rec(flds) {
+ for f: field in flds {
+ if !type_is_pod(cx, f.mt.ty) { result = false; }
}
- ty_constr(subt, _) { result = type_is_pod(cx, subt); }
+ }
+ ty_tup(elts) {
+ for elt in elts { if !type_is_pod(cx, elt) { result = false; } }
+ }
+ ty_res(_, inner, tps) {
+ result = type_is_pod(cx, substitute_type_params(cx, tps, inner));
+ }
+ ty_constr(subt, _) { result = type_is_pod(cx, subt); }
+
- ty_var(_) { fail "ty_var in type_is_pod"; }
- ty_param(_,_) { result = false; }
+ ty_var(_) {
+ fail "ty_var in type_is_pod";
+ }
+ ty_param(_, _) { result = false; }
}
ret result;
fn type_param(cx: &ctxt, ty: &t) -> option::t<uint> {
alt struct(cx, ty) {
- ty_param(id,_) { ret some(id); }
+ ty_param(id, _) { ret some(id); }
_ {/* fall through */ }
}
ret none;
// Returns a vec of all the type variables
// occurring in t. It may contain duplicates.
-fn vars_in_type(cx:&ctxt, ty: &t) -> [int] {
- fn collect_var(cx:&ctxt, vars: &@mutable [int], ty: t) {
- alt struct(cx, ty) {
- ty_var(v) {
- *vars += ~[v];
- }
- _ {}
- }
+fn vars_in_type(cx: &ctxt, ty: &t) -> [int] {
+ fn collect_var(cx: &ctxt, vars: &@mutable [int], ty: t) {
+ alt struct(cx, ty) { ty_var(v) { *vars += [v]; } _ { } }
}
- let rslt: @mutable [int] = @mutable (~[]);
+ let rslt: @mutable [int] = @mutable [];
walk_ty(cx, bind collect_var(cx, rslt, _), ty);
// Works because of a "convenient" bug that lets us
// return a mutable vec as if it's immutable
}
ty::ty_tag(did, tps) {
let variants = tag_variants(cx, did);
- if vec::len(variants) != 1u || vec::len(variants.(0).args) != 1u
- {
+ if vec::len(variants) != 1u || vec::len(variants[0].args) != 1u {
break;
}
- t1 = substitute_type_params(cx, tps, variants.(0).args.(0));
+ t1 = substitute_type_params(cx, tps, variants[0].args[0]);
}
_ { break; }
}
ret h;
}
+
// ???
ty_fn(_, args, rty, _, _) {
ret hash_fn(27u, args, rty);
ret h;
}
ty_var(v) { ret hash_uint(30u, v as uint); }
- ty_param(pid,_) { ret hash_uint(31u, pid); }
+ ty_param(pid, _) { ret hash_uint(31u, pid); }
ty_type. { ret 32u; }
ty_native(did) { ret hash_def(33u, did); }
ty_bot. { ret 34u; }
for c: @type_constr in cs { h += h << 5u + hash_type_constr(h, c); }
ret h;
}
- ty_uniq(t) {
- let h = 37u;
- h += h << 5u + hash_ty(t);
- ret h;
- }
+ ty_uniq(t) { let h = 37u; h += h << 5u + hash_ty(t); ret h; }
}
}
// users should use `eq_ty()` instead.
fn eq_int(x: &uint, y: &uint) -> bool { ret x == y; }
-fn arg_eq<T>(eq: &fn(&T, &T) -> bool , a: @sp_constr_arg<T>,
+fn arg_eq<T>(eq: &fn(&T, &T) -> bool, a: @sp_constr_arg<T>,
b: @sp_constr_arg<T>) -> bool {
alt a.node {
ast::carg_base. {
}
}
-fn args_eq<T>(eq: fn(&T, &T) -> bool , a: &[@sp_constr_arg<T>],
+fn args_eq<T>(eq: fn(&T, &T) -> bool, a: &[@sp_constr_arg<T>],
b: &[@sp_constr_arg<T>]) -> bool {
let i: uint = 0u;
for arg: @sp_constr_arg<T> in a {
- if !arg_eq(eq, arg, b.(i)) { ret false; }
+ if !arg_eq(eq, arg, b[i]) { ret false; }
i += 1u;
}
ret true;
fn constrs_eq(cs: &[@constr], ds: &[@constr]) -> bool {
if vec::len(cs) != vec::len(ds) { ret false; }
let i = 0u;
- for c: @constr in cs { if !constr_eq(c, ds.(i)) { ret false; } i += 1u; }
+ for c: @constr in cs { if !constr_eq(c, ds[i]) { ret false; } i += 1u; }
ret true;
}
fn node_id_to_type_params(cx: &ctxt, id: &ast::node_id) -> [t] {
alt node_id_to_ty_param_substs_opt_and_ty(cx, id).substs {
- none. { ret ~[]; }
+ none. { ret []; }
some(tps) { ret tps; }
}
}
fn count_ty_params(cx: &ctxt, ty: t) -> uint {
fn counter(cx: &ctxt, param_indices: @mutable [uint], ty: t) {
alt struct(cx, ty) {
- ty_param(param_idx,_) {
+ ty_param(param_idx, _) {
let seen = false;
for other_param_idx: uint in *param_indices {
if param_idx == other_param_idx { seen = true; }
}
- if !seen { *param_indices += ~[param_idx]; }
+ if !seen { *param_indices += [param_idx]; }
}
_ {/* fall through */ }
}
}
- let param_indices: @mutable [uint] = @mutable ~[];
+ let param_indices: @mutable [uint] = @mutable [];
let f = bind counter(cx, param_indices, _);
walk_ty(cx, f, ty);
ret vec::len::<uint>(*param_indices);
}
}
-fn occurs_check_fails(tcx: &ctxt, sp: &option::t<span>, vid: int, rt: &t)
- -> bool {
- if (!type_contains_vars(tcx, rt)) {
+fn occurs_check_fails(tcx: &ctxt, sp: &option::t<span>, vid: int, rt: &t) ->
+ bool {
+ if !type_contains_vars(tcx, rt) {
// Fast path
ret false;
}
+
// Occurs check!
if vec::member(vid, vars_in_type(tcx, rt)) {
alt sp {
- some (s) {
+ some(s) {
// Maybe this should be span_err -- however, there's an
// assertion later on that the type doesn't contain
// variables, so in this case we have to be sure to die.
- tcx.sess.span_fatal(s,
- "Type inference failed because I \
- could not find a type\n that's both of the form " +
- ty_to_str(tcx, ty::mk_var(tcx, (vid)))
- + " and of the form " + ty_to_str(tcx, rt)
- + ". Such a type would have to be infinitely \
- large.");
+ tcx.sess.span_fatal(
+ s,
+ "Type inference failed because I \
+ could not find a type\n that's both of the form "
+ + ty_to_str(tcx, ty::mk_var(tcx, vid)) +
+ " and of the form " + ty_to_str(tcx, rt) +
+ ". Such a type would have to be infinitely \
+ large.");
}
_ { ret true; }
}
- }
- else { ret false; }
+ } else { ret false; }
}
// Type unification via Robinson's algorithm (Robinson 1965). Implemented as
alt smallintmap::find(cx.vb.types, root_a) {
none. {
alt smallintmap::find(cx.vb.types, root_b) {
- none. {
- ufind::union(cx.vb.sets, set_a, set_b);
- ret unres_ok;
- }
+ none. { ufind::union(cx.vb.sets, set_a, set_b); ret unres_ok; }
some(t_b) { replace_type(cx, t_b); ret unres_ok; }
}
}
let i = 0u;
let rslt;
for c: @type_constr in expected {
- rslt = unify_constr(base_t, c, actual.(i));
+ rslt = unify_constr(base_t, c, actual[i]);
alt rslt { ures_ok(_) { } ures_err(_) { ret rslt; } }
i += 1u;
}
let i = 0u;
let actual;
for a: @ty_constr_arg in expected.node.args {
- actual = actual_constr.node.args.(i);
+ actual = actual_constr.node.args[i];
alt a.node {
carg_base. {
alt actual.node { carg_base. { } _ { ret err_res; } }
}
// TODO: as above, we should have an iter2 iterator.
- let result_ins: [arg] = ~[];
+ let result_ins: [arg] = [];
let i = 0u;
while i < expected_len {
- let expected_input = expected_inputs.(i);
- let actual_input = actual_inputs.(i);
+ let expected_input = expected_inputs[i];
+ let actual_input = actual_inputs[i];
// Unify the result modes.
let result_mode;
if expected_input.mode != actual_input.mode {
- ret fn_common_res_err
- (ures_err(terr_mode_mismatch(expected_input.mode,
- actual_input.mode)));
+ ret fn_common_res_err(
+ ures_err(terr_mode_mismatch(expected_input.mode,
+ actual_input.mode)));
} else { result_mode = expected_input.mode; }
let result = unify_step(cx, expected_input.ty, actual_input.ty);
alt result {
- ures_ok(rty) { result_ins += ~[{mode: result_mode, ty: rty}]; }
+ ures_ok(rty) { result_ins += [{mode: result_mode, ty: rty}]; }
_ { ret fn_common_res_err(result); }
}
i += 1u;
expected: &t, actual: &t, expected_inputs: &[arg],
expected_output: &t, actual_inputs: &[arg], actual_output: &t,
expected_cf: &controlflow, actual_cf: &controlflow,
- _expected_constrs: &[@constr], actual_constrs: &[@constr])
- -> result {
+ _expected_constrs: &[@constr], actual_constrs: &[@constr]) ->
+ result {
if e_proto != a_proto { ret ures_err(terr_mismatch); }
alt expected_cf {
ast::return. { }
- // ok
+
+ // ok
ast::noreturn. {
alt actual_cf {
ast::noreturn. {
fn unify_obj(cx: &@ctxt, expected: &t, actual: &t,
expected_meths: &[method], actual_meths: &[method]) ->
result {
- let result_meths: [method] = ~[];
+ let result_meths: [method] = [];
let i: uint = 0u;
let expected_len: uint = vec::len::<method>(expected_meths);
let actual_len: uint = vec::len::<method>(actual_meths);
if expected_len != actual_len { ret ures_err(terr_meth_count); }
while i < expected_len {
- let e_meth = expected_meths.(i);
- let a_meth = actual_meths.(i);
+ let e_meth = expected_meths[i];
+ let a_meth = actual_meths[i];
if !str::eq(e_meth.ident, a_meth.ident) {
ret ures_err(terr_obj_meths(e_meth.ident, a_meth.ident));
}
alt struct(cx.tcx, tfn) {
ty_fn(proto, ins, out, cf, constrs) {
result_meths +=
- ~[{inputs: ins, output: out, cf: cf, constrs: constrs
- with e_meth}];
+ [{inputs: ins, output: out, cf: cf, constrs: constrs
+ with e_meth}];
}
}
}
fixup_result {
alt struct(tcx, typ) {
ty_var(vid) {
- if vid as uint >= ufind::set_count(vb.sets) {
- ret fix_err(vid);
- }
+ if vid as uint >= ufind::set_count(vb.sets) { ret fix_err(vid); }
let root_id = ufind::find(vb.sets, vid as uint);
alt smallintmap::find::<t>(vb.types, root_id) {
none. { ret fix_err(vid); }
alt struct(cx.tcx, actual) {
+
// If the RHS is a variable type, then just do the
// appropriate binding.
ty::ty_var(actual_id) {
alt struct(cx.tcx, expected) {
ty::ty_nil. { ret struct_cmp(cx, expected, actual); }
+
// _|_ unifies with anything
ty::ty_bot. {
ret ures_ok(actual);
_ { ret ures_err(terr_mismatch); }
}
}
- ty::ty_param(_,_) { ret struct_cmp(cx, expected, actual); }
+ ty::ty_param(_, _) { ret struct_cmp(cx, expected, actual); }
ty::ty_tag(expected_id, expected_tps) {
alt struct(cx.tcx, actual) {
ty::ty_tag(actual_id, actual_tps) {
ret ures_err(terr_mismatch);
}
// TODO: factor this cruft out
- let result_tps: [t] = ~[];
+ let result_tps: [t] = [];
let i = 0u;
let expected_len = vec::len::<t>(expected_tps);
while i < expected_len {
- let expected_tp = expected_tps.(i);
- let actual_tp = actual_tps.(i);
+ let expected_tp = expected_tps[i];
+ let actual_tp = actual_tps[i];
let result = unify_step(cx, expected_tp, actual_tp);
alt result {
- ures_ok(rty) { result_tps += ~[rty]; }
+ ures_ok(rty) { result_tps += [rty]; }
_ { ret result; }
}
i += 1u;
alt result {
ures_ok(res_inner) {
let i = 0u;
- let res_tps = ~[];
+ let res_tps = [];
for ex_tp: t in ex_tps {
- let result = unify_step(cx, ex_tp, act_tps.(i));
+ let result = unify_step(cx, ex_tp, act_tps[i]);
alt result {
- ures_ok(rty) { res_tps += ~[rty]; }
+ ures_ok(rty) { res_tps += [rty]; }
_ { ret result; }
}
i += 1u;
// TODO: implement an iterator that can iterate over
// two arrays simultaneously.
- let result_fields: [field] = ~[];
+ let result_fields: [field] = [];
let i = 0u;
while i < expected_len {
- let expected_field = expected_fields.(i);
- let actual_field = actual_fields.(i);
+ let expected_field = expected_fields[i];
+ let actual_field = actual_fields[i];
let mut;
alt unify_mut(expected_field.mt.mut, actual_field.mt.mut)
{
alt result {
ures_ok(rty) {
let mt = {ty: rty, mut: mut};
- result_fields += ~[{mt: mt with expected_field}];
+ result_fields += [{mt: mt with expected_field}];
}
_ { ret result; }
}
ty::ty_tup(actual_elems) {
let expected_len = vec::len(expected_elems);
let actual_len = vec::len(actual_elems);
- if (expected_len != actual_len) {
+ if expected_len != actual_len {
let err = terr_tuple_size(expected_len, actual_len);
ret ures_err(err);
}
// TODO: implement an iterator that can iterate over
// two arrays simultaneously.
- let result_elems = ~[];
+ let result_elems = [];
let i = 0u;
while i < expected_len {
- let expected_elem = expected_elems.(i);
- let actual_elem = actual_elems.(i);
- let result = unify_step(cx, expected_elem,
- actual_elem);
+ let expected_elem = expected_elems[i];
+ let actual_elem = actual_elems[i];
+ let result = unify_step(cx, expected_elem, actual_elem);
alt result {
- ures_ok(rty) {
- result_elems += ~[rty];
- }
+ ures_ok(rty) { result_elems += [rty]; }
_ { ret result; }
}
i += 1u;
let sets = "";
let j = 0u;
while j < vec::len::<option::t<uint>>(vb.sets.nodes) {
- if ufind::find(vb.sets, j) == i {
- sets += #fmt(" %u", j);
- }
+ if ufind::find(vb.sets, j) == i { sets += #fmt[" %u", j]; }
j += 1u;
}
let typespec;
none. { typespec = ""; }
some(typ) { typespec = " =" + ty_to_str(tcx, typ); }
}
- log_err #fmt("set %u:%s%s", i, typespec, sets);
+ log_err #fmt["set %u:%s%s", i, typespec, sets];
i += 1u;
}
}
// Takes an optional span - complain about occurs check violations
// iff the span is present (so that if we already know we're going
// to error anyway, we don't complain)
- fn fixup_vars(tcx: ty_ctxt, sp: &option::t<span>,
- vb: @var_bindings, typ: t) -> fixup_result {
+ fn fixup_vars(tcx: ty_ctxt, sp: &option::t<span>, vb: @var_bindings,
+ typ: t) -> fixup_result {
fn subst_vars(tcx: ty_ctxt, sp: &option::t<span>, vb: @var_bindings,
unresolved: @mutable option::t<int>, vid: int) -> t {
// Should really return a fixup_result instead of a t, but fold_ty
none. { *unresolved = some(vid); ret ty::mk_var(tcx, vid); }
some(rt) {
if occurs_check_fails(tcx, sp, vid, rt) {
- // Return the type unchanged, so we can error out downstream
+ // Return the type unchanged, so we can error out
+ // downstream
ret rt;
}
ret fold_ty(tcx,
- fm_var(bind subst_vars(tcx, sp, vb, unresolved, _)), rt);
+ fm_var(bind subst_vars(tcx, sp, vb, unresolved,
+ _)), rt);
}
}
}
}
}
fn resolve_type_var(tcx: &ty_ctxt, sp: &option::t<span>,
- vb: &@var_bindings, vid: int) ->
- fixup_result {
+ vb: &@var_bindings, vid: int) -> fixup_result {
if vid as uint >= ufind::set_count(vb.sets) { ret fix_err(vid); }
let root_id = ufind::find(vb.sets, vid as uint);
alt smallintmap::find::<t>(vb.types, root_id) {
terr_vec_mutability. { ret "vectors differ in mutability"; }
terr_tuple_size(e_sz, a_sz) {
ret "expected a tuple with " + uint::to_str(e_sz, 10u) +
- " elements but found one with " + uint::to_str(a_sz, 10u)
- + " elements";
+ " elements but found one with " + uint::to_str(a_sz, 10u) +
+ " elements";
}
terr_record_size(e_sz, a_sz) {
ret "expected a record with " + uint::to_str(e_sz, 10u) +
// Converts type parameters in a type to type variables and returns the
// resulting type along with a list of type variable IDs.
-fn bind_params_in_type(sp: &span, cx: &ctxt, next_ty_var: fn() -> int ,
- typ: t, ty_param_count: uint) -> {ids: [int], ty: t} {
- let param_var_ids: @mutable [int] = @mutable ~[];
+fn bind_params_in_type(sp: &span, cx: &ctxt, next_ty_var: fn() -> int, typ: t,
+ ty_param_count: uint) -> {ids: [int], ty: t} {
+ let param_var_ids: @mutable [int] = @mutable [];
let i = 0u;
- while i < ty_param_count { *param_var_ids += ~[next_ty_var()]; i += 1u; }
+ while i < ty_param_count { *param_var_ids += [next_ty_var()]; i += 1u; }
fn binder(sp: span, cx: ctxt, param_var_ids: @mutable [int],
- _next_ty_var: fn() -> int , index: uint, _kind: ast::kind)
- -> t {
+ _next_ty_var: fn() -> int, index: uint, _kind: ast::kind) -> t {
if index < vec::len(*param_var_ids) {
- ret mk_var(cx, param_var_ids.(index));
+ ret mk_var(cx, param_var_ids[index]);
} else {
cx.sess.span_fatal(sp, "Unbound type parameter in callee's type");
}
}
let new_typ =
fold_ty(cx,
- fm_param(bind binder(sp, cx, param_var_ids, next_ty_var,
- _, _)),
- typ);
+ fm_param(bind binder(sp, cx, param_var_ids, next_ty_var, _,
+ _)), typ);
ret {ids: *param_var_ids, ty: new_typ};
}
// substitions.
fn substitute_type_params(cx: &ctxt, substs: &[ty::t], typ: t) -> t {
if !type_contains_params(cx, typ) { ret typ; }
- fn substituter(_cx: ctxt, substs: @[ty::t], idx: uint,
- _kind: ast::kind) -> t {
+ fn substituter(_cx: ctxt, substs: @[ty::t], idx: uint, _kind: ast::kind)
+ -> t {
// FIXME: bounds check can fail
- ret substs.(idx);
+ ret substs[idx];
}
ret fold_ty(cx, fm_param(bind substituter(cx, @substs, _, _)), typ);
}
ast::def_local(_) { ret false; }
ast::def_variant(_, _) { ret true; }
ast::def_ty(_) { ret false; }
- ast::def_ty_arg(_,_) { ret false; }
+ ast::def_ty_arg(_, _) { ret false; }
ast::def_binding(_) { ret false; }
ast::def_use(_) { ret false; }
ast::def_native_ty(_) { ret false; }
ast_map::node_item(item) {
alt item.node {
ast::item_tag(variants, _) {
- let result: [variant_info] = ~[];
+ let result: [variant_info] = [];
for variant: ast::variant in variants {
let ctor_ty = node_id_to_monotype(cx, variant.node.id);
- let arg_tys: [t] = ~[];
+ let arg_tys: [t] = [];
if std::vec::len(variant.node.args) > 0u {
for a: arg in ty_fn_args(cx, ctor_ty) {
- arg_tys += ~[a.ty];
+ arg_tys += [a.ty];
}
}
let did = variant.node.id;
result +=
- ~[{args: arg_tys,
- ctor_ty: ctor_ty,
- id: ast::local_def(did)}];
+ [{args: arg_tys,
+ ctor_ty: ctor_ty,
+ id: ast::local_def(did)}];
}
ret result;
}
let variants = tag_variants(cx, tag_id);
let i = 0u;
while i < vec::len::<variant_info>(variants) {
- let variant = variants.(i);
+ let variant = variants[i];
if def_eq(variant.id, variant_id) { ret variant; }
i += 1u;
}
ty_rec(_) { tycat_struct }
ty_tup(_) { tycat_struct }
ty_tag(_, _) { tycat_struct }
- ty_bot. { tycat_bot }
+ ty_bot. { tycat_bot }
_ { tycat_other }
}
}
/*. add, shift, bit
. sub, rel, logic
. mult, eq, */
- let /*other*/
- /*bool*/
- /*int*/
- /*float*/
- /*str*/
- /*vec*/
- /*bot*/
- tbl =
- ~[~[f, f, f, f, t, t, f, f],
- ~[f, f, f, f, t, t, t, t],
- ~[t, t, t, t, t, t, t, f],
- ~[t, t, t, f, t, t, f, f],
- ~[t, f, f, f, t, t, f, f],
- ~[t, f, f, f, t, t, f, f],
- ~[f, f, f, f, t, t, f, f],
- ~[t, t, t, t, t, t, t, t]]; /*struct*/
-
- ret tbl.(tycat(cx, ty)).(opcat(op));
+ /*other*/
+ /*bool*/
+ /*int*/
+ /*float*/
+ /*str*/
+ /*vec*/
+ /*bot*/
+ let tbl =
+ [[f, f, f, f, t, t, f, f], [f, f, f, f, t, t, t, t],
+ [t, t, t, t, t, t, t, f], [t, t, t, f, t, t, f, f],
+ [t, f, f, f, t, t, f, f], [t, f, f, f, t, t, f, f],
+ [f, f, f, f, t, t, f, f], [t, t, t, t, t, t, t, t]]; /*struct*/
+
+ ret tbl[tycat(cx, ty)][opcat(op)];
}
fn ast_constr_to_constr<T>(tcx: ty::ctxt, c: &@ast::constr_general<T>) ->
{path: c.node.path, args: c.node.args, id: pred_id});
}
_ {
- tcx.sess.span_fatal
- (c.span, "Predicate " + path_to_str(c.node.path) +
- " is unbound or bound to a non-function or an \
- impure function");
+ tcx.sess.span_fatal(c.span,
+ "Predicate " + path_to_str(c.node.path) +
+ " is unbound or bound to a non-function or an \
+ impure function");
}
}
}
// Used for typechecking the methods of an object.
tag obj_info {
+
// Regular objects have a node_id at compile time.
regular_obj([ast::obj_field], ast::node_id);
+
// Anonymous objects only have a type at compile time. It's optional
// because not all anonymous objects have a inner_obj to attach to.
anon_obj([ast::obj_field], option::t<ty::sty>);
// Used for ast_ty_to_ty() below.
-type ty_getter = fn(&ast::def_id) -> ty::ty_param_kinds_and_ty ;
+type ty_getter = fn(&ast::def_id) -> ty::ty_param_kinds_and_ty;
fn lookup_local(fcx: &@fn_ctxt, sp: &span, id: ast::node_id) -> int {
alt fcx.locals.find(id) {
some(x) { x }
_ {
- fcx.ccx.tcx.sess.span_fatal
- (sp, "internal error looking up a local var")
+ fcx.ccx.tcx.sess.span_fatal(sp,
+ "internal error looking up a local var")
}
}
}
alt fcx.ccx.tcx.def_map.find(id) {
some(x) { x }
_ {
- fcx.ccx.tcx.sess.span_fatal
- (sp, "internal error looking up a definition")
+ fcx.ccx.tcx.sess.span_fatal(sp,
+ "internal error looking up a definition")
}
}
}
fn ident_for_local(loc: &@ast::local) -> ast::ident {
ret alt loc.node.pat.node {
- ast::pat_bind(name) { name }
- _ { "local" } // FIXME DESTR
- };
+ ast::pat_bind(name) { name }
+ _ { "local" }
+ }; // FIXME DESTR
}
// Returns the type parameter count and the type for the given definition.
fn ty_param_kinds_and_ty_for_def(fcx: &@fn_ctxt, sp: &span, defn: &ast::def)
-> ty_param_kinds_and_ty {
- let no_kinds: [ast::kind] = ~[];
+ let no_kinds: [ast::kind] = [];
alt defn {
ast::def_arg(id) {
if ty_substs_len > 0u {
let param_var_len = vec::len(ty_param_vars);
if param_var_len == 0u {
- fcx.ccx.tcx.sess.span_fatal
- (sp, "this item does not take type parameters");
- } else if (ty_substs_len > param_var_len) {
- fcx.ccx.tcx.sess.span_fatal
- (sp, "too many type parameter provided for this item");
- } else if (ty_substs_len < param_var_len) {
- fcx.ccx.tcx.sess.span_fatal
- (sp, "not enough type parameters provided for this item");
- }
- let ty_substs: [ty::t] = ~[];
+ fcx.ccx.tcx.sess.span_fatal(
+ sp,
+ "this item does not take type parameters");
+ } else if ty_substs_len > param_var_len {
+ fcx.ccx.tcx.sess.span_fatal(
+ sp,
+ "too many type parameter provided for this item");
+ } else if ty_substs_len < param_var_len {
+ fcx.ccx.tcx.sess.span_fatal(
+ sp,
+ "not enough type parameters provided for this item");
+ }
+ let ty_substs: [ty::t] = [];
let i = 0u;
while i < ty_substs_len {
- let ty_var = ty::mk_var(fcx.ccx.tcx, ty_param_vars.(i));
- let ty_subst = ast_ty_to_ty_crate(fcx.ccx, pth.node.types.(i));
+ let ty_var = ty::mk_var(fcx.ccx.tcx, ty_param_vars[i]);
+ let ty_subst = ast_ty_to_ty_crate(fcx.ccx, pth.node.types[i]);
let res_ty = demand::simple(fcx, pth.span, ty_var, ty_subst);
- ty_substs += ~[res_ty];
+ ty_substs += [res_ty];
i += 1u;
}
ty_substs_opt = some::<[ty::t]>(ty_substs);
}
} else {
// We will acquire the type parameters through unification.
- let ty_substs: [ty::t] = ~[];
+ let ty_substs: [ty::t] = [];
let i = 0u;
while i < ty_param_count {
- ty_substs += ~[ty::mk_var(fcx.ccx.tcx, ty_param_vars.(i))];
+ ty_substs += [ty::mk_var(fcx.ccx.tcx, ty_param_vars[i])];
i += 1u;
}
ty_substs_opt = some::<[ty::t]>(ty_substs);
// Type tests
-fn structurally_resolved_type(fcx: &@fn_ctxt, sp: &span, tp: ty::t) ->
- ty::t {
+fn structurally_resolved_type(fcx: &@fn_ctxt, sp: &span, tp: ty::t) -> ty::t {
alt ty::unify::resolve_type_structure(fcx.ccx.tcx, fcx.var_bindings, tp) {
fix_ok(typ_s) { ret typ_s; }
fix_err(_) {
- fcx.ccx.tcx.sess.span_fatal
- (sp, "the type of this value must be known in this context");
+ fcx.ccx.tcx.sess.span_fatal(
+ sp,
+ "the type of this value must be known in this context");
}
}
}
// The typedef is type-parametric. Do the type substitution.
//
- let param_bindings: [ty::t] = ~[];
+ let param_bindings: [ty::t] = [];
for ast_ty: @ast::ty in args {
- param_bindings += ~[ast_ty_to_ty(tcx, getter, ast_ty)];
+ param_bindings += [ast_ty_to_ty(tcx, getter, ast_ty)];
}
- if vec::len(param_bindings) !=
- vec::len(ty_param_kinds_and_ty.kinds) {
+ if vec::len(param_bindings) != vec::len(ty_param_kinds_and_ty.kinds) {
tcx.sess.span_fatal(sp,
"Wrong number of type arguments for a \
polymorphic type");
typ = ty::mk_tup(tcx, flds);
}
ast::ty_rec(fields) {
- let flds: [field] = ~[];
+ let flds: [field] = [];
for f: ast::ty_field in fields {
let tm = ast_mt_to_mt(tcx, getter, f.node.mt);
- flds += ~[{ident: f.node.ident, mt: tm}];
+ flds += [{ident: f.node.ident, mt: tm}];
}
typ = ty::mk_rec(tcx, flds);
}
ast::ty_fn(proto, inputs, output, cf, constrs) {
- let i = ~[];
+ let i = [];
for ta: ast::ty_arg in inputs {
- i += ~[ast_arg_to_arg(tcx, getter, ta)];
+ i += [ast_arg_to_arg(tcx, getter, ta)];
}
let out_ty = ast_ty_to_ty(tcx, getter, output);
- let out_constrs = ~[];
+ let out_constrs = [];
for constr: @ast::constr in constrs {
- out_constrs += ~[ty::ast_constr_to_constr(tcx, constr)];
+ out_constrs += [ty::ast_constr_to_constr(tcx, constr)];
}
typ = ty::mk_fn(tcx, proto, i, out_ty, cf, out_constrs);
}
typ = instantiate(tcx, ast_ty.span, getter, id, path.node.types);
}
some(ast::def_native_ty(id)) { typ = getter(id).ty; }
- some(ast::def_ty_arg(id,k)) { typ = ty::mk_param(tcx, id, k); }
+ some(ast::def_ty_arg(id, k)) { typ = ty::mk_param(tcx, id, k); }
some(_) {
tcx.sess.span_fatal(ast_ty.span,
"found type name used as a variable");
cname = some(path_to_str(path));
}
ast::ty_obj(meths) {
- let tmeths: [ty::method] = ~[];
+ let tmeths: [ty::method] = [];
for m: ast::ty_method in meths {
- let ins = ~[];
+ let ins = [];
for ta: ast::ty_arg in m.node.inputs {
- ins += ~[ast_arg_to_arg(tcx, getter, ta)];
+ ins += [ast_arg_to_arg(tcx, getter, ta)];
}
let out = ast_ty_to_ty(tcx, getter, m.node.output);
- let out_constrs = ~[];
+ let out_constrs = [];
for constr: @ast::constr in m.node.constrs {
- out_constrs += ~[ty::ast_constr_to_constr(tcx, constr)];
+ out_constrs += [ty::ast_constr_to_constr(tcx, constr)];
}
let new_m: ty::method =
{proto: m.node.proto,
output: out,
cf: m.node.cf,
constrs: out_constrs};
- tmeths += ~[new_m];
+ tmeths += [new_m];
}
typ = ty::mk_obj(tcx, ty::sort_methods(tmeths));
}
ast::ty_constr(t, cs) {
- let out_cs = ~[];
+ let out_cs = [];
for constr: @ast::ty_constr in cs {
- out_cs += ~[ty::ast_constr_to_constr(tcx, constr)];
+ out_cs += [ty::ast_constr_to_constr(tcx, constr)];
}
typ = ty::mk_constr(tcx, ast_ty_to_ty(tcx, getter, t), out_cs);
}
ast::ty_infer. {
- tcx.sess.span_bug(ast_ty.span,
- "found ty_infer in unexpected place");
+ tcx.sess.span_bug(ast_ty.span, "found ty_infer in unexpected place");
}
}
alt cname {
}
// A wrapper around ast_ty_to_ty_crate that handles ty_infer.
-fn ast_ty_to_ty_crate_infer(ccx: @crate_ctxt, ast_ty: &@ast::ty)
- -> option::t<ty::t> {
+fn ast_ty_to_ty_crate_infer(ccx: @crate_ctxt, ast_ty: &@ast::ty) ->
+ option::t<ty::t> {
alt ast_ty.node {
ast::ty_infer. { none }
_ { some(ast_ty_to_ty_crate(ccx, ast_ty)) }
tpot: &ty_param_substs_opt_and_ty) {
inner(fcx.ccx.tcx.node_types, node_id, tpot);
if ty::type_contains_vars(fcx.ccx.tcx, tpot.ty) {
- fcx.fixups += ~[node_id];
+ fcx.fixups += [node_id];
}
}
type ctxt = {tcx: ty::ctxt};
fn mk_ty_params(cx: &@ctxt, atps: &[ast::ty_param]) -> [ty::t] {
- let tps = ~[];
+ let tps = [];
let i = 0u;
for atp: ast::ty_param in atps {
- tps += ~[ty::mk_param(cx.tcx, i, atp.kind)];
+ tps += [ty::mk_param(cx.tcx, i, atp.kind)];
i += 1u;
}
ret tps;
}
fn ty_param_kinds(tps: &[ast::ty_param]) -> [ast::kind] {
- let k: [ast::kind] = ~[];
- for p: ast::ty_param in tps {
- k += ~[p.kind]
- }
+ let k: [ast::kind] = [];
+ for p: ast::ty_param in tps { k += [p.kind] }
ret k;
}
- fn ty_of_fn_decl(cx: &@ctxt, convert: &fn(&@ast::ty) -> ty::t ,
- ty_of_arg: &fn(&ast::arg) -> arg , decl: &ast::fn_decl,
+ fn ty_of_fn_decl(cx: &@ctxt, convert: &fn(&@ast::ty) -> ty::t,
+ ty_of_arg: &fn(&ast::arg) -> arg, decl: &ast::fn_decl,
proto: ast::proto, ty_params: &[ast::ty_param],
def_id: &option::t<ast::def_id>) ->
ty::ty_param_kinds_and_ty {
- let input_tys = ~[];
- for a: ast::arg in decl.inputs { input_tys += ~[ty_of_arg(a)]; }
+ let input_tys = [];
+ for a: ast::arg in decl.inputs { input_tys += [ty_of_arg(a)]; }
let output_ty = convert(decl.output);
- let out_constrs = ~[];
+ let out_constrs = [];
for constr: @ast::constr in decl.constraints {
- out_constrs += ~[ty::ast_constr_to_constr(cx.tcx, constr)];
+ out_constrs += [ty::ast_constr_to_constr(cx.tcx, constr)];
}
let t_fn =
ty::mk_fn(cx.tcx, proto_to_ty_proto(proto), input_tys, output_ty,
alt def_id { some(did) { cx.tcx.tcache.insert(did, tpt); } _ { } }
ret tpt;
}
- fn ty_of_native_fn_decl(cx: &@ctxt, convert: &fn(&@ast::ty) -> ty::t ,
- ty_of_arg: &fn(&ast::arg) -> arg ,
+ fn ty_of_native_fn_decl(cx: &@ctxt, convert: &fn(&@ast::ty) -> ty::t,
+ ty_of_arg: &fn(&ast::arg) -> arg,
decl: &ast::fn_decl, abi: ast::native_abi,
ty_params: &[ast::ty_param], def_id: &ast::def_id)
-> ty::ty_param_kinds_and_ty {
- let input_tys = ~[];
- for a: ast::arg in decl.inputs { input_tys += ~[ty_of_arg(a)]; }
+ let input_tys = [];
+ for a: ast::arg in decl.inputs { input_tys += [ty_of_arg(a)]; }
let output_ty = convert(decl.output);
let t_fn = ty::mk_native_fn(cx.tcx, abi, input_tys, output_ty);
let get = bind getter(cx, _);
let convert = bind ast_ty_to_ty(cx.tcx, get, _);
- let inputs = ~[];
+ let inputs = [];
for a: ast::arg in m.node.meth.decl.inputs {
- inputs += ~[ty_of_arg(cx, a)];
+ inputs += [ty_of_arg(cx, a)];
}
let output = convert(m.node.meth.decl.output);
- let out_constrs = ~[];
+ let out_constrs = [];
for constr: @ast::constr in m.node.meth.decl.constraints {
- out_constrs += ~[ty::ast_constr_to_constr(cx.tcx, constr)];
+ out_constrs += [ty::ast_constr_to_constr(cx.tcx, constr)];
}
ret {proto: proto_to_ty_proto(m.node.meth.proto),
ident: m.node.ident,
ty::ty_param_kinds_and_ty {
let t_obj = ty_of_obj(cx, id, ob, ty_params);
- let t_inputs: [arg] = ~[];
+ let t_inputs: [arg] = [];
for f: ast::obj_field in ob.fields {
let g = bind getter(cx, _);
let t_field = ast_ty_to_ty(cx.tcx, g, f.ty);
- t_inputs += ~[{mode: ty::mo_alias(false), ty: t_field}];
+ t_inputs += [{mode: ty::mo_alias(false), ty: t_field}];
}
let t_fn =
ty::mk_fn(cx.tcx, ast::proto_fn, t_inputs, t_obj.ty, ast::return,
- ~[]);
+ []);
let tpt = {kinds: ty_param_kinds(ty_params), ty: t_fn};
cx.tcx.tcache.insert(local_def(ctor_id), tpt);
ret tpt;
fn ty_of_item(cx: &@ctxt, it: &@ast::item) -> ty::ty_param_kinds_and_ty {
let get = bind getter(cx, _);
let convert = bind ast_ty_to_ty(cx.tcx, get, _);
- let no_kinds: [ast::kind] = ~[];
+ let no_kinds: [ast::kind] = [];
alt it.node {
ast::item_const(t, _) {
let typ = convert(t);
ret tpt;
}
ast::item_res(f, _, tps, _) {
- let t_arg = ty_of_arg(cx, f.decl.inputs.(0));
+ let t_arg = ty_of_arg(cx, f.decl.inputs[0]);
let t_res =
{kinds: ty_param_kinds(tps),
ty:
}
fn ty_of_native_item(cx: &@ctxt, it: &@ast::native_item,
abi: ast::native_abi) -> ty::ty_param_kinds_and_ty {
- let no_kinds: [ast::kind] = ~[];
+ let no_kinds: [ast::kind] = [];
alt it.node {
ast::native_item_fn(_, fn_decl, params) {
let get = bind getter(cx, _);
// should be called to resolve named types.
let f = bind getter(cx, _);
- let args: [arg] = ~[];
+ let args: [arg] = [];
for va: ast::variant_arg in variant.node.args {
let arg_ty = ast_ty_to_ty(cx.tcx, f, va.ty);
- args += ~[{mode: ty::mo_alias(false), ty: arg_ty}];
+ args += [{mode: ty::mo_alias(false), ty: arg_ty}];
}
let tag_t = ty::mk_tag(cx.tcx, tag_id, ty_param_tys);
// FIXME: this will be different for constrained types
result_ty =
ty::mk_fn(cx.tcx, ast::proto_fn, args, tag_t, ast::return,
- ~[]);
+ []);
}
let tpt = {kinds: ty_param_kinds(ty_params), ty: result_ty};
cx.tcx.tcache.insert(local_def(variant.node.id), tpt);
}
}
fn get_obj_method_types(cx: &@ctxt, object: &ast::_obj) -> [ty::method] {
- let meths = ~[];
+ let meths = [];
for m: @ast::method in object.methods {
- meths += ~[ty_of_method(cx, m)];
+ meths += [ty_of_method(cx, m)];
}
ret meths;
}
// we write into the table for this item.
ty_of_item(cx, it);
- let tpt = ty_of_obj_ctor(cx, it.ident, object,
- ctor_id, ty_params);
+ let tpt =
+ ty_of_obj_ctor(cx, it.ident, object, ctor_id, ty_params);
write::ty_only(cx.tcx, ctor_id, tpt.ty);
// Write the methods into the type table.
//
let method_types = get_obj_method_types(cx, object);
let i = 0u;
while i < vec::len::<@ast::method>(object.methods) {
- write::ty_only(cx.tcx, object.methods.(i).node.id,
+ write::ty_only(cx.tcx, object.methods[i].node.id,
ty::method_ty_to_fn_ty(cx.tcx,
- method_types.(i)));
+ method_types[i]));
i += 1u;
}
// Write in the types of the object fields.
let args = ty::ty_fn_args(cx.tcx, tpt.ty);
i = 0u;
while i < vec::len::<ty::arg>(args) {
- let fld = object.fields.(i);
- write::ty_only(cx.tcx, fld.id, args.(i).ty);
+ let fld = object.fields[i];
+ write::ty_only(cx.tcx, fld.id, args[i].ty);
i += 1u;
}
}
ast::item_res(f, dtor_id, tps, ctor_id) {
- let t_arg = ty_of_arg(cx, f.decl.inputs.(0));
+ let t_arg = ty_of_arg(cx, f.decl.inputs[0]);
let t_res =
ty::mk_res(cx.tcx, local_def(it.id), t_arg.ty,
mk_ty_params(cx, tps));
let t_ctor =
- ty::mk_fn(cx.tcx, ast::proto_fn, ~[t_arg], t_res, ast::return,
- ~[]);
+ ty::mk_fn(cx.tcx, ast::proto_fn, [t_arg], t_res, ast::return,
+ []);
let t_dtor =
- ty::mk_fn(cx.tcx, ast::proto_fn, ~[t_arg], ty::mk_nil(cx.tcx),
- ast::return, ~[]);
+ ty::mk_fn(cx.tcx, ast::proto_fn, [t_arg], ty::mk_nil(cx.tcx),
+ ast::return, []);
write::ty_only(cx.tcx, it.id, t_res);
write::ty_only(cx.tcx, ctor_id, t_ctor);
cx.tcx.tcache.insert(local_def(ctor_id),
// contained within the native module.
let abi = @mutable none::<ast::native_abi>;
let cx = @{tcx: tcx};
- let visit = visit::mk_simple_visitor
- (@{visit_item: bind convert(cx, abi, _),
- visit_native_item: bind convert_native(cx, abi, _)
- with *visit::default_simple_visitor()});
+ let visit =
+ visit::mk_simple_visitor(@{visit_item: bind convert(cx, abi, _),
+ visit_native_item:
+ bind convert_native(cx, abi, _)
+ with
+ *visit::default_simple_visitor()});
visit::visit_crate(*crate, (), visit);
}
}
break;
}
}
- _ {}
+ _ { }
}
t1 = inner.ty;
}
}
ty::ty_tag(did, tps) {
let variants = ty::tag_variants(fcx.ccx.tcx, did);
- if vec::len(variants) != 1u || vec::len(variants.(0).args) != 1u
- {
+ if vec::len(variants) != 1u || vec::len(variants[0].args) != 1u {
ret t1;
}
t1 =
ty::substitute_type_params(fcx.ccx.tcx, tps,
- variants.(0).args.(0));
+ variants[0].args[0]);
}
_ { ret t1; }
}
fn do_fn_block_coerce(fcx: &@fn_ctxt, sp: &span, actual: &ty::t,
expected: &ty::t) -> ty::t {
+
// fns can be silently coerced to blocks when being used as
// function call or bind arguments, but not the reverse.
// If our actual type is a fn and our expected type is a block,
mod demand {
fn simple(fcx: &@fn_ctxt, sp: &span, expected: &ty::t, actual: &ty::t) ->
ty::t {
- full(fcx, sp, expected, actual, ~[], false).ty
+ full(fcx, sp, expected, actual, [], false).ty
}
- fn block_coerce(fcx: &@fn_ctxt, sp: &span,
- expected: &ty::t, actual: &ty::t) -> ty::t {
- full(fcx, sp, expected, actual, ~[], true).ty
+ fn block_coerce(fcx: &@fn_ctxt, sp: &span, expected: &ty::t,
+ actual: &ty::t) -> ty::t {
+ full(fcx, sp, expected, actual, [], true).ty
}
fn with_substs(fcx: &@fn_ctxt, sp: &span, expected: &ty::t,
actual: &ty::t, ty_param_substs_0: &[ty::t]) ->
- ty_param_substs_and_ty {
+ ty_param_substs_and_ty {
full(fcx, sp, expected, actual, ty_param_substs_0, false)
}
actual = do_fn_block_coerce(fcx, sp, actual, expected);
}
- let ty_param_substs: [mutable ty::t] = ~[mutable];
- let ty_param_subst_var_ids: [int] = ~[];
+ let ty_param_substs: [mutable ty::t] = [mutable];
+ let ty_param_subst_var_ids: [int] = [];
for ty_param_subst: ty::t in ty_param_substs_0 {
// Generate a type variable and unify it with the type parameter
// substitution. We will then pull out these type variables.
let t_0 = next_ty_var(fcx);
- ty_param_substs += ~[mutable t_0];
- ty_param_subst_var_ids += ~[ty::ty_var_id(fcx.ccx.tcx, t_0)];
+ ty_param_substs += [mutable t_0];
+ ty_param_subst_var_ids += [ty::ty_var_id(fcx.ccx.tcx, t_0)];
simple(fcx, sp, ty_param_subst, t_0);
}
fn mk_result(fcx: &@fn_ctxt, result_ty: &ty::t,
ty_param_subst_var_ids: &[int]) ->
ty_param_substs_and_ty {
- let result_ty_param_substs: [ty::t] = ~[];
+ let result_ty_param_substs: [ty::t] = [];
for var_id: int in ty_param_subst_var_ids {
let tp_subst = ty::mk_var(fcx.ccx.tcx, var_id);
- result_ty_param_substs += ~[tp_subst];
+ result_ty_param_substs += [tp_subst];
}
ret {substs: result_ty_param_substs, ty: result_ty};
}
alt unify::unify(fcx, expected, actual) {
- ures_ok(t) {
- ret mk_result(fcx, t, ty_param_subst_var_ids);
- }
+ ures_ok(t) { ret mk_result(fcx, t, ty_param_subst_var_ids); }
ures_err(err) {
let e_err = resolve_type_vars_if_possible(fcx, expected);
let a_err = resolve_type_vars_if_possible(fcx, actual);
// Returns the types of the arguments to a tag variant.
fn variant_arg_types(ccx: &@crate_ctxt, _sp: &span, vid: &ast::def_id,
tag_ty_params: &[ty::t]) -> [ty::t] {
- let result: [ty::t] = ~[];
+ let result: [ty::t] = [];
let tpt = ty::lookup_item_type(ccx.tcx, vid);
alt ty::struct(ccx.tcx, tpt.ty) {
ty::ty_fn(_, ins, _, _, _) {
for arg: ty::arg in ins {
let arg_ty =
ty::substitute_type_params(ccx.tcx, tag_ty_params, arg.ty);
- result += ~[arg_ty];
+ result += [arg_ty];
}
}
_ {
fn resolve_type_vars_in_type(fcx: &@fn_ctxt, sp: &span, typ: ty::t) ->
option::t<ty::t> {
if !ty::type_contains_vars(fcx.ccx.tcx, typ) { ret some(typ); }
- alt ty::unify::fixup_vars(fcx.ccx.tcx, some(sp),
- fcx.var_bindings, typ) {
+ alt ty::unify::fixup_vars(fcx.ccx.tcx, some(sp), fcx.var_bindings,
+ typ) {
fix_ok(new_type) { ret some(new_type); }
fix_err(vid) {
fcx.ccx.tcx.sess.span_err(sp,
alt tpot.substs {
none::<[ty::t]>. { new_substs_opt = none::<[ty::t]>; }
some::<[ty::t]>(substs) {
- let new_substs: [ty::t] = ~[];
+ let new_substs: [ty::t] = [];
for subst: ty::t in substs {
alt resolve_type_vars_in_type(fcx, sp, subst) {
- some(t) { new_substs += ~[t]; }
+ some(t) { new_substs += [t]; }
none. { wbcx.success = false; ret; }
}
}
fn resolve_type_vars_in_expr(fcx: &@fn_ctxt, e: &@ast::expr) -> bool {
let wbcx = {fcx: fcx, mutable success: true};
- let visit = visit::mk_vt
- (@{visit_item: visit_item,
- visit_stmt: visit_stmt,
- visit_expr: visit_expr,
- visit_block: visit_block,
- visit_pat: visit_pat,
- visit_local: visit_local
- with *visit::default_visitor()});
+ let visit =
+ visit::mk_vt(@{visit_item: visit_item,
+ visit_stmt: visit_stmt,
+ visit_expr: visit_expr,
+ visit_block: visit_block,
+ visit_pat: visit_pat,
+ visit_local: visit_local
+ with *visit::default_visitor()});
visit::visit_expr(e, wbcx, visit);
ret wbcx.success;
}
fn resolve_type_vars_in_block(fcx: &@fn_ctxt, blk: &ast::blk) -> bool {
let wbcx = {fcx: fcx, mutable success: true};
- let visit = visit::mk_vt
- (@{visit_item: visit_item,
- visit_stmt: visit_stmt,
- visit_expr: visit_expr,
- visit_block: visit_block,
- visit_pat: visit_pat,
- visit_local: visit_local
- with *visit::default_visitor()});
+ let visit =
+ visit::mk_vt(@{visit_item: visit_item,
+ visit_stmt: visit_stmt,
+ visit_expr: visit_expr,
+ visit_block: visit_block,
+ visit_pat: visit_pat,
+ visit_local: visit_local
+ with *visit::default_visitor()});
visit::visit_block(blk, wbcx, visit);
ret wbcx.success;
}
// Used only as a helper for check_fn.
fn gather_locals(ccx: &@crate_ctxt, f: &ast::_fn, id: &ast::node_id,
old_fcx: &option::t<@fn_ctxt>) -> gather_result {
- let {vb, locals, local_names, nvi} = alt old_fcx {
- none. {
- { vb: ty::unify::mk_var_bindings(),
- locals: new_int_hash::<int>(),
- local_names: new_int_hash::<ast::ident>(),
- nvi: @mutable 0 }
- }
- some(fcx) {
- { vb: fcx.var_bindings,
- locals: fcx.locals,
- local_names: fcx.local_names,
- nvi: fcx.next_var_id }
- }
- };
+ let {vb: vb, locals: locals, local_names: local_names, nvi: nvi} =
+ alt old_fcx {
+ none. {
+ {vb: ty::unify::mk_var_bindings(),
+ locals: new_int_hash::<int>(),
+ local_names: new_int_hash::<ast::ident>(),
+ nvi: @mutable 0}
+ }
+ some(fcx) {
+ {vb: fcx.var_bindings,
+ locals: fcx.locals,
+ local_names: fcx.local_names,
+ nvi: fcx.next_var_id}
+ }
+ };
let tcx = ccx.tcx;
- let next_var_id = lambda() -> int {
- let rv = *nvi;
- *nvi += 1;
- ret rv;
- };
- let assign = lambda(nid: ast::node_id, ident: &ast::ident,
- ty_opt: option::t<ty::t>) {
- let var_id = next_var_id();
- locals.insert(nid, var_id);
- local_names.insert(nid, ident);
- alt ty_opt {
- none. {/* nothing to do */ }
- some(typ) {
- ty::unify::unify(ty::mk_var(tcx, var_id), typ, vb, tcx);
- }
- }
- };
+ let next_var_id = lambda () -> int { let rv = *nvi; *nvi += 1; ret rv; };
+ let assign =
+ lambda (nid: ast::node_id, ident: &ast::ident,
+ ty_opt: option::t<ty::t>) {
+ let var_id = next_var_id();
+ locals.insert(nid, var_id);
+ local_names.insert(nid, ident);
+ alt ty_opt {
+ none. {/* nothing to do */ }
+ some(typ) {
+ ty::unify::unify(ty::mk_var(tcx, var_id), typ, vb, tcx);
+ }
+ }
+ };
// Add object fields, if any.
- let obj_fields = ~[];
+ let obj_fields = [];
alt get_obj_info(ccx) {
some(oinfo) {
alt oinfo {
let args = ty::ty_fn_args(ccx.tcx, ty::node_id_to_type(ccx.tcx, id));
let i = 0u;
for arg: ty::arg in args {
- assign(f.decl.inputs.(i).id, f.decl.inputs.(i).ident, some(arg.ty));
+ assign(f.decl.inputs[i].id, f.decl.inputs[i].ident, some(arg.ty));
i += 1u;
}
// Add explicitly-declared locals.
- let visit_local = lambda(local: &@ast::local, e: &(), v: &visit::vt<()>) {
- let local_ty = ast_ty_to_ty_crate_infer(ccx, local.node.ty);
- assign(local.node.id, ident_for_local(local), local_ty);
- visit::visit_local(local, e, v);
- };
+ let visit_local =
+ lambda (local: &@ast::local, e: &(), v: &visit::vt<()>) {
+ let local_ty = ast_ty_to_ty_crate_infer(ccx, local.node.ty);
+ assign(local.node.id, ident_for_local(local), local_ty);
+ visit::visit_local(local, e, v);
+ };
// Add pattern bindings.
- let visit_pat = lambda(p: &@ast::pat, e: &(), v: &visit::vt<()>) {
- alt p.node {
- ast::pat_bind(ident) {
- assign(p.id, ident, none);
- }
- _ {/* no-op */ }
- }
- visit::visit_pat(p, e, v);
- };
+ let visit_pat =
+ lambda (p: &@ast::pat, e: &(), v: &visit::vt<()>) {
+ alt p.node {
+ ast::pat_bind(ident) { assign(p.id, ident, none); }
+ _ {/* no-op */ }
+ }
+ visit::visit_pat(p, e, v);
+ };
// Don't descend into fns and items
fn visit_fn<E>(_f: &ast::_fn, _tp: &[ast::ty_param], _sp: &span,
_i: &ast::fn_ident, _id: ast::node_id, _e: &E,
- _v: &visit::vt<E>) { }
+ _v: &visit::vt<E>) {
+ }
fn visit_item<E>(_i: &@ast::item, _e: &E, _v: &visit::vt<E>) { }
let visit =
// TODO (issue #448): Wrap a #fmt string over multiple
// lines...
let s =
- #fmt("this pattern has %u field%s, but the \
+ #fmt["this pattern has %u field%s, but the \
corresponding variant has %u field%s",
subpats_len,
if subpats_len == 1u { "" } else { "s" },
- arg_len, if arg_len == 1u { "" } else { "s" });
+ arg_len, if arg_len == 1u { "" } else { "s" }];
fcx.ccx.tcx.sess.span_fatal(pat.span, s);
}
let i = 0u;
for subpat: @ast::pat in subpats {
- check_pat(fcx, map, subpat, arg_types.(i));
+ check_pat(fcx, map, subpat, arg_types[i]);
i += 1u;
}
- } else if (subpats_len > 0u) {
+ } else if subpats_len > 0u {
// TODO: note definition of tag variant
- fcx.ccx.tcx.sess.span_fatal
- (pat.span, #fmt("this pattern has %u field%s, \
- but the corresponding \
- variant has no fields",
- subpats_len,
- if subpats_len == 1u { "" }
- else { "s" }));
+ fcx.ccx.tcx.sess.span_fatal(
+ pat.span,
+ #fmt["this pattern has %u field%s, \
+ but the corresponding \
+ variant has no fields",
+ subpats_len,
+ if subpats_len == 1u {
+ ""
+ } else { "s" }]);
}
write::ty_fixup(fcx, pat.id, path_tpot);
}
// FIXME: Switch expected and actual in this message? I
// can never tell.
fcx.ccx.tcx.sess.span_fatal(pat.span,
- #fmt("mismatched types: \
+ #fmt["mismatched types: \
expected %s, found tag",
ty_to_str(fcx.ccx.tcx,
- expected)));
+ expected)]);
}
}
write::ty_fixup(fcx, pat.id, path_tpot);
ty::ty_rec(fields) { ex_fields = fields; }
_ {
fcx.ccx.tcx.sess.span_fatal(pat.span,
- #fmt("mismatched types: expected %s, \
+ #fmt["mismatched types: expected %s, \
found record",
ty_to_str(fcx.ccx.tcx,
- expected)));
+ expected)]);
}
}
let f_count = vec::len(fields);
let ex_f_count = vec::len(ex_fields);
if ex_f_count < f_count || !etc && ex_f_count > f_count {
- fcx.ccx.tcx.sess.span_fatal
- (pat.span, #fmt("mismatched types: expected a record \
- with %u fields, found one with %u \
- fields", ex_f_count, f_count));
+ fcx.ccx.tcx.sess.span_fatal(
+ pat.span,
+ #fmt["mismatched types: expected a record \
+ with %u fields, found one with %u \
+ fields",
+ ex_f_count, f_count]);
}
fn matches(name: &str, f: &ty::field) -> bool {
ret str::eq(name, f.ident);
some(field) { check_pat(fcx, map, f.pat, field.mt.ty); }
none. {
fcx.ccx.tcx.sess.span_fatal(pat.span,
- #fmt("mismatched types: did not \
+ #fmt["mismatched types: did not \
expect a record with a field %s",
- f.ident));
+ f.ident]);
}
}
}
ty::ty_tup(elts) { ex_elts = elts; }
_ {
fcx.ccx.tcx.sess.span_fatal(pat.span,
- #fmt("mismatched types: expected %s, \
- found tuple", ty_to_str(fcx.ccx.tcx,
- expected)));
+ #fmt["mismatched types: expected %s, \
+ found tuple",
+ ty_to_str(fcx.ccx.tcx,
+ expected)]);
}
}
let e_count = vec::len(elts);
if e_count != vec::len(ex_elts) {
- fcx.ccx.tcx.sess.span_fatal
- (pat.span, #fmt("mismatched types: expected a tuple \
- with %u fields, found one with %u \
- fields", vec::len(ex_elts), e_count));
+ fcx.ccx.tcx.sess.span_fatal(
+ pat.span,
+ #fmt["mismatched types: expected a tuple \
+ with %u fields, found one with %u \
+ fields",
+ vec::len(ex_elts), e_count]);
}
let i = 0u;
- for elt in elts {
- check_pat(fcx, map, elt, ex_elts.(i));
- i += 1u;
- }
+ for elt in elts { check_pat(fcx, map, elt, ex_elts[i]); i += 1u; }
write::ty_only_fixup(fcx, pat.id, expected);
}
ast::pat_box(inner) {
alt ccx.tcx.def_map.find(callee.id) {
some(ast::def_fn(_, ast::pure_fn.)) { ret; }
_ {
- ccx.tcx.sess.span_fatal
- (sp, "Pure function calls function not known to be pure");
+ ccx.tcx.sess.span_fatal(
+ sp,
+ "Pure function calls function not known to be pure");
}
}
}
}
}
-type unifier = fn(fcx: &@fn_ctxt, sp: &span,
- expected: &ty::t, actual: &ty::t) -> ty::t;
+type unifier = fn(&@fn_ctxt, &span, &ty::t, &ty::t) -> ty::t;
fn check_expr(fcx: &@fn_ctxt, expr: &@ast::expr) -> bool {
- fn dummy_unify(_fcx: &@fn_ctxt, _sp: &span,
- _expected: &ty::t, actual: &ty::t) -> ty::t {
+ fn dummy_unify(_fcx: &@fn_ctxt, _sp: &span, _expected: &ty::t,
+ actual: &ty::t) -> ty::t {
actual
}
ret check_expr_with_unifier(fcx, expr, dummy_unify, 0u);
}
-fn check_expr_with(fcx: &@fn_ctxt, expr: &@ast::expr, expected: &ty::t)
- -> bool {
+fn check_expr_with(fcx: &@fn_ctxt, expr: &@ast::expr, expected: &ty::t) ->
+ bool {
ret check_expr_with_unifier(fcx, expr, demand::simple, expected);
}
-fn check_expr_with_unifier(fcx: &@fn_ctxt, expr: &@ast::expr,
- unify: &unifier, expected: &ty::t) -> bool {
+fn check_expr_with_unifier(fcx: &@fn_ctxt, expr: &@ast::expr, unify: &unifier,
+ expected: &ty::t) -> bool {
//log_err "typechecking expr " + syntax::print::pprust::expr_to_str(expr);
// A generic function to factor out common logic from call and bind
ty::ty_fn(ast::proto_iter., _, _, _, _) {
if call_kind != kind_for_each {
fcx.ccx.tcx.sess.span_err(
- sp, "calling iter outside of for each loop");
+ sp,
+ "calling iter outside of for each loop");
}
}
_ {
- if call_kind == kind_for_each {
+ if call_kind == kind_for_each {
fcx.ccx.tcx.sess.span_err(
- sp, "calling non-iter as sequence of for each loop");
+ sp,
+ "calling non-iter as sequence of for each loop");
}
}
}
// Grab the argument types
- let arg_tys = alt sty {
- ty::ty_fn(_, arg_tys, _, _, _) |
- ty::ty_native_fn(_, arg_tys, _) { arg_tys }
- _ {
- fcx.ccx.tcx.sess.span_fatal(f.span,
- "mismatched types: \
+ let arg_tys =
+ alt sty {
+ ty::ty_fn(_, arg_tys, _, _, _) | ty::ty_native_fn(_, arg_tys, _)
+ {
+ arg_tys
+ }
+ _ {
+ fcx.ccx.tcx.sess.span_fatal(f.span,
+ "mismatched types: \
expected function or native \
function but found "
- + ty_to_str(fcx.ccx.tcx, fty))
- }
- };
+ + ty_to_str(fcx.ccx.tcx, fty))
+ }
+ };
// Check that the correct number of arguments were supplied.
let expected_arg_count = vec::len(arg_tys);
let supplied_arg_count = vec::len(args);
if expected_arg_count != supplied_arg_count {
- fcx.ccx.tcx.sess.span_err(
- sp,
- #fmt("this function takes %u \
+ fcx.ccx.tcx.sess.span_err(sp,
+ #fmt["this function takes %u \
parameter%s but %u parameter%s supplied",
- expected_arg_count,
- if expected_arg_count == 1u { "" } else { "s" },
- supplied_arg_count,
- if supplied_arg_count == 1u
- { " was" } else { "s were" }));
+ expected_arg_count,
+ if expected_arg_count == 1u {
+ ""
+ } else { "s" }, supplied_arg_count,
+ if supplied_arg_count == 1u {
+ " was"
+ } else { "s were" }]);
// HACK: extend the arguments list with dummy arguments to
// check against
let dummy = {mode: ty::mo_val, ty: ty::mk_nil(fcx.ccx.tcx)};
while vec::len(arg_tys) < supplied_arg_count {
- arg_tys += ~[dummy];
+ arg_tys += [dummy];
}
}
// functions. This is so that we have more information about the types
// of arguments when we typecheck the functions. This isn't really the
// right way to do this.
- let check_args = lambda(check_blocks: bool) -> bool {
- let i = 0u;
- let bot = false;
- for a_opt: option::t<@ast::expr> in args {
- alt a_opt {
- some(a) {
- let is_block =
- alt a.node { ast::expr_fn(_) { true } _ { false } };
- if is_block == check_blocks {
- bot |= check_expr_with_unifier(fcx, a,
- demand::block_coerce,
- arg_tys.(i).ty);
+ let check_args =
+ lambda (check_blocks: bool) -> bool {
+ let i = 0u;
+ let bot = false;
+ for a_opt: option::t<@ast::expr> in args {
+ alt a_opt {
+ some(a) {
+ let is_block =
+ alt a.node {
+ ast::expr_fn(_) { true }
+ _ { false }
+ };
+ if is_block == check_blocks {
+ bot |=
+ check_expr_with_unifier(fcx, a,
+ demand::block_coerce,
+ arg_tys[i].ty);
+ }
+ }
+ none. { }
}
- }
- none. {}
+ i += 1u;
}
- i += 1u;
- }
- ret bot;
- };
+ ret bot;
+ };
bot |= check_args(false);
bot |= check_args(true);
// A generic function for checking call expressions
fn check_call(fcx: &@fn_ctxt, sp: &span, f: &@ast::expr,
args: &[@ast::expr], call_kind: call_kind) -> bool {
- let args_opt_0: [option::t<@ast::expr>] = ~[];
+ let args_opt_0: [option::t<@ast::expr>] = [];
for arg: @ast::expr in args {
- args_opt_0 += ~[some::<@ast::expr>(arg)];
+ args_opt_0 += [some::<@ast::expr>(arg)];
}
// Call the generic checker.
element_ty: ty::t, body: &ast::blk,
node_id: ast::node_id) -> bool {
let locid = lookup_local(fcx, local.span, local.node.id);
- element_ty = demand::simple(fcx, local.span, element_ty,
- ty::mk_var(fcx.ccx.tcx, locid));
+ element_ty =
+ demand::simple(fcx, local.span, element_ty,
+ ty::mk_var(fcx.ccx.tcx, locid));
let bot = check_decl_local(fcx, local);
check_block(fcx, body);
// Unify type of decl with element type of the seq
bot = check_expr(fcx, oper);
let oper_t = expr_ty(tcx, oper);
alt unop {
- ast::box(mut) {
- oper_t = ty::mk_box(tcx, {ty: oper_t, mut: mut});
- }
+ ast::box(mut) { oper_t = ty::mk_box(tcx, {ty: oper_t, mut: mut}); }
ast::deref. {
alt structure_of(fcx, expr.span, oper_t) {
ty::ty_box(inner) { oper_t = inner.ty; }
ty::ty_tag(id, tps) {
let variants = ty::tag_variants(tcx, id);
if vec::len(variants) != 1u ||
- vec::len(variants.(0).args) != 1u {
- tcx.sess.span_fatal
- (expr.span, "can only dereference tags " +
- "with a single variant which has a "
- + "single argument");
+ vec::len(variants[0].args) != 1u {
+ tcx.sess.span_fatal(
+ expr.span,
+ "can only dereference tags " +
+ "with a single variant which has a "
+ + "single argument");
}
oper_t =
- ty::substitute_type_params(tcx, tps,
- variants.(0).args.(0));
+ ty::substitute_type_params(tcx, tps, variants[0].args[0]);
}
ty::ty_ptr(inner) { oper_t = inner.ty; }
_ {
tcx.sess.span_fatal(expr.span,
"dereferencing non-" +
- "dereferenceable type: " +
- ty_to_str(tcx, oper_t));
+ "dereferenceable type: " +
+ ty_to_str(tcx, oper_t));
}
}
}
if !type_is_integral(fcx, oper.span, oper_t) &&
structure_of(fcx, oper.span, oper_t) != ty::ty_bool {
tcx.sess.span_err(expr.span,
- #fmt("mismatched types: expected bool \
+ #fmt["mismatched types: expected bool \
or integer but found %s",
- ty_to_str(tcx, oper_t)));
+ ty_to_str(tcx, oper_t)]);
}
}
ast::neg. {
oper_t = structurally_resolved_type(fcx, oper.span, oper_t);
if !(ty::type_is_integral(tcx, oper_t) ||
- ty::type_is_fp(tcx, oper_t)) {
- tcx.sess.span_err(expr.span, "applying unary minus to \
- non-numeric type " + ty_to_str(tcx, oper_t));
+ ty::type_is_fp(tcx, oper_t)) {
+ tcx.sess.span_err(expr.span,
+ "applying unary minus to \
+ non-numeric type "
+ + ty_to_str(tcx, oper_t));
}
}
}
bot = true;
alt expr_opt {
none. {/* do nothing */ }
- some(e) {
- check_expr_with(fcx, e, ty::mk_str(tcx));
- }
+ some(e) { check_expr_with(fcx, e, ty::mk_str(tcx)); }
}
write::bot_ty(tcx, id);
}
"ret; in function returning non-nil");
}
}
- some(e) {
- check_expr_with(fcx, e, fcx.ret_ty);
- }
+ some(e) { check_expr_with(fcx, e, fcx.ret_ty); }
}
write::bot_ty(tcx, id);
}
ast::expr_put(expr_opt) {
require_impure(tcx.sess, fcx.purity, expr.span);
- if (fcx.proto != ast::proto_iter) {
+ if fcx.proto != ast::proto_iter {
tcx.sess.span_err(expr.span, "put in non-iterator");
}
alt expr_opt {
"put; in iterator yielding non-nil");
}
}
- some(e) {
- bot = check_expr_with(fcx, e, fcx.ret_ty);
- }
+ some(e) { bot = check_expr_with(fcx, e, fcx.ret_ty); }
}
write::nil_ty(tcx, id);
}
write::nil_ty(tcx, id);
}
ast::expr_if_check(cond, thn, elsopt) {
- bot = check_pred_expr(fcx, cond) |
- check_then_else(fcx, thn, elsopt, id, expr.span);
+ bot =
+ check_pred_expr(fcx, cond) |
+ check_then_else(fcx, thn, elsopt, id, expr.span);
}
ast::expr_ternary(_, _, _) {
bot = check_expr(fcx, ast::ternary_to_if(expr));
}
ast::expr_copy(a) {
bot = check_expr_with_unifier(fcx, a, unify, expected);
- let tpot = ty::node_id_to_ty_param_substs_opt_and_ty(fcx.ccx.tcx,
- a.id);
+ let tpot =
+ ty::node_id_to_ty_param_substs_opt_and_ty(fcx.ccx.tcx, a.id);
write::ty_fixup(fcx, id, tpot);
}
ast::expr_assign_op(op, lhs, rhs) {
require_impure(tcx.sess, fcx.purity, expr.span);
bot = check_assignment(fcx, expr.span, lhs, rhs, id);
- check_binop_type_compat(fcx, expr.span, expr_ty(tcx, lhs),
- op);
+ check_binop_type_compat(fcx, expr.span, expr_ty(tcx, lhs), op);
}
ast::expr_if(cond, thn, elsopt) {
- bot = check_expr_with(fcx, cond, ty::mk_bool(tcx)) |
- check_then_else(fcx, thn, elsopt, id, expr.span);
+ bot =
+ check_expr_with(fcx, cond, ty::mk_bool(tcx)) |
+ check_then_else(fcx, thn, elsopt, id, expr.span);
}
ast::expr_for(decl, seq, body) {
bot = check_expr(fcx, seq);
ty::ty_vec(vec_elt_ty) { elt_ty = vec_elt_ty.ty; }
ty::ty_istr. { elt_ty = ty::mk_mach(tcx, ast::ty_u8); }
_ {
- tcx.sess.span_fatal
- (expr.span, "mismatched types: expected vector or string but "
- + "found " + ty_to_str(tcx, ety));
+ tcx.sess.span_fatal(
+ expr.span,
+ "mismatched types: expected vector or string but "
+ + "found " + ty_to_str(tcx, ety));
}
}
bot |= check_for_or_for_each(fcx, decl, elt_ty, body, id);
}
ast::expr_for_each(decl, seq, body) {
- alt (seq.node) {
+ alt seq.node {
ast::expr_call(f, args) {
- bot = check_call_full(fcx, seq.span, f, args,
- kind_for_each, seq.id);
+ bot =
+ check_call_full(fcx, seq.span, f, args, kind_for_each,
+ seq.id);
+ }
+ _ {
+ tcx.sess.span_fatal(expr.span,
+ "sequence in for each loop not a call");
}
- _ { tcx.sess.span_fatal(
- expr.span, "sequence in for each loop not a call"); }
}
- bot |= check_for_or_for_each(fcx, decl, expr_ty(tcx, seq),
- body, id);
+ bot |= check_for_or_for_each(fcx, decl, expr_ty(tcx, seq), body, id);
}
ast::expr_while(cond, body) {
bot = check_expr_with(fcx, cond, ty::mk_bool(tcx));
// bindings.
let pattern_ty = ty::expr_ty(tcx, expr);
for arm: ast::arm in arms {
- let id_map = ast::pat_id_map(arm.pats.(0));
+ let id_map = ast::pat_id_map(arm.pats[0]);
for p: @ast::pat in arm.pats {
check_pat(fcx, id_map, p, pattern_ty);
}
ast::expr_fn(f) {
let cx = @{tcx: tcx};
let convert = bind ast_ty_to_ty_crate_tyvar(fcx, _);
- let ty_of_arg = lambda(a: &ast::arg) -> ty::arg {
- let ty_mode = ast_mode_to_mode(a.mode);
- let tt = ast_ty_to_ty_crate_tyvar(fcx, a.ty);
- ret {mode: ty_mode, ty: tt};
- };
+ let ty_of_arg =
+ lambda (a: &ast::arg) -> ty::arg {
+ let ty_mode = ast_mode_to_mode(a.mode);
+ let tt = ast_ty_to_ty_crate_tyvar(fcx, a.ty);
+ ret {mode: ty_mode, ty: tt};
+ };
let fty =
collect::ty_of_fn_decl(cx, convert, ty_of_arg, f.decl, f.proto,
- ~[], none).ty;
+ [], none).ty;
write::ty_only_fixup(fcx, id, fty);
// Unify the type of the function with the expected type before we
}
ast::expr_block(b) {
bot = check_block(fcx, b);
- let typ = alt b.node.expr {
- some(expr) { expr_ty(tcx, expr) }
- none. { ty::mk_nil(tcx) }
- };
+ let typ =
+ alt b.node.expr {
+ some(expr) { expr_ty(tcx, expr) }
+ none. { ty::mk_nil(tcx) }
+ };
write::ty_only_fixup(fcx, id, typ);
}
ast::expr_bind(f, args) {
// Pull the argument and return types out.
let proto_1;
- let arg_tys_1: [ty::arg] = ~[];
+ let arg_tys_1: [ty::arg] = [];
let rt_1;
let fty = expr_ty(tcx, f);
let t_1;
// to the resulting function type.
let i = 0u;
while i < vec::len::<option::t<@ast::expr>>(args) {
- alt args.(i) {
+ alt args[i] {
some(_) {/* no-op */ }
- none. { arg_tys_1 += ~[arg_tys.(i)]; }
+ none. { arg_tys_1 += [arg_tys[i]]; }
}
i += 1u;
}
t_1 = ty::mk_fn(tcx, proto_1, arg_tys_1, rt_1, cf, constrs);
}
- _ {
- fail "LHS of bind expr didn't have a function type?!";
- }
+ _ { fail "LHS of bind expr didn't have a function type?!"; }
}
write::ty_only_fixup(fcx, id, t_1);
}
alt oinfo {
regular_obj(_, obj_id) {
let did = local_def(obj_id);
+
// Try looking up the current object in the type
// cache.
alt tcx.tcache.find(did) {
}
none. {
tcx.sess.bug("didn't find " + int::str(did.node) +
- " in type cache");
+ " in type cache");
}
}
}
type_is_scalar(fcx, expr.span, t_1)) {
tcx.sess.span_err(expr.span,
"non-scalar cast: " +
- ty_to_str(tcx, expr_ty(tcx, e))
- + " as " + ty_to_str(tcx, t_1));
+ ty_to_str(tcx, expr_ty(tcx, e)) + " as " +
+ ty_to_str(tcx, t_1));
}
write::ty_only_fixup(fcx, id, t_1);
}
ast::expr_vec(args, mut) {
let t: ty::t = next_ty_var(fcx);
- for e: @ast::expr in args {
- bot |= check_expr_with(fcx, e, t);
- }
+ for e: @ast::expr in args { bot |= check_expr_with(fcx, e, t); }
let typ = ty::mk_vec(tcx, {ty: t, mut: mut});
write::ty_only_fixup(fcx, id, typ);
}
ast::expr_tup(elts) {
- let elt_ts = ~[];
+ let elt_ts = [];
vec::reserve(elt_ts, vec::len(elts));
for e in elts {
check_expr(fcx, e);
let ety = expr_ty(fcx.ccx.tcx, e);
- elt_ts += ~[ety];
+ elt_ts += [ety];
}
let typ = ty::mk_tup(fcx.ccx.tcx, elt_ts);
write::ty_only_fixup(fcx, id, typ);
}
ast::expr_rec(fields, base) {
alt base { none. {/* no-op */ } some(b_0) { check_expr(fcx, b_0); } }
- let fields_t: [spanned<field>] = ~[];
+ let fields_t: [spanned<field>] = [];
for f: ast::field in fields {
bot |= check_expr(fcx, f.node.expr);
let expr_t = expr_ty(tcx, f.node.expr);
// for the most precise error message,
// should be f.node.expr.span, not f.span
fields_t +=
- ~[respan(f.node.expr.span,
- {ident: f.node.ident, mt: expr_mt})];
+ [respan(f.node.expr.span,
+ {ident: f.node.ident, mt: expr_mt})];
}
alt base {
none. {
some(bexpr) {
bot |= check_expr(fcx, bexpr);
let bexpr_t = expr_ty(tcx, bexpr);
- let base_fields: [field] = ~[];
+ let base_fields: [field] = [];
alt structure_of(fcx, expr.span, bexpr_t) {
ty::ty_rec(flds) { base_fields = flds; }
_ {
}
if !found {
tcx.sess.span_fatal(f.span,
- "unknown field in record update: "
- + f.node.ident);
+ "unknown field in record update: " +
+ f.node.ident);
}
}
}
base_t = do_autoderef(fcx, expr.span, base_t);
alt structure_of(fcx, expr.span, base_t) {
ty::ty_rec(fields) {
- let ix: uint =
- ty::field_idx(tcx.sess, expr.span, field, fields);
+ let ix: uint = ty::field_idx(tcx.sess, expr.span, field, fields);
if ix >= vec::len::<ty::field>(fields) {
tcx.sess.span_fatal(expr.span, "bad index on record");
}
- write::ty_only_fixup(fcx, id, fields.(ix).mt.ty);
+ write::ty_only_fixup(fcx, id, fields[ix].mt.ty);
}
ty::ty_obj(methods) {
let ix: uint =
if ix >= vec::len::<ty::method>(methods) {
tcx.sess.span_fatal(expr.span, "bad index on obj");
}
- let meth = methods.(ix);
+ let meth = methods[ix];
let t =
- ty::mk_fn(tcx, meth.proto, meth.inputs, meth.output,
- meth.cf, meth.constrs);
+ ty::mk_fn(tcx, meth.proto, meth.inputs, meth.output, meth.cf,
+ meth.constrs);
write::ty_only_fixup(fcx, id, t);
}
_ {
let t_err = resolve_type_vars_if_possible(fcx, base_t);
let msg =
- #fmt("attempted field access on type %s",
- ty_to_str(tcx, t_err));
+ #fmt["attempted field access on type %s",
+ ty_to_str(tcx, t_err)];
tcx.sess.span_fatal(expr.span, msg);
}
}
tcx.sess.span_err(idx.span,
"mismatched types: expected \
integer but found "
- + ty_to_str(tcx, idx_t));
+ + ty_to_str(tcx, idx_t));
}
alt structure_of(fcx, expr.span, base_t) {
ty::ty_vec(mt) { write::ty_only_fixup(fcx, id, mt.ty); }
_ {
tcx.sess.span_fatal(expr.span,
"vector-indexing bad type: " +
- ty_to_str(tcx, base_t));
+ ty_to_str(tcx, base_t));
}
}
}
ast::expr_anon_obj(ao) {
- let fields: [ast::anon_obj_field] = ~[];
+ let fields: [ast::anon_obj_field] = [];
alt ao.fields { none. { } some(v) { fields = v; } }
// FIXME: These next three functions are largely ripped off from
fn ty_of_method(ccx: @crate_ctxt, m: &@ast::method) -> ty::method {
let convert = bind ast_ty_to_ty_crate(ccx, _);
- let inputs = ~[];
+ let inputs = [];
for aa: ast::arg in m.node.meth.decl.inputs {
- inputs += ~[ty_of_arg(ccx, aa)];
+ inputs += [ty_of_arg(ccx, aa)];
}
let output = convert(m.node.meth.decl.output);
- let out_constrs = ~[];
+ let out_constrs = [];
for constr: @ast::constr in m.node.meth.decl.constraints {
- out_constrs += ~[ty::ast_constr_to_constr(ccx.tcx, constr)];
+ out_constrs += [ty::ast_constr_to_constr(ccx.tcx, constr)];
}
ret {proto: m.node.meth.proto,
constrs: out_constrs};
}
- let method_types: [ty::method] = ~[];
+ let method_types: [ty::method] = [];
{
// Outer methods.
for m: @ast::method in ao.methods {
- method_types += ~[ty_of_method(fcx.ccx, m)];
+ method_types += [ty_of_method(fcx.ccx, m)];
}
// Inner methods.
// Typecheck 'inner_obj'. If it exists, it had better have object
// type.
- let inner_obj_methods: [ty::method] = ~[];
+ let inner_obj_methods: [ty::method] = [];
let inner_obj_ty: ty::t = ty::mk_nil(tcx);
let inner_obj_sty: option::t<ty::sty> = none;
alt ao.inner_obj {
ty::ty_obj(ms) { inner_obj_methods = ms; }
_ {
// The user is trying to extend a non-object.
- tcx.sess.span_fatal
- (e.span, syntax::print::pprust::expr_to_str(e) +
- " does not have object type");
+ tcx.sess.span_fatal(
+ e.span,
+ syntax::print::pprust::expr_to_str(e)
+ +
+ " does not have object type");
}
}
}
}
fcx.ccx.obj_infos +=
- ~[anon_obj(vec::map(ast::obj_field_from_anon_obj_field,
- fields), inner_obj_sty)];
+ [anon_obj(vec::map(ast::obj_field_from_anon_obj_field,
+ fields), inner_obj_sty)];
// Whenever an outer method overrides an inner, we need to remove
// that inner from the type. Filter inner_obj_methods to remove
// any methods that share a name with an outer method.
- fn filtering_fn(ccx: @crate_ctxt,
- m: &ty::method,
+ fn filtering_fn(ccx: @crate_ctxt, m: &ty::method,
outer_obj_methods: [@ast::method]) ->
- option::t<ty::method> {
+ option::t<ty::method> {
for om: @ast::method in outer_obj_methods {
if str::eq(om.node.ident, m.ident) {
if new_type != m {
ccx.tcx.sess.span_fatal(
om.span,
- "Attempted to override method " +
- m.ident + " with one of a different type");
+ "Attempted to override method "
+ + m.ident +
+ " with one of a different type");
}
ret none;
}
// collect::convert for regular objects.)
let i = 0u;
while i < vec::len::<@ast::method>(ao.methods) {
- write::ty_only(tcx, ao.methods.(i).node.id,
- ty::method_ty_to_fn_ty(tcx,
- method_types.(i)));
+ write::ty_only(tcx, ao.methods[i].node.id,
+ ty::method_ty_to_fn_ty(tcx, method_types[i]));
i += 1u;
}
}
_ { tcx.sess.unimpl("expr type in typeck::check_expr"); }
}
- if bot {
- write::ty_only_fixup(fcx, expr.id, ty::mk_bot(tcx));
- }
+ if bot { write::ty_only_fixup(fcx, expr.id, ty::mk_bot(tcx)); }
unify(fcx, expr.span, expected, expr_ty(tcx, expr));
ret bot;
alt fcx.locals.find(local.node.id) {
none. {
fcx.ccx.tcx.sess.bug("check_decl_local: local id not found " +
- ident_for_local(local));
+ ident_for_local(local));
}
some(i) {
let t = ty::mk_var(fcx.ccx.tcx, i);
let warned = false;
for s: @ast::stmt in blk.node.stmts {
if bot && !warned &&
- alt s.node {
- ast::stmt_decl(@{node: ast::decl_local(_), _}, _) |
- ast::stmt_expr(_, _) { true }
- _ { false }
- } {
+ alt s.node {
+ ast::stmt_decl(@{node: ast::decl_local(_), _}, _) |
+ ast::stmt_expr(_, _) {
+ true
+ }
+ _ { false }
+ } {
fcx.ccx.tcx.sess.span_warn(s.span, "unreachable statement");
warned = true;
}
// FIXME: this is kinda a kludge; we manufacture a fake function context
// and statement context for checking the initializer expression.
let rty = node_id_to_type(ccx.tcx, id);
- let fixups: [ast::node_id] = ~[];
+ let fixups: [ast::node_id] = [];
let fcx: @fn_ctxt =
@{ret_ty: rty,
purity: ast::pure_fn,
let decl = f.decl;
let body = f.body;
let gather_result = gather_locals(ccx, f, id, old_fcx);
- let fixups: [ast::node_id] = ~[];
+ let fixups: [ast::node_id] = [];
let fcx: @fn_ctxt =
@{ret_ty: ty::ty_fn_ret(ccx.tcx, ty::node_id_to_type(ccx.tcx, id)),
purity: decl.purity,
check_block(fcx, body);
alt decl.purity {
ast::pure_fn. {
+
// This just checks that the declared type is bool, and trusts
// that that's the actual return type.
if !ty::type_is_bool(ccx.tcx, fcx.ret_ty) {
_ { }
}
-// For non-iterator fns, we unify the tail expr's type with the
-// function result type, if there is a tail expr.
-// We don't do this check for an iterator, as the tail expr doesn't
-// have to have the result type of the iterator.
+ // For non-iterator fns, we unify the tail expr's type with the
+ // function result type, if there is a tail expr.
+ // We don't do this check for an iterator, as the tail expr doesn't
+ // have to have the result type of the iterator.
if option::is_some(body.node.expr) && f.proto != ast::proto_iter {
let tail_expr = option::get(body.node.expr);
// The use of resolve_type_vars_if_possible makes me very
// afraid :-(
- let tail_expr_ty = resolve_type_vars_if_possible(
- fcx, expr_ty(ccx.tcx, tail_expr));
+ let tail_expr_ty =
+ resolve_type_vars_if_possible(fcx, expr_ty(ccx.tcx, tail_expr));
+
// Hacky compromise: use eq and not are_compatible
// This allows things like while loops and ifs with no
// else to appear in tail position without a trailing
// force any remaining type vars to be resolved.
// If we have an enclosing function scope, our type variables will be
// resolved when the enclosing scope finishes up.
- if (option::is_none(old_fcx)) {
+ if option::is_none(old_fcx) {
writeback::resolve_type_vars_in_block(fcx, body);
}
}
ast::item_res(f, dtor_id, _, _) { check_fn(ccx, f, dtor_id, none); }
ast::item_obj(ob, _, _) {
// We're entering an object, so gather up the info we need.
- ccx.obj_infos += ~[regular_obj(ob.fields, it.id)];
+ ccx.obj_infos += [regular_obj(ob.fields, it.id)];
// Typecheck the methods.
for method: @ast::method in ob.methods { check_method(ccx, method); }
ok &= ty::type_is_nil(tcx, rs);
let num_args = vec::len(args);
ok &=
- num_args == 0u || num_args == 1u && arg_is_argv_ty(tcx, args.(0));
+ num_args == 0u || num_args == 1u && arg_is_argv_ty(tcx, args[0]);
if !ok {
let span = ast_map::node_span(tcx.items.get(main_id));
- tcx.sess.span_err(span, "wrong type in main function: found " +
- ty_to_str(tcx, main_t));
+ tcx.sess.span_err(span,
+ "wrong type in main function: found " +
+ ty_to_str(tcx, main_t));
}
}
_ {
let span = ast_map::node_span(tcx.items.get(main_id));
- tcx.sess.span_bug(span, "main has a non-function type: found" +
- ty_to_str(tcx, main_t));
+ tcx.sess.span_bug(span,
+ "main has a non-function type: found" +
+ ty_to_str(tcx, main_t));
}
}
}
fn check_crate(tcx: &ty::ctxt, crate: &@ast::crate) {
collect::collect_item_types(tcx, crate);
- let obj_infos: [obj_info] = ~[];
+ let obj_infos: [obj_info] = [];
let ccx = @{mutable obj_infos: obj_infos, tcx: tcx};
- let visit = visit::mk_simple_visitor
- (@{visit_item: bind check_item(ccx, _)
- with *visit::default_simple_visitor()});
+ let visit =
+ visit::mk_simple_visitor(@{visit_item: bind check_item(ccx, _)
+ with *visit::default_simple_visitor()});
visit::visit_crate(*crate, (), visit);
check_for_main_fn(tcx, crate);
tcx.sess.abort_if_errors();
def_arg(def_id);
def_local(def_id);
def_variant(def_id, /* tag */def_id);
+
/* variant */
def_ty(def_id);
def_ty_arg(uint, kind);
def_use(def_id);
def_native_ty(def_id);
def_native_fn(def_id);
+
/* A "fake" def for upvars. This never appears in the def_map, but
* freevars::def_lookup will return it for a def that is an upvar.
* It contains the actual def. */
def_local(id) { ret id; }
def_variant(_, id) { ret id; }
def_ty(id) { ret id; }
- def_ty_arg(_,_) { fail; }
+ def_ty_arg(_, _) { fail; }
def_binding(id) { ret id; }
def_use(id) { ret id; }
def_native_ty(id) { ret id; }
tag crate_directive_ {
cdir_src_mod(ident, option::t<filename>, [attribute]);
- cdir_dir_mod(ident,
- option::t<filename>,
- [@crate_directive],
- [attribute]);
+ cdir_dir_mod(ident, option::t<filename>, [@crate_directive], [attribute]);
cdir_view_item(@view_item);
cdir_syntax(path);
cdir_auth(path, _auth);
alt pat.node {
pat_bind(_) { put pat; }
pat_tag(_, sub) {
- for p in sub {
- for each b in pat_bindings(p) { put b; }
- }
+ for p in sub { for each b in pat_bindings(p) { put b; } }
}
pat_rec(fields, _) {
- for f in fields {
- for each b in pat_bindings(f.pat) { put b; }
- }
+ for f in fields { for each b in pat_bindings(f.pat) { put b; } }
}
pat_tup(elts) {
- for elt in elts {
- for each b in pat_bindings(elt) { put b; }
- }
- }
- pat_box(sub) {
- for each b in pat_bindings(sub) { put b; }
+ for elt in elts { for each b in pat_bindings(elt) { put b; } }
}
- pat_wild. | pat_lit(_) {}
+ pat_box(sub) { for each b in pat_bindings(sub) { put b; } }
+ pat_wild. | pat_lit(_) { }
}
}
fn pat_binding_ids(pat: &@pat) -> [node_id] {
- let found = ~[];
- for each b in pat_bindings(pat) { found += ~[b.id]; }
+ let found = [];
+ for each b in pat_bindings(pat) { found += [b.id]; }
ret found;
}
tag stmt_ {
stmt_decl(@decl, node_id);
stmt_expr(@expr, node_id);
+
// These only exist in crate-level blocks.
stmt_crate_directive(@crate_directive);
}
type initializer = {op: init_op, expr: @expr};
-type local_ = {ty: @ty,
- pat: @pat, // FIXME: should really be a refinement on pat
- init: option::t<initializer>,
- id: node_id};
+type local_ = // FIXME: should really be a refinement on pat
+ {ty: @ty, pat: @pat, init: option::t<initializer>, id: node_id};
type local = spanned<local_>;
expr_alt(@expr, [arm]);
expr_fn(_fn);
expr_block(blk);
+
/*
* FIXME: many of these @exprs should be constrained with
* is_lval once we have constrained types working.
expr_put(option::t<@expr>);
expr_be(@expr);
expr_log(int, @expr);
+
/* just an assert, no significance to typestate */
expr_assert(@expr);
+
/* preds that typestate is aware of */
expr_check(check_mode, @expr);
+
/* FIXME Would be nice if expr_check desugared
to expr_if_check. */
expr_if_check(@expr, blk, option::t<@expr>);
ty_bot; /* return type of ! functions and type of
ret/fail/break/cont. there is no syntax
for this type. */
+
/* bot represents the value of functions that don't return a value
locally to their context. in contrast, things like log that do
return, but don't return a meaningful value, have result type nil. */
- ty_bool;
+ ty_bool;
ty_int;
ty_uint;
ty_float;
ty_type;
ty_constr(@ty, [@ty_constr]);
ty_mac(mac);
+
// ty_infer means the type should be inferred instead of it having been
// specified. This should only appear at the "top level" of a type and not
// nested in one.
tag controlflow {
noreturn; // functions with return type _|_ that always
// raise an error or exit (i.e. never return to the caller)
+
return; // everything else
}
type anon_obj =
// New fields and methods, if they exist.
+ // inner_obj: the original object being extended, if it exists.
{fields: option::t<[anon_obj_field]>,
methods: [@method],
- // inner_obj: the original object being extended, if it exists.
inner_obj: option::t<@expr>};
type _mod = {view_items: [@view_item], items: [@item]};
item_ty(@ty, [ty_param]);
item_tag([variant], [ty_param]);
item_obj(_obj, [ty_param], /* constructor id */node_id);
- item_res(_fn, /* dtor */
- node_id, /* dtor id */
+ item_res(_fn,
+ /* dtor */
+ node_id,
+ /* dtor id */
[ty_param],
- node_id /* ctor id */);
+
+ /* ctor id */
+ node_id);
}
type native_item =
for vi: @ast::view_item in m.view_items {
alt vi.node {
ast::view_item_export(ids, _) {
- for id in ids {
- if str::eq(i, id) {
- ret true;
- }
- }
+ for id in ids { if str::eq(i, id) { ret true; } }
count += 1u;
}
_ {/* fall through */ }
fn hash_ty(t: &@ty) -> uint { ret t.span.lo << 16u + t.span.hi; }
fn block_from_expr(e: @expr) -> blk {
- let blk_ = {stmts: ~[], expr: option::some::<@expr>(e), id: e.id};
+ let blk_ = {stmts: [], expr: option::some::<@expr>(e), id: e.id};
ret {node: blk_, span: e.span};
}
type loc = {filename: filename, line: uint, col: uint};
-fn new_codemap() -> codemap { ret @{mutable files: ~[]}; }
+fn new_codemap() -> codemap { ret @{mutable files: []}; }
fn new_filemap(filename: filename, start_pos_ch: uint, start_pos_byte: uint)
-> filemap {
ret @{name: filename,
start_pos: {ch: start_pos_ch, byte: start_pos_byte},
- mutable lines: ~[{ch: start_pos_ch, byte: start_pos_byte}]};
+ mutable lines: [{ch: start_pos_ch, byte: start_pos_byte}]};
}
fn next_line(file: filemap, chpos: uint, byte_pos: uint) {
- file.lines += ~[{ch: chpos, byte: byte_pos}];
+ file.lines += [{ch: chpos, byte: byte_pos}];
}
-type lookup_fn = fn(file_pos) -> uint ;
+type lookup_fn = fn(file_pos) -> uint;
fn lookup_pos(map: codemap, pos: uint, lookup: lookup_fn) -> loc {
let a = 0u;
let b = vec::len(map.files);
while b - a > 1u {
let m = (a + b) / 2u;
- if lookup(map.files.(m).start_pos) > pos { b = m; } else { a = m; }
+ if lookup(map.files[m].start_pos) > pos { b = m; } else { a = m; }
}
- let f = map.files.(a);
+ let f = map.files[a];
a = 0u;
b = vec::len(f.lines);
while b - a > 1u {
let m = (a + b) / 2u;
- if lookup(f.lines.(m)) > pos { b = m; } else { a = m; }
+ if lookup(f.lines[m]) > pos { b = m; } else { a = m; }
}
- ret {filename: f.name, line: a + 1u, col: pos - lookup(f.lines.(a))};
+ ret {filename: f.name, line: a + 1u, col: pos - lookup(f.lines[a])};
}
fn lookup_char_pos(map: codemap, pos: uint) -> loc {
ret lookup_pos(map, pos, lookup);
}
-tag opt_span { //hack (as opposed to option::t), to make `span` compile
+tag opt_span {
+ //hack (as opposed to option::t), to make `span` compile
os_none;
os_some(@span);
}
let cur = sp;
let res = "";
let prev_file = none;
- while(true) {
+ while true {
let lo = lookup_char_pos(cm, cur.lo);
let hi = lookup_char_pos(cm, cur.hi);
- res += #fmt("%s:%u:%u:%u:%u",
- if some(lo.filename) == prev_file { "-" }
- else { lo.filename },
- lo.line, lo.col, hi.line, hi.col);
+ res +=
+ #fmt["%s:%u:%u:%u:%u",
+ if some(lo.filename) == prev_file {
+ "-"
+ } else { lo.filename }, lo.line, lo.col, hi.line, hi.col];
alt cur.expanded_from {
os_none. { break; }
os_some(new_sp) {
if term::color_supported() {
term::fg(io::stdout().get_buf_writer(), color);
}
- io::stdout().write_str(#fmt("%s:", kind));
- if term::color_supported() {
- term::reset(io::stdout().get_buf_writer());
- }
- io::stdout().write_str(#fmt(" %s\n", msg));
+ io::stdout().write_str(#fmt["%s:", kind]);
+ if term::color_supported() { term::reset(io::stdout().get_buf_writer()); }
+ io::stdout().write_str(#fmt[" %s\n", msg]);
maybe_highlight_lines(sp, cm, maybe_lines);
}
}
// Print the offending lines
for line: uint in display_lines {
- io::stdout().write_str(#fmt("%s:%u ", fm.name, line + 1u));
+ io::stdout().write_str(#fmt["%s:%u ", fm.name, line + 1u]);
let s = get_line(fm, line as int, file);
if !str::ends_with(s, "\n") { s += "\n"; }
io::stdout().write_str(s);
}
if elided {
- let last_line = display_lines.(vec::len(display_lines) - 1u);
- let s = #fmt("%s:%u ", fm.name, last_line + 1u);
+ let last_line = display_lines[vec::len(display_lines) - 1u];
+ let s = #fmt["%s:%u ", fm.name, last_line + 1u];
let indent = str::char_len(s);
let out = "";
while indent > 0u { out += " "; indent -= 1u; }
if vec::len(lines.lines) == 1u {
let lo = lookup_char_pos(cm, option::get(sp).lo);
let digits = 0u;
- let num = lines.lines.(0) / 10u;
+ let num = lines.lines[0] / 10u;
// how many digits must be indent past?
while num > 0u { num /= 10u; digits += 1u; }
fn span_to_lines(sp: span, cm: codemap::codemap) -> @file_lines {
let lo = lookup_char_pos(cm, sp.lo);
let hi = lookup_char_pos(cm, sp.hi);
- let lines = ~[];
+ let lines = [];
for each i: uint in uint::range(lo.line - 1u, hi.line as uint) {
- lines += ~[i];
+ lines += [i];
}
ret @{name: lo.filename, lines: lines};
}
fn get_line(fm: filemap, line: int, file: &str) -> str {
- let begin: uint = fm.lines.(line).byte - fm.start_pos.byte;
+ let begin: uint = fm.lines[line].byte - fm.start_pos.byte;
let end: uint;
if line as uint < vec::len(fm.lines) - 1u {
- end = fm.lines.(line + 1).byte - fm.start_pos.byte;
+ end = fm.lines[line + 1].byte - fm.start_pos.byte;
} else {
// If we're not done parsing the file, we're at the limit of what's
// parsed. If we just slice the rest of the string, we'll print out
// (or expected function, found _|_)
fail; // ("asking for " + filename + " which we don't know about");
}
-
//
// Local Variables:
// mode: rust
import codemap;
type syntax_expander =
- fn(&ext_ctxt, span, @ast::expr, option::t<str>) -> @ast::expr ;
+ fn(&ext_ctxt, span, @ast::expr, option::t<str>) -> @ast::expr;
type macro_def = {ident: str, ext: syntax_extension};
type macro_definer =
- fn(&ext_ctxt, span, @ast::expr, option::t<str>) -> macro_def ;
+ fn(&ext_ctxt, span, @ast::expr, option::t<str>) -> macro_def;
tag syntax_extension {
normal(syntax_expander);
ret syntax_expanders;
}
-obj ext_ctxt(sess: @session, crate_file_name_hack: str,
+obj ext_ctxt(sess: @session,
+ crate_file_name_hack: str,
mutable backtrace: codemap::opt_span) {
fn crate_file_name() -> str { ret crate_file_name_hack; }
fn session() -> @session { ret sess; }
- fn print_backtrace() {
- }
+ fn print_backtrace() { }
fn backtrace() -> codemap::opt_span { ret backtrace; }
fn bt_push(sp: span) {
- backtrace = codemap::os_some(@{lo: sp.lo, hi: sp.hi,
- expanded_from: backtrace});
+ backtrace =
+ codemap::os_some(@{lo: sp.lo,
+ hi: sp.hi,
+ expanded_from: backtrace});
}
fn bt_pop() {
alt backtrace {
self.print_backtrace();
sess.span_err(sp, msg);
}
- fn span_unimpl(sp:span, msg: str) -> ! {
+ fn span_unimpl(sp: span, msg: str) -> ! {
self.print_backtrace();
sess.span_unimpl(sp, msg);
}
- fn span_bug(sp:span, msg: str) -> ! {
+ fn span_bug(sp: span, msg: str) -> ! {
self.print_backtrace();
sess.span_bug(sp, msg);
}
- fn bug(msg: str) -> ! {
- self.print_backtrace();
- sess.bug(msg);
- }
- fn next_id() -> ast::node_id {
- ret sess.next_node_id();
- }
+ fn bug(msg: str) -> ! { self.print_backtrace(); sess.bug(msg); }
+ fn next_id() -> ast::node_id { ret sess.next_node_id(); }
}
// the extensions the file name of the crate being compiled so they can
// use it to guess whether paths should be prepended with "std::". This is
// super-ugly and needs a better solution.
- let crate_file_name_hack = sess.get_codemap().files.(0).name;
+ let crate_file_name_hack = sess.get_codemap().files[0].name;
ret ext_ctxt(@sess, crate_file_name_hack, codemap::os_none);
}
ast::expr_path(p) {
if vec::len(p.node.types) > 0u || vec::len(p.node.idents) != 1u {
cx.span_fatal(expr.span, error);
- } else { ret p.node.idents.(0); }
+ } else { ret p.node.idents[0]; }
}
_ { cx.span_fatal(expr.span, error); }
}
fn expand_syntax_ext(cx: &ext_ctxt, sp: codemap::span, arg: @ast::expr,
_body: option::t<str>) -> @ast::expr {
- let args: [@ast::expr] = alt arg.node {
- ast::expr_vec(elts, _) { elts }
- _ { cx.span_fatal(sp, "#concat_idents requires a vector argument .") }
- };
+ let args: [@ast::expr] =
+ alt arg.node {
+ ast::expr_vec(elts, _) { elts }
+ _ {
+ cx.span_fatal(sp, "#concat_idents requires a vector argument .")
+ }
+ };
let res: ast::ident = "";
for e: @ast::expr in args {
res += expr_to_ident(cx, e, "expected an ident");
}
ret @{id: cx.next_id(),
- node: ast::expr_path( {
- node: {global: false, idents: ~[res], types: ~[]},
- span: sp}),
+ node:
+ ast::expr_path({node: {global: false, idents: [res], types: []},
+ span: sp}),
span: sp};
}
fn expand_syntax_ext(cx: &ext_ctxt, sp: codemap::span, arg: @ast::expr,
_body: option::t<str>) -> @ast::expr {
- let args: [@ast::expr] = alt arg.node {
- ast::expr_vec(elts, _) { elts }
- _ { cx.span_fatal(sp, "#env requires arguments of the form `[...]`.") }
- };
+ let args: [@ast::expr] =
+ alt arg.node {
+ ast::expr_vec(elts, _) { elts }
+ _ {
+ cx.span_fatal(sp, "#env requires arguments of the form `[...]`.")
+ }
+ };
if vec::len::<@ast::expr>(args) != 1u {
cx.span_fatal(sp, "malformed #env call");
}
// FIXME: if this was more thorough it would manufacture an
// option::t<str> rather than just an maybe-empty string.
- let var = expr_to_str(cx, args.(0), "#env requires a string");
+ let var = expr_to_str(cx, args[0], "#env requires a string");
alt generic_os::getenv(var) {
option::none. { ret make_new_str(cx, sp, ""); }
option::some(s) { ret make_new_str(cx, sp, s); }
fn expand_expr(exts: &hashmap<str, syntax_extension>, cx: &ext_ctxt,
- e: &expr_, fld: ast_fold,
- orig: &fn(&expr_, ast_fold) -> expr_ ) -> expr_ {
+ e: &expr_, fld: ast_fold, orig: &fn(&expr_, ast_fold) -> expr_)
+ -> expr_ {
ret alt e {
expr_mac(mac) {
alt mac.node {
mac_invoc(pth, args, body) {
assert (vec::len(pth.node.idents) > 0u);
- let extname = pth.node.idents.(0);
+ let extname = pth.node.idents[0];
alt exts.find(extname) {
none. {
cx.span_fatal(pth.span,
some(macro_defining(ext)) {
let named_extension = ext(cx, pth.span, args, body);
exts.insert(named_extension.ident, named_extension.ext);
- ast::expr_rec(~[], none)
+ ast::expr_rec([], none)
}
}
}
ret res;
}
-
// Local Variables:
// mode: rust
// fill-column: 78;
fn expand_syntax_ext(cx: &ext_ctxt, sp: span, arg: @ast::expr,
_body: option::t<str>) -> @ast::expr {
- let args: [@ast::expr] = alt arg.node {
- ast::expr_vec(elts, _) { elts }
- _ { cx.span_fatal(sp, "#fmt requires arguments of the form `[...]`.") }
- };
+ let args: [@ast::expr] =
+ alt arg.node {
+ ast::expr_vec(elts, _) { elts }
+ _ {
+ cx.span_fatal(sp, "#fmt requires arguments of the form `[...]`.")
+ }
+ };
if vec::len::<@ast::expr>(args) == 0u {
cx.span_fatal(sp, "#fmt requires a format string");
}
let fmt =
- expr_to_str(cx, args.(0),
+ expr_to_str(cx, args[0],
"first argument to #fmt must be a " + "string literal.");
- let fmtspan = args.(0).span;
+ let fmtspan = args[0].span;
log "Format string:";
log fmt;
fn parse_fmt_err_(cx: &ext_ctxt, sp: span, msg: str) -> ! {
}
fn make_path_expr(cx: &ext_ctxt, sp: span, idents: &[ast::ident]) ->
@ast::expr {
- let path = {global: false, idents: idents, types: ~[]};
+ let path = {global: false, idents: idents, types: []};
let sp_path = {node: path, span: sp};
let pathexpr = ast::expr_path(sp_path);
ret @{id: cx.next_id(), node: pathexpr, span: sp};
fn make_rec_expr(cx: &ext_ctxt, sp: span,
fields: &[{ident: ast::ident, ex: @ast::expr}]) ->
@ast::expr {
- let astfields: [ast::field] = ~[];
+ let astfields: [ast::field] = [];
for field: {ident: ast::ident, ex: @ast::expr} in fields {
let ident = field.ident;
let val = field.ex;
let astfield =
{node: {mut: ast::imm, ident: ident, expr: val}, span: sp};
- astfields += ~[astfield];
+ astfields += [astfield];
}
let recexpr = ast::expr_rec(astfields, option::none::<@ast::expr>);
ret @{id: cx.next_id(), node: recexpr, span: sp};
ret str::find(cx.crate_file_name(), "std.rc") >= 0;
}
if compiling_std(cx) {
- ret ~["extfmt", "rt", ident];
- } else { ret ~["std", "extfmt", "rt", ident]; }
+ ret ["extfmt", "rt", ident];
+ } else { ret ["std", "extfmt", "rt", ident]; }
}
fn make_rt_path_expr(cx: &ext_ctxt, sp: span, ident: str) -> @ast::expr {
let path = make_path_vec(cx, ident);
// which tells the RT::conv* functions how to perform the conversion
fn make_rt_conv_expr(cx: &ext_ctxt, sp: span, cnv: &conv) -> @ast::expr {
- fn make_flags(cx: &ext_ctxt, sp: span, flags: &[flag]) ->
- @ast::expr {
- let flagexprs: [@ast::expr] = ~[];
+ fn make_flags(cx: &ext_ctxt, sp: span, flags: &[flag]) -> @ast::expr {
+ let flagexprs: [@ast::expr] = [];
for f: flag in flags {
let fstr;
alt f {
flag_sign_always. { fstr = "flag_sign_always"; }
flag_alternate. { fstr = "flag_alternate"; }
}
- flagexprs += ~[make_rt_path_expr(cx, sp, fstr)];
+ flagexprs += [make_rt_path_expr(cx, sp, fstr)];
}
// FIXME: 0-length vectors can't have their type inferred
// through the rec that these flags are a member of, so
// this is a hack placeholder flag
if vec::len::<@ast::expr>(flagexprs) == 0u {
- flagexprs += ~[make_rt_path_expr(cx, sp, "flag_none")];
+ flagexprs += [make_rt_path_expr(cx, sp, "flag_none")];
}
ret make_vec_expr(cx, sp, flagexprs);
}
count_is(c) {
let count_lit = make_new_int(cx, sp, c);
let count_is_path = make_path_vec(cx, "count_is");
- let count_is_args = ~[count_lit];
+ let count_is_args = [count_lit];
ret make_call(cx, sp, count_is_path, count_is_args);
}
_ { cx.span_unimpl(sp, "unimplemented #fmt conversion"); }
width_expr: @ast::expr, precision_expr: @ast::expr,
ty_expr: @ast::expr) -> @ast::expr {
ret make_rec_expr(cx, sp,
- ~[{ident: "flags", ex: flags_expr},
- {ident: "width", ex: width_expr},
- {ident: "precision", ex: precision_expr},
- {ident: "ty", ex: ty_expr}]);
+ [{ident: "flags", ex: flags_expr},
+ {ident: "width", ex: width_expr},
+ {ident: "precision", ex: precision_expr},
+ {ident: "ty", ex: ty_expr}]);
}
let rt_conv_flags = make_flags(cx, sp, cnv.flags);
let rt_conv_width = make_count(cx, sp, cnv.width);
let fname = "conv_" + conv_type;
let path = make_path_vec(cx, fname);
let cnv_expr = make_rt_conv_expr(cx, sp, cnv);
- let args = ~[cnv_expr, arg];
+ let args = [cnv_expr, arg];
ret make_call(cx, arg.span, path, args);
}
fn make_new_conv(cx: &ext_ctxt, sp: span, cnv: conv, arg: @ast::expr) ->
ty_octal. { log "type: octal"; }
}
}
- let fmt_sp = args.(0).span;
+ let fmt_sp = args[0].span;
let n = 0u;
let tmp_expr = make_new_str(cx, sp, "");
let nargs = vec::len::<@ast::expr>(args);
}
log "Building conversion:";
log_conv(conv);
- let arg_expr = args.(n);
+ let arg_expr = args[n];
let c_expr = make_new_conv(cx, fmt_sp, conv, arg_expr);
tmp_expr = make_add_expr(cx, fmt_sp, tmp_expr, c_expr);
}
let expected_nargs = n + 1u; // n conversions + the fmt string
if expected_nargs < nargs {
- cx.span_fatal
- (sp, #fmt("too many arguments to #fmt. found %u, expected %u",
- nargs, expected_nargs));
+ cx.span_fatal(
+ sp,
+ #fmt["too many arguments to #fmt. found %u, expected %u",
+ nargs, expected_nargs]);
}
ret tmp_expr;
}
fn expand_syntax_ext(cx: &ext_ctxt, sp: codemap::span, arg: @ast::expr,
_body: option::t<str>) -> @ast::expr {
- let args: [@ast::expr] = alt arg.node {
- ast::expr_vec(elts, _) { elts }
- _ { cx.span_fatal(sp, "#ident_to_str requires a vector argument .") }
- };
+ let args: [@ast::expr] =
+ alt arg.node {
+ ast::expr_vec(elts, _) { elts }
+ _ {
+ cx.span_fatal(sp, "#ident_to_str requires a vector argument .")
+ }
+ };
if vec::len::<@ast::expr>(args) != 1u {
cx.span_fatal(sp, "malformed #ident_to_str call");
}
ret make_new_lit(cx, sp,
- ast::lit_str(expr_to_ident(cx, args.(0u),
+ ast::lit_str(expr_to_ident(cx, args[0u],
"expected an ident"),
ast::sk_rc));
std::io::stdout().write_line(print::pprust::expr_to_str(arg));
//trivial expression
- ret @{id: cx.next_id(), node: ast::expr_rec(~[], option::none), span: sp};
+ ret @{id: cx.next_id(), node: ast::expr_rec([], option::none), span: sp};
}
fn path_to_ident(pth: &path) -> option::t<ident> {
if vec::len(pth.node.idents) == 1u && vec::len(pth.node.types) == 0u {
- ret some(pth.node.idents.(0u));
+ ret some(pth.node.idents[0u]);
}
ret none;
}
// we'll want to return something indicating amount of progress and location
// of failure instead of `none`.
type match_result = option::t<arb_depth<matchable>>;
-type selector = fn(&matchable) -> match_result ;
+type selector = fn(&matchable) -> match_result;
-fn elts_to_ell(cx: &ext_ctxt, elts: &[@expr])
- -> {pre: [@expr], rep: option::t<@expr>, post: [@expr]} {
+fn elts_to_ell(cx: &ext_ctxt, elts: &[@expr]) ->
+ {pre: [@expr], rep: option::t<@expr>, post: [@expr]} {
let idx: uint = 0u;
let res = none;
for elt: @expr in elts {
if res != none {
cx.span_fatal(m.span, "only one ellipsis allowed");
}
- res = some({pre: vec::slice(elts, 0u, idx - 1u),
- rep: some(elts.(idx - 1u)),
- post: vec::slice(elts, idx + 1u,
- vec::len(elts))});
+ res =
+ some({pre: vec::slice(elts, 0u, idx - 1u),
+ rep: some(elts[idx - 1u]),
+ post: vec::slice(elts, idx + 1u, vec::len(elts))});
}
_ { }
}
idx += 1u;
}
ret alt res {
- some(val) { val }
- none. { {pre: elts, rep: none, post: ~[]} }
- }
+ some(val) { val }
+ none. { {pre: elts, rep: none, post: []} }
+ }
}
fn option_flatten_map<T, U>(f: &fn(&T) -> option::t<U>, v: &[T]) ->
option::t<[U]> {
- let res = ~[];
+ let res = [];
for elem: T in v {
- alt f(elem) { none. { ret none; } some(fv) { res += ~[fv]; } }
+ alt f(elem) { none. { ret none; } some(fv) { res += [fv]; } }
}
ret some(res);
}
fn pattern_to_selectors(cx: &ext_ctxt, e: @expr) -> binders {
let res: binders =
{real_binders: new_str_hash::<selector>(),
- mutable literal_ast_matchers: ~[]};
+ mutable literal_ast_matchers: []};
//this oughta return binders instead, but macro args are a sequence of
//expressions, rather than a single expression
fn trivial_selector(m: &matchable) -> match_result { ret some(leaf(m)); }
/* use the bindings on the body to generate the expanded code */
fn transcribe(cx: &ext_ctxt, b: &bindings, body: @expr) -> @expr {
- let idx_path: @mutable [uint] = @mutable ~[];
+ let idx_path: @mutable [uint] = @mutable [];
fn new_id(_old: node_id, cx: &ext_ctxt) -> node_id { ret cx.next_id(); }
fn new_span(cx: &ext_ctxt, sp: &span) -> span {
/* this discards information in the case of macro-defining macros */
for idx: uint in *idx_path {
alt res {
leaf(_) { ret res;/* end of the line */ }
- seq(new_ms, _) { res = new_ms.(idx); }
+ seq(new_ms, _) { res = new_ms[idx]; }
}
}
ret res;
/* handle sequences (anywhere in the AST) of exprs, either real or ...ed */
fn transcribe_exprs(cx: &ext_ctxt, b: &bindings, idx_path: @mutable [uint],
- recur: fn(&@expr) -> @expr , exprs: [@expr])
- -> [@expr] {
+ recur: fn(&@expr) -> @expr, exprs: [@expr]) -> [@expr] {
alt elts_to_ell(cx, exprs) {
{pre: pre, rep: repeat_me_maybe, post: post} {
let res = vec::map(recur, pre);
alt repeat_me_maybe {
- none. {}
+ none. { }
some(repeat_me) {
let repeat: option::t<{rep_count: uint, name: ident}> = none;
/* we need to walk over all the free vars in lockstep, except for
some({rep_count: old_len, name: old_name}) {
let len = vec::len(*ms);
if old_len != len {
- let msg = #fmt("'%s' occurs %u times, but ", fv,
- len) + #fmt("'%s' occurs %u times",
- old_name, old_len);
+ let msg =
+ #fmt["'%s' occurs %u times, but ", fv, len] +
+ #fmt["'%s' occurs %u times", old_name,
+ old_len];
cx.span_fatal(repeat_me.span, msg);
}
}
none. {
cx.span_fatal(repeat_me.span,
"'...' surrounds an expression without any" +
- " repeating syntax variables");
+ " repeating syntax variables");
}
some({rep_count: rc, _}) {
/* Whew, we now know how how many times to repeat */
let idx: uint = 0u;
while idx < rc {
- *idx_path += ~[idx];
- res += ~[recur(repeat_me)]; // whew!
+ *idx_path += [idx];
+ res += [recur(repeat_me)]; // whew!
vec::pop(*idx_path);
idx += 1u;
}
p: &path_, _fld: ast_fold) -> path_ {
// Don't substitute into qualified names.
if vec::len(p.types) > 0u || vec::len(p.idents) != 1u { ret p; }
- ret alt follow_for_trans(cx, b.find(p.idents.(0)), idx_path) {
+ ret alt follow_for_trans(cx, b.find(p.idents[0]), idx_path) {
some(match_ident(id)) {
- {global: false, idents: ~[id.node], types: ~[]}
+ {global: false, idents: [id.node], types: []}
}
some(match_path(a_pth)) { a_pth.node }
some(m) { match_error(cx, m, "a path") }
fn transcribe_expr(cx: &ext_ctxt, b: &bindings, idx_path: @mutable [uint],
e: &ast::expr_, fld: ast_fold,
- orig: fn(&ast::expr_, ast_fold) -> ast::expr_ ) ->
+ orig: fn(&ast::expr_, ast_fold) -> ast::expr_) ->
ast::expr_ {
ret alt e {
expr_path(p) {
// Don't substitute into qualified names.
- if vec::len(p.node.types) > 0u || vec::len(p.node.idents) != 1u
- {
+ if vec::len(p.node.types) > 0u || vec::len(p.node.idents) != 1u {
e
}
- alt follow_for_trans(cx, b.find(p.node.idents.(0)), idx_path) {
+ alt follow_for_trans(cx, b.find(p.node.idents[0]), idx_path) {
some(match_ident(id)) {
expr_path(respan(id.span,
{global: false,
- idents: ~[id.node],
- types: ~[]}))
+ idents: [id.node],
+ types: []}))
}
some(match_path(a_pth)) { expr_path(a_pth) }
some(match_expr(a_exp)) { a_exp.node }
fn transcribe_type(cx: &ext_ctxt, b: &bindings, idx_path: @mutable [uint],
t: &ast::ty_, fld: ast_fold,
- orig: fn(&ast::ty_, ast_fold) -> ast::ty_ ) -> ast::ty_ {
+ orig: fn(&ast::ty_, ast_fold) -> ast::ty_) -> ast::ty_ {
ret alt t {
ast::ty_path(pth, _) {
alt path_to_ident(pth) {
fn transcribe_block(cx: &ext_ctxt, b: &bindings, idx_path: @mutable [uint],
blk: &blk_, fld: ast_fold,
- orig: fn(&blk_, ast_fold) -> blk_ ) -> blk_ {
+ orig: fn(&blk_, ast_fold) -> blk_) -> blk_ {
ret alt block_to_ident(blk) {
some(id) {
alt follow_for_trans(cx, b.find(id), idx_path) {
some(match_block(new_blk)) { new_blk.node }
+
// possibly allow promotion of ident/path/expr to blocks?
some(m) {
match_error(cx, m, "a block")
expr_vec(p_elts, _) {
alt elts_to_ell(cx, p_elts) {
{pre: pre, rep: some(repeat_me), post: post} {
- p_t_s_r_length(cx, vec::len(pre) + vec::len(post),
- true, s, b);
- if(vec::len(pre) > 0u) {
+ p_t_s_r_length(cx, vec::len(pre) + vec::len(post), true, s,
+ b);
+ if vec::len(pre) > 0u {
p_t_s_r_actual_vector(cx, pre, true, s, b);
}
p_t_s_r_ellipses(cx, repeat_me, vec::len(pre), s, b);
- if(vec::len(post) > 0u) {
+ if vec::len(post) > 0u {
cx.span_unimpl(e.span,
"matching after `...` not yet supported");
}
}
{pre: pre, rep: none., post: post} {
- if post != ~[] {
+ if post != [] {
cx.bug("elts_to_ell provided an invalid result");
}
p_t_s_r_length(cx, vec::len(pre), false, s, b);
}
}
+
/* TODO: handle embedded types and blocks, at least */
expr_mac(mac) {
p_t_s_r_mac(cx, mac, s, b);
_ { cx.bug("broken traversal in p_t_s_r") }
}
}
- b.literal_ast_matchers += ~[bind select(cx, _, e)];
+ b.literal_ast_matchers += [bind select(cx, _, e)];
}
}
}
fn p_t_s_r_mac(cx: &ext_ctxt, mac: &ast::mac, s: &selector, b: &binders) {
fn select_pt_1(cx: &ext_ctxt, m: &matchable,
- fn_m: fn(&ast::mac) -> match_result ) -> match_result {
+ fn_m: fn(&ast::mac) -> match_result) -> match_result {
ret alt m {
match_expr(e) {
alt e.node { expr_mac(mac) { fn_m(mac) } _ { none } }
fn p_t_s_r_ellipses(cx: &ext_ctxt, repeat_me: @expr, offset: uint,
s: &selector, b: &binders) {
fn select(cx: &ext_ctxt, repeat_me: @expr, offset: uint, m: &matchable) ->
- match_result {
+ match_result {
ret alt m {
match_expr(e) {
alt e.node {
expr_vec(arg_elts, _) {
- let elts = ~[];
+ let elts = [];
let idx = offset;
while idx < vec::len(arg_elts) {
- elts += ~[leaf(match_expr(arg_elts.(idx)))];
+ elts += [leaf(match_expr(arg_elts[idx]))];
idx += 1u;
}
+
// using repeat_me.span is a little wacky, but the
// error we want to report is one in the macro def
some(seq(@elts, repeat_me.span))
fn p_t_s_r_length(cx: &ext_ctxt, len: uint, at_least: bool, s: selector,
b: &binders) {
- fn len_select(_cx: &ext_ctxt, m: &matchable, at_least: bool, len: uint)
- -> match_result {
+ fn len_select(_cx: &ext_ctxt, m: &matchable, at_least: bool, len: uint) ->
+ match_result {
ret alt m {
match_expr(e) {
alt e.node {
expr_vec(arg_elts, _) {
let actual_len = vec::len(arg_elts);
- if (at_least && actual_len >= len) || actual_len == len {
+ if at_least && actual_len >= len || actual_len == len {
some(leaf(match_exact))
} else { none }
}
}
}
b.literal_ast_matchers +=
- ~[compose_sels(s, bind len_select(cx, _, at_least, len))];
+ [compose_sels(s, bind len_select(cx, _, at_least, len))];
}
fn p_t_s_r_actual_vector(cx: &ext_ctxt, elts: [@expr], _repeat_after: bool,
match_expr(e) {
alt e.node {
expr_vec(arg_elts, _) {
- some(leaf(match_expr(arg_elts.(idx))))
+ some(leaf(match_expr(arg_elts[idx])))
}
_ { none }
}
_ { cx.bug("broken traversal in p_t_s_r") }
}
}
- p_t_s_rec(cx, match_expr(elts.(idx)),
+ p_t_s_rec(cx, match_expr(elts[idx]),
compose_sels(s, bind select(cx, _, idx)), b);
idx += 1u;
}
fn add_new_extension(cx: &ext_ctxt, sp: span, arg: @expr,
_body: option::t<str>) -> base::macro_def {
- let args: [@ast::expr] = alt arg.node {
- ast::expr_vec(elts, _) { elts }
- _ {
- cx.span_fatal(sp, "#macro requires arguments of the form `[...]`.")
- }
- };
+ let args: [@ast::expr] =
+ alt arg.node {
+ ast::expr_vec(elts, _) { elts }
+ _ {
+ cx.span_fatal(sp,
+ "#macro requires arguments of the form `[...]`.")
+ }
+ };
let macro_name: option::t<str> = none;
- let clauses: [@clause] = ~[];
+ let clauses: [@clause] = [];
for arg: @expr in args {
alt arg.node {
expr_vec(elts, mut) {
}
- alt elts.(0u).node {
+ alt elts[0u].node {
expr_mac(mac) {
alt mac.node {
mac_invoc(pth, invoc_arg, body) {
none. { macro_name = some(id); }
some(other_id) {
if id != other_id {
- cx.span_fatal(pth.span, "macro name must be "
- + "consistent");
+ cx.span_fatal(pth.span,
+ "macro name must be " +
+ "consistent");
}
}
}
}
}
clauses +=
- ~[@{params: pattern_to_selectors(cx, invoc_arg),
- body: elts.(1u)}];
+ [@{params: pattern_to_selectors(cx, invoc_arg),
+ body: elts[1u]}];
// FIXME: check duplicates (or just simplify
// the macro arg situation)
}
}
}
_ {
- cx.span_fatal(elts.(0u).span,
+ cx.span_fatal(elts[0u].span,
"extension clause must" +
" start with a macro invocation.");
}
_body: option::t<str>, clauses: [@clause]) -> @expr {
for c: @clause in clauses {
alt use_selectors_to_bind(c.params, arg) {
- some(bindings) {
- ret transcribe(cx, bindings, c.body)
- }
+ some(bindings) { ret transcribe(cx, bindings, c.body) }
none. { cont; }
}
}
type ast_fold_precursor =
//unlike the others, item_ is non-trivial
- {fold_crate: fn(&crate_, ast_fold) -> crate_ ,
+ {fold_crate: fn(&crate_, ast_fold) -> crate_,
fold_crate_directive:
- fn(&crate_directive_, ast_fold) -> crate_directive_ ,
- fold_view_item: fn(&view_item_, ast_fold) -> view_item_ ,
- fold_native_item: fn(&@native_item, ast_fold) -> @native_item ,
- fold_item: fn(&@item, ast_fold) -> @item ,
- fold_item_underscore: fn(&item_, ast_fold) -> item_ ,
- fold_method: fn(&method_, ast_fold) -> method_ ,
- fold_block: fn(&blk_, ast_fold) -> blk_ ,
- fold_stmt: fn(&stmt_, ast_fold) -> stmt_ ,
- fold_arm: fn(&arm, ast_fold) -> arm ,
- fold_pat: fn(&pat_, ast_fold) -> pat_ ,
- fold_decl: fn(&decl_, ast_fold) -> decl_ ,
- fold_expr: fn(&expr_, ast_fold) -> expr_ ,
- fold_ty: fn(&ty_, ast_fold) -> ty_ ,
- fold_constr: fn(&ast::constr_, ast_fold) -> constr_ ,
- fold_fn: fn(&_fn, ast_fold) -> _fn ,
- fold_mod: fn(&_mod, ast_fold) -> _mod ,
- fold_native_mod: fn(&native_mod, ast_fold) -> native_mod ,
- fold_variant: fn(&variant_, ast_fold) -> variant_ ,
- fold_ident: fn(&ident, ast_fold) -> ident ,
- fold_path: fn(&path_, ast_fold) -> path_ ,
- fold_local: fn(&local_, ast_fold) -> local_ ,
- map_exprs: fn(fn(&@expr) -> @expr , [@expr]) -> [@expr],
+ fn(&crate_directive_, ast_fold) -> crate_directive_,
+ fold_view_item: fn(&view_item_, ast_fold) -> view_item_,
+ fold_native_item: fn(&@native_item, ast_fold) -> @native_item,
+ fold_item: fn(&@item, ast_fold) -> @item,
+ fold_item_underscore: fn(&item_, ast_fold) -> item_,
+ fold_method: fn(&method_, ast_fold) -> method_,
+ fold_block: fn(&blk_, ast_fold) -> blk_,
+ fold_stmt: fn(&stmt_, ast_fold) -> stmt_,
+ fold_arm: fn(&arm, ast_fold) -> arm,
+ fold_pat: fn(&pat_, ast_fold) -> pat_,
+ fold_decl: fn(&decl_, ast_fold) -> decl_,
+ fold_expr: fn(&expr_, ast_fold) -> expr_,
+ fold_ty: fn(&ty_, ast_fold) -> ty_,
+ fold_constr: fn(&ast::constr_, ast_fold) -> constr_,
+ fold_fn: fn(&_fn, ast_fold) -> _fn,
+ fold_mod: fn(&_mod, ast_fold) -> _mod,
+ fold_native_mod: fn(&native_mod, ast_fold) -> native_mod,
+ fold_variant: fn(&variant_, ast_fold) -> variant_,
+ fold_ident: fn(&ident, ast_fold) -> ident,
+ fold_path: fn(&path_, ast_fold) -> path_,
+ fold_local: fn(&local_, ast_fold) -> local_,
+ map_exprs: fn(fn(&@expr) -> @expr, [@expr]) -> [@expr],
new_id: fn(node_id) -> node_id,
new_span: fn(&span) -> span};
type a_f =
- {fold_crate: fn(&crate) -> crate ,
- fold_crate_directive: fn(&@crate_directive) -> @crate_directive ,
- fold_view_item: fn(&@view_item) -> @view_item ,
- fold_native_item: fn(&@native_item) -> @native_item ,
- fold_item: fn(&@item) -> @item ,
- fold_item_underscore: fn(&item_) -> item_ ,
- fold_method: fn(&@method) -> @method ,
- fold_block: fn(&blk) -> blk ,
- fold_stmt: fn(&@stmt) -> @stmt ,
- fold_arm: fn(&arm) -> arm ,
- fold_pat: fn(&@pat) -> @pat ,
- fold_decl: fn(&@decl) -> @decl ,
- fold_expr: fn(&@expr) -> @expr ,
- fold_ty: fn(&@ty) -> @ty ,
- fold_constr: fn(&@constr) -> @constr ,
- fold_fn: fn(&_fn) -> _fn ,
- fold_mod: fn(&_mod) -> _mod ,
- fold_native_mod: fn(&native_mod) -> native_mod ,
- fold_variant: fn(&variant) -> variant ,
- fold_ident: fn(&ident) -> ident ,
- fold_path: fn(&path) -> path ,
- fold_local: fn(&@local) -> @local ,
- map_exprs: fn(fn(&@expr) -> @expr , [@expr]) -> [@expr],
+ {fold_crate: fn(&crate) -> crate,
+ fold_crate_directive: fn(&@crate_directive) -> @crate_directive,
+ fold_view_item: fn(&@view_item) -> @view_item,
+ fold_native_item: fn(&@native_item) -> @native_item,
+ fold_item: fn(&@item) -> @item,
+ fold_item_underscore: fn(&item_) -> item_,
+ fold_method: fn(&@method) -> @method,
+ fold_block: fn(&blk) -> blk,
+ fold_stmt: fn(&@stmt) -> @stmt,
+ fold_arm: fn(&arm) -> arm,
+ fold_pat: fn(&@pat) -> @pat,
+ fold_decl: fn(&@decl) -> @decl,
+ fold_expr: fn(&@expr) -> @expr,
+ fold_ty: fn(&@ty) -> @ty,
+ fold_constr: fn(&@constr) -> @constr,
+ fold_fn: fn(&_fn) -> _fn,
+ fold_mod: fn(&_mod) -> _mod,
+ fold_native_mod: fn(&native_mod) -> native_mod,
+ fold_variant: fn(&variant) -> variant,
+ fold_ident: fn(&ident) -> ident,
+ fold_path: fn(&path) -> path,
+ fold_local: fn(&@local) -> @local,
+ map_exprs: fn(fn(&@expr) -> @expr, [@expr]) -> [@expr],
new_id: fn(node_id) -> node_id,
new_span: fn(&span) -> span};
span: mi.span};
}
//used in noop_fold_item and noop_fold_crate
-fn fold_attribute_(at: &attribute, fmi: fn(&@meta_item) -> @meta_item ) ->
+fn fold_attribute_(at: &attribute, fmi: fn(&@meta_item) -> @meta_item) ->
attribute {
ret {node: {style: at.node.style, value: *fmi(@at.node.value)},
span: at.span};
//used in noop_fold_expr, and possibly elsewhere in the future
fn fold_mac_(m: &mac, fld: ast_fold) -> mac {
ret {node:
- alt m.node {
- mac_invoc(pth, arg, body) {
- mac_invoc(fld.fold_path(pth), fld.fold_expr(arg), body)
- }
- mac_embed_type(ty) { mac_embed_type(fld.fold_ty(ty)) }
- mac_embed_block(blk) { mac_embed_block(fld.fold_block(blk)) }
- mac_ellipsis. { mac_ellipsis }
- },
+ alt m.node {
+ mac_invoc(pth, arg, body) {
+ mac_invoc(fld.fold_path(pth), fld.fold_expr(arg), body)
+ }
+ mac_embed_type(ty) { mac_embed_type(fld.fold_ty(ty)) }
+ mac_embed_block(blk) { mac_embed_block(fld.fold_block(blk)) }
+ mac_ellipsis. { mac_ellipsis }
+ },
span: m.span};
}
cf: fdec.cf,
constraints:
vec::map(fld.fold_constr,
- fdec.constraints)}, typms)
+ fdec.constraints)}, typms)
}
},
id: ni.id,
}
item_obj(o, typms, d) {
item_obj({fields: vec::map(fold_obj_field, o.fields),
- methods: vec::map(fld.fold_method, o.methods)},
- typms, d)
+ methods: vec::map(fld.fold_method, o.methods)}, typms,
+ d)
}
item_res(dtor, did, typms, cid) {
item_res(fld.fold_fn(dtor), did, typms, cid)
}
fn noop_fold_arm(a: &arm, fld: ast_fold) -> arm {
- ret {pats: vec::map(fld.fold_pat, a.pats),
- body: fld.fold_block(a.body)};
+ ret {pats: vec::map(fld.fold_pat, a.pats), body: fld.fold_block(a.body)};
}
fn noop_fold_pat(p: &pat_, fld: ast_fold) -> pat_ {
pat_tag(fld.fold_path(pth), vec::map(fld.fold_pat, pats))
}
pat_rec(fields, etc) {
- let fs = ~[];
+ let fs = [];
for f: ast::field_pat in fields {
- fs += ~[{ident: f.ident, pat: fld.fold_pat(f.pat)}];
+ fs += [{ident: f.ident, pat: fld.fold_pat(f.pat)}];
}
pat_rec(fs, etc)
}
- pat_tup(elts) {
- pat_tup(vec::map(fld.fold_pat, elts))
- }
+ pat_tup(elts) { pat_tup(vec::map(fld.fold_pat, elts)) }
pat_box(inner) { pat_box(fld.fold_pat(inner)) }
};
}
expr_rec(vec::map(fold_field, fields),
option::map(fld.fold_expr, maybe_expr))
}
- expr_tup(elts) {
- expr_tup(vec::map(fld.fold_expr, elts))
- }
+ expr_tup(elts) { expr_tup(vec::map(fld.fold_expr, elts)) }
expr_call(f, args) {
expr_call(fld.fold_expr(f), fld.map_exprs(fld.fold_expr, args))
}
expr_move(el, er) {
expr_move(fld.fold_expr(el), fld.fold_expr(er))
}
- expr_copy(e) {
- expr_copy(fld.fold_expr(e))
- }
+ expr_copy(e) { expr_copy(fld.fold_expr(e)) }
expr_assign(el, er) {
expr_assign(fld.fold_expr(el), fld.fold_expr(er))
}
fn noop_fold_local(l: &local_, fld: ast_fold) -> local_ {
ret {ty: fld.fold_ty(l.ty),
pat: fld.fold_pat(l.pat),
- init: alt l.init {
- option::none::<initializer>. { l.init }
- option::some::<initializer>(init) {
- option::some::<initializer>({op: init.op,
- expr: fld.fold_expr(init.expr)})
- }
- },
+ init:
+ alt l.init {
+ option::none::<initializer>. { l.init }
+ option::some::<initializer>(init) {
+ option::some::<initializer>({op: init.op,
+ expr: fld.fold_expr(init.expr)})
+ }
+ },
id: l.id};
}
/* temporarily eta-expand because of a compiler bug with using `fn<T>` as a
value */
-fn noop_map_exprs(f: fn(&@expr) -> @expr , es: [@expr]) -> [@expr] {
+fn noop_map_exprs(f: fn(&@expr) -> @expr, es: [@expr]) -> [@expr] {
ret vec::map(f, es);
}
}
fn f_pat(afp: &ast_fold_precursor, f: ast_fold, x: &@pat) -> @pat {
ret @{id: afp.new_id(x.id),
- node: afp.fold_pat(x.node, f), span: afp.new_span(x.span)};
+ node: afp.fold_pat(x.node, f),
+ span: afp.new_span(x.span)};
}
fn f_decl(afp: &ast_fold_precursor, f: ast_fold, x: &@decl) -> @decl {
ret @{node: afp.fold_decl(x.node, f), span: afp.new_span(x.span)};
}
fn f_expr(afp: &ast_fold_precursor, f: ast_fold, x: &@expr) -> @expr {
ret @{id: afp.new_id(x.id),
- node: afp.fold_expr(x.node, f), span: afp.new_span(x.span)};
+ node: afp.fold_expr(x.node, f),
+ span: afp.new_span(x.span)};
}
fn f_ty(afp: &ast_fold_precursor, f: ast_fold, x: &@ty) -> @ty {
ret @{node: afp.fold_ty(x.node, f), span: afp.new_span(x.span)};
cfg: ast::crate_cfg};
fn eval_crate_directives(cx: ctx, cdirs: &[@ast::crate_directive],
- prefix: str,
- view_items: &mutable [@ast::view_item],
+ prefix: str, view_items: &mutable [@ast::view_item],
items: &mutable [@ast::item]) {
for sub_cdir: @ast::crate_directive in cdirs {
eval_crate_directive(cx, sub_cdir, prefix, view_items, items);
fn eval_crate_directives_to_mod(cx: ctx, cdirs: &[@ast::crate_directive],
prefix: str) -> ast::_mod {
- let view_items: [@ast::view_item] = ~[];
- let items: [@ast::item] = ~[];
+ let view_items: [@ast::view_item] = [];
+ let items: [@ast::item] = [];
eval_crate_directives(cx, cdirs, prefix, view_items, items);
ret {view_items: view_items, items: items};
}
if std::fs::path_is_absolute(file_path) {
file_path
} else { prefix + std::fs::path_sep() + file_path };
- if cx.mode == mode_depend { cx.deps += ~[full_path]; ret; }
+ if cx.mode == mode_depend { cx.deps += [full_path]; ret; }
let p0 =
new_parser_from_file(cx.sess, cx.cfg, full_path, cx.chpos,
cx.byte_pos, SOURCE_FILE);
// Thread defids, chpos and byte_pos through the parsers
cx.chpos = p0.get_chpos();
cx.byte_pos = p0.get_byte_pos();
- items += ~[i];
+ items += [i];
}
ast::cdir_dir_mod(id, dir_opt, cdirs, attrs) {
let path = id;
node: ast::item_mod(m0),
span: cdir.span};
cx.sess.next_id += 1;
- items += ~[i];
+ items += [i];
}
- ast::cdir_view_item(vi) { view_items += ~[vi]; }
+ ast::cdir_view_item(vi) { view_items += [vi]; }
ast::cdir_syntax(pth) { }
ast::cdir_auth(pth, eff) { }
}
type reader =
obj {
- fn is_eof() -> bool ;
- fn curr() -> char ;
- fn next() -> char ;
- fn init() ;
- fn bump() ;
- fn get_str_from(uint) -> str ;
- fn get_interner() -> @interner::interner<str> ;
- fn get_chpos() -> uint ;
- fn get_byte_pos() -> uint ;
- fn get_col() -> uint ;
- fn get_filemap() -> codemap::filemap ;
- fn err(str) ;
+ fn is_eof() -> bool;
+ fn curr() -> char;
+ fn next() -> char;
+ fn init();
+ fn bump();
+ fn get_str_from(uint) -> str;
+ fn get_interner() -> @interner::interner<str>;
+ fn get_chpos() -> uint;
+ fn get_byte_pos() -> uint;
+ fn get_col() -> uint;
+ fn get_filemap() -> codemap::filemap;
+ fn err(str);
};
fn new_reader(cm: &codemap::codemap, src: str, filemap: codemap::filemap,
codemap::emit_error(some(ast::mk_sp(chpos, chpos)), m, cm);
}
}
- let strs: [str] = ~[];
+ let strs: [str] = [];
let rd =
reader(cm, src, str::byte_len(src), 0u, 0u, -1 as char,
filemap.start_pos.ch, strs, filemap, itr);
fn digits_to_string(s: str) -> int {
let accum_int: int = 0;
- for c: u8 in s {
- accum_int *= 10;
- accum_int += dec_digit_val(c as char);
- }
+ for c: u8 in s { accum_int *= 10; accum_int += dec_digit_val(c as char); }
ret accum_int;
}
let c = rdr.curr();
let rslt = "";
if c == 'e' || c == 'E' {
- rslt += str::unsafe_from_bytes(~[c as u8]);
+ rslt += str::unsafe_from_bytes([c as u8]);
rdr.bump();
c = rdr.curr();
if c == '-' || c == '+' {
- rslt += str::unsafe_from_bytes(~[c as u8]);
+ rslt += str::unsafe_from_bytes([c as u8]);
rdr.bump();
}
let exponent = scan_dec_digits(rdr);
let c = rdr.curr();
let rslt: str = "";
while is_dec_digit(c) || c == '_' {
- if c != '_' { rslt += str::unsafe_from_bytes(~[c as u8]); }
+ if c != '_' { rslt += str::unsafe_from_bytes([c as u8]); }
rdr.bump();
c = rdr.curr();
}
rdr.bump();
c = rdr.curr();
}
- } else if (c == '0' && n == 'b') {
+ } else if c == '0' && n == 'b' {
rdr.bump();
rdr.bump();
c = rdr.curr();
ret token::LIT_MACH_FLOAT(ast::ty_f32,
intern(*rdr.get_interner(),
float_str));
- } else if (c == '6' && n == '4') {
+ } else if c == '6' && n == '4' {
rdr.bump();
rdr.bump();
ret token::LIT_MACH_FLOAT(ast::ty_f64,
}
} else {
ret token::LIT_FLOAT(interner::intern::<str>(*rdr.get_interner(),
- float_str));
+ float_str));
}
}
let maybe_exponent = scan_exponent(rdr);
alt maybe_exponent {
some(s) {
ret token::LIT_FLOAT(interner::intern::<str>(*rdr.get_interner(),
- dec_str + s));
+ dec_str + s));
}
none. { ret token::LIT_INT(accum_int); }
}
let n = rdr.curr();
rdr.bump();
if !is_hex_digit(n) {
- rdr.err(#fmt("illegal numeric character escape: %d", n as int));
+ rdr.err(#fmt["illegal numeric character escape: %d", n as int]);
fail;
}
accum_int *= 16;
if str::eq(accum_str, "_") { ret token::UNDERSCORE; }
let is_mod_name = c == ':' && rdr.next() == ':';
ret token::IDENT(interner::intern::<str>(*rdr.get_interner(),
- accum_str), is_mod_name);
+ accum_str), is_mod_name);
}
if is_dec_digit(c) { ret scan_number(c, rdr); }
fn binop(rdr: &reader, op: token::binop) -> token::token {
}
alt c {
+
// One-byte tokens.
'?' {
rdr.bump();
} else { ret token::COLON; }
}
+
// Multi-byte tokens.
'=' {
rdr.bump();
'u' { c2 = scan_numeric_escape(rdr, 4u); }
'U' { c2 = scan_numeric_escape(rdr, 8u); }
c2 {
- rdr.err(#fmt("unknown character escape: %d", c2 as int));
+ rdr.err(#fmt["unknown character escape: %d", c2 as int]);
fail;
}
}
str::push_char(accum_str, scan_numeric_escape(rdr, 8u));
}
c2 {
- rdr.err(#fmt("unknown string escape: %d", c2 as int));
+ rdr.err(#fmt["unknown string escape: %d", c2 as int]);
fail;
}
}
}
rdr.bump();
ret token::LIT_STR(interner::intern::<str>(*rdr.get_interner(),
- accum_str));
+ accum_str));
}
'-' {
if rdr.next() == '>' {
'/' { ret binop(rdr, token::SLASH); }
'^' { ret binop(rdr, token::CARET); }
'%' { ret binop(rdr, token::PERCENT); }
- c { rdr.err(#fmt("unkown start of token: %d", c as int)); fail; }
+ c { rdr.err(#fmt["unkown start of token: %d", c as int]); fail; }
}
}
fn read_one_line_comment(rdr: &reader) -> str {
let val = read_to_eol(rdr);
- assert (val.(0) == '/' as u8 && val.(1) == '/' as u8);
+ assert (val[0] == '/' as u8 && val[1] == '/' as u8);
ret val;
}
fn push_blank_line_comment(rdr: &reader, comments: &mutable [cmnt]) {
log ">>> blank-line comment";
- let v: [str] = ~[];
- comments += ~[{style: blank_line, lines: v, pos: rdr.get_chpos()}];
+ let v: [str] = [];
+ comments += [{style: blank_line, lines: v, pos: rdr.get_chpos()}];
}
fn consume_whitespace_counting_blank_lines(rdr: &reader,
fn read_line_comments(rdr: &reader, code_to_the_left: bool) -> cmnt {
log ">>> line comments";
let p = rdr.get_chpos();
- let lines: [str] = ~[];
+ let lines: [str] = [];
while rdr.curr() == '/' && rdr.next() == '/' {
let line = read_one_line_comment(rdr);
log line;
- lines += ~[line];
+ lines += [line];
consume_non_eol_whitespace(rdr);
}
log "<<< line comments";
fn all_whitespace(s: &str, begin: uint, end: uint) -> bool {
let i: uint = begin;
- while i != end {
- if !is_whitespace(s.(i) as char) { ret false; }
- i += 1u;
- }
+ while i != end { if !is_whitespace(s[i] as char) { ret false; } i += 1u; }
ret true;
}
} else { s1 = ""; }
} else { s1 = s; }
log "pushing line: " + s1;
- lines += ~[s1];
+ lines += [s1];
}
fn read_block_comment(rdr: &reader, code_to_the_left: bool) -> cmnt {
log ">>> block comment";
let p = rdr.get_chpos();
- let lines: [str] = ~[];
+ let lines: [str] = [];
let col: uint = rdr.get_col();
rdr.bump();
rdr.bump();
let curr_line = "/*";
let level: int = 1;
while level > 0 {
- log #fmt("=== block comment level %d", level);
+ log #fmt["=== block comment level %d", level];
if rdr.is_eof() { rdr.err("unterminated block comment"); fail; }
if rdr.curr() == '\n' {
trim_whitespace_prefix_and_push_line(lines, curr_line, col);
comments: &mutable [cmnt]) {
log ">>> consume comment";
if rdr.curr() == '/' && rdr.next() == '/' {
- comments += ~[read_line_comments(rdr, code_to_the_left)];
- } else if (rdr.curr() == '/' && rdr.next() == '*') {
- comments += ~[read_block_comment(rdr, code_to_the_left)];
+ comments += [read_line_comments(rdr, code_to_the_left)];
+ } else if rdr.curr() == '/' && rdr.next() == '*' {
+ comments += [read_block_comment(rdr, code_to_the_left)];
} else { fail; }
log "<<< consume comment";
}
let src = str::unsafe_from_bytes(srdr.read_whole_stream());
let itr = @interner::mk::<str>(str::hash, str::eq);
let rdr = new_reader(cm, src, codemap::new_filemap(path, 0u, 0u), itr);
- let comments: [cmnt] = ~[];
- let literals: [lit] = ~[];
+ let comments: [cmnt] = [];
+ let literals: [lit] = [];
let first_read: bool = true;
while !rdr.is_eof() {
while true {
}
let tok = next_token(rdr);
if is_lit(tok.tok) {
- literals += ~[{lit: rdr.get_str_from(tok.bpos), pos: tok.chpos}];
+ literals += [{lit: rdr.get_str_from(tok.bpos), pos: tok.chpos}];
}
log "tok: " + token::to_str(rdr, tok.tok);
first_read = false;
type parser =
obj {
- fn peek() -> token::token ;
- fn bump() ;
- fn swap(token::token, uint, uint) ;
- fn look_ahead(uint) -> token::token ;
- fn fatal(str) -> ! ;
- fn warn(str) ;
- fn restrict(restriction) ;
- fn get_restriction() -> restriction ;
- fn get_file_type() -> file_type ;
- fn get_cfg() -> ast::crate_cfg ;
- fn get_span() -> span ;
- fn get_lo_pos() -> uint ;
- fn get_hi_pos() -> uint ;
- fn get_last_lo_pos() -> uint ;
- fn get_last_hi_pos() -> uint ;
- fn get_prec_table() -> @[op_spec] ;
- fn get_str(token::str_num) -> str ;
- fn get_reader() -> lexer::reader ;
- fn get_filemap() -> codemap::filemap ;
- fn get_bad_expr_words() -> hashmap<str, ()> ;
- fn get_chpos() -> uint ;
- fn get_byte_pos() -> uint ;
- fn get_id() -> node_id ;
- fn get_sess() -> parse_sess ;
+ fn peek() -> token::token;
+ fn bump();
+ fn swap(token::token, uint, uint);
+ fn look_ahead(uint) -> token::token;
+ fn fatal(str) -> ! ;
+ fn warn(str);
+ fn restrict(restriction);
+ fn get_restriction() -> restriction;
+ fn get_file_type() -> file_type;
+ fn get_cfg() -> ast::crate_cfg;
+ fn get_span() -> span;
+ fn get_lo_pos() -> uint;
+ fn get_hi_pos() -> uint;
+ fn get_last_lo_pos() -> uint;
+ fn get_last_hi_pos() -> uint;
+ fn get_prec_table() -> @[op_spec];
+ fn get_str(token::str_num) -> str;
+ fn get_reader() -> lexer::reader;
+ fn get_filemap() -> codemap::filemap;
+ fn get_bad_expr_words() -> hashmap<str, ()>;
+ fn get_chpos() -> uint;
+ fn get_byte_pos() -> uint;
+ fn get_id() -> node_id;
+ fn get_sess() -> parse_sess;
};
-fn new_parser_from_file(sess: parse_sess, cfg:
- ast::crate_cfg, path: str,
- chpos: uint, byte_pos: uint,
- ftype: file_type) -> parser {
+fn new_parser_from_file(sess: parse_sess, cfg: ast::crate_cfg, path: str,
+ chpos: uint, byte_pos: uint, ftype: file_type) ->
+ parser {
let src = io::read_whole_file_str(path);
let filemap = codemap::new_filemap(path, chpos, byte_pos);
- sess.cm.files += ~[filemap];
+ sess.cm.files += [filemap];
let itr = @interner::mk(str::hash, str::eq);
let rdr = lexer::new_reader(sess.cm, src, filemap, itr);
while vec::len(buffer) < distance {
let next = lexer::next_token(rdr);
let sp = ast::mk_sp(next.chpos, rdr.get_chpos());
- buffer = ~[{tok: next.tok, span: sp}] + buffer;
+ buffer = [{tok: next.tok, span: sp}] + buffer;
}
- ret buffer.(distance - 1u).tok;
+ ret buffer[distance - 1u].tok;
}
fn fatal(m: str) -> ! {
codemap::emit_error(some(self.get_span()), m, sess.cm);
let tok0 = lexer::next_token(rdr);
let span0 = ast::mk_sp(tok0.chpos, rdr.get_chpos());
- ret stdio_parser(sess, cfg, ftype, tok0.tok, span0, span0, ~[],
+ ret stdio_parser(sess, cfg, ftype, tok0.tok, span0, span0, [],
UNRESTRICTED, rdr, prec_table(), bad_expr_word_table());
}
} else if p.peek() == token::BINOP(token::LSR) {
p.swap(token::GT, p.get_lo_pos() + 1u, p.get_hi_pos());
} else if p.peek() == token::BINOP(token::ASR) {
- p.swap(token::BINOP(token::LSR), p.get_lo_pos() + 1u,
- p.get_hi_pos());
+ p.swap(token::BINOP(token::LSR), p.get_lo_pos() + 1u, p.get_hi_pos());
} else {
let s: str = "expecting ";
s += token::to_str(p.get_reader(), token::GT);
parse_fn_input_ty, p);
// FIXME: there's no syntax for this right now anyway
// auto constrs = parse_constrs(~[], p);
- let constrs: [@ast::constr] = ~[];
+ let constrs: [@ast::constr] = [];
let output: @ast::ty;
let cf = ast::return;
if p.peek() == token::RARROW {
fn parse_proto(p: &parser) -> ast::proto {
if eat_word(p, "iter") {
ret ast::proto_iter;
- } else if (eat_word(p, "fn")) {
+ } else if eat_word(p, "fn") {
ret ast::proto_fn;
- } else if (eat_word(p, "block")) {
+ } else if eat_word(p, "block") {
ret ast::proto_block;
- } else if (eat_word(p, "pred")) {
+ } else if eat_word(p, "pred") {
ret ast::proto_fn;
} else { unexpected(p, p.peek()); }
}
fn parse_constrs<T>(pser: fn(&parser) -> @ast::constr_general<T>, p: &parser)
-> [@ast::constr_general<T>] {
- let constrs: [@ast::constr_general<T>] = ~[];
+ let constrs: [@ast::constr_general<T>] = [];
while true {
let constr = pser(p);
- constrs += ~[constr];
+ constrs += [constr];
if p.peek() == token::COMMA { p.bump(); } else { break; }
}
constrs
}
fn parse_ty_postfix(orig_t: ast::ty_, p: &parser, colons_before_params: bool)
- -> @ast::ty {
+ -> @ast::ty {
let lo = p.get_lo_pos();
if colons_before_params && p.peek() == token::MOD_SEP {
expect(p, token::LT);
} else if !colons_before_params && p.peek() == token::LT {
p.bump();
- } else {
- ret @spanned(lo, p.get_lo_pos(), orig_t);
- }
+ } else { ret @spanned(lo, p.get_lo_pos(), orig_t); }
// If we're here, we have explicit type parameter instantiation.
let seq = parse_seq_to_gt(some(token::COMMA), bind parse_ty(_, false), p);
idents: pth.node.idents,
types: seq}), ann));
}
- _ {
- p.fatal("type parameter instantiation only allowed for paths");
- }
+ _ { p.fatal("type parameter instantiation only allowed for paths"); }
}
}
if eat_word(p, "bool") {
t = ast::ty_bool;
- } else if (eat_word(p, "int")) {
+ } else if eat_word(p, "int") {
t = ast::ty_int;
- } else if (eat_word(p, "uint")) {
+ } else if eat_word(p, "uint") {
t = ast::ty_uint;
- } else if (eat_word(p, "float")) {
+ } else if eat_word(p, "float") {
t = ast::ty_float;
- } else if (eat_word(p, "str")) {
+ } else if eat_word(p, "str") {
t = ast::ty_str;
- } else if (eat_word(p, "istr")) {
+ } else if eat_word(p, "istr") {
t = ast::ty_istr;
- } else if (eat_word(p, "char")) {
+ } else if eat_word(p, "char") {
t = ast::ty_char;
-/*
- } else if (eat_word(p, "task")) {
- t = ast::ty_task;
-*/
- } else if (eat_word(p, "i8")) {
+ /*
+ } else if (eat_word(p, "task")) {
+ t = ast::ty_task;
+ */
+ } else if eat_word(p, "i8") {
t = ast::ty_machine(ast::ty_i8);
- } else if (eat_word(p, "i16")) {
+ } else if eat_word(p, "i16") {
t = ast::ty_machine(ast::ty_i16);
- } else if (eat_word(p, "i32")) {
+ } else if eat_word(p, "i32") {
t = ast::ty_machine(ast::ty_i32);
- } else if (eat_word(p, "i64")) {
+ } else if eat_word(p, "i64") {
t = ast::ty_machine(ast::ty_i64);
- } else if (eat_word(p, "u8")) {
+ } else if eat_word(p, "u8") {
t = ast::ty_machine(ast::ty_u8);
- } else if (eat_word(p, "u16")) {
+ } else if eat_word(p, "u16") {
t = ast::ty_machine(ast::ty_u16);
- } else if (eat_word(p, "u32")) {
+ } else if eat_word(p, "u32") {
t = ast::ty_machine(ast::ty_u32);
- } else if (eat_word(p, "u64")) {
+ } else if eat_word(p, "u64") {
t = ast::ty_machine(ast::ty_u64);
- } else if (eat_word(p, "f32")) {
+ } else if eat_word(p, "f32") {
t = ast::ty_machine(ast::ty_f32);
- } else if (eat_word(p, "f64")) {
+ } else if eat_word(p, "f64") {
t = ast::ty_machine(ast::ty_f64);
- } else if (p.peek() == token::LPAREN) {
+ } else if p.peek() == token::LPAREN {
p.bump();
if p.peek() == token::RPAREN {
hi = p.get_hi_pos();
p.bump();
t = ast::ty_nil;
} else {
- let ts = ~[parse_ty(p, false)];
+ let ts = [parse_ty(p, false)];
while p.peek() == token::COMMA {
p.bump();
- ts += ~[parse_ty(p, false)];
+ ts += [parse_ty(p, false)];
}
if vec::len(ts) == 1u {
- t = ts.(0).node;
- } else {
- t = ast::ty_tup(ts);
- }
+ t = ts[0].node;
+ } else { t = ast::ty_tup(ts); }
hi = p.get_hi_pos();
expect(p, token::RPAREN);
}
- } else if (p.peek() == token::AT) {
+ } else if p.peek() == token::AT {
p.bump();
let mt = parse_mt(p);
hi = mt.ty.span.hi;
t = ast::ty_box(mt);
- } else if (p.peek() == token::BINOP(token::STAR)) {
+ } else if p.peek() == token::BINOP(token::STAR) {
p.bump();
let mt = parse_mt(p);
hi = mt.ty.span.hi;
t = ast::ty_ptr(mt);
- } else if (p.peek() == token::LBRACE) {
+ } else if p.peek() == token::LBRACE {
let elems =
parse_seq(token::LBRACE, token::RBRACE, some(token::COMMA),
parse_ty_field, p);
ast::ty_constr(@spanned(lo, hi, t),
parse_type_constraints(p));
}
- } else if (p.peek() == token::LBRACKET) {
+ } else if p.peek() == token::LBRACKET {
expect(p, token::LBRACKET);
t = ast::ty_vec(parse_mt(p));
hi = p.get_hi_pos();
expect(p, token::RBRACKET);
- } else if (eat_word(p, "fn")) {
+ } else if eat_word(p, "fn") {
t = parse_ty_fn(ast::proto_fn, p);
alt t { ast::ty_fn(_, _, out, _, _) { hi = out.span.hi; } }
- } else if (eat_word(p, "block")) {
+ } else if eat_word(p, "block") {
t = parse_ty_fn(ast::proto_block, p);
alt t { ast::ty_fn(_, _, out, _, _) { hi = out.span.hi; } }
- } else if (eat_word(p, "iter")) {
+ } else if eat_word(p, "iter") {
t = parse_ty_fn(ast::proto_iter, p);
alt t { ast::ty_fn(_, _, out, _, _) { hi = out.span.hi; } }
- } else if (eat_word(p, "obj")) {
+ } else if eat_word(p, "obj") {
t = parse_ty_obj(p, hi);
- } else if (eat_word(p, "mutable")) {
+ } else if eat_word(p, "mutable") {
p.warn("ignoring deprecated 'mutable' type constructor");
let typ = parse_ty(p, false);
t = typ.node;
hi = typ.span.hi;
- } else if (p.peek() == token::MOD_SEP || is_ident(p.peek())) {
+ } else if p.peek() == token::MOD_SEP || is_ident(p.peek()) {
let path = parse_path(p);
t = ast::ty_path(path, p.get_id());
hi = path.span.hi;
ast::alias(eat_word(p, "mutable"))
} else if eat(p, token::BINOP(token::MINUS)) {
ast::move
- } else {
- ast::val
- }
+ } else { ast::val }
}
fn parse_arg(p: &parser) -> ast::arg {
fn parse_seq_to_before_gt<T>(sep: option::t<token::token>,
f: fn(&parser) -> T, p: &parser) -> [T] {
let first = true;
- let v = ~[];
- while p.peek() != token::GT &&
- p.peek() != token::BINOP(token::LSR) &&
- p.peek() != token::BINOP(token::ASR) {
+ let v = [];
+ while p.peek() != token::GT && p.peek() != token::BINOP(token::LSR) &&
+ p.peek() != token::BINOP(token::ASR) {
alt sep {
some(t) { if first { first = false; } else { expect(p, t); } }
_ { }
}
- v += ~[f(p)];
+ v += [f(p)];
}
ret v;
}
fn parse_seq_to_end<T>(ket: token::token, sep: option::t<token::token>,
- f: fn(&parser) -> T , p: &parser) -> [T] {
+ f: fn(&parser) -> T, p: &parser) -> [T] {
let val = parse_seq_to_before_end(ket, sep, f, p);
p.bump();
ret val;
}
fn parse_seq_to_before_end<T>(ket: token::token, sep: option::t<token::token>,
- f: fn(&parser) -> T , p: &parser) -> [T] {
+ f: fn(&parser) -> T, p: &parser) -> [T] {
let first: bool = true;
- let v: [T] = ~[];
+ let v: [T] = [];
while p.peek() != ket {
alt sep {
some(t) { if first { first = false; } else { expect(p, t); } }
_ { }
}
- v += ~[f(p)];
+ v += [f(p)];
}
ret v;
}
fn parse_seq<T>(bra: token::token, ket: token::token,
- sep: option::t<token::token>, f: fn(&parser) -> T ,
- p: &parser) -> spanned<[T]> {
+ sep: option::t<token::token>, f: fn(&parser) -> T, p: &parser)
+ -> spanned<[T]> {
let lo = p.get_lo_pos();
expect(p, bra);
let result = parse_seq_to_before_end::<T>(ket, sep, f, p);
let lit: ast::lit_ = ast::lit_nil;
if eat_word(p, "true") {
lit = ast::lit_bool(true);
- } else if (eat_word(p, "false")) {
+ } else if eat_word(p, "false") {
lit = ast::lit_bool(false);
} else {
alt p.peek() {
p.bump();
} else { global = false; }
- let ids: [ast::ident] = ~[];
+ let ids: [ast::ident] = [];
while true {
alt p.peek() {
token::IDENT(i, _) {
hi = p.get_hi_pos();
- ids += ~[p.get_str(i)];
+ ids += [p.get_str(i)];
hi = p.get_hi_pos();
p.bump();
if p.peek() == token::MOD_SEP && p.look_ahead(1u) != token::LT {
p.bump();
- } else {
- break;
- }
+ } else { break; }
}
_ { break; }
}
}
- ret spanned(lo, hi, {global: global, idents: ids, types: ~[]});
+ ret spanned(lo, hi, {global: global, idents: ids, types: []});
}
fn parse_path_and_ty_param_substs(p: &parser) -> ast::path {
if p.peek() == token::MOD_SEP {
p.bump();
- let seq = parse_seq_lt_gt(some(token::COMMA), bind parse_ty(_, false),
- p);
+ let seq =
+ parse_seq_lt_gt(some(token::COMMA), bind parse_ty(_, false), p);
let hi = seq.span.hi;
path =
spanned(lo, hi,
let lit = @spanned(lo, hi, ast::lit_nil);
ret mk_expr(p, lo, hi, ast::expr_lit(lit));
}
- let es = ~[parse_expr(p)];
- while p.peek() == token::COMMA {
- p.bump();
- es += ~[parse_expr(p)];
- }
+ let es = [parse_expr(p)];
+ while p.peek() == token::COMMA { p.bump(); es += [parse_expr(p)]; }
hi = p.get_hi_pos();
expect(p, token::RPAREN);
if vec::len(es) == 1u {
- ret mk_expr(p, lo, hi, es.(0).node);
- } else {
- ret mk_expr(p, lo, hi, ast::expr_tup(es));
- }
- } else if (p.peek() == token::LBRACE) {
+ ret mk_expr(p, lo, hi, es[0].node);
+ } else { ret mk_expr(p, lo, hi, ast::expr_tup(es)); }
+ } else if p.peek() == token::LBRACE {
p.bump();
if is_word(p, "mutable") ||
is_plain_ident(p) && p.look_ahead(1u) == token::COLON {
- let fields = ~[parse_field(p, token::COLON)];
+ let fields = [parse_field(p, token::COLON)];
let base = none;
while p.peek() != token::RBRACE {
if eat_word(p, "with") { base = some(parse_expr(p)); break; }
expect(p, token::COMMA);
- fields += ~[parse_field(p, token::COLON)];
+ fields += [parse_field(p, token::COLON)];
}
hi = p.get_hi_pos();
expect(p, token::RBRACE);
let blk = parse_block_tail(p, lo);
ret mk_expr(p, blk.span.lo, blk.span.hi, ast::expr_block(blk));
}
- } else if (eat_word(p, "if")) {
+ } else if eat_word(p, "if") {
ret parse_if_expr(p);
- } else if (eat_word(p, "for")) {
+ } else if eat_word(p, "for") {
ret parse_for_expr(p);
- } else if (eat_word(p, "while")) {
+ } else if eat_word(p, "while") {
ret parse_while_expr(p);
- } else if (eat_word(p, "do")) {
+ } else if eat_word(p, "do") {
ret parse_do_while_expr(p);
- } else if (eat_word(p, "alt")) {
+ } else if eat_word(p, "alt") {
ret parse_alt_expr(p);
-/*
- } else if (eat_word(p, "spawn")) {
- ret parse_spawn_expr(p);
-*/
- } else if (eat_word(p, "fn")) {
+ /*
+ } else if (eat_word(p, "spawn")) {
+ ret parse_spawn_expr(p);
+ */
+ } else if eat_word(p, "fn") {
ret parse_fn_expr(p, ast::proto_fn);
- } else if (eat_word(p, "block")) {
+ } else if eat_word(p, "block") {
ret parse_fn_expr(p, ast::proto_block);
- } else if (eat_word(p, "lambda")) {
+ } else if eat_word(p, "lambda") {
ret parse_fn_expr(p, ast::proto_closure);
- } else if (p.peek() == token::LBRACKET) {
+ } else if p.peek() == token::LBRACKET {
p.bump();
let mut = parse_mutability(p);
let es =
parse_seq_to_end(token::RBRACKET, some(token::COMMA), parse_expr,
p);
ex = ast::expr_vec(es, mut);
- } else if (p.peek() == token::POUND_LT) {
+ } else if p.peek() == token::POUND_LT {
p.bump();
let ty = parse_ty(p, false);
expect(p, token::GT);
/* hack: early return to take advantage of specialized function */
ret mk_mac_expr(p, lo, p.get_hi_pos(), ast::mac_embed_type(ty))
- } else if (p.peek() == token::POUND_LBRACE) {
+ } else if p.peek() == token::POUND_LBRACE {
p.bump();
let blk = ast::mac_embed_block(parse_block_tail(p, lo));
ret mk_mac_expr(p, lo, p.get_hi_pos(), blk);
- } else if (p.peek() == token::ELLIPSIS) {
+ } else if p.peek() == token::ELLIPSIS {
p.bump();
ret mk_mac_expr(p, lo, p.get_hi_pos(), ast::mac_ellipsis)
- } else if (p.peek() == token::TILDE) {
+ } else if p.peek() == token::TILDE {
p.bump();
alt p.peek() {
token::LBRACKET. { // unique array (temporary)
}
_ { ex = ast::expr_uniq(parse_expr(p)); }
}
- } else if (eat_word(p, "obj")) {
+ } else if eat_word(p, "obj") {
// Anonymous object
// Only make people type () if they're actually adding new fields
some(parse_seq_to_end(token::RPAREN, some(token::COMMA),
parse_anon_obj_field, p));
}
- let meths: [@ast::method] = ~[];
+ let meths: [@ast::method] = [];
let inner_obj: option::t<@ast::expr> = none;
expect(p, token::LBRACE);
while p.peek() != token::RBRACE {
if eat_word(p, "with") {
inner_obj = some(parse_expr(p));
- } else { meths += ~[parse_method(p)]; }
+ } else { meths += [parse_method(p)]; }
}
hi = p.get_hi_pos();
expect(p, token::RBRACE);
// "spanned".
let ob = {fields: fields, methods: meths, inner_obj: inner_obj};
ex = ast::expr_anon_obj(ob);
- } else if (eat_word(p, "bind")) {
+ } else if eat_word(p, "bind") {
let e = parse_expr_res(p, RESTRICT_NO_CALL_EXPRS);
fn parse_expr_opt(p: &parser) -> option::t<@ast::expr> {
alt p.peek() {
parse_expr_opt, p);
hi = es.span.hi;
ex = ast::expr_bind(e, es.node);
- } else if (p.peek() == token::POUND) {
+ } else if p.peek() == token::POUND {
let ex_ext = parse_syntax_ext(p);
hi = ex_ext.span.hi;
ex = ex_ext.node;
- } else if (eat_word(p, "fail")) {
+ } else if eat_word(p, "fail") {
if can_begin_expr(p.peek()) {
let e = parse_expr(p);
hi = e.span.hi;
ex = ast::expr_fail(some(e));
} else { ex = ast::expr_fail(none); }
- } else if (eat_word(p, "log")) {
+ } else if eat_word(p, "log") {
let e = parse_expr(p);
ex = ast::expr_log(1, e);
hi = e.span.hi;
- } else if (eat_word(p, "log_err")) {
+ } else if eat_word(p, "log_err") {
let e = parse_expr(p);
ex = ast::expr_log(0, e);
hi = e.span.hi;
- } else if (eat_word(p, "assert")) {
+ } else if eat_word(p, "assert") {
let e = parse_expr(p);
ex = ast::expr_assert(e);
hi = e.span.hi;
- } else if (eat_word(p, "check")) {
+ } else if eat_word(p, "check") {
/* Should be a predicate (pure boolean function) applied to
arguments that are all either slot variables or literals.
but the typechecker enforces that. */
let e = parse_expr(p);
hi = e.span.hi;
ex = ast::expr_check(ast::checked, e);
- } else if (eat_word(p, "claim")) {
+ } else if eat_word(p, "claim") {
/* Same rules as check, except that if check-claims
is enabled (a command-line flag), then the parser turns
claims into check */
let e = parse_expr(p);
hi = e.span.hi;
ex = ast::expr_check(ast::unchecked, e);
- } else if (eat_word(p, "ret")) {
+ } else if eat_word(p, "ret") {
if can_begin_expr(p.peek()) {
let e = parse_expr(p);
hi = e.span.hi;
ex = ast::expr_ret(some(e));
} else { ex = ast::expr_ret(none); }
- } else if (eat_word(p, "break")) {
+ } else if eat_word(p, "break") {
ex = ast::expr_break;
hi = p.get_hi_pos();
- } else if (eat_word(p, "cont")) {
+ } else if eat_word(p, "cont") {
ex = ast::expr_cont;
hi = p.get_hi_pos();
- } else if (eat_word(p, "put")) {
+ } else if eat_word(p, "put") {
alt p.peek() {
token::SEMI. { ex = ast::expr_put(none); }
_ {
ex = ast::expr_put(some(e));
}
}
- } else if (eat_word(p, "be")) {
+ } else if eat_word(p, "be") {
let e = parse_expr(p);
+
// FIXME: Is this the right place for this check?
if /*check*/ast::is_call_expr(e) {
hi = e.span.hi;
ex = ast::expr_be(e);
} else { p.fatal("Non-call expression in tail call"); }
- } else if (eat_word(p, "copy")) {
+ } else if eat_word(p, "copy") {
let e = parse_expr(p);
ex = ast::expr_copy(e);
hi = e.span.hi;
- } else if (eat_word(p, "self")) {
+ } else if eat_word(p, "self") {
expect(p, token::DOT);
// The rest is a call expression.
let f: @ast::expr = parse_self_method(p);
parse_expr, p);
hi = es.span.hi;
ex = ast::expr_call(f, es.node);
- } else if (p.peek() == token::MOD_SEP ||
- is_ident(p.peek()) && !is_word(p, "true") &&
- !is_word(p, "false")) {
+ } else if p.peek() == token::MOD_SEP ||
+ is_ident(p.peek()) && !is_word(p, "true") &&
+ !is_word(p, "false") {
check_bad_word(p);
let pth = parse_path_and_ty_param_substs(p);
hi = pth.span.hi;
p.fatal("expected a syntax expander name");
}
//temporary for a backwards-compatible cycle:
- let es = if p.peek() == token::LPAREN {
- parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA),
- parse_expr, p)
- } else {
- parse_seq(token::LBRACKET, token::RBRACKET, some(token::COMMA),
- parse_expr, p)
- };
+ let es =
+ if p.peek() == token::LPAREN {
+ parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA),
+ parse_expr, p)
+ } else {
+ parse_seq(token::LBRACKET, token::RBRACKET, some(token::COMMA),
+ parse_expr, p)
+ };
let hi = es.span.hi;
- let e = mk_expr(p, es.span.lo, hi,
- ast::expr_vec(es.node, ast::imm));
+ let e = mk_expr(p, es.span.lo, hi, ast::expr_vec(es.node, ast::imm));
ret mk_mac_expr(p, lo, hi, ast::mac_invoc(pth, e, none));
}
// FIXME make this a const, don't store it in parser state
fn prec_table() -> @[op_spec] {
- ret @~[{tok: token::BINOP(token::STAR), op: ast::mul, prec: 11},
- {tok: token::BINOP(token::SLASH), op: ast::div, prec: 11},
- {tok: token::BINOP(token::PERCENT), op: ast::rem, prec: 11},
- {tok: token::BINOP(token::PLUS), op: ast::add, prec: 10},
- {tok: token::BINOP(token::MINUS), op: ast::sub, prec: 10},
- {tok: token::BINOP(token::LSL), op: ast::lsl, prec: 9},
- {tok: token::BINOP(token::LSR), op: ast::lsr, prec: 9},
- {tok: token::BINOP(token::ASR), op: ast::asr, prec: 9},
- {tok: token::BINOP(token::AND), op: ast::bitand, prec: 8},
- {tok: token::BINOP(token::CARET), op: ast::bitxor, prec: 6},
- {tok: token::BINOP(token::OR), op: ast::bitor, prec: 6},
- // 'as' sits between here with 5
- {tok: token::LT, op: ast::lt, prec: 4},
- {tok: token::LE, op: ast::le, prec: 4},
- {tok: token::GE, op: ast::ge, prec: 4},
- {tok: token::GT, op: ast::gt, prec: 4},
- {tok: token::EQEQ, op: ast::eq, prec: 3},
- {tok: token::NE, op: ast::ne, prec: 3},
- {tok: token::ANDAND, op: ast::and, prec: 2},
- {tok: token::OROR, op: ast::or, prec: 1}];
+ ret @[{tok: token::BINOP(token::STAR), op: ast::mul, prec: 11},
+ {tok: token::BINOP(token::SLASH), op: ast::div, prec: 11},
+ {tok: token::BINOP(token::PERCENT), op: ast::rem, prec: 11},
+ {tok: token::BINOP(token::PLUS), op: ast::add, prec: 10},
+ {tok: token::BINOP(token::MINUS), op: ast::sub, prec: 10},
+ {tok: token::BINOP(token::LSL), op: ast::lsl, prec: 9},
+ {tok: token::BINOP(token::LSR), op: ast::lsr, prec: 9},
+ {tok: token::BINOP(token::ASR), op: ast::asr, prec: 9},
+ {tok: token::BINOP(token::AND), op: ast::bitand, prec: 8},
+ {tok: token::BINOP(token::CARET), op: ast::bitxor, prec: 6},
+ {tok: token::BINOP(token::OR), op: ast::bitor, prec: 6},
+ // 'as' sits between here with 5
+ {tok: token::LT, op: ast::lt, prec: 4},
+ {tok: token::LE, op: ast::le, prec: 4},
+ {tok: token::GE, op: ast::ge, prec: 4},
+ {tok: token::GT, op: ast::gt, prec: 4},
+ {tok: token::EQEQ, op: ast::eq, prec: 3},
+ {tok: token::NE, op: ast::ne, prec: 3},
+ {tok: token::ANDAND, op: ast::and, prec: 2},
+ {tok: token::OROR, op: ast::or, prec: 1}];
}
fn parse_binops(p: &parser) -> @ast::expr {
let lo = p.get_last_lo_pos();
let discriminant = parse_expr(p);
expect(p, token::LBRACE);
- let arms: [ast::arm] = ~[];
+ let arms: [ast::arm] = [];
while p.peek() != token::RBRACE {
let pats = parse_pats(p);
let blk = parse_block(p);
- arms += ~[{pats: pats, body: blk}];
+ arms += [{pats: pats, body: blk}];
}
let hi = p.get_hi_pos();
p.bump();
ret some({op: ast::init_move, expr: parse_expr(p)});
}
+
// Now that the the channel is the first argument to receive,
// combining it with an initializer doesn't really make sense.
// case (token::RECV) {
}
fn parse_pats(p: &parser) -> [@ast::pat] {
- let pats = ~[];
+ let pats = [];
while true {
- pats += ~[parse_pat(p)];
+ pats += [parse_pat(p)];
if p.peek() == token::BINOP(token::OR) { p.bump(); } else { break; }
}
ret pats;
}
token::LBRACE. {
p.bump();
- let fields = ~[];
+ let fields = [];
let etc = false;
let first = true;
while p.peek() != token::RBRACE {
node: ast::pat_bind(fieldname),
span: ast::mk_sp(lo, hi)};
}
- fields += ~[{ident: fieldname, pat: subpat}];
+ fields += [{ident: fieldname, pat: subpat}];
}
hi = p.get_hi_pos();
p.bump();
if p.peek() == token::RPAREN {
hi = p.get_hi_pos();
p.bump();
- pat = ast::pat_lit(@{node: ast::lit_nil,
- span: ast::mk_sp(lo,hi)});
+ pat =
+ ast::pat_lit(@{node: ast::lit_nil, span: ast::mk_sp(lo, hi)});
} else {
- let fields = ~[parse_pat(p)];
+ let fields = [parse_pat(p)];
while p.peek() == token::COMMA {
p.bump();
- fields += ~[parse_pat(p)];
+ fields += [parse_pat(p)];
}
if vec::len(fields) == 1u { expect(p, token::COMMA); }
hi = p.get_hi_pos();
let lit = parse_lit(p);
hi = lit.span.hi;
pat = ast::pat_lit(@lit);
- } else if (is_plain_ident(p) &&
- alt p.look_ahead(1u) {
- token::DOT. | token::LPAREN. | token::LBRACKET. {
- false
- }
- _ { true }
- }) {
+ } else if is_plain_ident(p) &&
+ alt p.look_ahead(1u) {
+ token::DOT. | token::LPAREN. | token::LBRACKET. {
+ false
+ }
+ _ { true }
+ } {
hi = p.get_hi_pos();
pat = ast::pat_bind(parse_value_ident(p));
} else {
args = a.node;
hi = a.span.hi;
}
- token::DOT. { args = ~[]; p.bump(); }
+ token::DOT. { args = []; p.bump(); }
_ { expect(p, token::LPAREN); fail; }
}
pat = ast::pat_tag(tag_path, args);
if eat(p, token::COLON) { ty = parse_ty(p, false); }
let init = if allow_init { parse_initializer(p) } else { none };
ret @spanned(lo, p.get_last_hi_pos(),
- {ty: ty,
- pat: pat,
- init: init,
- id: p.get_id()});
+ {ty: ty, pat: pat, init: init, id: p.get_id()});
}
fn parse_let(p: &parser) -> @ast::decl {
let lo = p.get_lo_pos();
- let locals = ~[parse_local(p, true)];
+ let locals = [parse_local(p, true)];
while p.peek() == token::COMMA {
p.bump();
- locals += ~[parse_local(p, true)];
+ locals += [parse_local(p, true)];
}
ret @spanned(lo, p.get_last_hi_pos(), ast::decl_local(locals));
}
}
fn parse_crate_stmt(p: &parser) -> @ast::stmt {
- let cdir = parse_crate_directive(p, ~[]);
+ let cdir = parse_crate_directive(p, []);
ret @spanned(cdir.span.lo, cdir.span.hi,
ast::stmt_crate_directive(@cdir));
}
let item_attrs;
alt parse_outer_attrs_or_ext(p) {
- none. { item_attrs = ~[]; }
+ none. { item_attrs = []; }
some(left(attrs)) { item_attrs = attrs; }
some(right(ext)) {
ret @spanned(lo, ext.span.hi, ast::stmt_expr(ext, p.get_id()));
}
}
+
// We should not be calling this on a cdir.
ast::stmt_crate_directive(cdir) {
fail;
// some blocks start with "#{"...
fn parse_block_tail(p: &parser, lo: uint) -> ast::blk {
- let stmts: [@ast::stmt] = ~[];
+ let stmts: [@ast::stmt] = [];
let expr: option::t<@ast::expr> = none;
while p.peek() != token::RBRACE {
alt p.peek() {
alt stmt_to_expr(stmt) {
some(e) {
alt p.peek() {
- token::SEMI. { p.bump(); stmts += ~[stmt]; }
+ token::SEMI. { p.bump(); stmts += [stmt]; }
token::RBRACE. { expr = some(e); }
t {
if stmt_ends_with_semi(*stmt) {
"expression but found " +
token::to_str(p.get_reader(), t));
}
- stmts += ~[stmt];
+ stmts += [stmt];
}
}
}
none. {
// Not an expression statement.
- stmts += ~[stmt];
+ stmts += [stmt];
if p.get_file_type() == SOURCE_FILE &&
}
fn parse_ty_param(p: &parser) -> ast::ty_param {
- let k = alt p.peek() {
- token::TILDE. { p.bump(); ast::kind_unique }
- token::AT. { p.bump(); ast::kind_shared }
- _ { ast::kind_pinned }
- };
+ let k =
+ alt p.peek() {
+ token::TILDE. { p.bump(); ast::kind_unique }
+ token::AT. { p.bump(); ast::kind_shared }
+ _ { ast::kind_pinned }
+ };
ret {ident: parse_ident(p), kind: k};
}
fn parse_ty_params(p: &parser) -> [ast::ty_param] {
- let ty_params: [ast::ty_param] = ~[];
+ let ty_params: [ast::ty_param] = [];
if p.peek() == token::LT {
p.bump();
ty_params = parse_seq_to_gt(some(token::COMMA), parse_ty_param, p);
ret ty_params;
}
-fn parse_fn_decl(p: &parser, purity: ast::purity, il: ast::inlineness)
- -> ast::fn_decl {
+fn parse_fn_decl(p: &parser, purity: ast::purity, il: ast::inlineness) ->
+ ast::fn_decl {
let inputs: ast::spanned<[ast::arg]> =
parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA), parse_arg,
p);
// Use the args list to translate each bound variable
// mentioned in a constraint to an arg index.
// Seems weird to do this in the parser, but I'm not sure how else to.
- let constrs = ~[];
+ let constrs = [];
if p.peek() == token::COLON {
p.bump();
constrs = parse_constrs(bind parse_ty_constr(inputs.node, _), p);
purity: ast::impure_fn,
il: ast::il_normal,
cf: ast::return,
- constraints: ~[]};
+ constraints: []};
}
fn parse_fn(p: &parser, proto: ast::proto, purity: ast::purity,
}
fn parse_item_fn_or_iter(p: &parser, purity: ast::purity, proto: ast::proto,
- attrs: &[ast::attribute], il: ast::inlineness)
- -> @ast::item {
+ attrs: &[ast::attribute], il: ast::inlineness) ->
+ @ast::item {
let lo = p.get_last_lo_pos();
let t = parse_fn_header(p);
let f = parse_fn(p, proto, purity, il);
ret @spanned(lo, f.body.span.hi, meth);
}
-fn parse_item_obj(p: &parser, attrs: &[ast::attribute]) ->
- @ast::item {
+fn parse_item_obj(p: &parser, attrs: &[ast::attribute]) -> @ast::item {
let lo = p.get_last_lo_pos();
let ident = parse_value_ident(p);
let ty_params = parse_ty_params(p);
let fields: ast::spanned<[ast::obj_field]> =
parse_seq(token::LPAREN, token::RPAREN, some(token::COMMA),
parse_obj_field, p);
- let meths: [@ast::method] = ~[];
+ let meths: [@ast::method] = [];
expect(p, token::LBRACE);
- while p.peek() != token::RBRACE {
- meths += ~[parse_method(p)];
- }
+ while p.peek() != token::RBRACE { meths += [parse_method(p)]; }
let hi = p.get_hi_pos();
expect(p, token::RBRACE);
let ob: ast::_obj = {fields: fields.node, methods: meths};
attrs);
}
-fn parse_item_res(p: &parser, attrs: &[ast::attribute]) ->
- @ast::item {
+fn parse_item_res(p: &parser, attrs: &[ast::attribute]) -> @ast::item {
let lo = p.get_last_lo_pos();
let ident = parse_value_ident(p);
let ty_params = parse_ty_params(p);
let dtor = parse_block(p);
let decl =
{inputs:
- ~[{mode: ast::alias(false),
- ty: t,
- ident: arg_ident,
- id: p.get_id()}],
+ [{mode: ast::alias(false),
+ ty: t,
+ ident: arg_ident,
+ id: p.get_id()}],
output: @spanned(lo, lo, ast::ty_nil),
purity: ast::impure_fn,
il: ast::il_normal,
cf: ast::return,
- constraints: ~[]};
+ constraints: []};
let f = {decl: decl, proto: ast::proto_fn, body: dtor};
ret mk_item(p, lo, dtor.span.hi, ident,
ast::item_res(f, p.get_id(), ty_params, p.get_id()), attrs);
first_item_attrs: &[ast::attribute]) -> ast::_mod {
// Shouldn't be any view items since we've already parsed an item attr
let view_items =
- if vec::len(first_item_attrs) == 0u { parse_view(p) } else { ~[] };
- let items: [@ast::item] = ~[];
+ if vec::len(first_item_attrs) == 0u { parse_view(p) } else { [] };
+ let items: [@ast::item] = [];
let initial_attrs = first_item_attrs;
while p.peek() != term {
let attrs = initial_attrs + parse_outer_attributes(p);
- initial_attrs = ~[];
+ initial_attrs = [];
alt parse_item(p, attrs) {
- some(i) { items += ~[i]; }
+ some(i) { items += [i]; }
_ {
p.fatal("expected item but found " +
token::to_str(p.get_reader(), p.peek()));
@ast::native_item {
if eat_word(p, "type") {
ret parse_item_native_type(p, attrs);
- } else if (eat_word(p, "fn")) {
+ } else if eat_word(p, "fn") {
ret parse_item_native_fn(p, attrs);
} else { unexpected(p, p.peek()); }
}
fn parse_native_mod_items(p: &parser, native_name: &str, abi: ast::native_abi,
- first_item_attrs: &[ast::attribute])
- -> ast::native_mod {
+ first_item_attrs: &[ast::attribute]) ->
+ ast::native_mod {
// Shouldn't be any view items since we've already parsed an item attr
let view_items =
if vec::len(first_item_attrs) == 0u {
parse_native_view(p)
- } else { ~[] };
- let items: [@ast::native_item] = ~[];
+ } else { [] };
+ let items: [@ast::native_item] = [];
let initial_attrs = first_item_attrs;
while p.peek() != token::RBRACE {
let attrs = initial_attrs + parse_outer_attributes(p);
- initial_attrs = ~[];
- items += ~[parse_native_item(p, attrs)];
+ initial_attrs = [];
+ items += [parse_native_item(p, attrs)];
}
ret {native_name: native_name,
abi: abi,
if !is_word(p, "mod") {
let t = parse_str(p);
if str::eq(t, "cdecl") {
- } else if (str::eq(t, "rust")) {
+ } else if str::eq(t, "rust") {
abi = ast::native_abi_rust;
- } else if (str::eq(t, "llvm")) {
+ } else if str::eq(t, "llvm") {
abi = ast::native_abi_llvm;
- } else if (str::eq(t, "rust-intrinsic")) {
+ } else if str::eq(t, "rust-intrinsic") {
abi = ast::native_abi_rust_intrinsic;
- } else if (str::eq(t, "x86stdcall")) {
+ } else if str::eq(t, "x86stdcall") {
abi = ast::native_abi_x86stdcall;
} else { p.fatal("unsupported abi: " + t); }
}
let lo = p.get_last_lo_pos();
let id = parse_ident(p);
let ty_params = parse_ty_params(p);
- let variants: [ast::variant] = ~[];
+ let variants: [ast::variant] = [];
// Newtype syntax
if p.peek() == token::EQ {
if p.get_bad_expr_words().contains_key(id) {
let variant =
spanned(ty.span.lo, ty.span.hi,
{name: id,
- args: ~[{ty: ty, id: p.get_id()}],
+ args: [{ty: ty, id: p.get_id()}],
id: p.get_id()});
ret mk_item(p, lo, ty.span.hi, id,
- ast::item_tag(~[variant], ty_params), attrs);
+ ast::item_tag([variant], ty_params), attrs);
}
expect(p, token::LBRACE);
while p.peek() != token::RBRACE {
check_bad_word(p);
let vlo = p.get_lo_pos();
p.bump();
- let args: [ast::variant_arg] = ~[];
+ let args: [ast::variant_arg] = [];
let vhi = p.get_hi_pos();
alt p.peek() {
token::LPAREN. {
parse_seq(token::LPAREN, token::RPAREN,
some(token::COMMA), bind parse_ty(_, false), p);
for ty: @ast::ty in arg_tys.node {
- args += ~[{ty: ty, id: p.get_id()}];
+ args += [{ty: ty, id: p.get_id()}];
}
vhi = arg_tys.span.hi;
}
expect(p, token::SEMI);
p.get_id();
let vr = {name: p.get_str(name), args: args, id: p.get_id()};
- variants += ~[spanned(vlo, vhi, vr)];
+ variants += [spanned(vlo, vhi, vr)];
}
token::RBRACE. {/* empty */ }
_ {
fn parse_item(p: &parser, attrs: &[ast::attribute]) -> option::t<@ast::item> {
if eat_word(p, "const") {
ret some(parse_item_const(p, attrs));
- } else if (eat_word(p, "inline")) {
+ } else if eat_word(p, "inline") {
expect_word(p, "fn");
ret some(parse_item_fn_or_iter(p, ast::impure_fn, ast::proto_fn,
attrs, ast::il_inline));
- } else if (is_word(p, "fn") && p.look_ahead(1u) != token::LPAREN) {
+ } else if is_word(p, "fn") && p.look_ahead(1u) != token::LPAREN {
p.bump();
ret some(parse_item_fn_or_iter(p, ast::impure_fn, ast::proto_fn,
attrs, ast::il_normal));
- } else if (eat_word(p, "pred")) {
- ret some(parse_item_fn_or_iter(p, ast::pure_fn, ast::proto_fn,
- attrs, ast::il_normal));
- } else if (eat_word(p, "iter")) {
+ } else if eat_word(p, "pred") {
+ ret some(parse_item_fn_or_iter(p, ast::pure_fn, ast::proto_fn, attrs,
+ ast::il_normal));
+ } else if eat_word(p, "iter") {
ret some(parse_item_fn_or_iter(p, ast::impure_fn, ast::proto_iter,
attrs, ast::il_normal));
- } else if (eat_word(p, "mod")) {
+ } else if eat_word(p, "mod") {
ret some(parse_item_mod(p, attrs));
- } else if (eat_word(p, "native")) {
+ } else if eat_word(p, "native") {
ret some(parse_item_native_mod(p, attrs));
}
if eat_word(p, "type") {
ret some(parse_item_type(p, attrs));
- } else if (eat_word(p, "tag")) {
+ } else if eat_word(p, "tag") {
ret some(parse_item_tag(p, attrs));
- } else if (is_word(p, "obj") && p.look_ahead(1u) != token::LPAREN) {
+ } else if is_word(p, "obj") && p.look_ahead(1u) != token::LPAREN {
p.bump();
ret some(parse_item_obj(p, attrs));
- } else if (eat_word(p, "resource")) {
+ } else if eat_word(p, "resource") {
ret some(parse_item_res(p, attrs));
} else { ret none; }
}
p.bump();
if p.peek() == token::LBRACKET {
let first_attr = parse_attribute_naked(p, ast::attr_outer, lo);
- ret some(left(~[first_attr] + parse_outer_attributes(p)));
- } else if (!(p.peek() == token::LT || p.peek() == token::LBRACKET)) {
+ ret some(left([first_attr] + parse_outer_attributes(p)));
+ } else if !(p.peek() == token::LT || p.peek() == token::LBRACKET) {
ret some(right(parse_syntax_ext_naked(p, lo)));
} else { ret none; }
} else { ret none; }
// Parse attributes that appear before an item
fn parse_outer_attributes(p: &parser) -> [ast::attribute] {
- let attrs: [ast::attribute] = ~[];
+ let attrs: [ast::attribute] = [];
while p.peek() == token::POUND {
- attrs += ~[parse_attribute(p, ast::attr_outer)];
+ attrs += [parse_attribute(p, ast::attr_outer)];
}
ret attrs;
}
// until we see the semi).
fn parse_inner_attrs_and_next(p: &parser) ->
{inner: [ast::attribute], next: [ast::attribute]} {
- let inner_attrs: [ast::attribute] = ~[];
- let next_outer_attrs: [ast::attribute] = ~[];
+ let inner_attrs: [ast::attribute] = [];
+ let next_outer_attrs: [ast::attribute] = [];
while p.peek() == token::POUND {
let attr = parse_attribute(p, ast::attr_inner);
if p.peek() == token::SEMI {
p.bump();
- inner_attrs += ~[attr];
+ inner_attrs += [attr];
} else {
// It's not really an inner attribute
let outer_attr =
spanned(attr.span.lo, attr.span.hi,
{style: ast::attr_outer, value: attr.node.value});
- next_outer_attrs += ~[outer_attr];
+ next_outer_attrs += [outer_attr];
break;
}
}
}
fn parse_optional_meta(p: &parser) -> [@ast::meta_item] {
- alt p.peek() { token::LPAREN. { ret parse_meta_seq(p); } _ { ret ~[]; } }
+ alt p.peek() { token::LPAREN. { ret parse_meta_seq(p); } _ { ret []; } }
}
fn parse_use(p: &parser) -> ast::view_item_ {
fn parse_rest_import_name(p: &parser, first: ast::ident,
def_ident: option::t<ast::ident>) ->
ast::view_item_ {
- let identifiers: [ast::ident] = ~[first];
+ let identifiers: [ast::ident] = [first];
let glob: bool = false;
let from_idents = option::none::<[ast::import_ident]>;
while true {
alt p.peek() {
token::SEMI. { break; }
token::MOD_SEP. {
- if glob {
- p.fatal("cannot path into a glob");
- }
+ if glob { p.fatal("cannot path into a glob"); }
if option::is_some(from_idents) {
p.fatal("cannot path into import list");
}
_ { p.fatal("expecting '::' or ';'"); }
}
alt p.peek() {
- token::IDENT(_, _) { identifiers += ~[parse_ident(p)]; }
+ token::IDENT(_, _) { identifiers += [parse_ident(p)]; }
+
//the lexer can't tell the different kinds of stars apart ) :
token::BINOP(token::STAR.) {
p.bump();
}
+
token::LBRACE. {
fn parse_import_ident(p: &parser) -> ast::import_ident {
let lo = p.get_lo_pos();
let ident = parse_ident(p);
let hi = p.get_hi_pos();
- ret spanned(lo, hi, {name: ident,
- id: p.get_id()});
+ ret spanned(lo, hi, {name: ident, id: p.get_id()});
}
- let from_idents_ = parse_seq(token::LBRACE,
- token::RBRACE,
- some(token::COMMA),
- parse_import_ident,
- p).node;
+ let from_idents_ =
+ parse_seq(token::LBRACE, token::RBRACE, some(token::COMMA),
+ parse_import_ident, p).node;
if vec::is_empty(from_idents_) {
p.fatal("at least one import is required");
}
from_idents = some(from_idents_);
}
- _ { p.fatal("expecting an identifier, or '*'"); }
+
+ _ {
+ p.fatal("expecting an identifier, or '*'");
+ }
}
}
alt def_ident {
some(i) {
- if glob {
- p.fatal("globbed imports can't be renamed");
- }
+ if glob { p.fatal("globbed imports can't be renamed"); }
if option::is_some(from_idents) {
p.fatal("can't rename import list");
}
p.get_id());
} else {
let len = vec::len(identifiers);
- ret ast::view_item_import(identifiers.(len - 1u), identifiers,
+ ret ast::view_item_import(identifiers[len - 1u], identifiers,
p.get_id());
}
}
}
fn parse_export(p: &parser) -> ast::view_item_ {
- let ids = parse_seq_to_before_end(
- token::SEMI, option::some(token::COMMA), parse_ident, p);
+ let ids =
+ parse_seq_to_before_end(token::SEMI, option::some(token::COMMA),
+ parse_ident, p);
ret ast::view_item_export(ids, p.get_id());
}
let the_item =
if eat_word(p, "use") {
parse_use(p)
- } else if (eat_word(p, "import")) {
+ } else if eat_word(p, "import") {
parse_import(p)
- } else if (eat_word(p, "export")) { parse_export(p) } else { fail };
+ } else if eat_word(p, "export") { parse_export(p) } else { fail };
let hi = p.get_lo_pos();
expect(p, token::SEMI);
ret @spanned(lo, hi, the_item);
}
fn parse_view(p: &parser) -> [@ast::view_item] {
- let items: [@ast::view_item] = ~[];
- while is_view_item(p) { items += ~[parse_view_item(p)]; }
+ let items: [@ast::view_item] = [];
+ while is_view_item(p) { items += [parse_view_item(p)]; }
ret items;
}
fn parse_native_view(p: &parser) -> [@ast::view_item] {
- let items: [@ast::view_item] = ~[];
- while is_view_item(p) { items += ~[parse_view_item(p)]; }
+ let items: [@ast::view_item] = [];
+ while is_view_item(p) { items += [parse_view_item(p)]; }
ret items;
}
sess: &parse_sess) -> @ast::crate {
let ftype = SOURCE_FILE;
let filemap = codemap::new_filemap(name, 0u, 0u);
- sess.cm.files += ~[filemap];
+ sess.cm.files += [filemap];
let itr = @interner::mk(str::hash, str::eq);
let rdr = lexer::new_reader(sess.cm, source, filemap, itr);
let p = new_parser(sess, cfg, rdr, ftype);
}
// Parses a source module as a crate
-fn parse_crate_mod(p: &parser, _cfg: &ast::crate_cfg) ->
- @ast::crate {
+fn parse_crate_mod(p: &parser, _cfg: &ast::crate_cfg) -> @ast::crate {
let lo = p.get_lo_pos();
let crate_attrs = parse_inner_attrs_and_next(p);
let first_item_outer_attrs = crate_attrs.next;
let m = parse_mod_items(p, token::EOF, first_item_outer_attrs);
ret @spanned(lo, p.get_lo_pos(),
- {directives: ~[],
+ {directives: [],
module: m,
attrs: crate_attrs.inner,
config: p.get_cfg()});
};
alt p.peek() {
+
// mod x = "foo.rs";
token::SEMI. {
let hi = p.get_hi_pos();
ret spanned(lo, hi, ast::cdir_src_mod(id, file_opt, outer_attrs));
}
+
// mod x = "foo_dir" { ...directives... }
token::LBRACE. {
p.bump();
}
t { unexpected(p, t); }
}
- } else if (eat_word(p, "auth")) {
+ } else if eat_word(p, "auth") {
let n = parse_path(p);
expect(p, token::EQ);
let a = parse_auth(p);
let hi = p.get_hi_pos();
expect(p, token::SEMI);
ret spanned(lo, hi, ast::cdir_auth(n, a));
- } else if (is_view_item(p)) {
+ } else if is_view_item(p) {
let vi = parse_view_item(p);
ret spanned(lo, vi.span.hi, ast::cdir_view_item(vi));
} else { ret p.fatal("expected crate directive"); }
expect_word(p, "mod");
}
- let cdirs: [@ast::crate_directive] = ~[];
+ let cdirs: [@ast::crate_directive] = [];
while p.peek() != term {
let cdir = @parse_crate_directive(p, first_outer_attr);
- cdirs += ~[cdir];
+ cdirs += [cdir];
}
ret cdirs;
}
let crate_attrs = leading_attrs.inner;
let first_cdir_attr = leading_attrs.next;
let cdirs = parse_crate_directives(p, token::EOF, first_cdir_attr);
- let deps: [str] = ~[];
+ let deps: [str] = [];
let cx =
@{p: p,
mode: eval::mode_parse,
config: p.get_cfg()});
}
-fn parse_crate_from_file(input: &str, cfg: &ast::crate_cfg,
- sess: &parse_sess) -> @ast::crate {
+fn parse_crate_from_file(input: &str, cfg: &ast::crate_cfg, sess: &parse_sess)
+ -> @ast::crate {
if str::ends_with(input, ".rc") {
parse_crate_from_crate_file(input, cfg, sess)
} else if str::ends_with(input, ".rs") {
parse_crate_from_source_file(input, cfg, sess)
} else {
- codemap::emit_error(none,
- "unknown input file type: " + input,
+ codemap::emit_error(none, "unknown input file type: " + input,
sess.cm);
fail
}
BINOP(op) { ret binop_to_str(op); }
BINOPEQ(op) { ret binop_to_str(op) + "="; }
+
/* Structural symbols */
AT. {
ret "@";
POUND_LBRACE. { ret "#{"; }
POUND_LT. { ret "#<"; }
+
/* Literals */
LIT_INT(i) {
ret int::to_str(i, 10u);
}
LIT_BOOL(b) { if b { ret "true"; } else { ret "false"; } }
+
/* Name components */
IDENT(s, _) {
ret interner::get::<str>(*r.get_interner(), s);
fn tok_str(t: token) -> str {
alt t {
- STRING(s, len) { ret #fmt("STR(%s,%d)", s, len); }
+ STRING(s, len) { ret #fmt["STR(%s,%d)", s, len]; }
BREAK(_) { ret "BREAK"; }
BEGIN(_) { ret "BEGIN"; }
END. { ret "END"; }
while i != right && L != 0u {
L -= 1u;
if i != left { s += ", "; }
- s += #fmt("%d=%s", szs.(i), tok_str(toks.(i)));
+ s += #fmt["%d=%s", szs[i], tok_str(toks[i])];
i += 1u;
i %= n;
}
// fall behind.
let n: uint = 3u * linewidth;
- log #fmt("mk_printer %u", linewidth);
+ log #fmt["mk_printer %u", linewidth];
let token: [mutable token] = vec::init_elt_mut(EOF, n);
let size: [mutable int] = vec::init_elt_mut(0, n);
let scan_stack: [mutable uint] = vec::init_elt_mut(0u, n);
- let print_stack: [print_stack_elt] = ~[];
+ let print_stack: [print_stack_elt] = [];
ret printer(out, n, linewidth as int, // margin
linewidth as int, // space
0u, // left
// buffered indentation to avoid writing trailing whitespace
mutable pending_indentation: int) {
- fn last_token() -> token { ret token.(right); }
+ fn last_token() -> token { ret token[right]; }
// be very careful with this!
- fn replace_last_token(t: token) { token.(right) = t; }
+ fn replace_last_token(t: token) { token[right] = t; }
fn pretty_print(t: token) {
- log #fmt("pp [%u,%u]", left, right);
+ log #fmt["pp [%u,%u]", left, right];
alt t {
EOF. {
if !scan_stack_empty {
self.check_stack(0);
- self.advance_left(token.(left), size.(left));
+ self.advance_left(token[left], size[left]);
}
self.indent(0);
}
left = 0u;
right = 0u;
} else { self.advance_right(); }
- log #fmt("pp BEGIN/buffer [%u,%u]", left, right);
- token.(right) = t;
- size.(right) = -right_total;
+ log #fmt["pp BEGIN/buffer [%u,%u]", left, right];
+ token[right] = t;
+ size[right] = -right_total;
self.scan_push(right);
}
END. {
if scan_stack_empty {
- log #fmt("pp END/print [%u,%u]", left, right);
+ log #fmt["pp END/print [%u,%u]", left, right];
self.print(t, 0);
} else {
- log #fmt("pp END/buffer [%u,%u]", left, right);
+ log #fmt["pp END/buffer [%u,%u]", left, right];
self.advance_right();
- token.(right) = t;
- size.(right) = -1;
+ token[right] = t;
+ size[right] = -1;
self.scan_push(right);
}
}
left = 0u;
right = 0u;
} else { self.advance_right(); }
- log #fmt("pp BREAK/buffer [%u,%u]", left, right);
+ log #fmt["pp BREAK/buffer [%u,%u]", left, right];
self.check_stack(0);
self.scan_push(right);
- token.(right) = t;
- size.(right) = -right_total;
+ token[right] = t;
+ size[right] = -right_total;
right_total += b.blank_space;
}
STRING(s, len) {
if scan_stack_empty {
- log #fmt("pp STRING/print [%u,%u]", left, right);
+ log #fmt["pp STRING/print [%u,%u]", left, right];
self.print(t, len);
} else {
- log #fmt("pp STRING/buffer [%u,%u]", left, right);
+ log #fmt["pp STRING/buffer [%u,%u]", left, right];
self.advance_right();
- token.(right) = t;
- size.(right) = len;
+ token[right] = t;
+ size[right] = len;
right_total += len;
self.check_stream();
}
}
}
fn check_stream() {
- log #fmt("check_stream [%u, %u] with left_total=%d, right_total=%d",
- left, right, left_total, right_total);
+ log #fmt["check_stream [%u, %u] with left_total=%d, right_total=%d",
+ left, right, left_total, right_total];
if right_total - left_total > space {
- log #fmt("scan window is %d, longer than space on line (%d)",
- right_total - left_total, space);
+ log #fmt["scan window is %d, longer than space on line (%d)",
+ right_total - left_total, space];
if !scan_stack_empty {
- if left == scan_stack.(bottom) {
- log #fmt("setting %u to infinity and popping", left);
- size.(self.scan_pop_bottom()) = size_infinity;
+ if left == scan_stack[bottom] {
+ log #fmt["setting %u to infinity and popping", left];
+ size[self.scan_pop_bottom()] = size_infinity;
}
}
- self.advance_left(token.(left), size.(left));
+ self.advance_left(token[left], size[left]);
if left != right { self.check_stream(); }
}
}
fn scan_push(x: uint) {
- log #fmt("scan_push %u", x);
+ log #fmt["scan_push %u", x];
if scan_stack_empty {
scan_stack_empty = false;
} else { top += 1u; top %= buf_len; assert (top != bottom); }
- scan_stack.(top) = x;
+ scan_stack[top] = x;
}
fn scan_pop() -> uint {
assert (!scan_stack_empty);
- let x = scan_stack.(top);
+ let x = scan_stack[top];
if top == bottom {
scan_stack_empty = true;
} else { top += buf_len - 1u; top %= buf_len; }
ret x;
}
- fn scan_top() -> uint {
- assert (!scan_stack_empty);
- ret scan_stack.(top);
- }
+ fn scan_top() -> uint { assert (!scan_stack_empty); ret scan_stack[top]; }
fn scan_pop_bottom() -> uint {
assert (!scan_stack_empty);
- let x = scan_stack.(bottom);
+ let x = scan_stack[bottom];
if top == bottom {
scan_stack_empty = true;
} else { bottom += 1u; bottom %= buf_len; }
assert (right != left);
}
fn advance_left(x: token, L: int) {
- log #fmt("advnce_left [%u,%u], sizeof(%u)=%d", left, right, left, L);
+ log #fmt["advnce_left [%u,%u], sizeof(%u)=%d", left, right, left, L];
if L >= 0 {
self.print(x, L);
alt x {
if left != right {
left += 1u;
left %= buf_len;
- self.advance_left(token.(left), size.(left));
+ self.advance_left(token[left], size[left]);
}
}
}
fn check_stack(k: int) {
if !scan_stack_empty {
let x = self.scan_top();
- alt token.(x) {
+ alt token[x] {
BEGIN(b) {
if k > 0 {
- size.(self.scan_pop()) = size.(x) + right_total;
+ size[self.scan_pop()] = size[x] + right_total;
self.check_stack(k - 1);
}
}
END. {
// paper says + not =, but that makes no sense.
- size.(self.scan_pop()) = 1;
+ size[self.scan_pop()] = 1;
self.check_stack(k + 1);
}
_ {
- size.(self.scan_pop()) = size.(x) + right_total;
+ size[self.scan_pop()] = size[x] + right_total;
if k > 0 { self.check_stack(k); }
}
}
}
}
fn print_newline(amount: int) {
- log #fmt("NEWLINE %d", amount);
+ log #fmt["NEWLINE %d", amount];
out.write_str("\n");
pending_indentation = 0;
self.indent(amount);
}
fn indent(amount: int) {
- log #fmt("INDENT %d", amount);
+ log #fmt["INDENT %d", amount];
pending_indentation += amount;
}
fn top() -> print_stack_elt {
let n = vec::len(print_stack);
let top: print_stack_elt = {offset: 0, pbreak: broken(inconsistent)};
- if n != 0u { top = print_stack.(n - 1u); }
+ if n != 0u { top = print_stack[n - 1u]; }
ret top;
}
fn write_str(s: str) {
out.write_str(s);
}
fn print(x: token, L: int) {
- log #fmt("print %s %d (remaining line space=%d)", tok_str(x), L,
- space);
+ log #fmt["print %s %d (remaining line space=%d)", tok_str(x), L,
+ space];
log buf_str(token, size, left, right, 6u);
alt x {
BEGIN(b) {
if L > space {
let col = margin - space + b.offset;
- log #fmt("print BEGIN -> push broken block at col %d", col);
- print_stack += ~[{offset: col, pbreak: broken(b.breaks)}];
+ log #fmt["print BEGIN -> push broken block at col %d", col];
+ print_stack += [{offset: col, pbreak: broken(b.breaks)}];
} else {
log "print BEGIN -> push fitting block";
- print_stack += ~[{offset: 0, pbreak: fits}];
+ print_stack += [{offset: 0, pbreak: fits}];
}
}
END. {
node_expr(ps, @ast::expr);
node_pat(ps, @ast::pat);
}
-type pp_ann = {pre: fn(&ann_node) , post: fn(&ann_node) };
+type pp_ann = {pre: fn(&ann_node), post: fn(&ann_node)};
fn no_ann() -> pp_ann {
fn ignore(_node: &ann_node) { }
mutable boxes: [pp::breaks],
ann: pp_ann};
-fn ibox(s: &ps, u: uint) { s.boxes += ~[pp::inconsistent]; pp::ibox(s.s, u); }
+fn ibox(s: &ps, u: uint) { s.boxes += [pp::inconsistent]; pp::ibox(s.s, u); }
fn end(s: &ps) { vec::pop(s.boxes); pp::end(s.s); }
fn rust_printer(writer: io::writer) -> ps {
- let boxes: [pp::breaks] = ~[];
+ let boxes: [pp::breaks] = [];
ret @{s: pp::mk_printer(writer, default_columns),
cm: none::<codemap>,
comments: none::<[lexer::cmnt]>,
// copy forward.
fn print_crate(cm: &codemap, crate: @ast::crate, filename: str,
in: io::reader, out: io::writer, ann: &pp_ann) {
- let boxes: [pp::breaks] = ~[];
+ let boxes: [pp::breaks] = [];
let r = lexer::gather_comments_and_literals(cm, filename, in);
let s =
@{s: pp::mk_printer(out, default_columns),
be to_str(attr, print_attribute);
}
-fn cbox(s: &ps, u: uint) { s.boxes += ~[pp::consistent]; pp::cbox(s.s, u); }
+fn cbox(s: &ps, u: uint) { s.boxes += [pp::consistent]; pp::cbox(s.s, u); }
-fn box(s: &ps, u: uint, b: pp::breaks) {
- s.boxes += ~[b];
- pp::box(s.s, u, b);
-}
+fn box(s: &ps, u: uint, b: pp::breaks) { s.boxes += [b]; pp::box(s.s, u, b); }
fn nbsp(s: &ps) { word(s.s, " "); }
fn bclose(s: &ps, span: codemap::span) { bclose_(s, span, indent_unit); }
fn is_begin(s: &ps) -> bool {
- alt s.s.last_token() {
- pp::BEGIN(_) { true }
- _ { false }
- }
+ alt s.s.last_token() { pp::BEGIN(_) { true } _ { false } }
}
fn is_end(s: &ps) -> bool {
- alt s.s.last_token() {
- pp::END. { true }
- _ { false }
- }
+ alt s.s.last_token() { pp::END. { true } _ { false } }
}
fn is_bol(s: &ps) -> bool {
ret s.s.last_token() == pp::EOF ||
- s.s.last_token() == pp::hardbreak_tok();
+ s.s.last_token() == pp::hardbreak_tok();
}
fn hardbreak_if_not_bol(s: &ps) { if !is_bol(s) { hardbreak(s.s); } }
word(s.s, "*/");
}
-fn commasep<IN>(s: &ps, b: breaks, elts: &[IN], op: fn(&ps, &IN) ) {
+fn commasep<IN>(s: &ps, b: breaks, elts: &[IN], op: fn(&ps, &IN)) {
box(s, 0u, b);
let first = true;
for elt: IN in elts {
}
-fn commasep_cmnt<IN>(s: &ps, b: breaks, elts: &[IN], op: fn(&ps, &IN) ,
- get_span: fn(&IN) -> codemap::span ) {
+fn commasep_cmnt<IN>(s: &ps, b: breaks, elts: &[IN], op: fn(&ps, &IN),
+ get_span: fn(&IN) -> codemap::span) {
box(s, 0u, b);
let len = vec::len::<IN>(elts);
let i = 0u;
if i < len {
word(s.s, ",");
maybe_print_trailing_comment(s, get_span(elt),
- some(get_span(elts.(i)).hi));
+ some(get_span(elts[i]).hi));
space_if_not_bol(s);
}
}
alt mt.mut {
ast::mut. { word_space(s, "mutable"); }
ast::maybe_mut. { word_space(s, "mutable?"); }
- ast::imm. {}
+ ast::imm. { }
}
print_type(s, mt.ty);
word(s.s, "]");
word(s.s, "}");
}
ast::ty_tup(elts) {
- popen(s);
- commasep(s, inconsistent, elts, print_type);
- pclose(s);
+ popen(s);
+ commasep(s, inconsistent, elts, print_type);
+ pclose(s);
}
ast::ty_fn(proto, inputs, output, cf, constrs) {
print_ty_fn(s, proto, none::<str>, inputs, output, cf, constrs);
}
+
ast::native_item_fn(lname, decl, typarams) {
print_fn(s, decl, ast::proto_fn, item.ident, typarams,
decl.constraints);
ast::item_tag(variants, params) {
let newtype =
vec::len(variants) == 1u &&
- str::eq(item.ident, variants.(0).node.name) &&
- vec::len(variants.(0).node.args) == 1u;
+ str::eq(item.ident, variants[0].node.name) &&
+ vec::len(variants[0].node.args) == 1u;
if newtype {
ibox(s, indent_unit);
word_space(s, "tag");
space(s.s);
if newtype {
word_space(s, "=");
- print_type(s, variants.(0).node.args.(0).ty);
+ print_type(s, variants[0].node.args[0].ty);
word(s.s, ";");
end(s);
} else {
space(s.s);
bopen(s);
for meth: @ast::method in _obj.methods {
- let typarams: [ast::ty_param] = ~[];
+ let typarams: [ast::ty_param] = [];
hardbreak_if_not_bol(s);
maybe_print_comment(s, meth.span.lo);
print_fn(s, meth.node.meth.decl, meth.node.meth.proto,
- meth.node.ident, typarams, ~[]);
+ meth.node.ident, typarams, []);
word(s.s, " ");
print_block(s, meth.node.meth.body);
}
word(s.s, item.ident);
print_type_params(s, tps);
popen(s);
- word_space(s, dt.decl.inputs.(0).ident + ":");
- print_type(s, dt.decl.inputs.(0).ty);
+ word_space(s, dt.decl.inputs[0].ident + ":");
+ print_type(s, dt.decl.inputs[0].ty);
pclose(s);
space(s.s);
print_block(s, dt.body);
// extra semi to make sure the output retains the same meaning.
fn maybe_protect_block(s: &ps, last: &option::t<@ast::stmt>,
next: &expr_or_stmt) {
- let last_expr_is_block = alt last {
- option::some(@{node: ast::stmt_expr(e, _), _}) {
- alt e.node {
- ast::expr_if(_ ,_ ,_)
- | ast::expr_alt(_, _)
- | ast::expr_block(_) { true }
+ let last_expr_is_block =
+ alt last {
+ option::some(@{node: ast::stmt_expr(e, _), _}) {
+ alt e.node {
+ ast::expr_if(_, _, _) | ast::expr_alt(_, _) |
+ ast::expr_block(_) {
+ true
+ }
+ _ { false }
+ }
+ true
+ }
_ { false }
- }
- true
- }
- _ { false }
- };
+ };
if !last_expr_is_block { ret; }
- let next_expr_is_ambig = alt next {
- expr_(e) { expr_is_ambig(e) }
- stmt_(@{node: ast::stmt_expr(e, _), _}) {
- expr_is_ambig(e)
- }
- _ { false }
- };
+ let next_expr_is_ambig =
+ alt next {
+ expr_(e) { expr_is_ambig(e) }
+ stmt_(@{node: ast::stmt_expr(e, _), _}) { expr_is_ambig(e) }
+ _ { false }
+ };
- if last_expr_is_block && next_expr_is_ambig {
- word(s.s, ";");
- }
+ if last_expr_is_block && next_expr_is_ambig { word(s.s, ";"); }
fn expr_is_ambig(ex: @ast::expr) -> bool {
- // We're going to walk the expression to the 'left' looking for
- // various properties that might indicate ambiguity
-
- type env = @mutable bool;
- let visitor = visit::mk_vt(@{
- visit_expr: visit_expr
- with *visit::default_visitor()
- });
- let env = @mutable false;
- visit_expr(ex, env, visitor);
- ret *env;
-
- fn visit_expr(ex: &@ast::expr, e: &env, v: &visit::vt<env>) {
- assert *e == false;
-
- if expr_is_ambig(ex) {
- *e = true;
- ret;
- }
-
- alt ex.node {
- ast::expr_assign(x, _) { v.visit_expr(x, e, v); }
- ast::expr_assign_op(_, x, _) { visit_expr(x, e, v); }
- ast::expr_move(x, _) { v.visit_expr(x, e, v); }
- ast::expr_field(x, _) { v.visit_expr(x, e, v); }
- ast::expr_index(x, _) { v.visit_expr(x, e, v); }
- ast::expr_binary(op, x, _) {
- if need_parens(x, operator_prec(op)) {
- *e = true;
- ret;
+ // We're going to walk the expression to the 'left' looking for
+ // various properties that might indicate ambiguity
+
+ type env = @mutable bool;
+ let visitor =
+ visit::mk_vt(@{visit_expr: visit_expr
+ with *visit::default_visitor()});
+ let env = @mutable false;
+ visit_expr(ex, env, visitor);
+ ret *env;
+
+ fn visit_expr(ex: &@ast::expr, e: &env, v: &visit::vt<env>) {
+ assert (*e == false);
+
+ if expr_is_ambig(ex) { *e = true; ret; }
+
+ alt ex.node {
+ ast::expr_assign(x, _) { v.visit_expr(x, e, v); }
+ ast::expr_assign_op(_, x, _) { visit_expr(x, e, v); }
+ ast::expr_move(x, _) { v.visit_expr(x, e, v); }
+ ast::expr_field(x, _) { v.visit_expr(x, e, v); }
+ ast::expr_index(x, _) { v.visit_expr(x, e, v); }
+ ast::expr_binary(op, x, _) {
+ if need_parens(x, operator_prec(op)) { *e = true; ret; }
+ v.visit_expr(x, e, v);
}
- v.visit_expr(x, e, v);
- }
- ast::expr_cast(x, _) {
- if need_parens(x, parse::parser::as_prec) {
- *e = true;
- ret;
+ ast::expr_cast(x, _) {
+ if need_parens(x, parse::parser::as_prec) {
+ *e = true;
+ ret;
+ }
}
+ ast::expr_ternary(x, _, _) { v.visit_expr(x, e, v); }
+ _ { }
}
- ast::expr_ternary(x, _, _) { v.visit_expr(x, e, v); }
- _ { }
- }
- }
+ }
- fn expr_is_ambig(ex: @ast::expr) -> bool {
- alt ex.node {
- ast::expr_unary(_, _) { true }
- ast::expr_tup(_) { true }
- _ { false }
- }
- }
+ fn expr_is_ambig(ex: @ast::expr) -> bool {
+ alt ex.node {
+ ast::expr_unary(_, _) { true }
+ ast::expr_tup(_) { true }
+ _ { false }
+ }
+ }
}
}
}
// ret and fail, without arguments cannot appear is the discriminant of if,
// alt, do, & while unambiguously without being parenthesized
fn print_maybe_parens_discrim(s: &ps, e: &@ast::expr) {
- let disambig = alt e.node {
- ast::expr_ret(option::none.) { true }
- _ { false }
- };
+ let disambig =
+ alt e.node { ast::expr_ret(option::none.) { true } _ { false } };
if disambig { popen(s) }
print_expr(s, e);
if disambig { pclose(s) }
some(_else) {
alt _else.node {
+
// "another else-if"
ast::expr_if(i, t, e) {
cbox(s, indent_unit - 1u);
do_else(s, e);
}
+
// "final else"
ast::expr_block(b) {
cbox(s, indent_unit - 1u);
ast::mac_invoc(path, arg, body) {
word(s.s, "#");
print_path(s, path, false);
- alt (arg.node) {
- ast::expr_vec(_,_) {}
- _ { word(s.s, " "); }
- }
+ alt arg.node { ast::expr_vec(_, _) { } _ { word(s.s, " "); } }
print_expr(s, arg);
// FIXME: extension 'body'
}
bclose_(s, expr.span, alt_indent_unit);
}
ast::expr_fn(f) {
+
// If the return type is the magic ty_infer, then we need to
// pretty print as a lambda-block
if f.decl.output.node == ast::ty_infer {
ibox(s, 0u);
word(s.s, "{");
print_fn_block_args(s, f.decl);
- print_possibly_embedded_block(s, f.body,
- block_block_fn, indent_unit);
+ print_possibly_embedded_block(s, f.body, block_block_fn,
+ indent_unit);
} else {
head(s, proto_to_str(f.proto));
- print_fn_args_and_ret(s, f.decl, ~[]);
+ print_fn_args_and_ret(s, f.decl, []);
space(s.s);
print_block(s, f.body);
}
ibox(s, 0u);
print_block(s, blk);
}
- ast::expr_copy(e) {
- word_space(s, "copy");
- print_expr(s, e);
- }
+ ast::expr_copy(e) { word_space(s, "copy"); print_expr(s, e); }
ast::expr_move(lhs, rhs) {
print_expr(s, lhs);
space(s.s);
// Methods
for meth: @ast::method in anon_obj.methods {
- let typarams: [ast::ty_param] = ~[];
+ let typarams: [ast::ty_param] = [];
hardbreak_if_not_bol(s);
maybe_print_comment(s, meth.span.lo);
print_fn(s, meth.node.meth.decl, meth.node.meth.proto,
- meth.node.ident, typarams, ~[]);
+ meth.node.ident, typarams, []);
word(s.s, " ");
print_block(s, meth.node.meth.body);
}
// With object
alt anon_obj.inner_obj {
none. { }
- some(e) {
- space(s.s);
- word_space(s, "with");
- print_expr(s, e);
- }
+ some(e) { space(s.s); word_space(s, "with"); print_expr(s, e); }
}
bclose(s, expr.span);
}
- ast::expr_uniq(expr) {
- word(s.s, "~");
- print_expr(s, expr);
- }
+ ast::expr_uniq(expr) { word(s.s, "~"); print_expr(s, expr); }
}
s.ann.post(ann_node);
end(s);
}
fn print_fn_args_and_ret(s: &ps, decl: &ast::fn_decl,
- constrs: [@ast::constr]) {
+ constrs: [@ast::constr]) {
popen(s);
fn print_arg(s: &ps, x: &ast::arg) {
ibox(s, indent_unit);
alt kind {
ast::kind_unique. { word(s.s, "~"); }
ast::kind_shared. { word(s.s, "@"); }
- _ { /* fallthrough */ }
+ _ {/* fallthrough */ }
}
}
}
ast::view_item_import(id, ids, _) {
head(s, "import");
- if !str::eq(id, ids.(vec::len(ids) - 1u)) {
+ if !str::eq(id, ids[vec::len(ids) - 1u]) {
word_space(s, id);
word_space(s, "=");
}
}
ast::view_item_import_from(mod_path, idents, _) {
head(s, "import");
- for elt: str in mod_path {
- word(s.s, elt);
- word(s.s, "::");
- }
+ for elt: str in mod_path { word(s.s, elt); word(s.s, "::"); }
word(s.s, "{");
commasep(s, inconsistent, idents,
- fn(s: &ps, w: &ast::import_ident) {
+ fn (s: &ps, w: &ast::import_ident) {
word(s.s, w.node.name)
});
word(s.s, "}");
}
ast::view_item_export(ids, _) {
head(s, "export");
- commasep(s, inconsistent, ids,
- fn(s: &ps, w: &str) { word(s.s, w) });
+ commasep(s, inconsistent, ids, fn (s: &ps, w: &str) { word(s.s, w) });
}
}
word(s.s, ";");
fn need_parens(expr: &@ast::expr, outer_prec: int) -> bool {
alt expr.node {
- ast::expr_binary(op, _, _) {
- operator_prec(op) < outer_prec
- }
+ ast::expr_binary(op, _, _) { operator_prec(op) < outer_prec }
ast::expr_cast(_, _) { parse::parser::as_prec < outer_prec }
- ast::expr_ternary(_, _, _) {
- parse::parser::ternary_prec < outer_prec
- }
+ ast::expr_ternary(_, _, _) { parse::parser::ternary_prec < outer_prec }
+
// This may be too conservative in some cases
- ast::expr_assign(_, _) { true }
+ ast::expr_assign(_, _) {
+ true
+ }
ast::expr_move(_, _) { true }
ast::expr_swap(_, _) { true }
ast::expr_assign_op(_, _, _) { true }
fn in_cbox(s: &ps) -> bool {
let len = vec::len(s.boxes);
if len == 0u { ret false; }
- ret s.boxes.(len - 1u) == pp::consistent;
+ ret s.boxes[len - 1u] == pp::consistent;
}
fn print_literal(s: &ps, lit: &@ast::lit) {
print_string(s, st);
}
ast::lit_char(ch) {
- word(s.s, "'" + escape_str(
- str::unsafe_from_bytes(~[ch as u8]), '\'') + "'");
+ word(s.s,
+ "'" + escape_str(str::unsafe_from_bytes([ch as u8]), '\'') +
+ "'");
}
ast::lit_int(val) { word(s.s, int::str(val)); }
ast::lit_uint(val) { word(s.s, uint::str(val) + "u"); }
alt s.literals {
some(lits) {
if s.cur_lit < vec::len(lits) {
- ret some(lits.(s.cur_lit));
+ ret some(lits[s.cur_lit]);
} else { ret none::<lexer::lit>; }
}
_ { ret none::<lexer::lit>; }
lexer::mixed. {
assert (vec::len(cmnt.lines) == 1u);
zerobreak(s.s);
- word(s.s, cmnt.lines.(0));
+ word(s.s, cmnt.lines[0]);
zerobreak(s.s);
}
lexer::isolated. {
lexer::trailing. {
word(s.s, " ");
if vec::len(cmnt.lines) == 1u {
- word(s.s, cmnt.lines.(0));
+ word(s.s, cmnt.lines[0]);
hardbreak(s.s);
} else {
ibox(s, 0u);
}
lexer::blank_line. {
// We need to do at least one, possibly two hardbreaks.
- let is_semi = alt s.s.last_token() {
- pp::STRING(s, _) { s == ";" }
- _ { false }
- };
+ let is_semi =
+ alt s.s.last_token() {
+ pp::STRING(s, _) { s == ";" }
+ _ { false }
+ };
if is_semi || is_begin(s) || is_end(s) { hardbreak(s.s) }
hardbreak(s.s);
}
let len = str::byte_len(st);
let i = 0u;
while i < len {
- alt st.(i) as char {
+ alt st[i] as char {
'\n' { out += "\\n"; }
'\t' { out += "\\t"; }
'\r' { out += "\\r"; }
ret out;
}
-fn to_str<T>(t: &T, f: fn(&ps, &T) ) -> str {
+fn to_str<T>(t: &T, f: fn(&ps, &T)) -> str {
let writer = io::string_writer();
let s = rust_printer(writer.get_writer());
f(s, t);
alt s.comments {
some(cmnts) {
if s.cur_cmnt < vec::len(cmnts) {
- ret some(cmnts.(s.cur_cmnt));
+ ret some(cmnts[s.cur_cmnt]);
} else { ret none::<lexer::cmnt>; }
}
_ { ret none::<lexer::cmnt>; }
// Removing the aliases from the type of f in the next two functions
// triggers memory corruption, but I haven't isolated the bug yet. FIXME
-fn constr_args_to_str<T>(f: &fn(&T) -> str ,
- args: &[@ast::sp_constr_arg<T>]) -> str {
+fn constr_args_to_str<T>(f: &fn(&T) -> str, args: &[@ast::sp_constr_arg<T>])
+ -> str {
let comma = false;
let s = "(";
for a: @ast::sp_constr_arg<T> in args {
ret s;
}
-fn constr_arg_to_str<T>(f: &fn(&T) -> str, c: &ast::constr_arg_general_<T>)
- -> str {
+fn constr_arg_to_str<T>(f: &fn(&T) -> str, c: &ast::constr_arg_general_<T>) ->
+ str {
alt c {
ast::carg_base. { ret "*"; }
ast::carg_ident(i) { ret f(i); }
}
fn fn_arg_idx_to_str(decl: &ast::fn_decl, idx: &uint) -> str {
- decl.inputs.(idx).ident
+ decl.inputs[idx].ident
}
fn ast_fn_constr_to_str(decl: &ast::fn_decl, c: &@ast::constr) -> str {
}
// FIXME: fix repeated code
-fn ast_fn_constrs_str(decl: &ast::fn_decl,
- constrs: &[@ast::constr]) -> str {
+fn ast_fn_constrs_str(decl: &ast::fn_decl, constrs: &[@ast::constr]) -> str {
let s = "";
let colon = true;
for c: @ast::constr in constrs {
}
fn ty_constr_to_str(c: &@ast::ty_constr) -> str {
- fn ty_constr_path_to_str(p: &ast::path) -> str {
- "*." + path_to_str(p)
- }
+ fn ty_constr_path_to_str(p: &ast::path) -> str { "*." + path_to_str(p) }
ret path_to_str(c.node.path) +
constr_args_to_str::<ast::path>(ty_constr_path_to_str,
fn mk<@T>(hasher: hashfn<T>, eqer: eqfn<T>) -> interner<T> {
let m = map::mk_hashmap::<T, uint>(hasher, eqer);
- ret {map: m, mutable vect: ~[], hasher: hasher, eqer: eqer};
+ ret {map: m, mutable vect: [], hasher: hasher, eqer: eqer};
}
fn intern<@T>(itr: &interner<T>, val: &T) -> uint {
none. {
let new_idx = vec::len::<T>(itr.vect);
itr.map.insert(val, new_idx);
- itr.vect += ~[val];
+ itr.vect += [val];
ret new_idx;
}
}
}
-fn get<T>(itr: &interner<T>, idx: uint) -> T { ret itr.vect.(idx); }
+fn get<T>(itr: &interner<T>, idx: uint) -> T { ret itr.vect[idx]; }
-fn len<T>(itr : &interner<T>) -> uint { ret vec::len(itr.vect); }
+fn len<T>(itr: &interner<T>) -> uint { ret vec::len(itr.vect); }
visit_expr: fn(&@expr, &E, &vt<E>),
visit_ty: fn(&@ty, &E, &vt<E>),
visit_constr: fn(&path, &span, node_id, &E, &vt<E>),
- visit_fn:
- fn(&_fn, &[ty_param], &span, &fn_ident, node_id, &E, &vt<E>) };
+ visit_fn: fn(&_fn, &[ty_param], &span, &fn_ident, node_id, &E, &vt<E>)};
fn default_visitor<E>() -> visitor<E> {
ret @{visit_mod: bind visit_mod::<E>(_, _, _, _),
item_obj(ob, _, _) {
for f: obj_field in ob.fields { v.visit_ty(f.ty, e, v); }
for m: @method in ob.methods {
- v.visit_fn(m.node.meth, ~[], m.span, some(m.node.ident),
- m.node.id, e, v);
+ v.visit_fn(m.node.meth, [], m.span, some(m.node.ident), m.node.id,
+ e, v);
}
}
}
ty_rec(flds) {
for f: ty_field in flds { v.visit_ty(f.node.mt.ty, e, v); }
}
- ty_tup(ts) {
- for tt in ts { v.visit_ty(tt, e, v); }
- }
+ ty_tup(ts) { for tt in ts { v.visit_ty(tt, e, v); } }
ty_fn(_, args, out, _, constrs) {
for a: ty_arg in args { v.visit_ty(a.node.ty, e, v); }
for c: @constr in constrs {
pat_rec(fields, _) {
for f: field_pat in fields { v.visit_pat(f.pat, e, v); }
}
- pat_tup(elts) {
- for elt in elts { v.visit_pat(elt, e, v); }
- }
+ pat_tup(elts) { for elt in elts { v.visit_pat(elt, e, v); } }
pat_box(inner) { v.visit_pat(inner, e, v); }
_ { }
}
for f: field in flds { v.visit_expr(f.node.expr, e, v); }
visit_expr_opt(base, e, v);
}
- expr_tup(elts) {
- for el in elts { v.visit_expr(el, e, v); }
- }
+ expr_tup(elts) { for el in elts { v.visit_expr(el, e, v); } }
expr_call(callee, args) {
v.visit_expr(callee, e, v);
visit_exprs(args, e, v);
v.visit_expr(x, e, v);
for a: arm in arms { v.visit_arm(a, e, v); }
}
- expr_fn(f) { v.visit_fn(f, ~[], ex.span, none, ex.id, e, v); }
+ expr_fn(f) { v.visit_fn(f, [], ex.span, none, ex.id, e, v); }
expr_block(b) { v.visit_block(b, e, v); }
expr_assign(a, b) { v.visit_expr(b, e, v); v.visit_expr(a, e, v); }
expr_copy(a) { v.visit_expr(a, e, v); }
some(ex) { v.visit_expr(ex, e, v); }
}
for m: @method in anon_obj.methods {
- v.visit_fn(m.node.meth, ~[], m.span, some(m.node.ident),
- m.node.id, e, v);
+ v.visit_fn(m.node.meth, [], m.span, some(m.node.ident), m.node.id,
+ e, v);
}
}
expr_mac(mac) { visit_mac(mac, e, v); }
type simple_visitor =
// takes the components so that one function can be
// generic over constr and ty_constr
- @{visit_mod: fn(&_mod, &span) ,
- visit_view_item: fn(&@view_item) ,
- visit_native_item: fn(&@native_item) ,
- visit_item: fn(&@item) ,
- visit_local: fn(&@local) ,
- visit_block: fn(&ast::blk) ,
- visit_stmt: fn(&@stmt) ,
- visit_arm: fn(&arm) ,
- visit_pat: fn(&@pat) ,
- visit_decl: fn(&@decl) ,
- visit_expr: fn(&@expr) ,
- visit_ty: fn(&@ty) ,
- visit_constr: fn(&path, &span, node_id) ,
- visit_fn: fn(&_fn, &[ty_param], &span, &fn_ident, node_id) };
+ @{visit_mod: fn(&_mod, &span),
+ visit_view_item: fn(&@view_item),
+ visit_native_item: fn(&@native_item),
+ visit_item: fn(&@item),
+ visit_local: fn(&@local),
+ visit_block: fn(&ast::blk),
+ visit_stmt: fn(&@stmt),
+ visit_arm: fn(&arm),
+ visit_pat: fn(&@pat),
+ visit_decl: fn(&@decl),
+ visit_expr: fn(&@expr),
+ visit_ty: fn(&@ty),
+ visit_constr: fn(&path, &span, node_id),
+ visit_fn: fn(&_fn, &[ty_param], &span, &fn_ident, node_id)};
fn default_simple_visitor() -> simple_visitor {
ret @{visit_mod: fn (_m: &_mod, _sp: &span) { },
}
fn mk_simple_visitor(v: &simple_visitor) -> vt<()> {
- fn v_mod(f: fn(&_mod, &span) , m: &_mod, sp: &span, e: &(), v: &vt<()>) {
+ fn v_mod(f: fn(&_mod, &span), m: &_mod, sp: &span, e: &(), v: &vt<()>) {
f(m, sp);
visit_mod(m, sp, e, v);
}
- fn v_view_item(f: fn(&@view_item) , vi: &@view_item, e: &(), v: &vt<()>) {
+ fn v_view_item(f: fn(&@view_item), vi: &@view_item, e: &(), v: &vt<()>) {
f(vi);
visit_view_item(vi, e, v);
}
- fn v_native_item(f: fn(&@native_item) , ni: &@native_item, e: &(),
+ fn v_native_item(f: fn(&@native_item), ni: &@native_item, e: &(),
v: &vt<()>) {
f(ni);
visit_native_item(ni, e, v);
}
- fn v_item(f: fn(&@item) , i: &@item, e: &(), v: &vt<()>) {
+ fn v_item(f: fn(&@item), i: &@item, e: &(), v: &vt<()>) {
f(i);
visit_item(i, e, v);
}
- fn v_local(f: fn(&@local) , l: &@local, e: &(), v: &vt<()>) {
+ fn v_local(f: fn(&@local), l: &@local, e: &(), v: &vt<()>) {
f(l);
visit_local(l, e, v);
}
- fn v_block(f: fn(&ast::blk) , bl: &ast::blk, e: &(), v: &vt<()>) {
+ fn v_block(f: fn(&ast::blk), bl: &ast::blk, e: &(), v: &vt<()>) {
f(bl);
visit_block(bl, e, v);
}
- fn v_stmt(f: fn(&@stmt) , st: &@stmt, e: &(), v: &vt<()>) {
+ fn v_stmt(f: fn(&@stmt), st: &@stmt, e: &(), v: &vt<()>) {
f(st);
visit_stmt(st, e, v);
}
- fn v_arm(f: fn(&arm) , a: &arm, e: &(), v: &vt<()>) {
+ fn v_arm(f: fn(&arm), a: &arm, e: &(), v: &vt<()>) {
f(a);
visit_arm(a, e, v);
}
- fn v_pat(f: fn(&@pat) , p: &@pat, e: &(), v: &vt<()>) {
+ fn v_pat(f: fn(&@pat), p: &@pat, e: &(), v: &vt<()>) {
f(p);
visit_pat(p, e, v);
}
- fn v_decl(f: fn(&@decl) , d: &@decl, e: &(), v: &vt<()>) {
+ fn v_decl(f: fn(&@decl), d: &@decl, e: &(), v: &vt<()>) {
f(d);
visit_decl(d, e, v);
}
- fn v_expr(f: fn(&@expr) , ex: &@expr, e: &(), v: &vt<()>) {
+ fn v_expr(f: fn(&@expr), ex: &@expr, e: &(), v: &vt<()>) {
f(ex);
visit_expr(ex, e, v);
}
- fn v_ty(f: fn(&@ty) , ty: &@ty, e: &(), v: &vt<()>) {
+ fn v_ty(f: fn(&@ty), ty: &@ty, e: &(), v: &vt<()>) {
f(ty);
visit_ty(ty, e, v);
}
- fn v_constr(f: fn(&path, &span, node_id) , pt: &path, sp: &span,
+ fn v_constr(f: fn(&path, &span, node_id), pt: &path, sp: &span,
id: node_id, e: &(), v: &vt<()>) {
f(pt, sp, id);
visit_constr(pt, sp, id, e, v);
}
- fn v_fn(f: fn(&_fn, &[ty_param], &span, &fn_ident, node_id) , ff: &_fn,
+ fn v_fn(f: fn(&_fn, &[ty_param], &span, &fn_ident, node_id), ff: &_fn,
tps: &[ty_param], sp: &span, ident: &fn_ident, id: node_id,
e: &(), v: &vt<()>) {
f(ff, tps, sp, ident, id);
fn field_expr(f: &ast::field) -> @ast::expr { ret f.node.expr; }
fn field_exprs(fields: &[ast::field]) -> [@ast::expr] {
- let es = ~[];
- for f: ast::field in fields { es += ~[f.node.expr]; }
+ let es = [];
+ for f: ast::field in fields { es += [f.node.expr]; }
ret es;
}
// FIXME mode this to std::float when editing the stdlib no longer
// requires a snapshot
fn float_to_str(num: float, digits: uint) -> str {
- let accum = if num < 0.0 { num = -num; "-" }
- else { "" };
+ let accum = if num < 0.0 { num = -num; "-" } else { "" };
let trunc = num as uint;
let frac = num - (trunc as float);
accum += uint::str(trunc);
}
fn get_id_ident(cx: &ctxt, id: ast::def_id) -> str {
- if (id.crate != ast::local_crate) {
+ if id.crate != ast::local_crate {
str::connect(cx.ext_map.get(id), "::")
} else {
alt cx.items.find(id.node) {
let s = proto_to_str(proto);
alt ident { some(i) { s += " "; s += i; } _ { } }
s += "(";
- let strs = ~[];
- for a: arg in inputs { strs += ~[fn_input_to_str(cx, a)]; }
+ let strs = [];
+ for a: arg in inputs { strs += [fn_input_to_str(cx, a)]; }
s += str::connect(strs, ", ");
s += ")";
if struct(cx, output) != ty_nil {
}
alt cname(cx, typ) { some(cs) { ret cs; } _ { } }
ret alt struct(cx, typ) {
- ty_native(_) { "native" }
- ty_nil. { "()" }
- ty_bot. { "_|_" }
- ty_bool. { "bool" }
- ty_int. { "int" }
- ty_float. { "float" }
- ty_uint. { "uint" }
- ty_machine(tm) { ty_mach_to_str(tm) }
- ty_char. { "char" }
- ty_str. { "str" }
- ty_istr. { "istr" }
- ty_box(tm) { "@" + mt_to_str(cx, tm) }
- ty_uniq(t) { "~" + ty_to_str(cx, t) }
- ty_vec(tm) { "[" + mt_to_str(cx, tm) + "]" }
- ty_type. { "type" }
- ty_rec(elems) {
- let strs: [str] = ~[];
- for fld: field in elems { strs += ~[field_to_str(cx, fld)]; }
- "{" + str::connect(strs, ",") + "}"
- }
- ty_tup(elems) {
- let strs = ~[];
- for elem in elems { strs += ~[ty_to_str(cx, elem)]; }
- "(" + str::connect(strs, ",") + ")"
- }
- ty_tag(id, tps) {
- let s = get_id_ident(cx, id);
- if vec::len::<t>(tps) > 0u {
- let strs: [str] = ~[];
- for typ: t in tps { strs += ~[ty_to_str(cx, typ)]; }
- s += "[" + str::connect(strs, ",") + "]";
+ ty_native(_) { "native" }
+ ty_nil. { "()" }
+ ty_bot. { "_|_" }
+ ty_bool. { "bool" }
+ ty_int. { "int" }
+ ty_float. { "float" }
+ ty_uint. { "uint" }
+ ty_machine(tm) { ty_mach_to_str(tm) }
+ ty_char. { "char" }
+ ty_str. { "str" }
+ ty_istr. { "istr" }
+ ty_box(tm) { "@" + mt_to_str(cx, tm) }
+ ty_uniq(t) { "~" + ty_to_str(cx, t) }
+ ty_vec(tm) { "[" + mt_to_str(cx, tm) + "]" }
+ ty_type. { "type" }
+ ty_rec(elems) {
+ let strs: [str] = [];
+ for fld: field in elems { strs += [field_to_str(cx, fld)]; }
+ "{" + str::connect(strs, ",") + "}"
+ }
+ ty_tup(elems) {
+ let strs = [];
+ for elem in elems { strs += [ty_to_str(cx, elem)]; }
+ "(" + str::connect(strs, ",") + ")"
+ }
+ ty_tag(id, tps) {
+ let s = get_id_ident(cx, id);
+ if vec::len::<t>(tps) > 0u {
+ let strs: [str] = [];
+ for typ: t in tps { strs += [ty_to_str(cx, typ)]; }
+ s += "[" + str::connect(strs, ",") + "]";
+ }
+ s
+ }
+ ty_fn(proto, inputs, output, cf, constrs) {
+ fn_to_str(cx, proto, none, inputs, output, cf, constrs)
+ }
+ ty_native_fn(_, inputs, output) {
+ fn_to_str(cx, ast::proto_fn, none, inputs, output, ast::return,
+ [])
+ }
+ ty_obj(meths) {
+ let strs = [];
+ for m: method in meths { strs += [method_to_str(cx, m)]; }
+ "obj {\n\t" + str::connect(strs, "\n\t") + "\n}"
+ }
+ ty_res(id, _, _) { get_id_ident(cx, id) }
+ ty_var(v) { "<T" + int::str(v) + ">" }
+ ty_param(id, _) {
+ "'" + str::unsafe_from_bytes([('a' as u8) + (id as u8)])
+ }
+ _ { ty_to_short_str(cx, typ) }
}
- s
- }
- ty_fn(proto, inputs, output, cf, constrs) {
- fn_to_str(cx, proto, none, inputs, output, cf, constrs)
- }
- ty_native_fn(_, inputs, output) {
- fn_to_str(cx, ast::proto_fn, none, inputs, output, ast::return, ~[])
- }
- ty_obj(meths) {
- let strs = ~[];
- for m: method in meths { strs += ~[method_to_str(cx, m)]; }
- "obj {\n\t" + str::connect(strs, "\n\t") + "\n}"
- }
- ty_res(id, _, _) {
- get_id_ident(cx, id)
- }
- ty_var(v) { "<T" + int::str(v) + ">" }
- ty_param(id,_) {
- "'" + str::unsafe_from_bytes(~[('a' as u8) + (id as u8)])
- }
- _ { ty_to_short_str(cx, typ) }
- }
}
fn ty_to_short_str(cx: &ctxt, typ: t) -> str {
use std;
import std::vec;
-fn vec_equal<T>(v: &[T], u: &[T], element_equality_test: fn(&T, &T) -> bool )
+fn vec_equal<T>(v: &[T], u: &[T], element_equality_test: fn(&T, &T) -> bool)
-> bool {
let Lv = vec::len(v);
if Lv != vec::len(u) { ret false; }
let i = 0u;
while i < Lv {
- if !element_equality_test(v.(i), u.(i)) { ret false; }
+ if !element_equality_test(v[i], u[i]) { ret false; }
i += 1u;
}
ret true;
fn main() {
assert (builtin_equal(5, 5));
assert (!builtin_equal(5, 4));
- assert (!vec_equal(~[5, 5], ~[5], builtin_equal));
- assert (!vec_equal(~[5, 5], ~[5, 4], builtin_equal));
- assert (!vec_equal(~[5, 5], ~[4, 5], builtin_equal));
- assert (vec_equal(~[5, 5], ~[5, 5], builtin_equal));
+ assert (!vec_equal([5, 5], [5], builtin_equal));
+ assert (!vec_equal([5, 5], [5, 4], builtin_equal));
+ assert (!vec_equal([5, 5], [4, 5], builtin_equal));
+ assert (vec_equal([5, 5], [5, 5], builtin_equal));
log_err "Pass";
}
import rustc::syntax::print::pprust;
fn write_file(filename: &str, content: &str) {
- io::file_writer(filename,
- ~[io::create,
- io::truncate]).write_str(content);
+ io::file_writer(filename, [io::create, io::truncate]).write_str(content);
// Work around https://github.com/graydon/rust/issues/726
- std::run::run_program("chmod", ~["644", filename]);
+ std::run::run_program("chmod", ["644", filename]);
}
fn file_contains(filename: &str, needle: &str) -> bool {
if str::ends_with(path, ".rs") {
if file_contains(path, "xfail-stage1") {
//log_err "Skipping " + path + " because it is marked as xfail-stage1";
- } else { files += ~[path]; }
- } else if (fs::file_is_dir(path) && str::find(path, "compile-fail") == -1)
- {
+ } else { files += [path]; }
+ } else if fs::file_is_dir(path) && str::find(path, "compile-fail") == -1 {
for p in fs::list_dir(path) { find_rust_files(files, p); }
}
}
fn safe_to_steal(e: ast::expr_) -> bool {
alt e {
+
// pretty-printer precedence issues -- https://github.com/graydon/rust/issues/670
ast::expr_unary(_, _) {
false
ast::expr_binary(_, _, _) { false }
ast::expr_assign(_, _) { false }
ast::expr_assign_op(_, _, _) { false }
- ast::expr_fail(option::none.) { false /* https://github.com/graydon/rust/issues/764 */ }
+ ast::expr_fail(option::none.) {
+ false
+ /* https://github.com/graydon/rust/issues/764 */
+
+ }
ast::expr_ret(option::none.) { false }
ast::expr_put(option::none.) { false }
- ast::expr_ret(_) { false /* lots of code generation issues, such as https://github.com/graydon/rust/issues/770 */ }
+
+ ast::expr_ret(_) {
+ false
+ /* lots of code generation issues, such as https://github.com/graydon/rust/issues/770 */
+
+ }
ast::expr_fail(_) { false }
+
_ {
true
}
}
fn steal_exprs(crate: &ast::crate) -> [ast::expr] {
- let exprs: @mutable [ast::expr] = @mutable ~[];
+ let exprs: @mutable [ast::expr] = @mutable [];
// "Stash" is not type-parameterized because of the need for safe_to_steal
fn stash_expr(es: @mutable [ast::expr], e: &@ast::expr) {
if safe_to_steal(e.node) {
- *es += ~[*e];
+ *es += [*e];
} else {/* now my indices are wrong :( */ }
}
- let v = visit::mk_simple_visitor
- (@{visit_expr: bind stash_expr(exprs, _)
- with *visit::default_simple_visitor()});
- visit::visit_crate(crate, (), v);
+ let v =
+ visit::mk_simple_visitor(@{visit_expr: bind stash_expr(exprs, _)
+ with *visit::default_simple_visitor()});
+ visit::visit_crate(crate, (), v);;
*exprs
}
let af = fold::make_fold(afp);
let crate2: @ast::crate = @af.fold_crate(crate);
fold::dummy_out(af); // work around a leak (https://github.com/graydon/rust/issues/651)
+ ;
*crate2
}
fn devnull() -> io::writer { std::io::string_writer().get_writer() }
-fn as_str(f: fn(io::writer) ) -> str {
+fn as_str(f: fn(io::writer)) -> str {
let w = std::io::string_writer();
f(w.get_writer());
ret w.get_str();
}
-fn check_variants_of_ast(crate: &ast::crate, codemap: &codemap::codemap, filename: &str) {
+fn check_variants_of_ast(crate: &ast::crate, codemap: &codemap::codemap,
+ filename: &str) {
let exprs = steal_exprs(crate);
let exprsL = vec::len(exprs);
- if (exprsL < 100u) {
+ if exprsL < 100u {
for each i: uint in under(uint::min(exprsL, 20u)) {
- log_err "Replacing... " + pprust::expr_to_str(@exprs.(i));
+ log_err "Replacing... " + pprust::expr_to_str(@exprs[i]);
for each j: uint in under(uint::min(exprsL, 5u)) {
- log_err "With... " + pprust::expr_to_str(@exprs.(j));
- let crate2 = @replace_expr_in_crate(crate, i, exprs.(j).node);
+ log_err "With... " + pprust::expr_to_str(@exprs[j]);
+ let crate2 = @replace_expr_in_crate(crate, i, exprs[j].node);
// It would be best to test the *crate* for stability, but testing the
// string for stability is easier and ok for now.
- let str3 = as_str(bind pprust::print_crate(codemap, crate2, filename,
- io::string_reader(""), _,
- pprust::no_ann()));
+ let str3 =
+ as_str(bind pprust::print_crate(codemap, crate2, filename,
+ io::string_reader(""), _,
+ pprust::no_ann()));
// 1u would be sane here, but the pretty-printer currently has lots of whitespace and paren issues,
// and https://github.com/graydon/rust/issues/766 is hilarious.
check_roundtrip_convergence(str3, 7u);
fn check_whole_compiler(code: &str) {
let filename = "test.rs";
write_file(filename, code);
- let p = std::run::program_output("/Users/jruderman/code/rust/build/stage1/rustc", ~["-c", filename]);
+ let p =
+ std::run::program_output("/Users/jruderman/code/rust/build/stage1/rustc",
+ ["-c", filename]);
+
//log_err #fmt("Status: %d", p.status);
//log_err "Output: " + p.out;
if p.err != "" {
if contains(p.err, "argument of incompatible type") {
log_err "https://github.com/graydon/rust/issues/769";
- } else if contains(p.err, "Cannot create binary operator with two operands of differing type") {
+ } else if contains(p.err,
+ "Cannot create binary operator with two operands of differing type")
+ {
log_err "https://github.com/graydon/rust/issues/770";
} else if contains(p.err, "May only branch on boolean predicates!") {
log_err "https://github.com/graydon/rust/issues/770 or https://github.com/graydon/rust/issues/776";
- } else if contains(p.err, "Invalid constantexpr cast!") && contains(code, "!") {
+ } else if contains(p.err, "Invalid constantexpr cast!") &&
+ contains(code, "!") {
log_err "https://github.com/graydon/rust/issues/777";
- } else if contains(p.err, "Both operands to ICmp instruction are not of the same type!") && contains(code, "!") {
+ } else if contains(p.err,
+ "Both operands to ICmp instruction are not of the same type!")
+ && contains(code, "!") {
log_err "https://github.com/graydon/rust/issues/777 #issuecomment-1678487";
- } else if contains(p.err, "Ptr must be a pointer to Val type!") && contains(code, "!") {
+ } else if contains(p.err, "Ptr must be a pointer to Val type!") &&
+ contains(code, "!") {
log_err "https://github.com/graydon/rust/issues/779";
- } else if contains(p.err, "Calling a function with bad signature!") && (contains(code, "iter") || contains(code, "range")) {
+ } else if contains(p.err, "Calling a function with bad signature!") &&
+ (contains(code, "iter") || contains(code, "range")) {
log_err "https://github.com/graydon/rust/issues/771 - calling an iter fails";
- } else if contains(p.err, "Calling a function with a bad signature!") && contains(code, "empty") {
+ } else if contains(p.err, "Calling a function with a bad signature!")
+ && contains(code, "empty") {
log_err "https://github.com/graydon/rust/issues/775 - possibly a modification of run-pass/import-glob-crate.rs";
- } else if contains(p.err, "Invalid type for pointer element!") && contains(code, "put") {
+ } else if contains(p.err, "Invalid type for pointer element!") &&
+ contains(code, "put") {
log_err "https://github.com/graydon/rust/issues/773 - put put ()";
- } else if contains(p.err, "pointer being freed was not allocated") && contains(p.out, "Out of stack space, sorry") {
+ } else if contains(p.err, "pointer being freed was not allocated") &&
+ contains(p.out, "Out of stack space, sorry") {
log_err "https://github.com/graydon/rust/issues/768 + https://github.com/graydon/rust/issues/778"
} else {
log_err "Stderr: " + p.err;
fail "Unfamiliar error message";
}
- } else if contains(p.out, "non-exhaustive match failure") && contains(p.out, "alias.rs") {
+ } else if contains(p.out, "non-exhaustive match failure") &&
+ contains(p.out, "alias.rs") {
log_err "https://github.com/graydon/rust/issues/772";
- } else if contains(p.out, "non-exhaustive match failure") && contains(p.out, "trans.rs") && contains(code, "put") {
+ } else if contains(p.out, "non-exhaustive match failure") &&
+ contains(p.out, "trans.rs") && contains(code, "put") {
log_err "https://github.com/graydon/rust/issues/774";
} else if contains(p.out, "Out of stack space, sorry") {
log_err "Possibly a variant of https://github.com/graydon/rust/issues/768";
}
} else if p.status == 11 {
log_err "What is this I don't even";
- } else if p.status != 0 {
- fail "Unfamiliar status code";
- }
+ } else if p.status != 0 { fail "Unfamiliar status code"; }
}
fn parse_and_print(code: &str) -> str {
let filename = "tmp.rs";
let sess = @{cm: codemap::new_codemap(), mutable next_id: 0};
//write_file(filename, code);
- let crate =
- parser::parse_crate_from_source_str(filename, code, ~[], sess);
+ let crate = parser::parse_crate_from_source_str(filename, code, [], sess);
ret as_str(bind pprust::print_crate(sess.cm, crate, filename,
io::string_reader(code), _,
pprust::no_ann()));
}
fn content_is_dangerous_to_modify(code: &str) -> bool {
- let dangerous_patterns = [
- "obj", // not safe to steal; https://github.com/graydon/rust/issues/761
+ let dangerous_patterns =
+ ["obj", // not safe to steal; https://github.com/graydon/rust/issues/761
"#macro", // not safe to steal things inside of it, because they have a special syntax
"#", // strange representation of the arguments to #fmt, for example
" be ", // don't want to replace its child with a non-call: "Non-call expression in tail call"
- "@" // hangs when compiling: https://github.com/graydon/rust/issues/768
- ];
+ "@"]; // hangs when compiling: https://github.com/graydon/rust/issues/768
for p: str in dangerous_patterns { if contains(code, p) { ret true; } }
ret false;
}
-fn content_is_confusing(code: &str) -> bool {
- let // https://github.com/graydon/rust/issues/671
- // https://github.com/graydon/rust/issues/669
- // https://github.com/graydon/rust/issues/669
- // https://github.com/graydon/rust/issues/669
- // crazy rules enforced by parser rather than typechecker?
- // more precedence issues
- // more precedence issues?
- confusing_patterns =
+fn content_is_confusing(code: &str) ->
+ bool { // https://github.com/graydon/rust/issues/671
+ // https://github.com/graydon/rust/issues/669
+ // https://github.com/graydon/rust/issues/669
+ // https://github.com/graydon/rust/issues/669
+ // crazy rules enforced by parser rather than typechecker?
+ // more precedence issues
+ // more precedence issues?
+
+ let confusing_patterns =
["#macro", "][]", "][mutable]", "][mutable ]", "self", "spawn",
- "bind",
- "\n\n\n\n\n", // https://github.com/graydon/rust/issues/759
+ "bind", "\n\n\n\n\n", // https://github.com/graydon/rust/issues/759
" : ", // https://github.com/graydon/rust/issues/760
- "if ret",
- "alt ret",
- "if fail",
- "alt fail"
- ];
+ "if ret", "alt ret", "if fail", "alt fail"];
for p: str in confusing_patterns { if contains(code, p) { ret true; } }
ret false;
}
fn file_is_confusing(filename: &str) -> bool {
- let
- // https://github.com/graydon/rust/issues/674
+ // https://github.com/graydon/rust/issues/674
- // something to do with () as a lone pattern
+ // something to do with () as a lone pattern
- // an issue where -2147483648 gains an
- // extra negative sign each time through,
- // which i can't reproduce using "rustc
- // --pretty normal"???
- confusing_files =
+ // an issue where -2147483648 gains an
+ // extra negative sign each time through,
+ // which i can't reproduce using "rustc
+ // --pretty normal"???
+ let confusing_files =
["block-expr-precedence.rs", "nil-pattern.rs",
"syntax-extension-fmt.rs",
- "newtype.rs" // modifying it hits something like https://github.com/graydon/rust/issues/670
- ];
+ "newtype.rs"]; // modifying it hits something like https://github.com/graydon/rust/issues/670
for f in confusing_files { if contains(filename, f) { ret true; } }
}
if old == new {
- log_err #fmt("Converged after %u iterations", i);
+ log_err #fmt["Converged after %u iterations", i];
} else {
- log_err #fmt("Did not converge after %u iterations!", i);
+ log_err #fmt["Did not converge after %u iterations!", i];
write_file("round-trip-a.rs", old);
write_file("round-trip-b.rs", new);
- std::run::run_program("diff", ~["-w", "-u", "round-trip-a.rs", "round-trip-b.rs"]);
+ std::run::run_program("diff",
+ ["-w", "-u", "round-trip-a.rs",
+ "round-trip-b.rs"]);
fail "Mismatch";
}
}
fn check_convergence(files: &[str]) {
- log_err #fmt("pp convergence tests: %u files", vec::len(files));
+ log_err #fmt["pp convergence tests: %u files", vec::len(files)];
for file in files {
if !file_is_confusing(file) {
let s = io::read_whole_file_str(file);
if !content_is_confusing(s) {
- log_err #fmt("pp converge: %s", file);
+ log_err #fmt["pp converge: %s", file];
// Change from 7u to 2u when https://github.com/graydon/rust/issues/759 is fixed
check_roundtrip_convergence(s, 7u);
}
for file in files {
if !file_is_confusing(file) {
let s = io::read_whole_file_str(file);
- if content_is_dangerous_to_modify(s) || content_is_confusing(s) { cont; }
+ if content_is_dangerous_to_modify(s) || content_is_confusing(s) {
+ cont;
+ }
log_err "check_variants: " + file;
let sess = @{cm: codemap::new_codemap(), mutable next_id: 0};
- let crate = parser::parse_crate_from_source_str(file, s, ~[], sess);
+ let crate =
+ parser::parse_crate_from_source_str(file, s, [], sess);
log_err as_str(bind pprust::print_crate(sess.cm, crate, file,
- io::string_reader(s), _,
- pprust::no_ann()));
+ io::string_reader(s), _,
+ pprust::no_ann()));
check_variants_of_ast(*crate, sess.cm, file);
}
}
fn main(args: [str]) {
if vec::len(args) != 2u {
- log_err #fmt("usage: %s <testdir>", args.(0));
+ log_err #fmt["usage: %s <testdir>", args[0]];
ret;
}
- let files = ~[];
- let root = args.(1);
+ let files = [];
+ let root = args[1];
find_rust_files(files, root);
check_convergence(files);
slice(v, 0u, i) + slice(v, i + 1u, len(v))
}
fn vec_dup<T>(v: &[T], i: uint) -> [T] {
- slice(v, 0u, i) + ~[v.(i)] + slice(v, i, len(v))
+ slice(v, 0u, i) + [v[i]] + slice(v, i, len(v))
}
fn vec_swadj<T>(v: &[T], i: uint) -> [T] {
- slice(v, 0u, i) + ~[v.(i + 1u), v.(i)] + slice(v, i + 2u, len(v))
+ slice(v, 0u, i) + [v[i + 1u], v[i]] + slice(v, i + 2u, len(v))
}
fn vec_prefix<T>(v: &[T], i: uint) -> [T] { slice(v, 0u, i) }
fn vec_suffix<T>(v: &[T], i: uint) -> [T] { slice(v, i, len(v)) }
fn vec_poke<T>(v: &[T], i: uint, x: &T) -> [T] {
- slice(v, 0u, i) + ~[x] + slice(v, i + 1u, len(v))
+ slice(v, 0u, i) + [x] + slice(v, i + 1u, len(v))
}
fn vec_insert<T>(v: &[T], i: uint, x: &T) -> [T] {
- slice(v, 0u, i) + ~[x] + slice(v, i, len(v))
+ slice(v, 0u, i) + [x] + slice(v, i, len(v))
}
// Iterates over 0...length, skipping the specified number on each side.
// Returns a bunch of modified versions of v, some of which introduce new elements (borrowed from xs).
fn vec_edits<T>(v: &[T], xs: &[T]) -> [[T]] {
- let edits: [[T]] = ~[];
+ let edits: [[T]] = [];
let Lv: uint = len(v);
if Lv != 1u {
edits +=
- ~[~[]]; // When Lv == 1u, this is redundant with omit
- //if (Lv >= 3u) { edits += ~[vec_reverse(v)]; }
+ [[]]; // When Lv == 1u, this is redundant with omit
+ //if (Lv >= 3u) { edits += ~[vec_reverse(v)]; }
- }
- for each i: uint in ix(0u, 1u, Lv) { edits += ~[vec_omit(v, i)]; }
- for each i: uint in ix(0u, 1u, Lv) { edits += ~[vec_dup(v, i)]; }
- for each i: uint in ix(0u, 2u, Lv) { edits += ~[vec_swadj(v, i)]; }
- for each i: uint in ix(1u, 2u, Lv) { edits += ~[vec_prefix(v, i)]; }
- for each i: uint in ix(2u, 1u, Lv) { edits += ~[vec_suffix(v, i)]; }
+ }
+ for each i: uint in ix(0u, 1u, Lv) { edits += [vec_omit(v, i)]; }
+ for each i: uint in ix(0u, 1u, Lv) { edits += [vec_dup(v, i)]; }
+ for each i: uint in ix(0u, 2u, Lv) { edits += [vec_swadj(v, i)]; }
+ for each i: uint in ix(1u, 2u, Lv) { edits += [vec_prefix(v, i)]; }
+ for each i: uint in ix(2u, 1u, Lv) { edits += [vec_suffix(v, i)]; }
for each j: uint in ix(0u, 1u, len(xs)) {
for each i: uint in ix(0u, 1u, Lv) {
- edits += ~[vec_poke(v, i, xs.(j))];
+ edits += [vec_poke(v, i, xs[j])];
}
for each i: uint in ix(0u, 0u, Lv) {
- edits += ~[vec_insert(v, i, xs.(j))];
+ edits += [vec_insert(v, i, xs[j])];
}
}
let i = 0u;
let s = "[";
while i < len(v) {
- s += int::str(v.(i));
+ s += int::str(v[i]);
if i + 1u < len(v) { s += ", " }
i += 1u;
}
fn show_edits(a: &[int], xs: &[int]) {
log_err "=== Edits of " + vec_to_str(a) + " ===";
let b = vec_edits(a, xs);
- for each i: uint in ix(0u, 1u, len(b)) { log_err vec_to_str(b.(i)); }
+ for each i: uint in ix(0u, 1u, len(b)) { log_err vec_to_str(b[i]); }
}
fn demo_edits() {
- let xs = ~[7, 8];
- show_edits(~[], xs);
- show_edits(~[1], xs);
- show_edits(~[1, 2], xs);
- show_edits(~[1, 2, 3], xs);
- show_edits(~[1, 2, 3, 4], xs);
+ let xs = [7, 8];
+ show_edits([], xs);
+ show_edits([1], xs);
+ show_edits([1, 2], xs);
+ show_edits([1, 2, 3], xs);
+ show_edits([1, 2, 3, 4], xs);
}
fn main() { demo_edits(); }
// currently in the sendable kind, so we'll unsafely cast between ints.
type server = rustrt::server;
type client = rustrt::socket;
-tag pending_connection {
- remote(net::ip_addr,int);
- incoming(server);
-}
+tag pending_connection { remote(net::ip_addr, int); incoming(server); }
-tag socket_event {
- connected(client);
- closed;
- received([u8]);
-}
+tag socket_event { connected(client); closed; received([u8]); }
-tag server_event {
- pending(_chan<_chan<socket_event>>);
-}
+tag server_event { pending(_chan<_chan<socket_event>>); }
tag request {
quit;
- connect(pending_connection,_chan<socket_event>);
- serve(net::ip_addr,int,_chan<server_event>,_chan<server>);
- write(client,[u8],_chan<bool>);
+ connect(pending_connection, _chan<socket_event>);
+ serve(net::ip_addr, int, _chan<server_event>, _chan<server>);
+ write(client, [u8], _chan<bool>);
close_server(server, _chan<bool>);
close_client(client);
}
send(evt, connected(client));
- while (true) {
+ while true {
log "waiting for bytes";
let data: [u8] = reader.recv();
log "got some bytes";
log vec::len::<u8>(data);
- if (vec::len::<u8>(data) == 0u) {
+ if vec::len::<u8>(data) == 0u {
log "got empty buffer, bailing";
break;
}
fn server_task(ip: net::ip_addr, portnum: int, events: _chan<server_event>,
server: _chan<server>) {
let accepter: _port<client> = mk_port();
- send(server, rustrt::aio_serve(ip_to_sbuf(ip), portnum,
- accepter.mk_chan()));
+ send(server,
+ rustrt::aio_serve(ip_to_sbuf(ip), portnum, accepter.mk_chan()));
let client: client;
- while (true) {
+ while true {
log "preparing to accept a client";
client = accepter.recv();
- if (rustrt::aio_is_null_client(client)) {
- log "client was actually null, returning";
- ret;
- } else {
- task::_spawn(bind accept_task(client, events));
- }
+ if rustrt::aio_is_null_client(client) {
+ log "client was actually null, returning";
+ ret;
+ } else { task::_spawn(bind accept_task(client, events)); }
}
}
log "uv run task spawned";
// Spin for requests
let req: request;
- while (true) {
+ while true {
req = p.recv();
alt req {
quit. {
rustrt::aio_stop();
ret;
}
- connect(remote(ip,portnum),client) {
+ connect(remote(ip, portnum), client) {
task::_spawn(bind connect_task(ip, portnum, client));
}
- serve(ip,portnum,events,server) {
+ serve(ip, portnum, events, server) {
task::_spawn(bind server_task(ip, portnum, events, server));
}
- write(socket,v,status) {
- rustrt::aio_writedata(socket,
- vec::to_ptr::<u8>(v), vec::len::<u8>(v),
- status);
+ write(socket, v, status) {
+ rustrt::aio_writedata(socket, vec::to_ptr::<u8>(v),
+ vec::len::<u8>(v), status);
}
- close_server(server,status) {
+ close_server(server, status) {
log "closing server";
- rustrt::aio_close_server(server,status);
+ rustrt::aio_close_server(server, status);
}
close_client(client) {
log "closing client";
ret @{storage: storage, nbits: nbits};
}
-fn process(op: &block(uint, uint) -> uint , v0: &t, v1: &t) -> bool {
+fn process(op: &block(uint, uint) -> uint, v0: &t, v1: &t) -> bool {
let len = vec::len(v1.storage);
assert (vec::len(v0.storage) == len);
assert (v0.nbits == v1.nbits);
let changed = false;
for each i: uint in uint::range(0u, len) {
- let w0 = v0.storage.(i);
- let w1 = v1.storage.(i);
+ let w0 = v0.storage[i];
+ let w1 = v1.storage[i];
let w = op(w0, w1);
- if w0 != w { changed = true; v0.storage.(i) = w; }
+ if w0 != w { changed = true; v0.storage[i] = w; }
}
ret changed;
}
fn clone(v: t) -> t {
let storage = vec::init_elt_mut::<uint>(0u, v.nbits / uint_bits() + 1u);
let len = vec::len(v.storage);
- for each i: uint in uint::range(0u, len) { storage.(i) = v.storage.(i); }
+ for each i: uint in uint::range(0u, len) { storage[i] = v.storage[i]; }
ret @{storage: storage, nbits: v.nbits};
}
let bits = uint_bits();
let w = i / bits;
let b = i % bits;
- let x = 1u & v.storage.(w) >> b;
+ let x = 1u & v.storage[w] >> b;
ret x == 1u;
}
let len = vec::len(v1.storage);
let i = 0u;
while i < len {
- if v0.storage.(i) != v1.storage.(i) { ret false; }
+ if v0.storage[i] != v1.storage[i] { ret false; }
i = i + 1u;
}
ret true;
fn clear(v: &t) {
for each i: uint in uint::range(0u, vec::len(v.storage)) {
- v.storage.(i) = 0u;
+ v.storage[i] = 0u;
}
}
fn invert(v: &t) {
for each i: uint in uint::range(0u, vec::len(v.storage)) {
- v.storage.(i) = !v.storage.(i);
+ v.storage[i] = !v.storage[i];
}
}
let w = i / bits;
let b = i % bits;
let flag = 1u << b;
- v.storage.(w) =
- if x { v.storage.(w) | flag } else { v.storage.(w) & !flag };
+ v.storage[w] = if x { v.storage[w] | flag } else { v.storage[w] & !flag };
}
fn to_str(v: &t) -> str {
let rs = "";
- for i: uint in to_vec(v) {
- if i == 1u { rs += "1"; } else { rs += "0"; }
- }
+ for i: uint in to_vec(v) { if i == 1u { rs += "1"; } else { rs += "0"; } }
ret rs;
}
let i = 0u;
while i < len {
let w0 = get(v0, i);
- let w1 = v1.(i);
+ let w1 = v1[i];
if !w0 && w1 != 0u || w0 && w1 == 0u { ret false; }
i = i + 1u;
}
const ch_next_line: char = '\u0085';
const ch_no_break_space: char = '\u00a0';
- if c == ch_space { true }
- else if c == ch_ogham_space_mark { true }
- else if c == ch_mongolian_vowel_sep { true }
- else if c == ch_en_quad { true }
- else if c == ch_em_quad { true }
- else if c == ch_en_space { true }
- else if c == ch_em_space { true }
- else if c == ch_three_per_em_space { true }
- else if c == ch_four_per_em_space { true }
- else if c == ch_six_per_em_space { true }
- else if c == ch_figure_space { true }
- else if c == ch_punctuation_space { true }
- else if c == ch_thin_space { true }
- else if c == ch_hair_space { true }
- else if c == ch_narrow_no_break_space { true }
- else if c == ch_medium_mathematical_space { true }
- else if c == ch_ideographic_space { true }
- else if c == ch_line_tabulation { true }
- else if c == ch_paragraph_separator { true }
- else if c == ch_character_tabulation { true }
- else if c == ch_line_feed { true }
- else if c == ch_line_tabulation { true }
- else if c == ch_form_feed { true }
- else if c == ch_carriage_return { true }
- else if c == ch_next_line { true }
- else if c == ch_no_break_space { true }
- else { false }
-}
\ No newline at end of file
+ if c == ch_space {
+ true
+ } else if c == ch_ogham_space_mark {
+ true
+ } else if c == ch_mongolian_vowel_sep {
+ true
+ } else if c == ch_en_quad {
+ true
+ } else if c == ch_em_quad {
+ true
+ } else if c == ch_en_space {
+ true
+ } else if c == ch_em_space {
+ true
+ } else if c == ch_three_per_em_space {
+ true
+ } else if c == ch_four_per_em_space {
+ true
+ } else if c == ch_six_per_em_space {
+ true
+ } else if c == ch_figure_space {
+ true
+ } else if c == ch_punctuation_space {
+ true
+ } else if c == ch_thin_space {
+ true
+ } else if c == ch_hair_space {
+ true
+ } else if c == ch_narrow_no_break_space {
+ true
+ } else if c == ch_medium_mathematical_space {
+ true
+ } else if c == ch_ideographic_space {
+ true
+ } else if c == ch_line_tabulation {
+ true
+ } else if c == ch_paragraph_separator {
+ true
+ } else if c == ch_character_tabulation {
+ true
+ } else if c == ch_line_feed {
+ true
+ } else if c == ch_line_tabulation {
+ true
+ } else if c == ch_form_feed {
+ true
+ } else if c == ch_carriage_return {
+ true
+ } else if c == ch_next_line {
+ true
+ } else if c == ch_no_break_space { true } else { false }
+}
type void;
type rust_port;
- fn chan_id_send<~T>(target_task : task_id, target_port : port_id,
- data : -T);
+ fn chan_id_send<~T>(target_task: task_id, target_port: port_id, data: -T);
- fn new_port(unit_sz : uint) -> *rust_port;
- fn del_port(po : *rust_port);
- fn drop_port(po : *rust_port);
- fn get_port_id(po : *rust_port) -> port_id;
+ fn new_port(unit_sz: uint) -> *rust_port;
+ fn del_port(po: *rust_port);
+ fn drop_port(po: *rust_port);
+ fn get_port_id(po: *rust_port) -> port_id;
}
native "rust-intrinsic" mod rusti {
- fn recv<~T>(port : *rustrt::rust_port) -> T;
+ fn recv<~T>(port: *rustrt::rust_port) -> T;
}
type port_id = int;
-type chan_handle<~T> = { task : task_id, port : port_id};
+type chan_handle<~T> = {task: task_id, port: port_id};
tag chan<~T> { chan_t(chan_handle<T>); }
type _chan<~T> = chan<T>;
tag port<~T> { port_t(@port_ptr); }
-obj port_obj<~T>(raw_port : port<T>) {
- fn mk_chan() -> chan<T> {
- chan(raw_port)
- }
+obj port_obj<~T>(raw_port: port<T>) {
+ fn mk_chan() -> chan<T> { chan(raw_port) }
- fn recv() -> T {
- recv(raw_port)
- }
+ fn recv() -> T { recv(raw_port) }
}
type _port<~T> = port_obj<T>;
-fn mk_port<~T>() -> _port<T> {
- ret port_obj::<T>(port::<T>());
-}
+fn mk_port<~T>() -> _port<T> { ret port_obj::<T>(port::<T>()); }
-fn send<~T>(ch : &chan<T>, data : -T) {
+fn send<~T>(ch: &chan<T>, data: -T) {
rustrt::chan_id_send(ch.task, ch.port, data);
}
port_t(@port_ptr(rustrt::new_port(sys::size_of::<T>())))
}
-fn recv<~T>(p : &port<T>) -> T {
- ret rusti::recv(***p)
-}
+fn recv<~T>(p: &port<T>) -> T { ret rusti::recv(***p) }
-fn chan<~T>(p : &port<T>) -> chan<T> {
- chan_t({
- task: task::get_task_id(),
- port: rustrt::get_port_id(***p)
- })
+fn chan<~T>(p: &port<T>) -> chan<T> {
+ chan_t({task: task::get_task_id(), port: rustrt::get_port_id(***p)})
}
*/
type t<T> =
obj {
- fn size() -> uint ;
- fn add_front(&T) ;
- fn add_back(&T) ;
- fn pop_front() -> T ;
- fn pop_back() -> T ;
- fn peek_front() -> T ;
- fn peek_back() -> T ;
- fn get(int) -> T ;
+ fn size() -> uint;
+ fn add_front(&T);
+ fn add_back(&T);
+ fn pop_front() -> T;
+ fn pop_back() -> T;
+ fn peek_front() -> T;
+ fn peek_back() -> T;
+ fn get(int) -> T;
};
fn create<@T>() -> t<T> {
*/
+
fn grow<@T>(nelts: uint, lo: uint, elts: &[mutable cell<T>]) ->
[mutable cell<T>] {
assert (nelts == vec::len(elts));
- let rv = ~[mutable];
+ let rv = [mutable];
let i = 0u;
let nalloc = uint::next_power_of_two(nelts + 1u);
while i < nalloc {
if i < nelts {
- rv += ~[mutable elts.((lo + i) % nelts)];
- } else { rv += ~[mutable option::none]; }
+ rv += [mutable elts[(lo + i) % nelts]];
+ } else { rv += [mutable option::none]; }
i += 1u;
}
ret rv;
}
fn get<@T>(elts: &[mutable cell<T>], i: uint) -> T {
- ret alt elts.(i) { option::some(t) { t } _ { fail } };
+ ret alt elts[i] { option::some(t) { t } _ { fail } };
}
obj deque<@T>(mutable nelts: uint,
mutable lo: uint,
lo = vec::len::<cell<T>>(elts) - 1u;
hi = nelts;
}
- elts.(lo) = option::some::<T>(t);
+ elts[lo] = option::some::<T>(t);
nelts += 1u;
}
fn add_back(t: &T) {
lo = 0u;
hi = nelts;
}
- elts.(hi) = option::some::<T>(t);
+ elts[hi] = option::some::<T>(t);
hi = (hi + 1u) % vec::len::<cell<T>>(elts);
nelts += 1u;
}
*/
fn pop_front() -> T {
let t: T = get::<T>(elts, lo);
- elts.(lo) = option::none::<T>;
+ elts[lo] = option::none::<T>;
lo = (lo + 1u) % vec::len::<cell<T>>(elts);
nelts -= 1u;
ret t;
hi = vec::len::<cell<T>>(elts) - 1u;
} else { hi -= 1u; }
let t: T = get::<T>(elts, hi);
- elts.(hi) = option::none::<T>;
+ elts[hi] = option::none::<T>;
nelts -= 1u;
ret t;
}
type doc = {data: @[u8], start: uint, end: uint};
fn vint_at(data: &[u8], start: uint) -> {val: uint, next: uint} {
- let a = data.(start);
+ let a = data[start];
if a & 0x80u8 != 0u8 { ret {val: a & 0x7fu8 as uint, next: start + 1u}; }
if a & 0x40u8 != 0u8 {
- ret {val: (a & 0x3fu8 as uint) << 8u | (data.(start + 1u) as uint),
+ ret {val: (a & 0x3fu8 as uint) << 8u | (data[start + 1u] as uint),
next: start + 2u};
- } else if (a & 0x20u8 != 0u8) {
+ } else if a & 0x20u8 != 0u8 {
ret {val:
(a & 0x1fu8 as uint) << 16u |
- (data.(start + 1u) as uint) << 8u |
- (data.(start + 2u) as uint),
+ (data[start + 1u] as uint) << 8u |
+ (data[start + 2u] as uint),
next: start + 3u};
- } else if (a & 0x10u8 != 0u8) {
+ } else if a & 0x10u8 != 0u8 {
ret {val:
(a & 0x0fu8 as uint) << 24u |
- (data.(start + 1u) as uint) << 16u |
- (data.(start + 2u) as uint) << 8u |
- (data.(start + 3u) as uint),
+ (data[start + 1u] as uint) << 16u |
+ (data[start + 2u] as uint) << 8u |
+ (data[start + 3u] as uint),
next: start + 4u};
} else { log_err "vint too big"; fail; }
}
let pos = start;
while sz > 0u {
sz -= 1u;
- val += (data.(pos) as uint) << sz * 8u;
+ val += (data[pos] as uint) << sz * 8u;
pos += 1u;
}
ret val;
fn write_sized_vint(w: &io::buf_writer, n: uint, size: uint) {
let buf: [u8];
alt size {
- 1u { buf = ~[0x80u8 | (n as u8)]; }
- 2u { buf = ~[0x40u8 | (n >> 8u as u8), n & 0xffu as u8]; }
+ 1u { buf = [0x80u8 | (n as u8)]; }
+ 2u { buf = [0x40u8 | (n >> 8u as u8), n & 0xffu as u8]; }
3u {
buf =
- ~[0x20u8 | (n >> 16u as u8), n >> 8u & 0xffu as u8,
- n & 0xffu as u8];
+ [0x20u8 | (n >> 16u as u8), n >> 8u & 0xffu as u8,
+ n & 0xffu as u8];
}
4u {
buf =
- ~[0x10u8 | (n >> 24u as u8), n >> 16u & 0xffu as u8,
- n >> 8u & 0xffu as u8, n & 0xffu as u8];
+ [0x10u8 | (n >> 24u as u8), n >> 16u & 0xffu as u8,
+ n >> 8u & 0xffu as u8, n & 0xffu as u8];
}
_ { log_err "vint to write too big"; fail; }
}
}
fn create_writer(w: &io::buf_writer) -> writer {
- let size_positions: [uint] = ~[];
+ let size_positions: [uint] = [];
ret {writer: w, mutable size_positions: size_positions};
}
write_vint(w.writer, tag_id);
// Write a placeholder four-byte size.
- w.size_positions += ~[w.writer.tell()];
- let zeroes: [u8] = ~[0u8, 0u8, 0u8, 0u8];
+ w.size_positions += [w.writer.tell()];
+ let zeroes: [u8] = [0u8, 0u8, 0u8, 0u8];
w.writer.write(zeroes);
}
tag t<T, U> { left(T); right(U); }
-fn either<T, U, V>(f_left: &block(&T) -> V, f_right: &block(&U) -> V,
- value: &t<T, U>) -> V {
+fn either<T, U,
+ V>(f_left: &block(&T) -> V, f_right: &block(&U) -> V,
+ value: &t<T, U>) -> V {
alt value { left(l) { f_left(l) } right(r) { f_right(r) } }
}
fn lefts<T, U>(eithers: &[t<T, U>]) -> [T] {
- let result: [T] = ~[];
+ let result: [T] = [];
for elt: t<T, U> in eithers {
- alt elt { left(l) { result += ~[l] } _ {/* fallthrough */ } }
+ alt elt { left(l) { result += [l] } _ {/* fallthrough */ } }
}
ret result;
}
fn rights<T, U>(eithers: &[t<T, U>]) -> [U] {
- let result: [U] = ~[];
+ let result: [U] = [];
for elt: t<T, U> in eithers {
- alt elt { right(r) { result += ~[r] } _ {/* fallthrough */ } }
+ alt elt { right(r) { result += [r] } _ {/* fallthrough */ } }
}
ret result;
}
fn partition<T, U>(eithers: &[t<T, U>]) -> {lefts: [T], rights: [U]} {
- let lefts: [T] = ~[];
- let rights: [U] = ~[];
+ let lefts: [T] = [];
+ let rights: [U] = [];
for elt: t<T, U> in eithers {
- alt elt { left(l) { lefts += ~[l] } right(r) { rights += ~[r] } }
+ alt elt { left(l) { lefts += [l] } right(r) { rights += [r] } }
}
ret {lefts: lefts, rights: rights};
}
// A fragment of the output sequence
tag piece { piece_string(str); piece_conv(conv); }
- type error_fn = fn(str) -> ! ;
+ type error_fn = fn(str) -> ! ;
fn parse_fmt_string(s: str, error: error_fn) -> [piece] {
- let pieces: [piece] = ~[];
+ let pieces: [piece] = [];
let lim = str::byte_len(s);
let buf = "";
fn flush_buf(buf: str, pieces: &mutable [piece]) -> str {
if str::byte_len(buf) > 0u {
let piece = piece_string(buf);
- pieces += ~[piece];
+ pieces += [piece];
}
ret "";
}
} else {
buf = flush_buf(buf, pieces);
let rs = parse_conversion(s, i, lim, error);
- pieces += ~[rs.piece];
+ pieces += [rs.piece];
i = rs.next;
}
} else { buf += curr; i += 1u; }
fn peek_num(s: str, i: uint, lim: uint) ->
option::t<{num: uint, next: uint}> {
if i >= lim { ret none; }
- let c = s.(i);
+ let c = s[i];
if !('0' as u8 <= c && c <= '9' as u8) { ret option::none; }
let n = c - ('0' as u8) as uint;
ret alt peek_num(s, i + 1u, lim) {
some(t) {
let n = t.num;
let j = t.next;
- if j < lim && s.(j) == '$' as u8 {
+ if j < lim && s[j] == '$' as u8 {
{param: some(n as int), next: j + 1u}
} else { {param: none, next: i} }
}
}
fn parse_flags(s: str, i: uint, lim: uint) ->
{flags: [flag], next: uint} {
- let noflags: [flag] = ~[];
+ let noflags: [flag] = [];
if i >= lim { ret {flags: noflags, next: i}; }
// FIXME: This recursion generates illegal instructions if the return
let next = parse_flags(s, i + 1u, lim);
let rest = next.flags;
let j = next.next;
- let curr: [flag] = ~[f];
+ let curr: [flag] = [f];
ret @{flags: curr + rest, next: j};
}
let more = bind more_(_, s, i, lim);
- let f = s.(i);
+ let f = s[i];
ret if f == '-' as u8 {
*more(flag_left_justify)
- } else if (f == '0' as u8) {
+ } else if f == '0' as u8 {
*more(flag_left_zero_pad)
- } else if (f == ' ' as u8) {
+ } else if f == ' ' as u8 {
*more(flag_space_for_sign)
- } else if (f == '+' as u8) {
+ } else if f == '+' as u8 {
*more(flag_sign_always)
- } else if (f == '#' as u8) {
+ } else if f == '#' as u8 {
*more(flag_alternate)
} else { {flags: noflags, next: i} };
}
fn parse_count(s: str, i: uint, lim: uint) -> {count: count, next: uint} {
ret if i >= lim {
{count: count_implied, next: i}
- } else if (s.(i) == '*' as u8) {
+ } else if s[i] == '*' as u8 {
let param = parse_parameter(s, i + 1u, lim);
let j = param.next;
alt param.param {
{count: count, next: uint} {
ret if i >= lim {
{count: count_implied, next: i}
- } else if (s.(i) == '.' as u8) {
+ } else if s[i] == '.' as u8 {
let count = parse_count(s, i + 1u, lim);
let t =
if str::eq(tstr, "b") {
ty_bool
- } else if (str::eq(tstr, "s")) {
+ } else if str::eq(tstr, "s") {
ty_str
- } else if (str::eq(tstr, "c")) {
+ } else if str::eq(tstr, "c") {
ty_char
- } else if (str::eq(tstr, "d") || str::eq(tstr, "i")) {
+ } else if str::eq(tstr, "d") || str::eq(tstr, "i") {
ty_int(signed)
- } else if (str::eq(tstr, "u")) {
+ } else if str::eq(tstr, "u") {
ty_int(unsigned)
- } else if (str::eq(tstr, "x")) {
+ } else if str::eq(tstr, "x") {
ty_hex(case_lower)
- } else if (str::eq(tstr, "X")) {
+ } else if str::eq(tstr, "X") {
ty_hex(case_upper)
- } else if (str::eq(tstr, "t")) {
+ } else if str::eq(tstr, "t") {
ty_bits
- } else if (str::eq(tstr, "o")) {
+ } else if str::eq(tstr, "o") {
ty_octal
} else { error("unknown type in conversion: " + tstr) };
ret {ty: t, next: i + 1u};
if 0 <= i {
if have_flag(cv.flags, flag_sign_always) {
s = "+" + s;
- } else if (have_flag(cv.flags, flag_space_for_sign)) {
+ } else if have_flag(cv.flags, flag_space_for_sign) {
s = " " + s;
}
}
// instead.
if signed && zero_padding && str::byte_len(s) > 0u {
- let head = s.(0);
+ let head = s[0];
if head == '+' as u8 || head == '-' as u8 || head == ' ' as u8 {
- let headstr = str::unsafe_from_bytes(~[head]);
+ let headstr = str::unsafe_from_bytes([head]);
let bytelen = str::byte_len(s);
let numpart = str::substr(s, 1u, bytelen - 1u);
ret headstr + padstr + numpart;
// FIXME: Need some typestate to avoid bounds check when len(pre) == 0
fn connect(pre: path, post: path) -> path {
let len = str::byte_len(pre);
- ret if pre.(len - 1u) == os_fs::path_sep as u8 {
+ ret if pre[len - 1u] == os_fs::path_sep as u8 {
// Trailing '/'?
pre + post
fn list_dir(p: path) -> [str] {
let pl = str::byte_len(p);
- if pl == 0u || p.(pl - 1u) as char != os_fs::path_sep { p += path_sep(); }
- let full_paths: [str] = ~[];
+ if pl == 0u || p[pl - 1u] as char != os_fs::path_sep { p += path_sep(); }
+ let full_paths: [str] = [];
for filename: str in os_fs::list_dir(p) {
if !str::eq(filename, ".") {
- if !str::eq(filename, "..") { full_paths += ~[p + filename]; }
+ if !str::eq(filename, "..") { full_paths += [p + filename]; }
}
}
ret full_paths;
let res = os::kernel32::GetEnvironmentVariableA(nbuf, vbuf, nsize);
if res == 0u {
ret option::none;
- } else if (res < nsize) {
+ } else if res < nsize {
ret option::some(str::str_from_cstr(vbuf));
} else { nsize = res; }
}
type match = {opts: [opt], vals: [mutable [optval]], free: [str]};
fn is_arg(arg: str) -> bool {
- ret str::byte_len(arg) > 1u && arg.(0) == '-' as u8;
+ ret str::byte_len(arg) > 1u && arg[0] == '-' as u8;
}
fn name_str(nm: name) -> str {
fn find_opt(opts: &[opt], nm: name) -> option::t<uint> {
let i = 0u;
let l = vec::len::<opt>(opts);
- while i < l { if opts.(i).name == nm { ret some::<uint>(i); } i += 1u; }
+ while i < l { if opts[i].name == nm { ret some::<uint>(i); } i += 1u; }
ret none::<uint>;
}
fn getopts(args: &[str], opts: &[opt]) -> result {
let n_opts = vec::len::<opt>(opts);
- fn f(_x: uint) -> [optval] { ret ~[]; }
+ fn f(_x: uint) -> [optval] { ret []; }
let vals = vec::init_fn_mut::<[optval]>(f, n_opts);
- let free: [str] = ~[];
+ let free: [str] = [];
let l = vec::len::<str>(args);
let i = 0u;
while i < l {
- let cur = args.(i);
+ let cur = args[i];
let curlen = str::byte_len(cur);
if !is_arg(cur) {
- free += ~[cur];
- } else if (str::eq(cur, "--")) {
+ free += [cur];
+ } else if str::eq(cur, "--") {
let j = i + 1u;
- while j < l { free += ~[args.(j)]; j += 1u; }
+ while j < l { free += [args[j]]; j += 1u; }
break;
} else {
let names;
let i_arg = option::none::<str>;
- if cur.(1) == '-' as u8 {
+ if cur[1] == '-' as u8 {
let tail = str::slice(cur, 2u, curlen);
let eq = str::index(tail, '=' as u8);
if eq == -1 {
- names = ~[long(tail)];
+ names = [long(tail)];
} else {
- names = ~[long(str::slice(tail, 0u, eq as uint))];
+ names = [long(str::slice(tail, 0u, eq as uint))];
i_arg =
option::some::<str>(str::slice(tail,
(eq as uint) + 1u,
}
} else {
let j = 1u;
- names = ~[];
+ names = [];
while j < curlen {
let range = str::char_range_at(cur, j);
- names += ~[short(range.ch)];
+ names += [short(range.ch)];
j = range.next;
}
}
some(id) { optid = id; }
none. { ret failure(unrecognized_option(name_str(nm))); }
}
- alt opts.(optid).hasarg {
+ alt opts[optid].hasarg {
no. {
if !option::is_none::<str>(i_arg) {
ret failure(unexpected_argument(name_str(nm)));
}
- vals.(optid) += ~[given];
+ vals[optid] += [given];
}
maybe. {
if !option::is_none::<str>(i_arg) {
- vals.(optid) += ~[val(option::get(i_arg))];
- } else if (name_pos < vec::len::<name>(names) ||
- i + 1u == l || is_arg(args.(i + 1u))) {
- vals.(optid) += ~[given];
- } else { i += 1u; vals.(optid) += ~[val(args.(i))]; }
+ vals[optid] += [val(option::get(i_arg))];
+ } else if name_pos < vec::len::<name>(names) ||
+ i + 1u == l || is_arg(args[i + 1u]) {
+ vals[optid] += [given];
+ } else { i += 1u; vals[optid] += [val(args[i])]; }
}
yes. {
if !option::is_none::<str>(i_arg) {
- vals.(optid) += ~[val(option::get::<str>(i_arg))];
- } else if (i + 1u == l) {
+ vals[optid] += [val(option::get::<str>(i_arg))];
+ } else if i + 1u == l {
ret failure(argument_missing(name_str(nm)));
- } else { i += 1u; vals.(optid) += ~[val(args.(i))]; }
+ } else { i += 1u; vals[optid] += [val(args[i])]; }
}
}
}
}
i = 0u;
while i < n_opts {
- let n = vec::len::<optval>(vals.(i));
- let occ = opts.(i).occur;
+ let n = vec::len::<optval>(vals[i]);
+ let occ = opts[i].occur;
if occ == req {
if n == 0u {
- ret failure(option_missing(name_str(opts.(i).name)));
+ ret failure(option_missing(name_str(opts[i].name)));
}
}
if occ != multi {
if n > 1u {
- ret failure(option_duplicated(name_str(opts.(i).name)));
+ ret failure(option_duplicated(name_str(opts[i].name)));
}
}
i += 1u;
fn opt_vals(m: &match, nm: str) -> [optval] {
ret alt find_opt(m.opts, mkname(nm)) {
- some(id) { m.vals.(id) }
+ some(id) { m.vals[id] }
none. { log_err "No option '" + nm + "' defined."; fail }
};
}
-fn opt_val(m: &match, nm: str) -> optval { ret opt_vals(m, nm).(0); }
+fn opt_val(m: &match, nm: str) -> optval { ret opt_vals(m, nm)[0]; }
fn opt_present(m: &match, nm: str) -> bool {
ret vec::len::<optval>(opt_vals(m, nm)) > 0u;
}
fn opt_strs(m: &match, nm: str) -> [str] {
- let acc: [str] = ~[];
+ let acc: [str] = [];
for v: optval in opt_vals(m, nm) {
- alt v { val(s) { acc += ~[s]; } _ { } }
+ alt v { val(s) { acc += [s]; } _ { } }
}
ret acc;
}
fn opt_maybe_str(m: &match, nm: str) -> option::t<str> {
let vals = opt_vals(m, nm);
if vec::len::<optval>(vals) == 0u { ret none::<str>; }
- ret alt vals.(0) { val(s) { some::<str>(s) } _ { none::<str> } };
+ ret alt vals[0] { val(s) { some::<str>(s) } _ { none::<str> } };
}
fn opt_default(m: &match, nm: str, def: str) -> option::t<str> {
let vals = opt_vals(m, nm);
if vec::len::<optval>(vals) == 0u { ret none::<str>; }
- ret alt vals.(0) { val(s) { some::<str>(s) } _ { some::<str>(def) } }
+ ret alt vals[0] { val(s) { some::<str>(s) } _ { some::<str>(def) } }
}
// Local Variables:
// mode: rust;
fn pow(base: int, exponent: uint) -> int {
ret if exponent == 0u {
1
- } else if (base == 0) {
+ } else if base == 0 {
0
} else {
let accum = base;
// The raw underlying reader class. All readers must implement this.
type buf_reader =
-
// FIXME: Seekable really should be orthogonal. We will need
// inheritance.
obj {
- fn read(uint) -> [u8] ;
- fn read_byte() -> int ;
- fn unread_byte(int) ;
- fn eof() -> bool ;
- fn seek(int, seek_style) ;
- fn tell() -> uint ;
+ fn read(uint) -> [u8];
+ fn read_byte() -> int;
+ fn unread_byte(int);
+ fn eof() -> bool;
+ fn seek(int, seek_style);
+ fn tell() -> uint;
};
// Convenience methods for reading.
type reader =
-
// FIXME: This should inherit from buf_reader.
- // FIXME: eventually u64
+ // FIXME: eventually u64
obj {
- fn get_buf_reader() -> buf_reader ;
- fn read_byte() -> int ;
- fn unread_byte(int) ;
- fn read_bytes(uint) -> [u8] ;
- fn read_char() -> char ;
- fn eof() -> bool ;
- fn read_line() -> str ;
- fn read_c_str() -> str ;
- fn read_le_uint(uint) -> uint ;
- fn read_le_int(uint) -> int ;
- fn read_be_uint(uint) -> uint ;
- fn read_whole_stream() -> [u8] ;
- fn seek(int, seek_style) ;
- fn tell() -> uint ;
+ fn get_buf_reader() -> buf_reader;
+ fn read_byte() -> int;
+ fn unread_byte(int);
+ fn read_bytes(uint) -> [u8];
+ fn read_char() -> char;
+ fn eof() -> bool;
+ fn read_line() -> str;
+ fn read_c_str() -> str;
+ fn read_le_uint(uint) -> uint;
+ fn read_le_int(uint) -> int;
+ fn read_be_uint(uint) -> uint;
+ fn read_whole_stream() -> [u8];
+ fn seek(int, seek_style);
+ fn tell() -> uint;
};
fn convert_whence(whence: seek_style) -> int {
ret alt whence { seek_set. { 0 } seek_cur. { 1 } seek_end. { 2 } };
}
-resource FILE_res(f: os::libc::FILE) {
- os::libc::fclose(f);
-}
+resource FILE_res(f: os::libc::FILE) { os::libc::fclose(f); }
obj FILE_buf_reader(f: os::libc::FILE, res: option::t<@FILE_res>) {
fn read(len: uint) -> [u8] {
- let buf = ~[];
+ let buf = [];
vec::reserve::<u8>(buf, len);
let read = os::libc::fread(vec::to_ptr::<u8>(buf), 1u, len, f);
vec::unsafe::set_len::<u8>(buf, read);
fn seek(offset: int, whence: seek_style) {
assert (os::libc::fseek(f, offset, convert_whence(whence)) == 0);
}
- fn tell() -> uint {
- ret os::libc::ftell(f) as uint;
- }
+ fn tell() -> uint { ret os::libc::ftell(f) as uint; }
}
}
fn eof() -> bool { ret rdr.eof(); }
fn read_line() -> str {
- let buf: [u8] = ~[];
+ let buf: [u8] = [];
// No break yet in rustc
let go_on = true;
let ch = rdr.read_byte();
if ch == -1 || ch == 10 {
go_on = false;
- } else { buf += ~[ch as u8]; }
+ } else { buf += [ch as u8]; }
}
ret str::unsafe_from_bytes(buf);
}
fn read_c_str() -> str {
- let buf: [u8] = ~[];
+ let buf: [u8] = [];
let go_on = true;
while go_on {
let ch = rdr.read_byte();
- if ch < 1 { go_on = false; } else { buf += ~[ch as u8]; }
+ if ch < 1 { go_on = false; } else { buf += [ch as u8]; }
}
ret str::unsafe_from_bytes(buf);
}
ret val;
}
fn read_whole_stream() -> [u8] {
- let buf: [u8] = ~[];
+ let buf: [u8] = [];
while !rdr.eof() { buf += rdr.read(2048u); }
ret buf;
}
}
fn read_byte() -> int {
if bbuf.pos == vec::len::<u8>(bbuf.buf) { ret -1; }
- let b = bbuf.buf.(bbuf.pos);
+ let b = bbuf.buf[bbuf.pos];
bbuf.pos += 1u;
ret b as int;
}
tag fileflag { append; create; truncate; none; }
type buf_writer =
-
// FIXME: Seekable really should be orthogonal. We will need
// inheritance.
- // FIXME: eventually u64
+ // FIXME: eventually u64
obj {
- fn write(&[u8]) ;
- fn seek(int, seek_style) ;
- fn tell() -> uint ;
+ fn write(&[u8]);
+ fn seek(int, seek_style);
+ fn tell() -> uint;
};
obj FILE_writer(f: os::libc::FILE, res: option::t<@FILE_res>) {
fn seek(offset: int, whence: seek_style) {
assert (os::libc::fseek(f, offset, convert_whence(whence)) == 0);
}
- fn tell() -> uint {
- ret os::libc::ftell(f) as uint;
- }
+ fn tell() -> uint { ret os::libc::ftell(f) as uint; }
}
-resource fd_res(fd: int) {
- os::libc::close(fd);
-}
+resource fd_res(fd: int) { os::libc::close(fd); }
obj fd_buf_writer(fd: int, res: option::t<@fd_res>) {
fn write(v: &[u8]) {
}
type writer =
-
// write_str will continue to do utf-8 output only. an alternative
// function will be provided for general encoded string output
obj {
- fn get_buf_writer() -> buf_writer ;
- fn write_str(str) ;
- fn write_line(str) ;
- fn write_char(char) ;
- fn write_int(int) ;
- fn write_uint(uint) ;
- fn write_bytes(&[u8]) ;
- fn write_le_uint(uint, uint) ;
- fn write_le_int(int, uint) ;
- fn write_be_uint(uint, uint) ;
+ fn get_buf_writer() -> buf_writer;
+ fn write_str(str);
+ fn write_line(str);
+ fn write_char(char);
+ fn write_int(int);
+ fn write_uint(uint);
+ fn write_bytes(&[u8]);
+ fn write_le_uint(uint, uint);
+ fn write_le_int(int, uint);
+ fn write_be_uint(uint, uint);
};
fn uint_to_le_bytes(n: uint, size: uint) -> [u8] {
- let bytes: [u8] = ~[];
- while size > 0u { bytes += ~[n & 255u as u8]; n >>= 8u; size -= 1u; }
+ let bytes: [u8] = [];
+ while size > 0u { bytes += [n & 255u as u8]; n >>= 8u; size -= 1u; }
ret bytes;
}
fn uint_to_be_bytes(n: uint, size: uint) -> [u8] {
- let bytes: [u8] = ~[];
+ let bytes: [u8] = [];
let i = size - 1u as int;
- while i >= 0 { bytes += ~[n >> (i * 8 as uint) & 255u as u8]; i -= 1; }
+ while i >= 0 { bytes += [n >> (i * 8 as uint) & 255u as u8]; i -= 1; }
ret bytes;
}
out.write(str::bytes(str::from_char(ch)));
}
fn write_int(n: int) { out.write(str::bytes(int::to_str(n, 10u))); }
- fn write_uint(n: uint) {
- out.write(str::bytes(uint::to_str(n, 10u)));
- }
+ fn write_uint(n: uint) { out.write(str::bytes(uint::to_str(n, 10u))); }
fn write_bytes(bytes: &[u8]) { out.write(bytes); }
fn write_le_uint(n: uint, size: uint) {
out.write(uint_to_le_bytes(n, size));
type str_writer =
obj {
- fn get_writer() -> writer ;
- fn get_str() -> str ;
+ fn get_writer() -> writer;
+ fn get_str() -> str;
};
type mutable_byte_buf = @{mutable buf: [mutable u8], mutable pos: uint};
// Fast path.
if buf.pos == vec::len(buf.buf) {
- for b: u8 in v { buf.buf += ~[mutable b]; }
+ for b: u8 in v { buf.buf += [mutable b]; }
buf.pos += vec::len::<u8>(v);
ret;
}
let vlen = vec::len::<u8>(v);
let vpos = 0u;
while vpos < vlen {
- let b = v.(vpos);
+ let b = v[vpos];
if buf.pos == vec::len(buf.buf) {
- buf.buf += ~[mutable b];
- } else { buf.buf.(buf.pos) = b; }
+ buf.buf += [mutable b];
+ } else { buf.buf[buf.pos] = b; }
buf.pos += 1u;
vpos += 1u;
}
fn string_writer() -> str_writer {
// FIXME: yikes, this is bad. Needs fixing of mutable syntax.
- let b: [mutable u8] = ~[mutable 0u8];
+ let b: [mutable u8] = [mutable 0u8];
vec::pop(b);
let buf: mutable_byte_buf = @{mutable buf: b, mutable pos: 0u};
obj str_writer_wrap(wr: writer, buf: mutable_byte_buf) {
seek_cur. { bpos += offset; }
seek_end. { bpos = blen + offset; }
}
- if bpos < 0 { bpos = 0; } else if (bpos > blen) { bpos = blen; }
+ if bpos < 0 { bpos = 0; } else if bpos > blen { bpos = blen; }
ret bpos as uint;
}
}
fn read_whole_file(file: &str) -> [u8] {
+
// FIXME: There's a lot of copying here
file_reader(file).read_whole_stream()
}
ret l;
}
-fn foldl<@T, @U>(ls_: &list<T>, u: &U, f: &block(&T, &U) -> U ) -> U {
+fn foldl<@T, @U>(ls_: &list<T>, u: &U, f: &block(&T, &U) -> U) -> U {
let accum: U = u;
let ls = ls_;
while true {
ret accum;
}
-fn find<@T, @U>(ls_: &list<T>, f: &block(&T) -> option::t<U>)
- -> option::t<U> {
+fn find<@T, @U>(ls_: &list<T>, f: &block(&T) -> option::t<U>) ->
+ option::t<U> {
let ls = ls_;
while true {
alt ls {
}
fn cdr<@T>(ls: &list<T>) -> list<T> {
- alt ls {
- cons(_, tl) { ret *tl; }
- nil. { fail "list empty" }
- }
+ alt ls { cons(_, tl) { ret *tl; } nil. { fail "list empty" } }
}
fn car<@T>(ls: &list<T>) -> T {
- alt ls {
- cons(hd, _) { ret hd; }
- nil. { fail "list empty" }
- }
+ alt ls { cons(hd, _) { ret hd; } nil. { fail "list empty" } }
}
fn append<@T>(l: &list<T>, m: &list<T>) -> list<T> {
alt l {
nil. { ret m; }
- cons(x, xs) {
- let rest = append(*xs, m);
- ret cons(x, @rest);
- }
+ cons(x, xs) { let rest = append(*xs, m); ret cons(x, @rest); }
}
}
/**
* Hashmap implementation.
*/
-type hashfn<K> = fn(&K) -> uint ;
+type hashfn<K> = fn(&K) -> uint;
-type eqfn<K> = fn(&K, &K) -> bool ;
+type eqfn<K> = fn(&K, &K) -> bool;
type hashmap<K, V> =
obj {
- fn size() -> uint ;
- fn insert(&K, &V) -> bool ;
- fn contains_key(&K) -> bool ;
- fn get(&K) -> V ;
- fn find(&K) -> option::t<V> ;
- fn remove(&K) -> option::t<V> ;
- fn rehash() ;
- iter items() -> @{key: K, val: V} ;
- iter keys() -> K ;
+ fn size() -> uint;
+ fn insert(&K, &V) -> bool;
+ fn contains_key(&K) -> bool;
+ fn get(&K) -> V;
+ fn find(&K) -> option::t<V>;
+ fn remove(&K) -> option::t<V>;
+ fn rehash();
+ iter items() -> @{key: K, val: V};
+ iter keys() -> K;
};
type hashset<K> = hashmap<K, ()>;
let load_factor: util::rational = {num: 3, den: 4};
tag bucket<@K, @V> { nil; deleted; some(K, V); }
- fn make_buckets<@K, @V>(nbkts: uint) -> [mutable (bucket<K, V>)] {
+ fn make_buckets<@K, @V>(nbkts: uint) -> [mutable bucket<K, V>] {
ret vec::init_elt_mut::<bucket<K, V>>(nil::<K, V>, nbkts);
}
// Derive two hash functions from the one given by taking the upper
* will fail.
*/
- fn insert_common<@K, @V>(hasher: &hashfn<K>, eqer: &eqfn<K>,
- bkts: &[mutable bucket<K, V>], nbkts: uint,
- key: &K, val: &V) -> bool {
+ fn insert_common<@K,
+ @V>(hasher: &hashfn<K>, eqer: &eqfn<K>,
+ bkts: &[mutable bucket<K, V>], nbkts: uint, key: &K,
+ val: &V) -> bool {
let i: uint = 0u;
let h: uint = hasher(key);
while i < nbkts {
let j: uint = hash(h, nbkts, i);
- alt bkts.(j) {
+ alt bkts[j] {
some(k, _) {
// Copy key to please alias analysis.
let k_ = k;
- if eqer(key, k_) {
- bkts.(j) = some(k_, val);
- ret false;
- }
+ if eqer(key, k_) { bkts[j] = some(k_, val); ret false; }
i += 1u;
}
- _ { bkts.(j) = some(key, val); ret true; }
+ _ { bkts[j] = some(key, val); ret true; }
}
}
fail; // full table
}
- fn find_common<@K, @V>(hasher: &hashfn<K>, eqer: &eqfn<K>,
- bkts: &[mutable bucket<K, V>], nbkts: uint,
- key: &K) -> option::t<V> {
+ fn find_common<@K,
+ @V>(hasher: &hashfn<K>, eqer: &eqfn<K>,
+ bkts: &[mutable bucket<K, V>], nbkts: uint, key: &K) ->
+ option::t<V> {
let i: uint = 0u;
let h: uint = hasher(key);
while i < nbkts {
let j: uint = hash(h, nbkts, i);
- alt bkts.(j) {
+ alt bkts[j] {
some(k, v) {
// Copy to please alias analysis.
let k_ = k;
}
ret option::none;
}
- fn rehash<@K, @V>(hasher: &hashfn<K>, eqer: &eqfn<K>,
- oldbkts: &[mutable bucket<K, V>], _noldbkts: uint,
- newbkts: &[mutable bucket<K, V>], nnewbkts: uint) {
+ fn rehash<@K,
+ @V>(hasher: &hashfn<K>, eqer: &eqfn<K>,
+ oldbkts: &[mutable bucket<K, V>], _noldbkts: uint,
+ newbkts: &[mutable bucket<K, V>], nnewbkts: uint) {
for b: bucket<K, V> in oldbkts {
alt b {
some(k_, v_) {
}
}
}
- obj hashmap<@K, @V>(hasher: hashfn<K>,
- eqer: eqfn<K>,
- mutable bkts: [mutable bucket<K, V>],
- mutable nbkts: uint,
- mutable nelts: uint,
- lf: util::rational) {
+ obj hashmap<@K,
+ @V>(hasher: hashfn<K>,
+ eqer: eqfn<K>,
+ mutable bkts: [mutable bucket<K, V>],
+ mutable nbkts: uint,
+ mutable nelts: uint,
+ lf: util::rational) {
fn size() -> uint { ret nelts; }
fn insert(key: &K, val: &V) -> bool {
let load: util::rational =
let h: uint = hasher(key);
while i < nbkts {
let j: uint = hash(h, nbkts, i);
- alt bkts.(j) {
+ alt bkts[j] {
some(k, v) {
let k_ = k;
let vo = option::some(v);
if eqer(key, k_) {
- bkts.(j) = deleted;
+ bkts[j] = deleted;
nelts -= 1u;
ret vo;
}
import vec;
import uint;
-tag ip_addr {
- ipv4(u8, u8, u8, u8);
-}
+tag ip_addr { ipv4(u8, u8, u8, u8); }
-fn format_addr(ip : ip_addr) -> str {
- alt(ip) {
+fn format_addr(ip: ip_addr) -> str {
+ alt ip {
ipv4(a, b, c, d) {
- #fmt("%u.%u.%u.%u",
- a as uint,
- b as uint,
- c as uint,
- d as uint)
+ #fmt["%u.%u.%u.%u", a as uint, b as uint, c as uint, d as uint]
}
_ { fail "Unsupported address type"; }
}
}
-fn parse_addr(ip : str) -> ip_addr {
- let parts = vec::map(uint::from_str, str::split(ip, ".".(0)));
+fn parse_addr(ip: str) -> ip_addr {
+ let parts = vec::map(uint::from_str, str::split(ip, "."[0]));
if vec::len(parts) != 4u { fail "Too many dots in IP address"; }
for i in parts { if i > 255u { fail "Invalid IP Address part."; } }
- ipv4(parts.(0) as u8,
- parts.(1) as u8,
- parts.(2) as u8,
- parts.(3) as u8)
+ ipv4(parts[0] as u8, parts[1] as u8, parts[2] as u8, parts[3] as u8)
}
tag t<@T> { none; some(T); }
fn get<@T>(opt: &t<T>) -> T {
- alt opt {
- some(x) { x }
- none. { fail "option none" }
- }
+ alt opt { some(x) { x } none. { fail "option none" } }
}
fn map<@T, @U>(f: &block(&T) -> U, opt: &t<T>) -> t<U> {
fn rand_free(c: rctx);
}
-type rng = obj { fn next() -> u32; };
+type rng =
+ obj {
+ fn next() -> u32;
+ };
-resource rand_res(c: rustrt::rctx) {
- rustrt::rand_free(c);
-}
+resource rand_res(c: rustrt::rctx) { rustrt::rand_free(c); }
fn mk_rng() -> rng {
obj rt_rng(c: @rand_res) {
- fn next() -> u32 {
- ret rustrt::rand_next(**c);
- }
+ fn next() -> u32 { ret rustrt::rand_next(**c); }
}
ret rt_rng(@rand_res(rustrt::rand_new()));
}
}
fn arg_vec(prog: str, args: &[str]) -> [sbuf] {
- let argptrs = ~[str::buf(prog)];
- for arg: str in args { argptrs += ~[str::buf(arg)]; }
- argptrs += ~[0 as sbuf];
+ let argptrs = [str::buf(prog)];
+ for arg: str in args { argptrs += [str::buf(arg)]; }
+ argptrs += [0 as sbuf];
ret argptrs;
}
// Note: we have to hold on to this vector reference while we hold a
// pointer to its buffer
let argv = arg_vec(prog, args);
- let pid = rustrt::rust_run_program(
- vec::to_ptr(argv), in_fd, out_fd, err_fd);
+ let pid =
+ rustrt::rust_run_program(vec::to_ptr(argv), in_fd, out_fd, err_fd);
ret pid;
}
fn destroy();
};
-resource program_res(p: program) {
- p.destroy();
-}
+resource program_res(p: program) { p.destroy(); }
fn start_program(prog: str, args: &[str]) -> @program_res {
let pipe_input = os::pipe();
let pipe_output = os::pipe();
let pipe_err = os::pipe();
- let pid = spawn_process(prog, args, pipe_input.in, pipe_output.out,
- pipe_err.out);
+ let pid =
+ spawn_process(prog, args, pipe_input.in, pipe_output.out,
+ pipe_err.out);
if pid == -1 { fail; }
os::libc::close(pipe_input.in);
mutable finished: bool) {
fn get_id() -> int { ret pid; }
fn input() -> io::writer {
- ret io::new_writer(
- io::fd_buf_writer(in_fd, option::none));
+ ret io::new_writer(io::fd_buf_writer(in_fd, option::none));
}
fn output() -> io::reader {
- ret io::new_reader(
- io::FILE_buf_reader(out_file, option::none));
+ ret io::new_reader(io::FILE_buf_reader(out_file, option::none));
}
fn err() -> io::reader {
- ret io::new_reader(
- io::FILE_buf_reader(err_file, option::none));
+ ret io::new_reader(io::FILE_buf_reader(err_file, option::none));
}
fn close_input() {
let invalid_fd = -1;
os::libc::fclose(err_file);
}
}
- ret @program_res(new_program(pid,
- pipe_input.out,
+ ret @program_res(new_program(pid, pipe_input.out,
os::fd_FILE(pipe_output.in),
- os::fd_FILE(pipe_err.in),
- false));
+ os::fd_FILE(pipe_err.in), false));
}
fn read_all(rd: &io::reader) -> str {
ret buf;
}
-fn program_output(prog: str, args: [str])
- -> {status: int, out: str, err: str} {
+fn program_output(prog: str, args: [str]) ->
+ {status: int, out: str, err: str} {
let pr = start_program(prog, args);
pr.close_input();
ret {status: pr.finish(),
export mk_sha1;
type sha1 =
-
// Provide message input as bytes
// Reset the sha1 state for reuse. This is called
// automatically during construction
obj {
- fn input(&[u8]) ;
- fn input_str(&str) ;
- fn result() -> [u8] ;
- fn result_str() -> str ;
- fn reset() ;
+ fn input(&[u8]);
+ fn input_str(&str);
+ fn result() -> [u8];
+ fn result_str() -> str;
+ fn reset();
};
assert (!st.computed);
for element: u8 in msg {
- st.msg_block.(st.msg_block_idx) = element;
+ st.msg_block[st.msg_block_idx] = element;
st.msg_block_idx += 1u;
st.len_low += 8u32;
if st.len_low == 0u32 {
t = 0;
while t < 16 {
let tmp;
- tmp = (st.msg_block.(t * 4) as u32) << 24u32;
- tmp = tmp | (st.msg_block.(t * 4 + 1) as u32) << 16u32;
- tmp = tmp | (st.msg_block.(t * 4 + 2) as u32) << 8u32;
- tmp = tmp | (st.msg_block.(t * 4 + 3) as u32);
- w.(t) = tmp;
+ tmp = (st.msg_block[t * 4] as u32) << 24u32;
+ tmp = tmp | (st.msg_block[t * 4 + 1] as u32) << 16u32;
+ tmp = tmp | (st.msg_block[t * 4 + 2] as u32) << 8u32;
+ tmp = tmp | (st.msg_block[t * 4 + 3] as u32);
+ w[t] = tmp;
t += 1;
}
// Initialize the rest of vector w
while t < 80 {
- let val = w.(t - 3) ^ w.(t - 8) ^ w.(t - 14) ^ w.(t - 16);
- w.(t) = circular_shift(1u32, val);
+ let val = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16];
+ w[t] = circular_shift(1u32, val);
t += 1;
}
- let a = st.h.(0);
- let b = st.h.(1);
- let c = st.h.(2);
- let d = st.h.(3);
- let e = st.h.(4);
+ let a = st.h[0];
+ let b = st.h[1];
+ let c = st.h[2];
+ let d = st.h[3];
+ let e = st.h[4];
let temp: u32;
t = 0;
while t < 20 {
- temp =
- circular_shift(5u32, a) + (b & c | !b & d) + e + w.(t) + k0;
+ temp = circular_shift(5u32, a) + (b & c | !b & d) + e + w[t] + k0;
e = d;
d = c;
c = circular_shift(30u32, b);
t += 1;
}
while t < 40 {
- temp = circular_shift(5u32, a) + (b ^ c ^ d) + e + w.(t) + k1;
+ temp = circular_shift(5u32, a) + (b ^ c ^ d) + e + w[t] + k1;
e = d;
d = c;
c = circular_shift(30u32, b);
}
while t < 60 {
temp =
- circular_shift(5u32, a) + (b & c | b & d | c & d) + e + w.(t)
- + k2;
+ circular_shift(5u32, a) + (b & c | b & d | c & d) + e + w[t] +
+ k2;
e = d;
d = c;
c = circular_shift(30u32, b);
t += 1;
}
while t < 80 {
- temp = circular_shift(5u32, a) + (b ^ c ^ d) + e + w.(t) + k3;
+ temp = circular_shift(5u32, a) + (b ^ c ^ d) + e + w[t] + k3;
e = d;
d = c;
c = circular_shift(30u32, b);
a = temp;
t += 1;
}
- st.h.(0) = st.h.(0) + a;
- st.h.(1) = st.h.(1) + b;
- st.h.(2) = st.h.(2) + c;
- st.h.(3) = st.h.(3) + d;
- st.h.(4) = st.h.(4) + e;
+ st.h[0] = st.h[0] + a;
+ st.h[1] = st.h[1] + b;
+ st.h[2] = st.h[2] + c;
+ st.h[3] = st.h[3] + d;
+ st.h[4] = st.h[4] + e;
st.msg_block_idx = 0u;
}
fn circular_shift(bits: u32, word: u32) -> u32 {
}
fn mk_result(st: &sha1state) -> [u8] {
if !st.computed { pad_msg(st); st.computed = true; }
- let rs: [u8] = ~[];
+ let rs: [u8] = [];
for hpart: u32 in st.h {
let a = hpart >> 24u32 & 0xFFu32 as u8;
let b = hpart >> 16u32 & 0xFFu32 as u8;
let c = hpart >> 8u32 & 0xFFu32 as u8;
let d = hpart & 0xFFu32 as u8;
- rs += ~[a, b, c, d];
+ rs += [a, b, c, d];
}
ret rs;
}
*/
if st.msg_block_idx > 55u {
- st.msg_block.(st.msg_block_idx) = 0x80u8;
+ st.msg_block[st.msg_block_idx] = 0x80u8;
st.msg_block_idx += 1u;
while st.msg_block_idx < msg_block_len {
- st.msg_block.(st.msg_block_idx) = 0u8;
+ st.msg_block[st.msg_block_idx] = 0u8;
st.msg_block_idx += 1u;
}
process_msg_block(st);
} else {
- st.msg_block.(st.msg_block_idx) = 0x80u8;
+ st.msg_block[st.msg_block_idx] = 0x80u8;
st.msg_block_idx += 1u;
}
while st.msg_block_idx < 56u {
- st.msg_block.(st.msg_block_idx) = 0u8;
+ st.msg_block[st.msg_block_idx] = 0u8;
st.msg_block_idx += 1u;
}
// Store the message length as the last 8 octets
- st.msg_block.(56) = st.len_high >> 24u32 & 0xFFu32 as u8;
- st.msg_block.(57) = st.len_high >> 16u32 & 0xFFu32 as u8;
- st.msg_block.(58) = st.len_high >> 8u32 & 0xFFu32 as u8;
- st.msg_block.(59) = st.len_high & 0xFFu32 as u8;
- st.msg_block.(60) = st.len_low >> 24u32 & 0xFFu32 as u8;
- st.msg_block.(61) = st.len_low >> 16u32 & 0xFFu32 as u8;
- st.msg_block.(62) = st.len_low >> 8u32 & 0xFFu32 as u8;
- st.msg_block.(63) = st.len_low & 0xFFu32 as u8;
+ st.msg_block[56] = st.len_high >> 24u32 & 0xFFu32 as u8;
+ st.msg_block[57] = st.len_high >> 16u32 & 0xFFu32 as u8;
+ st.msg_block[58] = st.len_high >> 8u32 & 0xFFu32 as u8;
+ st.msg_block[59] = st.len_high & 0xFFu32 as u8;
+ st.msg_block[60] = st.len_low >> 24u32 & 0xFFu32 as u8;
+ st.msg_block[61] = st.len_low >> 16u32 & 0xFFu32 as u8;
+ st.msg_block[62] = st.len_low >> 8u32 & 0xFFu32 as u8;
+ st.msg_block[63] = st.len_low & 0xFFu32 as u8;
process_msg_block(st);
}
obj sha1(st: sha1state) {
st.len_low = 0u32;
st.len_high = 0u32;
st.msg_block_idx = 0u;
- st.h.(0) = 0x67452301u32;
- st.h.(1) = 0xEFCDAB89u32;
- st.h.(2) = 0x98BADCFEu32;
- st.h.(3) = 0x10325476u32;
- st.h.(4) = 0xC3D2E1F0u32;
+ st.h[0] = 0x67452301u32;
+ st.h[1] = 0xEFCDAB89u32;
+ st.h[2] = 0x98BADCFEu32;
+ st.h[3] = 0x10325476u32;
+ st.h[4] = 0xC3D2E1F0u32;
st.computed = false;
}
fn input(msg: &[u8]) { add_input(st, msg); }
import net;
type ctx = aio::ctx;
-type client = { ctx: ctx, client: aio::client,
- evt: _port<aio::socket_event> };
-type server = { ctx: ctx, server: aio::server,
- evt: _port<aio::server_event> };
+type client = {ctx: ctx, client: aio::client, evt: _port<aio::socket_event>};
+type server = {ctx: ctx, server: aio::server, evt: _port<aio::server_event>};
-fn new() -> ctx {
- ret aio::new();
-}
+fn new() -> ctx { ret aio::new(); }
-fn destroy(ctx: ctx) {
- send(ctx, aio::quit);
-}
+fn destroy(ctx: ctx) { send(ctx, aio::quit); }
fn make_socket(ctx: ctx, p: _port<aio::socket_event>) -> client {
let evt: aio::socket_event = p.recv();
alt evt {
- aio::connected(client) {
- ret { ctx: ctx, client: client, evt: p };
- }
+ aio::connected(client) { ret {ctx: ctx, client: client, evt: p}; }
_ { fail "Could not connect to client"; }
}
}
fn read(c: client) -> [u8] {
alt c.evt.recv() {
- aio::closed. {
- ret ~[];
- }
- aio::received(buf) {
- ret buf;
- }
+ aio::closed. { ret []; }
+ aio::received(buf) { ret buf; }
}
}
fn create_server(ctx: ctx, ip: net::ip_addr, portnum: int) -> server {
let evt: _port<aio::server_event> = mk_port();
let p: _port<aio::server> = mk_port();
- send(ctx, aio::serve(ip, portnum,
- evt.mk_chan(), p.mk_chan()));
+ send(ctx, aio::serve(ip, portnum, evt.mk_chan(), p.mk_chan()));
let srv: aio::server = p.recv();
- ret { ctx: ctx, server: srv, evt: evt };
+ ret {ctx: ctx, server: srv, evt: evt};
}
fn accept_from(server: server) -> client {
fn close_client(client: client) {
send(client.ctx, aio::close_client(client.client));
let evt: aio::socket_event;
- do {
- evt = client.evt.recv();
- alt evt {
- aio::closed. {
- ret;
- }
- _ {}
- }
- } while (true);
+ do { evt = client.evt.recv(); alt evt { aio::closed. { ret; } _ { } } }
+ while true
}
// Local Variables:
type smallintmap<T> = @{mutable v: [mutable option::t<T>]};
fn mk<@T>() -> smallintmap<T> {
- let v: [mutable option::t<T>] = ~[mutable];
+ let v: [mutable option::t<T>] = [mutable];
ret @{mutable v: v};
}
}
fn find<@T>(m: &smallintmap<T>, key: uint) -> option::t<T> {
- if key < vec::len::<option::t<T>>(m.v) { ret m.v.(key); }
+ if key < vec::len::<option::t<T>>(m.v) { ret m.v[key]; }
ret none::<T>;
}
export quick_sort;
export quick_sort3;
-type lteq<T> = block(&T, &T) -> bool ;
+type lteq<T> = block(&T, &T) -> bool;
fn merge_sort<@T>(le: <eq<T>, v: &[T]) -> [T] {
fn merge<@T>(le: <eq<T>, a: &[T], b: &[T]) -> [T] {
- let rs: [T] = ~[];
+ let rs: [T] = [];
let a_len: uint = len::<T>(a);
let a_ix: uint = 0u;
let b_len: uint = len::<T>(b);
let b_ix: uint = 0u;
while a_ix < a_len && b_ix < b_len {
- if le(a.(a_ix), b.(b_ix)) {
- rs += ~[a.(a_ix)];
+ if le(a[a_ix], b[b_ix]) {
+ rs += [a[a_ix]];
a_ix += 1u;
- } else { rs += ~[b.(b_ix)]; b_ix += 1u; }
+ } else { rs += [b[b_ix]]; b_ix += 1u; }
}
rs += slice::<T>(a, a_ix, a_len);
rs += slice::<T>(b, b_ix, b_len);
}
fn swap<@T>(arr: &[mutable T], x: uint, y: uint) {
- let a = arr.(x);
- arr.(x) = arr.(y);
- arr.(y) = a;
+ let a = arr[x];
+ arr[x] = arr[y];
+ arr[y] = a;
}
fn part<@T>(compare_func: <eq<T>, arr: &[mutable T], left: uint,
right: uint, pivot: uint) -> uint {
- let pivot_value = arr.(pivot);
+ let pivot_value = arr[pivot];
swap::<T>(arr, pivot, right);
let storage_index: uint = left;
let i: uint = left;
while i < right {
- if compare_func({ arr.(i) }, pivot_value) {
+ if compare_func({ arr[i] }, pivot_value) {
swap::<T>(arr, i, storage_index);
storage_index += 1u;
}
fn qsort3<@T>(compare_func_lt: <eq<T>, compare_func_eq: <eq<T>,
arr: &[mutable T], left: int, right: int) {
if right <= left { ret; }
- let v: T = arr.(right);
+ let v: T = arr[right];
let i: int = left - 1;
let j: int = right;
let p: int = i;
let q: int = j;
while true {
i += 1;
- while compare_func_lt({ arr.(i) }, v) { i += 1; }
+ while compare_func_lt({ arr[i] }, v) { i += 1; }
j -= 1;
- while compare_func_lt(v, { arr.(j) }) {
+ while compare_func_lt(v, { arr[j] }) {
if j == left { break; }
j -= 1;
}
if i >= j { break; }
swap::<T>(arr, i as uint, j as uint);
- if compare_func_eq({ arr.(i) }, v) {
+ if compare_func_eq({ arr[i] }, v) {
p += 1;
swap::<T>(arr, p as uint, i as uint);
}
- if compare_func_eq(v, { arr.(j) }) {
+ if compare_func_eq(v, { arr[j] }) {
q -= 1;
swap::<T>(arr, j as uint, q as uint);
}
arr: &[mutable T]) {
if len::<T>(arr) == 0u { ret; }
qsort3::<T>(compare_func_lt, compare_func_eq, arr, 0,
- (len::<T>(arr) as int) - 1);
+ (len::<T>(arr) as int) - 1);
}
// Local Variables:
if byte_len(b) != i { ret false; }
while i > 0u {
i -= 1u;
- let cha = a.(i);
- let chb = b.(i);
+ let cha = a[i];
+ let chb = b[i];
if cha != chb { ret false; }
}
ret true;
if j < n { n = j; }
let x: uint = 0u;
while x < n {
- let cha = a.(x);
- let chb = b.(x);
- if cha < chb { ret true; } else if (cha > chb) { ret false; }
+ let cha = a[x];
+ let chb = b[x];
+ if cha < chb { ret true; } else if cha > chb { ret false; }
x += 1u;
}
ret i <= j;
let i = 0u;
let total = vec::len::<u8>(v);
while i < total {
- let chsize = utf8_char_width(v.(i));
+ let chsize = utf8_char_width(v[i]);
if chsize == 0u { ret false; }
if i + chsize > total { ret false; }
i += 1u;
while chsize > 1u {
- if v.(i) & 192u8 != tag_cont_u8 { ret false; }
+ if v[i] & 192u8 != tag_cont_u8 { ret false; }
i += 1u;
chsize -= 1u;
}
fn is_ascii(s: str) -> bool {
let i: uint = byte_len(s);
- while i > 0u { i -= 1u; if s.(i) & 128u8 != 0u8 { ret false; } }
+ while i > 0u { i -= 1u; if s[i] & 128u8 != 0u8 { ret false; } }
ret true;
}
let i = 0u;
let len = char_len(s);
while i < len {
- if !char::is_whitespace(char_at(s, i)) {
- ret false;
- }
+ if !char::is_whitespace(char_at(s, i)) { ret false; }
i += 1u
}
ret true;
ret rustrt::str_from_ivec(v);
}
-fn unsafe_from_byte(u: u8) -> str { ret rustrt::str_from_ivec(~[u]); }
+fn unsafe_from_byte(u: u8) -> str { ret rustrt::str_from_ivec([u]); }
fn str_from_cstr(cstr: sbuf) -> str { ret rustrt::str_from_cstr(cstr); }
let code = ch as uint;
if code < max_one_b {
s = rustrt::str_push_byte(s, code);
- } else if (code < max_two_b) {
+ } else if code < max_two_b {
s = rustrt::str_push_byte(s, code >> 6u & 31u | tag_two_b);
s = rustrt::str_push_byte(s, code & 63u | tag_cont);
- } else if (code < max_three_b) {
+ } else if code < max_three_b {
s = rustrt::str_push_byte(s, code >> 12u & 15u | tag_three_b);
s = rustrt::str_push_byte(s, code >> 6u & 63u | tag_cont);
s = rustrt::str_push_byte(s, code & 63u | tag_cont);
- } else if (code < max_four_b) {
+ } else if code < max_four_b {
s = rustrt::str_push_byte(s, code >> 18u & 7u | tag_four_b);
s = rustrt::str_push_byte(s, code >> 12u & 63u | tag_cont);
s = rustrt::str_push_byte(s, code >> 6u & 63u | tag_cont);
s = rustrt::str_push_byte(s, code & 63u | tag_cont);
- } else if (code < max_five_b) {
+ } else if code < max_five_b {
s = rustrt::str_push_byte(s, code >> 24u & 3u | tag_five_b);
s = rustrt::str_push_byte(s, code >> 18u & 63u | tag_cont);
s = rustrt::str_push_byte(s, code >> 12u & 63u | tag_cont);
}
fn char_range_at(s: str, i: uint) -> {ch: char, next: uint} {
- let b0 = s.(i);
+ let b0 = s[i];
let w = utf8_char_width(b0);
assert (w != 0u);
if w == 1u { ret {ch: b0 as char, next: i + 1u}; }
let end = i + w;
i += 1u;
while i < end {
- let byte = s.(i);
+ let byte = s[i];
assert (byte & 192u8 == tag_cont_u8);
val <<= 6u;
val += byte & 63u8 as uint;
let len = 0u;
let total = byte_len(s);
while i < total {
- let chsize = utf8_char_width(s.(i));
+ let chsize = utf8_char_width(s[i]);
assert (chsize > 0u);
len += 1u;
i += chsize;
}
fn to_chars(s: str) -> [char] {
- let buf: [char] = ~[];
+ let buf: [char] = [];
let i = 0u;
let len = byte_len(s);
while i < len {
let cur = char_range_at(s, i);
- buf += ~[cur.ch];
+ buf += [cur.ch];
i = cur.next;
}
ret buf;
fn pop_char(s: &mutable str) -> char {
let end = byte_len(s);
- while end > 0u && s.(end - 1u) & 192u8 == tag_cont_u8 { end -= 1u; }
+ while end > 0u && s[end - 1u] & 192u8 == tag_cont_u8 { end -= 1u; }
assert (end > 0u);
let ch = char_at(s, end - 1u);
s = substr(s, 0u, end - 1u);
fn rindex(s: str, c: u8) -> int {
let n: int = str::byte_len(s) as int;
- while n >= 0 { if s.(n) == c { ret n; } n -= 1; }
+ while n >= 0 { if s[n] == c { ret n; } n -= 1; }
ret n;
}
if needle_len == 0 { ret 0; }
fn match_at(haystack: &str, needle: &str, i: int) -> bool {
let j: int = i;
- for c: u8 in needle { if haystack.(j) != c { ret false; } j += 1; }
+ for c: u8 in needle { if haystack[j] != c { ret false; } j += 1; }
ret true;
}
let i: int = 0;
let needle_len: uint = byte_len(needle);
ret if needle_len == 0u {
true
- } else if (needle_len > haystack_len) {
+ } else if needle_len > haystack_len {
false
} else {
eq(substr(haystack, haystack_len - needle_len, needle_len),
ret rustrt::str_slice(s, begin, end);
}
-fn safe_slice(s: str, begin: uint, end: uint): le(begin, end) -> str {
+fn safe_slice(s: str, begin: uint, end: uint) : le(begin, end) -> str {
assert (end <=
str::byte_len(s)); // would need some magic to
// make this a precondition
+
ret rustrt::str_slice(s, begin, end);
}
fn shift_byte(s: &mutable str) -> u8 {
let len = byte_len(s);
assert (len > 0u);
- let b = s.(0);
+ let b = s[0];
s = substr(s, 1u, len - 1u);
ret b;
}
fn pop_byte(s: &mutable str) -> u8 {
let len = byte_len(s);
assert (len > 0u);
- let b = s.(len - 1u);
+ let b = s[len - 1u];
s = substr(s, 0u, len - 1u);
ret b;
}
}
fn split(s: str, sep: u8) -> [str] {
- let v: [str] = ~[];
+ let v: [str] = [];
let accum: str = "";
let ends_with_sep: bool = false;
for c: u8 in s {
if c == sep {
- v += ~[accum];
+ v += [accum];
accum = "";
ends_with_sep = true;
} else { accum += unsafe_from_byte(c); ends_with_sep = false; }
}
- if str::byte_len(accum) != 0u || ends_with_sep { v += ~[accum]; }
+ if str::byte_len(accum) != 0u || ends_with_sep { v += [accum]; }
ret v;
}
check (is_not_empty(from));
if byte_len(s) == 0u {
ret "";
- } else if (starts_with(s, from)) {
+ } else if starts_with(s, from) {
ret to + replace(slice(s, byte_len(from), byte_len(s)), from, to);
} else {
- ret unsafe_from_byte(s.(0)) +
+ ret unsafe_from_byte(s[0]) +
replace(slice(s, 1u, byte_len(s)), from, to);
}
}
fn count_whities(s: &[char]) -> uint {
let i = 0u;
while i < vec::len(s) {
- if !char::is_whitespace(s.(i)) {
- break;
- }
+ if !char::is_whitespace(s[i]) { break; }
i += 1u;
}
ret i;
fn count_whities(s: &[char]) -> uint {
let i = vec::len(s);
while 0u < i {
- if !char::is_whitespace(s.(i - 1u)) {
- break;
- }
+ if !char::is_whitespace(s[i - 1u]) { break; }
i -= 1u;
}
ret i;
ret from_chars(vec::slice(chars, 0u, whities));
}
-fn trim(s: &str) -> str {
- trim_left(trim_right(s))
-}
+fn trim(s: &str) -> str { trim_left(trim_right(s)) }
// Local Variables:
// mode: rust;
fn set_min_stack(stack_size: uint);
fn new_task() -> task_id;
- fn drop_task(task : *rust_task);
- fn get_task_pointer(id : task_id) -> *rust_task;
- fn start_task(id : task_id);
+ fn drop_task(task: *rust_task);
+ fn get_task_pointer(id: task_id) -> *rust_task;
+ fn start_task(id: task_id);
fn get_task_trampoline() -> u32;
- fn migrate_alloc(alloc : *u8, target : task_id);
+ fn migrate_alloc(alloc: *u8, target: task_id);
- fn leak<@T>(thing : -T);
+ fn leak<@T>(thing: -T);
}
-type rust_task = {
- id : task,
- mutable notify_enabled : u8,
- mutable notify_chan : comm::chan_handle<task_notification>,
- ctx : task_context,
- stack_ptr : *u8
-};
-
-type task_context = {
- regs : x86_registers,
- next : *u8
-};
-
-resource rust_task_ptr(task : *rust_task) {
- rustrt::drop_task(task);
-}
+type rust_task =
+ {id: task,
+ mutable notify_enabled: u8,
+ mutable notify_chan: comm::chan_handle<task_notification>,
+ ctx: task_context,
+ stack_ptr: *u8};
+
+type task_context = {regs: x86_registers, next: *u8};
+
+resource rust_task_ptr(task: *rust_task) { rustrt::drop_task(task); }
-fn get_task_ptr(id : task) -> rust_task_ptr {
+fn get_task_ptr(id: task) -> rust_task_ptr {
ret rust_task_ptr(rustrt::get_task_pointer(id));
}
type task = int;
type task_id = task;
-fn get_task_id() -> task_id {
- rustrt::get_task_id()
-}
+fn get_task_id() -> task_id { rustrt::get_task_id() }
/**
* Hints the scheduler to yield this task for a specified ammount of time.
tag task_result { tr_success; tr_failure; }
-tag task_notification {
- exit(task, task_result);
-}
+tag task_notification { exit(task, task_result); }
-fn join(task_port : (task_id, comm::port<task_notification>))
- -> task_result {
+fn join(task_port: (task_id, comm::port<task_notification>)) -> task_result {
let (id, port) = task_port;
alt comm::recv::<task_notification>(port) {
exit(_id, res) {
- if _id == id { ret res }
- else { fail #fmt("join received id %d, expected %d", _id, id) }
+ if _id == id {
+ ret res
+ } else { fail #fmt["join received id %d, expected %d", _id, id] }
}
}
}
-fn join_id(t : task_id) -> task_result {
+fn join_id(t: task_id) -> task_result {
alt rustrt::task_join(t) { 0 { tr_success } _ { tr_failure } }
}
fn unpin() { rustrt::unpin_task(); }
-fn set_min_stack(stack_size : uint) {
- rustrt::set_min_stack(stack_size);
-}
+fn set_min_stack(stack_size: uint) { rustrt::set_min_stack(stack_size); }
-fn _spawn(thunk : -fn() -> ()) -> task {
- spawn(thunk)
-}
+fn _spawn(thunk: -fn()) -> task { spawn(thunk) }
-fn spawn(thunk : -fn() -> ()) -> task {
- spawn_inner(thunk, none)
-}
+fn spawn(thunk: -fn()) -> task { spawn_inner(thunk, none) }
-fn spawn_notify(thunk : -fn() -> (), notify : comm::chan<task_notification>)
- -> task {
+fn spawn_notify(thunk: -fn(), notify: comm::chan<task_notification>) -> task {
spawn_inner(thunk, some(notify))
}
-fn spawn_joinable(thunk : -fn()) -> (task_id, comm::port<task_notification>) {
+fn spawn_joinable(thunk: -fn()) -> (task_id, comm::port<task_notification>) {
let p = comm::port::<task_notification>();
let id = spawn_notify(thunk, comm::chan::<task_notification>(p));
ret (id, p);
}
// FIXME: make this a fn~ once those are supported.
-fn spawn_inner(thunk : -fn() -> (),
- notify : option<comm::chan<task_notification>>)
- -> task_id {
+fn spawn_inner(thunk: -fn(), notify: option<comm::chan<task_notification>>) ->
+ task_id {
let id = rustrt::new_task();
// the order of arguments are outptr, taskptr, envptr.
// set up the task pointer
let task_ptr = get_task_ptr(id);
let regs = ptr::addr_of((**task_ptr).ctx.regs);
- (*regs).edx = cast(*task_ptr);
+ (*regs).edx = cast(*task_ptr);;
(*regs).esp = cast((**task_ptr).stack_ptr);
- assert ptr::null() != (**task_ptr).stack_ptr;
+ assert (ptr::null() != (**task_ptr).stack_ptr);
- let raw_thunk : { code: u32, env: u32 } = cast(thunk);
+ let raw_thunk: {code: u32, env: u32} = cast(thunk);
(*regs).eip = raw_thunk.code;
// set up notifications if they are enabled.
alt notify {
some(c) {
- (**task_ptr).notify_enabled = 1u8;
+ (**task_ptr).notify_enabled = 1u8;;
(**task_ptr).notify_chan = *c;
}
- none {}
+ none { }
};
// okay, now we align the stack and add the environment pointer and a fake
// -4 for the return address.
(*regs).esp = align_down((*regs).esp - 12u32) - 4u32;
- let ra : *mutable u32 = cast((*regs).esp);
- let env : *mutable u32 = cast((*regs).esp+4u32);
- let tptr : *mutable u32 = cast((*regs).esp+12u32);
+ let ra: *mutable u32 = cast((*regs).esp);
+ let env: *mutable u32 = cast((*regs).esp + 4u32);
+ let tptr: *mutable u32 = cast((*regs).esp + 12u32);
// put the return pointer in ecx.
- (*regs).ecx = (*regs).esp + 8u32;
+ (*regs).ecx = (*regs).esp + 8u32;;
- *tptr = cast(*task_ptr);
- *env = raw_thunk.env;
+ *tptr = cast(*task_ptr);;
+ *env = raw_thunk.env;;
*ra = rustrt::get_task_trampoline();
rustrt::migrate_alloc(cast(raw_thunk.env), id);
}
// Who says we can't write an operating system in Rust?
-type x86_registers = {
+type x86_registers =
// This needs to match the structure in context.h
- mutable eax : u32,
- mutable ebx : u32,
- mutable ecx : u32,
- mutable edx : u32,
- mutable ebp : u32,
- mutable esi : u32,
- mutable edi : u32,
- mutable esp : u32,
-
- mutable cs : u16,
- mutable ds : u16,
- mutable ss : u16,
- mutable es : u16,
- mutable fs : u16,
- mutable gs : u16,
-
- mutable eflags : u32,
- mutable eip : u32
-};
-
-fn align_down(x : u32) -> u32 {
+
+
+ {mutable eax: u32,
+ mutable ebx: u32,
+ mutable ecx: u32,
+ mutable edx: u32,
+ mutable ebp: u32,
+ mutable esi: u32,
+ mutable edi: u32,
+ mutable esp: u32,
+ mutable cs: u16,
+ mutable ds: u16,
+ mutable ss: u16,
+ mutable es: u16,
+ mutable fs: u16,
+ mutable gs: u16,
+ mutable eflags: u32,
+ mutable eip: u32};
+
+fn align_down(x: u32) -> u32 {
+
// Aligns x down to 16 bytes
- x & !(15u32)
+ x & !15u32
}
// Local Variables:
const color_bright_white: u8 = 15u8;
-fn esc(writer: io::buf_writer) { writer.write(~[0x1bu8, '[' as u8]); }
+fn esc(writer: io::buf_writer) { writer.write([0x1bu8, '[' as u8]); }
fn reset(writer: io::buf_writer) {
esc(writer);
- writer.write(~['0' as u8, 'm' as u8]);
+ writer.write(['0' as u8, 'm' as u8]);
}
fn color_supported() -> bool {
- let supported_terms = ~["xterm-color", "xterm", "screen-bce"];
+ let supported_terms = ["xterm-color", "xterm", "screen-bce"];
ret alt generic_os::getenv("TERM") {
option::some(env) {
for term: str in supported_terms {
fn set_color(writer: io::buf_writer, first_char: u8, color: u8) {
assert (color < 16u8);
esc(writer);
- if color >= 8u8 { writer.write(~['1' as u8, ';' as u8]); color -= 8u8; }
- writer.write(~[first_char, ('0' as u8) + color, 'm' as u8]);
+ if color >= 8u8 { writer.write(['1' as u8, ';' as u8]); color -= 8u8; }
+ writer.write([first_char, ('0' as u8) + color, 'm' as u8]);
}
fn fg(writer: io::buf_writer, color: u8) {
// the test succeeds; if the function fails then the test fails. We
// may need to come up with a more clever definition of test in order
// to support isolation of tests into tasks.
-type test_fn = fn() ;
+type test_fn = fn();
// The definition of a single test. A test runner will run a list of
// these.
// FIXME (#649): Shouldn't have to check here
check (vec::is_not_empty(args));
let args_ = vec::tail(args);
- let opts = ~[getopts::optflag("ignored")];
+ let opts = [getopts::optflag("ignored")];
let match =
alt getopts::getopts(args_, opts) {
getopts::success(m) { m }
let filter =
if vec::len(match.free) > 0u {
- option::some(match.free.(0))
+ option::some(match.free[0])
} else { option::none };
let run_ignored = getopts::opt_present(match, "ignored");
fn run_tests_console_(opts: &test_opts, tests: &[test_desc],
to_task: &test_to_task) -> bool {
- type test_state = @{
- out: io::writer,
- use_color: bool,
- mutable total: uint,
- mutable passed: uint,
- mutable failed: uint,
- mutable ignored: uint,
- mutable failures: [test_desc]
- };
+ type test_state =
+ @{out: io::writer,
+ use_color: bool,
+ mutable total: uint,
+ mutable passed: uint,
+ mutable failed: uint,
+ mutable ignored: uint,
+ mutable failures: [test_desc]};
fn callback(event: testevent, st: test_state) {
alt event {
te_filtered(filtered_tests) {
st.total = vec::len(filtered_tests);
- st.out.write_line(#fmt("\nrunning %u tests", st.total));
- }
- te_wait(test) {
- st.out.write_str(#fmt("test %s ... ", test.name));
+ st.out.write_line(#fmt["\nrunning %u tests", st.total]);
}
+ te_wait(test) { st.out.write_str(#fmt["test %s ... ", test.name]); }
te_result(test, result) {
alt result {
tr_ok. {
st.failed += 1u;
write_failed(st.out, st.use_color);
st.out.write_line("");
- st.failures += ~[test];
+ st.failures += [test];
}
tr_ignored. {
st.ignored += 1u;
}
}
- let st = @{
- out: io::stdout(),
- use_color: use_color(),
- mutable total: 0u,
- mutable passed: 0u,
- mutable failed: 0u,
- mutable ignored: 0u,
- mutable failures: ~[]
- };
+ let st =
+ @{out: io::stdout(),
+ use_color: use_color(),
+ mutable total: 0u,
+ mutable passed: 0u,
+ mutable failed: 0u,
+ mutable ignored: 0u,
+ mutable failures: []};
- run_tests(opts, tests, to_task,
- bind callback(_, st));
+ run_tests(opts, tests, to_task, bind callback(_, st));
- assert st.passed + st.failed + st.ignored == st.total;
+ assert (st.passed + st.failed + st.ignored == st.total);
let success = st.failed == 0u;
if !success {
st.out.write_line("\nfailures:");
for test: test_desc in st.failures {
let testname = test.name; // Satisfy alias analysis
- st.out.write_line(#fmt(" %s", testname));
+ st.out.write_line(#fmt[" %s", testname]);
}
}
- st.out.write_str(#fmt("\nresult: "));
+ st.out.write_str(#fmt["\nresult: "]);
if success {
// There's no parallelism at this point so it's safe to use color
write_ok(st.out, true);
} else { write_failed(st.out, true); }
- st.out.write_str(#fmt(". %u passed; %u failed; %u ignored\n\n",
- st.passed, st.failed, st.ignored));
+ st.out.write_str(#fmt[". %u passed; %u failed; %u ignored\n\n", st.passed,
+ st.failed, st.ignored]);
ret success;
}
}
-fn use_color() -> bool {
- ret get_concurrency() == 1u;
-}
+fn use_color() -> bool { ret get_concurrency() == 1u; }
tag testevent {
te_filtered([test_desc]);
te_result(test_desc, test_result);
}
-fn run_tests(opts: &test_opts, tests: &[test_desc],
- to_task: &test_to_task, callback: fn(testevent)) {
+fn run_tests(opts: &test_opts, tests: &[test_desc], to_task: &test_to_task,
+ callback: fn(testevent)) {
let filtered_tests = filter_tests(opts, tests);
// provide a great user experience because you might sit waiting for the
// result of a particular test for an unusually long amount of time.
let concurrency = get_concurrency();
- log #fmt("using %u test tasks", concurrency);
+ log #fmt["using %u test tasks", concurrency];
let total = vec::len(filtered_tests);
let run_idx = 0u;
let wait_idx = 0u;
- let futures = ~[];
+ let futures = [];
while wait_idx < total {
while vec::len(futures) < concurrency && run_idx < total {
- futures += ~[run_test(filtered_tests.(run_idx), to_task)];
+ futures += [run_test(filtered_tests[run_idx], to_task)];
run_idx += 1u;
}
- let future = futures.(0);
+ let future = futures[0];
callback(te_wait(future.test));
let result = future.wait();
callback(te_result(future.test, result));
ret filtered;
}
-type test_future =
- {test: test_desc, wait: fn() -> test_result };
+type test_future = {test: test_desc, wait: fn() -> test_result};
fn run_test(test: &test_desc, to_task: &test_to_task) -> test_future {
if !test.ignore {
let test_task = to_task(test.fn);
ret {test: test,
wait:
- bind fn (test_task: joinable)-> test_result {
- alt task::join(test_task) {
- task::tr_success. { tr_ok }
- task::tr_failure. { tr_failed }
- }
- }(test_task)};
- } else {
- ret {test: test,
- wait: fn () -> test_result { tr_ignored }};
- }
+ bind fn (test_task: joinable) -> test_result {
+ alt task::join(test_task) {
+ task::tr_success. { tr_ok }
+ task::tr_failure. { tr_failed }
+ }
+ }(test_task)};
+ } else { ret {test: test, wait: fn () -> test_result { tr_ignored }}; }
}
// We need to run our tests in another task in order to trap test failures.
// This function only works with functions that don't contain closures.
fn default_test_to_task(f: &fn()) -> joinable {
- fn run_task(f: fn()) {
- configure_test_task();
- f();
- }
+ fn run_task(f: fn()) { configure_test_task(); f(); }
ret task::spawn_joinable(bind run_task(f));
}
fn precise_time_s() -> float {
ret (precise_time_ns() as float) / 1000000000.;
-}
\ No newline at end of file
+}
ret s;
}
-fn str(n: u64) -> str { ret to_str(n, 10u); }
\ No newline at end of file
+fn str(n: u64) -> str { ret to_str(n, 10u); }
type ufind = {mutable nodes: [mutable node]};
-fn make() -> ufind { ret {mutable nodes: ~[mutable]}; }
+fn make() -> ufind { ret {mutable nodes: [mutable]}; }
fn make_set(ufnd: &ufind) -> uint {
let idx = vec::len(ufnd.nodes);
- ufnd.nodes += ~[mutable none::<uint>];
+ ufnd.nodes += [mutable none::<uint>];
ret idx;
}
}
fn find(ufnd: &ufind, n: uint) -> uint {
- alt ufnd.nodes.(n) {
+ alt ufnd.nodes[n] {
none. { ret n; }
some(m) { let m_ = m; be find(ufnd, m_); }
}
let m_root = find(ufnd, m);
let n_root = find(ufnd, n);
if m_root < n_root {
- ufnd.nodes.(n_root) = some::<uint>(m_root);
- } else if (m_root > n_root) {
- ufnd.nodes.(m_root) = some::<uint>(n_root);
- }
+ ufnd.nodes[n_root] = some::<uint>(m_root);
+ } else if m_root > n_root { ufnd.nodes[m_root] = some::<uint>(n_root); }
}
fn set_count(ufnd: &ufind) -> uint { ret vec::len::<node>(ufnd.nodes); }
let power = 1u;
let n = 0u;
while true {
- n += (buf.(i) - ('0' as u8) as uint) * power;
+ n += (buf[i] - ('0' as u8) as uint) * power;
power *= radix;
if i == 0u { ret n; }
i -= 1u;
fail;
}
-fn from_str(s : &str) -> uint {
- parse_buf(str::bytes(s), 10u)
-}
+fn from_str(s: &str) -> uint { parse_buf(str::bytes(s), 10u) }
fn to_str(num: uint, radix: uint) -> str {
let n = num;
}
let s1: str = "";
let len: uint = str::byte_len(s);
- while len != 0u { len -= 1u; s1 += str::unsafe_from_byte(s.(len)); }
+ while len != 0u { len -= 1u; s1 += str::unsafe_from_byte(s[len]); }
ret s1;
}
fn str(i: uint) -> str { ret to_str(i, 10u); }
fn len<T>(v: &[mutable? T]) -> uint { ret rusti::ivec_len(v); }
-type init_op<T> = fn(uint) -> T ;
+type init_op<T> = fn(uint) -> T;
fn init_fn<@T>(op: &init_op<T>, n_elts: uint) -> [T] {
- let v = ~[];
+ let v = [];
reserve(v, n_elts);
let i: uint = 0u;
- while i < n_elts { v += ~[op(i)]; i += 1u; }
+ while i < n_elts { v += [op(i)]; i += 1u; }
ret v;
}
// TODO: Remove me once we have slots.
fn init_fn_mut<@T>(op: &init_op<T>, n_elts: uint) -> [mutable T] {
- let v = ~[mutable];
+ let v = [mutable];
reserve(v, n_elts);
let i: uint = 0u;
- while i < n_elts { v += ~[mutable op(i)]; i += 1u; }
+ while i < n_elts { v += [mutable op(i)]; i += 1u; }
ret v;
}
fn init_elt<@T>(t: &T, n_elts: uint) -> [T] {
- let v = ~[];
+ let v = [];
reserve(v, n_elts);
let i: uint = 0u;
- while i < n_elts { v += ~[t]; i += 1u; }
+ while i < n_elts { v += [t]; i += 1u; }
ret v;
}
// TODO: Remove me once we have slots.
fn init_elt_mut<@T>(t: &T, n_elts: uint) -> [mutable T] {
- let v = ~[mutable];
+ let v = [mutable];
reserve(v, n_elts);
let i: uint = 0u;
- while i < n_elts { v += ~[mutable t]; i += 1u; }
+ while i < n_elts { v += [mutable t]; i += 1u; }
ret v;
}
fn to_mut<@T>(v: &[T]) -> [mutable T] {
- let vres = ~[mutable];
- for t: T in v { vres += ~[mutable t]; }
+ let vres = [mutable];
+ for t: T in v { vres += [mutable t]; }
ret vres;
}
fn from_mut<@T>(v: &[mutable T]) -> [T] {
- let vres = ~[];
- for t: T in v { vres += ~[t]; }
+ let vres = [];
+ for t: T in v { vres += [t]; }
ret vres;
}
// Accessors
/// Returns the first element of a vector
-fn head<@T>(v: &[mutable? T]) : is_not_empty(v) -> T { ret v.(0); }
+fn head<@T>(v: &[mutable? T]) : is_not_empty(v) -> T { ret v[0]; }
/// Returns all but the first element of a vector
fn tail<@T>(v: &[mutable? T]) : is_not_empty(v) -> [mutable? T] {
/// Returns the last element of `v`.
fn last<@T>(v: &[mutable? T]) -> option::t<T> {
if len(v) == 0u { ret none; }
- ret some(v.(len(v) - 1u));
+ ret some(v[len(v) - 1u]);
}
/// Returns a copy of the elements from [`start`..`end`) from `v`.
fn slice<@T>(v: &[mutable? T], start: uint, end: uint) -> [T] {
assert (start <= end);
assert (end <= len(v));
- let result = ~[];
+ let result = [];
reserve(result, end - start);
let i = start;
- while i < end { result += ~[v.(i)]; i += 1u; }
+ while i < end { result += [v[i]]; i += 1u; }
ret result;
}
fn slice_mut<@T>(v: &[mutable? T], start: uint, end: uint) -> [mutable T] {
assert (start <= end);
assert (end <= len(v));
- let result = ~[mutable];
+ let result = [mutable];
reserve(result, end - start);
let i = start;
- while i < end { result += ~[mutable v.(i)]; i += 1u; }
+ while i < end { result += [mutable v[i]]; i += 1u; }
ret result;
}
fn shift<@T>(v: &mutable [mutable? T]) -> T {
let ln = len::<T>(v);
assert (ln > 0u);
- let e = v.(0);
+ let e = v[0];
v = slice::<T>(v, 1u, ln);
ret e;
}
let ln = len(v);
assert (ln > 0u);
ln -= 1u;
- let e = v.(ln);
+ let e = v[ln];
v = slice(v, 0u, ln);
ret e;
}
fn grow<@T>(v: &mutable [T], n: uint, initval: &T) {
reserve(v, next_power_of_two(len(v) + n));
let i: uint = 0u;
- while i < n { v += ~[initval]; i += 1u; }
+ while i < n { v += [initval]; i += 1u; }
}
// TODO: Remove me once we have slots.
fn grow_mut<@T>(v: &mutable [mutable T], n: uint, initval: &T) {
reserve(v, next_power_of_two(len(v) + n));
let i: uint = 0u;
- while i < n { v += ~[mutable initval]; i += 1u; }
+ while i < n { v += [mutable initval]; i += 1u; }
}
/// Calls `f` `n` times and appends the results of these calls to the given
/// vector.
-fn grow_fn<@T>(v: &mutable [T], n: uint, init_fn: fn(uint) -> T ) {
+fn grow_fn<@T>(v: &mutable [T], n: uint, init_fn: fn(uint) -> T) {
reserve(v, next_power_of_two(len(v) + n));
let i: uint = 0u;
- while i < n { v += ~[init_fn(i)]; i += 1u; }
+ while i < n { v += [init_fn(i)]; i += 1u; }
}
/// Sets the element at position `index` to `val`. If `index` is past the end
/// intervening space.
fn grow_set<@T>(v: &mutable [mutable T], index: uint, initval: &T, val: &T) {
if index >= len(v) { grow_mut(v, index - len(v) + 1u, initval); }
- v.(index) = val;
+ v[index] = val;
}
// Functional utilities
-fn map<@T, @U>(f: &block(&T) -> U , v: &[mutable? T]) -> [U] {
- let result = ~[];
+fn map<@T, @U>(f: &block(&T) -> U, v: &[mutable? T]) -> [U] {
+ let result = [];
reserve(result, len(v));
for elem: T in v {
let elem2 = elem; // satisfies alias checker
- result += ~[f(elem2)];
+ result += [f(elem2)];
}
ret result;
}
-fn map2<@T, @U, @V>(f: &block(&T, &U) -> V, v0: &[T], v1: &[U])
- -> [V] {
+fn map2<@T, @U, @V>(f: &block(&T, &U) -> V, v0: &[T], v1: &[U]) -> [V] {
let v0_len = len::<T>(v0);
if v0_len != len::<U>(v1) { fail; }
- let u: [V] = ~[];
+ let u: [V] = [];
let i = 0u;
- while i < v0_len { u += ~[f({ v0.(i) }, { v1.(i) })]; i += 1u; }
+ while i < v0_len { u += [f({ v0[i] }, { v1[i] })]; i += 1u; }
ret u;
}
-fn filter_map<@T, @U>(f: &block(&T) -> option::t<U>,
- v: &[mutable? T]) -> [U] {
- let result = ~[];
+fn filter_map<@T, @U>(f: &block(&T) -> option::t<U>, v: &[mutable? T]) ->
+ [U] {
+ let result = [];
for elem: T in v {
let elem2 = elem; // satisfies alias checker
alt f(elem2) {
none. {/* no-op */ }
- some(result_elem) { result += ~[result_elem]; }
+ some(result_elem) { result += [result_elem]; }
}
}
ret result;
}
-fn foldl<@T, @U>(p: &block(&U, &T) -> U , z: &U, v: &[mutable? T]) -> U {
+fn foldl<@T, @U>(p: &block(&U, &T) -> U, z: &U, v: &[mutable? T]) -> U {
let sz = len(v);
if sz == 0u { ret z; }
- let first = v.(0);
+ let first = v[0];
let rest = slice(v, 1u, sz);
ret p(foldl(p, z, rest), first);
}
fn position<@T>(x: &T, v: &[T]) -> option::t<uint> {
let i: uint = 0u;
- while i < len(v) { if x == v.(i) { ret some::<uint>(i); } i += 1u; }
+ while i < len(v) { if x == v[i] { ret some::<uint>(i); } i += 1u; }
ret none;
}
fn position_pred<T>(f: fn(&T) -> bool, v: &[T]) -> option::t<uint> {
let i: uint = 0u;
- while i < len(v) { if f(v.(i)) { ret some::<uint>(i); } i += 1u; }
+ while i < len(v) { if f(v[i]) { ret some::<uint>(i); } i += 1u; }
ret none;
}
fn unzip<@T, @U>(v: &[(T, U)]) -> ([T], [U]) {
- let as = ~[], bs = ~[];
- for (a, b) in v {
- as += ~[a];
- bs += ~[b];
- }
+ let as = [], bs = [];
+ for (a, b) in v { as += [a]; bs += [b]; }
ret (as, bs);
}
// FIXME make the lengths being equal a constraint
fn zip<@T, @U>(v: &[T], u: &[U]) -> [(T, U)] {
- let zipped = ~[];
+ let zipped = [];
let sz = len(v), i = 0u;
assert (sz == len(u));
- while i < sz {
- zipped += ~[(v.(i), u.(i))];
- i += 1u;
- }
+ while i < sz { zipped += [(v[i], u[i])]; i += 1u; }
ret zipped;
}
// Swaps two elements in a vector
fn swap<@T>(v: &[mutable T], a: uint, b: uint) {
- let t: T = v.(a);
- v.(a) = v.(b);
- v.(b) = t;
+ let t: T = v[a];
+ v[a] = v[b];
+ v[b] = t;
}
// In place vector reversal
// Functional vector reversal. Returns a reversed copy of v.
fn reversed<@T>(v: &[T]) -> [T] {
- let rs: [T] = ~[];
+ let rs: [T] = [];
let i = len::<T>(v);
if i == 0u { ret rs; } else { i -= 1u; }
- while i != 0u { rs += ~[v.(i)]; i -= 1u; }
- rs += ~[v.(0)];
+ while i != 0u { rs += [v[i]]; i -= 1u; }
+ rs += [v[0]];
ret rs;
}
}
fn from_buf<T>(ptr: *T, bytes: uint) -> [T] {
- let v = ~[];
+ let v = [];
copy_from_buf(v, ptr, bytes);
ret v;
}
fn rust_file_is_dir(path: str) -> int;
}
-fn list_dir(path: str) -> [str] {
- ret *rustrt::rust_list_files(path + "*");
-}
+fn list_dir(path: str) -> [str] { ret *rustrt::rust_list_files(path + "*"); }
fn path_is_absolute(p: str) -> bool {
ret str::char_at(p, 0u) == '/' ||
fn O_TRUNC() -> int { ret 512; }
fn O_TEXT() -> int { ret 16384; }
fn O_BINARY() -> int { ret 32768; }
- fn O_NOINHERIT() -> int { ret 0x0080; }
+ fn O_NOINHERIT() -> int { ret 128; }
fn S_IRUSR() -> uint {
ret 256u; // really _S_IREAD in win32
// which means to pass it to a subprocess they need to be duplicated
// first, as in rust_run_program.
let fds = {mutable in: 0, mutable out: 0};
- let res = os::libc::_pipe(ptr::addr_of(fds.in), 1024u,
- libc_constants::O_BINARY()
- | libc_constants::O_NOINHERIT());
- assert res == 0;
- assert fds.in != -1 && fds.in != 0;
- assert fds.out != -1 && fds.in != 0;
+ let res =
+ os::libc::_pipe(ptr::addr_of(fds.in), 1024u,
+ libc_constants::O_BINARY() |
+ libc_constants::O_NOINHERIT());
+ assert (res == 0);
+ assert (fds.in != -1 && fds.in != 0);
+ assert (fds.out != -1 && fds.in != 0);
ret {in: fds.in, out: fds.out};
}
_ { ns = int::to_str(n, 10u) + " bottles"; }
}
while i < str::byte_len(t) {
- if t.(i) == '#' as u8 { b += ns; } else { str::push_byte(b, t.(i)); }
+ if t[i] == '#' as u8 { b += ns; } else { str::push_byte(b, t[i]); }
i += 1u;
}
ret b;
let b: bottle = multiple(99);
let running: bool = true;
while running { show(b); log ""; running = more(b); b = next(b); }
-}
\ No newline at end of file
+}
_ { ns = int::to_str(n, 10u) + " bottles"; }
}
while i < str::byte_len(t) {
- if t.(i) == '#' as u8 { b += ns; } else { str::push_byte(b, t.(i)); }
+ if t[i] == '#' as u8 { b += ns; } else { str::push_byte(b, t[i]); }
i += 1u;
}
ret b;
while n > 0 { log sub(b1(), n); log sub(b2(), n - 1); log ""; n -= 1; }
log b7();
log sub(b8(), 99);
-}
\ No newline at end of file
+}
log "";
}
multiple(99);
-}
\ No newline at end of file
+}
// assert (ack(4,1) == 65533);
-}
\ No newline at end of file
+}
} else { max_depth = n; }
let stretch_depth = max_depth + 1;
let stretch_tree = bottom_up_tree(0, stretch_depth);
- log #fmt("stretch tree of depth %d\t check: %d", stretch_depth,
- item_check(stretch_tree));
+ log #fmt["stretch tree of depth %d\t check: %d", stretch_depth,
+ item_check(stretch_tree)];
let long_lived_tree = bottom_up_tree(0, max_depth);
let depth = min_depth;
while depth <= max_depth {
chk += item_check(temp_tree);
i += 1;
}
- log #fmt("%d\t trees of depth %d\t check: %d", iterations * 2, depth,
- chk);
+ log #fmt["%d\t trees of depth %d\t check: %d", iterations * 2, depth,
+ chk];
depth += 2;
}
- log #fmt("long lived trees of depth %d\t check: %d", max_depth,
- item_check(long_lived_tree));
-}
\ No newline at end of file
+ log #fmt["long lived trees of depth %d\t check: %d", max_depth,
+ item_check(long_lived_tree)];
+}
r = n;
while r > 0 {
i = 0;
- while r != 1 { count.(r - 1) = r; r -= 1; }
- while i < n { perm.(i) = perm1.(i); i += 1; }
+ while r != 1 { count[r - 1] = r; r -= 1; }
+ while i < n { perm[i] = perm1[i]; i += 1; }
// Count flips and update max and checksum
f = 0;
- k = perm.(0);
+ k = perm[0];
while k != 0 {
i = 0;
while 2 * i < k {
- let t = perm.(i);
- perm.(i) = perm.(k - i);
- perm.(k - i) = t;
+ let t = perm[i];
+ perm[i] = perm[k - i];
+ perm[k - i] = t;
i += 1;
}
- k = perm.(0);
+ k = perm[0];
f += 1;
}
if f > flips { flips = f; }
let go = true;
while go {
if r == n { log checksum; ret flips; }
- let p0 = perm1.(0);
+ let p0 = perm1[0];
i = 0;
- while i < r { let j = i + 1; perm1.(i) = perm1.(j); i = j; }
- perm1.(r) = p0;
- count.(r) -= 1;
- if count.(r) > 0 { go = false; } else { r += 1; }
+ while i < r { let j = i + 1; perm1[i] = perm1[j]; i = j; }
+ perm1[r] = p0;
+ count[r] -= 1;
+ if count[r] > 0 { go = false; } else { r += 1; }
}
nperm += 1;
}
fn main(args: [str]) {
let n = 7;
- log #fmt("Pfannkuchen(%d) = %d", n, fannkuch(n));
+ log #fmt["Pfannkuchen(%d) = %d", n, fannkuch(n)];
}
fn make_cumulative(aa: &[aminoacids]) -> [aminoacids] {
let cp: u32 = 0u32;
- let ans: [aminoacids] = ~[];
- for a: aminoacids in aa { cp += a.prob; ans += ~[{ch: a.ch, prob: cp}]; }
+ let ans: [aminoacids] = [];
+ for a: aminoacids in aa { cp += a.prob; ans += [{ch: a.ch, prob: cp}]; }
ret ans;
}
fn select_random(r: u32, genelist: &[aminoacids]) -> char {
- if r < genelist.(0).prob { ret genelist.(0).ch; }
+ if r < genelist[0].prob { ret genelist[0].ch; }
fn bisect(v: &[aminoacids], lo: uint, hi: uint, target: u32) -> char {
if hi > lo + 1u {
let mid: uint = lo + (hi - lo) / 2u;
- if target < v.(mid).prob {
+ if target < v[mid].prob {
be bisect(v, lo, mid, target);
} else { be bisect(v, mid, hi, target); }
- } else { ret v.(hi).ch; }
+ } else { ret v[hi].ch; }
}
ret bisect(genelist, 0u, vec::len::<aminoacids>(genelist) - 1u, r);
}
let op: str = "";
let sl: uint = str::byte_len(s);
for each i: uint in uint::range(0u, n as uint) {
- str::push_byte(op, s.(i % sl));
+ str::push_byte(op, s[i % sl]);
if str::byte_len(op) >= LINE_LENGTH() { log op; op = ""; }
}
if str::byte_len(op) > 0u { log op; }
fn main(args: [str]) {
let iub: [aminoacids] =
- make_cumulative(
- ~[acid('a', 27u32), acid('c', 12u32), acid('g', 12u32),
- acid('t', 27u32), acid('B', 2u32), acid('D', 2u32),
- acid('H', 2u32), acid('K', 2u32), acid('M', 2u32),
- acid('N', 2u32), acid('R', 2u32), acid('S', 2u32),
- acid('V', 2u32), acid('W', 2u32), acid('Y', 2u32)]);
+ make_cumulative([acid('a', 27u32), acid('c', 12u32), acid('g', 12u32),
+ acid('t', 27u32), acid('B', 2u32), acid('D', 2u32),
+ acid('H', 2u32), acid('K', 2u32), acid('M', 2u32),
+ acid('N', 2u32), acid('R', 2u32), acid('S', 2u32),
+ acid('V', 2u32), acid('W', 2u32), acid('Y', 2u32)]);
let homosapiens: [aminoacids] =
- make_cumulative(
- ~[acid('a', 30u32), acid('c', 20u32), acid('g', 20u32),
- acid('t', 30u32)]);
+ make_cumulative([acid('a', 30u32), acid('c', 20u32), acid('g', 20u32),
+ acid('t', 30u32)]);
let alu: str =
"GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG" +
"GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA" +
assert (fib(15) == 610);
log fib(8);
log fib(15);
-}
\ No newline at end of file
+}
// during 'make check' under valgrind
// 5000000
// 50000000
- let inputs: [int] = ~[50000, 500000];
+ let inputs: [int] = [50000, 500000];
let bodies: [Body::props] = NBodySystem::MakeNBodySystem();
fn MakeNBodySystem() -> [Body::props] {
// these each return a Body::props
let bodies: [Body::props] =
- ~[Body::sun(), Body::jupiter(), Body::saturn(), Body::uranus(),
+ [Body::sun(), Body::jupiter(), Body::saturn(), Body::uranus(),
Body::neptune()];
let px: float = 0.0;
let i: int = 0;
while i < 5 {
- px += bodies.(i).vx * bodies.(i).mass;
- py += bodies.(i).vy * bodies.(i).mass;
- pz += bodies.(i).vz * bodies.(i).mass;
+ px += bodies[i].vx * bodies[i].mass;
+ py += bodies[i].vy * bodies[i].mass;
+ pz += bodies[i].vz * bodies[i].mass;
i += 1;
}
// side-effecting
- Body::offsetMomentum(bodies.(0), px, py, pz);
+ Body::offsetMomentum(bodies[0], px, py, pz);
ret bodies;
}
let i: int = 0;
while i < 5 {
let j: int = i + 1;
- while j < 5 { advance_one(bodies.(i), bodies.(j), dt); j += 1; }
+ while j < 5 { advance_one(bodies[i], bodies[j], dt); j += 1; }
i += 1;
}
i = 0;
- while i < 5 { move(bodies.(i), dt); i += 1; }
+ while i < 5 { move(bodies[i], dt); i += 1; }
}
fn advance_one(bi: &Body::props, bj: &Body::props, dt: float) {
let i: int = 0;
while i < 5 {
e +=
- 0.5 * bodies.(i).mass *
- (bodies.(i).vx * bodies.(i).vx +
- bodies.(i).vy * bodies.(i).vy +
- bodies.(i).vz * bodies.(i).vz);
+ 0.5 * bodies[i].mass *
+ (bodies[i].vx * bodies[i].vx + bodies[i].vy * bodies[i].vy
+ + bodies[i].vz * bodies[i].vz);
let j: int = i + 1;
while j < 5 {
- dx = bodies.(i).x - bodies.(j).x;
- dy = bodies.(i).y - bodies.(j).y;
- dz = bodies.(i).z - bodies.(j).z;
+ dx = bodies[i].x - bodies[j].x;
+ dy = bodies[i].y - bodies[j].y;
+ dz = bodies[i].z - bodies[j].z;
distance = llvm::sqrt(dx * dx + dy * dy + dz * dz);
- e -= bodies.(i).mass * bodies.(j).mass / distance;
+ e -= bodies[i].mass * bodies[j].mass / distance;
j += 1;
}
const PI: float = 3.141592653589793;
const SOLAR_MASS: float = 39.478417604357432;
- // was 4 * PI * PI originally
+ // was 4 * PI * PI originally
const DAYS_PER_YEAR: float = 365.24;
type props =
fn pfib(c: _chan<int>, n: int) {
if n == 0 {
send(c, 0);
- } else if (n <= 2) {
+ } else if n <= 2 {
send(c, 1);
} else {
let p = mk_port::<int>();
type config = {stress: bool};
fn parse_opts(argv: [str]) -> config {
- let opts = ~[getopts::optflag("stress")];
+ let opts = [getopts::optflag("stress")];
let opt_args = vec::slice(argv, 1u, vec::len(argv));
let n = 15;
assert (fib(n) == fib(n));
i += 1;
- log_err #fmt("%d: Completed %d iterations", id, i);
+ log_err #fmt["%d: Completed %d iterations", id, i];
}
}
if opts.stress {
stress(2);
} else {
- let max = uint::parse_buf(str::bytes(argv.(1)), 10u) as int;
+ let max = uint::parse_buf(str::bytes(argv[1]), 10u) as int;
let num_trials = 10;
let elapsed = stop - start;
- out.write_line(#fmt("%d\t%d\t%s", n, fibn,
- u64::str(elapsed)));
+ out.write_line(#fmt["%d\t%d\t%s", n, fibn,
+ u64::str(elapsed)]);
}
}
}
fn f(n: uint) {
let i = 0u;
- while i < n {
- let thunk = g;
- task::join_id(task::spawn(thunk));
- i += 1u;
- }
+ while i < n { let thunk = g; task::join_id(task::spawn(thunk)); i += 1u; }
}
-fn g() {}
+fn g() { }
fn main(args: [str]) {
- let n = if vec::len(args) < 2u {
- 10u
- } else {
- uint::parse_buf(str::bytes(args.(1)), 10u)
- };
+ let n =
+ if vec::len(args) < 2u {
+ 10u
+ } else { uint::parse_buf(str::bytes(args[1]), 10u) };
let i = 0u;
- while i < n {
- task::spawn(bind f(n));
- i += 1u;
- }
+ while i < n { task::spawn(bind f(n)); i += 1u; }
}
let count = 0;
- while true {
- alt get() {
- some(_) {
- count += 1;
- }
- none. { break }
- }
- }
+ while true { alt get() { some(_) { count += 1; } none. { break } } }
}
mod map_reduce {
export reducer;
export map_reduce;
- type putter = fn(str, int) ;
+ type putter = fn(str, int);
- type mapper = fn(str, putter) ;
+ type mapper = fn(str, putter);
- type getter = fn() -> option<int> ;
+ type getter = fn() -> option<int>;
- type reducer = fn(str, getter) ;
+ type reducer = fn(str, getter);
tag ctrl_proto {
find_reducer([u8], _chan<_chan<reduce_proto>>);
tag reduce_proto { emit_val(int); done; ref; release; }
fn start_mappers(ctrl: _chan<ctrl_proto>, inputs: &[str]) -> [task_id] {
- let tasks = ~[];
+ let tasks = [];
for i: str in inputs {
- tasks += ~[task::spawn(bind map_task(ctrl, i))];
+ tasks += [task::spawn(bind map_task(ctrl, i))];
}
ret tasks;
}
map(input, bind emit(intermediates, ctrl, _, _));
- for each kv: @{key: str, val: _chan<reduce_proto>} in
+ for each kv: @{key: str, val: _chan<reduce_proto>} in
intermediates.items() {
send(kv.val, release);
}
none. {
// log_err "creating new reducer for " + k;
let p = mk_port();
- tasks +=
- ~[task::spawn(bind reduce_task(k, p.mk_chan()))];
+ tasks += [task::spawn(bind reduce_task(k, p.mk_chan()))];
c = p.recv();
reducers.insert(k, c);
}
if vec::len(argv) < 2u {
let out = io::stdout();
- out.write_line(#fmt("Usage: %s <filename> ...", argv.(0)));
+ out.write_line(#fmt["Usage: %s <filename> ...", argv[0]]);
// TODO: run something just to make sure the code hasn't
// broken yet. This is the unit test mode of this program.
fn main() {
fn f(i: uint) -> bool { true }
- let a = map(f, ~[5u]);
-}
\ No newline at end of file
+ let a = map(f, [5u]);
+}
fn f(x: &int) { log_err x; }
fn h(x: int) { log_err x; }
-fn main() { let g: fn(int) = f; g(10); g = h; g(10); }
+fn main() { let g: fn(int) = f; g(10); g = h; g(10); }
fn my_fail() -> ! { fail; }
fn main() {
- alt (true) {
- false { my_fail(); }
- true {}
- }
+ alt true { false { my_fail(); } true { } }
log x;
- let x:int;
-}
\ No newline at end of file
+ let x: int;
+}
log false && { i = 5; true };
log i;
-}
\ No newline at end of file
+}
fn f(x: int) { }
-fn main() { let i: (); i = f(); }
\ No newline at end of file
+fn main() { let i: (); i = f(); }
fn f(x: int) { }
-fn main() { let i: (); i = f(()); }
\ No newline at end of file
+fn main() { let i: (); i = f(()); }
fn f(i: &int) { i += 2; }
-fn main() { f(1); }
\ No newline at end of file
+fn main() { f(1); }
// error-pattern: mismatched types
fn add1(i: int) -> int { ret i + 1; }
-fn main() { let f = @add1; let g = bind f(5); }
\ No newline at end of file
+fn main() { let f = @add1; let g = bind f(5); }
fn bad_bang(i: uint) -> ! { log 3; }
-fn main() { bad_bang(5u); }
\ No newline at end of file
+fn main() { bad_bang(5u); }
fn bad_bang(i: uint) -> ! { ret 7u; }
-fn main() { bad_bang(5u); }
\ No newline at end of file
+fn main() { bad_bang(5u); }
fn bad_bang(i: uint) -> ! { if i < 0u { } else { fail; } }
-fn main() { bad_bang(5u); }
\ No newline at end of file
+fn main() { bad_bang(5u); }
let x: int;
fn bar() { log x; }
}
-fn main() { foo(); }
\ No newline at end of file
+fn main() { foo(); }
fn foo(x: int) {
fn bar() { log x; }
}
-fn main() { foo(2); }
\ No newline at end of file
+fn main() { foo(2); }
}
}
-fn main() { foo(2); }
\ No newline at end of file
+fn main() { foo(2); }
// error-pattern:wrong type in main function
-fn main(x: int) { }
\ No newline at end of file
+fn main(x: int) { }
// error-pattern: unresolved import: vec
import vec;
-fn main() { let foo = vec::len([]); }
\ No newline at end of file
+fn main() { let foo = vec::len([]); }
// error-pattern:did not expect a record with a field q
-fn main() { alt {x: 1, y: 2} { {x: x, q: q} { } } }
\ No newline at end of file
+fn main() { alt {x: 1, y: 2} { {x: x, q: q} { } } }
// error-pattern:expected a record with 2 fields, found one with 1
-fn main() { alt {x: 1, y: 2} { {x: x} { } } }
\ No newline at end of file
+fn main() { alt {x: 1, y: 2} { {x: x} { } } }
// error-pattern: some control paths may return
fn f() -> ! { 3 }
-fn main(){}
+fn main() { }
// error-pattern:+ cannot be applied to type `{x: bool}`
-fn main() { let x = {x: true}; x += {x: false}; }
\ No newline at end of file
+fn main() { let x = {x: true}; x += {x: false}; }
// error-pattern:+ cannot be applied to type `{x: bool}`
-fn main() { let x = {x: true} + {x: false}; }
\ No newline at end of file
+fn main() { let x = {x: true} + {x: false}; }
// error-pattern:^ cannot be applied to type `str`
-fn main() { let x = "a" ^ "b"; }
\ No newline at end of file
+fn main() { let x = "a" ^ "b"; }
// error-pattern:|| cannot be applied to type `f32`
-fn main() { let x = 1.0_f32 || 2.0_f32; }
\ No newline at end of file
+fn main() { let x = 1.0_f32 || 2.0_f32; }
// error-pattern:&& cannot be applied to type `int`
-fn main() { let x = 1 && 2; }
\ No newline at end of file
+fn main() { let x = 1 && 2; }
// error-pattern:* cannot be applied to type `bool`
-fn main() { let x = true * false; }
\ No newline at end of file
+fn main() { let x = true * false; }
// error-pattern:- cannot be applied to type `obj
-fn main() { let x = obj () { } - obj () { }; }
\ No newline at end of file
+fn main() { let x = obj () { } - obj () { }; }
// error-pattern:mismatched types
// issue #500
-fn main() { let x = true; let y = 1; let z = x + y; }
\ No newline at end of file
+fn main() { let x = true; let y = 1; let z = x + y; }
// Make sure that fn-to-block coercion isn't incorrectly lifted over
// other tycons.
-fn coerce(b: &block() ) -> fn() {
- fn lol(f: &fn(&block() ) -> fn() , g: &block() ) -> fn() { ret f(g); }
- fn fn_id(f: &fn() ) -> fn() { ret f }
+fn coerce(b: &block()) -> fn() {
+ fn lol(f: &fn(&block()) -> fn(), g: &block()) -> fn() { ret f(g); }
+ fn fn_id(f: &fn()) -> fn() { ret f }
ret lol(fn_id, b);
}
-fn main() { let i = 8; let f = coerce(block () { log_err i; }); f(); }
\ No newline at end of file
+fn main() { let i = 8; let f = coerce(block () { log_err i; }); f(); }
// error-pattern: non-copyable
-fn lol(f: &block() ) -> block() { ret f; }
-fn main() { let i = 8; let f = lol(block () { log_err i; }); f(); }
\ No newline at end of file
+fn lol(f: &block()) -> block() { ret f; }
+fn main() { let i = 8; let f = lol(block () { log_err i; }); f(); }
// error-pattern: Unsatisfied precondition constraint
-fn force(f: &block() ) { f(); }
-fn main() { let x: int; force(block () { log_err x; }); }
\ No newline at end of file
+fn force(f: &block()) { f(); }
+fn main() { let x: int; force(block () { log_err x; }); }
let rs: {t: str} = {t: pth};
-}
\ No newline at end of file
+}
ret 17;
}
-fn main() { log foo(); }
\ No newline at end of file
+fn main() { log foo(); }
ret 17;
}
-fn main() { log foo(); }
\ No newline at end of file
+fn main() { log foo(); }
fn main() {
let bar: int = 5;
fn foo() -> int { ret bar; }
-}
\ No newline at end of file
+}
// error-pattern: unresolved name: base
type base =
obj {
- fn foo() ;
+ fn foo();
};
obj derived() {
fn foo() { }
fn bar() { }
}
-fn main() { let d: derived = derived(); let b: base = base(d); }
\ No newline at end of file
+fn main() { let d: derived = derived(); let b: base = base(d); }
resource foo(i: int) { }
-fn main() { let x <- foo(10); let y = x; }
\ No newline at end of file
+fn main() { let x <- foo(10); let y = x; }
fn member() { }
}
-fn main() { member() }
\ No newline at end of file
+fn main() { member() }
fn hello() { log "hello"; }
}
-fn main() { x.hello(); }
\ No newline at end of file
+fn main() { x.hello(); }
log y;
do { do { do { x <- y; } while true } while true } while true
} while true
-}
\ No newline at end of file
+}
// error-pattern: Unsatisfied precondition constraint (for example, even(y
-fn print_even(y: int) : even(y) {
- log y;
-}
+fn print_even(y: int) : even(y) { log y; }
-pred even(y: int) -> bool {
- true
-}
+pred even(y: int) -> bool { true }
fn main() {
- let y: int = 42;
- check even(y);
- do {
- print_even(y);
- do {
- do {
- do {
- y += 1;
- } while (true);
- } while (true);
- } while (true);
- } while (true);
+ let y: int = 42;
+ check (even(y));
+ do {
+ print_even(y);
+ do { do { do { y += 1; } while true } while true } while true
+ } while true
}
#[link(name = "test", name)];
-fn main() { }
\ No newline at end of file
+fn main() { }
fn baz() { }
}
-fn main() { }
\ No newline at end of file
+fn main() { }
}
-fn main() { unexported(); }
\ No newline at end of file
+fn main() { unexported(); }
tag t { t1; }
}
-fn main() { let x = foo::t1; }
\ No newline at end of file
+fn main() { let x = foo::t1; }
tag y { y1; }
}
-fn main() { let z = foo::y1; }
\ No newline at end of file
+fn main() { let z = foo::y1; }
fn z(y: int) { log y; }
}
-fn main() { foo::z(10); }
\ No newline at end of file
+fn main() { foo::z(10); }
fn y() { }
}
-fn main() { foo::x(); }
\ No newline at end of file
+fn main() { foo::x(); }
// error-pattern:macro undefined
-fn main() { #iamnotanextensionthatexists(""); }
\ No newline at end of file
+fn main() { #iamnotanextensionthatexists[""]; }
with
x
};
-}
\ No newline at end of file
+}
// error-pattern:malformed #env call
-fn main() {
- #env();
-}
+fn main() { #env[]; }
// error-pattern:requires a string
-fn main() { #env(10); }
\ No newline at end of file
+fn main() { #env[10]; }
// error-pattern:malformed #env call
-fn main() { #env("one", "two"); }
\ No newline at end of file
+fn main() { #env["one", "two"]; }
// error-pattern:missing type
-fn main() { #fmt("%+"); }
\ No newline at end of file
+fn main() { #fmt["%+"]; }
// error-pattern:format string
-fn main() {
- #fmt();
-}
\ No newline at end of file
+fn main() { #fmt[]; }
// #fmt's first argument must be a literal. Hopefully this
// restriction can be eased eventually to just require a
// compile-time constant.
- let x = #fmt("a" + "b");
-}
\ No newline at end of file
+ let x = #fmt["a" + "b"];
+}
// #fmt's first argument must be a literal. Hopefully this
// restriction can be eased eventually to just require a
// compile-time constant.
- let x = #fmt(20);
-}
\ No newline at end of file
+ let x = #fmt[20];
+}
use std;
-fn main() { let s = #fmt("%s%s%s", "test", "test"); }
\ No newline at end of file
+fn main() { let s = #fmt["%s%s%s", "test", "test"]; }
use std;
-fn main() { let s = #fmt("%s", "test", "test"); }
\ No newline at end of file
+fn main() { let s = #fmt["%s", "test", "test"]; }
// error-pattern:unknown type
-fn main() { #fmt("%w"); }
\ No newline at end of file
+fn main() { #fmt["%w"]; }
fn main() {
// Can't use a sign on unsigned conversions
- #fmt("%+u", 10u);
-}
\ No newline at end of file
+ #fmt["%+u", 10u];
+}
fn main() {
// Can't use a space on unsigned conversions
- #fmt("% u", 10u);
-}
\ No newline at end of file
+ #fmt["% u", 10u];
+}
// error-pattern:unterminated conversion
-fn main() { #fmt("%"); }
\ No newline at end of file
+fn main() { #fmt["%"]; }
// error-pattern:mismatched types
-fn main() { fail 5; }
\ No newline at end of file
+fn main() { fail 5; }
// error-pattern:expected str but found [int]
-fn main() { fail ~[0]; }
\ No newline at end of file
+fn main() { fail [0]; }
fn f() -> int { true }
-fn main() { }
\ No newline at end of file
+fn main() { }
fn f() { }
fn g(i: int) { }
let x = f == g;
-}
\ No newline at end of file
+}
let a: uint = 4u;
let b: uint = 1u;
log_err safe_slice("kitties", a, b);
-}
\ No newline at end of file
+}
// Typestate should work even in a lambda. we should reject this program.
let f = fn () -> int { let i: int; ret i; };
log_err f();
-}
\ No newline at end of file
+}
// error-pattern:Unsatisfied precondition
-fn main() { let j = fn () -> int { let i: int; ret i; }(); log_err j; }
\ No newline at end of file
+fn main() { let j = fn () -> int { let i: int; ret i; }(); log_err j; }
// error-pattern:sequence in for each loop not a call
-fn main() { for each p in 1 {} }
+fn main() { for each p in 1 { } }
fn f(a: int) -> int { if god_exists(a) { ret 5; } }
-fn main() { f(12); }
\ No newline at end of file
+fn main() { f(12); }
let origin: point = {x: 0, y: 0};
let origin3d: point = {z: 0 with origin};
-}
\ No newline at end of file
+}
let right: point = {x: 10 with origin};
origin = {x: 0, y: 0};
-}
\ No newline at end of file
+}
// error-pattern:mismatched types
-fn main() { let x = if true { 10 } else { 10u }; }
\ No newline at end of file
+fn main() { let x = if true { 10 } else { 10u }; }
pred even(x: uint) -> bool {
if x < 2u {
ret false;
- } else if (x == 2u) { ret true; } else { ret even(x - 2u); }
+ } else if x == 2u { ret true; } else { ret even(x - 2u); }
}
fn print_even(x: uint) : even(x) { log x; }
fn foo(x: uint) { if check even(x) { fail; } else { print_even(x); } }
-fn main() { foo(3u); }
\ No newline at end of file
+fn main() { foo(3u); }
// f is not a bool
if f { }
-}
\ No newline at end of file
+}
import m2::{f};
mod m1 {
- fn f() {}
+ fn f() { }
}
mod m2 {
- fn f() {}
+ fn f() { }
}
-fn main() {}
\ No newline at end of file
+fn main() { }
import spam::{ham, eggs};
mod spam {
- fn ham() {}
+ fn ham() { }
}
-fn main() {
- ham();
- eggs();
-}
\ No newline at end of file
+fn main() { ham(); eggs(); }
f2();
f999(); // 'export' currently doesn't work?
f4();
-}
\ No newline at end of file
+}
import circ1::*;
fn test() { f1066(); }
-}
\ No newline at end of file
+}
fn f2() { }
}
-fn main() { f2(); }
\ No newline at end of file
+fn main() { f2(); }
-fn main() { common2(); }
\ No newline at end of file
+fn main() { common2(); }
export x;
fn main() { let y = x; }
-}
\ No newline at end of file
+}
export x;
}
-fn main() { }
\ No newline at end of file
+fn main() { }
import m2::foo;
}
-fn main() { }
\ No newline at end of file
+fn main() { }
let x = 0;
check (f(x));
-}
\ No newline at end of file
+}
type x = [x];
-fn main() { let b: x = ~[]; }
+fn main() { let b: x = []; }
// mutate upvars from a lambda.
fn main() {
let i = 0;
- let ctr = lambda() -> int {
- block() { i = i + 1; }();
- ret i;
- };
+ let ctr = lambda () -> int { block () { i = i + 1; }(); ret i; };
log_err ctr();
log_err ctr();
log_err ctr();
// Make sure we can't write to upvars from lambdas
fn main() {
let i = 0;
- let ctr = lambda() -> int {
- i = i + 1;
- ret i;
- };
+ let ctr = lambda () -> int { i = i + 1; ret i; };
log_err ctr();
log_err ctr();
log_err ctr();
// error-pattern:refutable pattern
-tag xx {
- xx(int);
- yy;
-}
+tag xx { xx(int); yy; }
fn main() {
- let @{x:xx(x), y} = @{x: xx(10), y: 20};
- assert x + y == 30;
+ let @{x: xx(x), y: y} = @{x: xx(10), y: 20};
+ assert (x + y == 30);
}
//error-pattern:is an expr, expected an identifier
fn main() {
- #macro([#mylambda(x, body), {fn f(x: int) -> int {ret body}; f}]);
+ #macro[[#mylambda[x, body],
+ {
+ fn f(x: int) -> int { ret body }
+ f
+ }]];
- assert(#mylambda(y*1, y*2)(8) == 16);
-}
\ No newline at end of file
+ assert (#mylambda[y * 1, y * 2](8) == 16);
+}
//error-pattern:no clauses match
fn main() {
- #macro([#trivial(), 1*2*4*2*1]);
+ #macro[[#trivial[], 1 * 2 * 4 * 2 * 1]];
- assert(#trivial(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16) == 16);
+ assert (#trivial[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] ==
+ 16);
}
// error-pattern:wrong type in main function: found fn() -> char
-fn main() -> char { }
\ No newline at end of file
+fn main() -> char { }
// error-pattern:wrong type in main function: found fn(
-fn main(foo: {x: int, y: int}) { }
\ No newline at end of file
+fn main(foo: {x: int, y: int}) { }
// error-pattern:applying unary minus to non-numeric type str
-fn main() {
- -"foo";
-}
\ No newline at end of file
+fn main() { -"foo"; }
// error-pattern:main function not found
-fn mian() { }
\ No newline at end of file
+fn mian() { }
alt true { true { } }
}
-fn main() { }
\ No newline at end of file
+fn main() { }
// error-pattern: Unsatisfied precondition constraint
-fn test(foo: -int) {
- assert (foo == 10);
-}
+fn test(foo: -int) { assert (foo == 10); }
-fn main() {
- let x = 10;
- test(x);
- log x;
-}
\ No newline at end of file
+fn main() { let x = 10; test(x); log x; }
fn main() {
let f: std::os::libc::FILE = std::io::rustrt::rust_get_stdin();
std::os::libc::fopen(f, f);
-}
\ No newline at end of file
+}
// error-pattern:Attempt to use a type argument out of scope
fn hd<U>(v: &[U]) -> U {
- fn hd1(w: &[U]) -> U { ret w.(0); }
+ fn hd1(w: &[U]) -> U { ret w[0]; }
ret hd1(v);
}
// prestate.
let d <- a;
log safe_slice("kitties", b, d);
-}
\ No newline at end of file
+}
fn get() -> int { ret 3; }
fn foo() { let c = get(); }
}
-fn main() { }
\ No newline at end of file
+fn main() { }
2); // should fail to typecheck, as (a == b)
// is not a manifest call
-}
\ No newline at end of file
+
+}
let z = f();
// should fail to typecheck, as z.g isn't an explicit name
check (z.g(42));
-}
\ No newline at end of file
+}
let x = 0;
check (f(x));
-}
\ No newline at end of file
+}
// -*- rust -*-
// error-pattern: Non-predicate in constraint: lt
-fn f(a: int, b: int) : lt(a,b) { }
+fn f(a: int, b: int) : lt(a, b) { }
obj lt(a: int, b: int) { }
-fn main() { let a: int = 10; let b: int = 23; check (lt(a, b)); f(a, b); }
\ No newline at end of file
+fn main() { let a: int = 10; let b: int = 23; check (lt(a, b)); f(a, b); }
// should fail to typecheck, as pred args must be slot variables
// or literals
check (f(42 * 17));
-}
\ No newline at end of file
+}
// error-pattern: Type inference failed because I could not find
-fn main() {
- let f;
- f = @f;
- f();
-}
\ No newline at end of file
+fn main() { let f; f = @f; f(); }
// error-pattern: Type inference failed because I could not find
-fn main() {
- let f;
- f = @f;
-}
+fn main() { let f; f = @f; }
log false || { i = 5; true };
log i;
-}
\ No newline at end of file
+}
tag blah { a(int, int, uint); b(int, int); }
-fn main() { alt a(1, 1, 2u) { a(_, x, y) | b(x, y) { } } }
\ No newline at end of file
+fn main() { alt a(1, 1, 2u) { a(_, x, y) | b(x, y) { } } }
fn f() { }
-fn main() { let i: int; i = f(); }
\ No newline at end of file
+fn main() { let i: int; i = f(); }
// error-pattern: Unsatisfied precondition constraint (for example, lt(a, b)
-fn f(a: int, b: int) : lt(a,b) { }
+fn f(a: int, b: int) : lt(a, b) { }
pred lt(a: int, b: int) -> bool { ret a < b; }
check (lt(a, b));
a = 24;
f(a, b);
-}
\ No newline at end of file
+}
pred bad(a: int) -> int { ret 37; }
-fn main() { }
\ No newline at end of file
+fn main() { }
// error-pattern: lt(a, c)
-fn f(a: int, b: int) : lt(a,b) { }
+fn f(a: int, b: int) : lt(a, b) { }
pred lt(a: int, b: int) -> bool { ret a < b; }
check (lt(b, c));
f(a, b);
f(a, c);
-}
\ No newline at end of file
+}
// error-pattern: Unsatisfied precondition constraint (for example, lt(a, b)
-fn f(a: int, b: int) : lt(a,b) { }
+fn f(a: int, b: int) : lt(a, b) { }
pred lt(a: int, b: int) -> bool { ret a < b; }
check (lt(a, b));
b <-> a;
f(a, b);
-}
\ No newline at end of file
+}
let a = {foo: 0};
let b = {foo: true with a};
-}
\ No newline at end of file
+}
type point = {x: int, y: int};
-fn main() { let p: point = {x: 10}; log p.y; }
\ No newline at end of file
+fn main() { let p: point = {x: 10}; log p.y; }
fn g() -> int { ret; }
-fn main() { f(); g(); }
\ No newline at end of file
+fn main() { f(); g(); }
fn f() -> int { let x: int; ret x; }
-fn main() { f(); }
\ No newline at end of file
+fn main() { f(); }
self.foo();
-}
\ No newline at end of file
+}
// -*- rust -*-
// error-pattern: unresolved name: lt
-fn f(a: int, b: int) : lt(a,b) { }
+fn f(a: int, b: int) : lt(a, b) { }
fn main() {
let lt: int;
let b: int = 23;
check (lt(a, b));
f(a, b);
-}
\ No newline at end of file
+}
fn f(x: int) -> int { ret x; }
-fn main() { task::_spawn(bind f(10)); }
\ No newline at end of file
+fn main() { task::_spawn(bind f(10)); }
// error-pattern: assignment to non-lvalue
-fn main() { 5 <-> 3; }
\ No newline at end of file
+fn main() { 5 <-> 3; }
// error-pattern:Unsatisfied precondition
-fn main() { let x = 3; let y; x <-> y; }
\ No newline at end of file
+fn main() { let x = 3; let y; x <-> y; }
fn g() -> uint { ret 0u; }
-fn main() { let y = f(); }
\ No newline at end of file
+fn main() { let y = f(); }
// error-pattern:Attempt to use a type argument out of scope
fn foo<T>(x: &T) {
- fn bar(f: fn(&T) -> T ) { }
+ fn bar(f: fn(&T) -> T) { }
}
fn main() { foo(1); }
// error-pattern:mismatched types: expected bool
// error-pattern:mismatched types: expected int
-fn main() { let a: bool = 1; let b: int = true; }
\ No newline at end of file
+fn main() { let a: bool = 1; let b: int = true; }
// error-pattern:expected bool but found int
// issue #516
-fn main() { let x = true; let y = 1; let z = x + y; }
\ No newline at end of file
+fn main() { let x = true; let y = 1; let z = x + y; }
// error-pattern:illegal recursive type
type t1 = {foo: int, foolish: t1};
-fn main() { }
\ No newline at end of file
+fn main() { }
type X = str;
let y: Y = "hello";
}
-}
\ No newline at end of file
+}
tag foo { a(@foo, int); b(uint); }
-fn main() { alt b(1u) { b(_) | a(@_, 1) { } a(_, 1) { } } }
\ No newline at end of file
+fn main() { alt b(1u) { b(_) | a(@_, 1) { } a(_, 1) { } } }
fn main() {
let box = @mutable 1;
alt *box { x { whoknows(box); log_err x; } }
-}
\ No newline at end of file
+}
// error-pattern:may alias with argument
-fn foo(x: &int, f: fn() ) { log x; }
+fn foo(x: &int, f: fn()) { log x; }
fn whoknows(x: @mutable int) { *x = 10; }
-fn main() { let box = @mutable 1; foo(*box, bind whoknows(box)); }
\ No newline at end of file
+fn main() { let box = @mutable 1; foo(*box, bind whoknows(box)); }
fn main() {
let x = left(10);
alt x { left(i) { x = right(false); log i; } _ { } }
-}
\ No newline at end of file
+}
// error-pattern:invalidate alias x
fn main() {
- let v: [mutable int] = ~[mutable 1, 2, 3];
- for x: int in v { v.(0) = 10; log x; }
+ let v: [mutable int] = [mutable 1, 2, 3];
+ for x: int in v { v[0] = 10; log x; }
}
fn f(a: &int, b: &mutable int) -> int { b += 1; ret a + b; }
-fn main() { let i = 4; log f(i, i); }
\ No newline at end of file
+fn main() { let i = 4; log f(i, i); }
// error-pattern: Unsatisfied precondition constraint (for example, init(x
-fn main() { let x = @5; let y <- x; log *x; }
\ No newline at end of file
+fn main() { let x = @5; let y <- x; log *x; }
// error-pattern: Unsatisfied precondition constraint
-fn send<~T>(ch : _chan<T>, data : -T) {
- log ch;
- log data;
- fail;
-}
+fn send<~T>(ch: _chan<T>, data: -T) { log ch; log data; fail; }
type _chan<T> = int;
// Tests that "log message;" is flagged as using
log message;
}
-fn main() {
- fail;
-}
\ No newline at end of file
+fn main() { fail; }
use std(name = "std", name = "nonstd");
-fn main() { }
\ No newline at end of file
+fn main() { }
use std(complex(meta(item)));
-fn main() { }
\ No newline at end of file
+fn main() { }
fn foo(x: int) { log x; }
-fn main() { let x: int; if 1 > 2 { x = 10; } foo(x); }
\ No newline at end of file
+fn main() { let x: int; if 1 > 2 { x = 10; } foo(x); }
fn foo(x: int) { log x; }
-fn main() { let x: int; if 1 > 2 { log "whoops"; } else { x = 10; } foo(x); }
\ No newline at end of file
+fn main() { let x: int; if 1 > 2 { log "whoops"; } else { x = 10; } foo(x); }
fn foo(x: int) { log x; }
-fn main() { let x: int; foo(x); }
\ No newline at end of file
+fn main() { let x: int; foo(x); }
// issue #367
fn f() {
- let v = ~[1];
+ let v = [1];
log v.some_field_name; //type error
}
// error-pattern:cannot determine a type
-fn main() { let foo = []; }
\ No newline at end of file
+fn main() { let foo = []; }
fn f() -> int { let x: int; while true { x = 10; } ret x; }
-fn main() { f(); }
\ No newline at end of file
+fn main() { f(); }
// error-pattern: precondition constraint
-fn main() { let x: bool; while x { } }
\ No newline at end of file
+fn main() { let x: bool; while x { } }
let y: int = 42;
let x: int;
while true { log y; while true { while true { while true { x <- y; } } } }
-}
\ No newline at end of file
+}
print_even(y);
while true { while true { while true { y += x; } } }
}
-}
\ No newline at end of file
+}
fn f(p: &point) { p.x = 13; }
-fn main() { let x: point = {x: 10, y: 11, z: 12}; f(x); }
\ No newline at end of file
+fn main() { let x: point = {x: 10, y: 11, z: 12}; f(x); }
// error-pattern: Unsatisfied precondition constraint
-fn test() { let w: [int]; w.(5) = 0; }
+fn test() { let w: [int]; w[5] = 0; }
fn main() { test(); }
obj objy(x: int) {
fn foo() { x = 5; }
}
-fn main() { }
\ No newline at end of file
+fn main() { }
// error-pattern: assignment to immutable field
-fn main() { let r: {x: int} = {x: 1}; r.x = 6; }
\ No newline at end of file
+fn main() { let r: {x: int} = {x: 1}; r.x = 6; }
// error-pattern:assignment to immutable vec content
-fn main() { let v: [int] = ~[1, 2, 3]; v.(1) = 4; }
+fn main() { let v: [int] = [1, 2, 3]; v[1] = 4; }
// error-pattern: mismatched types
fn mk_int() -> uint { let i: int = 3; ret i; }
-fn main() { }
\ No newline at end of file
+fn main() { }
import std::option;
-tag mode {
- mode_compile_fail;
- mode_run_fail;
- mode_run_pass;
- mode_pretty;
-}
+tag mode { mode_compile_fail; mode_run_fail; mode_run_pass; mode_pretty; }
-type config = {
+type config =
// The library paths required for running the compiler
- compile_lib_path: str,
// The library paths required for running compiled programs
- run_lib_path: str,
// The rustc executable
- rustc_path: str,
// The directory containing the tests to run
- src_base: str,
// The directory where programs should be built
- build_base: str,
// The name of the stage being built (stage1, etc)
- stage_id: str,
// The test mode, compile-fail, run-fail, run-pass
- mode: mode,
// Run ignored tests
- run_ignored: bool,
// Only run tests that match this filter
- filter: option::t<str>,
// A command line to prefix program execution with,
// for running under valgrind
- runtool: option::t<str>,
// Flags to pass to the compiler
- rustcflags: option::t<str>,
// Explain what's going on
- verbose: bool
-};
+ {compile_lib_path: str,
+ run_lib_path: str,
+ rustc_path: str,
+ src_base: str,
+ build_base: str,
+ stage_id: str,
+ mode: mode,
+ run_ignored: bool,
+ filter: option::t<str>,
+ runtool: option::t<str>,
+ rustcflags: option::t<str>,
+ verbose: bool};
type cx = {config: config, procsrv: procsrv::handle};
fn parse_config(args: &[str]) -> config {
let opts =
- ~[getopts::reqopt("compile-lib-path"),
- getopts::reqopt("run-lib-path"), getopts::reqopt("rustc-path"),
- getopts::reqopt("src-base"), getopts::reqopt("build-base"),
- getopts::reqopt("stage-id"), getopts::reqopt("mode"),
- getopts::optflag("ignored"), getopts::optopt("runtool"),
- getopts::optopt("rustcflags"), getopts::optflag("verbose")];
+ [getopts::reqopt("compile-lib-path"), getopts::reqopt("run-lib-path"),
+ getopts::reqopt("rustc-path"), getopts::reqopt("src-base"),
+ getopts::reqopt("build-base"), getopts::reqopt("stage-id"),
+ getopts::reqopt("mode"), getopts::optflag("ignored"),
+ getopts::optopt("runtool"), getopts::optopt("rustcflags"),
+ getopts::optflag("verbose")];
check (vec::is_not_empty(args));
let args_ = vec::tail(args);
run_ignored: getopts::opt_present(match, "ignored"),
filter:
if vec::len(match.free) > 0u {
- option::some(match.free.(0))
+ option::some(match.free[0])
} else { option::none },
runtool: getopts::opt_maybe_str(match, "runtool"),
rustcflags: getopts::opt_maybe_str(match, "rustcflags"),
fn log_config(config: &config) {
let c = config;
- logv(c, #fmt("configuration:"));
- logv(c, #fmt("compile_lib_path: %s", config.compile_lib_path));
- logv(c, #fmt("run_lib_path: %s", config.run_lib_path));
- logv(c, #fmt("rustc_path: %s", config.rustc_path));
- logv(c, #fmt("src_base: %s", config.src_base));
- logv(c, #fmt("build_base: %s", config.build_base));
- logv(c, #fmt("stage_id: %s", config.stage_id));
- logv(c, #fmt("mode: %s", mode_str(config.mode)));
- logv(c, #fmt("run_ignored: %b", config.run_ignored));
- logv(c, #fmt("filter: %s", opt_str(config.filter)));
- logv(c, #fmt("runtool: %s", opt_str(config.runtool)));
- logv(c, #fmt("rustcflags: %s", opt_str(config.rustcflags)));
- logv(c, #fmt("verbose: %b", config.verbose));
- logv(c, #fmt("\n"));
+ logv(c, #fmt["configuration:"]);
+ logv(c, #fmt["compile_lib_path: %s", config.compile_lib_path]);
+ logv(c, #fmt["run_lib_path: %s", config.run_lib_path]);
+ logv(c, #fmt["rustc_path: %s", config.rustc_path]);
+ logv(c, #fmt["src_base: %s", config.src_base]);
+ logv(c, #fmt["build_base: %s", config.build_base]);
+ logv(c, #fmt["stage_id: %s", config.stage_id]);
+ logv(c, #fmt["mode: %s", mode_str(config.mode)]);
+ logv(c, #fmt["run_ignored: %b", config.run_ignored]);
+ logv(c, #fmt["filter: %s", opt_str(config.filter)]);
+ logv(c, #fmt["runtool: %s", opt_str(config.runtool)]);
+ logv(c, #fmt["rustcflags: %s", opt_str(config.rustcflags)]);
+ logv(c, #fmt["verbose: %b", config.verbose]);
+ logv(c, #fmt["\n"]);
}
fn opt_str(maybestr: option::t<str>) -> str {
}
type tests_and_conv_fn =
- {tests: [test::test_desc], to_task: fn(&fn() ) -> test::joinable };
+ {tests: [test::test_desc], to_task: fn(&fn()) -> test::joinable};
fn make_tests(cx: &cx) -> tests_and_conv_fn {
- log #fmt("making tests from %s", cx.config.src_base);
+ log #fmt["making tests from %s", cx.config.src_base];
let configport = mk_port::<[u8]>();
- let tests = ~[];
+ let tests = [];
for file: str in fs::list_dir(cx.config.src_base) {
- log #fmt("inspecting file %s", file);
+ log #fmt["inspecting file %s", file];
if is_test(cx.config, file) {
- tests += ~[make_test(cx, file, configport)];
+ tests += [make_test(cx, file, configport)];
}
}
ret {tests: tests, to_task: bind closure_to_task(cx, configport, _)};
fn is_test(config: &config, testfile: &str) -> bool {
// Pretty-printer does not work with .rc files yet
- let valid_extensions = alt config.mode {
- mode_pretty. { ~[".rs"] }
- _ { ~[".rc", ".rs"] }
- };
- let invalid_prefixes = ~[".", "#", "~"];
+ let valid_extensions =
+ alt config.mode { mode_pretty. { [".rs"] } _ { [".rc", ".rs"] } };
+ let invalid_prefixes = [".", "#", "~"];
let name = fs::basename(testfile);
let valid = false;
}
fn make_test_name(config: &config, testfile: &str) -> str {
- #fmt("[%s] %s", mode_str(config.mode), testfile)
+ #fmt["[%s] %s", mode_str(config.mode), testfile]
}
/*
Really convoluted. Need to think up of a better definition for tests.
*/
-fn make_test_closure(testfile: &str, configchan: _chan<[u8]>) -> test::test_fn
-{
+fn make_test_closure(testfile: &str, configchan: _chan<[u8]>) ->
+ test::test_fn {
bind send_config(testfile, configchan)
}
function.
*/
-fn closure_to_task(cx: cx, configport: _port<[u8]>, testfn: &fn() )
- -> test::joinable
-{
+fn closure_to_task(cx: cx, configport: _port<[u8]>, testfn: &fn()) ->
+ test::joinable {
testfn();
let testfile = configport.recv();
- let testthunk = bind run_test_task(cx.config.compile_lib_path,
- cx.config.run_lib_path,
- cx.config.rustc_path,
- cx.config.src_base,
- cx.config.build_base,
- cx.config.stage_id,
- mode_str(cx.config.mode),
- cx.config.run_ignored,
- opt_str(cx.config.filter),
- opt_str(cx.config.runtool),
- opt_str(cx.config.rustcflags),
- cx.config.verbose,
- cx.procsrv.chan,
- testfile);
+ let testthunk =
+ bind run_test_task(cx.config.compile_lib_path, cx.config.run_lib_path,
+ cx.config.rustc_path, cx.config.src_base,
+ cx.config.build_base, cx.config.stage_id,
+ mode_str(cx.config.mode), cx.config.run_ignored,
+ opt_str(cx.config.filter),
+ opt_str(cx.config.runtool),
+ opt_str(cx.config.rustcflags), cx.config.verbose,
+ cx.procsrv.chan, testfile);
ret task::spawn_joinable(testthunk);
}
type handle = {task: option::t<task_id>, chan: reqchan};
-tag request {
- exec([u8], [u8], [[u8]], chan<response>);
- stop;
-}
+tag request { exec([u8], [u8], [[u8]], chan<response>); stop; }
type response = {pid: int, infd: int, outfd: int, errfd: int};
fn mk() -> handle {
let setupport = port();
- let task = task::spawn(bind fn(setupchan: chan<chan<request>>) {
- let reqport = port();
- let reqchan = chan(reqport);
- send(setupchan, reqchan);
- worker(reqport);
- } (chan(setupport)));
- ret {task: option::some(task),
- chan: recv(setupport)
- };
+ let task =
+ task::spawn(bind fn (setupchan: chan<chan<request>>) {
+ let reqport = port();
+ let reqchan = chan(reqport);
+ send(setupchan, reqchan);
+ worker(reqport);
+ }(chan(setupport)));
+ ret {task: option::some(task), chan: recv(setupport)};
}
fn from_chan(ch: &reqchan) -> handle { {task: option::none, chan: ch} }
task::join_id(option::get(handle.task));
}
-fn run(handle: &handle, lib_path: &str,
- prog: &str, args: &[str], input: &option::t<str>) ->
-{status: int, out: str, err: str} {
+fn run(handle: &handle, lib_path: &str, prog: &str, args: &[str],
+ input: &option::t<str>) -> {status: int, out: str, err: str} {
let p = port();
let ch = chan(p);
- send(handle.chan, exec(str::bytes(lib_path),
- str::bytes(prog),
- clone_vecstr(args),
- ch));
+ send(handle.chan,
+ exec(str::bytes(lib_path), str::bytes(prog), clone_vecstr(args),
+ ch));
let resp = recv(p);
writeclose(resp.infd, input);
fn writeclose(fd: int, s: &option::t<str>) {
if option::is_some(s) {
- let writer = io::new_writer(
- io::fd_buf_writer(fd, option::none));
+ let writer = io::new_writer(io::fd_buf_writer(fd, option::none));
writer.write_str(option::get(s));
}
fn readclose(fd: int) -> str {
// Copied from run::program_output
let file = os::fd_FILE(fd);
- let reader = io::new_reader(
- io::FILE_buf_reader(file, option::none));
+ let reader = io::new_reader(io::FILE_buf_reader(file, option::none));
let buf = "";
while !reader.eof() {
let bytes = reader.read_bytes(4096u);
// the receiver's poniters outlive the sender's. Here we clone
// everything and let the originals go out of scope before sending
// a response.
- execparms = {
- // FIXME (785): The 'discriminant' of an alt expression has
- // the same scope as the alt expression itself, so we have to
- // put the entire alt in another block to make sure the exec
- // message goes out of scope. Seems like the scoping rules for
- // the alt discriminant are wrong.
- alt recv(p) {
- exec(lib_path, prog, args, respchan) {
- {
- lib_path: str::unsafe_from_bytes(lib_path),
- prog: str::unsafe_from_bytes(prog),
- args: clone_vecu8str(args),
- respchan: respchan
+ execparms =
+ {
+
+ // FIXME (785): The 'discriminant' of an alt expression has
+ // the same scope as the alt expression itself, so we have to
+ // put the entire alt in another block to make sure the exec
+ // message goes out of scope. Seems like the scoping rules for
+ // the alt discriminant are wrong.
+ alt recv(p) {
+ exec(lib_path, prog, args, respchan) {
+ {lib_path: str::unsafe_from_bytes(lib_path),
+ prog: str::unsafe_from_bytes(prog),
+ args: clone_vecu8str(args),
+ respchan: respchan}
+ }
+ stop. { ret }
}
- }
- stop. { ret }
- }
- };
+ };
// This is copied from run::start_program
let pipe_in = os::pipe();
let pipe_out = os::pipe();
let pipe_err = os::pipe();
let spawnproc =
- bind run::spawn_process(execparms.prog,
- execparms.args,
- pipe_in.in,
- pipe_out.out,
- pipe_err.out);
+ bind run::spawn_process(execparms.prog, execparms.args,
+ pipe_in.in, pipe_out.out, pipe_err.out);
let pid = with_lib_path(execparms.lib_path, spawnproc);
os::libc::close(pipe_in.in);
}
}
-fn with_lib_path<T>(path: &str, f: fn() -> T ) -> T {
+fn with_lib_path<T>(path: &str, f: fn() -> T) -> T {
let maybe_oldpath = getenv(util::lib_path_env_var());
append_lib_path(path);
let res = f();
fn export_lib_path(path: &str) { setenv(util::lib_path_env_var(), path); }
fn clone_vecstr(v: &[str]) -> [[u8]] {
- let r = ~[];
- for t: str in vec::slice(v, 0u, vec::len(v)) {
- r += ~[str::bytes(t)];
- }
+ let r = [];
+ for t: str in vec::slice(v, 0u, vec::len(v)) { r += [str::bytes(t)]; }
ret r;
}
fn clone_vecu8str(v: &[[u8]]) -> [str] {
- let r = ~[];
+ let r = [];
for t in vec::slice(v, 0u, vec::len(v)) {
- r += ~[str::unsafe_from_bytes(t)];
+ r += [str::unsafe_from_bytes(t)];
}
ret r;
}
fn run(cx: &cx, _testfile: -[u8]) {
let testfile = str::unsafe_from_bytes(_testfile);
- if (cx.config.verbose) {
+ if cx.config.verbose {
// We're going to be dumping a lot of info. Start on a new line.
io::stdout().write_str("\n\n");
}
- log #fmt("running %s", testfile);
+ log #fmt["running %s", testfile];
let props = load_props(testfile);
alt cx.config.mode {
mode_compile_fail. { run_cfail_test(cx, props, testfile); }
let procres = compile_test(cx, props, testfile);
if procres.status == 0 {
- fatal_procres("compile-fail test compiled successfully!",
- procres);
+ fatal_procres("compile-fail test compiled successfully!", procres);
}
check_error_patterns(props, testfile, procres);
fn run_rfail_test(cx: &cx, props: &test_props, testfile: &str) {
let procres = compile_test(cx, props, testfile);
- if procres.status != 0 {
- fatal_procres("compilation failed!", procres); }
+ if procres.status != 0 { fatal_procres("compilation failed!", procres); }
procres = exec_compiled_test(cx, props, testfile);
if procres.status == 0 {
- fatal_procres("run-fail test didn't produce an error!",
- procres);
+ fatal_procres("run-fail test didn't produce an error!", procres);
}
// This is the value valgrind returns on failure
fn run_rpass_test(cx: &cx, props: &test_props, testfile: &str) {
let procres = compile_test(cx, props, testfile);
- if procres.status != 0 {
- fatal_procres("compilation failed!", procres); }
+ if procres.status != 0 { fatal_procres("compilation failed!", procres); }
procres = exec_compiled_test(cx, props, testfile);
fn run_pretty_test(cx: &cx, props: &test_props, testfile: &str) {
if option::is_some(props.pp_exact) {
logv(cx.config, "testing for exact pretty-printing");
- } else {
- logv(cx.config, "testing for converging pretty-printing");
- }
+ } else { logv(cx.config, "testing for converging pretty-printing"); }
- let rounds = alt props.pp_exact {
- option::some(_) { 1 }
- option::none. { 2 }
- };
+ let rounds =
+ alt props.pp_exact { option::some(_) { 1 } option::none. { 2 } };
- let srcs = ~[io::read_whole_file_str(testfile)];
+ let srcs = [io::read_whole_file_str(testfile)];
let round = 0;
while round < rounds {
- logv(cx.config, #fmt("pretty-printing round %d", round));
- let procres = print_source(cx, testfile, srcs.(round));
+ logv(cx.config, #fmt["pretty-printing round %d", round]);
+ let procres = print_source(cx, testfile, srcs[round]);
if procres.status != 0 {
- fatal_procres(#fmt("pretty-printing failed in round %d", round),
+ fatal_procres(#fmt["pretty-printing failed in round %d", round],
procres);
}
- srcs += ~[procres.stdout];
+ srcs += [procres.stdout];
round += 1;
}
- let expected = alt props.pp_exact {
- option::some(file) {
- let filepath = fs::connect(fs::dirname(testfile), file);
- io::read_whole_file_str(filepath)
- }
- option::none. {
- srcs.(vec::len(srcs) - 2u)
- }
- };
- let actual = srcs.(vec::len(srcs) - 1u);
+ let expected =
+ alt props.pp_exact {
+ option::some(file) {
+ let filepath = fs::connect(fs::dirname(testfile), file);
+ io::read_whole_file_str(filepath)
+ }
+ option::none. { srcs[vec::len(srcs) - 2u] }
+ };
+ let actual = srcs[vec::len(srcs) - 1u];
if option::is_some(props.pp_exact) {
// Now we have to care about line endings
let cr = "\r";
- check str::is_not_empty(cr);
+ check (str::is_not_empty(cr));
actual = str::replace(actual, cr, "");
expected = str::replace(expected, cr, "");
}
let procres = typecheck_source(cx, testfile, actual);
if procres.status != 0 {
- fatal_procres("pretty-printed source does not typecheck",
- procres);
+ fatal_procres("pretty-printed source does not typecheck", procres);
}
ret;
fn make_pp_args(config: &config, testfile: &str) -> procargs {
let prog = config.rustc_path;
- let args = ~["-", "--pretty", "normal"];
+ let args = ["-", "--pretty", "normal"];
ret {prog: prog, args: args};
}
fn compare_source(expected: &str, actual: &str) {
if expected != actual {
error("pretty-printed source does match expected source");
- let msg = #fmt("\n\
+ let msg =
+ #fmt["\n\
expected:\n\
------------------------------------------\n\
%s\n\
%s\n\
------------------------------------------\n\
\n",
- expected, actual);
+ expected, actual];
io::stdout().write_str(msg);
fail;
}
fn make_typecheck_args(config: &config, testfile: &str) -> procargs {
let prog = config.rustc_path;
- let args = ~["-", "--no-trans", "--lib"];
+ let args = ["-", "--no-trans", "--lib"];
ret {prog: prog, args: args};
}
}
}
let next_err_idx = 0u;
- let next_err_pat = props.error_patterns.(next_err_idx);
+ let next_err_pat = props.error_patterns[next_err_idx];
for line: str in str::split(procres.stdout, '\n' as u8) {
if str::find(line, next_err_pat) > 0 {
- log #fmt("found error pattern %s", next_err_pat);
+ log #fmt["found error pattern %s", next_err_pat];
next_err_idx += 1u;
if next_err_idx == vec::len(props.error_patterns) {
log "found all error patterns";
ret;
}
- next_err_pat = props.error_patterns.(next_err_idx);
+ next_err_pat = props.error_patterns[next_err_idx];
}
}
let missing_patterns =
vec::slice(props.error_patterns, next_err_idx,
- vec::len(props.error_patterns));
+ vec::len(props.error_patterns));
if vec::len(missing_patterns) == 1u {
- fatal_procres(#fmt("error pattern '%s' not found!",
- missing_patterns.(0)), procres);
+ fatal_procres(#fmt["error pattern '%s' not found!",
+ missing_patterns[0]], procres);
} else {
for pattern: str in missing_patterns {
- error(#fmt("error pattern '%s' not found!", pattern));
+ error(#fmt["error pattern '%s' not found!", pattern]);
}
fatal_procres("multiple error patterns not found", procres);
}
cx.config.compile_lib_path, option::none)
}
-fn exec_compiled_test(cx: &cx, props: &test_props,
- testfile: &str) -> procres {
+fn exec_compiled_test(cx: &cx, props: &test_props, testfile: &str) ->
+ procres {
compose_and_run(cx, testfile, bind make_run_args(_, props, _),
cx.config.run_lib_path, option::none)
}
fn compose_and_run(cx: &cx, testfile: &str,
- make_args: fn(&config, &str) -> procargs ,
- lib_path: &str,
+ make_args: fn(&config, &str) -> procargs, lib_path: &str,
input: option::t<str>) -> procres {
let procargs = make_args(cx.config, testfile);
- ret program_output(cx, testfile, lib_path,
- procargs.prog, procargs.args,
+ ret program_output(cx, testfile, lib_path, procargs.prog, procargs.args,
input);
}
-fn make_compile_args(config: &config,
- props: &test_props, testfile: &str) ->
- procargs {
+fn make_compile_args(config: &config, props: &test_props, testfile: &str) ->
+ procargs {
let prog = config.rustc_path;
- let args = ~[testfile, "-o", make_exe_name(config, testfile)];
+ let args = [testfile, "-o", make_exe_name(config, testfile)];
args += split_maybe_args(config.rustcflags);
args += split_maybe_args(props.compile_flags);
ret {prog: prog, args: args};
output_base_name(config, testfile) + os::exec_suffix()
}
-fn make_run_args(config: &config,
- props: &test_props, testfile: &str) -> procargs {
- let toolargs = if !props.no_valgrind {
- // If we've got another tool to run under (valgrind),
- // then split apart its command
- split_maybe_args(config.runtool)
- } else {
- ~[]
- };
+fn make_run_args(config: &config, props: &test_props, testfile: &str) ->
+ procargs {
+ let toolargs =
+ if !props.no_valgrind {
- let args = toolargs + ~[make_exe_name(config, testfile)];
- ret {prog: args.(0), args: vec::slice(args, 1u, vec::len(args))};
+ // If we've got another tool to run under (valgrind),
+ // then split apart its command
+ split_maybe_args(config.runtool)
+ } else { [] };
+
+ let args = toolargs + [make_exe_name(config, testfile)];
+ ret {prog: args[0], args: vec::slice(args, 1u, vec::len(args))};
}
fn split_maybe_args(argstr: &option::t<str>) -> [str] {
fn rm_whitespace(v: &[str]) -> [str] {
fn flt(s: &str) -> option::t<str> {
- if !is_whitespace(s) {
- option::some(s)
- } else {
- option::none
- }
+ if !is_whitespace(s) { option::some(s) } else { option::none }
}
// FIXME: This should be in std
fn is_whitespace(s: str) -> bool {
- for c: u8 in s {
- if c != (' ' as u8) { ret false; }
- }
+ for c: u8 in s { if c != ' ' as u8 { ret false; } }
ret true;
}
vec::filter_map(flt, v)
alt argstr {
option::some(s) { rm_whitespace(str::split(s, ' ' as u8)) }
- option::none. { ~[] }
+ option::none. { [] }
}
}
fn program_output(cx: &cx, testfile: &str, lib_path: &str, prog: &str,
args: &[str], input: option::t<str>) -> procres {
let cmdline =
- {
- let cmdline = make_cmdline(lib_path, prog, args);
- logv(cx.config, #fmt("executing %s", cmdline));
- cmdline
- };
- let res = procsrv::run(cx.procsrv, lib_path,
- prog, args, input);
+ {
+ let cmdline = make_cmdline(lib_path, prog, args);
+ logv(cx.config, #fmt["executing %s", cmdline]);
+ cmdline
+ };
+ let res = procsrv::run(cx.procsrv, lib_path, prog, args, input);
dump_output(cx.config, testfile, res.out, res.err);
- ret {status: res.status, stdout: res.out,
- stderr: res.err, cmdline: cmdline};
+ ret {status: res.status,
+ stdout: res.out,
+ stderr: res.err,
+ cmdline: cmdline};
}
fn make_cmdline(libpath: &str, prog: &str, args: &[str]) -> str {
- #fmt("%s %s %s", lib_path_cmd_prefix(libpath), prog,
- str::connect(args, " "))
+ #fmt["%s %s %s", lib_path_cmd_prefix(libpath), prog,
+ str::connect(args, " ")]
}
// 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) -> str {
- #fmt("%s=\"%s\"", util::lib_path_env_var(), util::make_new_path(path))
+ #fmt["%s=\"%s\"", util::lib_path_env_var(), util::make_new_path(path)]
}
-fn dump_output(config: &config, testfile: &str,
- out: &str, err: &str) {
+fn dump_output(config: &config, testfile: &str, out: &str, err: &str) {
dump_output_file(config, testfile, out, "out");
dump_output_file(config, testfile, err, "err");
maybe_dump_to_stdout(config, out, err);
#[cfg(target_os = "win32")]
#[cfg(target_os = "linux")]
-fn dump_output_file(config: &config, testfile: &str,
- out: &str, extension: &str) {
+fn dump_output_file(config: &config, testfile: &str, out: &str,
+ extension: &str) {
let outfile = make_out_name(config, testfile, extension);
- let writer = io::file_writer(outfile,
- ~[io::create, io::truncate]);
+ let writer = io::file_writer(outfile, [io::create, io::truncate]);
writer.write_str(out);
}
// FIXME (726): Can't use file_writer on mac
#[cfg(target_os = "macos")]
-fn dump_output_file(config: &config, testfile: &str,
- out: &str, extension: &str) {
+fn dump_output_file(config: &config, testfile: &str, out: &str,
+ extension: &str) {
}
-fn make_out_name(config: &config, testfile: &str,
- extension: &str) -> str {
+fn make_out_name(config: &config, testfile: &str, extension: &str) -> str {
output_base_name(config, testfile) + "." + extension
}
parts = vec::slice(parts, 0u, vec::len(parts) - 1u);
str::connect(parts, ".")
};
- #fmt("%s%s.%s", base, filename, config.stage_id)
+ #fmt["%s%s.%s", base, filename, config.stage_id]
}
-fn maybe_dump_to_stdout(config: &config,
- out: &str, err: &str) {
+fn maybe_dump_to_stdout(config: &config, out: &str, err: &str) {
if config.verbose {
- let sep1 = #fmt("------%s------------------------------",
- "stdout");
- let sep2 = #fmt("------%s------------------------------",
- "stderr");
+ let sep1 = #fmt["------%s------------------------------", "stdout"];
+ let sep2 = #fmt["------%s------------------------------", "stderr"];
let sep3 = "------------------------------------------";
io::stdout().write_line(sep1);
io::stdout().write_line(out);
}
}
-fn error(err: &str) { io::stdout().write_line(#fmt("\nerror: %s", err)); }
+fn error(err: &str) { io::stdout().write_line(#fmt["\nerror: %s", err]); }
fn fatal(err: &str) -> ! { error(err); fail; }
fn fatal_procres(err: &str, procres: procres) -> ! {
let msg =
- #fmt("\n\
+ #fmt["\n\
error: %s\n\
command: %s\n\
stdout:\n\
%s\n\
------------------------------------------\n\
\n",
- err, procres.cmdline, procres.stdout, procres.stderr);
+ err, procres.cmdline, procres.stdout, procres.stderr];
io::stdout().write_str(msg);
fail;
}
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
alt getenv(lib_path_env_var()) {
- option::some(curr) { #fmt("%s:%s", path, curr) }
+ option::some(curr) { #fmt["%s:%s", path, curr] }
option::none. { path }
}
}
// Tests that the pretty printer correctly disambiguates various scenarios
// involving block statements by ending them with a semi-colon
-fn test1() {
- let val = @0;
- {};
- *val;
-}
+fn test1() { let val = @0; { }; *val; }
-fn test2() -> int {
- let val = @0;
- {};
- *val
-}
+fn test2() -> int { let val = @0; { }; *val }
fn test3() {
let regs = @{mutable eax: 0};
- alt true {
- true { }
- };
+ alt true { true { } };
(*regs).eax = 1;
}
-fn test4() -> bool {
- let regs = @true;
- if true { };
- *regs || false
-}
+fn test4() -> bool { let regs = @true; if true { }; *regs || false }
-fn test5() -> (int, int) {
- {};
- (0, 1)
-}
+fn test5() -> (int, int) { { }; (0, 1) }
-fn test6() -> bool {
- {};
- (true || false) && true
-}
+fn test6() -> bool { { }; (true || false) && true }
fn test7() -> uint {
let regs = @0;
(*regs < 2) as uint
}
-fn test8() -> int {
- let val = @0;
- alt true { true { } };
- *val < 1 ? 0 : 1
-}
+fn test8() -> int { let val = @0; alt true { true { } }; *val < 1 ? 0 : 1 }
-fn test9() {
- let regs = @mutable 0;
- alt true {
- true { }
- };
- *regs += 1;
-}
+fn test9() { let regs = @mutable 0; alt true { true { } }; *regs += 1; }
fn test10() -> int {
let regs = @mutable [0];
- alt true {
- true { }
- };
- (*regs).(0)
+ alt true { true { } };
+ (*regs)[0]
}
fn a() -> uint {
1u
-}
\ No newline at end of file
+}
// pp-exact:example2.pp
-fn
-main
-()
-{
-}
+fn main() { }
fn f() { }
-fn block_semi() -> int {
- { f() };
- -1
-}
-
-fn block_nosemi() -> int {
- { 0 } - 1
-}
-
-fn if_semi() -> int {
- if true { f() } else { f() };
- -1
-}
-
-fn if_nosemi() -> int {
- if true { 0 } else { 0 } - 1
-}
-
-fn alt_semi() -> int {
- alt true { true { f() } };
- -1
-}
-
-fn alt_no_semi() -> int {
- alt true { true { 0 } } - 1
-}
-
-fn stmt() {
- { f() };
- -1;
-}
\ No newline at end of file
+fn block_semi() -> int { { f() }; -1 }
+
+fn block_nosemi() -> int { { 0 } - 1 }
+
+fn if_semi() -> int { if true { f() } else { f() }; -1 }
+
+fn if_nosemi() -> int { if true { 0 } else { 0 } - 1 }
+
+fn alt_semi() -> int { alt true { true { f() } }; -1 }
+
+fn alt_no_semi() -> int { alt true { true { 0 } } - 1 }
+
+fn stmt() { { f() }; -1; }
// Testing that comments are correctly interleaved
// pp-exact:vec-comments.pp
fn main() {
- let v1 = ~[
- // Comment
- 0,
- // Comment
- 1,
- // Comment
- 2
- ];
- let v2 = ~[
- 0, // Comment
- 1, // Comment
- 2 // Comment
- ];
- let v3 = ~[
- /* Comment */
- 0,
- /* Comment */
- 1,
- /* Comment */
- 2
- ];
- let v4 = ~[
- 0, /* Comment */
- 1, /* Comment */
- 2 /* Comment */
- ];
+ let v1 =
+ [
+ // Comment
+ 0,
+ // Comment
+ 1,
+ // Comment
+ 2];
+ let v2 =
+ [0, // Comment
+ 1, // Comment
+ 2]; // Comment
+ let v3 =
+ [
+ /* Comment */
+ 0,
+ /* Comment */
+ 1,
+ /* Comment */
+ 2];
+ let v4 =
+ [0, /* Comment */
+ 1, /* Comment */
+ 2]; /* Comment */
}
fn f1(x: [int]) { }
-fn g1() { f1(~[1, 2, 3]); }
+fn g1() { f1([1, 2, 3]); }
fn foo(s: str) { }
fn main() {
- let i = alt some::<int>(3) {
- none::<int>. { fail }
- some::<int>(_) { fail }
- };
+ let i =
+ alt some::<int>(3) { none::<int>. { fail } some::<int>(_) { fail } };
foo(i);
}
// error-pattern:quux
fn f() -> ! { fail "quux" }
-fn g() -> int { alt f() { true { 1 } false { 0 } }; }
+fn g() -> int { alt f() { true { 1 } false { 0 } } }
fn main() { g(); }
// error-pattern:meep
fn f(a: int, b: int, c: @int) { fail "moop"; }
-fn main() { f(1, fail "meep", @42); }
\ No newline at end of file
+fn main() { f(1, fail "meep", @42); }
// error-pattern:quux
-fn test00_start(ch: chan_t<int>, message: int) {
- send(ch, message);
-}
+fn test00_start(ch: chan_t<int>, message: int) { send(ch, message); }
type task_id = int;
type port_id = int;
-type chan_t<~T> = {
- task : task_id,
- port : port_id
-};
+type chan_t<~T> = {task: task_id, port: port_id};
-fn send<~T>(ch : chan_t<T>, data : -T) { fail; }
+fn send<~T>(ch: chan_t<T>, data: -T) { fail; }
fn main() { fail "quux"; }
// error-pattern:quux
-fn main() {
- let x: int = do { fail "quux" } while (true);
-}
+fn main() { let x: int = do { fail "quux" } while true; }
// error-pattern:wooooo
// no-valgrind
-fn main() { let a = 1; if 1 == 1 { a = 2; } fail "woooo" + "o"; }
\ No newline at end of file
+fn main() { let a = 1; if 1 == 1 { a = 2; } fail "woooo" + "o"; }
// error-pattern:explicit
-fn main() { fail; }
\ No newline at end of file
+fn main() { fail; }
fn g() -> int { let x = alt true { true { f() } false { 10 } }; ret x; }
-fn main() { g(); }
\ No newline at end of file
+fn main() { g(); }
// error-pattern:explicit failure
-fn main() { let x = alt true { false { 0 } true { fail } }; }
\ No newline at end of file
+fn main() { let x = alt true { false { 0 } true { fail } }; }
// error-pattern:explicit failure
fn f() -> ! { fail }
-fn main() { f(); }
\ No newline at end of file
+fn main() { f(); }
fn g() -> int { let x = if true { f() } else { 10 }; ret x; }
-fn main() { g(); }
\ No newline at end of file
+fn main() { g(); }
// error-pattern:explicit failure
-fn main() { let x = if false { 0 } else if (true) { fail } else { 10 }; }
\ No newline at end of file
+fn main() { let x = if false { 0 } else if true { fail } else { 10 }; }
// error-pattern:woe
fn f(a: int) { log a; }
-fn main() { f(fail "woe"); }
\ No newline at end of file
+fn main() { f(fail "woe"); }
// error-pattern:moop
use std;
import std::uint;
-fn main() { fail "moop"; }
\ No newline at end of file
+fn main() { fail "moop"; }
// error-pattern:1 == 2
-fn main() { assert (1 == 2); }
\ No newline at end of file
+fn main() { assert (1 == 2); }
use std;
import std::str;
-fn main() { let str_var: str = "meh"; fail #fmt("%s", str_var); }
\ No newline at end of file
+fn main() { let str_var: str = "meh"; fail #fmt["%s", str_var]; }
fn nop(a: uint, b: uint) : le(a, b) { fail "quux"; }
-fn main() {
- let a: uint = 5u;
- let b: uint = 4u;
- claim (le(a, b));
- nop(a, b);
-}
+fn main() { let a: uint = 5u; let b: uint = 4u; claim (le(a, b)); nop(a, b); }
let b: uint = 1u;
check (le(a, b));
log_err safe_slice("kitties", a, b);
-}
\ No newline at end of file
+}
pred even(x: uint) -> bool {
if x < 2u {
ret false;
- } else if (x == 2u) { ret true; } else { ret even(x - 2u); }
+ } else if x == 2u { ret true; } else { ret even(x - 2u); }
}
fn foo(x: uint) { if check even(x) { log x; } else { fail "Number is odd"; } }
-fn main() { foo(3u); }
\ No newline at end of file
+fn main() { foo(3u); }
// error-pattern:non-exhaustive match failure
tag t { a; b; }
-fn main() { let x = a; alt x { b. { } } }
\ No newline at end of file
+fn main() { let x = a; alt x { b. { } } }
pred lt(a: int, b: int) -> bool { ret a < b; }
-fn main() { let a: int = 10; let b: int = 23; check (lt(b, a)); f(b, a); }
\ No newline at end of file
+fn main() { let a: int = 10; let b: int = 23; check (lt(b, a)); f(b, a); }
// Tests that trans treats the rhs of pth's decl
// as a _|_-typed thing, not a str-typed thing
// error-pattern:bye
-fn main() { let pth = fail "bye"; let rs: {t: str} = {t: pth}; }
\ No newline at end of file
+fn main() { let pth = fail "bye"; let rs: {t: str} = {t: pth}; }
fn main() {
let s: str = "hello";
let x: int = 0;
- assert (s.(x) == 0x68 as u8);
+ assert (s[x] == 0x68 as u8);
// NB: at the moment a string always has a trailing NULL,
// so the largest index value on the string above is 5, not
// 4. Possibly change this.
// Bounds-check failure.
- assert (s.(x + 6) == 0x0 as u8);
-}
\ No newline at end of file
+ assert (s[x + 6] == 0x0 as u8);
+}
// error-pattern:bounds check
// no-valgrind
fn main() {
- let v: [int] = ~[10];
+ let v: [int] = [10];
let x: int = 0;
- assert (v.(x) == 10);
+ assert (v[x] == 10);
// Bounds-check failure.
- assert (v.(x + 2) == 20);
+ assert (v[x + 2] == 20);
}
// error-pattern:bounds check
// no-valgrind
fn main() {
- let v: [int] = ~[10, 20];
+ let v: [int] = [10, 20];
let x: int = 0;
- assert (v.(x) == 10);
+ assert (v[x] == 10);
// Bounds-check failure.
- assert (v.(x - 1) == 20);
+ assert (v[x - 1] == 20);
}
type r<T> = {mutable v: [option<T>]};
-fn f<T>() -> [T] { ret ~[]; }
+fn f<T>() -> [T] { ret []; }
-fn main() { let r: r<int> = {mutable v: ~[]}; r.v = f(); }
+fn main() { let r: r<int> = {mutable v: []}; r.v = f(); }
import std::option::*;
fn main() {
- let i: int = alt some::<int>(3) {
- none::<int>. { fail }
- some::<int>(_) { 5 }
- };
+ let i: int =
+ alt some::<int>(3) { none::<int>. { fail } some::<int>(_) { 5 } };
log i;
}
fn foo<T>(y: &option::t<T>) {
let x: int;
- let rs: [int] = ~[];
+ let rs: [int] = [];
/* tests that x doesn't get put in the precondition for the
entire if expression */
if true {
- } else { alt y { none::<T>. { x = 17; } _ { x = 42; } } rs += ~[x]; }
+ } else { alt y { none::<T>. { x = 17; } _ { x = 42; } } rs += [x]; }
ret;
}
fn bar(x: m1::foo) { alt x { m1::foo1. { } } }
-fn main() { }
\ No newline at end of file
+fn main() { }
log str::refcount(s);
assert (str::refcount(s) == const_refcount);
-}
\ No newline at end of file
+}
alt f { 10 { log "case 10"; ret 20; } 11 { log "case 11"; ret 22; } }
}
-fn main() { assert (altlit(10) == 20); assert (altlit(11) == 22); }
\ No newline at end of file
+fn main() { assert (altlit(10) == 20); assert (altlit(11) == 22); }
fn altsimple(f: int) { alt f { x { } } }
-fn main() { }
\ No newline at end of file
+fn main() { }
tag1("test") { }
_ { fail; }
}
-}
\ No newline at end of file
+}
assert (process(gray) == 127);
assert (process(clear) == 0);
assert (process(red) == 255);
-}
\ No newline at end of file
+}
let my_a = a();
- let my_b = obj () {
- fn baz() -> int { ret self.foo(); }
- with my_a
- };
+ let my_b =
+ obj () {
+ fn baz() -> int { ret self.foo(); }
+ with
+ my_a
+ };
- assert my_a.foo() == 2;
- assert my_a.bar() == 2;
- assert my_b.foo() == 2;
- assert my_b.baz() == 2;
- assert my_b.bar() == 2;
+ assert (my_a.foo() == 2);
+ assert (my_a.bar() == 2);
+ assert (my_b.foo() == 2);
+ assert (my_b.baz() == 2);
+ assert (my_b.bar() == 2);
}
// The Internet made me do it.
obj cat() {
- fn ack() -> str {
- ret "ack";
- }
- fn meow() -> str {
- ret "meow";
- }
- fn zzz() -> str {
- ret self.meow();
- }
+ fn ack() -> str { ret "ack"; }
+ fn meow() -> str { ret "meow"; }
+ fn zzz() -> str { ret self.meow(); }
}
let shortcat = cat();
- let longcat = obj() {
- fn lol() -> str {
- ret "lol";
- }
- fn nyan() -> str {
- ret "nyan";
- }
- with shortcat
- };
-
- let longercat = obj() {
- fn meow() -> str {
- ret "zzz";
- }
- with shortcat
- };
-
- let evenlongercat = obj() {
- fn meow() -> str {
- ret "zzzzzz";
- }
- with longercat
- };
+ let longcat =
+ obj () {
+ fn lol() -> str { ret "lol"; }
+ fn nyan() -> str { ret "nyan"; }
+ with
+ shortcat
+ };
+
+ let longercat =
+ obj () {
+ fn meow() -> str { ret "zzz"; }
+ with
+ shortcat
+ };
+
+ let evenlongercat =
+ obj () {
+ fn meow() -> str { ret "zzzzzz"; }
+ with
+ longercat
+ };
// Tests self-call.
assert (shortcat.zzz() == "meow");
assert (my_d.foo() == 2);
assert (my_d.bar() == 2);
-}
\ No newline at end of file
+}
fn main() {
// Anonymous object that doesn't extend an existing one.
- let my_obj = obj() {
- fn foo() -> int { ret 2; }
- fn bar() -> int { ret 3; }
- fn baz() -> str { "hello!" }
- };
+ let my_obj =
+ obj () {
+ fn foo() -> int { ret 2; }
+ fn bar() -> int { ret 3; }
+ fn baz() -> str { "hello!" }
+ };
- assert my_obj.foo() == 2;
- assert my_obj.bar() == 3;
- assert my_obj.baz() == "hello!";
+ assert (my_obj.foo() == 2);
+ assert (my_obj.bar() == 3);
+ assert (my_obj.baz() == "hello!");
// Make sure the result is extendable.
- let my_ext_obj = obj() {
- fn foo() -> int { ret 3; }
- fn quux() -> str { ret self.baz(); }
- with my_obj
- };
+ let my_ext_obj =
+ obj () {
+ fn foo() -> int { ret 3; }
+ fn quux() -> str { ret self.baz(); }
+ with
+ my_obj
+ };
- assert my_ext_obj.foo() == 3;
- assert my_ext_obj.bar() == 3;
- assert my_ext_obj.baz() == "hello!";
- assert my_ext_obj.quux() == "hello!";
+ assert (my_ext_obj.foo() == 3);
+ assert (my_ext_obj.bar() == 3);
+ assert (my_ext_obj.baz() == "hello!");
+ assert (my_ext_obj.quux() == "hello!");
// And again.
- let my_ext_ext_obj = obj() {
- fn baz() -> str { "world!" }
- with my_ext_obj
- };
+ let my_ext_ext_obj =
+ obj () {
+ fn baz() -> str { "world!" }
+ with
+ my_ext_obj
+ };
- assert my_ext_ext_obj.foo() == 3;
- assert my_ext_ext_obj.bar() == 3;
- assert my_ext_ext_obj.baz() == "world!";
- assert my_ext_ext_obj.quux() == "world!";
+ assert (my_ext_ext_obj.foo() == 3);
+ assert (my_ext_ext_obj.bar() == 3);
+ assert (my_ext_ext_obj.baz() == "world!");
+ assert (my_ext_ext_obj.quux() == "world!");
}
};
assert (my_b.foo() == 3);
-}
\ No newline at end of file
+}
assert (my_c.baz(1, 2) == 6);
assert (my_d.baz(1, 2) == 5);
-}
\ No newline at end of file
+}
};
assert (my_b.baz() == 2);
-}
\ No newline at end of file
+}
assert (my_c.baz() == 3);
assert (my_c.bar() == 3);
-}
\ No newline at end of file
+}
fn main(args: [str]) {
- let vs: [str] = ~["hi", "there", "this", "is", "a", "vec"];
- let vvs: [[str]] = ~[args, vs];
+ let vs: [str] = ["hi", "there", "this", "is", "a", "vec"];
+ let vvs: [[str]] = [args, vs];
for vs: [str] in vvs { for s: str in vs { log s; } }
}
-fn main() { let a: int = 10; log a; assert (a * (a - 1) == 90); }
\ No newline at end of file
+fn main() { let a: int = 10; log a; assert (a * (a - 1) == 90); }
assert (i32_b & i32_b << 1 == 0);
log i32_b | i32_b << 1;
assert (i32_b | i32_b << 1 == 0x30303030);
-}
\ No newline at end of file
+}
let i32_c: int = 0x10101010;
assert (i32_c + i32_c * 2 / 3 * 2 + (i32_c - 7 % 3) ==
i32_c + i32_c * 2 / 3 * 2 + (i32_c - 7 % 3));
-}
\ No newline at end of file
+}
assert (4000000005u32 % 10u32 == 5u32);
// 64-bit numbers have some flakiness yet. Not tested
-}
\ No newline at end of file
+}
fn f() -> int { { ret 3; } }
-fn main() { assert (f() == 3); }
\ No newline at end of file
+fn main() { assert (f() == 3); }
assert (x == 33);
}
-fn main() { test_assign(); test_assign_op(); }
\ No newline at end of file
+fn main() { test_assign(); test_assign_op(); }
assert (g(8) == 9);
assert (h(0x1badd00d) == 0x1badd00e);
assert ((@add1)(42) == 43);
-}
\ No newline at end of file
+}
fn main() {
let sum = 0;
- for x in ~[1, 2, 3, 4, 5] { sum += x; }
+ for x in [1, 2, 3, 4, 5] { sum += x; }
assert (sum == 15);
}
-fn f<T>(x: &[T]) -> T { ret x.(0); }
+fn f<T>(x: &[T]) -> T { ret x[0]; }
-fn g(act: fn(&[int]) -> int ) -> int { ret act(~[1, 2, 3]); }
+fn g(act: fn(&[int]) -> int) -> int { ret act([1, 2, 3]); }
fn main() {
assert (g(f) == 1);
- let f1: fn(&[str]) -> str = f;
- assert (f1(~["x", "y", "z"]) == "x");
+ let f1: fn(&[str]) -> str = f;
+ assert (f1(["x", "y", "z"]) == "x");
}
fn foo(c: @clam) { c.chowder(); }
-fn main() { let c: clam = clam(); foo(@c); }
\ No newline at end of file
+fn main() { let c: clam = clam(); foo(@c); }
fn f(n: int) -> int { ret n; }
fn main() {
- let g: fn() -> int = bind f(10);
+ let g: fn() -> int = bind f(10);
let i: int = g();
assert (i == 10);
-}
\ No newline at end of file
+}
assert (obj0.sum() == 3);
assert (obj1.sum() == 3);
assert (obj2.sum() == 3);
-}
\ No newline at end of file
+}
let y = bind echo(42, _);
- y(fn(i: &str){});
+ y(fn (i: &str) { });
}
fn main() {
fn echo<T>(c: int, x: &[T]) { }
- let y: fn(&[int]) = bind echo(42, _);
+ let y: fn(&[int]) = bind echo(42, _);
- y(~[1]);
+ y([1]);
}
fn f() -> int { ret 42; }
fn main() {
- let g: fn() -> int = bind f();
+ let g: fn() -> int = bind f();
let i: int = g();
assert (i == 42);
-}
\ No newline at end of file
+}
fn f(n: int) -> int { ret n; }
fn main() {
- let g: fn(int) -> int = bind f(_);
+ let g: fn(int) -> int = bind f(_);
let i: int = g(42);
assert (i == 42);
-}
\ No newline at end of file
+}
let p1 = comm::mk_port::<int>();
let p2 = comm::mk_port::<int>();
- assert p1 == p1;
- assert p1 != p2;
+ assert (p1 == p1);
+ assert (p1 != p2);
}
fn test_chan() {
let ch1 = p.mk_chan();
let ch2 = p.mk_chan();
- assert ch1 == ch1;
+ assert (ch1 == ch1);
// Chans are equal because they are just task:port addresses.
- assert ch1 == ch2;
+ assert (ch1 == ch2);
}
fn test_ptr() {
let t1 = task::spawn(f1);
let t2 = task::spawn(f2);
- assert t1 == t1;
- assert t1 != t2;
+ assert (t1 == t1);
+ assert (t1 != t2);
}
fn test_fn() {
}
fn test_obj() {
- let o1 = obj () { };
- let o2 = obj () { };
+ let o1 = obj () { };
+ let o2 = obj () { };
assert (o1 == o1);
assert (-16 >>> 2 == -4);
assert (0b1010_1010 | 0b0101_0101 == 0xff);
assert (-1000 >> 3 == 536870787);
-}
\ No newline at end of file
+}
-fn force(f: &block() -> int ) -> int { ret f(); }
+fn force(f: &block() -> int) -> int { ret f(); }
fn main() {
let f = fn () -> int { ret 7 };
assert (force(f) == 7);
let g = bind force(f);
assert (g() == 7);
-}
\ No newline at end of file
+}
-fn iter_vec<T>(v: &[T], f: &block(&T) ) { for x: T in v { f(x); } }
+fn iter_vec<T>(v: &[T], f: &block(&T)) { for x: T in v { f(x); } }
fn main() {
- let v = ~[1, 2, 3, 4, 5, 6, 7];
+ let v = [1, 2, 3, 4, 5, 6, 7];
let odds = 0;
iter_vec(v,
- {|&i|
- log_err i;
- if i % 2 == 1 { odds += 1; }
- log_err odds;
- });
+ {|&i| log_err i; if i % 2 == 1 { odds += 1; } log_err odds; });
log_err odds;
assert (odds == 4);
}
-fn iter_vec<T>(v: &[T], f: &block(&T) ) { for x: T in v { f(x); } }
+fn iter_vec<T>(v: &[T], f: &block(&T)) { for x: T in v { f(x); } }
fn main() {
- let v = ~[1, 2, 3, 4, 5];
+ let v = [1, 2, 3, 4, 5];
let sum = 0;
- iter_vec(v,
- {|&i|
- iter_vec(v, {|&j| log_err i * j; sum += i * j; });
- });
+ iter_vec(v, {|&i| iter_vec(v, {|&j| log_err i * j; sum += i * j; }); });
log_err sum;
assert (sum == 225);
}
import std::vec;
fn main() {
- let v = std::vec::map2({|&i, &b| if b { -i } else { i }},
- ~[1, 2, 3, 4, 5],
- ~[true, false, false, true, true]);
+ let v =
+ std::vec::map2({|&i, &b| if b { -i } else { i } }, [1, 2, 3, 4, 5],
+ [true, false, false, true, true]);
log_err v;
- assert v == ~[-1, 2, 3, -4, -5];
+ assert (v == [-1, 2, 3, -4, -5]);
}
fn main() {
if !false { assert (true); } else { assert (false); }
if !true { assert (false); } else { assert (true); }
-}
\ No newline at end of file
+}
assert (@1 < @3);
assert (@@"hello " > @@"hello");
assert (@@@"hello" != @@@"there");
-}
\ No newline at end of file
+}
-fn main() {
- let i: (@int, int) = (@10, 10);
- let (a, _) = i;
-}
\ No newline at end of file
+fn main() { let i: (@int, int) = (@10, 10); let (a, _) = i; }
u(@{a: a, b: b}) { a + (b as int) }
_ { 66 }
} == 50);
-}
\ No newline at end of file
+}
-fn main() { let x: @int = @10; assert (*x == 10); }
\ No newline at end of file
+fn main() { let x: @int = @10; assert (*x == 10); }
fn int_id(x: int) -> int { ret x; }
-fn main() { while true { int_id(break); } }
\ No newline at end of file
+fn main() { while true { int_id(break); } }
assert (i == 10);
do { i += 1; if i == 20 { break; } } while i < 30
assert (i == 20);
- for x: int in ~[1, 2, 3, 4, 5, 6] {
- if x == 3 { break; }
- assert (x <= 3);
- }
+ for x: int in [1, 2, 3, 4, 5, 6] { if x == 3 { break; } assert (x <= 3); }
i = 0;
while i < 10 { i += 1; if i % 2 == 0 { cont; } assert (i % 2 != 0); }
i = 0;
do { i += 1; if i % 2 == 0 { cont; } assert (i % 2 != 0); } while i < 10
- for x: int in ~[1, 2, 3, 4, 5, 6] {
+ for x: int in [1, 2, 3, 4, 5, 6] {
if x % 2 == 0 { cont; }
assert (x % 2 != 0);
}
-tag int_fn { f(fn(int) -> int ); }
-tag int_box_fn { fb(@fn(int) -> int ); }
+tag int_fn { f(fn(int) -> int); }
+tag int_box_fn { fb(@fn(int) -> int); }
fn add1(i: int) -> int { ret i + 1; }
fn main() {
let g = f(add1);
assert (f(add1)(5) == 6);
assert ((@f(add1))(5) == 6);
assert (fb(@add1)(7) == 8);
-}
\ No newline at end of file
+}
assert (0x51 as char == 'Q');
assert (true == 1 as bool);
assert (0 as u32 == false as u32);
-}
\ No newline at end of file
+}
import std::comm;
import std::comm::mk_port;
-tag request {
- quit;
- close(_chan<bool>);
-}
+tag request { quit; close(_chan<bool>); }
type ctx = _chan<request>;
assert (d == c);
assert (d == 'x');
assert ('x' == d);
-}
\ No newline at end of file
+}
fn child2(s: str) { }
-fn main() { let x = task::_spawn(bind child2("hi")); }
\ No newline at end of file
+fn main() { let x = task::_spawn(bind child2("hi")); }
pred fails(a: uint) -> bool { fail; }
-fn main() { let b: uint = 4u; claim (fails(b)); }
\ No newline at end of file
+fn main() { let b: uint = 4u; claim (fails(b)); }
-fn main(args: [str]) { log args.(0); }
+fn main(args: [str]) { log args[0]; }
ret 0;
}
-fn main() { let x: int = 2 + 2; log x; log "hello, world"; log 10; }
\ No newline at end of file
+fn main() { let x: int = 2 + 2; log x; log "hello, world"; log 10; }
const i: int = 10;
-fn main() { log i; }
\ No newline at end of file
+fn main() { log i; }
pred less_than(x: int, y: int) -> bool { ret x < y; }
-type ordered_range = {low: int, high: int} : less_than(*.low, *.high);
+type ordered_range = {low: int, high: int} : less_than(*.low, *.high);
-fn main() { }
\ No newline at end of file
+fn main() { }
check (le(a, b));
c <- a;
log safe_slice("kitties", c, b);
-}
\ No newline at end of file
+}
check (le(a, b));
let c <- a;
log safe_slice("kitties", c, b);
-}
\ No newline at end of file
+}
check (le(b, a));
b <-> a;
log safe_slice("kitties", a, b);
-}
\ No newline at end of file
+}
check (le(a, b));
let c = b;
log safe_slice("kitties", a, c);
-}
\ No newline at end of file
+}
// Attributes of the following function
#[attr1 = "val"]
#[attr2 = "val"]
-fn main() { }
\ No newline at end of file
+fn main() { }
// -*- rust -*-
-fn main() { if 1 == 1 { ret; } log "Paul is dead"; }
\ No newline at end of file
+fn main() { if 1 == 1 { ret; } log "Paul is dead"; }
if x == 1 { ret 1; } else { let y: int = 1 + f(x - 1); ret y; }
}
-fn main() { assert (f(5000) == 5000); }
\ No newline at end of file
+fn main() { assert (f(5000) == 5000); }
-fn main() { let x = @mutable 5; *x = 1000; log *x; }
\ No newline at end of file
+fn main() { let x = @mutable 5; *x = 1000; log *x; }
-fn main() { let x: @int = @10; let y: int = *x; }
\ No newline at end of file
+fn main() { let x: @int = @10; let y: int = *x; }
assert (x % 3 == 0);
assert (x % y == 0);
assert (15 % y == 0);
-}
\ No newline at end of file
+}
fn g(i: &int) { }
fn f(foo: @@quux) { g(foo.bar); }
-fn main() { }
\ No newline at end of file
+fn main() { }
fn f(x: @int) { }
-fn main() { let x = @10; let ff = bind f(_); ff(x); ff(x); }
\ No newline at end of file
+fn main() { let x = @10; let ff = bind f(_); ff(x); ff(x); }
tag t { foo(@int); }
-fn main() { let tt = foo(@10); alt tt { foo(z) { } } }
\ No newline at end of file
+fn main() { let tt = foo(@10); alt tt { foo(z) { } } }
// -*- rust -*-
fn f() -> int { if true { let s: str = "should not leak"; ret 1; } ret 0; }
-fn main() { f(); }
\ No newline at end of file
+fn main() { f(); }
-fn wsucc(n: int) -> int {
- { ret n + 1 } + 0;
-}
-fn main() {}
+fn wsucc(n: int) -> int { { ret n + 1 } + 0; }
+fn main() { }
-fn wsucc(n: int) -> int {
- { ret n + 1 } == 0;
-}
-fn main() {}
+fn wsucc(n: int) -> int { { ret n + 1 } == 0; }
+fn main() { }
fn main() {
if 1 == 2 {
assert (false);
- } else if (2 == 3) {
+ } else if 2 == 3 {
assert (false);
- } else if (3 == 4) { assert (false); } else { assert (true); }
- if 1 == 2 { assert (false); } else if (2 == 2) { assert (true); }
+ } else if 3 == 4 { assert (false); } else { assert (true); }
+ if 1 == 2 { assert (false); } else if 2 == 2 { assert (true); }
if 1 == 2 {
assert (false);
- } else if (2 == 2) {
+ } else if 2 == 2 {
if 1 == 1 {
assert (true);
} else { if 2 == 1 { assert (false); } else { assert (false); } }
if 1 == 2 {
assert (false);
} else { if 1 == 2 { assert (false); } else { assert (true); } }
-}
\ No newline at end of file
+}
-fn main() { let v: [mutable int] = ~[mutable ]; }
+fn main() { let v: [mutable int] = [mutable]; }
fn f() -> t { ret t1; }
}
-fn main() { let v: foo::t = foo::f(); }
\ No newline at end of file
+fn main() { let v: foo::t = foo::f(); }
mod m {
export f, g;
- fn f() {}
- fn g() {}
+ fn f() { }
+ fn g() { }
}
-fn main() {
- f();
- g();
- m::f();
- m::g();
-}
\ No newline at end of file
+fn main() { f(); g(); m::f(); m::g(); }
fn x() { log "x"; }
}
-fn main() { foo::bar::y(); }
\ No newline at end of file
+fn main() { foo::bar::y(); }
fn x() { log "x"; }
}
-fn main() { foo::x(); }
\ No newline at end of file
+fn main() { foo::x(); }
tag t { t1; }
}
-fn main() { let v = foo::t1; }
\ No newline at end of file
+fn main() { let v = foo::t1; }
fn g(v: t) { assert (v == t1); }
}
-fn main() { foo::g(foo::f()); }
\ No newline at end of file
+fn main() { foo::g(foo::f()); }
assert (res == "happy");
}
-fn main() { test_box(); test_str(); }
\ No newline at end of file
+fn main() { test_box(); test_str(); }
true { 10 }
false { alt true { true { fail } false { fail } } }
};
-}
\ No newline at end of file
+}
}
fn test_box() {
- let r = alt true { true { ~[10] } false { fail } };
- assert (r.(0) == 10);
+ let r = alt true { true { [10] } false { fail } };
+ assert (r[0] == 10);
}
-fn main() { test_simple(); test_box(); }
\ No newline at end of file
+fn main() { test_simple(); test_box(); }
// -*- rust -*-
-type compare<T> = fn(@T, @T) -> bool ;
+type compare<T> = fn(@T, @T) -> bool;
fn test_generic<T>(expected: @T, eq: &compare<T>) {
let actual: @T = alt true { true { expected } };
// -*- rust -*-
-type compare<T> = fn(&T, &T) -> bool ;
+type compare<T> = fn(&T, &T) -> bool;
fn test_generic<T>(expected: &T, eq: &compare<T>) {
let actual: T = alt true { true { expected } };
// -*- rust -*-
-type compare<T> = fn(&T, &T) -> bool ;
+type compare<T> = fn(&T, &T) -> bool;
fn test_generic<T>(expected: &T, eq: &compare<T>) {
let actual: T = alt true { true { expected } };
assert (rs == happy);
}
-fn main() { test_rec(); test_tag(); }
\ No newline at end of file
+fn main() { test_rec(); test_tag(); }
test_inferrence();
test_alt_as_alt_head();
test_alt_as_block_result();
-}
\ No newline at end of file
+}
// -*- rust -*-
-fn main() { let x = { @100 }; assert (*x == 100); }
\ No newline at end of file
+fn main() { let x = { @100 }; assert (*x == 100); }
fn test_fn() {
- type t = fn() -> int ;
+ type t = fn() -> int;
fn ten() -> int { ret 10; }
let rs: t = { ten };
assert (rs() == 10);
}
-fn main() { test_fn(); }
\ No newline at end of file
+fn main() { test_fn(); }
// -*- rust -*-
-type compare<T> = fn(@T, @T) -> bool ;
+type compare<T> = fn(@T, @T) -> bool;
fn test_generic<T>(expected: @T, eq: &compare<T>) {
let actual: @T = { expected };
// -*- rust -*-
-type compare<T> = fn(&T, &T) -> bool ;
+type compare<T> = fn(&T, &T) -> bool;
fn test_generic<T>(expected: &T, eq: &compare<T>) {
let actual: T = { expected };
// -*- rust -*-
// Tests for standalone blocks as expressions with dynamic type sizes
-type compare<T> = fn(&T, &T) -> bool ;
+type compare<T> = fn(&T, &T) -> bool;
fn test_generic<T>(expected: &T, eq: &compare<T>) {
let actual: T = { expected };
// Regression test for issue #388
-fn main() { let x = { { @10 } }; }
\ No newline at end of file
+fn main() { let x = { { @10 } }; }
assert (a.a == 3);
let c = { let d = {v: 3}; d };
assert (c.v == 3);
-}
\ No newline at end of file
+}
assert (rs == 10);
}
-fn main() { test_basic(); test_rec(); test_filled_with_stuff(); }
\ No newline at end of file
+fn main() { test_basic(); test_rec(); test_filled_with_stuff(); }
-fn main() {
- let x = 10;
- let y = copy x;
- log y;
-}
\ No newline at end of file
+fn main() { let x = 10; let y = copy x; log y; }
// values from the else if branch
fn main() {
let y: @uint = @10u;
- let x = if false { y } else if (true) { y } else { y };
+ let x = if false { y } else if true { y } else { y };
assert (*y == 10u);
}
// Regression test for issue #388
-fn main() {
- let x = if false { @0u } else if (true) { @10u } else { @0u };
-}
\ No newline at end of file
+fn main() { let x = if false { @0u } else if true { @10u } else { @0u }; }
fn f() { let x = alt true { true { 10 } false { ret } }; }
-fn main() { }
\ No newline at end of file
+fn main() { }
}
fn test_vec() {
- fn f() -> [int] { ~[10, 11] }
- assert (f().(1) == 11);
+ fn f() -> [int] { [10, 11] }
+ assert (f()[1] == 11);
}
fn test_generic() {
assert (rs == "happy");
}
-fn main() { test_box(); test_str(); }
\ No newline at end of file
+fn main() { test_box(); test_str(); }
// When all branches of an if expression result in fail, the entire if
// expression results in fail.
-fn main() { let x = if true { 10 } else { if true { fail } else { fail } }; }
\ No newline at end of file
+fn main() { let x = if true { 10 } else { if true { fail } else { fail } }; }
}
fn test_elseif_fail() {
- let x = if false { 0 } else if (false) { fail } else { 10 };
+ let x = if false { 0 } else if false { fail } else { 10 };
assert (x == 10);
}
-fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
\ No newline at end of file
+fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
// -*- rust -*-
-type compare<T> = fn(@T, @T) -> bool ;
+type compare<T> = fn(@T, @T) -> bool;
fn test_generic<T>(expected: @T, not_expected: @T, eq: &compare<T>) {
let actual: @T = if true { expected } else { not_expected };
// -*- rust -*-
-type compare<T> = fn(&T, &T) -> bool ;
+type compare<T> = fn(&T, &T) -> bool;
fn test_generic<T>(expected: &T, not_expected: &T, eq: &compare<T>) {
let actual: T = if true { expected } else { not_expected };
// -*- rust -*-
// Tests for if as expressions with dynamic type sizes
-type compare<T> = fn(&T, &T) -> bool ;
+type compare<T> = fn(&T, &T) -> bool;
fn test_generic<T>(expected: &T, not_expected: &T, eq: &compare<T>) {
let actual: T = if true { expected } else { not_expected };
assert (rs == happy);
}
-fn main() { test_rec(); test_tag(); }
\ No newline at end of file
+fn main() { test_rec(); test_tag(); }
}
fn test_elseif1() {
- let rs: bool = if true { true } else if (true) { false } else { false };
+ let rs: bool = if true { true } else if true { false } else { false };
assert (rs);
}
fn test_elseif2() {
- let rs: bool = if false { false } else if (true) { true } else { false };
+ let rs: bool = if false { false } else if true { true } else { false };
assert (rs);
}
fn test_elseif3() {
- let rs: bool = if false { false } else if (false) { false } else { true };
+ let rs: bool = if false { false } else if false { false } else { true };
assert (rs);
}
test_inferrence();
test_if_as_if_condition();
test_if_as_block_result();
-}
\ No newline at end of file
+}
// xfail-fast
fn f() { }
-fn main() { ret ::f(); }
\ No newline at end of file
+fn main() { ret ::f(); }
f(b);
assert (a.z == 12);
assert (b.z == 13);
-}
\ No newline at end of file
+}
assert (f(5) == 120);
// log "all done";
-}
\ No newline at end of file
+}
-fn fix_help<A, B>(f: @fn(@fn(&A) -> B , &A) -> B , x: &A) -> B {
+fn fix_help<A, B>(f: @fn(@fn(&A) -> B, &A) -> B, x: &A) -> B {
ret f(@bind fix_help(f, _), x);
}
-fn fix<A, B>(f: @fn(@fn(&A) -> B , &A) -> B ) -> @fn(&A) -> B {
+fn fix<A, B>(f: @fn(@fn(&A) -> B, &A) -> B) -> @fn(&A) -> B {
ret @bind fix_help(f, _);
}
-fn fact_(f: @fn(&int) -> int , n: &int) -> int {
+fn fact_(f: @fn(&int) -> int, n: &int) -> int {
// fun fact 0 = 1
ret if n == 0 { 1 } else { n * f(n - 1) };
}
let n: float = 0.1;
let m: float = foo(n);
log m;
-}
\ No newline at end of file
+}
|| pi > 1.0 {
log "yes";
}
-}
\ No newline at end of file
+}
assert (h == i);
assert (j > k);
assert (k < a);
-}
\ No newline at end of file
+}
let g = 4.90000000001e-10;
assert (g > 5e-11);
assert (g < 5e-9);
-}
\ No newline at end of file
+}
let b: uint = 4u;
check (le(a, b));
log safe_slice("kitties", a, b);
-}
\ No newline at end of file
+}
-fn main() { let x = fn (a: int) -> int { ret a + 1; }; assert (x(4) == 5); }
\ No newline at end of file
+fn main() { let x = fn (a: int) -> int { ret a + 1; }; assert (x(4) == 5); }
// -*- rust -*-
-fn foo(f: fn(int) -> int ) { }
+fn foo(f: fn(int) -> int) { }
fn id(x: int) -> int { ret x; }
-fn main() { foo(id); }
\ No newline at end of file
+fn main() { foo(id); }
fn main() {
// We should be able to type infer inside of lambdas.
let f = fn () { let i = 10; };
-}
\ No newline at end of file
+}
fn main() {
- for {x, y}: {x: int, y: int} in ~[{x: 10, y: 20}, {x: 30, y: 0}] {
- assert x + y == 30;
+ for {x: x, y: y}: {x: int, y: int} in [{x: 10, y: 20}, {x: 30, y: 0}] {
+ assert (x + y == 30);
}
}
iter x() -> {x: int, y: int} {
let i = 0;
- while i < 40 {
- put {x: i, y: 30 - i};
- i += 10;
- }
+ while i < 40 { put {x: i, y: 30 - i}; i += 10; }
}
fn main() {
- for each {x, y}: {x: int, y: int} in x() {
- assert x + y == 30;
- }
+ for each {x: x, y: y}: {x: int, y: int} in x() { assert (x + y == 30); }
}
-fn main() { let x: [int] = ~[]; for i: int in x { fail "moop"; } }
+fn main() { let x: [int] = []; for i: int in x { fail "moop"; } }
}
fn main() {
- let a: [mutable int] = ~[mutable -1, -1, -1, -1, -1, -1, -1, -1];
+ let a: [mutable int] = [mutable -1, -1, -1, -1, -1, -1, -1, -1];
let p: int = 0;
for each i: int in two() {
for each j: int in range(0, 2) {
let tmp: int = 10 * i + j;
- for each k: int in range(0, 2) { a.(p) = 10 * tmp + k; p += 1; }
+ for each k: int in range(0, 2) { a[p] = 10 * tmp + k; p += 1; }
}
}
- assert (a.(0) == 0);
- assert (a.(1) == 1);
- assert (a.(2) == 10);
- assert (a.(3) == 11);
- assert (a.(4) == 100);
- assert (a.(5) == 101);
- assert (a.(6) == 110);
- assert (a.(7) == 111);
+ assert (a[0] == 0);
+ assert (a[1] == 1);
+ assert (a[2] == 10);
+ assert (a[3] == 11);
+ assert (a[4] == 100);
+ assert (a[5] == 101);
+ assert (a[6] == 110);
+ assert (a[7] == 111);
}
iter two() -> int { put 0; put 1; }
fn main() {
- let a: [mutable int] = ~[mutable -1, -1, -1, -1];
+ let a: [mutable int] = [mutable -1, -1, -1, -1];
let p: int = 0;
for each i: int in two() {
- for each j: int in two() { a.(p) = 10 * i + j; p += 1; }
+ for each j: int in two() { a[p] = 10 * i + j; p += 1; }
}
- assert (a.(0) == 0);
- assert (a.(1) == 1);
- assert (a.(2) == 10);
- assert (a.(3) == 11);
+ assert (a[0] == 0);
+ assert (a[1] == 1);
+ assert (a[2] == 10);
+ assert (a[3] == 11);
}
// -*- rust -*-
-fn ho(f: fn(int) -> int ) -> int { let n: int = f(3); ret n; }
+fn ho(f: fn(int) -> int) -> int { let n: int = f(3); ret n; }
fn direct(x: int) -> int { ret x + 1; }
fn main() {
- let a: int =
- direct(3); // direct
+ let a: int = direct(3); // direct
let b: int = ho(direct); // indirect unbound
- let c: int =
- ho(bind direct(_)); // indirect bound
+ let c: int = ho(bind direct(_)); // indirect bound
assert (a == b);
assert (b == c);
-}
\ No newline at end of file
+}
// -*- rust -*-
fn f() -> int { ret 42; }
-fn main() { let g: fn() -> int = f; let i: int = g(); assert (i == 42); }
\ No newline at end of file
+fn main() { let g: fn() -> int = f; let i: int = g(); assert (i == 42); }
tag wrapper<T> { wrapped(T); }
-fn main() { let w = wrapped(~[1, 2, 3, 4, 5]); }
+fn main() { let w = wrapped([1, 2, 3, 4, 5]); }
fn f<T>(v: @T) { }
-fn main() { f(@~[1, 2, 3, 4, 5]); }
+fn main() { f(@[1, 2, 3, 4, 5]); }
fn chk(a: &int) { log a; assert (a == 1); }
-fn apply<T>(produce: fn() -> T , consume: fn(&T) ) { consume(produce()); }
+fn apply<T>(produce: fn() -> T, consume: fn(&T)) { consume(produce()); }
fn main() {
- let produce: fn() -> int = mk;
- let consume: fn(&int) = chk;
+ let produce: fn() -> int = mk;
+ let consume: fn(&int) = chk;
apply::<int>(produce, consume);
}
-fn get_third<T>(t: &(T, T, T)) -> T {
- let (_, _, x) = t;
- ret x;
-}
+fn get_third<T>(t: &(T, T, T)) -> T { let (_, _, x) = t; ret x; }
fn main() {
log get_third((1, 2, 3));
export mapper;
export map_reduce;
- type putter = fn(str, str) ;
+ type putter = fn(str, str);
- type mapper = fn(str, putter) ;
+ type mapper = fn(str, putter);
tag ctrl_proto { find_reducer([u8], _chan<int>); mapper_done; }
}
fn main() {
- map_reduce::map_reduce(~["../src/test/run-pass/hashmap-memory.rs"]);
+ map_reduce::map_reduce(["../src/test/run-pass/hashmap-memory.rs"]);
}
// -*- rust -*-
-fn main() { log "hello, world."; }
\ No newline at end of file
+fn main() { log "hello, world."; }
// -*- rust -*-
-fn main() { let x: i32 = -400_i32; x = 0_i32 - x; assert (x == 400_i32); }
\ No newline at end of file
+fn main() { let x: i32 = -400_i32; x = 0_i32 - x; assert (x == 400_i32); }
x = x + 1i8;
x = x - 1i8;
assert (x == y);
-}
\ No newline at end of file
+}
-fn main() { let i: int = if false { fail } else { 5 }; log i; }
\ No newline at end of file
+fn main() { let i: int = if false { fail } else { 5 }; log i; }
pred even(x: uint) -> bool {
if x < 2u {
ret false;
- } else if (x == 2u) { ret true; } else { ret even(x - 2u); }
+ } else if x == 2u { ret true; } else { ret even(x - 2u); }
}
fn print_even(x: uint) : even(x) { log x; }
fn foo(x: uint) { if check even(x) { print_even(x); } else { fail; } }
-fn main() { foo(2u); }
\ No newline at end of file
+fn main() { foo(2u); }
pred even(x: uint) -> bool {
if x < 2u {
ret false;
- } else if (x == 2u) { ret true; } else { ret even(x - 2u); }
+ } else if x == 2u { ret true; } else { ret even(x - 2u); }
}
fn foo(x: uint) { if check even(x) { log x; } else { fail; } }
-fn main() { foo(2u); }
\ No newline at end of file
+fn main() { foo(2u); }
fn foo() { if (ret) { } }
-fn main() { foo(); }
\ No newline at end of file
+fn main() { foo(); }
mod spam {
- fn ham() {}
- fn eggs() {}
+ fn ham() { }
+ fn eggs() { }
}
native "rust" mod rustrt {
export eggs;
}
-fn main() {
- rustrt::ham();
- rustrt::eggs();
-}
\ No newline at end of file
+fn main() { rustrt::ham(); rustrt::eggs(); }
import spam::{ham, eggs};
mod spam {
- fn ham() {}
- fn eggs() {}
+ fn ham() { }
+ fn eggs() { }
}
-fn main() {
- ham();
- eggs();
-}
\ No newline at end of file
+fn main() { ham(); eggs(); }
}
-fn main() { f1(); f2(); f4(); nameless_fear(); also_redstone(); }
\ No newline at end of file
+fn main() { f1(); f2(); f4(); nameless_fear(); also_redstone(); }
import a1::b1::word_traveler;
mod a1 {
- //
+ //
mod b1 {
- //
+ //
import a2::b1::*;
- // <-\
+ // <-\
export word_traveler; // |
}
- // |
+ // |
mod b2 {
- // |
+ // |
import a2::b2::*;
- // <-\ -\ |
+ // <-\ -\ |
export word_traveler; // | | |
} // | | |
}
- // | | |
- // | | |
- mod a2 {
- // | | |
- native "cdecl" mod b1 = "" {
- // | | |
- import a1::b2::*;
- // | <-/ -/
- export word_traveler; // |
- }
- // |
- mod b2 {
- // |
- fn word_traveler() { // |
- log "ahoy!"; // -/
- } //
- } //
- }
- //
+// | | |
+// | | |
+mod a2 {
+ // | | |
+ native "cdecl" mod b1 = "" {
+ // | | |
+ import a1::b2::*;
+ // | <-/ -/
+ export word_traveler; // |
+ }
+ // |
+ mod b2 {
+ // |
+ fn word_traveler() { // |
+ log "ahoy!"; // -/
+ } //
+ } //
+}
+//
-fn main() { word_traveler(); }
\ No newline at end of file
+fn main() { word_traveler(); }
-fn main() { test1(); test2(); }
\ No newline at end of file
+fn main() { test1(); test2(); }
fn main() {
let v = init_elt(0, 0u);
- v += ~[4, 2];
- assert (reversed(v) == ~[2, 4]);
+ v += [4, 2];
+ assert (reversed(v) == [2, 4]);
}
fn thing() { x(10); z(10); }
}
-fn main() { bar::thing(); }
\ No newline at end of file
+fn main() { bar::thing(); }
fn bar() { log "bar"; }
}
-fn main() { bar(); }
\ No newline at end of file
+fn main() { bar(); }
}
}
-fn main() { bar(); }
\ No newline at end of file
+fn main() { bar(); }
import zed::baz;
export baz;
}
-fn main() { baz(); }
\ No newline at end of file
+fn main() { baz(); }
fn x(y: int) { log y; }
}
-fn main() { x(10); z(10); }
\ No newline at end of file
+fn main() { x(10); z(10); }
// issue #680
-fn f() -> [int] { ~[] }
+fn f() -> [int] { [] }
fn main() { }
fn hello() { inner2::hello(); }
}
-fn main() { inner::hello(); inner::inner2::hello(); }
\ No newline at end of file
+fn main() { inner::hello(); inner::inner2::hello(); }
// -*- rust -*-
-fn main() { let x: int = 10; }
\ No newline at end of file
+fn main() { let x: int = 10; }
// This is a testcase for issue #94.
fn main() {
- let v: [int] = ~[0, 1, 2, 3, 4, 5];
+ let v: [int] = [0, 1, 2, 3, 4, 5];
let s: str = "abcdef";
assert (v[3u] == 3);
assert (v[3u8] == 3);
}
fn main() {
- let v: [int] = ~[];
+ let v: [int] = [];
assert (ivec_len(v) == 0u); // zero-length
- let x = ~[1, 2];
+ let x = [1, 2];
assert (ivec_len(x) == 2u); // on stack
- let y = ~[1, 2, 3, 4, 5];
+ let y = [1, 2, 3, 4, 5];
assert (ivec_len(y) == 5u); // on heap
- v += ~[];
+ v += [];
assert (ivec_len(v) == 0u); // zero-length append
- x += ~[3];
+ x += [3];
assert (ivec_len(x) == 3u); // on-stack append
- y += ~[6, 7, 8, 9];
+ y += [6, 7, 8, 9];
assert (ivec_len(y) == 9u); // on-heap append
let vv = v + v;
assert (ivec_len(vv) == 0u); // zero-length add
- let xx = x + ~[4];
+ let xx = x + [4];
assert (ivec_len(xx) == 4u); // on-stack add
- let yy = y + ~[10, 11];
+ let yy = y + [10, 11];
assert (ivec_len(yy) == 11u); // on-heap add
}
-
fn task_yield();
}
-fn yield_wrap() {
- rustrt::task_yield();
-}
+fn yield_wrap() { rustrt::task_yield(); }
-fn main() {
- let f = yield_wrap;
- task::_spawn(f);
-}
+fn main() { let f = yield_wrap; task::_spawn(f); }
tag msg { closed; received([u8]); }
fn producer(c: _chan<[u8]>) {
- send(c, ~[1u8, 2u8, 3u8, 4u8]);
- let empty: [u8] = ~[];
+ send(c, [1u8, 2u8, 3u8, 4u8]);
+ let empty: [u8] = [];
send(c, empty);
}
log "waiting for bytes";
let data = p.recv();
log "got bytes";
- if vec::len(data) == 0u {
- log "got empty bytes, quitting";
- break;
- }
+ if vec::len(data) == 0u { log "got empty bytes, quitting"; break; }
log "sending non-empty buffer of length";
log vec::len(data);
send(msg, received(data));
fn main() {
let p: _port<msg> = mk_port();
let recv_reader: _port<_chan<[u8]>> = mk_port();
- let pack = task::_spawn(bind packager(recv_reader.mk_chan(),
- p.mk_chan()));
+ let pack =
+ task::_spawn(bind packager(recv_reader.mk_chan(), p.mk_chan()));
let source_chan: _chan<[u8]> = recv_reader.recv();
let prod = task::_spawn(bind producer(source_chan));
use std;
fn f() {
- #fmt("test%s", "s");
+ #fmt["test%s", "s"];
#[attr = "val"]
fn g() { }
}
fn baz() { }
}
-fn main() { }
\ No newline at end of file
+fn main() { }
-fn double<T>(a: &T) -> [T] { ret ~[a] + ~[a]; }
+fn double<T>(a: &T) -> [T] { ret [a] + [a]; }
-fn double_int(a: int) -> [int] { ret ~[a] + ~[a]; }
+fn double_int(a: int) -> [int] { ret [a] + [a]; }
fn main() {
let d = double(1);
- assert (d.(0) == 1);
- assert (d.(1) == 1);
+ assert (d[0] == 1);
+ assert (d[1] == 1);
d = double_int(1);
- assert (d.(0) == 1);
- assert (d.(1) == 1);
+ assert (d[0] == 1);
+ assert (d[1] == 1);
}
fn f(a: [int]) { }
-fn main() { f(~[1, 2, 3, 4, 5]); }
+fn main() { f([1, 2, 3, 4, 5]); }
import std::comm::send;
fn producer(c: _chan<[u8]>) {
- send(c, ~[1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8,
- 8u8, 9u8, 10u8, 11u8, 12u8, 13u8 ]);
+ send(c,
+ [1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8,
+ 13u8]);
}
fn main() {
log_err "3";
}
-fn child() { log_err "2"; }
\ No newline at end of file
+fn child() { log_err "2"; }
// This should typecheck even though the type of e is not fully
// resolved when we finish typechecking the lambda.
fn main() {
- let e = @{mutable refs: ~[], n: 0};
- let f = lambda() { log_err e.n; };
- e.refs += ~[1];
+ let e = @{mutable refs: [], n: 0};
+ let f = lambda () { log_err e.n; };
+ e.refs += [1];
}
fn force(f: &fn()) { f() }
fn main() {
let x = 7;
- lambda() { log_err x; };
- force(lambda() { log_err x; });
+ lambda () { log_err x; }
+ force(lambda () { log_err x; });
}
l: 0};
}
-fn main() { f(); }
\ No newline at end of file
+fn main() { f(); }
log x || incr(y);
assert (y == 10);
if true && x { assert (true); } else { assert (false); }
-}
\ No newline at end of file
+}
fn foo(x: int) { log x; }
-fn main() { let x: int; if 1 > 2 { x = 12; } else { x = 10; } foo(x); }
\ No newline at end of file
+fn main() { let x: int; if 1 > 2 { x = 12; } else { x = 10; } foo(x); }
tag t { a; b(@int); }
-fn main() { let x = b(@10); x = a; }
\ No newline at end of file
+fn main() { let x = b(@10); x = a; }
fn main() {
let u = {x: 10, y: @{a: 20}};
- let {x, y: @{a}} = u;
+ let {x: x, y: @{a: a}} = u;
x = 100;
a = 100;
- assert x == 100;
- assert a == 100;
- assert u.x == 10;
- assert u.y.a == 20;
+ assert (x == 100);
+ assert (a == 100);
+ assert (u.x == 10);
+ assert (u.y.a == 20);
}
-tag xx {
- xx(int);
-}
+tag xx = int;
fn main() {
- let @{x:xx(x), y} = @{x: xx(10), y: 20};
- assert x + y == 30;
+ let @{x: xx(x), y: y} = @{x: xx(10), y: 20};
+ assert (x + y == 30);
}
fn main() {
- let x = ~[1, 2, 3];
+ let x = [1, 2, 3];
let y = 0;
for i: int in x { log i; y += i; }
log y;
// -*- rust -*-
tag list { cons(int, @list); nil; }
-fn main() { cons(10, @cons(11, @cons(12, @nil))); }
\ No newline at end of file
+fn main() { cons(10, @cons(11, @cons(12, @nil))); }
-fn main() { if false { log_err "foo" + "bar"; } }
\ No newline at end of file
+fn main() { if false { log_err "foo" + "bar"; } }
-fn main() { let i: int = 0; while i < 1000000 { i += 1; let x = 3; } }
\ No newline at end of file
+fn main() { let i: int = 0; while i < 1000000 { i += 1; let x = 3; } }
fn main() {
- let x = ~[10, 20, 30];
+ let x = [10, 20, 30];
let sum = 0;
for x in x { sum += x; }
assert (sum == 60);
fn main() {
- #macro([#mylambda[x,body], {fn f(x: int) -> int { ret body }; f}]);
+ #macro[[#mylambda[x, body],
+ {
+ fn f(x: int) -> int { ret body }
+ f
+ }]];
- assert(#mylambda[y,y*2](8) == 16);
-}
\ No newline at end of file
+ assert (#mylambda[y, y * 2](8) == 16);
+}
fn main() {
- #macro([#trivial[], 1*2*4*2*1]);
+ #macro[[#trivial[], 1 * 2 * 4 * 2 * 1]];
- assert(#trivial[] == 16);
+ assert (#trivial[] == 16);
}
fn main() {
- #macro([#apply[f, [x, ...]], f(x, ...)]);
+ #macro[[#apply[f, [x, ...]], f(x, ...)]];
fn add(a: int, b: int) -> int { ret a + b; }
assert (#apply[add, [1, 15]] == 16);
-}
\ No newline at end of file
+}
fn main() {
- #macro([#zip_or_unzip[[x, ...], [y, ...]], [[x, y], ...]],
- [#zip_or_unzip[[xx, yy], ...], [[xx, ...], [yy, ...]]]);
+ #macro[[#zip_or_unzip[[x, ...], [y, ...]], [[x, y], ...]],
+ [#zip_or_unzip[[xx, yy], ...], [[xx, ...], [yy, ...]]]];
assert (#zip_or_unzip[[1, 2, 3, 4], [5, 6, 7, 8]] ==
[[1, 2, 3, 4], [5, 6, 7, 8]]);
- #macro([#nested[[[x, ...], ...], [[y, ...], ...]],
- [[[x, y], ...], ...]]);
+ #macro[[#nested[[[x, ...], ...], [[y, ...], ...]], [[[x, y], ...], ...]]];
assert (#nested[[[1, 2, 3, 4, 5], [7, 8, 9, 10, 11, 12]],
[[-1, -2, -3, -4, -5], [-7, -8, -9, -10, -11, -12]]] ==
[[[1, -1], [2, -2], [3, -3], [4, -4], [5, -5]],
[[7, -7], [8, -8], [9, -9], [10, -10], [11, -11],
[12, -12]]]);
- #macro([#dup[y, [x, ...]], [[y, x], ...]]);
+ #macro[[#dup[y, [x, ...]], [[y, x], ...]]];
assert (#dup[1, [1, 2, 3, 4]] == [[1, 1], [1, 2], [1, 3], [1, 4]]);
- #macro([#lambda[x, #<t>, body, #<s>],
+ #macro[[#lambda[x, #<t>, body, #<s>],
{
fn result(x: t) -> s { ret body }
result
- }]);
+ }]];
- assert ((#lambda[i, #<uint>, i + 4u, #<uint>])(12u) == 16u);
+ assert (#lambda[i, #<uint>, i + 4u, #<uint>](12u) == 16u);
- #macro[[#sum[x, xs, ...], x + #sum[xs, ...]],
- [#sum[], 0]];
+ #macro[[#sum[x, xs, ...], x + #sum[xs, ...]], [#sum[], 0]];
- assert (#sum[1,2,3,4] == 10);
+ assert (#sum[1, 2, 3, 4] == 10);
#macro[[#transcr_mixed[a, as, ...], #sum[6, as, ...] * a]];
assert (#transcr_mixed[10, 5, 4, 3, 2, 1] == 210);
- #macro[[#surround[pre, [xs, ...], post],
- [pre, xs, ..., post]]];
+ #macro[[#surround[pre, [xs, ...], post], [pre, xs, ..., post]]];
- assert (#surround[1, [2,3,4], 5] == [1,2,3,4,5]);
+ assert (#surround[1, [2, 3, 4], 5] == [1, 2, 3, 4, 5]);
-}
\ No newline at end of file
+}
-fn main() {
- #macro[[#m1[a], a*4]];
- assert (#m1[2] == 8);
-}
+fn main() { #macro[[#m1[a], a * 4]]; assert (#m1[2] == 8); }
-fn main(args: [str]) {
- for s in args { log s }
-}
\ No newline at end of file
+fn main(args: [str]) { for s in args { log s } }
import std::comm;
fn sub(parent: comm::_chan<int>, id: int) {
- if (id == 0) {
- comm::send(parent, 0);
- } else {
- let p = comm::mk_port();
- let child = task::_spawn(bind sub(p.mk_chan(), id-1));
- let y = p.recv();
- comm::send(parent, y + 1);
- }
+ if id == 0 {
+ comm::send(parent, 0);
+ } else {
+ let p = comm::mk_port();
+ let child = task::_spawn(bind sub(p.mk_chan(), id - 1));
+ let y = p.recv();
+ comm::send(parent, y + 1);
+ }
}
fn main() {
- let p = comm::mk_port();
- let child = task::_spawn(bind sub(p.mk_chan(), 200));
- let y = p.recv();
- log "transmission complete";
- log y;
- assert (y == 200);
+ let p = comm::mk_port();
+ let child = task::_spawn(bind sub(p.mk_chan(), 200));
+ let y = p.recv();
+ log "transmission complete";
+ log y;
+ assert (y == 200);
}
}
fn main() {
- let v0 = ~[1, 2, 3, 4, 5];
+ let v0 = [1, 2, 3, 4, 5];
log len(v0);
- let v1 = ~[mutable 1, 2, 3, 4, 5];
+ let v1 = [mutable 1, 2, 3, 4, 5];
log len(v1);
}
// -*- rust -*-
tag mlist { cons(int, @mlist); nil; }
-fn main() { cons(10, @cons(11, @cons(12, @nil))); }
\ No newline at end of file
+fn main() { cons(10, @cons(11, @cons(12, @nil))); }
assert (test(true, x) == 2);
assert (test(true, x) == 2);
assert (test(false, x) == 5);
-}
\ No newline at end of file
+}
-fn main() { let x = @{x: 1, y: 2, z: 3}; let y <- x; assert (y.y == 2); }
\ No newline at end of file
+fn main() { let x = @{x: 1, y: 2, z: 3}; let y <- x; assert (y.y == 2); }
ret quux;
}
-fn main() { let x = @{a: 1, b: 2, c: 3}; let y = test(x); assert (y.c == 3); }
\ No newline at end of file
+fn main() { let x = @{a: 1, b: 2, c: 3}; let y = test(x); assert (y.c == 3); }
-fn test(foo: -@[int]) {
- assert (foo.(0) == 10);
-}
+fn test(foo: -@[int]) { assert (foo[0] == 10); }
fn main() {
- let x = @~[10];
+ let x = @[10];
// Test forgetting a local by move-in
test(x);
// Test forgetting a temporary by move-in.
- test(@~[10]);
+ test(@[10]);
}
-fn test(foo: -int) {
- assert (foo == 10);
-}
+fn test(foo: -int) { assert (foo == 10); }
-fn main() {
- let x = 10;
- test(x);
-}
\ No newline at end of file
+fn main() { let x = 10; test(x); }
let x: int;
x <- y;
assert (x == 42);
-}
\ No newline at end of file
+}
-fn main() {
- let x = 10, y = x;
- assert (y == 10);
-}
\ No newline at end of file
+fn main() { let x = 10, y = x; assert (y == 10); }
-fn other() { log "yes"; }
\ No newline at end of file
+fn other() { log "yes"; }
-fn main() { log "hello, multi-file world."; bar::other(); }
\ No newline at end of file
+fn main() { log "hello, multi-file world."; bar::other(); }
/*
* This is a /* depth-balanced */ multi-line comment.
*/
-fn main() { }
\ No newline at end of file
+fn main() { }
// -*- rust -*-
use std;
-fn grow(v: &mutable [int]) { v += ~[1]; }
+fn grow(v: &mutable [int]) { v += [1]; }
fn main() {
- let v: [int] = ~[];
+ let v: [int] = [];
grow(v);
grow(v);
grow(v);
fn main() {
// This just tests whether the vec leaks its members.
let pvec: [mutable @{a: int, b: int}] =
- ~[mutable @{a: 1, b: 2}, @{a: 3, b: 4}, @{a: 5, b: 6}];
+ [mutable @{a: 1, b: 2}, @{a: 3, b: 4}, @{a: 5, b: 6}];
}
tag small_list { kons(int, @small_list); neel; }
-fn main() { }
\ No newline at end of file
+fn main() { }
libc.write(1, buf, 1024);
libc.close(fd);
libc.free(buf);
-}
\ No newline at end of file
+}
type file_handle;
}
-fn main() { assert (true); }
\ No newline at end of file
+fn main() { assert (true); }
libc.puts(rustrt.str_buf("hello, native world 1"));
libc.puts(rustrt.str_buf("hello, native world 2"));
libc.puts(rustrt.str_buf("hello, native world 3"));
-}
\ No newline at end of file
+}
assert (s2 == "foo.m1");
let s3: str = a.m3();
assert (s3 == "bar.m1");
-}
\ No newline at end of file
+}
fn myvec_deref<X>(mv: &myvec<X>) -> [X] { ret *mv; }
-fn myvec_elt<X>(mv: &myvec<X>) -> X { ret mv.(0); }
+fn myvec_elt<X>(mv: &myvec<X>) -> X { ret mv[0]; }
fn main() {
- let mv = myvec(~[1, 2, 3]);
- assert (myvec_deref(mv).(1) == 2);
+ let mv = myvec([1, 2, 3]);
+ assert (myvec_deref(mv)[1] == 2);
assert (myvec_elt(mv) == 1);
- assert (mv.(2) == 3);
+ assert (mv[2] == 3);
}
-tag mytype = {compute: fn(&mytype) -> int , val: int};
+tag mytype = {compute: fn(&mytype) -> int, val: int};
fn compute(i: &mytype) -> int { ret i.val + 20; }
fn main() {
let myval = mytype({compute: compute, val: 30});
assert (myval.compute(myval) == 50);
-}
\ No newline at end of file
+}
-fn main() { let x = (); alt x { () { } } }
\ No newline at end of file
+fn main() { let x = (); alt x { () { } } }
// Ref.Item.Obj
obj counter(state: @mutable int) {
- fn incr() {
- *state += 1;
- }
- fn get() -> int {
- ret *state;
- }
- }
+ fn incr() { *state += 1; }
+ fn get() -> int { ret *state; }
+ }
let c: counter = counter(@mutable 1);
c.incr();
c.incr();
- assert c.get() == 3;
+ assert (c.get() == 3);
obj my_obj() {
- fn get() -> int {
- ret 3;
- }
- fn foo() -> int{
+ fn get() -> int { ret 3; }
+ fn foo() -> int {
let c = self.get();
ret c + 2; // returns 5
}
}
let o = my_obj();
- assert o.foo() == 5;
+ assert (o.foo() == 5);
// Ref.Type.Obj
- type taker = obj {
- fn take(int);
- };
+ type taker =
+ obj {
+ fn take(int);
+ };
obj adder(x: @mutable int) {
- fn take(y: int) {
- *x += y;
- }
+ fn take(y: int) { *x += y; }
}
obj sender(c: _chan<int>) {
- fn take(z: int) {
- send(c, z);
- }
+ fn take(z: int) { send(c, z); }
}
- fn give_ints(t: taker) {
- t.take(1);
- t.take(2);
- t.take(3);
- }
+ fn give_ints(t: taker) { t.take(1); t.take(2); t.take(3); }
let p = mk_port::<int>();
// This just tests whether the obj leaks its box state members.
let ob = handle(@0xf00f00);
-}
\ No newline at end of file
+}
type adder =
obj {
- fn add() ;
+ fn add();
};
obj leaf_adder(x: int) {
fn main() {
let x = delegate_adder(delegate_adder(delegate_adder(leaf_adder(10))));
x.add();
-}
\ No newline at end of file
+}
let i: int = 0;
a.m1(i);
a.m2(i);
-}
\ No newline at end of file
+}
assert (i == 2);
i = a.m3(i);
assert (i == 4);
-}
\ No newline at end of file
+}
assert (rs == 8);
rs = o.get();
assert (rs == 8);
-}
\ No newline at end of file
+}
let a = foo();
a.m1();
a.m2();
-}
\ No newline at end of file
+}
fn main() {
obj buf(data: [u8]) {
- fn get(i: int) -> u8 { ret data.(i); }
+ fn get(i: int) -> u8 { ret data[i]; }
}
- let b = buf(~[1 as u8, 2 as u8, 3 as u8]);
+ let b = buf([1 as u8, 2 as u8, 3 as u8]);
log b.get(1);
assert (b.get(1) == 2 as u8);
}
x /= 5;
log x;
assert (x == 5);
-}
\ No newline at end of file
+}
// Testcase for issue #130, operator associativity.
-fn main() { assert (3 * 5 / 2 == 7); }
\ No newline at end of file
+fn main() { assert (3 * 5 / 2 == 7); }
assert (or_alt(c) == 0);
assert (or_alt(a(10, 100, 0u)) == 110);
assert (or_alt(b(20, 200)) == 220);
-}
\ No newline at end of file
+}
ext_ext_mem = ret_ext_ext_mem(); // non-initializing
-}
\ No newline at end of file
+}
// Regression test for issue #152.
-fn main() { let b: uint = 1u; while b <= 32u { 0u << b; b <<= 1u; log b; } }
\ No newline at end of file
+fn main() { let b: uint = 1u; while b <= 32u { 0u << b; b <<= 1u; log b; } }
let x = true;
if x { let i = 10; while i > 0 { i -= 1; } }
alt x { true { log "right"; } false { log "wrong"; } }
-}
\ No newline at end of file
+}
// -*- rust -*-
fn dont_call_me() { fail; log 1; }
-fn main() { }
\ No newline at end of file
+fn main() { }
iter iter2<@T>() -> T { }
-fn main() {
- for each i: int in iter2() { }
-}
+fn main() { for each i: int in iter2() { } }
// -*- rust -*-
pred f(q: int) -> bool { ret true; }
-fn main() { let x = 0; check (f(x)); }
\ No newline at end of file
+fn main() { let x = 0; check (f(x)); }
check (lt(a, c));
f(a, b);
f(a, c);
-}
\ No newline at end of file
+}
fn f(p: &point) { assert (p.z == 12); }
-fn main() { let x: point = {x: 10, y: 11, z: 12}; f(x); }
\ No newline at end of file
+fn main() { let x: point = {x: 10, y: 11, z: 12}; f(x); }
fn add(i: int, j: int) -> int { ret i + j; }
-fn binder(n: int) -> fn() -> int {
- let f = bind add(n, _);
- ret bind f(2);
-}
+fn binder(n: int) -> fn() -> int { let f = bind add(n, _); ret bind f(2); }
fn main() {
binder(5);
let f = binder(1);
- assert(f() == 3);
- assert(binder(8)() == 10);
+ assert (f() == 3);
+ assert (binder(8)() == 10);
}
// -*- rust -*-
// Issue #50.
-fn main() { let x = {foo: "hello", bar: "world"}; log x.foo; log x.bar; }
\ No newline at end of file
+fn main() { let x = {foo: "hello", bar: "world"}; log x.foo; log x.bar; }
assert (right.y == 0);
assert (up.x == 0);
assert (up.y == 10);
-}
\ No newline at end of file
+}
type rect = (point, point);
-fn fst(r: &rect) -> point {
- let (fst, _) = r;
- ret fst;
-}
-fn snd(r: &rect) -> point {
- let (_, snd) = r;
- ret snd;
-}
+fn fst(r: &rect) -> point { let (fst, _) = r; ret fst; }
+fn snd(r: &rect) -> point { let (_, snd) = r; ret snd; }
fn f(r: rect, x1: int, y1: int, x2: int, y2: int) {
assert (fst(r).x == x1);
assert (x == 10);
f(r, 10, 20, 100, 200);
f(r2, 10, 20, 100, 200);
-}
\ No newline at end of file
+}
fn main() {
assert (m(c({x: a(10), y: 5}, 4u)) == 10);
assert (m(c({x: b(10u), y: 5}, 4u)) == 19);
-}
\ No newline at end of file
+}
let my_total = @mutable 10;
{ let pt <- shrinky_pointer(my_total); assert (look_at(pt) == 10); }
assert (*my_total == 9);
-}
\ No newline at end of file
+}
-resource finish<T>(arg: {val: T, fin: fn(&T) }) { arg.fin(arg.val); }
+resource finish<T>(arg: {val: T, fin: fn(&T)}) { arg.fin(arg.val); }
fn main() {
let box = @mutable 10;
type closable = @mutable bool;
-resource close_res(i: closable) {
- *i = false;
-}
+resource close_res(i: closable) { *i = false; }
tag option<T> { none; some(T); }
-fn sink(res: option<close_res>) {}
+fn sink(res: option<close_res>) { }
fn main() {
let c = @mutable true;
sink(none);
sink(some(close_res(c)));
- assert !*c;
+ assert (!*c);
}
if i == 3u { my_err("I don't like three"); } else { ret 42; }
}
-fn main() { okay(4u); }
\ No newline at end of file
+fn main() { okay(4u); }
fn f() { let x: () = (); ret x; }
-fn main() { let x = f(); }
\ No newline at end of file
+fn main() { let x = f(); }
fn test_grow() {
let myport: comm::_port<record> = comm::mk_port();
let mychan = myport.mk_chan();
- for each i: uint in uint::range(0u, 100u) {
+ for each i: uint in uint::range(0u, 100u) {
let val: record = {val1: 0u32, val2: 0u32, val3: 0u32};
comm::send(mychan, val);
}
fn test_shrink2() {
let myport = mk_port::<record>();
let mychan = myport.mk_chan();
- for each i: uint in uint::range(0u, 100u) {
+ for each i: uint in uint::range(0u, 100u) {
let val: record = {val1: 0u32, val2: 0u32, val3: 0u32};
send(mychan, val);
}
- for each i: uint in uint::range(0u, 100u) { let x = myport.recv(); }
+ for each i: uint in uint::range(0u, 100u) { let x = myport.recv(); }
}
fn test_rotate() {
let myport = mk_port::<record>();
let mychan = myport.mk_chan();
- for each i: uint in uint::range(0u, 100u) {
+ for each i: uint in uint::range(0u, 100u) {
let val = {val1: i as u32, val2: i as u32, val3: i as u32};
send(mychan, val);
let x = myport.recv();
fn test_rotate_grow() {
let myport = mk_port::<record>();
let mychan = myport.mk_chan();
- for each j: uint in uint::range(0u, 10u) {
- for each i: uint in uint::range(0u, 10u) {
+ for each j: uint in uint::range(0u, 10u) {
+ for each i: uint in uint::range(0u, 10u) {
let val: record =
{val1: i as u32, val2: i as u32, val3: i as u32};
send(mychan, val);
}
- for each i: uint in uint::range(0u, 10u) {
+ for each i: uint in uint::range(0u, 10u) {
let x = myport.recv();
assert (x.val1 == i as u32);
assert (x.val2 == i as u32);
fn bar() { assert (a::foo() == 1); }
}
-fn main() { c::bar(); }
\ No newline at end of file
+fn main() { c::bar(); }
assert ("hello" < "hellr");
assert ("hello " > "hello");
assert ("hello" != "there");
- assert (~[1, 2, 3, 4] > ~[1, 2, 3]);
- assert (~[1, 2, 3] < ~[1, 2, 3, 4]);
- assert (~[1, 2, 4, 4] > ~[1, 2, 3, 4]);
- assert (~[1, 2, 3, 4] < ~[1, 2, 4, 4]);
- assert (~[1, 2, 3] <= ~[1, 2, 3]);
- assert (~[1, 2, 3] <= ~[1, 2, 3, 3]);
- assert (~[1, 2, 3, 4] > ~[1, 2, 3]);
- assert (~[1, 2, 3] == ~[1, 2, 3]);
- assert (~[1, 2, 3] != ~[1, 1, 3]);
-}
\ No newline at end of file
+ assert ([1, 2, 3, 4] > [1, 2, 3]);
+ assert ([1, 2, 3] < [1, 2, 3, 4]);
+ assert ([1, 2, 4, 4] > [1, 2, 3, 4]);
+ assert ([1, 2, 3, 4] < [1, 2, 4, 4]);
+ assert ([1, 2, 3] <= [1, 2, 3]);
+ assert ([1, 2, 3] <= [1, 2, 3, 3]);
+ assert ([1, 2, 3, 4] > [1, 2, 3]);
+ assert ([1, 2, 3] == [1, 2, 3]);
+ assert ([1, 2, 3] != [1, 1, 3]);
+}
// -*- rust -*-
fn foo(c: [int]) {
let a: int = 5;
- let b: [int] = ~[];
+ let b: [int] = [];
alt none::<int> {
- some::<int>(_) { for i: int in c { log a; let a = 17; b += ~[a]; } }
- _ {}
+ some::<int>(_) { for i: int in c { log a; let a = 17; b += [a]; } }
+ _ { }
}
}
tag t<T> { none; some(T); }
-fn main() {
- let x = 10;
- let x = x + 20;
- assert x == 30;
- foo(~[]);
-}
+fn main() { let x = 10; let x = x + 20; assert (x == 30); foo([]); }
tag opt<T> { none; }
fn main() {
- let x = none::<int>; alt x { none::<int>. { log "hello world"; } }
+ let x = none::<int>;
+ alt x { none::<int>. { log "hello world"; } }
}
assert (another_anon_obj.baz() == 4);
-}
\ No newline at end of file
+}
-fn main() { let n; n = 1; log n; }
\ No newline at end of file
+fn main() { let n; n = 1; log n; }
fn hello() { log "hello, object world"; }
}
-fn main() { let mx = x(); mx.hello(); }
\ No newline at end of file
+fn main() { let mx = x(); mx.hello(); }
tag clam<T> { a(T, int); b; }
fn uhoh<T>(v: &[clam<T>]) {
- alt v.(1) {
+ alt v[1] {
a::<T>(t, u) { log "incorrect"; log u; fail; }
b::<T>. { log "correct"; }
}
}
fn main() {
- let v: [clam<int>] = ~[b::<int>, b::<int>, a::<int>(42, 17)];
+ let v: [clam<int>] = [b::<int>, b::<int>, a::<int>(42, 17)];
uhoh::<int>(v);
}
task::_spawn(bind x("hello from third spawned fn", 67));
let i: int = 30;
while i > 0 { i = i - 1; log "parent sleeping"; yield(); }
-}
\ No newline at end of file
+}
import std::task::join_id;
import std::task::_spawn;
-fn main() {
- let x = _spawn(bind m::child(10));
- join_id(x);
-}
+fn main() { let x = _spawn(bind m::child(10)); join_id(x); }
mod m {
- fn child(i: int) {
- log i;
- }
+ fn child(i: int) { log i; }
}
import std::task;
-fn main() {
- let t = task::_spawn(bind child(10));
- task::join_id(t);
-}
+fn main() { let t = task::_spawn(bind child(10)); task::join_id(t); }
fn child(i: int) { log_err i; assert (i == 10); }
// Test case for issue #435.
obj foo() {
- fn add5(n: int) -> int {
- ret n + 5;
- }
+ fn add5(n: int) -> int { ret n + 5; }
}
-fn add5(n: int) -> int {
- ret n + 5;
-}
+fn add5(n: int) -> int { ret n + 5; }
fn main() {
let fiveplusseven = bind add5(7);
- assert add5(7) == 12;
- assert fiveplusseven() == 12;
+ assert (add5(7) == 12);
+ assert (fiveplusseven() == 12);
let my_foo = foo();
let fiveplusseven_too = bind my_foo.add5(7);
- assert my_foo.add5(7) == 12;
- assert fiveplusseven_too() == 12;
+ assert (my_foo.add5(7) == 12);
+ assert (fiveplusseven_too() == 12);
}
y.incr();
log y.get();
assert (y.get() == 2);
-}
\ No newline at end of file
+}
let s: str = "hello";
s += "world";
log s;
- assert (s.(9) == 'd' as u8);
+ assert (s[9] == 'd' as u8);
}
fn test2() {
assert (str::eq(b, "ABCabcABC"));
}
-fn main() { test1(); test2(); }
\ No newline at end of file
+fn main() { test1(); test2(); }
let b: str = "world";
let s: str = a + b;
log s;
- assert (s.(9) == 'd' as u8);
-}
\ No newline at end of file
+ assert (s[9] == 'd' as u8);
+}
fn main() {
let s = "a";
s += "b";
- assert (s.(0) == 'a' as u8);
- assert (s.(1) == 'b' as u8);
+ assert (s[0] == 'a' as u8);
+ assert (s[1] == 'b' as u8);
s += "c";
s += "d";
- assert (s.(0) == 'a' as u8);
- assert (s.(1) == 'b' as u8);
- assert (s.(2) == 'c' as u8);
- assert (s.(3) == 'd' as u8);
-}
\ No newline at end of file
+ assert (s[0] == 'a' as u8);
+ assert (s[1] == 'b' as u8);
+ assert (s[2] == 'c' as u8);
+ assert (s[3] == 'd' as u8);
+}
let c: u8 = s[4];
log c;
assert (c == 0x6f as u8);
-}
\ No newline at end of file
+}
test";
assert (str::eq(a, "this is a test"));
assert (str::eq(b, "this is another test"));
-}
\ No newline at end of file
+}
i -= 1;
expected_len *= 2u;
}
-}
\ No newline at end of file
+}
tag taggy { foo(@taggy); bar; }
-fn main() { assert (bar <= bar); }
\ No newline at end of file
+fn main() { assert (bar <= bar); }
assert (x != y);
assert (x == large);
assert (x != small);
-}
\ No newline at end of file
+}
-fn main() { let x = 3; let y = 7; x <-> y; assert (x == 7); assert (y == 3); }
\ No newline at end of file
+fn main() { let x = 3; let y = 7; x <-> y; assert (x == 7); assert (y == 3); }
-fn swap<@T>(v: &[mutable T], i: int, j: int) { v.(i) <-> v.(j); }
+fn swap<@T>(v: &[mutable T], i: int, j: int) { v[i] <-> v[j]; }
fn main() {
- let a: [mutable int] = ~[mutable 0, 1, 2, 3, 4, 5, 6];
+ let a: [mutable int] = [mutable 0, 1, 2, 3, 4, 5, 6];
swap(a, 2, 4);
- assert (a.(2) == 4);
- assert (a.(4) == 2);
+ assert (a[2] == 4);
+ assert (a[4] == 2);
let n = 42;
- n <-> a.(0);
- assert (a.(0) == 42);
+ n <-> a[0];
+ assert (a[0] == 42);
assert (n == 0);
}
}
fn main() {
- test(#fmt("hello %d friends and %s things", 10, "formatted"),
+ test(#fmt["hello %d friends and %s things", 10, "formatted"],
"hello 10 friends and formatted things");
- test(#fmt("test"), "test");
+ test(#fmt["test"], "test");
// a quadratic optimization in LLVM (jump-threading) makes this test a
// bit slow to compile unless we break it up
fn part1() {
// Simple tests for types
- test(#fmt("%d", 1), "1");
- test(#fmt("%i", 2), "2");
- test(#fmt("%i", -1), "-1");
- test(#fmt("%u", 10u), "10");
- test(#fmt("%s", "test"), "test");
- test(#fmt("%b", true), "true");
- test(#fmt("%b", false), "false");
- test(#fmt("%c", 'A'), "A");
- test(#fmt("%x", 0xff_u), "ff");
- test(#fmt("%X", 0x12ab_u), "12AB");
- test(#fmt("%o", 10u), "12");
- test(#fmt("%t", 0b11010101_u), "11010101");
+ test(#fmt["%d", 1], "1");
+ test(#fmt["%i", 2], "2");
+ test(#fmt["%i", -1], "-1");
+ test(#fmt["%u", 10u], "10");
+ test(#fmt["%s", "test"], "test");
+ test(#fmt["%b", true], "true");
+ test(#fmt["%b", false], "false");
+ test(#fmt["%c", 'A'], "A");
+ test(#fmt["%x", 0xff_u], "ff");
+ test(#fmt["%X", 0x12ab_u], "12AB");
+ test(#fmt["%o", 10u], "12");
+ test(#fmt["%t", 0b11010101_u], "11010101");
// 32-bit limits
- test(#fmt("%i", -2147483648), "-2147483648");
- test(#fmt("%i", 2147483647), "2147483647");
- test(#fmt("%u", 4294967295u), "4294967295");
- test(#fmt("%x", 0xffffffff_u), "ffffffff");
- test(#fmt("%o", 0xffffffff_u), "37777777777");
- test(#fmt("%t", 0xffffffff_u), "11111111111111111111111111111111");
+ test(#fmt["%i", -2147483648], "-2147483648");
+ test(#fmt["%i", 2147483647], "2147483647");
+ test(#fmt["%u", 4294967295u], "4294967295");
+ test(#fmt["%x", 0xffffffff_u], "ffffffff");
+ test(#fmt["%o", 0xffffffff_u], "37777777777");
+ test(#fmt["%t", 0xffffffff_u], "11111111111111111111111111111111");
}
fn part2() {
// Widths
- test(#fmt("%1d", 500), "500");
- test(#fmt("%10d", 500), " 500");
- test(#fmt("%10d", -500), " -500");
- test(#fmt("%10u", 500u), " 500");
- test(#fmt("%10s", "test"), " test");
- test(#fmt("%10b", true), " true");
- test(#fmt("%10x", 0xff_u), " ff");
- test(#fmt("%10X", 0xff_u), " FF");
- test(#fmt("%10o", 10u), " 12");
- test(#fmt("%10t", 0xff_u), " 11111111");
- test(#fmt("%10c", 'A'), " A");
+ test(#fmt["%1d", 500], "500");
+ test(#fmt["%10d", 500], " 500");
+ test(#fmt["%10d", -500], " -500");
+ test(#fmt["%10u", 500u], " 500");
+ test(#fmt["%10s", "test"], " test");
+ test(#fmt["%10b", true], " true");
+ test(#fmt["%10x", 0xff_u], " ff");
+ test(#fmt["%10X", 0xff_u], " FF");
+ test(#fmt["%10o", 10u], " 12");
+ test(#fmt["%10t", 0xff_u], " 11111111");
+ test(#fmt["%10c", 'A'], " A");
// Left justify
- test(#fmt("%-10d", 500), "500 ");
- test(#fmt("%-10d", -500), "-500 ");
- test(#fmt("%-10u", 500u), "500 ");
- test(#fmt("%-10s", "test"), "test ");
- test(#fmt("%-10b", true), "true ");
- test(#fmt("%-10x", 0xff_u), "ff ");
- test(#fmt("%-10X", 0xff_u), "FF ");
- test(#fmt("%-10o", 10u), "12 ");
- test(#fmt("%-10t", 0xff_u), "11111111 ");
- test(#fmt("%-10c", 'A'), "A ");
+ test(#fmt["%-10d", 500], "500 ");
+ test(#fmt["%-10d", -500], "-500 ");
+ test(#fmt["%-10u", 500u], "500 ");
+ test(#fmt["%-10s", "test"], "test ");
+ test(#fmt["%-10b", true], "true ");
+ test(#fmt["%-10x", 0xff_u], "ff ");
+ test(#fmt["%-10X", 0xff_u], "FF ");
+ test(#fmt["%-10o", 10u], "12 ");
+ test(#fmt["%-10t", 0xff_u], "11111111 ");
+ test(#fmt["%-10c", 'A'], "A ");
}
fn part3() {
// Precision
- test(#fmt("%.d", 0), "");
- test(#fmt("%.u", 0u), "");
- test(#fmt("%.x", 0u), "");
- test(#fmt("%.t", 0u), "");
- test(#fmt("%.d", 10), "10");
- test(#fmt("%.d", -10), "-10");
- test(#fmt("%.u", 10u), "10");
- test(#fmt("%.s", "test"), "");
- test(#fmt("%.x", 127u), "7f");
- test(#fmt("%.o", 10u), "12");
- test(#fmt("%.t", 3u), "11");
- test(#fmt("%.c", 'A'), "A");
- test(#fmt("%.0d", 0), "");
- test(#fmt("%.0u", 0u), "");
- test(#fmt("%.0x", 0u), "");
- test(#fmt("%.0t", 0u), "");
- test(#fmt("%.0d", 10), "10");
- test(#fmt("%.0d", -10), "-10");
- test(#fmt("%.0u", 10u), "10");
- test(#fmt("%.0s", "test"), "");
- test(#fmt("%.0x", 127u), "7f");
- test(#fmt("%.0o", 10u), "12");
- test(#fmt("%.0t", 3u), "11");
- test(#fmt("%.0c", 'A'), "A");
- test(#fmt("%.1d", 0), "0");
- test(#fmt("%.1u", 0u), "0");
- test(#fmt("%.1x", 0u), "0");
- test(#fmt("%.1t", 0u), "0");
- test(#fmt("%.1d", 10), "10");
- test(#fmt("%.1d", -10), "-10");
- test(#fmt("%.1u", 10u), "10");
- test(#fmt("%.1s", "test"), "t");
- test(#fmt("%.1x", 127u), "7f");
- test(#fmt("%.1o", 10u), "12");
- test(#fmt("%.1t", 3u), "11");
- test(#fmt("%.1c", 'A'), "A");
+ test(#fmt["%.d", 0], "");
+ test(#fmt["%.u", 0u], "");
+ test(#fmt["%.x", 0u], "");
+ test(#fmt["%.t", 0u], "");
+ test(#fmt["%.d", 10], "10");
+ test(#fmt["%.d", -10], "-10");
+ test(#fmt["%.u", 10u], "10");
+ test(#fmt["%.s", "test"], "");
+ test(#fmt["%.x", 127u], "7f");
+ test(#fmt["%.o", 10u], "12");
+ test(#fmt["%.t", 3u], "11");
+ test(#fmt["%.c", 'A'], "A");
+ test(#fmt["%.0d", 0], "");
+ test(#fmt["%.0u", 0u], "");
+ test(#fmt["%.0x", 0u], "");
+ test(#fmt["%.0t", 0u], "");
+ test(#fmt["%.0d", 10], "10");
+ test(#fmt["%.0d", -10], "-10");
+ test(#fmt["%.0u", 10u], "10");
+ test(#fmt["%.0s", "test"], "");
+ test(#fmt["%.0x", 127u], "7f");
+ test(#fmt["%.0o", 10u], "12");
+ test(#fmt["%.0t", 3u], "11");
+ test(#fmt["%.0c", 'A'], "A");
+ test(#fmt["%.1d", 0], "0");
+ test(#fmt["%.1u", 0u], "0");
+ test(#fmt["%.1x", 0u], "0");
+ test(#fmt["%.1t", 0u], "0");
+ test(#fmt["%.1d", 10], "10");
+ test(#fmt["%.1d", -10], "-10");
+ test(#fmt["%.1u", 10u], "10");
+ test(#fmt["%.1s", "test"], "t");
+ test(#fmt["%.1x", 127u], "7f");
+ test(#fmt["%.1o", 10u], "12");
+ test(#fmt["%.1t", 3u], "11");
+ test(#fmt["%.1c", 'A'], "A");
}
fn part4() {
- test(#fmt("%.5d", 0), "00000");
- test(#fmt("%.5u", 0u), "00000");
- test(#fmt("%.5x", 0u), "00000");
- test(#fmt("%.5t", 0u), "00000");
- test(#fmt("%.5d", 10), "00010");
- test(#fmt("%.5d", -10), "-00010");
- test(#fmt("%.5u", 10u), "00010");
- test(#fmt("%.5s", "test"), "test");
- test(#fmt("%.5x", 127u), "0007f");
- test(#fmt("%.5o", 10u), "00012");
- test(#fmt("%.5t", 3u), "00011");
- test(#fmt("%.5c", 'A'), "A");
+ test(#fmt["%.5d", 0], "00000");
+ test(#fmt["%.5u", 0u], "00000");
+ test(#fmt["%.5x", 0u], "00000");
+ test(#fmt["%.5t", 0u], "00000");
+ test(#fmt["%.5d", 10], "00010");
+ test(#fmt["%.5d", -10], "-00010");
+ test(#fmt["%.5u", 10u], "00010");
+ test(#fmt["%.5s", "test"], "test");
+ test(#fmt["%.5x", 127u], "0007f");
+ test(#fmt["%.5o", 10u], "00012");
+ test(#fmt["%.5t", 3u], "00011");
+ test(#fmt["%.5c", 'A'], "A");
// Bool precision. I'm not sure if it's good or bad to have bool
// conversions support precision - it's not standard printf so we
// can do whatever. For now I'm making it behave the same as string
// conversions.
- test(#fmt("%.b", true), "");
- test(#fmt("%.0b", true), "");
- test(#fmt("%.1b", true), "t");
+ test(#fmt["%.b", true], "");
+ test(#fmt["%.0b", true], "");
+ test(#fmt["%.1b", true], "t");
}
fn part5() {
// Explicit + sign. Only for signed conversions
- test(#fmt("%+d", 0), "+0");
- test(#fmt("%+d", 1), "+1");
- test(#fmt("%+d", -1), "-1");
+ test(#fmt["%+d", 0], "+0");
+ test(#fmt["%+d", 1], "+1");
+ test(#fmt["%+d", -1], "-1");
// Leave space for sign
- test(#fmt("% d", 0), " 0");
- test(#fmt("% d", 1), " 1");
- test(#fmt("% d", -1), "-1");
+ test(#fmt["% d", 0], " 0");
+ test(#fmt["% d", 1], " 1");
+ test(#fmt["% d", -1], "-1");
// Plus overrides space
- test(#fmt("% +d", 0), "+0");
- test(#fmt("%+ d", 0), "+0");
+ test(#fmt["% +d", 0], "+0");
+ test(#fmt["%+ d", 0], "+0");
// 0-padding
- test(#fmt("%05d", 0), "00000");
- test(#fmt("%05d", 1), "00001");
- test(#fmt("%05d", -1), "-0001");
- test(#fmt("%05u", 1u), "00001");
- test(#fmt("%05x", 127u), "0007f");
- test(#fmt("%05X", 127u), "0007F");
- test(#fmt("%05o", 10u), "00012");
- test(#fmt("%05t", 3u), "00011");
+ test(#fmt["%05d", 0], "00000");
+ test(#fmt["%05d", 1], "00001");
+ test(#fmt["%05d", -1], "-0001");
+ test(#fmt["%05u", 1u], "00001");
+ test(#fmt["%05x", 127u], "0007f");
+ test(#fmt["%05X", 127u], "0007F");
+ test(#fmt["%05o", 10u], "00012");
+ test(#fmt["%05t", 3u], "00011");
// 0-padding a string is undefined but glibc does this:
- test(#fmt("%05s", "test"), " test");
- test(#fmt("%05c", 'A'), " A");
- test(#fmt("%05b", true), " true");
+ test(#fmt["%05s", "test"], " test");
+ test(#fmt["%05c", 'A'], " A");
+ test(#fmt["%05b", true], " true");
// Left-justify overrides 0-padding
- test(#fmt("%-05d", 0), "0 ");
- test(#fmt("%-05d", 1), "1 ");
- test(#fmt("%-05d", -1), "-1 ");
- test(#fmt("%-05u", 1u), "1 ");
- test(#fmt("%-05x", 127u), "7f ");
- test(#fmt("%-05X", 127u), "7F ");
- test(#fmt("%-05o", 10u), "12 ");
- test(#fmt("%-05t", 3u), "11 ");
- test(#fmt("%-05s", "test"), "test ");
- test(#fmt("%-05c", 'A'), "A ");
- test(#fmt("%-05b", true), "true ");
+ test(#fmt["%-05d", 0], "0 ");
+ test(#fmt["%-05d", 1], "1 ");
+ test(#fmt["%-05d", -1], "-1 ");
+ test(#fmt["%-05u", 1u], "1 ");
+ test(#fmt["%-05x", 127u], "7f ");
+ test(#fmt["%-05X", 127u], "7F ");
+ test(#fmt["%-05o", 10u], "12 ");
+ test(#fmt["%-05t", 3u], "11 ");
+ test(#fmt["%-05s", "test"], "test ");
+ test(#fmt["%-05c", 'A'], "A ");
+ test(#fmt["%-05b", true], "true ");
}
fn part6() {
// Precision overrides 0-padding
- test(#fmt("%06.5d", 0), " 00000");
- test(#fmt("%06.5u", 0u), " 00000");
- test(#fmt("%06.5x", 0u), " 00000");
- test(#fmt("%06.5d", 10), " 00010");
- test(#fmt("%06.5d", -10), "-00010");
- test(#fmt("%06.5u", 10u), " 00010");
- test(#fmt("%06.5s", "test"), " test");
- test(#fmt("%06.5c", 'A'), " A");
- test(#fmt("%06.5x", 127u), " 0007f");
- test(#fmt("%06.5X", 127u), " 0007F");
- test(#fmt("%06.5o", 10u), " 00012");
+ test(#fmt["%06.5d", 0], " 00000");
+ test(#fmt["%06.5u", 0u], " 00000");
+ test(#fmt["%06.5x", 0u], " 00000");
+ test(#fmt["%06.5d", 10], " 00010");
+ test(#fmt["%06.5d", -10], "-00010");
+ test(#fmt["%06.5u", 10u], " 00010");
+ test(#fmt["%06.5s", "test"], " test");
+ test(#fmt["%06.5c", 'A'], " A");
+ test(#fmt["%06.5x", 127u], " 0007f");
+ test(#fmt["%06.5X", 127u], " 0007F");
+ test(#fmt["%06.5o", 10u], " 00012");
// Signed combinations
- test(#fmt("% 5d", 1), " 1");
- test(#fmt("% 5d", -1), " -1");
- test(#fmt("%+5d", 1), " +1");
- test(#fmt("%+5d", -1), " -1");
- test(#fmt("% 05d", 1), " 0001");
- test(#fmt("% 05d", -1), "-0001");
- test(#fmt("%+05d", 1), "+0001");
- test(#fmt("%+05d", -1), "-0001");
- test(#fmt("%- 5d", 1), " 1 ");
- test(#fmt("%- 5d", -1), "-1 ");
- test(#fmt("%-+5d", 1), "+1 ");
- test(#fmt("%-+5d", -1), "-1 ");
- test(#fmt("%- 05d", 1), " 1 ");
- test(#fmt("%- 05d", -1), "-1 ");
- test(#fmt("%-+05d", 1), "+1 ");
- test(#fmt("%-+05d", -1), "-1 ");
-}
\ No newline at end of file
+ test(#fmt["% 5d", 1], " 1");
+ test(#fmt["% 5d", -1], " -1");
+ test(#fmt["%+5d", 1], " +1");
+ test(#fmt["%+5d", -1], " -1");
+ test(#fmt["% 05d", 1], " 0001");
+ test(#fmt["% 05d", -1], "-0001");
+ test(#fmt["%+05d", 1], "+0001");
+ test(#fmt["%+05d", -1], "-0001");
+ test(#fmt["%- 5d", 1], " 1 ");
+ test(#fmt["%- 5d", -1], "-1 ");
+ test(#fmt["%-+5d", 1], "+1 ");
+ test(#fmt["%-+5d", -1], "-1 ");
+ test(#fmt["%- 05d", 1], " 1 ");
+ test(#fmt["%- 05d", -1], "-1 ");
+ test(#fmt["%-+05d", 1], "+1 ");
+ test(#fmt["%-+05d", -1], "-1 ");
+}
fn main() {
let asdf_fdsa = "<.<";
- assert(#concat_idents[asd,f_f,dsa] == "<.<");
+ assert (#concat_idents[asd, f_f, dsa] == "<.<");
- assert(#ident_to_str[use_mention_distinction]
- == "use_mention_distinction");
+ assert (#ident_to_str[use_mention_distinction] ==
+ "use_mention_distinction");
}
}
-fn main() { f(); }
\ No newline at end of file
+fn main() { f(); }
// use of tail calls causes arg slot leaks, issue #160.
fn inner(dummy: str, b: bool) { if b { be inner(dummy, false); } }
-fn main() { inner("hi", true); }
\ No newline at end of file
+fn main() { inner("hi", true); }
fn main() { let k = checktrue; evenk(42, k); oddk(45, k); }
-fn evenk(n: int, k: fn(bool) -> bool ) -> bool {
+fn evenk(n: int, k: fn(bool) -> bool) -> bool {
log "evenk";
log n;
if n == 0 { be k(true); } else { be oddk(n - 1, k); }
}
-fn oddk(n: int, k: fn(bool) -> bool ) -> bool {
+fn oddk(n: int, k: fn(bool) -> bool) -> bool {
log "oddk";
log n;
if n == 0 { be k(false); } else { be evenk(n - 1, k); }
-}
\ No newline at end of file
+}
fn even(n: int) -> bool { if n == 0 { ret true; } else { be odd(n - 1); } }
-fn odd(n: int) -> bool { if n == 0 { ret false; } else { be even(n - 1); } }
\ No newline at end of file
+fn odd(n: int) -> bool { if n == 0 { ret false; } else { be even(n - 1); } }
import std::task;
fn start(c: comm::_chan<comm::_chan<int>>) {
- let p : comm::_port<int> = comm::mk_port();
+ let p: comm::_port<int> = comm::mk_port();
comm::send(c, p.mk_chan());
}
fn main() {
log "Check that we don't deadlock.";
- let p : comm::_port<int> = comm::mk_port();
+ let p: comm::_port<int> = comm::mk_port();
let a = task::_spawn(bind start(p.mk_chan(), 0, 10));
task::join_id(a);
log "Joined task";
import std::comm;
import std::task;
-fn start(c : comm::chan<int>, n: int) {
+fn start(c: comm::chan<int>, n: int) {
let i: int = n;
while i > 0 { comm::send(c, 0); i = i - 1; }
fn test_vec() {
let po = comm::mk_port();
let ch = po.mk_chan();
- let v0: [int] = ~[0, 1, 2];
+ let v0: [int] = [0, 1, 2];
send(ch, v0);
let v1: [int];
v1 = po.recv();
- assert (v1.(0) == 0);
- assert (v1.(1) == 1);
- assert (v1.(2) == 2);
+ assert (v1[0] == 0);
+ assert (v1[1] == 1);
+ assert (v1[2] == 2);
}
fn test_str() {
// FIXME: re-enable this once strings are unique and sendable
-/*
- let po = comm::mk_port();
- let ch = po.mk_chan();
- let s0: str = "test";
- send(ch, s0);
- let s1: str;
- s1 = po.recv();
- assert (s1.(0) as u8 == 't' as u8);
- assert (s1.(1) as u8 == 'e' as u8);
- assert (s1.(2) as u8 == 's' as u8);
- assert (s1.(3) as u8 == 't' as u8);
-*/
+ /*
+ let po = comm::mk_port();
+ let ch = po.mk_chan();
+ let s0: str = "test";
+ send(ch, s0);
+ let s1: str;
+ s1 = po.recv();
+ assert (s1.(0) as u8 == 't' as u8);
+ assert (s1.(1) as u8 == 'e' as u8);
+ assert (s1.(2) as u8 == 's' as u8);
+ assert (s1.(3) as u8 == 't' as u8);
+ */
}
fn test_tag() {
assert (i == 10);
}
-fn main() {
- test_rec();
- test_vec();
- test_str();
- test_tag();
- test_chan();
-}
+fn main() { test_rec(); test_vec(); test_str(); test_tag(); test_chan(); }
let i: int = 0;
while i < count {
log "Sending Message";
- send(ch, message+0);
+ send(ch, message + 0);
i = i + 1;
}
log "Ending test00_start";
// Create and spawn tasks...
let tasks = [];
while i < number_of_tasks {
- tasks +=
- [task::_spawn(bind test00_start(ch, i, number_of_messages))];
+ tasks += [task::_spawn(bind test00_start(ch, i, number_of_messages))];
i = i + 1;
}
sum += r;
log r;
assert (sum == 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8);
-}
\ No newline at end of file
+}
let c = p.mk_chan();
let number_of_messages: int = 1000;
let i: int = 0;
- while i < number_of_messages { comm::send(c, i+0); i += 1; }
+ while i < number_of_messages { comm::send(c, i + 0); i += 1; }
i = 0;
while i < number_of_messages { r = p.recv(); sum += r; i += 1; }
assert (sum == number_of_messages * (number_of_messages - 1) / 2);
-}
\ No newline at end of file
+}
let number_of_messages: int = 1000;
let i: int = 0;
while i < number_of_messages {
- send(c0, i+0);
- send(c1, i+0);
- send(c2, i+0);
- send(c3, i+0);
+ send(c0, i + 0);
+ send(c1, i + 0);
+ send(c2, i + 0);
+ send(c3, i + 0);
i += 1;
}
i = 0;
// assert (sum == 4 * ((number_of_messages *
// (number_of_messages - 1)) / 2));
-}
\ No newline at end of file
+}
fn main() { test00(); }
-fn test00_start(c : comm::_chan<int>, start: int, number_of_messages: int) {
+fn test00_start(c: comm::_chan<int>, start: int, number_of_messages: int) {
let i: int = 0;
while i < number_of_messages { comm::send(c, start + i); i += 1; }
}
fn test00_start(c: comm::_chan<int>, number_of_messages: int) {
let i: int = 0;
- while i < number_of_messages { comm::send(c, i+0); i += 1; }
+ while i < number_of_messages { comm::send(c, i + 0); i += 1; }
}
fn test00() {
let p = comm::mk_port();
let number_of_messages: int = 10;
- let t0 = task::_spawn(bind test00_start(p.mk_chan(),
- number_of_messages));
+ let t0 = task::_spawn(bind test00_start(p.mk_chan(), number_of_messages));
let i: int = 0;
while i < number_of_messages { r = p.recv(); sum += r; log r; i += 1; }
fn test00_start(ch: _chan<int>, message: int, count: int) {
log "Starting test00_start";
let i: int = 0;
- while i < count { log "Sending Message"; send(ch, message+0); i = i + 1; }
+ while i < count {
+ log "Sending Message";
+ send(ch, message + 0);
+ i = i + 1;
+ }
log "Ending test00_start";
}
i = i + 1;
tasks += [task::spawn(bind test00_start(ch, i, number_of_messages))];
}
-
let sum: int = 0;
for t: task_id in tasks {
i = 0;
- while i < number_of_messages {
- sum += po.recv();
- i = i + 1;
- }
+ while i < number_of_messages { sum += po.recv(); i = i + 1; }
}
for t: task_id in tasks { task::join_id(t); }
log "Completed: Final number is: ";
assert (sum ==
- number_of_messages *
- (number_of_tasks * number_of_tasks + number_of_tasks) / 2);
+ number_of_messages *
+ (number_of_tasks * number_of_tasks + number_of_tasks) /
+ 2);
}
fn test01() {
fn test04() {
log "Spawning lots of tasks.";
let i: int = 4;
- while i > 0 {
- i = i - 1;
- let f = test04_start;
- task::spawn(f);
- }
+ while i > 0 { i = i - 1; let f = test04_start; task::spawn(f); }
log "Finishing up.";
}
let tasks = [];
while i < number_of_tasks {
- i = i + 1; tasks += [task::spawn(bind test06_start(i))]; }
+ i = i + 1;
+ tasks += [task::spawn(bind test06_start(i))];
+ }
for t: task_id in tasks { task::join_id(t); }
import std::task;
-fn main() { task::pin(); task::unpin(); }
\ No newline at end of file
+fn main() { task::pin(); task::unpin(); }
test_associativity();
test_lval();
test_as_stmt();
-}
\ No newline at end of file
+}
// Building as a test runner means that a synthetic main will be run,
// not ours
-fn main() { fail; }
\ No newline at end of file
+fn main() { fail; }
import std::task;
fn main() {
- let i = 10;
- while (i > 0) {
- task::_spawn(bind child(i));
- i = i - 1;
- }
- log "main thread exiting";
+ let i = 10;
+ while i > 0 { task::_spawn(bind child(i)); i = i - 1; }
+ log "main thread exiting";
}
-fn child(x : int) {
- log x;
-}
+fn child(x: int) { log x; }
let p2: point = p;
f(p, 10, 20);
f(p2, 10, 20);
-}
\ No newline at end of file
+}
}
}
-fn main() { }
\ No newline at end of file
+fn main() { }
fn a(a: a) -> int { ret a.a; }
-fn main() { let x: a = {a: 1}; assert (a(x) == 1); }
\ No newline at end of file
+fn main() { let x: a = {a: 1}; assert (a(x) == 1); }
-fn p_foo<T>(pinned: &T) { }
-fn s_foo<@T>(shared: &T) { }
-fn u_foo<~T>(unique: &T) { }
+fn p_foo<T>(pinned: &T) { }
+fn s_foo<@T>(shared: &T) { }
+fn u_foo<~T>(unique: &T) { }
resource r(i: int) { }
-type lteq<T> = fn(&T) -> bool ;
+type lteq<T> = fn(&T) -> bool;
fn main(args: [str]) { }
while lo_ < hi { put lo_; lo_ += 1u; }
}
-fn create_index<T>(index: &[{a: T, b: uint}], hash_fn: fn(&T) -> uint ) {
- for each i: uint in range(0u, 256u) { let bucket: [T] = ~[]; }
+fn create_index<T>(index: &[{a: T, b: uint}], hash_fn: fn(&T) -> uint) {
+ for each i: uint in range(0u, 256u) { let bucket: [T] = []; }
}
fn main() { }
let x = 10;
let y = 11;
if true { while false { y = x; } } else { }
-}
\ No newline at end of file
+}
-fn main() {
- let x = 10, y = 20;
- let z = x + y;
- assert (z == 30);
-}
+fn main() { let x = 10, y = 20; let z = x + y; assert (z == 30); }
fn g(i: int) : p(i) -> int { f(i) }
-fn main() { }
\ No newline at end of file
+fn main() { }
let word: u32 = 200000u32;
word = word - 1u32;
assert (word == 199999u32);
-}
\ No newline at end of file
+}
y = y - 9u8; // 0x9
assert (x == y);
-}
\ No newline at end of file
+}
// x = 14u8;
// x = x + 1u8;
-}
\ No newline at end of file
+}
// -*- rust -*-
-fn main() { let x: uint = 10 as uint; }
\ No newline at end of file
+fn main() { let x: uint = 10 as uint; }
fn null<T>() -> *T { unsafe::reinterpret_cast(0) }
-fn main() {
- null::<int>();
-}
+fn main() { null::<int>(); }
// -*- rust -*-
fn f(u: ()) { ret u; }
-fn main() { let u1: () = (); let u2: () = f(u1); u2 = (); ret (); }
\ No newline at end of file
+fn main() { let u1: () = (); let u2: () = f(u1); u2 = (); ret (); }
fn y() -> int { ret 1; }
}
-fn main() { foo::x(); bar::y(); }
\ No newline at end of file
+fn main() { foo::x(); bar::y(); }
for ab: u8 in a {
log i;
log ab;
- let bb: u8 = b.(i);
+ let bb: u8 = b[i];
log bb;
assert (ab == bb);
i += 1;
fn main() {
// Chars of 1, 2, 3, and 4 bytes
- let chs: [char] = ~['e', 'é', '€', 0x10000 as char];
+ let chs: [char] = ['e', 'é', '€', 0x10000 as char];
let s: str = str::from_chars(chs);
assert (str::byte_len(s) == 10u);
assert (str::char_at(s, 1u) == 'é');
assert (str::is_utf8(str::bytes(s)));
- assert (!str::is_utf8(~[0x80_u8]));
- assert (!str::is_utf8(~[0xc0_u8]));
- assert (!str::is_utf8(~[0xc0_u8, 0x10_u8]));
+ assert (!str::is_utf8([0x80_u8]));
+ assert (!str::is_utf8([0xc0_u8]));
+ assert (!str::is_utf8([0xc0_u8, 0x10_u8]));
let stack = "a×c€";
assert (str::pop_char(stack) == '€');
const const_refcount: uint = 0x7bad_face_u;
fn fast_growth() {
- let v: [int] = ~[1, 2, 3, 4, 5];
- v += ~[6, 7, 8, 9, 0];
- log v.(9);
- assert (v.(0) == 1);
- assert (v.(7) == 8);
- assert (v.(9) == 0);
+ let v: [int] = [1, 2, 3, 4, 5];
+ v += [6, 7, 8, 9, 0];
+ log v[9];
+ assert (v[0] == 1);
+ assert (v[7] == 8);
+ assert (v[9] == 0);
}
fn slow_growth() {
- let v: [int] = ~[];
+ let v: [int] = [];
let u: [int] = v;
- v += ~[17];
- log v.(0);
- assert (v.(0) == 17);
+ v += [17];
+ log v[0];
+ assert (v[0] == 17);
}
fn slow_growth2_helper(s: str) { // ref up: s
obj acc(mutable v: [str]) {
- fn add(s: &str) { v += ~[s]; }
+ fn add(s: &str) { v += [s]; }
}
let ss: str = s; // ref up: s
* mumble, the existing str in the originally- shared vec.
*/
- let v: [str] = ~[mumble]; // ref up: mumble
+ let v: [str] = [mumble]; // ref up: mumble
let a: acc = acc(v);
log str::refcount(mumble);
assert (str::refcount(s) == const_refcount);
assert (str::refcount(mumble) == const_refcount);
- log v.(0);
+ log v[0];
log vec::len::<str>(v);
- assert (str::eq(v.(0), mumble));
+ assert (str::eq(v[0], mumble));
assert (vec::len::<str>(v) == 1u);
} // ref down: mumble, s,
// -*- rust -*-
fn main() {
- let a: [int] = ~[1, 2, 3, 4, 5];
- let b: [int] = ~[6, 7, 8, 9, 0];
+ let a: [int] = [1, 2, 3, 4, 5];
+ let b: [int] = [6, 7, 8, 9, 0];
let v: [int] = a + b;
- log v.(9);
- assert (v.(0) == 1);
- assert (v.(7) == 8);
- assert (v.(9) == 0);
+ log v[9];
+ assert (v[0] == 1);
+ assert (v[7] == 8);
+ assert (v[9] == 0);
}
// This just tests whether the vec leaks its members.
let pvec: [@{x: int, y: int}] =
- ~[@{x: 1, y: 2}, @{x: 3, y: 4}, @{x: 5, y: 6}];
+ [@{x: 1, y: 2}, @{x: 3, y: 4}, @{x: 5, y: 6}];
}
fn main() {
- let v = ~[1];
- v += ~[2];
- v += ~[3];
- v += ~[4];
- v += ~[5];
- assert (v.(0) == 1);
- assert (v.(1) == 2);
- assert (v.(2) == 3);
- assert (v.(3) == 4);
- assert (v.(4) == 5);
-}
\ No newline at end of file
+ let v = [1];
+ v += [2];
+ v += [3];
+ v += [4];
+ v += [5];
+ assert (v[0] == 1);
+ assert (v[1] == 2);
+ assert (v[2] == 3);
+ assert (v[3] == 4);
+ assert (v[4] == 5);
+}
-fn main() { let a = ~[1, 2, 3, 4, 5]; let b = ~[a, a]; b += b; }
\ No newline at end of file
+fn main() { let a = [1, 2, 3, 4, 5]; let b = [a, a]; b += b; }
fn main() {
let later: [int];
- if true { later = ~[1]; } else { later = ~[2]; }
- log later.(0);
+ if true { later = [1]; } else { later = [2]; }
+ log later[0];
}
-fn push<T>(v: &mutable [mutable? T], t: &T) { v += ~[t]; }
+fn push<T>(v: &mutable [mutable? T], t: &T) { v += [t]; }
-fn main() { let v = ~[1, 2, 3]; push(v, 1); }
+fn main() { let v = [1, 2, 3]; push(v, 1); }
// -*- rust -*-
fn main() {
- let v: [int] = ~[10, 20];
- assert (v[0]== 10);
+ let v: [int] = [10, 20];
+ assert (v[0] == 10);
assert (v[1] == 20);
let x: int = 0;
assert (v[x] == 10);
-fn main() { let quux: @[uint] = @~[]; }
+fn main() { let quux: @[uint] = @[]; }
let y: int = 0;
while y < x { log y; log "hello"; y = y + 1; }
do { log "goodbye"; x = x - 1; log x; } while x > 0
-}
\ No newline at end of file
+}
-fn main() { let x: int = 10; while x == 10 && x == 11 { let y = 0xf00; } }
\ No newline at end of file
+fn main() { let x: int = 10; while x == 10 && x == 11 { let y = 0xf00; } }
let x: int;
while z < 50 { z += 1; while false { x <- y; y = z; } log y; }
assert (y == 42 && z == 50);
-}
\ No newline at end of file
+}
// The auto slot for the result of make(i) should not leak.
while make(i) != a { i += 1; }
-}
\ No newline at end of file
+}
i = i + 1;
if i == 95 {
let v: [int] =
- ~[1, 2, 3, 4, 5]; // we check that it is freed by break
+ [1, 2, 3, 4, 5]; // we check that it is freed by break
log "breaking";
break;
// Just a grab bug of stuff that you wouldn't want to actualy write
-fn strange() -> bool {
- let _x = ret true;
-}
+fn strange() -> bool { let _x = ret true; }
fn funny() {
- fn f(_x: ()) {}
+ fn f(_x: ()) { }
f(ret);
}
}
fn what() {
- fn the(x: @mutable bool){
- ret while !*x { *x = true };
- }
+ fn the(x: @mutable bool) { ret while !*x { *x = true }; }
let i = @mutable false;
let dont = bind the(i);
dont();
- assert *i;
+ assert (*i);
}
fn zombiejesus() {
- do { while (ret) { if (ret) {
- alt (ret) { _ {
- ret ? ret : ret
- }}
- }}} while ret;
+ do { while (ret) { if (ret) { alt (ret) { _ { ret ? ret : ret } } } } }
+ while ret
}
fn notsure() {
fn canttouchthis() -> uint {
pred p() -> bool { true }
- let _a = (assert true) == (check p());
- let _c = (check p()) == ();
+ let _a = (assert (true)) == (check (p()));
+ let _c = (check (p())) == ();
let _b = (log 0) == (ret 0u);
}
fn angrydome() {
- while true {
- if (break) { }
- }
+ while true { if break { } }
let i = 0;
- do {
- i += 1;
- if i == 1 {
- alt cont { _ { } }
- }
- } while false;
+ do { i += 1; if i == 1 { alt cont { _ { } } } } while false
}
-fn evil_lincoln() {
- let evil <- log "lincoln";
-}
+fn evil_lincoln() { let evil <- log "lincoln"; }
fn main() {
strange();
let x: point = {x: 10, y: 11, mutable z: 12};
f(x);
assert (x.z == 13);
-}
\ No newline at end of file
+}
#[cfg(target_os = "macos")]
#[cfg(target_os = "linux")]
-fn main() { }
\ No newline at end of file
+fn main() { }
join_id(other);
}
-fn child() { log_err "4"; yield(); log_err "5"; yield(); log_err "6"; }
\ No newline at end of file
+fn child() { log_err "4"; yield(); log_err "5"; yield(); log_err "6"; }
fn main() {
let c = child;
let other = task::spawn(c);
- log_err "1"; yield();
+ log_err "1";
+ yield();
join_id(other);
}
fn test_1_element() {
let act;
act = bitv::create(1u, false);
- assert (bitv::eq_vec(act, ~[0u]));
+ assert (bitv::eq_vec(act, [0u]));
act = bitv::create(1u, true);
- assert (bitv::eq_vec(act, ~[1u]));
+ assert (bitv::eq_vec(act, [1u]));
}
#[test]
// all 0
act = bitv::create(10u, false);
- assert (bitv::eq_vec(act, ~[0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u]));
+ assert (bitv::eq_vec(act, [0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u]));
// all 1
act = bitv::create(10u, true);
- assert (bitv::eq_vec(act, ~[1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u]));
+ assert (bitv::eq_vec(act, [1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u]));
// mixed
act = bitv::create(10u, false);
bitv::set(act, 2u, true);
bitv::set(act, 3u, true);
bitv::set(act, 4u, true);
- assert (bitv::eq_vec(act, ~[1u, 1u, 1u, 1u, 1u, 0u, 0u, 0u, 0u, 0u]));
+ assert (bitv::eq_vec(act, [1u, 1u, 1u, 1u, 1u, 0u, 0u, 0u, 0u, 0u]));
// mixed
act = bitv::create(10u, false);
bitv::set(act, 7u, true);
bitv::set(act, 8u, true);
bitv::set(act, 9u, true);
- assert (bitv::eq_vec(act, ~[0u, 0u, 0u, 0u, 0u, 1u, 1u, 1u, 1u, 1u]));
+ assert (bitv::eq_vec(act, [0u, 0u, 0u, 0u, 0u, 1u, 1u, 1u, 1u, 1u]));
// mixed
act = bitv::create(10u, false);
bitv::set(act, 3u, true);
bitv::set(act, 6u, true);
bitv::set(act, 9u, true);
- assert (bitv::eq_vec(act, ~[1u, 0u, 0u, 1u, 0u, 0u, 1u, 0u, 0u, 1u]));
+ assert (bitv::eq_vec(act, [1u, 0u, 0u, 1u, 0u, 0u, 1u, 0u, 0u, 1u]));
}
#[test]
act = bitv::create(31u, false);
assert (bitv::eq_vec(act,
- ~[0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u]));
+ [0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u]));
// all 1
act = bitv::create(31u, true);
assert (bitv::eq_vec(act,
- ~[1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u,
- 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u,
- 1u, 1u, 1u, 1u, 1u]));
+ [1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u,
+ 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u,
+ 1u, 1u, 1u, 1u, 1u]));
// mixed
act = bitv::create(31u, false);
bitv::set(act, 6u, true);
bitv::set(act, 7u, true);
assert (bitv::eq_vec(act,
- ~[1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u]));
+ [1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u]));
// mixed
act = bitv::create(31u, false);
bitv::set(act, 22u, true);
bitv::set(act, 23u, true);
assert (bitv::eq_vec(act,
- ~[0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u]));
+ [0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u]));
// mixed
act = bitv::create(31u, false);
bitv::set(act, 29u, true);
bitv::set(act, 30u, true);
assert (bitv::eq_vec(act,
- ~[0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 1u, 1u,
- 1u, 1u, 1u, 1u, 1u]));
+ [0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 1u, 1u,
+ 1u, 1u, 1u, 1u, 1u]));
// mixed
act = bitv::create(31u, false);
bitv::set(act, 17u, true);
bitv::set(act, 30u, true);
assert (bitv::eq_vec(act,
- ~[0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 1u]));
+ [0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 1u]));
}
#[test]
act = bitv::create(32u, false);
assert (bitv::eq_vec(act,
- ~[0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u]));
+ [0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u]));
// all 1
act = bitv::create(32u, true);
assert (bitv::eq_vec(act,
- ~[1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u,
- 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u,
- 1u, 1u, 1u, 1u, 1u, 1u]));
+ [1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u,
+ 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u,
+ 1u, 1u, 1u, 1u, 1u, 1u]));
// mixed
act = bitv::create(32u, false);
bitv::set(act, 6u, true);
bitv::set(act, 7u, true);
assert (bitv::eq_vec(act,
- ~[1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u]));
+ [1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u]));
// mixed
act = bitv::create(32u, false);
bitv::set(act, 22u, true);
bitv::set(act, 23u, true);
assert (bitv::eq_vec(act,
- ~[0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u]));
+ [0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u]));
// mixed
act = bitv::create(32u, false);
bitv::set(act, 30u, true);
bitv::set(act, 31u, true);
assert (bitv::eq_vec(act,
- ~[0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 1u, 1u,
- 1u, 1u, 1u, 1u, 1u, 1u]));
+ [0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 1u, 1u,
+ 1u, 1u, 1u, 1u, 1u, 1u]));
// mixed
act = bitv::create(32u, false);
bitv::set(act, 30u, true);
bitv::set(act, 31u, true);
assert (bitv::eq_vec(act,
- ~[0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 1u, 1u]));
+ [0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 1u, 1u]));
}
#[test]
act = bitv::create(33u, false);
assert (bitv::eq_vec(act,
- ~[0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u, 0u]));
+ [0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u, 0u]));
// all 1
act = bitv::create(33u, true);
assert (bitv::eq_vec(act,
- ~[1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u,
- 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u,
- 1u, 1u, 1u, 1u, 1u, 1u, 1u]));
+ [1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u,
+ 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u,
+ 1u, 1u, 1u, 1u, 1u, 1u, 1u]));
// mixed
act = bitv::create(33u, false);
bitv::set(act, 6u, true);
bitv::set(act, 7u, true);
assert (bitv::eq_vec(act,
- ~[1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u, 0u]));
+ [1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u, 0u]));
// mixed
act = bitv::create(33u, false);
bitv::set(act, 22u, true);
bitv::set(act, 23u, true);
assert (bitv::eq_vec(act,
- ~[0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u, 0u]));
+ [0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 1u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u, 0u]));
// mixed
act = bitv::create(33u, false);
bitv::set(act, 30u, true);
bitv::set(act, 31u, true);
assert (bitv::eq_vec(act,
- ~[0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 1u, 1u,
- 1u, 1u, 1u, 1u, 1u, 1u, 0u]));
+ [0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 1u, 1u,
+ 1u, 1u, 1u, 1u, 1u, 1u, 0u]));
// mixed
act = bitv::create(33u, false);
bitv::set(act, 31u, true);
bitv::set(act, 32u, true);
assert (bitv::eq_vec(act,
- ~[0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 0u, 0u, 0u, 0u, 1u, 1u, 1u]));
+ [0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 1u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 1u, 1u, 1u]));
}
comm::send(c, 42);
let v = p.recv();
log_err v;
- assert(42 == v);
+ assert (42 == v);
}
#[test]
let p = comm::port::<int>();
let c = comm::chan::<int>(p);
comm::send(c, 42);
- assert(comm::recv(p) == 42);
+ assert (comm::recv(p) == 42);
}
#[test]
let p = comm::port();
let c = comm::chan(p);
comm::send(c, 42);
- assert(comm::recv(p) == 42);
+ assert (comm::recv(p) == 42);
}
#[test]
assert (deq.get(3) == d);
}
-type eqfn<T> = fn(&T, &T) -> bool ;
+type eqfn<T> = fn(&T, &T) -> bool;
fn test_parameterized<@T>(e: eqfn<T>, a: &T, b: &T, c: &T, d: &T) {
let deq: deque::t<T> = deque::create::<T>();
log "test parameterized: taggy";
let eq3: eqfn<taggy> = taggyeq;
test_parameterized::<taggy>(eq3, one(1), two(1, 2), three(1, 2, 3),
- two(17, 42));
+ two(17, 42));
log "*** test parameterized: taggypar<int>";
let eq4: eqfn<taggypar<int>> = taggypareq::<int>;
- test_parameterized::<taggypar<int>>(eq4,
- onepar::<int>(1),
- twopar::<int>(1, 2),
- threepar::<int>(1, 2, 3),
- twopar::<int>(17, 42));
+ test_parameterized::<taggypar<int>>(eq4, onepar::<int>(1),
+ twopar::<int>(1, 2),
+ threepar::<int>(1, 2, 3),
+ twopar::<int>(17, 42));
log "*** end test parameterized: taggypar::<int>";
log "*** test parameterized: reccy";
#[test]
fn test_lefts() {
- let input = ~[left(10), right(11), left(12), right(13), left(14)];
+ let input = [left(10), right(11), left(12), right(13), left(14)];
let result = lefts(input);
- assert (result == ~[10, 12, 14]);
+ assert (result == [10, 12, 14]);
}
#[test]
fn test_lefts_none() {
- let input: [t<int, int>] = ~[right(10), right(10)];
+ let input: [t<int, int>] = [right(10), right(10)];
let result = lefts(input);
assert (len(result) == 0u);
}
#[test]
fn test_lefts_empty() {
- let input: [t<int, int>] = ~[];
+ let input: [t<int, int>] = [];
let result = lefts(input);
assert (len(result) == 0u);
}
#[test]
fn test_rights() {
- let input = ~[left(10), right(11), left(12), right(13), left(14)];
+ let input = [left(10), right(11), left(12), right(13), left(14)];
let result = rights(input);
- assert (result == ~[11, 13]);
+ assert (result == [11, 13]);
}
#[test]
fn test_rights_none() {
- let input: [t<int, int>] = ~[left(10), left(10)];
+ let input: [t<int, int>] = [left(10), left(10)];
let result = rights(input);
assert (len(result) == 0u);
}
#[test]
fn test_rights_empty() {
- let input: [t<int, int>] = ~[];
+ let input: [t<int, int>] = [];
let result = rights(input);
assert (len(result) == 0u);
}
#[test]
fn test_partition() {
- let input = ~[left(10), right(11), left(12), right(13), left(14)];
+ let input = [left(10), right(11), left(12), right(13), left(14)];
let result = partition(input);
- assert (result.lefts.(0) == 10);
- assert (result.lefts.(1) == 12);
- assert (result.lefts.(2) == 14);
- assert (result.rights.(0) == 11);
- assert (result.rights.(1) == 13);
+ assert (result.lefts[0] == 10);
+ assert (result.lefts[1] == 12);
+ assert (result.lefts[2] == 14);
+ assert (result.rights[0] == 11);
+ assert (result.rights[1] == 13);
}
#[test]
fn test_partition_no_lefts() {
- let input: [t<int, int>] = ~[right(10), right(11)];
+ let input: [t<int, int>] = [right(10), right(11)];
let result = partition(input);
assert (len(result.lefts) == 0u);
assert (len(result.rights) == 2u);
#[test]
fn test_partition_no_rights() {
- let input: [t<int, int>] = ~[left(10), left(11)];
+ let input: [t<int, int>] = [left(10), left(11)];
let result = partition(input);
assert (len(result.lefts) == 2u);
assert (len(result.rights) == 0u);
#[test]
fn test_partition_empty() {
- let input: [t<int, int>] = ~[];
+ let input: [t<int, int>] = [];
let result = partition(input);
assert (len(result.lefts) == 0u);
assert (len(result.rights) == 0u);
// Tests for reqopt
#[test]
fn test_reqopt_long() {
- let args = ~["--test=20"];
- let opts = ~[opt::reqopt("test")];
+ let args = ["--test=20"];
+ let opts = [opt::reqopt("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) {
#[test]
fn test_reqopt_long_missing() {
- let args = ~["blah"];
- let opts = ~[opt::reqopt("test")];
+ let args = ["blah"];
+ let opts = [opt::reqopt("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, option_missing); }
#[test]
fn test_reqopt_long_no_arg() {
- let args = ~["--test"];
- let opts = ~[opt::reqopt("test")];
+ let args = ["--test"];
+ let opts = [opt::reqopt("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, argument_missing); }
#[test]
fn test_reqopt_long_multi() {
- let args = ~["--test=20", "--test=30"];
- let opts = ~[opt::reqopt("test")];
+ let args = ["--test=20", "--test=30"];
+ let opts = [opt::reqopt("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, option_duplicated); }
#[test]
fn test_reqopt_short() {
- let args = ~["-t", "20"];
- let opts = ~[opt::reqopt("t")];
+ let args = ["-t", "20"];
+ let opts = [opt::reqopt("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) {
#[test]
fn test_reqopt_short_missing() {
- let args = ~["blah"];
- let opts = ~[opt::reqopt("t")];
+ let args = ["blah"];
+ let opts = [opt::reqopt("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, option_missing); }
#[test]
fn test_reqopt_short_no_arg() {
- let args = ~["-t"];
- let opts = ~[opt::reqopt("t")];
+ let args = ["-t"];
+ let opts = [opt::reqopt("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, argument_missing); }
#[test]
fn test_reqopt_short_multi() {
- let args = ~["-t", "20", "-t", "30"];
- let opts = ~[opt::reqopt("t")];
+ let args = ["-t", "20", "-t", "30"];
+ let opts = [opt::reqopt("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, option_duplicated); }
// Tests for optopt
#[test]
fn test_optopt_long() {
- let args = ~["--test=20"];
- let opts = ~[opt::optopt("test")];
+ let args = ["--test=20"];
+ let opts = [opt::optopt("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) {
#[test]
fn test_optopt_long_missing() {
- let args = ~["blah"];
- let opts = ~[opt::optopt("test")];
+ let args = ["blah"];
+ let opts = [opt::optopt("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) { assert (!opt::opt_present(m, "test")); }
#[test]
fn test_optopt_long_no_arg() {
- let args = ~["--test"];
- let opts = ~[opt::optopt("test")];
+ let args = ["--test"];
+ let opts = [opt::optopt("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, argument_missing); }
#[test]
fn test_optopt_long_multi() {
- let args = ~["--test=20", "--test=30"];
- let opts = ~[opt::optopt("test")];
+ let args = ["--test=20", "--test=30"];
+ let opts = [opt::optopt("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, option_duplicated); }
#[test]
fn test_optopt_short() {
- let args = ~["-t", "20"];
- let opts = ~[opt::optopt("t")];
+ let args = ["-t", "20"];
+ let opts = [opt::optopt("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) {
#[test]
fn test_optopt_short_missing() {
- let args = ~["blah"];
- let opts = ~[opt::optopt("t")];
+ let args = ["blah"];
+ let opts = [opt::optopt("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) { assert (!opt::opt_present(m, "t")); }
#[test]
fn test_optopt_short_no_arg() {
- let args = ~["-t"];
- let opts = ~[opt::optopt("t")];
+ let args = ["-t"];
+ let opts = [opt::optopt("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, argument_missing); }
#[test]
fn test_optopt_short_multi() {
- let args = ~["-t", "20", "-t", "30"];
- let opts = ~[opt::optopt("t")];
+ let args = ["-t", "20", "-t", "30"];
+ let opts = [opt::optopt("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, option_duplicated); }
// Tests for optflag
#[test]
fn test_optflag_long() {
- let args = ~["--test"];
- let opts = ~[opt::optflag("test")];
+ let args = ["--test"];
+ let opts = [opt::optflag("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) { assert (opt::opt_present(m, "test")); }
#[test]
fn test_optflag_long_missing() {
- let args = ~["blah"];
- let opts = ~[opt::optflag("test")];
+ let args = ["blah"];
+ let opts = [opt::optflag("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) { assert (!opt::opt_present(m, "test")); }
#[test]
fn test_optflag_long_arg() {
- let args = ~["--test=20"];
- let opts = ~[opt::optflag("test")];
+ let args = ["--test=20"];
+ let opts = [opt::optflag("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) {
#[test]
fn test_optflag_long_multi() {
- let args = ~["--test", "--test"];
- let opts = ~[opt::optflag("test")];
+ let args = ["--test", "--test"];
+ let opts = [opt::optflag("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, option_duplicated); }
#[test]
fn test_optflag_short() {
- let args = ~["-t"];
- let opts = ~[opt::optflag("t")];
+ let args = ["-t"];
+ let opts = [opt::optflag("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) { assert (opt::opt_present(m, "t")); }
#[test]
fn test_optflag_short_missing() {
- let args = ~["blah"];
- let opts = ~[opt::optflag("t")];
+ let args = ["blah"];
+ let opts = [opt::optflag("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) { assert (!opt::opt_present(m, "t")); }
#[test]
fn test_optflag_short_arg() {
- let args = ~["-t", "20"];
- let opts = ~[opt::optflag("t")];
+ let args = ["-t", "20"];
+ let opts = [opt::optflag("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) {
// The next variable after the flag is just a free argument
- assert (m.free.(0) == "20");
+ assert (m.free[0] == "20");
}
_ { fail; }
}
#[test]
fn test_optflag_short_multi() {
- let args = ~["-t", "-t"];
- let opts = ~[opt::optflag("t")];
+ let args = ["-t", "-t"];
+ let opts = [opt::optflag("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, option_duplicated); }
// Tests for optmulti
#[test]
fn test_optmulti_long() {
- let args = ~["--test=20"];
- let opts = ~[opt::optmulti("test")];
+ let args = ["--test=20"];
+ let opts = [opt::optmulti("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) {
#[test]
fn test_optmulti_long_missing() {
- let args = ~["blah"];
- let opts = ~[opt::optmulti("test")];
+ let args = ["blah"];
+ let opts = [opt::optmulti("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) { assert (!opt::opt_present(m, "test")); }
#[test]
fn test_optmulti_long_no_arg() {
- let args = ~["--test"];
- let opts = ~[opt::optmulti("test")];
+ let args = ["--test"];
+ let opts = [opt::optmulti("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, argument_missing); }
#[test]
fn test_optmulti_long_multi() {
- let args = ~["--test=20", "--test=30"];
- let opts = ~[opt::optmulti("test")];
+ let args = ["--test=20", "--test=30"];
+ let opts = [opt::optmulti("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) {
assert (opt::opt_present(m, "test"));
assert (opt::opt_str(m, "test") == "20");
- assert (opt::opt_strs(m, "test").(0) == "20");
- assert (opt::opt_strs(m, "test").(1) == "30");
+ assert (opt::opt_strs(m, "test")[0] == "20");
+ assert (opt::opt_strs(m, "test")[1] == "30");
}
_ { fail; }
}
#[test]
fn test_optmulti_short() {
- let args = ~["-t", "20"];
- let opts = ~[opt::optmulti("t")];
+ let args = ["-t", "20"];
+ let opts = [opt::optmulti("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) {
#[test]
fn test_optmulti_short_missing() {
- let args = ~["blah"];
- let opts = ~[opt::optmulti("t")];
+ let args = ["blah"];
+ let opts = [opt::optmulti("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) { assert (!opt::opt_present(m, "t")); }
#[test]
fn test_optmulti_short_no_arg() {
- let args = ~["-t"];
- let opts = ~[opt::optmulti("t")];
+ let args = ["-t"];
+ let opts = [opt::optmulti("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, argument_missing); }
#[test]
fn test_optmulti_short_multi() {
- let args = ~["-t", "20", "-t", "30"];
- let opts = ~[opt::optmulti("t")];
+ let args = ["-t", "20", "-t", "30"];
+ let opts = [opt::optmulti("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) {
assert (opt::opt_present(m, "t"));
assert (opt::opt_str(m, "t") == "20");
- assert (opt::opt_strs(m, "t").(0) == "20");
- assert (opt::opt_strs(m, "t").(1) == "30");
+ assert (opt::opt_strs(m, "t")[0] == "20");
+ assert (opt::opt_strs(m, "t")[1] == "30");
}
_ { fail; }
}
#[test]
fn test_unrecognized_option_long() {
- let args = ~["--untest"];
- let opts = ~[opt::optmulti("t")];
+ let args = ["--untest"];
+ let opts = [opt::optmulti("t")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, unrecognized_option); }
#[test]
fn test_unrecognized_option_short() {
- let args = ~["-t"];
- let opts = ~[opt::optmulti("test")];
+ let args = ["-t"];
+ let opts = [opt::optmulti("test")];
let rs = opt::getopts(args, opts);
alt rs {
opt::failure(f) { check_fail_type(f, unrecognized_option); }
#[test]
fn test_combined() {
let args =
- ~["prog", "free1", "-s", "20", "free2", "--flag", "--long=30", "-f",
+ ["prog", "free1", "-s", "20", "free2", "--flag", "--long=30", "-f",
"-m", "40", "-m", "50"];
let opts =
- ~[opt::optopt("s"), opt::optflag("flag"), opt::reqopt("long"),
+ [opt::optopt("s"), opt::optflag("flag"), opt::reqopt("long"),
opt::optflag("f"), opt::optmulti("m"), opt::optopt("notpresent")];
let rs = opt::getopts(args, opts);
alt rs {
opt::success(m) {
- assert (m.free.(0) == "prog");
- assert (m.free.(1) == "free1");
+ assert (m.free[0] == "prog");
+ assert (m.free[1] == "free1");
assert (opt::opt_str(m, "s") == "20");
- assert (m.free.(2) == "free2");
+ assert (m.free[2] == "free2");
assert (opt::opt_present(m, "flag"));
assert (opt::opt_str(m, "long") == "30");
assert (opt::opt_present(m, "f"));
- assert (opt::opt_strs(m, "m").(0) == "40");
- assert (opt::opt_strs(m, "m").(1) == "50");
+ assert (opt::opt_strs(m, "m")[0] == "40");
+ assert (opt::opt_strs(m, "m")[1] == "50");
assert (!opt::opt_present(m, "notpresent"));
}
_ { fail; }
assert (int::pow(-3, 2u) == 9);
assert (int::pow(-3, 3u) == -27);
assert (int::pow(4, 9u) == 262144);
-}
\ No newline at end of file
+}
log frood;
{
let out: io::writer =
- io::file_writer(tmpfile, ~[io::create, io::truncate]);
+ io::file_writer(tmpfile, [io::create, io::truncate]);
out.write_str(frood);
}
let inp: io::reader = io::file_reader(tmpfile);
#[test]
fn test_from_vec() {
- let l = from_vec(~[0, 1, 2]);
+ let l = from_vec([0, 1, 2]);
assert (car(l) == 0);
assert (car(cdr(l)) == 1);
assert (car(cdr(cdr(l))) == 2);
#[test]
fn test_foldl() {
- let l = from_vec(~[0, 1, 2, 3, 4]);
+ let l = from_vec([0, 1, 2, 3, 4]);
fn add(a: &int, b: &uint) -> uint { ret (a as uint) + b; }
let rs = list::foldl(l, 0u, add);
assert (rs == 10u);
#[test]
fn test_find_success() {
- let l = from_vec(~[0, 1, 2]);
+ let l = from_vec([0, 1, 2]);
fn match(i: &int) -> option::t<int> {
ret if i == 2 { option::some(i) } else { option::none::<int> };
}
#[test]
fn test_find_fail() {
- let l = from_vec(~[0, 1, 2]);
+ let l = from_vec([0, 1, 2]);
fn match(i: &int) -> option::t<int> { ret option::none::<int>; }
let rs = list::find(l, match);
assert (rs == option::none::<int>);
#[test]
fn test_has() {
- let l = from_vec(~[5, 8, 6]);
+ let l = from_vec([5, 8, 6]);
let empty = list::nil::<int>;
assert (list::has(l, 5));
assert (!list::has(l, 7));
#[test]
fn test_length() {
- let l = from_vec(~[0, 1, 2]);
+ let l = from_vec([0, 1, 2]);
assert (list::length(l) == 3u);
}
#[test]
fn test_format_ip() {
- assert(net::format_addr(net::ipv4(127u8,0u8,0u8,1u8)) == "127.0.0.1")
+ assert (net::format_addr(net::ipv4(127u8, 0u8, 0u8, 1u8)) == "127.0.0.1")
}
#[test]
fn test_parse_ip() {
- assert(net::parse_addr("127.0.0.1") == net::ipv4(127u8,0u8,0u8,1u8));
+ assert (net::parse_addr("127.0.0.1") == net::ipv4(127u8, 0u8, 0u8, 1u8));
}
log fs::make_absolute("test-path");
log fs::make_absolute("/usr/bin");
-}
\ No newline at end of file
+}
let p = {mutable fst: 10, mutable snd: 20};
let pptr: *mutable pair = ptr::addr_of(p);
let iptr: *mutable int = unsafe::reinterpret_cast(pptr);
- assert (*iptr == 10);
+ assert (*iptr == 10);;
*iptr = 30;
assert (*iptr == 30);
- assert (p.fst == 30);
+ assert (p.fst == 30);;
*pptr = {mutable fst: 50, mutable snd: 60};
assert (*iptr == 50);
let f = ltequal;
std::sort::quick_sort::<int>(f, v1);
let i = 0u;
- while i < len { log v2.(i); assert (v2.(i) == v1.(i)); i += 1u; }
+ while i < len { log v2[i]; assert (v2[i] == v1[i]); i += 1u; }
}
#[test]
fn test() {
{
- let v1 = ~[mutable 3, 7, 4, 5, 2, 9, 5, 8];
- let v2 = ~[mutable 2, 3, 4, 5, 5, 7, 8, 9];
+ let v1 = [mutable 3, 7, 4, 5, 2, 9, 5, 8];
+ let v2 = [mutable 2, 3, 4, 5, 5, 7, 8, 9];
check_sort(v1, v2);
}
{
- let v1 = ~[mutable 1, 1, 1];
- let v2 = ~[mutable 1, 1, 1];
+ let v1 = [mutable 1, 1, 1];
+ let v2 = [mutable 1, 1, 1];
check_sort(v1, v2);
}
{
- let v1: [mutable int] = ~[mutable ];
- let v2: [mutable int] = ~[mutable ];
+ let v1: [mutable int] = [mutable];
+ let v2: [mutable int] = [mutable];
check_sort(v1, v2);
}
- { let v1 = ~[mutable 9]; let v2 = ~[mutable 9]; check_sort(v1, v2); }
+ { let v1 = [mutable 9]; let v2 = [mutable 9]; check_sort(v1, v2); }
{
- let v1 = ~[mutable 9, 3, 3, 3, 9];
- let v2 = ~[mutable 3, 3, 3, 9, 9];
+ let v1 = [mutable 9, 3, 3, 3, 9];
+ let v2 = [mutable 3, 3, 3, 9, 9];
check_sort(v1, v2);
}
}
// Regression test for #705
#[test]
fn test_simple() {
- let names = ~[mutable 2, 1, 3];
+ let names = [mutable 2, 1, 3];
- let expected = ~[1, 2, 3];
+ let expected = [1, 2, 3];
fn lteq(a: &int, b: &int) -> bool { int::le(a, b) }
sort::quick_sort(lteq, names);
let pairs = vec::zip(expected, vec::from_mut(names));
- for (a, b) in pairs {
- log #fmt("%d %d", a, b);
- assert (a == b);
- }
+ for (a, b) in pairs { log #fmt["%d %d", a, b]; assert (a == b); }
}
// Local Variables:
let f2 = equal;
std::sort::quick_sort3::<int>(f1, f2, v1);
let i = 0u;
- while i < len { log v2.(i); assert (v2.(i) == v1.(i)); i += 1u; }
+ while i < len { log v2[i]; assert (v2[i] == v1[i]); i += 1u; }
}
#[test]
fn test() {
{
- let v1 = ~[mutable 3, 7, 4, 5, 2, 9, 5, 8];
- let v2 = ~[mutable 2, 3, 4, 5, 5, 7, 8, 9];
+ let v1 = [mutable 3, 7, 4, 5, 2, 9, 5, 8];
+ let v2 = [mutable 2, 3, 4, 5, 5, 7, 8, 9];
check_sort(v1, v2);
}
{
- let v1 = ~[mutable 1, 1, 1];
- let v2 = ~[mutable 1, 1, 1];
+ let v1 = [mutable 1, 1, 1];
+ let v2 = [mutable 1, 1, 1];
check_sort(v1, v2);
}
{
- let v1: [mutable int] = ~[mutable ];
- let v2: [mutable int] = ~[mutable ];
+ let v1: [mutable int] = [mutable];
+ let v2: [mutable int] = [mutable];
check_sort(v1, v2);
}
- { let v1 = ~[mutable 9]; let v2 = ~[mutable 9]; check_sort(v1, v2); }
+ { let v1 = [mutable 9]; let v2 = [mutable 9]; check_sort(v1, v2); }
{
- let v1 = ~[mutable 9, 3, 3, 3, 9];
- let v2 = ~[mutable 3, 3, 3, 9, 9];
+ let v1 = [mutable 9, 3, 3, 3, 9];
+ let v2 = [mutable 3, 3, 3, 9, 9];
check_sort(v1, v2);
}
}
}
log r1.next();
log r1.next();
-}
\ No newline at end of file
+}
#[cfg(target_os = "macos")]
#[test]
fn test_leaks() {
- run::run_program("echo", ~[]);
- run::start_program("echo", ~[]);
- run::program_output("echo", ~[]);
+ run::run_program("echo", []);
+ run::start_program("echo", []);
+ run::program_output("echo", []);
}
// FIXME
let pipe_out = os::pipe();
let pipe_err = os::pipe();
- let pid = run::spawn_process("cat", ~[],
- pipe_in.in, pipe_out.out, pipe_err.out);
+ let pid =
+ run::spawn_process("cat", [], pipe_in.in, pipe_out.out, pipe_err.out);
os::libc::close(pipe_in.in);
os::libc::close(pipe_out.out);
os::libc::close(pipe_err.out);
log expected;
log actual;
- assert expected == actual;
+ assert (expected == actual);
fn writeclose(fd: int, s: &str) {
- let writer = io::new_writer(
- io::fd_buf_writer(fd, option::none));
+ let writer = io::new_writer(io::fd_buf_writer(fd, option::none));
writer.write_str(s);
os::libc::close(fd);
fn readclose(fd: int) -> str {
// Copied from run::program_output
let file = os::fd_FILE(fd);
- let reader = io::new_reader(
- io::FILE_buf_reader(file, option::none));
+ let reader = io::new_reader(io::FILE_buf_reader(file, option::none));
let buf = "";
while !reader.eof() {
let bytes = reader.read_bytes(4096u);
os::libc::fclose(file);
ret buf;
}
-}
\ No newline at end of file
+}
// Test messages from FIPS 180-1
let fips_180_1_tests: [test] =
- ~[{input: "abc",
+ [{input: "abc",
output:
- ~[0xA9u8, 0x99u8, 0x3Eu8, 0x36u8,
- 0x47u8, 0x06u8, 0x81u8, 0x6Au8,
- 0xBAu8, 0x3Eu8, 0x25u8, 0x71u8,
- 0x78u8, 0x50u8, 0xC2u8, 0x6Cu8,
- 0x9Cu8, 0xD0u8, 0xD8u8, 0x9Du8]},
+ [0xA9u8, 0x99u8, 0x3Eu8, 0x36u8, 0x47u8, 0x06u8, 0x81u8, 0x6Au8,
+ 0xBAu8, 0x3Eu8, 0x25u8, 0x71u8, 0x78u8, 0x50u8, 0xC2u8, 0x6Cu8,
+ 0x9Cu8, 0xD0u8, 0xD8u8, 0x9Du8]},
{input:
"abcdbcdecdefdefgefghfghighij" + "hijkijkljklmklmnlmnomnopnopq",
output:
- ~[0x84u8, 0x98u8, 0x3Eu8, 0x44u8,
- 0x1Cu8, 0x3Bu8, 0xD2u8, 0x6Eu8,
- 0xBAu8, 0xAEu8, 0x4Au8, 0xA1u8,
- 0xF9u8, 0x51u8, 0x29u8, 0xE5u8,
- 0xE5u8, 0x46u8, 0x70u8, 0xF1u8]},
+ [0x84u8, 0x98u8, 0x3Eu8, 0x44u8, 0x1Cu8, 0x3Bu8, 0xD2u8, 0x6Eu8,
+ 0xBAu8, 0xAEu8, 0x4Au8, 0xA1u8, 0xF9u8, 0x51u8, 0x29u8, 0xE5u8,
+ 0xE5u8, 0x46u8, 0x70u8, 0xF1u8]},
{input: a_million_letter_a(),
output:
- ~[0x34u8, 0xAAu8, 0x97u8, 0x3Cu8,
- 0xD4u8, 0xC4u8, 0xDAu8, 0xA4u8,
- 0xF6u8, 0x1Eu8, 0xEBu8, 0x2Bu8,
- 0xDBu8, 0xADu8, 0x27u8, 0x31u8,
- 0x65u8, 0x34u8, 0x01u8, 0x6Fu8]}];
+ [0x34u8, 0xAAu8, 0x97u8, 0x3Cu8, 0xD4u8, 0xC4u8, 0xDAu8, 0xA4u8,
+ 0xF6u8, 0x1Eu8, 0xEBu8, 0x2Bu8, 0xDBu8, 0xADu8, 0x27u8, 0x31u8,
+ 0x65u8, 0x34u8, 0x01u8, 0x6Fu8]}];
// Examples from wikipedia
let wikipedia_tests: [test] =
- ~[{input: "The quick brown fox jumps over the lazy dog",
+ [{input: "The quick brown fox jumps over the lazy dog",
output:
- ~[0x2fu8, 0xd4u8, 0xe1u8, 0xc6u8,
- 0x7au8, 0x2du8, 0x28u8, 0xfcu8,
- 0xedu8, 0x84u8, 0x9eu8, 0xe1u8,
- 0xbbu8, 0x76u8, 0xe7u8, 0x39u8,
- 0x1bu8, 0x93u8, 0xebu8, 0x12u8]},
+ [0x2fu8, 0xd4u8, 0xe1u8, 0xc6u8, 0x7au8, 0x2du8, 0x28u8, 0xfcu8,
+ 0xedu8, 0x84u8, 0x9eu8, 0xe1u8, 0xbbu8, 0x76u8, 0xe7u8, 0x39u8,
+ 0x1bu8, 0x93u8, 0xebu8, 0x12u8]},
{input: "The quick brown fox jumps over the lazy cog",
output:
- ~[0xdeu8, 0x9fu8, 0x2cu8, 0x7fu8,
- 0xd2u8, 0x5eu8, 0x1bu8, 0x3au8,
- 0xfau8, 0xd3u8, 0xe8u8, 0x5au8,
- 0x0bu8, 0xd1u8, 0x7du8, 0x9bu8,
- 0x10u8, 0x0du8, 0xb4u8, 0xb3u8]}];
+ [0xdeu8, 0x9fu8, 0x2cu8, 0x7fu8, 0xd2u8, 0x5eu8, 0x1bu8, 0x3au8,
+ 0xfau8, 0xd3u8, 0xe8u8, 0x5au8, 0x0bu8, 0xd1u8, 0x7du8, 0x9bu8,
+ 0x10u8, 0x0du8, 0xb4u8, 0xb3u8]}];
let tests = fips_180_1_tests + wikipedia_tests;
fn check_vec_eq(v0: &[u8], v1: &[u8]) {
assert (vec::len::<u8>(v0) == vec::len::<u8>(v1));
let len = vec::len::<u8>(v0);
let i = 0u;
while i < len {
- let a = v0.(i);
- let b = v1.(i);
+ let a = v0[i];
+ let b = v1[i];
assert (a == b);
i += 1u;
}
let f = lteq;
let v3 = std::sort::merge_sort::<int>(f, v1);
let i = 0u;
- while i < len { log v3.(i); assert (v3.(i) == v2.(i)); i += 1u; }
+ while i < len { log v3[i]; assert (v3[i] == v2[i]); i += 1u; }
}
#[test]
fn test() {
{
- let v1 = ~[3, 7, 4, 5, 2, 9, 5, 8];
- let v2 = ~[2, 3, 4, 5, 5, 7, 8, 9];
+ let v1 = [3, 7, 4, 5, 2, 9, 5, 8];
+ let v2 = [2, 3, 4, 5, 5, 7, 8, 9];
check_sort(v1, v2);
}
- { let v1 = ~[1, 1, 1]; let v2 = ~[1, 1, 1]; check_sort(v1, v2); }
- { let v1: [int] = ~[]; let v2: [int] = ~[]; check_sort(v1, v2); }
- { let v1 = ~[9]; let v2 = ~[9]; check_sort(v1, v2); }
+ { let v1 = [1, 1, 1]; let v2 = [1, 1, 1]; check_sort(v1, v2); }
+ { let v1: [int] = []; let v2: [int] = []; check_sort(v1, v2); }
+ { let v1 = [9]; let v2 = [9]; check_sort(v1, v2); }
{
- let v1 = ~[9, 3, 3, 3, 9];
- let v2 = ~[3, 3, 3, 9, 9];
+ let v1 = [9, 3, 3, 3, 9];
+ let v2 = [3, 3, 3, 9, 9];
check_sort(v1, v2);
}
}
let v = str::split(s, c as u8);
log "split to: ";
for z: str in v { log z; }
- log "comparing: " + v.(i) + " vs. " + k;
- assert (str::eq(v.(i), k));
+ log "comparing: " + v[i] + " vs. " + k;
+ assert (str::eq(v[i], k));
}
t("abc.hello.there", '.', 0, "abc");
t("abc.hello.there", '.', 1, "hello");
#[test]
fn test_concat() {
fn t(v: &[str], s: &str) { assert (str::eq(str::concat(v), s)); }
- t(~["you", "know", "I'm", "no", "good"], "youknowI'mnogood");
- let v: [str] = ~[];
+ t(["you", "know", "I'm", "no", "good"], "youknowI'mnogood");
+ let v: [str] = [];
t(v, "");
- t(~["hi"], "hi");
+ t(["hi"], "hi");
}
#[test]
fn t(v: &[str], sep: &str, s: &str) {
assert (str::eq(str::connect(v, sep), s));
}
- t(~["you", "know", "I'm", "no", "good"], " ", "you know I'm no good");
- let v: [str] = ~[];
+ t(["you", "know", "I'm", "no", "good"], " ", "you know I'm no good");
+ let v: [str] = [];
t(v, " ", "");
- t(~["hi"], " ", "hi");
+ t(["hi"], " ", "hi");
}
#[test]
#[test]
fn trim_left() {
- assert str::trim_left("") == "";
- assert str::trim_left("a") == "a";
- assert str::trim_left(" ") == "";
- assert str::trim_left(" blah") == "blah";
- assert str::trim_left(" \u3000 wut") == "wut";
- assert str::trim_left("hey ") == "hey ";
+ assert (str::trim_left("") == "");
+ assert (str::trim_left("a") == "a");
+ assert (str::trim_left(" ") == "");
+ assert (str::trim_left(" blah") == "blah");
+ assert (str::trim_left(" \u3000 wut") == "wut");
+ assert (str::trim_left("hey ") == "hey ");
}
#[test]
fn trim_right() {
- assert str::trim_right("") == "";
- assert str::trim_right("a") == "a";
- assert str::trim_right(" ") == "";
- assert str::trim_right("blah ") == "blah";
- assert str::trim_right("wut \u3000 ") == "wut";
- assert str::trim_right(" hey") == " hey";
+ assert (str::trim_right("") == "");
+ assert (str::trim_right("a") == "a");
+ assert (str::trim_right(" ") == "");
+ assert (str::trim_right("blah ") == "blah");
+ assert (str::trim_right("wut \u3000 ") == "wut");
+ assert (str::trim_right(" hey") == " hey");
}
#[test]
fn trim() {
- assert str::trim("") == "";
- assert str::trim("a") == "a";
- assert str::trim(" ") == "";
- assert str::trim(" blah ") == "blah";
- assert str::trim("\nwut \u3000 ") == "wut";
- assert str::trim(" hey dude ") == "hey dude";
+ assert (str::trim("") == "");
+ assert (str::trim("a") == "a");
+ assert (str::trim(" ") == "");
+ assert (str::trim(" blah ") == "blah");
+ assert (str::trim("\nwut \u3000 ") == "wut");
+ assert (str::trim(" hey dude ") == "hey dude");
}
#[test]
fn is_whitespace() {
- assert str::is_whitespace("");
- assert str::is_whitespace(" ");
- assert str::is_whitespace("\u2009"); // Thin space
- assert str::is_whitespace(" \n\t ");
- assert !str::is_whitespace(" _ ");
+ assert (str::is_whitespace(""));
+ assert (str::is_whitespace(" "));
+ assert (str::is_whitespace("\u2009")); // Thin space
+ assert (str::is_whitespace(" \n\t "));
+ assert (!str::is_whitespace(" _ "));
}
// Local Variables:
assert (str::eq(s_cstr, s));
let s_buf = str::str_from_buf(sb, 5u);
assert (str::eq(s_buf, s));
-}
\ No newline at end of file
+}
#[test]
fn test_lib_spawn2() {
- fn foo(x : int) { assert(x == 42); }
+ fn foo(x: int) { assert (x == 42); }
task::_spawn(bind foo(42));
}
log_err "received task status message";
log_err s;
alt s {
- task::exit(_, task::tr_success.) { /* yay! */ }
+ task::exit(_, task::tr_success.) {/* yay! */ }
_ { fail "invalid task status received" }
}
}
log_err "received task status message";
log_err s;
alt s {
- task::exit(_, task::tr_failure.) { /* yay! */ }
+ task::exit(_, task::tr_failure.) {/* yay! */ }
_ { fail "invalid task status received" }
}
}
fn winner() { }
let f = winner;
let handle = task::spawn_joinable(f);
- assert(task::tr_success == task::join(handle));
+ assert (task::tr_success == task::join(handle));
}
#[test]
fn first_free_arg_should_be_a_filter() {
- let args = ~["progname", "filter"];
+ let args = ["progname", "filter"];
check (vec::is_not_empty(args));
let opts = alt test::parse_opts(args) { either::left(o) { o } };
assert (str::eq("filter", option::get(opts.filter)));
#[test]
fn parse_ignored_flag() {
- let args = ~["progname", "filter", "--ignored"];
+ let args = ["progname", "filter", "--ignored"];
check (vec::is_not_empty(args));
let opts = alt test::parse_opts(args) { either::left(o) { o } };
assert (opts.run_ignored);
let opts = {filter: option::none, run_ignored: true};
let tests =
- ~[{name: "1", fn: fn () { }, ignore: true},
- {name: "2", fn: fn () { }, ignore: false}];
+ [{name: "1", fn: fn () { }, ignore: true},
+ {name: "2", fn: fn () { }, ignore: false}];
let filtered = test::filter_tests(opts, tests);
assert (vec::len(filtered) == 1u);
- assert (filtered.(0).name == "1");
- assert (filtered.(0).ignore == false);
+ assert (filtered[0].name == "1");
+ assert (filtered[0].ignore == false);
}
#[test]
let opts = {filter: option::none, run_ignored: false};
let names =
- ~["sha1::test", "int::test_to_str", "int::test_pow",
- "test::do_not_run_ignored_tests",
- "test::ignored_tests_result_in_ignored",
- "test::first_free_arg_should_be_a_filter",
- "test::parse_ignored_flag", "test::filter_for_ignored_option",
- "test::sort_tests"];
+ ["sha1::test", "int::test_to_str", "int::test_pow",
+ "test::do_not_run_ignored_tests",
+ "test::ignored_tests_result_in_ignored",
+ "test::first_free_arg_should_be_a_filter",
+ "test::parse_ignored_flag", "test::filter_for_ignored_option",
+ "test::sort_tests"];
let tests =
{
let testfn = fn () { };
- let tests = ~[];
+ let tests = [];
for name: str in names {
let test = {name: name, fn: testfn, ignore: false};
- tests += ~[test];
+ tests += [test];
}
tests
};
let filtered = test::filter_tests(opts, tests);
let expected =
- ~["int::test_pow", "int::test_to_str", "sha1::test",
- "test::do_not_run_ignored_tests", "test::filter_for_ignored_option",
- "test::first_free_arg_should_be_a_filter",
- "test::ignored_tests_result_in_ignored", "test::parse_ignored_flag",
- "test::sort_tests"];
+ ["int::test_pow", "int::test_to_str", "sha1::test",
+ "test::do_not_run_ignored_tests", "test::filter_for_ignored_option",
+ "test::first_free_arg_should_be_a_filter",
+ "test::ignored_tests_result_in_ignored", "test::parse_ignored_flag",
+ "test::sort_tests"];
let pairs = vec::zip(expected, filtered);
- for (a, b) in pairs {
- assert (a == b.name);
- }
+ for (a, b) in pairs { assert (a == b.name); }
}
// Local Variables:
assert (uint::next_power_of_two(37u) == 64u);
assert (uint::next_power_of_two(38u) == 64u);
assert (uint::next_power_of_two(39u) == 64u);
-}
\ No newline at end of file
+}
#[test]
fn test_reserve_and_on_heap() {
- let v: [int] = ~[1, 2];
+ let v: [int] = [1, 2];
assert (!vec::on_heap(v));
vec::reserve(v, 8u);
assert (vec::on_heap(v));
#[test]
fn test_unsafe_ptrs() {
// Test on-stack copy-from-buf.
- let a = ~[1, 2, 3];
+ let a = [1, 2, 3];
let ptr = vec::to_ptr(a);
- let b = ~[];
+ let b = [];
vec::unsafe::copy_from_buf(b, ptr, 3u);
assert (vec::len(b) == 3u);
- assert (b.(0) == 1);
- assert (b.(1) == 2);
- assert (b.(2) == 3);
+ assert (b[0] == 1);
+ assert (b[1] == 2);
+ assert (b[2] == 3);
// Test on-heap copy-from-buf.
- let c = ~[1, 2, 3, 4, 5];
+ let c = [1, 2, 3, 4, 5];
ptr = vec::to_ptr(c);
- let d = ~[];
+ let d = [];
vec::unsafe::copy_from_buf(d, ptr, 5u);
assert (vec::len(d) == 5u);
- assert (d.(0) == 1);
- assert (d.(1) == 2);
- assert (d.(2) == 3);
- assert (d.(3) == 4);
- assert (d.(4) == 5);
+ assert (d[0] == 1);
+ assert (d[1] == 2);
+ assert (d[2] == 3);
+ assert (d[3] == 4);
+ assert (d[4] == 5);
}
#[test]
// Test on-stack init_fn.
let v = vec::init_fn(square, 3u);
assert (vec::len(v) == 3u);
- assert (v.(0) == 0u);
- assert (v.(1) == 1u);
- assert (v.(2) == 4u);
+ assert (v[0] == 0u);
+ assert (v[1] == 1u);
+ assert (v[2] == 4u);
// Test on-heap init_fn.
v = vec::init_fn(square, 5u);
assert (vec::len(v) == 5u);
- assert (v.(0) == 0u);
- assert (v.(1) == 1u);
- assert (v.(2) == 4u);
- assert (v.(3) == 9u);
- assert (v.(4) == 16u);
+ assert (v[0] == 0u);
+ assert (v[1] == 1u);
+ assert (v[2] == 4u);
+ assert (v[3] == 9u);
+ assert (v[4] == 16u);
}
#[test]
// Test on-stack init_elt.
let v = vec::init_elt(10u, 2u);
assert (vec::len(v) == 2u);
- assert (v.(0) == 10u);
- assert (v.(1) == 10u);
+ assert (v[0] == 10u);
+ assert (v[1] == 10u);
// Test on-heap init_elt.
v = vec::init_elt(20u, 6u);
- assert (v.(0) == 20u);
- assert (v.(1) == 20u);
- assert (v.(2) == 20u);
- assert (v.(3) == 20u);
- assert (v.(4) == 20u);
- assert (v.(5) == 20u);
+ assert (v[0] == 20u);
+ assert (v[1] == 20u);
+ assert (v[2] == 20u);
+ assert (v[3] == 20u);
+ assert (v[4] == 20u);
+ assert (v[5] == 20u);
}
#[test]
fn test_is_empty() {
- assert (vec::is_empty::<int>(~[]));
- assert (!vec::is_empty(~[0]));
+ assert (vec::is_empty::<int>([]));
+ assert (!vec::is_empty([0]));
}
#[test]
fn test_is_not_empty() {
- assert (vec::is_not_empty(~[0]));
- assert (!vec::is_not_empty::<int>(~[]));
+ assert (vec::is_not_empty([0]));
+ assert (!vec::is_not_empty::<int>([]));
}
#[test]
fn test_head() {
- let a = ~[11, 12];
+ let a = [11, 12];
check (vec::is_not_empty(a));
assert (vec::head(a) == 11);
}
#[test]
fn test_tail() {
- let a = ~[11];
+ let a = [11];
check (vec::is_not_empty(a));
- assert (vec::tail(a) == ~[]);
+ assert (vec::tail(a) == []);
- a = ~[11, 12];
+ a = [11, 12];
check (vec::is_not_empty(a));
- assert (vec::tail(a) == ~[12]);
+ assert (vec::tail(a) == [12]);
}
#[test]
fn test_last() {
- let n = vec::last(~[]);
+ let n = vec::last([]);
assert (n == none);
- n = vec::last(~[1, 2, 3]);
+ n = vec::last([1, 2, 3]);
assert (n == some(3));
- n = vec::last(~[1, 2, 3, 4, 5]);
+ n = vec::last([1, 2, 3, 4, 5]);
assert (n == some(5));
}
#[test]
fn test_slice() {
// Test on-stack -> on-stack slice.
- let v = vec::slice(~[1, 2, 3], 1u, 3u);
+ let v = vec::slice([1, 2, 3], 1u, 3u);
assert (vec::len(v) == 2u);
- assert (v.(0) == 2);
- assert (v.(1) == 3);
+ assert (v[0] == 2);
+ assert (v[1] == 3);
// Test on-heap -> on-stack slice.
- v = vec::slice(~[1, 2, 3, 4, 5], 0u, 3u);
+ v = vec::slice([1, 2, 3, 4, 5], 0u, 3u);
assert (vec::len(v) == 3u);
- assert (v.(0) == 1);
- assert (v.(1) == 2);
- assert (v.(2) == 3);
+ assert (v[0] == 1);
+ assert (v[1] == 2);
+ assert (v[2] == 3);
// Test on-heap -> on-heap slice.
- v = vec::slice(~[1, 2, 3, 4, 5, 6], 1u, 6u);
+ v = vec::slice([1, 2, 3, 4, 5, 6], 1u, 6u);
assert (vec::len(v) == 5u);
- assert (v.(0) == 2);
- assert (v.(1) == 3);
- assert (v.(2) == 4);
- assert (v.(3) == 5);
- assert (v.(4) == 6);
+ assert (v[0] == 2);
+ assert (v[1] == 3);
+ assert (v[2] == 4);
+ assert (v[3] == 5);
+ assert (v[4] == 6);
}
#[test]
fn test_pop() {
// Test on-stack pop.
- let v = ~[1, 2, 3];
+ let v = [1, 2, 3];
let e = vec::pop(v);
assert (vec::len(v) == 2u);
- assert (v.(0) == 1);
- assert (v.(1) == 2);
+ assert (v[0] == 1);
+ assert (v[1] == 2);
assert (e == 3);
// Test on-heap pop.
- v = ~[1, 2, 3, 4, 5];
+ v = [1, 2, 3, 4, 5];
e = vec::pop(v);
assert (vec::len(v) == 4u);
- assert (v.(0) == 1);
- assert (v.(1) == 2);
- assert (v.(2) == 3);
- assert (v.(3) == 4);
+ assert (v[0] == 1);
+ assert (v[1] == 2);
+ assert (v[2] == 3);
+ assert (v[3] == 4);
assert (e == 5);
}
#[test]
fn test_grow() {
// Test on-stack grow().
- let v = ~[];
+ let v = [];
vec::grow(v, 2u, 1);
assert (vec::len(v) == 2u);
- assert (v.(0) == 1);
- assert (v.(1) == 1);
+ assert (v[0] == 1);
+ assert (v[1] == 1);
// Test on-heap grow().
vec::grow(v, 3u, 2);
assert (vec::len(v) == 5u);
- assert (v.(0) == 1);
- assert (v.(1) == 1);
- assert (v.(2) == 2);
- assert (v.(3) == 2);
- assert (v.(4) == 2);
+ assert (v[0] == 1);
+ assert (v[1] == 1);
+ assert (v[2] == 2);
+ assert (v[3] == 2);
+ assert (v[4] == 2);
}
#[test]
fn test_grow_fn() {
- let v = ~[];
+ let v = [];
vec::grow_fn(v, 3u, square);
assert (vec::len(v) == 3u);
- assert (v.(0) == 0u);
- assert (v.(1) == 1u);
- assert (v.(2) == 4u);
+ assert (v[0] == 0u);
+ assert (v[1] == 1u);
+ assert (v[2] == 4u);
}
#[test]
fn test_grow_set() {
- let v = ~[mutable 1, 2, 3];
+ let v = [mutable 1, 2, 3];
vec::grow_set(v, 4u, 4, 5);
assert (vec::len(v) == 5u);
- assert (v.(0) == 1);
- assert (v.(1) == 2);
- assert (v.(2) == 3);
- assert (v.(3) == 4);
- assert (v.(4) == 5);
+ assert (v[0] == 1);
+ assert (v[1] == 2);
+ assert (v[2] == 3);
+ assert (v[3] == 4);
+ assert (v[4] == 5);
}
#[test]
fn test_map() {
// Test on-stack map.
- let v = ~[1u, 2u, 3u];
+ let v = [1u, 2u, 3u];
let w = vec::map(square_alias, v);
assert (vec::len(w) == 3u);
- assert (w.(0) == 1u);
- assert (w.(1) == 4u);
- assert (w.(2) == 9u);
+ assert (w[0] == 1u);
+ assert (w[1] == 4u);
+ assert (w[2] == 9u);
// Test on-heap map.
- v = ~[1u, 2u, 3u, 4u, 5u];
+ v = [1u, 2u, 3u, 4u, 5u];
w = vec::map(square_alias, v);
assert (vec::len(w) == 5u);
- assert (w.(0) == 1u);
- assert (w.(1) == 4u);
- assert (w.(2) == 9u);
- assert (w.(3) == 16u);
- assert (w.(4) == 25u);
+ assert (w[0] == 1u);
+ assert (w[1] == 4u);
+ assert (w[2] == 9u);
+ assert (w[3] == 16u);
+ assert (w[4] == 25u);
}
#[test]
fn test_map2() {
fn times(x: &int, y: &int) -> int { ret x * y; }
let f = times;
- let v0 = ~[1, 2, 3, 4, 5];
- let v1 = ~[5, 4, 3, 2, 1];
+ let v0 = [1, 2, 3, 4, 5];
+ let v1 = [5, 4, 3, 2, 1];
let u = vec::map2::<int, int, int>(f, v0, v1);
let i = 0;
- while i < 5 { assert (v0.(i) * v1.(i) == u.(i)); i += 1; }
+ while i < 5 { assert (v0[i] * v1[i] == u[i]); i += 1; }
}
#[test]
fn test_filter_map() {
// Test on-stack filter-map.
- let v = ~[1u, 2u, 3u];
+ let v = [1u, 2u, 3u];
let w = vec::filter_map(square_if_odd, v);
assert (vec::len(w) == 2u);
- assert (w.(0) == 1u);
- assert (w.(1) == 9u);
+ assert (w[0] == 1u);
+ assert (w[1] == 9u);
// Test on-heap filter-map.
- v = ~[1u, 2u, 3u, 4u, 5u];
+ v = [1u, 2u, 3u, 4u, 5u];
w = vec::filter_map(square_if_odd, v);
assert (vec::len(w) == 3u);
- assert (w.(0) == 1u);
- assert (w.(1) == 9u);
- assert (w.(2) == 25u);
+ assert (w[0] == 1u);
+ assert (w[1] == 9u);
+ assert (w[2] == 25u);
fn halve(i: &int) -> option::t<int> {
if i % 2 == 0 {
} else { ret option::none::<int>; }
}
fn halve_for_sure(i: &int) -> int { ret i / 2; }
- let all_even: [int] = ~[0, 2, 8, 6];
- let all_odd1: [int] = ~[1, 7, 3];
- let all_odd2: [int] = ~[];
- let mix: [int] = ~[9, 2, 6, 7, 1, 0, 0, 3];
- let mix_dest: [int] = ~[1, 3, 0, 0];
+ let all_even: [int] = [0, 2, 8, 6];
+ let all_odd1: [int] = [1, 7, 3];
+ let all_odd2: [int] = [];
+ let mix: [int] = [9, 2, 6, 7, 1, 0, 0, 3];
+ let mix_dest: [int] = [1, 3, 0, 0];
assert (filter_map(halve, all_even) == map(halve_for_sure, all_even));
- assert (filter_map(halve, all_odd1) == ~[]);
- assert (filter_map(halve, all_odd2) == ~[]);
+ assert (filter_map(halve, all_odd1) == []);
+ assert (filter_map(halve, all_odd2) == []);
assert (filter_map(halve, mix) == mix_dest);
}
#[test]
fn test_foldl() {
// Test on-stack fold.
- let v = ~[1u, 2u, 3u];
+ let v = [1u, 2u, 3u];
let sum = vec::foldl(add, 0u, v);
assert (sum == 6u);
// Test on-heap fold.
- v = ~[1u, 2u, 3u, 4u, 5u];
+ v = [1u, 2u, 3u, 4u, 5u];
sum = vec::foldl(add, 0u, v);
assert (sum == 15u);
}
#[test]
fn test_any_and_all() {
- assert (vec::any(is_three, ~[1u, 2u, 3u]));
- assert (!vec::any(is_three, ~[0u, 1u, 2u]));
- assert (vec::any(is_three, ~[1u, 2u, 3u, 4u, 5u]));
- assert (!vec::any(is_three, ~[1u, 2u, 4u, 5u, 6u]));
-
- assert (vec::all(is_three, ~[3u, 3u, 3u]));
- assert (!vec::all(is_three, ~[3u, 3u, 2u]));
- assert (vec::all(is_three, ~[3u, 3u, 3u, 3u, 3u]));
- assert (!vec::all(is_three, ~[3u, 3u, 0u, 1u, 2u]));
+ assert (vec::any(is_three, [1u, 2u, 3u]));
+ assert (!vec::any(is_three, [0u, 1u, 2u]));
+ assert (vec::any(is_three, [1u, 2u, 3u, 4u, 5u]));
+ assert (!vec::any(is_three, [1u, 2u, 4u, 5u, 6u]));
+
+ assert (vec::all(is_three, [3u, 3u, 3u]));
+ assert (!vec::all(is_three, [3u, 3u, 2u]));
+ assert (vec::all(is_three, [3u, 3u, 3u, 3u, 3u]));
+ assert (!vec::all(is_three, [3u, 3u, 0u, 1u, 2u]));
}
#[test]
fn test_zip_unzip() {
- let v1 = ~[1, 2, 3];
- let v2 = ~[4, 5, 6];
+ let v1 = [1, 2, 3];
+ let v2 = [4, 5, 6];
let z1 = vec::zip(v1, v2);
- assert ((1, 4) == z1.(0));
- assert ((2, 5) == z1.(1));
- assert ((3, 6) == z1.(2));
+ assert ((1, 4) == z1[0]);
+ assert ((2, 5) == z1[1]);
+ assert ((3, 6) == z1[2]);
let (left, right) = vec::unzip(z1);
- assert ((1, 4) == (left.(0), right.(0)));
- assert ((2, 5) == (left.(1), right.(1)));
- assert ((3, 6) == (left.(2), right.(2)));
+ assert ((1, 4) == (left[0], right[0]));
+ assert ((2, 5) == (left[1], right[1]));
+ assert ((3, 6) == (left[2], right[2]));
}
#[test]
fn test_position() {
- let v1: [int] = ~[1, 2, 3, 3, 2, 5];
+ let v1: [int] = [1, 2, 3, 3, 2, 5];
assert (position(1, v1) == option::some::<uint>(0u));
assert (position(2, v1) == option::some::<uint>(1u));
assert (position(5, v1) == option::some::<uint>(5u));
fn test_position_pred() {
fn less_than_three(i: &int) -> bool { ret i < 3; }
fn is_eighteen(i: &int) -> bool { ret i == 18; }
- let v1: [int] = ~[5, 4, 3, 2, 1];
+ let v1: [int] = [5, 4, 3, 2, 1];
assert (position_pred(less_than_three, v1) == option::some::<uint>(3u));
assert (position_pred(is_eighteen, v1) == option::none::<uint>);
}
#[test]
fn reverse_and_reversed() {
- let v: [mutable int] = ~[mutable 10, 20];
- assert (v.(0) == 10);
- assert (v.(1) == 20);
+ let v: [mutable int] = [mutable 10, 20];
+ assert (v[0] == 10);
+ assert (v[1] == 20);
vec::reverse(v);
- assert (v.(0) == 20);
- assert (v.(1) == 10);
- let v2 = vec::reversed::<int>(~[10, 20]);
- assert (v2.(0) == 20);
- assert (v2.(1) == 10);
- v.(0) = 30;
- assert (v2.(0) == 20);
+ assert (v[0] == 20);
+ assert (v[1] == 10);
+ let v2 = vec::reversed::<int>([10, 20]);
+ assert (v2[0] == 20);
+ assert (v2[1] == 10);
+ v[0] = 30;
+ assert (v2[0] == 20);
// Make sure they work with 0-length vectors too.
- let v4 = vec::reversed::<int>(~[]);
- let v3: [mutable int] = ~[mutable];
+ let v4 = vec::reversed::<int>([]);
+ let v3: [mutable int] = [mutable];
vec::reverse::<int>(v3);
}
let n2: uint = vec::len::<u8>(v);
assert (n1 == n2);
while i < n1 {
- let a: u8 = s1.(i);
- let b: u8 = s2.(i);
+ let a: u8 = s1[i];
+ let b: u8 = s2[i];
log a;
log b;
assert (a == b);