const abi_version: uint = 1u;
-fn memcpy_glue_name() -> istr { ret ~"rust_memcpy_glue"; }
+fn memcpy_glue_name() -> str { ret "rust_memcpy_glue"; }
-fn bzero_glue_name() -> istr { ret ~"rust_bzero_glue"; }
+fn bzero_glue_name() -> str { ret "rust_bzero_glue"; }
-fn yield_glue_name() -> istr { ret ~"rust_yield_glue"; }
+fn yield_glue_name() -> str { ret "rust_yield_glue"; }
-fn no_op_type_glue_name() -> istr { ret ~"rust_no_op_type_glue"; }
+fn no_op_type_glue_name() -> str { ret "rust_no_op_type_glue"; }
//
// Local Variables:
// mode: rust
output_type_exe;
}
-fn llvm_err(sess: session::session, msg: &istr) {
+fn llvm_err(sess: session::session, msg: &str) {
let buf = llvm::LLVMRustGetLastError();
if buf == std::ptr::null() {
sess.fatal(msg);
- } else {
- sess.fatal(
- msg + ~": " + str::str_from_cstr(buf));
- }
+ } else { sess.fatal(msg + ": " + str::str_from_cstr(buf)); }
}
fn link_intrinsics(sess: session::session, llmod: ModuleRef) {
- let path =
- fs::connect(sess.get_opts().sysroot,
- ~"lib/intrinsics.bc");
- let membuf = str::as_buf(path, { |buf|
- llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf)
- });
+ let path = fs::connect(sess.get_opts().sysroot, "lib/intrinsics.bc");
+ let membuf =
+ str::as_buf(
+ path,
+ {|buf|
+ llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf)
+ });
if membuf as uint == 0u {
- llvm_err(sess, ~"installation problem: couldn't open " + path);
+ llvm_err(sess, "installation problem: couldn't open " + path);
fail;
}
let llintrinsicsmod = llvm::LLVMRustParseBitcode(membuf);
llvm::LLVMDisposeMemoryBuffer(membuf);
if llintrinsicsmod as uint == 0u {
- llvm_err(sess, ~"installation problem: couldn't parse intrinsics.bc");
+ llvm_err(sess, "installation problem: couldn't parse intrinsics.bc");
fail;
}
let linkres = llvm::LLVMLinkModules(llmod, llintrinsicsmod);
llvm::LLVMDisposeModule(llintrinsicsmod);
if linkres == False {
- llvm_err(sess, ~"couldn't link the module with the intrinsics");
+ llvm_err(sess, "couldn't link the module with the intrinsics");
fail;
}
}
// Decides what to call an intermediate file, given the name of the output
// and the extension to use.
- fn mk_intermediate_name(output_path: &istr, extension: &istr) -> istr {
+ fn mk_intermediate_name(output_path: &str, extension: &str) -> str {
let dot_pos = str::index(output_path, '.' as u8);
let stem;
if dot_pos < 0 {
stem = output_path;
} else { stem = str::substr(output_path, 0u, dot_pos as uint); }
- ret stem + ~"." + extension;
+ ret stem + "." + extension;
}
- fn run_passes(sess: session::session, llmod: ModuleRef, output: &istr) {
+ fn run_passes(sess: session::session, llmod: ModuleRef, output: &str) {
let opts = sess.get_opts();
if opts.time_llvm_passes { llvm::LLVMRustEnableTimePasses(); }
link_intrinsics(sess, llmod);
alt opts.output_type {
output_type_bitcode. {
if opts.optimize != 0u {
- let filename = mk_intermediate_name(output, ~"no-opt.bc");
- str::as_buf(filename, { |buf|
- llvm::LLVMWriteBitcodeToFile(llmod, buf)
- });
+ let filename = mk_intermediate_name(output, "no-opt.bc");
+ str::as_buf(filename,
+ {|buf|
+ llvm::LLVMWriteBitcodeToFile(llmod, buf)
+ });
}
}
_ {
- let filename = mk_intermediate_name(output, ~"bc");
- str::as_buf(filename, { |buf|
- llvm::LLVMWriteBitcodeToFile(llmod, buf)
- });
+ let filename = mk_intermediate_name(output, "bc");
+ str::as_buf(filename,
+ {|buf|
+ llvm::LLVMWriteBitcodeToFile(llmod, buf)
+ });
}
}
}
if opts.save_temps {
// Always output the bitcode file with --save-temps
- let filename = mk_intermediate_name(output, ~"opt.bc");
+ let filename = mk_intermediate_name(output, "opt.bc");
llvm::LLVMRunPassManager(pm.llpm, llmod);
- str::as_buf(filename, { |buf|
- llvm::LLVMWriteBitcodeToFile(llmod, buf)
- });
+ str::as_buf(filename,
+ {|buf|
+ llvm::LLVMWriteBitcodeToFile(llmod, buf)
+ });
pm = mk_pass_manager();
// Save the assembly file if -S is used
if opts.output_type == output_type_assembly {
let _: () =
- str::as_buf(x86::get_target_triple(), { |buf_t|
- str::as_buf(output, { |buf_o|
+ str::as_buf(x86::get_target_triple(), {|buf_t|
+ str::as_buf(output, {|buf_o|
llvm::LLVMRustWriteOutputFile(
- pm.llpm, llmod,
+ pm.llpm,
+ llmod,
buf_t,
buf_o,
LLVMAssemblyFile,
CodeGenOptLevel)
- })});
+ })
+ });
}
if opts.output_type == output_type_object ||
opts.output_type == output_type_exe {
let _: () =
- str::as_buf(x86::get_target_triple(), { |buf_t|
- str::as_buf(output, { |buf_o|
- llvm::LLVMRustWriteOutputFile(
- pm.llpm, llmod,
- buf_t,
- buf_o,
- LLVMObjectFile,
- CodeGenOptLevel)
- })});
+ str::as_buf(x86::get_target_triple(), {|buf_t|
+ str::as_buf(output, {|buf_o|
+ llvm::LLVMRustWriteOutputFile(pm.llpm,
+ llmod,
+ buf_t,
+ buf_o,
+ LLVMObjectFile,
+ CodeGenOptLevel)
+ })
+ });
}
} else {
// If we aren't saving temps then just output the file
// type corresponding to the '-c' or '-S' flag used
- let _: () = str::as_buf(x86::get_target_triple(), { |buf_t|
- str::as_buf(output, { |buf_o|
- llvm::LLVMRustWriteOutputFile(pm.llpm, llmod,
- buf_t,
- buf_o,
- FileType,
- CodeGenOptLevel)
- })});
+ let _: () =
+ str::as_buf(x86::get_target_triple(), {|buf_t|
+ str::as_buf(output, {|buf_o|
+ llvm::LLVMRustWriteOutputFile(pm.llpm,
+ llmod,
+ buf_t,
+ buf_o,
+ FileType,
+ CodeGenOptLevel)
+ })
+ });
}
// Clean up and return
// flag, then output it here
llvm::LLVMRunPassManager(pm.llpm, llmod);
- str::as_buf(output, { |buf|
- llvm::LLVMWriteBitcodeToFile(llmod, buf)
- });
+ str::as_buf(output,
+ {|buf| llvm::LLVMWriteBitcodeToFile(llmod, buf) });
llvm::LLVMDisposeModule(llmod);
if opts.time_llvm_passes { llvm::LLVMRustPrintPassTimings(); }
}
*
*/
-type link_meta = {name: istr, vers: istr, extras_hash: istr};
+type link_meta = {name: str, vers: str, extras_hash: str};
-fn build_link_meta(sess: &session::session, c: &ast::crate, output: &istr,
+fn build_link_meta(sess: &session::session, c: &ast::crate, output: &str,
sha: sha1) -> link_meta {
type provided_metas =
- {name: option::t<istr>,
- vers: option::t<istr>,
+ {name: option::t<str>,
+ vers: option::t<str>,
cmh_items: [@ast::meta_item]};
fn provided_link_metas(sess: &session::session, c: &ast::crate) ->
provided_metas {
- let name: option::t<istr> = none;
- let vers: option::t<istr> = none;
+ let name: option::t<str> = none;
+ let vers: option::t<str> = none;
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" {
+ 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]; }
}
- } 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]; }
// This calculates CMH as defined above
fn crate_meta_extras_hash(sha: sha1, _crate: &ast::crate,
- metas: &provided_metas) -> istr {
- fn len_and_str(s: &istr) -> istr {
+ metas: &provided_metas) -> str {
+ fn len_and_str(s: &str) -> str {
ret #fmt["%u_%s", str::byte_len(s), s];
}
- fn len_and_str_lit(l: &ast::lit) -> istr {
+ fn len_and_str_lit(l: &ast::lit) -> str {
ret len_and_str(pprust::lit_to_str(@l));
}
sha.input_str(len_and_str(key));
sha.input_str(len_and_str_lit(value));
}
- ast::meta_word(name) {
- sha.input_str(len_and_str(name));
- }
+ ast::meta_word(name) { sha.input_str(len_and_str(name)); }
ast::meta_list(_, _) {
// FIXME (#607): Implement this
fail "unimplemented meta_item variant";
ret truncated_sha1_result(sha);
}
- fn warn_missing(sess: &session::session, name: &istr, default: &istr) {
+ 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",
+ sess.warn(#fmt["missing crate link meta '%s', using '%s' as default",
name, default]);
}
fn crate_meta_name(sess: &session::session, _crate: &ast::crate,
- output: &istr, metas: &provided_metas) -> istr {
+ output: &str, metas: &provided_metas) -> str {
ret alt metas.name {
some(v) { v }
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, ~".")
+ str::connect(os, ".")
};
- warn_missing(sess, ~"name", name);
+ warn_missing(sess, "name", name);
name
}
};
}
fn crate_meta_vers(sess: &session::session, _crate: &ast::crate,
- metas: &provided_metas) -> istr {
+ metas: &provided_metas) -> str {
ret alt metas.vers {
some(v) { v }
none. {
- let vers = ~"0.0";
- warn_missing(sess, ~"vers", vers);
+ let vers = "0.0";
+ warn_missing(sess, "vers", vers);
vers
}
};
ret {name: name, vers: vers, extras_hash: extras_hash};
}
-fn truncated_sha1_result(sha: sha1) -> istr {
+fn truncated_sha1_result(sha: sha1) -> str {
ret str::substr(sha.result_str(), 0u, 16u);
}
// This calculates STH for a symbol, as defined above
fn symbol_hash(tcx: ty::ctxt, sha: sha1, t: ty::t, link_meta: &link_meta) ->
- istr {
+ str {
// NB: do *not* use abbrevs here as we want the symbol names
// to be independent of one another in the crate.
sha.reset();
sha.input_str(link_meta.name);
- sha.input_str(~"-");
+ sha.input_str("-");
// FIXME: This wants to be link_meta.meta_hash
sha.input_str(link_meta.name);
- sha.input_str(~"-");
+ sha.input_str("-");
sha.input_str(encoder::encoded_ty(tcx, t));
let hash = truncated_sha1_result(sha);
// Prefix with _ so that it never blends into adjacent digits
- ret ~"_" + hash;
+ ret "_" + hash;
}
-fn get_symbol_hash(ccx: &@crate_ctxt, t: ty::t) -> istr {
- let hash = ~"";
+fn get_symbol_hash(ccx: &@crate_ctxt, t: ty::t) -> str {
+ let hash = "";
alt ccx.type_sha1s.find(t) {
some(h) { hash = h; }
none. {
ret hash;
}
-fn mangle(ss: &[istr]) -> istr {
+fn mangle(ss: &[str]) -> str {
// Follow C++ namespace-mangling style
- let n = ~"_ZN"; // Begin name-sequence.
+ let n = "_ZN"; // Begin name-sequence.
- for s: istr in ss {
- n += #fmt["%u%s", str::byte_len(s), s];
- }
- n += ~"E"; // End name-sequence.
+ 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: &[istr], hash: &istr, _vers: &istr) -> istr {
+fn exported_name(path: &[str], hash: &str, _vers: &str) -> str {
// FIXME: versioning isn't working yet
ret mangle(path + [hash]); // + "@" + vers;
}
-fn mangle_exported_name(ccx: &@crate_ctxt, path: &[istr], t: ty::t) -> istr {
+fn mangle_exported_name(ccx: &@crate_ctxt, path: &[str], t: ty::t) -> str {
let hash = get_symbol_hash(ccx, t);
ret exported_name(path, hash, ccx.link_meta.vers);
}
-fn mangle_internal_name_by_type_only(ccx: &@crate_ctxt, t: ty::t, name: &istr)
- -> istr {
+fn mangle_internal_name_by_type_only(ccx: &@crate_ctxt, t: ty::t, name: &str)
+ -> str {
let s = util::ppaux::ty_to_short_str(ccx.tcx, t);
let hash = get_symbol_hash(ccx, t);
ret mangle([name, s, hash]);
}
-fn mangle_internal_name_by_path_and_seq(ccx: &@crate_ctxt, path: &[istr],
- flav: &istr) -> istr {
+fn mangle_internal_name_by_path_and_seq(ccx: &@crate_ctxt, path: &[str],
+ flav: &str) -> str {
ret mangle(path + [ccx.names.next(flav)]);
}
-fn mangle_internal_name_by_path(_ccx: &@crate_ctxt, path: &[istr]) -> istr {
+fn mangle_internal_name_by_path(_ccx: &@crate_ctxt, path: &[str]) -> str {
ret mangle(path);
}
-fn mangle_internal_name_by_seq(ccx: &@crate_ctxt, flav: &istr) -> istr {
+fn mangle_internal_name_by_seq(ccx: &@crate_ctxt, flav: &str) -> str {
ret ccx.names.next(flav);
}
//
fn declare_upcalls(_tn: type_names, tydesc_type: TypeRef,
taskptr_type: TypeRef, llmod: ModuleRef) -> @upcalls {
- fn decl(llmod: ModuleRef, name: &istr, tys: [TypeRef], rv: TypeRef) ->
+ 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);
+ ret trans::decl_cdecl_fn(llmod, "upcall_" + name, fn_ty);
}
- fn decl_with_taskptr(taskptr_type: TypeRef, llmod: ModuleRef,
- name: &istr,
+ 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 dr = bind decl(llmod, _, _, _);
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]),
- exit: dv(~"exit", empty_vec),
+ 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]),
+ 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()),
+ shared_free: dv("shared_free", [T_ptr(T_i8())]),
+ mark: d("mark", [T_ptr(T_i8())], T_int()),
get_type_desc:
- d(~"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_int()], T_ptr(tydesc_type)),
vec_grow:
- d(~"vec_grow", [T_ptr(T_ptr(T_opaque_vec())), T_int()],
+ d("vec_grow", [T_ptr(T_ptr(T_opaque_vec())), T_int()],
T_void()),
vec_push:
- d(~"vec_push",
+ d("vec_push",
[T_ptr(T_ptr(T_opaque_vec())), T_ptr(tydesc_type),
T_ptr(T_i8())], T_void()),
cmp_type:
- dr(~"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()),
log_type:
- dr(~"log_type",
+ 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_2",
- [T_size_t(), T_ptr(tydesc_type)], 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_2", [T_size_t(), T_ptr(tydesc_type)],
+ T_ptr(T_i8())),
+ dynastack_free: d("dynastack_free", [T_ptr(T_i8())], T_void())};
}
//
// Local Variables:
import std::str;
import std::os::target_os;
-fn get_module_asm() -> istr { ret ~""; }
+fn get_module_asm() -> str { ret ""; }
-fn get_meta_sect_name() -> istr {
- if str::eq(target_os(), ~"macos") { ret ~"__DATA,__note.rustc"; }
- if str::eq(target_os(), ~"win32") { ret ~".note.rustc"; }
- ret ~".note.rustc";
+fn get_meta_sect_name() -> str {
+ if str::eq(target_os(), "macos") { ret "__DATA,__note.rustc"; }
+ if str::eq(target_os(), "win32") { ret ".note.rustc"; }
+ ret ".note.rustc";
}
-fn get_data_layout() -> istr {
- if str::eq(target_os(), ~"macos") {
- ret ~"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16" +
- ~"-i32:32:32-i64:32:64" +
- ~"-f32:32:32-f64:32:64-v64:64:64" +
- ~"-v128:128:128-a0:0:64-f80:128:128" +
- ~"-n8:16:32";
+fn get_data_layout() -> str {
+ if str::eq(target_os(), "macos") {
+ ret "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16" + "-i32:32:32-i64:32:64" +
+ "-f32:32:32-f64:32:64-v64:64:64" +
+ "-v128:128:128-a0:0:64-f80:128:128" + "-n8:16:32";
}
- if str::eq(target_os(), ~"win32") {
- ret ~"e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32";
+ if str::eq(target_os(), "win32") {
+ ret "e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32";
}
- ret ~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32";
+ ret "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32";
}
-fn get_target_triple() -> istr {
- if str::eq(target_os(), ~"macos") { ret ~"i686-apple-darwin"; }
- if str::eq(target_os(), ~"win32") { ret ~"i686-pc-mingw32"; }
- ret ~"i686-unknown-linux-gnu";
+fn get_target_triple() -> str {
+ if str::eq(target_os(), "macos") { ret "i686-apple-darwin"; }
+ if str::eq(target_os(), "win32") { ret "i686-pc-mingw32"; }
+ ret "i686-unknown-linux-gnu";
}
//
// Local Variables:
tag pp_mode { ppm_normal; ppm_expanded; ppm_typed; ppm_identified; }
-fn default_configuration(sess: session::session,
- argv0: &istr, input: &istr) ->
+fn default_configuration(sess: session::session, argv0: &str, input: &str) ->
ast::crate_cfg {
let libc =
alt sess.get_targ_cfg().os {
- session::os_win32. { ~"msvcrt.dll" }
- session::os_macos. { ~"libc.dylib" }
- session::os_linux. { ~"libc.so.6" }
- _ { ~"libc.so" }
+ session::os_win32. { "msvcrt.dll" }
+ session::os_macos. { "libc.dylib" }
+ session::os_linux. { "libc.so.6" }
+ _ { "libc.so" }
};
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),
+ 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)];
+ mk("build_compiler", argv0), mk("build_input", input)];
}
-fn build_configuration(sess: session::session, argv0: &istr, input: &istr) ->
+fn build_configuration(sess: session::session, argv0: &str, input: &str) ->
ast::crate_cfg {
// Combine the configuration requested by the session (command line) with
// some default and generated configuration items
// If the user wants a test runner, then add the test cfg
let gen_cfg =
{
- if sess.get_opts().test
- && !attr::contains_name(user_cfg, ~"test") {
- [attr::mk_word_item(~"test")]
+ if sess.get_opts().test && !attr::contains_name(user_cfg, "test")
+ {
+ [attr::mk_word_item("test")]
} else { [] }
};
ret user_cfg + gen_cfg + default_cfg;
}
// Convert strings provided as --cfg [cfgspec] into a crate_cfg
-fn parse_cfgspecs(cfgspecs: &[istr]) -> ast::crate_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: istr in cfgspecs {
- words += [attr::mk_word_item(s)];
- }
+ for s: str in cfgspecs { words += [attr::mk_word_item(s)]; }
ret words;
}
-fn input_is_stdin(filename: &istr) -> bool { filename == ~"-" }
+fn input_is_stdin(filename: &str) -> bool { filename == "-" }
-fn parse_input(sess: session::session, cfg: &ast::crate_cfg,
- input: &istr) -> @ast::crate {
+fn parse_input(sess: session::session, cfg: &ast::crate_cfg, input: &str) ->
+ @ast::crate {
if !input_is_stdin(input) {
- parser::parse_crate_from_file(
- input, cfg, sess.get_parse_sess())
+ parser::parse_crate_from_file(input, cfg, sess.get_parse_sess())
} else { parse_input_src(sess, cfg, input).crate }
}
-fn parse_input_src(sess: session::session, cfg: &ast::crate_cfg,
- infile: &istr) -> {crate: @ast::crate, src: istr} {
+fn parse_input_src(sess: session::session, cfg: &ast::crate_cfg, infile: &str)
+ -> {crate: @ast::crate, src: str} {
let srcbytes =
- if infile != ~"-" {
+ 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());
+ 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: &istr, 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();
ret rv;
}
-fn compile_input(sess: session::session, cfg: ast::crate_cfg, input: &istr,
- output: &istr) {
+fn compile_input(sess: session::session, cfg: ast::crate_cfg, input: &str,
+ output: &str) {
let time_passes = sess.get_opts().time_passes;
let crate =
- time(time_passes, ~"parsing", bind parse_input(sess, cfg, input));
+ time(time_passes, "parsing", bind parse_input(sess, cfg, input));
if sess.get_opts().parse_only { ret; }
crate =
- time(time_passes, ~"configuration",
+ time(time_passes, "configuration",
bind front::config::strip_unconfigured_items(crate));
if sess.get_opts().test {
crate =
- time(time_passes, ~"building test harness",
+ time(time_passes, "building test harness",
bind front::test::modify_for_testing(crate));
}
crate =
- time(time_passes, ~"expansion",
+ time(time_passes, "expansion",
bind syntax::ext::expand::expand_crate(sess, crate));
let ast_map =
- time(time_passes, ~"ast indexing",
+ time(time_passes, "ast indexing",
bind middle::ast_map::map_crate(*crate));
- time(time_passes, ~"external crate/lib resolution",
+ time(time_passes, "external crate/lib resolution",
bind creader::read_crates(sess, *crate));
let {def_map: def_map, ext_map: ext_map} =
- time(time_passes, ~"resolution",
+ time(time_passes, "resolution",
bind resolve::resolve_crate(sess, ast_map, crate));
let freevars =
- time(time_passes, ~"freevar finding",
+ time(time_passes, "freevar finding",
bind freevars::annotate_freevars(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));
- time(time_passes, ~"alt checking",
+ time(time_passes, "typechecking", bind typeck::check_crate(ty_cx, crate));
+ time(time_passes, "alt checking",
bind middle::check_alt::check_crate(ty_cx, crate));
if sess.get_opts().run_typestate {
- time(time_passes, ~"typestate checking",
+ time(time_passes, "typestate checking",
bind middle::tstate::ck::check_crate(ty_cx, crate));
}
- let mut_map = time(time_passes, ~"mutability checking",
- bind middle::mut::check_crate(ty_cx, crate));
- time(time_passes, ~"alias checking",
+ let mut_map =
+ time(time_passes, "mutability checking",
+ bind middle::mut::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));
+ time(time_passes, "kind checking", bind kind::check_crate(ty_cx, crate));
if sess.get_opts().no_trans { ret; }
- let llmod = time(time_passes, ~"translation",
- bind trans::trans_crate(sess, crate, ty_cx,
- output,
- ast_map, mut_map));
- time(time_passes, ~"LLVM passes",
+ let llmod =
+ time(time_passes, "translation",
+ bind trans::trans_crate(sess, crate, ty_cx, output, ast_map,
+ mut_map));
+ time(time_passes, "LLVM passes",
bind link::write::run_passes(sess, llmod, output));
}
fn pretty_print_input(sess: session::session, cfg: ast::crate_cfg,
- input: &istr, ppm: pp_mode) {
+ input: &str, ppm: pp_mode) {
fn ann_paren_for_expr(node: &pprust::ann_node) {
alt node { pprust::node_expr(s, expr) { pprust::popen(s); } _ { } }
}
alt node {
pprust::node_expr(s, expr) {
pp::space(s.s);
- pp::word(s.s, ~"as");
+ pp::word(s.s, "as");
pp::space(s.s);
- pp::word(
- s.s,
- ppaux::ty_to_str(tcx, ty::expr_ty(tcx, expr)));
+ pp::word(s.s, ppaux::ty_to_str(tcx, ty::expr_ty(tcx, expr)));
pprust::pclose(s);
}
_ { }
alt node {
pprust::node_item(s, item) {
pp::space(s.s);
- pprust::synth_comment(
- s, int::to_str(item.id, 10u));
+ pprust::synth_comment(s, int::to_str(item.id, 10u));
}
pprust::node_block(s, blk) {
pp::space(s.s);
- pprust::synth_comment(
- s, ~"block " + int::to_str(blk.node.id, 10u));
+ pprust::synth_comment(s,
+ "block " + int::to_str(blk.node.id, 10u));
}
pprust::node_expr(s, expr) {
pp::space(s.s);
- pprust::synth_comment(
- s, int::to_str(expr.id, 10u));
+ pprust::synth_comment(s, int::to_str(expr.id, 10u));
pprust::pclose(s);
}
_ { }
}
ppm_normal. { ann = pprust::no_ann(); }
}
- pprust::print_crate(sess.get_codemap(), crate,
- input,
- io::string_reader(src),
- io::stdout(), ann);
+ pprust::print_crate(sess.get_codemap(), crate, input,
+ io::string_reader(src), io::stdout(), ann);
}
-fn version(argv0: &istr) {
- let vers = ~"unknown version";
+fn version(argv0: &str) {
+ let vers = "unknown 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: &istr) {
- io::stdout().write_str(
- #fmt["usage: %s [options] <input>\n", argv0] +
- ~"
+fn usage(argv0: &str) {
+ io::stdout().write_str(#fmt["usage: %s [options] <input>\n", argv0] +
+ "
options:
-h --help display this message
");
}
-fn get_os(triple: &istr) -> session::os {
- ret if str::find(triple, ~"win32") >= 0 ||
- str::find(triple, ~"mingw32") >= 0 {
+fn get_os(triple: &str) -> session::os {
+ 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 };
+ } else { log_err "Unknown operating system!"; fail };
}
-fn get_arch(triple: &istr) -> session::arch {
- ret if str::find(triple, ~"i386") >= 0 ||
- str::find(triple, ~"i486") >= 0 ||
- str::find(triple, ~"i586") >= 0 ||
- str::find(triple, ~"i686") >= 0 ||
- str::find(triple, ~"i786") >= 0 {
+fn get_arch(triple: &str) -> session::arch {
+ ret if str::find(triple, "i386") >= 0 || str::find(triple, "i486") >= 0 ||
+ str::find(triple, "i586") >= 0 ||
+ 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 };
+ } else { log_err "Unknown architecture! " + triple; fail };
}
-fn get_default_sysroot(binary: &istr) -> istr {
+fn get_default_sysroot(binary: &str) -> str {
let dirname = fs::dirname(binary);
- if str::eq(dirname, binary) { ret ~"."; }
+ if str::eq(dirname, binary) { ret "."; }
ret dirname;
}
fn build_target_config() -> @session::config {
- let triple: istr =
- str::str_from_cstr(llvm::llvm::LLVMRustGetHostTriple());
+ let triple: str = str::str_from_cstr(llvm::llvm::LLVMRustGetHostTriple());
let target_cfg: @session::config =
@{os: get_os(triple),
arch: get_arch(triple),
ret target_cfg;
}
-fn build_session_options(binary: &istr, match: &getopts::match,
- binary_dir: &istr) -> @session::options {
- let library = opt_present(match, ~"lib");
- let static = opt_present(match, ~"static");
+fn build_session_options(binary: &str, match: &getopts::match,
+ binary_dir: &str) -> @session::options {
+ let library = opt_present(match, "lib");
+ let static = opt_present(match, "static");
- let library_search_paths = [binary_dir + ~"/lib"];
- let lsp_vec = getopts::opt_strs(match, ~"L");
- for lsp: istr in lsp_vec {
- library_search_paths += [lsp];
- }
+ 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]; }
- let parse_only = opt_present(match, ~"parse-only");
- let no_trans = opt_present(match, ~"no-trans");
+ 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");
- let save_temps = opt_present(match, ~"save-temps");
- let debuginfo = opt_present(match, ~"g");
- let stats = opt_present(match, ~"stats");
- let time_passes = opt_present(match, ~"time-passes");
- let time_llvm_passes = opt_present(match, ~"time-llvm-passes");
- let run_typestate = !opt_present(match, ~"no-typestate");
- let sysroot_opt = getopts::opt_maybe_str(match, ~"sysroot");
+ let verify = !opt_present(match, "noverify");
+ let save_temps = opt_present(match, "save-temps");
+ let debuginfo = opt_present(match, "g");
+ let stats = opt_present(match, "stats");
+ let time_passes = opt_present(match, "time-passes");
+ let time_llvm_passes = opt_present(match, "time-llvm-passes");
+ let run_typestate = !opt_present(match, "no-typestate");
+ let sysroot_opt = getopts::opt_maybe_str(match, "sysroot");
let opt_level: uint =
- if opt_present(match, ~"O") {
- if opt_present(match, ~"OptLevel") {
+ if opt_present(match, "O") {
+ if opt_present(match, "OptLevel") {
log_err "error: -O and --OptLevel both provided";
fail;
}
2u
- } else if opt_present(match, ~"OptLevel") {
- alt getopts::opt_str(match, ~"OptLevel") {
- ~"0" { 0u }
- ~"1" { 1u }
- ~"2" { 2u }
- ~"3" { 3u }
+ } else if opt_present(match, "OptLevel") {
+ alt getopts::opt_str(match, "OptLevel") {
+ "0" { 0u }
+ "1" { 1u }
+ "2" { 2u }
+ "3" { 3u }
_ {
log_err "error: optimization level needs " +
"to be between 0-3";
none. { get_default_sysroot(binary) }
some(s) { s }
};
- let cfg = parse_cfgspecs(
- getopts::opt_strs(match, ~"cfg"));
- let test = opt_present(match, ~"test");
- let do_gc = opt_present(match, ~"gc");
+ let cfg = parse_cfgspecs(getopts::opt_strs(match, "cfg"));
+ let test = opt_present(match, "test");
+ let do_gc = opt_present(match, "gc");
let sopts: @session::options =
@{library: library,
static: static,
none, 0u);
}
-fn parse_pretty(sess: session::session, name: &istr) -> pp_mode {
- if str::eq(name, ~"normal") {
+fn parse_pretty(sess: session::session, name: &str) -> pp_mode {
+ if str::eq(name, "normal") {
ret ppm_normal;
- } else if str::eq(name, ~"expanded") {
+ } else if str::eq(name, "expanded") {
ret ppm_expanded;
- } else if str::eq(name, ~"typed") {
+ } else if str::eq(name, "typed") {
ret ppm_typed;
- } else if str::eq(name, ~"identified") { ret ppm_identified; }
- sess.fatal(~"argument to `pretty` must be one of `normal`, `typed`, or "
- + ~"`identified`");
+ } else if str::eq(name, "identified") { ret ppm_identified; }
+ sess.fatal("argument to `pretty` 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"),
- 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"),
+ 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: [istr]) {
+fn main(args: [str]) {
let binary = vec::shift(args);
let binary_dir = fs::dirname(binary);
let match =
fail
}
};
- if opt_present(match, ~"h") || opt_present(match, ~"help") {
+ if opt_present(match, "h") || opt_present(match, "help") {
usage(binary);
ret;
}
- if opt_present(match, ~"v") || opt_present(match, ~"version") {
+ if opt_present(match, "v") || opt_present(match, "version") {
version(binary);
ret;
}
let sopts = build_session_options(binary, match, binary_dir);
let sess = build_session(sopts);
- let n_inputs = vec::len::<istr>(match.free);
- let output_file = getopts::opt_maybe_str(match, ~"o");
- let glue = opt_present(match, ~"glue");
+ let n_inputs = vec::len::<str>(match.free);
+ let output_file = getopts::opt_maybe_str(match, "o");
+ let glue = opt_present(match, "glue");
if glue {
if n_inputs > 0u {
- sess.fatal(~"No input files allowed with --glue.");
+ sess.fatal("No input files allowed with --glue.");
}
- let out = option::from_maybe::<istr>(~"glue.bc", output_file);
+ let out = option::from_maybe::<str>("glue.bc", output_file);
middle::trans::make_common_glue(sess, out);
ret;
}
if n_inputs == 0u {
- sess.fatal(~"No input filename given.");
+ sess.fatal("No input filename given.");
} else if n_inputs > 1u {
- sess.fatal(~"Multiple input filenames provided.");
+ sess.fatal("Multiple input filenames provided.");
}
let ifile = match.free[0];
- let saved_out_filename: istr = ~"";
- let cfg = build_configuration(sess, binary,
- ifile);
+ let saved_out_filename: str = "";
+ let cfg = build_configuration(sess, binary, ifile);
let pretty =
- option::map::<istr,
+ option::map::<str,
pp_mode>(bind parse_pretty(sess, _),
- getopts::opt_default(match, ~"pretty",
- ~"normal"));
+ getopts::opt_default(match, "pretty",
+ "normal"));
alt pretty {
- some::<pp_mode>(ppm) {
- pretty_print_input(sess, cfg, ifile, ppm);
- ret;
- }
+ some::<pp_mode>(ppm) { pretty_print_input(sess, cfg, ifile, ppm); ret; }
none::<pp_mode>. {/* continue */ }
}
- let ls = opt_present(match, ~"ls");
+ let ls = opt_present(match, "ls");
if ls { metadata::creader::list_file_metadata(ifile, io::stdout()); ret; }
let stop_after_codegen =
let parts =
if !input_is_stdin(ifile) {
str::split(ifile, '.' as u8)
- } else { [~"default", ~"rs"] };
+ } else { ["default", "rs"] };
vec::pop(parts);
- saved_out_filename = str::connect(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" }
+ 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"
+ "o"
}
};
- let ofile = saved_out_filename + ~"." + suffix;
+ 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 };
+ if !stop_after_codegen { ofile + ".o" } else { ofile };
compile_input(sess, cfg, ifile, temp_filename);
}
}
// TODO: Factor this out of main.
if stop_after_codegen { ret; }
- let glu: istr = binary_dir + ~"/lib/glue.o";
- let main: istr = binary_dir + ~"/lib/main.o";
- let stage: istr = ~"-L" + binary_dir + ~"/lib";
- let prog: istr = ~"gcc";
+ let glu: str = binary_dir + "/lib/glue.o";
+ let main: str = binary_dir + "/lib/main.o";
+ let stage: str = "-L" + binary_dir + "/lib";
+ let prog: str = "gcc";
// 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;
if os == session::os_macos {
- lib_cmd = ~"-dynamiclib";
- } else { lib_cmd = ~"-shared"; }
+ lib_cmd = "-dynamiclib";
+ } else { lib_cmd = "-shared"; }
// Converts a library file name into a gcc -l argument
- fn unlib(config: @session::config, filename: &istr) -> istr {
+ fn unlib(config: @session::config, filename: &str) -> str {
let rmlib =
- bind fn (config: @session::config, filename: &istr) -> istr {
- if config.os == session::os_macos ||
- config.os == session::os_linux &&
- str::find(filename, ~"lib") == 0 {
- ret str::slice(filename, 3u,
- str::byte_len(filename));
- } else { ret filename; }
- }(config, _);
- fn rmext(filename: &istr) -> istr {
+ bind fn (config: @session::config, filename: &str) -> str {
+ if config.os == session::os_macos ||
+ config.os == session::os_linux &&
+ str::find(filename, "lib") == 0 {
+ ret str::slice(filename, 3u,
+ str::byte_len(filename));
+ } else { ret filename; }
+ }(config, _);
+ fn rmext(filename: &str) -> str {
let parts = str::split(filename, '.' as u8);
vec::pop(parts);
- ret str::connect(parts, ~".");
+ ret str::connect(parts, ".");
}
ret alt config.os {
session::os_macos. { rmext(rmlib(filename)) }
}
let cstore = sess.get_cstore();
- for cratepath: istr in cstore::get_used_crate_files(cstore) {
- if str::ends_with(cratepath, ~".rlib") {
+ for cratepath: str in cstore::get_used_crate_files(cstore) {
+ if str::ends_with(cratepath, ".rlib") {
gcc_args += [cratepath];
cont;
}
let cratepath = cratepath;
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: istr in ula { gcc_args += [arg]; }
+ for arg: str in ula { gcc_args += [arg]; }
let used_libs = cstore::get_used_libraries(cstore);
- for l: istr in used_libs { gcc_args += [~"-l" + l]; }
+ for l: str in used_libs { gcc_args += ["-l" + l]; }
if sopts.library {
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");
+ let sessopts = build_session_options("whatever", match, "whatever");
let sess = build_session(sessopts);
- let cfg = build_configuration(sess, ~"whatever", ~"whatever");
- assert (attr::contains_name(cfg, ~"test"));
+ let cfg = build_configuration(sess, "whatever", "whatever");
+ assert (attr::contains_name(cfg, "test"));
}
// When the user supplies --test and --cfg test, don't implicitly add
#[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");
+ let sessopts = build_session_options("whatever", match, "whatever");
let sess = build_session(sessopts);
- let cfg = build_configuration(sess, ~"whatever", ~"whatever");
- let test_items = attr::find_meta_items_by_name(cfg, ~"test");
+ let cfg = build_configuration(sess, "whatever", "whatever");
+ let test_items = attr::find_meta_items_by_name(cfg, "test");
assert (vec::len(test_items) == 1u);
}
}
time_passes: bool,
time_llvm_passes: bool,
output_type: back::link::output_type,
- library_search_paths: [istr],
- sysroot: istr,
+ library_search_paths: [str],
+ sysroot: str,
cfg: ast::crate_cfg,
test: bool,
parse_only: bool,
no_trans: bool,
do_gc: bool};
-type crate_metadata = {name: istr, data: [u8]};
+type crate_metadata = {name: str, data: [u8]};
obj session(targ_cfg: @config,
opts: @options,
fn get_targ_cfg() -> @config { ret targ_cfg; }
fn get_opts() -> @options { ret opts; }
fn get_cstore() -> metadata::cstore::cstore { cstore }
- fn span_fatal(sp: span, msg: &istr) -> ! {
+ fn span_fatal(sp: span, msg: &str) -> ! {
// FIXME: Use constants, but rustboot doesn't know how to export them.
codemap::emit_error(some(sp), msg, parse_sess.cm);
fail;
}
- fn fatal(msg: &istr) -> ! {
+ fn fatal(msg: &str) -> ! {
codemap::emit_error(none, msg, parse_sess.cm);
fail;
}
- fn span_err(sp: span, msg: &istr) {
+ fn span_err(sp: span, msg: &str) {
codemap::emit_error(some(sp), msg, parse_sess.cm);
err_count += 1u;
}
- fn err(msg: &istr) {
+ fn err(msg: &str) {
codemap::emit_error(none, msg, parse_sess.cm);
err_count += 1u;
}
fn abort_if_errors() {
- if err_count > 0u { self.fatal(~"aborting due to previous errors"); }
+ if err_count > 0u { self.fatal("aborting due to previous errors"); }
}
- fn span_warn(sp: span, msg: &istr) {
+ fn span_warn(sp: span, msg: &str) {
// FIXME: Use constants, but rustboot doesn't know how to export them.
codemap::emit_warning(some(sp), msg, parse_sess.cm);
}
- fn warn(msg: &istr) {
- codemap::emit_warning(none, msg, parse_sess.cm);
- }
- fn span_note(sp: span, msg: &istr) {
+ fn warn(msg: &str) { codemap::emit_warning(none, msg, parse_sess.cm); }
+ fn span_note(sp: span, msg: &str) {
// FIXME: Use constants, but rustboot doesn't know how to export them.
codemap::emit_note(some(sp), msg, parse_sess.cm);
}
- fn note(msg: &istr) {
- codemap::emit_note(none, msg, parse_sess.cm);
- }
- fn span_bug(sp: span, msg: &istr) -> ! {
- self.span_fatal(sp,
- #fmt["internal compiler error %s",
- msg]);
+ 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]);
}
- fn bug(msg: &istr) -> ! {
- self.fatal(
- #fmt["internal compiler error %s",
- msg]);
+ fn bug(msg: &str) -> ! {
+ self.fatal(#fmt["internal compiler error %s", msg]);
}
- fn span_unimpl(sp: span, msg: &istr) -> ! {
- self.span_bug(sp, ~"unimplemented " + msg);
+ fn span_unimpl(sp: span, msg: &str) -> ! {
+ self.span_bug(sp, "unimplemented " + msg);
}
- fn unimpl(msg: &istr) -> ! { self.bug(~"unimplemented " + msg); }
+ fn unimpl(msg: &str) -> ! { self.bug("unimplemented " + msg); }
fn get_codemap() -> codemap::codemap { ret parse_sess.cm; }
fn lookup_pos(pos: uint) -> codemap::loc {
ret codemap::lookup_char_pos(parse_sess.cm, pos);
fn next_node_id() -> ast::node_id {
ret syntax::parse::parser::next_node_id(parse_sess);
}
- fn span_str(sp: span) -> istr {
+ fn span_str(sp: span) -> str {
ret codemap::span_to_str(sp, self.get_codemap());
}
fn set_main_id(d: node_id) { main_fn = some(d); }
// linkage
fn find_linkage_metas(attrs: &[ast::attribute]) -> [@ast::meta_item] {
let metas: [@ast::meta_item] = [];
- for attr: ast::attribute in find_attrs_by_name(attrs, ~"link") {
+ for attr: ast::attribute in find_attrs_by_name(attrs, "link") {
alt attr.node.value.node {
ast::meta_list(_, items) { metas += items; }
_ { log "ignoring link attribute that has incorrect type"; }
// Gets the string value if the meta_item is a meta_name_value variant
// containing a string, otherwise none
-fn get_meta_item_value_str(meta: &@ast::meta_item) -> option::t<istr> {
+fn get_meta_item_value_str(meta: &@ast::meta_item) -> option::t<str> {
alt meta.node {
ast::meta_name_value(_, v) {
- alt v.node {
- ast::lit_str(s) { option::some(s) }
- _ { option::none }
- }
+ alt v.node { ast::lit_str(s) { option::some(s) } _ { option::none } }
}
_ { option::none }
}
fn contains(haystack: &[@ast::meta_item], needle: @ast::meta_item) -> bool {
log #fmt["looking for %s",
- syntax::print::pprust::meta_item_to_str(*needle)];
+ 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)];
+ syntax::print::pprust::meta_item_to_str(*item)];
if eq(item, needle) { log "found it!"; ret true; }
}
log "found it not :(";
ret v2;
}
-fn remove_meta_items_by_name(items: &[@ast::meta_item], name: &istr) ->
+fn remove_meta_items_by_name(items: &[@ast::meta_item], name: &str) ->
[@ast::meta_item] {
let filter =
- bind fn (item: &@ast::meta_item, name: &istr) ->
+ bind fn (item: &@ast::meta_item, name: &str) ->
option::t<@ast::meta_item> {
if get_meta_item_name(item) != name {
option::some(item)
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, ());
}
ret {node: item, span: ast_util::dummy_sp()};
}
-fn mk_name_value_item_str(name: ast::ident,
- value: &istr) -> @ast::meta_item {
+fn mk_name_value_item_str(name: ast::ident, value: &str) -> @ast::meta_item {
let value_lit = span(ast::lit_str(value));
ret mk_name_value_item(name, value_lit);
}
let filtered_stmts = vec::filter_map(filter, b.stmts);
ret {stmts: vec::map(fld.fold_stmt, filtered_stmts),
expr: option::map(fld.fold_expr, b.expr),
- id: b.id, rules: b.rules};
+ id: b.id,
+ rules: b.rules};
}
fn item_in_cfg(cfg: &ast::crate_cfg, item: &@ast::item) -> bool {
fn in_cfg(cfg: &ast::crate_cfg, attrs: &[ast::attribute]) -> bool {
// The "cfg" attributes on the item
- let item_cfg_attrs = attr::find_attrs_by_name(attrs, ~"cfg");
+ let item_cfg_attrs = attr::find_attrs_by_name(attrs, "cfg");
let item_has_cfg_attrs = vec::len(item_cfg_attrs) > 0u;
if !item_has_cfg_attrs { ret true; }
[@ast::meta_item] {
alt cfg_item.node {
ast::meta_list(name, items) {
- assert (name == ~"cfg");
+ assert (name == "cfg");
inner_items + items
}
_ { inner_items }
fn nomain(item: &@ast::item) -> option::t<@ast::item> {
alt item.node {
ast::item_fn(f, _) {
- if item.ident == ~"main" {
+ if item.ident == "main" {
option::none
} else { option::some(item) }
}
@ast::item {
cx.path += [i.ident];
- log #fmt["current path: %s",
- ast_util::path_name_i(cx.path)];
+ log #fmt["current path: %s", ast_util::path_name_i(cx.path)];
if is_test_fn(i) {
log "this is a test function";
fn is_test_fn(i: &@ast::item) -> bool {
let has_test_attr =
- vec::len(attr::find_attrs_by_name(i.attrs, ~"test")) > 0u;
+ vec::len(attr::find_attrs_by_name(i.attrs, "test")) > 0u;
fn has_test_signature(i: &@ast::item) -> bool {
alt i.node {
}
fn is_ignored(i: &@ast::item) -> bool {
- attr::contains_name(attr::attr_metas(i.attrs), ~"ignore")
+ attr::contains_name(attr::attr_metas(i.attrs), "ignore")
}
fn add_test_module(cx: &test_ctxt, m: &ast::_mod) -> ast::_mod {
let testmod: ast::_mod = {view_items: [], items: [mainfn, testsfn]};
let item_ = ast::item_mod(testmod);
let item: ast::item =
- {ident: ~"__test",
+ {ident: "__test",
attrs: [],
id: cx.next_node_id(),
node: item_,
span: 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;
}
-fn nospan<@T>(t: &T) -> ast::spanned<T> {
- ret {node: t, span: dummy_sp()};
-}
+fn nospan<@T>(t: &T) -> ast::spanned<T> { ret {node: t, span: dummy_sp()}; }
fn mk_tests(cx: &test_ctxt) -> @ast::item {
let ret_ty = mk_test_desc_vec_ty(cx);
// The vector of test_descs for this crate
let test_descs = mk_test_desc_vec(cx);
- let body_: ast::blk_ = checked_blk([], option::some(test_descs),
- cx.next_node_id());
+ let body_: ast::blk_ =
+ checked_blk([], option::some(test_descs), 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 =
- {ident: ~"tests",
+ {ident: "tests",
attrs: [],
id: cx.next_node_id(),
node: item_,
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"],
+ idents: ["std", "test", "test_desc"],
types: []});
let test_desc_ty: ast::ty =
fn mk_test_desc_rec(cx: &test_ctxt, test: test) -> @ast::expr {
let path = test.path;
- log #fmt["encoding %s",
- ast_util::path_name_i(path)];
+ log #fmt["encoding %s", ast_util::path_name_i(path)];
let name_lit: ast::lit =
nospan(ast::lit_str(ast_util::path_name_i(path)));
span: dummy_sp()};
let name_field: ast::field =
- nospan({mut: ast::imm, ident: ~"name", expr: @name_expr});
+ nospan({mut: ast::imm, ident: "name", expr: @name_expr});
let fn_path: ast::path = nospan({global: false, idents: path, types: []});
span: dummy_sp()};
let fn_field: ast::field =
- nospan({mut: ast::imm, ident: ~"fn", expr: @fn_expr});
+ nospan({mut: ast::imm, ident: "fn", expr: @fn_expr});
let ignore_lit: ast::lit = nospan(ast::lit_bool(test.ignore));
span: dummy_sp()};
let ignore_field: ast::field =
- nospan({mut: ast::imm, ident: ~"ignore", expr: @ignore_expr});
+ 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);
let args_ty: ast::ty = nospan(ast::ty_vec(args_mt));
let args_arg: ast::arg =
- {mode: ast::val, ty: @args_ty, ident: ~"args", id: cx.next_node_id()};
+ {mode: ast::val, ty: @args_ty, ident: "args", id: cx.next_node_id()};
let ret_ty = nospan(ast::ty_nil);
let test_main_call_expr = mk_test_main_call(cx);
- let body_: ast::blk_ = checked_blk([], option::some(test_main_call_expr),
- cx.next_node_id());
+ let body_: ast::blk_ =
+ checked_blk([], option::some(test_main_call_expr), cx.next_node_id());
let body = {node: body_, span: dummy_sp()};
let fn_ = {decl: decl, proto: proto, body: body};
let item_ = ast::item_fn(fn_, []);
let item: ast::item =
- {ident: ~"main",
+ {ident: "main",
attrs: [],
id: cx.next_node_id(),
node: item_,
// 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);
// 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);
// Call std::test::test_main
let test_main_path: ast::path =
nospan({global: false,
- idents: [~"std", ~"test", ~"test_main"],
+ idents: ["std", "test", "test_main"],
types: []});
let test_main_path_expr_: ast::expr_ = ast::expr_path(test_main_path);
let test_main_path_expr: ast::expr =
- {id: cx.next_node_id(),
- node: test_main_path_expr_,
- span: dummy_sp()};
+ {id: cx.next_node_id(), node: test_main_path_expr_, span: dummy_sp()};
let test_main_call_expr_: ast::expr_ =
ast::expr_call(@test_main_path_expr,
[@args_path_expr, @test_call_expr]);
let test_main_call_expr: ast::expr =
- {id: cx.next_node_id(),
- node: test_main_call_expr_,
- span: dummy_sp()};
+ {id: cx.next_node_id(), node: test_main_call_expr_, span: dummy_sp()};
ret @test_main_call_expr;
}
fn LLVMPassManagerBuilderSetDisableUnrollLoops(PMB: PassManagerBuilderRef,
Value: Bool);
fn LLVMPassManagerBuilderSetDisableSimplifyLibCalls(
- PMB: PassManagerBuilderRef,
- Value: Bool);
+ PMB: PassManagerBuilderRef, Value: Bool);
fn LLVMPassManagerBuilderUseInlinerWithThreshold(
- PMB: PassManagerBuilderRef,
- threshold: uint);
+ PMB: PassManagerBuilderRef, threshold: uint);
fn LLVMPassManagerBuilderPopulateModulePassManager(
- PMB: PassManagerBuilderRef,
- PM: PassManagerRef);
+ PMB: PassManagerBuilderRef, PM: PassManagerRef);
fn LLVMPassManagerBuilderPopulateFunctionPassManager(
- PMB: PassManagerBuilderRef,
- PM: PassManagerRef);
+ PMB: PassManagerBuilderRef, PM: PassManagerRef);
/** Destroys a memory buffer. */
fn LLVMDisposeMemoryBuffer(MemBuf: MemoryBufferRef);
/* Memory-managed object interface to type handles. */
-obj type_names(type_names: std::map::hashmap<TypeRef, istr>,
- named_types: std::map::hashmap<istr, TypeRef>) {
+obj type_names(type_names: std::map::hashmap<TypeRef, str>,
+ named_types: std::map::hashmap<str, TypeRef>) {
- fn associate(s: &istr, t: TypeRef) {
+ fn associate(s: &str, t: TypeRef) {
assert (!named_types.contains_key(s));
assert (!type_names.contains_key(t));
type_names.insert(t, s);
fn type_has_name(t: TypeRef) -> bool { ret type_names.contains_key(t); }
- fn get_name(t: TypeRef) -> istr { ret type_names.get(t); }
+ fn get_name(t: TypeRef) -> str { ret type_names.get(t); }
- fn name_has_type(s: &istr) -> bool {
- ret named_types.contains_key(s);
- }
+ fn name_has_type(s: &str) -> bool { ret named_types.contains_key(s); }
- fn get_type(s: &istr) -> TypeRef {
- ret named_types.get(s);
- }
+ fn get_type(s: &str) -> TypeRef { ret named_types.get(s); }
}
fn mk_type_names() -> type_names {
let hasher: std::map::hashfn<TypeRef> = hash;
let eqer: std::map::eqfn<TypeRef> = eq;
- let tn = std::map::mk_hashmap::<TypeRef, istr>(hasher, eqer);
+ let tn = std::map::mk_hashmap::<TypeRef, str>(hasher, eqer);
ret type_names(tn, nt);
}
-fn type_to_str(names: type_names, ty: TypeRef) -> istr {
+fn type_to_str(names: type_names, ty: TypeRef) -> str {
ret type_to_str_inner(names, [], ty);
}
fn type_to_str_inner(names: type_names, outer0: &[TypeRef], ty: TypeRef) ->
- istr {
+ str {
if names.type_has_name(ty) { ret names.get_name(ty); }
let kind: int = llvm::LLVMGetTypeKind(ty);
- fn tys_str(names: type_names, outer: &[TypeRef],
- tys: &[TypeRef]) -> istr {
- let s: istr = ~"";
+ fn tys_str(names: type_names, outer: &[TypeRef], tys: &[TypeRef]) -> str {
+ let s: str = "";
let first: bool = true;
for t: TypeRef in tys {
- if first { first = false; } else { s += ~", "; }
+ if first { first = false; } else { s += ", "; }
s += type_to_str_inner(names, outer, t);
}
ret s;
+
// FIXME: more enum-as-int constants determined from Core::h;
// horrible, horrible. Complete as needed.
0 {
- ret ~"Void";
+ ret "Void";
}
- 1 { ret ~"Float"; }
- 2 { ret ~"Double"; }
- 3 { ret ~"X86_FP80"; }
- 4 { ret ~"FP128"; }
- 5 { ret ~"PPC_FP128"; }
- 6 { ret ~"Label"; }
+ 1 { ret "Float"; }
+ 2 { ret "Double"; }
+ 3 { ret "X86_FP80"; }
+ 4 { ret "FP128"; }
+ 5 { ret "PPC_FP128"; }
+ 6 { ret "Label"; }
+
7 {
- ret ~"i" + std::int::str(
- llvm::LLVMGetIntTypeWidth(ty) as int);
+ ret "i" + std::int::str(llvm::LLVMGetIntTypeWidth(ty) as int);
}
+
8 {
- let s = ~"fn(";
+ let s = "fn(";
let out_ty: TypeRef = llvm::LLVMGetReturnType(ty);
let n_args: uint = llvm::LLVMCountParamTypes(ty);
let args: [TypeRef] = vec::init_elt::<TypeRef>(0 as TypeRef, n_args);
llvm::LLVMGetParamTypes(ty, vec::to_ptr(args));
s += tys_str(names, outer, args);
- s += ~") -> ";
+ s += ") -> ";
s += type_to_str_inner(names, outer, out_ty);
ret s;
}
+
9 {
- let s: istr = ~"{";
+ let s: str = "{";
let n_elts: uint = llvm::LLVMCountStructElementTypes(ty);
let elts: [TypeRef] = vec::init_elt::<TypeRef>(0 as TypeRef, n_elts);
llvm::LLVMGetStructElementTypes(ty, vec::to_ptr(elts));
s += tys_str(names, outer, elts);
- s += ~"}";
+ s += "}";
ret s;
}
+
10 {
let el_ty = llvm::LLVMGetElementType(ty);
- ret ~"[" + type_to_str_inner(names, outer, el_ty) + ~"]";
+ ret "[" + type_to_str_inner(names, outer, el_ty) + "]";
}
+
11 {
let i: uint = 0u;
for tout: TypeRef in outer0 {
i += 1u;
if tout as int == ty as int {
let n: uint = vec::len::<TypeRef>(outer0) - i;
- ret ~"*\\" + std::int::str(n as int);
+ ret "*\\" + std::int::str(n as int);
}
}
- ret ~"*" +
+ ret "*" +
type_to_str_inner(names, outer, llvm::LLVMGetElementType(ty));
}
+
12 {
- ret ~"Opaque";
+ ret "Opaque";
}
- 13 { ret ~"Vector"; }
- 14 { ret ~"Metadata"; }
+ 13 { ret "Vector"; }
+ 14 { ret "Metadata"; }
_ { log_err #fmt["unknown TypeKind %d", kind as int]; fail; }
}
}
type target_data = {lltd: TargetDataRef, dtor: @target_data_res};
-fn mk_target_data(string_rep: &istr) -> target_data {
- let lltd = str::as_buf(string_rep, { |buf|
- llvm::LLVMCreateTargetData(buf)
- });
+fn mk_target_data(string_rep: &str) -> target_data {
+ let lltd =
+ str::as_buf(string_rep, {|buf| llvm::LLVMCreateTargetData(buf) });
ret {lltd: lltd, dtor: @target_data_res(lltd)};
}
// djb's cdb hashes.
fn hash_node_id(node_id: &int) -> uint { ret 177573u ^ (node_id as uint); }
-fn hash_path(s: &istr) -> uint {
+fn hash_path(s: &str) -> uint {
let h = 5381u;
for ch: u8 in str::bytes(s) { h = (h << 5u) + h ^ (ch as uint); }
ret h;
let e =
@{sess: sess,
crate_cache: @std::map::new_str_hash::<int>(),
- library_search_paths:
- sess.get_opts().library_search_paths,
+ library_search_paths: sess.get_opts().library_search_paths,
mutable next_crate_num: 1};
let v =
visit::mk_simple_visitor(@{visit_view_item:
type env =
@{sess: session::session,
- crate_cache: @hashmap<istr, int>,
- library_search_paths: [istr],
+ crate_cache: @hashmap<str, int>,
+ library_search_paths: [str],
mutable next_crate_num: ast::crate_num};
fn visit_view_item(e: env, i: &@ast::view_item) {
ret;
}
let cstore = e.sess.get_cstore();
- if !cstore::add_used_library(cstore,
- m.native_name) { ret; }
+ if !cstore::add_used_library(cstore, m.native_name) { ret; }
for a: ast::attribute in
- attr::find_attrs_by_name(i.attrs, ~"link_args") {
+ 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);
- }
+ some(linkarg) { cstore::add_used_link_args(cstore, linkarg); }
none. {/* fallthrough */ }
}
}
}
// A diagnostic function for dumping crate metadata to an output stream
-fn list_file_metadata(path: &istr, out: io::writer) {
+fn list_file_metadata(path: &str, out: io::writer) {
alt get_metadata_section(path) {
option::some(bytes) { decoder::list_crate_metadata(bytes, out); }
option::none. {
- out.write_str(
- ~"Could not find metadata in " + path + ~".\n");
+ out.write_str("Could not find metadata in " + path + ".\n");
}
}
}
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 default_native_lib_naming(sess: session::session, static: bool) ->
- {prefix: istr, suffix: istr} {
- if static { ret {prefix: ~"lib", suffix: ~".rlib"}; }
+ {prefix: str, suffix: str} {
+ if static { ret {prefix: "lib", suffix: ".rlib"}; }
alt sess.get_targ_cfg().os {
- session::os_win32. { ret {prefix: ~"", suffix: ~".dll"}; }
- session::os_macos. { ret {prefix: ~"lib", suffix: ~".dylib"}; }
- session::os_linux. { ret {prefix: ~"lib", suffix: ~".so"}; }
+ session::os_win32. { ret {prefix: "", suffix: ".dll"}; }
+ session::os_macos. { ret {prefix: "lib", suffix: ".dylib"}; }
+ session::os_linux. { ret {prefix: "lib", suffix: ".so"}; }
}
}
fn find_library_crate(sess: &session::session, ident: &ast::ident,
- metas: &[@ast::meta_item],
- library_search_paths: &[istr])
- -> option::t<{ident: istr, data: @[u8]}> {
+ metas: &[@ast::meta_item], library_search_paths: &[str])
+ -> option::t<{ident: str, data: @[u8]}> {
attr::require_unique_names(sess, metas);
// is using the wrong type of meta item
let crate_name =
{
- let name_items = attr::find_meta_items_by_name(metas, ~"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) {
let nn = default_native_lib_naming(sess, sess.get_opts().static);
let x =
- find_library_crate_aux(nn, crate_name,
- metas, library_search_paths);
+ find_library_crate_aux(nn, crate_name, metas, library_search_paths);
if x != none || sess.get_opts().static { ret x; }
let nn2 = default_native_lib_naming(sess, true);
- ret find_library_crate_aux(nn2, crate_name,
- metas, library_search_paths);
+ ret find_library_crate_aux(nn2, crate_name, metas, library_search_paths);
}
-fn find_library_crate_aux(nn: &{prefix: istr, suffix: istr},
- crate_name: &istr,
+fn find_library_crate_aux(nn: &{prefix: str, suffix: str}, crate_name: &str,
metas: &[@ast::meta_item],
- library_search_paths: &[istr]) ->
- option::t<{ident: istr, data: @[u8]}> {
- let prefix: istr = nn.prefix + crate_name;
- let suffix: istr = nn.suffix;
+ library_search_paths: &[str]) ->
+ option::t<{ident: str, data: @[u8]}> {
+ let prefix: str = nn.prefix + crate_name;
+ let suffix: str = nn.suffix;
// FIXME: we could probably use a 'glob' function in std::fs but it will
// be much easier to write once the unsafe module knows more about FFI
// tricks. Currently the glob(3) interface is a bit more than we can
// stomach from here, and writing a C++ wrapper is more work than just
// manually filtering fs::list_dir here.
- for library_search_path: istr in library_search_paths {
+ for library_search_path: str in library_search_paths {
log #fmt["searching %s", library_search_path];
- for path: istr in fs::list_dir(library_search_path) {
+ for path: str in fs::list_dir(library_search_path) {
log #fmt["searching %s", path];
- let f: istr = fs::basename(path);
- if !(str::starts_with(f, prefix) && str::ends_with(f, suffix))
- {
- log #fmt["skipping %s, doesn't look like %s*%s",
- path,
- prefix,
+ let f: str = fs::basename(path);
+ if !(str::starts_with(f, prefix) && str::ends_with(f, suffix)) {
+ log #fmt["skipping %s, doesn't look like %s*%s", path, prefix,
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});
}
_ { }
ret none;
}
-fn get_metadata_section(filename: &istr) -> option::t<@[u8]> {
- let mb = str::as_buf(filename, { |buf|
- llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf)
- });
+fn get_metadata_section(filename: &str) -> option::t<@[u8]> {
+ let mb =
+ str::as_buf(filename, {|buf|
+ llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf)
+ });
if mb as int == 0 { ret option::none::<@[u8]>; }
let of = mk_object_file(mb);
let si = mk_section_iter(of.llof);
}
fn load_library_crate(sess: &session::session, span: span, ident: &ast::ident,
- metas: &[@ast::meta_item],
- library_search_paths: &[istr])
- -> {ident: istr, 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]);
}
}
}
// Now resolve the crates referenced by this crate
let cnum_map = resolve_crate_deps(e, cdata);
- let cmeta = {name: ident,
- data: cdata, cnum_map: cnum_map};
+ let cmeta = {name: ident, data: cdata, cnum_map: cnum_map};
let cstore = e.sess.get_cstore();
cstore::set_crate_data(cstore, cnum, cmeta);
- cstore::add_used_crate_file(cstore,
- cfilename);
+ cstore::add_used_crate_file(cstore, cfilename);
ret cnum;
} else { ret e.crate_cache.get(ident); }
}
// 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_util::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);
}
}
export get_tag_variants;
export get_type;
-fn get_symbol(cstore: &cstore::cstore, def: ast::def_id) -> istr {
+fn get_symbol(cstore: &cstore::cstore, def: ast::def_id) -> str {
let cdata = cstore::get_crate_data(cstore, def.crate).data;
ret decoder::get_symbol(cdata, def.node);
}
let local_cnum =
alt cmeta.cnum_map.find(ext_cnum) {
option::some(n) { n }
- option::none. { sess.bug(~"didn't find a crate in the cnum_map") }
+ option::none. { sess.bug("didn't find a crate in the cnum_map") }
};
ret {crate: local_cnum, node: node_id};
// own crate numbers.
type cnum_map = map::hashmap<ast::crate_num, ast::crate_num>;
-type crate_metadata = {name: istr, data: @[u8], cnum_map: cnum_map};
+type crate_metadata = {name: str, data: @[u8], cnum_map: cnum_map};
// This is a bit of an experiment at encapsulating the data in cstore. By
// keeping all the data in a non-exported tag variant, it's impossible for
type cstore_private =
@{metas: map::hashmap<ast::crate_num, crate_metadata>,
use_crate_map: use_crate_map,
- mutable used_crate_files: [istr],
- mutable used_libraries: [istr],
- mutable used_link_args: [istr]};
+ mutable used_crate_files: [str],
+ mutable used_libraries: [str],
+ mutable used_link_args: [str]};
// Map from node_id's of local use statements to crate numbers
type use_crate_map = map::hashmap<ast::node_id, ast::crate_num>;
}
}
-fn add_used_crate_file(cstore: &cstore, lib: &istr) {
+fn add_used_crate_file(cstore: &cstore, lib: &str) {
if !vec::member(lib, p(cstore).used_crate_files) {
p(cstore).used_crate_files += [lib];
}
}
-fn get_used_crate_files(cstore: &cstore) -> [istr] {
+fn get_used_crate_files(cstore: &cstore) -> [str] {
ret p(cstore).used_crate_files;
}
-fn add_used_library(cstore: &cstore, lib: &istr) -> bool {
- if lib == ~"" { ret false; }
+fn add_used_library(cstore: &cstore, lib: &str) -> bool {
+ if lib == "" { ret false; }
if vec::member(lib, p(cstore).used_libraries) { ret false; }
ret true;
}
-fn get_used_libraries(cstore: &cstore) -> [istr] {
+fn get_used_libraries(cstore: &cstore) -> [str] {
ret p(cstore).used_libraries;
}
-fn add_used_link_args(cstore: &cstore, args: &istr) {
+fn add_used_link_args(cstore: &cstore, args: &str) {
p(cstore).used_link_args += str::split(args, ' ' as u8);
}
-fn get_used_link_args(cstore: &cstore) -> [istr] {
+fn get_used_link_args(cstore: &cstore) -> [str] {
ret p(cstore).used_link_args;
}
ret ebml::doc_as_uint(fam) as u8;
}
-fn item_symbol(item: &ebml::doc) -> istr {
+fn item_symbol(item: &ebml::doc) -> str {
let sym = ebml::get_doc(item, tag_items_data_item_symbol);
ret str::unsafe_from_bytes(ebml::doc_data(sym));
}
fn item_type(item: &ebml::doc, this_cnum: ast::crate_num, tcx: ty::ctxt,
extres: &external_resolver) -> ty::t {
fn parse_external_def_id(this_cnum: ast::crate_num,
- extres: &external_resolver, s: &istr) ->
+ extres: &external_resolver, s: &str) ->
ast::def_id {
let buf = str::bytes(s);
let external_def_id = parse_def_id(buf);
// Given a path and serialized crate metadata, returns the ID of the
// definition the path refers to.
fn resolve_path(path: &[ast::ident], data: @[u8]) -> [ast::def_id] {
- fn eq_item(data: &[u8], s: &istr) -> bool {
+ fn eq_item(data: &[u8], s: &str) -> bool {
ret str::eq(str::unsafe_from_bytes(data), s);
}
- let s = str::connect(path, ~"::");
+ let s = str::connect(path, "::");
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] = [];
- for doc: ebml::doc in lookup_hash(paths, eqer,
- hash_path(s)) {
+ 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))];
}
ret item_ty_param_kinds(lookup_item(id, data));
}
-fn get_symbol(data: @[u8], id: ast::node_id) -> istr {
+fn get_symbol(data: @[u8], id: ast::node_id) -> str {
ret item_symbol(lookup_item(id, data));
}
};
}
-fn read_path(d: &ebml::doc) -> {path: istr, pos: uint} {
+fn read_path(d: &ebml::doc) -> {path: str, pos: uint} {
let desc = ebml::doc_data(d);
let pos = ebml::be_uint_from_bytes(@desc, 0u, 4u);
let pathbytes = vec::slice::<u8>(desc, 4u, vec::len::<u8>(desc));
ret {path: path, pos: pos};
}
-fn describe_def(items: &ebml::doc, id: ast::def_id) -> istr {
- if id.crate != ast::local_crate { ret ~"external"; }
+fn describe_def(items: &ebml::doc, id: ast::def_id) -> str {
+ if id.crate != ast::local_crate { ret "external"; }
ret item_family_to_str(item_family(find_item(id.node, items)));
}
-fn item_family_to_str(fam: u8) -> istr {
+fn item_family_to_str(fam: u8) -> str {
alt fam as char {
- 'c' { ret ~"const"; }
- 'f' { ret ~"fn"; }
- 'p' { ret ~"pure fn"; }
- 'F' { ret ~"native fn"; }
- 'y' { ret ~"type"; }
- 'T' { ret ~"native type"; }
- 't' { ret ~"type"; }
- 'm' { ret ~"mod"; }
- 'n' { ret ~"native mod"; }
- 'v' { ret ~"tag"; }
+ 'c' { ret "const"; }
+ 'f' { ret "fn"; }
+ 'p' { ret "pure fn"; }
+ 'F' { ret "native fn"; }
+ 'y' { ret "type"; }
+ 'T' { ret "native type"; }
+ 't' { ret "type"; }
+ 'm' { ret "mod"; }
+ 'n' { ret "native mod"; }
+ 'v' { ret "tag"; }
}
}
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)]);
}
}
fn list_crate_attributes(md: &ebml::doc, out: io::writer) {
- out.write_str(~"=Crate Attributes=\n");
+ 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");
+ out.write_str("\n\n");
}
fn get_crate_attributes(data: @[u8]) -> [ast::attribute] {
ret get_attributes(ebml::new_doc(data));
}
-type crate_dep = {cnum: ast::crate_num, ident: istr};
+type crate_dep = {cnum: ast::crate_num, ident: str};
fn get_crate_deps(data: @[u8]) -> [crate_dep] {
let deps: [crate_dep] = [];
}
fn list_crate_deps(data: @[u8], out: io::writer) {
- out.write_str(~"=External Dependencies=\n");
+ 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");
+ out.write_str("\n");
}
fn list_crate_items(bytes: &@[u8], md: &ebml::doc, out: io::writer) {
- out.write_str(~"=Items=\n");
+ out.write_str("=Items=\n");
let paths = ebml::get_doc(md, tag_paths);
let items = ebml::get_doc(md, tag_items);
let index = ebml::get_doc(paths, tag_index);
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");
+ out.write_str("\n");
}
fn list_crate_metadata(bytes: &@[u8], out: io::writer) {
type encode_ctxt = {ccx: @crate_ctxt, type_abbrevs: abbrev_map};
// Path table encoding
-fn encode_name(ebml_w: &ebml::writer, name: &istr) {
+fn encode_name(ebml_w: &ebml::writer, name: &str) {
ebml::start_tag(ebml_w, tag_paths_data_name);
ebml_w.writer.write(str::bytes(name));
ebml::end_tag(ebml_w);
type entry<T> = {val: T, pos: uint};
fn encode_tag_variant_paths(ebml_w: &ebml::writer, variants: &[variant],
- path: &[istr], index: &mutable [entry<istr>]) {
+ path: &[str], index: &mutable [entry<str>]) {
for variant: variant in variants {
add_to_index(ebml_w, path, index, variant.node.name);
ebml::start_tag(ebml_w, tag_paths_data_item);
}
}
-fn add_to_index(ebml_w: &ebml::writer, path: &[istr],
- index: &mutable [entry<istr>], name: &istr) {
+fn add_to_index(ebml_w: &ebml::writer, path: &[str],
+ index: &mutable [entry<str>], name: &str) {
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: &[istr],
- index: &mutable [entry<istr>]) {
+ 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_item);
}
fn encode_module_item_paths(ebml_w: &ebml::writer, module: &_mod,
- path: &[istr], index: &mutable [entry<istr>]) {
+ path: &[str], index: &mutable [entry<str>]) {
for it: @item in module.items {
if !ast_util::is_exported(it.ident, module) { cont; }
alt it.node {
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],
- index);
+ encode_native_module_item_paths(ebml_w, nmod, path + [it.ident],
+ index);
ebml::end_tag(ebml_w);
}
item_ty(_, tps) {
}
}
-fn encode_item_paths(ebml_w: &ebml::writer, crate: &@crate) -> [entry<istr>] {
- let index: [entry<istr>] = [];
- let path: [istr] = [];
+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);
ebml::end_tag(ebml_w);
}
-fn def_to_str(did: &def_id) -> istr {
- 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::end_tag(ebml_w);
}
-fn write_str(writer: &io::writer, s: &istr) {
- writer.write_str(s);
-}
+fn write_str(writer: &io::writer, s: &str) { writer.write_str(s); }
fn write_int(writer: &io::writer, n: &int) {
writer.write_be_uint(n as uint, 4u);
fn synthesize_link_attr(ecx: &@encode_ctxt, items: &[@meta_item]) ->
attribute {
- assert (ecx.ccx.link_meta.name != ~"");
- assert (ecx.ccx.link_meta.vers != ~"");
+ assert (ecx.ccx.link_meta.name != "");
+ assert (ecx.ccx.link_meta.vers != "");
let name_item =
- attr::mk_name_value_item_str(
- ~"name", ecx.ccx.link_meta.name);
+ attr::mk_name_value_item_str("name", ecx.ccx.link_meta.name);
let vers_item =
- attr::mk_name_value_item_str(
- ~"vers", ecx.ccx.link_meta.vers);
+ attr::mk_name_value_item_str("vers", ecx.ccx.link_meta.vers);
let other_items =
{
- let tmp = attr::remove_meta_items_by_name(items, ~"name");
- attr::remove_meta_items_by_name(tmp, ~"vers")
+ let tmp = attr::remove_meta_items_by_name(items, "name");
+ attr::remove_meta_items_by_name(tmp, "vers")
};
let meta_items = [name_item, vers_item] + other_items;
- let link_item = attr::mk_list_item(~"link", meta_items);
+ let link_item = attr::mk_list_item("link", meta_items);
ret attr::mk_attr(link_item);
}
let found_link_attr = false;
for attr: attribute in crate.node.attrs {
attrs +=
- if attr::get_attr_name(attr) != ~"link" {
+ if attr::get_attr_name(attr) != "link" {
[attr]
} else {
alt attr.node.value.node {
fn encode_crate_deps(ebml_w: &ebml::writer, cstore: &cstore::cstore) {
- fn get_ordered_names(cstore: &cstore::cstore) -> [istr] {
+ fn get_ordered_names(cstore: &cstore::cstore) -> [str] {
type hashkv = @{key: crate_num, val: cstore::crate_metadata};
- type numname = {crate: crate_num, ident: istr};
+ type numname = {crate: crate_num, ident: str};
// Pull the cnums and names out of cstore
let pairs: [mutable numname] = [mutable];
}
// Return just the names
- fn name(kv: &numname) -> istr { kv.ident }
+ fn name(kv: &numname) -> str { kv.ident }
// mutable -> immutable hack for vec::map
let immpairs = vec::slice(pairs, 0u, vec::len(pairs));
ret vec::map(name, immpairs);
// FIXME: This is not nearly enough to support correct versioning
// but is enough to get transitive crate dependencies working.
ebml::start_tag(ebml_w, tag_crate_deps);
- for cname: istr in get_ordered_names(cstore) {
+ for cname: str in get_ordered_names(cstore) {
ebml::start_tag(ebml_w, tag_crate_dep);
ebml_w.writer.write(str::bytes(cname));
ebml::end_tag(ebml_w);
ebml::end_tag(ebml_w);
}
-fn encode_metadata(cx: &@crate_ctxt, crate: &@crate) -> istr {
+fn encode_metadata(cx: &@crate_ctxt, crate: &@crate) -> str {
let abbrevs = map::mk_hashmap(ty::hash_ty, ty::eq_ty);
let ecx = @{ccx: cx, type_abbrevs: abbrevs};
}
// Get the encoded string for a type
-fn encoded_ty(tcx: &ty::ctxt, t: ty::t) -> istr {
+fn encoded_ty(tcx: &ty::ctxt, t: ty::t) -> str {
let cx = @{ds: def_to_str, tcx: tcx, abbrevs: tyencode::ac_no_abbrevs};
let sw = io::string_writer();
tyencode::enc_ty(sw.get_writer(), cx, t);
// data buffer. Whatever format you choose should not contain pipe characters.
// Callback to translate defs to strs or back:
-type str_def = fn(&istr) -> 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};
fn parse_ident_(st: @pstate, _sd: str_def, is_last: fn(char) -> bool) ->
ast::ident {
- let rslt = ~"";
+ let rslt = "";
while !is_last(peek(st) as char) {
rslt += str::unsafe_from_byte(next(st));
}
assert (next(st) as char == '[');
let fields: [ty::field] = [];
while peek(st) as char != ']' {
- let name = ~"";
+ let name = "";
while peek(st) as char != '=' {
name += str::unsafe_from_byte(next(st));
}
'W' { proto = ast::proto_iter; }
'F' { proto = ast::proto_fn; }
}
- let name = ~"";
+ let name = "";
while peek(st) as char != '[' {
name += str::unsafe_from_byte(next(st));
}
}
fn parse_def(st: @pstate, sd: str_def) -> ast::def_id {
- let def = ~"";
- while peek(st) as char != '|' {
- def += str::unsafe_from_byte(next(st));
- }
+ let def = "";
+ while peek(st) as char != '|' { def += str::unsafe_from_byte(next(st)); }
st.pos = st.pos + 1u;
ret sd(def);
}
export enc_ty;
type ctxt =
- // Def -> str Callback:
- // The type context.
- {ds: fn(&def_id) -> istr, tcx: ty::ctxt, abbrevs: abbrev_ctxt};
+ // Def -> str Callback:
+ // The type context.
+ {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.
// Whatever format you choose should not contain pipe characters.
-type ty_abbrev = {pos: uint, len: uint, s: @istr};
+type ty_abbrev = {pos: uint, len: uint, s: @str};
tag abbrev_ctxt { ac_no_abbrevs; ac_use_abbrevs(hashmap<ty::t, ty_abbrev>); }
fn enc_ty(w: &io::writer, cx: &@ctxt, t: ty::t) {
alt cx.abbrevs {
ac_no_abbrevs. {
- let result_str: @istr;
+ let result_str: @str;
alt cx.tcx.short_names_cache.find(t) {
some(s) { result_str = s; }
none. {
// I.e. it's actually an abbreviation.
let s =
- ~"#" + uint::to_str(pos, 16u) + ~":" +
- uint::to_str(len, 16u) + ~"#";
+ "#" + uint::to_str(pos, 16u) + ":" +
+ uint::to_str(len, 16u) + "#";
let a = {pos: pos, len: len, s: @s};
abbrevs.insert(t, a);
}
ty::ty_float. { w.write_char('l'); }
ty::ty_machine(mach) {
alt mach {
- ty_u8. { w.write_str(~"Mb"); }
- ty_u16. { w.write_str(~"Mw"); }
- ty_u32. { w.write_str(~"Ml"); }
- ty_u64. { w.write_str(~"Md"); }
- ty_i8. { w.write_str(~"MB"); }
- ty_i16. { w.write_str(~"MW"); }
- ty_i32. { w.write_str(~"ML"); }
- ty_i64. { w.write_str(~"MD"); }
- ty_f32. { w.write_str(~"Mf"); }
- ty_f64. { w.write_str(~"MF"); }
+ ty_u8. { w.write_str("Mb"); }
+ ty_u16. { w.write_str("Mw"); }
+ ty_u32. { w.write_str("Ml"); }
+ ty_u64. { w.write_str("Md"); }
+ ty_i8. { w.write_str("MB"); }
+ ty_i16. { w.write_str("MW"); }
+ ty_i32. { w.write_str("ML"); }
+ ty_i64. { w.write_str("MD"); }
+ ty_f32. { w.write_str("Mf"); }
+ ty_f64. { w.write_str("MF"); }
}
}
ty::ty_char. { w.write_char('c'); }
ty::ty_istr. { w.write_char('S'); }
ty::ty_tag(def, tys) {
- w.write_str(~"t[");
+ w.write_str("t[");
w.write_str(cx.ds(def));
w.write_char('|');
for t: ty::t in tys { enc_ty(w, cx, t); }
w.write_char(']');
}
ty::ty_tup(ts) {
- w.write_str(~"T[");
+ w.write_str("T[");
for t in ts { enc_ty(w, cx, t); }
w.write_char(']');
}
ty::ty_ptr(mt) { w.write_char('*'); enc_mt(w, cx, mt); }
ty::ty_vec(mt) { w.write_char('I'); enc_mt(w, cx, mt); }
ty::ty_rec(fields) {
- w.write_str(~"R[");
+ w.write_str("R[");
for field: ty::field in fields {
w.write_str(field.ident);
w.write_char('=');
enc_ty_fn(w, cx, args, out, return, []);
}
ty::ty_obj(methods) {
- w.write_str(~"O[");
+ w.write_str("O[");
for m: ty::method in methods {
enc_proto(w, m.proto);
w.write_str(m.ident);
w.write_char(']');
}
ty::ty_res(def, ty, tps) {
- w.write_str(~"r[");
+ w.write_str("r[");
w.write_str(cx.ds(def));
w.write_char('|');
enc_ty(w, cx, ty);
for t: ty::t in tps { enc_ty(w, cx, t); }
w.write_char(']');
}
- ty::ty_var(id) {
- w.write_char('X');
- w.write_str(int::str(id));
- }
+ ty::ty_var(id) { w.write_char('X'); w.write_str(int::str(id)); }
ty::ty_native(def) {
w.write_char('E');
w.write_str(cx.ds(def));
}
ty::ty_param(id, k) {
alt k {
- kind_unique. { w.write_str(~"pu"); }
- kind_shared. { w.write_str(~"ps"); }
- kind_pinned. { w.write_str(~"pp"); }
+ kind_unique. { w.write_str("pu"); }
+ kind_shared. { w.write_str("ps"); }
+ kind_pinned. { w.write_str("pp"); }
}
w.write_str(uint::str(id));
}
ty::ty_type. { w.write_char('Y'); }
ty::ty_constr(ty, cs) {
- w.write_str(~"A[");
+ w.write_str("A[");
enc_ty(w, cx, ty);
for tc: @ty::type_constr in cs { enc_ty_constr(w, cx, tc); }
w.write_char(']');
alt a.node {
carg_base. { w.write_char('*'); }
carg_ident(i) { w.write_uint(i); }
- carg_lit(l) {
- w.write_str(lit_to_str(l));
- }
+ carg_lit(l) { w.write_str(lit_to_str(l)); }
}
}
w.write_char(')');
if semi { w.write_char(';'); } else { semi = true; }
alt a.node {
carg_base. { w.write_char('*'); }
- carg_ident(p) {
- w.write_str(path_to_str(p)); }
- carg_lit(l) {
- w.write_str(lit_to_str(l)); }
+ carg_ident(p) { w.write_str(path_to_str(p)); }
+ carg_lit(l) { w.write_str(lit_to_str(l)); }
}
}
w.write_char(')');
type scope = @[restrict];
-tag local_info {
- local(uint);
-}
+tag local_info { local(uint); }
-type ctx = {tcx: ty::ctxt,
- local_map: std::map::hashmap<node_id, local_info>,
- mutable next_local: uint};
+type ctx =
+ {tcx: ty::ctxt,
+ local_map: std::map::hashmap<node_id, local_info>,
+ mutable next_local: uint};
fn check_crate(tcx: ty::ctxt, crate: &@ast::crate) {
// 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(),
- mutable next_local: 0u};
- let v = @{visit_fn: visit_fn,
- visit_expr: bind visit_expr(cx, _, _, _),
- visit_decl: bind visit_decl(cx, _, _, _)
- with *visit::default_visitor::<scope>()};
+ let cx =
+ @{tcx: tcx,
+ local_map: std::map::new_int_hash(),
+ mutable next_local: 0u};
+ let v =
+ @{visit_fn: visit_fn,
+ 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();
}
-fn visit_fn(f: &ast::_fn, _tp: &[ast::ty_param], _sp: &span,
- _name: &fn_ident, _id: ast::node_id, sc: &scope, v: &vt<scope>) {
+fn visit_fn(f: &ast::_fn, _tp: &[ast::ty_param], _sp: &span, _name: &fn_ident,
+ _id: ast::node_id, sc: &scope, v: &vt<scope>) {
visit::visit_fn_decl(f.decl, sc, v);
- let scope = alt f.proto {
- // Blocks need to obey any restrictions from the enclosing scope.
- ast::proto_block. | ast::proto_closure. { sc }
- // Non capturing functions start out fresh.
- _ { @[] }
- };
+ let scope =
+ alt f.proto {
+
+ // Blocks need to obey any restrictions from the enclosing scope.
+ ast::proto_block. | ast::proto_closure. {
+ sc
+ }
+
+ // Non capturing functions start out fresh.
+ _ {
+ @[]
+ }
+ };
v.visit_block(f.body, scope, v);
}
let root = expr_root(cx.tcx, ex, false);
if mut_field(root.ds) {
cx.tcx.sess.span_err(ex.span,
- ~"result of put must be" +
- ~" immutably rooted");
+ "result of put must be" +
+ " immutably rooted");
}
visit_expr(cx, ex, sc, v);
}
}
}
-fn check_call(cx: &ctx, f: &@ast::expr, args: &[@ast::expr], sc: &scope)
- -> [restrict] {
+fn check_call(cx: &ctx, f: &@ast::expr, args: &[@ast::expr], sc: &scope) ->
+ [restrict] {
let fty = ty::type_autoderef(cx.tcx, ty::expr_ty(cx.tcx, f));
let arg_ts = ty::ty_fn_args(cx.tcx, fty);
let mut_roots: [{arg: uint, node: node_id}] = [];
let dnum = ast_util::def_id_of_def(def).node;
mut_roots += [{arg: i, node: dnum}];
}
- _ {}
+ _ { }
}
}
let root_var = path_def_id(cx, root.ex);
- let unsafe_t = alt inner_mut(root.ds) {
- some(t) { some(t) }
- _ { none }
- };
- restricts += [@{root_var: root_var,
- local_id: cx.next_local,
- bindings: [arg.id],
- unsafe_ty: unsafe_t,
- depends_on: deps(sc, root_var),
- mutable ok: valid}];
+ let unsafe_t =
+ alt inner_mut(root.ds) { some(t) { some(t) } _ { none } };
+ restricts +=
+ [@{root_var: root_var,
+ local_id: cx.next_local,
+ bindings: [arg.id],
+ unsafe_ty: unsafe_t,
+ depends_on: deps(sc, root_var),
+ mutable ok: valid}];
}
i += 1u;
}
- let f_may_close = alt f.node {
- ast::expr_path(_) { def_is_local(cx.tcx.def_map.get(f.id), true) }
- _ { true }
- };
+ let f_may_close =
+ alt f.node {
+ ast::expr_path(_) { def_is_local(cx.tcx.def_map.get(f.id), true) }
+ _ { true }
+ };
if f_may_close {
let i = 0u;
for r in restricts {
cx.tcx.sess.span_err(f.span,
#fmt["function may alias with argument \
%u, which is not immutably rooted",
- i]);
+ i]);
}
i += 1u;
}
}
let j = 0u;
- for @{unsafe_ty, _} in restricts {
+ for @{unsafe_ty: unsafe_ty, _} in restricts {
alt unsafe_ty {
some(ty) {
let i = 0u;
for arg_t: ty::arg in arg_ts {
let mut_alias = arg_t.mode == ty::mo_alias(true);
if i != j &&
- ty_can_unsafely_include(cx, ty, arg_t.ty, mut_alias) {
- cx.tcx.sess.span_err(args[i].span,
+ ty_can_unsafely_include(cx, ty, arg_t.ty, mut_alias) {
+ cx.tcx.sess.span_err(
+ args[i].span,
#fmt["argument %u may alias with argument %u, \
- which is not immutably rooted", i, j]);
+ which is not immutably rooted",
+ i, j]);
}
i += 1u;
}
}
- _ {}
+ _ { }
}
j += 1u;
}
// Ensure we're not passing a root by mutable alias.
- for {node, arg} in mut_roots {
+ for {node: node, arg: arg} in mut_roots {
let mut_alias_to_root = false;
let mut_alias_to_root_count = 0u;
- for @{root_var, _} in restricts {
+ for @{root_var: root_var, _} in restricts {
alt root_var {
some(root) {
if node == root {
}
}
}
- none. {}
+ none. { }
}
}
if mut_alias_to_root {
cx.tcx.sess.span_err(args[arg].span,
- ~"passing a mutable alias to a variable \
+ "passing a mutable alias to a variable \
that roots another alias");
}
}
let new_sc = sc;
if vec::len(dnums) > 0u {
let root_var = path_def_id(cx, root.ex);
- new_sc = @(*sc + [@{root_var: root_var,
- local_id: cx.next_local,
- bindings: dnums,
- unsafe_ty: inner_mut(root.ds),
- depends_on: deps(sc, root_var),
- mutable ok: valid}]);
+ new_sc =
+ @(*sc +
+ [@{root_var: root_var,
+ local_id: cx.next_local,
+ bindings: dnums,
+ unsafe_ty: inner_mut(root.ds),
+ depends_on: deps(sc, root_var),
+ mutable ok: valid}]);
}
register_locals(cx, a.pats[0]);
visit::visit_arm(a, new_sc, v);
ty::ty_vec(mt) { if mt.mut != ast::imm { unsafe = some(seq_t); } }
ty::ty_istr. {/* no-op */ }
_ {
- cx.tcx.sess.span_unimpl(seq.span, ~"unknown seq type " +
- util::ppaux::ty_to_str(cx.tcx, seq_t));
+ cx.tcx.sess.span_unimpl(seq.span,
+ "unknown seq type " +
+ util::ppaux::ty_to_str(cx.tcx, seq_t));
}
}
let root_var = path_def_id(cx, root.ex);
let def = cx.tcx.def_map.get(id);
if !def_is_local(def, true) { ret; }
let my_defnum = ast_util::def_id_of_def(def).node;
- let my_local_id = alt cx.local_map.find(my_defnum) {
- some(local(id)) { id }
- _ { 0u }
- };
+ let my_local_id =
+ alt cx.local_map.find(my_defnum) { some(local(id)) { id } _ { 0u } };
let var_t = ty::expr_ty(cx.tcx, ex);
for r: restrict in *sc {
+
// excludes variables introduced since the alias was made
if my_local_id < r.local_id {
alt r.unsafe_ty {
r.ok = val_taken(ex.span, p);
}
}
- _ {}
+ _ { }
}
} else if vec::member(my_defnum, r.bindings) {
test_scope(cx, sc, r, p);
let def = cx.tcx.def_map.get(dest.id);
let dnum = ast_util::def_id_of_def(def).node;
for r: restrict in *sc {
- if r.root_var == some(dnum) {
- r.ok = overwritten(dest.span, p);
- }
+ if r.root_var == some(dnum) { r.ok = overwritten(dest.span, p); }
}
}
_ { visit_expr(cx, dest, sc, v); }
let msg =
alt prob {
overwritten(sp, wpt) {
- {span: sp, msg: ~"overwriting " +
- ast_util::path_name(wpt)}
+ {span: sp, msg: "overwriting " + ast_util::path_name(wpt)}
}
val_taken(sp, vpt) {
{span: sp,
- msg: ~"taking the value of " +
- ast_util::path_name(vpt)}
+ msg: "taking the value of " + ast_util::path_name(vpt)}
}
};
cx.tcx.sess.span_err(msg.span,
- msg.msg + ~" will invalidate alias " +
- ast_util::path_name(p) +
- ~", which is still used");
+ msg.msg + " will invalidate alias " +
+ ast_util::path_name(p) +
+ ", which is still used");
}
}
i += 1u;
}
}
- _ {}
+ _ { }
}
ret result;
}
}
+
// 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
fn def_is_local(d: &ast::def, objfields_count: bool) -> bool {
ret alt d {
- ast::def_local(_) | ast::def_arg(_, _) | ast::def_binding(_) |
- ast::def_upvar(_, _, _) { true }
- ast::def_obj_field(_, _) { objfields_count }
- _ { false }
- };
+ ast::def_local(_) | ast::def_arg(_, _) | ast::def_binding(_) |
+ ast::def_upvar(_, _, _) {
+ true
+ }
+ ast::def_obj_field(_, _) { objfields_count }
+ _ { false }
+ };
}
// Local Variables:
fn test_node_span_item() {
let expected: codemap::span = ast_util::mk_sp(20u, 30u);
let node =
- node_item(@{ident: ~"test",
+ node_item(@{ident: "test",
attrs: [],
id: 0,
node: item_mod({view_items: [], items: []}),
fn test_node_span_obj_ctor() {
let expected: codemap::span = ast_util::mk_sp(20u, 30u);
let node =
- node_obj_ctor(@{ident: ~"test",
+ node_obj_ctor(@{ident: "test",
attrs: [],
id: 0,
node: item_mod({view_items: [], items: []}),
fn test_node_span_native_item() {
let expected: codemap::span = ast_util::mk_sp(20u, 30u);
let node =
- node_native_item(@{ident: ~"test",
+ node_native_item(@{ident: "test",
attrs: [],
node: native_item_ty,
id: 0,
j += 1;
}
if !reachable {
- tcx.sess.span_err(arm_pat.span, ~"unreachable pattern");
+ tcx.sess.span_err(arm_pat.span, "unreachable pattern");
}
}
i += 1;
visit::visit_local(loc, s, v);
if is_refutable(tcx, loc.node.pat) {
tcx.sess.span_err(loc.node.pat.span,
- ~"refutable pattern in local binding");
+ "refutable pattern in local binding");
}
}
// Since we want to be able to collect upvars in some arbitrary piece
// 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,
- walker: &fn(&visit::vt<int>)) -> freevar_info {
+fn collect_freevars(def_map: &resolve::def_map, walker: &fn(&visit::vt<int>))
+ -> freevar_info {
let seen = new_int_hash();
let refs = @mutable [];
- fn ignore_item(_i: &@ast::item, _depth: &int, _v: &visit::vt<int>) {}
+ fn ignore_item(_i: &@ast::item, _depth: &int, _v: &visit::vt<int>) { }
- let walk_expr = lambda(expr: &@ast::expr, depth: &int,
- v: &visit::vt<int>) {
- alt expr.node {
- ast::expr_fn(f) {
- if f.proto == ast::proto_block ||
- f.proto == ast::proto_closure {
- visit::visit_expr(expr, depth + 1, v);
- }
- }
- ast::expr_for_each(dcl, x, b) {
- v.visit_local(dcl, depth, v);
- v.visit_expr(x, depth, v);
- v.visit_block(b, depth + 1, v);
- }
- ast::expr_path(path) {
- let def = def_map.get(expr.id), i = 0;
- while i < depth {
- alt {def} {
- ast::def_upvar(_, inner, _) {
- def = *inner;
- }
- _ { break; }
+ let walk_expr =
+ lambda (expr: &@ast::expr, depth: &int, v: &visit::vt<int>) {
+ alt expr.node {
+ ast::expr_fn(f) {
+ if f.proto == ast::proto_block ||
+ f.proto == ast::proto_closure {
+ visit::visit_expr(expr, depth + 1, v);
}
- i += 1;
- }
- if i == depth { // Made it to end of loop
- let dnum = ast_util::def_id_of_def(def).node;
- if !seen.contains_key(dnum) {
- *refs += [def];
- seen.insert(dnum, ());
+ }
+ ast::expr_for_each(dcl, x, b) {
+ v.visit_local(dcl, depth, v);
+ v.visit_expr(x, depth, v);
+ v.visit_block(b, depth + 1, v);
+ }
+ ast::expr_path(path) {
+ let def = def_map.get(expr.id), i = 0;
+ while i < depth {
+ alt { def } {
+ ast::def_upvar(_, inner, _) { def = *inner; }
+ _ { break; }
+ }
+ i += 1;
}
+ if i == depth { // Made it to end of loop
+ let dnum = ast_util::def_id_of_def(def).node;
+ if !seen.contains_key(dnum) {
+ *refs += [def];
+ seen.insert(dnum, ());
+ }
+ }
+ }
+ _ { visit::visit_expr(expr, depth, v); }
}
- }
- _ { visit::visit_expr(expr, depth, v); }
- }
- };
+ };
- walker(visit::mk_vt(@{visit_item: ignore_item,
- visit_expr: walk_expr
- with *visit::default_visitor()}));
+ walker(visit::mk_vt(@{visit_item: ignore_item, visit_expr: walk_expr
+ with *visit::default_visitor()}));
ret @*refs;
}
// efficient as it fully recomputes the free variables at every
// node of interest rather than building up the free variables in
// one pass. This could be improved upon if it turns out to matter.
-fn annotate_freevars(def_map: &resolve::def_map,
- crate: &@ast::crate) -> freevar_map {
+fn annotate_freevars(def_map: &resolve::def_map, 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<int>) {
- v.visit_fn(f, tps, sp, i, nid, 1, v);
- };
- let vars = collect_freevars(def_map, 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<int>) {
- v.visit_block(body, 1, 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<int>) {
+ v.visit_fn(f, tps, sp, i, nid, 1, v);
+ };
let vars = collect_freevars(def_map, start_walk);
- freevars.insert(body.node.id, vars);
- }
- _ { }
- }
- };
+ 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<int>) {
+ v.visit_block(body, 1, v);
+ };
+ let vars = collect_freevars(def_map, start_walk);
+ freevars.insert(body.node.id, vars);
+ }
+ _ { }
+ }
+ };
let visitor =
visit::mk_simple_visitor(@{visit_fn: walk_fn, visit_expr: walk_expr
fn get_freevars(tcx: &ty::ctxt, fid: ast::node_id) -> freevar_info {
alt tcx.freevars.find(fid) {
- none. {
- fail ~"get_freevars: " + int::str(fid)
- + ~" has no freevars";
- }
+ none. { fail "get_freevars: " + int::str(fid) + " has no freevars"; }
some(d) { ret d; }
}
}
import lib::llvm::True;
import lib::llvm::llvm::ValueRef;
import middle::trans;
-import middle::trans::{ get_tydesc, tps_normal };
+import middle::trans::{get_tydesc, tps_normal};
import middle::trans_common::*;
import middle::ty;
import std::option::none;
fn mk_ctxt() -> ctxt { ret @{mutable next_tydesc_num: 0u}; }
-fn add_global(ccx: &@crate_ctxt, llval: ValueRef, name: &istr) -> ValueRef {
- let llglobal = str::as_buf(name, { |buf|
- lll::LLVMAddGlobal(ccx.llmod, val_ty(llval), buf)
- });
+fn add_global(ccx: &@crate_ctxt, llval: ValueRef, name: &str) -> ValueRef {
+ let llglobal =
+ str::as_buf(name,
+ {|buf|
+ lll::LLVMAddGlobal(ccx.llmod, val_ty(llval), buf)
+ });
lll::LLVMSetInitializer(llglobal, llval);
lll::LLVMSetGlobalConstant(llglobal, True);
ret llglobal;
bcx = td_r.result.bcx;
let lltydesc = td_r.result.val;
- let gcroot = bcx_ccx(bcx).intrinsics.get(~"llvm.gcroot");
+ let gcroot = bcx_ccx(bcx).intrinsics.get("llvm.gcroot");
let llvalptr = bld::PointerCast(bcx, llval, T_ptr(T_ptr(T_i8())));
alt td_r.kind {
let lldestindex =
add_global(bcx_ccx(bcx), C_struct([C_int(0), C_uint(number)]),
- ~"rust_gc_tydesc_dest_index");
+ "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");
+ "rust_gc_tydesc_src_index");
lldestindex = lll::LLVMConstPointerCast(lldestindex, T_ptr(T_i8()));
llsrcindex = lll::LLVMConstPointerCast(llsrcindex, T_ptr(T_i8()));
- lltydescptr = bld::PointerCast(llderivedtydescs, lltydescptr,
- T_ptr(T_ptr(T_i8())));
+ lltydescptr =
+ bld::PointerCast(llderivedtydescs, lltydescptr,
+ T_ptr(T_ptr(T_i8())));
bld::Call(llderivedtydescs, gcroot, [lltydescptr, lldestindex]);
bld::Call(bcx, gcroot, [llvalptr, llsrcindex]);
}
tk_param. {
- bcx_tcx(cx).sess.bug(~"we should never be trying to root values " +
- ~"of a type parameter");
+ 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");
+ "rust_gc_tydesc_static_gc_meta");
let llstaticgcmetaptr =
lll::LLVMConstPointerCast(llstaticgcmeta, T_ptr(T_i8()));
}
+
ty::ty_rec(fields) {
for f in fields { if type_is_gc_relevant(cx, f.mt.ty) { ret true; } }
ret false;
}
+
ty::ty_tag(did, tps) {
let variants = ty::tag_variants(cx, did);
for variant in variants {
}
+
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_box(_) | ty::ty_uniq(_) | ty::ty_fn(_, _, _, _, _)
- | ty::ty_native_fn(_, _, _) | ty::ty_obj(_) | ty::ty_param(_, _) |
+
+ 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";
}
if kind_lteq(a, b) { a } else { b }
}
-fn kind_to_str(k: kind) -> istr {
+fn kind_to_str(k: kind) -> str {
alt k {
- ast::kind_pinned. { ~"pinned" }
- ast::kind_unique. { ~"unique" }
- ast::kind_shared. { ~"shared" }
+ ast::kind_pinned. { "pinned" }
+ ast::kind_unique. { "unique" }
+ ast::kind_shared. { "shared" }
}
}
}
fn need_expr_kind(tcx: &ty::ctxt, e: &@ast::expr, k_need: ast::kind,
- descr: &istr) {
+ 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),
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),
+ 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,
- op: &istr) {
- need_expr_kind(tcx, a, ast::kind_shared, op + ~" lhs");
- need_expr_kind(tcx, b, ast::kind_shared, op + ~" rhs");
+ op: &str) {
+ need_expr_kind(tcx, a, ast::kind_shared, op + " lhs");
+ need_expr_kind(tcx, b, ast::kind_shared, op + " rhs");
}
fn check_expr(tcx: &ty::ctxt, e: &@ast::expr) {
alt e.node {
- ast::expr_move(a, b) { need_shared_lhs_rhs(tcx, a, b, ~"<-"); }
- ast::expr_assign(a, b) { need_shared_lhs_rhs(tcx, a, b, ~"="); }
- ast::expr_assign_op(_, a, b) { need_shared_lhs_rhs(tcx, a, b, ~"op="); }
- ast::expr_swap(a, b) { need_shared_lhs_rhs(tcx, a, b, ~"<->"); }
+ ast::expr_move(a, b) { need_shared_lhs_rhs(tcx, a, b, "<-"); }
+ ast::expr_assign(a, b) { need_shared_lhs_rhs(tcx, a, b, "="); }
+ ast::expr_assign_op(_, a, b) { need_shared_lhs_rhs(tcx, a, b, "op="); }
+ ast::expr_swap(a, b) { need_shared_lhs_rhs(tcx, a, b, "<->"); }
ast::expr_copy(a) {
- need_expr_kind(tcx, a, ast::kind_shared, ~"'copy' operand");
+ need_expr_kind(tcx, a, ast::kind_shared, "'copy' operand");
}
ast::expr_ret(option::some(a)) {
- need_expr_kind(tcx, a, ast::kind_shared, ~"'ret' operand");
+ need_expr_kind(tcx, a, ast::kind_shared, "'ret' operand");
}
ast::expr_be(a) {
- need_expr_kind(tcx, a, ast::kind_shared, ~"'be' operand");
+ need_expr_kind(tcx, a, ast::kind_shared, "'be' operand");
}
ast::expr_fail(option::some(a)) {
- need_expr_kind(tcx, a, ast::kind_shared, ~"'fail' operand");
+ need_expr_kind(tcx, a, ast::kind_shared, "'fail' operand");
}
ast::expr_call(callee, _) {
let tpt = ty::expr_ty_params_and_ty(tcx, callee);
// that all the types we're supplying as typarams conform to the
// typaram kind constraints on that item.
if vec::len(tpt.params) != 0u {
- let callee_def = ast_util::def_id_of_def(
- tcx.def_map.get(callee.id));
+ let callee_def =
+ ast_util::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));
// vec of dereferences that were used on this root. Note that, in this vec,
// the inner derefs come in front, so foo.bar[1] becomes rec(ex=foo,
// ds=[index,field])
-fn expr_root(tcx: &ty::ctxt, ex: @expr, autoderef: bool)
- -> {ex: @expr, ds: @[deref]} {
+fn expr_root(tcx: &ty::ctxt, ex: @expr, autoderef: bool) ->
+ {ex: @expr, ds: @[deref]} {
fn maybe_auto_unbox(tcx: &ty::ctxt, t: ty::t) -> {t: ty::t, ds: [deref]} {
let ds = [];
while true {
ty::ty_tag(did, tps) {
let variants = ty::tag_variants(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}];
- t =
- ty::substitute_type_params(tcx, tps,
- variants[0].args[0]);
+ t = ty::substitute_type_params(tcx, tps, variants[0].args[0]);
}
_ { break; }
}
fn check_crate(tcx: ty::ctxt, crate: &@crate) -> mut_map {
let cx = @{tcx: tcx, mut_map: std::map::new_int_hash()};
- let v = @{visit_expr: bind visit_expr(cx, _, _, _),
- visit_decl: bind visit_decl(cx, _, _, _)
- with *visit::default_visitor::<()>()};
+ let v =
+ @{visit_expr: bind visit_expr(cx, _, _, _),
+ visit_decl: bind visit_decl(cx, _, _, _)
+ with *visit::default_visitor::<()>()};
visit::visit_crate(*crate, (), visit::mk_vt(v));
ret cx.mut_map;
}
tag msg { msg_assign; msg_move_out; msg_mut_alias; }
-fn mk_err(cx: &@ctx, span: &syntax::codemap::span, msg: msg, name: &istr) {
- cx.tcx.sess.span_err(span, alt msg {
- msg_assign. { ~"assigning to " + name }
- msg_move_out. { ~"moving out of " + name }
- msg_mut_alias. { ~"passing " + name + ~" by mutable alias" }
- });
+fn mk_err(cx: &@ctx, span: &syntax::codemap::span, msg: msg, name: &str) {
+ cx.tcx.sess.span_err(span,
+ alt msg {
+ msg_assign. { "assigning to " + name }
+ msg_move_out. { "moving out of " + name }
+ msg_mut_alias. {
+ "passing " + name + " by mutable alias"
+ }
+ });
}
fn visit_decl(cx: &@ctx, d: &@decl, e: &(), v: &visit::vt<()>) {
for loc: @local in locs {
alt loc.node.init {
some(init) {
- if init.op == init_move {
- check_move_rhs(cx, init.expr);
- }
+ if init.op == init_move { check_move_rhs(cx, init.expr); }
}
none. { }
}
fn visit_expr(cx: &@ctx, ex: &@expr, e: &(), v: &visit::vt<()>) {
alt ex.node {
- expr_call(f, args) {
- check_call(cx, f, args);
- }
+ expr_call(f, args) { check_call(cx, f, args); }
expr_swap(lhs, rhs) {
check_lval(cx, lhs, msg_assign);
check_lval(cx, rhs, msg_assign);
expr_assign(dest, src) | expr_assign_op(_, dest, src) {
check_lval(cx, dest, msg_assign);
}
- _ {}
+ _ { }
}
visit::visit_expr(ex, e, v);
}
let def = cx.tcx.def_map.get(dest.id);
alt is_immutable_def(def) {
some(name) { mk_err(cx, dest.span, msg, name); }
- _ {}
+ _ { }
}
cx.mut_map.insert(ast_util::def_id_of_def(def).node, ());
}
_ {
let root = expr_root(cx.tcx, dest, false);
if vec::len(*root.ds) == 0u {
- mk_err(cx, dest.span, msg, ~"non-lvalue");
+ mk_err(cx, dest.span, msg, "non-lvalue");
} else if !root.ds[0].mut {
- let name = alt root.ds[0].kind {
- mut::unbox. { ~"immutable box" }
- mut::field. { ~"immutable field" }
- mut::index. { ~"immutable vec content" }
- };
+ let name =
+ alt root.ds[0].kind {
+ mut::unbox. { "immutable box" }
+ mut::field. { "immutable field" }
+ mut::index. { "immutable vec content" }
+ };
mk_err(cx, dest.span, msg, name);
}
}
expr_path(p) {
alt cx.tcx.def_map.get(src.id) {
def_obj_field(_, _) {
- mk_err(cx, src.span, msg_move_out, ~"object field");
+ mk_err(cx, src.span, msg_move_out, "object field");
}
_ { }
}
}
_ {
let root = expr_root(cx.tcx, src, false);
+
// Not a path and no-derefs means this is a temporary.
if vec::len(*root.ds) != 0u {
- cx.tcx.sess.span_err(src.span, ~"moving out of a data structure");
+ cx.tcx.sess.span_err(src.span, "moving out of a data structure");
}
}
}
}
fn check_call(cx: &@ctx, f: &@expr, args: &[@expr]) {
- let arg_ts = ty::ty_fn_args(cx.tcx, ty::type_autoderef
- (cx.tcx, ty::expr_ty(cx.tcx, f)));
+ let arg_ts =
+ ty::ty_fn_args(cx.tcx,
+ ty::type_autoderef(cx.tcx, ty::expr_ty(cx.tcx, f)));
let i = 0u;
for arg_t: ty::arg in arg_ts {
if arg_t.mode == ty::mo_alias(true) {
}
}
-fn is_immutable_def(def: &def) -> option::t<istr> {
+fn is_immutable_def(def: &def) -> option::t<str> {
alt def {
def_fn(_, _) | def_mod(_) | def_native_mod(_) | def_const(_) |
- def_use(_) { some(~"static item") }
- def_obj_field(_, imm.) { some(~"immutable object field") }
- def_arg(_, alias(false)) { some(~"immutable alias") }
+ def_use(_) {
+ some("static item")
+ }
+ def_obj_field(_, imm.) { some("immutable object field") }
+ def_arg(_, alias(false)) { some("immutable alias") }
def_upvar(_, inner, mut) {
- if !mut { some(~"upvar") }
- else { is_immutable_def(*inner) }
+ if !mut { some("upvar") } else { is_immutable_def(*inner) }
}
- def_binding(_) { some(~"binding") }
+ def_binding(_) { some("binding") }
_ { none }
}
}
option::t<def>); /* module */
}
-type ext_hash = hashmap<{did: def_id, ident: istr, ns: namespace}, def>;
+type ext_hash = hashmap<{did: def_id, ident: str, ns: namespace}, def>;
fn new_ext_hash() -> ext_hash {
- type key = {did: def_id, ident: istr, ns: namespace};
+ type key = {did: def_id, ident: str, ns: namespace};
fn hash(v: &key) -> uint {
ret str::hash(v.ident) + util::common::hash_def(v.did) +
alt v.ns {
{m: option::t<ast::_mod>,
index: mod_index,
mutable glob_imports: [glob_imp_def],
- glob_imported_names: hashmap<istr, import_state>};
+ glob_imported_names: hashmap<str, import_state>};
/* native modules can't contain tags, and we don't store their ASTs because we
mod_map: hashmap<ast::node_id, @indexed_mod>,
ext_map: hashmap<def_id, [ident]>,
ext_cache: ext_hash,
- mutable reported: [{ident: istr, sc: scope}],
+ mutable reported: [{ident: str, sc: scope}],
sess: session};
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);
}
_ {
e.sess.span_err(p.span,
- ~"not a tag variant: " +
- ast_util::path_name(p));
+ "not a tag variant: " +
+ ast_util::path_name(p));
}
}
}
ast::def_mod(_) | ast::def_native_mod(_) { ret dcur; }
_ {
e.sess.span_err(sp,
- str::connect(path, ~"::") +
- ~" does not name a module.");
+ str::connect(path, "::") +
+ " does not name a module.");
ret none;
}
}
}
_ {
e.sess.span_err(c.span,
- ~"Non-predicate in constraint: " +
- path_to_str(c.node.path));
+ "Non-predicate in constraint: " +
+ path_to_str(c.node.path));
}
}
}
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 ()
}
{
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)
}
val: &option::t<def>, typ: &option::t<def>,
md: &option::t<def>) {
if is_none(val) && is_none(typ) && is_none(md) {
- unresolved_err(e, sc, sp, name, ~"import");
+ unresolved_err(e, sc, sp, name, "import");
} else { e.imports.insert(defid.node, resolved(val, typ, md)); }
}
fn remove_if_unresolved(imports: hashmap<ast::node_id, import_state>,
// Utilities
-fn ns_name(ns: namespace) -> istr {
+fn ns_name(ns: namespace) -> str {
alt ns {
- ns_type. { ret ~"typename"; }
- ns_value. { ret ~"name"; }
- ns_module. { ret ~"modulename"; }
+ ns_type. { ret "typename"; }
+ ns_value. { ret "name"; }
+ ns_module. { ret "modulename"; }
}
}
-fn unresolved_err(e: &env, sc: &scopes, sp: &span,
- name: &ident, kind: &istr) {
+fn unresolved_err(e: &env, sc: &scopes, sp: &span, name: &ident, kind: &str) {
fn find_fn_or_mod_scope(sc: scopes) -> scope {
while true {
alt sc {
fail;
}
let err_scope = find_fn_or_mod_scope(sc);
- for rs: {ident: istr, sc: scope} in e.reported {
- if str::eq(rs.ident, name)
- && err_scope == rs.sc { ret; }
+ 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.sess.span_err(sp, mk_unresolved_msg(name, kind));
}
-fn unresolved_fatal(e: &env, sp: &span, id: &ident, kind: &istr) -> ! {
+fn unresolved_fatal(e: &env, sp: &span, id: &ident, kind: &str) -> ! {
e.sess.span_fatal(sp, mk_unresolved_msg(id, kind));
}
-fn mk_unresolved_msg(id: &ident, kind: &istr) -> istr {
+fn mk_unresolved_msg(id: &ident, kind: &str) -> str {
ret #fmt["unresolved %s: %s", kind, id];
}
fn lookup_in_scope_strict(e: &env, sc: scopes, sp: &span, name: &ident,
ns: namespace) -> option::t<def> {
alt lookup_in_scope(e, sc, sp, name, ns) {
- none. { unresolved_err(e, sc, sp, name,
- ns_name(ns)); ret none; }
+ none. { unresolved_err(e, sc, sp, name, ns_name(ns)); ret none; }
some(d) { ret some(d); }
}
}
fn def_is_local(d: &def) -> bool {
ret alt d {
- ast::def_arg(_, _) | ast::def_local(_) | ast::def_binding(_) |
- ast::def_upvar(_, _, _) { true }
- _ { false }
- };
+ ast::def_arg(_, _) | ast::def_local(_) | ast::def_binding(_) |
+ ast::def_upvar(_, _, _) {
+ true
+ }
+ _ { false }
+ };
}
fn def_is_obj_field(d: &def) -> bool {
if !is_none(fnd) {
let df = option::get(fnd);
let local = def_is_local(df);
- if left_fn && local ||
- left_fn_level2 && def_is_obj_field(df) ||
- scope_is_fn(hd) && left_fn && def_is_ty_arg(df) {
- let msg = alt ns {
- ns_type. {
- ~"Attempt to use a type argument out of scope"
- }
- _ {
- ~"attempted dynamic environment-capture"
- }
- };
+ if left_fn && local || left_fn_level2 && def_is_obj_field(df)
+ || scope_is_fn(hd) && left_fn && def_is_ty_arg(df) {
+ let msg =
+ alt ns {
+ ns_type. {
+ "Attempt to use a type argument out of scope"
+ }
+ _ { "attempted dynamic environment-capture" }
+ };
e.sess.span_fatal(sp, msg);
} else if local {
let i = vec::len(closing);
while i > 0u {
i -= 1u;
- df = ast::def_upvar(ast_util::def_id_of_def(df),
- @df, closing[i]);
+ df =
+ ast::def_upvar(ast_util::def_id_of_def(df), @df,
+ closing[i]);
fnd = some(df);
}
}
left_fn_level2 = true;
} else if ns == ns_value || ns == ns_type {
left_fn = scope_is_fn(hd);
- alt scope_closes(hd) {
- some(mut) { closing += [mut]; }
- _ {}
- }
+ alt scope_closes(hd) { some(mut) { closing += [mut]; } _ { } }
}
sc = *tl;
}
}
}
- e.sess.bug(~"reached unreachable code in lookup_in_scope"); // sigh
+ e.sess.bug("reached unreachable code in lookup_in_scope"); // sigh
}
fn lookup_in_mod_strict(e: &env, sc: &scopes, m: def, sp: &span, name: &ident,
ns: namespace, dr: dir) -> option::t<def> {
alt lookup_in_mod(e, m, sp, name, ns, dr) {
- none. { unresolved_err(e, sc, sp, name,
- ns_name(ns)); ret none; }
+ none. { unresolved_err(e, sc, sp, name, ns_name(ns)); ret none; }
some(d) { ret some(d); }
}
}
if defid.crate != ast::local_crate {
// examining a module in an external crate
- let cached = e.ext_cache.find({did: defid,
- ident: name, ns: ns});
+ let cached = e.ext_cache.find({did: defid, ident: name, ns: ns});
if !is_none(cached) { ret cached; }
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) {
- e.ext_cache.insert({did: defid,
- ident: name, ns: ns},
+ e.ext_cache.insert({did: defid, ident: name, ns: ns},
option::get(fnd));
}
ret fnd;
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; }
+ resolving(sp) { e.sess.span_err(sp, "cyclic import"); ret none; }
resolved(val, typ, md) {
ret alt ns { ns_value. { val } ns_type. { typ } ns_module. { md } };
}
} 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" +
- ~" multiple different modules.");
+ "'" + id + "' is glob-imported from" +
+ " multiple different modules.");
}
}
// since we don't know what names we have in advance,
let val = per_ns(e, info, sp, id, ns_value, dr);
let typ = per_ns(e, info, sp, id, ns_type, dr);
let md = per_ns(e, info, sp, id, ns_module, dr);
- info.glob_imported_names.insert(id,
- resolved(val, typ, md));
+ info.glob_imported_names.insert(id, resolved(val, typ, md));
}
alt info.glob_imported_names.get(id) {
- todo(_, _, _, _, _) { e.sess.bug(~"Shouldn't've put a todo in."); }
+ todo(_, _, _, _, _) { e.sess.bug("Shouldn't've put a todo in."); }
resolving(sp) {
ret none::<def>; //circularity is okay in import globs
// Module indexing
-fn add_to_index(index: &hashmap<ident, list<mod_index_entry>>,
- id: &ident, ent: &mod_index_entry) {
+fn add_to_index(index: &hashmap<ident, list<mod_index_entry>>, id: &ident,
+ ent: &mod_index_entry) {
alt index.find(id) {
- none. { index.insert(id,
- cons(ent, @nil::<mod_index_entry>)); }
+ none. { index.insert(id, cons(ent, @nil::<mod_index_entry>)); }
some(prev) { index.insert(id, cons(ent, @prev)); }
}
}
}
+
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(_, _) {
}
let saw_mod = false;
let saw_type = false;
let saw_value = false;
- fn dup(e: &env, sp: &span, word: &istr, name: &ident) {
- e.sess.span_fatal(sp, ~"duplicate definition of " +
- word + name);
+ fn dup(e: &env, sp: &span, word: &str, name: &ident) {
+ e.sess.span_fatal(sp, "duplicate definition of " + word + name);
}
while true {
alt entries {
cons(entry, rest) {
if !is_none(lookup_in_mie(e, entry, ns_value)) {
if saw_value {
- dup(e, mie_span(entry), ~"", name);
+ dup(e, mie_span(entry), "", name);
} else { saw_value = true; }
}
if !is_none(lookup_in_mie(e, entry, ns_type)) {
if saw_type {
- dup(e, mie_span(entry), ~"type ", name);
+ dup(e, mie_span(entry), "type ", name);
} else { saw_type = true; }
}
if !is_none(lookup_in_mie(e, entry, ns_module)) {
if saw_mod {
- dup(e, mie_span(entry), ~"module ", name);
+ dup(e, mie_span(entry), "module ", name);
} else { saw_mod = true; }
}
entries = *rest;
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");
+ "type parameter");
}
ast::item_obj(ob, ty_params, _) {
fn field_name(field: &ast::obj_field) -> ident { ret field.ident; }
- ensure_unique(*e, i.span, ob.fields, field_name, ~"object field");
+ ensure_unique(*e, i.span, ob.fields, field_name, "object field");
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");
+ "type parameter");
}
ast::item_tag(_, ty_params) {
ensure_unique(*e, i.span, typaram_names(ty_params), ident_id,
- ~"type parameter");
+ "type parameter");
}
_ { }
}
fn check_arm(e: &@env, a: &ast::arm, x: &(), v: &vt<()>) {
visit::visit_arm(a, x, v);
- let ch0 = checker(*e, ~"binding");
+ let ch0 = checker(*e, "binding");
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");
+ let ch = checker(*e, "binding");
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,
- ~"inconsistent number of bindings");
+ "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,
- ~"binding " + name_ +
- ~" does not occur in first pattern");
+ "binding " + name_ +
+ " does not occur in first pattern");
}
}
}
fn check_block(e: &@env, b: &ast::blk, x: &(), v: &vt<()>) {
visit::visit_block(b, x, v);
- let values = checker(*e, ~"value");
- let types = checker(*e, ~"type");
- let mods = checker(*e, ~"module");
+ let values = checker(*e, "value");
+ let types = checker(*e, "type");
+ let mods = checker(*e, "module");
for st: @ast::stmt in b.node.stmts {
alt st.node {
ast::stmt_decl(d, _) {
alt d.node {
ast::decl_local(locs) {
- let local_values = checker(*e, ~"value");
+ let local_values = checker(*e, "value");
for loc in locs {
for each p in ast_util::pat_bindings(loc.node.pat) {
let ident = alt p.node { pat_bind(n) { n } };
fn check_fn(e: &env, sp: &span, f: &ast::_fn) {
fn arg_name(a: &ast::arg) -> ident { ret a.ident; }
- ensure_unique(e, sp, f.decl.inputs, arg_name, ~"argument");
+ ensure_unique(e, sp, f.decl.inputs, arg_name, "argument");
}
fn check_expr(e: &@env, ex: &@ast::expr, x: &(), v: &vt<()>) {
alt ex.node {
ast::expr_rec(fields, _) {
fn field_name(f: &ast::field) -> ident { ret f.node.ident; }
- ensure_unique(*e, ex.span, fields, field_name, ~"field");
+ ensure_unique(*e, ex.span, fields, field_name, "field");
}
_ { }
}
alt ty.node {
ast::ty_rec(fields) {
fn field_name(f: &ast::ty_field) -> ident { ret f.node.ident; }
- ensure_unique(*e, ty.span, fields, field_name, ~"field");
+ ensure_unique(*e, ty.span, fields, field_name, "field");
}
_ { }
}
visit::visit_ty(ty, x, v);
}
-type checker = @{mutable seen: [ident], kind: istr, sess: session};
+type checker = @{mutable seen: [ident], kind: str, sess: session};
-fn checker(e: &env, kind: &istr) -> checker {
+fn checker(e: &env, kind: &str) -> checker {
let seen: [ident] = [];
ret @{mutable seen: seen, kind: kind, sess: e.sess};
}
fn check_name(ch: &checker, sp: &span, name: &ident) {
for s: ident in ch.seen {
if str::eq(s, name) {
- ch.sess.span_fatal(sp, ~"duplicate " + ch.kind
- + ~" name: " + name);
+ ch.sess.span_fatal(sp, "duplicate " + ch.kind + " name: " + name);
}
}
}
fn ident_id(i: &ident) -> ident { ret i; }
fn ensure_unique<T>(e: &env, sp: &span, elts: &[T], id: fn(&T) -> ident,
- kind: &istr) {
+ kind: &str) {
let ch = checker(e, kind);
for elt: T in elts { add_name(ch, sp, id(elt)); }
}
fn check_bad_exports(e: &@env) {
- fn lookup_glob_any(e: &env, info: &@indexed_mod, sp: &span,
- ident: &ident) -> bool {
- ret !option::is_none(lookup_glob_in_mod(e, info, sp, ident,
- ns_module, inside)) ||
- !option::is_none(lookup_glob_in_mod(e, info, sp, ident,
- ns_value, inside)) ||
- !option::is_none(lookup_glob_in_mod(e, info, sp, ident,
- ns_type, inside));
+ fn lookup_glob_any(e: &env, info: &@indexed_mod, sp: &span, ident: &ident)
+ -> bool {
+ ret !option::is_none(lookup_glob_in_mod(e, info, sp, ident, ns_module,
+ inside)) ||
+ !option::is_none(lookup_glob_in_mod(e, info, sp, ident,
+ ns_value, inside)) ||
+ !option::is_none(lookup_glob_in_mod(e, info, sp, ident,
+ ns_type, inside));
}
- for each @{val, _} in e.mod_map.items() {
+ for each @{val: val, _} in e.mod_map.items() {
alt val.m {
some(m) {
for vi in m.view_items {
ast::view_item_export(idents, _) {
for ident in idents {
if !val.index.contains_key(ident) &&
- !lookup_glob_any(*e, val, vi.span, ident) {
- e.sess.span_warn(vi.span, ~"exported item " +
- ident + ~" is not defined");
+ !lookup_glob_any(*e, val, vi.span, ident) {
+ e.sess.span_warn(vi.span,
+ "exported item " + ident +
+ " is not defined");
}
}
}
- _ {}
+ _ { }
}
}
}
- none. {}
+ none. { }
}
}
}
ret a.did.crate == b.did.crate && a.did.node == b.did.node && a.t == b.t;
}
-fn mk_global(ccx: &@crate_ctxt, name: &istr, llval: ValueRef,
- internal: bool) -> ValueRef {
- let llglobal = str::as_buf(name, { |buf|
- lib::llvm::llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval), buf)
- });
+fn mk_global(ccx: &@crate_ctxt, name: &str, llval: ValueRef, internal: bool)
+ -> ValueRef {
+ let llglobal =
+ str::as_buf(name,
+ {|buf|
+ lib::llvm::llvm::LLVMAddGlobal(ccx.llmod,
+ val_ty(llval), buf)
+ });
lib::llvm::llvm::LLVMSetInitializer(llglobal, llval);
lib::llvm::llvm::LLVMSetGlobalConstant(llglobal, True);
- if (internal) {
+ if internal {
lib::llvm::llvm::LLVMSetLinkage(llglobal,
lib::llvm::LLVMInternalLinkage as
lib::llvm::llvm::Linkage);
}
fn mk_ctxt(llmod: ModuleRef) -> ctxt {
- let llshapetablesty = trans_common::T_named_struct(~"shapes");
- let llshapetables = str::as_buf(~"shapes", { |buf|
- lib::llvm::llvm::LLVMAddGlobal(llmod, llshapetablesty, buf)
- });
+ let llshapetablesty = trans_common::T_named_struct("shapes");
+ let llshapetables =
+ str::as_buf("shapes",
+ {|buf|
+ lib::llvm::llvm::LLVMAddGlobal(llmod, llshapetablesty,
+ buf)
+ });
ret {mutable next_tag_id: 0u16,
pad: 0u16,
}
+
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)];
}
+
ty::ty_machine(ast::ty_i8.) {
s += [shape_i8];
}
ty::ty_machine(ast::ty_i64.) { s += [shape_i64]; }
+
ty::ty_istr. {
s += [shape_vec];
add_bool(s, true); // type is POD
add_substr(s, shape_of(ccx, unit_ty, ty_param_map));
}
+
ty::ty_tag(did, tps) {
alt tag_kind(ccx, did) {
tk_unit. {
}
+
ty::ty_box(mt) {
s += [shape_box];
add_substr(s, shape_of(ccx, mt.ty, ty_param_map));
}
+
ty::ty_fn(_, _, _, _, _) {
s += [shape_fn];
}
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};
}
+
ty::ty_var(n) {
fail "shape_of ty_var";
}
+
ty::ty_param(n, _) {
// Find the type parameter in the parameter list.
let found = false;
let i = 0u;
- while (i < vec::len(ty_param_map)) {
+ while i < vec::len(ty_param_map) {
if n == ty_param_map[i] {
s += [shape_var, i as u8];
found = true;
}
i += 1u;
}
- assert found;
+ assert (found);
}
}
}
// FIXME: We might discover other variants as we traverse these. Handle this.
-fn shape_of_variant(ccx: &@crate_ctxt,
- v: &ty::variant_info,
+fn shape_of_variant(ccx: &@crate_ctxt, v: &ty::variant_info,
ty_param_count: uint) -> [u8] {
let ty_param_map = [];
let i = 0u;
- while (i < ty_param_count) {
- ty_param_map += [i];
- i += 1u;
- }
+ while i < ty_param_count { ty_param_map += [i]; i += 1u; }
let s = [];
for t: ty::t in v.args { s += shape_of(ccx, t, ty_param_map); }
header += data;
header += lv_table;
- ret mk_global(ccx, ~"tag_shapes", C_bytes(header), true);
+ ret mk_global(ccx, "tag_shapes", C_bytes(header), true);
}
fn gen_resource_shapes(ccx: &@crate_ctxt) -> ValueRef {
i += 1u;
}
- ret mk_global(ccx, ~"resource_shapes", C_struct(dtors), true);
+ ret mk_global(ccx, "resource_shapes", C_struct(dtors), true);
}
fn gen_shape_tables(ccx: &@crate_ctxt) {
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) }
- _ {
- if ty::type_is_structural(cx.tcx, arg.ty) { T_ptr(t) }
- else { t }
- }
- };
+ t =
+ alt arg.mode {
+ ty::mo_alias(_) { T_ptr(t) }
+ ty::mo_move. { T_ptr(t) }
+ _ {
+ if ty::type_is_structural(cx.tcx, arg.ty) {
+ T_ptr(t)
+ } else { t }
+ }
+ };
atys += [t];
}
ret atys;
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");
+ 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); }
// Name sanitation. LLVM will happily accept identifiers with weird names, but
// gas doesn't!
-fn sanitize(s: &istr) -> istr {
- let result = ~"";
+fn sanitize(s: &str) -> str {
+ let result = "";
for c: u8 in s {
if c == '@' as u8 {
- result += ~"boxed_";
+ result += "boxed_";
} else {
if c == ',' as u8 {
- result += ~"_";
+ result += "_";
} else {
if c == '{' as u8 || c == '(' as u8 {
- result += ~"_of_";
+ result += "_of_";
} else {
if c != 10u8 && c != '}' as u8 && c != ')' as u8 &&
c != ' ' as u8 && c != '\t' as u8 && c != ';' as u8
}
-fn log_fn_time(ccx: &@crate_ctxt, name: &istr, start: &time::timeval,
+fn log_fn_time(ccx: &@crate_ctxt, name: &str, start: &time::timeval,
end: &time::timeval) {
let elapsed =
1000 * (end.sec - start.sec as int) +
}
-fn decl_fn(llmod: ModuleRef, name: &istr, cc: uint, llty: TypeRef) ->
+fn decl_fn(llmod: ModuleRef, name: &str, cc: uint, llty: TypeRef) ->
ValueRef {
- let llfn: ValueRef = str::as_buf(name, { |buf|
- llvm::LLVMAddFunction(llmod, buf, llty)
- });
+ let llfn: ValueRef =
+ str::as_buf(name, {|buf| llvm::LLVMAddFunction(llmod, buf, llty) });
llvm::LLVMSetFunctionCallConv(llfn, cc);
ret llfn;
}
-fn decl_cdecl_fn(llmod: ModuleRef, name: &istr, llty: TypeRef) -> ValueRef {
+fn decl_cdecl_fn(llmod: ModuleRef, name: &str, llty: TypeRef) -> ValueRef {
ret decl_fn(llmod, name, lib::llvm::LLVMCCallConv, llty);
}
-fn decl_fastcall_fn(llmod: ModuleRef, name: &istr,
- llty: TypeRef) -> ValueRef {
+fn decl_fastcall_fn(llmod: ModuleRef, name: &str, llty: TypeRef) -> ValueRef {
let llfn = decl_fn(llmod, name, lib::llvm::LLVMFastCallConv, llty);
- let _: () = str::as_buf(~"rust", { |buf|
- llvm::LLVMSetGC(llfn, buf)
- });
+ let _: () = str::as_buf("rust", {|buf| llvm::LLVMSetGC(llfn, buf) });
ret llfn;
}
// Only use this if you are going to actually define the function. It's
// not valid to simply declare a function as internal.
-fn decl_internal_fastcall_fn(llmod: ModuleRef, name: &istr, llty: TypeRef) ->
+fn decl_internal_fastcall_fn(llmod: ModuleRef, name: &str, llty: TypeRef) ->
ValueRef {
let llfn = decl_fn(llmod, name, lib::llvm::LLVMFastCallConv, llty);
llvm::LLVMSetLinkage(llfn,
lib::llvm::LLVMInternalLinkage as llvm::Linkage);
- let _: () = str::as_buf(~"rust", { |buf|
- llvm::LLVMSetGC(llfn, buf)
- });
+ let _: () = str::as_buf("rust", {|buf| llvm::LLVMSetGC(llfn, buf) });
ret llfn;
}
-fn decl_glue(llmod: ModuleRef, cx: &crate_ctxt, s: &istr) -> ValueRef {
+fn decl_glue(llmod: ModuleRef, cx: &crate_ctxt, s: &str) -> ValueRef {
ret decl_cdecl_fn(llmod, s, T_fn([T_taskptr(cx)], T_void()));
}
-fn get_extern_fn(externs: &hashmap<istr, ValueRef>, llmod: ModuleRef,
- name: &istr, cc: uint, ty: TypeRef) -> ValueRef {
- if externs.contains_key(name) {
- ret externs.get(name);
- }
+fn get_extern_fn(externs: &hashmap<str, ValueRef>, llmod: ModuleRef,
+ name: &str, cc: uint, ty: TypeRef) -> ValueRef {
+ if externs.contains_key(name) { ret externs.get(name); }
let f = decl_fn(llmod, name, cc, ty);
externs.insert(name, f);
ret f;
}
-fn get_extern_const(externs: &hashmap<istr, ValueRef>, llmod: ModuleRef,
- name: &istr, ty: TypeRef) -> ValueRef {
- if externs.contains_key(name) {
- ret externs.get(name);
- }
- let c = str::as_buf(name, { |buf|
- llvm::LLVMAddGlobal(llmod, ty, buf)
- });
+fn get_extern_const(externs: &hashmap<str, ValueRef>, llmod: ModuleRef,
+ name: &str, ty: TypeRef) -> ValueRef {
+ if externs.contains_key(name) { ret externs.get(name); }
+ let c = str::as_buf(name, {|buf| llvm::LLVMAddGlobal(llmod, ty, buf) });
externs.insert(name, c);
ret c;
}
-fn get_simple_extern_fn(externs: &hashmap<istr, ValueRef>, llmod: ModuleRef,
- name: &istr, n_args: int) -> ValueRef {
+fn get_simple_extern_fn(externs: &hashmap<str, ValueRef>, llmod: ModuleRef,
+ name: &str, n_args: int) -> ValueRef {
let inputs = std::vec::init_elt::<TypeRef>(T_int(), n_args as uint);
let output = T_int();
let t = T_fn(inputs, output);
ret get_extern_fn(externs, llmod, name, lib::llvm::LLVMCCallConv, t);
}
-fn trans_native_call(cx: &@block_ctxt, externs: &hashmap<istr, ValueRef>,
- llmod: ModuleRef, name: &istr, args: &[ValueRef]) ->
+fn trans_native_call(cx: &@block_ctxt, externs: &hashmap<str, 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 += [ZExtOrBitCast(cx, a, T_int())];
- }
+ for a: ValueRef in args { call_args += [ZExtOrBitCast(cx, a, T_int())]; }
ret Call(cx, llnative, call_args);
}
fn trans_non_gc_free(cx: &@block_ctxt, v: ValueRef) -> @block_ctxt {
Call(cx, bcx_ccx(cx).upcalls.free,
- [cx.fcx.lltaskptr, PointerCast(cx, v, T_ptr(T_i8())),
- C_int(0)]);
+ [cx.fcx.lltaskptr, PointerCast(cx, v, T_ptr(T_i8())), C_int(0)]);
ret cx;
}
fn trans_shared_free(cx: &@block_ctxt, v: ValueRef) -> @block_ctxt {
Call(cx, bcx_ccx(cx).upcalls.shared_free,
- [cx.fcx.lltaskptr, PointerCast(cx, v, T_ptr(T_i8()))]);
+ [cx.fcx.lltaskptr, PointerCast(cx, v, T_ptr(T_i8()))]);
ret cx;
}
ret Alloca(new_raw_block_ctxt(cx.fcx, cx.fcx.llstaticallocas), t);
}
-fn dynastack_alloca(cx: &@block_ctxt, t: TypeRef, n: ValueRef, ty: ty::t)
- -> ValueRef {
+fn dynastack_alloca(cx: &@block_ctxt, t: TypeRef, n: ValueRef, ty: ty::t) ->
+ ValueRef {
let bcx = cx;
let dy_cx = new_raw_block_ctxt(cx.fcx, cx.fcx.lldynamicallocas);
let lltaskptr = bcx_fcx(bcx).lltaskptr;
ret PointerCast(dy_cx, llresult, T_ptr(t));
}
-fn mk_obstack_token(ccx: &@crate_ctxt, fcx: @fn_ctxt,
- lltaskptr: ValueRef) -> ValueRef {
+fn mk_obstack_token(ccx: &@crate_ctxt, fcx: @fn_ctxt, lltaskptr: ValueRef) ->
+ ValueRef {
let cx = new_raw_block_ctxt(fcx, fcx.lldynamicallocas);
ret Call(cx, ccx.upcalls.dynastack_mark, [lltaskptr]);
}
fn static_size_of_tag(cx: &@crate_ctxt, sp: &span, t: ty::t) -> uint {
if ty::type_has_dynamic_size(cx.tcx, t) {
cx.tcx.sess.span_fatal(sp,
- ~"dynamically sized type passed to \
+ "dynamically sized type passed to \
static_size_of_tag()");
}
if cx.tag_sizes.contains_key(t) { ret cx.tag_sizes.get(t); }
ret max_size;
}
_ {
- cx.tcx.sess.span_fatal(sp, ~"non-tag passed to static_size_of_tag()");
+ cx.tcx.sess.span_fatal(sp, "non-tag passed to static_size_of_tag()");
}
}
}
// appropriate. @llblobptr is the data part of a tag value; its actual type is
// meaningless, as it will be cast away.
fn GEP_tag(cx: @block_ctxt, llblobptr: ValueRef, tag_id: &ast::def_id,
- variant_id: &ast::def_id, ty_substs: &[ty::t], ix: uint)
- : valid_variant_index(ix, cx, tag_id, variant_id) -> result {
+ variant_id: &ast::def_id, ty_substs: &[ty::t],
+ ix: uint) : valid_variant_index(ix, cx, tag_id, variant_id) ->
+ result {
let variant = ty::tag_variant_with_id(bcx_tcx(cx), tag_id, variant_id);
// Synthesize a tuple type so that GEP_tup_like() can work its magic.
// Separately, store the type of the element we're interested in.
let tydesc = C_null(T_ptr(bcx_ccx(cx).tydesc_type));
let rval =
Call(cx, bcx_ccx(cx).upcalls.malloc,
- [cx.fcx.lltaskptr, llsize, tydesc]);
+ [cx.fcx.lltaskptr, llsize, tydesc]);
ret rslt(cx, PointerCast(cx, rval, llptr_ty));
}
let tydesc = C_null(T_ptr(bcx_ccx(cx).tydesc_type));
let rval =
Call(cx, bcx_ccx(cx).upcalls.shared_malloc,
- [cx.fcx.lltaskptr, llsize, tydesc]);
+ [cx.fcx.lltaskptr, llsize, tydesc]);
ret rslt(cx, PointerCast(cx, rval, llptr_ty));
}
fn trans_stack_local_derived_tydesc(cx: &@block_ctxt, llsz: ValueRef,
llalign: ValueRef, llroottydesc: ValueRef,
llfirstparam: ValueRef, n_params: uint,
- obj_params: uint)
- -> ValueRef {
+ obj_params: uint) -> ValueRef {
let llmyroottydesc = alloca(cx, bcx_ccx(cx).tydesc_type);
// By convention, desc 0 is the root descriptor.
// Objects and closures store their type parameters differently (in the object
// or closure itself rather than in the type descriptor).
-tag ty_param_storage {
- tps_normal;
- tps_obj(uint);
- tps_fn(uint);
-}
+tag ty_param_storage { tps_normal; tps_obj(uint); tps_fn(uint); }
fn get_derived_tydesc(cx: &@block_ctxt, t: ty::t, escapes: bool,
storage: ty_param_storage,
let llfirstparam =
PointerCast(bcx, llparamtydescs,
- T_ptr(T_ptr(bcx_ccx(bcx).tydesc_type)));
+ T_ptr(T_ptr(bcx_ccx(bcx).tydesc_type)));
// The top bit indicates whether this type descriptor describes an object
// (0) or a function (1).
let obj_params;
alt storage {
- tps_normal. { obj_params = 0u; }
- tps_obj(np) { obj_params = np; }
- tps_fn(np) { obj_params = 0x80000000u | np; }
+ tps_normal. { obj_params = 0u; }
+ tps_obj(np) { obj_params = np; }
+ tps_fn(np) { obj_params = 0x80000000u | np; }
}
let v;
if escapes {
let td_val =
Call(bcx, bcx_ccx(bcx).upcalls.get_type_desc,
- [bcx.fcx.lltaskptr, C_null(T_ptr(T_nil())), sz.val,
- align.val, C_uint(1u + n_params),
- llfirstparam, C_uint(obj_params)]);
+ [bcx.fcx.lltaskptr, C_null(T_ptr(T_nil())), sz.val,
+ align.val, C_uint(1u + n_params), llfirstparam,
+ C_uint(obj_params)]);
v = td_val;
} else {
- v = trans_stack_local_derived_tydesc(bcx, sz.val, align.val, root,
+ v =
+ trans_stack_local_derived_tydesc(bcx, sz.val, align.val, root,
llfirstparam, n_params,
obj_params);
}
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));
+ 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 */ }
ret {kind: tk_derived,
result: get_derived_tydesc(cx, t, escapes, storage, static_ti)};
}
-
// Otherwise, generate a tydesc if necessary, and return it.
let info = get_static_tydesc(cx, t, []);
static_ti = some::<@tydesc_info>(info);
// Generates the declaration for (but doesn't emit) a type descriptor.
fn declare_tydesc(cx: &@local_ctxt, sp: &span, t: ty::t, ty_params: &[uint])
-> @tydesc_info {
- log ~"+++ declare_tydesc " + ty_to_str(cx.ccx.tcx, t);
+ log "+++ declare_tydesc " + ty_to_str(cx.ccx.tcx, t);
let ccx = cx.ccx;
let llsize;
let llalign;
}
let name;
if cx.ccx.sess.get_opts().debuginfo {
- name = mangle_internal_name_by_type_only(cx.ccx, t, ~"tydesc");
+ name = mangle_internal_name_by_type_only(cx.ccx, t, "tydesc");
name = sanitize(name);
- } else { name = mangle_internal_name_by_seq(cx.ccx, ~"tydesc"); }
- let gvar = str::as_buf(name, { |buf|
- llvm::LLVMAddGlobal(ccx.llmod, ccx.tydesc_type, buf)
- });
+ } else { name = mangle_internal_name_by_seq(cx.ccx, "tydesc"); }
+ let gvar =
+ str::as_buf(name,
+ {|buf|
+ llvm::LLVMAddGlobal(ccx.llmod, ccx.tydesc_type, buf)
+ });
let info =
@{ty: t,
tydesc: gvar,
mutable free_glue: none::<ValueRef>,
mutable cmp_glue: none::<ValueRef>,
ty_params: ty_params};
- log ~"--- declare_tydesc " + ty_to_str(cx.ccx.tcx, t);
+ log "--- declare_tydesc " + ty_to_str(cx.ccx.tcx, t);
ret info;
}
}
fn declare_generic_glue(cx: &@local_ctxt, t: ty::t, llfnty: TypeRef,
- name: &istr) -> ValueRef {
+ name: &str) -> ValueRef {
let name = name;
let fn_nm;
if cx.ccx.sess.get_opts().debuginfo {
- fn_nm = mangle_internal_name_by_type_only(cx.ccx, t, ~"glue_" + name);
+ fn_nm = mangle_internal_name_by_type_only(cx.ccx, t, "glue_" + name);
fn_nm = sanitize(fn_nm);
- } else { fn_nm = mangle_internal_name_by_seq(cx.ccx, ~"glue_" + name); }
+ } else { fn_nm = mangle_internal_name_by_seq(cx.ccx, "glue_" + name); }
let llfn = decl_cdecl_fn(cx.ccx.llmod, fn_nm, llfnty);
set_glue_inlining(cx, llfn, t);
ret llfn;
}
fn make_generic_glue_inner(cx: &@local_ctxt, sp: &span, t: ty::t,
- llfn: ValueRef,
- helper: &glue_helper,
+ llfn: ValueRef, helper: &glue_helper,
ty_params: &[uint]) -> ValueRef {
let fcx = new_fn_ctxt(cx, sp, llfn);
llvm::LLVMSetLinkage(llfn,
let llrawptr0 = llvm::LLVMGetParam(llfn, 4u);
let llval0 = BitCast(bcx, llrawptr0, llty);
alt helper {
- default_helper(helper) {
- helper(bcx, llval0, t);
- }
+ default_helper(helper) { helper(bcx, llval0, t); }
copy_helper(helper) {
let llrawptr1 = llvm::LLVMGetParam(llfn, 5u);
let llval1 = BitCast(bcx, llrawptr1, llty);
}
fn make_generic_glue(cx: &@local_ctxt, sp: &span, t: ty::t, llfn: ValueRef,
- helper: &glue_helper, ty_params: &[uint],
- name: &istr) -> ValueRef {
+ helper: &glue_helper, ty_params: &[uint], name: &str) ->
+ ValueRef {
if !cx.ccx.sess.get_opts().stats {
ret make_generic_glue_inner(cx, sp, t, llfn, helper, ty_params);
}
let start = time::get_time();
let llval = make_generic_glue_inner(cx, sp, t, llfn, helper, ty_params);
let end = time::get_time();
- log_fn_time(cx.ccx, ~"glue " + name + ~" " +
- ty_to_short_str(cx.ccx.tcx, t),
+ log_fn_time(cx.ccx, "glue " + name + " " + ty_to_short_str(cx.ccx.tcx, t),
start, end);
ret llval;
}
cmp_glue, // cmp_glue
C_shape(ccx, shape), // shape
shape_tables, // shape_tables
- C_int(0), // n_params
+ C_int(0), // n_params
C_int(0)]); // n_obj_params
let gvar = ti.tydesc;
fn make_free_glue(bcx: &@block_ctxt, v0: ValueRef, t: ty::t) {
// NB: v is an *alias* of type t here, not a direct value.
- let bcx = alt ty::struct(bcx_tcx(bcx), t) {
- ty::ty_box(body_mt) {
- let v = Load(bcx, v0);
- let body = GEP(bcx, v, [C_int(0), C_int(abi::box_rc_field_body)]);
- let bcx = drop_ty(bcx, body, body_mt.ty);
- if !bcx_ccx(bcx).sess.get_opts().do_gc {
- trans_non_gc_free(bcx, v)
- } else { bcx }
- }
- 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 =
- GEP(bcx, v0, [C_int(0), C_int(abi::obj_field_box)]);
- let b = Load(bcx, box_cell);
- let ccx = bcx_ccx(bcx);
- let llbox_ty = T_opaque_obj_ptr(*ccx);
- b = PointerCast(bcx, b, llbox_ty);
- let body =
- GEP(bcx, b, [C_int(0), C_int(abi::box_rc_field_body)]);
- let tydescptr =
- GEP(bcx, body, [C_int(0), C_int(abi::obj_body_elt_tydesc)]);
- let tydesc = Load(bcx, tydescptr);
- let ti = none;
- call_tydesc_glue_full(bcx, body, tydesc,
- abi::tydesc_field_drop_glue, ti);
- if !bcx_ccx(bcx).sess.get_opts().do_gc {
- trans_non_gc_free(bcx, b)
- } else { bcx }
- }
- ty::ty_fn(_, _, _, _, _) {
- // Call through the closure's own fields-drop glue first.
- // Then free the body.
- let box_cell = GEP(bcx, v0, [C_int(0), C_int(abi::fn_field_box)]);
- let v = Load(bcx, box_cell);
- let body = GEP(bcx, v, [C_int(0), C_int(abi::box_rc_field_body)]);
- let bindings =
- GEP(bcx, body, [C_int(0), C_int(abi::closure_elt_bindings)]);
- let tydescptr =
- GEP(bcx, body, [C_int(0), C_int(abi::closure_elt_tydesc)]);
- let ti = none;
- call_tydesc_glue_full(bcx, bindings, Load(bcx, tydescptr),
- abi::tydesc_field_drop_glue, ti);
- if !bcx_ccx(bcx).sess.get_opts().do_gc {
- trans_non_gc_free(bcx, v)
- } else { bcx }
- }
- _ { bcx }
- };
+ let bcx =
+ alt ty::struct(bcx_tcx(bcx), t) {
+ ty::ty_box(body_mt) {
+ let v = Load(bcx, v0);
+ let body = GEP(bcx, v, [C_int(0), C_int(abi::box_rc_field_body)]);
+ let bcx = drop_ty(bcx, body, body_mt.ty);
+ if !bcx_ccx(bcx).sess.get_opts().do_gc {
+ trans_non_gc_free(bcx, v)
+ } else { bcx }
+ }
+ 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 =
+ GEP(bcx, v0, [C_int(0), C_int(abi::obj_field_box)]);
+ let b = Load(bcx, box_cell);
+ let ccx = bcx_ccx(bcx);
+ let llbox_ty = T_opaque_obj_ptr(*ccx);
+ b = PointerCast(bcx, b, llbox_ty);
+ let body = GEP(bcx, b, [C_int(0), C_int(abi::box_rc_field_body)]);
+ let tydescptr =
+ GEP(bcx, body, [C_int(0), C_int(abi::obj_body_elt_tydesc)]);
+ let tydesc = Load(bcx, tydescptr);
+ let ti = none;
+ call_tydesc_glue_full(bcx, body, tydesc,
+ abi::tydesc_field_drop_glue, ti);
+ if !bcx_ccx(bcx).sess.get_opts().do_gc {
+ trans_non_gc_free(bcx, b)
+ } else { bcx }
+ }
+ ty::ty_fn(_, _, _, _, _) {
+ // Call through the closure's own fields-drop glue first.
+ // Then free the body.
+ let box_cell = GEP(bcx, v0, [C_int(0), C_int(abi::fn_field_box)]);
+ let v = Load(bcx, box_cell);
+ let body = GEP(bcx, v, [C_int(0), C_int(abi::box_rc_field_body)]);
+ let bindings =
+ GEP(bcx, body, [C_int(0), C_int(abi::closure_elt_bindings)]);
+ let tydescptr =
+ GEP(bcx, body, [C_int(0), C_int(abi::closure_elt_tydesc)]);
+ let ti = none;
+ call_tydesc_glue_full(bcx, bindings, Load(bcx, tydescptr),
+ abi::tydesc_field_drop_glue, ti);
+ if !bcx_ccx(bcx).sess.get_opts().do_gc {
+ trans_non_gc_free(bcx, v)
+ } else { bcx }
+ }
+ _ { bcx }
+ };
build_return(bcx);
}
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 drop_cx = new_sub_block_ctxt(cx, ~"drop res");
- let next_cx = new_sub_block_ctxt(cx, ~"next");
+ 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]);
cx = drop_flag.bcx;
// Find and call the actual destructor.
let dtor_pair = trans_common::get_res_dtor(ccx, cx.sp, did, inner_t);
let dtor_addr =
- Load(cx, GEP(cx, dtor_pair,
- [C_int(0), C_int(abi::fn_field_code)]));
+ Load(cx, GEP(cx, dtor_pair, [C_int(0), C_int(abi::fn_field_code)]));
let dtor_env =
- Load(cx, GEP(cx, dtor_pair,
- [C_int(0), C_int(abi::fn_field_box)]));
+ Load(cx, GEP(cx, 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 {
let ti: option::t<@tydesc_info> = none;
// 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 = BitCast(cx, val.val, val_llty);
FastCall(cx, dtor_addr, args + [val_cast]);
fn decr_refcnt_maybe_free(cx: &@block_ctxt, box_ptr_alias: ValueRef,
full_alias: ValueRef, t: ty::t) -> @block_ctxt {
let ccx = bcx_ccx(cx);
- let rc_adj_cx = new_sub_block_ctxt(cx, ~"rc--");
- let free_cx = new_sub_block_ctxt(cx, ~"free");
- let next_cx = new_sub_block_ctxt(cx, ~"next");
+ let rc_adj_cx = new_sub_block_ctxt(cx, "rc--");
+ let free_cx = new_sub_block_ctxt(cx, "free");
+ let next_cx = new_sub_block_ctxt(cx, "next");
let box_ptr = Load(cx, box_ptr_alias);
let llbox_ty = T_opaque_obj_ptr(*ccx);
box_ptr = PointerCast(cx, box_ptr, llbox_ty);
let null_test = IsNull(cx, box_ptr);
CondBr(cx, null_test, next_cx.llbb, rc_adj_cx.llbb);
let rc_ptr =
- GEP(rc_adj_cx, box_ptr,
- [C_int(0), C_int(abi::box_rc_field_refcnt)]);
+ GEP(rc_adj_cx, box_ptr, [C_int(0), C_int(abi::box_rc_field_refcnt)]);
let rc = Load(rc_adj_cx, rc_ptr);
rc = Sub(rc_adj_cx, rc, C_int(1));
Store(rc_adj_cx, rc, rc_ptr);
// Structural comparison: a rather involved form of glue.
-fn maybe_name_value(cx: &@crate_ctxt, v: ValueRef, s: &istr) {
+fn maybe_name_value(cx: &@crate_ctxt, v: ValueRef, s: &str) {
if cx.sess.get_opts().save_temps {
- let _: () = str::as_buf(s, { |buf|
- llvm::LLVMSetValueName(v, buf)
- });
+ let _: () = str::as_buf(s, {|buf| llvm::LLVMSetValueName(v, buf) });
}
}
}
}
ty::ty_type. {
- trans_fail(cx, none, ~"attempt to compare values of type type");
+ trans_fail(cx, none, "attempt to compare values of type type");
// This is a bit lame, because we return a dummy block to the
// caller that's actually unreachable, but I don't think it
// matters.
- ret rslt(new_sub_block_ctxt(cx, ~"after_fail_dummy"), C_bool(false));
+ ret rslt(new_sub_block_ctxt(cx, "after_fail_dummy"), C_bool(false));
}
ty::ty_native(_) {
trans_fail(cx, none::<span>,
- ~"attempt to compare values of type native");
- ret rslt(new_sub_block_ctxt(cx, ~"after_fail_dummy"), C_bool(false));
+ "attempt to compare values of type native");
+ ret rslt(new_sub_block_ctxt(cx, "after_fail_dummy"), C_bool(false));
}
_ {
// Should never get here, because t is scalar.
- bcx_ccx(cx).sess.bug(~"non-scalar type passed to \
+ bcx_ccx(cx).sess.bug("non-scalar type passed to \
compare_scalar_types");
}
}
} else { r = ICmp(cx, op, lhs, rhs); }
ret r;
}
- let last_cx = new_sub_block_ctxt(cx, ~"last");
- let eq_cx = new_sub_block_ctxt(cx, ~"eq");
+ let last_cx = new_sub_block_ctxt(cx, "last");
+ let eq_cx = new_sub_block_ctxt(cx, "eq");
let eq_result = generic_cmp(eq_cx, nt, eq_cmp, lhs, rhs);
Br(eq_cx, last_cx.llbb);
- let lt_cx = new_sub_block_ctxt(cx, ~"lt");
+ let lt_cx = new_sub_block_ctxt(cx, "lt");
let lt_result = generic_cmp(lt_cx, nt, lt_cmp, lhs, rhs);
Br(lt_cx, last_cx.llbb);
- let le_cx = new_sub_block_ctxt(cx, ~"le");
+ let le_cx = new_sub_block_ctxt(cx, "le");
let le_result = generic_cmp(le_cx, nt, le_cmp, lhs, rhs);
Br(le_cx, last_cx.llbb);
- let unreach_cx = new_sub_block_ctxt(cx, ~"unreach");
+ let unreach_cx = new_sub_block_ctxt(cx, "unreach");
Unreachable(unreach_cx);
let llswitch = Switch(cx, llop, unreach_cx.llbb, 3u);
llvm::LLVMAddCase(llswitch, C_u8(abi::cmp_glue_op_eq), eq_cx.llbb);
llvm::LLVMAddCase(llswitch, C_u8(abi::cmp_glue_op_le), le_cx.llbb);
let last_result =
Phi(last_cx, T_i1(), [eq_result, lt_result, le_result],
- [eq_cx.llbb, lt_cx.llbb, le_cx.llbb]);
+ [eq_cx.llbb, lt_cx.llbb, le_cx.llbb]);
ret rslt(last_cx, last_result);
}
// Iterates through the elements of a structural type.
fn iter_structural_ty(cx: @block_ctxt, av: ValueRef, t: ty::t,
f: &val_and_ty_fn) -> @block_ctxt {
- fn iter_boxpp(cx: @block_ctxt, box_cell: ValueRef, f: &val_and_ty_fn)
- -> @block_ctxt {
+ fn iter_boxpp(cx: @block_ctxt, box_cell: ValueRef, f: &val_and_ty_fn) ->
+ @block_ctxt {
let box_ptr = Load(cx, box_cell);
let tnil = ty::mk_nil(bcx_tcx(cx));
let tbox = ty::mk_imm_box(bcx_tcx(cx), tnil);
- let inner_cx = new_sub_block_ctxt(cx, ~"iter box");
- let next_cx = new_sub_block_ctxt(cx, ~"next");
+ let inner_cx = new_sub_block_ctxt(cx, "iter box");
+ let next_cx = new_sub_block_ctxt(cx, "next");
let null_test = IsNull(cx, box_ptr);
CondBr(cx, null_test, next_cx.llbb, inner_cx.llbb);
let inner_cx = f(inner_cx, box_cell, tbox);
let j = 0u;
let v_id = variant.id;
for a: ty::arg in args {
- check valid_variant_index(j, cx, tid, v_id);
+ check (valid_variant_index(j, cx, tid, v_id));
let rslt = GEP_tag(cx, a_tup, tid, v_id, tps, j);
let llfldp_a = rslt.val;
cx = rslt.bcx;
ty::ty_rec(fields) {
let i: int = 0;
for fld: ty::field in fields {
- let {bcx, val: llfld_a} = GEP_tup_like(cx, t, av, [0, i]);
+ let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, t, av, [0, i]);
cx = f(bcx, llfld_a, fld.mt.ty);
i += 1;
}
ty::ty_tup(args) {
let i = 0;
for arg in args {
- let {bcx, val: llfld_a} = GEP_tup_like(cx, t, av, [0, i]);
+ let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, t, av, [0, i]);
cx = f(bcx, llfld_a, arg);
i += 1;
}
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]);
- let {bcx, val: llfld_a} = GEP_tup_like(cx, tup_t, av, [0, 1]);
+ let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, tup_t, av, [0, 1]);
ret f(bcx, llfld_a, inner1);
}
ty::ty_tag(tid, tps) {
// NB: we must hit the discriminant first so that structural
// comparison know not to proceed when the discriminants differ.
cx = f(cx, lldiscrim_a_ptr, ty::mk_int(bcx_tcx(cx)));
- let unr_cx = new_sub_block_ctxt(cx, ~"tag-iter-unr");
+ let unr_cx = new_sub_block_ctxt(cx, "tag-iter-unr");
Unreachable(unr_cx);
let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb, n_variants);
- let next_cx = new_sub_block_ctxt(cx, ~"tag-iter-next");
+ let next_cx = new_sub_block_ctxt(cx, "tag-iter-next");
let i = 0u;
for variant: ty::variant_info in variants {
let variant_cx =
- new_sub_block_ctxt(cx, ~"tag-iter-variant-" +
- uint::to_str(i, 10u));
+ new_sub_block_ctxt(cx,
+ "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);
+ variant_cx =
+ iter_variant(variant_cx, llunion_a_ptr, variant, tps, tid, f);
Br(variant_cx, next_cx.llbb);
i += 1u;
}
ret next_cx;
}
ty::ty_fn(_, _, _, _, _) {
- let box_cell_a =
- GEP(cx, av, [C_int(0), C_int(abi::fn_field_box)]);
+ let box_cell_a = GEP(cx, 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 =
- GEP(cx, av, [C_int(0), C_int(abi::obj_field_box)]);
+ let box_cell_a = GEP(cx, av, [C_int(0), C_int(abi::obj_field_box)]);
ret iter_boxpp(cx, box_cell_a, f);
}
- _ { bcx_ccx(cx).sess.unimpl(~"type in iter_structural_ty"); }
+ _ { bcx_ccx(cx).sess.unimpl("type in iter_structural_ty"); }
}
ret cx;
}
// Iterates through a pointer range, until the src* hits the src_lim*.
-fn iter_sequence_raw(cx: @block_ctxt, dst: ValueRef,
- src: ValueRef, src_lim: ValueRef,
- elt_sz: ValueRef, f: &val_pair_fn) -> @block_ctxt {
+fn iter_sequence_raw(cx: @block_ctxt, dst: ValueRef, src: ValueRef,
+ src_lim: ValueRef, elt_sz: ValueRef, f: &val_pair_fn) ->
+ @block_ctxt {
let bcx = cx;
let dst_int: ValueRef = vp2i(bcx, dst);
let src_int: ValueRef = vp2i(bcx, src);
let src_lim_int: ValueRef = vp2i(bcx, src_lim);
- let cond_cx = new_scope_block_ctxt(cx, ~"sequence-iter cond");
- let body_cx = new_scope_block_ctxt(cx, ~"sequence-iter body");
- let next_cx = new_sub_block_ctxt(cx, ~"next");
+ let cond_cx = new_scope_block_ctxt(cx, "sequence-iter cond");
+ let body_cx = new_scope_block_ctxt(cx, "sequence-iter body");
+ let next_cx = new_sub_block_ctxt(cx, "next");
Br(bcx, cond_cx.llbb);
- let dst_curr: ValueRef =
- Phi(cond_cx, T_int(), [dst_int], [bcx.llbb]);
- let src_curr: ValueRef =
- Phi(cond_cx, T_int(), [src_int], [bcx.llbb]);
+ let dst_curr: ValueRef = Phi(cond_cx, T_int(), [dst_int], [bcx.llbb]);
+ let src_curr: ValueRef = Phi(cond_cx, T_int(), [src_int], [bcx.llbb]);
let end_test =
ICmp(cond_cx, lib::llvm::LLVMIntULT, src_curr, src_lim_int);
CondBr(cond_cx, end_test, body_cx.llbb, next_cx.llbb);
ret next_cx;
}
-fn iter_sequence_inner(cx: &@block_ctxt, src: ValueRef,
- src_lim: ValueRef,
+fn iter_sequence_inner(cx: &@block_ctxt, src: ValueRef, src_lim: ValueRef,
elt_ty: &ty::t, f: &val_and_ty_fn) -> @block_ctxt {
fn adaptor_fn(f: val_and_ty_fn, elt_ty: ty::t, cx: &@block_ctxt,
_dst: ValueRef, src: ValueRef) -> @block_ctxt {
// Iterates through the elements of a vec or str.
-fn iter_sequence(cx: @block_ctxt, v: ValueRef, t: ty::t, f: &val_and_ty_fn)
- -> @block_ctxt {
+fn iter_sequence(cx: @block_ctxt, v: ValueRef, t: ty::t, f: &val_and_ty_fn) ->
+ @block_ctxt {
fn iter_sequence_body(bcx: @block_ctxt, v: ValueRef, elt_ty: ty::t,
- f: &val_and_ty_fn, trailing_null: bool)
- -> @block_ctxt {
+ f: &val_and_ty_fn, trailing_null: bool) ->
+ @block_ctxt {
let llunit_ty = type_of_or_i8(bcx, elt_ty);
let p0 = tvec::get_dataptr(bcx, v, llunit_ty);
let len = tvec::get_fill(bcx, v);
bcx = unit_sz.bcx;
len = Sub(bcx, len, unit_sz.val);
}
- let p1 =
- vi2p(bcx, Add(bcx, vp2i(bcx, p0), len), T_ptr(llunit_ty));
+ let p1 = vi2p(bcx, Add(bcx, vp2i(bcx, p0), len), T_ptr(llunit_ty));
ret iter_sequence_inner(bcx, p0, p1, elt_ty, f);
}
alt ty::struct(bcx_tcx(cx), t) {
- ty::ty_vec(elt) {
- ret iter_sequence_body(cx, v, elt.ty, f, false);
- }
+ ty::ty_vec(elt) { ret iter_sequence_body(cx, v, elt.ty, f, false); }
ty::ty_istr. {
let et = ty::mk_mach(bcx_tcx(cx), ast::ty_u8);
ret iter_sequence_body(cx, v, et, f, true);
}
_ {
- bcx_ccx(cx).sess.bug(
- ~"unexpected type in trans::iter_sequence: "
- + ty_to_str(cx.fcx.lcx.ccx.tcx, t));
+ bcx_ccx(cx).sess.bug("unexpected type in trans::iter_sequence: " +
+ ty_to_str(cx.fcx.lcx.ccx.tcx, t));
}
}
}
let lcx = cx.fcx.lcx;
let glue_fn =
declare_generic_glue(lcx, ti.ty, T_glue_fn(*lcx.ccx),
- ~"take");
+ "take");
ti.take_glue = some::<ValueRef>(glue_fn);
make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
default_helper(make_take_glue),
- ti.ty_params, ~"take");
+ ti.ty_params, "take");
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),
- ~"drop");
+ "drop");
ti.drop_glue = some::<ValueRef>(glue_fn);
make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
default_helper(make_drop_glue),
- ti.ty_params, ~"drop");
+ 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. {
let lcx = cx.fcx.lcx;
let glue_fn =
declare_generic_glue(lcx, ti.ty, T_glue_fn(*lcx.ccx),
- ~"free");
+ "free");
ti.free_glue = some::<ValueRef>(glue_fn);
make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
default_helper(make_free_glue),
- ti.ty_params, ~"free");
+ ti.ty_params, "free");
log #fmt["--- lazily_emit_tydesc_glue FREE %s",
ty_to_str(bcx_tcx(cx), ti.ty)];
}
let llrawptr = PointerCast(cx, v, T_ptr(T_i8()));
let lltydescs =
- GEP(cx, tydesc,
- [C_int(0), C_int(abi::tydesc_field_first_param)]);
+ GEP(cx, tydesc, [C_int(0), C_int(abi::tydesc_field_first_param)]);
lltydescs = Load(cx, lltydescs);
let llfn;
}
Call(cx, 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) ->
- @block_ctxt {
+ @block_ctxt {
let ti: option::t<@tydesc_info> = none::<@tydesc_info>;
- let {bcx, val: td} = get_tydesc(cx, t, false, tps_normal, ti).result;
+ let {bcx: bcx, val: td} = get_tydesc(cx, t, false, tps_normal, ti).result;
call_tydesc_glue_full(bcx, v, td, field, ti);
ret bcx;
}
let bcx = cx;
let r = spill_if_immediate(bcx, lhs, t);
- let lllhs = r.val; bcx = r.bcx;
+ let lllhs = r.val;
+ bcx = r.bcx;
r = spill_if_immediate(bcx, rhs, t);
- let llrhs = r.val; bcx = r.bcx;
+ let llrhs = r.val;
+ bcx = r.bcx;
let llrawlhsptr = BitCast(bcx, lllhs, T_ptr(T_i8()));
let llrawrhsptr = BitCast(bcx, llrhs, T_ptr(T_i8()));
let ti = none::<@tydesc_info>;
r = get_tydesc(bcx, t, false, tps_normal, ti).result;
- let lltydesc = r.val; bcx = r.bcx;
+ let lltydesc = r.val;
+ bcx = r.bcx;
lazily_emit_tydesc_glue(bcx, abi::tydesc_field_cmp_glue, ti);
- let lltydescs = GEP(bcx, lltydesc,
- [C_int(0), C_int(abi::tydesc_field_first_param)]);
+ let lltydescs =
+ GEP(bcx, lltydesc, [C_int(0), C_int(abi::tydesc_field_first_param)]);
lltydescs = Load(bcx, lltydescs);
let llfn;
alt ti {
none. {
- let llfnptr = GEP(bcx, lltydesc,
- [C_int(0), C_int(abi::tydesc_field_cmp_glue)]);
+ let llfnptr =
+ GEP(bcx, lltydesc, [C_int(0), C_int(abi::tydesc_field_cmp_glue)]);
llfn = Load(bcx, llfnptr);
}
some(sti) { llfn = option::get(sti.cmp_glue); }
let llcmpresultptr = alloca(bcx, T_i1());
let llargs: [ValueRef] =
- [llcmpresultptr, bcx.fcx.lltaskptr, lltydesc, lltydescs,
- llrawlhsptr, llrawrhsptr, llop];
+ [llcmpresultptr, bcx.fcx.lltaskptr, lltydesc, lltydescs, llrawlhsptr,
+ llrawrhsptr, llop];
Call(bcx, llfn, llargs);
ret rslt(bcx, Load(bcx, llcmpresultptr));
}
// LLVM complains -- not even a constant element of a tydesc works).
let i = bcx_ccx(cx).intrinsics;
- assert (i.contains_key(~"llvm.memmove.p0i8.p0i8.i32"));
- let memmove = i.get(~"llvm.memmove.p0i8.p0i8.i32");
+ assert (i.contains_key("llvm.memmove.p0i8.p0i8.i32"));
+ let memmove = i.get("llvm.memmove.p0i8.p0i8.i32");
let src_ptr = PointerCast(cx, src, T_ptr(T_i8()));
let dst_ptr = PointerCast(cx, dst, T_ptr(T_i8()));
let size = IntCast(cx, n_bytes, T_i32());
let align = C_int(1);
let volatile = C_bool(false);
ret rslt(cx,
- Call(cx, memmove,
- [dst_ptr, src_ptr, size, align, volatile]));
+ Call(cx, memmove, [dst_ptr, src_ptr, size, align, volatile]));
}
fn call_bzero(cx: &@block_ctxt, dst: ValueRef, n_bytes: ValueRef,
// FIXME: switch to the 64-bit variant when on such a platform.
let i = bcx_ccx(cx).intrinsics;
- assert (i.contains_key(~"llvm.memset.p0i8.i32"));
- let memset = i.get(~"llvm.memset.p0i8.i32");
+ assert (i.contains_key("llvm.memset.p0i8.i32"));
+ let memset = i.get("llvm.memset.p0i8.i32");
let dst_ptr = PointerCast(cx, dst, T_ptr(T_i8()));
let size = IntCast(cx, n_bytes, T_i32());
let align =
} else { IntCast(cx, C_int(0), T_i32()) };
let volatile = C_bool(false);
ret rslt(cx,
- Call(cx, memset,
- [dst_ptr, C_u8(0u), size, align, volatile]));
+ Call(cx, memset, [dst_ptr, C_u8(0u), size, align, volatile]));
}
fn memmove_ty(cx: &@block_ctxt, dst: ValueRef, src: ValueRef, t: ty::t) ->
fn copy_val(cx: &@block_ctxt, action: copy_action, dst: ValueRef,
src: ValueRef, t: ty::t) -> @block_ctxt {
if type_is_structural_or_param(bcx_ccx(cx).tcx, t) &&
- action == DROP_EXISTING {
- let do_copy_cx = new_sub_block_ctxt(cx, ~"do_copy");
- let next_cx = new_sub_block_ctxt(cx, ~"next");
+ action == DROP_EXISTING {
+ let do_copy_cx = new_sub_block_ctxt(cx, "do_copy");
+ let next_cx = new_sub_block_ctxt(cx, "next");
let self_assigning =
- ICmp(cx, lib::llvm::LLVMIntNE,
- PointerCast(cx, dst, val_ty(src)), src);
+ ICmp(cx, lib::llvm::LLVMIntNE, PointerCast(cx, dst, val_ty(src)),
+ src);
CondBr(cx, self_assigning, do_copy_cx.llbb, next_cx.llbb);
do_copy_cx = copy_val_no_check(do_copy_cx, action, dst, src, t);
Br(do_copy_cx, next_cx.llbb);
// FIXME this is just a clunky stopgap. we should do proper checking in an
// earlier pass.
if !ty::type_is_copyable(ccx.tcx, t) {
- ccx.sess.span_fatal(cx.sp, ~"Copying a non-copyable type.");
+ ccx.sess.span_fatal(cx.sp, "Copying a non-copyable type.");
}
if ty::type_is_scalar(ccx.tcx, t) || ty::type_is_native(ccx.tcx, t) {
ret cx;
} else if ty::type_is_nil(ccx.tcx, t) || ty::type_is_bot(ccx.tcx, t) {
ret cx;
- } else if ty::type_is_boxed(ccx.tcx, t) ||
- ty::type_is_vec(ccx.tcx, t) {
- let bcx = if action == DROP_EXISTING {
- drop_ty(cx, dst, t)
- } else { cx };
+ } else if ty::type_is_boxed(ccx.tcx, t) || ty::type_is_vec(ccx.tcx, t) {
+ let bcx =
+ if action == DROP_EXISTING { drop_ty(cx, dst, t) } else { cx };
Store(bcx, src, dst);
bcx = take_ty(bcx, dst, t);
ret bcx;
} else if type_is_structural_or_param(ccx.tcx, t) {
- let bcx = if action == DROP_EXISTING {
- drop_ty(cx, dst, t)
- } else { cx };
+ let bcx =
+ if action == DROP_EXISTING { drop_ty(cx, dst, t) } else { cx };
bcx = memmove_ty(bcx, dst, src, t).bcx;
ret take_ty(bcx, dst, t);
}
- ccx.sess.bug(~"unexpected type in trans::copy_val_no_check: " +
- ty_to_str(ccx.tcx, t));
+ ccx.sess.bug("unexpected type in trans::copy_val_no_check: " +
+ ty_to_str(ccx.tcx, t));
}
src: &lval_result, t: ty::t) -> @block_ctxt {
let src_val = src.res.val;
let tcx = bcx_tcx(cx);
- if ty::type_is_scalar(tcx, t) ||
- ty::type_is_native(tcx, t) {
+ if ty::type_is_scalar(tcx, t) || ty::type_is_native(tcx, t) {
if src.is_mem { src_val = Load(cx, src_val); }
Store(cx, src_val, dst);
ret cx;
} else if ty::type_is_nil(tcx, t) || ty::type_is_bot(tcx, t) {
ret cx;
- } else if ty::type_is_unique(tcx, t) ||
- ty::type_is_boxed(tcx, t) {
+ } else if ty::type_is_unique(tcx, t) || ty::type_is_boxed(tcx, t) {
if src.is_mem { src_val = Load(cx, src_val); }
- if action == DROP_EXISTING {
- cx = drop_ty(cx, dst, t);
- }
+ if action == DROP_EXISTING { cx = drop_ty(cx, dst, t); }
Store(cx, src_val, dst);
if src.is_mem { ret zero_alloca(cx, src.res.val, t).bcx; }
ret cx;
}
}
- bcx_ccx(cx).sess.bug(~"unexpected type in trans::move_val: " +
- ty_to_str(tcx, t));
+ bcx_ccx(cx).sess.bug("unexpected type in trans::move_val: " +
+ ty_to_str(tcx, t));
}
fn move_val_if_temp(cx: @block_ctxt, action: copy_action, dst: ValueRef,
ast::lit_bool(b) { ret C_bool(b); }
ast::lit_nil. { ret C_nil(); }
ast::lit_str(s) {
- cx.sess.span_unimpl(lit.span, ~"unique string in this context");
+ cx.sess.span_unimpl(lit.span, "unique string in this context");
}
}
}
ret rslt(bcx, sub.box);
}
ast::deref. {
- bcx_ccx(cx).sess.bug(~"deref expressions should have been \
+ bcx_ccx(cx).sess.bug("deref expressions should have been \
translated using trans_lval(), not \
trans_unary()");
}
while true {
alt ty::struct(ccx.tcx, t1) {
ty::ty_box(mt) {
- let body =
- GEP(cx, v1, [C_int(0), C_int(abi::box_rc_field_body)]);
+ let body = GEP(cx, 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
ast::and. {
// Lazy-eval and
let lhs_res = trans_expr(cx, a);
- let rhs_cx = new_scope_block_ctxt(cx, ~"rhs");
+ let rhs_cx = new_scope_block_ctxt(cx, "rhs");
let rhs_res = trans_expr(rhs_cx, b);
- let lhs_false_cx = new_scope_block_ctxt(cx, ~"lhs false");
+ let lhs_false_cx = new_scope_block_ctxt(cx, "lhs false");
let lhs_false_res = rslt(lhs_false_cx, C_bool(false));
// The following line ensures that any cleanups for rhs
ast::or. {
// Lazy-eval or
let lhs_res = trans_expr(cx, a);
- let rhs_cx = new_scope_block_ctxt(cx, ~"rhs");
+ let rhs_cx = new_scope_block_ctxt(cx, "rhs");
let rhs_res = trans_expr(rhs_cx, b);
- let lhs_true_cx = new_scope_block_ctxt(cx, ~"lhs true");
+ let lhs_true_cx = new_scope_block_ctxt(cx, "lhs true");
let lhs_true_res = rslt(lhs_true_cx, C_bool(true));
// see the and case for an explanation
}
// We have >1 incoming edges. Make a join block and br+phi them into it.
- let join_cx = new_sub_block_ctxt(parent_cx, ~"join");
+ let join_cx = new_sub_block_ctxt(parent_cx, "join");
for r: result in live { Br(r.bcx, join_cx.llbb); }
let phi = Phi(join_cx, t, vals, bbs);
ret rslt(join_cx, phi);
}
fn join_branches(parent_cx: &@block_ctxt, ins: &[result]) -> @block_ctxt {
- let out = new_sub_block_ctxt(parent_cx, ~"join");
- for r: result in ins {
- if !is_terminated(r.bcx) { Br(r.bcx, out.llbb); }
- }
+ let out = new_sub_block_ctxt(parent_cx, "join");
+ for r: result in ins { if !is_terminated(r.bcx) { Br(r.bcx, out.llbb); } }
ret out;
}
} else { ret cond_res; }
}
- let then_cx = new_scope_block_ctxt(cx, ~"then");
+ let then_cx = new_scope_block_ctxt(cx, "then");
let then_res = trans_block(then_cx, thn, output);
- let else_cx = new_scope_block_ctxt(cx, ~"else");
+ let else_cx = new_scope_block_ctxt(cx, "else");
// Synthesize a block here to act as the else block
// containing an if expression. Needed in order for the
// else scope to behave like a normal block scope. A tad
// obviously a bug.
fn inner(cx: &@block_ctxt, local: @ast::local, curr: ValueRef, t: ty::t,
body: &ast::blk, outer_next_cx: @block_ctxt) -> @block_ctxt {
- let next_cx = new_sub_block_ctxt(cx, ~"next");
+ let next_cx = new_sub_block_ctxt(cx, "next");
let scope_cx =
new_loop_scope_block_ctxt(cx,
option::some::<@block_ctxt>(next_cx),
- outer_next_cx, ~"for loop scope");
+ outer_next_cx, "for loop scope");
Br(cx, scope_cx.llbb);
let local_res = alloc_local(scope_cx, local);
let bcx = 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
- (bcx, local.node.pat, local_res.val, cx.fcx.lllocals, false);
+ let bcx =
+ trans_alt::bind_irrefutable_pat(bcx, local.node.pat,
+ local_res.val, cx.fcx.lllocals,
+ false);
bcx = trans_block(bcx, body, return).bcx;
if !is_terminated(bcx) {
Br(bcx, next_cx.llbb);
}
ret next_cx;
}
- let next_cx = new_sub_block_ctxt(cx, ~"next");
+ let next_cx = new_sub_block_ctxt(cx, "next");
let seq_ty = ty::expr_ty(bcx_tcx(cx), seq);
let seq_res = trans_expr(cx, seq);
- let bcx = iter_sequence(seq_res.bcx, seq_res.val, seq_ty,
- bind inner(_, local, _, _, body, next_cx));
+ let bcx =
+ iter_sequence(seq_res.bcx, seq_res.val, seq_ty,
+ bind inner(_, local, _, _, body, next_cx));
Br(bcx, next_cx.llbb);
ret rslt(next_cx, C_nil());
}
// 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::def], copying: bool)
- -> {ptr: ValueRef, ptrty: ty::t, bcx: @block_ctxt} {
+fn build_closure(cx: &@block_ctxt, upvars: &@[ast::def], 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
let llenv = GEPi(bcx, closure, [0, abi::box_rc_field_body]);
// Load the tydesc and find the size of the body
let lldesc =
- Load(bcx, GEPi(bcx, llenv,
- [0, abi::closure_elt_tydesc]));
+ Load(bcx, GEPi(bcx, llenv, [0, abi::closure_elt_tydesc]));
let llsz =
- Load(bcx, GEPi(bcx, lldesc,
- [0, abi::tydesc_field_size]));
+ Load(bcx, 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]);
let llenv = build_closure(cx, upvars, false);
// Step 2: Declare foreach body function.
- let s: istr =
- mangle_internal_name_by_path_and_seq(lcx.ccx,
- lcx.path,
- ~"foreach");
+ let s: str =
+ mangle_internal_name_by_path_and_seq(lcx.ccx, lcx.path, "foreach");
// The 'env' arg entering the body function is a fake env member (as in
// the env-part of the normal rust calling convention) that actually
type_of_fn_from_ty(lcx.ccx, cx.sp,
ty::mk_iter_body_fn(lcx.ccx.tcx, decl_ty), 0u);
let lliterbody: ValueRef =
- decl_internal_fastcall_fn(lcx.ccx.llmod,
- s, iter_body_llty);
+ decl_internal_fastcall_fn(lcx.ccx.llmod, s, iter_body_llty);
let fcx = new_fn_ctxt_w_id(lcx, cx.sp, lliterbody, body.node.id);
fcx.iterbodyty = cx.fcx.iterbodyty;
fn trans_while(cx: &@block_ctxt, cond: &@ast::expr, body: &ast::blk) ->
result {
- let next_cx = new_sub_block_ctxt(cx, ~"while next");
- let cond_cx = new_loop_scope_block_ctxt(cx, option::none::<@block_ctxt>,
- next_cx, ~"while cond");
- let body_cx =
- new_scope_block_ctxt(cond_cx, ~"while loop body");
+ let next_cx = new_sub_block_ctxt(cx, "while next");
+ let cond_cx =
+ new_loop_scope_block_ctxt(cx, option::none::<@block_ctxt>, next_cx,
+ "while cond");
+ let body_cx = new_scope_block_ctxt(cond_cx, "while loop body");
let body_res = trans_block(body_cx, body, return);
let cond_res = trans_expr(cond_cx, cond);
Br(body_res.bcx, cond_cx.llbb);
fn trans_do_while(cx: &@block_ctxt, body: &ast::blk, cond: &@ast::expr) ->
result {
- let next_cx = new_sub_block_ctxt(cx, ~"next");
+ let next_cx = new_sub_block_ctxt(cx, "next");
let body_cx =
new_loop_scope_block_ctxt(cx, option::none::<@block_ctxt>, next_cx,
- ~"do-while loop body");
+ "do-while loop body");
let body_res = trans_block(body_cx, body, return);
if is_terminated(body_res.bcx) {
// This is kind of ridiculous, but no permutations
tpt: &ty::ty_param_kinds_and_ty) -> ValueRef {
let lcx = cx.fcx.lcx;
let name = csearch::get_symbol(lcx.ccx.sess.get_cstore(), did);
- ret get_extern_const(lcx.ccx.externs, lcx.ccx.llmod,
- name,
+ ret get_extern_const(lcx.ccx.externs, lcx.ccx.llmod, name,
type_of_ty_param_kinds_and_ty(lcx, cx.sp, tpt));
}
// It's an external discriminant that we haven't seen yet.
assert (vid.crate != ast::local_crate);
let sym = csearch::get_symbol(lcx.ccx.sess.get_cstore(), vid);
- let gvar = str::as_buf(sym, { |buf|
- llvm::LLVMAddGlobal(lcx.ccx.llmod, T_int(), buf)
- });
+ let gvar =
+ str::as_buf(sym,
+ {|buf|
+ llvm::LLVMAddGlobal(lcx.ccx.llmod, T_int(), buf)
+ });
llvm::LLVMSetLinkage(gvar,
lib::llvm::LLVMExternalLinkage as llvm::Linkage);
llvm::LLVMSetGlobalConstant(gvar, True);
ret lval_mem(cx, cx.fcx.llobjfields.get(did.node));
}
_ {
- bcx_ccx(cx).sess.span_unimpl
- (cx.sp, ~"unsupported def type in trans_local_def");
+ bcx_ccx(cx).sess.span_unimpl(
+ cx.sp,
+ "unsupported def type in trans_local_def");
}
}
}
-fn trans_var(cx: &@block_ctxt, sp: &span, def: &ast::def,
- id: ast::node_id) -> lval_result {
+fn trans_var(cx: &@block_ctxt, sp: &span, def: &ast::def, id: ast::node_id) ->
+ lval_result {
let ccx = bcx_ccx(cx);
alt def {
ast::def_fn(did, _) {
if std::vec::len(ty::tag_variants(ccx.tcx, tid)) != 1u {
let lldiscrim_gv = lookup_discriminant(bcx.fcx.lcx, vid);
let lldiscrim = Load(bcx, lldiscrim_gv);
- let lldiscrimptr =
- GEP(bcx, lltagptr, [C_int(0), C_int(0)]);
+ let lldiscrimptr = GEP(bcx, lltagptr, [C_int(0), C_int(0)]);
Store(bcx, lldiscrim, lldiscrimptr);
}
ret lval_val(bcx, lltagptr);
}
ty::ty_obj(methods) {
let ix: uint = ty::method_idx(bcx_ccx(cx).sess, sp, field, methods);
- let vtbl =
- GEP(r.bcx, r.val, [C_int(0), C_int(abi::obj_field_vtbl)]);
+ let vtbl = GEP(r.bcx, r.val, [C_int(0), C_int(abi::obj_field_vtbl)]);
vtbl = Load(r.bcx, vtbl);
let vtbl_type = T_ptr(T_array(T_ptr(T_nil()), ix + 1u));
ret {llobj: some::<ValueRef>(r.val), method_ty: some::<ty::t>(fn_ty)
with lvo};
}
- _ { bcx_ccx(cx).sess.unimpl(~"field variant in trans_field"); }
+ _ { bcx_ccx(cx).sess.unimpl("field variant in trans_field"); }
}
}
let unit_ty = node_id_type(bcx_ccx(cx), id);
let unit_sz = size_of(bcx, unit_ty);
bcx = unit_sz.bcx;
- maybe_name_value(bcx_ccx(cx), unit_sz.val, ~"unit_sz");
+ maybe_name_value(bcx_ccx(cx), unit_sz.val, "unit_sz");
let scaled_ix = Mul(bcx, ix_val, unit_sz.val);
- maybe_name_value(bcx_ccx(cx), scaled_ix, ~"scaled_ix");
+ maybe_name_value(bcx_ccx(cx), scaled_ix, "scaled_ix");
let lim = tvec::get_fill(bcx, v);
let body = tvec::get_dataptr(bcx, v, type_of_or_i8(bcx, unit_ty));
let bounds_check = ICmp(bcx, lib::llvm::LLVMIntULT, scaled_ix, lim);
- let fail_cx = new_sub_block_ctxt(bcx, ~"fail");
- let next_cx = new_sub_block_ctxt(bcx, ~"next");
+ let fail_cx = new_sub_block_ctxt(bcx, "fail");
+ let next_cx = new_sub_block_ctxt(bcx, "next");
let ncx = bcx_ccx(next_cx);
CondBr(bcx, bounds_check, next_cx.llbb, fail_cx.llbb);
// fail: bad bounds check.
- trans_fail(fail_cx, some::<span>(sp), ~"bounds check");
+ trans_fail(fail_cx, some::<span>(sp), "bounds check");
let elt = if check type_has_static_size(ncx, unit_ty) {
let elt_1 = GEP(next_cx, body, [ix_val]);
let llunitty = type_of(ncx, sp, unit_ty);
alt ty::struct(ccx.tcx, t) {
ty::ty_box(_) {
InBoundsGEP(sub.bcx, 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(_, _, _) {
}
_ {
// Shouldn't happen.
- bcx_ccx(cx).sess.bug(~"trans_lval called on \
+ bcx_ccx(cx).sess.bug("trans_lval called on \
expr_self_method in \
a context without llself");
}
{in: native_., out: native_.} {
PointerCast(e_res.bcx, e_res.val, ll_t_out)
}
- _ { ccx.sess.bug(~"Translating unsupported cast.") }
+ _ { ccx.sess.bug("Translating unsupported cast.") }
};
ret rslt(e_res.bcx, newval);
}
// construct and return that thunk.
// Give the thunk a name, type, and value.
- let s: istr =
- mangle_internal_name_by_path_and_seq(ccx, cx.path, ~"thunk");
+ let s: str =
+ mangle_internal_name_by_path_and_seq(ccx, cx.path, "thunk");
let llthunk_ty: TypeRef =
get_pair_fn_ty(type_of(ccx, sp, incoming_fty));
let llthunk: ValueRef =
let is_val = out_arg.mode == ty::mo_val;
alt arg {
+
// Arg provided at binding time; thunk copies it from
// closure.
some(e) {
}
+
// Arg will be provided when the thunk is invoked.
none. {
let arg: ValueRef = llvm::LLVMGetParam(llthunk, a);
}
} else if type_is_immediate(ccx, e_ty) && !lv.is_mem {
let r = do_spill(bcx, val, e_ty);
- val = r.val; bcx = r.bcx;
+ val = r.val;
+ bcx = r.bcx;
}
if !is_bot && ty::type_contains_params(ccx.tcx, arg.ty) {
// NB: 'f' isn't necessarily a function; it might be an entire self-call
// expression because of the hack that allows us to process self-calls
// with trans_call.
- let cx = new_scope_block_ctxt(in_cx, ~"call");
+ let cx = new_scope_block_ctxt(in_cx, "call");
Br(in_cx, cx.llbb);
let f_res = trans_lval_gen(cx, f);
let fn_ty: ty::t;
let pair = res.val;
faddr = GEP(bcx, pair, [C_int(0), C_int(abi::fn_field_code)]);
faddr = Load(bcx, faddr);
- let llclosure =
- GEP(bcx, pair, [C_int(0), C_int(abi::fn_field_box)]);
+ let llclosure = GEP(bcx, pair, [C_int(0), C_int(abi::fn_field_box)]);
llenv = Load(bcx, llclosure);
}
}
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) }
bcx = trans_block_cleanups(bcx, cx);
- let next_cx = new_sub_block_ctxt(in_cx, ~"next");
+ let next_cx = new_sub_block_ctxt(in_cx, "next");
Br(bcx, next_cx.llbb);
bcx = next_cx;
}
if str::eq(f.node.ident, tf.ident) {
expr_provided = true;
let lv = trans_lval(bcx, f.node.expr);
- bcx = move_val_if_temp(lv.res.bcx, INIT, dst_res.val,
- lv, e_ty);
+ bcx =
+ move_val_if_temp(lv.res.bcx, INIT, dst_res.val, lv, e_ty);
break;
}
}
let ccx = bcx_ccx(cx);
let llfnty: TypeRef =
type_of_fn_from_ty(ccx, e.span, node_id_type(ccx, e.id), 0u);
- let sub_cx = extend_path(cx.fcx.lcx,
- ccx.names.next(~"anon"));
- let s = mangle_internal_name_by_path(ccx,
- sub_cx.path);
- let llfn = decl_internal_fastcall_fn(ccx.llmod,
- s, llfnty);
+ let sub_cx = extend_path(cx.fcx.lcx, ccx.names.next("anon"));
+ let s = mangle_internal_name_by_path(ccx, sub_cx.path);
+ let llfn = decl_internal_fastcall_fn(ccx.llmod, s, llfnty);
let fn_res =
trans_closure(some(cx), some(llfnty), sub_cx, e.span, f, llfn,
alt fn_res {
some(fn_pair) { fn_pair }
none. {
- {fn_pair: create_fn_pair(ccx, s,
- llfnty, llfn, false),
+ {fn_pair: create_fn_pair(ccx, s, llfnty, llfn, false),
bcx: cx}
}
};
ret rslt(fn_pair.bcx, fn_pair.fn_pair);
}
ast::expr_block(blk) {
- let sub_cx = new_scope_block_ctxt(cx, ~"block-expr body");
- let next_cx = new_sub_block_ctxt(cx, ~"next");
+ let sub_cx = new_scope_block_ctxt(cx, "block-expr body");
+ let next_cx = new_sub_block_ctxt(cx, "next");
let sub =
with_out_method(bind trans_block(sub_cx, blk, _), cx, e.id,
output);
let t = ty::expr_ty(bcx_tcx(cx), src);
// FIXME: calculate copy init-ness in typestate.
- let bcx = move_val(rhs_res.res.bcx, DROP_EXISTING, lhs_res.res.val,
- rhs_res, t);
+ let bcx =
+ move_val(rhs_res.res.bcx, DROP_EXISTING, lhs_res.res.val, rhs_res,
+ t);
ret rslt(bcx, C_nil());
}
ast::expr_assign(dst, src) {
let rhs = trans_lval(lhs_res.res.bcx, src);
let t = ty::expr_ty(bcx_tcx(cx), src);
// FIXME: calculate copy init-ness in typestate.
- let bcx = move_val_if_temp(rhs.res.bcx, DROP_EXISTING,
- lhs_res.res.val, rhs, t);
+ let bcx =
+ move_val_if_temp(rhs.res.bcx, DROP_EXISTING, lhs_res.res.val, rhs,
+ t);
ret rslt(bcx, C_nil());
}
ast::expr_swap(dst, src) {
let rhs_res = trans_lval(lhs_res.res.bcx, src);
let t = ty::expr_ty(bcx_tcx(cx), src);
- let {bcx, val: tmp_alloc} = alloc_ty(rhs_res.res.bcx, t);
+ let {bcx: bcx, val: tmp_alloc} = alloc_ty(rhs_res.res.bcx, t);
// Swap through a temporary.
bcx = move_val(bcx, INIT, tmp_alloc, lhs_res, t);
bcx = move_val(bcx, INIT, lhs_res.res.val, rhs_res, t);
- bcx = move_val(bcx, INIT, rhs_res.res.val,
- lval_mem(bcx, tmp_alloc), t);
+ bcx =
+ move_val(bcx, INIT, rhs_res.res.val, lval_mem(bcx, tmp_alloc), t);
ret rslt(bcx, C_nil());
}
ast::expr_assign_op(op, dst, src) {
ty::ty_vec(_) {
alt src.node {
ast::expr_vec(args, _) {
- let bcx = tvec::trans_append_literal
- (lhs_res.res.bcx, lhs_res.res.val, t, args);
+ let bcx =
+ tvec::trans_append_literal(lhs_res.res.bcx,
+ lhs_res.res.val, t, args);
ret rslt(bcx, C_nil());
}
- _ {}
+ _ { }
}
}
- _ {}
+ _ { }
}
// FIXME Fill in lhs_res.res.bcx.sp
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 bcx = move_val(v.bcx, DROP_EXISTING, lhs_res.res.val,
- lval_val(v.bcx, v.val), t);
+ let bcx =
+ move_val(v.bcx, DROP_EXISTING, lhs_res.res.val,
+ lval_val(v.bcx, v.val), t);
ret rslt(bcx, C_nil());
}
ast::expr_bind(f, args) { ret trans_bind(cx, f, args, e.id); }
ast::expr_vec(args, _) { ret tvec::trans_vec(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"); }
+ ast::expr_mac(_) { ret bcx_ccx(cx).sess.bug("unexpanded macro"); }
ast::expr_fail(expr) { ret trans_fail_expr(cx, some(e.span), expr); }
ast::expr_log(lvl, a) { ret trans_log(lvl, cx, a); }
- ast::expr_assert(a) { ret trans_check_expr(cx, a, ~"Assertion"); }
+ ast::expr_assert(a) { ret trans_check_expr(cx, a, "Assertion"); }
ast::expr_check(ast::checked., a) {
- ret trans_check_expr(cx, a, ~"Predicate");
+ ret trans_check_expr(cx, a, "Predicate");
}
ast::expr_check(ast::unchecked., a) {
/* Claims are turned on and off by a global variable
otherwise. */
let c =
get_extern_const(bcx_ccx(cx).externs, bcx_ccx(cx).llmod,
- ~"check_claims", T_bool());
+ "check_claims", T_bool());
let cond = Load(cx, c);
- let then_cx = new_scope_block_ctxt(cx, ~"claim_then");
- let check_res = trans_check_expr(then_cx, a, ~"Claim");
- let else_cx = new_scope_block_ctxt(cx, ~"else");
+ let then_cx = new_scope_block_ctxt(cx, "claim_then");
+ let check_res = trans_check_expr(then_cx, a, "Claim");
+ let else_cx = new_scope_block_ctxt(cx, "else");
let els = rslt(else_cx, C_nil());
CondBr(cx, cond, then_cx.llbb, else_cx.llbb);
// that is_call_expr(ex) -- but we don't support that
// yet
// FIXME
- check ast_util::is_call_expr(ex);
+ check (ast_util::is_call_expr(ex));
ret trans_be(cx, ex);
}
ast::expr_anon_obj(anon_obj) {
// immediate-ness of the type.
fn type_is_immediate(ccx: &@crate_ctxt, t: ty::t) -> bool {
ret ty::type_is_scalar(ccx.tcx, t) || ty::type_is_boxed(ccx.tcx, t) ||
- ty::type_is_native(ccx.tcx, t) || ty::type_is_vec(ccx.tcx, t);
+ ty::type_is_native(ccx.tcx, t) || ty::type_is_vec(ccx.tcx, t);
}
fn do_spill(cx: &@block_ctxt, v: ValueRef, t: ty::t) -> result {
fn trans_log(lvl: int, cx: &@block_ctxt, e: &@ast::expr) -> result {
let lcx = cx.fcx.lcx;
- let modname = str::connect(lcx.module_path, ~"::");
+ let modname = str::connect(lcx.module_path, "::");
let global;
if lcx.ccx.module_data.contains_key(modname) {
global = lcx.ccx.module_data.get(modname);
} else {
let s =
- link::mangle_internal_name_by_path_and_seq(
- lcx.ccx,
- lcx.module_path,
- ~"loglevel");
- global = str::as_buf(s, { |buf|
- llvm::LLVMAddGlobal(lcx.ccx.llmod, T_int(), buf)
- });
+ link::mangle_internal_name_by_path_and_seq(lcx.ccx,
+ lcx.module_path,
+ "loglevel");
+ global =
+ str::as_buf(s,
+ {|buf|
+ llvm::LLVMAddGlobal(lcx.ccx.llmod, T_int(), buf)
+ });
llvm::LLVMSetGlobalConstant(global, False);
llvm::LLVMSetInitializer(global, C_null(T_int()));
llvm::LLVMSetLinkage(global,
lib::llvm::LLVMInternalLinkage as llvm::Linkage);
lcx.ccx.module_data.insert(modname, global);
}
- let log_cx = new_scope_block_ctxt(cx, ~"log");
- let after_cx = new_sub_block_ctxt(cx, ~"after");
+ let log_cx = new_scope_block_ctxt(cx, "log");
+ let after_cx = new_sub_block_ctxt(cx, "after");
let load = Load(cx, global);
let test = ICmp(cx, lib::llvm::LLVMIntSGE, load, C_int(lvl));
CondBr(cx, test, log_cx.llbb, after_cx.llbb);
ret rslt(after_cx, C_nil());
}
-fn trans_check_expr(cx: &@block_ctxt, e: &@ast::expr, s: &istr) -> result {
+fn trans_check_expr(cx: &@block_ctxt, e: &@ast::expr, s: &str) -> result {
let cond_res = trans_expr(cx, e);
- let expr_str = s + ~" " + expr_to_str(e) + ~" failed";
- let fail_cx = new_sub_block_ctxt(cx, ~"fail");
+ let expr_str = s + " " + expr_to_str(e) + " failed";
+ let fail_cx = new_sub_block_ctxt(cx, "fail");
trans_fail(fail_cx, some::<span>(e.span), expr_str);
- let next_cx = new_sub_block_ctxt(cx, ~"next");
+ let next_cx = new_sub_block_ctxt(cx, "next");
CondBr(cond_res.bcx, cond_res.val, next_cx.llbb, fail_cx.llbb);
ret rslt(next_cx, C_nil());
}
bcx = expr_res.bcx;
if ty::type_is_str(tcx, e_ty) {
- let data = tvec::get_dataptr(
- bcx, expr_res.val,
- type_of_or_i8(bcx, ty::mk_mach(tcx, ast::ty_u8)));
+ let data =
+ tvec::get_dataptr(bcx, expr_res.val,
+ type_of_or_i8(bcx,
+ ty::mk_mach(tcx,
+ ast::ty_u8)));
ret trans_fail_value(bcx, sp_opt, data);
} else {
bcx_ccx(cx).sess.span_bug(expr.span,
- ~"fail called with unsupported type "
- + ty_to_str(tcx, e_ty));
+ "fail called with unsupported type " +
+ ty_to_str(tcx, e_ty));
}
}
- _ { ret trans_fail(bcx, sp_opt, ~"explicit failure"); }
+ _ { ret trans_fail(bcx, sp_opt, "explicit failure"); }
}
}
-fn trans_fail(cx: &@block_ctxt, sp_opt: &option::t<span>, fail_str: &istr) ->
+fn trans_fail(cx: &@block_ctxt, sp_opt: &option::t<span>, fail_str: &str) ->
result {
let V_fail_str = C_cstr(bcx_ccx(cx), fail_str);
ret trans_fail_value(cx, sp_opt, V_fail_str);
V_filename = C_cstr(bcx_ccx(cx), loc.filename);
V_line = loc.line as int;
}
- none. { V_filename = C_cstr(bcx_ccx(cx), ~"<runtime>"); V_line = 0; }
+ none. { V_filename = C_cstr(bcx_ccx(cx), "<runtime>"); V_line = 0; }
}
let V_str = PointerCast(cx, V_fail_str, T_ptr(T_i8()));
V_filename = PointerCast(cx, V_filename, T_ptr(T_i8()));
}
fn trans_put(in_cx: &@block_ctxt, e: &option::t<@ast::expr>) -> result {
- let cx = new_scope_block_ctxt(in_cx, ~"put");
+ let cx = new_scope_block_ctxt(in_cx, "put");
Br(in_cx, cx.llbb);
let llcallee = C_nil();
let llenv = C_nil();
}
FastCall(bcx, llcallee, llargs);
bcx = trans_block_cleanups(bcx, cx);
- let next_cx = new_sub_block_ctxt(in_cx, ~"next");
+ let next_cx = new_sub_block_ctxt(in_cx, "next");
Br(bcx, next_cx.llbb);
ret rslt(next_cx, C_nil());
}
_ { Br(bcx, cleanup_cx.llbb); }
}
}
- ret rslt(new_sub_block_ctxt(bcx, ~"break_cont.unreachable"),
+ ret rslt(new_sub_block_ctxt(bcx, "break_cont.unreachable"),
C_nil());
}
_ {
parent_none. {
bcx_ccx(cx).sess.span_fatal(sp,
if to_end {
- ~"Break"
- } else { ~"Cont" } +
- ~" outside a loop");
+ "Break"
+ } else { "Cont" } +
+ " outside a loop");
}
}
}
}
// If we get here without returning, it's a bug
- bcx_ccx(cx).sess.bug(~"in trans::trans_break_cont()");
+ bcx_ccx(cx).sess.bug("in trans::trans_break_cont()");
}
fn trans_break(sp: &span, cx: &@block_ctxt) -> result {
};
if is_local {
bcx = move_val(bcx, INIT, cx.fcx.llretptr, lv, t);
- } else {
- bcx = move_val_if_temp(bcx, INIT, cx.fcx.llretptr, lv, t);
- }
+ } else { bcx = move_val_if_temp(bcx, INIT, cx.fcx.llretptr, lv, t); }
}
_ {
let t = llvm::LLVMGetElementType(val_ty(cx.fcx.llretptr));
}
}
build_return(bcx);
- ret rslt(new_sub_block_ctxt(bcx, ~"ret.unreachable"), C_nil());
+ ret rslt(new_sub_block_ctxt(bcx, "ret.unreachable"), C_nil());
}
fn build_return(bcx: &@block_ctxt) { Br(bcx, bcx_fcx(bcx).llreturn); }
// fn trans_be(cx: &@block_ctxt, e: &@ast::expr) -> result {
-fn trans_be(cx: &@block_ctxt, e: &@ast::expr)
- : ast_util::is_call_expr(e) -> result {
+fn trans_be(cx: &@block_ctxt, e: &@ast::expr) : ast_util::is_call_expr(e) ->
+ result {
// FIXME: Turn this into a real tail call once
// calling convention issues are settled
// Make a note to drop this slot on the way out.
add_clean(bcx, llptr, ty);
- if (must_zero(local)) {
- bcx = zero_alloca(bcx, llptr, ty).bcx;
- }
+ if must_zero(local) { bcx = zero_alloca(bcx, llptr, ty).bcx; }
alt local.node.init {
some(init) {
fn must_zero(local: &@ast::local) -> bool {
alt local.node.init {
- some(init) {
- might_not_init(init.expr)
- }
+ some(init) { might_not_init(init.expr) }
none. { true }
}
}
fn might_not_init(expr: &@ast::expr) -> bool {
type env = @mutable bool;
let e = @mutable false;
- let visitor = visit::mk_vt(@{
- visit_expr: fn(ex: &@ast::expr, e: &env, v: &vt<env>) {
- // FIXME: Probably also need to account for expressions that
- // fail but since we don't unwind yet, it doesn't seem to be a
- // problem
- let might_not_init = alt ex.node {
- ast::expr_ret(_) { true }
- ast::expr_break. { true }
- ast::expr_cont. { true }
- _ { false }
- };
- if might_not_init {
- *e = true;
- } else {
- visit::visit_expr(ex, e, v);
- }
- }
- with *visit::default_visitor()
- });
+ // FIXME: Probably also need to account for expressions that
+ // fail but since we don't unwind yet, it doesn't seem to be a
+ // problem
+ let visitor =
+ visit::mk_vt(
+ @{visit_expr:
+ fn (ex: &@ast::expr, e: &env, v: &vt<env>) {
+ let might_not_init =
+ alt ex.node {
+ ast::expr_ret(_) { true }
+ ast::expr_break. { true }
+ ast::expr_cont. { true }
+ _ { false }
+ };
+ if might_not_init {
+ *e = true;
+ } else { visit::visit_expr(ex, e, v); }
+ } with *visit::default_visitor()});
visitor.visit_expr(expr, e, visitor);
ret *e;
}
ast::decl_item(i) { trans_item(cx.fcx.lcx, *i); }
}
}
- _ { bcx_ccx(cx).sess.unimpl(~"stmt variant"); }
+ _ { bcx_ccx(cx).sess.unimpl("stmt variant"); }
}
ret rslt(bcx, C_nil());
}
// You probably don't want to use this one. See the
// next three functions instead.
fn new_block_ctxt(cx: &@fn_ctxt, parent: &block_parent, kind: block_kind,
- name: &istr) -> @block_ctxt {
- let s = ~"";
+ name: &str) -> @block_ctxt {
+ let s = "";
if cx.lcx.ccx.sess.get_opts().save_temps ||
cx.lcx.ccx.sess.get_opts().debuginfo {
s = cx.lcx.ccx.names.next(name);
}
- let llbb: BasicBlockRef = str::as_buf(s, { |buf|
- llvm::LLVMAppendBasicBlock(cx.llfn, buf)
- });
+ let llbb: BasicBlockRef =
+ str::as_buf(s, {|buf| llvm::LLVMAppendBasicBlock(cx.llfn, buf) });
ret @{llbb: llbb,
mutable terminated: false,
parent: parent,
// Use this when you're at the top block of a function or the like.
fn new_top_block_ctxt(fcx: &@fn_ctxt) -> @block_ctxt {
- ret new_block_ctxt(fcx, parent_none, SCOPE_BLOCK, ~"function top level");
+ ret new_block_ctxt(fcx, parent_none, SCOPE_BLOCK, "function top level");
}
// Use this when you're at a curly-brace or similar lexical scope.
-fn new_scope_block_ctxt(bcx: &@block_ctxt, n: &istr) -> @block_ctxt {
+fn new_scope_block_ctxt(bcx: &@block_ctxt, n: &str) -> @block_ctxt {
ret new_block_ctxt(bcx.fcx, parent_some(bcx), SCOPE_BLOCK, n);
}
fn new_loop_scope_block_ctxt(bcx: &@block_ctxt,
_cont: &option::t<@block_ctxt>,
- _break: &@block_ctxt, n: &istr) -> @block_ctxt {
+ _break: &@block_ctxt, n: &str) -> @block_ctxt {
ret new_block_ctxt(bcx.fcx, parent_some(bcx),
LOOP_SCOPE_BLOCK(_cont, _break), n);
}
// Use this when you're making a general CFG BB within a scope.
-fn new_sub_block_ctxt(bcx: &@block_ctxt, n: &istr) -> @block_ctxt {
+fn new_sub_block_ctxt(bcx: &@block_ctxt, n: &str) -> @block_ctxt {
ret new_block_ctxt(bcx.fcx, parent_some(bcx), NON_SCOPE_BLOCK, n);
}
some(lltoken_) {
let lltoken = lltoken_; // satisfy alias checker
Call(cx, fcx_ccx(fcx).upcalls.dynastack_free,
- [fcx.lltaskptr, lltoken]);
+ [fcx.lltaskptr, lltoken]);
}
none. {/* nothing to do */ }
}
alt local.node.pat.node {
ast::pat_bind(ident) {
if bcx_ccx(cx).sess.get_opts().debuginfo {
- let _: () = str::as_buf(ident, { |buf|
- llvm::LLVMSetValueName(r.val, buf)
- });
+ let _: () =
+ str::as_buf(ident,
+ {|buf| llvm::LLVMSetValueName(r.val, buf) });
}
}
_ { }
}
fn new_local_ctxt(ccx: &@crate_ctxt) -> @local_ctxt {
- let pth: [istr] = [];
+ let pth: [str] = [];
ret @{path: pth,
module_path: [ccx.link_meta.name],
obj_typarams: [],
dt: BasicBlockRef,
da: BasicBlockRef,
rt: BasicBlockRef} {
- ret {sa: str::as_buf(~"statuc_allocas", { |buf|
- llvm::LLVMAppendBasicBlock(llfn, buf)
- }),
- ca: str::as_buf(~"copy_args", { |buf|
- llvm::LLVMAppendBasicBlock(llfn, buf)
- }),
- dt: str::as_buf(~"derived_tydescs", { |buf|
- llvm::LLVMAppendBasicBlock(llfn, buf)
- }),
- da: str::as_buf(~"dynamic_allocas", { |buf|
- llvm::LLVMAppendBasicBlock(llfn, buf)
- }),
- rt: str::as_buf(~"return", { |buf|
- llvm::LLVMAppendBasicBlock(llfn, buf)
- })};
+ ret {sa:
+ str::as_buf("statuc_allocas",
+ {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
+ ca:
+ str::as_buf("copy_args",
+ {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
+ dt:
+ str::as_buf("derived_tydescs",
+ {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
+ da:
+ str::as_buf("dynamic_allocas",
+ {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
+ rt:
+ str::as_buf("return",
+ {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) })};
}
}
}
-fn copy_args_to_allocas(fcx: @fn_ctxt, scope: @block_ctxt,
- args: &[ast::arg], arg_tys: &[ty::arg]) {
+fn copy_args_to_allocas(fcx: @fn_ctxt, scope: @block_ctxt, args: &[ast::arg],
+ arg_tys: &[ty::arg]) {
let llcopyargs = new_raw_block_ctxt(fcx, fcx.llcopyargs);
let bcx = llcopyargs;
let arg_n: uint = 0u;
let arg_ty = arg_tys[arg_n].ty;
alt aarg.mode {
ast::val. {
+
// Structural types are passed by pointer, and we use the
// pointed-to memory for the local.
if !type_is_structural_or_param(fcx_tcx(fcx), arg_ty) {
ast::move. {
add_clean(scope, bcx.fcx.llargs.get(aarg.id), arg_ty);
}
- _ {}
+ _ { }
}
arg_n += 1u;
}
let fields_tup_ty = ty::mk_tup(fcx.lcx.ccx.tcx, field_tys);
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 =
- GEP(bcx, llself.v, [C_int(0), C_int(abi::obj_field_box)]);
+ let box_cell = GEP(bcx, llself.v, [C_int(0), C_int(abi::obj_field_box)]);
let box_ptr = Load(bcx, box_cell);
box_ptr = PointerCast(bcx, box_ptr, llobj_box_ty);
let obj_typarams =
GEP(bcx, 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.
// lldynamicallocas -> lltop edges, and builds the return block.
fn finish_fn(fcx: &@fn_ctxt, lltop: BasicBlockRef) {
Br(new_raw_block_ctxt(fcx, fcx.llstaticallocas), fcx.llcopyargs);
- Br(new_raw_block_ctxt(fcx, fcx.llcopyargs),
- fcx.llderivedtydescs_first);
- Br(new_raw_block_ctxt(fcx, fcx.llderivedtydescs),
- fcx.lldynamicallocas);
+ Br(new_raw_block_ctxt(fcx, fcx.llcopyargs), fcx.llderivedtydescs_first);
+ Br(new_raw_block_ctxt(fcx, fcx.llderivedtydescs), fcx.lldynamicallocas);
Br(new_raw_block_ctxt(fcx, fcx.lldynamicallocas), lltop);
let ret_cx = new_raw_block_ctxt(fcx, fcx.llreturn);
let start = time::get_time();
trans_fn_inner(cx, sp, f, llfndecl, ty_self, ty_params, id);
let end = time::get_time();
- log_fn_time(cx.ccx, str::connect(cx.path, ~"::"),
- start, end);
+ log_fn_time(cx.ccx, str::connect(cx.path, "::"), start, end);
}
fn trans_res_ctor(cx: @local_ctxt, sp: &span, dtor: &ast::_fn,
let llctor_decl;
alt cx.ccx.item_ids.find(ctor_id) {
some(x) { llctor_decl = x; }
- _ { cx.ccx.sess.span_fatal(sp, ~"unbound ctor_id in trans_res_ctor"); }
+ _ { cx.ccx.sess.span_fatal(sp, "unbound ctor_id in trans_res_ctor"); }
}
let fcx = new_fn_ctxt(cx, sp, llctor_decl);
let ret_t = ty::ret_ty_of_fn(cx.ccx.tcx, ctor_id);
let arg;
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"); }
+ _ { 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) {
fn_args +=
[{mode: ast::alias(false),
ty: varg.ty,
- ident: ~"arg" + uint::to_str(i, 10u),
+ ident: "arg" + uint::to_str(i, 10u),
id: varg.id}];
}
assert (cx.ccx.item_ids.contains_key(variant.node.id));
some(x) { llfndecl = x; }
_ {
cx.ccx.sess.span_fatal(variant.span,
- ~"unbound variant id in trans_tag_variant");
+ "unbound variant id in trans_tag_variant");
}
}
let fcx = new_fn_ctxt(cx, variant.span, llfndecl);
} else {
let lltagptr =
PointerCast(bcx, fcx.llretptr,
- T_opaque_tag_ptr(fcx.lcx.ccx.tn));
+ T_opaque_tag_ptr(fcx.lcx.ccx.tn));
let lldiscrimptr = GEP(bcx, lltagptr, [C_int(0), C_int(0)]);
Store(bcx, C_int(index), lldiscrimptr);
GEP(bcx, lltagptr, [C_int(0), C_int(1)])
let t_id = ast_util::local_def(tag_id);
let v_id = ast_util::local_def(variant.node.id);
for va: ast::variant_arg in variant.node.args {
- check valid_variant_index(i, bcx, t_id, v_id);
- let rslt =
- GEP_tag(bcx, llblobptr, t_id, v_id, ty_param_substs, i);
+ check (valid_variant_index(i, bcx, t_id, v_id));
+ let rslt = GEP_tag(bcx, llblobptr, t_id, v_id, ty_param_substs, i);
bcx = rslt.bcx;
let lldestptr = rslt.val;
// If this argument to this function is a tag, it'll have come in to
alt fcx.llargs.find(va.id) {
some(x) { llargptr = PointerCast(bcx, x, val_ty(lldestptr)); }
none. {
- bcx_ccx(bcx).sess.bug(~"unbound argptr in \
+ bcx_ccx(bcx).sess.bug("unbound argptr in \
trans_tag_variant");
}
}
fn trans_const_expr(cx: &@crate_ctxt, e: @ast::expr) -> ValueRef {
alt e.node {
ast::expr_lit(lit) { ret trans_crate_lit(cx, *lit); }
- _ { cx.sess.span_unimpl(e.span, ~"consts that's not a plain literal"); }
+ _ { cx.sess.span_unimpl(e.span, "consts that's not a plain literal"); }
}
}
llvm::LLVMSetInitializer(g, v);
llvm::LLVMSetGlobalConstant(g, True);
}
- _ { cx.sess.span_fatal(e.span, ~"Unbound const in trans_const"); }
+ _ { cx.sess.span_fatal(e.span, "Unbound const in trans_const"); }
}
}
}
_ {
cx.ccx.sess.span_fatal(item.span,
- ~"unbound function item in trans_item");
+ "unbound function item in trans_item");
}
}
}
trans_fn(cx, item.span, dtor, lldtor_decl, none, tps, dtor_id);
}
_ {
- cx.ccx.sess.span_fatal(item.span, ~"unbound dtor in trans_item");
+ cx.ccx.sess.span_fatal(item.span, "unbound dtor in trans_item");
}
}
}
ast::item_mod(m) {
let sub_cx =
@{path: cx.path + [item.ident],
- module_path: cx.module_path
- + [item.ident] with *cx};
+ module_path: cx.module_path + [item.ident] with *cx};
trans_mod(sub_cx, m);
}
ast::item_tag(variants, tps) {
ret struct_elt(llpairty, 0u);
}
-fn decl_fn_and_pair(ccx: &@crate_ctxt, sp: &span, path: &[istr], flav: &istr,
+fn decl_fn_and_pair(ccx: &@crate_ctxt, sp: &span, path: &[str], flav: &str,
ty_params: &[ast::ty_param], node_id: ast::node_id) {
decl_fn_and_pair_full(ccx, sp, path, flav, ty_params, node_id,
node_id_type(ccx, node_id));
}
-fn decl_fn_and_pair_full(ccx: &@crate_ctxt, sp: &span, path: &[istr],
- _flav: &istr, ty_params: &[ast::ty_param],
+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 path = path;
let llfty =
type_of_fn(ccx, sp, proto, inputs, output,
std::vec::len::<ast::ty_param>(ty_params));
}
- _ { ccx.sess.bug(
- ~"decl_fn_and_pair(): fn item doesn't have fn type!"); }
+ _ { ccx.sess.bug("decl_fn_and_pair(): fn item doesn't have fn type!"); }
}
- let s: istr = mangle_internal_name_by_path(ccx, path);
- let llfn: ValueRef = decl_internal_fastcall_fn(ccx.llmod,
- s, llfty);
+ 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.
- let ps: istr = mangle_exported_name(ccx, path, node_type);
+ let ps: str = mangle_exported_name(ccx, path, node_type);
register_fn_pair(ccx, ps, llfty, llfn, node_id);
let is_main: bool = is_main_name(path) && !ccx.sess.get_opts().library;
main_node_type: ty::t) {
if ccx.main_fn != none::<ValueRef> {
- ccx.sess.span_fatal(sp, ~"multiple 'main' functions");
+ ccx.sess.span_fatal(sp, "multiple 'main' functions");
}
let main_takes_argv =
alt ty::struct(ccx.tcx, main_node_type) {
- ty::ty_fn(_, args, _, _, _) {
- std::vec::len(args) != 0u
- }
+ ty::ty_fn(_, args, _, _, _) { std::vec::len(args) != 0u }
};
- let llfn = create_main(ccx, sp, main_llfn,
- main_takes_argv);
+ let llfn = create_main(ccx, sp, main_llfn, main_takes_argv);
ccx.main_fn = some(llfn);
fn create_main(ccx: &@crate_ctxt, sp: &span, main_llfn: ValueRef,
let unit_ty = ty::mk_istr(ccx.tcx);
let vecarg_ty: ty::arg =
{mode: ty::mo_val,
- ty:
- ty::mk_vec(ccx.tcx,
- {ty: unit_ty, mut: ast::imm})};
+ ty: ty::mk_vec(ccx.tcx, {ty: unit_ty, mut: ast::imm})};
let llfty =
type_of_fn(ccx, sp, ast::proto_fn, [vecarg_ty],
ty::mk_nil(ccx.tcx), 0u);
- let llfdecl = decl_fastcall_fn(ccx.llmod, ~"_rust_main", llfty);
+ let llfdecl = decl_fastcall_fn(ccx.llmod, "_rust_main", llfty);
let fcx = new_fn_ctxt(new_local_ctxt(ccx), sp, llfdecl);
// Create a closure: a pair containing (1) a ValueRef, pointing to where the
// fn's definition is in the executable we're creating, and (2) a pointer to
// space for the function's environment.
-fn create_fn_pair(cx: &@crate_ctxt, ps: &istr, llfnty: TypeRef,
- llfn: ValueRef, external: bool) -> ValueRef {
- let gvar = str::as_buf(ps, { |buf|
- llvm::LLVMAddGlobal(cx.llmod, T_fn_pair(*cx, llfnty), buf)
- });
+fn create_fn_pair(cx: &@crate_ctxt, ps: &str, llfnty: TypeRef, llfn: ValueRef,
+ external: bool) -> ValueRef {
+ let gvar =
+ str::as_buf(ps,
+ {|buf|
+ llvm::LLVMAddGlobal(cx.llmod, T_fn_pair(*cx, llfnty),
+ buf)
+ });
let pair = C_struct([llfn, C_null(T_opaque_closure_ptr(*cx))]);
llvm::LLVMSetInitializer(gvar, pair);
llvm::LLVMSetGlobalConstant(gvar, True);
ret pair;
}
-fn register_fn_pair(cx: &@crate_ctxt, ps: &istr, llfnty: TypeRef,
+fn register_fn_pair(cx: &@crate_ctxt, ps: &str, llfnty: TypeRef,
llfn: ValueRef, id: ast::node_id) {
// FIXME: We should also hide the unexported pairs in crates.
alt cx.ast_map.find(id) { some(ast_map::node_native_item(i)) { i } };
alt native_item.node {
ast::native_item_ty. {
- cx.sess.bug(~"decl_native_fn_and_pair(): native fn isn't \
+ cx.sess.bug("decl_native_fn_and_pair(): native fn isn't \
actually a fn");
}
ast::native_item_fn(_, _, tps) {
}
}
-fn decl_native_fn_and_pair(ccx: &@crate_ctxt, sp: &span, path: &[istr],
- name: &istr, id: ast::node_id) {
+fn decl_native_fn_and_pair(ccx: &@crate_ctxt, sp: &span, path: &[str],
+ name: &str, id: ast::node_id) {
let path = path;
let num_ty_param = native_fn_ty_param_count(ccx, id);
// Declare the wrapper.
let t = node_id_type(ccx, id);
let wrapper_type = native_fn_wrapper_type(ccx, sp, num_ty_param, t);
- let s: istr = mangle_internal_name_by_path(ccx, path);
+ let s: str = mangle_internal_name_by_path(ccx, path);
let wrapper_fn: ValueRef =
- decl_internal_fastcall_fn(ccx.llmod,
- s, wrapper_type);
+ decl_internal_fastcall_fn(ccx.llmod, s, wrapper_type);
// Declare the global constant pair that points to it.
- let ps: istr = mangle_exported_name(ccx, path, node_id_type(ccx, id));
+ let ps: str = mangle_exported_name(ccx, path, node_id_type(ccx, id));
register_fn_pair(ccx, ps, wrapper_type, wrapper_fn, id);
// Build the wrapper.
}
ret TruncOrBitCast(cx, v, T_int());
}
- if ty::type_is_fp(bcx_tcx(cx), t) {
- ret FPToSI(cx, v, T_int());
- }
+ if ty::type_is_fp(bcx_tcx(cx), t) { ret FPToSI(cx, v, T_int()); }
}
ret vp2i(cx, v);
}
- fn trans_simple_native_abi(bcx: &@block_ctxt, name: &istr,
+ 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} {
rptr = result.rptr;
}
ast::native_abi_rust_intrinsic. {
- let external_name = ~"rust_intrinsic_" + name;
+ let external_name = "rust_intrinsic_" + name;
let result =
trans_simple_native_abi(bcx, external_name, call_args, fn_type,
uses_retptr, lib::llvm::LLVMCCallConv);
rptr = result.rptr;
}
_ {
- r = trans_native_call(new_raw_block_ctxt(bcx.fcx, bcx.llbb),
+ r =
+ trans_native_call(new_raw_block_ctxt(bcx.fcx, bcx.llbb),
ccx.externs, ccx.llmod, name, call_args);
rptr = BitCast(bcx, fcx.llretptr, T_ptr(T_i32()));
}
finish_fn(fcx, lltop);
}
-fn item_path(item: &@ast::item) -> [istr] { 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: &[istr],
- _v: &vt<[istr]>) {
+fn collect_native_item(ccx: @crate_ctxt, i: &@ast::native_item, pt: &[str],
+ _v: &vt<[str]>) {
alt i.node {
ast::native_item_fn(_, _, _) {
if !ccx.obj_methods.contains_key(i.id) {
- decl_native_fn_and_pair(ccx, i.span, pt,
- i.ident, i.id);
+ decl_native_fn_and_pair(ccx, i.span, pt, i.ident, i.id);
}
}
_ { }
}
}
-fn collect_item_1(ccx: @crate_ctxt, i: &@ast::item, pt: &[istr],
- v: &vt<[istr]>) {
+fn collect_item_1(ccx: @crate_ctxt, i: &@ast::item, pt: &[str],
+ v: &vt<[str]>) {
visit::visit_item(i, pt + item_path(i), v);
alt i.node {
ast::item_const(_, _) {
}
}
-fn collect_item_2(ccx: &@crate_ctxt, i: &@ast::item, pt: &[istr],
- v: &vt<[istr]>) {
+fn collect_item_2(ccx: &@crate_ctxt, i: &@ast::item, pt: &[str],
+ v: &vt<[str]>) {
let new_pt = pt + item_path(i);
visit::visit_item(i, new_pt, v);
alt i.node {
ast::item_fn(f, tps) {
if !ccx.obj_methods.contains_key(i.id) {
- decl_fn_and_pair(ccx, i.span, new_pt, ~"fn", tps, i.id);
+ decl_fn_and_pair(ccx, i.span, new_pt, "fn", tps, i.id);
}
}
ast::item_obj(ob, tps, ctor_id) {
- decl_fn_and_pair(ccx, i.span, new_pt, ~"obj_ctor", tps, ctor_id);
+ decl_fn_and_pair(ccx, i.span, new_pt, "obj_ctor", tps, ctor_id);
for m: @ast::method in ob.methods {
ccx.obj_methods.insert(m.node.id, ());
}
}
ast::item_res(_, dtor_id, tps, ctor_id) {
- decl_fn_and_pair(ccx, i.span, new_pt, ~"res_ctor", tps, ctor_id);
+ decl_fn_and_pair(ccx, i.span, new_pt, "res_ctor", tps, ctor_id);
// Note that the destructor is associated with the item's id, not
// the dtor_id. This is a bit counter-intuitive, but simplifies
// ty_res, which would have to carry around two def_ids otherwise
// -- one to identify the type, and one to find the dtor symbol.
- decl_fn_and_pair_full(ccx, i.span, new_pt, ~"res_dtor", tps, i.id,
+ decl_fn_and_pair_full(ccx, i.span, new_pt, "res_dtor", tps, i.id,
node_id_type(ccx, dtor_id));
}
_ { }
visit::visit_crate(*crate, [], visit::mk_vt(visitor2));
}
-fn collect_tag_ctor(ccx: @crate_ctxt, i: &@ast::item, pt: &[istr],
- v: &vt<[istr]>) {
+fn collect_tag_ctor(ccx: @crate_ctxt, i: &@ast::item, pt: &[str],
+ v: &vt<[str]>) {
let new_pt = pt + item_path(i);
visit::visit_item(i, new_pt, v);
alt i.node {
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],
- ~"tag", tps, variant.node.id);
+ decl_fn_and_pair(ccx, i.span, new_pt + [variant.node.name],
+ "tag", tps, variant.node.id);
}
}
}
// The constant translation pass.
-fn trans_constant(ccx: @crate_ctxt, it: &@ast::item, pt: &[istr],
- v: &vt<[istr]>) {
+fn trans_constant(ccx: @crate_ctxt, it: &@ast::item, pt: &[str],
+ v: &vt<[str]>) {
let new_pt = pt + item_path(it);
visit::visit_item(it, new_pt, v);
alt it.node {
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 s = mangle_exported_name(ccx, p,
- ty::mk_int(ccx.tcx));
- let discrim_gvar = str::as_buf(s, { |buf|
- llvm::LLVMAddGlobal(ccx.llmod, T_int(), buf)
- });
+ 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 =
+ str::as_buf(s,
+ {|buf|
+ llvm::LLVMAddGlobal(ccx.llmod, T_int(), buf)
+ });
if n_variants != 1u {
llvm::LLVMSetInitializer(discrim_gvar, C_int(i as int));
llvm::LLVMSetGlobalConstant(discrim_gvar, True);
fn p2i(v: ValueRef) -> ValueRef { ret llvm::LLVMConstPtrToInt(v, T_int()); }
-fn declare_intrinsics(llmod: ModuleRef) -> hashmap<istr, 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()];
let T_memmove64_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",
+ decl_cdecl_fn(llmod, "llvm.gcroot",
T_fn([T_ptr(T_ptr(T_i8())), T_ptr(T_i8())], T_void()));
let gcread =
- decl_cdecl_fn(llmod, ~"llvm.gcread",
+ decl_cdecl_fn(llmod, "llvm.gcread",
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",
+ decl_cdecl_fn(llmod, "llvm.memmove.p0i8.p0i8.i32",
T_fn(T_memmove32_args, T_void()));
let memmove64 =
- decl_cdecl_fn(llmod, ~"llvm.memmove.p0i8.p0i8.i64",
+ decl_cdecl_fn(llmod, "llvm.memmove.p0i8.p0i8.i64",
T_fn(T_memmove64_args, T_void()));
let memset32 =
- decl_cdecl_fn(llmod, ~"llvm.memset.p0i8.i32",
+ decl_cdecl_fn(llmod, "llvm.memset.p0i8.i32",
T_fn(T_memset32_args, T_void()));
let memset64 =
- decl_cdecl_fn(llmod, ~"llvm.memset.p0i8.i64",
+ decl_cdecl_fn(llmod, "llvm.memset.p0i8.i64",
T_fn(T_memset64_args, T_void()));
- let trap = decl_cdecl_fn(llmod, ~"llvm.trap",
- T_fn(T_trap_args, T_void()));
+ let trap = decl_cdecl_fn(llmod, "llvm.trap", T_fn(T_trap_args, T_void()));
let intrinsics = new_str_hash::<ValueRef>();
- intrinsics.insert(~"llvm.gcroot", gcroot);
- intrinsics.insert(~"llvm.gcread", gcread);
- intrinsics.insert(~"llvm.memmove.p0i8.p0i8.i32", memmove32);
- intrinsics.insert(~"llvm.memmove.p0i8.p0i8.i64", memmove64);
- intrinsics.insert(~"llvm.memset.p0i8.i32", memset32);
- intrinsics.insert(~"llvm.memset.p0i8.i64", memset64);
- intrinsics.insert(~"llvm.trap", trap);
+ intrinsics.insert("llvm.gcroot", gcroot);
+ intrinsics.insert("llvm.gcread", gcread);
+ intrinsics.insert("llvm.memmove.p0i8.p0i8.i32", memmove32);
+ intrinsics.insert("llvm.memmove.p0i8.p0i8.i64", memmove64);
+ intrinsics.insert("llvm.memset.p0i8.i32", memset32);
+ intrinsics.insert("llvm.memset.p0i8.i64", memset64);
+ intrinsics.insert("llvm.trap", trap);
ret intrinsics;
}
fn trap(bcx: &@block_ctxt) {
let v: [ValueRef] = [];
- alt bcx_ccx(bcx).intrinsics.find(~"llvm.trap") {
+ alt bcx_ccx(bcx).intrinsics.find("llvm.trap") {
some(x) { Call(bcx, x, v); }
- _ { bcx_ccx(bcx).sess.bug(~"unbound llvm.trap in trap"); }
+ _ { 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());
- ret decl_fastcall_fn(llmod,
- abi::no_op_type_glue_name(), ty);
+ ret decl_fastcall_fn(llmod, abi::no_op_type_glue_name(), ty);
}
fn make_glues(llmod: ModuleRef, taskptr_type: TypeRef) -> @glue_fns {
ret @{no_op_type_glue: decl_no_op_type_glue(llmod, taskptr_type)};
}
-fn make_common_glue(sess: &session::session, output: &istr) {
+fn make_common_glue(sess: &session::session, output: &str) {
// FIXME: part of this is repetitive and is probably a good idea
// to autogen it.
let task_type = T_task();
let taskptr_type = T_ptr(task_type);
- let llmod = str::as_buf(~"rust_out", { |buf|
- llvm::LLVMModuleCreateWithNameInContext(buf,
- llvm::LLVMGetGlobalContext())
- });
- let _: () = str::as_buf(x86::get_data_layout(), { |buf|
- llvm::LLVMSetDataLayout(llmod, buf)
- });
- let _: () = str::as_buf(x86::get_target_triple(), { |buf|
- llvm::LLVMSetTarget(llmod, buf)
- });
+ let llmod =
+ str::as_buf("rust_out", {|buf|
+ llvm::LLVMModuleCreateWithNameInContext(
+ buf, llvm::LLVMGetGlobalContext())
+ });
+ let _: () =
+ str::as_buf(x86::get_data_layout(),
+ {|buf| llvm::LLVMSetDataLayout(llmod, buf) });
+ let _: () =
+ str::as_buf(x86::get_target_triple(),
+ {|buf| llvm::LLVMSetTarget(llmod, buf) });
mk_target_data(x86::get_data_layout());
declare_intrinsics(llmod);
- let _: () = str::as_buf(x86::get_module_asm(), { |buf|
- llvm::LLVMSetModuleInlineAsm(llmod, buf)
- });
+ let _: () =
+ str::as_buf(x86::get_module_asm(),
+ {|buf| llvm::LLVMSetModuleInlineAsm(llmod, buf) });
make_glues(llmod, taskptr_type);
link::write::run_passes(sess, llmod, output);
}
fn create_module_map(ccx: &@crate_ctxt) -> ValueRef {
let elttype = T_struct([T_int(), T_int()]);
let maptype = T_array(elttype, ccx.module_data.size() + 1u);
- let map = str::as_buf(~"_rust_mod_map", { |buf|
- llvm::LLVMAddGlobal(ccx.llmod, maptype, buf)
- });
+ let map =
+ str::as_buf("_rust_mod_map",
+ {|buf| llvm::LLVMAddGlobal(ccx.llmod, maptype, buf) });
llvm::LLVMSetLinkage(map,
lib::llvm::LLVMInternalLinkage as llvm::Linkage);
let elts: [ValueRef] = [];
- for each item: @{key: istr, val: ValueRef} in ccx.module_data.items() {
- let elt = C_struct([p2i(C_cstr(ccx, item.key)),
- p2i(item.val)]);
+ 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 term = C_struct([C_int(0), C_int(0)]);
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 = str::as_buf(nm, { |buf|
- llvm::LLVMAddGlobal(ccx.llmod, T_int(), buf)
- });
+ let nm = "_rust_crate_map_" + cstore::get_crate_data(cstore, i).name;
+ let cr =
+ str::as_buf(nm,
+ {|buf|
+ llvm::LLVMAddGlobal(ccx.llmod, T_int(), buf)
+ });
subcrates += [p2i(cr)];
i += 1;
}
let mapname;
if ccx.sess.get_opts().library {
mapname = ccx.link_meta.name;
- } else { mapname = ~"toplevel"; }
- let sym_name = ~"_rust_crate_map_" + mapname;
+ } 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 map = str::as_buf(sym_name, { |buf|
- llvm::LLVMAddGlobal(ccx.llmod, maptype, buf)
- });
+ let map =
+ str::as_buf(sym_name,
+ {|buf| llvm::LLVMAddGlobal(ccx.llmod, maptype, buf) });
llvm::LLVMSetLinkage(map,
lib::llvm::LLVMExternalLinkage as llvm::Linkage);
llvm::LLVMSetInitializer(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 llmeta = C_postr(metadata::encoder::encode_metadata(cx, crate));
let llconst = trans_common::C_struct([llmeta]);
- let llglobal = str::as_buf(~"rust_metadata", { |buf|
- llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst), buf)
- });
+ let llglobal =
+ str::as_buf("rust_metadata",
+ {|buf|
+ llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst), buf)
+ });
llvm::LLVMSetInitializer(llglobal, llconst);
- let _: () = str::as_buf(x86::get_meta_sect_name(), { |buf|
- llvm::LLVMSetSection(llglobal, buf)
- });
+ let _: () =
+ str::as_buf(x86::get_meta_sect_name(),
+ {|buf| llvm::LLVMSetSection(llglobal, buf) });
llvm::LLVMSetLinkage(llglobal,
lib::llvm::LLVMInternalLinkage as llvm::Linkage);
let t_ptr_i8 = T_ptr(T_i8());
llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8);
- let llvm_used = str::as_buf(~"llvm.used", { |buf|
- llvm::LLVMAddGlobal(cx.llmod, T_array(t_ptr_i8, 1u), buf)
- });
+ let llvm_used =
+ str::as_buf("llvm.used",
+ {|buf|
+ llvm::LLVMAddGlobal(cx.llmod, T_array(t_ptr_i8, 1u),
+ buf)
+ });
llvm::LLVMSetLinkage(llvm_used,
lib::llvm::LLVMAppendingLinkage as llvm::Linkage);
llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
// Writes the current ABI version into the crate.
fn write_abi_version(ccx: &@crate_ctxt) {
- shape::mk_global(ccx, ~"rust_abi_version", C_uint(abi::abi_version),
+ shape::mk_global(ccx, "rust_abi_version", C_uint(abi::abi_version),
false);
}
fn trans_crate(sess: &session::session, crate: &@ast::crate, tcx: &ty::ctxt,
- output: &istr, amap: &ast_map::map, mut_map: mut::mut_map)
- -> ModuleRef {
- let llmod = str::as_buf(~"rust_out", { |buf|
- llvm::LLVMModuleCreateWithNameInContext(buf,
- llvm::LLVMGetGlobalContext())
- });
- let _: () = str::as_buf(x86::get_data_layout(), { |buf|
- llvm::LLVMSetDataLayout(llmod, buf)
- });
- let _: () = str::as_buf(x86::get_target_triple(), { |buf|
- llvm::LLVMSetTarget(llmod, buf)
- });
+ output: &str, amap: &ast_map::map, mut_map: mut::mut_map) ->
+ ModuleRef {
+ let llmod =
+ str::as_buf("rust_out", {|buf|
+ llvm::LLVMModuleCreateWithNameInContext(
+ buf, llvm::LLVMGetGlobalContext())
+ });
+ let _: () =
+ str::as_buf(x86::get_data_layout(),
+ {|buf| llvm::LLVMSetDataLayout(llmod, buf) });
+ let _: () =
+ str::as_buf(x86::get_target_triple(),
+ {|buf| llvm::LLVMSetTarget(llmod, buf) });
let td = mk_target_data(x86::get_data_layout());
let tn = mk_type_names();
let intrinsics = declare_intrinsics(llmod);
let task_type = T_task();
let taskptr_type = T_ptr(task_type);
- tn.associate(~"taskptr", taskptr_type);
+ tn.associate("taskptr", taskptr_type);
let tydesc_type = T_tydesc(taskptr_type);
- tn.associate(~"tydesc", tydesc_type);
+ tn.associate("tydesc", tydesc_type);
let glues = make_glues(llmod, taskptr_type);
let hasher = ty::hash_ty;
let eqer = ty::eq_ty;
let tag_sizes = map::mk_hashmap::<ty::t, uint>(hasher, eqer);
let tydescs = map::mk_hashmap::<ty::t, @tydesc_info>(hasher, eqer);
let lltypes = map::mk_hashmap::<ty::t, TypeRef>(hasher, eqer);
- let sha1s = map::mk_hashmap::<ty::t, istr>(hasher, eqer);
- let short_names = map::mk_hashmap::<ty::t, istr>(hasher, eqer);
+ let sha1s = map::mk_hashmap::<ty::t, str>(hasher, eqer);
+ let short_names = map::mk_hashmap::<ty::t, str>(hasher, eqer);
let sha = std::sha1::mk_sha1();
let ccx =
@{sess: sess,
intrinsics: intrinsics,
item_ids: new_int_hash::<ValueRef>(),
ast_map: amap,
- item_symbols: new_int_hash::<istr>(),
+ item_symbols: new_int_hash::<str>(),
mutable main_fn: none::<ValueRef>,
- link_meta: link::build_link_meta(sess, *crate,
- output, sha),
+ link_meta: link::build_link_meta(sess, *crate, output, sha),
tag_sizes: tag_sizes,
discrims: new_int_hash::<ValueRef>(),
- discrim_symbols: new_int_hash::<istr>(),
+ discrim_symbols: new_int_hash::<str>(),
fn_pairs: new_int_hash::<ValueRef>(),
consts: new_int_hash::<ValueRef>(),
obj_methods: new_int_hash::<()>(),
log_err #fmt["n_real_glues: %u", ccx.stats.n_real_glues];
- for timing: {ident: istr, time: int} in *ccx.stats.fn_times {
- log_err #fmt["time: %s took %d ms",
- timing.ident, timing.time];
+ for timing: {ident: str, time: int} in *ccx.stats.fn_times {
+ log_err #fmt["time: %s took %d ms", timing.ident, timing.time];
}
}
ret llmod;
}
type bind_map = [{ident: ast::ident, val: ValueRef}];
-fn assoc(key: &istr, list: &bind_map) -> option::t<ValueRef> {
+fn assoc(key: &str, list: &bind_map) -> option::t<ValueRef> {
for elt: {ident: ast::ident, val: ValueRef} in list {
if str::eq(elt.ident, key) { ret some(elt.val); }
}
type match_branch =
@{pats: [@ast::pat],
bound: bind_map,
- data: @{body: BasicBlockRef,
- guard: option::t<@ast::expr>,
- id_map: ast_util::pat_id_map}};
+ data:
+ @{body: BasicBlockRef,
+ guard: option::t<@ast::expr>,
+ id_map: ast_util::pat_id_map}};
type match = [match_branch];
fn matches_always(p: &@ast::pat) -> bool {
for br: match_branch in m {
alt e(br.pats[col]) {
some(sub) {
- let pats = vec::slice(br.pats, 0u, col) + 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,
- bound: alt br.pats[col].node {
- ast::pat_bind(name) {
- br.bound + [{ident: name, val: val}]
- }
- _ { br.bound }
- }
- with *br};
+ let new_br =
+ @{pats: pats,
+ bound:
+ alt br.pats[col].node {
+ ast::pat_bind(name) {
+ br.bound + [{ident: name, val: val}]
+ }
+ _ { br.bound }
+ } with *br};
result += [new_br];
}
none. { }
vec::len(ty::tag_variant_with_id(ccx.tcx, vdefs.tg, vdefs.var).args);
if size > 0u && vec::len(variants) != 1u {
let tagptr =
- PointerCast(bcx, val,
- trans_common::T_opaque_tag_ptr(ccx.tn));
+ PointerCast(bcx, val, trans_common::T_opaque_tag_ptr(ccx.tn));
blobptr = GEP(bcx, tagptr, [C_int(0), C_int(1)]);
}
let i = 0u;
let vdefs_tg = vdefs.tg;
let vdefs_var = vdefs.var;
while i < size {
- check valid_variant_index(i, bcx, vdefs_tg, vdefs_var);
+ check (valid_variant_index(i, bcx, vdefs_tg, vdefs_var));
let r =
trans::GEP_tag(bcx, blobptr, vdefs_tg, vdefs_var, ty_param_substs,
i);
let data = m[0].data;
alt data.guard {
some(e) {
- let guard_cx = new_scope_block_ctxt(bcx, ~"submatch_guard");
- let next_cx = new_sub_block_ctxt(bcx, ~"submatch_next");
- let else_cx = new_sub_block_ctxt(bcx, ~"submatch_else");
+ let guard_cx = new_scope_block_ctxt(bcx, "submatch_guard");
+ let next_cx = new_sub_block_ctxt(bcx, "submatch_next");
+ let else_cx = new_sub_block_ctxt(bcx, "submatch_else");
Br(bcx, guard_cx.llbb);
// Temporarily set bindings. They'll be rewritten to PHI nodes for
// the actual arm block.
- for each @{key, val} in data.id_map.items() {
- bcx.fcx.lllocals.insert
- (val, option::get(assoc(key,
- m[0].bound)));
+ for each @{key: key, val: val} in data.id_map.items() {
+ bcx.fcx.lllocals.insert(val,
+ option::get(assoc(key, m[0].bound)));
}
let {bcx: guard_bcx, val: guard_val} =
trans::trans_expr(guard_cx, e);
guard_bcx = trans::trans_block_cleanups(guard_bcx, guard_cx);
CondBr(guard_bcx, guard_val, next_cx.llbb, else_cx.llbb);
- compile_submatch(else_cx, vec::slice(m, 1u, vec::len(m)),
- vals, f, exits);
+ compile_submatch(else_cx, vec::slice(m, 1u, vec::len(m)), vals, f,
+ exits);
bcx = next_cx;
}
- _ {}
+ _ { }
}
exits += [{bound: m[0].bound, from: bcx.llbb, to: data.body}];
Br(bcx, data.body);
let box = Load(bcx, val);
let unboxed =
InBoundsGEP(bcx, box,
- [C_int(0),
- C_int(back::abi::box_rc_field_body)]);
+ [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;
} else {
let tagptr =
PointerCast(bcx, val,
- trans_common::T_opaque_tag_ptr(ccx.tn));
+ trans_common::T_opaque_tag_ptr(ccx.tn));
let discrimptr = GEP(bcx, tagptr, [C_int(0), C_int(0)]);
test_val = Load(bcx, discrimptr);
kind = switch;
let else_cx =
alt kind {
no_branch. | single. { bcx }
- _ { new_sub_block_ctxt(bcx, ~"match_else") }
+ _ { new_sub_block_ctxt(bcx, "match_else") }
};
let sw =
if kind == switch {
// Compile subtrees for each option
for opt: opt in opts {
- let opt_cx = new_sub_block_ctxt(bcx, ~"match_case");
+ let opt_cx = new_sub_block_ctxt(bcx, "match_case");
alt kind {
single. { Br(bcx, opt_cx.llbb); }
switch. {
llvm::LLVMAddCase(sw, r.val, opt_cx.llbb);
}
compare. {
- let compare_cx = new_scope_block_ctxt(bcx, ~"compare_scope");
+ let compare_cx = new_scope_block_ctxt(bcx, "compare_scope");
Br(bcx, compare_cx.llbb);
bcx = compare_cx;
let r = trans_opt(bcx, opt);
let eq =
trans::trans_compare(bcx, ast::eq, test_val, t, r.val, t);
let cleanup_cx = trans::trans_block_cleanups(bcx, compare_cx);
- bcx = new_sub_block_ctxt(bcx, ~"compare_next");
+ bcx = new_sub_block_ctxt(bcx, "compare_next");
CondBr(cleanup_cx, eq.val, opt_cx.llbb, bcx.llbb);
}
_ { }
}
for a: ast::arm in arms {
- let body = new_scope_block_ctxt(cx, ~"case_body");
+ let body = new_scope_block_ctxt(cx, "case_body");
let id_map = ast_util::pat_id_map(a.pats[0]);
bodies += [body];
for p: @ast::pat in a.pats {
- match += [@{pats: [p],
- bound: [],
- data: @{body: body.llbb,
- guard: a.guard,
- id_map: id_map}}];
+ match +=
+ [@{pats: [p],
+ bound: [],
+ data: @{body: body.llbb, guard: a.guard, id_map: id_map}}];
}
}
fn mk_fail(cx: &@block_ctxt, sp: &span,
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");
+ let fail_cx = new_sub_block_ctxt(cx, "case_fallthrough");
+ trans::trans_fail(fail_cx, some(sp), "non-exhaustive match failure");;
*done = some(fail_cx.llbb);
ret fail_cx.llbb;
}
check type_has_static_size(ccx, ty);
let llty = trans::type_of(ccx, pat.span, ty);
let alloc = trans::alloca(bcx, llty);
- bcx = trans::copy_val(bcx, trans::INIT, alloc,
- trans::load_if_immediate(bcx, val, ty), ty);
+ bcx =
+ trans::copy_val(bcx, trans::INIT, alloc,
+ trans::load_if_immediate(bcx, val, ty), ty);
table.insert(pat.id, alloc);
trans_common::add_clean(bcx, alloc, ty);
} else { table.insert(pat.id, val); }
}
ast::pat_box(inner) {
let box = Load(bcx, val);
- let unboxed = InBoundsGEP(bcx, box,
- [C_int(0),
- C_int(back::abi::box_rc_field_body)]);
+ let unboxed =
+ InBoundsGEP(bcx, 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(_) { }
import std::{vec, str};
import std::str::sbuf;
import lib::llvm::llvm;
-import llvm::{ValueRef, TypeRef, BasicBlockRef, BuilderRef,
- Opcode, ModuleRef};
+import llvm::{ValueRef, TypeRef, BasicBlockRef, BuilderRef, Opcode,
+ ModuleRef};
import trans_common::block_ctxt;
fn B(cx: &@block_ctxt) -> BuilderRef {
}
fn RetVoid(cx: &@block_ctxt) -> ValueRef {
- assert (!cx.terminated);;
+ assert (!cx.terminated);
cx.terminated = true;
ret llvm::LLVMBuildRetVoid(B(cx));
}
fn Ret(cx: &@block_ctxt, V: ValueRef) -> ValueRef {
- assert (!cx.terminated);;
+ assert (!cx.terminated);
cx.terminated = true;
ret llvm::LLVMBuildRet(B(cx), V);
}
fn AggregateRet(cx: &@block_ctxt, RetVals: &[ValueRef]) -> ValueRef {
- assert (!cx.terminated);;
+ assert (!cx.terminated);
cx.terminated = true;
ret llvm::LLVMBuildAggregateRet(B(cx), vec::to_ptr(RetVals),
vec::len(RetVals));
}
fn Br(cx: &@block_ctxt, Dest: BasicBlockRef) -> ValueRef {
- assert (!cx.terminated);;
+ assert (!cx.terminated);
cx.terminated = true;
ret llvm::LLVMBuildBr(B(cx), Dest);
}
fn CondBr(cx: &@block_ctxt, If: ValueRef, Then: BasicBlockRef,
Else: BasicBlockRef) -> ValueRef {
- assert (!cx.terminated);;
+ assert (!cx.terminated);
cx.terminated = true;
ret llvm::LLVMBuildCondBr(B(cx), If, Then, Else);
}
-fn Switch(cx: &@block_ctxt, V: ValueRef, Else: BasicBlockRef,
- NumCases: uint) -> ValueRef {
- assert (!cx.terminated);;
+fn Switch(cx: &@block_ctxt, V: ValueRef, Else: BasicBlockRef, NumCases: uint)
+ -> ValueRef {
+ assert (!cx.terminated);
cx.terminated = true;
ret llvm::LLVMBuildSwitch(B(cx), V, Else, NumCases);
}
-fn IndirectBr(cx: &@block_ctxt, Addr: ValueRef,
- NumDests: uint) -> ValueRef {
- assert (!cx.terminated);;
+fn IndirectBr(cx: &@block_ctxt, Addr: ValueRef, NumDests: uint) -> ValueRef {
+ assert (!cx.terminated);
cx.terminated = true;
ret llvm::LLVMBuildIndirectBr(B(cx), Addr, NumDests);
}
fn Invoke(cx: &@block_ctxt, Fn: ValueRef, Args: &[ValueRef],
Then: BasicBlockRef, Catch: BasicBlockRef) -> ValueRef {
- assert (!cx.terminated);;
+ assert (!cx.terminated);
cx.terminated = true;
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildInvoke(B(cx), Fn, vec::to_ptr(Args),
- vec::len(Args), Then, Catch, buf)
- });
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildInvoke(B(cx), Fn, vec::to_ptr(Args),
+ vec::len(Args), Then, Catch,
+ buf)
+ });
}
fn Unreachable(cx: &@block_ctxt) -> ValueRef {
- assert (!cx.terminated);;
+ assert (!cx.terminated);
cx.terminated = true;
ret llvm::LLVMBuildUnreachable(B(cx));
}
/* Arithmetic */
fn Add(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildAdd(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildAdd(B(cx), LHS, RHS, buf) });
}
fn NSWAdd(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildNSWAdd(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildNSWAdd(B(cx), LHS, RHS, buf) });
}
fn NUWAdd(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildNUWAdd(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildNUWAdd(B(cx), LHS, RHS, buf) });
}
fn FAdd(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildFAdd(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildFAdd(B(cx), LHS, RHS, buf) });
}
fn Sub(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildSub(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildSub(B(cx), LHS, RHS, buf) });
}
fn NSWSub(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildNSWSub(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildNSWSub(B(cx), LHS, RHS, buf) });
}
fn NUWSub(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildNUWSub(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildNUWSub(B(cx), LHS, RHS, buf) });
}
fn FSub(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildFSub(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildFSub(B(cx), LHS, RHS, buf) });
}
fn Mul(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildMul(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildMul(B(cx), LHS, RHS, buf) });
}
fn NSWMul(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildNSWMul(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildNSWMul(B(cx), LHS, RHS, buf) });
}
fn NUWMul(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildNUWMul(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildNUWMul(B(cx), LHS, RHS, buf) });
}
fn FMul(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildFMul(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildFMul(B(cx), LHS, RHS, buf) });
}
fn UDiv(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildUDiv(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildUDiv(B(cx), LHS, RHS, buf) });
}
fn SDiv(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildSDiv(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildSDiv(B(cx), LHS, RHS, buf) });
}
fn ExactSDiv(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildExactSDiv(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildExactSDiv(B(cx), LHS, RHS, buf) });
}
fn FDiv(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildFDiv(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildFDiv(B(cx), LHS, RHS, buf) });
}
fn URem(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildURem(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildURem(B(cx), LHS, RHS, buf) });
}
fn SRem(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildSRem(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildSRem(B(cx), LHS, RHS, buf) });
}
fn FRem(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildFRem(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildFRem(B(cx), LHS, RHS, buf) });
}
fn Shl(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildShl(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildShl(B(cx), LHS, RHS, buf) });
}
fn LShr(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildLShr(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildLShr(B(cx), LHS, RHS, buf) });
}
fn AShr(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildAShr(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildAShr(B(cx), LHS, RHS, buf) });
}
fn And(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildAnd(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildAnd(B(cx), LHS, RHS, buf) });
}
fn Or(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildOr(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildOr(B(cx), LHS, RHS, buf) });
}
fn Xor(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildXor(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildXor(B(cx), LHS, RHS, buf) });
}
-fn BinOp(cx: &@block_ctxt, Op: Opcode, LHS: ValueRef,
- RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildBinOp(B(cx), Op, LHS, RHS, buf)
- });
+fn BinOp(cx: &@block_ctxt, Op: Opcode, LHS: ValueRef, RHS: ValueRef) ->
+ ValueRef {
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildBinOp(B(cx), Op, LHS, RHS, buf) });
}
fn Neg(cx: &@block_ctxt, V: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildNeg(B(cx), V, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildNeg(B(cx), V, buf) });
}
fn NSWNeg(cx: &@block_ctxt, V: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildNSWNeg(B(cx), V, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildNSWNeg(B(cx), V, buf) });
}
fn NUWNeg(cx: &@block_ctxt, V: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildNUWNeg(B(cx), V, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildNUWNeg(B(cx), V, buf) });
}
fn FNeg(cx: &@block_ctxt, V: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildFNeg(B(cx), V, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildFNeg(B(cx), V, buf) });
}
fn Not(cx: &@block_ctxt, V: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildNot(B(cx), V, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildNot(B(cx), V, buf) });
}
/* Memory */
fn Malloc(cx: &@block_ctxt, Ty: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildMalloc(B(cx), Ty, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildMalloc(B(cx), Ty, buf) });
}
fn ArrayMalloc(cx: &@block_ctxt, Ty: TypeRef, Val: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildArrayMalloc(B(cx), Ty, Val, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildArrayMalloc(B(cx), Ty, Val, buf) });
}
fn Alloca(cx: &@block_ctxt, Ty: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildAlloca(B(cx), Ty, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildAlloca(B(cx), Ty, buf) });
}
fn ArrayAlloca(cx: &@block_ctxt, Ty: TypeRef, Val: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildArrayAlloca(B(cx), Ty, Val, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildArrayAlloca(B(cx), Ty, Val, buf) });
}
fn Free(cx: &@block_ctxt, PointerVal: ValueRef) -> ValueRef {
}
fn Load(cx: &@block_ctxt, PointerVal: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildLoad(B(cx), PointerVal, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildLoad(B(cx), PointerVal, buf) });
}
fn Store(cx: &@block_ctxt, Val: ValueRef, Ptr: ValueRef) -> ValueRef {
ret llvm::LLVMBuildStore(B(cx), Val, Ptr);
}
-fn GEP(cx: &@block_ctxt, Pointer: ValueRef,
- Indices: &[ValueRef]) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildGEP(B(cx), Pointer, vec::to_ptr(Indices),
- vec::len(Indices), buf)
- });
+fn GEP(cx: &@block_ctxt, Pointer: ValueRef, Indices: &[ValueRef]) ->
+ ValueRef {
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildGEP(B(cx), Pointer,
+ vec::to_ptr(Indices),
+ vec::len(Indices), buf)
+ });
}
-fn InBoundsGEP(cx: &@block_ctxt, Pointer: ValueRef,
- Indices: &[ValueRef]) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildInBoundsGEP(B(cx), Pointer, vec::to_ptr(Indices),
- vec::len(Indices), buf)
- });
+fn InBoundsGEP(cx: &@block_ctxt, Pointer: ValueRef, Indices: &[ValueRef]) ->
+ ValueRef {
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildInBoundsGEP(B(cx), Pointer,
+ vec::to_ptr(Indices),
+ vec::len(Indices), buf)
+ });
}
fn StructGEP(cx: &@block_ctxt, Pointer: ValueRef, Idx: uint) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildStructGEP(B(cx), Pointer, Idx, buf)
- });
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildStructGEP(B(cx), Pointer, Idx, buf)
+ });
}
fn GlobalString(cx: &@block_ctxt, _Str: sbuf) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildGlobalString(B(cx), _Str, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildGlobalString(B(cx), _Str, buf) });
}
fn GlobalStringPtr(cx: &@block_ctxt, _Str: sbuf) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildGlobalStringPtr(B(cx), _Str, buf)
- });
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildGlobalStringPtr(B(cx), _Str, buf)
+ });
}
/* Casts */
fn Trunc(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildTrunc(B(cx), Val, DestTy, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildTrunc(B(cx), Val, DestTy, buf) });
}
fn ZExt(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildZExt(B(cx), Val, DestTy, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildZExt(B(cx), Val, DestTy, buf) });
}
fn SExt(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildSExt(B(cx), Val, DestTy, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildSExt(B(cx), Val, DestTy, buf) });
}
fn FPToUI(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildFPToUI(B(cx), Val, DestTy, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildFPToUI(B(cx), Val, DestTy, buf) });
}
fn FPToSI(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildFPToSI(B(cx), Val, DestTy, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildFPToSI(B(cx), Val, DestTy, buf) });
}
fn UIToFP(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildUIToFP(B(cx), Val, DestTy, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildUIToFP(B(cx), Val, DestTy, buf) });
}
fn SIToFP(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildSIToFP(B(cx), Val, DestTy, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildSIToFP(B(cx), Val, DestTy, buf) });
}
fn FPTrunc(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildFPTrunc(B(cx), Val, DestTy, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildFPTrunc(B(cx), Val, DestTy, buf) });
}
fn FPExt(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildFPExt(B(cx), Val, DestTy, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildFPExt(B(cx), Val, DestTy, buf) });
}
-fn PtrToInt(cx: &@block_ctxt, Val: ValueRef,
- DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildPtrToInt(B(cx), Val, DestTy, buf)
- });
+fn PtrToInt(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildPtrToInt(B(cx), Val, DestTy, buf)
+ });
}
-fn IntToPtr(cx: &@block_ctxt, Val: ValueRef,
- DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildIntToPtr(B(cx), Val, DestTy, buf)
- });
+fn IntToPtr(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildIntToPtr(B(cx), Val, DestTy, buf)
+ });
}
fn BitCast(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildBitCast(B(cx), Val, DestTy, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildBitCast(B(cx), Val, DestTy, buf) });
}
-fn ZExtOrBitCast(cx: &@block_ctxt, Val: ValueRef,
- DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildZExtOrBitCast(B(cx), Val, DestTy, buf)
- });
+fn ZExtOrBitCast(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) ->
+ ValueRef {
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildZExtOrBitCast(B(cx), Val, DestTy, buf)
+ });
}
-fn SExtOrBitCast(cx: &@block_ctxt, Val: ValueRef,
- DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildSExtOrBitCast(B(cx), Val, DestTy, buf)
- });
+fn SExtOrBitCast(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) ->
+ ValueRef {
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildSExtOrBitCast(B(cx), Val, DestTy, buf)
+ });
}
-fn TruncOrBitCast(cx: &@block_ctxt, Val: ValueRef,
- DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildTruncOrBitCast(B(cx), Val, DestTy, buf)
- });
+fn TruncOrBitCast(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) ->
+ ValueRef {
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildTruncOrBitCast(B(cx), Val, DestTy, buf)
+ });
}
-fn Cast(cx: &@block_ctxt, Op: Opcode, Val: ValueRef,
- DestTy: TypeRef, _Name: sbuf) ->
- ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildCast(B(cx), Op, Val, DestTy, buf)
- });
+fn Cast(cx: &@block_ctxt, Op: Opcode, Val: ValueRef, DestTy: TypeRef,
+ _Name: sbuf) -> ValueRef {
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildCast(B(cx), Op, Val, DestTy, buf)
+ });
}
fn PointerCast(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildPointerCast(B(cx), Val, DestTy, buf)
- });
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildPointerCast(B(cx), Val, DestTy, buf)
+ });
}
fn IntCast(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildIntCast(B(cx), Val, DestTy, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildIntCast(B(cx), Val, DestTy, buf) });
}
fn FPCast(cx: &@block_ctxt, Val: ValueRef, DestTy: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildFPCast(B(cx), Val, DestTy, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildFPCast(B(cx), Val, DestTy, buf) });
}
/* Comparisons */
-fn ICmp(cx: &@block_ctxt, Op: uint, LHS: ValueRef,
- RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildICmp(B(cx), Op, LHS, RHS, buf)
- });
+fn ICmp(cx: &@block_ctxt, Op: uint, LHS: ValueRef, RHS: ValueRef) ->
+ ValueRef {
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildICmp(B(cx), Op, LHS, RHS, buf) });
}
-fn FCmp(cx: &@block_ctxt, Op: uint, LHS: ValueRef,
- RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildFCmp(B(cx), Op, LHS, RHS, buf)
- });
+fn FCmp(cx: &@block_ctxt, Op: uint, LHS: ValueRef, RHS: ValueRef) ->
+ ValueRef {
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildFCmp(B(cx), Op, LHS, RHS, buf) });
}
/* Miscellaneous instructions */
fn Phi(cx: &@block_ctxt, Ty: TypeRef, vals: &[ValueRef],
bbs: &[BasicBlockRef]) -> ValueRef {
- let phi = str::as_buf(~"", { |buf|
- llvm::LLVMBuildPhi(B(cx), Ty, buf)
- });
+ let phi = str::as_buf("", {|buf| llvm::LLVMBuildPhi(B(cx), Ty, buf) });
assert (vec::len::<ValueRef>(vals) == vec::len::<BasicBlockRef>(bbs));
llvm::LLVMAddIncoming(phi, vec::to_ptr(vals), vec::to_ptr(bbs),
vec::len(vals));
}
fn Call(cx: &@block_ctxt, Fn: ValueRef, Args: &[ValueRef]) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildCall(B(cx), Fn, vec::to_ptr(Args),
- vec::len(Args), buf)
- });
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildCall(B(cx), Fn, vec::to_ptr(Args),
+ vec::len(Args), buf)
+ });
}
fn FastCall(cx: &@block_ctxt, Fn: ValueRef, Args: &[ValueRef]) -> ValueRef {
- let v = str::as_buf(~"", { |buf|
- llvm::LLVMBuildCall(B(cx), Fn, vec::to_ptr(Args), vec::len(Args), buf)
- });
+ let v =
+ str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildCall(B(cx), Fn, vec::to_ptr(Args),
+ vec::len(Args), buf)
+ });
llvm::LLVMSetInstructionCallConv(v, lib::llvm::LLVMFastCallConv);
ret v;
}
-fn CallWithConv(cx: &@block_ctxt, Fn: ValueRef, Args: &[ValueRef],
- Conv: uint) -> ValueRef {
- let v = str::as_buf(~"", { |buf|
- llvm::LLVMBuildCall(B(cx), Fn, vec::to_ptr(Args), vec::len(Args), buf)
- });
+fn CallWithConv(cx: &@block_ctxt, Fn: ValueRef, Args: &[ValueRef], Conv: uint)
+ -> ValueRef {
+ let v =
+ str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildCall(B(cx), Fn, vec::to_ptr(Args),
+ vec::len(Args), buf)
+ });
llvm::LLVMSetInstructionCallConv(v, Conv);
ret v;
}
-fn Select(cx: &@block_ctxt, If: ValueRef, Then: ValueRef,
- Else: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildSelect(B(cx), If, Then, Else, buf)
- });
+fn Select(cx: &@block_ctxt, If: ValueRef, Then: ValueRef, Else: ValueRef) ->
+ ValueRef {
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildSelect(B(cx), If, Then, Else, buf)
+ });
}
fn VAArg(cx: &@block_ctxt, list: ValueRef, Ty: TypeRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildVAArg(B(cx), list, Ty, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildVAArg(B(cx), list, Ty, buf) });
}
-fn ExtractElement(cx: &@block_ctxt, VecVal: ValueRef,
- Index: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildExtractElement(B(cx), VecVal, Index, buf)
- });
+fn ExtractElement(cx: &@block_ctxt, VecVal: ValueRef, Index: ValueRef) ->
+ ValueRef {
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildExtractElement(B(cx), VecVal, Index,
+ buf)
+ });
}
fn InsertElement(cx: &@block_ctxt, VecVal: ValueRef, EltVal: ValueRef,
- Index: ValueRef) ->
- ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildInsertElement(B(cx), VecVal, EltVal, Index, buf)
- });
+ Index: ValueRef) -> ValueRef {
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildInsertElement(B(cx), VecVal, EltVal,
+ Index, buf)
+ });
}
-fn ShuffleVector(cx: &@block_ctxt, V1: ValueRef, V2: ValueRef,
- Mask: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildShuffleVector(B(cx), V1, V2, Mask, buf)
- });
+fn ShuffleVector(cx: &@block_ctxt, V1: ValueRef, V2: ValueRef, Mask: ValueRef)
+ -> ValueRef {
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildShuffleVector(B(cx), V1, V2, Mask, buf)
+ });
}
fn ExtractValue(cx: &@block_ctxt, AggVal: ValueRef, Index: uint) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildExtractValue(B(cx), AggVal, Index, buf)
- });
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildExtractValue(B(cx), AggVal, Index, buf)
+ });
}
-fn InsertValue(cx: &@block_ctxt, AggVal: ValueRef,
- EltVal: ValueRef, Index: uint) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildInsertValue(B(cx), AggVal, EltVal, Index, buf)
- });
+fn InsertValue(cx: &@block_ctxt, AggVal: ValueRef, EltVal: ValueRef,
+ Index: uint) -> ValueRef {
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildInsertValue(B(cx), AggVal, EltVal,
+ Index, buf)
+ });
}
fn IsNull(cx: &@block_ctxt, Val: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildIsNull(B(cx), Val, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildIsNull(B(cx), Val, buf) });
}
fn IsNotNull(cx: &@block_ctxt, Val: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildIsNotNull(B(cx), Val, buf)
- });
+ ret str::as_buf("", {|buf| llvm::LLVMBuildIsNotNull(B(cx), Val, buf) });
}
fn PtrDiff(cx: &@block_ctxt, LHS: ValueRef, RHS: ValueRef) -> ValueRef {
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildPtrDiff(B(cx), LHS, RHS, buf)
- });
+ ret str::as_buf("",
+ {|buf| llvm::LLVMBuildPtrDiff(B(cx), LHS, RHS, buf) });
}
fn Trap(cx: &@block_ctxt) -> ValueRef {
let BB: BasicBlockRef = llvm::LLVMGetInsertBlock(b);
let FN: ValueRef = llvm::LLVMGetBasicBlockParent(BB);
let M: ModuleRef = llvm::LLVMGetGlobalParent(FN);
- let T: ValueRef = str::as_buf(~"llvm.trap", { |buf|
- llvm::LLVMGetNamedFunction(M, buf)
- });
+ let T: ValueRef =
+ str::as_buf("llvm.trap", {|buf| llvm::LLVMGetNamedFunction(M, buf) });
assert (T as int != 0);
let Args: [ValueRef] = [];
- ret str::as_buf(~"", { |buf|
- llvm::LLVMBuildCall(b, T, vec::to_ptr(Args), vec::len(Args), buf)
- });
+ ret str::as_buf("",
+ {|buf|
+ llvm::LLVMBuildCall(b, T, vec::to_ptr(Args),
+ vec::len(Args), buf)
+ });
}
//
import trans::drop_ty;
obj namegen(mutable i: int) {
- fn next(prefix: &istr) -> istr {
- i += 1; ret prefix + int::str(i);
- }
+ fn next(prefix: &str) -> str { i += 1; ret prefix + int::str(i); }
}
type derived_tydesc_info = {lltydesc: ValueRef, escapes: bool};
mutable n_glues_created: uint,
mutable n_null_glues: uint,
mutable n_real_glues: uint,
- fn_times: @mutable [{ident: istr, time: int}]};
+ fn_times: @mutable [{ident: str, time: int}]};
-resource BuilderRef_res(B: llvm::BuilderRef) {
- llvm::LLVMDisposeBuilder(B);
-}
+resource BuilderRef_res(B: llvm::BuilderRef) { llvm::LLVMDisposeBuilder(B); }
// Crate context. Every crate we compile has one of these.
type crate_ctxt =
llmod: ModuleRef,
td: target_data,
tn: type_names,
- externs: hashmap<istr, ValueRef>,
- intrinsics: hashmap<istr, ValueRef>,
+ 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, istr>,
+ 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, istr>,
+ 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<istr, ValueRef>,
+ module_data: hashmap<str, ValueRef>,
lltypes: hashmap<ty::t, TypeRef>,
glues: @glue_fns,
names: namegen,
sha: std::sha1::sha1,
- type_sha1s: hashmap<ty::t, istr>,
- type_short_names: hashmap<ty::t, istr>,
+ type_sha1s: hashmap<ty::t, str>,
+ type_short_names: hashmap<ty::t, str>,
tcx: ty::ctxt,
mut_map: mut::mut_map,
stats: stats,
gc_cx: gc::ctxt};
type local_ctxt =
- {path: [istr],
- module_path: [istr],
+ {path: [str],
+ module_path: [str],
obj_typarams: [ast::ty_param],
obj_fields: [ast::obj_field],
ccx: @crate_ctxt};
find_scope_cx(cx).cleanups += [clean(bind drop_ty(_, val, ty))];
}
fn add_clean_temp(cx: &@block_ctxt, val: ValueRef, ty: ty::t) {
- fn spill_and_drop(cx: &@block_ctxt, val: ValueRef, ty: ty::t)
- -> @block_ctxt {
+ fn spill_and_drop(cx: &@block_ctxt, val: ValueRef, ty: ty::t) ->
+ @block_ctxt {
let bcx = cx;
let r = trans::spill_if_immediate(bcx, val, ty);
- let spilled = r.val; bcx = r.bcx;
+ let spilled = r.val;
+ bcx = r.bcx;
ret drop_ty(bcx, spilled, ty);
}
find_scope_cx(cx).cleanups +=
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!"); }
+ _ { ccx.tcx.sess.bug("get_res_dtor: can't find resource dtor!"); }
}
}
[{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),
+ csearch::get_symbol(ccx.sess.get_cstore(),
+ did),
T_fn_pair(*ccx, f_t));
}
// 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.
+ // The block pointing to this one in the function's digraph.
+ // The 'kind' of basic block this is.
+ // 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.
+ // The source span where this block comes from, for error
+ // reporting. FIXME this is not currently reliable
+ // The function context for the function to which this block is
+ // attached.
{llbb: BasicBlockRef,
mutable terminated: bool,
- // 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. FIXME this is not currently reliable
sp: span,
- // The function context for the function to which this block is
- // attached.
fcx: @fn_ctxt};
-fn is_terminated(cx: &@block_ctxt) -> bool {
- ret cx.terminated;
-}
+fn is_terminated(cx: &@block_ctxt) -> bool { ret cx.terminated; }
// FIXME: we should be able to use option::t<@block_parent> here but
// the infinite-tag check in rustboot gets upset.
type result = {bcx: @block_ctxt, val: ValueRef};
type result_t = {bcx: @block_ctxt, val: ValueRef, ty: ty::t};
-fn extend_path(cx: @local_ctxt, name: &istr) -> @local_ctxt {
+fn extend_path(cx: @local_ctxt, name: &str) -> @local_ctxt {
ret @{path: cx.path + [name] with *cx};
}
ret {bcx: bcx, val: val};
}
-fn ty_str(tn: type_names, t: TypeRef) -> istr {
+fn ty_str(tn: type_names, t: TypeRef) -> str {
ret lib::llvm::type_to_str(tn, t);
}
fn val_ty(v: ValueRef) -> TypeRef { ret llvm::LLVMTypeOf(v); }
-fn val_str(tn: type_names, v: ValueRef) -> istr {
- ret ty_str(tn, val_ty(v));
-}
+fn val_str(tn: type_names, v: ValueRef) -> str { ret ty_str(tn, val_ty(v)); }
// Returns the nth element of the given LLVM structure type.
fn struct_elt(llstructty: TypeRef, n: uint) -> TypeRef {
alt cx.parent {
parent_some(b) { ret find_scope_cx(b); }
parent_none. {
- cx.fcx.lcx.ccx.sess.bug(~"trans::find_scope_cx() " +
- ~"called on parentless block_ctxt");
+ cx.fcx.lcx.ccx.sess.bug("trans::find_scope_cx() " +
+ "called on parentless block_ctxt");
}
}
}
fn T_ptr(t: TypeRef) -> TypeRef { ret llvm::LLVMPointerType(t, 0u); }
fn T_struct(elts: &[TypeRef]) -> TypeRef {
- ret llvm::LLVMStructType(to_ptr(elts),
- std::vec::len(elts), False);
+ ret llvm::LLVMStructType(to_ptr(elts), std::vec::len(elts), False);
}
-fn T_named_struct(name: &istr) -> TypeRef {
+fn T_named_struct(name: &str) -> TypeRef {
let c = llvm::LLVMGetGlobalContext();
- ret str::as_buf(name, { |buf|
- llvm::LLVMStructCreateNamed(c, buf)
- });
+ ret str::as_buf(name, {|buf| llvm::LLVMStructCreateNamed(c, buf) });
}
fn set_struct_body(t: TypeRef, elts: &[TypeRef]) {
- llvm::LLVMStructSetBody(t, to_ptr(elts),
- std::vec::len(elts), False);
+ llvm::LLVMStructSetBody(t, to_ptr(elts), std::vec::len(elts), False);
}
fn T_empty_struct() -> TypeRef { ret T_struct([]); }
// existing objects, use ccx.rust_object_type. Calling
// T_rust_object() again will return a different one.
fn T_rust_object() -> TypeRef {
- let t = T_named_struct(~"rust_object");
+ let t = T_named_struct("rust_object");
let e = T_ptr(T_empty_struct());
set_struct_body(t, [e, e]);
ret t;
}
fn T_task() -> TypeRef {
- let t = T_named_struct(~"task");
+ let t = T_named_struct("task");
- // Refcount
- // Delegate pointer
- // Stack segment pointer
- // Runtime SP
- // Rust SP
- // GC chain
+ // Refcount
+ // Delegate pointer
+ // Stack segment pointer
+ // Runtime SP
+ // Rust SP
+ // GC chain
- // Domain pointer
- // Crate cache pointer
+ // Domain pointer
+ // Crate cache pointer
let elems =
[T_int(), T_int(), T_int(), T_int(), T_int(), T_int(), T_int(),
}
fn T_glue_fn(cx: &crate_ctxt) -> TypeRef {
- let s = ~"glue_fn";
+ let s = "glue_fn";
if cx.tn.name_has_type(s) { ret cx.tn.get_type(s); }
let t = T_tydesc_field(cx, abi::tydesc_field_drop_glue);
cx.tn.associate(s, t);
}
fn T_cmp_glue_fn(cx: &crate_ctxt) -> TypeRef {
- let s = ~"cmp_glue_fn";
+ let s = "cmp_glue_fn";
if cx.tn.name_has_type(s) { ret cx.tn.get_type(s); }
let t = T_tydesc_field(cx, abi::tydesc_field_cmp_glue);
cx.tn.associate(s, t);
}
fn T_tydesc(taskptr_type: TypeRef) -> TypeRef {
- let tydesc = T_named_struct(~"tydesc");
+ let tydesc = T_named_struct("tydesc");
let tydescpp = T_ptr(T_ptr(tydesc));
let pvoid = T_ptr(T_i8());
let glue_fn_ty =
}
// Note that the size of this one is in bytes.
-fn T_opaque_vec() -> TypeRef {
- ret T_vec(T_i8());
-}
+fn T_opaque_vec() -> TypeRef { ret T_vec(T_i8()); }
fn T_box(t: TypeRef) -> TypeRef { ret T_struct([T_int(), t]); }
// This type must never be used directly; it must always be cast away.
fn T_typaram(tn: &type_names) -> TypeRef {
- let s = ~"typaram";
+ let s = "typaram";
if tn.name_has_type(s) { ret tn.get_type(s); }
let t = T_i8();
tn.associate(s, t);
}
fn T_opaque_closure_ptr(cx: &crate_ctxt) -> TypeRef {
- let s = ~"*closure";
+ let s = "*closure";
if cx.tn.name_has_type(s) { ret cx.tn.get_type(s); }
let t = T_closure_ptr(cx, T_nil(), 0u);
cx.tn.associate(s, t);
}
fn T_tag(tn: &type_names, size: uint) -> TypeRef {
- let s = ~"tag_" + uint::to_str(size, 10u);
+ 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)]);
tn.associate(s, t);
}
fn T_opaque_tag(tn: &type_names) -> TypeRef {
- let s = ~"opaque_tag";
+ let s = "opaque_tag";
if tn.name_has_type(s) { ret tn.get_type(s); }
let t = T_struct([T_int(), T_i8()]);
tn.associate(s, t);
ret llvm::LLVMRustConstSmallInt(t, u, sign_extend);
}
-fn C_float(s: &istr) -> ValueRef {
- ret str::as_buf(s, { |buf|
- llvm::LLVMConstRealOfString(T_float(), buf)
- });
+fn C_float(s: &str) -> ValueRef {
+ ret str::as_buf(s, {|buf| llvm::LLVMConstRealOfString(T_float(), buf) });
}
-fn C_floating(s: &istr, t: TypeRef) -> ValueRef {
- ret str::as_buf(s, { |buf|
- llvm::LLVMConstRealOfString(t, buf)
- });
+fn C_floating(s: &str, t: TypeRef) -> ValueRef {
+ ret str::as_buf(s, {|buf| llvm::LLVMConstRealOfString(t, buf) });
}
fn C_nil() -> ValueRef {
// This is a 'c-like' raw string, which differs from
// our boxed-and-length-annotated strings.
-fn C_cstr(cx: &@crate_ctxt, s: &istr) -> ValueRef {
- let sc = str::as_buf(s, { |buf|
- llvm::LLVMConstString(buf, str::byte_len(s), False)
- });
- let g = str::as_buf(cx.names.next(~"str"), { |buf|
- llvm::LLVMAddGlobal(cx.llmod, val_ty(sc), buf)
- });
+fn C_cstr(cx: &@crate_ctxt, s: &str) -> ValueRef {
+ let sc =
+ str::as_buf(s,
+ {|buf|
+ llvm::LLVMConstString(buf, str::byte_len(s), False)
+ });
+ let g =
+ str::as_buf(cx.names.next("str"),
+ {|buf| llvm::LLVMAddGlobal(cx.llmod, val_ty(sc), buf) });
llvm::LLVMSetInitializer(g, sc);
llvm::LLVMSetGlobalConstant(g, True);
llvm::LLVMSetLinkage(g, lib::llvm::LLVMInternalLinkage as llvm::Linkage);
}
// Returns a Plain Old LLVM String:
-fn C_postr(s: &istr) -> ValueRef {
- ret str::as_buf(s, { |buf|
- llvm::LLVMConstString(buf, str::byte_len(s), False)
- });
+fn C_postr(s: &str) -> ValueRef {
+ ret str::as_buf(s,
+ {|buf|
+ llvm::LLVMConstString(buf, str::byte_len(s), False)
+ });
}
fn C_zero_byte_arr(size: uint) -> ValueRef {
fn C_shape(ccx: &@crate_ctxt, bytes: &[u8]) -> ValueRef {
let llshape = C_bytes(bytes);
- let llglobal = str::as_buf(ccx.names.next(~"shape"), { |buf|
- llvm::LLVMAddGlobal(ccx.llmod, val_ty(llshape), buf)
- });
+ let llglobal =
+ str::as_buf(ccx.names.next("shape"),
+ {|buf|
+ llvm::LLVMAddGlobal(ccx.llmod, val_ty(llshape), buf)
+ });
llvm::LLVMSetInitializer(llglobal, llshape);
llvm::LLVMSetGlobalConstant(llglobal, True);
llvm::LLVMSetLinkage(llglobal,
}
-pure fn valid_variant_index(ix:uint, cx:@block_ctxt, tag_id: &ast::def_id,
+pure fn valid_variant_index(ix: uint, cx: @block_ctxt, tag_id: &ast::def_id,
variant_id: &ast::def_id) -> bool {
+
// Handwaving: it's ok to pretend this code is referentially
// transparent, because the relevant parts of the type context don't
// change. (We're not adding new variants during trans.)
- unchecked {
- let variant = ty::tag_variant_with_id(bcx_tcx(cx), tag_id, variant_id);
- ix < vec::len(variant.args)
+ unchecked{
+ let variant =
+ ty::tag_variant_with_id(bcx_tcx(cx), tag_id, variant_id);
+ ix < vec::len(variant.args)
}
}
let llctor_decl;
alt ccx.item_ids.find(ctor_id) {
some(x) { llctor_decl = x; }
- _ { cx.ccx.sess.span_fatal(sp, ~"unbound llctor_decl in trans_obj"); }
+ _ { cx.ccx.sess.span_fatal(sp, "unbound llctor_decl in trans_obj"); }
}
// Much like trans_fn, we must create an LLVM function, but since we're
// Grab onto the first and second elements of the pair.
// abi::obj_field_vtbl and abi::obj_field_box simply specify words 0 and 1
// of 'pair'.
- let pair_vtbl =
- GEP(bcx, pair, [C_int(0), C_int(abi::obj_field_vtbl)]);
+ let pair_vtbl = GEP(bcx, pair, [C_int(0), C_int(abi::obj_field_vtbl)]);
let pair_box = GEP(bcx, pair, [C_int(0), C_int(abi::obj_field_box)]);
// Make a vtable for this object: a static array of pointers to functions.
bcx = body_tydesc.bcx;
let ti = none::<@tydesc_info>;
- let r = GEP_tup_like(bcx, body_ty, body,
- [0, abi::obj_body_elt_typarams]);
+ let r =
+ GEP_tup_like(bcx, body_ty, body, [0, abi::obj_body_elt_typarams]);
bcx = r.bcx;
let body_typarams = r.val;
}
none. {
bcx_ccx(bcx).sess.span_fatal(f.ty.span,
- ~"internal error in trans_obj");
+ "internal error in trans_obj");
}
}
}
add_clean_temp(bcx, pair, t);
// Grab onto the first and second elements of the pair.
- let pair_vtbl =
- GEP(bcx, pair, [C_int(0), C_int(abi::obj_field_vtbl)]);
+ let pair_vtbl = GEP(bcx, pair, [C_int(0), C_int(abi::obj_field_vtbl)]);
let pair_box = GEP(bcx, pair, [C_int(0), C_int(abi::obj_field_box)]);
vtbl = PointerCast(bcx, vtbl, T_ptr(T_empty_struct()));
GEP_tup_like(bcx, body_ty, body,
[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,
- inner_obj_ty);
+ bcx =
+ copy_val(bcx, INIT, body_inner_obj.val, inner_obj_val.val,
+ inner_obj_ty);
}
}
ret some(fwding_mthd(fm));
}
normal_mthd(_) {
- cx.ccx.sess.bug(~"create_vtbl(): shouldn't be any \
+ cx.ccx.sess.bug("create_vtbl(): shouldn't be any \
normal_mthds in meths here");
}
}
}
}
_ {
- cx.ccx.sess.bug(~"create_vtbl(): trying to extend a \
+ cx.ccx.sess.bug("create_vtbl(): trying to extend a \
non-object");
}
}
}
}
- ret finish_vtbl(cx, llmethods, ~"vtbl");
+ ret finish_vtbl(cx, llmethods, "vtbl");
}
// create_backwarding_vtbl: Create a vtable for the inner object of an
}
_ {
// Shouldn't happen.
- cx.ccx.sess.bug(~"create_backwarding_vtbl(): trying to extend a \
+ cx.ccx.sess.bug("create_backwarding_vtbl(): trying to extend a \
non-object");
}
}
// being forwarded to.
llmethods += [process_bkwding_mthd(cx, sp, @m, [], outer_obj_ty, [])];
}
- ret finish_vtbl(cx, llmethods, ~"backwarding_vtbl");
+ 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: &istr) ->
+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 gvar = str::as_buf(vtbl_name, { |buf|
- llvm::LLVMAddGlobal(cx.ccx.llmod, val_ty(vtbl), buf)
- });
+ let vtbl_name = mangle_internal_name_by_path(cx.ccx, cx.path + [name]);
+ let gvar =
+ str::as_buf(vtbl_name,
+ {|buf|
+ llvm::LLVMAddGlobal(cx.ccx.llmod, val_ty(vtbl), buf)
+ });
llvm::LLVMSetInitializer(gvar, vtbl);
llvm::LLVMSetGlobalConstant(gvar, True);
llvm::LLVMSetLinkage(gvar,
// 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: istr = ~"backwarding_fn";
- let s: istr =
- mangle_internal_name_by_path_and_seq(
- mcx.ccx, mcx.path, fn_name);
+ let fn_name: str = "backwarding_fn";
+ 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 =
type_of_fn_full(cx.ccx, sp, m.proto, true, m.inputs, m.output,
std::vec::len::<ast::ty_param>(ty_params));
let llbackwarding_fn: ValueRef =
- decl_internal_fastcall_fn(
- cx.ccx.llmod, s, llbackwarding_fn_ty);
+ decl_internal_fastcall_fn(cx.ccx.llmod, s, llbackwarding_fn_ty);
// Create a new function context and block context for the backwarding
// function, holding onto a pointer to the first block.
// Cast to self-stack's type.
let llenv =
PointerCast(bcx, fcx.llenv,
- T_ptr(T_struct([cx.ccx.rust_object_type,
- T_ptr(cx.ccx.rust_object_type)])));
+ T_ptr(T_struct([cx.ccx.rust_object_type,
+ T_ptr(cx.ccx.rust_object_type)])));
let llself_obj_ptr = GEP(bcx, llenv, [C_int(0), C_int(1)]);
llself_obj_ptr = Load(bcx, llself_obj_ptr);
}
_ {
// Shouldn't happen.
- cx.ccx.sess.bug(~"process_bkwding_mthd(): non-object type passed \
+ cx.ccx.sess.bug("process_bkwding_mthd(): non-object type passed \
as outer_obj_ty");
}
}
// 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: istr = ~"forwarding_fn";
- let s: istr =
- mangle_internal_name_by_path_and_seq(
- mcx.ccx, mcx.path, fn_name);
+ let fn_name: str = "forwarding_fn";
+ 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 =
type_of_fn_full(cx.ccx, sp, m.proto, true, m.inputs, m.output,
std::vec::len::<ast::ty_param>(ty_params));
let llforwarding_fn: ValueRef =
- decl_internal_fastcall_fn(
- cx.ccx.llmod, s, llforwarding_fn_ty);
+ decl_internal_fastcall_fn(cx.ccx.llmod, s, llforwarding_fn_ty);
// Create a new function context and block context for the forwarding
// function, holding onto a pointer to the first block.
// Now, reach into the box and grab the body.
let llself_obj_body =
- GEP(bcx, llself_obj_box,
- [C_int(0), C_int(abi::box_rc_field_body)]);
+ GEP(bcx, llself_obj_box, [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.
// method's entry out of the vtable so that the forwarding function can
// call it.
let llinner_obj_vtbl =
- GEP(bcx, llinner_obj.val,
- [C_int(0), C_int(abi::obj_field_vtbl)]);
+ GEP(bcx, llinner_obj.val, [C_int(0), C_int(abi::obj_field_vtbl)]);
llinner_obj_vtbl = Load(bcx, llinner_obj_vtbl);
let llinner_obj_body =
}
_ {
// Shouldn't happen.
- cx.ccx.sess.bug(~"process_fwding_mthd(): non-object type passed \
+ cx.ccx.sess.bug("process_fwding_mthd(): non-object type passed \
as target_obj_ty");
}
}
ty::ty_fn_proto(bcx_tcx(bcx), orig_mthd_ty), true,
m.inputs, m.output,
std::vec::len::<ast::ty_param>(ty_params));
- llorig_mthd =
- PointerCast(bcx, llorig_mthd, T_ptr(T_ptr(llorig_mthd_ty)));
+ llorig_mthd = PointerCast(bcx, llorig_mthd, T_ptr(T_ptr(llorig_mthd_ty)));
llorig_mthd = Load(bcx, llorig_mthd);
// Set up the self-stack.
llinner_obj_body);
// Cast self_stack back to pointer-to-object-type to make LLVM happy.
- self_stack =
- PointerCast(bcx, self_stack, T_ptr(cx.ccx.rust_object_type));
+ self_stack = PointerCast(bcx, 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 mcx: @local_ctxt =
- @{path: cx.path + [~"method", m.node.ident] with *cx};
- let s: istr = mangle_internal_name_by_path(mcx.ccx,
- mcx.path);
- let llfn: ValueRef = decl_internal_fastcall_fn(
- cx.ccx.llmod, s, llfnty);
+ @{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);
// Every method on an object gets its node_id inserted into the crate-wide
// item_ids map, together with the ValueRef that points to where that
import syntax::ast;
import lib::llvm::llvm::{ValueRef, TypeRef};
import back::abi;
-import trans::{call_memmove, trans_shared_malloc, llsize_of,
- type_of_or_i8, incr_ptr, INIT, copy_val, load_if_immediate,
- alloca, size_of, llderivedtydescs_block_ctxt,
- lazily_emit_tydesc_glue, get_tydesc, load_inbounds,
- move_val_if_temp, trans_lval, node_id_type,
- new_sub_block_ctxt, tps_normal, do_spill_noroot};
+import trans::{call_memmove, trans_shared_malloc, llsize_of, type_of_or_i8,
+ incr_ptr, INIT, copy_val, load_if_immediate, alloca, size_of,
+ llderivedtydescs_block_ctxt, lazily_emit_tydesc_glue,
+ get_tydesc, load_inbounds, move_val_if_temp, trans_lval,
+ node_id_type, new_sub_block_ctxt, tps_normal, do_spill_noroot};
import trans_build::*;
import trans_common::*;
fn get_alloc(bcx: &@block_ctxt, vptr: ValueRef) -> ValueRef {
Load(bcx, InBoundsGEP(bcx, vptr, [C_int(0), C_uint(abi::vec_elt_alloc)]))
}
-fn get_dataptr(bcx: &@block_ctxt, vpt: ValueRef,
- unit_ty: TypeRef) -> ValueRef {
+fn get_dataptr(bcx: &@block_ctxt, vpt: ValueRef, unit_ty: TypeRef) ->
+ ValueRef {
let ptr = InBoundsGEP(bcx, vpt, [C_int(0), C_uint(abi::vec_elt_elems)]);
PointerCast(bcx, ptr, T_ptr(unit_ty))
}
-fn pointer_add(bcx: &@block_ctxt, ptr: ValueRef, bytes: ValueRef)
- -> ValueRef {
+fn pointer_add(bcx: &@block_ctxt, ptr: ValueRef, bytes: ValueRef) ->
+ ValueRef {
let old_ty = val_ty(ptr);
let bptr = PointerCast(bcx, ptr, T_ptr(T_i8()));
ret PointerCast(bcx, InBoundsGEP(bcx, bptr, [bytes]), old_ty);
fn alloc_raw(bcx: &@block_ctxt, fill: ValueRef, alloc: ValueRef) -> result {
let llvecty = T_opaque_vec();
let vecsize = Add(bcx, alloc, llsize_of(llvecty));
- let {bcx, val: vecptr} =
+ let {bcx: bcx, val: vecptr} =
trans_shared_malloc(bcx, T_ptr(llvecty), vecsize);
- Store(bcx, fill, InBoundsGEP
- (bcx, vecptr, [C_int(0), C_uint(abi::vec_elt_fill)]));
- Store(bcx, alloc, InBoundsGEP
- (bcx, vecptr, [C_int(0), C_uint(abi::vec_elt_alloc)]));
+ Store(bcx, fill,
+ InBoundsGEP(bcx, vecptr, [C_int(0), C_uint(abi::vec_elt_fill)]));
+ Store(bcx, alloc,
+ InBoundsGEP(bcx, vecptr, [C_int(0), C_uint(abi::vec_elt_alloc)]));
ret {bcx: bcx, val: vecptr};
}
-type alloc_result = {bcx: @block_ctxt,
- val: ValueRef,
- unit_ty: ty::t,
- llunitsz: ValueRef,
- llunitty: TypeRef};
+type alloc_result =
+ {bcx: @block_ctxt,
+ val: ValueRef,
+ unit_ty: ty::t,
+ llunitsz: ValueRef,
+ llunitty: TypeRef};
fn alloc(bcx: &@block_ctxt, vec_ty: &ty::t, elts: uint) -> alloc_result {
let unit_ty = ty::sequence_element_type(bcx_tcx(bcx), vec_ty);
let llunitty = type_of_or_i8(bcx, unit_ty);
let llvecty = T_vec(llunitty);
- let {bcx, val: unit_sz} = size_of(bcx, unit_ty);
+ let {bcx: bcx, val: unit_sz} = size_of(bcx, unit_ty);
let fill = Mul(bcx, C_uint(elts), unit_sz);
let alloc = if elts < 4u { Mul(bcx, C_int(4), unit_sz) } else { fill };
- let {bcx, val: vptr} = alloc_raw(bcx, fill, alloc);
+ let {bcx: bcx, val: vptr} = alloc_raw(bcx, fill, alloc);
let vptr = PointerCast(bcx, vptr, T_ptr(llvecty));
add_clean_temp(bcx, vptr, vec_ty);
- ret {bcx: bcx, val: vptr, unit_ty: unit_ty,
- llunitsz: unit_sz, llunitty: llunitty};
+ ret {bcx: bcx,
+ val: vptr,
+ unit_ty: unit_ty,
+ llunitsz: unit_sz,
+ llunitty: llunitty};
}
fn duplicate(bcx: &@block_ctxt, vptrptr: ValueRef) -> @block_ctxt {
let vptr = Load(bcx, vptrptr);
let fill = get_fill(bcx, vptr);
let size = Add(bcx, fill, llsize_of(T_opaque_vec()));
- let {bcx, val: newptr} = trans_shared_malloc(bcx, val_ty(vptr), size);
+ let {bcx: bcx, val: newptr} =
+ trans_shared_malloc(bcx, val_ty(vptr), size);
let bcx = call_memmove(bcx, newptr, vptr, size).bcx;
Store(bcx, fill,
InBoundsGEP(bcx, newptr, [C_int(0), C_uint(abi::vec_elt_alloc)]));
Store(bcx, newptr, vptrptr);
ret bcx;
}
-fn make_drop_glue(bcx: &@block_ctxt, vptrptr: ValueRef, vec_ty: ty::t)
- -> @block_ctxt {
+fn make_drop_glue(bcx: &@block_ctxt, vptrptr: ValueRef, vec_ty: ty::t) ->
+ @block_ctxt {
let unit_ty = ty::sequence_element_type(bcx_tcx(bcx), vec_ty);
let vptr = Load(bcx, vptrptr);
- let drop_cx = new_sub_block_ctxt(bcx, ~"drop");
- let next_cx = new_sub_block_ctxt(bcx, ~"next");
+ let drop_cx = new_sub_block_ctxt(bcx, "drop");
+ let next_cx = new_sub_block_ctxt(bcx, "next");
let null_test = IsNull(bcx, vptr);
CondBr(bcx, null_test, next_cx.llbb, drop_cx.llbb);
if ty::type_needs_drop(bcx_tcx(bcx), unit_ty) {
ret next_cx;
}
-fn trans_vec(bcx: &@block_ctxt, args: &[@ast::expr],
- id: ast::node_id) -> result {
+fn trans_vec(bcx: &@block_ctxt, args: &[@ast::expr], id: ast::node_id) ->
+ result {
let vec_ty = node_id_type(bcx_ccx(bcx), id);
- let {bcx, val: vptr, llunitsz, unit_ty, llunitty} =
+ let {bcx: bcx,
+ val: vptr,
+ llunitsz: llunitsz,
+ unit_ty: unit_ty,
+ llunitty: llunitty} =
alloc(bcx, vec_ty, vec::len(args));
// Store the individual elements.
for e in args {
let lv = trans_lval(bcx, e);
bcx = lv.res.bcx;
- let lleltptr = if ty::type_has_dynamic_size(bcx_tcx(bcx), unit_ty) {
- InBoundsGEP(bcx, dataptr, [Mul(bcx, C_uint(i), llunitsz)])
- } else {
- InBoundsGEP(bcx, dataptr, [C_uint(i)])
- };
+ let lleltptr =
+ if ty::type_has_dynamic_size(bcx_tcx(bcx), unit_ty) {
+ InBoundsGEP(bcx, dataptr, [Mul(bcx, C_uint(i), llunitsz)])
+ } else { InBoundsGEP(bcx, dataptr, [C_uint(i)]) };
bcx = move_val_if_temp(bcx, INIT, lleltptr, lv, unit_ty);
i += 1u;
}
ret rslt(bcx, vptr);
}
-fn trans_istr(bcx: &@block_ctxt, s: istr) -> result {
+fn trans_istr(bcx: &@block_ctxt, s: str) -> result {
let veclen = std::str::byte_len(s) + 1u; // +1 for \0
- let {bcx, val: sptr, _} =
+ let {bcx: bcx, val: sptr, _} =
alloc(bcx, ty::mk_istr(bcx_tcx(bcx)), veclen);
let llcstr = C_cstr(bcx_ccx(bcx), s);
- let bcx = call_memmove(bcx, get_dataptr(bcx, sptr, T_i8()),
- llcstr, C_uint(veclen)).bcx;
+ let bcx =
+ call_memmove(bcx, get_dataptr(bcx, sptr, T_i8()), llcstr,
+ C_uint(veclen)).bcx;
ret rslt(bcx, sptr);
}
lhsptr = PointerCast(cx, lhsptr, T_ptr(T_ptr(T_opaque_vec())));
rhs = PointerCast(cx, rhs, T_ptr(T_opaque_vec()));
}
- let strings = alt ty::struct(bcx_tcx(cx), vec_ty) {
- ty::ty_istr. { true }
- ty::ty_vec(_) { false }
- };
+ let strings =
+ alt ty::struct(bcx_tcx(cx), vec_ty) {
+ ty::ty_istr. { true }
+ ty::ty_vec(_) { false }
+ };
- let {bcx, val: unit_sz} = size_of(cx, unit_ty);
+ let {bcx: bcx, val: unit_sz} = size_of(cx, unit_ty);
let llunitty = type_of_or_i8(cx, unit_ty);
let lhs = Load(bcx, lhsptr);
if strings { lhs_off = Sub(bcx, lhs_off, C_int(1)); }
let write_ptr = pointer_add(bcx, lhs_data, lhs_off);
let write_ptr_ptr = do_spill_noroot(bcx, write_ptr);
- let bcx = iter_vec_raw(bcx, rhs, vec_ty, rfill, { | &bcx, addr, _ty |
- let write_ptr = Load(bcx, write_ptr_ptr);
- let bcx = copy_val(bcx, INIT, write_ptr,
- load_if_immediate(bcx, addr, unit_ty), unit_ty);
- if dynamic {
- // We have to increment by the dynamically-computed size.
- incr_ptr(bcx, write_ptr, unit_sz, write_ptr_ptr);
- } else {
- incr_ptr(bcx, write_ptr, C_int(1), write_ptr_ptr);
- }
- ret bcx;
- });
+ let bcx =
+ iter_vec_raw(bcx, rhs, vec_ty, rfill,
+ // We have to increment by the dynamically-computed size.
+ {|&bcx, addr, _ty|
+ let write_ptr = Load(bcx, write_ptr_ptr);
+ let bcx =
+ copy_val(bcx, INIT, write_ptr,
+ load_if_immediate(bcx, addr, unit_ty),
+ unit_ty);
+ if dynamic {
+ incr_ptr(bcx, write_ptr, unit_sz, write_ptr_ptr);
+ } else {
+ incr_ptr(bcx, write_ptr, C_int(1),
+ write_ptr_ptr);
+ }
+ ret bcx;
+ });
ret rslt(bcx, C_nil());
}
vals: &[@ast::expr]) -> @block_ctxt {
let elt_ty = ty::sequence_element_type(bcx_tcx(bcx), vec_ty);
let ti = none;
- let {bcx, val: td} =
+ let {bcx: bcx, val: td} =
get_tydesc(bcx, elt_ty, false, tps_normal, ti).result;
trans::lazily_emit_tydesc_glue(bcx, abi::tydesc_field_take_glue, ti);
let opaque_v = PointerCast(bcx, vptrptr, T_ptr(T_ptr(T_opaque_vec())));
let {bcx: e_bcx, val: elt} = trans::trans_expr(bcx, val);
bcx = e_bcx;
let r = trans::spill_if_immediate(bcx, elt, elt_ty);
- let spilled = r.val; bcx = r.bcx;
+ let spilled = r.val;
+ bcx = r.bcx;
Call(bcx, bcx_ccx(bcx).upcalls.vec_push,
[bcx.fcx.lltaskptr, opaque_v, td,
PointerCast(bcx, spilled, T_ptr(T_i8()))]);
ret bcx;
}
-fn trans_add(bcx: &@block_ctxt, vec_ty: ty::t, lhs: ValueRef,
- rhs: ValueRef) -> result {
- let strings = alt ty::struct(bcx_tcx(bcx), vec_ty) {
- ty::ty_istr. { true }
- ty::ty_vec(_) { false }
- };
+fn trans_add(bcx: &@block_ctxt, vec_ty: ty::t, lhs: ValueRef, rhs: ValueRef)
+ -> result {
+ let strings =
+ alt ty::struct(bcx_tcx(bcx), vec_ty) {
+ ty::ty_istr. { true }
+ ty::ty_vec(_) { false }
+ };
let unit_ty = ty::sequence_element_type(bcx_tcx(bcx), vec_ty);
let llunitty = type_of_or_i8(bcx, unit_ty);
- let {bcx, val: llunitsz} = size_of(bcx, unit_ty);
+ let {bcx: bcx, val: llunitsz} = size_of(bcx, unit_ty);
let lhs_fill = get_fill(bcx, lhs);
if strings { lhs_fill = Sub(bcx, lhs_fill, C_int(1)); }
let rhs_fill = get_fill(bcx, rhs);
let new_fill = Add(bcx, lhs_fill, rhs_fill);
- let {bcx, val: new_vec} = alloc_raw(bcx, new_fill, new_fill);
+ let {bcx: bcx, val: new_vec} = alloc_raw(bcx, new_fill, new_fill);
let new_vec = PointerCast(bcx, new_vec, T_ptr(T_vec(llunitty)));
add_clean_temp(bcx, new_vec, vec_ty);
- let write_ptr_ptr = do_spill_noroot(bcx,
- get_dataptr(bcx, new_vec, llunitty));
- let copy_fn = bind fn(bcx: &@block_ctxt, addr: ValueRef, _ty: ty::t,
- write_ptr_ptr: ValueRef, unit_ty: ty::t,
- llunitsz: ValueRef) -> @block_ctxt {
- let write_ptr = Load(bcx, write_ptr_ptr);
- let bcx = copy_val(bcx, INIT, write_ptr,
- load_if_immediate(bcx, addr, unit_ty), unit_ty);
- if ty::type_has_dynamic_size(bcx_tcx(bcx), unit_ty) {
- // We have to increment by the dynamically-computed size.
- incr_ptr(bcx, write_ptr, llunitsz, write_ptr_ptr);
- } else {
- incr_ptr(bcx, write_ptr, C_int(1), write_ptr_ptr);
- }
- ret bcx;
- } (_, _, _, write_ptr_ptr, unit_ty, llunitsz);
+ let write_ptr_ptr =
+ do_spill_noroot(bcx, get_dataptr(bcx, new_vec, llunitty));
+ let copy_fn =
+ bind fn (bcx: &@block_ctxt, addr: ValueRef, _ty: ty::t,
+ write_ptr_ptr: ValueRef, unit_ty: ty::t, llunitsz: ValueRef)
+ -> @block_ctxt {
+ let write_ptr = Load(bcx, write_ptr_ptr);
+ let bcx =
+ copy_val(bcx, INIT, write_ptr,
+ load_if_immediate(bcx, addr, unit_ty), unit_ty);
+ if ty::type_has_dynamic_size(bcx_tcx(bcx), unit_ty) {
+ // We have to increment by the dynamically-computed size.
+ incr_ptr(bcx, write_ptr, llunitsz, write_ptr_ptr);
+ } else { incr_ptr(bcx, write_ptr, C_int(1), write_ptr_ptr); }
+ ret bcx;
+ }(_, _, _, write_ptr_ptr, unit_ty, llunitsz);
let bcx = iter_vec_raw(bcx, lhs, vec_ty, lhs_fill, copy_fn);
let bcx = iter_vec_raw(bcx, rhs, vec_ty, rhs_fill, copy_fn);
type iter_vec_block = block(&@block_ctxt, ValueRef, ty::t) -> @block_ctxt;
fn iter_vec_raw(bcx: &@block_ctxt, vptr: ValueRef, vec_ty: ty::t,
- fill: ValueRef, f: &iter_vec_block) -> @block_ctxt {
+ fill: ValueRef, f: &iter_vec_block) -> @block_ctxt {
let unit_ty = ty::sequence_element_type(bcx_tcx(bcx), vec_ty);
let llunitty = type_of_or_i8(bcx, unit_ty);
- let {bcx, val: unit_sz} = size_of(bcx, unit_ty);
+ let {bcx: bcx, val: unit_sz} = size_of(bcx, unit_ty);
let vptr = PointerCast(bcx, vptr, T_ptr(T_vec(llunitty)));
let data_ptr = get_dataptr(bcx, vptr, llunitty);
let data_ptr_ptr = do_spill_noroot(bcx, data_ptr);
// Now perform the iteration.
- let header_cx = new_sub_block_ctxt(bcx, ~"iter_vec_loop_header");
+ let header_cx = new_sub_block_ctxt(bcx, "iter_vec_loop_header");
Br(bcx, header_cx.llbb);
let data_ptr = Load(header_cx, data_ptr_ptr);
- let not_yet_at_end = ICmp(header_cx, lib::llvm::LLVMIntULT,
- data_ptr, data_end_ptr);
- let body_cx = new_sub_block_ctxt(bcx, ~"iter_vec_loop_body");
- let next_cx = new_sub_block_ctxt(bcx, ~"iter_vec_next");
+ let not_yet_at_end =
+ ICmp(header_cx, lib::llvm::LLVMIntULT, data_ptr, data_end_ptr);
+ let body_cx = new_sub_block_ctxt(bcx, "iter_vec_loop_body");
+ let next_cx = new_sub_block_ctxt(bcx, "iter_vec_next");
CondBr(header_cx, not_yet_at_end, body_cx.llbb, next_cx.llbb);
body_cx = f(body_cx, data_ptr, unit_ty);
- let increment = if ty::type_has_dynamic_size(bcx_tcx(bcx), unit_ty) {
- unit_sz
- } else { C_int(1) };
+ let increment =
+ if ty::type_has_dynamic_size(bcx_tcx(bcx), unit_ty) {
+ unit_sz
+ } else { C_int(1) };
incr_ptr(body_cx, data_ptr, increment, data_ptr_ptr);
Br(body_cx, header_cx.llbb);
}
fn iter_vec(bcx: &@block_ctxt, vptrptr: ValueRef, vec_ty: ty::t,
- f: &iter_vec_block) -> @block_ctxt {
- let vptr = Load(bcx, PointerCast(bcx, vptrptr,
- T_ptr(T_ptr(T_opaque_vec()))));
+ f: &iter_vec_block) -> @block_ctxt {
+ let vptr =
+ Load(bcx, PointerCast(bcx, vptrptr, T_ptr(T_ptr(T_opaque_vec()))));
ret iter_vec_raw(bcx, vptr, vec_ty, get_fill(bcx, vptr), f);
}
ret tritv_doesntcare(tmp);
}
-fn trit_str(t: trit) -> istr {
- alt t { dont_care. { ~"?" } ttrue. { ~"1" } tfalse. { ~"0" } }
+fn trit_str(t: trit) -> str {
+ alt t { dont_care. { "?" } ttrue. { "1" } tfalse. { "0" } }
}
//
// Local Variables:
fn collect_ids_stmt(s: &@stmt, rs: @mutable [node_id]) {
alt s.node {
stmt_decl(_, id) {
- log ~"node_id " + int::str(id);
+ log "node_id " + int::str(id);
log_stmt(*s);;
*rs += [id];
}
stmt_expr(_, id) {
- log ~"node_id " + int::str(id);
+ log "node_id " + int::str(id);
log_stmt(*s);;
*rs += [id];
}
fn init_vecs(ccx: &crate_ctxt, node_ids: &[node_id], len: uint) {
for i: node_id in node_ids {
- log int::str(i) + ~" |-> " + uint::str(len);
+ log int::str(i) + " |-> " + uint::str(len);
add_node(ccx, i, empty_ann(len));
}
}
}
/* logging funs */
-fn def_id_to_str(d: def_id) -> istr {
- ret int::str(d.crate) + ~"," + int::str(d.node);
+fn def_id_to_str(d: def_id) -> str {
+ ret int::str(d.crate) + "," + int::str(d.node);
}
-fn comma_str(args: &[@constr_arg_use]) -> istr {
- let rslt = ~"";
+fn comma_str(args: &[@constr_arg_use]) -> str {
+ let rslt = "";
let comma = false;
for a: @constr_arg_use in args {
- if comma { rslt += ~", "; } else { comma = true; }
+ if comma { rslt += ", "; } else { comma = true; }
alt a.node {
- carg_base. { rslt += ~"*"; }
+ carg_base. { rslt += "*"; }
carg_ident(i) { rslt += i.ident; }
carg_lit(l) { rslt += lit_to_str(l); }
}
ret rslt;
}
-fn constraint_to_str(tcx: &ty::ctxt, c: &sp_constr) -> istr {
+fn constraint_to_str(tcx: &ty::ctxt, c: &sp_constr) -> str {
alt c.node {
ninit(_, i) {
- ret ~"init(" + i + ~" [" +
- tcx.sess.span_str(c.span) + ~"])";
+ ret "init(" + i + " [" + tcx.sess.span_str(c.span) + "])";
}
npred(p, _, args) {
- ret path_to_str(p) + ~"(" +
- comma_str(args) + ~")" + ~"[" +
- tcx.sess.span_str(c.span) + ~"]";
+ ret path_to_str(p) + "(" + comma_str(args) + ")" + "[" +
+ tcx.sess.span_str(c.span) + "]";
}
}
}
-fn tritv_to_str(fcx: fn_ctxt, v: &tritv::t) -> istr {
- let s = ~"";
+fn tritv_to_str(fcx: fn_ctxt, v: &tritv::t) -> str {
+ let s = "";
let comma = false;
for p: norm_constraint in constraints(fcx) {
alt tritv_get(v, p.bit_num) {
dont_care. { }
t {
s +=
- if comma { ~", " } else { comma = true; ~"" } +
- if t == tfalse { ~"!" } else { ~"" } +
+ if comma { ", " } else { comma = true; "" } +
+ if t == tfalse { "!" } else { "" } +
constraint_to_str(fcx.ccx.tcx, p.c);
}
}
fn log_tritv(fcx: &fn_ctxt, v: &tritv::t) { log tritv_to_str(fcx, v); }
fn first_difference_string(fcx: &fn_ctxt, expected: &tritv::t,
- actual: &tritv::t) -> istr {
- let s: istr = ~"";
+ actual: &tritv::t) -> str {
+ let s: str = "";
for c: norm_constraint in constraints(fcx) {
if tritv_get(expected, c.bit_num) == ttrue &&
tritv_get(actual, c.bit_num) != ttrue {
fn log_tritv_err(fcx: fn_ctxt, v: tritv::t) { log_err tritv_to_str(fcx, v); }
-fn tos(v: &[uint]) -> istr {
- let rslt = ~"";
+fn tos(v: &[uint]) -> str {
+ let rslt = "";
for i: uint in v {
if i == 0u {
- rslt += ~"0";
- } else if i == 1u { rslt += ~"1"; } else { rslt += ~"?"; }
+ rslt += "0";
+ } else if i == 1u { rslt += "1"; } else { rslt += "?"; }
}
ret rslt;
}
log_cond_err(p2);
}
-fn print_ident(i: &ident) { log ~" " + i + ~" "; }
+fn print_ident(i: &ident) { log " " + i + " "; }
fn print_idents(idents: &mutable [ident]) {
if vec::len::<ident>(idents) == 0u { ret; }
- log ~"an ident: " + vec::pop::<ident>(idents);
+ log "an ident: " + vec::pop::<ident>(idents);
print_idents(idents);
}
constraints.
*/
type fn_info =
+ /* list, accumulated during pre/postcondition
+ computation, of all local variables that may be
+ used */
+ // Doesn't seem to work without the @ -- bug
{constrs: constr_map,
num_constraints: uint,
cf: controlflow,
i_return: tsconstr,
i_diverge: tsconstr,
- /* list, accumulated during pre/postcondition
- computation, of all local variables that may be
- used */
- // Doesn't seem to work without the @ -- bug
used_vars: @mutable [node_id]};
fn tsconstr_to_def_id(t: &tsconstr) -> def_id {
fn node_id_to_ts_ann(ccx: &crate_ctxt, id: node_id) -> ts_ann {
alt get_ts_ann(ccx, id) {
none. {
- log_err ~"node_id_to_ts_ann: no ts_ann for node_id "
- + int::str(id);
+ log_err "node_id_to_ts_ann: no ts_ann for node_id " + int::str(id);
fail;
}
some(t) { ret t; }
fn node_id_to_def_strict(cx: &ty::ctxt, id: node_id) -> def {
alt cx.def_map.find(id) {
none. {
- log_err ~"node_id_to_def: node_id "
- + int::str(id) + ~" has no def";
+ log_err "node_id_to_def: node_id " + int::str(id) + " has no def";
fail;
}
some(d) { ret d; }
// should freeze it at some earlier point.
fn match_args(fcx: &fn_ctxt, occs: &@mutable [pred_args],
occ: &[@constr_arg_use]) -> uint {
- log ~"match_args: looking at " +
- constr_args_to_str(fn (i: &inst) -> istr {
- ret i.ident;
- }, occ);
+ log "match_args: looking at " +
+ constr_args_to_str(fn (i: &inst) -> str { ret i.ident; }, occ);
for pd: pred_args in *occs {
- log ~"match_args: candidate " + pred_args_to_str(pd);
+ log "match_args: candidate " + pred_args_to_str(pd);
fn eq(p: &inst, q: &inst) -> bool { ret p.node == q.node; }
if ty::args_eq(eq, pd.node.args, occ) { ret pd.node.bit_num; }
}
- fcx.ccx.tcx.sess.bug(~"match_args: no match for occurring args");
+ fcx.ccx.tcx.sess.bug("match_args: no match for occurring args");
}
fn def_id_for_constr(tcx: ty::ctxt, t: node_id) -> def_id {
alt tcx.def_map.find(t) {
none. {
- tcx.sess.bug(~"node_id_for_constr: bad node_id "
- + int::str(t));
+ tcx.sess.bug("node_id_for_constr: bad node_id " + int::str(t));
}
some(def_fn(i, _)) { ret i; }
- _ { tcx.sess.bug(~"node_id_for_constr: pred is not a function"); }
+ _ { tcx.sess.bug("node_id_for_constr: pred is not a function"); }
}
}
carg_ident({ident: p.node.idents[0], node: id.node}));
}
some(_) {
- tcx.sess.bug(~"exprs_to_constr_args: non-local variable " +
- ~"as pred arg");
+ tcx.sess.bug("exprs_to_constr_args: non-local variable " +
+ "as pred arg");
}
none {
- tcx.sess.bug(~"exprs_to_constr_args: NONE " +
- ~"as pred arg");
+ tcx.sess.bug("exprs_to_constr_args: NONE " + "as pred arg");
}
}
expr_lit(l) { ret @respan(e.span, carg_lit(l)); }
_ {
tcx.sess.span_fatal(e.span,
- ~"Arguments to constrained functions must be " +
- ~"literals or local variables");
+ "Arguments to constrained functions must be " +
+ "literals or local variables");
}
}
}
}
_ {
tcx.sess.span_fatal(operator.span,
- ~"Internal error: " +
- ~" ill-formed operator \
+ "Internal error: " +
+ " ill-formed operator \
in predicate");
}
}
}
_ {
tcx.sess.span_fatal(e.span,
- ~"Internal error: " + ~" ill-formed predicate");
+ "Internal error: " + " ill-formed predicate");
}
}
}
-fn pred_args_to_str(p: &pred_args) -> istr {
- ~"<" + uint::str(p.node.bit_num) + ~", " +
- constr_args_to_str(fn (i: &inst) -> istr {
- ret i.ident;
- }, p.node.args)
- + ~">"
+fn pred_args_to_str(p: &pred_args) -> str {
+ "<" + uint::str(p.node.bit_num) + ", " +
+ constr_args_to_str(fn (i: &inst) -> str { ret i.ident; }, p.node.args)
+ + ">"
}
fn substitute_constr_args(cx: &ty::ctxt, actuals: &[@expr], c: &@ty::constr)
if i < num_actuals {
ret expr_to_constr_arg(cx, actuals[i]);
} else {
- cx.sess.span_fatal(a.span, ~"Constraint argument out of bounds");
+ cx.sess.span_fatal(a.span, "Constraint argument out of bounds");
}
}
carg_base. { ret @respan(a.span, carg_base); }
is_some(find_in_subst(id, s))
}
-fn insts_to_str(stuff: &[constr_arg_general_<inst>]) -> istr {
- let rslt = ~"<";
+fn insts_to_str(stuff: &[constr_arg_general_<inst>]) -> str {
+ let rslt = "<";
for i: constr_arg_general_<inst> in stuff {
rslt +=
- ~" " +
+ " " +
alt i {
carg_ident(p) { p.ident }
- carg_base. { ~"*" }
- carg_lit(_) { ~"[lit]" }
- } + ~" ";
+ carg_base. { "*" }
+ carg_lit(_) { "[lit]" }
+ } + " ";
}
- rslt += ~">";
+ rslt += ">";
rslt
}
fn path_to_ident(cx: &ty::ctxt, p: &path) -> ident {
alt vec::last(p.node.idents) {
- none. { cx.sess.span_fatal(p.span, ~"Malformed path"); }
+ none. { cx.sess.span_fatal(p.span, "Malformed path"); }
some(i) { ret i; }
}
}
}
some(_) {
fcx.ccx.tcx.sess.span_fatal(sp,
- ~"local_node_id_to_def_id: id \
+ "local_node_id_to_def_id: id \
isn't a local");
}
none. {
// should really be bug. span_bug()?
fcx.ccx.tcx.sess.span_fatal(sp,
- ~"local_node_id_to_def_id: id \
+ "local_node_id_to_def_id: id \
is unbound");
}
}
fn local_node_id_to_def_id(fcx: &fn_ctxt, i: &node_id) -> option::t<def_id> {
alt local_node_id_to_def(fcx, i) {
some(def_local(id)) | some(def_arg(id, _)) | some(def_binding(id)) |
- some(def_upvar(id, _, _)) { some(id) }
+ some(def_upvar(id, _, _)) {
+ some(id)
+ }
_ { none }
}
}
fn args_to_constr_args(tcx: &ty::ctxt, args: &[arg],
- indices:&[@sp_constr_arg<uint>]) -> [@constr_arg_use] {
+ indices: &[@sp_constr_arg<uint>]) ->
+ [@constr_arg_use] {
let actuals: [@constr_arg_use] = [];
let num_args = vec::len(args);
- for a:@sp_constr_arg<uint> in indices {
- actuals += [@respan(a.span, alt a.node {
- carg_base. { carg_base }
- carg_ident(i) {
- if i < num_args {
- carg_ident({ident: args[i].ident, node:args[i].id})
- }
- else {
- tcx.sess.span_bug(a.span, ~"Index out of bounds in \
+ for a: @sp_constr_arg<uint> in indices {
+ actuals +=
+ [@respan(a.span,
+ alt a.node {
+ carg_base. { carg_base }
+ carg_ident(i) {
+ if i < num_args {
+ carg_ident({ident: args[i].ident,
+ node: args[i].id})
+ } else {
+ tcx.sess.span_bug(a.span,
+ "Index out of bounds in \
constraint arg");
- }
- }
- carg_lit(l) { carg_lit(l) }
- })];
+ }
+ }
+ carg_lit(l) { carg_lit(l) }
+ })];
}
ret actuals;
}
tsconstr {
let tconstr = ty::ast_constr_to_constr(tcx, c);
ret npred(tconstr.node.path, tconstr.node.id,
- args_to_constr_args(tcx, args, tconstr.node.args));
+ args_to_constr_args(tcx, args, tconstr.node.args));
}
fn ast_constr_to_sp_constr(tcx: &ty::ctxt, args: &[arg], c: &@constr) ->
}
_ {
// 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));
}
}
}
alt rslt {
cinit(n, _, _) { ret n; }
_ {
- fcx.ccx.tcx.sess.bug(~"bit_num: asked for init constraint," +
- ~" found a pred constraint");
+ fcx.ccx.tcx.sess.bug("bit_num: asked for init constraint," +
+ " found a pred constraint");
}
}
}
alt rslt {
cpred(_, descs) { ret match_args(fcx, descs, args); }
_ {
- fcx.ccx.tcx.sess.bug(~"bit_num: asked for pred constraint," +
- ~" found an init constraint");
+ fcx.ccx.tcx.sess.bug("bit_num: asked for pred constraint," +
+ " found an init constraint");
}
}
}
}
some(_) {/* ignore args (for now...) */ }
_ {
- fcx.ccx.tcx.sess.bug(~"clear_in_poststate_expr: \
+ fcx.ccx.tcx.sess.bug("clear_in_poststate_expr: \
unbound var");
}
}
}
- _ { fcx.ccx.tcx.sess.bug(~"clear_in_poststate_expr"); }
+ _ { fcx.ccx.tcx.sess.bug("clear_in_poststate_expr"); }
}
}
_ {/* do nothing */ }
ninit(id, v) {
if !vec_contains(fcx.enclosing.used_vars, id) && v[0] != '_' as u8
{
- fcx.ccx.tcx.sess.span_warn(c.c.span,
- ~"unused variable "
- + v);
+ fcx.ccx.tcx.sess.span_warn(c.c.span, "unused variable " + v);
}
}
_ {/* ignore pred constraints */ }
*/
if !implies(pres, prec) {
- let s = ~"";
+ let s = "";
let diff = first_difference_string(fcx, prec, pres);
s +=
- ~"Unsatisfied precondition constraint (for example, " + diff +
- ~") for expression:\n";
+ "Unsatisfied precondition constraint (for example, " + diff +
+ ") for expression:\n";
s += syntax::print::pprust::expr_to_str(e);
- s += ~"\nPrecondition:\n";
+ s += "\nPrecondition:\n";
s += tritv_to_str(fcx, prec);
- s += ~"\nPrestate:\n";
+ s += "\nPrestate:\n";
s += tritv_to_str(fcx, pres);
fcx.ccx.tcx.sess.span_fatal(e.span, s);
}
*/
if !implies(pres, prec) {
- let ss = ~"";
+ let ss = "";
let diff = first_difference_string(fcx, prec, pres);
ss +=
- ~"Unsatisfied precondition constraint (for example, " + diff +
- ~") for statement:\n";
+ "Unsatisfied precondition constraint (for example, " + diff +
+ ") for statement:\n";
ss += syntax::print::pprust::stmt_to_str(*s);
- ss += ~"\nPrecondition:\n";
+ ss += "\nPrecondition:\n";
ss += tritv_to_str(fcx, prec);
- ss += ~"\nPrestate: \n";
+ ss += "\nPrestate: \n";
ss += tritv_to_str(fcx, pres);
fcx.ccx.tcx.sess.span_fatal(s.span, ss);
}
!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) + ~"'");
+ 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 {
// check that this really always fails
if !promises(fcx, post, fcx.enclosing.i_diverge) {
fcx.ccx.tcx.sess.span_fatal(f.body.span,
- ~"In non-returning function " +
+ "In non-returning function " +
fcx.name +
- ~", some control paths may \
+ ", some control paths may \
return to the caller");
}
}
assert (ccx.fm.contains_key(id));
let f_info = ccx.fm.get(id);
- let name = option::from_maybe(~"anon", i);
- let fcx = {enclosing: f_info,
- id: id,
- name: name,
- ccx: ccx};
+ let name = option::from_maybe("anon", i);
+ let fcx = {enclosing: f_info, id: id, name: name, ccx: ccx};
check_fn_states(fcx, f, tps, id, sp, i);
}
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;;
+ log "collect_local: pushing " + ident;;
*cx.cs += [respan(loc.span, ninit(p.id, ident))];
}
visit::visit_local(loc, cx, v);
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.
expr_call(operator, operands) {
fn add_constraint(tcx: &ty::ctxt, c: sp_constr, next: uint, tbl: constr_map)
-> uint {
- log constraint_to_str(tcx, c) + ~" |-> "
- + std::uint::str(next);
+ log constraint_to_str(tcx, c) + " |-> " + std::uint::str(next);
alt c.node {
ninit(id, i) { tbl.insert(local_def(id), cinit(next, c.span, i)); }
npred(p, d_id, args) {
some(ct) {
alt ct {
cinit(_, _, _) {
- tcx.sess.bug(~"add_constraint: same def_id used" +
- ~" as a variable and a pred");
+ tcx.sess.bug("add_constraint: same def_id used" +
+ " as a variable and a pred");
}
cpred(_, pds) {
*pds += [respan(c.span, {args: args, bit_num: next})];
// and the name of the function, with a '!' appended to it, for the
// "diverges" constraint
let diverges_id = ccx.tcx.sess.next_node_id();
- let diverges_name = name + ~"!";
+ let diverges_name = name + "!";
add_constraint(cx.tcx, respan(f_sp, ninit(diverges_id, diverges_name)),
next, res_map);
i_diverge: ninit(diverges_id, diverges_name),
used_vars: v};
ccx.fm.insert(id, rslt);
- log name + ~" has "
- + std::uint::str(num_constraints(rslt))
- + ~" constraints";
+ log name + " has " + std::uint::str(num_constraints(rslt)) +
+ " constraints";
}
{constrs: @new_def_hash::<constraint>(),
num_constraints: 0u,
cf: return,
- i_return: ninit(0, ~""),
- i_diverge: ninit(0, ~""),
+ i_return: ninit(0, ""),
+ i_diverge: ninit(0, ""),
used_vars: v},
id: 0,
- name: ~"",
+ name: "",
ccx: ccx};
find_pre_post_expr(fake_fcx, e);
}
let rslt = expr_pp(fcx.ccx, e);
clear_pp(rslt);
for def in *freevars::get_freevars(fcx.ccx.tcx, e.id) {
- handle_var_def(fcx, rslt, def, ~"upvar");
+ handle_var_def(fcx, rslt, def, "upvar");
}
}
expr_block(b) {
let rslt = expr_pp(fcx.ccx, e);
clear_pp(rslt);
for def in *freevars::get_freevars(fcx.ccx.tcx, body.node.id) {
- handle_var_def(fcx, rslt, def, ~"upvar");
+ handle_var_def(fcx, rslt, def, "upvar");
}
}
expr_index(val, sub) { find_pre_post_exprs(fcx, [val, sub], e.id); }
+
expr_bind(operator, maybe_args) {
let args = [];
let cmodes = callee_modes(fcx, operator.id);
}
expr_break. { clear_pp(expr_pp(fcx.ccx, e)); }
expr_cont. { clear_pp(expr_pp(fcx.ccx, e)); }
- expr_mac(_) { fcx.ccx.tcx.sess.bug(~"unexpanded macro"); }
+ expr_mac(_) { fcx.ccx.tcx.sess.bug("unexpanded macro"); }
expr_anon_obj(anon_obj) {
alt anon_obj.inner_obj {
some(ex) {
pat_bind(n) { n }
_ {
fcx.ccx.tcx.sess.span_bug(pat.span,
- ~"Impossible LHS");
+ "Impossible LHS");
}
};
alt p {
}
_ {
fcx.ccx.tcx.sess.span_bug(pat.span,
- ~"Impossible LHS");
+ "Impossible LHS");
}
}
}
expr_log(_, ex) {
ret find_pre_post_state_sub(fcx, pres, ex, e.id, none);
}
- expr_mac(_) { fcx.ccx.tcx.sess.bug(~"unexpanded macro"); }
+ expr_mac(_) { fcx.ccx.tcx.sess.bug("unexpanded macro"); }
expr_put(maybe_e) {
alt maybe_e {
some(arg) {
// Treat the tail expression as a return statement
alt f.body.node.expr {
some(tailexpr) {
+
// We don't want to clear the diverges bit for bottom typed things,
// which really do diverge. I feel like there is a cleaner way
// to do this than checking the type.
ttrue. { dont_care }
tfalse. { ttrue }
+
/* internally contradictory, but
I guess it'll get flagged? */
dont_care. {
alt b {
ttrue. { tfalse }
+
/* see above comment */
_ {
tfalse
alt b {
ttrue. { dont_care }
+
/* FIXME: ?????? */
_ {
tfalse
alt a {
dont_care. { b }
+
// also seems wrong for case b = ttrue
ttrue. {
alt b {
dont_care. { ttrue }
+
// ??? 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. {
ret rslt;
}
-fn to_str(v: &t) -> istr {
+fn to_str(v: &t) -> str {
let i: uint = 0u;
- let rs: istr = ~"";
+ let rs: str = "";
while i < v.nbits {
rs +=
alt tritv_get(v, i) {
- dont_care. { ~"?" }
- ttrue. { ~"1" }
- tfalse. { ~"0" }
+ dont_care. { "?" }
+ ttrue. { "1" }
+ tfalse. { "0" }
};
i += 1u;
}
freevars: freevars::freevar_map,
tcache: type_cache,
rcache: creader_cache,
- short_names_cache: hashmap<t, @istr>,
+ short_names_cache: hashmap<t, @str>,
has_pointer_cache: hashmap<t, bool>,
kind_cache: hashmap<t, ast::kind>,
ast_ty_to_ty_cache: hashmap<@ast::ty, option::t<t>>};
// Never construct these manually. These are interned.
type raw_t =
{struct: sty,
- cname: option::t<istr>,
+ cname: option::t<str>,
hash: uint,
has_params: bool,
has_vars: bool};
short_names_cache: map::mk_hashmap(ty::hash_ty, ty::eq_ty),
has_pointer_cache: map::mk_hashmap(ty::hash_ty, ty::eq_ty),
kind_cache: map::mk_hashmap(ty::hash_ty, ty::eq_ty),
- ast_ty_to_ty_cache: map::mk_hashmap(ast_util::hash_ty,
- ast_util::eq_ty)};
+ ast_ty_to_ty_cache:
+ map::mk_hashmap(ast_util::hash_ty, ast_util::eq_ty)};
populate_type_store(cx);
ret cx;
}
// Type constructors
-fn mk_raw_ty(cx: &ctxt, st: &sty, _in_cname: &option::t<istr>) -> @raw_t {
- let cname: option::t<istr> = none;
+fn mk_raw_ty(cx: &ctxt, st: &sty, _in_cname: &option::t<str>) -> @raw_t {
+ let cname: option::t<str> = none;
let h = hash_type_info(st, cname);
let has_params: bool = false;
let has_vars: bool = false;
has_vars: has_vars};
}
-fn intern(cx: &ctxt, st: &sty, cname: &option::t<istr>) {
+fn intern(cx: &ctxt, st: &sty, cname: &option::t<str>) {
interner::intern(*cx.ts, mk_raw_ty(cx, st, cname));
}
-fn gen_ty_full(cx: &ctxt, st: &sty, cname: &option::t<istr>) -> t {
+fn gen_ty_full(cx: &ctxt, st: &sty, cname: &option::t<str>) -> t {
let raw_type = mk_raw_ty(cx, st, cname);
ret interner::intern(*cx.ts, raw_type);
}
fn mk_tup(cx: &ctxt, ts: &[t]) -> t { ret gen_ty(cx, ty_tup(ts)); }
-fn mk_fn(cx: &ctxt, proto: &ast::proto, args: &[arg], ty: t,
- cf: &controlflow, constrs: &[@constr]) -> t {
+fn mk_fn(cx: &ctxt, proto: &ast::proto, args: &[arg], ty: t, cf: &controlflow,
+ constrs: &[@constr]) -> t {
ret gen_ty(cx, ty_fn(proto, args, ty, cf, constrs));
}
}
// Returns the one-level-deep type structure of the given type.
-fn struct(cx: &ctxt, typ: t) -> sty {
- ret interner::get(*cx.ts, typ).struct;
-}
+fn struct(cx: &ctxt, typ: t) -> sty { ret interner::get(*cx.ts, typ).struct; }
// Returns the canonical name of the given type.
-fn cname(cx: &ctxt, typ: t) -> option::t<istr> {
+fn cname(cx: &ctxt, typ: t) -> option::t<str> {
ret interner::get(*cx.ts, typ).cname;
}
// Type utilities
-fn rename(cx: &ctxt, typ: t, new_cname: &istr) -> t {
+fn rename(cx: &ctxt, typ: t, new_cname: &str) -> t {
ret gen_ty_full(cx, struct(cx, typ), some(new_cname));
}
}
fn type_is_str(cx: &ctxt, ty: t) -> bool {
- alt struct(cx, ty) {
- ty_istr. { ret true; }
- _ { ret false; }
- }
+ alt struct(cx, ty) { ty_istr. { ret true; } _ { ret false; } }
}
fn sequence_element_type(cx: &ctxt, ty: t) -> t {
alt struct(cx, ty) {
ty_istr. { ret mk_mach(cx, ast::ty_u8); }
ty_vec(mt) { ret mt.ty; }
- _ { cx.sess.bug(
- ~"sequence_element_type called on non-sequence value"); }
+ _ { cx.sess.bug("sequence_element_type called on non-sequence value"); }
}
}
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 \
+ cx.sess.bug("get_element_type called on type " + ty_to_str(cx, ty) +
+ " - expected a \
tuple or record");
}
}
}
fn type_is_boxed(cx: &ctxt, ty: t) -> bool {
- alt struct(cx, ty) {
- ty_box(_) { ret true; }
- _ { ret false; }
- }
+ alt struct(cx, ty) { ty_box(_) { ret true; } _ { ret false; } }
}
fn type_is_vec(cx: &ctxt, ty: t) -> bool {
ret alt struct(cx, ty) {
- ty_vec(_) { true }
- ty_istr. { true }
- _ { false }
- };
+ ty_vec(_) { true }
+ ty_istr. { true }
+ _ { false }
+ };
}
fn type_is_unique(cx: &ctxt, ty: t) -> bool {
ty_uniq(_) { ret true; }
ty_vec(_) { true }
ty_istr. { true }
- _ { ret false; } }
+ _ { ret false; }
+ }
}
fn type_is_scalar(cx: &ctxt, ty: t) -> bool {
let result = false;
alt struct(cx, ty) {
+
// scalar types
- ty_nil. {/* no-op */ }
+ ty_nil. {
+ /* no-op */
+
+ }
ty_bot. {/* no-op */ }
ty_bool. {/* no-op */ }
ty_int. {/* no-op */ }
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(_) {
}
+
// A handful of other built-in are unique too.
ty_type. | ty_istr. | ty_native_fn(_, _, _) {
// no-op
}
+
// FIXME: obj is broken for now, since we aren't asserting
// anything about its fields.
ty_obj(_) {
}
+
// FIXME: the environment capture mode is not fully encoded
// here yet, leading to weirdness around closure.
ty_fn(proto, _, _, _, _) {
}
+
// Those with refcounts-to-inner raise pinned to shared,
// lower unique to shared. Therefore just set result to shared.
ty_box(mt) {
}
+
// Pointers and unique boxes / vecs raise pinned to shared,
// otherwise pass through their pointee kind.
ty_ptr(tm) | ty_vec(tm) {
}
+
// Records lower to the lowest of their members.
ty_rec(flds) {
for f: field in flds {
}
}
+
// 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) {
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));
}
}
alt struct(cx, ty) { ty_native(_) { ret true; } _ { ret false; } }
}
-fn type_structurally_contains(cx: &ctxt, ty: t,
- test: fn(&sty) -> bool) -> bool {
+fn type_structurally_contains(cx: &ctxt, ty: t, test: fn(&sty) -> bool) ->
+ bool {
let sty = struct(cx, ty);
if test(sty) { ret true; }
alt sty {
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(_) {
}
+
// Boxed types
ty_istr. | ty_box(_) | ty_vec(_) | ty_fn(_, _, _, _, _) |
ty_native_fn(_, _, _) | ty_obj(_) {
}
+
// Structural types
ty_tag(did, tps) {
let variants = tag_variants(cx, did);
ty_constr(subt, _) { result = type_is_pod(cx, subt); }
+
ty_var(_) {
fail "ty_var in type_is_pod";
}
}
+
// ???
ty_fn(_, args, rty, _, _) {
ret hash_fn(27u, args, rty);
}
}
-fn hash_type_info(st: &sty, cname_opt: &option::t<istr>) -> uint {
+fn hash_type_info(st: &sty, cname_opt: &option::t<str>) -> uint {
let h = hash_type_structure(st);
alt cname_opt {
none. {/* no-op */ }
// Pull out the node type table.
alt smallintmap::find(*cx.node_types, id as uint) {
none. {
- cx.sess.bug(~"node_id_to_ty_param_substs_opt_and_ty() called on " +
- ~"an untyped node (" +
- std::int::to_str(id, 10u) +
- ~")");
+ cx.sess.bug("node_id_to_ty_param_substs_opt_and_ty() called on " +
+ "an untyped node (" + std::int::to_str(id, 10u) +
+ ")");
}
some(tpot) { ret tpot; }
}
alt struct(cx, fty) {
ty::ty_fn(_, a, _, _, _) { ret a; }
ty::ty_native_fn(_, a, _) { ret a; }
- _ { cx.sess.bug(~"ty_fn_args() called on non-fn type"); }
+ _ { cx.sess.bug("ty_fn_args() called on non-fn type"); }
}
}
fn ty_fn_proto(cx: &ctxt, fty: t) -> ast::proto {
alt struct(cx, fty) {
ty::ty_fn(p, _, _, _, _) { ret p; }
- _ { cx.sess.bug(~"ty_fn_proto() called on non-fn type"); }
+ _ { cx.sess.bug("ty_fn_proto() called on non-fn type"); }
}
}
fn ty_fn_abi(cx: &ctxt, fty: t) -> ast::native_abi {
alt struct(cx, fty) {
ty::ty_native_fn(a, _, _) { ret a; }
- _ { cx.sess.bug(~"ty_fn_abi() called on non-native-fn type"); }
+ _ { cx.sess.bug("ty_fn_abi() called on non-native-fn type"); }
}
}
alt struct(cx, fty) {
ty::ty_fn(_, _, r, _, _) { ret r; }
ty::ty_native_fn(_, _, r) { ret r; }
- _ { cx.sess.bug(~"ty_fn_ret() called on non-fn type"); }
+ _ { cx.sess.bug("ty_fn_ret() called on non-fn type"); }
}
}
// Just checks whether it's a fn that returns bool,
// not its purity.
-fn is_pred_ty(cx: &ctxt, fty:t) -> bool {
+fn is_pred_ty(cx: &ctxt, fty: t) -> bool {
is_fn_ty(cx, fty) && type_is_bool(cx, ty_fn_ret(cx, fty))
}
fields: &[field]) -> uint {
let i: uint = 0u;
for f: field in fields { if str::eq(f.ident, id) { ret i; } i += 1u; }
- sess.span_fatal(sp, ~"unknown field '" +
- id + ~"' of record");
+ sess.span_fatal(sp, "unknown field '" + id + "' of record");
}
fn method_idx(sess: &session::session, sp: &span, id: &ast::ident,
meths: &[method]) -> uint {
let i: uint = 0u;
for m: method in meths { if str::eq(m.ident, id) { ret i; } i += 1u; }
- sess.span_fatal(sp, ~"unknown method '" + id + ~"' of obj");
+ sess.span_fatal(sp, "unknown method '" + id + "' of obj");
}
fn sort_methods(meths: &[method]) -> [method] {
// variables, so in this case we have to be sure to die.
tcx.sess.span_fatal(
s,
- ~"Type inference failed because I \
+ "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 \
+ " and of the form " + ty_to_str(tcx, rt) +
+ ". Such a type would have to be infinitely \
large.");
}
_ { ret true; }
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 {
alt expected_cf {
ast::return. { }
+
// ok
ast::noreturn. {
alt actual_cf {
alt struct(cx.tcx, actual) {
+
// If the RHS is a variable type, then just do the
// appropriate binding.
ty::ty_var(actual_id) {
ty::ty_nil. { ret struct_cmp(cx, expected, actual); }
+
// _|_ unifies with anything
ty::ty_bot. {
ret ures_ok(actual);
fn dump_var_bindings(tcx: ty_ctxt, vb: @var_bindings) {
let i = 0u;
while i < vec::len::<ufind::node>(vb.sets.nodes) {
- let sets = ~"";
+ 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]; }
}
let typespec;
alt smallintmap::find::<t>(vb.types, i) {
- none. { typespec = ~""; }
- some(typ) {
- typespec = ~" =" + ty_to_str(tcx, typ);
- }
+ none. { typespec = ""; }
+ some(typ) { typespec = " =" + ty_to_str(tcx, typ); }
}
log_err #fmt["set %u:%s%s", i, typespec, sets];
i += 1u;
}
}
-fn type_err_to_str(err: &ty::type_err) -> istr {
+fn type_err_to_str(err: &ty::type_err) -> str {
alt err {
- terr_mismatch. { ret ~"types differ"; }
+ terr_mismatch. { ret "types differ"; }
terr_controlflow_mismatch. {
- ret ~"returning function used where non-returning function" +
- ~" was expected";
+ ret "returning function used where non-returning function" +
+ " was expected";
}
- terr_box_mutability. { ret ~"boxed values differ in mutability"; }
- terr_vec_mutability. { ret ~"vectors differ in mutability"; }
+ terr_box_mutability. { ret "boxed values differ in mutability"; }
+ 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";
+ ret "expected a tuple with " + uint::to_str(e_sz, 10u) +
+ " 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) +
- ~" fields but found one with " +
- uint::to_str(a_sz, 10u) +
- ~" fields";
+ ret "expected a record with " + uint::to_str(e_sz, 10u) +
+ " fields but found one with " + uint::to_str(a_sz, 10u) +
+ " fields";
}
- terr_record_mutability. { ret ~"record elements differ in mutability"; }
+ terr_record_mutability. { ret "record elements differ in mutability"; }
terr_record_fields(e_fld, a_fld) {
- ret ~"expected a record with field '" + e_fld +
- ~"' but found one with field '" + a_fld + ~"'";
+ ret "expected a record with field '" + e_fld +
+ "' but found one with field '" + a_fld + "'";
}
- terr_arg_count. { ret ~"incorrect number of function parameters"; }
- terr_meth_count. { ret ~"incorrect number of object methods"; }
+ terr_arg_count. { ret "incorrect number of function parameters"; }
+ terr_meth_count. { ret "incorrect number of object methods"; }
terr_obj_meths(e_meth, a_meth) {
- ret ~"expected an obj with method '" + e_meth +
- ~"' but found one with method '" + a_meth + ~"'";
+ ret "expected an obj with method '" + e_meth +
+ "' but found one with method '" + a_meth + "'";
}
terr_mode_mismatch(e_mode, a_mode) {
- ret ~"expected argument mode " + mode_str_1(e_mode) + ~" but found " +
+ ret "expected argument mode " + mode_str_1(e_mode) + " but found " +
mode_str_1(a_mode);
}
terr_constr_len(e_len, a_len) {
- ret ~"Expected a type with " +
- uint::str(e_len) +
- ~" constraints, but found one with " +
- uint::str(a_len) + ~" constraints";
+ ret "Expected a type with " + uint::str(e_len) +
+ " constraints, but found one with " + uint::str(a_len) +
+ " constraints";
}
terr_constr_mismatch(e_constr, a_constr) {
- ret ~"Expected a type with constraint " + ty_constr_to_str(e_constr) +
- ~" but found one with constraint " +
- ty_constr_to_str(a_constr);
+ ret "Expected a type with constraint " + ty_constr_to_str(e_constr) +
+ " but found one with constraint " +
+ ty_constr_to_str(a_constr);
}
}
}
if index < vec::len(*param_var_ids) {
ret mk_var(cx, param_var_ids[index]);
} else {
- cx.sess.span_fatal(
- sp, ~"Unbound type parameter in callee's type");
+ cx.sess.span_fatal(sp, "Unbound type parameter in callee's type");
}
}
let new_typ =
let item =
alt cx.items.find(id.node) {
some(i) { i }
- none. { cx.sess.bug(~"expected to find cached node_item") }
+ none. { cx.sess.bug("expected to find cached node_item") }
};
alt item {
ast_map::node_item(item) {
if def_eq(variant.id, variant_id) { ret variant; }
i += 1u;
}
- cx.sess.bug(~"tag_variant_with_id(): no variant exists with that ID");
+ cx.sess.bug("tag_variant_with_id(): no variant exists with that ID");
}
ty::ty_fn(_, _, ret_ty, _, _) { ret ret_ty; }
ty::ty_native_fn(_, _, ret_ty) { ret ret_ty; }
_ {
- cx.sess.bug(~"ret_ty_of_fn_ty() called on non-function type: " +
- ty_to_str(cx, a_ty));
+ cx.sess.bug("ret_ty_of_fn_ty() called on non-function type: " +
+ ty_to_str(cx, a_ty));
}
}
}
/*. add, shift, bit
. sub, rel, logic
. mult, eq, */
- /*other*/
- /*bool*/
- /*int*/
- /*float*/
- /*str*/
- /*vec*/
- /*bot*/
+ /*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],
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");
}
}
}
some(x) { x }
_ {
fcx.ccx.tcx.sess.span_fatal(sp,
- ~"internal error looking up a local var")
+ "internal error looking up a local var")
}
}
}
some(x) { x }
_ {
fcx.ccx.tcx.sess.span_fatal(sp,
- ~"internal error looking up a definition")
+ "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" }
+ _ { "local" }
}; // FIXME DESTR
}
ret {kinds: no_kinds, ty: ty::mk_nil(fcx.ccx.tcx)};
}
ast::def_ty(_) {
- fcx.ccx.tcx.sess.span_fatal(sp, ~"expected value but found type");
+ fcx.ccx.tcx.sess.span_fatal(sp, "expected value but found type");
}
ast::def_upvar(_, inner, _) {
ret ty_param_kinds_and_ty_for_def(fcx, sp, *inner);
}
_ {
// FIXME: handle other names.
- fcx.ccx.tcx.sess.unimpl(~"definition variant");
+ fcx.ccx.tcx.sess.unimpl("definition variant");
}
}
}
if param_var_len == 0u {
fcx.ccx.tcx.sess.span_fatal(
sp,
- ~"this item does not take type parameters");
+ "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");
+ "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");
+ "not enough type parameters provided for this item");
}
let ty_substs: [ty::t] = [];
let i = 0u;
ty_substs_opt = some::<[ty::t]>(ty_substs);
if ty_param_count == 0u {
fcx.ccx.tcx.sess.span_fatal(sp,
- ~"this item does not take type \
+ "this item does not take type \
parameters");
}
} else {
fix_err(_) {
fcx.ccx.tcx.sess.span_fatal(
sp,
- ~"the type of this value must be known in this context");
+ "the type of this value must be known in this context");
}
}
}
some(some(ty)) { ret ty; }
some(none.) {
tcx.sess.span_fatal(ast_ty.span,
- ~"illegal recursive type \
+ "illegal recursive type \
insert a tag in the cycle, \
if this is desired)");
}
}
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 \
+ "Wrong number of type arguments for a \
polymorphic type");
}
let typ =
ret typ;
}
let typ;
- let cname = none::<istr>;
+ let cname = none::<str>;
alt ast_ty.node {
ast::ty_nil. { typ = ty::mk_nil(tcx); }
ast::ty_bot. { typ = ty::mk_bot(tcx); }
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");
+ "found type name used as a variable");
}
_ {
- tcx.sess.span_fatal(
- ast_ty.span, ~"internal error in instantiate");
+ tcx.sess.span_fatal(ast_ty.span, "internal error in instantiate");
}
}
cname = some(path_to_str(path));
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 {
none. {/* no-op */ }
- some(cname_str) {
- typ = ty::rename(tcx, typ, cname_str);
- }
+ some(cname_str) { typ = ty::rename(tcx, typ, cname_str); }
}
tcx.ast_ty_to_ty_cache.insert(ast_ty, some(typ));
ret typ;
some(ast_map::node_native_item(native_item)) {
tpt = ty_of_native_item(cx, native_item, ast::native_abi_cdecl);
}
- _ {
- cx.tcx.sess.fatal(
- ~"internal error " + std::int::str(id.node));
- }
+ _ { cx.tcx.sess.fatal("internal error " + std::int::str(id.node)); }
}
ret tpt;
}
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()});
+ bind convert_native(cx, abi, _)
+ with
+ *visit::default_simple_visitor()});
visit::visit_crate(*crate, (), visit);
}
}
ty::t {
full(fcx, sp, expected, actual, [], false).ty
}
- fn block_coerce(fcx: &@fn_ctxt, sp: &span, expected: ty::t,
- actual: ty::t) -> ty::t {
+ 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 {
+ 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 {
full(fcx, sp, expected, actual, ty_param_substs_0, false)
}
ures_err(err) {
let e_err = resolve_type_vars_if_possible(fcx, expected);
let a_err = resolve_type_vars_if_possible(fcx, actual);
- fcx.ccx.tcx.sess.span_err(
- sp,
- ~"mismatched types: expected " +
- ty_to_str(fcx.ccx.tcx, e_err) +
- ~" but found " +
- ty_to_str(fcx.ccx.tcx, a_err) + ~" ("
- + ty::type_err_to_str(err)
- + ~")");
+ fcx.ccx.tcx.sess.span_err(sp,
+ "mismatched types: expected " +
+ ty_to_str(fcx.ccx.tcx, e_err) +
+ " but found " +
+ ty_to_str(fcx.ccx.tcx, a_err) + " ("
+ + ty::type_err_to_str(err) + ")");
ret mk_result(fcx, expected, ty_param_subst_var_ids);
}
}
fix_ok(new_type) { ret some(new_type); }
fix_err(vid) {
fcx.ccx.tcx.sess.span_err(sp,
- ~"cannot determine a type \
+ "cannot determine a type \
for this expression");
ret none;
}
resolve_type_vars_for_node(wbcx, e.span, input.id);
}
}
- _ {}
+ _ { }
}
visit::visit_expr(e, wbcx, v);
}
fix_ok(lty) { write::ty_only(wbcx.fcx.ccx.tcx, l.node.id, lty); }
fix_err(_) {
wbcx.fcx.ccx.tcx.sess.span_err(l.span,
- ~"cannot determine a type \
+ "cannot determine a type \
for this local variable");
wbcx.success = false;
}
#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" }];
- fcx.ccx.tcx.sess.span_fatal(
- pat.span, s);
+ if subpats_len == 1u { "" } else { "s" },
+ arg_len, if arg_len == 1u { "" } else { "s" }];
+ fcx.ccx.tcx.sess.span_fatal(pat.span, s);
}
// TODO: vec::iter2
#fmt["this pattern has %u field%s, \
but the corresponding \
variant has no fields",
- subpats_len,
- if subpats_len == 1u {
- ~""
- } else { ~"s" }]);
+ subpats_len,
+ if subpats_len == 1u {
+ ""
+ } else { "s" }]);
}
write::ty_fixup(fcx, pat.id, path_tpot);
}
fcx.ccx.tcx.sess.span_fatal(
pat.span,
#fmt["mismatched types: expected %s, found tag",
- ty_to_str(fcx.ccx.tcx, expected)]);
+ ty_to_str(fcx.ccx.tcx,
+ expected)]);
}
}
write::ty_fixup(fcx, pat.id, path_tpot);
fcx.ccx.tcx.sess.span_fatal(
pat.span,
#fmt["mismatched types: expected %s, found record",
- ty_to_str(fcx.ccx.tcx, expected)]);
+ ty_to_str(fcx.ccx.tcx,
+ expected)]);
}
}
let f_count = vec::len(fields);
#fmt["mismatched types: expected a record \
with %u fields, found one with %u \
fields",
- ex_f_count, f_count]);
+ ex_f_count, f_count]);
}
- fn matches(name: &istr, f: &ty::field) -> bool {
+ fn matches(name: &str, f: &ty::field) -> bool {
ret str::eq(name, f.ident);
}
for f: ast::field_pat in fields {
fcx.ccx.tcx.sess.span_fatal(
pat.span,
#fmt["mismatched types: expected %s, found tuple",
- ty_to_str(fcx.ccx.tcx, expected)]);
+ ty_to_str(fcx.ccx.tcx,
+ expected)]);
}
}
let e_count = vec::len(elts);
#fmt["mismatched types: expected a tuple \
with %u fields, found one with %u \
fields",
- vec::len(ex_elts), e_count]);
+ vec::len(ex_elts), e_count]);
}
let i = 0u;
for elt in elts { check_pat(fcx, map, elt, ex_elts[i]); i += 1u; }
write::ty_only_fixup(fcx, pat.id, expected);
}
_ {
- fcx.ccx.tcx.sess.span_fatal(
- pat.span,
- ~"mismatched types: expected " +
- ty_to_str(fcx.ccx.tcx, expected) +
- ~" found box");
+ fcx.ccx.tcx.sess.span_fatal(pat.span,
+ "mismatched types: expected " +
+ ty_to_str(fcx.ccx.tcx, expected) +
+ " found box");
}
}
}
alt f_purity {
ast::impure_fn. { ret; }
ast::pure_fn. {
- sess.span_fatal(sp, ~"Found impure expression in pure function decl");
+ sess.span_fatal(sp, "Found impure expression in pure function decl");
}
}
}
_ {
ccx.tcx.sess.span_fatal(
sp,
- ~"Pure function calls function not known to be pure");
+ "Pure function calls function not known to be pure");
}
}
}
if call_kind != kind_for_each {
fcx.ccx.tcx.sess.span_err(
sp,
- ~"calling iter outside of for each loop");
+ "calling iter outside of for each loop");
}
}
_ {
if call_kind == kind_for_each {
fcx.ccx.tcx.sess.span_err(
sp,
- ~"calling non-iter as sequence of for each loop");
+ "calling non-iter as sequence of for each loop");
}
}
}
arg_tys
}
_ {
- fcx.ccx.tcx.sess.span_fatal(
- f.span,
- ~"mismatched types: \
+ 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))
}
};
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: build an arguments list with dummy arguments to
// check against
let dummy = {mode: ty::mo_val, ty: ty::mk_bot(fcx.ccx.tcx)};
let binopstr = ast_util::binop_to_str(binop);
let t_str = ty_to_str(fcx.ccx.tcx, resolved_t);
let errmsg =
- ~"binary operation " + binopstr +
- ~" cannot be applied to type `" +
- t_str + ~"`";
+ "binary operation " + binopstr +
+ " cannot be applied to type `" + t_str + "`";
fcx.ccx.tcx.sess.span_err(span, errmsg);
}
}
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");
+ "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::ty_ptr(inner) { oper_t = inner.ty; }
_ {
- tcx.sess.span_fatal(
- expr.span,
- ~"dereferencing non-" +
- ~"dereferenceable type: " +
- ty_to_str(tcx, oper_t));
+ tcx.sess.span_fatal(expr.span,
+ "dereferencing non-" +
+ "dereferenceable type: " +
+ ty_to_str(tcx, oper_t));
}
}
}
ast::not. {
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 \
+ tcx.sess.span_err(expr.span,
+ #fmt["mismatched types: expected bool \
or integer but found %s",
- ty_to_str(tcx, oper_t)]);
+ ty_to_str(tcx, oper_t)]);
}
}
ast::neg. {
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 \
+ "applying unary minus to \
non-numeric type "
- + ty_to_str(tcx, oper_t));
+ + ty_to_str(tcx, oper_t));
}
}
}
// supplied some, that's an error.
if vec::len::<@ast::ty>(pth.node.types) > 0u {
tcx.sess.span_fatal(expr.span,
- ~"this kind of value does not \
+ "this kind of value does not \
take type parameters");
}
write::ty_only_fixup(fcx, id, tpt.ty);
}
}
- ast::expr_mac(_) { tcx.sess.bug(~"unexpanded macro"); }
+ ast::expr_mac(_) { tcx.sess.bug("unexpanded macro"); }
ast::expr_fail(expr_opt) {
bot = true;
alt expr_opt {
none. {/* do nothing */ }
- some(e) {
- check_expr_with(fcx, e, ty::mk_istr(tcx));
- }
+ some(e) { check_expr_with(fcx, e, ty::mk_istr(tcx)); }
}
write::bot_ty(tcx, id);
}
let nil = ty::mk_nil(tcx);
if !are_compatible(fcx, fcx.ret_ty, nil) {
tcx.sess.span_err(expr.span,
- ~"ret; in function returning non-nil");
+ "ret; in function returning non-nil");
}
}
some(e) { check_expr_with(fcx, e, fcx.ret_ty); }
ast::expr_put(expr_opt) {
require_impure(tcx.sess, fcx.purity, expr.span);
if fcx.proto != ast::proto_iter {
- tcx.sess.span_err(expr.span, ~"put in non-iterator");
+ tcx.sess.span_err(expr.span, "put in non-iterator");
}
alt expr_opt {
none. {
let nil = ty::mk_nil(tcx);
if !are_compatible(fcx, fcx.ret_ty, nil) {
tcx.sess.span_err(expr.span,
- ~"put; in iterator yielding non-nil");
+ "put; in iterator yielding non-nil");
}
}
some(e) { bot = check_expr_with(fcx, e, fcx.ret_ty); }
_ {
tcx.sess.span_fatal(
expr.span,
- ~"mismatched types: expected vector or string but "
- + ~"found " + ty_to_str(tcx, ety));
+ "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);
}
_ {
tcx.sess.span_fatal(expr.span,
- ~"sequence in for each loop not a call");
+ "sequence in for each loop not a call");
}
}
bot |= check_for_or_for_each(fcx, decl, expr_ty(tcx, seq), body, id);
let arm_non_bot = false;
for arm: ast::arm in arms {
alt arm.guard {
- some(e) {
- check_expr_with(fcx, e, ty::mk_bool(tcx));
- }
- none. {}
+ some(e) { check_expr_with(fcx, e, ty::mk_bool(tcx)); }
+ none. { }
}
if !check_block(fcx, arm.body) { arm_non_bot = true; }
let bty = block_ty(tcx, arm.body);
}
ast::expr_block(b) {
// If this is an unchecked block, turn off purity-checking
- let fcx_for_block = alt b.node.rules {
- ast::unchecked. { @{ purity: ast::impure_fn with *fcx } }
- _ { fcx }
- };
+ let fcx_for_block =
+ alt b.node.rules {
+ ast::unchecked. { @{purity: ast::impure_fn with *fcx} }
+ _ { fcx }
+ };
bot = check_block(fcx_for_block, b);
let typ =
alt b.node.expr {
this_obj_sty = some(structure_of(fcx, expr.span, tpt.ty));
}
none. {
- tcx.sess.bug(~"didn't find " +
- int::str(did.node) +
- ~" in type cache");
+ tcx.sess.bug("didn't find " + int::str(did.node) +
+ " in type cache");
}
}
}
}
none. {
// Shouldn't happen.
- tcx.sess.span_err(expr.span, ~"self-call in non-object context");
+ tcx.sess.span_err(expr.span, "self-call in non-object context");
}
}
if !(type_is_scalar(fcx, expr.span, expr_ty(tcx, e)) &&
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));
+ "non-scalar cast: " +
+ ty_to_str(tcx, expr_ty(tcx, e)) + " as " +
+ ty_to_str(tcx, t_1));
}
write::ty_only_fixup(fcx, id, t_1);
}
ty::ty_rec(flds) { base_fields = flds; }
_ {
tcx.sess.span_fatal(expr.span,
- ~"record update has non-record base");
+ "record update has non-record base");
}
}
write::ty_only_fixup(fcx, id, bexpr_t);
}
if !found {
tcx.sess.span_fatal(f.span,
- ~"unknown field in record update: " +
- f.node.ident);
+ "unknown field in record update: " +
+ f.node.ident);
}
}
}
ty::ty_rec(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");
+ tcx.sess.span_fatal(expr.span, "bad index on record");
}
write::ty_only_fixup(fcx, id, fields[ix].mt.ty);
}
let ix: uint =
ty::method_idx(tcx.sess, expr.span, field, methods);
if ix >= vec::len::<ty::method>(methods) {
- tcx.sess.span_fatal(expr.span, ~"bad index on obj");
+ tcx.sess.span_fatal(expr.span, "bad index on obj");
}
let meth = methods[ix];
let t =
let idx_t = expr_ty(tcx, idx);
if !type_is_integral(fcx, idx.span, idx_t) {
tcx.sess.span_err(idx.span,
- ~"mismatched types: expected \
+ "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));
+ "vector-indexing bad type: " +
+ ty_to_str(tcx, base_t));
}
}
}
// The user is trying to extend a non-object.
tcx.sess.span_fatal(
e.span,
- syntax::print::pprust::expr_to_str(e)
+ syntax::print::pprust::expr_to_str(e)
+
- ~" does not have object type");
+ " does not have object type");
}
}
}
if new_type != m {
ccx.tcx.sess.span_fatal(
om.span,
- ~"Attempted to override method "
+ "Attempted to override method "
+ m.ident +
- ~" with one of a different type");
+ " with one of a different type");
}
ret none;
}
check_expr_with(fcx, x, t);
write::ty_only_fixup(fcx, id, ty::mk_uniq(tcx, t));
}
- _ { tcx.sess.unimpl(~"expr type in typeck::check_expr"); }
+ _ { tcx.sess.unimpl("expr type in typeck::check_expr"); }
}
if bot { write::ty_only_fixup(fcx, expr.id, ty::mk_bot(tcx)); }
alt fcx.locals.find(local.node.id) {
none. {
- fcx.ccx.tcx.sess.bug(~"check_decl_local: local id not found " +
- ident_for_local(local));
+ fcx.ccx.tcx.sess.bug("check_decl_local: local id not found " +
+ ident_for_local(local));
}
some(i) {
let t = ty::mk_var(fcx.ccx.tcx, i);
}
_ { false }
} {
- fcx.ccx.tcx.sess.span_warn(s.span, ~"unreachable statement");
+ fcx.ccx.tcx.sess.span_warn(s.span, "unreachable statement");
warned = true;
}
bot |= check_stmt(fcx, s);
none. { write::nil_ty(fcx.ccx.tcx, blk.node.id); }
some(e) {
if bot && !warned {
- fcx.ccx.tcx.sess.span_warn(e.span, ~"unreachable expression");
+ fcx.ccx.tcx.sess.span_warn(e.span, "unreachable expression");
}
bot |= check_expr(fcx, e);
let ety = expr_ty(fcx.ccx.tcx, e);
alt e.node {
ast::expr_call(operator, operands) {
if !ty::is_pred_ty(fcx.ccx.tcx, expr_ty(fcx.ccx.tcx, operator)) {
- fcx.ccx.tcx.sess.span_fatal(operator.span,
- ~"Operator in constraint has non-boolean return type");
+ fcx.ccx.tcx.sess.span_fatal(
+ operator.span,
+ "Operator in constraint has non-boolean return type");
}
alt operator.node {
}
_ {
fcx.ccx.tcx.sess.span_fatal(operator.span,
- ~"Impure function as operator \
+ "Impure function as operator \
in constraint");
}
}
for operand: @ast::expr in operands {
if !ast_util::is_constraint_arg(operand) {
let s =
- ~"Constraint args must be \
+ "Constraint args must be \
slot variables or literals";
fcx.ccx.tcx.sess.span_fatal(e.span, s);
}
}
_ {
let s =
- ~"In a constraint, expected the \
+ "In a constraint, expected the \
constraint name to be an explicit name";
fcx.ccx.tcx.sess.span_fatal(e.span, s);
}
}
}
- _ { fcx.ccx.tcx.sess.span_fatal(
- e.span, ~"check on non-predicate"); }
+ _ { fcx.ccx.tcx.sess.span_fatal(e.span, "check on non-predicate"); }
}
ret bot;
}
-fn check_constraints(fcx: &@fn_ctxt, cs: [@ast::constr], args:[ast::arg]) {
+fn check_constraints(fcx: &@fn_ctxt, cs: [@ast::constr], args: [ast::arg]) {
let c_args;
let num_args = vec::len(args);
for c: @ast::constr in cs {
c_args = [];
for a: @spanned<ast::fn_constr_arg> in c.node.args {
- c_args += [@(alt a.node {
- ast::carg_base. {
- // "base" should not occur in a fn type thing, as of
- // yet, b/c we don't allow constraints on the return type
-
- fcx.ccx.tcx.sess.span_bug(a.span, ~"check_constraints:\
+ c_args +=
+ [
+ // "base" should not occur in a fn type thing, as of
+ // yet, b/c we don't allow constraints on the return type
+
+ // Works b/c no higher-order polymorphism
+ /*
+ This is kludgy, and we probably shouldn't be assigning
+ node IDs here, but we're creating exprs that are
+ ephemeral, just for the purposes of typechecking. So
+ that's my justification.
+ */
+ @alt a.node {
+ ast::carg_base. {
+ fcx.ccx.tcx.sess.span_bug(a.span,
+ "check_constraints:\
unexpected carg_base");
- }
- ast::carg_lit(l) {
- let tmp_node_id = fcx.ccx.tcx.sess.next_node_id();
- {id:tmp_node_id, node: ast::expr_lit(l), span:a.span} }
- ast::carg_ident(i) {
- if i < num_args {
- let p : ast::path_ =
- {global:false, idents:[(args[i]).ident],
- // Works b/c no higher-order polymorphism
- types:[]};
- /*
- This is kludgy, and we probably shouldn't be assigning
- node IDs here, but we're creating exprs that are
- ephemeral, just for the purposes of typechecking. So
- that's my justification.
- */
- let arg_occ_node_id = fcx.ccx.tcx.sess.next_node_id();
- fcx.ccx.tcx.def_map.insert
- (arg_occ_node_id, ast::def_arg(local_def(args[i].id),
- args[i].mode));
- {id:arg_occ_node_id,
- node: ast::expr_path(respan(a.span, p)),
- span:a.span}
- }
- else {
- fcx.ccx.tcx.sess.span_bug(a.span, ~"check_constraints:\
+ }
+ ast::carg_lit(l) {
+ let tmp_node_id = fcx.ccx.tcx.sess.next_node_id();
+ {id: tmp_node_id, node: ast::expr_lit(l), span: a.span}
+ }
+ ast::carg_ident(i) {
+ if i < num_args {
+ let p: ast::path_ =
+ {global: false,
+ idents: [args[i].ident],
+ types: []};
+ let arg_occ_node_id =
+ fcx.ccx.tcx.sess.next_node_id();
+ fcx.ccx.tcx.def_map.insert(
+ arg_occ_node_id,
+ ast::def_arg(local_def(args[i].id),
+ args[i].mode));
+ {id: arg_occ_node_id,
+ node: ast::expr_path(respan(a.span, p)),
+ span: a.span}
+ } else {
+ fcx.ccx.tcx.sess.span_bug(a.span,
+ "check_constraints:\
carg_ident index out of bounds");
- }
- }
- })]
+ }
+ }
+ }]
}
let p_op: ast::expr_ = ast::expr_path(c.node.path);
- let oper: @ast::expr = @{id:c.node.id,
- node: p_op, span:c.span};
+ let oper: @ast::expr = @{id: c.node.id, node: p_op, span: c.span};
// Another ephemeral expr
let call_expr_id = fcx.ccx.tcx.sess.next_node_id();
- let call_expr = @{id: call_expr_id,
- node: ast::expr_call(oper, c_args),
- span: c.span};
+ let call_expr =
+ @{id: call_expr_id,
+ node: ast::expr_call(oper, c_args),
+ span: c.span};
check_pred_expr(fcx, call_expr);
}
}
// 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.
- alt (body.node.expr) {
+ alt body.node.expr {
some(tail_expr) {
if f.proto != ast::proto_iter {
let tail_expr_ty = expr_ty(ccx.tcx, tail_expr);
demand::simple(fcx, tail_expr.span, fcx.ret_ty, tail_expr_ty);
}
}
- none. {}
+ none. { }
}
let args = ty::ty_fn_args(ccx.tcx, ty::node_id_to_type(ccx.tcx, id));
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));
+ "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));
+ "main has a non-function type: found" +
+ ty_to_str(tcx, main_t));
}
}
}
if !tcx.sess.get_opts().library {
alt tcx.sess.get_main_id() {
some(id) { check_main_fn_ty(tcx, id); }
- none. { tcx.sess.span_err(crate.span, ~"main function not found"); }
+ none. { tcx.sess.span_err(crate.span, "main function not found"); }
}
}
}
type spanned<T> = {node: T, span: span};
-type ident = istr;
+type ident = str;
// Functions may or may not have names.
type fn_ident = option::t<ident>;
def_use(def_id);
def_native_ty(def_id);
def_native_fn(def_id);
- def_upvar(def_id, @def, bool /* writable */);
+ def_upvar(def_id, @def, /* writable */bool);
}
// The set of meta_items that define the compilation environment of the crate,
type blk = spanned<blk_>;
-type blk_ = {stmts: [@stmt], expr: option::t<@expr>,
- id: node_id, rules: check_mode};
+type blk_ =
+ {stmts: [@stmt], expr: option::t<@expr>, id: node_id, rules: check_mode};
type pat = {id: node_id, node: pat_, span: span};
type mac = spanned<mac_>;
tag mac_ {
- mac_invoc(path, @expr, option::t<istr>);
+ mac_invoc(path, @expr, option::t<str>);
mac_embed_type(@ty);
mac_embed_block(blk);
mac_ellipsis;
type lit = spanned<lit_>;
tag lit_ {
- lit_str(istr);
+ lit_str(str);
lit_char(char);
lit_int(int);
lit_uint(uint);
lit_mach_int(ty_mach, int);
- lit_float(istr);
- lit_mach_float(ty_mach, istr);
+ lit_float(str);
+ lit_mach_float(ty_mach, str);
lit_nil;
lit_bool(bool);
}
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. */
noreturn; // functions with return type _|_ that always
// raise an error or exit (i.e. never return to the caller)
+
return; // everything else
}
}
type native_mod =
- {native_name: istr,
+ {native_name: str,
abi: native_abi,
view_items: [@view_item],
items: [@native_item]};
item_tag([variant], [ty_param]);
item_obj(_obj, [ty_param], /* constructor id */node_id);
item_res(_fn,
- /* dtor */
+
+ /* dtor */
node_id,
- /* dtor id */
+
+ /* dtor id */
[ty_param],
/* ctor id */
tag native_item_ {
native_item_ty;
- native_item_fn(option::t<istr>, fn_decl, [ty_param]);
+ native_item_fn(option::t<str>, fn_decl, [ty_param]);
}
//
// make this a const, once the compiler supports it
fn dummy_sp() -> span { ret mk_sp(0u, 0u); }
-fn path_name(p: &path) -> istr { path_name_i(p.node.idents) }
+fn path_name(p: &path) -> str { path_name_i(p.node.idents) }
-fn path_name_i(idents: &[ident]) -> istr {
- str::connect(idents, ~"::")
-}
+fn path_name_i(idents: &[ident]) -> str { str::connect(idents, "::") }
fn local_def(id: node_id) -> def_id { ret {crate: local_crate, node: id}; }
}
}
-type pat_id_map = std::map::hashmap<istr, node_id>;
+type pat_id_map = std::map::hashmap<str, node_id>;
// This is used because same-named variables in alternative patterns need to
// use the node_id of their namesake in the first pattern.
ret found;
}
-fn binop_to_str(op: binop) -> istr {
+fn binop_to_str(op: binop) -> str {
alt op {
- add. { ret ~"+"; }
- sub. { ret ~"-"; }
- mul. { ret ~"*"; }
- div. { ret ~"/"; }
- rem. { ret ~"%"; }
- and. { ret ~"&&"; }
- or. { ret ~"||"; }
- bitxor. { ret ~"^"; }
- bitand. { ret ~"&"; }
- bitor. { ret ~"|"; }
- lsl. { ret ~"<<"; }
- lsr. { ret ~">>"; }
- asr. { ret ~">>>"; }
- eq. { ret ~"=="; }
- lt. { ret ~"<"; }
- le. { ret ~"<="; }
- ne. { ret ~"!="; }
- ge. { ret ~">="; }
- gt. { ret ~">"; }
+ add. { ret "+"; }
+ sub. { ret "-"; }
+ mul. { ret "*"; }
+ div. { ret "/"; }
+ rem. { ret "%"; }
+ and. { ret "&&"; }
+ or. { ret "||"; }
+ bitxor. { ret "^"; }
+ bitand. { ret "&"; }
+ bitor. { ret "|"; }
+ lsl. { ret "<<"; }
+ lsr. { ret ">>"; }
+ asr. { ret ">>>"; }
+ eq. { ret "=="; }
+ lt. { ret "<"; }
+ le. { ret "<="; }
+ ne. { ret "!="; }
+ ge. { ret ">="; }
+ gt. { ret ">"; }
}
}
alt b { and. { true } or. { true } _ { false } }
}
-fn unop_to_str(op: unop) -> istr {
+fn unop_to_str(op: unop) -> str {
alt op {
- box(mt) { if mt == mut { ret ~"@mutable "; } ret ~"@"; }
- deref. { ret ~"*"; }
- not. { ret ~"!"; }
- neg. { ret ~"-"; }
+ box(mt) { if mt == mut { ret "@mutable "; } ret "@"; }
+ deref. { ret "*"; }
+ not. { ret "!"; }
+ neg. { ret "-"; }
}
}
ret alt e.node { expr_path(_) { true } _ { false } };
}
-fn ty_mach_to_str(tm: ty_mach) -> istr {
+fn ty_mach_to_str(tm: ty_mach) -> str {
alt tm {
- ty_u8. { ret ~"u8"; }
- ty_u16. { ret ~"u16"; }
- ty_u32. { ret ~"u32"; }
- ty_u64. { ret ~"u64"; }
- ty_i8. { ret ~"i8"; }
- ty_i16. { ret ~"i16"; }
- ty_i32. { ret ~"i32"; }
- ty_i64. { ret ~"i64"; }
- ty_f32. { ret ~"f32"; }
- ty_f64. { ret ~"f64"; }
+ ty_u8. { ret "u8"; }
+ ty_u16. { ret "u16"; }
+ ty_u32. { ret "u32"; }
+ ty_u64. { ret "u64"; }
+ ty_i8. { ret "i8"; }
+ ty_i16. { ret "i16"; }
+ ty_i32. { ret "i32"; }
+ ty_i64. { ret "i64"; }
+ ty_f32. { ret "f32"; }
+ ty_f64. { ret "f64"; }
}
}
ret {node: blk_, span: e.span};
}
-fn checked_blk(stmts1: [@stmt], expr1: option::t<@expr>, id1: node_id)
- -> blk_ {
+fn checked_blk(stmts1: [@stmt], expr1: option::t<@expr>, id1: node_id) ->
+ blk_ {
ret {stmts: stmts1, expr: expr1, id: id1, rules: checked};
}
import std::option::some;
import std::option::none;
-type filename = istr;
+type filename = str;
type file_pos = {ch: uint, byte: uint};
}
tag opt_span {
- //hack (as opposed to option::t), to make `span` compile
+
+ //hack (as opposed to option::t), to make `span` compile
os_none;
os_some(@span);
}
type span = {lo: uint, hi: uint, expanded_from: opt_span};
-fn span_to_str(sp: &span, cm: &codemap) -> istr {
+fn span_to_str(sp: &span, cm: &codemap) -> str {
let cur = sp;
- let res = ~"";
+ let res = "";
let prev_file = none;
while true {
let lo = lookup_char_pos(cm, cur.lo);
res +=
#fmt["%s:%u:%u: %u:%u",
if some(lo.filename) == prev_file {
- ~"-"
- } else {
- lo.filename
- }, lo.line, lo.col, hi.line, hi.col];
+ "-"
+ } else { lo.filename }, lo.line, lo.col, hi.line, hi.col];
alt cur.expanded_from {
os_none. { break; }
os_some(new_sp) {
cur = *new_sp;
prev_file = some(lo.filename);
- res += ~"<<";
+ res += "<<";
}
}
}
ret res;
}
-fn emit_diagnostic(sp: &option::t<span>, msg: &istr, kind: &istr, color: u8,
+fn emit_diagnostic(sp: &option::t<span>, msg: &str, kind: &str, color: u8,
cm: &codemap) {
- let ss = ~"";
+ let ss = "";
let maybe_lines: option::t<@file_lines> = none;
alt sp {
some(ssp) {
- ss = span_to_str(ssp, cm) + ~" ";
+ ss = span_to_str(ssp, cm) + " ";
maybe_lines = some(span_to_lines(ssp, cm));
}
none. { }
if term::color_supported() {
term::fg(io::stdout().get_buf_writer(), color);
}
- io::stdout().write_str(#fmt[~"%s:", kind]);
+ 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\n", msg]);
maybe_highlight_lines(sp, cm, maybe_lines);
}
some(lines) {
// If we're not looking at a real file then we can't re-open it to
// pull out the lines
- if lines.name == ~"-" { ret; }
+ if lines.name == "-" { ret; }
// FIXME: reading in the entire file is the worst possible way to
// get access to the necessary 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"; }
+ 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 s = #fmt["%s:%u ", fm.name, last_line + 1u];
let indent = str::char_len(s);
- let out = ~"";
- while indent > 0u { out += ~" "; indent -= 1u; }
- out += ~"...\n";
+ let out = "";
+ while indent > 0u { out += " "; indent -= 1u; }
+ out += "...\n";
io::stdout().write_str(out);
}
// indent past |name:## | and the 0-offset column location
let left = str::char_len(fm.name) + digits + lo.col + 3u;
- let s = ~"";
+ let s = "";
while left > 0u { str::push_char(s, ' '); left -= 1u; }
- s += ~"^";
+ s += "^";
let hi = lookup_char_pos(cm, option::get(sp).hi);
if hi.col != lo.col {
// the ^ already takes up one space
let width = hi.col - lo.col - 1u;
while width > 0u { str::push_char(s, '~'); width -= 1u; }
}
- io::stdout().write_str(s + ~"\n");
+ io::stdout().write_str(s + "\n");
}
}
_ { }
}
}
-fn emit_warning(sp: &option::t<span>, msg: &istr, cm: &codemap) {
- emit_diagnostic(sp, msg, ~"warning", 11u8, cm);
+fn emit_warning(sp: &option::t<span>, msg: &str, cm: &codemap) {
+ emit_diagnostic(sp, msg, "warning", 11u8, cm);
}
-fn emit_error(sp: &option::t<span>, msg: &istr, cm: &codemap) {
- emit_diagnostic(sp, msg, ~"error", 9u8, cm);
+fn emit_error(sp: &option::t<span>, msg: &str, cm: &codemap) {
+ emit_diagnostic(sp, msg, "error", 9u8, cm);
}
-fn emit_note(sp: &option::t<span>, msg: &istr, cm: &codemap) {
- emit_diagnostic(sp, msg, ~"note", 10u8, cm);
+fn emit_note(sp: &option::t<span>, msg: &str, cm: &codemap) {
+ emit_diagnostic(sp, msg, "note", 10u8, cm);
}
-type file_lines = {name: istr, lines: [uint]};
+type file_lines = {name: str, lines: [uint]};
fn span_to_lines(sp: span, cm: codemap::codemap) -> @file_lines {
let lo = lookup_char_pos(cm, sp.lo);
ret @{name: lo.filename, lines: lines};
}
-fn get_line(fm: filemap, line: int, file: &istr) -> istr {
+fn get_line(fm: filemap, line: int, file: &str) -> str {
let begin: uint = fm.lines[line].byte - fm.start_pos.byte;
let end: uint;
if line as uint < vec::len(fm.lines) - 1u {
ret str::slice(file, begin, end);
}
-fn get_filemap(cm: codemap, filename: istr) -> filemap {
- for fm: filemap in cm.files {
- if fm.name == filename { ret fm; }
- }
+fn get_filemap(cm: codemap, filename: str) -> filemap {
+ for fm: filemap in cm.files { if fm.name == filename { ret fm; } }
//XXjdm the following triggers a mismatched type bug
// (or expected function, found _|_)
fail; // ("asking for " + filename + " which we don't know about");
import codemap;
type syntax_expander =
- fn(&ext_ctxt, span, @ast::expr, &option::t<istr>) -> @ast::expr;
-type macro_def = {ident: istr, ext: syntax_extension};
+ 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<istr>) -> macro_def;
+ fn(&ext_ctxt, span, @ast::expr, &option::t<str>) -> macro_def;
tag syntax_extension {
normal(syntax_expander);
// A temporary hard-coded map of methods for expanding syntax extension
// AST nodes into full ASTs
-fn syntax_expander_table() -> hashmap<istr, syntax_extension> {
+fn syntax_expander_table() -> hashmap<str, syntax_extension> {
let syntax_expanders = new_str_hash::<syntax_extension>();
- syntax_expanders.insert(~"fmt", normal(ext::fmt::expand_syntax_ext));
- syntax_expanders.insert(~"env", normal(ext::env::expand_syntax_ext));
- syntax_expanders.insert(~"macro",
+ syntax_expanders.insert("fmt", normal(ext::fmt::expand_syntax_ext));
+ syntax_expanders.insert("env", normal(ext::env::expand_syntax_ext));
+ syntax_expanders.insert("macro",
macro_defining(ext::simplext::add_new_extension));
- syntax_expanders.insert(~"concat_idents",
+ syntax_expanders.insert("concat_idents",
normal(ext::concat_idents::expand_syntax_ext));
- syntax_expanders.insert(~"ident_to_str",
+ syntax_expanders.insert("ident_to_str",
normal(ext::ident_to_str::expand_syntax_ext));
- syntax_expanders.insert(~"log_syntax",
+ syntax_expanders.insert("log_syntax",
normal(ext::log_syntax::expand_syntax_ext));
ret syntax_expanders;
}
obj ext_ctxt(sess: @session,
- crate_file_name_hack: istr,
+ crate_file_name_hack: str,
mutable backtrace: codemap::opt_span) {
- fn crate_file_name() -> istr { ret crate_file_name_hack; }
+ fn crate_file_name() -> str { ret crate_file_name_hack; }
fn session() -> @session { ret sess; }
let tmp = pre;
backtrace = tmp;
}
- _ { self.bug(~"tried to pop without a push"); }
+ _ { self.bug("tried to pop without a push"); }
}
}
- fn span_fatal(sp: span, msg: istr) -> ! {
+ fn span_fatal(sp: span, msg: str) -> ! {
self.print_backtrace();
sess.span_fatal(sp, msg);
}
- fn span_err(sp: span, msg: istr) {
+ fn span_err(sp: span, msg: str) {
self.print_backtrace();
sess.span_err(sp, msg);
}
- fn span_unimpl(sp: span, msg: istr) -> ! {
+ fn span_unimpl(sp: span, msg: str) -> ! {
self.print_backtrace();
sess.span_unimpl(sp, msg);
}
- fn span_bug(sp: span, msg: istr) -> ! {
+ fn span_bug(sp: span, msg: str) -> ! {
self.print_backtrace();
sess.span_bug(sp, msg);
}
- fn bug(msg: istr) -> ! {
- self.print_backtrace();
- sess.bug(msg);
- }
+ fn bug(msg: str) -> ! { self.print_backtrace(); sess.bug(msg); }
fn next_id() -> ast::node_id { ret sess.next_node_id(); }
}
// super-ugly and needs a better solution.
let crate_file_name_hack = sess.get_codemap().files[0].name;
- ret ext_ctxt(@sess, crate_file_name_hack,
- codemap::os_none);
+ ret ext_ctxt(@sess, crate_file_name_hack, codemap::os_none);
}
-fn expr_to_str(cx: &ext_ctxt, expr: @ast::expr, error: &istr) -> istr {
+fn expr_to_str(cx: &ext_ctxt, expr: @ast::expr, error: &str) -> str {
alt expr.node {
ast::expr_lit(l) {
alt l.node {
}
}
-fn expr_to_ident(cx: &ext_ctxt, expr: @ast::expr,
- error: &istr) -> ast::ident {
+fn expr_to_ident(cx: &ext_ctxt, expr: @ast::expr, error: &str) -> ast::ident {
alt expr.node {
ast::expr_path(p) {
if vec::len(p.node.types) > 0u || vec::len(p.node.idents) != 1u {
import syntax::ast;
fn expand_syntax_ext(cx: &ext_ctxt, sp: codemap::span, arg: @ast::expr,
- _body: &option::t<istr>) -> @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 .")
+ cx.span_fatal(sp, "#concat_idents requires a vector argument .")
}
};
- let res: ast::ident = ~"";
+ let res: ast::ident = "";
for e: @ast::expr in args {
- res += expr_to_ident(cx, e, ~"expected an ident");
+ res += expr_to_ident(cx, e, "expected an ident");
}
ret @{id: cx.next_id(),
export expand_syntax_ext;
fn expand_syntax_ext(cx: &ext_ctxt, sp: codemap::span, arg: @ast::expr,
- _body: &option::t<istr>) -> @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 `[...]`.")
+ cx.span_fatal(sp, "#env requires arguments of the form `[...]`.")
}
};
if vec::len::<@ast::expr>(args) != 1u {
- cx.span_fatal(sp, ~"malformed #env call");
+ 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);
- }
+ option::none. { ret make_new_str(cx, sp, ""); }
+ option::some(s) { ret make_new_str(cx, sp, s); }
}
}
-fn make_new_str(cx: &ext_ctxt, sp: codemap::span, s: &istr) -> @ast::expr {
+fn make_new_str(cx: &ext_ctxt, sp: codemap::span, s: &str) -> @ast::expr {
ret make_new_lit(cx, sp, ast::lit_str(s));
}
//
import syntax::ext::base::*;
-fn expand_expr(exts: &hashmap<istr, syntax_extension>, cx: &ext_ctxt,
+fn expand_expr(exts: &hashmap<str, syntax_extension>, cx: &ext_ctxt,
e: &expr_, fld: ast_fold, orig: &fn(&expr_, ast_fold) -> expr_)
-> expr_ {
ret alt e {
alt exts.find(extname) {
none. {
cx.span_fatal(pth.span,
- #fmt["macro undefined: '%s'",
- extname])
+ #fmt["macro undefined: '%s'", extname])
}
some(normal(ext)) {
let expanded = ext(cx, pth.span, args, body);
}
some(macro_defining(ext)) {
let named_extension = ext(cx, pth.span, args, body);
- exts.insert(
- named_extension.ident,
- named_extension.ext);
+ exts.insert(named_extension.ident, named_extension.ext);
ast::expr_rec([], none)
}
}
}
- _ { cx.span_bug(mac.span, ~"naked syntactic bit") }
+ _ { cx.span_bug(mac.span, "naked syntactic bit") }
}
}
_ { orig(e, fld) }
export expand_syntax_ext;
fn expand_syntax_ext(cx: &ext_ctxt, sp: span, arg: @ast::expr,
- _body: &option::t<istr>) -> @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 `[...]`.")
+ 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");
+ cx.span_fatal(sp, "#fmt requires a format string");
}
let fmt =
expr_to_str(cx, args[0],
- ~"first argument to #fmt must be a "
- + ~"string literal.");
+ "first argument to #fmt must be a " + "string literal.");
let fmtspan = args[0].span;
log "Format string:";
log fmt;
- fn parse_fmt_err_(cx: &ext_ctxt, sp: span, msg: &istr) -> ! {
+ fn parse_fmt_err_(cx: &ext_ctxt, sp: span, msg: &str) -> ! {
cx.span_fatal(sp, msg);
}
let parse_fmt_err = bind parse_fmt_err_(cx, fmtspan, _);
let sp_lit = @{node: lit, span: sp};
ret @{id: cx.next_id(), node: ast::expr_lit(sp_lit), span: sp};
}
- fn make_new_str(cx: &ext_ctxt, sp: span, s: &istr) -> @ast::expr {
+ fn make_new_str(cx: &ext_ctxt, sp: span, s: &str) -> @ast::expr {
let lit = ast::lit_str(s);
ret make_new_lit(cx, sp, lit);
}
}
fn make_path_vec(cx: &ext_ctxt, ident: &ast::ident) -> [ast::ident] {
fn compiling_std(cx: &ext_ctxt) -> bool {
- ret str::find(cx.crate_file_name(), ~"std.rc") >= 0;
+ 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: &istr) -> @ast::expr {
+ fn make_rt_path_expr(cx: &ext_ctxt, sp: span, ident: &str) -> @ast::expr {
let path = make_path_vec(cx, ident);
ret make_path_expr(cx, sp, path);
}
for f: flag in flags {
let fstr;
alt f {
- flag_left_justify. { fstr = ~"flag_left_justify"; }
- flag_left_zero_pad. { fstr = ~"flag_left_zero_pad"; }
- flag_space_for_sign. { fstr = ~"flag_space_for_sign"; }
- flag_sign_always. { fstr = ~"flag_sign_always"; }
- flag_alternate. { fstr = ~"flag_alternate"; }
+ flag_left_justify. { fstr = "flag_left_justify"; }
+ flag_left_zero_pad. { fstr = "flag_left_zero_pad"; }
+ flag_space_for_sign. { fstr = "flag_space_for_sign"; }
+ flag_sign_always. { fstr = "flag_sign_always"; }
+ flag_alternate. { fstr = "flag_alternate"; }
}
flagexprs += [make_rt_path_expr(cx, sp, fstr)];
}
// 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);
}
fn make_count(cx: &ext_ctxt, sp: span, cnt: &count) -> @ast::expr {
alt cnt {
count_implied. {
- ret make_rt_path_expr(cx, sp, ~"count_implied");
+ ret make_rt_path_expr(cx, sp, "count_implied");
}
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_path = make_path_vec(cx, "count_is");
let count_is_args = [count_lit];
ret make_call(cx, sp, count_is_path, count_is_args);
}
- _ { cx.span_unimpl(sp, ~"unimplemented #fmt conversion"); }
+ _ { cx.span_unimpl(sp, "unimplemented #fmt conversion"); }
}
}
fn make_ty(cx: &ext_ctxt, sp: span, t: &ty) -> @ast::expr {
alt t {
ty_hex(c) {
alt c {
- case_upper. { rt_type = ~"ty_hex_upper"; }
- case_lower. { rt_type = ~"ty_hex_lower"; }
+ case_upper. { rt_type = "ty_hex_upper"; }
+ case_lower. { rt_type = "ty_hex_lower"; }
}
}
- ty_bits. { rt_type = ~"ty_bits"; }
- ty_octal. { rt_type = ~"ty_octal"; }
- _ { rt_type = ~"ty_default"; }
+ ty_bits. { rt_type = "ty_bits"; }
+ ty_octal. { rt_type = "ty_octal"; }
+ _ { rt_type = "ty_default"; }
}
ret make_rt_path_expr(cx, sp, rt_type);
}
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);
ret make_conv_rec(cx, sp, rt_conv_flags, rt_conv_width,
rt_conv_precision, rt_conv_ty);
}
- fn make_conv_call(cx: &ext_ctxt, sp: span, conv_type: &istr,
- cnv: &conv, arg: @ast::expr) -> @ast::expr {
- let fname = ~"conv_" + conv_type;
+ fn make_conv_call(cx: &ext_ctxt, sp: span, conv_type: &str, cnv: &conv,
+ arg: @ast::expr) -> @ast::expr {
+ 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];
_ { ret false; }
}
}
- let unsupported = ~"conversion not supported in #fmt string";
+ let unsupported = "conversion not supported in #fmt string";
alt cnv.param {
option::none. { }
_ { cx.span_unimpl(sp, unsupported); }
flag_sign_always. {
if !is_signed_type(cnv) {
cx.span_fatal(sp,
- ~"+ flag only valid in " +
- ~"signed #fmt conversion");
+ "+ flag only valid in " +
+ "signed #fmt conversion");
}
}
flag_space_for_sign. {
if !is_signed_type(cnv) {
cx.span_fatal(sp,
- ~"space flag only valid in " +
- ~"signed #fmt conversions");
+ "space flag only valid in " +
+ "signed #fmt conversions");
}
}
flag_left_zero_pad. { }
_ { cx.span_unimpl(sp, unsupported); }
}
alt cnv.ty {
- ty_str. { ret make_conv_call(cx, arg.span, ~"str", cnv, arg); }
+ ty_str. { ret make_conv_call(cx, arg.span, "str", cnv, arg); }
ty_int(sign) {
alt sign {
- signed. { ret make_conv_call(cx, arg.span, ~"int", cnv, arg); }
+ signed. { ret make_conv_call(cx, arg.span, "int", cnv, arg); }
unsigned. {
- ret make_conv_call(cx, arg.span, ~"uint", cnv, arg);
+ ret make_conv_call(cx, arg.span, "uint", cnv, arg);
}
}
}
- ty_bool. { ret make_conv_call(cx, arg.span, ~"bool", cnv, arg); }
- ty_char. { ret make_conv_call(cx, arg.span, ~"char", cnv, arg); }
- ty_hex(_) { ret make_conv_call(cx, arg.span, ~"uint", cnv, arg); }
- ty_bits. { ret make_conv_call(cx, arg.span, ~"uint", cnv, arg); }
- ty_octal. { ret make_conv_call(cx, arg.span, ~"uint", cnv, arg); }
+ ty_bool. { ret make_conv_call(cx, arg.span, "bool", cnv, arg); }
+ ty_char. { ret make_conv_call(cx, arg.span, "char", cnv, arg); }
+ ty_hex(_) { ret make_conv_call(cx, arg.span, "uint", cnv, arg); }
+ ty_bits. { ret make_conv_call(cx, arg.span, "uint", cnv, arg); }
+ ty_octal. { ret make_conv_call(cx, arg.span, "uint", cnv, arg); }
_ { cx.span_unimpl(sp, unsupported); }
}
}
fn log_conv(c: conv) {
alt c.param {
- some(p) {
- log ~"param: " + std::int::to_str(p, 10u);
- }
+ some(p) { log "param: " + std::int::to_str(p, 10u); }
_ { log "param: none"; }
}
for f: flag in c.flags {
}
}
alt c.width {
- count_is(i) { log ~"width: count is "
- + std::int::to_str(i, 10u); }
+ count_is(i) { log "width: count is " + std::int::to_str(i, 10u); }
count_is_param(i) {
- log ~"width: count is param "
- + std::int::to_str(i, 10u);
+ log "width: count is param " + std::int::to_str(i, 10u);
}
count_is_next_param. { log "width: count is next param"; }
count_implied. { log "width: count is implied"; }
}
alt c.precision {
- count_is(i) { log ~"prec: count is "
- + std::int::to_str(i, 10u); }
+ count_is(i) { log "prec: count is " + std::int::to_str(i, 10u); }
count_is_param(i) {
- log ~"prec: count is param "
- + std::int::to_str(i, 10u);
+ log "prec: count is param " + std::int::to_str(i, 10u);
}
count_is_next_param. { log "prec: count is next param"; }
count_implied. { log "prec: count is implied"; }
}
let fmt_sp = args[0].span;
let n = 0u;
- let tmp_expr = make_new_str(cx, sp, ~"");
+ let tmp_expr = make_new_str(cx, sp, "");
let nargs = vec::len::<@ast::expr>(args);
for pc: piece in pieces {
alt pc {
n += 1u;
if n >= nargs {
cx.span_fatal(sp,
- ~"not enough arguments to #fmt " +
- ~"for the given format string");
+ "not enough arguments to #fmt " +
+ "for the given format string");
}
log "Building conversion:";
log_conv(conv);
import syntax::ast;
fn expand_syntax_ext(cx: &ext_ctxt, sp: codemap::span, arg: @ast::expr,
- _body: &option::t<istr>) -> @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 .")
+ 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");
+ cx.span_fatal(sp, "malformed #ident_to_str call");
}
ret make_new_lit(cx, sp,
ast::lit_str(expr_to_ident(cx, args[0u],
- ~"expected an ident")));
+ "expected an ident")));
}
import std::str;
fn expand_syntax_ext(cx: &ext_ctxt, sp: codemap::span, arg: @ast::expr,
- _body: &option::t<istr>) -> @ast::expr {
+ _body: &option::t<str>) -> @ast::expr {
cx.print_backtrace();
- std::io::stdout().write_line(
- print::pprust::expr_to_str(arg));
+ 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};
}
/* for when given an incompatible bit of AST */
-fn match_error(cx: &ext_ctxt, m: &matchable, expected: &istr) -> ! {
+fn match_error(cx: &ext_ctxt, m: &matchable, expected: &str) -> ! {
alt m {
match_expr(x) {
cx.span_fatal(x.span,
- ~"this argument is an expr, expected " + expected);
+ "this argument is an expr, expected " + expected);
}
match_path(x) {
cx.span_fatal(x.span,
- ~"this argument is a path, expected " + expected);
+ "this argument is a path, expected " + expected);
}
match_ident(x) {
cx.span_fatal(x.span,
- ~"this argument is an ident, expected " + expected);
+ "this argument is an ident, expected " + expected);
}
match_ty(x) {
cx.span_fatal(x.span,
- ~"this argument is a type, expected " + expected);
+ "this argument is a type, expected " + expected);
}
match_block(x) {
cx.span_fatal(x.span,
- ~"this argument is a block, expected " + expected);
+ "this argument is a block, expected " + expected);
}
- match_exact. { cx.bug(~"what is a match_exact doing in a bindings?"); }
+ match_exact. { cx.bug("what is a match_exact doing in a bindings?"); }
}
}
alt m.node {
ast::mac_ellipsis. {
if res != none {
- cx.span_fatal(m.span, ~"only one ellipsis allowed");
+ cx.span_fatal(m.span, "only one ellipsis allowed");
}
res =
some({pre: vec::slice(elts, 0u, idx - 1u),
alt sel(match_expr(e)) { none. { ret none; } _ { } }
}
let never_mind: bool = false;
- for each pair: @{key: ident,
- val: selector} in b.real_binders.items() {
+ for each pair: @{key: ident, val: selector} in b.real_binders.items() {
alt pair.val(match_expr(e)) {
none. { never_mind = true; }
some(mtc) { res.insert(pair.key, mtc); }
ret alt follow(m, idx_path) {
seq(_, sp) {
cx.span_fatal(sp,
- ~"syntax matched under ... but not " +
- ~"used that way.")
+ "syntax matched under ... but not " +
+ "used that way.")
}
leaf(m) { ret some(m) }
}
let idents: hashmap<ident, ()> = new_str_hash::<()>();
fn mark_ident(i: &ident, _fld: ast_fold, b: &bindings,
idents: &hashmap<ident, ()>) -> ident {
- if b.contains_key(i) {
- idents.insert(i, ());
- }
+ if b.contains_key(i) { idents.insert(i, ()); }
ret i;
}
// using fold is a hack: we want visit, but it doesn't hit idents ) :
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,
+ #fmt["'%s' occurs %u times, but ", fv, len] +
+ #fmt["'%s' occurs %u times", old_name,
old_len];
- cx.span_fatal(
- repeat_me.span, msg);
+ cx.span_fatal(repeat_me.span, msg);
}
}
}
alt repeat {
none. {
cx.span_fatal(repeat_me.span,
- ~"'...' surrounds an expression without any" +
- ~" repeating syntax variables");
+ "'...' surrounds an expression without any" +
+ " repeating syntax variables");
}
some({rep_count: rc, _}) {
/* Whew, we now know how how many times to repeat */
i: &ident, _fld: ast_fold) -> ident {
ret alt follow_for_trans(cx, b.find(i), idx_path) {
some(match_ident(a_id)) { a_id.node }
- some(m) { match_error(cx, m, ~"an identifier") }
+ some(m) { match_error(cx, m, "an identifier") }
none. { i }
}
}
{global: false, idents: [id.node], types: []}
}
some(match_path(a_pth)) { a_pth.node }
- some(m) { match_error(cx, m, ~"a path") }
+ some(m) { match_error(cx, m, "a path") }
none. { p }
}
}
}
some(match_path(a_pth)) { expr_path(a_pth) }
some(match_expr(a_exp)) { a_exp.node }
- some(m) { match_error(cx, m, ~"an expression") }
+ some(m) { match_error(cx, m, "an expression") }
none. { orig(e, fld) }
}
}
some(id) {
alt follow_for_trans(cx, b.find(id), idx_path) {
some(match_ty(ty)) { ty.node }
- some(m) { match_error(cx, m, ~"a type") }
+ some(m) { match_error(cx, m, "a type") }
none. { orig(t, fld) }
}
}
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) {
+ 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")
+ match_error(cx, m, "a block")
}
none. { orig(blk, fld) }
}
if vec::len(post) > 0u {
cx.span_unimpl(e.span,
- ~"matching after `...` not yet supported");
+ "matching after `...` not yet supported");
}
}
{pre: pre, rep: none., post: post} {
if post != [] {
- cx.bug(~"elts_to_ell provided an invalid result");
+ cx.bug("elts_to_ell provided an invalid result");
}
p_t_s_r_length(cx, vec::len(pre), false, s, b);
p_t_s_r_actual_vector(cx, pre, false, s, b);
}
+
/* TODO: handle embedded types and blocks, at least */
expr_mac(mac) {
p_t_s_r_mac(cx, mac, s, b);
match_expr(e) {
if e == pat { some(leaf(match_exact)) } else { none }
}
- _ { cx.bug(~"broken traversal in p_t_s_r") }
+ _ { cx.bug("broken traversal in p_t_s_r") }
}
}
b.literal_ast_matchers += [bind select(cx, _, e)];
fn select(cx: &ext_ctxt, m: &matchable) -> match_result {
ret alt m {
match_expr(e) { some(leaf(specialize_match(m))) }
- _ { cx.bug(~"broken traversal in p_t_s_r") }
+ _ { cx.bug("broken traversal in p_t_s_r") }
}
}
if b.real_binders.contains_key(p_id) {
- cx.span_fatal(p.span, ~"duplicate binding identifier");
+ cx.span_fatal(p.span, "duplicate binding identifier");
}
- b.real_binders.insert(p_id,
- compose_sels(s, bind select(cx, _)));
+ b.real_binders.insert(p_id, compose_sels(s, bind select(cx, _)));
}
none. { }
}
match_expr(e) {
alt e.node { expr_mac(mac) { fn_m(mac) } _ { none } }
}
- _ { cx.bug(~"broken traversal in p_t_s_r") }
+ _ { cx.bug("broken traversal in p_t_s_r") }
}
}
- fn no_des(cx: &ext_ctxt, sp: &span, syn: &istr) -> ! {
- cx.span_fatal(sp, ~"destructuring "
- + syn + ~" is not yet supported");
+ fn no_des(cx: &ext_ctxt, sp: &span, syn: &str) -> ! {
+ cx.span_fatal(sp, "destructuring " + syn + " is not yet supported");
}
alt mac.node {
- ast::mac_ellipsis. { cx.span_fatal(mac.span, ~"misused `...`"); }
- ast::mac_invoc(_, _, _) { no_des(cx, mac.span, ~"macro calls"); }
+ ast::mac_ellipsis. { cx.span_fatal(mac.span, "misused `...`"); }
+ ast::mac_invoc(_, _, _) { no_des(cx, mac.span, "macro calls"); }
ast::mac_embed_type(ty) {
alt ty.node {
ast::ty_path(pth, _) {
}
}
let final_step = bind select_pt_1(cx, _, select_pt_2);
- b.real_binders.insert(
- id, compose_sels(s, final_step));
+ b.real_binders.insert(id, compose_sels(s, final_step));
}
- none. { no_des(cx, pth.span, ~"under `#<>`"); }
+ none. { no_des(cx, pth.span, "under `#<>`"); }
}
}
- _ { no_des(cx, ty.span, ~"under `#<>`"); }
+ _ { no_des(cx, ty.span, "under `#<>`"); }
}
}
ast::mac_embed_block(blk) {
}
}
let final_step = bind select_pt_1(cx, _, select_pt_2);
- b.real_binders.insert(id,
- compose_sels(s, final_step));
+ b.real_binders.insert(id, compose_sels(s, final_step));
}
- none. { no_des(cx, blk.span, ~"under `#{}`"); }
+ none. { no_des(cx, blk.span, "under `#{}`"); }
}
}
}
_ { none }
}
}
- _ { cx.bug(~"broken traversal in p_t_s_r") }
+ _ { cx.bug("broken traversal in p_t_s_r") }
}
}
p_t_s_rec(cx, match_expr(repeat_me),
_ { none }
}
}
- _ { cx.bug(~"broken traversal in p_t_s_r") }
+ _ { cx.bug("broken traversal in p_t_s_r") }
}
}
p_t_s_rec(cx, match_expr(elts[idx]),
}
fn add_new_extension(cx: &ext_ctxt, sp: span, arg: @expr,
- _body: &option::t<istr>) -> base::macro_def {
+ _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 `[...]`.")
+ "#macro requires arguments of the form `[...]`.")
}
};
- let macro_name: option::t<istr> = none;
+ let macro_name: option::t<str> = none;
let clauses: [@clause] = [];
for arg: @expr in args {
alt arg.node {
expr_vec(elts, mut) {
if vec::len(elts) != 2u {
cx.span_fatal((*arg).span,
- ~"extension clause must consist of [" +
- ~"macro invocation, expansion body]");
+ "extension clause must consist of [" +
+ "macro invocation, expansion body]");
}
some(other_id) {
if id != other_id {
cx.span_fatal(pth.span,
- ~"macro name must be " +
- ~"consistent");
+ "macro name must be " +
+ "consistent");
}
}
}
}
none. {
cx.span_fatal(pth.span,
- ~"macro name must not be a path");
+ "macro name must not be a path");
}
}
clauses +=
}
_ {
cx.span_fatal(elts[0u].span,
- ~"extension clause must" +
- ~" start with a macro invocation.");
+ "extension clause must" +
+ " start with a macro invocation.");
}
}
}
_ {
cx.span_fatal((*arg).span,
- ~"extension must be [clause, " + ~" ...]");
+ "extension must be [clause, " + " ...]");
}
}
}
some(id) { id }
none. {
cx.span_fatal(sp,
- ~"macro definition must have " +
- ~"at least one clause")
+ "macro definition must have " +
+ "at least one clause")
}
},
ext: normal(ext)};
fn generic_extension(cx: &ext_ctxt, sp: span, arg: @expr,
- _body: &option::t<istr>,
- clauses: [@clause]) -> @expr {
+ _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) }
none. { cont; }
}
}
- cx.span_fatal(sp, ~"no clauses match macro invocation");
+ cx.span_fatal(sp, "no clauses match macro invocation");
}
}
type ctx =
@{p: parser,
mode: eval_mode,
- mutable deps: [istr],
+ mutable deps: [str],
sess: parser::parse_sess,
mutable chpos: uint,
mutable byte_pos: uint,
cfg: ast::crate_cfg};
fn eval_crate_directives(cx: ctx, cdirs: &[@ast::crate_directive],
- prefix: &istr,
- 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: &istr) -> ast::_mod {
+ prefix: &str) -> ast::_mod {
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};
}
-fn eval_crate_directive(cx: ctx, cdir: @ast::crate_directive, prefix: &istr,
+fn eval_crate_directive(cx: ctx, cdir: @ast::crate_directive, prefix: &str,
view_items: &mutable [@ast::view_item],
items: &mutable [@ast::item]) {
alt cdir.node {
ast::cdir_src_mod(id, file_opt, attrs) {
- let file_path = id + ~".rs";
- alt file_opt {
- some(f) {
- file_path = f;
- }
- none. { }
- }
- let full_path = if std::fs::path_is_absolute(file_path) {
- file_path
- } else {
- prefix + std::fs::path_sep() + file_path
- };
+ let file_path = id + ".rs";
+ alt file_opt { some(f) { file_path = f; } none. { } }
+ let full_path =
+ 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; }
let p0 =
- new_parser_from_file(cx.sess, cx.cfg,
- full_path, cx.chpos,
+ new_parser_from_file(cx.sess, cx.cfg, full_path, cx.chpos,
cx.byte_pos, SOURCE_FILE);
let inner_attrs = parse_inner_attrs_and_next(p0);
let mod_attrs = attrs + inner_attrs.inner;
}
ast::cdir_dir_mod(id, dir_opt, cdirs, attrs) {
let path = id;
- alt dir_opt {
- some(d) {
- path = d;
- }
- none. { }
- }
+ alt dir_opt { some(d) { path = d; } none. { } }
let full_path =
if std::fs::path_is_absolute(path) {
path
- } else {
- prefix + std::fs::path_sep() + path
- };
+ } else { prefix + std::fs::path_sep() + path };
let m0 = eval_crate_directives_to_mod(cx, cdirs, full_path);
let i =
@{ident: id,
fn next() -> char;
fn init();
fn bump();
- fn get_str_from(uint) -> istr;
- fn get_interner() -> @interner::interner<istr>;
+ 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(&istr);
+ fn err(&str);
};
-fn new_reader(cm: &codemap::codemap, src: &istr, filemap: codemap::filemap,
- itr: @interner::interner<istr>) -> reader {
+fn new_reader(cm: &codemap::codemap, src: &str, filemap: codemap::filemap,
+ itr: @interner::interner<str>) -> reader {
obj reader(cm: codemap::codemap,
- src: istr,
+ src: str,
len: uint,
mutable col: uint,
mutable pos: uint,
mutable ch: char,
mutable chpos: uint,
- mutable strs: [istr],
+ mutable strs: [str],
fm: codemap::filemap,
- itr: @interner::interner<istr>) {
+ itr: @interner::interner<str>) {
fn is_eof() -> bool { ret ch == -1 as char; }
- fn get_str_from(start: uint) -> istr {
+ fn get_str_from(start: uint) -> str {
// I'm pretty skeptical about this subtraction. What if there's a
// multi-byte character before the mark?
ret str::slice(src, start - 1u, pos - 1u);
ch = next.ch;
} else { ch = -1 as char; }
}
- fn get_interner() -> @interner::interner<istr> { ret itr; }
+ fn get_interner() -> @interner::interner<str> { ret itr; }
fn get_col() -> uint { ret col; }
fn get_filemap() -> codemap::filemap { ret fm; }
- fn err(m: &istr) {
- codemap::emit_error(
- some(ast_util::mk_sp(chpos, chpos)),
- m, cm);
+ fn err(m: &str) {
+ codemap::emit_error(some(ast_util::mk_sp(chpos, chpos)), m, cm);
}
}
- let strs: [istr] = [];
+ 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 consume_block_comment(rdr: &reader) {
let level: int = 1;
while level > 0 {
- if rdr.is_eof() {
- rdr.err(~"unterminated block comment"); fail;
- }
+ if rdr.is_eof() { rdr.err("unterminated block comment"); fail; }
if rdr.curr() == '/' && rdr.next() == '*' {
rdr.bump();
rdr.bump();
be consume_whitespace_and_comments(rdr);
}
-fn digits_to_string(s: &istr) -> int {
+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); }
ret accum_int;
}
-fn scan_exponent(rdr: &reader) -> option::t<istr> {
+fn scan_exponent(rdr: &reader) -> option::t<str> {
let c = rdr.curr();
- let rslt = ~"";
+ let rslt = "";
if c == 'e' || c == 'E' {
rslt += str::unsafe_from_bytes([c as u8]);
rdr.bump();
let exponent = scan_dec_digits(rdr);
if str::byte_len(exponent) > 0u {
ret some(rslt + exponent);
- } else { rdr.err(~"scan_exponent: bad fp literal"); fail; }
- } else { ret none::<istr>; }
+ } else { rdr.err("scan_exponent: bad fp literal"); fail; }
+ } else { ret none::<str>; }
}
-fn scan_dec_digits(rdr: &reader) -> istr {
+fn scan_dec_digits(rdr: &reader) -> str {
let c = rdr.curr();
- let rslt: istr = ~"";
+ let rslt: str = "";
while is_dec_digit(c) || c == '_' {
if c != '_' { rslt += str::unsafe_from_bytes([c as u8]); }
rdr.bump();
fn scan_number(c: char, rdr: &reader) -> token::token {
let accum_int = 0;
- let dec_str: istr = ~"";
+ let dec_str: str = "";
let is_dec_integer: bool = false;
let n = rdr.next();
if c == '0' && n == 'x' {
rdr.bump();
let dec_part = scan_dec_digits(rdr);
- let float_str = dec_str + ~"." + dec_part;
+ let float_str = dec_str + "." + dec_part;
c = rdr.curr();
let exponent_str = scan_exponent(rdr);
alt exponent_str { some(s) { float_str += s; } none. { } }
}
} else {
- ret token::LIT_FLOAT(interner::intern::<istr>(
- *rdr.get_interner(),
- float_str));
+ ret token::LIT_FLOAT(interner::intern::<str>(*rdr.get_interner(),
+ float_str));
}
}
let maybe_exponent = scan_exponent(rdr);
alt maybe_exponent {
some(s) {
- ret token::LIT_FLOAT(interner::intern::<istr>(
- *rdr.get_interner(),
- dec_str + s));
+ ret token::LIT_FLOAT(interner::intern::<str>(*rdr.get_interner(),
+ 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;
}
fn next_token_inner(rdr: &reader) -> token::token {
- let accum_str = ~"";
+ let accum_str = "";
let c = rdr.curr();
if is_alpha(c) || c == '_' {
while is_alnum(c) || c == '_' {
rdr.bump();
c = rdr.curr();
}
- if str::eq(accum_str, ~"_") { ret token::UNDERSCORE; }
+ if str::eq(accum_str, "_") { ret token::UNDERSCORE; }
let is_mod_name = c == ':' && rdr.next() == ':';
- ret token::IDENT(interner::intern::<istr>(
- *rdr.get_interner(),
- accum_str), is_mod_name);
+ ret token::IDENT(interner::intern::<str>(*rdr.get_interner(),
+ 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();
}
+
// 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;
}
}
}
if rdr.curr() != '\'' {
- rdr.err(~"unterminated character constant");
+ rdr.err("unterminated character constant");
fail;
}
rdr.bump(); // advance curr past token
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::<istr>(
- *rdr.get_interner(),
- accum_str));
+ ret token::LIT_STR(interner::intern::<str>(*rdr.get_interner(),
+ 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; }
}
}
blank_line; // Just a manual blank line "\n\n", for layout
}
-type cmnt = {style: cmnt_style, lines: [istr], pos: uint};
+type cmnt = {style: cmnt_style, lines: [str], pos: uint};
-fn read_to_eol(rdr: &reader) -> istr {
- let val = ~"";
+fn read_to_eol(rdr: &reader) -> str {
+ let val = "";
while rdr.curr() != '\n' && !rdr.is_eof() {
str::push_char(val, rdr.curr());
rdr.bump();
ret val;
}
-fn read_one_line_comment(rdr: &reader) -> istr {
+fn read_one_line_comment(rdr: &reader) -> str {
let val = read_to_eol(rdr);
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: [istr] = [];
+ let v: [str] = [];
comments += [{style: blank_line, lines: v, pos: rdr.get_chpos()}];
}
fn read_line_comments(rdr: &reader, code_to_the_left: bool) -> cmnt {
log ">>> line comments";
let p = rdr.get_chpos();
- let lines: [istr] = [];
+ let lines: [str] = [];
while rdr.curr() == '/' && rdr.next() == '/' {
let line = read_one_line_comment(rdr);
log line;
pos: p};
}
-fn all_whitespace(s: &istr, begin: uint, end: uint) -> bool {
+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; }
ret true;
}
-fn trim_whitespace_prefix_and_push_line(lines: &mutable [istr], s: &istr,
+fn trim_whitespace_prefix_and_push_line(lines: &mutable [str], s: &str,
col: uint) {
let s1;
if all_whitespace(s, 0u, col) {
if col < str::byte_len(s) {
s1 = str::slice(s, col, str::byte_len(s));
- } else { s1 = ~""; }
+ } else { s1 = ""; }
} else { s1 = s; }
- log ~"pushing line: " + s1;
+ log "pushing line: " + 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: [istr] = [];
+ let lines: [str] = [];
let col: uint = rdr.get_col();
rdr.bump();
rdr.bump();
- let curr_line = ~"/*";
+ let curr_line = "/*";
let level: int = 1;
while level > 0 {
log #fmt["=== block comment level %d", level];
- if rdr.is_eof() { rdr.err(~"unterminated block comment"); fail; }
+ if rdr.is_eof() { rdr.err("unterminated block comment"); fail; }
if rdr.curr() == '\n' {
trim_whitespace_prefix_and_push_line(lines, curr_line, col);
- curr_line = ~"";
+ curr_line = "";
rdr.bump();
} else {
str::push_char(curr_line, rdr.curr());
if rdr.curr() == '/' && rdr.next() == '*' {
rdr.bump();
rdr.bump();
- curr_line += ~"*";
+ curr_line += "*";
level += 1;
} else {
if rdr.curr() == '*' && rdr.next() == '/' {
rdr.bump();
rdr.bump();
- curr_line += ~"/";
+ curr_line += "/";
level -= 1;
} else { rdr.bump(); }
}
}
}
-type lit = {lit: istr, pos: uint};
+type lit = {lit: str, pos: uint};
-fn gather_comments_and_literals(cm: &codemap::codemap, path: &istr,
+fn gather_comments_and_literals(cm: &codemap::codemap, path: &str,
srdr: io::reader) ->
{cmnts: [cmnt], lits: [lit]} {
let src = str::unsafe_from_bytes(srdr.read_whole_stream());
- let itr = @interner::mk::<istr>(str::hash, str::eq);
- let rdr = new_reader(cm, src,
- codemap::new_filemap(
- path, 0u, 0u), itr);
+ 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 first_read: bool = true;
if is_lit(tok.tok) {
literals += [{lit: rdr.get_str_from(tok.bpos), pos: tok.chpos}];
}
- log ~"tok: " + token::to_str(rdr, tok.tok);
+ log "tok: " + token::to_str(rdr, tok.tok);
first_read = false;
}
ret {cmnts: comments, lits: literals};
fn bump();
fn swap(token::token, uint, uint);
fn look_ahead(uint) -> token::token;
- fn fatal(&istr) -> ! ;
- fn warn(&istr);
+ fn fatal(&str) -> ! ;
+ fn warn(&str);
fn restrict(restriction);
fn get_restriction() -> restriction;
fn get_file_type() -> file_type;
fn get_last_lo_pos() -> uint;
fn get_last_hi_pos() -> uint;
fn get_prec_table() -> @[op_spec];
- fn get_str(token::str_num) -> istr;
+ fn get_str(token::str_num) -> str;
fn get_reader() -> lexer::reader;
fn get_filemap() -> codemap::filemap;
- fn get_bad_expr_words() -> hashmap<istr, ()>;
+ 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: &istr,
+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);
+ let filemap = codemap::new_filemap(path, chpos, byte_pos);
sess.cm.files += [filemap];
let itr = @interner::mk(str::hash, str::eq);
let rdr = lexer::new_reader(sess.cm, src, filemap, itr);
mutable restr: restriction,
rdr: lexer::reader,
precs: @[op_spec],
- bad_words: hashmap<istr, ()>) {
+ bad_words: hashmap<str, ()>) {
fn peek() -> token::token { ret tok; }
fn bump() {
last_tok_span = tok_span;
}
ret buffer[distance - 1u].tok;
}
- fn fatal(m: &istr) -> ! {
- codemap::emit_error(some(self.get_span()),
- m, sess.cm);
+ fn fatal(m: &str) -> ! {
+ codemap::emit_error(some(self.get_span()), m, sess.cm);
fail;
}
- fn warn(m: &istr) {
- codemap::emit_warning(some(self.get_span()),
- m, sess.cm);
+ fn warn(m: &str) {
+ codemap::emit_warning(some(self.get_span()), m, sess.cm);
}
fn restrict(r: restriction) { restr = r; }
fn get_restriction() -> restriction { ret restr; }
fn get_file_type() -> file_type { ret ftype; }
fn get_cfg() -> ast::crate_cfg { ret cfg; }
fn get_prec_table() -> @[op_spec] { ret precs; }
- fn get_str(i: token::str_num) -> istr {
+ fn get_str(i: token::str_num) -> str {
ret interner::get(*rdr.get_interner(), i);
}
fn get_reader() -> lexer::reader { ret rdr; }
fn get_filemap() -> codemap::filemap { ret rdr.get_filemap(); }
- fn get_bad_expr_words() -> hashmap<istr, ()> { ret bad_words; }
+ fn get_bad_expr_words() -> hashmap<str, ()> { ret bad_words; }
fn get_chpos() -> uint { ret rdr.get_chpos(); }
fn get_byte_pos() -> uint { ret rdr.get_byte_pos(); }
fn get_id() -> node_id { ret next_node_id(sess); }
// These are the words that shouldn't be allowed as value identifiers,
// because, if used at the start of a line, they will cause the line to be
// interpreted as a specific kind of statement, which would be confusing.
-fn bad_expr_word_table() -> hashmap<istr, ()> {
+fn bad_expr_word_table() -> hashmap<str, ()> {
let words = new_str_hash();
- words.insert(~"mod", ());
- words.insert(~"if", ());
- words.insert(~"else", ());
- words.insert(~"while", ());
- words.insert(~"do", ());
- words.insert(~"alt", ());
- words.insert(~"for", ());
- words.insert(~"each", ());
- words.insert(~"break", ());
- words.insert(~"cont", ());
- words.insert(~"put", ());
- words.insert(~"ret", ());
- words.insert(~"be", ());
- words.insert(~"fail", ());
- words.insert(~"type", ());
- words.insert(~"resource", ());
- words.insert(~"check", ());
- words.insert(~"assert", ());
- words.insert(~"claim", ());
- words.insert(~"prove", ());
- words.insert(~"native", ());
- words.insert(~"fn", ());
- words.insert(~"lambda", ());
- words.insert(~"pure", ());
- words.insert(~"iter", ());
- words.insert(~"block", ());
- words.insert(~"import", ());
- words.insert(~"export", ());
- words.insert(~"let", ());
- words.insert(~"const", ());
- words.insert(~"log", ());
- words.insert(~"log_err", ());
- words.insert(~"tag", ());
- words.insert(~"obj", ());
- words.insert(~"copy", ());
+ words.insert("mod", ());
+ words.insert("if", ());
+ words.insert("else", ());
+ words.insert("while", ());
+ words.insert("do", ());
+ words.insert("alt", ());
+ words.insert("for", ());
+ words.insert("each", ());
+ words.insert("break", ());
+ words.insert("cont", ());
+ words.insert("put", ());
+ words.insert("ret", ());
+ words.insert("be", ());
+ words.insert("fail", ());
+ words.insert("type", ());
+ words.insert("resource", ());
+ words.insert("check", ());
+ words.insert("assert", ());
+ words.insert("claim", ());
+ words.insert("prove", ());
+ words.insert("native", ());
+ words.insert("fn", ());
+ words.insert("lambda", ());
+ words.insert("pure", ());
+ words.insert("iter", ());
+ words.insert("block", ());
+ words.insert("import", ());
+ words.insert("export", ());
+ words.insert("let", ());
+ words.insert("const", ());
+ words.insert("log", ());
+ words.insert("log_err", ());
+ words.insert("tag", ());
+ words.insert("obj", ());
+ words.insert("copy", ());
ret words;
}
fn unexpected(p: &parser, t: token::token) -> ! {
- let s: istr = ~"unexpected token: ";
+ let s: str = "unexpected token: ";
s += token::to_str(p.get_reader(), t);
p.fatal(s);
}
if p.peek() == t {
p.bump();
} else {
- let s: istr = ~"expecting ";
+ let s: str = "expecting ";
s += token::to_str(p.get_reader(), t);
- s += ~", found ";
+ s += ", found ";
s += token::to_str(p.get_reader(), p.peek());
p.fatal(s);
}
} else if p.peek() == token::BINOP(token::ASR) {
p.swap(token::BINOP(token::LSR), p.get_lo_pos() + 1u, p.get_hi_pos());
} else {
- let s: istr = ~"expecting ";
+ let s: str = "expecting ";
s += token::to_str(p.get_reader(), token::GT);
- s += ~", found ";
+ s += ", found ";
s += token::to_str(p.get_reader(), p.peek());
p.fatal(s);
}
fn parse_ident(p: &parser) -> ast::ident {
alt p.peek() {
- token::IDENT(i, _) {
- p.bump();
- ret p.get_str(i);
- }
- _ { p.fatal(~"expecting ident"); }
+ token::IDENT(i, _) { p.bump(); ret p.get_str(i); }
+ _ { p.fatal("expecting ident"); }
}
}
ret if p.peek() == tok { p.bump(); true } else { false };
}
-fn is_word(p: &parser, word: &istr) -> bool {
+fn is_word(p: &parser, word: &str) -> bool {
ret alt p.peek() {
token::IDENT(sid, false) { str::eq(word, p.get_str(sid)) }
_ { false }
};
}
-fn eat_word(p: &parser, word: &istr) -> bool {
+fn eat_word(p: &parser, word: &str) -> bool {
alt p.peek() {
token::IDENT(sid, false) {
if str::eq(word, p.get_str(sid)) {
}
}
-fn expect_word(p: &parser, word: &istr) {
+fn expect_word(p: &parser, word: &str) {
if !eat_word(p, word) {
- p.fatal(~"expecting " + word + ~", found " +
- token::to_str(p.get_reader(), p.peek()));
+ p.fatal("expecting " + word + ", found " +
+ token::to_str(p.get_reader(), p.peek()));
}
}
token::IDENT(sid, false) {
let w = p.get_str(sid);
if p.get_bad_expr_words().contains_key(w) {
- p.fatal(~"found " + w + ~" in expression position");
+ p.fatal("found " + w + " in expression position");
}
}
_ { }
let mode = ast::val;
if p.peek() == token::BINOP(token::AND) {
p.bump();
- mode = ast::alias(eat_word(p, ~"mutable"));
+ mode = ast::alias(eat_word(p, "mutable"));
}
let t = parse_ty(p, false);
ret spanned(lo, t.span.hi, {mode: mode, ty: t});
}
fn parse_proto(p: &parser) -> ast::proto {
- if eat_word(p, ~"iter") {
+ 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 { unexpected(p, p.peek()); }
}
fn ident_index(p: &parser, args: &[ast::arg], i: &ast::ident) -> uint {
let j = 0u;
for a: ast::arg in args { if a.ident == i { ret j; } j += 1u; }
- p.fatal(~"Unbound variable " +
- i + ~" in constraint arg");
+ p.fatal("Unbound variable " + i + " in constraint arg");
}
fn parse_type_constr_arg(p: &parser) -> @ast::ty_constr_arg {
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"); }
}
}
let t: ast::ty_;
// FIXME: do something with this
- if eat_word(p, ~"bool") {
+ 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_istr;
- } 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, "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 {
p.bump();
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") {
- p.warn(~"ignoring deprecated 'mutable' type constructor");
+ } 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;
let path = parse_path(p);
t = ast::ty_path(path, p.get_id());
hi = path.span.hi;
- } else { p.fatal(~"expecting type"); }
+ } else { p.fatal("expecting type"); }
ret parse_ty_postfix(t, p, colons_before_params);
}
fn parse_arg_mode(p: &parser) -> ast::mode {
if eat(p, token::BINOP(token::AND)) {
- ast::alias(eat_word(p, ~"mutable"))
+ ast::alias(eat_word(p, "mutable"))
} else if eat(p, token::BINOP(token::MINUS)) {
ast::move
} else { ast::val }
fn parse_lit(p: &parser) -> ast::lit {
let sp = p.get_span();
let lit: ast::lit_ = ast::lit_nil;
- if eat_word(p, ~"true") {
+ 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() {
lit = ast::lit_mach_float(tm, p.get_str(s));
}
token::LIT_CHAR(c) { p.bump(); lit = ast::lit_char(c); }
- token::LIT_STR(s) {
- p.bump();
- lit = ast::lit_str(p.get_str(s));
- }
+ token::LIT_STR(s) { p.bump(); lit = ast::lit_str(p.get_str(s)); }
token::LPAREN. {
p.bump();
expect(p, token::RPAREN);
}
fn parse_mutability(p: &parser) -> ast::mutability {
- if eat_word(p, ~"mutable") {
+ if eat_word(p, "mutable") {
if p.peek() == token::QUES { p.bump(); ret ast::maybe_mut; }
ret ast::mut;
}
} else { ret mk_expr(p, lo, hi, ast::expr_tup(es)); }
} else if p.peek() == token::LBRACE {
p.bump();
- if is_word(p, ~"mutable") ||
+ if is_word(p, "mutable") ||
is_plain_ident(p) && p.look_ahead(1u) == 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; }
+ if eat_word(p, "with") { base = some(parse_expr(p)); break; }
expect(p, token::COMMA);
fields += [parse_field(p, token::COLON)];
}
let blk = parse_block_tail(p, lo, ast::checked);
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, "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 eat_word(p, ~"unchecked") {
+ } else if eat_word(p, "unchecked") {
expect(p, token::LBRACE);
let blk = parse_block_tail(p, lo, ast::unchecked);
ret mk_expr(p, blk.span.lo, blk.span.hi, ast::expr_block(blk));
token::LIT_STR(s) {
let sp = p.get_span();
p.bump();
- let lit =
- @{node: ast::lit_str(p.get_str(s)),
- span: sp};
+ let lit = @{node: ast::lit_str(p.get_str(s)), span: sp};
ex = ast::expr_lit(lit);
}
_ { 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
let inner_obj: option::t<@ast::expr> = none;
expect(p, token::LBRACE);
while p.peek() != token::RBRACE {
- if eat_word(p, ~"with") {
+ if eat_word(p, "with") {
inner_obj = some(parse_expr(p));
} else { meths += [parse_method(p)]; }
}
// "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() {
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_util::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 { p.fatal("Non-call expression in tail call"); }
+ } 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);
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") {
+ 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;
fn parse_syntax_ext_naked(p: &parser, lo: uint) -> @ast::expr {
let pth = parse_path(p);
if vec::len(pth.node.idents) == 0u {
- p.fatal(~"expected a syntax expander name");
+ p.fatal("expected a syntax expander name");
}
//temporary for a backwards-compatible cycle:
let es =
token::IDENT(i, _) {
hi = p.get_hi_pos();
p.bump();
- e = mk_expr(p, lo, hi,
- ast::expr_field(
- e, p.get_str(i)));
+ e = mk_expr(p, lo, hi, ast::expr_field(e, p.get_str(i)));
}
t { unexpected(p, t); }
}
}
fn parse_prefix_expr(p: &parser) -> @ast::expr {
- if eat_word(p, ~"mutable") {
- p.warn(~"ignoring deprecated 'mutable' prefix operator");
+ if eat_word(p, "mutable") {
+ p.warn("ignoring deprecated 'mutable' prefix operator");
}
let lo = p.get_lo_pos();
let hi = p.get_hi_pos();
ret parse_more_binops(p, bin, min_prec);
}
}
- if as_prec > min_prec && eat_word(p, ~"as") {
+ if as_prec > min_prec && eat_word(p, "as") {
let rhs = parse_ty(p, true);
let _as =
mk_expr(p, lhs.span.lo, rhs.span.hi, ast::expr_cast(lhs, rhs));
let thn = parse_block(p);
let els: option::t<@ast::expr> = none;
let hi = thn.span.hi;
- if eat_word(p, ~"else") {
+ if eat_word(p, "else") {
let elexpr = parse_else_expr(p);
els = some(elexpr);
hi = elexpr.span.hi;
}
fn parse_if_expr(p: &parser) -> @ast::expr {
- if eat_word(p, ~"check") {
+ if eat_word(p, "check") {
let q = parse_if_expr_1(p);
ret mk_expr(p, q.lo, q.hi, ast::expr_if_check(q.cond, q.then, q.els));
} else {
}
fn parse_else_expr(p: &parser) -> @ast::expr {
- if eat_word(p, ~"if") {
+ if eat_word(p, "if") {
ret parse_if_expr(p);
} else {
let blk = parse_block(p);
fn parse_for_expr(p: &parser) -> @ast::expr {
let lo = p.get_last_lo_pos();
- let is_each = eat_word(p, ~"each");
+ let is_each = eat_word(p, "each");
let decl = parse_local(p, false);
- expect_word(p, ~"in");
+ expect_word(p, "in");
let seq = parse_expr(p);
let body = parse_block(p);
let hi = body.span.hi;
fn parse_do_while_expr(p: &parser) -> @ast::expr {
let lo = p.get_last_lo_pos();
let body = parse_block(p);
- expect_word(p, ~"while");
+ expect_word(p, "while");
let cond = parse_expr(p);
let hi = cond.span.hi;
ret mk_expr(p, lo, hi, ast::expr_do_while(body, cond));
while p.peek() != token::RBRACE {
let pats = parse_pats(p);
let guard = none;
- if eat_word(p, ~"when") {
- guard = some(parse_expr(p));
- }
+ if eat_word(p, "when") { guard = some(parse_expr(p)); }
let blk = parse_block(p);
arms += [{pats: pats, guard: guard, body: blk}];
}
}
+
// Now that the the channel is the first argument to receive,
// combining it with an initializer doesn't really make sense.
// case (token::RECV) {
if p.peek() == token::UNDERSCORE {
p.bump();
if p.peek() != token::RBRACE {
- p.fatal(~"expecting }, found " +
- token::to_str(p.get_reader(), p.peek()));
+ p.fatal("expecting }, found " +
+ token::to_str(p.get_reader(), p.peek()));
}
etc = true;
break;
subpat = parse_pat(p);
} else {
if p.get_bad_expr_words().contains_key(fieldname) {
- p.fatal(~"found " + fieldname
- + ~" in binding position");
+ p.fatal("found " + fieldname + " in binding position");
}
subpat =
@{id: p.get_id(),
token::LIT_STR(s) {
let sp = p.get_span();
p.bump();
- let lit =
- @{node: ast::lit_str(p.get_str(s)),
- span: sp};
+ let lit = @{node: ast::lit_str(p.get_str(s)), span: sp};
hi = lit.span.hi;
pat = ast::pat_lit(lit);
}
- _ { p.fatal(~"expected string literal"); }
+ _ { p.fatal("expected string literal"); }
}
}
tok {
- if !is_ident(tok) || is_word(p, ~"true") || is_word(p, ~"false") {
+ if !is_ident(tok) || is_word(p, "true") || is_word(p, "false") {
let lit = parse_lit(p);
hi = lit.span.hi;
pat = ast::pat_lit(@lit);
fn parse_source_stmt(p: &parser) -> @ast::stmt {
let lo = p.get_lo_pos();
- if eat_word(p, ~"let") {
+ if eat_word(p, "let") {
let decl = parse_let(p);
ret @spanned(lo, decl.span.hi, ast::stmt_decl(decl, p.get_id()));
} else {
if vec::len(item_attrs) > 0u {
alt maybe_item {
some(_) {/* fallthrough */ }
- _ { ret p.fatal(~"expected item"); }
+ _ { ret p.fatal("expected item"); }
}
}
let e = parse_expr(p);
ret @spanned(lo, e.span.hi, ast::stmt_expr(e, p.get_id()));
}
- _ { p.fatal(~"expected statement"); }
+ _ { p.fatal("expected statement"); }
}
}
}
}
+
// We should not be calling this on a cdir.
ast::stmt_crate_directive(cdir) {
fail;
fn parse_block(p: &parser) -> ast::blk {
let lo = p.get_lo_pos();
- if eat_word(p, ~"unchecked") {
+ if eat_word(p, "unchecked") {
be parse_block_tail(p, lo, ast::unchecked);
- }
- else {
+ } else {
expect(p, token::LBRACE);
be parse_block_tail(p, lo, ast::checked);
}
token::RBRACE. { expr = some(e); }
t {
if stmt_ends_with_semi(*stmt) {
- p.fatal(~"expected ';' or '}' after " +
- ~"expression but found " +
+ p.fatal("expected ';' or '}' after " +
+ "expression but found " +
token::to_str(p.get_reader(), t));
}
stmts += [stmt];
alt parse_item(p, attrs) {
some(i) { items += [i]; }
_ {
- p.fatal(~"expected item but found " +
+ p.fatal("expected item but found " +
token::to_str(p.get_reader(), p.peek()));
}
}
let t = parse_fn_header(p);
let decl = parse_fn_decl(p, ast::impure_fn, ast::il_normal);
let link_name = none;
- if p.peek() == token::EQ {
- p.bump();
- link_name = some(parse_str(p));
- }
+ if p.peek() == token::EQ { p.bump(); link_name = some(parse_str(p)); }
let hi = p.get_hi_pos();
expect(p, token::SEMI);
ret @{ident: t.ident,
fn parse_native_item(p: &parser, attrs: &[ast::attribute]) ->
@ast::native_item {
- if eat_word(p, ~"type") {
+ 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: &istr,
- abi: ast::native_abi,
+fn parse_native_mod_items(p: &parser, native_name: &str, abi: ast::native_abi,
first_item_attrs: &[ast::attribute]) ->
ast::native_mod {
// Shouldn't be any view items since we've already parsed an item attr
fn parse_item_native_mod(p: &parser, attrs: &[ast::attribute]) -> @ast::item {
let lo = p.get_last_lo_pos();
let abi = ast::native_abi_cdecl;
- if !is_word(p, ~"mod") {
+ if !is_word(p, "mod") {
let t = parse_str(p);
- if str::eq(t, ~"cdecl") {
- } else if str::eq(t, ~"rust") {
+ if str::eq(t, "cdecl") {
+ } 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); }
+ } else { p.fatal("unsupported abi: " + t); }
}
- expect_word(p, ~"mod");
+ expect_word(p, "mod");
let id = parse_ident(p);
let native_name;
if p.peek() == token::EQ {
// Newtype syntax
if p.peek() == token::EQ {
if p.get_bad_expr_words().contains_key(id) {
- p.fatal(~"found " + id
- + ~" in tag constructor position");
+ p.fatal("found " + id + " in tag constructor position");
}
p.bump();
let ty = parse_ty(p, false);
}
expect(p, token::SEMI);
p.get_id();
- let vr = {name: p.get_str(name),
- args: args, id: p.get_id()};
+ let vr = {name: p.get_str(name), args: args, id: p.get_id()};
variants += [spanned(vlo, vhi, vr)];
}
token::RBRACE. {/* empty */ }
_ {
- p.fatal(~"expected name of variant or '}' but found " +
+ p.fatal("expected name of variant or '}' but found " +
token::to_str(p.get_reader(), tok));
}
}
}
fn parse_auth(p: &parser) -> ast::_auth {
- if eat_word(p, ~"unsafe") {
+ if eat_word(p, "unsafe") {
ret ast::auth_unsafe;
} else { unexpected(p, p.peek()); }
}
fn parse_item(p: &parser, attrs: &[ast::attribute]) -> option::t<@ast::item> {
- if eat_word(p, ~"const") {
+ if eat_word(p, "const") {
ret some(parse_item_const(p, attrs));
- } else if eat_word(p, ~"inline") {
- expect_word(p, ~"fn");
+ } 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, ~"pure") {
- expect_word(p, ~"fn");
+ } else if eat_word(p, "pure") {
+ expect_word(p, "fn");
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, "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") {
+ 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; }
}
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("cannot path into import list");
}
p.bump();
}
- _ { p.fatal(~"expecting '::' or ';'"); }
+ _ { p.fatal("expecting '::' or ';'"); }
}
alt p.peek() {
token::IDENT(_, _) { identifiers += [parse_ident(p)]; }
+
//the lexer can't tell the different kinds of stars apart ) :
token::BINOP(token::STAR.) {
glob = true;
}
+
token::LBRACE. {
fn parse_import_ident(p: &parser) -> ast::import_ident {
let lo = p.get_lo_pos();
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");
+ 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.fatal("can't rename import list");
}
ret ast::view_item_import(i, identifiers, p.get_id());
}
alt p.peek() {
token::IDENT(i, _) {
p.bump();
- ret parse_rest_import_name(
- p, p.get_str(i), some(def_ident));
+ ret parse_rest_import_name(p, p.get_str(i), some(def_ident));
}
- _ { p.fatal(~"expecting an identifier"); }
+ _ { p.fatal("expecting an identifier"); }
}
}
p.bump();
ret parse_full_import_name(p, p.get_str(i));
}
- _ {
- ret parse_rest_import_name(
- p, p.get_str(i), none);
- }
+ _ { ret parse_rest_import_name(p, p.get_str(i), none); }
}
}
- _ { p.fatal(~"expecting an identifier"); }
+ _ { p.fatal("expecting an identifier"); }
}
}
fn parse_view_item(p: &parser) -> @ast::view_item {
let lo = p.get_lo_pos();
let the_item =
- if eat_word(p, ~"use") {
+ 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);
alt p.peek() {
token::IDENT(sid, false) {
let st = p.get_str(sid);
- ret str::eq(st, ~"use") || str::eq(st, ~"import") ||
- str::eq(st, ~"export");
+ ret str::eq(st, "use") || str::eq(st, "import") ||
+ str::eq(st, "export");
}
_ { ret false; }
}
ret items;
}
-fn parse_crate_from_source_file(input: &istr, cfg: &ast::crate_cfg,
+fn parse_crate_from_source_file(input: &str, cfg: &ast::crate_cfg,
sess: &parse_sess) -> @ast::crate {
let p = new_parser_from_file(sess, cfg, input, 0u, 0u, SOURCE_FILE);
ret parse_crate_mod(p, cfg);
}
-fn parse_crate_from_source_str(name: &istr, source: &istr,
- cfg: &ast::crate_cfg,
+fn parse_crate_from_source_str(name: &str, source: &str, cfg: &ast::crate_cfg,
sess: &parse_sess) -> @ast::crate {
let ftype = SOURCE_FILE;
let filemap = codemap::new_filemap(name, 0u, 0u);
sess.cm.files += [filemap];
let itr = @interner::mk(str::hash, str::eq);
- let rdr = lexer::new_reader(sess.cm, source,
- filemap, itr);
+ let rdr = lexer::new_reader(sess.cm, source, filemap, itr);
let p = new_parser(sess, cfg, rdr, ftype);
ret parse_crate_mod(p, cfg);
}
config: p.get_cfg()});
}
-fn parse_str(p: &parser) -> istr {
+fn parse_str(p: &parser) -> str {
alt p.peek() {
token::LIT_STR(s) { p.bump(); ret p.get_str(s); }
_ { fail; }
let expect_mod = vec::len(outer_attrs) > 0u;
let lo = p.get_lo_pos();
- if expect_mod || is_word(p, ~"mod") {
- expect_word(p, ~"mod");
+ if expect_mod || is_word(p, "mod") {
+ expect_word(p, "mod");
let id = parse_ident(p);
let file_opt =
alt p.peek() {
alt p.peek() {
+
// mod x = "foo.rs";
token::SEMI. {
let hi = p.get_hi_pos();
}
+
// 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);
} 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"); }
+ } else { ret p.fatal("expected crate directive"); }
}
fn parse_crate_directives(p: &parser, term: token::token,
// seeing the terminator next, so if we do see it then fail the same way
// parse_crate_directive would
if vec::len(first_outer_attr) > 0u && p.peek() == term {
- expect_word(p, ~"mod");
+ expect_word(p, "mod");
}
let cdirs: [@ast::crate_directive] = [];
ret cdirs;
}
-fn parse_crate_from_crate_file(input: &istr, cfg: &ast::crate_cfg,
+fn parse_crate_from_crate_file(input: &str, cfg: &ast::crate_cfg,
sess: &parse_sess) -> @ast::crate {
let p = new_parser_from_file(sess, cfg, input, 0u, 0u, CRATE_FILE);
let lo = p.get_lo_pos();
- let prefix =
- std::fs::dirname(p.get_filemap().name);
+ let prefix = std::fs::dirname(p.get_filemap().name);
let leading_attrs = parse_inner_attrs_and_next(p);
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: [istr] = [];
+ let deps: [str] = [];
let cx =
@{p: p,
mode: eval::mode_parse,
config: p.get_cfg()});
}
-fn parse_crate_from_file(input: &istr, cfg: &ast::crate_cfg,
- sess: &parse_sess) -> @ast::crate {
- if str::ends_with(input, ~".rc") {
+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") {
+ } 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
}
EOF;
}
-fn binop_to_str(o: binop) -> istr {
+fn binop_to_str(o: binop) -> str {
alt o {
- PLUS. { ret ~"+"; }
- MINUS. { ret ~"-"; }
- STAR. { ret ~"*"; }
- SLASH. { ret ~"/"; }
- PERCENT. { ret ~"%"; }
- CARET. { ret ~"^"; }
- AND. { ret ~"&"; }
- OR. { ret ~"|"; }
- LSL. { ret ~"<<"; }
- LSR. { ret ~">>"; }
- ASR. { ret ~">>>"; }
+ PLUS. { ret "+"; }
+ MINUS. { ret "-"; }
+ STAR. { ret "*"; }
+ SLASH. { ret "/"; }
+ PERCENT. { ret "%"; }
+ CARET. { ret "^"; }
+ AND. { ret "&"; }
+ OR. { ret "|"; }
+ LSL. { ret "<<"; }
+ LSR. { ret ">>"; }
+ ASR. { ret ">>>"; }
}
}
-fn to_str(r: lexer::reader, t: token) -> istr {
+fn to_str(r: lexer::reader, t: token) -> str {
alt t {
- EQ. { ret ~"="; }
- LT. { ret ~"<"; }
- LE. { ret ~"<="; }
- EQEQ. { ret ~"=="; }
- NE. { ret ~"!="; }
- GE. { ret ~">="; }
- GT. { ret ~">"; }
- NOT. { ret ~"!"; }
- TILDE. { ret ~"~"; }
- OROR. { ret ~"||"; }
- ANDAND. { ret ~"&&"; }
+ EQ. { ret "="; }
+ LT. { ret "<"; }
+ LE. { ret "<="; }
+ EQEQ. { ret "=="; }
+ NE. { ret "!="; }
+ GE. { ret ">="; }
+ GT. { ret ">"; }
+ NOT. { ret "!"; }
+ TILDE. { ret "~"; }
+ OROR. { ret "||"; }
+ ANDAND. { ret "&&"; }
BINOP(op) { ret binop_to_str(op); }
- BINOPEQ(op) { ret binop_to_str(op) + ~"="; }
+ BINOPEQ(op) { ret binop_to_str(op) + "="; }
+
/* Structural symbols */
AT. {
- ret ~"@";
+ ret "@";
}
- DOT. { ret ~"."; }
- ELLIPSIS. { ret ~"..."; }
- COMMA. { ret ~","; }
- SEMI. { ret ~";"; }
- COLON. { ret ~":"; }
- MOD_SEP. { ret ~"::"; }
- QUES. { ret ~"?"; }
- RARROW. { ret ~"->"; }
- LARROW. { ret ~"<-"; }
- DARROW. { ret ~"<->"; }
- LPAREN. { ret ~"("; }
- RPAREN. { ret ~")"; }
- LBRACKET. { ret ~"["; }
- RBRACKET. { ret ~"]"; }
- LBRACE. { ret ~"{"; }
- RBRACE. { ret ~"}"; }
- POUND. { ret ~"#"; }
- POUND_LBRACE. { ret ~"#{"; }
- POUND_LT. { ret ~"#<"; }
+ DOT. { ret "."; }
+ ELLIPSIS. { ret "..."; }
+ COMMA. { ret ","; }
+ SEMI. { ret ";"; }
+ COLON. { ret ":"; }
+ MOD_SEP. { ret "::"; }
+ QUES. { ret "?"; }
+ RARROW. { ret "->"; }
+ LARROW. { ret "<-"; }
+ DARROW. { ret "<->"; }
+ LPAREN. { ret "("; }
+ RPAREN. { ret ")"; }
+ LBRACKET. { ret "["; }
+ RBRACKET. { ret "]"; }
+ LBRACE. { ret "{"; }
+ RBRACE. { ret "}"; }
+ POUND. { ret "#"; }
+ POUND_LBRACE. { ret "#{"; }
+ POUND_LT. { ret "#<"; }
+
/* Literals */
}
LIT_UINT(u) { ret uint::to_str(u, 10u); }
LIT_MACH_INT(tm, i) {
- ret int::to_str(i, 10u) + ~"_" + ty_mach_to_str(tm);
+ ret int::to_str(i, 10u) + "_" + ty_mach_to_str(tm);
}
LIT_MACH_FLOAT(tm, s) {
- ret interner::get::<istr>(
- *r.get_interner(), s) + ~"_" +
- ty_mach_to_str(tm);
- }
- LIT_FLOAT(s) {
- ret interner::get::<istr>(*r.get_interner(), s);
+ ret interner::get::<str>(*r.get_interner(), s) + "_" +
+ ty_mach_to_str(tm);
}
+ LIT_FLOAT(s) { ret interner::get::<str>(*r.get_interner(), s); }
LIT_STR(s) { // FIXME: escape.
- ret ~"\"" +
- interner::get::<istr>(*r.get_interner(), s)
- + ~"\"";
+ ret "\"" + interner::get::<str>(*r.get_interner(), s) + "\"";
}
LIT_CHAR(c) {
// FIXME: escape.
- let tmp = ~"'";
+ let tmp = "'";
str::push_char(tmp, c);
str::push_byte(tmp, '\'' as u8);
ret tmp;
}
- LIT_BOOL(b) { if b { ret ~"true"; } else { ret ~"false"; } }
+ LIT_BOOL(b) { if b { ret "true"; } else { ret "false"; } }
+
/* Name components */
IDENT(s, _) {
- ret interner::get::<istr>(*r.get_interner(), s);
+ ret interner::get::<str>(*r.get_interner(), s);
}
- IDX(i) { ret ~"_" + int::to_str(i, 10u); }
- UNDERSCORE. { ret ~"_"; }
- BRACEQUOTE(_) { ret ~"<bracequote>"; }
- EOF. { ret ~"<eof>"; }
+ IDX(i) { ret "_" + int::to_str(i, 10u); }
+ UNDERSCORE. { ret "_"; }
+ BRACEQUOTE(_) { ret "<bracequote>"; }
+ EOF. { ret "<eof>"; }
}
}
type begin_t = {offset: int, breaks: breaks};
-tag token { STRING(istr, int); BREAK(break_t); BEGIN(begin_t); END; EOF; }
+tag token { STRING(str, int); BREAK(break_t); BEGIN(begin_t); END; EOF; }
-fn tok_str(t: token) -> istr {
+fn tok_str(t: token) -> str {
alt t {
- STRING(s, len) {
- ret #fmt[~"STR(%s,%d)", s, len];
- }
- BREAK(_) { ret ~"BREAK"; }
- BEGIN(_) { ret ~"BEGIN"; }
- END. { ret ~"END"; }
- EOF. { ret ~"EOF"; }
+ STRING(s, len) { ret #fmt["STR(%s,%d)", s, len]; }
+ BREAK(_) { ret "BREAK"; }
+ BEGIN(_) { ret "BEGIN"; }
+ END. { ret "END"; }
+ EOF. { ret "EOF"; }
}
}
fn buf_str(toks: &[mutable token], szs: &[mutable int], left: uint,
- right: uint, lim: uint) -> istr {
+ right: uint, lim: uint) -> str {
let n = vec::len(toks);
assert (n == vec::len(szs));
let i = left;
let L = lim;
- let s = ~"[";
+ let s = "[";
while i != right && L != 0u {
L -= 1u;
- if i != left { s += ~", "; }
- s += #fmt[~"%d=%s", szs[i], tok_str(toks[i])];
+ if i != left { s += ", "; }
+ s += #fmt["%d=%s", szs[i], tok_str(toks[i])];
i += 1u;
i %= n;
}
- s += ~"]";
+ s += "]";
ret s;
}
// 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);
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 {
left = 0u;
right = 0u;
} else { self.advance_right(); }
- log #fmt[~"pp BEGIN/buffer [%u,%u]", left, right];
+ 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;
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;
}
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;
}
}
fn check_stream() {
- log #fmt[~"check_stream [%u, %u] with left_total=%d, right_total=%d",
+ 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)",
+ 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] {
}
fn print_newline(amount: int) {
log #fmt["NEWLINE %d", amount];
- out.write_str(~"\n");
+ out.write_str("\n");
pending_indentation = 0;
self.indent(amount);
}
if n != 0u { top = print_stack[n - 1u]; }
ret top;
}
- fn write_str(s: &istr) {
+ fn write_str(s: &str) {
while pending_indentation > 0 {
- out.write_str(~" ");
+ out.write_str(" ");
pending_indentation -= 1;
}
out.write_str(s);
}
fn print(x: token, L: int) {
- log #fmt["print %s %d (remaining line space=%d)",
- tok_str(x), L,
+ log #fmt["print %s %d (remaining line space=%d)", tok_str(x), L,
space];
log buf_str(token, size, left, right, 6u);
alt x {
fn eof(p: printer) { p.pretty_print(EOF); }
-fn word(p: printer, wrd: &istr) {
+fn word(p: printer, wrd: &str) {
p.pretty_print(STRING(wrd, str::char_len(wrd) as int));
}
-fn huge_word(p: printer, wrd: &istr) {
+fn huge_word(p: printer, wrd: &str) {
p.pretty_print(STRING(wrd, size_infinity));
}
-fn zero_word(p: printer, wrd: &istr) { p.pretty_print(STRING(wrd, 0)); }
+fn zero_word(p: printer, wrd: &str) { p.pretty_print(STRING(wrd, 0)); }
fn spaces(p: printer, n: uint) { break_offset(p, n, 0); }
// Requires you to pass an input filename and reader so that
// it can scan the input text for comments and literals to
// copy forward.
-fn print_crate(cm: &codemap, crate: @ast::crate, filename: &istr,
+fn print_crate(cm: &codemap, crate: @ast::crate, filename: &str,
in: io::reader, out: io::writer, ann: &pp_ann) {
let boxes: [pp::breaks] = [];
- let r = lexer::gather_comments_and_literals(
- cm, filename, in);
+ let r = lexer::gather_comments_and_literals(cm, filename, in);
let s =
@{s: pp::mk_printer(out, default_columns),
cm: some(cm),
eof(s.s);
}
-fn ty_to_str(ty: &@ast::ty) -> istr { be to_str(ty, print_type); }
+fn ty_to_str(ty: &@ast::ty) -> str { be to_str(ty, print_type); }
-fn pat_to_str(pat: &@ast::pat) -> istr { be to_str(pat, print_pat); }
+fn pat_to_str(pat: &@ast::pat) -> str { be to_str(pat, print_pat); }
-fn expr_to_str(e: &@ast::expr) -> istr { be to_str(e, print_expr); }
+fn expr_to_str(e: &@ast::expr) -> str { be to_str(e, print_expr); }
-fn stmt_to_str(s: &ast::stmt) -> istr { be to_str(s, print_stmt); }
+fn stmt_to_str(s: &ast::stmt) -> str { be to_str(s, print_stmt); }
-fn item_to_str(i: &@ast::item) -> istr { be to_str(i, print_item); }
+fn item_to_str(i: &@ast::item) -> str { be to_str(i, print_item); }
-fn path_to_str(p: &ast::path) -> istr {
+fn path_to_str(p: &ast::path) -> str {
be to_str(p, bind print_path(_, _, false));
}
-fn fun_to_str(f: &ast::_fn, name: &ast::ident,
- params: &[ast::ty_param]) -> istr {
+fn fun_to_str(f: &ast::_fn, name: &ast::ident, params: &[ast::ty_param]) ->
+ str {
let writer = io::string_writer();
let s = rust_printer(writer.get_writer());
print_fn(s, f.decl, f.proto, name, params, f.decl.constraints);
ret writer.get_str();
}
-fn block_to_str(blk: &ast::blk) -> istr {
+fn block_to_str(blk: &ast::blk) -> str {
let writer = io::string_writer();
let s = rust_printer(writer.get_writer());
// containing cbox, will be closed by print-block at }
ret writer.get_str();
}
-fn meta_item_to_str(mi: &ast::meta_item) -> istr {
+fn meta_item_to_str(mi: &ast::meta_item) -> str {
ret to_str(@mi, print_meta_item);
}
-fn attribute_to_str(attr: &ast::attribute) -> istr {
+fn attribute_to_str(attr: &ast::attribute) -> str {
be to_str(attr, print_attribute);
}
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 nbsp(s: &ps) { word(s.s, " "); }
-fn word_nbsp(s: &ps, w: &istr) { word(s.s, w); nbsp(s); }
+fn word_nbsp(s: &ps, w: &str) { word(s.s, w); nbsp(s); }
-fn word_space(s: &ps, w: &istr) { word(s.s, w); space(s.s); }
+fn word_space(s: &ps, w: &str) { word(s.s, w); space(s.s); }
-fn popen(s: &ps) { word(s.s, ~"("); }
+fn popen(s: &ps) { word(s.s, "("); }
-fn pclose(s: &ps) { word(s.s, ~")"); }
+fn pclose(s: &ps) { word(s.s, ")"); }
-fn head(s: &ps, w: &istr) {
+fn head(s: &ps, w: &str) {
// outer-box is consistent
cbox(s, indent_unit);
// head-box is inconsistent
}
fn bopen(s: &ps) {
- word(s.s, ~"{");
+ word(s.s, "{");
end(s); // close the head-box
}
fn bclose_(s: &ps, span: codemap::span, indented: uint) {
maybe_print_comment(s, span.hi);
break_offset_if_not_bol(s, 1u, -(indented as int));
- word(s.s, ~"}");
+ word(s.s, "}");
end(s); // close the outer-box
}
fn bclose(s: &ps, span: codemap::span) { bclose_(s, span, indent_unit); }
// Synthesizes a comment that was not textually present in the original source
// file.
-fn synth_comment(s: &ps, text: &istr) {
- word(s.s, ~"/*");
+fn synth_comment(s: &ps, text: &str) {
+ word(s.s, "/*");
space(s.s);
word(s.s, text);
space(s.s);
- word(s.s, ~"*/");
+ word(s.s, "*/");
}
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 {
- if first { first = false; } else { word_space(s, ~","); }
+ if first { first = false; } else { word_space(s, ","); }
op(s, elt);
}
end(s);
op(s, elt);
i += 1u;
if i < len {
- word(s.s, ~",");
+ word(s.s, ",");
maybe_print_trailing_comment(s, get_span(elt),
some(get_span(elts[i]).hi));
space_if_not_bol(s);
maybe_print_comment(s, ty.span.lo);
ibox(s, 0u);
alt ty.node {
- ast::ty_nil. { word(s.s, ~"()"); }
- ast::ty_bool. { word(s.s, ~"bool"); }
- ast::ty_bot. { word(s.s, ~"!"); }
- ast::ty_int. { word(s.s, ~"int"); }
- ast::ty_uint. { word(s.s, ~"uint"); }
- ast::ty_float. { word(s.s, ~"float"); }
- ast::ty_machine(tm) {
- word(s.s, ast_util::ty_mach_to_str(tm));
- }
- ast::ty_char. { word(s.s, ~"char"); }
- ast::ty_istr. { word(s.s, ~"str"); }
- ast::ty_box(mt) { word(s.s, ~"@"); print_mt(s, mt); }
+ ast::ty_nil. { word(s.s, "()"); }
+ ast::ty_bool. { word(s.s, "bool"); }
+ ast::ty_bot. { word(s.s, "!"); }
+ ast::ty_int. { word(s.s, "int"); }
+ ast::ty_uint. { word(s.s, "uint"); }
+ ast::ty_float. { word(s.s, "float"); }
+ ast::ty_machine(tm) { word(s.s, ast_util::ty_mach_to_str(tm)); }
+ ast::ty_char. { word(s.s, "char"); }
+ ast::ty_istr. { word(s.s, "str"); }
+ ast::ty_box(mt) { word(s.s, "@"); print_mt(s, mt); }
ast::ty_vec(mt) {
- word(s.s, ~"[");
+ word(s.s, "[");
alt mt.mut {
- ast::mut. { word_space(s, ~"mutable"); }
- ast::maybe_mut. { word_space(s, ~"mutable?"); }
+ ast::mut. { word_space(s, "mutable"); }
+ ast::maybe_mut. { word_space(s, "mutable?"); }
ast::imm. { }
}
print_type(s, mt.ty);
- word(s.s, ~"]");
+ word(s.s, "]");
}
- ast::ty_ptr(mt) { word(s.s, ~"*"); print_mt(s, mt); }
- ast::ty_task. { word(s.s, ~"task"); }
+ ast::ty_ptr(mt) { word(s.s, "*"); print_mt(s, mt); }
+ ast::ty_task. { word(s.s, "task"); }
ast::ty_port(t) {
- word(s.s, ~"port<");
+ word(s.s, "port<");
print_type(s, t);
- word(s.s, ~">");
+ word(s.s, ">");
}
ast::ty_chan(t) {
- word(s.s, ~"chan<");
+ word(s.s, "chan<");
print_type(s, t);
- word(s.s, ~">");
+ word(s.s, ">");
}
ast::ty_rec(fields) {
- word(s.s, ~"{");
+ word(s.s, "{");
fn print_field(s: &ps, f: &ast::ty_field) {
cbox(s, indent_unit);
print_mutability(s, f.node.mt.mut);
word(s.s, f.node.ident);
- word_space(s, ~":");
+ word_space(s, ":");
print_type(s, f.node.mt.ty);
end(s);
}
fn get_span(f: &ast::ty_field) -> codemap::span { ret f.span; }
commasep_cmnt(s, consistent, fields, print_field, get_span);
- word(s.s, ~"}");
+ word(s.s, "}");
}
ast::ty_tup(elts) {
popen(s);
pclose(s);
}
ast::ty_fn(proto, inputs, output, cf, constrs) {
- print_ty_fn(s, proto, none::<istr>, inputs, output, cf, constrs);
+ print_ty_fn(s, proto, none::<str>, inputs, output, cf, constrs);
}
ast::ty_obj(methods) {
- head(s, ~"obj");
+ head(s, "obj");
bopen(s);
for m: ast::ty_method in methods {
hardbreak_if_not_bol(s);
maybe_print_comment(s, m.span.lo);
print_ty_fn(s, m.node.proto, some(m.node.ident), m.node.inputs,
m.node.output, m.node.cf, m.node.constrs);
- word(s.s, ~";");
+ word(s.s, ";");
end(s);
}
bclose(s, ty.span);
}
ast::ty_path(path, _) { print_path(s, path, false); }
- ast::ty_type. { word(s.s, ~"type"); }
+ ast::ty_type. { word(s.s, "type"); }
ast::ty_constr(t, cs) {
print_type(s, t);
space(s.s);
ast::native_item_ty. {
ibox(s, indent_unit);
ibox(s, 0u);
- word_nbsp(s, ~"type");
+ word_nbsp(s, "type");
word(s.s, item.ident);
end(s); // end the inner ibox
- word(s.s, ~";");
+ word(s.s, ";");
end(s); // end the outer ibox
}
+
ast::native_item_fn(lname, decl, typarams) {
print_fn(s, decl, ast::proto_fn, item.ident, typarams,
decl.constraints);
alt lname {
none. { }
- some(ss) {
- space(s.s);
- word_space(s, ~"=");
- print_string(s, ss);
- }
+ some(ss) { space(s.s); word_space(s, "="); print_string(s, ss); }
}
end(s); // end head-ibox
- word(s.s, ~";");
+ word(s.s, ";");
end(s); // end the outer fn box
}
}
s.ann.pre(ann_node);
alt item.node {
ast::item_const(ty, expr) {
- head(s, ~"const");
- word_space(s, item.ident + ~":");
+ head(s, "const");
+ word_space(s, item.ident + ":");
print_type(s, ty);
space(s.s);
end(s); // end the head-ibox
- word_space(s, ~"=");
+ word_space(s, "=");
print_expr(s, expr);
- word(s.s, ~";");
+ word(s.s, ";");
end(s); // end the outer cbox
}
ast::item_fn(_fn, typarams) {
print_fn(s, _fn.decl, _fn.proto, item.ident, typarams,
_fn.decl.constraints);
- word(s.s, ~" ");
+ word(s.s, " ");
print_block(s, _fn.body);
}
ast::item_mod(_mod) {
- head(s, ~"mod");
+ head(s, "mod");
word_nbsp(s, item.ident);
bopen(s);
print_mod(s, _mod, item.attrs);
bclose(s, item.span);
}
ast::item_native_mod(nmod) {
- head(s, ~"native");
+ head(s, "native");
alt nmod.abi {
- ast::native_abi_llvm. { word_nbsp(s, ~"\"llvm\""); }
- ast::native_abi_rust. { word_nbsp(s, ~"\"rust\""); }
- ast::native_abi_cdecl. { word_nbsp(s, ~"\"cdecl\""); }
+ ast::native_abi_llvm. { word_nbsp(s, "\"llvm\""); }
+ ast::native_abi_rust. { word_nbsp(s, "\"rust\""); }
+ ast::native_abi_cdecl. { word_nbsp(s, "\"cdecl\""); }
ast::native_abi_rust_intrinsic. {
- word_nbsp(s, ~"\"rust-intrinsic\"");
+ word_nbsp(s, "\"rust-intrinsic\"");
}
- ast::native_abi_x86stdcall. { word_nbsp(s, ~"\"x86stdcall\""); }
+ ast::native_abi_x86stdcall. { word_nbsp(s, "\"x86stdcall\""); }
}
- word_nbsp(s, ~"mod");
+ word_nbsp(s, "mod");
word_nbsp(s, item.ident);
if !str::eq(nmod.native_name, item.ident) {
- word_space(s, ~"=");
+ word_space(s, "=");
print_string(s, nmod.native_name);
nbsp(s);
}
ast::item_ty(ty, params) {
ibox(s, indent_unit);
ibox(s, 0u);
- word_nbsp(s, ~"type");
+ word_nbsp(s, "type");
word(s.s, item.ident);
print_type_params(s, params);
end(s); // end the inner ibox
space(s.s);
- word_space(s, ~"=");
+ word_space(s, "=");
print_type(s, ty);
- word(s.s, ~";");
+ word(s.s, ";");
end(s); // end the outer ibox
}
ast::item_tag(variants, params) {
vec::len(variants[0].node.args) == 1u;
if newtype {
ibox(s, indent_unit);
- word_space(s, ~"tag");
- } else { head(s, ~"tag"); }
+ word_space(s, "tag");
+ } else { head(s, "tag"); }
word(s.s, item.ident);
print_type_params(s, params);
space(s.s);
if newtype {
- word_space(s, ~"=");
+ word_space(s, "=");
print_type(s, variants[0].node.args[0].ty);
- word(s.s, ~";");
+ word(s.s, ";");
end(s);
} else {
bopen(s);
commasep(s, consistent, v.node.args, print_variant_arg);
pclose(s);
}
- word(s.s, ~";");
+ word(s.s, ";");
maybe_print_trailing_comment(s, v.span, none::<uint>);
}
bclose(s, item.span);
}
}
ast::item_obj(_obj, params, _) {
- head(s, ~"obj");
+ head(s, "obj");
word(s.s, item.ident);
print_type_params(s, params);
popen(s);
fn print_field(s: &ps, field: &ast::obj_field) {
ibox(s, indent_unit);
print_mutability(s, field.mut);
- word_space(s, field.ident + ~":");
+ word_space(s, field.ident + ":");
print_type(s, field.ty);
end(s);
}
maybe_print_comment(s, meth.span.lo);
print_fn(s, meth.node.meth.decl, meth.node.meth.proto,
meth.node.ident, typarams, []);
- word(s.s, ~" ");
+ word(s.s, " ");
print_block(s, meth.node.meth.body);
}
bclose(s, item.span);
}
ast::item_res(dt, dt_id, tps, ct_id) {
- head(s, ~"resource");
+ head(s, "resource");
word(s.s, item.ident);
print_type_params(s, tps);
popen(s);
- word_space(s, dt.decl.inputs[0].ident + ~":");
+ word_space(s, dt.decl.inputs[0].ident + ":");
print_type(s, dt.decl.inputs[0].ty);
pclose(s);
space(s.s);
alt attr.node.style {
ast::attr_inner. {
print_attribute(s, attr);
- word(s.s, ~";");
+ word(s.s, ";");
count += 1;
}
_ {/* fallthrough */ }
fn print_attribute(s: &ps, attr: &ast::attribute) {
hardbreak_if_not_bol(s);
maybe_print_comment(s, attr.span.lo);
- word(s.s, ~"#[");
+ word(s.s, "#[");
print_meta_item(s, @attr.node.value);
- word(s.s, ~"]");
+ word(s.s, "]");
}
fn print_stmt(s: &ps, st: &ast::stmt) {
ast::stmt_decl(decl, _) { print_decl(s, decl); }
ast::stmt_expr(expr, _) { space_if_not_bol(s); print_expr(s, expr); }
}
- if parse::parser::stmt_ends_with_semi(st) { word(s.s, ~";"); }
+ if parse::parser::stmt_ends_with_semi(st) { word(s.s, ";"); }
maybe_print_trailing_comment(s, st.span, none::<uint>);
}
fn print_possibly_embedded_block(s: &ps, blk: &ast::blk, embedded: embed_type,
indented: uint) {
- alt blk.node.rules {
- ast::unchecked. { word(s.s, ~"unchecked"); }
- _ {}
- }
+ alt blk.node.rules { ast::unchecked. { word(s.s, "unchecked"); } _ { } }
maybe_print_comment(s, blk.span.lo);
let ann_node = node_block(s, blk);
s.ann.pre(ann_node);
alt embedded {
- block_macro. { word(s.s, ~"#{"); end(s); }
+ block_macro. { word(s.s, "#{"); end(s); }
block_block_fn. { end(s); }
block_normal. { bopen(s); }
}
_ { 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
fn print_if(s: &ps, test: &@ast::expr, blk: &ast::blk,
elseopt: &option::t<@ast::expr>, chk: bool) {
- head(s, ~"if");
- if chk { word_nbsp(s, ~"check"); }
+ head(s, "if");
+ if chk { word_nbsp(s, "check"); }
print_maybe_parens_discrim(s, test);
space(s.s);
print_block(s, blk);
alt _else.node {
+
// "another else-if"
ast::expr_if(i, t, e) {
cbox(s, indent_unit - 1u);
ibox(s, 0u);
- word(s.s, ~" else if ");
+ word(s.s, " else if ");
print_expr(s, i);
space(s.s);
print_block(s, t);
}
+
// "final else"
ast::expr_block(b) {
cbox(s, indent_unit - 1u);
ibox(s, 0u);
- word(s.s, ~" else ");
+ word(s.s, " else ");
print_block(s, b);
}
}
fn print_mac(s: &ps, m: &ast::mac) {
alt m.node {
ast::mac_invoc(path, arg, body) {
- word(s.s, ~"#");
+ 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'
}
ast::mac_embed_type(ty) {
- word(s.s, ~"#<");
+ word(s.s, "#<");
print_type(s, ty);
- word(s.s, ~">");
+ word(s.s, ">");
}
ast::mac_embed_block(blk) {
print_possibly_embedded_block(s, blk, block_normal, indent_unit);
}
- ast::mac_ellipsis. { word(s.s, ~"..."); }
+ ast::mac_ellipsis. { word(s.s, "..."); }
}
}
alt expr.node {
ast::expr_vec(exprs, mut) {
ibox(s, indent_unit);
- word(s.s, ~"[");
+ word(s.s, "[");
if mut == ast::mut {
- word(s.s, ~"mutable");
+ word(s.s, "mutable");
if vec::len(exprs) > 0u { nbsp(s); }
}
commasep_exprs(s, inconsistent, exprs);
- word(s.s, ~"]");
+ word(s.s, "]");
end(s);
}
ast::expr_rec(fields, wth) {
fn print_field(s: &ps, field: &ast::field) {
ibox(s, indent_unit);
- if field.node.mut == ast::mut { word_nbsp(s, ~"mutable"); }
+ if field.node.mut == ast::mut { word_nbsp(s, "mutable"); }
word(s.s, field.node.ident);
- word_space(s, ~":");
+ word_space(s, ":");
print_expr(s, field.node.expr);
end(s);
}
fn get_span(field: &ast::field) -> codemap::span { ret field.span; }
- word(s.s, ~"{");
+ word(s.s, "{");
commasep_cmnt(s, consistent, fields, print_field, get_span);
alt wth {
some(expr) {
if vec::len(fields) > 0u { space(s.s); }
ibox(s, indent_unit);
- word_space(s, ~"with");
+ word_space(s, "with");
print_expr(s, expr);
end(s);
}
_ { }
}
- word(s.s, ~"}");
+ word(s.s, "}");
}
ast::expr_tup(exprs) {
popen(s);
pclose(s);
}
ast::expr_self_method(ident) {
- word(s.s, ~"self.");
+ word(s.s, "self.");
print_ident(s, ident);
}
ast::expr_bind(func, args) {
fn print_opt(s: &ps, expr: &option::t<@ast::expr>) {
alt expr {
some(expr) { print_expr(s, expr); }
- _ { word(s.s, ~"_"); }
+ _ { word(s.s, "_"); }
}
}
- word_nbsp(s, ~"bind");
+ word_nbsp(s, "bind");
print_expr(s, func);
popen(s);
commasep(s, inconsistent, args, print_opt);
ast::expr_cast(expr, ty) {
print_maybe_parens(s, expr, parse::parser::as_prec);
space(s.s);
- word_space(s, ~"as");
+ word_space(s, "as");
print_type(s, ty);
}
ast::expr_if(test, blk, elseopt) {
ast::expr_ternary(test, then, els) {
print_expr(s, test);
space(s.s);
- word_space(s, ~"?");
+ word_space(s, "?");
print_expr(s, then);
space(s.s);
- word_space(s, ~":");
+ word_space(s, ":");
print_expr(s, els);
}
ast::expr_while(test, blk) {
- head(s, ~"while");
+ head(s, "while");
print_maybe_parens_discrim(s, test);
space(s.s);
print_block(s, blk);
}
ast::expr_for(decl, expr, blk) {
- head(s, ~"for");
+ head(s, "for");
print_for_decl(s, decl, expr);
space(s.s);
print_block(s, blk);
}
ast::expr_for_each(decl, expr, blk) {
- head(s, ~"for each");
+ head(s, "for each");
print_for_decl(s, decl, expr);
space(s.s);
print_block(s, blk);
}
ast::expr_do_while(blk, expr) {
- head(s, ~"do");
+ head(s, "do");
space(s.s);
print_block(s, blk);
space(s.s);
- word_space(s, ~"while");
+ word_space(s, "while");
print_expr(s, expr);
}
ast::expr_alt(expr, arms) {
cbox(s, alt_indent_unit);
ibox(s, 4u);
- word_nbsp(s, ~"alt");
+ word_nbsp(s, "alt");
print_maybe_parens_discrim(s, expr);
space(s.s);
bopen(s);
for p: @ast::pat in arm.pats {
if first {
first = false;
- } else { space(s.s); word_space(s, ~"|"); }
+ } else { space(s.s); word_space(s, "|"); }
print_pat(s, p);
}
space(s.s);
alt arm.guard {
- some(e) {
- word_space(s, ~"when");
- print_expr(s, e);
- space(s.s);
- }
- none. {}
+ some(e) { word_space(s, "when"); print_expr(s, e); space(s.s); }
+ none. { }
}
print_possibly_embedded_block(s, arm.body, block_normal,
alt_indent_unit);
cbox(s, indent_unit);
// head-box, will be closed by print-block at start
ibox(s, 0u);
- word(s.s, ~"{");
+ word(s.s, "{");
print_fn_block_args(s, f.decl);
print_possibly_embedded_block(s, f.body, block_block_fn,
indent_unit);
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);
- word_space(s, ~"<-");
+ word_space(s, "<-");
print_expr(s, rhs);
}
ast::expr_assign(lhs, rhs) {
print_expr(s, lhs);
space(s.s);
- word_space(s, ~"=");
+ word_space(s, "=");
print_expr(s, rhs);
}
ast::expr_swap(lhs, rhs) {
print_expr(s, lhs);
space(s.s);
- word_space(s, ~"<->");
+ word_space(s, "<->");
print_expr(s, rhs);
}
ast::expr_assign_op(op, lhs, rhs) {
print_expr(s, lhs);
space(s.s);
word(s.s, ast_util::binop_to_str(op));
- word_space(s, ~"=");
+ word_space(s, "=");
print_expr(s, rhs);
}
ast::expr_field(expr, id) {
print_expr_parens_if_unary(s, expr);
- word(s.s, ~".");
+ word(s.s, ".");
word(s.s, id);
}
ast::expr_index(expr, index) {
print_expr_parens_if_unary(s, expr);
- word(s.s, ~"[");
+ word(s.s, "[");
print_expr(s, index);
- word(s.s, ~"]");
+ word(s.s, "]");
}
ast::expr_path(path) { print_path(s, path, true); }
ast::expr_fail(maybe_fail_val) {
- word(s.s, ~"fail");
+ word(s.s, "fail");
alt maybe_fail_val {
- some(expr) { word(s.s, ~" "); print_expr(s, expr); }
+ some(expr) { word(s.s, " "); print_expr(s, expr); }
_ { }
}
}
- ast::expr_break. { word(s.s, ~"break"); }
- ast::expr_cont. { word(s.s, ~"cont"); }
+ ast::expr_break. { word(s.s, "break"); }
+ ast::expr_cont. { word(s.s, "cont"); }
ast::expr_ret(result) {
- word(s.s, ~"ret");
+ word(s.s, "ret");
alt result {
- some(expr) { word(s.s, ~" "); print_expr(s, expr); }
+ some(expr) { word(s.s, " "); print_expr(s, expr); }
_ { }
}
}
ast::expr_put(result) {
- word(s.s, ~"put");
+ word(s.s, "put");
alt result {
- some(expr) { word(s.s, ~" "); print_expr(s, expr); }
+ some(expr) { word(s.s, " "); print_expr(s, expr); }
_ { }
}
}
- ast::expr_be(result) { word_nbsp(s, ~"be"); print_expr(s, result); }
+ ast::expr_be(result) { word_nbsp(s, "be"); print_expr(s, result); }
ast::expr_log(lvl, expr) {
- alt lvl {
- 1 { word_nbsp(s, ~"log"); } 0 { word_nbsp(s, ~"log_err"); }
- }
+ alt lvl { 1 { word_nbsp(s, "log"); } 0 { word_nbsp(s, "log_err"); } }
print_expr(s, expr);
}
ast::expr_check(m, expr) {
alt m {
- ast::unchecked. { word_nbsp(s, ~"claim"); }
- ast::checked. { word_nbsp(s, ~"check"); }
+ ast::unchecked. { word_nbsp(s, "claim"); }
+ ast::checked. { word_nbsp(s, "check"); }
}
popen(s);
print_expr(s, expr);
pclose(s);
}
ast::expr_assert(expr) {
- word_nbsp(s, ~"assert");
+ word_nbsp(s, "assert");
popen(s);
print_expr(s, expr);
pclose(s);
}
ast::expr_mac(m) { print_mac(s, m); }
ast::expr_anon_obj(anon_obj) {
- head(s, ~"obj");
+ head(s, "obj");
// Fields
popen(s);
fn print_field(s: &ps, field: &ast::anon_obj_field) {
ibox(s, indent_unit);
print_mutability(s, field.mut);
- word_space(s, field.ident + ~":");
+ word_space(s, field.ident + ":");
print_type(s, field.ty);
space(s.s);
- word_space(s, ~"=");
+ word_space(s, "=");
print_expr(s, field.expr);
end(s);
}
maybe_print_comment(s, meth.span.lo);
print_fn(s, meth.node.meth.decl, meth.node.meth.proto,
meth.node.ident, typarams, []);
- word(s.s, ~" ");
+ 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);
print_pat(s, loc.node.pat);
alt loc.node.ty.node {
ast::ty_infer. { }
- _ { word_space(s, ~":"); print_type(s, loc.node.ty); }
+ _ { word_space(s, ":"); print_type(s, loc.node.ty); }
}
}
ast::decl_local(locs) {
space_if_not_bol(s);
ibox(s, indent_unit);
- word_nbsp(s, ~"let");
+ word_nbsp(s, "let");
fn print_local(s: &ps, loc: &@ast::local) {
ibox(s, indent_unit);
print_local_decl(s, loc);
some(init) {
nbsp(s);
alt init.op {
- ast::init_assign. { word_space(s, ~"="); }
- ast::init_move. { word_space(s, ~"<-"); }
+ ast::init_assign. { word_space(s, "="); }
+ ast::init_move. { word_space(s, "<-"); }
}
print_expr(s, init.expr);
}
}
}
-fn print_ident(s: &ps, ident: &ast::ident) {
- word(s.s, ident);
-}
+fn print_ident(s: &ps, ident: &ast::ident) { word(s.s, ident); }
fn print_for_decl(s: &ps, loc: &@ast::local, coll: &@ast::expr) {
print_local_decl(s, loc);
space(s.s);
- word_space(s, ~"in");
+ word_space(s, "in");
print_expr(s, coll);
}
fn print_path(s: &ps, path: &ast::path, colons_before_params: bool) {
maybe_print_comment(s, path.span.lo);
- if path.node.global { word(s.s, ~"::"); }
+ if path.node.global { word(s.s, "::"); }
let first = true;
for id: ast::ident in path.node.idents {
- if first { first = false; } else { word(s.s, ~"::"); }
+ if first { first = false; } else { word(s.s, "::"); }
word(s.s, id);
}
if vec::len(path.node.types) > 0u {
- if colons_before_params { word(s.s, ~"::"); }
- word(s.s, ~"<");
+ if colons_before_params { word(s.s, "::"); }
+ word(s.s, "<");
commasep(s, inconsistent, path.node.types, print_type);
- word(s.s, ~">");
+ word(s.s, ">");
}
}
let ann_node = node_pat(s, pat);
s.ann.pre(ann_node);
alt pat.node {
- ast::pat_wild. { word(s.s, ~"_"); }
+ ast::pat_wild. { word(s.s, "_"); }
ast::pat_bind(id) { word(s.s, id); }
ast::pat_lit(lit) { print_literal(s, lit); }
ast::pat_tag(path, args) {
popen(s);
commasep(s, inconsistent, args, print_pat);
pclose(s);
- } else { word(s.s, ~"."); }
+ } else { word(s.s, "."); }
}
ast::pat_rec(fields, etc) {
- word(s.s, ~"{");
+ word(s.s, "{");
fn print_field(s: &ps, f: &ast::field_pat) {
cbox(s, indent_unit);
word(s.s, f.ident);
- word_space(s, ~":");
+ word_space(s, ":");
print_pat(s, f.pat);
end(s);
}
fn get_span(f: &ast::field_pat) -> codemap::span { ret f.pat.span; }
commasep_cmnt(s, consistent, fields, print_field, get_span);
if etc {
- if vec::len(fields) != 0u { word_space(s, ~","); }
- word(s.s, ~"_");
+ if vec::len(fields) != 0u { word_space(s, ","); }
+ word(s.s, "_");
}
- word(s.s, ~"}");
+ word(s.s, "}");
}
ast::pat_tup(elts) {
popen(s);
commasep(s, inconsistent, elts, print_pat);
pclose(s);
}
- ast::pat_box(inner) { word(s.s, ~"@"); print_pat(s, inner); }
+ ast::pat_box(inner) { word(s.s, "@"); print_pat(s, inner); }
}
s.ann.post(ann_node);
}
typarams: &[ast::ty_param], constrs: [@ast::constr]) {
alt decl.purity {
ast::impure_fn. { head(s, proto_to_str(proto)); }
- _ { head(s, ~"pure fn"); }
+ _ { head(s, "pure fn"); }
}
word(s.s, name);
print_type_params(s, typarams);
popen(s);
fn print_arg(s: &ps, x: &ast::arg) {
ibox(s, indent_unit);
- word_space(s, x.ident + ~":");
+ word_space(s, x.ident + ":");
print_alias(s, x.mode);
print_type(s, x.ty);
end(s);
maybe_print_comment(s, decl.output.span.lo);
if decl.output.node != ast::ty_nil {
space_if_not_bol(s);
- word_space(s, ~"->");
+ word_space(s, "->");
print_type(s, decl.output);
}
}
fn print_fn_block_args(s: &ps, decl: &ast::fn_decl) {
- word(s.s, ~"|");
+ word(s.s, "|");
fn print_arg(s: &ps, x: &ast::arg) {
ibox(s, indent_unit);
print_alias(s, x.mode);
end(s);
}
commasep(s, inconsistent, decl.inputs, print_arg);
- word(s.s, ~"|");
+ word(s.s, "|");
maybe_print_comment(s, decl.output.span.lo);
}
fn print_alias(s: &ps, m: ast::mode) {
alt m {
- ast::alias(true) { word_space(s, ~"&mutable"); }
- ast::alias(false) { word(s.s, ~"&"); }
- ast::move. { word(s.s, ~"-"); }
+ ast::alias(true) { word_space(s, "&mutable"); }
+ ast::alias(false) { word(s.s, "&"); }
+ ast::move. { word(s.s, "-"); }
ast::val. { }
}
}
fn print_kind(s: &ps, kind: ast::kind) {
alt kind {
- ast::kind_unique. { word(s.s, ~"~"); }
- ast::kind_shared. { word(s.s, ~"@"); }
+ ast::kind_unique. { word(s.s, "~"); }
+ ast::kind_shared. { word(s.s, "@"); }
_ {/* fallthrough */ }
}
}
fn print_type_params(s: &ps, params: &[ast::ty_param]) {
if vec::len(params) > 0u {
- word(s.s, ~"<");
+ word(s.s, "<");
fn printParam(s: &ps, param: &ast::ty_param) {
print_kind(s, param.kind);
word(s.s, param.ident);
}
commasep(s, inconsistent, params, printParam);
- word(s.s, ~">");
+ word(s.s, ">");
}
}
ast::meta_word(name) { word(s.s, name); }
ast::meta_name_value(name, value) {
word_space(s, name);
- word_space(s, ~"=");
+ word_space(s, "=");
print_literal(s, @value);
}
ast::meta_list(name, items) {
maybe_print_comment(s, item.span.lo);
alt item.node {
ast::view_item_use(id, mta, _) {
- head(s, ~"use");
+ head(s, "use");
word(s.s, id);
if vec::len(mta) > 0u {
popen(s);
}
}
ast::view_item_import(id, ids, _) {
- head(s, ~"import");
+ head(s, "import");
if !str::eq(id, ids[vec::len(ids) - 1u]) {
word_space(s, id);
- word_space(s, ~"=");
+ word_space(s, "=");
}
let first = true;
for elt: ast::ident in ids {
- if first { first = false; } else { word(s.s, ~"::"); }
+ if first { first = false; } else { word(s.s, "::"); }
word(s.s, elt);
}
}
ast::view_item_import_from(mod_path, idents, _) {
- head(s, ~"import");
- for elt: ast::ident in mod_path {
- word(s.s, elt); word(s.s, ~"::");
- }
- word(s.s, ~"{");
+ head(s, "import");
+ for elt: ast::ident in mod_path { word(s.s, elt); word(s.s, "::"); }
+ word(s.s, "{");
commasep(s, inconsistent, idents,
fn (s: &ps, w: &ast::import_ident) {
word(s.s, w.node.name)
});
- word(s.s, ~"}");
+ word(s.s, "}");
}
ast::view_item_import_glob(ids, _) {
- head(s, ~"import");
+ head(s, "import");
let first = true;
for elt: ast::ident in ids {
- if first { first = false; } else { word(s.s, ~"::"); }
+ if first { first = false; } else { word(s.s, "::"); }
word(s.s, elt);
}
- word(s.s, ~"::*");
+ word(s.s, "::*");
}
ast::view_item_export(ids, _) {
- head(s, ~"export");
+ head(s, "export");
commasep(s, inconsistent, ids,
- fn (s: &ps, w: &ast::ident) {
- word(s.s, w)
- });
+ fn (s: &ps, w: &ast::ident) { word(s.s, w) });
}
}
- word(s.s, ~";");
+ word(s.s, ";");
end(s); // end inner head-block
end(s); // end outer head-block
ast::expr_ternary(_, _, _) { parse::parser::ternary_prec < outer_prec }
+
// This may be too conservative in some cases
ast::expr_assign(_, _) {
true
fn print_mutability(s: &ps, mut: &ast::mutability) {
alt mut {
- ast::mut. { word_nbsp(s, ~"mutable"); }
- ast::maybe_mut. { word_nbsp(s, ~"mutable?"); }
+ ast::mut. { word_nbsp(s, "mutable"); }
+ ast::maybe_mut. { word_nbsp(s, "mutable?"); }
ast::imm. {/* nothing */ }
}
}
cf: &ast::controlflow, constrs: &[@ast::constr]) {
ibox(s, indent_unit);
word(s.s, proto_to_str(proto));
- alt id {
- some(id) {
- word(s.s, ~" ");
- word(s.s, id);
- }
- _ { }
- }
+ alt id { some(id) { word(s.s, " "); word(s.s, id); } _ { } }
zerobreak(s.s);
popen(s);
fn print_arg(s: &ps, input: &ast::ty_arg) {
if output.node != ast::ty_nil {
space_if_not_bol(s);
ibox(s, indent_unit);
- word_space(s, ~"->");
+ word_space(s, "->");
alt cf {
ast::return. { print_type(s, output); }
- ast::noreturn. { word_nbsp(s, ~"!"); }
+ ast::noreturn. { word_nbsp(s, "!"); }
}
end(s);
}
maybe_print_comment(s, lit.span.lo);
alt next_lit(s) {
some(lt) {
- if lt.pos == lit.span.lo {
- word(s.s, lt.lit);
- s.cur_lit += 1u;
- ret;
- }
+ if lt.pos == lit.span.lo { word(s.s, lt.lit); s.cur_lit += 1u; ret; }
}
_ { }
}
alt lit.node {
- ast::lit_str(st) {
- print_string(s, st);
- }
+ ast::lit_str(st) { print_string(s, st); }
ast::lit_char(ch) {
word(s.s,
- ~"'" + escape_str(str::unsafe_from_bytes([ch as u8]), '\'') +
- ~"'");
+ "'" + 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"); }
+ ast::lit_uint(val) { word(s.s, uint::str(val) + "u"); }
ast::lit_float(fstr) { word(s.s, fstr); }
ast::lit_mach_int(mach, val) {
word(s.s, int::str(val as int));
word(s.s, val);
word(s.s, ast_util::ty_mach_to_str(mach));
}
- ast::lit_nil. { word(s.s, ~"()"); }
+ ast::lit_nil. { word(s.s, "()"); }
ast::lit_bool(val) {
- if val { word(s.s, ~"true"); } else { word(s.s, ~"false"); }
+ if val { word(s.s, "true"); } else { word(s.s, "false"); }
}
}
}
-fn lit_to_str(l: &@ast::lit) -> istr { be to_str(l, print_literal); }
+fn lit_to_str(l: &@ast::lit) -> str { be to_str(l, print_literal); }
fn next_lit(s: &ps) -> option::t<lexer::lit> {
alt s.literals {
}
lexer::isolated. {
pprust::hardbreak_if_not_bol(s);
- for line: istr in cmnt.lines {
+ for line: str in cmnt.lines {
// Don't print empty lines because they will end up as trailing
// whitespace
- if str::is_not_empty(line) {
- word(s.s, line);
- }
+ if str::is_not_empty(line) { word(s.s, line); }
hardbreak(s.s);
}
}
lexer::trailing. {
- word(s.s, ~" ");
+ word(s.s, " ");
if vec::len(cmnt.lines) == 1u {
word(s.s, cmnt.lines[0]);
hardbreak(s.s);
} else {
ibox(s, 0u);
- for line: istr in cmnt.lines {
- if str::is_not_empty(line) {
- word(s.s, line);
- }
+ for line: str in cmnt.lines {
+ if str::is_not_empty(line) { word(s.s, line); }
hardbreak(s.s);
}
end(s);
// We need to do at least one, possibly two hardbreaks.
let is_semi =
alt s.s.last_token() {
- pp::STRING(s, _) { s == ~";" }
+ pp::STRING(s, _) { s == ";" }
_ { false }
};
if is_semi || is_begin(s) || is_end(s) { hardbreak(s.s) }
}
}
-fn print_string(s: &ps, st: &istr) {
- word(s.s, ~"\"");
+fn print_string(s: &ps, st: &str) {
+ word(s.s, "\"");
word(s.s, escape_str(st, '"'));
- word(s.s, ~"\"");
+ word(s.s, "\"");
}
-fn escape_str(st: &istr, to_escape: char) -> istr {
- let out: istr = ~"";
+fn escape_str(st: &str, to_escape: char) -> str {
+ let out: str = "";
let len = str::byte_len(st);
let i = 0u;
while i < len {
alt st[i] as char {
- '\n' { out += ~"\\n"; }
- '\t' { out += ~"\\t"; }
- '\r' { out += ~"\\r"; }
- '\\' { out += ~"\\\\"; }
+ '\n' { out += "\\n"; }
+ '\t' { out += "\\t"; }
+ '\r' { out += "\\r"; }
+ '\\' { out += "\\\\"; }
cur {
- if cur == to_escape { out += ~"\\"; }
+ if cur == to_escape { out += "\\"; }
// FIXME some (or all?) non-ascii things should be escaped
str::push_char(out, cur);
ret out;
}
-fn to_str<T>(t: &T, f: fn(&ps, &T)) -> istr {
+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);
// 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) -> istr, args: &[@ast::sp_constr_arg<T>])
- -> istr {
+fn constr_args_to_str<T>(f: &fn(&T) -> str, args: &[@ast::sp_constr_arg<T>])
+ -> str {
let comma = false;
- let s = ~"(";
+ let s = "(";
for a: @ast::sp_constr_arg<T> in args {
- if comma { s += ~", "; } else { comma = true; }
+ if comma { s += ", "; } else { comma = true; }
s += constr_arg_to_str::<T>(f, a.node);
}
- s += ~")";
+ s += ")";
ret s;
}
-fn constr_arg_to_str<T>(f: &fn(&T) -> istr,
- c: &ast::constr_arg_general_<T>) ->
- istr {
+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_base. { ret "*"; }
ast::carg_ident(i) { ret f(i); }
ast::carg_lit(l) { ret lit_to_str(l); }
}
// needed b/c constr_args_to_str needs
// something that takes an alias
// (argh)
-fn uint_to_str(i: &uint) -> istr { ret uint::str(i); }
+fn uint_to_str(i: &uint) -> str { ret uint::str(i); }
-fn ast_ty_fn_constr_to_str(c: &@ast::constr) -> istr {
+fn ast_ty_fn_constr_to_str(c: &@ast::constr) -> str {
ret path_to_str(c.node.path) +
constr_args_to_str(uint_to_str, c.node.args);
}
// FIXME: fix repeated code
-fn ast_ty_fn_constrs_str(constrs: &[@ast::constr]) -> istr {
- let s = ~"";
+fn ast_ty_fn_constrs_str(constrs: &[@ast::constr]) -> str {
+ let s = "";
let colon = true;
for c: @ast::constr in constrs {
- if colon { s += ~" : "; colon = false; } else { s += ~", "; }
+ if colon { s += " : "; colon = false; } else { s += ", "; }
s += ast_ty_fn_constr_to_str(c);
}
ret s;
}
-fn fn_arg_idx_to_str(decl: &ast::fn_decl, idx: &uint) -> istr {
+fn fn_arg_idx_to_str(decl: &ast::fn_decl, idx: &uint) -> str {
decl.inputs[idx].ident
}
-fn ast_fn_constr_to_str(decl: &ast::fn_decl, c: &@ast::constr) -> istr {
+fn ast_fn_constr_to_str(decl: &ast::fn_decl, c: &@ast::constr) -> str {
let arg_to_str = bind fn_arg_idx_to_str(decl, _);
ret path_to_str(c.node.path) +
constr_args_to_str(arg_to_str, c.node.args);
}
// FIXME: fix repeated code
-fn ast_fn_constrs_str(decl: &ast::fn_decl, constrs: &[@ast::constr]) -> istr {
- let s = ~"";
+fn ast_fn_constrs_str(decl: &ast::fn_decl, constrs: &[@ast::constr]) -> str {
+ let s = "";
let colon = true;
for c: @ast::constr in constrs {
- if colon { s += ~" : "; colon = false; } else { s += ~", "; }
+ if colon { s += " : "; colon = false; } else { s += ", "; }
s += ast_fn_constr_to_str(decl, c);
}
ret s;
}
-fn proto_to_str(p: &ast::proto) -> istr {
+fn proto_to_str(p: &ast::proto) -> str {
ret alt p {
- ast::proto_fn. { ~"fn" }
- ast::proto_iter. { ~"iter" }
- ast::proto_block. { ~"block" }
- ast::proto_closure. { ~"lambda" }
+ ast::proto_fn. { "fn" }
+ ast::proto_iter. { "iter" }
+ ast::proto_block. { "block" }
+ ast::proto_closure. { "lambda" }
};
}
-fn ty_constr_to_str(c: &@ast::ty_constr) -> istr {
- fn ty_constr_path_to_str(p: &ast::path) -> istr { ~"*." + path_to_str(p) }
+fn ty_constr_to_str(c: &@ast::ty_constr) -> str {
+ 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 ast_ty_constrs_str(constrs: &[@ast::ty_constr]) -> istr {
- let s = ~"";
+fn ast_ty_constrs_str(constrs: &[@ast::ty_constr]) -> str {
+ let s = "";
let colon = true;
for c: @ast::ty_constr in constrs {
- if colon { s += ~" : "; colon = false; } else { s += ~", "; }
+ if colon { s += " : "; colon = false; } else { s += ", "; }
s += ty_constr_to_str(c);
}
ret s;
fn lit_eq(l: &@ast::lit, m: &@ast::lit) -> bool {
alt l.node {
ast::lit_str(s) {
- alt m.node {
- ast::lit_str(t) { ret s == t }
- _ { ret false; }
- }
+ alt m.node { ast::lit_str(t) { ret s == t } _ { ret false; } }
}
ast::lit_char(c) {
alt m.node { ast::lit_char(d) { ret c == d; } _ { ret false; } }
tag call_kind { kind_call; kind_spawn; kind_bind; kind_for_each; }
-fn call_kind_str(c: call_kind) -> istr {
+fn call_kind_str(c: call_kind) -> str {
alt c {
- kind_call. { ~"Call" }
- kind_spawn. { ~"Spawn" }
- kind_bind. { ~"Bind" }
- kind_for_each. { ~"For-Each" }
+ kind_call. { "Call" }
+ kind_spawn. { "Spawn" }
+ kind_bind. { "Bind" }
+ kind_for_each. { "For-Each" }
}
}
fn is_main_name(path: &[ast::ident]) -> bool {
- str::eq(option::get(std::vec::last(path)), ~"main")
+ str::eq(option::get(std::vec::last(path)), "main")
}
// FIXME mode this to std::float when editing the stdlib no longer
// requires a snapshot
-fn float_to_str(num: float, digits: uint) -> istr {
- let accum = if num < 0.0 { num = -num; ~"-" } else { ~"" };
+fn float_to_str(num: float, digits: uint) -> str {
+ let accum = if num < 0.0 { num = -num; "-" } else { "" };
let trunc = num as uint;
let frac = num - (trunc as float);
accum += uint::str(trunc);
if frac == 0.0 || digits == 0u { ret accum; }
- accum += ~".";
+ accum += ".";
while digits > 0u && frac > 0.0 {
frac *= 10.0;
let digit = frac as uint;
import middle::ast_map;
import metadata::csearch;
-fn mode_str(m: &ty::mode) -> istr {
+fn mode_str(m: &ty::mode) -> str {
alt m {
- mo_val. { ~"" }
- mo_alias(false) { ~"&" }
- mo_alias(true) { ~"&mutable " }
- mo_move. { ~"-" }
+ mo_val. { "" }
+ mo_alias(false) { "&" }
+ mo_alias(true) { "&mutable " }
+ mo_move. { "-" }
}
}
-fn mode_str_1(m: &ty::mode) -> istr {
- alt m { mo_val. { ~"val" } _ { mode_str(m) } }
+fn mode_str_1(m: &ty::mode) -> str {
+ alt m { mo_val. { "val" } _ { mode_str(m) } }
}
-fn fn_ident_to_string(id: ast::node_id, i: &ast::fn_ident) -> istr {
- ret alt i {
- none. { ~"anon" + int::str(id) }
- some(s) { s }
- };
+fn fn_ident_to_string(id: ast::node_id, i: &ast::fn_ident) -> str {
+ ret alt i { none. { "anon" + int::str(id) } some(s) { s } };
}
-fn get_id_ident(cx: &ctxt, id: ast::def_id) -> istr {
+fn get_id_ident(cx: &ctxt, id: ast::def_id) -> str {
if id.crate != ast::local_crate {
alt cx.ext_map.find(id) {
- some(j) { str::connect(j, ~"::") }
- _ { fail (~"get_id_ident: can't find item in ext_map, id.crate = "
- + int::str(id.crate)) }
+ some(j) { str::connect(j, "::") }
+ _ {
+ fail "get_id_ident: can't find item in ext_map, id.crate = " +
+ int::str(id.crate)
+ }
}
} else {
alt cx.items.find(id.node) {
}
}
-fn ty_to_str(cx: &ctxt, typ: &t) -> istr {
+fn ty_to_str(cx: &ctxt, typ: &t) -> str {
fn fn_input_to_str(cx: &ctxt, input: &{mode: middle::ty::mode, ty: t}) ->
- istr {
+ str {
let s = mode_str(input.mode);
ret s + ty_to_str(cx, input.ty);
}
fn fn_to_str(cx: &ctxt, proto: ast::proto, ident: option::t<ast::ident>,
inputs: &[arg], output: t, cf: ast::controlflow,
- constrs: &[@constr]) -> istr {
+ constrs: &[@constr]) -> str {
let s = proto_to_str(proto);
- alt ident {
- some(i) {
- s += ~" ";
- s += i;
- }
- _ { }
- }
- s += ~"(";
+ alt ident { some(i) { s += " "; s += i; } _ { } }
+ s += "(";
let strs = [];
for a: arg in inputs { strs += [fn_input_to_str(cx, a)]; }
- s += str::connect(strs, ~", ");
- s += ~")";
+ s += str::connect(strs, ", ");
+ s += ")";
if struct(cx, output) != ty_nil {
alt cf {
- ast::noreturn. { s += ~" -> !"; }
- ast::return. { s += ~" -> " + ty_to_str(cx, output); }
+ ast::noreturn. { s += " -> !"; }
+ ast::return. { s += " -> " + ty_to_str(cx, output); }
}
}
s += constrs_str(constrs);
ret s;
}
- fn method_to_str(cx: &ctxt, m: &method) -> istr {
+ fn method_to_str(cx: &ctxt, m: &method) -> str {
ret fn_to_str(cx, m.proto, some::<ast::ident>(m.ident), m.inputs,
- m.output, m.cf, m.constrs) + ~";";
+ m.output, m.cf, m.constrs) + ";";
}
- fn field_to_str(cx: &ctxt, f: &field) -> istr {
- ret f.ident + ~": " + mt_to_str(cx, f.mt);
+ fn field_to_str(cx: &ctxt, f: &field) -> str {
+ ret f.ident + ": " + mt_to_str(cx, f.mt);
}
- fn mt_to_str(cx: &ctxt, m: &mt) -> istr {
+ fn mt_to_str(cx: &ctxt, m: &mt) -> str {
let mstr;
alt m.mut {
- ast::mut. { mstr = ~"mutable "; }
- ast::imm. { mstr = ~""; }
- ast::maybe_mut. { mstr = ~"mutable? "; }
+ ast::mut. { mstr = "mutable "; }
+ ast::imm. { mstr = ""; }
+ ast::maybe_mut. { mstr = "mutable? "; }
}
ret mstr + ty_to_str(cx, m.ty);
}
- alt cname(cx, typ) {
- some(cs) {
- ret cs;
- }
- _ { }
- }
+ 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_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_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_char. { "char" }
+ 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: [istr] = [];
+ let strs: [str] = [];
for fld: field in elems { strs += [field_to_str(cx, fld)]; }
- ~"{" + str::connect(strs, ~",") + ~"}"
+ "{" + str::connect(strs, ",") + "}"
}
ty_tup(elems) {
let strs = [];
for elem in elems { strs += [ty_to_str(cx, elem)]; }
- ~"(" + str::connect(strs, ~",") + ~")"
+ "(" + str::connect(strs, ",") + ")"
}
ty_tag(id, tps) {
let s = get_id_ident(cx, id);
if vec::len::<t>(tps) > 0u {
- let strs: [istr] = [];
+ let strs: [str] = [];
for typ: t in tps { strs += [ty_to_str(cx, typ)]; }
- s += ~"[" + str::connect(strs, ~",") + ~"]";
+ s += "[" + str::connect(strs, ",") + "]";
}
s
}
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}"
+ "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_var(v) { "<T" + int::str(v) + ">" }
ty_param(id, _) {
- ~"'" + str::unsafe_from_bytes([('a' as u8) + (id as u8)])
+ "'" + 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) -> istr {
+fn ty_to_short_str(cx: &ctxt, typ: t) -> str {
let s = encoder::encoded_ty(cx, typ);
if str::byte_len(s) >= 32u { s = str::substr(s, 0u, 32u); }
ret s;
}
-fn constr_to_str(c: &@constr) -> istr {
+fn constr_to_str(c: &@constr) -> str {
ret path_to_str(c.node.path) +
- pprust::constr_args_to_str(pprust::uint_to_str, c.node.args);
+ pprust::constr_args_to_str(pprust::uint_to_str, c.node.args);
}
-fn constrs_str(constrs: &[@constr]) -> istr {
- let s = ~"";
+fn constrs_str(constrs: &[@constr]) -> str {
+ let s = "";
let colon = true;
for c: @constr in constrs {
- if colon { s += ~" : "; colon = false; } else { s += ~", "; }
+ if colon { s += " : "; colon = false; } else { s += ", "; }
s += constr_to_str(c);
}
ret s;
}
fn ty_constr_to_str<Q>(c: &@ast::spanned<ast::constr_general_<ast::path, Q>>)
- -> istr {
+ -> str {
ret path_to_str(c.node.path) +
- constr_args_to_str::<ast::path>(path_to_str, c.node.args);
+ constr_args_to_str::<ast::path>(path_to_str, c.node.args);
}
// Local Variables:
import rustc::syntax::parse::parser;
import rustc::syntax::print::pprust;
-fn write_file(filename: &istr, content: &istr) {
+fn write_file(filename: &str, content: &str) {
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: &istr, needle: &istr) -> bool {
+fn file_contains(filename: &str, needle: &str) -> bool {
let contents = io::read_whole_file_str(filename);
ret str::find(contents, needle) != -1;
}
-fn contains(haystack: &istr, needle: &istr) -> bool {
+fn contains(haystack: &str, needle: &str) -> bool {
str::find(haystack, needle) != -1
}
-fn find_rust_files(files: &mutable [istr], path: &istr) {
- if str::ends_with(path, ~".rs") {
- if file_contains(path, ~"xfail-test") {
+fn find_rust_files(files: &mutable [str], path: &str) {
+ if str::ends_with(path, ".rs") {
+ if file_contains(path, "xfail-test") {
//log_err "Skipping " + path + " because it is marked as xfail-test";
} else { files += [path]; }
} else if fs::file_is_dir(path)
- && str::find(path, ~"compile-fail") == -1 {
+ && str::find(path, "compile-fail") == -1 {
for p in fs::list_dir(path) {
find_rust_files(files, p);
}
fn devnull() -> io::writer { std::io::string_writer().get_writer() }
-fn as_str(f: fn(io::writer)) -> istr {
+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: &istr) {
+ filename: &str) {
let exprs = steal_exprs(crate);
let exprsL = vec::len(exprs);
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]);
+ 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(~""), _,
+ 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.
// - that would find many "false positives" or unimportant bugs
// - that would be tricky, requiring use of tasks or serialization or randomness.
// This seems to find plenty of bugs as it is :)
-fn check_whole_compiler(code: &istr) {
- let filename = ~"test.rs";
+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]);
+ "/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") {
+ 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")
+ "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!") {
+ } 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, ~"!") {
+ "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;
+ 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") {
+ } 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 == 256 {
- if !contains(p.out, ~"error:") {
+ if !contains(p.out, "error:") {
fail "Exited with status 256 without a span-error";
}
} else if p.status == 11 {
} else if p.status != 0 { fail "Unfamiliar status code"; }
}
-fn parse_and_print(code: &istr) -> istr {
- let filename = ~"tmp.rs";
+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(
pprust::no_ann()));
}
-fn content_is_dangerous_to_modify(code: &istr) -> bool {
+fn content_is_dangerous_to_modify(code: &str) -> bool {
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
+ ["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
- for p: istr in dangerous_patterns { if contains(code, p) { ret true; } }
+ for p: str in dangerous_patterns { if contains(code, p) { ret true; } }
ret false;
}
-fn content_is_confusing(code: &istr) ->
+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
// more precedence issues?
let confusing_patterns =
- [~"#macro", ~"][]", ~"][mutable]", ~"][mutable ]", ~"self", ~"spawn",
- ~"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"];
+ ["#macro", "][]", "][mutable]", "][mutable ]", "self", "spawn",
+ "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"];
- for p: istr in confusing_patterns { if contains(code, p) { ret true; } }
+ for p: str in confusing_patterns { if contains(code, p) { ret true; } }
ret false;
}
-fn file_is_confusing(filename: &istr) -> bool {
+fn file_is_confusing(filename: &str) -> bool {
// https://github.com/graydon/rust/issues/674
// 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
+ ["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
for f in confusing_files { if contains(filename, f) { ret true; } }
ret false;
}
-fn check_roundtrip_convergence(code: &istr, maxIters: uint) {
+fn check_roundtrip_convergence(code: &str, maxIters: uint) {
let i = 0u;
let new = code;
log_err #fmt["Converged after %u iterations", i];
} else {
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"]);
+ 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"]);
fail "Mismatch";
}
}
-fn check_convergence(files: &[istr]) {
+fn check_convergence(files: &[str]) {
log_err #fmt["pp convergence tests: %u files", vec::len(files)];
for file in files {
if !file_is_confusing(file) {
}
}
-fn check_variants(files: &[istr]) {
+fn check_variants(files: &[str]) {
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;
}
- log_err ~"check_variants: " + file;
+ log_err "check_variants: " + file;
let sess = @{cm: codemap::new_codemap(), mutable next_id: 0};
let crate =
parser::parse_crate_from_source_str(
}
}
-fn main(args: [istr]) {
+fn main(args: [str]) {
if vec::len(args) != 2u {
log_err #fmt["usage: %s <testdir>", args[0]];
ret;
//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)]; }
type ctx = chan<request>;
fn ip_to_sbuf(ip: net::ip_addr) -> *u8 {
+
// FIXME: This is broken. We're creating a vector, getting a pointer
// to its buffer, then dropping the vector. On top of that, the vector
// created by str::bytes is not null-terminated.
fn server_task(ip: net::ip_addr, portnum: int, events: chan<server_event>,
server: chan<server>) {
let accepter = port();
- send(server,
- rustrt::aio_serve(ip_to_sbuf(ip), portnum, chan(accepter)));
+ send(server, rustrt::aio_serve(ip_to_sbuf(ip), portnum, chan(accepter)));
let client: client;
while true {
ret vec::init_fn::<uint>(sub, v.nbits);
}
-fn to_str(v: &t) -> istr {
- let rs = ~"";
- for i: uint in to_vec(v) {
- if i == 1u { rs += ~"1"; } else { rs += ~"0"; }
- }
+fn to_str(v: &t) -> str {
+ let rs = "";
+ for i: uint in to_vec(v) { if i == 1u { rs += "1"; } else { rs += "0"; } }
ret rs;
}
type void;
type rust_port;
- fn chan_id_send<~T>(target_task: task::task,
- target_port: port_id, data: -T);
+ fn chan_id_send<~T>(target_task: task::task, target_port: port_id,
+ data: -T);
fn new_port(unit_sz: uint) -> *rust_port;
fn del_port(po: *rust_port);
+
fn grow<@T>(nelts: uint, lo: uint, elts: &[mutable cell<T>]) ->
[mutable cell<T>] {
assert (nelts == vec::len(elts));
alt maybe_get_doc(d, tg) {
some(d) { ret d; }
none. {
- log_err ~"failed to find block with tag " + uint::to_str(tg, 10u);
+ log_err "failed to find block with tag " + uint::to_str(tg, 10u);
fail;
}
}
// A fragment of the output sequence
- tag piece { piece_string(istr); piece_conv(conv); }
- type error_fn = fn(&istr) -> ! ;
+ tag piece { piece_string(str); piece_conv(conv); }
+ type error_fn = fn(&str) -> ! ;
- fn parse_fmt_string(s: &istr, error: error_fn) -> [piece] {
+ fn parse_fmt_string(s: &str, error: error_fn) -> [piece] {
let pieces: [piece] = [];
let lim = str::byte_len(s);
- let buf = ~"";
- fn flush_buf(buf: &istr, pieces: &mutable [piece]) -> istr {
+ let buf = "";
+ fn flush_buf(buf: &str, pieces: &mutable [piece]) -> str {
if str::byte_len(buf) > 0u {
let piece = piece_string(buf);
pieces += [piece];
}
- ret ~"";
+ ret "";
}
let i = 0u;
while i < lim {
let curr = str::substr(s, i, 1u);
- if str::eq(curr, ~"%") {
+ if str::eq(curr, "%") {
i += 1u;
if i >= lim {
- error(~"unterminated conversion at end of string");
+ error("unterminated conversion at end of string");
}
let curr2 = str::substr(s, i, 1u);
- if str::eq(curr2, ~"%") {
+ if str::eq(curr2, "%") {
i += 1u;
} else {
buf = flush_buf(buf, pieces);
buf = flush_buf(buf, pieces);
ret pieces;
}
- fn peek_num(s: &istr, i: uint, lim: uint) ->
+ fn peek_num(s: &str, i: uint, lim: uint) ->
option::t<{num: uint, next: uint}> {
if i >= lim { ret none; }
let c = s[i];
}
};
}
- fn parse_conversion(s: &istr, i: uint, lim: uint, error: error_fn) ->
+ fn parse_conversion(s: &str, i: uint, lim: uint, error: error_fn) ->
{piece: piece, next: uint} {
let parm = parse_parameter(s, i, lim);
let flags = parse_flags(s, parm.next, lim);
ty: ty.ty}),
next: ty.next};
}
- fn parse_parameter(s: &istr, i: uint, lim: uint) ->
+ fn parse_parameter(s: &str, i: uint, lim: uint) ->
{param: option::t<int>, next: uint} {
if i >= lim { ret {param: none, next: i}; }
let num = peek_num(s, i, lim);
}
};
}
- fn parse_flags(s: &istr, i: uint, lim: uint) ->
+ fn parse_flags(s: &str, i: uint, lim: uint) ->
{flags: [flag], next: uint} {
let noflags: [flag] = [];
if i >= lim { ret {flags: noflags, next: i}; }
// FIXME: This recursion generates illegal instructions if the return
// value isn't boxed. Only started happening after the ivec conversion
- fn more_(f: flag, s: &istr, i: uint, lim: uint) ->
+ fn more_(f: flag, s: &str, i: uint, lim: uint) ->
@{flags: [flag], next: uint} {
let next = parse_flags(s, i + 1u, lim);
let rest = next.flags;
*more(flag_alternate)
} else { {flags: noflags, next: i} };
}
- fn parse_count(s: &istr, i: uint,
- lim: uint) -> {count: count, next: uint} {
+ 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 {
}
};
}
- fn parse_precision(s: &istr, i: uint, lim: uint) ->
+ fn parse_precision(s: &str, i: uint, lim: uint) ->
{count: count, next: uint} {
ret if i >= lim {
{count: count_implied, next: i}
}
} else { {count: count_implied, next: i} };
}
- fn parse_type(s: &istr, i: uint, lim: uint, error: error_fn) ->
+ fn parse_type(s: &str, i: uint, lim: uint, error: error_fn) ->
{ty: ty, next: uint} {
- if i >= lim { error(~"missing type in conversion"); }
+ if i >= lim { error("missing type in conversion"); }
let tstr = str::substr(s, i, 1u);
// TODO: Do we really want two signed types here?
// How important is it to be printf compatible?
let t =
- if str::eq(tstr, ~"b") {
+ 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) };
+ } else { error("unknown type in conversion: " + tstr) };
ret {ty: t, next: i + 1u};
}
}
// instead just use a bool per flag
type conv = {flags: [flag], width: count, precision: count, ty: ty};
- fn conv_int(cv: &conv, i: int) -> istr {
+ fn conv_int(cv: &conv, i: int) -> str {
let radix = 10u;
let prec = get_int_precision(cv);
let s = int_to_str_prec(i, radix, prec);
if 0 <= i {
if have_flag(cv.flags, flag_sign_always) {
- s = ~"+" + s;
+ s = "+" + s;
} else if have_flag(cv.flags, flag_space_for_sign) {
- s = ~" " + s;
+ s = " " + s;
}
}
ret pad(cv, s, pad_signed);
}
- fn conv_uint(cv: &conv, u: uint) -> istr {
+ fn conv_uint(cv: &conv, u: uint) -> str {
let prec = get_int_precision(cv);
let rs =
alt cv.ty {
};
ret pad(cv, rs, pad_unsigned);
}
- fn conv_bool(cv: &conv, b: bool) -> istr {
- let s = if b { ~"true" } else { ~"false" };
+ fn conv_bool(cv: &conv, b: bool) -> str {
+ let s = if b { "true" } else { "false" };
// run the boolean conversion through the string conversion logic,
// giving it the same rules for precision, etc.
ret conv_str(cv, s);
}
- fn conv_char(cv: &conv, c: char) -> istr {
+ fn conv_char(cv: &conv, c: char) -> str {
ret pad(cv, str::from_char(c), pad_nozero);
}
- fn conv_str(cv: &conv, s: &istr) -> istr {
+ fn conv_str(cv: &conv, s: &str) -> str {
// For strings, precision is the maximum characters
// displayed
// Convert an int to string with minimum number of digits. If precision is
// 0 and num is 0 then the result is the empty string.
- fn int_to_str_prec(num: int, radix: uint, prec: uint) -> istr {
+ fn int_to_str_prec(num: int, radix: uint, prec: uint) -> str {
ret if num < 0 {
- ~"-" + uint_to_str_prec(-num as uint, radix, prec)
+ "-" + uint_to_str_prec(-num as uint, radix, prec)
} else { uint_to_str_prec(num as uint, radix, prec) };
}
// Convert a uint to string with a minimum number of digits. If precision
// is 0 and num is 0 then the result is the empty string. Could move this
// to uint: but it doesn't seem all that useful.
- fn uint_to_str_prec(num: uint, radix: uint, prec: uint) -> istr {
+ fn uint_to_str_prec(num: uint, radix: uint, prec: uint) -> str {
ret if prec == 0u && num == 0u {
- ~""
+ ""
} else {
let s = uint::to_str(num, radix);
let len = str::char_len(s);
}
// FIXME: This might be useful in str: but needs to be utf8 safe first
- fn str_init_elt(c: char, n_elts: uint) -> istr {
+ fn str_init_elt(c: char, n_elts: uint) -> str {
let svec = vec::init_elt::<u8>(c as u8, n_elts);
ret str::unsafe_from_bytes(svec);
}
tag pad_mode { pad_signed; pad_unsigned; pad_nozero; }
- fn pad(cv: &conv, s: &istr, mode: pad_mode) -> istr {
+ fn pad(cv: &conv, s: &str, mode: pad_mode) -> str {
let uwidth;
alt cv.width {
count_implied. { ret s; }
fn rust_file_is_dir(path: str::sbuf) -> int;
}
-fn path_sep() -> istr { ret str::from_char(os_fs::path_sep); }
+fn path_sep() -> str { ret str::from_char(os_fs::path_sep); }
-type path = istr;
+type path = str;
fn dirname(p: &path) -> path {
let i: int = str::rindex(p, os_fs::path_sep as u8);
if i == -1 {
i = str::rindex(p, os_fs::alt_path_sep as u8);
- if i == -1 { ret ~"."; }
+ if i == -1 { ret "."; }
}
ret str::substr(p, 0u, i as uint);
}
}
fn file_is_dir(p: &path) -> bool {
- ret str::as_buf(p, { |buf|
- rustrt::rust_file_is_dir(buf) != 0
- });
+ ret str::as_buf(p, {|buf| rustrt::rust_file_is_dir(buf) != 0 });
}
-fn list_dir(p: &path) -> [istr] {
+fn list_dir(p: &path) -> [str] {
let p = p;
let pl = str::byte_len(p);
if pl == 0u || p[pl - 1u] as char != os_fs::path_sep { p += path_sep(); }
- let full_paths: [istr] = [];
- for filename: istr in os_fs::list_dir(p) {
- if !str::eq(filename, ~".") {
- if !str::eq(filename, ~"..") { full_paths += [p + filename]; }
+ 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]; }
}
}
ret full_paths;
}
-fn path_is_absolute(p: &path) -> bool {
- ret os_fs::path_is_absolute(p);
-}
+fn path_is_absolute(p: &path) -> bool { ret os_fs::path_is_absolute(p); }
// FIXME: under Windows, we should prepend the current drive letter to paths
// that start with a slash.
fn make_absolute(p: &path) -> path {
- if path_is_absolute(p) {
- ret p;
- } else {
- ret connect(getcwd(), p);
- }
+ if path_is_absolute(p) { ret p; } else { ret connect(getcwd(), p); }
}
// Local Variables:
fn init<@K, @V>() -> treemap<K, V> { @empty }
-fn insert<@K, @V>(m : &treemap<K, V>, k : &K, v : &V) -> treemap<K,V> {
+fn insert<@K, @V>(m: &treemap<K, V>, k: &K, v: &V) -> treemap<K, V> {
@alt m {
- @empty. {
- node(@k, @v, @empty, @empty)
- }
- @node(@kk, vv, left, right) {
- if k < kk {
- node(@kk, vv, insert(left, k, v), right)
- } else if k == kk {
- node(@kk, @v, left, right)
- } else {
- node(@kk, vv, left, insert(right, k, v))
- }
- }
- }
+ @empty. { node(@k, @v, @empty, @empty) }
+ @node(@kk, vv, left, right) {
+ if k < kk {
+ node(@kk, vv, insert(left, k, v), right)
+ } else if k == kk {
+ node(@kk, @v, left, right)
+ } else { node(@kk, vv, left, insert(right, k, v)) }
+ }
+ }
}
-fn find<@K, @V>(m : &treemap<K, V>, k : &K) -> option<V> {
- alt *m {
- empty. { none }
- node(@kk, @v, left, right) {
- if k == kk { some(v) }
- else if k < kk { find(left, k) }
- else { find(right, k) }
+fn find<@K, @V>(m: &treemap<K, V>, k: &K) -> option<V> {
+ alt *m {
+ empty. { none }
+ node(@kk, @v, left, right) {
+ if k == kk {
+ some(v)
+ } else if k < kk { find(left, k) } else { find(right, k) }
+ }
}
- }
}
// Performs an in-order traversal
-fn traverse<@K, @V>(m : &treemap<K, V>, f : fn(&K, &V)) {
- alt *m {
- empty. { }
- node(@k, @v, _, _) {
- // copy v to make aliases work out
- let v1 = v;
- alt *m {
- node(_, _, left, _) {
- traverse(left, f);
- }
- }
- f(k, v1);
- alt *m {
- node(_, _, _, right) {
- traverse(right, f);
- }
+fn traverse<@K, @V>(m: &treemap<K, V>, f: fn(&K, &V)) {
+ alt *m {
+ empty. { }
+ node(@k, @v, _, _) {
+ // copy v to make aliases work out
+ let v1 = v;
+ alt *m { node(_, _, left, _) { traverse(left, f); } }
+ f(k, v1);
+ alt *m { node(_, _, _, right) { traverse(right, f); } }
}
}
- }
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
-fn getenv(n: &istr) -> option::t<istr> {
- let s = str::as_buf(n, { |buf|
- os::libc::getenv(buf)
- });
+fn getenv(n: &str) -> option::t<str> {
+ let s = str::as_buf(n, {|buf| os::libc::getenv(buf) });
ret if unsafe::reinterpret_cast(s) == 0 {
- option::none::<istr>
- } else {
- let s = unsafe::reinterpret_cast(s);
- option::some::<istr>(str::str_from_cstr(s))
- };
+ option::none::<str>
+ } else {
+ let s = unsafe::reinterpret_cast(s);
+ option::some::<str>(str::str_from_cstr(s))
+ };
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
-fn setenv(n: &istr, v: &istr) {
+fn setenv(n: &str, v: &str) {
// FIXME (868)
- let _: () = str::as_buf(n, { |nbuf|
- // FIXME (868)
- let _: () = str::as_buf(v, { |vbuf|
- os::libc::setenv(nbuf, vbuf, 1);
- });
- });
+ let _: () =
+ str::as_buf(n,
+ // FIXME (868)
+ {|nbuf|
+ let _: () =
+ str::as_buf(v,
+ {|vbuf|
+ os::libc::setenv(nbuf, vbuf, 1);
+ });
+ });
}
#[cfg(target_os = "win32")]
-fn getenv(n: &istr) -> option::t<istr> {
+fn getenv(n: &str) -> option::t<str> {
let nsize = 256u;
while true {
let v: [u8] = [];
vec::reserve(v, nsize);
- let res = str::as_buf(n, { |nbuf|
- let vbuf = vec::to_ptr(v);
- os::kernel32::GetEnvironmentVariableA(nbuf, vbuf, nsize)
- });
+ let res =
+ str::as_buf(n,
+ {|nbuf|
+ let vbuf = vec::to_ptr(v);
+ os::kernel32::GetEnvironmentVariableA(nbuf, vbuf,
+ nsize)
+ });
if res == 0u {
ret option::none;
} else if res < nsize {
}
#[cfg(target_os = "win32")]
-fn setenv(n: &istr, v: &istr) {
+fn setenv(n: &str, v: &str) {
// FIXME (868)
- let _: () = str::as_buf(n, { |nbuf|
- let _: () = str::as_buf(v, { |vbuf|
+ let _: () = str::as_buf(n, {|nbuf|
+ let _: () = str::as_buf(v, {|vbuf|
os::kernel32::SetEnvironmentVariableA(nbuf, vbuf);
});
});
export opt_maybe_str;
export opt_default;
-tag name { long(istr); short(char); }
+tag name { long(str); short(char); }
tag hasarg { yes; no; maybe; }
type opt = {name: name, hasarg: hasarg, occur: occur};
-fn mkname(nm: &istr) -> name {
+fn mkname(nm: &str) -> name {
ret if str::char_len(nm) == 1u {
short(str::char_at(nm, 0u))
} else { long(nm) };
}
-fn reqopt(name: &istr) -> opt {
+fn reqopt(name: &str) -> opt {
ret {name: mkname(name), hasarg: yes, occur: req};
}
-fn optopt(name: &istr) -> opt {
+fn optopt(name: &str) -> opt {
ret {name: mkname(name), hasarg: yes, occur: optional};
}
-fn optflag(name: &istr) -> opt {
+fn optflag(name: &str) -> opt {
ret {name: mkname(name), hasarg: no, occur: optional};
}
-fn optflagopt(name: &istr) -> opt {
+fn optflagopt(name: &str) -> opt {
ret {name: mkname(name), hasarg: maybe, occur: optional};
}
-fn optmulti(name: &istr) -> opt {
+fn optmulti(name: &str) -> opt {
ret {name: mkname(name), hasarg: yes, occur: multi};
}
-tag optval { val(istr); given; }
+tag optval { val(str); given; }
-type match = {opts: [opt], vals: [mutable [optval]], free: [istr]};
+type match = {opts: [opt], vals: [mutable [optval]], free: [str]};
-fn is_arg(arg: &istr) -> bool {
+fn is_arg(arg: &str) -> bool {
ret str::byte_len(arg) > 1u && arg[0] == '-' as u8;
}
-fn name_str(nm: &name) -> istr {
+fn name_str(nm: &name) -> str {
ret alt nm { short(ch) { str::from_char(ch) } long(s) { s } };
}
}
tag fail_ {
- argument_missing(istr);
- unrecognized_option(istr);
- option_missing(istr);
- option_duplicated(istr);
- unexpected_argument(istr);
+ argument_missing(str);
+ unrecognized_option(str);
+ option_missing(str);
+ option_duplicated(str);
+ unexpected_argument(str);
}
-fn fail_str(f: &fail_) -> istr {
+fn fail_str(f: &fail_) -> str {
ret alt f {
- argument_missing(nm) {
- ~"Argument to option '" + nm + ~"' missing." }
- unrecognized_option(nm) {
- ~"Unrecognized option: '" + nm + ~"'." }
- option_missing(nm) { ~"Required option '" + nm + ~"' missing." }
+ argument_missing(nm) { "Argument to option '" + nm + "' missing." }
+ unrecognized_option(nm) { "Unrecognized option: '" + nm + "'." }
+ option_missing(nm) { "Required option '" + nm + "' missing." }
option_duplicated(nm) {
- ~"Option '" + nm + ~"' given more than once."
+ "Option '" + nm + "' given more than once."
}
unexpected_argument(nm) {
- ~"Option " + nm + ~" does not take an argument."
+ "Option " + nm + " does not take an argument."
}
};
}
tag result { success(match); failure(fail_); }
-fn getopts(args: &[istr], opts: &[opt]) -> result {
+fn getopts(args: &[str], opts: &[opt]) -> result {
let n_opts = vec::len::<opt>(opts);
fn f(_x: uint) -> [optval] { ret []; }
let vals = vec::init_fn_mut::<[optval]>(f, n_opts);
- let free: [istr] = [];
+ let free: [str] = [];
let l = vec::len(args);
let i = 0u;
while i < l {
let curlen = str::byte_len(cur);
if !is_arg(cur) {
free += [cur];
- } else if str::eq(cur, ~"--") {
+ } else if str::eq(cur, "--") {
let j = i + 1u;
while j < l { free += [args[j]]; j += 1u; }
break;
} else {
let names;
- let i_arg = option::none::<istr>;
+ let i_arg = option::none::<str>;
if cur[1] == '-' as u8 {
let tail = str::slice(cur, 2u, curlen);
let eq = str::index(tail, '=' as u8);
} else {
names = [long(str::slice(tail, 0u, eq as uint))];
i_arg =
- option::some::<istr>(str::slice(tail,
- (eq as uint) + 1u,
- curlen - 2u));
+ option::some::<str>(str::slice(tail,
+ (eq as uint) + 1u,
+ curlen - 2u));
}
} else {
let j = 1u;
}
alt opts[optid].hasarg {
no. {
- if !option::is_none::<istr>(i_arg) {
+ if !option::is_none::<str>(i_arg) {
ret failure(unexpected_argument(name_str(nm)));
}
vals[optid] += [given];
}
maybe. {
- if !option::is_none::<istr>(i_arg) {
+ 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]) {
} else { i += 1u; vals[optid] += [val(args[i])]; }
}
yes. {
- if !option::is_none::<istr>(i_arg) {
- vals[optid] += [val(option::get::<istr>(i_arg))];
+ if !option::is_none::<str>(i_arg) {
+ 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])]; }
ret success({opts: opts, vals: vals, free: free});
}
-fn opt_vals(m: &match, nm: &istr) -> [optval] {
+fn opt_vals(m: &match, nm: &str) -> [optval] {
ret alt find_opt(m.opts, mkname(nm)) {
some(id) { m.vals[id] }
- none. { log_err ~"No option '" + nm + ~"' defined."; fail }
+ none. { log_err "No option '" + nm + "' defined."; fail }
};
}
-fn opt_val(m: &match, nm: &istr) -> 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: &istr) -> bool {
+fn opt_present(m: &match, nm: &str) -> bool {
ret vec::len::<optval>(opt_vals(m, nm)) > 0u;
}
-fn opt_str(m: &match, nm: &istr) -> istr {
+fn opt_str(m: &match, nm: &str) -> str {
ret alt opt_val(m, nm) { val(s) { s } _ { fail } };
}
-fn opt_strs(m: &match, nm: &istr) -> [istr] {
- let acc: [istr] = [];
+fn opt_strs(m: &match, nm: &str) -> [str] {
+ let acc: [str] = [];
for v: optval in opt_vals(m, nm) {
alt v { val(s) { acc += [s]; } _ { } }
}
ret acc;
}
-fn opt_maybe_str(m: &match, nm: &istr) -> option::t<istr> {
+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::<istr>; }
- ret alt vals[0] { val(s) { some::<istr>(s) } _ { none::<istr> } };
+ if vec::len::<optval>(vals) == 0u { ret none::<str>; }
+ ret alt vals[0] { val(s) { some::<str>(s) } _ { none::<str> } };
}
/// Returns none if the option was not present, `def` if the option was
/// present but no argument was provided, and the argument if the option was
/// present and an argument was provided.
-fn opt_default(m: &match, nm: &istr, def: &istr) -> option::t<istr> {
+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::<istr>; }
- ret alt vals[0] { val(s) { some::<istr>(s) } _ { some::<istr>(def) } }
+ if vec::len::<optval>(vals) == 0u { ret none::<str>; }
+ ret alt vals[0] { val(s) { some::<str>(s) } _ { some::<str>(def) } }
}
// Local Variables:
// mode: rust;
while lo_ < hi { put lo_; lo_ += 1; }
}
-fn to_str(n: int, radix: uint) -> istr {
+fn to_str(n: int, radix: uint) -> str {
assert (0u < radix && radix <= 16u);
ret if n < 0 {
- ~"-" + uint::to_str(-n as uint, radix)
+ "-" + uint::to_str(-n as uint, radix)
} else { uint::to_str(n as uint, radix) };
}
-fn str(i: int) -> istr { ret to_str(i, 10u); }
+fn str(i: int) -> str { ret to_str(i, 10u); }
fn pow(base: int, exponent: uint) -> int {
ret if exponent == 0u {
fn read_bytes(uint) -> [u8];
fn read_char() -> char;
fn eof() -> bool;
- fn read_line() -> istr;
- fn read_c_str() -> istr;
+ 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(len: uint) -> [u8] {
let buf = [];
vec::reserve::<u8>(buf, len);
- let read = os::libc::fread(vec::unsafe::to_ptr::<u8>(buf),
- 1u, len, f);
+ let read =
+ os::libc::fread(vec::unsafe::to_ptr::<u8>(buf), 1u, len, f);
vec::unsafe::set_len::<u8>(buf, read);
ret buf;
}
ret val as char;
}
fn eof() -> bool { ret rdr.eof(); }
- fn read_line() -> istr {
+ fn read_line() -> str {
let buf: [u8] = [];
// No break yet in rustc
}
ret str::unsafe_from_bytes(buf);
}
- fn read_c_str() -> istr {
+ fn read_c_str() -> str {
let buf: [u8] = [];
let go_on = true;
while go_on {
ret new_reader(FILE_buf_reader(rustrt::rust_get_stdin(), option::none));
}
-fn file_reader(path: &istr) -> reader {
- let f = str::as_buf(path, { |pathbuf|
- str::as_buf(~"r", { |modebuf|
- os::libc::fopen(pathbuf, modebuf)
- })
- });
- if f as uint == 0u { log_err ~"error opening " + path; fail; }
+fn file_reader(path: &str) -> reader {
+ let f =
+ str::as_buf(path,
+ {|pathbuf|
+ str::as_buf("r",
+ {|modebuf|
+ os::libc::fopen(pathbuf, modebuf)
+ })
+ });
+ if f as uint == 0u { log_err "error opening " + path; fail; }
ret new_reader(FILE_buf_reader(f, option::some(@FILE_res(f))));
}
ret byte_buf_reader(@{buf: buf, mutable pos: 0u});
}
-fn string_reader(s: &istr) -> reader {
+fn string_reader(s: &str) -> reader {
ret new_reader(new_byte_buf_reader(str::bytes(s)));
}
}
}
-fn file_buf_writer(path: &istr, flags: &[fileflag]) -> buf_writer {
+fn file_buf_writer(path: &str, flags: &[fileflag]) -> buf_writer {
let fflags: int =
os::libc_constants::O_WRONLY() | os::libc_constants::O_BINARY();
for f: fileflag in flags {
none. { }
}
}
- let fd = str::as_buf(path, { |pathbuf|
- os::libc::open(pathbuf, fflags,
- os::libc_constants::S_IRUSR() |
- os::libc_constants::S_IWUSR())
- });
+ let fd =
+ str::as_buf(path,
+ {|pathbuf|
+ os::libc::open(pathbuf, fflags,
+ os::libc_constants::S_IRUSR() |
+ os::libc_constants::S_IWUSR())
+ });
if fd < 0 {
log_err "error opening file for writing";
log_err sys::rustrt::last_os_error();
// function will be provided for general encoded string output
obj {
fn get_buf_writer() -> buf_writer;
- fn write_str(&istr);
- fn write_line(&istr);
+ fn write_str(&str);
+ fn write_line(&str);
fn write_char(char);
fn write_int(int);
fn write_uint(uint);
obj new_writer(out: buf_writer) {
fn get_buf_writer() -> buf_writer { ret out; }
- fn write_str(s: &istr) { out.write(str::bytes(s)); }
- fn write_line(s: &istr) {
+ fn write_str(s: &str) { out.write(str::bytes(s)); }
+ fn write_line(s: &str) {
out.write(str::bytes(s));
- out.write(str::bytes(~"\n"));
+ out.write(str::bytes("\n"));
}
fn write_char(ch: char) {
// FIXME needlessly consy
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_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_bytes(bytes: &[u8]) { out.write(bytes); }
fn write_le_uint(n: uint, size: uint) {
out.write(uint_to_le_bytes(n, size));
}
}
-fn file_writer(path: &istr, flags: &[fileflag]) -> writer {
+fn file_writer(path: &str, flags: &[fileflag]) -> writer {
ret new_writer(file_buf_writer(path, flags));
}
// FIXME: fileflags
-fn buffered_file_buf_writer(path: &istr) -> buf_writer {
- let f = str::as_buf(path, { |pathbuf|
- str::as_buf(~"w", { |modebuf|
- os::libc::fopen(pathbuf, modebuf)
- })
- });
- if f as uint == 0u { log_err ~"error opening " + path; fail; }
+fn buffered_file_buf_writer(path: &str) -> buf_writer {
+ let f =
+ str::as_buf(path,
+ {|pathbuf|
+ str::as_buf("w",
+ {|modebuf|
+ os::libc::fopen(pathbuf, modebuf)
+ })
+ });
+ if f as uint == 0u { log_err "error opening " + path; fail; }
ret FILE_writer(f, option::some(@FILE_res(f)));
}
type str_writer =
obj {
fn get_writer() -> writer;
- fn get_str() -> istr;
+ fn get_str() -> str;
};
type mutable_byte_buf = @{mutable buf: [mutable u8], mutable pos: uint};
let buf: mutable_byte_buf = @{mutable buf: b, mutable pos: 0u};
obj str_writer_wrap(wr: writer, buf: mutable_byte_buf) {
fn get_writer() -> writer { ret wr; }
- fn get_str() -> istr { ret str::unsafe_from_bytes(buf.buf); }
+ fn get_str() -> str { ret str::unsafe_from_bytes(buf.buf); }
}
ret str_writer_wrap(new_writer(byte_buf_writer(buf)), buf);
}
ret bpos as uint;
}
-fn read_whole_file_str(file: &istr) -> istr {
+fn read_whole_file_str(file: &str) -> str {
str::unsafe_from_bytes(read_whole_file(file))
}
-fn read_whole_file(file: &istr) -> [u8] {
+fn read_whole_file(file: &str) -> [u8] {
// FIXME: There's a lot of copying here
file_reader(file).read_whole_stream()
fn S_IWUSR() -> uint { ret 128u; }
}
-fn exec_suffix() -> istr { ret ~""; }
+fn exec_suffix() -> str { ret ""; }
-fn target_os() -> istr { ret ~"linux"; }
+fn target_os() -> str { ret "linux"; }
-fn dylib_filename(base: &istr) -> istr { ret ~"lib" + base + ~".so"; }
+fn dylib_filename(base: &str) -> str { ret "lib" + base + ".so"; }
fn pipe() -> {in: int, out: int} {
let fds = {mutable in: 0, mutable out: 0};
}
fn fd_FILE(fd: int) -> libc::FILE {
- ret str::as_buf(~"r", { |modebuf|
- libc::fdopen(fd, modebuf)
- });
+ ret str::as_buf("r", {|modebuf| libc::fdopen(fd, modebuf) });
}
fn waitpid(pid: int) -> int {
}
native "rust" mod rustrt {
- fn rust_getcwd() -> istr;
+ fn rust_getcwd() -> str;
}
-fn getcwd() -> istr {
- ret rustrt::rust_getcwd();
-}
+fn getcwd() -> str { ret rustrt::rust_getcwd(); }
// Local Variables:
fn S_IWUSR() -> uint { ret 512u; }
}
-fn exec_suffix() -> istr { ret ~""; }
+fn exec_suffix() -> str { ret ""; }
-fn target_os() -> istr { ret ~"macos"; }
+fn target_os() -> str { ret "macos"; }
-fn dylib_filename(base: &istr) -> istr { ret ~"lib" + base + ~".dylib"; }
+fn dylib_filename(base: &str) -> str { ret "lib" + base + ".dylib"; }
fn pipe() -> {in: int, out: int} {
let fds = {mutable in: 0, mutable out: 0};
}
fn fd_FILE(fd: int) -> libc::FILE {
- ret str::as_buf(~"r", { |modebuf|
- libc::fdopen(fd, modebuf)
- });
+ ret str::as_buf("r", {|modebuf| libc::fdopen(fd, modebuf) });
}
fn waitpid(pid: int) -> int {
}
native "rust" mod rustrt {
- fn rust_getcwd() -> istr;
+ fn rust_getcwd() -> str;
}
-fn getcwd() -> istr {
- ret rustrt::rust_getcwd();
-}
+fn getcwd() -> str { ret rustrt::rust_getcwd(); }
// Local Variables:
// Hash map constructors for basic types
-fn new_str_hash<@V>() -> hashmap<istr, V> {
+fn new_str_hash<@V>() -> hashmap<str, V> {
ret mk_hashmap(str::hash, str::eq);
}
tag ip_addr { ipv4(u8, u8, u8, u8); }
-fn format_addr(ip: ip_addr) -> istr {
+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]
}
}
-fn parse_addr(ip: &istr) -> ip_addr {
- let parts = vec::map(
- { |&s| uint::from_str(s) },
- str::split(ip, ~"."[0]));
+fn parse_addr(ip: &str) -> ip_addr {
+ let parts = vec::map({|&s| uint::from_str(s) }, 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)
native "rust" mod rustrt {
- fn rust_list_files(path: &istr) -> [istr];
+ fn rust_list_files(path: &str) -> [str];
}
-fn list_dir(path: &istr) -> [istr] {
+fn list_dir(path: &str) -> [str] {
ret rustrt::rust_list_files(path);
// FIXME: No idea why, but this appears to corrupt memory on OSX. I
}
-fn path_is_absolute(p: &istr) -> bool { ret str::char_at(p, 0u) == '/'; }
+fn path_is_absolute(p: &str) -> bool { ret str::char_at(p, 0u) == '/'; }
const path_sep: char = '/';
int;
}
-fn arg_vec(prog: &istr, args: &[@istr]) -> [sbuf] {
- let argptrs = str::as_buf(prog, { |buf| [buf] });
- for arg in args {
- argptrs += str::as_buf(*arg, { |buf| [buf] });
- }
+fn arg_vec(prog: &str, args: &[@str]) -> [sbuf] {
+ let argptrs = str::as_buf(prog, {|buf| [buf] });
+ for arg in args { argptrs += str::as_buf(*arg, {|buf| [buf] }); }
argptrs += [unsafe::reinterpret_cast(0)];
ret argptrs;
}
-fn spawn_process(prog: &istr, args: &[istr], in_fd: int, out_fd: int,
+fn spawn_process(prog: &str, args: &[str], in_fd: int, out_fd: int,
err_fd: int) -> int {
// Note: we have to hold on to these vector references while we hold a
// pointer to their buffers
let prog = prog;
- let args = vec::map({ |&arg| @arg }, args);
+ let args = vec::map({|&arg| @arg }, args);
let argv = arg_vec(prog, args);
let pid =
- rustrt::rust_run_program(vec::unsafe::to_ptr(argv),
- in_fd, out_fd, err_fd);
+ rustrt::rust_run_program(vec::unsafe::to_ptr(argv), in_fd, out_fd,
+ err_fd);
ret pid;
}
-fn run_program(prog: &istr, args: &[istr]) -> int {
+fn run_program(prog: &str, args: &[str]) -> int {
ret os::waitpid(spawn_process(prog, args, 0, 0, 0));
}
resource program_res(p: program) { p.destroy(); }
-fn start_program(prog: &istr, args: &[istr]) -> @program_res {
+fn start_program(prog: &str, args: &[str]) -> @program_res {
let pipe_input = os::pipe();
let pipe_output = os::pipe();
let pipe_err = os::pipe();
os::fd_FILE(pipe_err.in), false));
}
-fn read_all(rd: &io::reader) -> istr {
- let buf = ~"";
+fn read_all(rd: &io::reader) -> str {
+ let buf = "";
while !rd.eof() {
let bytes = rd.read_bytes(4096u);
buf += str::unsafe_from_bytes(bytes);
ret buf;
}
-fn program_output(prog: &istr, args: &[istr]) ->
- {status: int, out: istr, err: istr} {
+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 sha1;
export mk_sha1;
-type sha1 = obj {
+type sha1 =
// Provide message input as bytes
- fn input(&[u8]);
// Provide message input as string
- fn input_str(&istr);
// Read the digest as a vector of 20 bytes. After calling this no further
// input may provided until reset is called
- fn result() -> [u8];
// Same as above, just a hex-string version.
- fn result_str() -> istr;
// Reset the sha1 state for reuse. This is called
// automatically during construction
- fn reset();
-};
+ obj {
+ fn input(&[u8]);
+ fn input_str(&str);
+ fn result() -> [u8];
+ fn result_str() -> str;
+ fn reset();
+ };
// Some unexported constants
st.computed = false;
}
fn input(msg: &[u8]) { add_input(st, msg); }
- fn input_str(msg: &istr) { add_input(st, str::bytes(msg)); }
+ fn input_str(msg: &str) { add_input(st, str::bytes(msg)); }
fn result() -> [u8] { ret mk_result(st); }
- fn result_str() -> istr {
+ fn result_str() -> str {
let r = mk_result(st);
- let s = ~"";
- for b: u8 in r {
- s += uint::to_str(b as uint, 16u);
- }
+ let s = "";
+ for b: u8 in r { s += uint::to_str(b as uint, 16u); }
ret s;
}
}
-export eq, lteq, hash, is_empty, is_not_empty, is_whitespace, byte_len,
-index, rindex, find, starts_with, ends_with, substr, slice, split,
-concat, connect, to_upper, replace, char_slice, trim_left, trim_right, trim,
-unshift_char, shift_char, pop_char, push_char, is_utf8, from_chars, to_chars,
-char_len, char_at, bytes, is_ascii, shift_byte, pop_byte, unsafe_from_byte,
-unsafe_from_bytes, from_char, char_range_at, str_from_cstr, sbuf,
-as_buf, push_byte, utf8_char_width, safe_slice;
+export eq, lteq, hash, is_empty, is_not_empty, is_whitespace, byte_len, index,
+ rindex, find, starts_with, ends_with, substr, slice, split, concat,
+ connect, to_upper, replace, char_slice, trim_left, trim_right, trim,
+ unshift_char, shift_char, pop_char, push_char, is_utf8, from_chars,
+ to_chars, char_len, char_at, bytes, is_ascii, shift_byte, pop_byte,
+ unsafe_from_byte, unsafe_from_bytes, from_char, char_range_at,
+ str_from_cstr, sbuf, as_buf, push_byte, utf8_char_width, safe_slice;
native "rust" mod rustrt {
- fn rust_istr_push(s: &mutable istr, ch: u8);
+ fn rust_istr_push(s: &mutable str, ch: u8);
}
-fn eq(a: &istr, b: &istr) -> bool { a == b }
+fn eq(a: &str, b: &str) -> bool { a == b }
-fn lteq(a: &istr, b: &istr) -> bool { a <= b }
+fn lteq(a: &str, b: &str) -> bool { a <= b }
-fn hash(s: &istr) -> uint {
+fn hash(s: &str) -> uint {
// djb hash.
// FIXME: replace with murmur.
ret true;
}
-fn is_ascii(s: &istr) -> bool {
+fn is_ascii(s: &str) -> bool {
let i: uint = byte_len(s);
while i > 0u { i -= 1u; if s[i] & 128u8 != 0u8 { ret false; } }
ret true;
}
/// Returns true if the string has length 0
-pure fn is_empty(s: &istr) -> bool {
- for c: u8 in s { ret false; } ret true;
-}
+pure fn is_empty(s: &str) -> bool { for c: u8 in s { ret false; } ret true; }
/// Returns true if the string has length greater than 0
-pure fn is_not_empty(s: &istr) -> bool {
- !is_empty(s)
-}
+pure fn is_not_empty(s: &str) -> bool { !is_empty(s) }
-fn is_whitespace(s: &istr) -> bool {
+fn is_whitespace(s: &str) -> bool {
let i = 0u;
let len = char_len(s);
while i < len {
ret true;
}
-fn byte_len(s: &istr) -> uint {
+fn byte_len(s: &str) -> uint {
let v: [u8] = unsafe::reinterpret_cast(s);
let vlen = vec::len(v);
unsafe::leak(v);
// There should always be a null terminator
- assert vlen > 0u;
+ assert (vlen > 0u);
ret vlen - 1u;
}
-fn bytes(s: &istr) -> [u8] {
+fn bytes(s: &str) -> [u8] {
let v = unsafe::reinterpret_cast(s);
let vcopy = vec::slice(v, 0u, vec::len(v) - 1u);
unsafe::leak(v);
ret vcopy;
}
-fn unsafe_from_bytes(v: &[mutable? u8]) -> istr {
+fn unsafe_from_bytes(v: &[mutable? u8]) -> str {
let vcopy: [u8] = v + [0u8];
- let scopy: istr = unsafe::reinterpret_cast(vcopy);
+ let scopy: str = unsafe::reinterpret_cast(vcopy);
unsafe::leak(vcopy);
ret scopy;
}
-fn unsafe_from_byte(u: u8) -> istr {
- unsafe_from_bytes([u])
-}
+fn unsafe_from_byte(u: u8) -> str { unsafe_from_bytes([u]) }
-fn push_utf8_bytes(s: &mutable istr, ch: char) {
+fn push_utf8_bytes(s: &mutable str, ch: char) {
let code = ch as uint;
- let bytes = if code < max_one_b {
- [code as u8]
- } else if code < max_two_b {
- [(code >> 6u & 31u | tag_two_b) as u8,
- (code & 63u | tag_cont) as u8]
- } else if code < max_three_b {
- [(code >> 12u & 15u | tag_three_b) as u8,
- (code >> 6u & 63u | tag_cont) as u8,
- (code & 63u | tag_cont) as u8]
- } else if code < max_four_b {
- [(code >> 18u & 7u | tag_four_b) as u8,
- (code >> 12u & 63u | tag_cont) as u8,
- (code >> 6u & 63u | tag_cont) as u8,
- (code & 63u | tag_cont) as u8]
- } else if code < max_five_b {
- [(code >> 24u & 3u | tag_five_b) as u8,
- (code >> 18u & 63u | tag_cont) as u8,
- (code >> 12u & 63u | tag_cont) as u8,
- (code >> 6u & 63u | tag_cont) as u8,
- (code & 63u | tag_cont) as u8]
- } else {
- [(code >> 30u & 1u | tag_six_b) as u8,
- (code >> 24u & 63u | tag_cont) as u8,
- (code >> 18u & 63u | tag_cont) as u8,
- (code >> 12u & 63u | tag_cont) as u8,
- (code >> 6u & 63u | tag_cont) as u8,
- (code & 63u | tag_cont) as u8]
- };
+ let bytes =
+ if code < max_one_b {
+ [code as u8]
+ } else if code < max_two_b {
+ [code >> 6u & 31u | tag_two_b as u8, code & 63u | tag_cont as u8]
+ } else if code < max_three_b {
+ [code >> 12u & 15u | tag_three_b as u8,
+ code >> 6u & 63u | tag_cont as u8, code & 63u | tag_cont as u8]
+ } else if code < max_four_b {
+ [code >> 18u & 7u | tag_four_b as u8,
+ code >> 12u & 63u | tag_cont as u8,
+ code >> 6u & 63u | tag_cont as u8, code & 63u | tag_cont as u8]
+ } else if code < max_five_b {
+ [code >> 24u & 3u | tag_five_b as u8,
+ code >> 18u & 63u | tag_cont as u8,
+ code >> 12u & 63u | tag_cont as u8,
+ code >> 6u & 63u | tag_cont as u8, code & 63u | tag_cont as u8]
+ } else {
+ [code >> 30u & 1u | tag_six_b as u8,
+ code >> 24u & 63u | tag_cont as u8,
+ code >> 18u & 63u | tag_cont as u8,
+ code >> 12u & 63u | tag_cont as u8,
+ code >> 6u & 63u | tag_cont as u8, code & 63u | tag_cont as u8]
+ };
push_bytes(s, bytes);
}
-fn from_char(ch: char) -> istr {
- let buf = ~"";
+fn from_char(ch: char) -> str {
+ let buf = "";
push_utf8_bytes(buf, ch);
ret buf;
}
-fn from_chars(chs: &[char]) -> istr {
- let buf = ~"";
+fn from_chars(chs: &[char]) -> str {
+ let buf = "";
for ch: char in chs { push_utf8_bytes(buf, ch); }
ret buf;
}
ret 6u;
}
-fn char_range_at(s: &istr, i: uint) -> {ch: char, next: uint} {
+fn char_range_at(s: &str, i: uint) -> {ch: char, next: uint} {
let b0 = s[i];
let w = utf8_char_width(b0);
assert (w != 0u);
ret {ch: val as char, next: i};
}
-fn char_at(s: &istr, i: uint) -> char { ret char_range_at(s, i).ch; }
+fn char_at(s: &str, i: uint) -> char { ret char_range_at(s, i).ch; }
-fn char_len(s: &istr) -> uint {
+fn char_len(s: &str) -> uint {
let i = 0u;
let len = 0u;
let total = byte_len(s);
ret len;
}
-fn to_chars(s: &istr) -> [char] {
+fn to_chars(s: &str) -> [char] {
let buf: [char] = [];
let i = 0u;
let len = byte_len(s);
ret buf;
}
-fn push_char(s: &mutable istr, ch: char) { s += from_char(ch); }
+fn push_char(s: &mutable str, ch: char) { s += from_char(ch); }
-fn pop_char(s: &mutable istr) -> char {
+fn pop_char(s: &mutable str) -> char {
let end = byte_len(s);
while end > 0u && s[end - 1u] & 192u8 == tag_cont_u8 { end -= 1u; }
assert (end > 0u);
ret ch;
}
-fn shift_char(s: &mutable istr) -> char {
+fn shift_char(s: &mutable str) -> char {
let r = char_range_at(s, 0u);
s = substr(s, r.next, byte_len(s) - r.next);
ret r.ch;
}
-fn unshift_char(s: &mutable istr, ch: char) { s = from_char(ch) + s; }
+fn unshift_char(s: &mutable str, ch: char) { s = from_char(ch) + s; }
-fn index(s: &istr, c: u8) -> int {
+fn index(s: &str, c: u8) -> int {
let i: int = 0;
for k: u8 in s { if k == c { ret i; } i += 1; }
ret -1;
}
-fn rindex(s: &istr, c: u8) -> int {
+fn rindex(s: &str, c: u8) -> int {
let n: int = byte_len(s) as int;
while n >= 0 { if s[n] == c { ret n; } n -= 1; }
ret n;
}
-fn find(haystack: &istr, needle: &istr) -> int {
+fn find(haystack: &str, needle: &str) -> int {
let haystack_len: int = byte_len(haystack) as int;
let needle_len: int = byte_len(needle) as int;
if needle_len == 0 { ret 0; }
- fn match_at(haystack: &istr, needle: &istr, i: int) -> bool {
+ 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; }
ret true;
ret -1;
}
-fn starts_with(haystack: &istr, needle: &istr) -> bool {
+fn starts_with(haystack: &str, needle: &str) -> bool {
let haystack_len: uint = byte_len(haystack);
let needle_len: uint = byte_len(needle);
if needle_len == 0u { ret true; }
ret eq(substr(haystack, 0u, needle_len), needle);
}
-fn ends_with(haystack: &istr, needle: &istr) -> bool {
+fn ends_with(haystack: &str, needle: &str) -> bool {
let haystack_len: uint = byte_len(haystack);
let needle_len: uint = byte_len(needle);
ret if needle_len == 0u {
};
}
-fn substr(s: &istr, begin: uint, len: uint) -> istr {
+fn substr(s: &str, begin: uint, len: uint) -> str {
ret slice(s, begin, begin + len);
}
-fn slice(s: &istr, begin: uint, end: uint) -> istr {
+fn slice(s: &str, begin: uint, end: uint) -> str {
// FIXME: Typestate precondition
assert (begin <= end);
assert (end <= byte_len(s));
let v2 = vec::slice(v, begin, end);
unsafe::leak(v);
v2 += [0u8];
- let s2: istr = unsafe::reinterpret_cast(v2);
+ let s2: str = unsafe::reinterpret_cast(v2);
unsafe::leak(v2);
ret s2;
}
-fn safe_slice(s: &istr, begin: uint, end: uint)
- : uint::le(begin, end) -> istr {
+fn safe_slice(s: &str, begin: uint, end: uint) : uint::le(begin, end) -> str {
// would need some magic to make this a precondition
assert (end <= byte_len(s));
ret slice(s, begin, end);
}
-fn shift_byte(s: &mutable istr) -> u8 {
+fn shift_byte(s: &mutable str) -> u8 {
let len = byte_len(s);
assert (len > 0u);
let b = s[0];
ret b;
}
-fn pop_byte(s: &mutable istr) -> u8 {
+fn pop_byte(s: &mutable str) -> u8 {
let len = byte_len(s);
assert (len > 0u);
let b = s[len - 1u];
ret b;
}
-fn push_byte(s: &mutable istr, b: u8) {
- rustrt::rust_istr_push(s, b);
-}
+fn push_byte(s: &mutable str, b: u8) { rustrt::rust_istr_push(s, b); }
-fn push_bytes(s: &mutable istr, bytes: &[u8]) {
- for byte in bytes {
- rustrt::rust_istr_push(s, byte);
- }
+fn push_bytes(s: &mutable str, bytes: &[u8]) {
+ for byte in bytes { rustrt::rust_istr_push(s, byte); }
}
-fn split(s: &istr, sep: u8) -> [istr] {
- let v: [istr] = [];
- let accum: istr = ~"";
+fn split(s: &str, sep: u8) -> [str] {
+ let v: [str] = [];
+ let accum: str = "";
let ends_with_sep: bool = false;
for c: u8 in s {
if c == sep {
v += [accum];
- accum = ~"";
+ accum = "";
ends_with_sep = true;
} else { accum += unsafe_from_byte(c); ends_with_sep = false; }
}
ret v;
}
-fn concat(v: &[istr]) -> istr {
- let s: istr = ~"";
- for ss: istr in v { s += ss; }
+fn concat(v: &[str]) -> str {
+ let s: str = "";
+ for ss: str in v { s += ss; }
ret s;
}
-fn connect(v: &[istr], sep: &istr) -> istr {
- let s: istr = ~"";
+fn connect(v: &[str], sep: &str) -> str {
+ let s: str = "";
let first: bool = true;
- for ss: istr in v {
+ for ss: str in v {
if first { first = false; } else { s += sep; }
s += ss;
}
}
// FIXME: This only handles ASCII
-fn to_upper(s: &istr) -> istr {
- let outstr = ~"";
+fn to_upper(s: &str) -> str {
+ let outstr = "";
let ascii_a = 'a' as u8;
let ascii_z = 'z' as u8;
let diff = 32u8;
}
// FIXME: This is super-inefficient
-fn replace(s: &istr, from: &istr, to: &istr) : is_not_empty(from) -> istr {
+fn replace(s: &str, from: &str, to: &str) : is_not_empty(from) -> str {
// FIXME (694): Shouldn't have to check this
check (is_not_empty(from));
if byte_len(s) == 0u {
- ret ~"";
+ ret "";
} else if starts_with(s, from) {
ret to + replace(slice(s, byte_len(from), byte_len(s)), from, to);
} else {
}
// FIXME: Also not efficient
-fn char_slice(s: &istr, begin: uint, end: uint) -> istr {
+fn char_slice(s: &str, begin: uint, end: uint) -> str {
from_chars(vec::slice(to_chars(s), begin, end))
}
-fn trim_left(s: &istr) -> istr {
+fn trim_left(s: &str) -> str {
fn count_whities(s: &[char]) -> uint {
let i = 0u;
while i < vec::len(s) {
ret from_chars(vec::slice(chars, whities, vec::len(chars)));
}
-fn trim_right(s: &istr) -> istr {
+fn trim_right(s: &str) -> str {
fn count_whities(s: &[char]) -> uint {
let i = vec::len(s);
while 0u < i {
ret from_chars(vec::slice(chars, 0u, whities));
}
-fn trim(s: &istr) -> istr {
- trim_left(trim_right(s))
-}
+fn trim(s: &str) -> str { trim_left(trim_right(s)) }
type sbuf = *u8;
-fn buf(s: &istr) -> sbuf {
+fn buf(s: &str) -> sbuf {
let saddr = ptr::addr_of(s);
let vaddr: *[u8] = unsafe::reinterpret_cast(saddr);
let buf = vec::to_ptr(*vaddr);
ret buf;
}
-fn as_buf<T>(s: &istr, f: &block(sbuf) -> T) -> T {
- let buf = buf(s);
- f(buf)
-}
+fn as_buf<T>(s: &str, f: &block(sbuf) -> T) -> T { let buf = buf(s); f(buf) }
-fn str_from_cstr(cstr: sbuf) -> istr {
- let res = ~"";
+fn str_from_cstr(cstr: sbuf) -> str {
+ let res = "";
let start = cstr;
let curr = start;
let i = 0u;
curr = ptr::offset(start, i);
}
ret res;
-}
\ No newline at end of file
+}
// set up the task pointer
let task_ptr = rust_task_ptr(rustrt::get_task_pointer(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);
}
fn color_supported() -> bool {
- let supported_terms = [~"xterm-color", ~"xterm", ~"screen-bce"];
- ret alt generic_os::getenv(~"TERM") {
+ let supported_terms = ["xterm-color", "xterm", "screen-bce"];
+ ret alt generic_os::getenv("TERM") {
option::some(env) {
- for term: istr in supported_terms {
+ for term: str in supported_terms {
if str::eq(term, env) { ret true; }
}
false
// paths, i.e it should be a series of identifiers seperated by double
// colons. This way if some test runner wants to arrange the tests
// heirarchically it may.
-type test_name = istr;
+type test_name = str;
// A function that runs a test. If the function returns successfully,
// the test succeeds; if the function fails then the test fails. We
// The default console test runner. It accepts the command line
// arguments and a vector of test_descs (generated at compile time).
-fn test_main(args: &[istr], tests: &[test_desc]) {
+fn test_main(args: &[str], tests: &[test_desc]) {
check (vec::is_not_empty(args));
let opts =
alt parse_opts(args) {
if !run_tests_console(opts, tests) { fail "Some tests failed"; }
}
-type test_opts = {filter: option::t<istr>, run_ignored: bool};
+type test_opts = {filter: option::t<str>, run_ignored: bool};
-type opt_res = either::t<test_opts, istr>;
+type opt_res = either::t<test_opts, str>;
// Parses command line arguments into test options
-fn parse_opts(args: &[istr]) : vec::is_not_empty(args) -> opt_res {
+fn parse_opts(args: &[str]) : vec::is_not_empty(args) -> opt_res {
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 }
- getopts::failure(f) {
- ret either::right(getopts::fail_str(f))
- }
+ getopts::failure(f) { ret either::right(getopts::fail_str(f)) }
};
let filter =
option::some(match.free[0])
} else { option::none };
- let run_ignored = getopts::opt_present(match, ~"ignored");
+ let run_ignored = getopts::opt_present(match, "ignored");
let test_opts = {filter: filter, run_ignored: run_ignored};
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.passed += 1u;
write_ok(st.out, st.use_color);
- st.out.write_line(~"");
+ st.out.write_line("");
}
tr_failed. {
st.failed += 1u;
write_failed(st.out, st.use_color);
- st.out.write_line(~"");
+ st.out.write_line("");
st.failures += [test];
}
tr_ignored. {
st.ignored += 1u;
write_ignored(st.out, st.use_color);
- st.out.write_line(~"");
+ st.out.write_line("");
}
}
}
let success = st.failed == 0u;
if !success {
- st.out.write_line(~"\nfailures:");
+ 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]);
// 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.out.write_str(#fmt[". %u passed; %u failed; %u ignored\n\n", st.passed,
st.failed, st.ignored]);
ret success;
fn write_ok(out: &io::writer, use_color: bool) {
- write_pretty(out, ~"ok", term::color_green, use_color);
+ write_pretty(out, "ok", term::color_green, use_color);
}
fn write_failed(out: &io::writer, use_color: bool) {
- write_pretty(out, ~"FAILED", term::color_red, use_color);
+ write_pretty(out, "FAILED", term::color_red, use_color);
}
fn write_ignored(out: &io::writer, use_color: bool) {
- write_pretty(out, ~"ignored", term::color_yellow, use_color);
+ write_pretty(out, "ignored", term::color_yellow, use_color);
}
- fn write_pretty(out: &io::writer, word: &istr, color: u8,
+ fn write_pretty(out: &io::writer, word: &str, color: u8,
use_color: bool) {
if use_color && term::color_supported() {
term::fg(out.get_buf_writer(), color);
let filter_str =
alt opts.filter {
option::some(f) { f }
- option::none. { ~"" }
+ option::none. { "" }
};
let filter =
- bind fn (test: &test_desc, filter_str: &istr) ->
+ bind fn (test: &test_desc, filter_str: &str) ->
option::t<test_desc> {
if str::find(test.name, filter_str) >= 0 {
ret option::some(test);
export find;
export traverse;
-tag tree_node<@K, @V> {
- empty;
- node(@K, @V, treemap<K, V>, treemap<K, V>);
-}
+tag tree_node<@K, @V> { empty; node(@K, @V, treemap<K, V>, treemap<K, V>); }
type treemap<@K, @V> = @mutable tree_node<K, V>;
-fn init<@K, @V>() -> treemap<K,V> { @mutable empty }
+fn init<@K, @V>() -> treemap<K, V> { @mutable empty }
-fn insert<@K, @V>(m : &treemap<K, V>, k : &K, v : &V) {
+fn insert<@K, @V>(m: &treemap<K, V>, k: &K, v: &V) {
alt m {
- @empty. {
- *m = node(@k, @v, @mutable empty, @mutable empty);
- }
+ @empty. { *m = node(@k, @v, @mutable empty, @mutable empty); }
@node(@kk, _, _, _) {
+
// We have to name left and right individually, because
// otherwise the alias checker complains.
if k < kk {
- alt m {
- @node(_, _, left, _) {
- insert(left, k, v);
- }
- }
- }
- else {
- alt m {
- @node(_, _, _, right) {
- insert(right, k, v);
- }
- }
- }
+ alt m { @node(_, _, left, _) { insert(left, k, v); } }
+ } else { alt m { @node(_, _, _, right) { insert(right, k, v); } } }
}
}
}
-fn find<@K, @V>(m : &treemap<K, V>, k : &K) -> option<V> {
- alt *m {
- empty. { none }
- node(@kk, @v, _, _) {
- if k == kk { some(v) }
- // Again, ugliness to unpack left and right individually.
- else if k < kk {
- alt *m {
- node(_, _, left, _) {
- find(left, k)
- }
- }
- }
- else {
- alt *m {
- node(_, _, _, right) {
- find(right, k)
- }
- }
+fn find<@K, @V>(m: &treemap<K, V>, k: &K) -> option<V> {
+ alt *m {
+ empty. { none }
+ node(@kk, @v, _, _) {
+ if k == kk {
+ some(v)
+ } else if k < kk {
+ // Again, ugliness to unpack left and right individually.
+ alt *m { node(_, _, left, _) { find(left, k) } }
+ } else { alt *m { node(_, _, _, right) { find(right, k) } } }
}
}
- }
}
// Performs an in-order traversal
-fn traverse<@K, @V>(m : &treemap<K, V>, f : fn(&K, &V)) {
- alt *m {
- empty. { }
- node(k, v, _, _) {
- let k1 = k, v1 = v;
- alt *m {
- node(_, _, left, _) {
- traverse(left, f);
- }
- }
- f(*k1, *v1);
- alt *m {
- node(_, _, _, right) {
- traverse(right, f);
- }
+fn traverse<@K, @V>(m: &treemap<K, V>, f: fn(&K, &V)) {
+ alt *m {
+ empty. { }
+ node(k, v, _, _) {
+ let k1 = k, v1 = v;
+ alt *m { node(_, _, left, _) { traverse(left, f); } }
+ f(*k1, *v1);
+ alt *m { node(_, _, _, right) { traverse(right, f); } }
}
}
- }
}
-fn to_str(n: u64, radix: uint) -> istr {
+fn to_str(n: u64, radix: uint) -> str {
assert (0u < radix && radix <= 16u);
let r64 = radix as u64;
- fn digit(n: u64) -> istr {
+ fn digit(n: u64) -> str {
ret alt n {
- 0u64 { ~"0" }
- 1u64 { ~"1" }
- 2u64 { ~"2" }
- 3u64 { ~"3" }
- 4u64 { ~"4" }
- 5u64 { ~"5" }
- 6u64 { ~"6" }
- 7u64 { ~"7" }
- 8u64 { ~"8" }
- 9u64 { ~"9" }
- 10u64 { ~"a" }
- 11u64 { ~"b" }
- 12u64 { ~"c" }
- 13u64 { ~"d" }
- 14u64 { ~"e" }
- 15u64 { ~"f" }
+ 0u64 { "0" }
+ 1u64 { "1" }
+ 2u64 { "2" }
+ 3u64 { "3" }
+ 4u64 { "4" }
+ 5u64 { "5" }
+ 6u64 { "6" }
+ 7u64 { "7" }
+ 8u64 { "8" }
+ 9u64 { "9" }
+ 10u64 { "a" }
+ 11u64 { "b" }
+ 12u64 { "c" }
+ 13u64 { "d" }
+ 14u64 { "e" }
+ 15u64 { "f" }
_ { fail }
};
}
- if n == 0u64 { ret ~"0"; }
+ if n == 0u64 { ret "0"; }
- let s = ~"";
+ let s = "";
while n > 0u64 { s = digit(n % r64) + s; n /= r64; }
ret s;
}
-fn str(n: u64) -> istr { ret to_str(n, 10u); }
+fn str(n: u64) -> str { ret to_str(n, 10u); }
fail;
}
-fn from_str(s: &istr) -> 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) -> istr {
+fn to_str(num: uint, radix: uint) -> str {
let n = num;
assert (0u < radix && radix <= 16u);
fn digit(n: uint) -> char {
_ { fail }
};
}
- if n == 0u { ret ~"0"; }
- let s: istr = ~"";
+ if n == 0u { ret "0"; }
+ let s: str = "";
while n != 0u {
s += str::unsafe_from_byte(digit(n % radix) as u8);
n /= radix;
}
- let s1: istr = ~"";
+ let s1: str = "";
let len: uint = str::byte_len(s);
while len != 0u { len -= 1u; s1 += str::unsafe_from_byte(s[len]); }
ret s1;
}
-fn str(i: uint) -> istr { ret to_str(i, 10u); }
+fn str(i: uint) -> str { ret to_str(i, 10u); }
// Local Variables:
// mode: rust;
// Casts the value at `src` to U. The two types must have the same length.
fn reinterpret_cast<T, @U>(src: &T) -> U { ret rusti::cast(src); }
-fn leak<@T>(thing: -T) {
- rustrt::leak(thing);
-}
\ No newline at end of file
+fn leak<@T>(thing: -T) { rustrt::leak(thing); }
}
pure fn same_length<T, U>(xs: &[T], ys: &[U]) -> bool {
- let xlen = unchecked { vec::len(xs) };
- let ylen = unchecked { vec::len(ys) };
+ let xlen = unchecked{ vec::len(xs) };
+ let ylen = unchecked{ vec::len(ys) };
xlen == ylen
}
}
// Generating vecs.
-fn enum_chars(start:u8, end:u8) : u8::le(start, end) -> [char] {
+fn enum_chars(start: u8, end: u8) : u8::le(start, end) -> [char] {
let i = start;
let r = [];
- while (i <= end) {
- r += [i as char];
- i += (1u as u8);
- }
+ while i <= end { r += [i as char]; i += 1u as u8; }
ret r;
}
-fn enum_uints(start:uint, end:uint) : uint::le(start, end) -> [uint] {
+fn enum_uints(start: uint, end: uint) : uint::le(start, end) -> [uint] {
let i = start;
let r = [];
- while (i <= end) {
- r += [i];
- i += 1u;
- }
+ while i <= end { r += [i]; i += 1u; }
ret r;
}
// Iterate over a list with with the indexes
iter iter2<@T>(v: &[T]) -> (uint, T) {
let i = 0u;
- for x in v {
- put (i, x);
- i += 1u;
- }
+ for x in v { put (i, x); i += 1u; }
}
mod unsafe {
- type vec_repr = {mutable fill: uint,
- mutable alloc: uint,
- data: u8};
+ type vec_repr = {mutable fill: uint, mutable alloc: uint, data: u8};
fn from_buf<T>(ptr: *T, elts: uint) -> [T] {
ret rustrt::vec_from_buf_shared(ptr, elts);
}
}
-fn to_ptr<T>(v: &[T]) -> *T {
- ret unsafe::to_ptr(v);
-}
+fn to_ptr<T>(v: &[T]) -> *T { ret unsafe::to_ptr(v); }
// Local Variables:
// mode: rust;
native "rust" mod rustrt {
- fn rust_list_files(path: &istr) -> [istr];
+ fn rust_list_files(path: &str) -> [str];
fn rust_file_is_dir(path: str) -> int;
}
-fn list_dir(path: &istr) -> [istr] {
- let path = path + ~"*";
+fn list_dir(path: &str) -> [str] {
+ let path = path + "*";
ret rustrt::rust_list_files(path);
}
-fn path_is_absolute(p: &istr) -> bool {
+fn path_is_absolute(p: &str) -> bool {
ret str::char_at(p, 0u) == '/' ||
str::char_at(p, 1u) == ':' && str::char_at(p, 2u) == '\\';
}
}
native "x86stdcall" mod kernel32 {
- fn GetEnvironmentVariableA(n: str::sbuf, v: str::sbuf,
- nsize: uint) -> uint;
+ fn GetEnvironmentVariableA(n: str::sbuf, v: str::sbuf, nsize: uint) ->
+ uint;
fn SetEnvironmentVariableA(n: str::sbuf, v: str::sbuf) -> int;
}
-fn exec_suffix() -> istr { ret ~".exe"; }
+fn exec_suffix() -> str { ret ".exe"; }
-fn target_os() -> istr { ret ~"win32"; }
+fn target_os() -> str { ret "win32"; }
-fn dylib_filename(base: &istr) -> istr { ret base + ~".dll"; }
+fn dylib_filename(base: &str) -> str { ret base + ".dll"; }
fn pipe() -> {in: int, out: int} {
// Windows pipes work subtly differently than unix pipes, and their
}
fn fd_FILE(fd: int) -> libc::FILE {
- ret str::as_buf(~"r", { |modebuf|
- libc::_fdopen(fd, modebuf)
- });
+ ret str::as_buf("r", {|modebuf| libc::_fdopen(fd, modebuf) });
}
native "rust" mod rustrt {
fn rust_process_wait(handle: int) -> int;
- fn rust_getcwd() -> istr;
+ fn rust_getcwd() -> str;
}
fn waitpid(pid: int) -> int { ret rustrt::rust_process_wait(pid); }
-fn getcwd() -> istr {
- ret rustrt::rust_getcwd();
-}
+fn getcwd() -> str { ret rustrt::rust_getcwd(); }
// Local Variables:
// mode: rust;
import std::int;
import std::str;
-fn b1() -> istr { ret ~"# of beer on the wall, # of beer."; }
+fn b1() -> str { ret "# of beer on the wall, # of beer."; }
-fn b2() -> istr {
- ret ~"Take one down and pass it around, # of beer on the wall.";
+fn b2() -> str {
+ ret "Take one down and pass it around, # of beer on the wall.";
}
-fn b7() -> istr {
- ret ~"No more bottles of beer on the wall, no more bottles of beer.";
+fn b7() -> str {
+ ret "No more bottles of beer on the wall, no more bottles of beer.";
}
-fn b8() -> istr {
- ret ~"Go to the store and buy some more, # of beer on the wall.";
+fn b8() -> str {
+ ret "Go to the store and buy some more, # of beer on the wall.";
}
-fn sub(t: &istr, n: int) -> istr {
- let b: istr = ~"";
+fn sub(t: &str, n: int) -> str {
+ let b: str = "";
let i: uint = 0u;
- let ns: istr;
+ let ns: str;
alt n {
- 0 { ns = ~"no more bottles"; }
- 1 { ns = ~"1 bottle"; }
- _ { ns = int::to_str(n, 10u) + ~" bottles"; }
+ 0 { ns = "no more bottles"; }
+ 1 { ns = "1 bottle"; }
+ _ { 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]); }
"1 bottle of beer on the wall.";
}
multiple(n) {
- let nb: istr = int::to_str(n, 10u);
- let mb: istr = int::to_str(n - 1, 10u);
- log nb + ~" bottles of beer on the wall, " + nb +
- ~" bottles of beer,";
- log ~"Take one down and pass it around, " + mb +
- ~" bottles of beer on the wall.";
+ let nb: str = int::to_str(n, 10u);
+ let mb: str = int::to_str(n - 1, 10u);
+ log nb + " bottles of beer on the wall, " + nb + " bottles of beer,";
+ log "Take one down and pass it around, " + mb +
+ " bottles of beer on the wall.";
}
}
}
import std::int;
import std::str;
-fn b1() -> istr { ret ~"# of beer on the wall, # of beer."; }
+fn b1() -> str { ret "# of beer on the wall, # of beer."; }
-fn b2() -> istr {
- ret ~"Take one down and pass it around, # of beer on the wall.";
+fn b2() -> str {
+ ret "Take one down and pass it around, # of beer on the wall.";
}
-fn b7() -> istr {
- ret ~"No more bottles of beer on the wall, no more bottles of beer.";
+fn b7() -> str {
+ ret "No more bottles of beer on the wall, no more bottles of beer.";
}
-fn b8() -> istr {
- ret ~"Go to the store and buy some more, # of beer on the wall.";
+fn b8() -> str {
+ ret "Go to the store and buy some more, # of beer on the wall.";
}
-fn sub(t: &istr, n: int) -> istr {
- let b: istr = ~"";
+fn sub(t: &str, n: int) -> str {
+ let b: str = "";
let i: uint = 0u;
- let ns: istr;
+ let ns: str;
alt n {
- 0 { ns = ~"no more bottles"; }
- 1 { ns = ~"1 bottle"; }
- _ { ns = int::to_str(n, 10u) + ~" bottles"; }
+ 0 { ns = "no more bottles"; }
+ 1 { ns = "1 bottle"; }
+ _ { 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]); }
fn main() {
fn multiple(n: int) {
- let nb: istr = int::to_str(n, 10u);
- let mb: istr = int::to_str(n - 1, 10u);
- log nb + ~" bottles of beer on the wall, " + nb +
- ~" bottles of beer,";
- log ~"Take one down and pass it around, " + mb +
- ~" bottles of beer on the wall.";
+ let nb: str = int::to_str(n, 10u);
+ let mb: str = int::to_str(n - 1, 10u);
+ log nb + " bottles of beer on the wall, " + nb + " bottles of beer,";
+ log "Take one down and pass it around, " + mb +
+ " bottles of beer on the wall.";
log "";
if n > 3 { be multiple(n - 1); } else { be dual(); }
}
ret flips;
}
-fn main(args: [istr]) {
+fn main(args: [str]) {
let n = 7;
log #fmt["Pfannkuchen(%d) = %d", n, fannkuch(n)];
}
ret bisect(genelist, 0u, vec::len::<aminoacids>(genelist) - 1u, r);
}
-fn make_random_fasta(id: &istr, desc: &istr,
- genelist: &[aminoacids], n: int) {
- log ~">" + id + ~" " + desc;
+fn make_random_fasta(id: &str, desc: &str, genelist: &[aminoacids], n: int) {
+ log ">" + id + " " + desc;
let rng = myrandom(std::rand::mk_rng().next());
- let op: istr = ~"";
+ let op: str = "";
for each i: uint in uint::range(0u, n as uint) {
str::push_byte(op, select_random(rng.next(100u32), genelist) as u8);
- if str::byte_len(op) >= LINE_LENGTH() { log op; op = ~""; }
+ if str::byte_len(op) >= LINE_LENGTH() { log op; op = ""; }
}
if str::byte_len(op) > 0u { log op; }
}
-fn make_repeat_fasta(id: &istr, desc: &istr, s: &istr, n: int) {
- log ~">" + id + ~" " + desc;
- let op: istr = ~"";
+fn make_repeat_fasta(id: &str, desc: &str, s: &str, n: int) {
+ log ">" + id + " " + desc;
+ 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]);
- if str::byte_len(op) >= LINE_LENGTH() { log op; op = ~""; }
+ if str::byte_len(op) >= LINE_LENGTH() { log op; op = ""; }
}
if str::byte_len(op) > 0u { log op; }
}
fn acid(ch: char, prob: u32) -> aminoacids { ret {ch: ch, prob: prob}; }
-fn main(args: [istr]) {
+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),
let homosapiens: [aminoacids] =
make_cumulative([acid('a', 30u32), acid('c', 20u32), acid('g', 20u32),
acid('t', 30u32)]);
- let alu: istr =
- ~"GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG" +
- ~"GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA" +
- ~"CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT" +
- ~"ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA" +
- ~"GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG" +
- ~"AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC" +
- ~"AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";
+ let alu: str =
+ "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG" +
+ "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA" +
+ "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT" +
+ "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA" +
+ "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG" +
+ "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC" +
+ "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";
let n: int = 512;
- make_repeat_fasta(~"ONE", ~"Homo sapiens alu", alu, n * 2);
- make_random_fasta(~"TWO", ~"IUB ambiguity codes", iub, n * 3);
- make_random_fasta(~"THREE", ~"Homo sapiens frequency",
- homosapiens, n * 5);
+ make_repeat_fasta("ONE", "Homo sapiens alu", alu, n * 2);
+ make_random_fasta("TWO", "IUB ambiguity codes", iub, n * 3);
+ make_random_fasta("THREE", "Homo sapiens frequency", homosapiens, n * 5);
}
type config = {stress: bool};
-fn parse_opts(argv: &[istr]) -> config {
- let opts = [getopts::optflag(~"stress")];
+fn parse_opts(argv: &[str]) -> config {
+ let opts = [getopts::optflag("stress")];
let opt_args = vec::slice(argv, 1u, vec::len(argv));
alt getopts::getopts(opt_args, opts) {
- getopts::success(m) { ret {stress: getopts::opt_present(m, ~"stress")} }
+ getopts::success(m) { ret {stress: getopts::opt_present(m, "stress")} }
getopts::failure(_) { fail; }
}
}
for t in tasks { task::join(t); }
}
-fn main(argv: [istr]) {
+fn main(argv: [str]) {
if vec::len(argv) == 1u {
assert (fib(8) == 21);
log fib(8);
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)]);
}
}
}
let i = 0u;
while i < n {
let thunk = g;
- task::join(task::spawn_joinable(thunk)); i += 1u; }
+ task::join(task::spawn_joinable(thunk));
+ i += 1u;
+ }
}
fn g() { }
-fn main(args: [istr]) {
+fn main(args: [str]) {
let n =
if vec::len(args) < 2u {
10u
}
}
-fn main(args: [istr]) {
- let n = if vec::len(args) < 2u {
- 100u
- } else {
- uint::parse_buf(str::bytes(args[1]), 10u)
- };
- for each i in uint::range(0u, 100u) {
- task::spawn(bind f(n));
- }
-}
\ No newline at end of file
+fn main(args: [str]) {
+ let n =
+ if vec::len(args) < 2u {
+ 100u
+ } else { uint::parse_buf(str::bytes(args[1]), 10u) };
+ for each i in uint::range(0u, 100u) { task::spawn(bind f(n)); }
+}
tag reduce_proto<~V> { emit_val(V); done; ref; release; }
- fn start_mappers<~K1, ~K2, ~V>(map : mapper<K1, K2, V>,
- ctrl: chan<ctrl_proto<K2, V>>, inputs: &[K1])
- -> [joinable_task] {
+ fn start_mappers<~K1, ~K2,
+ ~V>(map: mapper<K1, K2, V>,
+ ctrl: chan<ctrl_proto<K2, V>>, inputs: &[K1]) ->
+ [joinable_task] {
let tasks = [];
for i in inputs {
let m = map, c = ctrl, ii = i;
ret tasks;
}
- fn map_task<~K1, ~K2, ~V>(map : -mapper<K1,K2,V>,
- ctrl: -chan<ctrl_proto<K2,V>>, input: -K1) {
+ fn map_task<~K1, ~K2,
+ ~V>(map: -mapper<K1, K2, V>, ctrl: -chan<ctrl_proto<K2, V>>,
+ input: -K1) {
// log_err "map_task " + input;
let intermediates = treemap::init();
- fn emit<~K2, ~V>(im: &treemap::treemap<K2, chan<reduce_proto<V>>>,
- ctrl: &chan<ctrl_proto<K2,V>>, key: &K2, val: &V) {
+ fn emit<~K2,
+ ~V>(im: &treemap::treemap<K2, chan<reduce_proto<V>>>,
+ ctrl: &chan<ctrl_proto<K2, V>>, key: &K2, val: &V) {
let c;
alt treemap::find(im, key) {
- some(_c) {
- c = _c
- }
+ some(_c) { c = _c }
none. {
let p = port();
send(ctrl, find_reducer(key, chan(p)));
map(input, bind emit(intermediates, ctrl, _, _));
- fn finish<~K, ~V>(k : &K, v : &chan<reduce_proto<V>>) {
+ fn finish<~K, ~V>(k: &K, v: &chan<reduce_proto<V>>) {
send(v, release);
}
treemap::traverse(intermediates, finish);
send(ctrl, mapper_done);
}
- fn reduce_task<~K, ~V>(reduce : -reducer<K,V>,
- key: -K, out: -chan<chan<reduce_proto<V>>>) {
+ fn reduce_task<~K,
+ ~V>(reduce: -reducer<K, V>, key: -K,
+ out: -chan<chan<reduce_proto<V>>>) {
let p = port();
send(out, chan(p));
let is_done = false;
fn get<~V>(p: &port<reduce_proto<V>>, ref_count: &mutable int,
- is_done: &mutable bool) -> option<V> {
+ is_done: &mutable bool) -> option<V> {
while !is_done || ref_count > 0 {
alt recv(p) {
emit_val(v) {
reduce(key, bind get(p, ref_count, is_done));
}
- fn map_reduce<~K1, ~K2, ~V>(map : mapper<K1,K2,V>,
- reduce : reducer<K2, V>,
- inputs: &[K1]) {
+ fn map_reduce<~K1, ~K2,
+ ~V>(map: mapper<K1, K2, V>, reduce: reducer<K2, V>,
+ inputs: &[K1]) {
let ctrl = port();
// This task becomes the master control task. It task::_spawns
let p = port();
let r = reduce, kk = k;
tasks +=
- [task::spawn_joinable(bind reduce_task(r,
- kk, chan(p)))];
+ [task::spawn_joinable(bind reduce_task(r, kk,
+ chan(p)))];
c = recv(p);
treemap::insert(reducers, k, c);
}
}
}
- fn finish<~K, ~V>(k : &K, v : &chan<reduce_proto<V>>) {
- send(v, done);
- }
+ fn finish<~K, ~V>(k: &K, v: &chan<reduce_proto<V>>) { send(v, done); }
treemap::traverse(reducers, finish);
for t in tasks { task::join(t); }
}
}
-fn main(argv: [istr]) {
+fn main(argv: [str]) {
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.
let elapsed = stop - start;
elapsed /= 1000000u64;
- log_err ~"MapReduce completed in " +
- u64::str(elapsed) + ~"ms";
+ log_err "MapReduce completed in " + u64::str(elapsed) + "ms";
}
-fn read_word(r: io::reader) -> option<istr> {
- let w = ~"";
+fn read_word(r: io::reader) -> option<str> {
+ let w = "";
while !r.eof() {
let c = r.read_char();
if is_word_char(c) {
w += str::from_char(c);
- } else { if w != ~"" { ret some(w); } }
+ } else { if w != "" { ret some(w); } }
}
ret none;
}
import std::comm::recv;
import std::comm::send;
-fn map(filename: &istr, emit: map_reduce::putter) {
+fn map(filename: &str, emit: map_reduce::putter) {
let f = io::file_reader(filename);
}
}
-fn reduce(word: &istr, get: map_reduce::getter) {
+fn reduce(word: &str, get: map_reduce::getter) {
let count = 0;
export reducer;
export map_reduce;
- type putter = fn(&istr, int);
+ type putter = fn(&str, int);
- type mapper = fn(&istr, putter);
+ type mapper = fn(&str, putter);
type getter = fn() -> option<int>;
- type reducer = fn(&istr, getter);
+ type reducer = fn(&str, getter);
tag ctrl_proto {
- find_reducer(istr, chan<chan<reduce_proto>>);
+ find_reducer(str, chan<chan<reduce_proto>>);
mapper_done;
}
tag reduce_proto { emit_val(int); done; ref; release; }
- fn start_mappers(ctrl: chan<ctrl_proto>, inputs: &[istr])
- -> [joinable_task] {
+ fn start_mappers(ctrl: chan<ctrl_proto>, inputs: &[str]) ->
+ [joinable_task] {
let tasks = [];
- for i: istr in inputs {
+ for i: str in inputs {
tasks += [task::spawn_joinable(bind map_task(ctrl, i))];
}
ret tasks;
}
- fn map_task(ctrl: chan<ctrl_proto>, input: &istr) {
+ fn map_task(ctrl: chan<ctrl_proto>, input: &str) {
// log_err "map_task " + input;
let intermediates = map::new_str_hash();
- fn emit(im: &map::hashmap<istr, chan<reduce_proto>>,
- ctrl: chan<ctrl_proto>, key: &istr, val: int) {
+ fn emit(im: &map::hashmap<str, chan<reduce_proto>>,
+ ctrl: chan<ctrl_proto>, key: &str, val: int) {
let c;
alt im.find(key) {
some(_c) {
map(input, bind emit(intermediates, ctrl, _, _));
- for each kv: @{key: istr, val: chan<reduce_proto>} in
+ for each kv: @{key: str, val: chan<reduce_proto>} in
intermediates.items() {
send(kv.val, release);
}
send(ctrl, mapper_done);
}
- fn reduce_task(key: &istr, out: chan<chan<reduce_proto>>) {
+ fn reduce_task(key: &str, out: chan<chan<reduce_proto>>) {
let p = port();
send(out, chan(p));
reduce(key, bind get(p, ref_count, is_done));
}
- fn map_reduce(inputs: &[istr]) {
+ fn map_reduce(inputs: &[str]) {
let ctrl = port::<ctrl_proto>();
// This task becomes the master control task. It task::_spawns
// to do the rest.
- let reducers: map::hashmap<istr, chan<reduce_proto>>;
+ let reducers: map::hashmap<str, chan<reduce_proto>>;
reducers = map::new_str_hash();
// log_err "creating new reducer for " + k;
let p = port();
tasks +=
- [task::spawn_joinable(
- bind reduce_task(k, chan(p)))];
+ [task::spawn_joinable(bind reduce_task(k, chan(p)))];
c = recv(p);
reducers.insert(k, c);
}
}
}
- for each kv: @{key: istr, val: chan<reduce_proto>} in reducers.items()
+ for each kv: @{key: str, val: chan<reduce_proto>} in reducers.items()
{
send(kv.val, done);
}
}
}
-fn main(argv: [istr]) {
+fn main(argv: [str]) {
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.
let elapsed = stop - start;
elapsed /= 1000000u64;
- log_err ~"MapReduce completed in " + u64::str(elapsed) + ~"ms";
+ log_err "MapReduce completed in " + u64::str(elapsed) + "ms";
}
-fn read_word(r: io::reader) -> option<istr> {
- let w = ~"";
+fn read_word(r: io::reader) -> option<str> {
+ let w = "";
while !r.eof() {
let c = r.read_char();
if is_word_char(c) {
w += str::from_char(c);
- } else { if w != ~"" { ret some(w); } }
+ } else { if w != "" { ret some(w); } }
}
ret none;
}
mod m1 { }
-fn main(args: [istr]) { log m1::a; }
+fn main(args: [str]) { log m1::a; }
mod a { }
}
-fn main(args: [istr]) { log m1::a; }
+fn main(args: [str]) { log m1::a; }
// error-pattern: not all control paths return
fn force(f: &block() -> int) -> int { f() }
-fn main() {
- log_err force({| | });
-}
+fn main() { log_err force({ | | }); }
// error-pattern:malformed #env call
-fn main() { #env[~"one", ~"two"]; }
+fn main() { #env["one", "two"]; }
fn main() {
let a: uint = 4u;
let b: uint = 1u;
- log_err safe_slice(~"kitties", a, b);
+ log_err safe_slice("kitties", a, b);
}
mod zed {
fn bar() { log "bar"; }
}
-fn main(args: [istr]) { bar(); }
+fn main(args: [str]) { bar(); }
mod zed {
fn bar() { log "bar3"; }
}
-fn main(args: [istr]) { bar(); }
+fn main(args: [str]) { bar(); }
// error-pattern: unresolved modulename
import main::bar;
-fn main(args: [istr]) { log "foo"; }
+fn main(args: [str]) { log "foo"; }
import zed::bar;
import bar::zed;
-fn main(args: [istr]) { log "loop"; }
+fn main(args: [str]) { log "loop"; }
// the next statement, since it's not true in the
// prestate.
let d <- a;
- log safe_slice(~"kitties", b, d);
+ log safe_slice("kitties", b, d);
}
use std;
import std::uint;
-fn enum_chars(start:u8, end:u8) : uint::le(start, end) -> [char] {
+fn enum_chars(start: u8, end: u8) : uint::le(start, end) -> [char] {
let i = start;
let r = [];
- while (i <= end) {
- r += [i as char];
- i += (1u as u8);
- }
+ while i <= end { r += [i as char]; i += 1u as u8; }
ret r;
}
-fn main() {
- log (enum_chars('a' as u8, 'z' as u8));
-}
\ No newline at end of file
+fn main() { log enum_chars('a' as u8, 'z' as u8); }
// is not a manifest call
+
}
fn main() {
let a = 'a' as u8, j = 'j' as u8, k = 1u, l = 10u;
// Silly, but necessary
- check u8::le(a, j);
- check uint::le(k, l);
+ check (u8::le(a, j));
+ check (uint::le(k, l));
let chars = enum_chars(a, j);
- let ints = enum_uints(k, l);
+ let ints = enum_uints(k, l);
let ps = zip(chars, ints);
fail "the impossible happened";
-}
\ No newline at end of file
+}
// for running under valgrind
// Flags to pass to the compiler
// Explain what's going on
- {compile_lib_path: istr,
- run_lib_path: istr,
- rustc_path: istr,
- src_base: istr,
- build_base: istr,
- stage_id: istr,
+ {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<istr>,
- runtool: option::t<istr>,
- rustcflags: option::t<istr>,
+ filter: option::t<str>,
+ runtool: option::t<str>,
+ rustcflags: option::t<str>,
verbose: bool};
type cx = {config: config, procsrv: procsrv::handle};
import common::mode;
import util::logv;
-fn main(args: [istr]) {
+fn main(args: [str]) {
let config = parse_config(args);
log_config(config);
run_tests(config);
}
-fn parse_config(args: &[istr]) -> config {
+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);
let match =
alt getopts::getopts(args_, opts) {
getopts::success(m) { m }
- getopts::failure(f) {
- fail getopts::fail_str(f)
- }
+ getopts::failure(f) { fail getopts::fail_str(f) }
};
- ret {compile_lib_path: getopts::opt_str(match, ~"compile-lib-path"),
- run_lib_path: getopts::opt_str(match, ~"run-lib-path"),
- rustc_path: getopts::opt_str(match, ~"rustc-path"),
- src_base: getopts::opt_str(match, ~"src-base"),
- build_base: getopts::opt_str(match, ~"build-base"),
- stage_id: getopts::opt_str(match, ~"stage-id"),
- mode: str_mode(getopts::opt_str(match, ~"mode")),
- run_ignored: getopts::opt_present(match, ~"ignored"),
+ ret {compile_lib_path: getopts::opt_str(match, "compile-lib-path"),
+ run_lib_path: getopts::opt_str(match, "run-lib-path"),
+ rustc_path: getopts::opt_str(match, "rustc-path"),
+ src_base: getopts::opt_str(match, "src-base"),
+ build_base: getopts::opt_str(match, "build-base"),
+ stage_id: getopts::opt_str(match, "stage-id"),
+ mode: str_mode(getopts::opt_str(match, "mode")),
+ run_ignored: getopts::opt_present(match, "ignored"),
filter:
if vec::len(match.free) > 0u {
option::some(match.free[0])
} else { option::none },
- runtool: getopts::opt_maybe_str(match, ~"runtool"),
- rustcflags: getopts::opt_maybe_str(match, ~"rustcflags"),
- verbose: getopts::opt_present(match, ~"verbose")};
+ runtool: getopts::opt_maybe_str(match, "runtool"),
+ rustcflags: getopts::opt_maybe_str(match, "rustcflags"),
+ verbose: getopts::opt_present(match, "verbose")};
}
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["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["\n"]);
}
-fn opt_str(maybestr: option::t<istr>) -> istr {
- alt maybestr {
- option::some(s) { s }
- option::none. { ~"(none)" }
- }
+fn opt_str(maybestr: option::t<str>) -> str {
+ alt maybestr { option::some(s) { s } option::none. { "(none)" } }
}
-fn str_opt(maybestr: &istr) -> option::t<istr> {
- if maybestr != ~"(none)" { option::some(maybestr) } else { option::none }
+fn str_opt(maybestr: &str) -> option::t<str> {
+ if maybestr != "(none)" { option::some(maybestr) } else { option::none }
}
-fn str_mode(s: &istr) -> mode {
+fn str_mode(s: &str) -> mode {
alt s {
- ~"compile-fail" { mode_compile_fail }
- ~"run-fail" { mode_run_fail }
- ~"run-pass" { mode_run_pass }
- ~"pretty" { mode_pretty }
+ "compile-fail" { mode_compile_fail }
+ "run-fail" { mode_run_fail }
+ "run-pass" { mode_run_pass }
+ "pretty" { mode_pretty }
_ { fail "invalid mode" }
}
}
-fn mode_str(mode: mode) -> istr {
+fn mode_str(mode: mode) -> str {
alt mode {
- mode_compile_fail. { ~"compile-fail" }
- mode_run_fail. { ~"run-fail" }
- mode_run_pass. { ~"run-pass" }
- mode_pretty. { ~"pretty" }
+ mode_compile_fail. { "compile-fail" }
+ mode_run_fail. { "run-fail" }
+ mode_run_pass. { "run-pass" }
+ mode_pretty. { "pretty" }
}
}
}
fn test_opts(config: &config) -> test::test_opts {
- {
- filter: alt config.filter {
- option::some(s) { option::some(s) }
- option::none. { option::none }
- },
- run_ignored: config.run_ignored
- }
+ {filter:
+ alt config.filter {
+ option::some(s) { option::some(s) }
+ option::none. { option::none }
+ },
+ run_ignored: config.run_ignored}
}
type tests_and_conv_fn =
log #fmt["making tests from %s", cx.config.src_base];
let configport = port::<[u8]>();
let tests = [];
- for file: istr in fs::list_dir(cx.config.src_base) {
+ for file: str in fs::list_dir(cx.config.src_base) {
let file = file;
log #fmt["inspecting file %s", file];
if is_test(cx.config, file) {
ret {tests: tests, to_task: bind closure_to_task(cx, configport, _)};
}
-fn is_test(config: &config, testfile: &istr) -> bool {
+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;
ret valid;
}
-fn make_test(cx: &cx, testfile: &istr, configport: &port<[u8]>) ->
+fn make_test(cx: &cx, testfile: &str, configport: &port<[u8]>) ->
test::test_desc {
{name: make_test_name(cx.config, testfile),
fn: make_test_closure(testfile, chan(configport)),
ignore: header::is_test_ignored(cx.config, testfile)}
}
-fn make_test_name(config: &config, testfile: &istr) -> istr {
+fn make_test_name(config: &config, testfile: &str) -> str {
#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: &istr, configchan: chan<[u8]>) ->
+fn make_test_closure(testfile: &str, configchan: chan<[u8]>) ->
test::test_fn {
bind send_config(testfile, configchan)
}
-fn send_config(testfile: istr, configchan: chan<[u8]>) {
+fn send_config(testfile: str, configchan: chan<[u8]>) {
send(configchan, str::bytes(testfile));
}
let chan = cx.procsrv.chan;
let testthunk =
- bind run_test_task(compile_lib_path, run_lib_path,
- rustc_path, src_base,
- build_base, stage_id,
- mode,
- run_ignored,
- filter,
- runtool,
- rustcflags,
- verbose,
- chan,
+ bind run_test_task(compile_lib_path, run_lib_path, rustc_path,
+ src_base, build_base, stage_id, mode, run_ignored,
+ filter, runtool, rustcflags, verbose, chan,
testfile);
ret task::spawn_joinable(testthunk);
}
-fn run_test_task(compile_lib_path: -istr, run_lib_path: -istr,
- rustc_path: -istr,
- src_base: -istr, build_base: -istr, stage_id: -istr,
- mode: -istr,
- run_ignored: -bool, opt_filter: -istr, opt_runtool: -istr,
- opt_rustcflags: -istr, verbose: -bool,
+fn run_test_task(compile_lib_path: -str, run_lib_path: -str, rustc_path: -str,
+ src_base: -str, build_base: -str, stage_id: -str, mode: -str,
+ run_ignored: -bool, opt_filter: -str, opt_runtool: -str,
+ opt_rustcflags: -str, verbose: -bool,
procsrv_chan: -procsrv::reqchan, testfile: -[u8]) {
test::configure_test_task();
type test_props = {
// Lines that should be expected, in order, on standard out
- error_patterns: [istr],
+ error_patterns: [str],
// Extra flags to pass to the compiler
- compile_flags: option::t<istr>,
+ compile_flags: option::t<str>,
// If present, the name of a file that this test should match when
// pretty-printed
- pp_exact: option::t<istr>,
+ pp_exact: option::t<str>,
// FIXME: no-valgrind is a temporary directive until all of run-fail
// is valgrind-clean
no_valgrind: bool
};
// Load any test directives embedded in the file
-fn load_props(testfile: &istr) -> test_props {
+fn load_props(testfile: &str) -> test_props {
let error_patterns = [];
let compile_flags = option::none;
let pp_exact = option::none;
let no_valgrind = false;
- for each ln: istr in iter_header(testfile) {
+ for each ln: str in iter_header(testfile) {
alt parse_error_pattern(ln) {
option::some(ep) { error_patterns += [ep]; }
option::none. { }
}
if no_valgrind == false {
- no_valgrind = parse_name_directive(ln, ~"no-valgrind");
+ no_valgrind = parse_name_directive(ln, "no-valgrind");
}
}
ret {
};
}
-fn is_test_ignored(config: &config, testfile: &istr) -> bool {
+fn is_test_ignored(config: &config, testfile: &str) -> bool {
let found = false;
- for each ln: istr in iter_header(testfile) {
+ for each ln: str in iter_header(testfile) {
// FIXME: Can't return or break from iterator
- found = found || parse_name_directive(ln, ~"xfail-test");
+ found = found || parse_name_directive(ln, "xfail-test");
if (config.mode == common::mode_pretty) {
- found = found || parse_name_directive(ln, ~"xfail-pretty");
+ found = found || parse_name_directive(ln, "xfail-pretty");
}
}
ret found;
}
-iter iter_header(testfile: &istr) -> istr {
+iter iter_header(testfile: &str) -> str {
let rdr = io::file_reader(testfile);
while !rdr.eof() {
let ln = rdr.read_line();
// Assume that any directives will be found before the first
// module or function. This doesn't seem to be an optimization
// with a warm page cache. Maybe with a cold one.
- if str::starts_with(ln, ~"fn")
- || str::starts_with(ln, ~"mod") {
+ if str::starts_with(ln, "fn")
+ || str::starts_with(ln, "mod") {
break;
} else { put ln; }
}
}
-fn parse_error_pattern(line: &istr) -> option::t<istr> {
- parse_name_value_directive(line, ~"error-pattern")
+fn parse_error_pattern(line: &str) -> option::t<str> {
+ parse_name_value_directive(line, "error-pattern")
}
-fn parse_compile_flags(line: &istr) -> option::t<istr> {
- parse_name_value_directive(line, ~"compile-flags")
+fn parse_compile_flags(line: &str) -> option::t<str> {
+ parse_name_value_directive(line, "compile-flags")
}
-fn parse_pp_exact(line: &istr, testfile: &istr) -> option::t<istr> {
- alt parse_name_value_directive(line, ~"pp-exact") {
+fn parse_pp_exact(line: &str, testfile: &str) -> option::t<str> {
+ alt parse_name_value_directive(line, "pp-exact") {
option::some(s) { option::some(s) }
option::none. {
- if parse_name_directive(line, ~"pp-exact") {
+ if parse_name_directive(line, "pp-exact") {
option::some(fs::basename(testfile))
} else {
option::none
}
}
-fn parse_name_directive(line: &istr, directive: &istr) -> bool {
+fn parse_name_directive(line: &str, directive: &str) -> bool {
str::find(line, directive) >= 0
}
-fn parse_name_value_directive(line: &istr,
- directive: &istr) -> option::t<istr> {
- let keycolon = directive + ~":";
+fn parse_name_value_directive(line: &str,
+ directive: &str) -> option::t<str> {
+ let keycolon = directive + ":";
if str::find(line, keycolon) >= 0 {
let colon = str::find(line, keycolon) as uint;
let value =
type reqchan = chan<request>;
-type handle = {task: option::t<(task::task, port<task::task_notification>)>,
- chan: reqchan};
+type handle =
+ {task: option::t<(task::task, port<task::task_notification>)>,
+ chan: reqchan};
tag request { exec([u8], [u8], [[u8]], chan<response>); stop; }
let setupport = port();
let task =
task::spawn_joinable(bind fn (setupchan: chan<chan<request>>) {
- let reqport = port();
- let reqchan = chan(reqport);
- send(setupchan, reqchan);
- worker(reqport);
- }(chan(setupport)));
+ let reqport = port();
+ let reqchan = chan(reqport);
+ send(setupchan, reqchan);
+ worker(reqport);
+ }(chan(setupport)));
ret {task: option::some(task), chan: recv(setupport)};
}
task::join(option::get(handle.task));
}
-fn run(handle: &handle, lib_path: &istr, prog: &istr, args: &[istr],
- input: &option::t<istr>) -> {status: int, out: istr, err: istr} {
+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,
ret {status: status, out: output, err: errput};
}
-fn writeclose(fd: int, s: &option::t<istr>) {
+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));
writer.write_str(option::get(s));
os::libc::close(fd);
}
-fn readclose(fd: int) -> istr {
+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 buf = ~"";
+ let buf = "";
while !reader.eof() {
let bytes = reader.read_bytes(4096u);
buf += str::unsafe_from_bytes(bytes);
let pipe_out = os::pipe();
let pipe_err = os::pipe();
let spawnproc =
- bind run::spawn_process(execparms.prog,
- execparms.args,
+ 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);
}
}
-fn with_lib_path<@T>(path: &istr, 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();
export_lib_path(option::get(maybe_oldpath));
} else {
// FIXME: This should really be unset but we don't have that yet
- export_lib_path(~"");
+ export_lib_path("");
}
ret res;
}
-fn append_lib_path(path: &istr) {
- export_lib_path(util::make_new_path(path));
-}
+fn append_lib_path(path: &str) { export_lib_path(util::make_new_path(path)); }
-fn export_lib_path(path: &istr) {
- setenv(util::lib_path_env_var(), path);
-}
+fn export_lib_path(path: &str) { setenv(util::lib_path_env_var(), path); }
-fn clone_vecstr(v: &[istr]) -> [[u8]] {
+fn clone_vecstr(v: &[str]) -> [[u8]] {
let r = [];
- for t: istr in vec::slice(v, 0u, vec::len(v)) { r += [str::bytes(t)]; }
+ for t: str in vec::slice(v, 0u, vec::len(v)) { r += [str::bytes(t)]; }
ret r;
}
-fn clone_vecu8str(v: &[[u8]]) -> [istr] {
+fn clone_vecu8str(v: &[[u8]]) -> [str] {
let r = [];
for t in vec::slice(v, 0u, vec::len(v)) {
r += [str::unsafe_from_bytes(t)];
let testfile = str::unsafe_from_bytes(_testfile);
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");
+ io::stdout().write_str("\n\n");
}
log #fmt["running %s", testfile];
let props = load_props(testfile);
}
}
-fn run_cfail_test(cx: &cx, props: &test_props, testfile: &istr) {
+fn run_cfail_test(cx: &cx, props: &test_props, testfile: &str) {
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: &istr) {
+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
// exit code on the command-line (137)?
const valgrind_err: int = 9;
if procres.status == valgrind_err {
- fatal_procres(~"run-fail test isn't valgrind-clean!", procres);
+ fatal_procres("run-fail test isn't valgrind-clean!", procres);
}
check_error_patterns(props, testfile, procres);
}
-fn run_rpass_test(cx: &cx, props: &test_props, testfile: &istr) {
+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);
- if procres.status != 0 { fatal_procres(~"test run failed!", procres); }
+ if procres.status != 0 { fatal_procres("test run failed!", procres); }
}
-fn run_pretty_test(cx: &cx, props: &test_props, testfile: &istr) {
+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"); }
+ logv(cx.config, "testing for exact pretty-printing");
+ } else { logv(cx.config, "testing for converging pretty-printing"); }
let rounds =
alt props.pp_exact { option::some(_) { 1 } option::none. { 2 } };
let procres = print_source(cx, testfile, srcs[round]);
if procres.status != 0 {
- fatal_procres(
- #fmt["pretty-printing failed in round %d", round],
- procres);
+ fatal_procres(#fmt["pretty-printing failed in round %d", round],
+ procres);
}
srcs += [procres.stdout];
if option::is_some(props.pp_exact) {
// Now we have to care about line endings
- let cr = ~"\r";
+ let cr = "\r";
check (str::is_not_empty(cr));
- actual = str::replace(actual, cr, ~"");
- expected = str::replace(expected, cr, ~"");
+ actual = str::replace(actual, cr, "");
+ expected = str::replace(expected, cr, "");
}
compare_source(expected, actual);
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 print_source(cx: &cx, testfile: &istr, src: &istr) -> procres {
+ fn print_source(cx: &cx, testfile: &str, src: &str) -> procres {
compose_and_run(cx, testfile, make_pp_args,
cx.config.compile_lib_path, option::some(src))
}
- fn make_pp_args(config: &config, _testfile: &istr) -> procargs {
+ 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: &istr, actual: &istr) {
+ fn compare_source(expected: &str, actual: &str) {
if expected != actual {
- error(~"pretty-printed source does match expected source");
+ error("pretty-printed source does match expected source");
let msg =
#fmt["\n\
expected:\n\
%s\n\
------------------------------------------\n\
\n",
- expected,
- actual];
+ expected, actual];
io::stdout().write_str(msg);
fail;
}
}
- fn typecheck_source(cx: &cx, testfile: &istr, src: &istr) -> procres {
+ fn typecheck_source(cx: &cx, testfile: &str, src: &str) -> procres {
compose_and_run(cx, testfile, make_typecheck_args,
cx.config.compile_lib_path, option::some(src))
}
- fn make_typecheck_args(config: &config, _testfile: &istr) -> procargs {
+ 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};
}
}
-fn check_error_patterns(props: &test_props, testfile: &istr,
+fn check_error_patterns(props: &test_props, testfile: &str,
procres: &procres) {
if vec::is_empty(props.error_patterns) {
- fatal(~"no error pattern specified in " + testfile);
+ fatal("no error pattern specified in " + testfile);
}
if procres.status == 0 {
- fatal(~"process did not return an error status");
+ fatal("process did not return an error status");
}
let next_err_idx = 0u;
let next_err_pat = props.error_patterns[next_err_idx];
- for line: istr in str::split(procres.stdout, '\n' as u8) {
+ 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";
vec::slice(props.error_patterns, next_err_idx,
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: istr in missing_patterns {
- error(#fmt["error pattern '%s' not found!",
- pattern]);
+ for pattern: str in missing_patterns {
+ error(#fmt["error pattern '%s' not found!", pattern]);
}
- fatal_procres(~"multiple error patterns not found", procres);
+ fatal_procres("multiple error patterns not found", procres);
}
}
-type procargs = {prog: istr, args: [istr]};
+type procargs = {prog: str, args: [str]};
-type procres = {status: int, stdout: istr, stderr: istr, cmdline: istr};
+type procres = {status: int, stdout: str, stderr: str, cmdline: str};
-fn compile_test(cx: &cx, props: &test_props, testfile: &istr) -> procres {
+fn compile_test(cx: &cx, props: &test_props, testfile: &str) -> procres {
compose_and_run(cx, testfile, bind make_compile_args(_, props, _),
cx.config.compile_lib_path, option::none)
}
-fn exec_compiled_test(cx: &cx, props: &test_props, testfile: &istr) ->
+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: &istr,
- make_args: fn(&config, &istr) -> procargs,
- lib_path: &istr,
- input: option::t<istr>) -> procres {
+fn compose_and_run(cx: &cx, testfile: &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,
input);
}
-fn make_compile_args(config: &config, props: &test_props, testfile: &istr) ->
+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 rustcflags = alt config.rustcflags {
- option::some(s) { option::some(s) }
- option::none. { option::none }
- };
+ let args = [testfile, "-o", make_exe_name(config, testfile)];
+ let rustcflags =
+ alt config.rustcflags {
+ option::some(s) { option::some(s) }
+ option::none. { option::none }
+ };
args += split_maybe_args(rustcflags);
args += split_maybe_args(props.compile_flags);
ret {prog: prog, args: args};
}
-fn make_exe_name(config: &config, testfile: &istr) -> istr {
+fn make_exe_name(config: &config, testfile: &str) -> str {
output_base_name(config, testfile) + os::exec_suffix()
}
-fn make_run_args(config: &config, props: &test_props, testfile: &istr) ->
+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
- let runtool = alt config.runtool {
- option::some(s) { option::some(s) }
- option::none. { option::none }
- };
- split_maybe_args(runtool)
- } else { [] };
+ let toolargs =
+ if !props.no_valgrind {
+ // If we've got another tool to run under (valgrind),
+ // then split apart its command
+ let runtool =
+ alt config.runtool {
+ option::some(s) { option::some(s) }
+ option::none. { option::none }
+ };
+ split_maybe_args(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<istr>) -> [istr] {
- fn rm_whitespace(v: &[istr]) -> [istr] {
- fn flt(s: &istr) -> option::t<istr> {
+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 }
}
// FIXME: This should be in std
- fn is_whitespace(s: &istr) -> bool {
+ fn is_whitespace(s: &str) -> bool {
for c: u8 in s { if c != ' ' as u8 { ret false; } }
ret true;
}
}
}
-fn program_output(cx: &cx, testfile: &istr, lib_path: &istr, prog: &istr,
- args: &[istr], input: option::t<istr>) -> procres {
+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]);
+ logv(cx.config, #fmt["executing %s", cmdline]);
cmdline
};
let res = procsrv::run(cx.procsrv, lib_path, prog, args, input);
cmdline: cmdline};
}
-fn make_cmdline(libpath: &istr, prog: &istr, args: &[istr]) -> istr {
- #fmt["%s %s %s",
- lib_path_cmd_prefix(libpath),
- prog,
- str::connect(args, ~" ")]
+fn make_cmdline(libpath: &str, prog: &str, args: &[str]) -> str {
+ #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: &istr) -> istr {
- #fmt["%s=\"%s\"",
- util::lib_path_env_var(),
- util::make_new_path(path)]
+fn lib_path_cmd_prefix(path: &str) -> str {
+ #fmt["%s=\"%s\"", util::lib_path_env_var(), util::make_new_path(path)]
}
-fn dump_output(config: &config, testfile: &istr, out: &istr, err: &istr) {
- dump_output_file(config, testfile, out, ~"out");
- dump_output_file(config, testfile, err, ~"err");
+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: &istr, out: &istr,
- extension: &istr) {
+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: &istr, out: &istr,
- extension: &istr) {
+fn dump_output_file(config: &config, testfile: &str, out: &str,
+ extension: &str) {
}
-fn make_out_name(config: &config, testfile: &istr,
- extension: &istr) -> istr {
- output_base_name(config, testfile) + ~"." + extension
+fn make_out_name(config: &config, testfile: &str, extension: &str) -> str {
+ output_base_name(config, testfile) + "." + extension
}
-fn output_base_name(config: &config, testfile: &istr) -> istr {
+fn output_base_name(config: &config, testfile: &str) -> str {
let base = config.build_base;
let filename =
{
- let parts = str::split(fs::basename(testfile),
- '.' as u8);
+ let parts = str::split(fs::basename(testfile), '.' as u8);
parts = vec::slice(parts, 0u, vec::len(parts) - 1u);
- str::connect(parts, ~".")
+ 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: &istr, err: &istr) {
+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 sep3 = ~"------------------------------------------";
+ let sep1 = #fmt["------%s------------------------------", "stdout"];
+ let sep2 = #fmt["------%s------------------------------", "stderr"];
+ let sep3 = "------------------------------------------";
io::stdout().write_line(sep1);
io::stdout().write_line(out);
io::stdout().write_line(sep2);
}
}
-fn error(err: &istr) {
- io::stdout().write_line(#fmt["\nerror: %s", err]);
-}
+fn error(err: &str) { io::stdout().write_line(#fmt["\nerror: %s", err]); }
-fn fatal(err: &istr) -> ! { error(err); fail; }
+fn fatal(err: &str) -> ! { error(err); fail; }
-fn fatal_procres(err: &istr, procres: procres) -> ! {
+fn fatal_procres(err: &str, procres: procres) -> ! {
let msg =
#fmt["\n\
error: %s\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;
}
import common::config;
-fn make_new_path(path: &istr) -> istr {
+fn make_new_path(path: &str) -> str {
// 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 }
}
}
#[cfg(target_os = "linux")]
-fn lib_path_env_var() -> istr { ~"LD_LIBRARY_PATH" }
+fn lib_path_env_var() -> str { "LD_LIBRARY_PATH" }
#[cfg(target_os = "macos")]
-fn lib_path_env_var() -> istr { ~"DYLD_LIBRARY_PATH" }
+fn lib_path_env_var() -> str { "DYLD_LIBRARY_PATH" }
#[cfg(target_os = "win32")]
-fn lib_path_env_var() -> istr { ~"PATH" }
+fn lib_path_env_var() -> str { "PATH" }
-fn logv(config: &config, s: &istr) {
+fn logv(config: &config, s: &str) {
log s;
- if config.verbose {
- io::stdout().write_line(s);
- }
+ if config.verbose { io::stdout().write_line(s); }
}
// error-pattern:wooooo
// no-valgrind
-fn main() { let a = 1; if 1 == 1 { a = 2; } fail ~"woooo" + ~"o"; }
+fn main() { let a = 1; if 1 == 1 { a = 2; } fail "woooo" + "o"; }
// no-valgrind
use std;
-fn main() { let str_var: istr = ~"meh"; fail #fmt["%s", str_var]; }
+fn main() { let str_var: str = "meh"; fail #fmt["%s", str_var]; }
let a: uint = 4u;
let b: uint = 1u;
check (le(a, b));
- log_err safe_slice(~"kitties", a, b);
+ log_err safe_slice("kitties", a, b);
}
fn main() {
let a = 'a' as u8, j = 'j' as u8, k = 1u, l = 9u;
// Silly, but necessary
- check u8::le(a, j);
- check uint::le(k, l);
+ check (u8::le(a, j));
+ check (uint::le(k, l));
let chars = enum_chars(a, j);
- let ints = enum_uints(k, l);
+ let ints = enum_uints(k, l);
- check same_length(chars, ints);
+ check (same_length(chars, ints));
let ps = zip(chars, ints);
fail "the impossible happened";
-}
\ No newline at end of file
+}
// Issue #53
fn main() {
- alt ~"test" {
- ~"not-test" { fail; }
- ~"test" { }
- _ { fail; }
- }
+ alt "test" { "not-test" { fail; } "test" { } _ { fail; } }
- tag t { tag1(istr); tag2; }
+ tag t { tag1(str); tag2; }
- alt tag1(~"test") {
+ alt tag1("test") {
tag2. { fail; }
- tag1(~"not-test") { fail; }
- tag1(~"test") { }
+ tag1("not-test") { fail; }
+ tag1("test") { }
_ { fail; }
}
- let x = alt ~"a" {
- ~"a" { 1 }
- ~"b" { 2 }
- };
- assert x == 1;
+ let x = alt "a" { "a" { 1 } "b" { 2 } };
+ assert (x == 1);
- alt ~"a" {
- ~"a" { }
- ~"b" { }
- }
+ alt "a" { "a" { } "b" { } }
}
-fn main(args: [istr]) {
- let vs: [istr] = [~"hi", ~"there", ~"this", ~"is", ~"a", ~"vec"];
- let vvs: [[istr]] = [args, vs];
- for vs: [istr] in vvs { for s: istr in vs { log s; } }
+fn main(args: [str]) {
+ 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 g(i: int, j: int) : p(j) -> int { f(i, j) }
-fn main() {
- let x = 1;
- check p(x);
- log g(x, x);
-}
\ No newline at end of file
+fn main() { let x = 1; check (p(x)); log g(x, x); }
use std;
import std::option::*;
-pure fn p(x:int) -> bool { true }
+pure fn p(x: int) -> bool { true }
-fn f(x:int) : p(x) { }
+fn f(x: int) : p(x) { }
fn main() {
- alt some(5) {
- some(y) {
- check p(y);
- f(y);
- }
- _ { fail "yuck"; }
- }
+ alt some(5) { some(y) { check (p(y)); f(y); } _ { fail "yuck"; } }
}
use std;
import std::task;
-fn child2(s: -istr) { }
+fn child2(s: -str) { }
-fn main() { let x = task::spawn(bind child2(~"hi")); }
+fn main() { let x = task::spawn(bind child2("hi")); }
-fn main(args: [istr]) { log args[0]; }
+fn main(args: [str]) { log args[0]; }
let c: uint = 17u;
check (le(a, b));
c <- a;
- log safe_slice(~"kitties", c, b);
+ log safe_slice("kitties", c, b);
}
let b: uint = 4u;
check (le(a, b));
let c <- a;
- log safe_slice(~"kitties", c, b);
+ log safe_slice("kitties", c, b);
}
let b: uint = 1u;
check (le(b, a));
b <-> a;
- log safe_slice(~"kitties", a, b);
+ log safe_slice("kitties", a, b);
}
let b: uint = 4u;
check (le(a, b));
let c = b;
- log safe_slice(~"kitties", a, c);
+ log safe_slice("kitties", a, c);
}
let a: uint = 1u;
let b: uint = 4u;
check (le(a, b));
- log safe_slice(~"kitties", a, b);
+ log safe_slice("kitties", a, b);
}
fn main() {
- let a = alt 10 {
- x when x < 7 { 1 }
- x when x < 11 { 2 }
- 10 { 3 }
- _ { 4 }
- };
- assert a == 2;
+ let a =
+ alt 10 { x when x < 7 { 1 } x when x < 11 { 2 } 10 { 3 } _ { 4 } };
+ assert (a == 2);
- let b = alt {x: 10, y: 20} {
- x when x.x < 5 && x.y < 5 { 1 }
- {x, y} when x == 10 && y == 20 { 2 }
- {x, y} { 3 }
- };
- assert b == 2;
+ let b =
+ alt {x: 10, y: 20} {
+ x when x.x < 5 && x.y < 5 { 1 }
+ {x: x, y: y} when x == 10 && y == 20 { 2 }
+ {x: x, y: y} { 3 }
+ };
+ assert (b == 2);
}
import std::comm::recv;
import std::comm;
-fn map(filename: &istr, emit: map_reduce::putter) { emit(filename, ~"1"); }
+fn map(filename: &str, emit: map_reduce::putter) { emit(filename, "1"); }
mod map_reduce {
export putter;
export mapper;
export map_reduce;
- type putter = fn(&istr, &istr);
+ type putter = fn(&str, &str);
- type mapper = fn(&istr, putter);
+ type mapper = fn(&str, putter);
tag ctrl_proto { find_reducer([u8], chan<int>); mapper_done; }
- fn start_mappers(ctrl: chan<ctrl_proto>, inputs: &[istr]) {
- for i: istr in inputs {
- task::spawn(bind map_task(ctrl, i));
- }
+ fn start_mappers(ctrl: chan<ctrl_proto>, inputs: &[str]) {
+ for i: str in inputs { task::spawn(bind map_task(ctrl, i)); }
}
- fn map_task(ctrl: chan<ctrl_proto>, input: -istr) {
+ fn map_task(ctrl: chan<ctrl_proto>, input: -str) {
let intermediates = map::new_str_hash();
- fn emit(im: &map::hashmap<istr, int>, ctrl: chan<ctrl_proto>,
- key: &istr, val: &istr) {
+ fn emit(im: &map::hashmap<str, int>, ctrl: chan<ctrl_proto>,
+ key: &str, val: &str) {
let c;
alt im.find(key) {
some(_c) { c = _c }
send(ctrl, mapper_done);
}
- fn map_reduce(inputs: &[istr]) {
+ fn map_reduce(inputs: &[str]) {
let ctrl = port();
// This task becomes the master control task. It spawns others
// to do the rest.
- let reducers: map::hashmap<istr, int>;
+ let reducers: map::hashmap<str, int>;
reducers = map::new_str_hash();
}
fn main() {
- map_reduce::map_reduce([~"../src/test/run-pass/hashmap-memory.rs"]);
+ map_reduce::map_reduce(["../src/test/run-pass/hashmap-memory.rs"]);
}
fn bar() { log "bar"; }
}
-fn main(args: [istr]) { let zed = 42; bar(); }
+fn main(args: [str]) { let zed = 42; bar(); }
}
}
-fn main(args: [istr]) { bar(); }
+fn main(args: [str]) { bar(); }
mod zed { }
}
}
-fn main(args: [istr]) { baz(); }
+fn main(args: [str]) { baz(); }
fn main() {
let p: port<msg> = port();
let recv_reader: port<chan<[u8]>> = port();
- let pack =
- task::spawn(bind packager(chan(recv_reader), chan(p)));
+ let pack = task::spawn(bind packager(chan(recv_reader), chan(p)));
let source_chan: chan<[u8]> = recv(recv_reader);
let prod = task::spawn(bind producer(source_chan));
fn test_stack_assign() {
- let s: istr = ~"a";
+ let s: str = "a";
log s;
- let t: istr = ~"a";
- assert s == t;
- let u: istr = ~"b";
- assert s != u;
+ let t: str = "a";
+ assert (s == t);
+ let u: str = "b";
+ assert (s != u);
}
-fn test_heap_lit() {
- ~"a big string";
-}
+fn test_heap_lit() { "a big string"; }
fn test_heap_assign() {
- let s: istr = ~"a big ol' string";
- let t: istr = ~"a big ol' string";
- assert s == t;
- let u: istr = ~"a bad ol' string";
- assert s != u;
+ let s: str = "a big ol' string";
+ let t: str = "a big ol' string";
+ assert (s == t);
+ let u: str = "a bad ol' string";
+ assert (s != u);
}
-fn test_heap_log() {
- let s = ~"a big ol' string";
- log s;
-}
+fn test_heap_log() { let s = "a big ol' string"; log s; }
fn test_stack_add() {
- assert ~"a" + ~"b" == ~"ab";
- let s: istr = ~"a";
- assert s + s == ~"aa";
- assert ~"" + ~"" == ~"";
+ assert ("a" + "b" == "ab");
+ let s: str = "a";
+ assert (s + s == "aa");
+ assert ("" + "" == "");
}
-fn test_stack_heap_add() {
- assert ~"a" + ~"bracadabra" == ~"abracadabra";
-}
+fn test_stack_heap_add() { assert ("a" + "bracadabra" == "abracadabra"); }
fn test_heap_add() {
- assert ~"this should" + ~" totally work" == ~"this should totally work";
+ assert ("this should" + " totally work" == "this should totally work");
}
fn test_append() {
- let s = ~"";
- s += ~"a";
- assert s == ~"a";
+ let s = "";
+ s += "a";
+ assert (s == "a");
- let s = ~"a";
- s += ~"b";
+ let s = "a";
+ s += "b";
log s;
- assert s == ~"ab";
+ assert (s == "ab");
- let s = ~"c";
- s += ~"offee";
- assert s == ~"coffee";
+ let s = "c";
+ s += "offee";
+ assert (s == "coffee");
- s += ~"&tea";
- assert s == ~"coffee&tea";
+ s += "&tea";
+ assert (s == "coffee&tea");
}
fn main() {
test_stack_heap_add();
test_heap_add();
test_append();
-}
\ No newline at end of file
+}
use std;
fn f() {
- #fmt["test%s", ~"s"];
+ #fmt["test%s", "s"];
#[attr = "val"]
fn g() { }
}
fn f() -> bool { for each i: int in x() { ret true; } ret false; }
-fn main(args: [istr]) { f(); }
+fn main(args: [str]) { f(); }
-fn main(args: [istr]) {
- for s in args { log s }
-}
+fn main(args: [str]) { for s in args { log s } }
native "cdecl" mod baz = "" { }
-fn main(args: [istr]) { }
+fn main(args: [str]) { }
import std::list::*;
pure fn pure_length_go<@T>(ls: &list<T>, acc: uint) -> uint {
- alt ls {
- nil. { acc }
- cons(_, tl) { pure_length_go(*tl, acc + 1u) }
- }
+ alt ls { nil. { acc } cons(_, tl) { pure_length_go(*tl, acc + 1u) } }
}
-pure fn pure_length<@T>(ls: &list<T>) -> uint {
- pure_length_go(ls, 0u)
-}
+pure fn pure_length<@T>(ls: &list<T>) -> uint { pure_length_go(ls, 0u) }
-pure fn nonempty_list<@T>(ls: &list<T>) -> bool {
- pure_length(ls) > 0u
-}
+pure fn nonempty_list<@T>(ls: &list<T>) -> bool { pure_length(ls) > 0u }
- // Of course, the compiler can't take advantage of the
- // knowledge that ls is a cons node. Future work.
- // Also, this is pretty contrived since nonempty_list
- // could be a "tag refinement", if we implement those.
+// Of course, the compiler can't take advantage of the
+// knowledge that ls is a cons node. Future work.
+// Also, this is pretty contrived since nonempty_list
+// could be a "tag refinement", if we implement those.
fn safe_head<@T>(ls: &list<T>) : nonempty_list(ls) -> T { car(ls) }
fn main() {
let mylist = cons(@1u, @nil);
// Again, a way to eliminate such "obvious" checks seems
// desirable. (Tags could have postconditions.)
- check(nonempty_list(mylist));
- assert (*(safe_head(mylist)) == 1u);
-}
\ No newline at end of file
+ check (nonempty_list(mylist));
+ assert (*safe_head(mylist) == 1u);
+}
fn bar(offset: uint) { }
}
-fn main(args: [istr]) { foo::bar(0u); }
+fn main(args: [str]) { foo::bar(0u); }
fn main() {
let cx: sio::ctx = sio::new();
let srv: sio::server = sio::create_server(
- cx, net::parse_addr(~"0.0.0.0"), 9090);
+ cx, net::parse_addr("0.0.0.0"), 9090);
let child = task::_spawn(bind connectTask(cx,
- net::parse_addr(~"127.0.0.1"),
+ net::parse_addr("127.0.0.1"),
9090));
let client: sio::client = sio::accept_from(srv);
task::join_id(child);
fn main() {
let cx: sio::ctx = sio::new();
let srv: sio::server = sio::create_server(
- cx, net::parse_addr(~"0.0.0.0"), 9090);
+ cx, net::parse_addr("0.0.0.0"), 9090);
let child = task::_spawn(bind connectTask(cx,
- net::parse_addr(~"127.0.0.1"),
+ net::parse_addr("127.0.0.1"),
9090));
let client: sio::client = sio::accept_from(srv);
sio::write_data(client, str::bytes("hello, world\n"));
fn main() {
let cx: sio::ctx = sio::new();
let srv: sio::server = sio::create_server(cx,
- net::parse_addr(~"127.0.0.1"),
+ net::parse_addr("127.0.0.1"),
9090);
sio::close_server(srv);
sio::destroy(cx);
fn main() {
let cx: sio::ctx = sio::new();
- let srv: sio::server = sio::create_server(cx, net::parse_addr(~"0.0.0.0"),
+ let srv: sio::server = sio::create_server(cx, net::parse_addr("0.0.0.0"),
9090);
- let child = task::_spawn(bind connectTask(cx, net::parse_addr(~"127.0.0.1"),
+ let child = task::_spawn(bind connectTask(cx, net::parse_addr("127.0.0.1"),
9090));
let client: sio::client = sio::accept_from(srv);
sio::write_data(client, str::bytes("hello, world\n"));
import std::task::yield;
import std::task;
-fn x(s: -istr, n: int) { log s; log n; }
+fn x(s: -str, n: int) { log s; log n; }
fn main() {
- task::spawn(bind x(~"hello from first spawned fn", 65));
- task::spawn(bind x(~"hello from second spawned fn", 66));
- task::spawn(bind x(~"hello from third spawned fn", 67));
+ task::spawn(bind x("hello from first spawned fn", 65));
+ task::spawn(bind x("hello from second spawned fn", 66));
+ task::spawn(bind x("hello from third spawned fn", 67));
let i: int = 30;
while i > 0 { i = i - 1; log "parent sleeping"; yield(); }
}
import std::task::join;
import std::task::spawn_joinable;
-fn main() {
- let x = spawn_joinable(bind m::child(10));
- join(x);
-}
+fn main() { let x = spawn_joinable(bind m::child(10)); join(x); }
mod m {
fn child(i: int) { log i; }
type ctx = comm::chan<int>;
-fn iotask(cx: ctx, ip: -istr) { assert (str::eq(ip, ~"localhost")); }
+fn iotask(cx: ctx, ip: -str) { assert (str::eq(ip, "localhost")); }
fn main() {
let p = comm::port::<int>();
- task::spawn(bind iotask(comm::chan(p), ~"localhost"));
+ task::spawn(bind iotask(comm::chan(p), "localhost"));
}
import std::task;
-fn main() {
- let t = task::spawn_joinable(bind child(10));
- task::join(t);
-}
+fn main() { let t = task::spawn_joinable(bind child(10)); task::join(t); }
fn child(i: int) { log_err i; assert (i == 10); }
import std::str;
fn test1() {
- let s: istr = ~"hello";
- s += ~"world";
+ let s: str = "hello";
+ s += "world";
log s;
assert (s[9] == 'd' as u8);
}
fn test2() {
// This tests for issue #163
- let ff: istr = ~"abc";
- let a: istr = ff + ~"ABC" + ff;
- let b: istr = ~"ABC" + ff + ~"ABC";
+ let ff: str = "abc";
+ let a: str = ff + "ABC" + ff;
+ let b: str = "ABC" + ff + "ABC";
log a;
log b;
- assert (str::eq(a, ~"abcABCabc"));
- assert (str::eq(b, ~"ABCabcABC"));
+ assert (str::eq(a, "abcABCabc"));
+ assert (str::eq(b, "ABCabcABC"));
}
fn main() { test1(); test2(); }
import std::str;
fn main() {
- let a: istr = ~"this \
+ let a: str = "this \
is a test";
- let b: istr =
- ~"this \
+ let b: str =
+ "this \
is \
another \
test";
- assert (str::eq(a, ~"this is a test"));
- assert (str::eq(b, ~"this is another test"));
+ assert (str::eq(a, "this is a test"));
+ assert (str::eq(b, "this is another test"));
}
fn main() {
// Make sure we properly handle repeated self-appends.
- let a: istr = ~"A";
+ let a: str = "A";
let i = 20;
let expected_len = 1u;
while i > 0 {
use std;
import std::str;
-fn test(actual: &istr, expected: &istr) {
+fn test(actual: &str, expected: &str) {
log actual;
log expected;
assert (str::eq(actual, expected));
}
fn main() {
- test(#fmt[~"hello %d friends and %s things", 10, ~"formatted"],
- ~"hello 10 friends and formatted things");
+ 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 ");
+ 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 baz() { zed(nil); }
}
-fn main(args: [istr]) { }
+fn main(args: [str]) { }
// -*- rust -*-
tag colour { red(int, int); green; }
-fn f() {
- let x = red(1, 2);
- let y = green;
- assert (x != y);
-}
+fn f() { let x = red(1, 2); let y = green; assert (x != y); }
fn main() { f(); }
use std;
import std::task;
-fn main() { task::spawn(bind child(~"Hello")); }
+fn main() { task::spawn(bind child("Hello")); }
fn child(s: -str) {
use std;
-fn test_break() {
- while true {
- let x: @int = break;
- }
-}
+fn test_break() { while true { let x: @int = break; } }
-fn test_cont() {
- let i = 0;
- while i < 1 {
- i += 1;
- let x: @int = cont;
- }
-}
+fn test_cont() { let i = 0; while i < 1 { i += 1; let x: @int = cont; } }
-fn test_ret() {
- let x: @int = ret;
-}
+fn test_ret() { let x: @int = ret; }
fn test_fail() {
- fn f() {
- std::task::unsupervise();
- let x: @int = fail;
- }
+ fn f() { std::task::unsupervise(); let x: @int = fail; }
let g = f;
std::task::spawn(g);
}
fn test_fail_indirect() {
- fn f() -> ! {
- fail;
- }
- fn g() {
- std::task::unsupervise();
- let x: @int = f();
- }
+ fn f() -> ! { fail; }
+ fn g() { std::task::unsupervise(); let x: @int = f(); }
let h = g;
std::task::spawn(h);
}
test_ret();
test_fail();
test_fail_indirect();
-}
\ No newline at end of file
+}
type lteq<T> = fn(&T) -> bool;
-fn main(args: [istr]) { }
+fn main(args: [str]) { }
fn g(a: *int) -> *int { let b = f(a); ret b; }
-fn main(args: [istr]) { ret; }
+fn main(args: [str]) { ret; }
// Can't easily be written as a "pure fn" because there's
// no syntax for specifying that f is pure.
fn pure_foldl<@T, @U>(ls: &list<T>, u: &U, f: &block(&T, &U) -> U) -> U {
- alt ls {
- nil. { u }
- cons(hd, tl) { f(hd, pure_foldl(*tl, f(hd, u), f)) }
- }
+ alt ls { nil. { u } cons(hd, tl) { f(hd, pure_foldl(*tl, f(hd, u), f)) } }
}
// Shows how to use an "unchecked" block to call a general
// fn from a pure fn
pure fn pure_length<@T>(ls: &list<T>) -> uint {
fn count<T>(_t: &T, u: &uint) -> uint { u + 1u }
- unchecked {
- pure_foldl(ls, 0u, count)
- }
+ unchecked{ pure_foldl(ls, 0u, count) }
}
-pure fn nonempty_list<@T>(ls: &list<T>) -> bool {
- pure_length(ls) > 0u
-}
+pure fn nonempty_list<@T>(ls: &list<T>) -> bool { pure_length(ls) > 0u }
- // Of course, the compiler can't take advantage of the
- // knowledge that ls is a cons node. Future work.
- // Also, this is pretty contrived since nonempty_list
- // could be a "tag refinement", if we implement those.
+// Of course, the compiler can't take advantage of the
+// knowledge that ls is a cons node. Future work.
+// Also, this is pretty contrived since nonempty_list
+// could be a "tag refinement", if we implement those.
fn safe_head<@T>(ls: &list<T>) : nonempty_list(ls) -> T { car(ls) }
fn main() {
let mylist = cons(@1u, @nil);
// Again, a way to eliminate such "obvious" checks seems
// desirable. (Tags could have postconditions.)
- check(nonempty_list(mylist));
- assert (*(safe_head(mylist)) == 1u);
-}
\ No newline at end of file
+ check (nonempty_list(mylist));
+ assert (*safe_head(mylist) == 1u);
+}
fn main() {
// Chars of 1, 2, 3, and 4 bytes
let chs: [char] = ['e', 'é', '€', 0x10000 as char];
- let s: istr = str::from_chars(chs);
+ let s: str = str::from_chars(chs);
assert (str::byte_len(s) == 10u);
assert (str::char_len(s) == 4u);
assert (!str::is_utf8([0xc0_u8]));
assert (!str::is_utf8([0xc0_u8, 0x10_u8]));
- let stack = ~"a×c€";
+ let stack = "a×c€";
assert (str::pop_char(stack) == '€');
assert (str::pop_char(stack) == 'c');
str::push_char(stack, 'u');
- assert (str::eq(stack, ~"a×u"));
+ assert (str::eq(stack, "a×u"));
assert (str::shift_char(stack) == 'a');
assert (str::shift_char(stack) == '×');
str::unshift_char(stack, 'ß');
- assert (str::eq(stack, ~"ßu"));
+ assert (str::eq(stack, "ßu"));
}
// a spills onto the heap
let a = [0, 1, 2, 3, 4];
a += a;
- assert vec::len(a) == 10u;
- assert a[0] == 0;
- assert a[1] == 1;
- assert a[2] == 2;
- assert a[3] == 3;
- assert a[4] == 4;
- assert a[5] == 0;
- assert a[6] == 1;
- assert a[7] == 2;
- assert a[8] == 3;
- assert a[9] == 4;
+ assert (vec::len(a) == 10u);
+ assert (a[0] == 0);
+ assert (a[1] == 1);
+ assert (a[2] == 2);
+ assert (a[3] == 3);
+ assert (a[4] == 4);
+ assert (a[5] == 0);
+ assert (a[6] == 1);
+ assert (a[7] == 2);
+ assert (a[8] == 3);
+ assert (a[9] == 4);
}
fn test_stack_to_heap() {
let a = [0, 1, 2];
// a spills to the heap
a += a;
- assert vec::len(a) == 6u;
- assert a[0] == 0;
- assert a[1] == 1;
- assert a[2] == 2;
- assert a[3] == 0;
- assert a[4] == 1;
- assert a[5] == 2;
+ assert (vec::len(a) == 6u);
+ assert (a[0] == 0);
+ assert (a[1] == 1);
+ assert (a[2] == 2);
+ assert (a[3] == 0);
+ assert (a[4] == 1);
+ assert (a[5] == 2);
}
fn test_loop() {
}
}
-fn main() {
- test_heap_to_heap();
- test_stack_to_heap();
- test_loop();
-}
+fn main() { test_heap_to_heap(); test_stack_to_heap(); test_loop(); }
// Issue #825: Should recheck the loop contition after continuing
-fn main() {
- let i = 1;
- while i > 0 {
- assert i > 0;
- log i;
- i -= 1;
- cont;
- }
-}
\ No newline at end of file
+fn main() { let i = 1; while i > 0 { assert (i > 0); log i; i -= 1; cont; } }
fn main() {
let a = 'a' as u8, j = 'j' as u8, k = 1u, l = 10u;
// Silly, but necessary
- check u8::le(a, j);
- check uint::le(k, l);
+ check (u8::le(a, j));
+ check (uint::le(k, l));
let chars = enum_chars(a, j);
- let ints = enum_uints(k, l);
+ let ints = enum_uints(k, l);
- check same_length(chars, ints);
+ check (same_length(chars, ints));
let ps = zip(chars, ints);
- check is_not_empty(ps);
+ check (is_not_empty(ps));
assert (head(ps) == ('a', 1u));
assert (last_total(ps) == (j as char, 10u));
}
import std::comm;
#[test]
-fn create_port_and_chan() {
- let p = comm::port::<int>();
- comm::chan(p);
-}
+fn create_port_and_chan() { let p = comm::port::<int>(); comm::chan(p); }
#[test]
fn send_recv_fn() {
#[test]
fn test_connect() {
let slash = fs::path_sep();
- log_err fs::connect(~"a", ~"b");
- assert (fs::connect(~"a", ~"b") == ~"a" + slash + ~"b");
- assert (fs::connect(~"a" + slash, ~"b") == ~"a" + slash + ~"b");
+ log_err fs::connect("a", "b");
+ assert (fs::connect("a", "b") == "a" + slash + "b");
+ assert (fs::connect("a" + slash, "b") == "a" + slash + "b");
}
// Issue #712
#[test]
-fn test_list_dir_no_invalid_memory_access() { fs::list_dir(~"."); }
+fn test_list_dir_no_invalid_memory_access() { fs::list_dir("."); }
#[test]
fn list_dir() {
- let dirs = fs::list_dir(~".");
+ let dirs = fs::list_dir(".");
// Just assuming that we've got some contents in the current directory
- assert std::vec::len(dirs) > 0u;
+ assert (std::vec::len(dirs) > 0u);
- for dir in dirs {
- log dir;
- }
+ for dir in dirs { log dir; }
}
#[test]
fn file_is_dir() {
- assert fs::file_is_dir(~".");
- assert !fs::file_is_dir(~"test/stdtest/fs.rs");
-}
\ No newline at end of file
+ assert (fs::file_is_dir("."));
+ assert (!fs::file_is_dir("test/stdtest/fs.rs"));
+}
// 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) {
- assert (opt::opt_present(m, ~"test"));
- assert (opt::opt_str(m, ~"test") == ~"20");
+ assert (opt::opt_present(m, "test"));
+ assert (opt::opt_str(m, "test") == "20");
}
_ { fail; }
}
#[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) {
- assert (opt::opt_present(m, ~"t"));
- assert (opt::opt_str(m, ~"t") == ~"20");
+ assert (opt::opt_present(m, "t"));
+ assert (opt::opt_str(m, "t") == "20");
}
_ { fail; }
}
#[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) {
- assert (opt::opt_present(m, ~"test"));
- assert (opt::opt_str(m, ~"test") == ~"20");
+ assert (opt::opt_present(m, "test"));
+ assert (opt::opt_str(m, "test") == "20");
}
_ { fail; }
}
#[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")); }
+ opt::success(m) { assert (!opt::opt_present(m, "test")); }
_ { fail; }
}
}
#[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) {
- assert (opt::opt_present(m, ~"t"));
- assert (opt::opt_str(m, ~"t") == ~"20");
+ assert (opt::opt_present(m, "t"));
+ assert (opt::opt_str(m, "t") == "20");
}
_ { fail; }
}
#[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")); }
+ opt::success(m) { assert (!opt::opt_present(m, "t")); }
_ { fail; }
}
}
#[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")); }
+ opt::success(m) { assert (opt::opt_present(m, "test")); }
_ { fail; }
}
}
#[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")); }
+ opt::success(m) { assert (!opt::opt_present(m, "test")); }
_ { fail; }
}
}
#[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")); }
+ opt::success(m) { assert (opt::opt_present(m, "t")); }
_ { fail; }
}
}
#[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")); }
+ opt::success(m) { assert (!opt::opt_present(m, "t")); }
_ { fail; }
}
}
#[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) {
- assert (opt::opt_present(m, ~"test"));
- assert (opt::opt_str(m, ~"test") == ~"20");
+ assert (opt::opt_present(m, "test"));
+ assert (opt::opt_str(m, "test") == "20");
}
_ { fail; }
}
#[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")); }
+ opt::success(m) { assert (!opt::opt_present(m, "test")); }
_ { fail; }
}
}
#[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_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");
}
_ { 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) {
- assert (opt::opt_present(m, ~"t"));
- assert (opt::opt_str(m, ~"t") == ~"20");
+ assert (opt::opt_present(m, "t"));
+ assert (opt::opt_str(m, "t") == "20");
}
_ { fail; }
}
#[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")); }
+ opt::success(m) { assert (!opt::opt_present(m, "t")); }
_ { fail; }
}
}
#[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_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");
}
_ { 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", ~"-m", ~"40", ~"-m", ~"50"];
+ ["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::optflag(~"f"), opt::optmulti(~"m"),
- opt::optopt(~"notpresent")];
+ [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 (opt::opt_str(m, ~"s") == ~"20");
- 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_present(m, ~"notpresent"));
+ assert (m.free[0] == "prog");
+ assert (m.free[1] == "free1");
+ assert (opt::opt_str(m, "s") == "20");
+ 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_present(m, "notpresent"));
}
_ { fail; }
}
#[test]
fn test_to_str() {
- assert (eq(int::to_str(0, 10u), ~"0"));
- assert (eq(int::to_str(1, 10u), ~"1"));
- assert (eq(int::to_str(-1, 10u), ~"-1"));
- assert (eq(int::to_str(255, 16u), ~"ff"));
- assert (eq(int::to_str(100, 10u), ~"100"));
+ assert (eq(int::to_str(0, 10u), "0"));
+ assert (eq(int::to_str(1, 10u), "1"));
+ assert (eq(int::to_str(-1, 10u), "-1"));
+ assert (eq(int::to_str(255, 16u), "ff"));
+ assert (eq(int::to_str(100, 10u), "100"));
}
#[test]
#[cfg(target_os = "win32")]
#[test]
fn test_simple() {
- let tmpfile: istr = ~"test/run-pass/lib-io-test-simple.tmp";
+ let tmpfile: str = "test/run-pass/lib-io-test-simple.tmp";
log tmpfile;
- let frood: istr = ~"A hoopy frood who really knows where his towel is.";
+ let frood: str = "A hoopy frood who really knows where his towel is.";
log frood;
{
let out: io::writer =
out.write_str(frood);
}
let inp: io::reader = io::file_reader(tmpfile);
- let frood2: istr = inp.read_c_str();
+ let frood2: str = inp.read_c_str();
log frood2;
assert (str::eq(frood, frood2));
}
fn eq_uint(x: &uint, y: &uint) -> bool { ret x == y; }
let hasher_uint: map::hashfn<uint> = util::id;
let eqer_uint: map::eqfn<uint> = eq_uint;
- let hasher_str: map::hashfn<istr> = str::hash;
- let eqer_str: map::eqfn<istr> = str::eq;
+ let hasher_str: map::hashfn<str> = str::hash;
+ let eqer_str: map::eqfn<str> = str::eq;
log "uint -> uint";
let hm_uu: map::hashmap<uint, uint> =
map::mk_hashmap::<uint, uint>(hasher_uint, eqer_uint);
assert (hm_uu.get(12u) == 14u);
assert (!hm_uu.insert(12u, 12u));
assert (hm_uu.get(12u) == 12u);
- let ten: istr = ~"ten";
- let eleven: istr = ~"eleven";
- let twelve: istr = ~"twelve";
+ let ten: str = "ten";
+ let eleven: str = "eleven";
+ let twelve: str = "twelve";
log "str -> uint";
- let hm_su: map::hashmap<istr, uint> =
- map::mk_hashmap::<istr, uint>(hasher_str, eqer_str);
- assert (hm_su.insert(~"ten", 12u));
+ let hm_su: map::hashmap<str, uint> =
+ map::mk_hashmap::<str, uint>(hasher_str, eqer_str);
+ assert (hm_su.insert("ten", 12u));
assert (hm_su.insert(eleven, 13u));
- assert (hm_su.insert(~"twelve", 14u));
+ assert (hm_su.insert("twelve", 14u));
assert (hm_su.get(eleven) == 13u);
- assert (hm_su.get(~"eleven") == 13u);
- assert (hm_su.get(~"twelve") == 14u);
- assert (hm_su.get(~"ten") == 12u);
- assert (!hm_su.insert(~"twelve", 14u));
- assert (hm_su.get(~"twelve") == 14u);
- assert (!hm_su.insert(~"twelve", 12u));
- assert (hm_su.get(~"twelve") == 12u);
+ assert (hm_su.get("eleven") == 13u);
+ assert (hm_su.get("twelve") == 14u);
+ assert (hm_su.get("ten") == 12u);
+ assert (!hm_su.insert("twelve", 14u));
+ assert (hm_su.get("twelve") == 14u);
+ assert (!hm_su.insert("twelve", 12u));
+ assert (hm_su.get("twelve") == 12u);
log "uint -> str";
- let hm_us: map::hashmap<uint, istr> =
- map::mk_hashmap::<uint, istr>(hasher_uint, eqer_uint);
- assert (hm_us.insert(10u, ~"twelve"));
- assert (hm_us.insert(11u, ~"thirteen"));
- assert (hm_us.insert(12u, ~"fourteen"));
- assert (str::eq(hm_us.get(11u), ~"thirteen"));
- assert (str::eq(hm_us.get(12u), ~"fourteen"));
- assert (str::eq(hm_us.get(10u), ~"twelve"));
- assert (!hm_us.insert(12u, ~"fourteen"));
- assert (str::eq(hm_us.get(12u), ~"fourteen"));
- assert (!hm_us.insert(12u, ~"twelve"));
- assert (str::eq(hm_us.get(12u), ~"twelve"));
+ let hm_us: map::hashmap<uint, str> =
+ map::mk_hashmap::<uint, str>(hasher_uint, eqer_uint);
+ assert (hm_us.insert(10u, "twelve"));
+ assert (hm_us.insert(11u, "thirteen"));
+ assert (hm_us.insert(12u, "fourteen"));
+ assert (str::eq(hm_us.get(11u), "thirteen"));
+ assert (str::eq(hm_us.get(12u), "fourteen"));
+ assert (str::eq(hm_us.get(10u), "twelve"));
+ assert (!hm_us.insert(12u, "fourteen"));
+ assert (str::eq(hm_us.get(12u), "fourteen"));
+ assert (!hm_us.insert(12u, "twelve"));
+ assert (str::eq(hm_us.get(12u), "twelve"));
log "str -> str";
- let hm_ss: map::hashmap<istr, istr> =
- map::mk_hashmap::<istr, istr>(hasher_str, eqer_str);
- assert (hm_ss.insert(ten, ~"twelve"));
- assert (hm_ss.insert(eleven, ~"thirteen"));
- assert (hm_ss.insert(twelve, ~"fourteen"));
- assert (str::eq(hm_ss.get(~"eleven"), ~"thirteen"));
- assert (str::eq(hm_ss.get(~"twelve"), ~"fourteen"));
- assert (str::eq(hm_ss.get(~"ten"), ~"twelve"));
- assert (!hm_ss.insert(~"twelve", ~"fourteen"));
- assert (str::eq(hm_ss.get(~"twelve"), ~"fourteen"));
- assert (!hm_ss.insert(~"twelve", ~"twelve"));
- assert (str::eq(hm_ss.get(~"twelve"), ~"twelve"));
+ let hm_ss: map::hashmap<str, str> =
+ map::mk_hashmap::<str, str>(hasher_str, eqer_str);
+ assert (hm_ss.insert(ten, "twelve"));
+ assert (hm_ss.insert(eleven, "thirteen"));
+ assert (hm_ss.insert(twelve, "fourteen"));
+ assert (str::eq(hm_ss.get("eleven"), "thirteen"));
+ assert (str::eq(hm_ss.get("twelve"), "fourteen"));
+ assert (str::eq(hm_ss.get("ten"), "twelve"));
+ assert (!hm_ss.insert("twelve", "fourteen"));
+ assert (str::eq(hm_ss.get("twelve"), "fourteen"));
+ assert (!hm_ss.insert("twelve", "twelve"));
+ assert (str::eq(hm_ss.get("twelve"), "twelve"));
log "*** finished test_simple";
}
let i: uint = 0u;
while i < num_to_insert {
assert (hm_uu.insert(i, i * i));
- log ~"inserting " + uint::to_str(i, 10u) + ~" -> " +
+ log "inserting " + uint::to_str(i, 10u) + " -> " +
uint::to_str(i * i, 10u);
i += 1u;
}
log "-----";
i = 0u;
while i < num_to_insert {
- log ~"get(" + uint::to_str(i, 10u) + ~") = " +
+ log "get(" + uint::to_str(i, 10u) + ") = " +
uint::to_str(hm_uu.get(i), 10u);
assert (hm_uu.get(i) == i * i);
i += 1u;
hm_uu.rehash();
i = 0u;
while i < num_to_insert {
- log ~"get(" + uint::to_str(i, 10u) + ~") = " +
+ log "get(" + uint::to_str(i, 10u) + ") = " +
uint::to_str(hm_uu.get(i), 10u);
assert (hm_uu.get(i) == i * i);
i += 1u;
}
log "str -> str";
- let hasher_str: map::hashfn<istr> = str::hash;
- let eqer_str: map::eqfn<istr> = str::eq;
- let hm_ss: map::hashmap<istr, istr> =
- map::mk_hashmap::<istr, istr>(hasher_str, eqer_str);
+ let hasher_str: map::hashfn<str> = str::hash;
+ let eqer_str: map::eqfn<str> = str::eq;
+ let hm_ss: map::hashmap<str, str> =
+ map::mk_hashmap::<str, str>(hasher_str, eqer_str);
i = 0u;
while i < num_to_insert {
- assert (hm_ss.insert(uint::to_str(i, 2u),
- uint::to_str(i * i, 2u)));
- log ~"inserting \"" + uint::to_str(i, 2u) + ~"\" -> \"" +
- uint::to_str(i * i, 2u) + ~"\"";
+ assert (hm_ss.insert(uint::to_str(i, 2u), uint::to_str(i * i, 2u)));
+ log "inserting \"" + uint::to_str(i, 2u) + "\" -> \"" +
+ uint::to_str(i * i, 2u) + "\"";
i += 1u;
}
log "-----";
i = 0u;
while i < num_to_insert {
- log ~"get(\"" + uint::to_str(i, 2u) + ~"\") = \"" +
- hm_ss.get(uint::to_str(i, 2u)) + ~"\"";
+ log "get(\"" + uint::to_str(i, 2u) + "\") = \"" +
+ hm_ss.get(uint::to_str(i, 2u)) + "\"";
assert (str::eq(hm_ss.get(uint::to_str(i, 2u)),
uint::to_str(i * i, 2u)));
i += 1u;
}
assert (hm_ss.insert(uint::to_str(num_to_insert, 2u),
uint::to_str(17u, 2u)));
- assert (str::eq(hm_ss.get(
- uint::to_str(num_to_insert, 2u)),
+ assert (str::eq(hm_ss.get(uint::to_str(num_to_insert, 2u)),
uint::to_str(17u, 2u)));
log "-----";
hm_ss.rehash();
i = 0u;
while i < num_to_insert {
- log ~"get(\"" + uint::to_str(i, 2u) + ~"\") = \"" +
- hm_ss.get(uint::to_str(i, 2u)) + ~"\"";
+ log "get(\"" + uint::to_str(i, 2u) + "\") = \"" +
+ hm_ss.get(uint::to_str(i, 2u)) + "\"";
assert (str::eq(hm_ss.get(uint::to_str(i, 2u)),
uint::to_str(i * i, 2u)));
i += 1u;
let i: uint = 0u;
while i < num_to_insert {
assert (hm.insert(i, i * i));
- log ~"inserting " + uint::to_str(i, 10u) + ~" -> " +
+ log "inserting " + uint::to_str(i, 10u) + " -> " +
uint::to_str(i * i, 10u);
i += 1u;
}
i = 0u;
while i < num_to_insert {
let v = hm.remove(i);
- alt (v) {
- option::some(u) {
- assert (u == (i * i));
- }
+ alt v {
+ option::some(u) { assert (u == i * i); }
option::none. { fail; }
}
i += 2u;
log "-----";
i = 1u;
while i < num_to_insert {
- log ~"get(" + uint::to_str(i, 10u) + ~") = " +
+ log "get(" + uint::to_str(i, 10u) + ") = " +
uint::to_str(hm.get(i), 10u);
assert (hm.get(i) == i * i);
i += 2u;
log "-----";
i = 1u;
while i < num_to_insert {
- log ~"get(" + uint::to_str(i, 10u) + ~") = " +
+ log "get(" + uint::to_str(i, 10u) + ") = " +
uint::to_str(hm.get(i), 10u);
assert (hm.get(i) == i * i);
i += 2u;
i = 0u;
while i < num_to_insert {
assert (hm.insert(i, i * i));
- log ~"inserting " + uint::to_str(i, 10u) + ~" -> " +
+ log "inserting " + uint::to_str(i, 10u) + " -> " +
uint::to_str(i * i, 10u);
i += 2u;
}
log "-----";
i = 0u;
while i < num_to_insert {
- log ~"get(" + uint::to_str(i, 10u) + ~") = " +
+ log "get(" + uint::to_str(i, 10u) + ") = " +
uint::to_str(hm.get(i), 10u);
assert (hm.get(i) == i * i);
i += 1u;
assert (hm.size() == num_to_insert);
i = 0u;
while i < num_to_insert {
- log ~"get(" + uint::to_str(i, 10u) + ~") = " +
+ log "get(" + uint::to_str(i, 10u) + ") = " +
uint::to_str(hm.get(i), 10u);
assert (hm.get(i) == i * i);
i += 1u;
#[test]
fn test_contains_key() {
- let key = ~"k";
- let map = map::mk_hashmap::<istr, istr>(str::hash, str::eq);
+ let key = "k";
+ let map = map::mk_hashmap::<str, str>(str::hash, str::eq);
assert (!map.contains_key(key));
- map.insert(key, ~"val");
+ map.insert(key, "val");
assert (map.contains_key(key));
}
#[test]
fn test_find() {
- let key = ~"k";
- let map = map::mk_hashmap::<istr, istr>(str::hash, str::eq);
+ let key = "k";
+ let map = map::mk_hashmap::<str, str>(str::hash, str::eq);
assert (std::option::is_none(map.find(key)));
- map.insert(key, ~"val");
- assert (std::option::get(map.find(key)) == ~"val");
+ map.insert(key, "val");
+ assert (std::option::get(map.find(key)) == "val");
}
#[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));
}
fn test_setenv() {
// NB: Each test of setenv needs to use different variable names or the
// tests will not be threadsafe
- setenv(~"NAME1", ~"VALUE");
- assert (getenv(~"NAME1") == option::some(~"VALUE"));
+ setenv("NAME1", "VALUE");
+ assert (getenv("NAME1") == option::some("VALUE"));
}
#[test]
fn test_setenv_overwrite() {
- setenv(~"NAME2", ~"1");
- setenv(~"NAME2", ~"2");
- assert (getenv(~"NAME2") == option::some(~"2"));
+ setenv("NAME2", "1");
+ setenv("NAME2", "2");
+ assert (getenv("NAME2") == option::some("2"));
}
// Windows GetEnvironmentVariable requires some extra work to make sure
// the buffer the variable is copied into is the right size
#[test]
fn test_getenv_big() {
- let s = ~"";
+ let s = "";
let i = 0;
- while i < 100 { s += ~"aaaaaaaaaa"; i += 1; }
- setenv(~"NAME3", s);
- assert (getenv(~"NAME3") == option::some(s));
+ while i < 100 { s += "aaaaaaaaaa"; i += 1; }
+ setenv("NAME3", s);
+ assert (getenv("NAME3") == option::some(s));
}
// Local Variables:
#[test]
fn test() {
- assert (!fs::path_is_absolute(~"test-path"));
+ assert (!fs::path_is_absolute("test-path"));
- log ~"Current working directory: " + os::getcwd();
+ log "Current working directory: " + os::getcwd();
- log fs::make_absolute(~"test-path");
- log fs::make_absolute(~"/usr/bin");
+ log fs::make_absolute("test-path");
+ log fs::make_absolute("/usr/bin");
}
let immut_names = vec::from_mut(names);
- // Silly, but what else can we do?
- check vec::same_length(expected, immut_names);
+ // Silly, but what else can we do?
+ check (vec::same_length(expected, immut_names));
let pairs = vec::zip(expected, immut_names);
for (a, b) in pairs { log #fmt["%d %d", a, b]; assert (a == b); }
}
#[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_err = os::pipe();
let pid =
- run::spawn_process(~"cat", [],
- pipe_in.in, pipe_out.out, pipe_err.out);
+ 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);
if pid == -1 { fail; }
- let expected = ~"test";
+ let expected = "test";
writeclose(pipe_in.out, expected);
let actual = readclose(pipe_out.in);
readclose(pipe_err.in);
log actual;
assert (expected == actual);
- fn writeclose(fd: int, s: &istr) {
+ fn writeclose(fd: int, s: &str) {
let writer = io::new_writer(io::fd_buf_writer(fd, option::none));
writer.write_str(s);
os::libc::close(fd);
}
- fn readclose(fd: int) -> istr {
+ 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 buf = ~"";
+ let buf = "";
while !reader.eof() {
let bytes = reader.read_bytes(4096u);
buf += str::unsafe_from_bytes(bytes);
#[test]
fn test() {
- type test = {input: istr, output: [u8]};
+ type test = {input: str, output: [u8]};
- fn a_million_letter_a() -> istr {
+ fn a_million_letter_a() -> str {
let i = 0;
- let rs = ~"";
- while i < 100000 { rs += ~"aaaaaaaaaa"; i += 1; }
+ let rs = "";
+ while i < 100000 { rs += "aaaaaaaaaa"; i += 1; }
ret rs;
}
// 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]},
- {input: ~"abcdbcdecdefdefgefghfghighij"
- + ~"hijkijkljklmklmnlmnomnopnopq",
+ {input:
+ "abcdbcdecdefdefgefghfghighij" + "hijkijkljklmklmnlmnomnopnopq",
output:
[0x84u8, 0x98u8, 0x3Eu8, 0x44u8, 0x1Cu8, 0x3Bu8, 0xD2u8, 0x6Eu8,
0xBAu8, 0xAEu8, 0x4Au8, 0xA1u8, 0xF9u8, 0x51u8, 0x29u8, 0xE5u8,
// 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]},
- {input: ~"The quick brown fox jumps over the lazy cog",
+ {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,
#[test]
fn test_eq() {
- assert str::eq(~"", ~"");
- assert str::eq(~"foo", ~"foo");
- assert !str::eq(~"foo", ~"bar");
+ assert (str::eq("", ""));
+ assert (str::eq("foo", "foo"));
+ assert (!str::eq("foo", "bar"));
}
#[test]
fn test_lteq() {
- assert str::lteq(~"", ~"");
- assert str::lteq(~"", ~"foo");
- assert str::lteq(~"foo", ~"foo");
- assert !str::eq(~"foo", ~"bar");
+ assert (str::lteq("", ""));
+ assert (str::lteq("", "foo"));
+ assert (str::lteq("foo", "foo"));
+ assert (!str::eq("foo", "bar"));
}
#[test]
fn test_bytes_len() {
- assert (str::byte_len(~"") == 0u);
- assert (str::byte_len(~"hello world") == 11u);
- assert (str::byte_len(~"\x63") == 1u);
- assert (str::byte_len(~"\xa2") == 2u);
- assert (str::byte_len(~"\u03c0") == 2u);
- assert (str::byte_len(~"\u2620") == 3u);
- assert (str::byte_len(~"\U0001d11e") == 4u);
+ assert (str::byte_len("") == 0u);
+ assert (str::byte_len("hello world") == 11u);
+ assert (str::byte_len("\x63") == 1u);
+ assert (str::byte_len("\xa2") == 2u);
+ assert (str::byte_len("\u03c0") == 2u);
+ assert (str::byte_len("\u2620") == 3u);
+ assert (str::byte_len("\U0001d11e") == 4u);
}
#[test]
fn test_index_and_rindex() {
- assert (str::index(~"hello", 'e' as u8) == 1);
- assert (str::index(~"hello", 'o' as u8) == 4);
- assert (str::index(~"hello", 'z' as u8) == -1);
- assert (str::rindex(~"hello", 'l' as u8) == 3);
- assert (str::rindex(~"hello", 'h' as u8) == 0);
- assert (str::rindex(~"hello", 'z' as u8) == -1);
+ assert (str::index("hello", 'e' as u8) == 1);
+ assert (str::index("hello", 'o' as u8) == 4);
+ assert (str::index("hello", 'z' as u8) == -1);
+ assert (str::rindex("hello", 'l' as u8) == 3);
+ assert (str::rindex("hello", 'h' as u8) == 0);
+ assert (str::rindex("hello", 'z' as u8) == -1);
}
#[test]
fn test_split() {
- fn t(s: &istr, c: char, i: int, k: &istr) {
- log ~"splitting: " + s;
+ fn t(s: &str, c: char, i: int, k: &str) {
+ log "splitting: " + s;
log i;
let v = str::split(s, c as u8);
- log ~"split to: ";
- for z: istr in v { log z; }
- log ~"comparing: " + v[i] + ~" vs. " + k;
+ log "split to: ";
+ for z: str in v { log z; }
+ log "comparing: " + v[i] + " vs. " + k;
assert (str::eq(v[i], k));
}
- t(~"abc.hello.there", '.', 0, ~"abc");
- t(~"abc.hello.there", '.', 1, ~"hello");
- t(~"abc.hello.there", '.', 2, ~"there");
- t(~".hello.there", '.', 0, ~"");
- t(~".hello.there", '.', 1, ~"hello");
- t(~"...hello.there.", '.', 3, ~"hello");
- t(~"...hello.there.", '.', 5, ~"");
+ t("abc.hello.there", '.', 0, "abc");
+ t("abc.hello.there", '.', 1, "hello");
+ t("abc.hello.there", '.', 2, "there");
+ t(".hello.there", '.', 0, "");
+ t(".hello.there", '.', 1, "hello");
+ t("...hello.there.", '.', 3, "hello");
+ t("...hello.there.", '.', 5, "");
}
#[test]
fn test_find() {
- fn t(haystack: &istr, needle: &istr, i: int) {
+ fn t(haystack: &str, needle: &str, i: int) {
let j: int = str::find(haystack, needle);
- log ~"searched for " + needle;
+ log "searched for " + needle;
log j;
assert (i == j);
}
- t(~"this is a simple", ~"is a", 5);
- t(~"this is a simple", ~"is z", -1);
- t(~"this is a simple", ~"", 0);
- t(~"this is a simple", ~"simple", 10);
- t(~"this", ~"simple", -1);
+ t("this is a simple", "is a", 5);
+ t("this is a simple", "is z", -1);
+ t("this is a simple", "", 0);
+ t("this is a simple", "simple", 10);
+ t("this", "simple", -1);
}
#[test]
fn test_substr() {
- fn t(a: &istr, b: &istr, start: int) {
- assert (str::eq(str::substr(a, start as uint,
- str::byte_len(b)), b));
+ fn t(a: &str, b: &str, start: int) {
+ assert (str::eq(str::substr(a, start as uint, str::byte_len(b)), b));
}
- t(~"hello", ~"llo", 2);
- t(~"hello", ~"el", 1);
- t(~"substr should not be a challenge", ~"not", 14);
+ t("hello", "llo", 2);
+ t("hello", "el", 1);
+ t("substr should not be a challenge", "not", 14);
}
#[test]
fn test_concat() {
- fn t(v: &[istr], s: &istr) { assert (str::eq(str::concat(v), s)); }
- t([~"you", ~"know", ~"I'm", ~"no", ~"good"], ~"youknowI'mnogood");
- let v: [istr] = [];
- t(v, ~"");
- t([~"hi"], ~"hi");
+ 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(v, "");
+ t(["hi"], "hi");
}
#[test]
fn test_connect() {
- fn t(v: &[istr], sep: &istr, s: &istr) {
+ 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: [istr] = [];
- t(v, ~" ", ~"");
- t([~"hi"], ~" ", ~"hi");
+ t(["you", "know", "I'm", "no", "good"], " ", "you know I'm no good");
+ let v: [str] = [];
+ t(v, " ", "");
+ t(["hi"], " ", "hi");
}
#[test]
// to_upper doesn't understand unicode yet,
// but we need to at least preserve it
- let unicode = ~"\u65e5\u672c";
- let input = ~"abcDEF" + unicode + ~"xyz:.;";
- let expected = ~"ABCDEF" + unicode + ~"XYZ:.;";
+ let unicode = "\u65e5\u672c";
+ let input = "abcDEF" + unicode + "xyz:.;";
+ let expected = "ABCDEF" + unicode + "XYZ:.;";
let actual = str::to_upper(input);
assert (str::eq(expected, actual));
}
#[test]
fn test_slice() {
- assert (str::eq(~"ab", str::slice(~"abc", 0u, 2u)));
- assert (str::eq(~"bc", str::slice(~"abc", 1u, 3u)));
- assert (str::eq(~"", str::slice(~"abc", 1u, 1u)));
- fn a_million_letter_a() -> istr {
+ assert (str::eq("ab", str::slice("abc", 0u, 2u)));
+ assert (str::eq("bc", str::slice("abc", 1u, 3u)));
+ assert (str::eq("", str::slice("abc", 1u, 1u)));
+ fn a_million_letter_a() -> str {
let i = 0;
- let rs = ~"";
- while i < 100000 { rs += ~"aaaaaaaaaa"; i += 1; }
+ let rs = "";
+ while i < 100000 { rs += "aaaaaaaaaa"; i += 1; }
ret rs;
}
- fn half_a_million_letter_a() -> istr {
+ fn half_a_million_letter_a() -> str {
let i = 0;
- let rs = ~"";
- while i < 100000 { rs += ~"aaaaa"; i += 1; }
+ let rs = "";
+ while i < 100000 { rs += "aaaaa"; i += 1; }
ret rs;
}
assert (str::eq(half_a_million_letter_a(),
#[test]
fn test_starts_with() {
- assert (str::starts_with(~"", ~""));
- assert (str::starts_with(~"abc", ~""));
- assert (str::starts_with(~"abc", ~"a"));
- assert (!str::starts_with(~"a", ~"abc"));
- assert (!str::starts_with(~"", ~"abc"));
+ assert (str::starts_with("", ""));
+ assert (str::starts_with("abc", ""));
+ assert (str::starts_with("abc", "a"));
+ assert (!str::starts_with("a", "abc"));
+ assert (!str::starts_with("", "abc"));
}
#[test]
fn test_ends_with() {
- assert (str::ends_with(~"", ~""));
- assert (str::ends_with(~"abc", ~""));
- assert (str::ends_with(~"abc", ~"c"));
- assert (!str::ends_with(~"a", ~"abc"));
- assert (!str::ends_with(~"", ~"abc"));
+ assert (str::ends_with("", ""));
+ assert (str::ends_with("abc", ""));
+ assert (str::ends_with("abc", "c"));
+ assert (!str::ends_with("a", "abc"));
+ assert (!str::ends_with("", "abc"));
}
#[test]
fn test_is_empty() {
- assert (str::is_empty(~""));
- assert (!str::is_empty(~"a"));
+ assert (str::is_empty(""));
+ assert (!str::is_empty("a"));
}
#[test]
fn test_is_not_empty() {
- assert (str::is_not_empty(~"a"));
- assert (!str::is_not_empty(~""));
+ assert (str::is_not_empty("a"));
+ assert (!str::is_not_empty(""));
}
#[test]
fn test_replace() {
- let a = ~"a";
+ let a = "a";
check (str::is_not_empty(a));
- assert (str::replace(~"", a, ~"b") == ~"");
- assert (str::replace(~"a", a, ~"b") == ~"b");
- assert (str::replace(~"ab", a, ~"b") == ~"bb");
- let test = ~"test";
+ assert (str::replace("", a, "b") == "");
+ assert (str::replace("a", a, "b") == "b");
+ assert (str::replace("ab", a, "b") == "bb");
+ let test = "test";
check (str::is_not_empty(test));
- assert (str::replace(~" test test ", test, ~"toast")
- == ~" toast toast ");
- assert (str::replace(~" test test ", test, ~"") == ~" ");
+ assert (str::replace(" test test ", test, "toast") == " toast toast ");
+ assert (str::replace(" test test ", test, "") == " ");
}
#[test]
fn test_char_slice() {
- assert (str::eq(~"ab", str::char_slice(~"abc", 0u, 2u)));
- assert (str::eq(~"bc", str::char_slice(~"abc", 1u, 3u)));
- assert (str::eq(~"", str::char_slice(~"abc", 1u, 1u)));
- assert (str::eq(~"\u65e5", str::char_slice(~"\u65e5\u672c", 0u, 1u)));
+ assert (str::eq("ab", str::char_slice("abc", 0u, 2u)));
+ assert (str::eq("bc", str::char_slice("abc", 1u, 3u)));
+ assert (str::eq("", str::char_slice("abc", 1u, 1u)));
+ assert (str::eq("\u65e5", str::char_slice("\u65e5\u672c", 0u, 1u)));
}
#[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(" _ "));
}
#[test]
fn is_ascii() {
- assert str::is_ascii(~"");
- assert str::is_ascii(~"a");
- assert !str::is_ascii(~"\u2009");
+ assert (str::is_ascii(""));
+ assert (str::is_ascii("a"));
+ assert (!str::is_ascii("\u2009"));
}
#[test]
fn shift_byte() {
- let s = ~"ABC";
+ let s = "ABC";
let b = str::shift_byte(s);
- assert s == ~"BC";
- assert b == 65u8;
+ assert (s == "BC");
+ assert (b == 65u8);
}
#[test]
fn pop_byte() {
- let s = ~"ABC";
+ let s = "ABC";
let b = str::pop_byte(s);
- assert s == ~"AB";
- assert b == 67u8;
+ assert (s == "AB");
+ assert (b == 67u8);
}
#[test]
fn unsafe_from_bytes() {
let a = [65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 65u8];
let b = str::unsafe_from_bytes(a);
- assert b == ~"AAAAAAA";
+ assert (b == "AAAAAAA");
}
#[test]
let a = [65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 0u8];
let b = vec::to_ptr(a);
let c = str::str_from_cstr(b);
- assert c == ~"AAAAAAA";
+ assert (c == "AAAAAAA");
}
#[test]
fn as_buf() {
- let a = ~"Abcdefg";
- let b = str::as_buf(a, { |buf|
- assert *buf == 65u8;
- 100
- });
- assert b == 100;
+ let a = "Abcdefg";
+ let b = str::as_buf(a, {|buf| assert (*buf == 65u8); 100 });
+ assert (b == 100);
}
#[test]
fn as_buf_small() {
- let a = ~"A";
- let b = str::as_buf(a, { |buf|
- assert *buf == 65u8;
- 100
- });
- assert b == 100;
+ let a = "A";
+ let b = str::as_buf(a, {|buf| assert (*buf == 65u8); 100 });
+ assert (b == 100);
}
#[test]
fn as_buf2() {
- let s = ~"hello";
- let sb = str::as_buf(s, { |b| b });
+ let s = "hello";
+ let sb = str::as_buf(s, {|b| b });
let s_cstr = str::str_from_cstr(sb);
assert (str::eq(s_cstr, s));
}
#[test]
fn vec_str_conversions() {
- let s1: istr = ~"All mimsy were the borogoves";
+ let s1: str = "All mimsy were the borogoves";
let v: [u8] = str::bytes(s1);
- let s2: istr = str::unsafe_from_bytes(v);
+ let s2: str = str::unsafe_from_bytes(v);
let i: uint = 0u;
let n1: uint = str::byte_len(s1);
let n2: uint = vec::len::<u8>(v);
import std::sys;
#[test]
-fn last_os_error() {
- log sys::rustrt::last_os_error();
-}
\ No newline at end of file
+fn last_os_error() { log sys::rustrt::last_os_error(); }
#[test]
fn spawn_polymorphic() {
- fn foo<~T>(x : -T) {
- log_err x;
- }
+ fn foo<~T>(x: -T) { log_err x; }
let fb = bind foo(true);
task::spawn(fb);
task::spawn(bind foo(42));
-}
\ No newline at end of file
+}
let ran = @mutable false;
let f = bind fn (ran: @mutable bool) { *ran = true; }(ran);
- let desc = {name: ~"whatever", fn: f, ignore: true};
+ let desc = {name: "whatever", fn: f, ignore: true};
test::run_test(desc, test::default_test_to_task);
#[test]
fn ignored_tests_result_in_ignored() {
fn f() { }
- let desc = {name: ~"whatever", fn: f, ignore: true};
+ let desc = {name: "whatever", fn: f, ignore: true};
let res = test::run_test(desc, test::default_test_to_task).wait();
assert (res == test::tr_ignored);
}
#[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)));
+ 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].name == "1");
assert (filtered[0].ignore == false);
}
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 = [];
- for name: istr in names {
+ for name: str in names {
let test = {name: name, fn: testfn, ignore: false};
tests += [test];
}
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"];
-
- check vec::same_length(expected, filtered);
+ ["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"];
+
+ check (vec::same_length(expected, filtered));
let pairs = vec::zip(expected, filtered);
import std::str;
#[test]
-fn init_treemap() {
- let m = init::<int, int>();
-}
+fn init_treemap() { let m = init::<int, int>(); }
#[test]
-fn insert_one() {
- let m = init();
- insert(m, 1, 2);
-}
+fn insert_one() { let m = init(); insert(m, 1, 2); }
#[test]
-fn insert_two() {
- let m = init();
- insert(m, 1, 2);
- insert(m, 3, 4);
-}
+fn insert_two() { let m = init(); insert(m, 1, 2); insert(m, 3, 4); }
#[test]
fn insert_find() {
let m = init();
insert(m, 1, 2);
- assert(find(m, 1) == some(2));
+ assert (find(m, 1) == some(2));
}
#[test]
-fn find_empty() {
- let m = init::<int, int>();
- assert(find(m, 1) == none);
-}
+fn find_empty() { let m = init::<int, int>(); assert (find(m, 1) == none); }
#[test]
fn find_not_found() {
let m = init();
insert(m, 1, 2);
- assert(find(m, 2) == none);
+ assert (find(m, 2) == none);
}
#[test]
insert(m, 1, ());
let n = 0;
- fn t(n : &mutable int, k : &int, v : &()) {
- assert(n == k);
- n += 1;
- }
+ fn t(n: &mutable int, k: &int, v: &()) { assert (n == k); n += 1; }
traverse(m, bind t(n, _, _));
}
fn u8_map() {
let m = init();
- let k1 = str::bytes(~"foo");
- let k2 = str::bytes(~"bar");
+ let k1 = str::bytes("foo");
+ let k2 = str::bytes("bar");
- insert(m, k1, ~"foo");
- insert(m, k2, ~"bar");
+ insert(m, k1, "foo");
+ insert(m, k2, "bar");
- assert(find(m, k2) == some(~"bar"));
- assert(find(m, k1) == some(~"foo"));
+ assert (find(m, k2) == some("bar"));
+ assert (find(m, k1) == some("foo"));
}
let v1 = [1, 2, 3];
let v2 = [4, 5, 6];
- check same_length(v1, v2); // Silly, but what else can we do?
+ check (same_length(v1, v2)); // Silly, but what else can we do?
let z1 = vec::zip(v1, v2);
assert ((1, 4) == z1[0]);
// Make sure they work with 0-length vectors too.
let v4 = vec::reversed::<int>([]);
- assert v4 == [];
+ assert (v4 == []);
let v3: [mutable int] = [mutable];
vec::reverse::<int>(v3);
}