import foo = core::info;
import core::float::sin;
import core::str::{slice, to_upper};
-import core::option::some;
+import core::option::Some;
fn main() {
// Equivalent to 'log(core::info, core::float::sin(1.0));'
log(foo, sin(1.0));
- // Equivalent to 'log(core::info, core::option::some(1.0));'
- log(info, some(1.0));
+ // Equivalent to 'log(core::info, core::option::Some(1.0));'
+ log(info, Some(1.0));
// Equivalent to 'log(core::info,
// core::str::to_upper(core::str::slice(~"foo", 0u, 1u)));'
guard may refer to the variables bound within the pattern they follow.
~~~~
-# let maybe_digit = some(0);
+# let maybe_digit = Some(0);
# fn process_digit(i: int) { }
# fn process_other(i: int) { }
let message = match maybe_digit {
- some(x) if x < 10 => process_digit(x),
- some(x) => process_other(x),
- none => fail
+ Some(x) if x < 10 => process_digit(x),
+ Some(x) => process_other(x),
+ None => fail
};
~~~~
programs that just can't be typed.
~~~~
-let n = option::none;
+let n = option::None;
# option::iter(n, fn&(&&x:int) {})
~~~~
this:
~~~~
-let n2: option<int> = option::none;
+let n2: Option<int> = option::None;
// or
-let n = option::none::<int>;
+let n = option::None::<int>;
~~~~
Note that, in a value expression, `<` already has a meaning as a
url: ~str,
method: ~str,
description: ~str,
- reference: option<~str>,
+ reference: Option<~str>,
tags: ~[~str],
versions: ~[(~str, ~str)]
};
name: ~str,
mut url: ~str,
mut method: ~str,
- mut key: option<~str>,
- mut keyfp: option<~str>,
+ mut key: Option<~str>,
+ mut keyfp: Option<~str>,
mut packages: ~[mut package]
};
name: ~str,
vers: ~str,
uuid: ~str,
- desc: option<~str>,
- sigs: option<~str>,
- crate_type: option<~str>,
+ desc: Option<~str>,
+ sigs: Option<~str>,
+ crate_type: Option<~str>,
deps: ~[~str]
};
// url parsing, we wouldn't need it
match str::find_str(u, ~"://") {
- option::some(_) => has_archive_extension(u),
+ option::Some(_) => has_archive_extension(u),
_ => false
}
}
~"curl"
}
-fn load_link(mis: ~[@ast::meta_item]) -> (option<~str>,
- option<~str>,
- option<~str>) {
- let mut name = none;
- let mut vers = none;
- let mut uuid = none;
+fn load_link(mis: ~[@ast::meta_item]) -> (Option<~str>,
+ Option<~str>,
+ Option<~str>) {
+ let mut name = None;
+ let mut vers = None;
+ let mut uuid = None;
for mis.each |a| {
match a.node {
ast::meta_name_value(v, {node: ast::lit_str(s), span: _}) => {
match v {
- ~"name" => name = some(*s),
- ~"vers" => vers = some(*s),
- ~"uuid" => uuid = some(*s),
+ ~"name" => name = Some(*s),
+ ~"vers" => vers = Some(*s),
+ ~"uuid" => uuid = Some(*s),
_ => { }
}
}
(name, vers, uuid)
}
-fn load_crate(filename: &Path) -> option<crate> {
- let sess = parse::new_parse_sess(none);
+fn load_crate(filename: &Path) -> Option<crate> {
+ let sess = parse::new_parse_sess(None);
let c = parse::parse_crate_from_crate_file(filename, ~[], sess);
- let mut name = none;
- let mut vers = none;
- let mut uuid = none;
- let mut desc = none;
- let mut sigs = none;
- let mut crate_type = none;
+ let mut name = None;
+ let mut vers = None;
+ let mut uuid = None;
+ let mut desc = None;
+ let mut sigs = None;
+ let mut crate_type = None;
for c.node.attrs.each |a| {
match a.node.value.node {
ast::meta_name_value(v, {node: ast::lit_str(_), span: _}) => {
match v {
- ~"desc" => desc = some(v),
- ~"sigs" => sigs = some(v),
- ~"crate_type" => crate_type = some(v),
+ ~"desc" => desc = Some(v),
+ ~"sigs" => sigs = Some(v),
+ ~"crate_type" => crate_type = Some(v),
_ => { }
}
}
for m.each |item| {
match attr::get_meta_item_value_str(item) {
- some(value) => {
+ Some(value) => {
let name = attr::get_meta_item_name(item);
match name {
_ => ()
}
}
- none => ()
+ None => ()
}
}
let deps = copy e.deps;
match (name, vers, uuid) {
- (some(name0), some(vers0), some(uuid0)) => {
- some({
+ (Some(name0), Some(vers0), Some(uuid0)) => {
+ Some({
name: name0,
vers: vers0,
uuid: uuid0,
crate_type: crate_type,
deps: deps })
}
- _ => return none
+ _ => return None
}
}
match j {
json::dict(j) => {
let mut url = match j.find(~"url") {
- some(json::string(u)) => *u,
+ Some(json::string(u)) => *u,
_ => fail ~"needed 'url' field in source"
};
let method = match j.find(~"method") {
- some(json::string(u)) => *u,
+ Some(json::string(u)) => *u,
_ => assume_source_method(url)
};
let key = match j.find(~"key") {
- some(json::string(u)) => some(*u),
- _ => none
+ Some(json::string(u)) => Some(*u),
+ _ => None
};
let keyfp = match j.find(~"keyfp") {
- some(json::string(u)) => some(*u),
- _ => none
+ Some(json::string(u)) => Some(*u),
+ _ => None
};
if method == ~"file" {
url = os::make_absolute(&Path(url)).to_str();
fn load_one_source_package(src: source, p: map::hashmap<~str, json::json>) {
let name = match p.find(~"name") {
- some(json::string(n)) => {
+ Some(json::string(n)) => {
if !valid_pkg_name(*n) {
warn(~"malformed source json: "
+ src.name + ~", '" + *n + ~"'"+
};
let uuid = match p.find(~"uuid") {
- some(json::string(n)) => {
+ Some(json::string(n)) => {
if !is_uuid(*n) {
warn(~"malformed source json: "
+ src.name + ~", '" + *n + ~"'"+
};
let url = match p.find(~"url") {
- some(json::string(n)) => *n,
+ Some(json::string(n)) => *n,
_ => {
warn(~"malformed source json: " + src.name + ~" (missing url)");
return;
};
let method = match p.find(~"method") {
- some(json::string(n)) => *n,
+ Some(json::string(n)) => *n,
_ => {
warn(~"malformed source json: "
+ src.name + ~" (missing method)");
};
let reference = match p.find(~"ref") {
- some(json::string(n)) => some(*n),
- _ => none
+ Some(json::string(n)) => Some(*n),
+ _ => None
};
let mut tags = ~[];
match p.find(~"tags") {
- some(json::list(js)) => {
+ Some(json::list(js)) => {
for (*js).each |j| {
match j {
json::string(j) => vec::grow(tags, 1u, *j),
}
let description = match p.find(~"description") {
- some(json::string(n)) => *n,
+ Some(json::string(n)) => *n,
_ => {
warn(~"malformed source json: " + src.name
+ ~" (missing description)");
};
match vec::position(src.packages, |pkg| pkg.uuid == uuid) {
- some(idx) => {
+ Some(idx) => {
src.packages[idx] = newpkg;
log(debug, ~" updated package: " + src.name + ~"/" + name);
}
- none => {
+ None => {
vec::grow(src.packages, 1u, newpkg);
}
}
// Runs rustc in <path + subdir> with the given flags
// and returns <patho + subdir>
fn run_in_buildpath(what: &str, path: &Path, subdir: &Path, cf: &Path,
- extra_flags: ~[~str]) -> option<Path> {
+ extra_flags: ~[~str]) -> Option<Path> {
let buildpath = path.push_rel(subdir);
need_dir(&buildpath);
debug!("%s: %s -> %s", what, cf.to_str(), buildpath.to_str());
cf.to_str()] + extra_flags);
if p.status != 0 {
error(fmt!("rustc failed: %d\n%s\n%s", p.status, p.err, p.out));
- return none;
+ return None;
}
- some(buildpath)
+ Some(buildpath)
}
fn test_one_crate(_c: cargo, path: &Path, cf: &Path) {
&Path("test"),
cf,
~[ ~"--test"]) {
- none => return,
- some(bp) => bp
+ None => return,
+ Some(bp) => bp
};
run_programs(&buildpath);
}
let buildpath = match run_in_buildpath(~"installing", path,
&Path("build"),
cf, ~[]) {
- none => return,
- some(bp) => bp
+ None => return,
+ Some(bp) => bp
};
let newv = os::list_dir_path(&buildpath);
let exec_suffix = os::exe_suffix();
fn rustc_sysroot() -> ~str {
match os::self_exe_path() {
- some(path) => {
+ Some(path) => {
let rustc = path.push_many([~"..", ~"bin", ~"rustc"]);
debug!(" rustc: %s", rustc.to_str());
rustc.to_str()
}
- none => ~"rustc"
+ None => ~"rustc"
}
}
let mut cratefiles = ~[];
for os::walk_dir(&Path(".")) |p| {
- if p.filetype() == some(~"rc") {
+ if p.filetype() == Some(~"rc") {
vec::push(cratefiles, *p);
}
}
for cratefiles.each |cf| {
match load_crate(&cf) {
- none => again,
- some(crate) => {
+ None => again,
+ Some(crate) => {
for crate.deps.each |query| {
// FIXME (#1356): handle cyclic dependencies
// (n.b. #1356 says "Cyclic dependency is an error
}
}
-fn install_git(c: cargo, wd: &Path, url: ~str, reference: option<~str>) {
+fn install_git(c: cargo, wd: &Path, url: ~str, reference: Option<~str>) {
run::program_output(~"git", ~[~"clone", url, wd.to_str()]);
if option::is_some(reference) {
let r = option::get(reference);
fn install_uuid_specific(c: cargo, wd: &Path, src: ~str, uuid: ~str) {
match c.sources.find(src) {
- some(s) => {
+ Some(s) => {
let packages = copy s.packages;
if vec::any(packages, |p| {
if p.uuid == uuid {
fn install_named_specific(c: cargo, wd: &Path, src: ~str, name: ~str) {
match c.sources.find(src) {
- some(s) => {
+ Some(s) => {
let packages = copy s.packages;
if vec::any(packages, |p| {
if p.name == name {
if is_uuid(target) {
for os::list_dir(lib).each |file| {
match str::find_str(file, ~"-" + target + ~"-") {
- some(_) => if !try_uninstall(&lib.push(file)) { return },
- none => ()
+ Some(_) => if !try_uninstall(&lib.push(file)) { return },
+ None => ()
}
}
error(~"can't find package with uuid: " + target);
} else {
for os::list_dir(lib).each |file| {
match str::find_str(file, ~"lib" + target + ~"-") {
- some(_) => if !try_uninstall(&lib.push(file)) { return },
- none => ()
+ Some(_) => if !try_uninstall(&lib.push(file)) { return },
+ None => ()
}
}
for os::list_dir(bin).each |file| {
match str::find_str(file, target) {
- some(_) => if !try_uninstall(&lib.push(file)) { return },
- none => ()
+ Some(_) => if !try_uninstall(&lib.push(file)) { return },
+ None => ()
}
}
fn install_query(c: cargo, wd: &Path, target: ~str) {
match c.dep_cache.find(target) {
- some(inst) => {
+ Some(inst) => {
if inst {
return;
}
}
- none => ()
+ None => ()
}
c.dep_cache.insert(target, true);
return;
} else if is_git_url(target) {
let reference = if c.opts.free.len() >= 4u {
- some(c.opts.free[3u])
+ Some(c.opts.free[3u])
} else {
- none
+ None
};
install_git(c, wd, target, reference);
} else if !valid_pkg_name(target) && has_archive_extension(target) {
let mut ps = copy target;
match str::find_char(ps, '/') {
- option::some(idx) => {
+ option::Some(idx) => {
let source = str::slice(ps, 0u, idx);
ps = str::slice(ps, idx + 1u, str::len(ps));
if is_uuid(ps) {
install_named_specific(c, wd, source, ps);
}
}
- option::none => {
+ option::None => {
if is_uuid(ps) {
install_uuid(c, wd, ps);
} else {
fn get_temp_workdir(c: cargo) -> Path {
match tempfile::mkdtemp(&c.workdir, "cargo") {
- some(wd) => wd,
- none => fail fmt!("needed temp dir: %s",
+ Some(wd) => wd,
+ None => fail fmt!("needed temp dir: %s",
c.workdir.to_str())
}
}
os::copy_file(&url.push("packages.json.sig"), &sigfile);
match copy src.key {
- some(u) => {
+ Some(u) => {
let p = run::program_output(~"curl",
~[~"-f", ~"-s",
~"-o", keyfile.to_str(), u]);
_ => ()
}
match (src.key, src.keyfp) {
- (some(_), some(f)) => {
+ (Some(_), Some(f)) => {
let r = pgp::verify(&c.root, &pkgfile, &sigfile, f);
if !r {
let has_src_file = os::path_exists(&srcfile);
match copy src.key {
- some(u) => {
+ Some(u) => {
let p = run::program_output(~"curl",
~[~"-f", ~"-s",
~"-o", keyfile.to_str(), u]);
_ => ()
}
match (src.key, src.keyfp) {
- (some(_), some(f)) => {
+ (Some(_), Some(f)) => {
let r = pgp::verify(&c.root, &pkgfile, &sigfile, f);
if !r {
}
match copy src.key {
- some(u) => {
+ Some(u) => {
let p = run::program_output(~"curl",
~[~"-f", ~"-s",
~"-o", keyfile.to_str(), u]);
_ => ()
}
match (src.key, src.keyfp) {
- (some(_), some(f)) => {
+ (Some(_), Some(f)) => {
if smart {
url = src.url + ~"/packages.json.sig";
}
error(fmt!("'%s' is an invalid source name", name));
} else {
match c.sources.find(name) {
- some(source) => {
+ Some(source) => {
print_source(source);
}
- none => {
+ None => {
error(fmt!("no such source: %s", name));
}
}
chash.insert(~"method", json::string(@v.method));
match copy v.key {
- some(key) => {
+ Some(key) => {
chash.insert(~"key", json::string(@key));
}
_ => ()
}
match copy v.keyfp {
- some(keyfp) => {
+ Some(keyfp) => {
chash.insert(~"keyfp", json::string(@keyfp));
}
_ => ()
name: name,
mut url: url,
mut method: assume_source_method(url),
- mut key: none,
- mut keyfp: none,
+ mut key: None,
+ mut keyfp: None,
mut packages: ~[mut]
});
info(fmt!("added source: %s", name));
}
match c.sources.find(name) {
- some(source) => {
+ Some(source) => {
let old = copy source.url;
let method = assume_source_method(url);
info(fmt!("changed source url: '%s' to '%s'", old, url));
}
- none => {
+ None => {
error(fmt!("no such source: %s", name));
}
}
}
match c.sources.find(name) {
- some(source) => {
+ Some(source) => {
let old = copy source.method;
source.method = match method {
info(fmt!("changed source method: '%s' to '%s'", old,
method));
}
- none => {
+ None => {
error(fmt!("no such source: %s", name));
}
}
}
match c.sources.find(name) {
- some(source) => {
+ Some(source) => {
c.sources.remove(name);
c.sources.insert(newn, source);
info(fmt!("renamed source: %s to %s", name, newn));
}
- none => {
+ None => {
error(fmt!("no such source: %s", name));
}
}
run_ignored: bool,
// Only run tests that match this filter
- filter: option<~str>,
+ filter: Option<~str>,
// Write out a parseable log of tests that were run
- logfile: option<Path>,
+ logfile: Option<Path>,
// A command line to prefix program execution with,
// for running under valgrind
- runtool: option<~str>,
+ runtool: Option<~str>,
// Flags to pass to the compiler
- rustcflags: option<~str>,
+ rustcflags: Option<~str>,
// Explain what's going on
verbose: bool};
run_ignored: getopts::opt_present(matches, ~"ignored"),
filter:
if vec::len(matches.free) > 0u {
- option::some(matches.free[0])
- } else { option::none },
+ option::Some(matches.free[0])
+ } else { option::None },
logfile: option::map(getopts::opt_maybe_str(matches,
~"logfile"),
|s| Path(s)),
logv(c, fmt!("\n"));
}
-fn opt_str(maybestr: option<~str>) -> ~str {
- match maybestr { option::some(s) => s, option::none => ~"(none)" }
+fn opt_str(maybestr: Option<~str>) -> ~str {
+ match maybestr { option::Some(s) => s, option::None => ~"(none)" }
}
-fn str_opt(maybestr: ~str) -> option<~str> {
- if maybestr != ~"(none)" { option::some(maybestr) } else { option::none }
+fn str_opt(maybestr: ~str) -> Option<~str> {
+ if maybestr != ~"(none)" { option::Some(maybestr) } else { option::None }
}
fn str_mode(s: ~str) -> mode {
fn test_opts(config: config) -> test::test_opts {
{filter:
match config.filter {
- option::some(s) => option::some(s),
- option::none => option::none
+ option::Some(s) => option::Some(s),
+ option::None => option::None
},
run_ignored: config.run_ignored,
logfile:
match config.logfile {
- option::some(s) => option::some(s.to_str()),
- option::none => option::none
+ option::Some(s) => option::Some(s.to_str()),
+ option::None => option::None
}
}
}
let error_tag = ~"//~";
let mut idx;
match str::find_str(line, error_tag) {
- option::none => return ~[],
- option::some(nn) => { idx = (nn as uint) + str::len(error_tag); }
+ option::None => return ~[],
+ option::Some(nn) => { idx = (nn as uint) + str::len(error_tag); }
}
// "//~^^^ kind msg" denotes a message expected
// Lines that should be expected, in order, on standard out
error_patterns: ~[~str],
// Extra flags to pass to the compiler
- compile_flags: option<~str>,
+ compile_flags: Option<~str>,
// If present, the name of a file that this test should match when
// pretty-printed
- pp_exact: option<Path>,
+ pp_exact: Option<Path>,
// Modules from aux directory that should be compiled
aux_builds: ~[~str],
// Environment settings to use during execution
let mut error_patterns = ~[];
let mut aux_builds = ~[];
let mut exec_env = ~[];
- let mut compile_flags = option::none;
- let mut pp_exact = option::none;
+ let mut compile_flags = option::None;
+ let mut pp_exact = option::None;
for iter_header(testfile) |ln| {
match parse_error_pattern(ln) {
- option::some(ep) => vec::push(error_patterns, ep),
- option::none => ()
+ option::Some(ep) => vec::push(error_patterns, ep),
+ option::None => ()
};
if option::is_none(compile_flags) {
return true;
}
-fn parse_error_pattern(line: ~str) -> option<~str> {
+fn parse_error_pattern(line: ~str) -> Option<~str> {
parse_name_value_directive(line, ~"error-pattern")
}
-fn parse_aux_build(line: ~str) -> option<~str> {
+fn parse_aux_build(line: ~str) -> Option<~str> {
parse_name_value_directive(line, ~"aux-build")
}
-fn parse_compile_flags(line: ~str) -> option<~str> {
+fn parse_compile_flags(line: ~str) -> Option<~str> {
parse_name_value_directive(line, ~"compile-flags")
}
-fn parse_exec_env(line: ~str) -> option<(~str, ~str)> {
+fn parse_exec_env(line: ~str) -> Option<(~str, ~str)> {
do parse_name_value_directive(line, ~"exec-env").map |nv| {
// nv is either FOO or FOO=BAR
let strs = str::splitn_char(nv, '=', 1u);
}
}
-fn parse_pp_exact(line: ~str, testfile: &Path) -> option<Path> {
+fn parse_pp_exact(line: ~str, testfile: &Path) -> Option<Path> {
match parse_name_value_directive(line, ~"pp-exact") {
- option::some(s) => option::some(Path(s)),
- option::none => {
+ option::Some(s) => option::Some(Path(s)),
+ option::None => {
if parse_name_directive(line, ~"pp-exact") {
- option::some(testfile.file_path())
+ option::Some(testfile.file_path())
} else {
- option::none
+ option::None
}
}
}
}
fn parse_name_value_directive(line: ~str,
- directive: ~str) -> option<~str> unsafe {
+ directive: ~str) -> Option<~str> unsafe {
let keycolon = directive + ~":";
match str::find_str(line, keycolon) {
- option::some(colon) => {
+ option::Some(colon) => {
let value = str::slice(line, colon + str::len(keycolon),
str::len(line));
debug!("%s: %s", directive, value);
- option::some(value)
+ option::Some(value)
}
- option::none => option::none
+ option::None => option::None
}
}
prog: ~str,
args: ~[~str],
env: ~[(~str, ~str)],
- input: option<~str>) -> {status: int, out: ~str, err: ~str} {
+ input: Option<~str>) -> {status: int, out: ~str, err: ~str} {
let pipe_in = os::pipe();
let pipe_out = os::pipe();
let pipe_err = os::pipe();
let pid = spawn_process(prog, args,
- &some(env + target_env(lib_path, prog)),
- &none, pipe_in.in, pipe_out.out, pipe_err.out);
+ &Some(env + target_env(lib_path, prog)),
+ &None, pipe_in.in, pipe_out.out, pipe_err.out);
os::close(pipe_in.in);
os::close(pipe_out.out);
return {status: status, out: outs, err: errs};
}
-fn writeclose(fd: c_int, s: option<~str>) {
+fn writeclose(fd: c_int, s: Option<~str>) {
if option::is_some(s) {
let writer = io::fd_writer(fd, false);
writer.write_str(option::get(s));
} else { logv(config, ~"testing for converging pretty-printing"); }
let rounds =
- match props.pp_exact { option::some(_) => 1, option::none => 2 };
+ match props.pp_exact { option::Some(_) => 1, option::None => 2 };
let mut srcs = ~[result::get(io::read_whole_file_str(testfile))];
let mut expected =
match props.pp_exact {
- option::some(file) => {
+ option::Some(file) => {
let filepath = testfile.dir_path().push_rel(&file);
result::get(io::read_whole_file_str(&filepath))
}
- option::none => { srcs[vec::len(srcs) - 2u] }
+ option::None => { srcs[vec::len(srcs) - 2u] }
};
let mut actual = srcs[vec::len(srcs) - 1u];
fn print_source(config: config, testfile: &Path, src: ~str) -> procres {
compose_and_run(config, testfile, make_pp_args(config, testfile),
- ~[], config.compile_lib_path, option::some(src))
+ ~[], config.compile_lib_path, option::Some(src))
}
fn make_pp_args(config: config, _testfile: &Path) -> procargs {
compose_and_run_compiler(
config, props, testfile,
make_typecheck_args(config, testfile),
- option::some(src))
+ option::Some(src))
}
fn make_typecheck_args(config: config, testfile: &Path) -> procargs {
config, props, testfile,
make_compile_args(config, props, link_args,
make_exe_name, testfile),
- none)
+ None)
}
fn exec_compiled_test(config: config, props: test_props,
compose_and_run(config, testfile,
make_run_args(config, props, testfile),
props.exec_env,
- config.run_lib_path, option::none)
+ config.run_lib_path, option::None)
}
fn compose_and_run_compiler(
props: test_props,
testfile: &Path,
args: procargs,
- input: option<~str>) -> procres {
+ input: Option<~str>) -> procres {
if props.aux_builds.is_not_empty() {
ensure_dir(&aux_output_dir_name(config, testfile));
make_compile_args(config, props, ~[~"--lib"] + extra_link_args,
|a,b| make_lib_name(a, b, testfile), &abs_ab);
let auxres = compose_and_run(config, &abs_ab, aux_args, ~[],
- config.compile_lib_path, option::none);
+ config.compile_lib_path, option::None);
if auxres.status != 0 {
fatal_procres(
fmt!("auxiliary build of %s failed to compile: ",
procargs: procargs,
procenv: ~[(~str, ~str)],
lib_path: ~str,
- input: option<~str>) -> procres {
+ input: Option<~str>) -> procres {
return program_output(config, testfile, lib_path,
procargs.prog, procargs.args, procenv, input);
}
// then split apart its command
let runtool =
match config.runtool {
- option::some(s) => option::some(s),
- option::none => option::none
+ option::Some(s) => option::Some(s),
+ option::None => option::None
};
split_maybe_args(runtool)
};
return {prog: args[0], args: vec::slice(args, 1u, vec::len(args))};
}
-fn split_maybe_args(argstr: option<~str>) -> ~[~str] {
+fn split_maybe_args(argstr: Option<~str>) -> ~[~str] {
fn rm_whitespace(v: ~[~str]) -> ~[~str] {
- fn flt(&&s: ~str) -> option<~str> {
- if !str::is_whitespace(s) { option::some(s) } else { option::none }
+ fn flt(&&s: ~str) -> Option<~str> {
+ if !str::is_whitespace(s) { option::Some(s) } else { option::None }
}
vec::filter_map(v, flt)
}
match argstr {
- option::some(s) => rm_whitespace(str::split_char(s, ' ')),
- option::none => ~[]
+ option::Some(s) => rm_whitespace(str::split_char(s, ' ')),
+ option::None => ~[]
}
}
fn program_output(config: config, testfile: &Path, lib_path: ~str, prog: ~str,
args: ~[~str], env: ~[(~str, ~str)],
- input: option<~str>) -> procres {
+ input: Option<~str>) -> procres {
let cmdline =
{
let cmdline = make_cmdline(lib_path, prog, args);
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
match getenv(lib_path_env_var()) {
- option::some(curr) => {
+ option::Some(curr) => {
fmt!("%s%s%s", path, path_div(), curr)
}
- option::none => path
+ option::None => path
}
}
}
fn find_rust_files(files: &mut ~[Path], path: &Path) {
- if path.filetype() == some(~"rs") && !contains(path.to_str(), ~"utf8") {
+ if path.filetype() == Some(~"rs") && !contains(path.to_str(), ~"utf8") {
// ignoring "utf8" tests because something is broken
vec::push(*files, *path);
} else if os::path_is_dir(path)
{ node: l, span: ast_util::dummy_sp() }
}
- ~[dse(ast::expr_break(option::none)),
- dse(ast::expr_again(option::none)),
- dse(ast::expr_fail(option::none)),
- dse(ast::expr_fail(option::some(
+ ~[dse(ast::expr_break(option::None)),
+ dse(ast::expr_again(option::None)),
+ dse(ast::expr_fail(option::None)),
+ dse(ast::expr_fail(option::Some(
@dse(ast::expr_lit(@dsl(ast::lit_str(@~"boo"))))))),
- dse(ast::expr_ret(option::none)),
+ dse(ast::expr_ret(option::None)),
dse(ast::expr_lit(@dsl(ast::lit_nil))),
dse(ast::expr_lit(@dsl(ast::lit_bool(false)))),
dse(ast::expr_lit(@dsl(ast::lit_bool(true)))),
ast::expr_binary(*) | ast::expr_assign(*) |
ast::expr_assign_op(*) => { false }
- ast::expr_fail(option::none) |
- ast::expr_ret(option::none) => { false }
+ ast::expr_fail(option::None) |
+ ast::expr_ret(option::None) => { false }
// https://github.com/mozilla/rust/issues/953
- ast::expr_fail(option::some(_)) => { false }
+ ast::expr_fail(option::Some(_)) => { false }
// https://github.com/mozilla/rust/issues/928
//ast::expr_cast(_, _) { false }
let crate2 = @replacer(crate, i, things[j], cx.mode);
// It would be best to test the *crate* for stability, but
// testing the string for stability is easier and ok for now.
- let handler = diagnostic::mk_handler(none);
+ let handler = diagnostic::mk_handler(None);
let str3 = do io::with_str_reader("") |rdr| {
@as_str(|a|pprust::print_crate(
codemap,
fn parse_and_print(code: @~str) -> ~str {
let filename = Path("tmp.rs");
- let sess = parse::new_parse_sess(option::none);
+ let sess = parse::new_parse_sess(option::None);
write_file(&filename, *code);
let crate = parse::parse_crate_from_source_str(
filename.to_str(), code, ~[], sess);
}
log(error, ~"check_variants: " + file.to_str());
- let sess = parse::new_parse_sess(option::none);
+ let sess = parse::new_parse_sess(option::None);
let crate =
parse::parse_crate_from_source_str(
file.to_str(),
* onto the vector being constructed.
*/
#[inline(always)]
-pure fn build_sized_opt<A>(size: option<uint>,
+pure fn build_sized_opt<A>(size: Option<uint>,
builder: fn(push: pure fn(+A))) -> @[A] {
build_sized(size.get_default(4), builder)
}
pure fn is_false(v: bool) -> bool { !v }
/// Parse logic value from `s`
-pure fn from_str(s: &str) -> option<bool> {
+pure fn from_str(s: &str) -> Option<bool> {
if s == "true" {
- some(true)
+ Some(true)
} else if s == "false" {
- some(false)
+ Some(false)
} else {
- none
+ None
}
}
#[test]
fn test_bool_from_str() {
do all_values |v| {
- assert some(v) == from_str(bool::to_str(v))
+ assert Some(v) == from_str(bool::to_str(v))
}
}
* 'b' or 'B', 11, etc. Returns none if the char does not
* refer to a digit in the given radix.
*/
-pure fn to_digit(c: char, radix: uint) -> option<uint> {
+pure fn to_digit(c: char, radix: uint) -> Option<uint> {
let val = match c {
'0' to '9' => c as uint - ('0' as uint),
'a' to 'z' => c as uint + 10u - ('a' as uint),
'A' to 'Z' => c as uint + 10u - ('A' as uint),
- _ => return none
+ _ => return None
};
- if val < radix { some(val) }
- else { none }
+ if val < radix { Some(val) }
+ else { None }
}
/**
#[test]
fn test_to_digit() {
- assert to_digit('0', 10u) == some(0u);
- assert to_digit('1', 2u) == some(1u);
- assert to_digit('2', 3u) == some(2u);
- assert to_digit('9', 10u) == some(9u);
- assert to_digit('a', 16u) == some(10u);
- assert to_digit('A', 16u) == some(10u);
- assert to_digit('b', 16u) == some(11u);
- assert to_digit('B', 16u) == some(11u);
- assert to_digit('z', 36u) == some(35u);
- assert to_digit('Z', 36u) == some(35u);
+ assert to_digit('0', 10u) == Some(0u);
+ assert to_digit('1', 2u) == Some(1u);
+ assert to_digit('2', 3u) == Some(2u);
+ assert to_digit('9', 10u) == Some(9u);
+ assert to_digit('a', 16u) == Some(10u);
+ assert to_digit('A', 16u) == Some(10u);
+ assert to_digit('b', 16u) == Some(11u);
+ assert to_digit('B', 16u) == Some(11u);
+ assert to_digit('z', 36u) == Some(35u);
+ assert to_digit('Z', 36u) == Some(35u);
- assert to_digit(' ', 10u) == none;
- assert to_digit('$', 36u) == none;
+ assert to_digit(' ', 10u) == None;
+ assert to_digit('$', 36u) == None;
}
#[test]
// Export various ubiquitous types, constructors, methods.
-import option::{some, none};
-import option = option::option;
+import option::{Some, None};
+import Option = option::Option;
+// XXX: snapshot rustc is generating code that wants lower-case option
+#[cfg(stage0)]
+import option = option::Option;
import Path = path2::Path;
import GenericPath = path2::GenericPath;
import to_str::ToStr;
export Path, WindowsPath, PosixPath, GenericPath;
-export option, some, none, unreachable;
+export Option, Some, None, unreachable;
export extensions;
// The following exports are the extension impls for numeric types
export Num, Times, TimesIx;
export DList, dlist, dlist_node;
export new_dlist, from_elem, from_vec, extensions;
-type DListLink<T> = option<DListNode<T>>;
+type DListLink<T> = Option<DListNode<T>>;
enum DListNode<T> = @{
data: T,
priv impl<T> DListNode<T> {
pure fn assert_links() {
match self.next {
- some(neighbour) => match neighbour.prev {
- some(me) => if !box::ptr_eq(*self, *me) {
+ Some(neighbour) => match neighbour.prev {
+ Some(me) => if !box::ptr_eq(*self, *me) {
fail ~"Asymmetric next-link in dlist node."
},
- none => fail ~"One-way next-link in dlist node."
+ None => fail ~"One-way next-link in dlist node."
},
- none => ()
+ None => ()
}
match self.prev {
- some(neighbour) => match neighbour.next {
- some(me) => if !box::ptr_eq(*me, *self) {
+ Some(neighbour) => match neighbour.next {
+ Some(me) => if !box::ptr_eq(*me, *self) {
fail ~"Asymmetric prev-link in dlist node."
},
- none => fail ~"One-way prev-link in dlist node."
+ None => fail ~"One-way prev-link in dlist node."
},
- none => ()
+ None => ()
}
}
}
impl<T> DListNode<T> {
/// Get the next node in the list, if there is one.
- pure fn next_link() -> option<DListNode<T>> {
+ pure fn next_link() -> Option<DListNode<T>> {
self.assert_links();
self.next
}
/// Get the next node in the list, failing if there isn't one.
pure fn next_node() -> DListNode<T> {
match self.next_link() {
- some(nobe) => nobe,
- none => fail ~"This dlist node has no next neighbour."
+ Some(nobe) => nobe,
+ None => fail ~"This dlist node has no next neighbour."
}
}
/// Get the previous node in the list, if there is one.
- pure fn prev_link() -> option<DListNode<T>> {
+ pure fn prev_link() -> Option<DListNode<T>> {
self.assert_links();
self.prev
}
/// Get the previous node in the list, failing if there isn't one.
pure fn prev_node() -> DListNode<T> {
match self.prev_link() {
- some(nobe) => nobe,
- none => fail ~"This dlist node has no previous neighbour."
+ Some(nobe) => nobe,
+ None => fail ~"This dlist node has no previous neighbour."
}
}
}
/// Creates a new dlist node with the given data.
pure fn new_dlist_node<T>(+data: T) -> DListNode<T> {
DListNode(@{data: data, mut linked: false,
- mut prev: none, mut next: none})
+ mut prev: None, mut next: None})
}
/// Creates a new, empty dlist.
pure fn new_dlist<T>() -> DList<T> {
- DList(@{mut size: 0, mut hd: none, mut tl: none})
+ DList(@{mut size: 0, mut hd: None, mut tl: None})
}
/// Creates a new dlist with a single element
priv impl<T> DList<T> {
pure fn new_link(-data: T) -> DListLink<T> {
- some(DListNode(@{data: data, mut linked: true,
- mut prev: none, mut next: none}))
+ Some(DListNode(@{data: data, mut linked: true,
+ mut prev: None, mut next: None}))
}
pure fn assert_mine(nobe: DListNode<T>) {
// These asserts could be stronger if we had node-root back-pointers,
#[inline(always)]
fn link(+before: DListLink<T>, +after: DListLink<T>) {
match before {
- some(neighbour) => neighbour.next = after,
- none => self.hd = after
+ Some(neighbour) => neighbour.next = after,
+ None => self.hd = after
}
match after {
- some(neighbour) => neighbour.prev = before,
- none => self.tl = before
+ Some(neighbour) => neighbour.prev = before,
+ None => self.tl = before
}
}
// Remove a node from the list.
self.assert_mine(nobe);
assert self.size > 0;
self.link(nobe.prev, nobe.next);
- nobe.prev = none; // Release extraneous references.
- nobe.next = none;
+ nobe.prev = None; // Release extraneous references.
+ nobe.next = None;
nobe.linked = false;
self.size -= 1;
}
self.assert_mine(neighbour);
assert self.size > 0;
self.link(neighbour.prev, nobe);
- self.link(nobe, some(neighbour));
+ self.link(nobe, Some(neighbour));
self.size += 1;
}
fn insert_right(neighbour: DListNode<T>, nobe: DListLink<T>) {
self.assert_mine(neighbour);
assert self.size > 0;
self.link(nobe, neighbour.next);
- self.link(some(neighbour), nobe);
+ self.link(Some(neighbour), nobe);
self.size += 1;
}
}
*/
fn insert_n_before(nobe: DListNode<T>, neighbour: DListNode<T>) {
self.make_mine(nobe);
- self.insert_left(some(nobe), neighbour);
+ self.insert_left(Some(nobe), neighbour);
}
/**
* Insert data in the middle of the list, left of the given node,
*/
fn insert_n_after(nobe: DListNode<T>, neighbour: DListNode<T>) {
self.make_mine(nobe);
- self.insert_right(neighbour, some(nobe));
+ self.insert_right(neighbour, Some(nobe));
}
/**
* Insert data in the middle of the list, right of the given node,
}
/// Remove a node from the head of the list. O(1).
- fn pop_n() -> option<DListNode<T>> {
+ fn pop_n() -> Option<DListNode<T>> {
let hd = self.peek_n();
hd.map(|nobe| self.unlink(nobe));
hd
}
/// Remove a node from the tail of the list. O(1).
- fn pop_tail_n() -> option<DListNode<T>> {
+ fn pop_tail_n() -> Option<DListNode<T>> {
let tl = self.peek_tail_n();
tl.map(|nobe| self.unlink(nobe));
tl
}
/// Get the node at the list's head. O(1).
- pure fn peek_n() -> option<DListNode<T>> { self.hd }
+ pure fn peek_n() -> Option<DListNode<T>> { self.hd }
/// Get the node at the list's tail. O(1).
- pure fn peek_tail_n() -> option<DListNode<T>> { self.tl }
+ pure fn peek_tail_n() -> Option<DListNode<T>> { self.tl }
/// Get the node at the list's head, failing if empty. O(1).
pure fn head_n() -> DListNode<T> {
match self.hd {
- some(nobe) => nobe,
- none => fail ~"Attempted to get the head of an empty dlist."
+ Some(nobe) => nobe,
+ None => fail ~"Attempted to get the head of an empty dlist."
}
}
/// Get the node at the list's tail, failing if empty. O(1).
pure fn tail_n() -> DListNode<T> {
match self.tl {
- some(nobe) => nobe,
- none => fail ~"Attempted to get the tail of an empty dlist."
+ Some(nobe) => nobe,
+ None => fail ~"Attempted to get the tail of an empty dlist."
}
}
self.tl = them.tl;
self.size += them.size;
them.size = 0;
- them.hd = none;
- them.tl = none;
+ them.hd = None;
+ them.tl = None;
}
}
/**
self.hd = them.hd;
self.size += them.size;
them.size = 0;
- them.hd = none;
- them.tl = none;
+ them.hd = None;
+ them.tl = None;
}
}
let next_nobe = nobe.next;
self.remove(nobe);
self.make_mine(nobe);
- self.add_head(some(nobe));
+ self.add_head(Some(nobe));
next_nobe
}
}
impl<T: copy> DList<T> {
/// Remove data from the head of the list. O(1).
- fn pop() -> option<T> { self.pop_n().map (|nobe| nobe.data) }
+ fn pop() -> Option<T> { self.pop_n().map (|nobe| nobe.data) }
/// Remove data from the tail of the list. O(1).
- fn pop_tail() -> option<T> { self.pop_tail_n().map (|nobe| nobe.data) }
+ fn pop_tail() -> Option<T> { self.pop_tail_n().map (|nobe| nobe.data) }
/// Get data at the list's head. O(1).
- pure fn peek() -> option<T> { self.peek_n().map (|nobe| nobe.data) }
+ pure fn peek() -> Option<T> { self.peek_n().map (|nobe| nobe.data) }
/// Get data at the list's tail. O(1).
- pure fn peek_tail() -> option<T> {
+ pure fn peek_tail() -> Option<T> {
self.peek_tail_n().map (|nobe| nobe.data)
}
/// Get data at the list's head, failing if empty. O(1).
l.assert_consistent(); l.remove(two);
l.assert_consistent(); l.remove(three);
l.assert_consistent(); l.remove(one); // Twenty-three is number one!
- l.assert_consistent(); assert l.peek() == none;
+ l.assert_consistent(); assert l.peek() == None;
l.assert_consistent(); assert l.is_empty();
}
#[test]
let l = new_dlist::<int>();
let _one = l.push_n(1);
let two = l.push_n(2);
- two.prev = none;
+ two.prev = None;
l.assert_consistent();
}
#[test] #[should_fail] #[ignore(cfg(windows))]
let one = l.push_n(1);
let _two = l.push_n(2);
let three = l.push_n(3);
- three.next = some(one);
- one.prev = some(three);
+ three.next = Some(one);
+ one.prev = Some(three);
l.assert_consistent();
}
#[test] #[should_fail] #[ignore(cfg(windows))]
*
* The reason that I did not use an unsafe pointer in the structure
* itself is that I wanted to ensure that the vector would be freed when
- * the dvec is dropped. The reason that I did not use an `option<T>`
+ * the dvec is dropped. The reason that I did not use an `Option<T>`
* instead of a nullable pointer is that I found experimentally that it
* becomes approximately 50% slower. This can probably be improved
* through optimization. You can run your own experiments using
do self.swap |v| {
let mut v = match ts.size_hint() {
none { v }
- some(h) {
+ Some(h) {
let len = v.len() + h;
let mut v <- v;
vec::reserve(v, len);
*/
-import option::{some, none};
+import option::{Some, None};
/*
// A formatted conversion from an expression to a string
type conv =
- {param: option<int>,
+ {param: Option<int>,
flags: ~[flag],
width: count,
precision: count,
return pieces;
}
fn peek_num(s: ~str, i: uint, lim: uint) ->
- option<{num: uint, next: uint}> {
+ Option<{num: uint, next: uint}> {
let mut j = i;
let mut accum = 0u;
let mut found = false;
while j < lim {
match char::to_digit(s[j] as char, 10) {
- some(x) => {
+ Some(x) => {
found = true;
accum *= 10;
accum += x;
j += 1;
},
- none => break
+ None => break
}
}
if found {
- some({num: accum, next: j})
+ Some({num: accum, next: j})
} else {
- none
+ None
}
}
fn parse_conversion(s: ~str, i: uint, lim: uint, error: error_fn) ->
next: ty.next};
}
fn parse_parameter(s: ~str, i: uint, lim: uint) ->
- {param: option<int>, next: uint} {
- if i >= lim { return {param: none, next: i}; }
+ {param: Option<int>, next: uint} {
+ if i >= lim { return {param: None, next: i}; }
let num = peek_num(s, i, lim);
return match num {
- none => {param: none, next: i},
- some(t) => {
+ None => {param: None, next: i},
+ Some(t) => {
let n = t.num;
let j = t.next;
if j < lim && s[j] == '$' as u8 {
- {param: some(n as int), next: j + 1u}
- } else { {param: none, next: i} }
+ {param: Some(n as int), next: j + 1u}
+ } else { {param: None, next: i} }
}
};
}
let param = parse_parameter(s, i + 1u, lim);
let j = param.next;
match param.param {
- none => {count: count_is_next_param, next: j},
- some(n) => {count: count_is_param(n), next: j}
+ None => {count: count_is_next_param, next: j},
+ Some(n) => {count: count_is_param(n), next: j}
}
} else {
let num = peek_num(s, i, lim);
match num {
- none => {count: count_implied, next: i},
- some(num) => {
+ None => {count: count_implied, next: i},
+ Some(num) => {
count: count_is(num.num as int),
next: num.next
}
* # Return value
*
* `none` if the string did not represent a valid number. Otherwise,
- * `some(n)` where `n` is the floating-point number represented by `[num]`.
+ * `Some(n)` where `n` is the floating-point number represented by `[num]`.
*/
-fn from_str(num: &str) -> option<float> {
+fn from_str(num: &str) -> Option<float> {
if num == "inf" {
- return some(infinity as float);
+ return Some(infinity as float);
} else if num == "-inf" {
- return some(neg_infinity as float);
+ return Some(neg_infinity as float);
} else if num == "NaN" {
- return some(NaN as float);
+ return Some(NaN as float);
}
let mut pos = 0u; //Current byte position in the string.
//Used to walk the string in O(n).
let len = str::len(num); //Length of the string, in bytes.
- if len == 0u { return none; }
+ if len == 0u { return None; }
let mut total = 0f; //Accumulated result
let mut c = 'z'; //Latest char.
//The string must start with one of the following characters.
match str::char_at(num, 0u) {
'-' | '+' | '0' to '9' | '.' => (),
- _ => return none
+ _ => return None
}
//Determine if first char is '-'/'+'. Set [pos] and [neg] accordingly.
total += ((c as int) - ('0' as int)) as float;
}
'.' | 'e' | 'E' => break,
- _ => return none
+ _ => return None
}
}
total += (((c as int) - ('0' as int)) as float)*decimal;
}
'e' | 'E' => break,
- _ => return none
+ _ => return None
}
}
}
total = total * multiplier;
}
} else {
- return none;
+ return None;
}
}
if(pos < len) {
- return none;
+ return None;
} else {
if(neg) {
total *= -1f;
}
- return some(total);
+ return Some(total);
}
}
#[test]
fn test_from_str() {
- assert from_str(~"3") == some(3.);
- assert from_str(~"3") == some(3.);
- assert from_str(~"3.14") == some(3.14);
- assert from_str(~"+3.14") == some(3.14);
- assert from_str(~"-3.14") == some(-3.14);
- assert from_str(~"2.5E10") == some(25000000000.);
- assert from_str(~"2.5e10") == some(25000000000.);
- assert from_str(~"25000000000.E-10") == some(2.5);
- assert from_str(~".") == some(0.);
- assert from_str(~".e1") == some(0.);
- assert from_str(~".e-1") == some(0.);
- assert from_str(~"5.") == some(5.);
- assert from_str(~".5") == some(0.5);
- assert from_str(~"0.5") == some(0.5);
- assert from_str(~"0.5") == some(0.5);
- assert from_str(~"0.5") == some(0.5);
- assert from_str(~"-.5") == some(-0.5);
- assert from_str(~"-.5") == some(-0.5);
- assert from_str(~"-5") == some(-5.);
- assert from_str(~"-0") == some(-0.);
- assert from_str(~"0") == some(0.);
- assert from_str(~"inf") == some(infinity);
- assert from_str(~"-inf") == some(neg_infinity);
+ assert from_str(~"3") == Some(3.);
+ assert from_str(~"3") == Some(3.);
+ assert from_str(~"3.14") == Some(3.14);
+ assert from_str(~"+3.14") == Some(3.14);
+ assert from_str(~"-3.14") == Some(-3.14);
+ assert from_str(~"2.5E10") == Some(25000000000.);
+ assert from_str(~"2.5e10") == Some(25000000000.);
+ assert from_str(~"25000000000.E-10") == Some(2.5);
+ assert from_str(~".") == Some(0.);
+ assert from_str(~".e1") == Some(0.);
+ assert from_str(~".e-1") == Some(0.);
+ assert from_str(~"5.") == Some(5.);
+ assert from_str(~".5") == Some(0.5);
+ assert from_str(~"0.5") == Some(0.5);
+ assert from_str(~"0.5") == Some(0.5);
+ assert from_str(~"0.5") == Some(0.5);
+ assert from_str(~"-.5") == Some(-0.5);
+ assert from_str(~"-.5") == Some(-0.5);
+ assert from_str(~"-5") == Some(-5.);
+ assert from_str(~"-0") == Some(-0.);
+ assert from_str(~"0") == Some(0.);
+ assert from_str(~"inf") == Some(infinity);
+ assert from_str(~"-inf") == Some(neg_infinity);
// note: NaN != NaN, hence this slightly complex test
match from_str(~"NaN") {
- some(f) => assert is_NaN(f),
- none => fail
+ Some(f) => assert is_NaN(f),
+ None => fail
}
- assert from_str(~"") == none;
- assert from_str(~"x") == none;
- assert from_str(~" ") == none;
- assert from_str(~" ") == none;
- assert from_str(~"e") == none;
- assert from_str(~"E") == none;
- assert from_str(~"E1") == none;
- assert from_str(~"1e1e1") == none;
- assert from_str(~"1e1.1") == none;
- assert from_str(~"1e1-1") == none;
+ assert from_str(~"") == None;
+ assert from_str(~"x") == None;
+ assert from_str(~" ") == None;
+ assert from_str(~" ") == None;
+ assert from_str(~"e") == None;
+ assert from_str(~"E") == None;
+ assert from_str(~"E1") == None;
+ assert from_str(~"1e1e1") == None;
+ assert from_str(~"1e1.1") == None;
+ assert from_str(~"1e1-1") == None;
}
#[test]
* waiting for the result to be received on the port.
*/
- let port = ~mut some(port);
+ let port = ~mut Some(port);
do from_fn |move port| {
- let mut port_ = none;
+ let mut port_ = None;
port_ <-> *port;
let port = option::unwrap(port_);
match recv(port) {
* * buf - A byte buffer
* * radix - The base of the number
*/
-fn parse_buf(buf: ~[u8], radix: uint) -> option<T> {
- if vec::len(buf) == 0u { return none; }
+fn parse_buf(buf: ~[u8], radix: uint) -> Option<T> {
+ if vec::len(buf) == 0u { return None; }
let mut i = vec::len(buf) - 1u;
let mut start = 0u;
let mut power = 1 as T;
let mut n = 0 as T;
loop {
match char::to_digit(buf[i] as char, radix) {
- some(d) => n += (d as T) * power,
- none => return none
+ Some(d) => n += (d as T) * power,
+ None => return None
}
power *= radix as T;
- if i <= start { return some(n); }
+ if i <= start { return Some(n); }
i -= 1u;
};
}
/// Parse a string to an int
-fn from_str(s: ~str) -> option<T> { parse_buf(str::to_bytes(s), 10u) }
+fn from_str(s: ~str) -> Option<T> { parse_buf(str::to_bytes(s), 10u) }
/// Convert to a string in a given base
fn to_str(n: T, radix: uint) -> ~str {
#[test]
#[ignore]
fn test_from_str() {
- assert from_str(~"0") == some(0 as T);
- assert from_str(~"3") == some(3 as T);
- assert from_str(~"10") == some(10 as T);
- assert from_str(~"123456789") == some(123456789 as T);
- assert from_str(~"00100") == some(100 as T);
-
- assert from_str(~"-1") == some(-1 as T);
- assert from_str(~"-3") == some(-3 as T);
- assert from_str(~"-10") == some(-10 as T);
- assert from_str(~"-123456789") == some(-123456789 as T);
- assert from_str(~"-00100") == some(-100 as T);
-
- assert from_str(~" ") == none;
- assert from_str(~"x") == none;
+ assert from_str(~"0") == Some(0 as T);
+ assert from_str(~"3") == Some(3 as T);
+ assert from_str(~"10") == Some(10 as T);
+ assert from_str(~"123456789") == Some(123456789 as T);
+ assert from_str(~"00100") == Some(100 as T);
+
+ assert from_str(~"-1") == Some(-1 as T);
+ assert from_str(~"-3") == Some(-3 as T);
+ assert from_str(~"-10") == Some(-10 as T);
+ assert from_str(~"-123456789") == Some(-123456789 as T);
+ assert from_str(~"-00100") == Some(-100 as T);
+
+ assert from_str(~" ") == None;
+ assert from_str(~"x") == None;
}
// FIXME: Has alignment issues on windows and 32-bit linux (#2609)
#[ignore]
fn test_parse_buf() {
import str::to_bytes;
- assert parse_buf(to_bytes(~"123"), 10u) == some(123 as T);
- assert parse_buf(to_bytes(~"1001"), 2u) == some(9 as T);
- assert parse_buf(to_bytes(~"123"), 8u) == some(83 as T);
- assert parse_buf(to_bytes(~"123"), 16u) == some(291 as T);
- assert parse_buf(to_bytes(~"ffff"), 16u) == some(65535 as T);
- assert parse_buf(to_bytes(~"FFFF"), 16u) == some(65535 as T);
- assert parse_buf(to_bytes(~"z"), 36u) == some(35 as T);
- assert parse_buf(to_bytes(~"Z"), 36u) == some(35 as T);
-
- assert parse_buf(to_bytes(~"-123"), 10u) == some(-123 as T);
- assert parse_buf(to_bytes(~"-1001"), 2u) == some(-9 as T);
- assert parse_buf(to_bytes(~"-123"), 8u) == some(-83 as T);
- assert parse_buf(to_bytes(~"-123"), 16u) == some(-291 as T);
- assert parse_buf(to_bytes(~"-ffff"), 16u) == some(-65535 as T);
- assert parse_buf(to_bytes(~"-FFFF"), 16u) == some(-65535 as T);
- assert parse_buf(to_bytes(~"-z"), 36u) == some(-35 as T);
- assert parse_buf(to_bytes(~"-Z"), 36u) == some(-35 as T);
-
- assert parse_buf(to_bytes(~"Z"), 35u) == none;
- assert parse_buf(to_bytes(~"-9"), 2u) == none;
+ assert parse_buf(to_bytes(~"123"), 10u) == Some(123 as T);
+ assert parse_buf(to_bytes(~"1001"), 2u) == Some(9 as T);
+ assert parse_buf(to_bytes(~"123"), 8u) == Some(83 as T);
+ assert parse_buf(to_bytes(~"123"), 16u) == Some(291 as T);
+ assert parse_buf(to_bytes(~"ffff"), 16u) == Some(65535 as T);
+ assert parse_buf(to_bytes(~"FFFF"), 16u) == Some(65535 as T);
+ assert parse_buf(to_bytes(~"z"), 36u) == Some(35 as T);
+ assert parse_buf(to_bytes(~"Z"), 36u) == Some(35 as T);
+
+ assert parse_buf(to_bytes(~"-123"), 10u) == Some(-123 as T);
+ assert parse_buf(to_bytes(~"-1001"), 2u) == Some(-9 as T);
+ assert parse_buf(to_bytes(~"-123"), 8u) == Some(-83 as T);
+ assert parse_buf(to_bytes(~"-123"), 16u) == Some(-291 as T);
+ assert parse_buf(to_bytes(~"-ffff"), 16u) == Some(-65535 as T);
+ assert parse_buf(to_bytes(~"-FFFF"), 16u) == Some(-65535 as T);
+ assert parse_buf(to_bytes(~"-z"), 36u) == Some(-35 as T);
+ assert parse_buf(to_bytes(~"-Z"), 36u) == Some(-35 as T);
+
+ assert parse_buf(to_bytes(~"Z"), 35u) == None;
+ assert parse_buf(to_bytes(~"-9"), 2u) == None;
}
#[test]
new(-arg: Arg<t>) { self.arg <- arg; }
drop {
match self.arg.opt_level {
- option::none => (),
- option::some(level) => {
+ option::None => (),
+ option::Some(level) => {
// fail hard if not succesful
assert(self.arg.fsync_fn(self.arg.val, level) != -1);
}
type Arg<t> = {
val: t,
- opt_level: option<Level>,
+ opt_level: Option<Level>,
fsync_fn: fn@(t, Level) -> int
};
// fsync file after executing blk
// FIXME (#2004) find better way to create resources within lifetime of
// outer res
- fn FILE_res_sync(&&file: FILERes, opt_level: option<Level>,
+ fn FILE_res_sync(&&file: FILERes, opt_level: Option<Level>,
blk: fn(&&Res<*libc::FILE>)) {
blk(Res({
val: file.f, opt_level: opt_level,
}
// fsync fd after executing blk
- fn fd_res_sync(&&fd: FdRes, opt_level: option<Level>,
+ fn fd_res_sync(&&fd: FdRes, opt_level: Option<Level>,
blk: fn(&&Res<fd_t>)) {
blk(Res({
val: fd.fd, opt_level: opt_level,
trait FSyncable { fn fsync(l: Level) -> int; }
// Call o.fsync after executing blk
- fn obj_sync(&&o: FSyncable, opt_level: option<Level>,
+ fn obj_sync(&&o: FSyncable, opt_level: Option<Level>,
blk: fn(&&Res<FSyncable>)) {
blk(Res({
val: o, opt_level: opt_level,
impl<A> IMPL_T<A>: iter::BaseIter<A> {
pure fn each(blk: fn(A) -> bool) { EACH(self, blk) }
- pure fn size_hint() -> option<uint> { SIZE_HINT(self) }
+ pure fn size_hint() -> Option<uint> { SIZE_HINT(self) }
}
impl<A> IMPL_T<A>: iter::ExtendedIter<A> {
}
pure fn contains(x: A) -> bool { iter::contains(self, x) }
pure fn count(x: A) -> uint { iter::count(self, x) }
- pure fn position(f: fn(A) -> bool) -> option<uint> {
+ pure fn position(f: fn(A) -> bool) -> Option<uint> {
iter::position(self, f)
}
}
pure fn min() -> A { iter::min(self) }
pure fn max() -> A { iter::max(self) }
- pure fn find(p: fn(A) -> bool) -> option<A> { iter::find(self, p) }
+ pure fn find(p: fn(A) -> bool) -> Option<A> { iter::find(self, p) }
}
}
}
-pure fn SIZE_HINT<A>(self: IMPL_T<A>) -> option<uint> {
- some(self.len())
+pure fn SIZE_HINT<A>(self: IMPL_T<A>) -> Option<uint> {
+ Some(self.len())
}
unsafe { self.swap(|v| { vec::each(v, f); v }) }
}
-pure fn SIZE_HINT<A>(self: IMPL_T<A>) -> option<uint> {
- some(self.len())
+pure fn SIZE_HINT<A>(self: IMPL_T<A>) -> Option<uint> {
+ Some(self.len())
}
-type IMPL_T<A> = option<A>;
+type IMPL_T<A> = Option<A>;
pure fn EACH<A>(self: IMPL_T<A>, f: fn(A) -> bool) {
match self {
- none => (),
- some(a) => { f(a); }
+ None => (),
+ Some(a) => { f(a); }
}
}
-pure fn SIZE_HINT<A>(self: IMPL_T<A>) -> option<uint> {
+pure fn SIZE_HINT<A>(self: IMPL_T<A>) -> Option<uint> {
match self {
- none => some(0u),
- some(_) => some(1u)
+ None => Some(0u),
+ Some(_) => Some(1u)
}
}
trait BaseIter<A> {
pure fn each(blk: fn(A) -> bool);
- pure fn size_hint() -> option<uint>;
+ pure fn size_hint() -> Option<uint>;
}
trait ExtendedIter<A> {
pure fn foldl<B>(+b0: B, blk: fn(B, A) -> B) -> B;
pure fn contains(x: A) -> bool;
pure fn count(x: A) -> uint;
- pure fn position(f: fn(A) -> bool) -> option<uint>;
+ pure fn position(f: fn(A) -> bool) -> Option<uint>;
}
trait Times {
pure fn to_vec() -> ~[A];
pure fn min() -> A;
pure fn max() -> A;
- pure fn find(p: fn(A) -> bool) -> option<A>;
+ pure fn find(p: fn(A) -> bool) -> Option<A>;
}
// A trait for sequences that can be by imperatively pushing elements
}
pure fn position<A,IA:BaseIter<A>>(self: IA, f: fn(A) -> bool)
- -> option<uint> {
+ -> Option<uint> {
let mut i = 0;
for self.each |a| {
- if f(a) { return some(i); }
+ if f(a) { return Some(i); }
i += 1;
}
- return none;
+ return None;
}
// note: 'rposition' would only make sense to provide with a bidirectional
}
pure fn min<A:copy,IA:BaseIter<A>>(self: IA) -> A {
- match do foldl::<A,option<A>,IA>(self, none) |a, b| {
+ match do foldl::<A,Option<A>,IA>(self, None) |a, b| {
match a {
- some(a_) if a_ < b => {
+ Some(a_) if a_ < b => {
// FIXME (#2005): Not sure if this is successfully optimized to
// a move
a
}
- _ => some(b)
+ _ => Some(b)
}
} {
- some(val) => val,
- none => fail ~"min called on empty iterator"
+ Some(val) => val,
+ None => fail ~"min called on empty iterator"
}
}
pure fn max<A:copy,IA:BaseIter<A>>(self: IA) -> A {
- match do foldl::<A,option<A>,IA>(self, none) |a, b| {
+ match do foldl::<A,Option<A>,IA>(self, None) |a, b| {
match a {
- some(a_) if a_ > b => {
+ Some(a_) if a_ > b => {
// FIXME (#2005): Not sure if this is successfully optimized to
// a move.
a
}
- _ => some(b)
+ _ => Some(b)
}
} {
- some(val) => val,
- none => fail ~"max called on empty iterator"
+ Some(val) => val,
+ None => fail ~"max called on empty iterator"
}
}
pure fn find<A: copy,IA:BaseIter<A>>(self: IA,
- p: fn(A) -> bool) -> option<A> {
+ p: fn(A) -> bool) -> Option<A> {
for self.each |i| {
- if p(i) { return some(i) }
+ if p(i) { return Some(i) }
}
- return none;
+ return None;
}
// Some functions for just building
*/
#[inline(always)]
pure fn build_sized_opt<A,B: Buildable<A>>(
- size: option<uint>,
+ size: Option<uint>,
builder: fn(push: pure fn(+A))) -> B {
build_sized(size.get_default(4), builder)
#[test]
fn test_filter_map() {
- fn negativate_the_evens(&&i: int) -> option<int> {
+ fn negativate_the_evens(&&i: int) -> Option<int> {
if i % 2 == 0 {
- some(-i)
+ Some(-i)
} else {
none
}
#[test]
fn test_flat_map_with_option() {
- fn if_even(&&i: int) -> option<int> {
- if (i % 2) == 0 { some(i) }
+ fn if_even(&&i: int) -> Option<int> {
+ if (i % 2) == 0 { Some(i) }
else { none }
}
*
* Type `option` represents an optional value.
*
- * Every `option<T>` value can either be `some(T)` or `none`. Where in other
+ * Every `Option<T>` value can either be `Some(T)` or `none`. Where in other
* languages you might use a nullable type, in Rust you would use an option
* type.
*/
/// The option type
-enum option<T> {
- none,
- some(T),
+enum Option<T> {
+ None,
+ Some(T),
}
-pure fn get<T: copy>(opt: option<T>) -> T {
+pure fn get<T: copy>(opt: Option<T>) -> T {
/*!
* Gets the value out of an option
*
*/
match opt {
- some(x) => return x,
- none => fail ~"option::get none"
+ Some(x) => return x,
+ None => fail ~"option::get none"
}
}
-pure fn get_ref<T>(opt: &r/option<T>) -> &r/T {
+pure fn get_ref<T>(opt: &r/Option<T>) -> &r/T {
/*!
* Gets an immutable reference to the value inside an option.
*
* Fails if the value equals `none`
*/
match *opt {
- some(ref x) => x,
- none => fail ~"option::get_ref none"
+ Some(ref x) => x,
+ None => fail ~"option::get_ref none"
}
}
-pure fn expect<T: copy>(opt: option<T>, reason: ~str) -> T {
+pure fn expect<T: copy>(opt: Option<T>, reason: ~str) -> T {
/*!
* Gets the value out of an option, printing a specified message on
* failure
*
* Fails if the value equals `none`
*/
- match opt { some(x) => x, none => fail reason }
+ match opt { Some(x) => x, None => fail reason }
}
-pure fn map<T, U>(opt: option<T>, f: fn(T) -> U) -> option<U> {
+pure fn map<T, U>(opt: Option<T>, f: fn(T) -> U) -> Option<U> {
//! Maps a `some` value from one type to another
- match opt { some(x) => some(f(x)), none => none }
+ match opt { Some(x) => Some(f(x)), None => None }
}
-pure fn map_ref<T, U>(opt: &option<T>, f: fn(x: &T) -> U) -> option<U> {
+pure fn map_ref<T, U>(opt: &Option<T>, f: fn(x: &T) -> U) -> Option<U> {
//! Maps a `some` value by reference from one type to another
- match *opt { some(ref x) => some(f(x)), none => none }
+ match *opt { Some(ref x) => Some(f(x)), None => None }
}
-pure fn map_consume<T, U>(+opt: option<T>, f: fn(+T) -> U) -> option<U> {
+pure fn map_consume<T, U>(+opt: Option<T>, f: fn(+T) -> U) -> Option<U> {
/*!
* As `map`, but consumes the option and gives `f` ownership to avoid
* copying.
*/
- if opt.is_some() { some(f(option::unwrap(opt))) } else { none }
+ if opt.is_some() { Some(f(option::unwrap(opt))) } else { None }
}
-pure fn chain<T, U>(opt: option<T>, f: fn(T) -> option<U>) -> option<U> {
+pure fn chain<T, U>(opt: Option<T>, f: fn(T) -> Option<U>) -> Option<U> {
/*!
* Update an optional value by optionally running its content through a
* function that returns an option.
*/
- match opt { some(x) => f(x), none => none }
+ match opt { Some(x) => f(x), None => None }
}
-pure fn chain_ref<T, U>(opt: &option<T>,
- f: fn(x: &T) -> option<U>) -> option<U> {
+pure fn chain_ref<T, U>(opt: &Option<T>,
+ f: fn(x: &T) -> Option<U>) -> Option<U> {
/*!
* Update an optional value by optionally running its content by reference
* through a function that returns an option.
*/
- match *opt { some(ref x) => f(x), none => none }
+ match *opt { Some(ref x) => f(x), None => None }
}
-pure fn or<T>(+opta: option<T>, +optb: option<T>) -> option<T> {
+pure fn or<T>(+opta: Option<T>, +optb: Option<T>) -> Option<T> {
/*!
* Returns the leftmost some() value, or none if both are none.
*/
match opta {
- some(_) => opta,
+ Some(_) => opta,
_ => optb
}
}
#[inline(always)]
-pure fn while_some<T>(+x: option<T>, blk: fn(+T) -> option<T>) {
+pure fn while_some<T>(+x: Option<T>, blk: fn(+T) -> Option<T>) {
//! Applies a function zero or more times until the result is none.
let mut opt <- x;
}
}
-pure fn is_none<T>(opt: option<T>) -> bool {
+pure fn is_none<T>(opt: Option<T>) -> bool {
//! Returns true if the option equals `none`
- match opt { none => true, some(_) => false }
+ match opt { None => true, Some(_) => false }
}
-pure fn is_some<T>(opt: option<T>) -> bool {
+pure fn is_some<T>(opt: Option<T>) -> bool {
//! Returns true if the option contains some value
!is_none(opt)
}
-pure fn get_default<T: copy>(opt: option<T>, def: T) -> T {
+pure fn get_default<T: copy>(opt: Option<T>, def: T) -> T {
//! Returns the contained value or a default
- match opt { some(x) => x, none => def }
+ match opt { Some(x) => x, None => def }
}
-pure fn map_default<T, U>(opt: option<T>, +def: U, f: fn(T) -> U) -> U {
+pure fn map_default<T, U>(opt: Option<T>, +def: U, f: fn(T) -> U) -> U {
//! Applies a function to the contained value or returns a default
- match opt { none => def, some(t) => f(t) }
+ match opt { None => def, Some(t) => f(t) }
}
// This should replace map_default.
-pure fn map_default_ref<T, U>(opt: &option<T>, +def: U,
+pure fn map_default_ref<T, U>(opt: &Option<T>, +def: U,
f: fn(x: &T) -> U) -> U {
//! Applies a function to the contained value or returns a default
- match *opt { none => def, some(ref t) => f(t) }
+ match *opt { None => def, Some(ref t) => f(t) }
}
// This should change to by-copy mode; use iter_ref below for by reference
-pure fn iter<T>(opt: option<T>, f: fn(T)) {
+pure fn iter<T>(opt: Option<T>, f: fn(T)) {
//! Performs an operation on the contained value or does nothing
- match opt { none => (), some(t) => f(t) }
+ match opt { None => (), Some(t) => f(t) }
}
-pure fn iter_ref<T>(opt: &option<T>, f: fn(x: &T)) {
+pure fn iter_ref<T>(opt: &Option<T>, f: fn(x: &T)) {
//! Performs an operation on the contained value by reference
- match *opt { none => (), some(ref t) => f(t) }
+ match *opt { None => (), Some(ref t) => f(t) }
}
#[inline(always)]
-pure fn unwrap<T>(+opt: option<T>) -> T {
+pure fn unwrap<T>(+opt: Option<T>) -> T {
/*!
* Moves a value out of an option type and returns it.
*
* of option types without copying them.
*/
match move opt {
- some(move x) => x,
- none => fail ~"option::unwrap none"
+ Some(move x) => x,
+ None => fail ~"option::unwrap none"
}
}
/// The ubiquitous option dance.
#[inline(always)]
-fn swap_unwrap<T>(opt: &mut option<T>) -> T {
+fn swap_unwrap<T>(opt: &mut Option<T>) -> T {
if opt.is_none() { fail ~"option::swap_unwrap none" }
- unwrap(util::replace(opt, none))
+ unwrap(util::replace(opt, None))
}
-pure fn unwrap_expect<T>(+opt: option<T>, reason: &str) -> T {
+pure fn unwrap_expect<T>(+opt: Option<T>, reason: &str) -> T {
//! As unwrap, but with a specified failure message.
if opt.is_none() { fail reason.to_unique(); }
unwrap(opt)
}
-// Some of these should change to be &option<T>, some should not. See below.
-impl<T> option<T> {
+// Some of these should change to be &Option<T>, some should not. See below.
+impl<T> Option<T> {
/**
* Update an optional value by optionally running its content through a
* function that returns an option.
*/
- pure fn chain<U>(f: fn(T) -> option<U>) -> option<U> { chain(self, f) }
+ pure fn chain<U>(f: fn(T) -> Option<U>) -> Option<U> { chain(self, f) }
/// Applies a function to the contained value or returns a default
pure fn map_default<U>(+def: U, f: fn(T) -> U) -> U
{ map_default(self, def, f) }
/// Returns true if the option contains some value
pure fn is_some() -> bool { is_some(self) }
/// Maps a `some` value from one type to another
- pure fn map<U>(f: fn(T) -> U) -> option<U> { map(self, f) }
+ pure fn map<U>(f: fn(T) -> U) -> Option<U> { map(self, f) }
}
-impl<T> &option<T> {
+impl<T> &Option<T> {
/**
* Update an optional value by optionally running its content by reference
* through a function that returns an option.
*/
- pure fn chain_ref<U>(f: fn(x: &T) -> option<U>) -> option<U> {
+ pure fn chain_ref<U>(f: fn(x: &T) -> Option<U>) -> Option<U> {
chain_ref(self, f)
}
/// Applies a function to the contained value or returns a default
/// Performs an operation on the contained value by reference
pure fn iter_ref(f: fn(x: &T)) { iter_ref(self, f) }
/// Maps a `some` value from one type to another by reference
- pure fn map_ref<U>(f: fn(x: &T) -> U) -> option<U> { map_ref(self, f) }
+ pure fn map_ref<U>(f: fn(x: &T) -> U) -> Option<U> { map_ref(self, f) }
/// Gets an immutable reference to the value inside a `some`.
pure fn get_ref() -> &self/T { get_ref(self) }
}
-impl<T: copy> option<T> {
+impl<T: copy> Option<T> {
/**
* Gets the value out of an option
*
*/
pure fn expect(reason: ~str) -> T { expect(self, reason) }
/// Applies a function zero or more times until the result is none.
- pure fn while_some(blk: fn(+T) -> option<T>) { while_some(self, blk) }
+ pure fn while_some(blk: fn(+T) -> Option<T>) { while_some(self, blk) }
}
#[test]
fn test_unwrap_ptr() {
let x = ~0;
let addr_x = ptr::addr_of(*x);
- let opt = some(x);
+ let opt = Some(x);
let y = unwrap(opt);
let addr_y = ptr::addr_of(*y);
assert addr_x == addr_y;
fn test_unwrap_str() {
let x = ~"test";
let addr_x = str::as_buf(x, |buf, _len| ptr::addr_of(buf));
- let opt = some(x);
+ let opt = Some(x);
let y = unwrap(opt);
let addr_y = str::as_buf(y, |buf, _len| ptr::addr_of(buf));
assert addr_x == addr_y;
let i = @mut 0;
{
let x = r(i);
- let opt = some(x);
+ let opt = Some(x);
let _y = unwrap(opt);
}
assert *i == 1;
#[test]
fn test_option_dance() {
- let x = some(());
- let mut y = some(5);
+ let x = Some(());
+ let mut y = Some(5);
let mut y2 = 0;
do x.iter |_x| {
y2 = swap_unwrap(&mut y);
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_option_too_much_dance() {
- let mut y = some(util::NonCopyable());
+ let mut y = Some(util::NonCopyable());
let _y2 = swap_unwrap(&mut y);
let _y3 = swap_unwrap(&mut y);
}
#[test]
fn test_option_while_some() {
let mut i = 0;
- do some(10).while_some |j| {
+ do Some(10).while_some |j| {
i += 1;
if (j > 0) {
- some(j-1)
+ Some(j-1)
} else {
- none
+ None
}
}
assert i == 11;
mode_t, pid_t, FILE};
import libc::{close, fclose};
-import option::{some, none};
+import option::{Some, None};
import consts::*;
import task::TaskBuilder;
}
fn fill_charp_buf(f: fn(*mut c_char, size_t) -> bool)
- -> option<~str> {
+ -> Option<~str> {
let buf = vec::to_mut(vec::from_elem(tmpbuf_sz, 0u8 as c_char));
do vec::as_mut_buf(buf) |b, sz| {
if f(b, sz as size_t) unsafe {
- some(str::unsafe::from_buf(b as *u8))
+ Some(str::unsafe::from_buf(b as *u8))
} else {
- none
+ None
}
}
}
import dword = libc::types::os::arch::extra::DWORD;
fn fill_utf16_buf_and_decode(f: fn(*mut u16, dword) -> dword)
- -> option<~str> {
+ -> Option<~str> {
// FIXME: remove these when export globs work properly. #1238
import libc::funcs::extra::kernel32::*;
import libc::consts::os::extra::*;
let mut n = tmpbuf_sz as dword;
- let mut res = none;
+ let mut res = None;
let mut done = false;
while !done {
let buf = vec::to_mut(vec::from_elem(n as uint, 0u16));
n *= (2 as dword);
} else {
let sub = vec::slice(buf, 0u, k as uint);
- res = option::some(str::from_utf16(sub));
+ res = option::Some(str::from_utf16(sub));
done = true;
}
}
}
}
-fn getenv(n: &str) -> option<~str> {
+fn getenv(n: &str) -> Option<~str> {
global_env::getenv(n)
}
}
enum Msg {
- MsgGetEnv(~str, comm::Chan<option<~str>>),
+ MsgGetEnv(~str, comm::Chan<Option<~str>>),
MsgSetEnv(~str, ~str, comm::Chan<()>),
MsgEnv(comm::Chan<~[(~str,~str)]>)
}
- fn getenv(n: &str) -> option<~str> {
+ fn getenv(n: &str) -> Option<~str> {
let env_ch = get_global_env_chan();
let po = comm::port();
comm::send(env_ch, MsgGetEnv(str::from_slice(n),
}
#[cfg(unix)]
- fn getenv(n: &str) -> option<~str> {
+ fn getenv(n: &str) -> Option<~str> {
unsafe {
let s = str::as_c_str(n, libc::getenv);
return if unsafe::reinterpret_cast(s) == 0 {
- option::none::<~str>
+ option::None::<~str>
} else {
let s = unsafe::reinterpret_cast(s);
- option::some::<~str>(str::unsafe::from_buf(s))
+ option::Some::<~str>(str::unsafe::from_buf(s))
};
}
}
#[cfg(windows)]
- fn getenv(n: &str) -> option<~str> {
+ fn getenv(n: &str) -> Option<~str> {
import libc::types::os::arch::extra::*;
import libc::funcs::extra::kernel32::*;
import win32::*;
}
-fn self_exe_path() -> option<Path> {
+fn self_exe_path() -> Option<Path> {
#[cfg(target_os = "freebsd")]
- fn load_self() -> option<~str> {
+ fn load_self() -> Option<~str> {
unsafe {
import libc::funcs::bsd44::*;
import libc::consts::os::extra::*;
}
#[cfg(target_os = "linux")]
- fn load_self() -> option<~str> {
+ fn load_self() -> Option<~str> {
import libc::funcs::posix01::unistd::readlink;
do fill_charp_buf() |buf, sz| {
do as_c_charp("/proc/self/exe") |proc_self_buf| {
}
#[cfg(target_os = "macos")]
- fn load_self() -> option<~str> {
+ fn load_self() -> Option<~str> {
// FIXME: remove imports when export globs work properly. #1238
import libc::funcs::extra::*;
do fill_charp_buf() |buf, sz| {
}
#[cfg(windows)]
- fn load_self() -> option<~str> {
+ fn load_self() -> Option<~str> {
// FIXME: remove imports when export globs work properly. #1238
import libc::types::os::arch::extra::*;
import libc::funcs::extra::kernel32::*;
*
* Otherwise, homedir returns option::none.
*/
-fn homedir() -> option<Path> {
+fn homedir() -> Option<Path> {
return match getenv(~"HOME") {
- some(p) => if !str::is_empty(p) {
- some(Path(p))
+ Some(p) => if !str::is_empty(p) {
+ Some(Path(p))
} else {
secondary()
},
- none => secondary()
+ None => secondary()
};
#[cfg(unix)]
- fn secondary() -> option<Path> {
- none
+ fn secondary() -> Option<Path> {
+ None
}
#[cfg(windows)]
- fn secondary() -> option<Path> {
+ fn secondary() -> Option<Path> {
do option::chain(getenv(~"USERPROFILE")) |p| {
if !str::is_empty(p) {
- some(Path(p))
+ Some(Path(p))
} else {
- none
+ None
}
}
}
fn tmpdir() -> Path {
return lookup();
- fn getenv_nonempty(v: &str) -> option<Path> {
+ fn getenv_nonempty(v: &str) -> Option<Path> {
match getenv(v) {
- some(x) =>
+ Some(x) =>
if str::is_empty(x) {
- none
+ None
} else {
- some(Path(x))
+ Some(Path(x))
},
- _ => none
+ _ => None
}
}
fn test_setenv() {
let n = make_rand_name();
setenv(n, ~"VALUE");
- assert getenv(n) == option::some(~"VALUE");
+ assert getenv(n) == option::Some(~"VALUE");
}
#[test]
let n = make_rand_name();
setenv(n, ~"1");
setenv(n, ~"2");
- assert getenv(n) == option::some(~"2");
+ assert getenv(n) == option::Some(~"2");
setenv(n, ~"");
- assert getenv(n) == option::some(~"");
+ assert getenv(n) == option::Some(~"");
}
// Windows GetEnvironmentVariable requires some extra work to make sure
let n = make_rand_name();
setenv(n, s);
log(debug, s);
- assert getenv(n) == option::some(s);
+ assert getenv(n) == option::Some(s);
}
#[test]
// MingW seems to set some funky environment variables like
// "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
// from env() but not visible from getenv().
- assert option::is_none(v2) || v2 == option::some(v);
+ assert option::is_none(v2) || v2 == option::Some(v);
}
}
let oldhome = getenv(~"HOME");
setenv(~"HOME", ~"/home/MountainView");
- assert os::homedir() == some(Path("/home/MountainView"));
+ assert os::homedir() == Some(Path("/home/MountainView"));
setenv(~"HOME", ~"");
- assert os::homedir() == none;
+ assert os::homedir() == None;
option::iter(oldhome, |s| setenv(~"HOME", s));
}
setenv(~"HOME", ~"");
setenv(~"USERPROFILE", ~"");
- assert os::homedir() == none;
+ assert os::homedir() == None;
setenv(~"HOME", ~"/home/MountainView");
- assert os::homedir() == some(Path("/home/MountainView"));
+ assert os::homedir() == Some(Path("/home/MountainView"));
setenv(~"HOME", ~"");
setenv(~"USERPROFILE", ~"/home/MountainView");
- assert os::homedir() == some(Path("/home/MountainView"));
+ assert os::homedir() == Some(Path("/home/MountainView"));
setenv(~"HOME", ~"/home/MountainView");
setenv(~"USERPROFILE", ~"/home/PaloAlto");
- assert os::homedir() == some(Path("/home/MountainView"));
+ assert os::homedir() == Some(Path("/home/MountainView"));
option::iter(oldhome, |s| setenv(~"HOME", s));
option::iter(olduserprofile,
match str::rfind(pp, |ch|
ch == consts::path_sep || ch == consts::alt_path_sep
) {
- some(i) => {
+ Some(i) => {
dirname: str::slice(pp, 0u, i),
basename: str::slice(pp, i + 1u, str::len(pp))
},
- none => {dirname: ~".", basename: pp}
+ None => {dirname: ~".", basename: pp}
}
}
fn strip_dots(s: ~[Path]) -> ~[Path] {
vec::filter_map(s, |elem|
if elem == ~"." {
- option::none
+ option::None
} else {
- option::some(elem)
+ option::Some(elem)
})
}
#[forbid(deprecated_pattern)];
struct WindowsPath {
- host: option<~str>;
- device: option<~str>;
+ host: Option<~str>;
+ device: Option<~str>;
is_absolute: bool;
components: ~[~str];
}
static pure fn from_str((&str)) -> self;
pure fn dirname() -> ~str;
- pure fn filename() -> option<~str>;
- pure fn filestem() -> option<~str>;
- pure fn filetype() -> option<~str>;
+ pure fn filename() -> Option<~str>;
+ pure fn filestem() -> Option<~str>;
+ pure fn filetype() -> Option<~str>;
pure fn with_dirname((&str)) -> self;
pure fn with_filename((&str)) -> self;
}
}
- pure fn filename() -> option<~str> {
+ pure fn filename() -> Option<~str> {
match self.components.len() {
- 0 => none,
- n => some(copy self.components[n - 1])
+ 0 => None,
+ n => Some(copy self.components[n - 1])
}
}
- pure fn filestem() -> option<~str> {
+ pure fn filestem() -> Option<~str> {
match self.filename() {
- none => none,
- some(ref f) => {
+ None => None,
+ Some(ref f) => {
match str::rfind_char(*f, '.') {
- some(p) => some(f.slice(0, p)),
- none => some(copy *f)
+ Some(p) => Some(f.slice(0, p)),
+ None => Some(copy *f)
}
}
}
}
- pure fn filetype() -> option<~str> {
+ pure fn filetype() -> Option<~str> {
match self.filename() {
- none => none,
- some(ref f) => {
+ None => None,
+ Some(ref f) => {
match str::rfind_char(*f, '.') {
- some(p) if p+1 < f.len() => some(f.slice(p+1, f.len())),
- _ => none
+ Some(p) if p+1 < f.len() => Some(f.slice(p+1, f.len())),
+ _ => None
}
}
}
pure fn with_dirname(d: &str) -> PosixPath {
let dpath = from_str::<PosixPath>(d);
match self.filename() {
- some(ref f) => dpath.push(*f),
- none => dpath
+ Some(ref f) => dpath.push(*f),
+ None => dpath
}
}
pure fn with_filestem(s: &str) -> PosixPath {
match self.filetype() {
- none => self.with_filename(s),
- some(ref t) =>
+ None => self.with_filename(s),
+ Some(ref t) =>
self.with_filename(str::from_slice(s) + "." + *t)
}
}
pure fn with_filetype(t: &str) -> PosixPath {
if t.len() == 0 {
match self.filestem() {
- none => copy self,
- some(s) => self.with_filename(s)
+ None => copy self,
+ Some(s) => self.with_filename(s)
}
} else {
let t = ~"." + str::from_slice(t);
match self.filestem() {
- none => self.with_filename(t),
- some(ref s) =>
+ None => self.with_filename(t),
+ Some(ref s) =>
self.with_filename(*s + t)
}
}
pure fn file_path() -> PosixPath {
let cs = match self.filename() {
- none => ~[],
- some(ref f) => ~[copy *f]
+ None => ~[],
+ Some(ref f) => ~[copy *f]
};
return PosixPath { is_absolute: false,
components: cs }
fn to_str() -> ~str {
let mut s = ~"";
match self.host {
- some(h) => { s += "\\\\"; s += h; }
- none => { }
+ Some(h) => { s += "\\\\"; s += h; }
+ None => { }
}
match self.device {
- some(d) => { s += d; s += ":"; }
- none => { }
+ Some(d) => { s += d; s += ":"; }
+ None => { }
}
if self.is_absolute {
s += "\\";
let rest;
match windows::extract_drive_prefix(s) {
- some((ref d, ref r)) => {
- host = none;
- device = some(copy *d);
+ Some((ref d, ref r)) => {
+ host = None;
+ device = Some(copy *d);
rest = copy *r;
}
- none => {
+ None => {
match windows::extract_unc_prefix(s) {
- some((ref h, ref r)) => {
- host = some(copy *h);
- device = none;
+ Some((ref h, ref r)) => {
+ host = Some(copy *h);
+ device = None;
rest = copy *r;
}
- none => {
- host = none;
- device = none;
+ None => {
+ host = None;
+ device = None;
rest = str::from_slice(s);
}
}
}
}
- pure fn filename() -> option<~str> {
+ pure fn filename() -> Option<~str> {
match self.components.len() {
- 0 => none,
- n => some(copy self.components[n - 1])
+ 0 => None,
+ n => Some(copy self.components[n - 1])
}
}
- pure fn filestem() -> option<~str> {
+ pure fn filestem() -> Option<~str> {
match self.filename() {
- none => none,
- some(ref f) => {
+ None => None,
+ Some(ref f) => {
match str::rfind_char(*f, '.') {
- some(p) => some(f.slice(0, p)),
- none => some(copy *f)
+ Some(p) => Some(f.slice(0, p)),
+ None => Some(copy *f)
}
}
}
}
- pure fn filetype() -> option<~str> {
+ pure fn filetype() -> Option<~str> {
match self.filename() {
- none => none,
- some(ref f) => {
+ None => None,
+ Some(ref f) => {
match str::rfind_char(*f, '.') {
- some(p) if p+1 < f.len() => some(f.slice(p+1, f.len())),
- _ => none
+ Some(p) if p+1 < f.len() => Some(f.slice(p+1, f.len())),
+ _ => None
}
}
}
pure fn with_dirname(d: &str) -> WindowsPath {
let dpath = from_str::<WindowsPath>(d);
match self.filename() {
- some(ref f) => dpath.push(*f),
- none => dpath
+ Some(ref f) => dpath.push(*f),
+ None => dpath
}
}
pure fn with_filestem(s: &str) -> WindowsPath {
match self.filetype() {
- none => self.with_filename(s),
- some(ref t) =>
+ None => self.with_filename(s),
+ Some(ref t) =>
self.with_filename(str::from_slice(s) + "." + *t)
}
}
pure fn with_filetype(t: &str) -> WindowsPath {
if t.len() == 0 {
match self.filestem() {
- none => copy self,
- some(s) => self.with_filename(s)
+ None => copy self,
+ Some(s) => self.with_filename(s)
}
} else {
let t = ~"." + str::from_slice(t);
match self.filestem() {
- none => self.with_filename(t),
- some(ref s) =>
+ None => self.with_filename(t),
+ Some(ref s) =>
self.with_filename(*s + t)
}
}
pure fn file_path() -> WindowsPath {
let cs = match self.filename() {
- none => ~[],
- some(ref f) => ~[copy *f]
+ None => ~[],
+ Some(ref f) => ~[copy *f]
};
- return WindowsPath { host: none,
- device: none,
+ return WindowsPath { host: None,
+ device: None,
is_absolute: false,
components: cs }
}
u == '/' as u8 || u == '\\' as u8
}
- pure fn extract_unc_prefix(s: &str) -> option<(~str,~str)> {
+ pure fn extract_unc_prefix(s: &str) -> Option<(~str,~str)> {
if (s.len() > 1 &&
s[0] == '\\' as u8 &&
s[1] == '\\' as u8) {
if s[i] == '\\' as u8 {
let pre = s.slice(2, i);
let rest = s.slice(i, s.len());
- return some((pre, rest));
+ return Some((pre, rest));
}
i += 1;
}
}
- none
+ None
}
- pure fn extract_drive_prefix(s: &str) -> option<(~str,~str)> {
+ pure fn extract_drive_prefix(s: &str) -> Option<(~str,~str)> {
unchecked {
if (s.len() > 1 &&
libc::isalpha(s[0] as libc::c_int) != 0 &&
} else {
s.slice(2, s.len())
};
- return some((s.slice(0,1), rest));
+ return Some((s.slice(0,1), rest));
}
- none
+ None
}
}
#[test]
fn test_extract_unc_prefixes() {
- assert extract_unc_prefix("\\\\") == none;
- assert extract_unc_prefix("\\\\hi") == none;
- assert extract_unc_prefix("\\\\hi\\") == some((~"hi", ~"\\"));
+ assert extract_unc_prefix("\\\\") == None;
+ assert extract_unc_prefix("\\\\hi") == None;
+ assert extract_unc_prefix("\\\\hi\\") == Some((~"hi", ~"\\"));
assert extract_unc_prefix("\\\\hi\\there") ==
- some((~"hi", ~"\\there"));
+ Some((~"hi", ~"\\there"));
assert extract_unc_prefix("\\\\hi\\there\\friends.txt") ==
- some((~"hi", ~"\\there\\friends.txt"));
+ Some((~"hi", ~"\\there\\friends.txt"));
}
#[test]
fn test_extract_drive_prefixes() {
- assert extract_drive_prefix("c") == none;
- assert extract_drive_prefix("c:") == some((~"c", ~""));
- assert extract_drive_prefix("d:") == some((~"d", ~""));
- assert extract_drive_prefix("z:") == some((~"z", ~""));
- assert extract_drive_prefix("c:\\hi") == some((~"c", ~"\\hi"));
- assert extract_drive_prefix("d:hi") == some((~"d", ~"hi"));
+ assert extract_drive_prefix("c") == None;
+ assert extract_drive_prefix("c:") == Some((~"c", ~""));
+ assert extract_drive_prefix("d:") == Some((~"d", ~""));
+ assert extract_drive_prefix("z:") == Some((~"z", ~""));
+ assert extract_drive_prefix("c:\\hi") == Some((~"c", ~"\\hi"));
+ assert extract_drive_prefix("d:hi") == Some((~"d", ~"hi"));
assert extract_drive_prefix("c:hi\\there.txt") ==
- some((~"c", ~"hi\\there.txt"));
+ Some((~"c", ~"hi\\there.txt"));
assert extract_drive_prefix("c:\\hi\\there.txt") ==
- some((~"c", ~"\\hi\\there.txt"));
+ Some((~"c", ~"\\hi\\there.txt"));
}
#[test]
#[doc(hidden)]
type packet<T: send> = {
header: packet_header,
- mut payload: option<T>,
+ mut payload: Option<T>,
};
#[doc(hidden)]
fn mk_packet<T: send>() -> packet<T> {
{
header: packet_header(),
- mut payload: none
+ mut payload: None
}
}
header: buffer_header(),
data: {
header: packet_header(),
- mut payload: none,
+ mut payload: None,
}
};
let p_ = p.unwrap();
let p = unsafe { &*p_ };
assert ptr::addr_of(p.header) == header;
- assert p.payload == none;
- p.payload <- some(payload);
+ assert p.payload == None;
+ p.payload <- Some(payload);
let old_state = swap_state_rel(&mut p.header.state, full);
match old_state {
empty => {
/** Attempts to receive a message from a pipe.
Returns `none` if the sender has closed the connection without sending
-a message, or `some(T)` if a message was received.
+a message, or `Some(T)` if a message was received.
*/
fn try_recv<T: send, Tbuffer: send>(+p: recv_packet_buffered<T, Tbuffer>)
- -> option<T>
+ -> Option<T>
{
let p_ = p.unwrap();
let p = unsafe { &*p_ };
// optimistic path
match p.header.state {
full => {
- let mut payload = none;
+ let mut payload = None;
payload <-> p.payload;
p.header.state = empty;
- return some(option::unwrap(payload))
+ return Some(option::unwrap(payload))
},
- terminated => return none,
+ terminated => return None,
_ => {}
}
fail ~"blocking on already blocked packet"
},
full => {
- let mut payload = none;
+ let mut payload = None;
payload <-> p.payload;
let old_task = swap_task(&mut p.header.blocked_task, ptr::null());
if !old_task.is_null() {
rustrt::rust_task_deref(old_task);
}
p.header.state = empty;
- return some(option::unwrap(payload))
+ return Some(option::unwrap(payload))
}
terminated => {
// This assert detects when we've accidentally unsafely
if !old_task.is_null() {
rustrt::rust_task_deref(old_task);
}
- return none;
+ return None;
}
}
first = false;
let pos = vec::position(pkts, |p| p.header() == event);
match pos {
- some(i) => {
+ Some(i) => {
ready_packet = i;
data_avail = true;
}
- none => debug!("ignoring spurious event, %?", event)
+ None => debug!("ignoring spurious event, %?", event)
}
}
right((a, none)) {
// endpoint b was closed.
}
- left((some(_), b)) {
+ left((Some(_), b)) {
// endpoint a received a message
}
- right(a, some(_)) {
+ right(a, Some(_)) {
// endpoint b received a message.
}
}
fn select2<A: send, Ab: send, B: send, Bb: send>(
+a: recv_packet_buffered<A, Ab>,
+b: recv_packet_buffered<B, Bb>)
- -> Either<(option<A>, recv_packet_buffered<B, Bb>),
- (recv_packet_buffered<A, Ab>, option<B>)>
+ -> Either<(Option<A>, recv_packet_buffered<B, Bb>),
+ (recv_packet_buffered<A, Ab>, Option<B>)>
{
let i = wait_many([a.header(), b.header()]/_);
*/
fn select<T: send, Tb: send>(+endpoints: ~[recv_packet_buffered<T, Tb>])
- -> (uint, option<T>, ~[recv_packet_buffered<T, Tb>])
+ -> (uint, Option<T>, ~[recv_packet_buffered<T, Tb>])
{
let ready = wait_many(endpoints.map(|p| p.header()));
let mut remaining = endpoints;
}
struct send_packet_buffered<T: send, Tbuffer: send> {
- let mut p: option<*packet<T>>;
- let mut buffer: option<buffer_resource<Tbuffer>>;
+ let mut p: Option<*packet<T>>;
+ let mut buffer: Option<buffer_resource<Tbuffer>>;
new(p: *packet<T>) {
//debug!("take send %?", p);
- self.p = some(p);
+ self.p = Some(p);
unsafe {
- self.buffer = some(
+ self.buffer = Some(
buffer_resource(
get_buffer(ptr::addr_of((*p).header))));
};
//if self.p != none {
// debug!("drop send %?", option::get(self.p));
//}
- if self.p != none {
- let mut p = none;
+ if self.p != None {
+ let mut p = None;
p <-> self.p;
sender_terminate(option::unwrap(p))
}
// } else { "some" }); }
}
fn unwrap() -> *packet<T> {
- let mut p = none;
+ let mut p = None;
p <-> self.p;
option::unwrap(p)
}
pure fn header() -> *packet_header {
match self.p {
- some(packet) => unsafe {
+ Some(packet) => unsafe {
let packet = &*packet;
let header = ptr::addr_of(packet.header);
//forget(packet);
header
},
- none => fail ~"packet already consumed"
+ None => fail ~"packet already consumed"
}
}
fn reuse_buffer() -> buffer_resource<Tbuffer> {
//error!("send reuse_buffer");
- let mut tmp = none;
+ let mut tmp = None;
tmp <-> self.buffer;
option::unwrap(tmp)
}
}
struct recv_packet_buffered<T: send, Tbuffer: send> : selectable {
- let mut p: option<*packet<T>>;
- let mut buffer: option<buffer_resource<Tbuffer>>;
+ let mut p: Option<*packet<T>>;
+ let mut buffer: Option<buffer_resource<Tbuffer>>;
new(p: *packet<T>) {
//debug!("take recv %?", p);
- self.p = some(p);
+ self.p = Some(p);
unsafe {
- self.buffer = some(
+ self.buffer = Some(
buffer_resource(
get_buffer(ptr::addr_of((*p).header))));
};
//if self.p != none {
// debug!("drop recv %?", option::get(self.p));
//}
- if self.p != none {
- let mut p = none;
+ if self.p != None {
+ let mut p = None;
p <-> self.p;
receiver_terminate(option::unwrap(p))
}
// } else { "some" }); }
}
fn unwrap() -> *packet<T> {
- let mut p = none;
+ let mut p = None;
p <-> self.p;
option::unwrap(p)
}
pure fn header() -> *packet_header {
match self.p {
- some(packet) => unsafe {
+ Some(packet) => unsafe {
let packet = &*packet;
let header = ptr::addr_of(packet.header);
//forget(packet);
header
},
- none => fail ~"packet already consumed"
+ None => fail ~"packet already consumed"
}
}
fn reuse_buffer() -> buffer_resource<Tbuffer> {
//error!("recv reuse_buffer");
- let mut tmp = none;
+ let mut tmp = None;
tmp <-> self.buffer;
option::unwrap(tmp)
}
// This is some nasty gymnastics required to safely move the pipe
// into a new task.
- let server = ~mut some(server);
+ let server = ~mut Some(server);
do task::spawn |move service| {
- let mut server_ = none;
+ let mut server_ = None;
server_ <-> *server;
service(option::unwrap(server_))
}
// This is some nasty gymnastics required to safely move the pipe
// into a new task.
- let server = ~mut some(server);
+ let server = ~mut Some(server);
do task::spawn |move service| {
- let mut server_ = none;
+ let mut server_ = None;
server_ <-> *server;
service(option::unwrap(server_))
}
the connection is closed.
*/
- fn try_recv() -> option<T>;
+ fn try_recv() -> Option<T>;
/** Returns true if a message is available or the connection is
closed.
}
#[doc(hidden)]
-type chan_<T:send> = { mut endp: option<streamp::client::open<T>> };
+type chan_<T:send> = { mut endp: Option<streamp::client::open<T>> };
/// An endpoint that can send many messages.
enum chan<T:send> {
}
#[doc(hidden)]
-type port_<T:send> = { mut endp: option<streamp::server::open<T>> };
+type port_<T:send> = { mut endp: Option<streamp::server::open<T>> };
/// An endpoint that can receive many messages.
enum port<T:send> {
fn stream<T:send>() -> (chan<T>, port<T>) {
let (c, s) = streamp::init();
- (chan_({ mut endp: some(c) }), port_({ mut endp: some(s) }))
+ (chan_({ mut endp: Some(c) }), port_({ mut endp: Some(s) }))
}
impl<T: send> chan<T>: channel<T> {
fn send(+x: T) {
- let mut endp = none;
+ let mut endp = None;
endp <-> self.endp;
- self.endp = some(
+ self.endp = Some(
streamp::client::data(unwrap(endp), x))
}
fn try_send(+x: T) -> bool {
- let mut endp = none;
+ let mut endp = None;
endp <-> self.endp;
match move streamp::client::try_data(unwrap(endp), x) {
- some(move next) => {
- self.endp = some(next);
+ Some(move next) => {
+ self.endp = Some(next);
true
}
- none => false
+ None => false
}
}
}
impl<T: send> port<T>: recv<T> {
fn recv() -> T {
- let mut endp = none;
+ let mut endp = None;
endp <-> self.endp;
let streamp::data(x, endp) = pipes::recv(unwrap(endp));
- self.endp = some(endp);
+ self.endp = Some(endp);
x
}
- fn try_recv() -> option<T> {
- let mut endp = none;
+ fn try_recv() -> Option<T> {
+ let mut endp = None;
endp <-> self.endp;
match move pipes::try_recv(unwrap(endp)) {
- some(streamp::data(move x, move endp)) => {
- self.endp = some(endp);
- some(x)
+ Some(streamp::data(move x, move endp)) => {
+ self.endp = Some(endp);
+ Some(x)
}
- none => none
+ None => None
}
}
pure fn peek() -> bool unchecked {
- let mut endp = none;
+ let mut endp = None;
endp <-> self.endp;
let peek = match endp {
- some(endp) => pipes::peek(&endp),
- none => fail ~"peeking empty stream"
+ Some(endp) => pipes::peek(&endp),
+ None => fail ~"peeking empty stream"
};
self.endp <-> endp;
peek
ch
}
- fn try_recv() -> option<T> {
- let mut result = none;
+ fn try_recv() -> Option<T> {
+ let mut result = None;
// we have to swap the ports array so we aren't borrowing
// aliasable mutable memory.
let mut ports = ~[];
ports <-> self.ports;
- while result == none && ports.len() > 0 {
+ while result == None && ports.len() > 0 {
let i = wait_many(ports);
match move ports[i].try_recv() {
- some(move m) => {
- result = some(m);
+ Some(move m) => {
+ result = Some(m);
}
- none => {
+ None => {
// Remove this port.
let _ = vec::swap_remove(ports, i);
}
impl<T: send> port<T>: selectable {
pure fn header() -> *packet_header unchecked {
match self.endp {
- some(endp) => endp.header(),
- none => fail ~"peeking empty stream"
+ Some(endp) => endp.header(),
+ None => fail ~"peeking empty stream"
}
}
}
impl<T: send> SharedChan<T>: channel<T> {
fn send(+x: T) {
- let mut xx = some(x);
+ let mut xx = Some(x);
do self.with |chan| {
- let mut x = none;
+ let mut x = None;
x <-> xx;
chan.send(option::unwrap(x))
}
}
fn try_send(+x: T) -> bool {
- let mut xx = some(x);
+ let mut xx = Some(x);
do self.with |chan| {
- let mut x = none;
+ let mut x = None;
x <-> xx;
chan.try_send(option::unwrap(x))
}
/// Receive a message from one of two endpoints.
trait select2<T: send, U: send> {
/// Receive a message or return `none` if a connection closes.
- fn try_select() -> Either<option<T>, option<U>>;
+ fn try_select() -> Either<Option<T>, Option<U>>;
/// Receive a message or fail if a connection closes.
fn select() -> Either<T, U>;
}
}
}
- fn try_select() -> Either<option<T>, option<U>> {
+ fn try_select() -> Either<Option<T>, Option<U>> {
match self {
(lp, rp) => match select2i(&lp, &rp) {
Left(()) => Left (lp.try_recv()),
}
/// Receive a message from a oneshot pipe unless the connection was closed.
-fn try_recv_one<T: send> (+port: port_one<T>) -> option<T> {
+fn try_recv_one<T: send> (+port: port_one<T>) -> Option<T> {
let message = try_recv(port);
- if message == none { none }
+ if message == None { None }
else {
let oneshot::send(message) = option::unwrap(message);
- some(message)
+ Some(message)
}
}
mod rt {
// These are used to hide the option constructors from the
// compiler because their names are changing
- fn make_some<T>(+val: T) -> option<T> { some(val) }
- fn make_none<T>() -> option<T> { none }
+ fn make_some<T>(+val: T) -> Option<T> { Some(val) }
+ fn make_none<T>() -> Option<T> { None }
}
#[cfg(test)]
self.choose_option(values).get()
}
- /// Choose some(item) randomly, returning none if values is empty
- fn choose_option<T:copy>(values: ~[T]) -> option<T> {
+ /// Choose Some(item) randomly, returning None if values is empty
+ fn choose_option<T:copy>(values: ~[T]) -> Option<T> {
if values.is_empty() {
- none
+ None
} else {
- some(values[self.gen_uint_range(0u, values.len())])
+ Some(values[self.gen_uint_range(0u, values.len())])
}
}
}
/**
- * Choose some(item) respecting the relative weights, returning none if
+ * Choose Some(item) respecting the relative weights, returning none if
* the sum of the weights is 0
*/
- fn choose_weighted_option<T:copy>(v: ~[Weighted<T>]) -> option<T> {
+ fn choose_weighted_option<T:copy>(v: ~[Weighted<T>]) -> Option<T> {
let mut total = 0u;
for v.each |item| {
total += item.weight;
}
if total == 0u {
- return none;
+ return None;
}
let chosen = self.gen_uint_range(0u, total);
let mut so_far = 0u;
for v.each |item| {
so_far += item.weight;
if so_far > chosen {
- return some(item.item);
+ return Some(item.item);
}
}
unreachable();
#[test]
fn choose_option() {
let r = rand::rng();
- assert r.choose_option(~[]) == none::<int>;
- assert r.choose_option(~[1, 1, 1]) == some(1);
+ assert r.choose_option(~[]) == None::<int>;
+ assert r.choose_option(~[1, 1, 1]) == Some(1);
}
#[test]
fn choose_weighted_option() {
let r = rand::rng();
assert r.choose_weighted_option(~[{weight: 1u, item: 42}]) ==
- some(42);
+ Some(42);
assert r.choose_weighted_option(~[
{weight: 0u, item: 42},
{weight: 1u, item: 43}
- ]) == some(43);
- assert r.choose_weighted_option(~[]) == none::<int>;
+ ]) == Some(43);
+ assert r.choose_weighted_option(~[]) == None::<int>;
}
#[test]
}
fn map_opt<T,U:copy,V:copy>(
- o_t: option<T>, op: fn(T) -> result<V,U>) -> result<option<V>,U> {
+ o_t: Option<T>, op: fn(T) -> result<V,U>) -> result<Option<V>,U> {
match o_t {
- none => ok(none),
- some(t) => match op(t) {
- ok(v) => ok(some(v)),
+ None => ok(None),
+ Some(t) => match op(t) {
+ ok(v) => ok(Some(v)),
err(e) => err(e)
}
}
#[forbid(deprecated_pattern)];
//! Process spawning
-import option::{some, none};
+import option::{Some, None};
import libc::{pid_t, c_void, c_int};
import io::ReaderUtil;
* The process id of the spawned process
*/
fn spawn_process(prog: &str, args: &[~str],
- env: &option<~[(~str,~str)]>,
- dir: &option<~str>,
+ env: &Option<~[(~str,~str)]>,
+ dir: &Option<~str>,
in_fd: c_int, out_fd: c_int, err_fd: c_int)
-> pid_t {
do with_argv(prog, args) |argv| {
}
#[cfg(unix)]
-fn with_envp<T>(env: &option<~[(~str,~str)]>,
+fn with_envp<T>(env: &Option<~[(~str,~str)]>,
cb: fn(*c_void) -> T) -> T {
// On posixy systems we can pass a char** for envp, which is
// a null-terminated array of "k=v\n" strings.
match *env {
- some(es) if !vec::is_empty(es) => {
+ Some(es) if !vec::is_empty(es) => {
let mut tmps = ~[];
let mut ptrs = ~[];
}
#[cfg(windows)]
-fn with_envp<T>(env: &option<~[(~str,~str)]>,
+fn with_envp<T>(env: &Option<~[(~str,~str)]>,
cb: fn(*c_void) -> T) -> T {
// On win32 we pass an "environment block" which is not a char**, but
// rather a concatenation of null-terminated k=v\0 sequences, with a final
// \0 to terminate.
unsafe {
match *env {
- some(es) if !vec::is_empty(es) => {
+ Some(es) if !vec::is_empty(es) => {
let mut blk : ~[u8] = ~[];
for vec::each(es) |e| {
let (k,v) = e;
}
}
-fn with_dirp<T>(d: &option<~str>,
+fn with_dirp<T>(d: &Option<~str>,
cb: fn(*libc::c_char) -> T) -> T {
match *d {
- some(dir) => str::as_c_str(dir, cb),
- none => cb(ptr::null())
+ Some(dir) => str::as_c_str(dir, cb),
+ None => cb(ptr::null())
}
}
* The process id
*/
fn run_program(prog: &str, args: &[~str]) -> int {
- let pid = spawn_process(prog, args, &none, &none,
+ let pid = spawn_process(prog, args, &None, &None,
0i32, 0i32, 0i32);
if pid == -1 as pid_t { fail; }
return waitpid(pid);
let pipe_output = os::pipe();
let pipe_err = os::pipe();
let pid =
- spawn_process(prog, args, &none, &none,
+ spawn_process(prog, args, &None, &None,
pipe_input.in, pipe_output.out,
pipe_err.out);
let pipe_in = os::pipe();
let pipe_out = os::pipe();
let pipe_err = os::pipe();
- let pid = spawn_process(prog, args, &none, &none,
+ let pid = spawn_process(prog, args, &None, &None,
pipe_in.in, pipe_out.out, pipe_err.out);
os::close(pipe_in.in);
let pid =
run::spawn_process(
- "cat", [], &none, &none,
+ "cat", [], &None, &None,
pipe_in.in, pipe_out.out, pipe_err.out);
os::close(pipe_in.in);
os::close(pipe_out.out);
#[test]
fn waitpid() {
let pid = run::spawn_process("false", [],
- &none, &none,
+ &None, &None,
0i32, 0i32, 0i32);
let status = run::waitpid(pid);
assert status == 1;
eqfn: pure fn~(x: &K, y: &K) -> bool,
resize_at: uint,
size: uint,
- buckets: ~[option<Bucket<K,V>>]})
+ buckets: ~[Option<Bucket<K,V>>]})
}
// FIXME(#3148) -- we could rewrite found_entry
eqfn: eqfn,
resize_at: resize_at(initial_capacity),
size: 0,
- buckets: vec::from_fn(initial_capacity, |_i| none)})
+ buckets: vec::from_fn(initial_capacity, |_i| None)})
}
priv impl<K, V> LinearMap<K,V> {
#[inline(always)]
pure fn bucket_for_key(&const self,
- buckets: &[option<Bucket<K,V>>],
+ buckets: &[Option<Bucket<K,V>>],
k: &K) -> SearchResult {
let hash = self.hashfn(k);
self.bucket_for_key_with_hash(buckets, hash, k)
#[inline(always)]
pure fn bucket_for_key_with_hash(&const self,
- buckets: &[option<Bucket<K,V>>],
+ buckets: &[Option<Bucket<K,V>>],
hash: uint,
k: &K) -> SearchResult {
let _ = for self.bucket_sequence(hash) |i| {
match buckets[i] {
- some(bkt) => if bkt.hash == hash && self.eqfn(k, &bkt.key) {
+ Some(bkt) => if bkt.hash == hash && self.eqfn(k, &bkt.key) {
return FoundEntry(i);
},
- none => return FoundHole(i)
+ None => return FoundHole(i)
}
};
return TableFull;
let new_capacity = old_capacity * 2;
self.resize_at = ((new_capacity as float) * 3.0 / 4.0) as uint;
- let mut old_buckets = vec::from_fn(new_capacity, |_i| none);
+ let mut old_buckets = vec::from_fn(new_capacity, |_i| None);
self.buckets <-> old_buckets;
for uint::range(0, old_capacity) |i| {
- let mut bucket = none;
+ let mut bucket = None;
bucket <-> old_buckets[i];
if bucket.is_some() {
self.insert_bucket(bucket);
}
}
- fn insert_bucket(&mut self, +bucket: option<Bucket<K,V>>) {
+ fn insert_bucket(&mut self, +bucket: Option<Bucket<K,V>>) {
let {hash, key, value} <- option::unwrap(bucket);
let _ = self.insert_internal(hash, key, value);
}
FoundHole(idx) => {
debug!("insert fresh (%?->%?) at idx %?, hash %?",
k, v, idx, hash);
- self.buckets[idx] = some({hash: hash, key: k, value: v});
+ self.buckets[idx] = Some({hash: hash, key: k, value: v});
self.size += 1;
return true;
}
FoundEntry(idx) => {
debug!("insert overwrite (%?->%?) at idx %?, hash %?",
k, v, idx, hash);
- self.buckets[idx] = some({hash: hash, key: k, value: v});
+ self.buckets[idx] = Some({hash: hash, key: k, value: v});
return false;
}
}
fn search(&self,
hash: uint,
- op: fn(x: &option<Bucket<K,V>>) -> bool) {
+ op: fn(x: &Option<Bucket<K,V>>) -> bool) {
let _ = self.bucket_sequence(hash, |i| op(&self.buckets[i]));
}
}
};
let len_buckets = self.buckets.len();
- self.buckets[idx] = none;
+ self.buckets[idx] = None;
idx = self.next_bucket(idx, len_buckets);
while self.buckets[idx].is_some() {
- let mut bucket = none;
+ let mut bucket = None;
bucket <-> self.buckets[idx];
self.insert_bucket(bucket);
idx = self.next_bucket(idx, len_buckets);
fn clear(&mut self) {
for uint::range(0, self.buckets.len()) |idx| {
- self.buckets[idx] = none;
+ self.buckets[idx] = None;
}
self.size = 0;
}
}
impl<K,V: copy> LinearMap<K,V> {
- fn find(&const self, k: &K) -> option<V> {
+ fn find(&const self, k: &K) -> Option<V> {
match self.bucket_for_key(self.buckets, k) {
FoundEntry(idx) => {
// FIXME (#3148): Once we rewrite found_entry, this
// failure case won't be necessary
match self.buckets[idx] {
- some(bkt) => {some(copy bkt.value)}
- none => fail ~"LinearMap::find: internal logic error"
+ Some(bkt) => {Some(copy bkt.value)}
+ None => fail ~"LinearMap::find: internal logic error"
}
}
TableFull | FoundHole(_) => {
- none
+ None
}
}
}
/// Returns a string with leading whitespace removed
pure fn trim_left(s: &str) -> ~str {
match find(s, |c| !char::is_whitespace(c)) {
- none => ~"",
- some(first) => unsafe { unsafe::slice_bytes(s, first, len(s)) }
+ None => ~"",
+ Some(first) => unsafe { unsafe::slice_bytes(s, first, len(s)) }
}
}
/// Returns a string with trailing whitespace removed
pure fn trim_right(s: &str) -> ~str {
match rfind(s, |c| !char::is_whitespace(c)) {
- none => ~"",
- some(last) => {
+ None => ~"",
+ Some(last) => {
let {next, _} = char_range_at(s, last);
unsafe { unsafe::slice_bytes(s, 0u, next) }
}
* An `option` containing the byte index of the first matching character
* or `none` if there is no match
*/
-pure fn find_char(s: &str, c: char) -> option<uint> {
+pure fn find_char(s: &str, c: char) -> Option<uint> {
find_char_between(s, c, 0u, len(s))
}
* `start` must be less than or equal to `len(s)`. `start` must be the
* index of a character boundary, as defined by `is_char_boundary`.
*/
-pure fn find_char_from(s: &str, c: char, start: uint) -> option<uint> {
+pure fn find_char_from(s: &str, c: char, start: uint) -> Option<uint> {
find_char_between(s, c, start, len(s))
}
* as defined by `is_char_boundary`.
*/
pure fn find_char_between(s: &str, c: char, start: uint, end: uint)
- -> option<uint> {
+ -> Option<uint> {
if c < 128u as char {
assert start <= end;
assert end <= len(s);
let mut i = start;
let b = c as u8;
while i < end {
- if s[i] == b { return some(i); }
+ if s[i] == b { return Some(i); }
i += 1u;
}
- return none;
+ return None;
} else {
find_between(s, start, end, |x| x == c)
}
* An `option` containing the byte index of the last matching character
* or `none` if there is no match
*/
-pure fn rfind_char(s: &str, c: char) -> option<uint> {
+pure fn rfind_char(s: &str, c: char) -> Option<uint> {
rfind_char_between(s, c, len(s), 0u)
}
* `start` must be less than or equal to `len(s)`. `start` must be
* the index of a character boundary, as defined by `is_char_boundary`.
*/
-pure fn rfind_char_from(s: &str, c: char, start: uint) -> option<uint> {
+pure fn rfind_char_from(s: &str, c: char, start: uint) -> Option<uint> {
rfind_char_between(s, c, start, 0u)
}
* as defined by `is_char_boundary`.
*/
pure fn rfind_char_between(s: &str, c: char, start: uint, end: uint)
- -> option<uint> {
+ -> Option<uint> {
if c < 128u as char {
assert start >= end;
assert start <= len(s);
let b = c as u8;
while i > end {
i -= 1u;
- if s[i] == b { return some(i); }
+ if s[i] == b { return Some(i); }
}
- return none;
+ return None;
} else {
rfind_between(s, start, end, |x| x == c)
}
* An `option` containing the byte index of the first matching character
* or `none` if there is no match
*/
-pure fn find(s: &str, f: fn(char) -> bool) -> option<uint> {
+pure fn find(s: &str, f: fn(char) -> bool) -> Option<uint> {
find_between(s, 0u, len(s), f)
}
* index of a character boundary, as defined by `is_char_boundary`.
*/
pure fn find_from(s: &str, start: uint, f: fn(char)
- -> bool) -> option<uint> {
+ -> bool) -> Option<uint> {
find_between(s, start, len(s), f)
}
* boundary, as defined by `is_char_boundary`.
*/
pure fn find_between(s: &str, start: uint, end: uint, f: fn(char) -> bool)
- -> option<uint> {
+ -> Option<uint> {
assert start <= end;
assert end <= len(s);
assert is_char_boundary(s, start);
let mut i = start;
while i < end {
let {ch, next} = char_range_at(s, i);
- if f(ch) { return some(i); }
+ if f(ch) { return Some(i); }
i = next;
}
- return none;
+ return None;
}
/**
* An option containing the byte index of the last matching character
* or `none` if there is no match
*/
-pure fn rfind(s: &str, f: fn(char) -> bool) -> option<uint> {
+pure fn rfind(s: &str, f: fn(char) -> bool) -> Option<uint> {
rfind_between(s, len(s), 0u, f)
}
* index of a character boundary, as defined by `is_char_boundary`
*/
pure fn rfind_from(s: &str, start: uint, f: fn(char) -> bool)
- -> option<uint> {
+ -> Option<uint> {
rfind_between(s, start, 0u, f)
}
* boundary, as defined by `is_char_boundary`
*/
pure fn rfind_between(s: &str, start: uint, end: uint, f: fn(char) -> bool)
- -> option<uint> {
+ -> Option<uint> {
assert start >= end;
assert start <= len(s);
assert is_char_boundary(s, start);
let mut i = start;
while i > end {
let {ch, prev} = char_range_at_reverse(s, i);
- if f(ch) { return some(prev); }
+ if f(ch) { return Some(prev); }
i = prev;
}
- return none;
+ return None;
}
// Utility used by various searching functions
* An `option` containing the byte index of the first matching substring
* or `none` if there is no match
*/
-pure fn find_str(haystack: &a/str, needle: &b/str) -> option<uint> {
+pure fn find_str(haystack: &a/str, needle: &b/str) -> Option<uint> {
find_str_between(haystack, needle, 0u, len(haystack))
}
* `start` must be less than or equal to `len(s)`
*/
pure fn find_str_from(haystack: &a/str, needle: &b/str, start: uint)
- -> option<uint> {
+ -> Option<uint> {
find_str_between(haystack, needle, start, len(haystack))
}
*/
pure fn find_str_between(haystack: &a/str, needle: &b/str, start: uint,
end:uint)
- -> option<uint> {
+ -> Option<uint> {
// See Issue #1932 for why this is a naive search
assert end <= len(haystack);
let needle_len = len(needle);
- if needle_len == 0u { return some(start); }
- if needle_len > end { return none; }
+ if needle_len == 0u { return Some(start); }
+ if needle_len > end { return None; }
let mut i = start;
let e = end - needle_len;
while i <= e {
- if match_at(haystack, needle, i) { return some(i); }
+ if match_at(haystack, needle, i) { return Some(i); }
i += 1u;
}
- return none;
+ return None;
}
/**
#[test]
fn test_rfind_char() {
- assert rfind_char(~"hello", 'l') == some(3u);
- assert rfind_char(~"hello", 'o') == some(4u);
- assert rfind_char(~"hello", 'h') == some(0u);
- assert rfind_char(~"hello", 'z') == none;
- assert rfind_char(~"ประเทศไทย中华Việt Nam", '华') == some(30u);
+ assert rfind_char(~"hello", 'l') == Some(3u);
+ assert rfind_char(~"hello", 'o') == Some(4u);
+ assert rfind_char(~"hello", 'h') == Some(0u);
+ assert rfind_char(~"hello", 'z') == None;
+ assert rfind_char(~"ประเทศไทย中华Việt Nam", '华') == Some(30u);
}
#[test]
#[test]
fn test_find_str() {
// byte positions
- assert find_str(~"banana", ~"apple pie") == none;
- assert find_str(~"", ~"") == some(0u);
+ assert find_str(~"banana", ~"apple pie") == None;
+ assert find_str(~"", ~"") == Some(0u);
let data = ~"ประเทศไทย中华Việt Nam";
- assert find_str(data, ~"") == some(0u);
- assert find_str(data, ~"ประเ") == some( 0u);
- assert find_str(data, ~"ะเ") == some( 6u);
- assert find_str(data, ~"中华") == some(27u);
- assert find_str(data, ~"ไท华") == none;
+ assert find_str(data, ~"") == Some(0u);
+ assert find_str(data, ~"ประเ") == Some( 0u);
+ assert find_str(data, ~"ะเ") == Some( 6u);
+ assert find_str(data, ~"中华") == Some(27u);
+ assert find_str(data, ~"ไท华") == None;
}
#[test]
fn test_find_str_between() {
// byte positions
- assert find_str_between(~"", ~"", 0u, 0u) == some(0u);
+ assert find_str_between(~"", ~"", 0u, 0u) == Some(0u);
let data = ~"abcabc";
- assert find_str_between(data, ~"ab", 0u, 6u) == some(0u);
- assert find_str_between(data, ~"ab", 2u, 6u) == some(3u);
- assert find_str_between(data, ~"ab", 2u, 4u) == none;
+ assert find_str_between(data, ~"ab", 0u, 6u) == Some(0u);
+ assert find_str_between(data, ~"ab", 2u, 6u) == Some(3u);
+ assert find_str_between(data, ~"ab", 2u, 4u) == None;
let mut data = ~"ประเทศไทย中华Việt Nam";
data += data;
- assert find_str_between(data, ~"", 0u, 43u) == some(0u);
- assert find_str_between(data, ~"", 6u, 43u) == some(6u);
-
- assert find_str_between(data, ~"ประ", 0u, 43u) == some( 0u);
- assert find_str_between(data, ~"ทศไ", 0u, 43u) == some(12u);
- assert find_str_between(data, ~"ย中", 0u, 43u) == some(24u);
- assert find_str_between(data, ~"iệt", 0u, 43u) == some(34u);
- assert find_str_between(data, ~"Nam", 0u, 43u) == some(40u);
-
- assert find_str_between(data, ~"ประ", 43u, 86u) == some(43u);
- assert find_str_between(data, ~"ทศไ", 43u, 86u) == some(55u);
- assert find_str_between(data, ~"ย中", 43u, 86u) == some(67u);
- assert find_str_between(data, ~"iệt", 43u, 86u) == some(77u);
- assert find_str_between(data, ~"Nam", 43u, 86u) == some(83u);
+ assert find_str_between(data, ~"", 0u, 43u) == Some(0u);
+ assert find_str_between(data, ~"", 6u, 43u) == Some(6u);
+
+ assert find_str_between(data, ~"ประ", 0u, 43u) == Some( 0u);
+ assert find_str_between(data, ~"ทศไ", 0u, 43u) == Some(12u);
+ assert find_str_between(data, ~"ย中", 0u, 43u) == Some(24u);
+ assert find_str_between(data, ~"iệt", 0u, 43u) == Some(34u);
+ assert find_str_between(data, ~"Nam", 0u, 43u) == Some(40u);
+
+ assert find_str_between(data, ~"ประ", 43u, 86u) == Some(43u);
+ assert find_str_between(data, ~"ทศไ", 43u, 86u) == Some(55u);
+ assert find_str_between(data, ~"ย中", 43u, 86u) == Some(67u);
+ assert find_str_between(data, ~"iệt", 43u, 86u) == Some(77u);
+ assert find_str_between(data, ~"Nam", 43u, 86u) == Some(83u);
}
#[test]
*/
type SchedOpts = {
mode: SchedMode,
- foreign_stack_size: option<uint>
+ foreign_stack_size: Option<uint>
};
/**
type TaskOpts = {
linked: bool,
supervised: bool,
- notify_chan: option<comm::Chan<Notification>>,
- sched: option<SchedOpts>,
+ notify_chan: Option<comm::Chan<Notification>>,
+ sched: Option<SchedOpts>,
};
/**
enum TaskBuilder = {
opts: TaskOpts,
gen_body: fn@(+fn~()) -> fn~(),
- can_not_copy: option<util::NonCopyable>,
+ can_not_copy: Option<util::NonCopyable>,
mut consumed: bool,
};
TaskBuilder({
opts: default_task_opts(),
gen_body: |body| body, // Identity function
- can_not_copy: none,
+ can_not_copy: None,
mut consumed: false,
})
}
fail ~"Cannot copy a task_builder"; // Fake move mode on self
}
self.consumed = true;
- TaskBuilder({ can_not_copy: none, mut consumed: false, with *self })
+ TaskBuilder({ can_not_copy: None, mut consumed: false, with *self })
}
}
fn unlinked() -> TaskBuilder {
TaskBuilder({
opts: { linked: false with self.opts },
- can_not_copy: none,
+ can_not_copy: None,
with *self.consume()
})
}
fn supervised() -> TaskBuilder {
TaskBuilder({
opts: { linked: false, supervised: true with self.opts },
- can_not_copy: none,
+ can_not_copy: None,
with *self.consume()
})
}
fn linked() -> TaskBuilder {
TaskBuilder({
opts: { linked: true, supervised: false with self.opts },
- can_not_copy: none,
+ can_not_copy: None,
with *self.consume()
})
}
// Reconfigure self to use a notify channel.
TaskBuilder({
- opts: { notify_chan: some(ch) with self.opts },
- can_not_copy: none,
+ opts: { notify_chan: Some(ch) with self.opts },
+ can_not_copy: None,
with *self.consume()
})
}
/// Configure a custom scheduler mode for the task.
fn sched_mode(mode: SchedMode) -> TaskBuilder {
TaskBuilder({
- opts: { sched: some({ mode: mode, foreign_stack_size: none})
+ opts: { sched: Some({ mode: mode, foreign_stack_size: None})
with self.opts },
- can_not_copy: none,
+ can_not_copy: None,
with *self.consume()
})
}
let prev_gen_body = self.gen_body;
TaskBuilder({
gen_body: |body| { wrapper(prev_gen_body(body)) },
- can_not_copy: none,
+ can_not_copy: None,
with *self.consume()
})
}
}
/// Runs a task, while transfering ownership of one argument to the child.
fn spawn_with<A: send>(+arg: A, +f: fn~(+A)) {
- let arg = ~mut some(arg);
+ let arg = ~mut Some(arg);
do self.spawn {
f(option::swap_unwrap(arg))
}
fn try<T: send>(+f: fn~() -> T) -> result<T,()> {
let po = comm::port();
let ch = comm::chan(po);
- let mut result = none;
+ let mut result = None;
- do self.future_result(|+r| { result = some(r); }).spawn {
+ do self.future_result(|+r| { result = Some(r); }).spawn {
comm::send(ch, f());
}
match future::get(&option::unwrap(result)) {
{
linked: true,
supervised: false,
- notify_chan: none,
- sched: none
+ notify_chan: None,
+ sched: None
}
}
// tasks in this group.
mut descendants: TaskSet,
};
-type TaskGroupArc = unsafe::Exclusive<option<TaskGroupData>>;
+type TaskGroupArc = unsafe::Exclusive<Option<TaskGroupData>>;
-type TaskGroupInner = &mut option<TaskGroupData>;
+type TaskGroupInner = &mut Option<TaskGroupData>;
// A taskgroup is 'dead' when nothing can cause it to fail; only members can.
pure fn taskgroup_is_dead(tg: &TaskGroupData) -> bool {
// FIXME(#3068): Make the generation counter togglable with #[cfg(debug)].
generation: uint,
// Should really be an immutable non-option. This way appeases borrowck.
- mut parent_group: option<TaskGroupArc>,
+ mut parent_group: Option<TaskGroupArc>,
// Recursive rest of the list.
mut ancestors: AncestorList,
};
-enum AncestorList = option<unsafe::Exclusive<AncestorNode>>;
+enum AncestorList = Option<unsafe::Exclusive<AncestorNode>>;
// Accessors for taskgroup arcs and ancestor arcs that wrap the unsafety.
#[inline(always)]
// taskgroups that forward_blk already ran on successfully (Note: bail_blk
// is NOT called on the block that forward_blk broke on!).
// (3) As a bonus, coalesces away all 'dead' taskgroup nodes in the list.
-// FIXME(#2190): Change option<fn@(...)> to option<fn&(...)>, to save on
+// FIXME(#2190): Change Option<fn@(...)> to Option<fn&(...)>, to save on
// allocations. Once that bug is fixed, changing the sigil should suffice.
fn each_ancestor(list: &mut AncestorList,
- bail_opt: option<fn@(TaskGroupInner)>,
+ bail_opt: Option<fn@(TaskGroupInner)>,
forward_blk: fn(TaskGroupInner) -> bool)
-> bool {
// "Kickoff" call - there was no last generation.
// Recursively iterates, and coalesces afterwards if needed. Returns
// whether or not unwinding is needed (i.e., !successful iteration).
fn coalesce(list: &mut AncestorList,
- bail_opt: option<fn@(TaskGroupInner)>,
+ bail_opt: Option<fn@(TaskGroupInner)>,
forward_blk: fn(TaskGroupInner) -> bool,
last_generation: uint) -> bool {
// Need to swap the list out to use it, to appease borrowck.
- let tmp_list = util::replace(list, AncestorList(none));
+ let tmp_list = util::replace(list, AncestorList(None));
let (coalesce_this, early_break) =
iterate(&tmp_list, bail_opt, forward_blk, last_generation);
// What should our next ancestor end up being?
}
// Returns an optional list-to-coalesce and whether unwinding is needed.
- // option<ancestor_list>:
+ // Option<ancestor_list>:
// Whether or not the ancestor taskgroup being iterated over is
// dead or not; i.e., it has no more tasks left in it, whether or not
// it has descendants. If dead, the caller shall coalesce it away.
// True if the supplied block did 'break', here or in any recursive
// calls. If so, must call the unwinder on all previous nodes.
fn iterate(ancestors: &AncestorList,
- bail_opt: option<fn@(TaskGroupInner)>,
+ bail_opt: Option<fn@(TaskGroupInner)>,
forward_blk: fn(TaskGroupInner) -> bool,
- last_generation: uint) -> (option<AncestorList>, bool) {
+ last_generation: uint) -> (Option<AncestorList>, bool) {
// At each step of iteration, three booleans are at play which govern
// how the iteration should behave.
// 'nobe_is_dead' - Should the list should be coalesced at this point?
// The map defaults to none, because if ancestors is none, we're at
// the end of the list, which doesn't make sense to coalesce.
- return do (**ancestors).map_default((none,false)) |ancestor_arc| {
+ return do (**ancestors).map_default((None,false)) |ancestor_arc| {
// NB: Takes a lock! (this ancestor node)
do access_ancestors(&ancestor_arc) |nobe| {
// Check monotonicity
// Decide whether this group is dead. Note that the
// group being *dead* is disjoint from it *failing*.
nobe_is_dead = match *tg_opt {
- some(ref tg) => taskgroup_is_dead(tg),
- none => nobe_is_dead
+ Some(ref tg) => taskgroup_is_dead(tg),
+ None => nobe_is_dead
};
// Call iterator block. (If the group is dead, it's
// safe to skip it. This will leave our *rust_task
if nobe_is_dead {
// Swap the list out here; the caller replaces us with it.
let rest = util::replace(&mut nobe.ancestors,
- AncestorList(none));
- (some(rest), need_unwind)
+ AncestorList(None));
+ (Some(rest), need_unwind)
} else {
- (none, need_unwind)
+ (None, need_unwind)
}
}
};
// Wrapper around exclusive::with that appeases borrowck.
- fn with_parent_tg<U>(parent_group: &mut option<TaskGroupArc>,
+ fn with_parent_tg<U>(parent_group: &mut Option<TaskGroupArc>,
blk: fn(TaskGroupInner) -> U) -> U {
// If this trips, more likely the problem is 'blk' failed inside.
let tmp_arc = option::swap_unwrap(parent_group);
let result = do access_group(&tmp_arc) |tg_opt| { blk(tg_opt) };
- *parent_group <- some(tmp_arc);
+ *parent_group <- Some(tmp_arc);
result
}
}
// Lists of tasks who will kill us if they fail, but whom we won't kill.
let mut ancestors: AncestorList;
let is_main: bool;
- let notifier: option<AutoNotify>;
+ let notifier: Option<AutoNotify>;
new(me: *rust_task, -tasks: TaskGroupArc, -ancestors: AncestorList,
- is_main: bool, -notifier: option<AutoNotify>) {
+ is_main: bool, -notifier: Option<AutoNotify>) {
self.me = me;
self.tasks = tasks;
self.ancestors = ancestors;
// It doesn't matter whether this happens before or after dealing with
// our own taskgroup, so long as both happen before we die. We need to
// remove ourself from every ancestor we can, so no cleanup; no break.
- for each_ancestor(&mut self.ancestors, none) |ancestor_group| {
+ for each_ancestor(&mut self.ancestors, None) |ancestor_group| {
leave_taskgroup(ancestor_group, self.me, false);
};
}
fn enlist_in_taskgroup(state: TaskGroupInner, me: *rust_task,
is_member: bool) -> bool {
- let newstate = util::replace(state, none);
+ let newstate = util::replace(state, None);
// If 'none', the group was failing. Can't enlist.
if newstate.is_some() {
let group = option::unwrap(newstate);
taskset_insert(if is_member { &mut group.members }
else { &mut group.descendants }, me);
- *state = some(group);
+ *state = Some(group);
true
} else {
false
// NB: Runs in destructor/post-exit context. Can't 'fail'.
fn leave_taskgroup(state: TaskGroupInner, me: *rust_task, is_member: bool) {
- let newstate = util::replace(state, none);
+ let newstate = util::replace(state, None);
// If 'none', already failing and we've already gotten a kill signal.
if newstate.is_some() {
let group = option::unwrap(newstate);
taskset_remove(if is_member { &mut group.members }
else { &mut group.descendants }, me);
- *state = some(group);
+ *state = Some(group);
}
}
// so if we're failing, all concurrently exiting tasks must wait for us.
// To do it differently, we'd have to use the runtime's task refcounting,
// but that could leave task structs around long after their task exited.
- let newstate = util::replace(state, none);
+ let newstate = util::replace(state, None);
// Might already be none, if somebody is failing simultaneously.
// That's ok; only one task needs to do the dirty work. (Might also
// see 'none' if somebody already failed and we got a kill signal.)
if is_main {
rustrt::rust_task_kill_all(me);
}
- // Do NOT restore state to some(..)! It stays none to indicate
+ // Do NOT restore state to Some(..)! It stays none to indicate
// that the whole taskgroup is failing, to forbid new spawns.
}
// (note: multiple tasks may reach this point)
*######################################################################*/
let spawner_group = match unsafe { local_get(spawner,
taskgroup_key!()) } {
- none => {
+ None => {
// Main task, doing first spawn ever. Lazily initialise here.
let mut members = new_taskset();
taskset_insert(&mut members, spawner);
let tasks =
- unsafe::exclusive(some({ mut members: members,
+ unsafe::exclusive(Some({ mut members: members,
mut descendants: new_taskset() }));
// Main task/group has no ancestors, no notifier, etc.
let group =
- @Tcb(spawner, tasks, AncestorList(none), true, none);
+ @Tcb(spawner, tasks, AncestorList(None), true, None);
unsafe { local_set(spawner, taskgroup_key!(), group); }
group
}
- some(group) => group
+ Some(group) => group
};
/*######################################################################*
* Step 2. Process spawn options for child.
(g, a, spawner_group.is_main)
} else {
// Child is in a separate group from spawner.
- let g = unsafe::exclusive(some({ mut members: new_taskset(),
+ let g = unsafe::exclusive(Some({ mut members: new_taskset(),
mut descendants: new_taskset() }));
let a = if supervised {
// Child's ancestors start with the spawner.
// it should be enabled only in debug builds.
let new_generation =
match *old_ancestors {
- some(arc) => access_ancestors(&arc, |a| a.generation+1),
- none => 0 // the actual value doesn't really matter.
+ Some(arc) => access_ancestors(&arc, |a| a.generation+1),
+ None => 0 // the actual value doesn't really matter.
};
assert new_generation < uint::max_value;
// Build a new node in the ancestor list.
- AncestorList(some(unsafe::exclusive(
+ AncestorList(Some(unsafe::exclusive(
{ generation: new_generation,
- mut parent_group: some(spawner_group.tasks.clone()),
+ mut parent_group: Some(spawner_group.tasks.clone()),
mut ancestors: old_ancestors })))
} else {
// Child has no ancestors.
- AncestorList(none)
+ AncestorList(None)
};
(g,a, false)
};
fn share_ancestors(ancestors: &mut AncestorList) -> AncestorList {
// Appease the borrow-checker. Really this wants to be written as:
// match ancestors
- // some(ancestor_arc) { ancestor_list(some(ancestor_arc.clone())) }
+ // Some(ancestor_arc) { ancestor_list(Some(ancestor_arc.clone())) }
// none { ancestor_list(none) }
- let tmp = util::replace(&mut **ancestors, none);
+ let tmp = util::replace(&mut **ancestors, None);
if tmp.is_some() {
let ancestor_arc = option::unwrap(tmp);
let result = ancestor_arc.clone();
- **ancestors <- some(ancestor_arc);
- AncestorList(some(result))
+ **ancestors <- Some(ancestor_arc);
+ AncestorList(Some(result))
} else {
- AncestorList(none)
+ AncestorList(None)
}
}
}
gen_child_taskgroup(opts.linked, opts.supervised);
unsafe {
- let child_data = ~mut some((child_tg, ancestors, f));
+ let child_data = ~mut Some((child_tg, ancestors, f));
// Being killed with the unsafe task/closure pointers would leak them.
do unkillable {
// Agh. Get move-mode items into the closure. FIXME (#2829)
let (child_tg, ancestors, f) = option::swap_unwrap(child_data);
// Create child task.
let new_task = match opts.sched {
- none => rustrt::new_task(),
- some(sched_opts) => new_task_in_new_sched(sched_opts)
+ None => rustrt::new_task(),
+ Some(sched_opts) => new_task_in_new_sched(sched_opts)
};
assert !new_task.is_null();
// Getting killed after here would leak the task.
// (4) ...and runs the provided body function.
fn make_child_wrapper(child: *rust_task, +child_arc: TaskGroupArc,
+ancestors: AncestorList, is_main: bool,
- notify_chan: option<comm::Chan<Notification>>,
+ notify_chan: Option<comm::Chan<Notification>>,
+f: fn~()) -> fn~() {
- let child_data = ~mut some((child_arc, ancestors));
+ let child_data = ~mut Some((child_arc, ancestors));
return fn~() {
// Agh. Get move-mode items into the closure. FIXME (#2829)
let mut (child_arc, ancestors) = option::swap_unwrap(child_data);
};
// Attempt to join every ancestor group.
result =
- for each_ancestor(ancestors, some(bail)) |ancestor_tg| {
+ for each_ancestor(ancestors, Some(bail)) |ancestor_tg| {
// Enlist as a descendant, not as an actual member.
// Descendants don't kill ancestor groups on failure.
if !enlist_in_taskgroup(ancestor_tg, child, false) {
}
fn new_task_in_new_sched(opts: SchedOpts) -> *rust_task {
- if opts.foreign_stack_size != none {
+ if opts.foreign_stack_size != None {
fail ~"foreign_stack_size scheduler option unimplemented";
}
// heavily in future, this could be made more efficient with a proper map.
type TaskLocalElement = (*libc::c_void, *libc::c_void, LocalData);
// Has to be a pointer at outermost layer; the foreign call returns void *.
-type TaskLocalMap = @dvec::DVec<option<TaskLocalElement>>;
+type TaskLocalMap = @dvec::DVec<Option<TaskLocalElement>>;
extern fn cleanup_task_local_map(map_ptr: *libc::c_void) unsafe {
assert !map_ptr.is_null();
pair.first()
}
-// If returning some(..), returns with @T with the map's reference. Careful!
+// If returning Some(..), returns with @T with the map's reference. Careful!
unsafe fn local_data_lookup<T: owned>(
map: TaskLocalMap, key: LocalDataKey<T>)
- -> option<(uint, *libc::c_void)> {
+ -> Option<(uint, *libc::c_void)> {
let key_value = key_to_key_value(key);
let map_pos = (*map).position(|entry|
match entry {
- some((k,_,_)) => k == key_value,
- none => false
+ Some((k,_,_)) => k == key_value,
+ None => false
}
);
do map_pos.map |index| {
unsafe fn local_get_helper<T: owned>(
task: *rust_task, key: LocalDataKey<T>,
- do_pop: bool) -> option<@T> {
+ do_pop: bool) -> Option<@T> {
let map = get_task_local_map(task);
// Interpreturn our findings from the map
let data: @T = unsafe::transmute(data_ptr);
unsafe::bump_box_refcount(data);
if do_pop {
- (*map).set_elt(index, none);
+ (*map).set_elt(index, None);
}
data
}
unsafe fn local_pop<T: owned>(
task: *rust_task,
- key: LocalDataKey<T>) -> option<@T> {
+ key: LocalDataKey<T>) -> Option<@T> {
local_get_helper(task, key, true)
}
unsafe fn local_get<T: owned>(
task: *rust_task,
- key: LocalDataKey<T>) -> option<@T> {
+ key: LocalDataKey<T>) -> Option<@T> {
local_get_helper(task, key, false)
}
let data_ptr = unsafe::reinterpret_cast(data);
let data_box = data as LocalData;
// Construct new entry to store in the map.
- let new_entry = some((keyval, data_ptr, data_box));
+ let new_entry = Some((keyval, data_ptr, data_box));
// Find a place to put it.
match local_data_lookup(map, key) {
- some((index, _old_data_ptr)) => {
+ Some((index, _old_data_ptr)) => {
// Key already had a value set, _old_data_ptr, whose reference
// will get dropped when the local_data box is overwritten.
(*map).set_elt(index, new_entry);
}
- none => {
+ None => {
// Find an empty slot. If not, grow the vector.
- match (*map).position(|x| x == none) {
- some(empty_index) => (*map).set_elt(empty_index, new_entry),
- none => (*map).push(new_entry)
+ match (*map).position(|x| x == None) {
+ Some(empty_index) => (*map).set_elt(empty_index, new_entry),
+ None => (*map).push(new_entry)
}
}
}
unsafe fn local_modify<T: owned>(
task: *rust_task, key: LocalDataKey<T>,
- modify_fn: fn(option<@T>) -> option<@T>) {
+ modify_fn: fn(Option<@T>) -> Option<@T>) {
// Could be more efficient by doing the lookup work, but this is easy.
let newdata = modify_fn(local_pop(task, key));
* reference that was originally created to insert it.
*/
unsafe fn local_data_pop<T: owned>(
- key: LocalDataKey<T>) -> option<@T> {
+ key: LocalDataKey<T>) -> Option<@T> {
local_pop(rustrt::rust_get_task(), key)
}
* table until explicitly removed.
*/
unsafe fn local_data_get<T: owned>(
- key: LocalDataKey<T>) -> option<@T> {
+ key: LocalDataKey<T>) -> Option<@T> {
local_get(rustrt::rust_get_task(), key)
}
*/
unsafe fn local_data_modify<T: owned>(
key: LocalDataKey<T>,
- modify_fn: fn(option<@T>) -> option<@T>) {
+ modify_fn: fn(Option<@T>) -> Option<@T>) {
local_modify(rustrt::rust_get_task(), key, modify_fn)
}
let b0 = task();
let b1 = TaskBuilder({
opts: { linked: true, supervised: true with b0.opts },
- can_not_copy: none,
+ can_not_copy: None,
with *b0
});
do b1.spawn { fail; }
let b0 = task();
let b1 = TaskBuilder({
opts: { linked: true, supervised: true with b0.opts },
- can_not_copy: none,
+ can_not_copy: None,
with *b0
});
do b1.spawn { loop { task::yield(); } }
let notify_ch = comm::chan(notify_po);
let opts = {
- notify_chan: some(notify_ch)
+ notify_chan: Some(notify_ch)
with default_task_opts()
};
do spawn_raw(opts) {
let opts = {
linked: false,
- notify_chan: some(notify_ch)
+ notify_chan: Some(notify_ch)
with default_task_opts()
};
do spawn_raw(opts) {
#[test]
#[ignore(cfg(windows))]
fn test_future_result() {
- let mut result = none;
- do task().future_result(|+r| { result = some(r); }).spawn { }
+ let mut result = None;
+ do task().future_result(|+r| { result = Some(r); }).spawn { }
assert future::get(&option::unwrap(result)) == Success;
- result = none;
- do task().future_result(|+r| { result = some(r); }).unlinked().spawn {
+ result = None;
+ do task().future_result(|+r| { result = Some(r); }).unlinked().spawn {
fail;
}
assert future::get(&option::unwrap(result)) == Failure;
fn my_key(+_x: @~str) { }
local_data_set(my_key, @~"parent data");
do task::spawn unsafe {
- assert local_data_get(my_key) == none; // TLS shouldn't carry over.
+ assert local_data_get(my_key) == None; // TLS shouldn't carry over.
local_data_set(my_key, @~"child data");
assert *(local_data_get(my_key).get()) == ~"child data";
// should be cleaned up for us
local_data_set(my_key, @~"weasel");
assert *(local_data_pop(my_key).get()) == ~"weasel";
// Pop must remove the data from the map.
- assert local_data_pop(my_key) == none;
+ assert local_data_pop(my_key) == None;
}
#[test]
fn my_key(+_x: @~str) { }
local_data_modify(my_key, |data| {
match data {
- some(@val) => fail ~"unwelcome value: " + val,
- none => some(@~"first data")
+ Some(@val) => fail ~"unwelcome value: " + val,
+ None => Some(@~"first data")
}
});
local_data_modify(my_key, |data| {
match data {
- some(@~"first data") => some(@~"next data"),
- some(@val) => fail ~"wrong value: " + val,
- none => fail ~"missing value"
+ Some(@~"first data") => Some(@~"next data"),
+ Some(@val) => fail ~"wrong value: " + val,
+ None => fail ~"missing value"
}
});
assert *(local_data_pop(my_key).get()) == ~"next data";
*
* `buf` must not be empty
*/
-fn parse_buf(buf: &[const u8], radix: uint) -> option<T> {
- if vec::len(buf) == 0u { return none; }
+fn parse_buf(buf: &[const u8], radix: uint) -> Option<T> {
+ if vec::len(buf) == 0u { return None; }
let mut i = vec::len(buf) - 1u;
let mut power = 1u as T;
let mut n = 0u as T;
loop {
match char::to_digit(buf[i] as char, radix) {
- some(d) => n += d as T * power,
- none => return none
+ Some(d) => n += d as T * power,
+ None => return None
}
power *= radix as T;
- if i == 0u { return some(n); }
+ if i == 0u { return Some(n); }
i -= 1u;
};
}
/// Parse a string to an int
-fn from_str(s: ~str) -> option<T> { parse_buf(str::to_bytes(s), 10u) }
+fn from_str(s: ~str) -> Option<T> { parse_buf(str::to_bytes(s), 10u) }
/// Parse a string as an unsigned integer.
-fn from_str_radix(buf: ~str, radix: u64) -> option<u64> {
- if str::len(buf) == 0u { return none; }
+fn from_str_radix(buf: ~str, radix: u64) -> Option<u64> {
+ if str::len(buf) == 0u { return None; }
let mut i = str::len(buf) - 1u;
let mut power = 1u64, n = 0u64;
loop {
match char::to_digit(buf[i] as char, radix as uint) {
- some(d) => n += d as u64 * power,
- none => return none
+ Some(d) => n += d as u64 * power,
+ None => return None
}
power *= radix;
- if i == 0u { return some(n); }
+ if i == 0u { return Some(n); }
i -= 1u;
};
}
#[test]
#[ignore]
fn test_from_str() {
- assert from_str(~"0") == some(0u as T);
- assert from_str(~"3") == some(3u as T);
- assert from_str(~"10") == some(10u as T);
- assert from_str(~"123456789") == some(123456789u as T);
- assert from_str(~"00100") == some(100u as T);
-
- assert from_str(~"") == none;
- assert from_str(~" ") == none;
- assert from_str(~"x") == none;
+ assert from_str(~"0") == Some(0u as T);
+ assert from_str(~"3") == Some(3u as T);
+ assert from_str(~"10") == Some(10u as T);
+ assert from_str(~"123456789") == Some(123456789u as T);
+ assert from_str(~"00100") == Some(100u as T);
+
+ assert from_str(~"") == None;
+ assert from_str(~" ") == None;
+ assert from_str(~"x") == None;
}
#[test]
#[ignore]
fn test_parse_buf() {
import str::to_bytes;
- assert parse_buf(to_bytes(~"123"), 10u) == some(123u as T);
- assert parse_buf(to_bytes(~"1001"), 2u) == some(9u as T);
- assert parse_buf(to_bytes(~"123"), 8u) == some(83u as T);
- assert parse_buf(to_bytes(~"123"), 16u) == some(291u as T);
- assert parse_buf(to_bytes(~"ffff"), 16u) == some(65535u as T);
- assert parse_buf(to_bytes(~"z"), 36u) == some(35u as T);
-
- assert parse_buf(to_bytes(~"Z"), 10u) == none;
- assert parse_buf(to_bytes(~"_"), 2u) == none;
+ assert parse_buf(to_bytes(~"123"), 10u) == Some(123u as T);
+ assert parse_buf(to_bytes(~"1001"), 2u) == Some(9u as T);
+ assert parse_buf(to_bytes(~"123"), 8u) == Some(83u as T);
+ assert parse_buf(to_bytes(~"123"), 16u) == Some(291u as T);
+ assert parse_buf(to_bytes(~"ffff"), 16u) == Some(65535u as T);
+ assert parse_buf(to_bytes(~"z"), 36u) == Some(35u as T);
+
+ assert parse_buf(to_bytes(~"Z"), 10u) == None;
+ assert parse_buf(to_bytes(~"_"), 2u) == None;
}
#[test]
// An unwrapper uses this protocol to communicate with the "other" task that
// drops the last refcount on an arc. Unfortunately this can't be a proper
// pipe protocol because the unwrapper has to access both stages at once.
-type UnwrapProto = ~mut option<(pipes::chan_one<()>, pipes::port_one<bool>)>;
+type UnwrapProto = ~mut Option<(pipes::chan_one<()>, pipes::port_one<bool>)>;
struct ArcData<T> {
mut count: libc::intptr_t;
mut unwrapper: libc::uintptr_t; // either a UnwrapProto or 0
// FIXME(#3224) should be able to make this non-option to save memory, and
// in unwrap() use "let ~ArcData { data: result, _ } = thing" to unwrap it
- mut data: option<T>;
+ mut data: Option<T>;
}
struct ArcDestruct<T> {
unsafe fn unwrap_shared_mutable_state<T: send>(+rc: SharedMutableState<T>)
-> T {
struct DeathThroes<T> {
- mut ptr: option<~ArcData<T>>;
- mut response: option<pipes::chan_one<bool>>;
+ mut ptr: Option<~ArcData<T>>;
+ mut response: Option<pipes::chan_one<bool>>;
drop unsafe {
let response = option::swap_unwrap(&mut self.response);
// In case we get killed early, we need to tell the person who
let ptr: ~ArcData<T> = unsafe::reinterpret_cast(rc.data);
let (c1,p1) = pipes::oneshot(); // ()
let (c2,p2) = pipes::oneshot(); // bool
- let server: UnwrapProto = ~mut some((c1,p2));
+ let server: UnwrapProto = ~mut Some((c1,p2));
let serverp: libc::uintptr_t = unsafe::transmute(server);
// Try to put our server end in the unwrapper slot.
if rustrt::rust_compare_and_swap_ptr(&mut ptr.unwrapper, 0, serverp) {
} else {
// The *next* person who sees the refcount hit 0 will wake us.
let end_result =
- DeathThroes { ptr: some(ptr), response: some(c2) };
- let mut p1 = some(p1); // argh
+ DeathThroes { ptr: Some(ptr), response: Some(c2) };
+ let mut p1 = Some(p1); // argh
do task::rekillable {
pipes::recv_one(option::swap_unwrap(&mut p1));
}
type SharedMutableState<T: send> = ArcDestruct<T>;
unsafe fn shared_mutable_state<T: send>(+data: T) -> SharedMutableState<T> {
- let data = ~ArcData { count: 1, unwrapper: 0, data: some(data) };
+ let data = ~ArcData { count: 1, unwrapper: 0, data: Some(data) };
unsafe {
let ptr = unsafe::transmute(data);
ArcDestruct(ptr)
#[test]
fn exclusive_unwrap_contended() {
let x = exclusive(~~"hello");
- let x2 = ~mut some(x.clone());
+ let x2 = ~mut Some(x.clone());
do task::spawn {
let x2 = option::swap_unwrap(x2);
do x2.with |_hello| { }
// Now try the same thing, but with the child task blocking.
let x = exclusive(~~"hello");
- let x2 = ~mut some(x.clone());
- let mut res = none;
- do task::task().future_result(|+r| res = some(r)).spawn {
+ let x2 = ~mut Some(x.clone());
+ let mut res = None;
+ do task::task().future_result(|+r| res = Some(r)).spawn {
let x2 = option::swap_unwrap(x2);
assert unwrap_exclusive(x2) == ~~"hello";
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn exclusive_unwrap_conflict() {
let x = exclusive(~~"hello");
- let x2 = ~mut some(x.clone());
- let mut res = none;
- do task::task().future_result(|+r| res = some(r)).spawn {
+ let x2 = ~mut Some(x.clone());
+ let mut res = None;
+ do task::task().future_result(|+r| res = Some(r)).spawn {
let x2 = option::swap_unwrap(x2);
assert unwrap_exclusive(x2) == ~~"hello";
}
}
#[test]
fn test_replace() {
- let mut x = some(NonCopyable());
- let y = replace(&mut x, none);
+ let mut x = Some(NonCopyable());
+ let y = replace(&mut x, None);
assert x.is_none();
assert y.is_some();
}
//! Vectors
-import option::{some, none};
+import option::{Some, None};
import ptr::addr_of;
import libc::size_t;
* onto the vector being constructed.
*/
#[inline(always)]
-pure fn build_sized_opt<A>(size: option<uint>,
+pure fn build_sized_opt<A>(size: Option<uint>,
builder: fn(push: pure fn(+A))) -> ~[A] {
build_sized(size.get_default(4), builder)
}
}
/**
- * Returns `some(x)` where `x` is the last element of the slice `v`,
+ * Returns `Some(x)` where `x` is the last element of the slice `v`,
* or `none` if the vector is empty.
*/
-pure fn last_opt<T: copy>(v: &[const T]) -> option<T> {
- if len(v) == 0u { return none; }
- some(v[len(v) - 1u])
+pure fn last_opt<T: copy>(v: &[const T]) -> Option<T> {
+ if len(v) == 0u { return None; }
+ Some(v[len(v) - 1u])
}
/// Returns a copy of the elements from [`start`..`end`) from `v`.
let mut result = ~[];
while start < ln {
match position_between(v, start, ln, f) {
- none => break,
- some(i) => {
+ None => break,
+ Some(i) => {
push(result, slice(v, start, i));
start = i + 1u;
}
let mut result = ~[];
while start < ln && count > 0u {
match position_between(v, start, ln, f) {
- none => break,
- some(i) => {
+ None => break,
+ Some(i) => {
push(result, slice(v, start, i));
// Make sure to skip the separator.
start = i + 1u;
let mut result = ~[];
while end > 0u {
match rposition_between(v, 0u, end, f) {
- none => break,
- some(i) => {
+ None => break,
+ Some(i) => {
push(result, slice(v, i + 1u, end));
end = i;
}
let mut result = ~[];
while end > 0u && count > 0u {
match rposition_between(v, 0u, end, f) {
- none => break,
- some(i) => {
+ None => break,
+ Some(i) => {
push(result, slice(v, i + 1u, end));
// Make sure to skip the separator.
end = i;
* If function `f` returns `none` then that element is excluded from
* the resulting vector.
*/
-pure fn filter_map<T, U: copy>(v: &[T], f: fn(T) -> option<U>)
+pure fn filter_map<T, U: copy>(v: &[T], f: fn(T) -> Option<U>)
-> ~[U] {
let mut result = ~[];
for each(v) |elem| {
match f(elem) {
- none => {/* no-op */ }
- some(result_elem) => unsafe { push(result, result_elem); }
+ None => {/* no-op */ }
+ Some(result_elem) => unsafe { push(result, result_elem); }
}
}
return result;
* When function `f` returns true then an option containing the element
* is returned. If `f` matches no elements then none is returned.
*/
-pure fn find<T: copy>(v: &[T], f: fn(T) -> bool) -> option<T> {
+pure fn find<T: copy>(v: &[T], f: fn(T) -> bool) -> Option<T> {
find_between(v, 0u, len(v), f)
}
* the element is returned. If `f` matches no elements then none is returned.
*/
pure fn find_between<T: copy>(v: &[T], start: uint, end: uint,
- f: fn(T) -> bool) -> option<T> {
+ f: fn(T) -> bool) -> Option<T> {
option::map(position_between(v, start, end, f), |i| v[i])
}
* `f` returns true then an option containing the element is returned. If `f`
* matches no elements then none is returned.
*/
-pure fn rfind<T: copy>(v: &[T], f: fn(T) -> bool) -> option<T> {
+pure fn rfind<T: copy>(v: &[T], f: fn(T) -> bool) -> Option<T> {
rfind_between(v, 0u, len(v), f)
}
* the element is returned. If `f` matches no elements then none is returned.
*/
pure fn rfind_between<T: copy>(v: &[T], start: uint, end: uint,
- f: fn(T) -> bool) -> option<T> {
+ f: fn(T) -> bool) -> Option<T> {
option::map(rposition_between(v, start, end, f), |i| v[i])
}
/// Find the first index containing a matching value
-pure fn position_elem<T>(v: &[T], x: T) -> option<uint> {
+pure fn position_elem<T>(v: &[T], x: T) -> Option<uint> {
position(v, |y| x == y)
}
* then an option containing the index is returned. If `f` matches no elements
* then none is returned.
*/
-pure fn position<T>(v: &[T], f: fn(T) -> bool) -> option<uint> {
+pure fn position<T>(v: &[T], f: fn(T) -> bool) -> Option<uint> {
position_between(v, 0u, len(v), f)
}
* the index is returned. If `f` matches no elements then none is returned.
*/
pure fn position_between<T>(v: &[T], start: uint, end: uint,
- f: fn(T) -> bool) -> option<uint> {
+ f: fn(T) -> bool) -> Option<uint> {
assert start <= end;
assert end <= len(v);
let mut i = start;
- while i < end { if f(v[i]) { return some::<uint>(i); } i += 1u; }
- return none;
+ while i < end { if f(v[i]) { return Some::<uint>(i); } i += 1u; }
+ return None;
}
/// Find the last index containing a matching value
-pure fn rposition_elem<T>(v: &[T], x: T) -> option<uint> {
+pure fn rposition_elem<T>(v: &[T], x: T) -> Option<uint> {
rposition(v, |y| x == y)
}
* `f` returns true then an option containing the index is returned. If `f`
* matches no elements then none is returned.
*/
-pure fn rposition<T>(v: &[T], f: fn(T) -> bool) -> option<uint> {
+pure fn rposition<T>(v: &[T], f: fn(T) -> bool) -> Option<uint> {
rposition_between(v, 0u, len(v), f)
}
* returned.
*/
pure fn rposition_between<T>(v: &[T], start: uint, end: uint,
- f: fn(T) -> bool) -> option<uint> {
+ f: fn(T) -> bool) -> Option<uint> {
assert start <= end;
assert end <= len(v);
let mut i = end;
while i > start {
- if f(v[i - 1u]) { return some::<uint>(i - 1u); }
+ if f(v[i - 1u]) { return Some::<uint>(i - 1u); }
i -= 1u;
}
- return none;
+ return None;
}
// FIXME: if issue #586 gets implemented, could have a postcondition
pure fn foldr<U: copy>(z: U, p: fn(T, U) -> U) -> U;
pure fn iter(f: fn(T));
pure fn iteri(f: fn(uint, T));
- pure fn position(f: fn(T) -> bool) -> option<uint>;
- pure fn position_elem(x: T) -> option<uint>;
+ pure fn position(f: fn(T) -> bool) -> Option<uint>;
+ pure fn position_elem(x: T) -> Option<uint>;
pure fn riter(f: fn(T));
pure fn riteri(f: fn(uint, T));
- pure fn rposition(f: fn(T) -> bool) -> option<uint>;
- pure fn rposition_elem(x: T) -> option<uint>;
+ pure fn rposition(f: fn(T) -> bool) -> Option<uint>;
+ pure fn rposition_elem(x: T) -> Option<uint>;
pure fn map<U>(f: fn(T) -> U) -> ~[U];
pure fn mapi<U>(f: fn(uint, T) -> U) -> ~[U];
fn map_r<U>(f: fn(x: &T) -> U) -> ~[U];
pure fn alli(f: fn(uint, T) -> bool) -> bool;
pure fn flat_map<U>(f: fn(T) -> ~[U]) -> ~[U];
- pure fn filter_map<U: copy>(f: fn(T) -> option<U>) -> ~[U];
+ pure fn filter_map<U: copy>(f: fn(T) -> Option<U>) -> ~[U];
}
/// Extension methods for vectors
* elements then none is returned.
*/
#[inline]
- pure fn position(f: fn(T) -> bool) -> option<uint> { position(self, f) }
+ pure fn position(f: fn(T) -> bool) -> Option<uint> { position(self, f) }
/// Find the first index containing a matching value
#[inline]
- pure fn position_elem(x: T) -> option<uint> { position_elem(self, x) }
+ pure fn position_elem(x: T) -> Option<uint> { position_elem(self, x) }
/**
* Iterates over a vector in reverse
*
* returned. If `f` matches no elements then none is returned.
*/
#[inline]
- pure fn rposition(f: fn(T) -> bool) -> option<uint> { rposition(self, f) }
+ pure fn rposition(f: fn(T) -> bool) -> Option<uint> { rposition(self, f) }
/// Find the last index containing a matching value
#[inline]
- pure fn rposition_elem(x: T) -> option<uint> { rposition_elem(self, x) }
+ pure fn rposition_elem(x: T) -> Option<uint> { rposition_elem(self, x) }
/// Apply a function to each element of a vector and return the results
#[inline]
pure fn map<U>(f: fn(T) -> U) -> ~[U] { map(self, f) }
* the resulting vector.
*/
#[inline]
- pure fn filter_map<U: copy>(f: fn(T) -> option<U>) -> ~[U] {
+ pure fn filter_map<U: copy>(f: fn(T) -> Option<U>) -> ~[U] {
filter_map(self, f)
}
}
trait ImmutableCopyableVector<T> {
pure fn filter(f: fn(T) -> bool) -> ~[T];
- pure fn rfind(f: fn(T) -> bool) -> option<T>;
+ pure fn rfind(f: fn(T) -> bool) -> Option<T>;
}
/// Extension methods for vectors
* returned. If `f` matches no elements then none is returned.
*/
#[inline]
- pure fn rfind(f: fn(T) -> bool) -> option<T> { rfind(self, f) }
+ pure fn rfind(f: fn(T) -> bool) -> Option<T> { rfind(self, f) }
}
/// Unsafe operations
*/
#[inline(always)]
unsafe fn set<T>(v: &[mut T], i: uint, +val: T) {
- let mut box = some(val);
+ let mut box = Some(val);
do as_mut_buf(v) |p, _len| {
- let mut box2 = none;
+ let mut box2 = None;
box2 <-> box;
rusti::move_val_init(*ptr::mut_offset(p, i),
option::unwrap(box2));
impl<A> &[A]: iter::BaseIter<A> {
pure fn each(blk: fn(A) -> bool) { each(self, blk) }
- pure fn size_hint() -> option<uint> { some(len(self)) }
+ pure fn size_hint() -> Option<uint> { Some(len(self)) }
}
impl<A> &[A]: iter::ExtendedIter<A> {
}
pure fn contains(x: A) -> bool { iter::contains(self, x) }
pure fn count(x: A) -> uint { iter::count(self, x) }
- pure fn position(f: fn(A) -> bool) -> option<uint> {
+ pure fn position(f: fn(A) -> bool) -> Option<uint> {
iter::position(self, f)
}
}
pure fn min() -> A { iter::min(self) }
pure fn max() -> A { iter::max(self) }
- pure fn find(p: fn(A) -> bool) -> option<A> { iter::find(self, p) }
+ pure fn find(p: fn(A) -> bool) -> Option<A> { iter::find(self, p) }
}
// ___________________________________________________________________________
pure fn is_equal(&&x: uint, &&y:uint) -> bool { return x == y; }
- fn square_if_odd(&&n: uint) -> option<uint> {
- return if n % 2u == 1u { some(n * n) } else { none };
+ fn square_if_odd(&&n: uint) -> Option<uint> {
+ return if n % 2u == 1u { Some(n * n) } else { None };
}
fn add(&&x: uint, &&y: uint) -> uint { return x + y; }
#[test]
fn test_last() {
let mut n = last_opt(~[]);
- assert (n == none);
+ assert (n == None);
n = last_opt(~[1, 2, 3]);
- assert (n == some(3));
+ assert (n == Some(3));
n = last_opt(~[1, 2, 3, 4, 5]);
- assert (n == some(5));
+ assert (n == Some(5));
}
#[test]
assert (w[1] == 9u);
assert (w[2] == 25u);
- fn halve(&&i: int) -> option<int> {
+ fn halve(&&i: int) -> Option<int> {
if i % 2 == 0 {
- return option::some::<int>(i / 2);
- } else { return option::none::<int>; }
+ return option::Some::<int>(i / 2);
+ } else { return option::None::<int>; }
}
fn halve_for_sure(&&i: int) -> int { return i / 2; }
let all_even: ~[int] = ~[0, 2, 8, 6];
#[test]
fn test_position_elem() {
- assert position_elem(~[], 1) == none;
+ assert position_elem(~[], 1) == None;
let v1 = ~[1, 2, 3, 3, 2, 5];
- assert position_elem(v1, 1) == some(0u);
- assert position_elem(v1, 2) == some(1u);
- assert position_elem(v1, 5) == some(5u);
- assert position_elem(v1, 4) == none;
+ assert position_elem(v1, 1) == Some(0u);
+ assert position_elem(v1, 2) == Some(1u);
+ assert position_elem(v1, 5) == Some(5u);
+ assert position_elem(v1, 4) == None;
}
#[test]
fn less_than_three(&&i: int) -> bool { return i < 3; }
fn is_eighteen(&&i: int) -> bool { return i == 18; }
- assert position(~[], less_than_three) == none;
+ assert position(~[], less_than_three) == None;
let v1 = ~[5, 4, 3, 2, 1];
- assert position(v1, less_than_three) == some(3u);
- assert position(v1, is_eighteen) == none;
+ assert position(v1, less_than_three) == Some(3u);
+ assert position(v1, is_eighteen) == None;
}
#[test]
fn test_position_between() {
- assert position_between(~[], 0u, 0u, f) == none;
+ assert position_between(~[], 0u, 0u, f) == None;
fn f(xy: (int, char)) -> bool { let (_x, y) = xy; y == 'b' }
let mut v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
- assert position_between(v, 0u, 0u, f) == none;
- assert position_between(v, 0u, 1u, f) == none;
- assert position_between(v, 0u, 2u, f) == some(1u);
- assert position_between(v, 0u, 3u, f) == some(1u);
- assert position_between(v, 0u, 4u, f) == some(1u);
+ assert position_between(v, 0u, 0u, f) == None;
+ assert position_between(v, 0u, 1u, f) == None;
+ assert position_between(v, 0u, 2u, f) == Some(1u);
+ assert position_between(v, 0u, 3u, f) == Some(1u);
+ assert position_between(v, 0u, 4u, f) == Some(1u);
- assert position_between(v, 1u, 1u, f) == none;
- assert position_between(v, 1u, 2u, f) == some(1u);
- assert position_between(v, 1u, 3u, f) == some(1u);
- assert position_between(v, 1u, 4u, f) == some(1u);
+ assert position_between(v, 1u, 1u, f) == None;
+ assert position_between(v, 1u, 2u, f) == Some(1u);
+ assert position_between(v, 1u, 3u, f) == Some(1u);
+ assert position_between(v, 1u, 4u, f) == Some(1u);
- assert position_between(v, 2u, 2u, f) == none;
- assert position_between(v, 2u, 3u, f) == none;
- assert position_between(v, 2u, 4u, f) == some(3u);
+ assert position_between(v, 2u, 2u, f) == None;
+ assert position_between(v, 2u, 3u, f) == None;
+ assert position_between(v, 2u, 4u, f) == Some(3u);
- assert position_between(v, 3u, 3u, f) == none;
- assert position_between(v, 3u, 4u, f) == some(3u);
+ assert position_between(v, 3u, 3u, f) == None;
+ assert position_between(v, 3u, 4u, f) == Some(3u);
- assert position_between(v, 4u, 4u, f) == none;
+ assert position_between(v, 4u, 4u, f) == None;
}
#[test]
fn test_find() {
- assert find(~[], f) == none;
+ assert find(~[], f) == None;
fn f(xy: (int, char)) -> bool { let (_x, y) = xy; y == 'b' }
fn g(xy: (int, char)) -> bool { let (_x, y) = xy; y == 'd' }
let mut v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
- assert find(v, f) == some((1, 'b'));
- assert find(v, g) == none;
+ assert find(v, f) == Some((1, 'b'));
+ assert find(v, g) == None;
}
#[test]
fn test_find_between() {
- assert find_between(~[], 0u, 0u, f) == none;
+ assert find_between(~[], 0u, 0u, f) == None;
fn f(xy: (int, char)) -> bool { let (_x, y) = xy; y == 'b' }
let mut v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
- assert find_between(v, 0u, 0u, f) == none;
- assert find_between(v, 0u, 1u, f) == none;
- assert find_between(v, 0u, 2u, f) == some((1, 'b'));
- assert find_between(v, 0u, 3u, f) == some((1, 'b'));
- assert find_between(v, 0u, 4u, f) == some((1, 'b'));
+ assert find_between(v, 0u, 0u, f) == None;
+ assert find_between(v, 0u, 1u, f) == None;
+ assert find_between(v, 0u, 2u, f) == Some((1, 'b'));
+ assert find_between(v, 0u, 3u, f) == Some((1, 'b'));
+ assert find_between(v, 0u, 4u, f) == Some((1, 'b'));
- assert find_between(v, 1u, 1u, f) == none;
- assert find_between(v, 1u, 2u, f) == some((1, 'b'));
- assert find_between(v, 1u, 3u, f) == some((1, 'b'));
- assert find_between(v, 1u, 4u, f) == some((1, 'b'));
+ assert find_between(v, 1u, 1u, f) == None;
+ assert find_between(v, 1u, 2u, f) == Some((1, 'b'));
+ assert find_between(v, 1u, 3u, f) == Some((1, 'b'));
+ assert find_between(v, 1u, 4u, f) == Some((1, 'b'));
- assert find_between(v, 2u, 2u, f) == none;
- assert find_between(v, 2u, 3u, f) == none;
- assert find_between(v, 2u, 4u, f) == some((3, 'b'));
+ assert find_between(v, 2u, 2u, f) == None;
+ assert find_between(v, 2u, 3u, f) == None;
+ assert find_between(v, 2u, 4u, f) == Some((3, 'b'));
- assert find_between(v, 3u, 3u, f) == none;
- assert find_between(v, 3u, 4u, f) == some((3, 'b'));
+ assert find_between(v, 3u, 3u, f) == None;
+ assert find_between(v, 3u, 4u, f) == Some((3, 'b'));
- assert find_between(v, 4u, 4u, f) == none;
+ assert find_between(v, 4u, 4u, f) == None;
}
#[test]
fn test_rposition() {
- assert find(~[], f) == none;
+ assert find(~[], f) == None;
fn f(xy: (int, char)) -> bool { let (_x, y) = xy; y == 'b' }
fn g(xy: (int, char)) -> bool { let (_x, y) = xy; y == 'd' }
let mut v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
- assert position(v, f) == some(1u);
- assert position(v, g) == none;
+ assert position(v, f) == Some(1u);
+ assert position(v, g) == None;
}
#[test]
fn test_rposition_between() {
- assert rposition_between(~[], 0u, 0u, f) == none;
+ assert rposition_between(~[], 0u, 0u, f) == None;
fn f(xy: (int, char)) -> bool { let (_x, y) = xy; y == 'b' }
let mut v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
- assert rposition_between(v, 0u, 0u, f) == none;
- assert rposition_between(v, 0u, 1u, f) == none;
- assert rposition_between(v, 0u, 2u, f) == some(1u);
- assert rposition_between(v, 0u, 3u, f) == some(1u);
- assert rposition_between(v, 0u, 4u, f) == some(3u);
+ assert rposition_between(v, 0u, 0u, f) == None;
+ assert rposition_between(v, 0u, 1u, f) == None;
+ assert rposition_between(v, 0u, 2u, f) == Some(1u);
+ assert rposition_between(v, 0u, 3u, f) == Some(1u);
+ assert rposition_between(v, 0u, 4u, f) == Some(3u);
- assert rposition_between(v, 1u, 1u, f) == none;
- assert rposition_between(v, 1u, 2u, f) == some(1u);
- assert rposition_between(v, 1u, 3u, f) == some(1u);
- assert rposition_between(v, 1u, 4u, f) == some(3u);
+ assert rposition_between(v, 1u, 1u, f) == None;
+ assert rposition_between(v, 1u, 2u, f) == Some(1u);
+ assert rposition_between(v, 1u, 3u, f) == Some(1u);
+ assert rposition_between(v, 1u, 4u, f) == Some(3u);
- assert rposition_between(v, 2u, 2u, f) == none;
- assert rposition_between(v, 2u, 3u, f) == none;
- assert rposition_between(v, 2u, 4u, f) == some(3u);
+ assert rposition_between(v, 2u, 2u, f) == None;
+ assert rposition_between(v, 2u, 3u, f) == None;
+ assert rposition_between(v, 2u, 4u, f) == Some(3u);
- assert rposition_between(v, 3u, 3u, f) == none;
- assert rposition_between(v, 3u, 4u, f) == some(3u);
+ assert rposition_between(v, 3u, 3u, f) == None;
+ assert rposition_between(v, 3u, 4u, f) == Some(3u);
- assert rposition_between(v, 4u, 4u, f) == none;
+ assert rposition_between(v, 4u, 4u, f) == None;
}
#[test]
fn test_rfind() {
- assert rfind(~[], f) == none;
+ assert rfind(~[], f) == None;
fn f(xy: (int, char)) -> bool { let (_x, y) = xy; y == 'b' }
fn g(xy: (int, char)) -> bool { let (_x, y) = xy; y == 'd' }
let mut v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
- assert rfind(v, f) == some((3, 'b'));
- assert rfind(v, g) == none;
+ assert rfind(v, f) == Some((3, 'b'));
+ assert rfind(v, g) == None;
}
#[test]
fn test_rfind_between() {
- assert rfind_between(~[], 0u, 0u, f) == none;
+ assert rfind_between(~[], 0u, 0u, f) == None;
fn f(xy: (int, char)) -> bool { let (_x, y) = xy; y == 'b' }
let mut v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
- assert rfind_between(v, 0u, 0u, f) == none;
- assert rfind_between(v, 0u, 1u, f) == none;
- assert rfind_between(v, 0u, 2u, f) == some((1, 'b'));
- assert rfind_between(v, 0u, 3u, f) == some((1, 'b'));
- assert rfind_between(v, 0u, 4u, f) == some((3, 'b'));
+ assert rfind_between(v, 0u, 0u, f) == None;
+ assert rfind_between(v, 0u, 1u, f) == None;
+ assert rfind_between(v, 0u, 2u, f) == Some((1, 'b'));
+ assert rfind_between(v, 0u, 3u, f) == Some((1, 'b'));
+ assert rfind_between(v, 0u, 4u, f) == Some((3, 'b'));
- assert rfind_between(v, 1u, 1u, f) == none;
- assert rfind_between(v, 1u, 2u, f) == some((1, 'b'));
- assert rfind_between(v, 1u, 3u, f) == some((1, 'b'));
- assert rfind_between(v, 1u, 4u, f) == some((3, 'b'));
+ assert rfind_between(v, 1u, 1u, f) == None;
+ assert rfind_between(v, 1u, 2u, f) == Some((1, 'b'));
+ assert rfind_between(v, 1u, 3u, f) == Some((1, 'b'));
+ assert rfind_between(v, 1u, 4u, f) == Some((3, 'b'));
- assert rfind_between(v, 2u, 2u, f) == none;
- assert rfind_between(v, 2u, 3u, f) == none;
- assert rfind_between(v, 2u, 4u, f) == some((3, 'b'));
+ assert rfind_between(v, 2u, 2u, f) == None;
+ assert rfind_between(v, 2u, 3u, f) == None;
+ assert rfind_between(v, 2u, 4u, f) == Some((3, 'b'));
- assert rfind_between(v, 3u, 3u, f) == none;
- assert rfind_between(v, 3u, 4u, f) == some((3, 'b'));
+ assert rfind_between(v, 3u, 3u, f) == None;
+ assert rfind_between(v, 3u, 4u, f) == Some((3, 'b'));
- assert rfind_between(v, 4u, 4u, f) == none;
+ assert rfind_between(v, 4u, 4u, f) == None;
}
#[test]
let arc = ~mutex_arc(false);
let arc2 = ~arc.clone();
let (c,p) = pipes::oneshot();
- let (c,p) = (~mut some(c), ~mut some(p));
+ let (c,p) = (~mut Some(c), ~mut Some(p));
do task::spawn {
// wait until parent gets in
pipes::recv_one(option::swap_unwrap(p));
}
struct dtor_res {
- let dtor: option<fn@()>;
- new(dtor: option<fn@()>) { self.dtor = dtor; }
+ let dtor: Option<fn@()>;
+ new(dtor: Option<fn@()>) { self.dtor = dtor; }
drop {
match self.dtor {
- option::none => (),
- option::some(f) => f()
+ option::None => (),
+ option::Some(f) => f()
}
}
}
return c_vec_({
base: base,
len: len,
- rsrc: @dtor_res(option::none)
+ rsrc: @dtor_res(option::None)
});
}
return c_vec_({
base: base,
len: len,
- rsrc: @dtor_res(option::some(dtor))
+ rsrc: @dtor_res(option::Some(dtor))
});
}
/// Similar to a mutable option type, but friendlier.
struct Cell<T> {
- mut value: option<T>;
+ mut value: Option<T>;
}
/// Creates a new full cell with the given value.
fn Cell<T>(+value: T) -> Cell<T> {
- Cell { value: some(move value) }
+ Cell { value: Some(move value) }
}
fn empty_cell<T>() -> Cell<T> {
- Cell { value: none }
+ Cell { value: None }
}
impl<T> Cell<T> {
fail ~"attempt to take an empty cell";
}
- let mut value = none;
+ let mut value = None;
value <-> self.value;
return option::unwrap(value);
}
if !self.is_empty() {
fail ~"attempt to put a value back into a full cell";
}
- self.value = some(move value);
+ self.value = Some(move value);
}
/// Returns true if the cell is empty and false if the cell is full.
self.port.recv()
}
- fn try_recv() -> option<U> {
+ fn try_recv() -> Option<U> {
self.port.try_recv()
}
//! A deque. Untested as of yet. Likely buggy
-import option::{some, none};
+import option::{Some, None};
import dvec::{DVec, dvec};
trait t<T> {
// FIXME (#2343) eventually, a proper datatype plus an exported impl would
// be preferrable.
fn create<T: copy>() -> t<T> {
- type cell<T> = option<T>;
+ type cell<T> = Option<T>;
let initial_capacity: uint = 32u; // 2^5
/**
while i < nalloc {
if i < nelts {
vec::push(rv, elts[(lo + i) % nelts]);
- } else { vec::push(rv, none); }
+ } else { vec::push(rv, None); }
i += 1u;
}
return rv;
}
fn get<T: copy>(elts: DVec<cell<T>>, i: uint) -> T {
- match elts.get_elt(i) { some(t) => t, _ => fail }
+ match elts.get_elt(i) { Some(t) => t, _ => fail }
}
type repr<T> = {mut nelts: uint,
self.lo = self.elts.len() - 1u;
self.hi = self.nelts;
}
- self.elts.set_elt(self.lo, some(t));
+ self.elts.set_elt(self.lo, Some(t));
self.nelts += 1u;
}
fn add_back(t: T) {
self.lo = 0u;
self.hi = self.nelts;
}
- self.elts.set_elt(self.hi, some(t));
+ self.elts.set_elt(self.hi, Some(t));
self.hi = (self.hi + 1u) % self.elts.len();
self.nelts += 1u;
}
*/
fn pop_front() -> T {
let t: T = get(self.elts, self.lo);
- self.elts.set_elt(self.lo, none);
+ self.elts.set_elt(self.lo, None);
self.lo = (self.lo + 1u) % self.elts.len();
self.nelts -= 1u;
return t;
self.hi = self.elts.len() - 1u;
} else { self.hi -= 1u; }
let t: T = get(self.elts, self.hi);
- self.elts.set_elt(self.hi, none);
+ self.elts.set_elt(self.hi, None);
self.nelts -= 1u;
return t;
}
elts:
dvec::from_vec(
vec::to_mut(
- vec::from_elem(initial_capacity, none)))
+ vec::from_elem(initial_capacity, None)))
};
repr as t::<T>
}
// Simple Extensible Binary Markup Language (ebml) reader and writer on a
// cursor model. See the specification here:
// http://www.matroska.org/technical/specs/rfc/index.html
-import core::option;
-import option::{some, none};
+import core::Option;
+import option::{Some, None};
export doc;
export doc_at;
doc: {data: data, start: elt_size.next, end: end}};
}
-fn maybe_get_doc(d: doc, tg: uint) -> option<doc> {
+fn maybe_get_doc(d: doc, tg: uint) -> Option<doc> {
let mut pos = d.start;
while pos < d.end {
let elt_tag = vuint_at(*d.data, pos);
let elt_size = vuint_at(*d.data, elt_tag.next);
pos = elt_size.next + elt_size.val;
if elt_tag.val == tg {
- return some::<doc>({
+ return Some::<doc>({
data: d.data,
start: elt_size.next,
end: pos
});
}
}
- return none::<doc>;
+ return None::<doc>;
}
fn get_doc(d: doc, tg: uint) -> doc {
match maybe_get_doc(d, tg) {
- some(d) => return d,
- none => {
+ Some(d) => return d,
+ None => {
error!("failed to find block with tag %u", tg);
fail;
}
s.emit_i64(v as i64);
}
- fn serialize_0<S: serialization::serializer>(s: S, v: option<int>) {
+ fn serialize_0<S: serialization::serializer>(s: S, v: Option<int>) {
do s.emit_enum(~"core::option::t") {
match v {
- none => s.emit_enum_variant(
- ~"core::option::none", 0u, 0u, || { } ),
- some(v0) => {
+ None => s.emit_enum_variant(
+ ~"core::option::None", 0u, 0u, || { } ),
+ Some(v0) => {
do s.emit_enum_variant(~"core::option::some", 1u, 1u) {
s.emit_enum_variant_arg(0u, || serialize_1(s, v0));
}
s.read_i64() as int
}
- fn deserialize_0<S: serialization::deserializer>(s: S) -> option<int> {
+ fn deserialize_0<S: serialization::deserializer>(s: S) -> Option<int> {
do s.read_enum(~"core::option::t") {
do s.read_enum_variant |i| {
match i {
- 0 => none,
+ 0 => None,
1 => {
let v0 = do s.read_enum_variant_arg(0u) {
deserialize_1(s)
};
- some(v0)
+ Some(v0)
}
_ => {
fail #fmt("deserialize_0: unexpected variant %u", i);
}
}
- fn test_v(v: option<int>) {
+ fn test_v(v: Option<int>) {
debug!("v == %?", v);
let mbuf = io::mem_buffer();
let ebml_w = ebml::writer(io::mem_buffer_writer(mbuf));
assert v == v1;
}
- test_v(some(22));
- test_v(none);
- test_v(some(3));
+ test_v(Some(22));
+ test_v(None);
+ test_v(Some(3));
}
* of features.
*/
-import option::{some, none};
+import option::{Some, None};
import option = option;
export treemap;
}
/// Find a value based on the key
-fn find<K, V: copy>(m: treemap<K, V>, k: K) -> option<V> {
+fn find<K, V: copy>(m: treemap<K, V>, k: K) -> Option<V> {
match *m {
- empty => none,
+ empty => None,
node(@kk, @v, left, right) => {
if k == kk {
- some(v)
+ Some(v)
} else if k < kk { find(left, k) } else { find(right, k) }
}
}
* import std::getopts::{optopt,optflag,getopts,opt_present,opt_maybe_str,
* fail_str};
*
- * fn do_work(in: str, out: option<str>) {
+ * fn do_work(in: str, out: Option<str>) {
* // ...
* }
*
import core::result::{err, ok};
import core::option;
-import core::option::{some, none};
+import core::option::{Some, None};
export opt;
export reqopt;
export optopt;
};
}
-fn find_opt(opts: ~[opt], nm: name) -> option<uint> {
+fn find_opt(opts: ~[opt], nm: name) -> Option<uint> {
vec::position(opts, |opt| opt.name == nm)
}
break;
} else {
let mut names;
- let mut i_arg = option::none::<~str>;
+ let mut i_arg = option::None::<~str>;
if cur[1] == '-' as u8 {
let tail = str::slice(cur, 2u, curlen);
let tail_eq = str::splitn_char(tail, '=', 1u);
names =
~[long(tail_eq[0])];
i_arg =
- option::some::<~str>(tail_eq[1]);
+ option::Some::<~str>(tail_eq[1]);
}
} else {
let mut j = 1u;
- let mut last_valid_opt_id = option::none;
+ let mut last_valid_opt_id = option::None;
names = ~[];
while j < curlen {
let range = str::char_range_at(cur, j);
*/
match find_opt(opts, opt) {
- some(id) => last_valid_opt_id = option::some(id),
- none => {
+ Some(id) => last_valid_opt_id = option::Some(id),
+ None => {
let arg_follows =
option::is_some(last_valid_opt_id) &&
match opts[option::get(last_valid_opt_id)]
no => false
};
if arg_follows && j + 1 < curlen {
- i_arg = option::some(str::slice(cur, j, curlen));
+ i_arg = option::Some(str::slice(cur, j, curlen));
break;
} else {
- last_valid_opt_id = option::none;
+ last_valid_opt_id = option::None;
}
}
}
for vec::each(names) |nm| {
name_pos += 1u;
let optid = match find_opt(opts, nm) {
- some(id) => id,
- none => return err(unrecognized_option(name_str(nm)))
+ Some(id) => id,
+ None => return err(unrecognized_option(name_str(nm)))
};
match opts[optid].hasarg {
no => {
fn opt_vals(m: matches, nm: ~str) -> ~[optval] {
return match find_opt(m.opts, mkname(nm)) {
- some(id) => m.vals[id],
- none => {
+ Some(id) => m.vals[id],
+ None => {
error!("No option '%s' defined", nm);
fail
}
fn opts_present(m: matches, names: ~[~str]) -> bool {
for vec::each(names) |nm| {
match find_opt(m.opts, mkname(nm)) {
- some(_) => return true,
+ Some(_) => return true,
_ => ()
}
}
}
/// Returns the string argument supplied to a matching option or none
-fn opt_maybe_str(m: matches, nm: ~str) -> option<~str> {
+fn opt_maybe_str(m: matches, nm: ~str) -> Option<~str> {
let vals = opt_vals(m, nm);
- if vec::len::<optval>(vals) == 0u { return none::<~str>; }
- return match vals[0] { val(s) => some::<~str>(s), _ => none::<~str> };
+ if vec::len::<optval>(vals) == 0u { return None::<~str>; }
+ return match vals[0] { val(s) => Some::<~str>(s), _ => None::<~str> };
}
* present but no argument was provided, and the argument if the option was
* present and an argument was provided.
*/
-fn opt_default(m: matches, nm: ~str, def: ~str) -> option<~str> {
+fn opt_default(m: matches, nm: ~str, def: ~str) -> Option<~str> {
let vals = opt_vals(m, nm);
- if vec::len::<optval>(vals) == 0u { return none::<~str>; }
- return match vals[0] { val(s) => some::<~str>(s), _ => some::<~str>(def) }
+ if vec::len::<optval>(vals) == 0u { return None::<~str>; }
+ return match vals[0] { val(s) => Some::<~str>(s), _ => Some::<~str>(def) }
}
#[cfg(test)]
let mut equal = true;
for d0.each |k, v0| {
match d1.find(k) {
- some(v1) => if !eq(v0, v1) { equal = false },
- none => equal = false
+ Some(v1) => if !eq(v0, v1) { equal = false },
+ None => equal = false
}
};
equal
}
}
-impl <A: to_json> option<A>: to_json {
+impl <A: to_json> Option<A>: to_json {
fn to_json() -> json {
match self {
- none => null,
- some(value) => value.to_json()
+ None => null,
+ Some(value) => value.to_json()
}
}
}
import core::option;
import option::*;
-import option::{some, none};
+import option::{Some, None};
enum list<T> {
cons(T, @list<T>),
* When function `f` returns true then an option containing the element
* is returned. If `f` matches no elements then none is returned.
*/
-fn find<T: copy>(ls: @list<T>, f: fn(T) -> bool) -> option<T> {
+fn find<T: copy>(ls: @list<T>, f: fn(T) -> bool) -> Option<T> {
let mut ls = ls;
loop {
ls = match *ls {
cons(hd, tl) => {
- if f(hd) { return some(hd); }
+ if f(hd) { return Some(hd); }
tl
}
- nil => return none
+ nil => return None
}
};
}
fn test_find_success() {
fn match_(&&i: int) -> bool { return i == 2; }
let l = from_vec(~[0, 1, 2]);
- assert (list::find(l, match_) == option::some(2));
+ assert (list::find(l, match_) == option::Some(2));
}
#[test]
fn match_(&&_i: int) -> bool { return false; }
let l = from_vec(~[0, 1, 2]);
let empty = @list::nil::<int>;
- assert (list::find(l, match_) == option::none::<int>);
- assert (list::find(empty, match_) == option::none::<int>);
+ assert (list::find(l, match_) == option::None::<int>);
+ assert (list::find(empty, match_) == option::None::<int>);
}
#[test]
* Get the value for the specified key. If the key does not exist in
* the map then returns none.
*/
- fn find(+key: K) -> option<V>;
+ fn find(+key: K) -> Option<V>;
/**
* Remove and return a value from the map. Returns true if the
hash: uint;
key: K;
value: V;
- mut next: option<@entry<K, V>>;
+ mut next: Option<@entry<K, V>>;
}
struct hashmap_<K, V> {
mut count: uint;
- mut chains: ~[mut option<@entry<K,V>>];
+ mut chains: ~[mut Option<@entry<K,V>>];
hasher: hashfn<K>;
eqer: eqfn<K>;
}
let mut comp = 1u; // for logging
loop {
match copy e0.next {
- none => {
+ None => {
debug!("search_tbl: absent, comp %u, hash %u, idx %u",
comp, h, idx);
return not_found;
}
- some(e1) => {
+ Some(e1) => {
comp += 1u;
if e1.hash == h && self.eqer(&e1.key, k) {
debug!("search_tbl: present, comp %u, \
fn search_tbl(k: &K, h: uint) -> search_result<K,V> {
let idx = h % vec::len(self.chains);
match copy self.chains[idx] {
- none => {
+ None => {
debug!("search_tbl: none, comp %u, hash %u, idx %u",
0u, h, idx);
return not_found;
}
- some(e) => {
+ Some(e) => {
if e.hash == h && self.eqer(&e.key, k) {
debug!("search_tbl: present, comp %u, hash %u, idx %u",
1u, h, idx);
for self.each_entry |entry| {
let idx = entry.hash % n_new_chains;
entry.next = new_chains[idx];
- new_chains[idx] = some(entry);
+ new_chains[idx] = Some(entry);
}
self.chains = new_chains;
}
let mut chain = self.chains[i];
loop {
chain = match chain {
- none => break,
- some(entry) => {
+ None => break,
+ Some(entry) => {
let next = entry.next;
if !blk(entry) { return; }
next
self.count += 1u;
let idx = hash % vec::len(self.chains);
let old_chain = self.chains[idx];
- self.chains[idx] = some(@entry {
+ self.chains[idx] = Some(@entry {
hash: hash,
key: k,
value: v,
return true;
}
found_first(idx, entry) => {
- self.chains[idx] = some(@entry {
+ self.chains[idx] = Some(@entry {
hash: hash,
key: k,
value: v,
return false;
}
found_after(prev, entry) => {
- prev.next = some(@entry {
+ prev.next = Some(@entry {
hash: hash,
key: k,
value: v,
}
}
- fn find(+k: K) -> option<V> {
+ fn find(+k: K) -> Option<V> {
match self.search_tbl(&k, self.hasher(&k)) {
- not_found => none,
- found_first(_, entry) => some(entry.value),
- found_after(_, entry) => some(entry.value)
+ not_found => None,
+ found_first(_, entry) => Some(entry.value),
+ found_after(_, entry) => Some(entry.value)
}
}
}
}
- fn chains<K,V>(nchains: uint) -> ~[mut option<@entry<K,V>>] {
- vec::to_mut(vec::from_elem(nchains, none))
+ fn chains<K,V>(nchains: uint) -> ~[mut Option<@entry<K,V>>] {
+ vec::to_mut(vec::from_elem(nchains, None))
}
fn mk<K, V: copy>(+hasher: hashfn<K>, +eqer: eqfn<K>) -> t<K,V> {
}
}
- fn find(+key: K) -> option<V> {
+ fn find(+key: K) -> Option<V> {
do self.borrow_const |p| {
p.find(&key)
}
fn parse_to_ipv4_rep(ip: ~str) -> result::result<ipv4_rep, ~str> {
let parts = vec::map(str::split_char(ip, '.'), |s| {
match uint::from_str(s) {
- some(n) if n <= 255u => n,
+ Some(n) if n <= 255u => n,
_ => 256u
}
});
let client_stream_handle_ptr =
(*client_socket_data_ptr).stream_handle_ptr;
- let result_po = core::comm::port::<option<tcp_err_data>>();
+ let result_po = core::comm::port::<Option<tcp_err_data>>();
let result_ch = core::comm::chan(result_po);
// UNSAFE LIBUV INTERACTION BEGIN
uv::ll::set_data_for_uv_handle(client_stream_handle_ptr,
client_socket_data_ptr
as *libc::c_void);
- core::comm::send(result_ch, none);
+ core::comm::send(result_ch, None);
}
_ => {
log(debug, ~"failed to accept client conn");
- core::comm::send(result_ch, some(
+ core::comm::send(result_ch, Some(
uv::ll::get_last_err_data(loop_ptr).to_tcp_err()));
}
}
}
_ => {
log(debug, ~"failed to init client stream");
- core::comm::send(result_ch, some(
+ core::comm::send(result_ch, Some(
uv::ll::get_last_err_data(loop_ptr).to_tcp_err()));
}
}
// UNSAFE LIBUV INTERACTION END
match core::comm::recv(result_po) {
- some(err_data) => result::err(err_data),
- none => result::ok(tcp_socket(client_socket_data))
+ Some(err_data) => result::err(err_data),
+ None => result::ok(tcp_socket(client_socket_data))
}
}
}
*/
fn listen(-host_ip: ip::ip_addr, port: uint, backlog: uint,
iotask: iotask,
- on_establish_cb: fn~(comm::Chan<option<tcp_err_data>>),
+ on_establish_cb: fn~(comm::Chan<Option<tcp_err_data>>),
+new_connect_cb: fn~(tcp_new_connection,
- comm::Chan<option<tcp_err_data>>))
+ comm::Chan<Option<tcp_err_data>>))
-> result::result<(), tcp_listen_err_data> unsafe {
do listen_common(host_ip, port, backlog, iotask, on_establish_cb)
// on_connect_cb
fn listen_common(-host_ip: ip::ip_addr, port: uint, backlog: uint,
iotask: iotask,
- on_establish_cb: fn~(comm::Chan<option<tcp_err_data>>),
+ on_establish_cb: fn~(comm::Chan<Option<tcp_err_data>>),
-on_connect_cb: fn~(*uv::ll::uv_tcp_t))
-> result::result<(), tcp_listen_err_data> unsafe {
let stream_closed_po = core::comm::port::<()>();
- let kill_po = core::comm::port::<option<tcp_err_data>>();
+ let kill_po = core::comm::port::<Option<tcp_err_data>>();
let kill_ch = core::comm::chan(kill_po);
let server_stream = uv::ll::tcp_t();
let server_stream_ptr = ptr::addr_of(server_stream);
match uv::ll::listen(server_stream_ptr,
backlog as libc::c_int,
tcp_lfc_on_connection_cb) {
- 0i32 => core::comm::send(setup_ch, none),
+ 0i32 => core::comm::send(setup_ch, None),
_ => {
log(debug, ~"failure to uv_listen()");
let err_data = uv::ll::get_last_err_data(loop_ptr);
- core::comm::send(setup_ch, some(err_data));
+ core::comm::send(setup_ch, Some(err_data));
}
}
}
_ => {
log(debug, ~"failure to uv_tcp_bind");
let err_data = uv::ll::get_last_err_data(loop_ptr);
- core::comm::send(setup_ch, some(err_data));
+ core::comm::send(setup_ch, Some(err_data));
}
}
}
_ => {
log(debug, ~"failure to uv_tcp_init");
let err_data = uv::ll::get_last_err_data(loop_ptr);
- core::comm::send(setup_ch, some(err_data));
+ core::comm::send(setup_ch, Some(err_data));
}
}
};
setup_ch.recv()
};
match setup_result {
- some(err_data) => {
+ Some(err_data) => {
do iotask::interact(iotask) |loop_ptr| unsafe {
log(debug, fmt!("tcp::listen post-kill recv hl interact %?",
loop_ptr));
}
}
}
- none => {
+ None => {
on_establish_cb(kill_ch);
let kill_result = core::comm::recv(kill_po);
do iotask::interact(iotask) |loop_ptr| unsafe {
stream_closed_po.recv();
match kill_result {
// some failure post bind/listen
- some(err_data) => result::err(generic_listen_err(err_data.err_name,
+ Some(err_data) => result::err(generic_listen_err(err_data.err_name,
err_data.err_msg)),
// clean exit
- none => result::ok(())
+ None => result::ok(())
}
}
}
timer::recv_timeout(
iotask, timeout_msecs, result::get(rs_result))
} else {
- some(core::comm::recv(result::get(rs_result)))
+ Some(core::comm::recv(result::get(rs_result)))
};
log(debug, ~"tcp::read after recv_timeout");
match read_result {
- none => {
+ None => {
log(debug, ~"tcp::read: timed out..");
let err_data = {
err_name: ~"TIMEOUT",
read_stop_common_impl(socket_data);
result::err(err_data)
}
- some(data_result) => {
+ Some(data_result) => {
log(debug, ~"tcp::read got data");
read_stop_common_impl(socket_data);
data_result
fn read_stop_common_impl(socket_data: *tcp_socket_data) ->
result::result<(), tcp_err_data> unsafe {
let stream_handle_ptr = (*socket_data).stream_handle_ptr;
- let stop_po = core::comm::port::<option<tcp_err_data>>();
+ let stop_po = core::comm::port::<Option<tcp_err_data>>();
let stop_ch = core::comm::chan(stop_po);
do iotask::interact((*socket_data).iotask) |loop_ptr| unsafe {
log(debug, ~"in interact cb for tcp::read_stop");
match uv::ll::read_stop(stream_handle_ptr as *uv::ll::uv_stream_t) {
0i32 => {
log(debug, ~"successfully called uv_read_stop");
- core::comm::send(stop_ch, none);
+ core::comm::send(stop_ch, None);
}
_ => {
log(debug, ~"failure in calling uv_read_stop");
let err_data = uv::ll::get_last_err_data(loop_ptr);
- core::comm::send(stop_ch, some(err_data.to_tcp_err()));
+ core::comm::send(stop_ch, Some(err_data.to_tcp_err()));
}
}
};
match core::comm::recv(stop_po) {
- some(err_data) => result::err(err_data.to_tcp_err()),
- none => result::ok(())
+ Some(err_data) => result::err(err_data.to_tcp_err()),
+ None => result::ok(())
}
}
-> result::result<comm::Port<
result::result<~[u8], tcp_err_data>>, tcp_err_data> unsafe {
let stream_handle_ptr = (*socket_data).stream_handle_ptr;
- let start_po = core::comm::port::<option<uv::ll::uv_err_data>>();
+ let start_po = core::comm::port::<Option<uv::ll::uv_err_data>>();
let start_ch = core::comm::chan(start_po);
log(debug, ~"in tcp::read_start before interact loop");
do iotask::interact((*socket_data).iotask) |loop_ptr| unsafe {
on_tcp_read_cb) {
0i32 => {
log(debug, ~"success doing uv_read_start");
- core::comm::send(start_ch, none);
+ core::comm::send(start_ch, None);
}
_ => {
log(debug, ~"error attempting uv_read_start");
let err_data = uv::ll::get_last_err_data(loop_ptr);
- core::comm::send(start_ch, some(err_data));
+ core::comm::send(start_ch, Some(err_data));
}
}
};
match core::comm::recv(start_po) {
- some(err_data) => result::err(err_data.to_tcp_err()),
- none => result::ok((*socket_data).reader_po)
+ Some(err_data) => result::err(err_data.to_tcp_err()),
+ None => result::ok((*socket_data).reader_po)
}
}
type tcp_listen_fc_data = {
server_stream_ptr: *uv::ll::uv_tcp_t,
stream_closed_ch: comm::Chan<()>,
- kill_ch: comm::Chan<option<tcp_err_data>>,
+ kill_ch: comm::Chan<Option<tcp_err_data>>,
on_connect_cb: fn~(*uv::ll::uv_tcp_t),
iotask: iotask,
mut active: bool
_ => {
let loop_ptr = uv::ll::get_loop_for_uv_handle(handle);
core::comm::send(kill_ch,
- some(uv::ll::get_last_err_data(loop_ptr)
+ Some(uv::ll::get_last_err_data(loop_ptr)
.to_tcp_err()));
(*server_data_ptr).active = false;
}
if result::is_err(accept_result) {
log(debug, ~"SERVER: error accept connection");
let err_data = result::get_err(accept_result);
- core::comm::send(kill_ch, some(err_data));
+ core::comm::send(kill_ch, Some(err_data));
log(debug,
~"SERVER/WORKER: send on err cont ch");
cont_ch.send(());
log(debug, ~"SERVER: before write");
tcp_write_single(sock, str::to_bytes(resp));
log(debug, ~"SERVER: after write.. die");
- core::comm::send(kill_ch, none);
+ core::comm::send(kill_ch, None);
}
result::err(err_data) => {
log(debug, fmt!("SERVER: error recvd: %s %s",
err_data.err_name, err_data.err_msg));
- core::comm::send(kill_ch, some(err_data));
+ core::comm::send(kill_ch, Some(err_data));
server_ch.send(~"");
}
}
type url = {
scheme: ~str,
- user: option<userinfo>,
+ user: Option<userinfo>,
host: ~str,
- port: option<~str>,
+ port: Option<~str>,
path: ~str,
query: query,
- fragment: option<~str>
+ fragment: Option<~str>
};
type userinfo = {
user: ~str,
- pass: option<~str>
+ pass: Option<~str>
};
type query = ~[(~str, ~str)];
-fn url(-scheme: ~str, -user: option<userinfo>, -host: ~str,
- -port: option<~str>, -path: ~str, -query: query,
- -fragment: option<~str>) -> url {
+fn url(-scheme: ~str, -user: Option<userinfo>, -host: ~str,
+ -port: Option<~str>, -path: ~str, -query: query,
+ -fragment: Option<~str>) -> url {
{ scheme: scheme, user: user, host: host, port: port,
path: path, query: query, fragment: fragment }
}
-fn userinfo(-user: ~str, -pass: option<~str>) -> userinfo {
+fn userinfo(-user: ~str, -pass: Option<~str>) -> userinfo {
{user: user, pass: pass}
}
'&' | ';' => {
if key != ~"" && value != ~"" {
let values = match m.find(key) {
- some(values) => values,
- none => {
+ Some(values) => values,
+ None => {
let values = @dvec();
m.insert(key, values);
values
if key != ~"" && value != ~"" {
let values = match m.find(key) {
- some(values) => values,
- none => {
+ Some(values) => values,
+ None => {
let values = @dvec();
m.insert(key, values);
values
fn userinfo_from_str(uinfo: ~str) -> userinfo {
let (user, p) = split_char_first(uinfo, ':');
let pass = if str::len(p) == 0 {
- option::none
+ option::None
} else {
- option::some(p)
+ option::Some(p)
};
return userinfo(user, pass);
}
// returns userinfo, host, port, and unparsed part, or an error
fn get_authority(rawurl: ~str) ->
- result::result<(option<userinfo>, ~str, option<~str>, ~str), @~str> {
+ result::result<(Option<userinfo>, ~str, Option<~str>, ~str), @~str> {
if !str::starts_with(rawurl, ~"//") {
// there is no authority.
- return result::ok((option::none, ~"", option::none, copy rawurl));
+ return result::ok((option::None, ~"", option::None, copy rawurl));
}
enum state {
let mut st : state = start;
let mut in : input = digit; // most restricted, start here.
- let mut userinfo : option<userinfo> = option::none;
+ let mut userinfo : Option<userinfo> = option::None;
let mut host : ~str = ~"";
- let mut port : option::option<~str> = option::none;
+ let mut port : option::Option<~str> = option::None;
let mut colon_count = 0;
let mut pos : uint = 0, begin : uint = 2, end : uint = len;
match st {
start => {
let user = str::slice(rawurl, begin, i);
- userinfo = option::some({user : user,
- pass: option::none});
+ userinfo = option::Some({user : user,
+ pass: option::None});
st = in_host;
}
pass_host_port => {
let user = str::slice(rawurl, begin, pos);
let pass = str::slice(rawurl, pos+1, i);
- userinfo = option::some({user: user,
- pass: option::some(pass)});
+ userinfo = option::Some({user: user,
+ pass: option::Some(pass)});
st = in_host;
}
_ => {
return result::err(@~"Non-digit characters in port.");
}
host = str::slice(rawurl, begin, pos);
- port = option::some(str::slice(rawurl, pos+1, end));
+ port = option::Some(str::slice(rawurl, pos+1, end));
}
ip6_host | in_host => {
host = str::slice(rawurl, begin, end);
if in != digit {
return result::err(@~"Non-digit characters in port.");
}
- port = option::some(str::slice(rawurl, pos+1, end));
+ port = option::Some(str::slice(rawurl, pos+1, end));
}
}
// returns the parsed query and the fragment, if present
fn get_query_fragment(rawurl: ~str) ->
- result::result<(query, option<~str>), @~str> {
+ result::result<(query, Option<~str>), @~str> {
if !str::starts_with(rawurl, ~"?") {
if str::starts_with(rawurl, ~"#") {
let f = decode_component(str::slice(rawurl,
1,
str::len(rawurl)));
- return result::ok((~[], option::some(f)));
+ return result::ok((~[], option::Some(f)));
} else {
- return result::ok((~[], option::none));
+ return result::ok((~[], option::None));
}
}
let (q, r) = split_char_first(str::slice(rawurl, 1,
str::len(rawurl)), '#');
let f = if str::len(r) != 0 {
- option::some(decode_component(r)) } else { option::none };
+ option::Some(decode_component(r)) } else { option::None };
return result::ok((query_from_str(q), f));
}
fn test_get_authority() {
let (u, h, p, r) = result::unwrap(get_authority(
~"//user:pass@rust-lang.org/something"));
- assert u == option::some({user: ~"user",
- pass: option::some(~"pass")});
+ assert u == option::Some({user: ~"user",
+ pass: option::Some(~"pass")});
assert h == ~"rust-lang.org";
assert option::is_none(p);
assert r == ~"/something";
~"//rust-lang.org:8000?something"));
assert option::is_none(u);
assert h == ~"rust-lang.org";
- assert p == option::some(~"8000");
+ assert p == option::Some(~"8000");
assert r == ~"?something";
let (u, h, p, r) = result::unwrap(get_authority(
let (_, h, p, _) = result::unwrap(get_authority(
~"//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah"));
assert h == ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334";
- assert p == option::some(~"8000");
+ assert p == option::Some(~"8000");
let (u, h, p, _) = result::unwrap(get_authority(
~"//us:p@2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah"));
- assert u == option::some({user: ~"us", pass : option::some(~"p")});
+ assert u == option::Some({user: ~"us", pass : option::Some(~"p")});
assert h == ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334";
- assert p == option::some(~"8000");
+ assert p == option::Some(~"8000");
// invalid authorities;
assert result::is_err(get_authority(
match (rope) {
node::empty => return rope,
node::content(x) => match (node::bal(x)) {
- option::none => rope,
- option::some(y) => node::content(y)
+ option::None => rope,
+ option::Some(y) => node::content(y)
}
}
}
node::content(x) => return node::leaf_iterator::start(x)
}
}
- fn next(it: node::leaf_iterator::t) -> option<node::leaf> {
+ fn next(it: node::leaf_iterator::t) -> Option<node::leaf> {
return node::leaf_iterator::next(it);
}
}
node::content(x) => return node::char_iterator::start(x)
}
}
- fn next(it: node::char_iterator::t) -> option<char> {
+ fn next(it: node::char_iterator::t) -> Option<char> {
return node::char_iterator::next(it)
}
}
let it = leaf_iterator::start(node);
loop {
match (leaf_iterator::next(it)) {
- option::none => break,
- option::some(x) => {
+ option::None => break,
+ option::Some(x) => {
//FIXME (#2744): Replace with memcpy or something similar
let mut local_buf: ~[u8] =
unsafe::reinterpret_cast(*x.content);
*
* # Return value
*
- * * `option::none` if no transformation happened
+ * * `option::None` if no transformation happened
* * `option::some(x)` otherwise, in which case `x` has the same contents
* as `node` bot lower height and/or fragmentation.
*/
- fn bal(node: @node) -> option<@node> {
- if height(node) < hint_max_node_height { return option::none; }
+ fn bal(node: @node) -> Option<@node> {
+ if height(node) < hint_max_node_height { return option::None; }
//1. Gather all leaves as a forest
let mut forest = ~[mut];
let it = leaf_iterator::start(node);
loop {
match (leaf_iterator::next(it)) {
- option::none => break,
- option::some(x) => vec::push(forest, @leaf(x))
+ option::None => break,
+ option::Some(x) => vec::push(forest, @leaf(x))
}
}
//2. Rebuild tree from forest
let root = @*tree_from_forest_destructive(forest);
- return option::some(root);
+ return option::Some(root);
}
let mut result = 0;
while result == 0 {
match ((char_iterator::next(ita), char_iterator::next(itb))) {
- (option::none, option::none) => break,
- (option::some(chara), option::some(charb)) => {
+ (option::None, option::None) => break,
+ (option::Some(chara), option::Some(charb)) => {
result = char::cmp(chara, charb);
}
- (option::some(_), _) => {
+ (option::Some(_), _) => {
result = 1;
}
- (_, option::some(_)) => {
+ (_, option::Some(_)) => {
result = -1;
}
}
}
}
- fn next(it: t) -> option<leaf> {
- if it.stackpos < 0 { return option::none; }
+ fn next(it: t) -> Option<leaf> {
+ if it.stackpos < 0 { return option::None; }
loop {
let current = it.stack[it.stackpos];
it.stackpos -= 1;
it.stackpos += 1;
it.stack[it.stackpos] = x.left;
}
- leaf(x) => return option::some(x)
+ leaf(x) => return option::Some(x)
}
};
}
mod char_iterator {
type t = {
leaf_iterator: leaf_iterator::t,
- mut leaf: option<leaf>,
+ mut leaf: Option<leaf>,
mut leaf_byte_pos: uint
};
fn start(node: @node) -> t {
return {
leaf_iterator: leaf_iterator::start(node),
- mut leaf: option::none,
+ mut leaf: option::None,
mut leaf_byte_pos: 0u
}
}
fn empty() -> t {
return {
leaf_iterator: leaf_iterator::empty(),
- mut leaf: option::none,
+ mut leaf: option::None,
mut leaf_byte_pos: 0u
}
}
- fn next(it: t) -> option<char> {
+ fn next(it: t) -> Option<char> {
loop {
match (get_current_or_next_leaf(it)) {
- option::none => return option::none,
- option::some(_) => {
+ option::None => return option::None,
+ option::Some(_) => {
let next_char = get_next_char_in_leaf(it);
match (next_char) {
- option::none => again,
- option::some(_) => return next_char
+ option::None => again,
+ option::Some(_) => return next_char
}
}
}
};
}
- fn get_current_or_next_leaf(it: t) -> option<leaf> {
+ fn get_current_or_next_leaf(it: t) -> Option<leaf> {
match (it.leaf) {
- option::some(_) => return it.leaf,
- option::none => {
+ option::Some(_) => return it.leaf,
+ option::None => {
let next = leaf_iterator::next(it.leaf_iterator);
match (next) {
- option::none => return option::none,
- option::some(_) => {
+ option::None => return option::None,
+ option::Some(_) => {
it.leaf = next;
it.leaf_byte_pos = 0u;
return next;
}
}
- fn get_next_char_in_leaf(it: t) -> option<char> {
+ fn get_next_char_in_leaf(it: t) -> Option<char> {
match copy it.leaf {
- option::none => return option::none,
- option::some(aleaf) => {
+ option::None => return option::None,
+ option::Some(aleaf) => {
if it.leaf_byte_pos >= aleaf.byte_len {
//We are actually past the end of the leaf
- it.leaf = option::none;
- return option::none
+ it.leaf = option::None;
+ return option::None
} else {
let {ch, next} =
str::char_range_at(*aleaf.content,
it.leaf_byte_pos + aleaf.byte_offset);
it.leaf_byte_pos = next - aleaf.byte_offset;
- return option::some(ch)
+ return option::Some(ch)
}
}
}
let mut equal = true;
while equal {
match (node::char_iterator::next(rope_iter)) {
- option::none => {
+ option::None => {
if string_iter < string_len {
equal = false;
} break; }
- option::some(c) => {
+ option::Some(c) => {
let {ch, next} = str::char_range_at(*sample, string_iter);
string_iter = next;
if ch != c { equal = false; break; }
let it = iterator::char::start(r);
loop {
match (node::char_iterator::next(it)) {
- option::none => break,
- option::some(_) => len += 1u
+ option::None => break,
+ option::Some(_) => len += 1u
}
}
d.read_bool()
}
-fn serialize_option<S: serializer,T>(s: S, v: option<T>, st: fn(T)) {
+fn serialize_Option<S: serializer,T>(s: S, v: Option<T>, st: fn(T)) {
do s.emit_enum(~"option") {
match v {
- none => do s.emit_enum_variant(~"none", 0u, 0u) {
+ None => do s.emit_enum_variant(~"none", 0u, 0u) {
},
- some(v) => do s.emit_enum_variant(~"some", 1u, 1u) {
+ Some(v) => do s.emit_enum_variant(~"some", 1u, 1u) {
do s.emit_enum_variant_arg(0u) {
st(v)
}
}
}
-fn deserialize_option<D: deserializer,T: copy>(d: D, st: fn() -> T)
- -> option<T> {
+fn deserialize_Option<D: deserializer,T: copy>(d: D, st: fn() -> T)
+ -> Option<T> {
do d.read_enum(~"option") {
do d.read_enum_variant |i| {
match i {
- 0 => none,
- 1 => some(d.read_enum_variant_arg(0u, || st() )),
+ 0 => None,
+ 1 => Some(d.read_enum_variant_arg(0u, || st() )),
_ => fail(#fmt("Bad variant for option: %u", i))
}
}
* are O(highest integer key).
*/
import core::option;
-import core::option::{some, none};
+import core::option::{Some, None};
import dvec::{DVec, dvec};
import map::map;
// FIXME (#2347): Should not be @; there's a bug somewhere in rustc that
// requires this to be.
-type smallintmap_<T: copy> = {v: DVec<option<T>>};
+type smallintmap_<T: copy> = {v: DVec<Option<T>>};
enum smallintmap<T:copy> {
smallintmap_(@smallintmap_<T>)
#[inline(always)]
fn insert<T: copy>(self: smallintmap<T>, key: uint, val: T) {
//io::println(fmt!("%?", key));
- self.v.grow_set_elt(key, none, some(val));
+ self.v.grow_set_elt(key, None, Some(val));
}
/**
* Get the value for the specified key. If the key does not exist
* in the map then returns none
*/
-pure fn find<T: copy>(self: smallintmap<T>, key: uint) -> option<T> {
+pure fn find<T: copy>(self: smallintmap<T>, key: uint) -> Option<T> {
if key < self.v.len() { return self.v.get_elt(key); }
- return none::<T>;
+ return None::<T>;
}
/**
*/
pure fn get<T: copy>(self: smallintmap<T>, key: uint) -> T {
match find(self, key) {
- none => {
+ None => {
error!("smallintmap::get(): key not present");
fail;
}
- some(v) => return v
+ Some(v) => return v
}
}
let mut sz = 0u;
for self.v.each |item| {
match item {
- some(_) => sz += 1u,
+ Some(_) => sz += 1u,
_ => ()
}
}
return false;
}
let old = self.v.get_elt(key);
- self.v.set_elt(key, none);
+ self.v.set_elt(key, None);
old.is_some()
}
fn clear() {
contains_key(self, *key)
}
fn get(+key: uint) -> V { get(self, key) }
- fn find(+key: uint) -> option<V> { find(self, key) }
+ fn find(+key: uint) -> Option<V> { find(self, key) }
fn rehash() { fail }
fn each(it: fn(+key: uint, +value: V) -> bool) {
let mut idx = 0u, l = self.v.len();
while idx < l {
match self.v.get_elt(idx) {
- some(elt) => if !it(idx, elt) { break },
- none => ()
+ Some(elt) => if !it(idx, elt) { break },
+ None => ()
}
idx += 1u;
}
let mut idx = 0u, l = self.v.len();
while idx < l {
match self.v.get_elt(idx) {
- some(elt) => if !it(&idx, &elt) { break },
- none => ()
+ Some(elt) => if !it(&idx, &elt) { break },
+ None => ()
}
idx += 1u;
}
#[doc(hidden)]
impl<Q: send> &sem<Q> {
fn acquire() {
- let mut waiter_nobe = none;
+ let mut waiter_nobe = None;
unsafe {
do (**self).with |state| {
state.count -= 1;
// Create waiter nobe.
let (signal_end, wait_end) = pipes::oneshot();
// Tell outer scope we need to block.
- waiter_nobe = some(wait_end);
+ waiter_nobe = Some(wait_end);
// Enqueue ourself.
state.waiters.tail.send(signal_end);
}
#[doc(hidden)]
impl &sem<()> {
fn access<U>(blk: fn() -> U) -> U {
- let mut release = none;
+ let mut release = None;
unsafe {
do task::unkillable {
self.acquire();
- release = some(sem_release(self));
+ release = Some(sem_release(self));
}
}
blk()
#[doc(hidden)]
impl &sem<~[mut waitqueue]> {
fn access<U>(blk: fn() -> U) -> U {
- let mut release = none;
+ let mut release = None;
unsafe {
do task::unkillable {
self.acquire();
- release = some(sem_and_signal_release(self));
+ release = Some(sem_and_signal_release(self));
}
}
blk()
fn wait_on(condvar_id: uint) {
// Create waiter nobe.
let (signal_end, wait_end) = pipes::oneshot();
- let mut wait_end = some(wait_end);
- let mut signal_end = some(signal_end);
- let mut reacquire = none;
- let mut out_of_bounds = none;
+ let mut wait_end = Some(wait_end);
+ let mut signal_end = Some(signal_end);
+ let mut reacquire = None;
+ let mut out_of_bounds = None;
unsafe {
do task::unkillable {
// Release lock, 'atomically' enqueuing ourselves in so doing.
let signal_end = option::swap_unwrap(&mut signal_end);
state.blocked[condvar_id].tail.send(signal_end);
} else {
- out_of_bounds = some(vec::len(state.blocked));
+ out_of_bounds = Some(vec::len(state.blocked));
}
}
// unkillably reacquire the lock needs to happen atomically
// wrt enqueuing.
if out_of_bounds.is_none() {
- reacquire = some(sem_and_signal_reacquire(self.sem));
+ reacquire = Some(sem_and_signal_reacquire(self.sem));
}
}
}
fn signal() -> bool { self.signal_on(0) }
/// As signal, but with a specified condvar_id. See wait_on.
fn signal_on(condvar_id: uint) -> bool {
- let mut out_of_bounds = none;
+ let mut out_of_bounds = None;
let mut result = false;
unsafe {
do (**self.sem).with |state| {
if condvar_id < vec::len(state.blocked) {
result = signal_waitqueue(&state.blocked[condvar_id]);
} else {
- out_of_bounds = some(vec::len(state.blocked));
+ out_of_bounds = Some(vec::len(state.blocked));
}
}
}
fn broadcast() -> uint { self.broadcast_on(0) }
/// As broadcast, but with a specified condvar_id. See wait_on.
fn broadcast_on(condvar_id: uint) -> uint {
- let mut out_of_bounds = none;
- let mut queue = none;
+ let mut out_of_bounds = None;
+ let mut queue = None;
unsafe {
do (**self.sem).with |state| {
if condvar_id < vec::len(state.blocked) {
// To avoid :broadcast_heavy, we make a new waitqueue,
// swap it out with the old one, and broadcast on the
// old one outside of the little-lock.
- queue = some(util::replace(&mut state.blocked[condvar_id],
+ queue = Some(util::replace(&mut state.blocked[condvar_id],
new_waitqueue()));
} else {
- out_of_bounds = some(vec::len(state.blocked));
+ out_of_bounds = Some(vec::len(state.blocked));
}
}
}
// something else next on success.
#[inline(always)]
#[doc(hidden)]
-fn check_cvar_bounds<U>(out_of_bounds: option<uint>, id: uint, act: &str,
+fn check_cvar_bounds<U>(out_of_bounds: Option<uint>, id: uint, act: &str,
blk: fn() -> U) -> U {
match out_of_bounds {
- some(0) =>
+ Some(0) =>
fail fmt!("%s with illegal ID %u - this lock has no condvars!",
act, id),
- some(length) =>
+ Some(length) =>
fail fmt!("%s with illegal ID %u - ID must be less than %u",
act, id, length),
- none => blk()
+ None => blk()
}
}
* tasks may run concurrently with this one.
*/
fn read<U>(blk: fn() -> U) -> U {
- let mut release = none;
+ let mut release = None;
unsafe {
do task::unkillable {
do (&self.order_lock).access {
}
}
}
- release = some(rwlock_release_read(self));
+ release = Some(rwlock_release_read(self));
}
}
blk()
fn write_downgrade<U>(blk: fn(+rwlock_write_mode) -> U) -> U {
// Implementation slightly different from the slicker 'write's above.
// The exit path is conditional on whether the caller downgrades.
- let mut _release = none;
+ let mut _release = None;
unsafe {
do task::unkillable {
(&self.order_lock).acquire();
(&self.access_lock).acquire();
(&self.order_lock).release();
}
- _release = some(rwlock_release_downgrade(self));
+ _release = Some(rwlock_release_downgrade(self));
}
blk(rwlock_write_mode { lock: self })
}
let s = ~semaphore(1);
let s2 = ~s.clone();
let (c,p) = pipes::stream();
- let child_data = ~mut some((s2,c));
+ let child_data = ~mut Some((s2,c));
do s.access {
let (s2,c) = option::swap_unwrap(child_data);
do task::spawn {
let mut sibling_convos = ~[];
for 2.times {
let (c,p) = pipes::stream();
- let c = ~mut some(c);
+ let c = ~mut Some(c);
vec::push(sibling_convos, p);
let mi = ~m2.clone();
// spawn sibling task
let x = ~rwlock();
let y = ~rwlock();
do x.write_downgrade |xwrite| {
- let mut xopt = some(xwrite);
+ let mut xopt = Some(xwrite);
do y.write_downgrade |_ywrite| {
y.downgrade(option::swap_unwrap(&mut xopt));
error!("oops, y.downgrade(x) should have failed!");
//! Temporary files and directories
import core::option;
-import option::{none, some};
+import option::{None, Some};
import rand;
-fn mkdtemp(tmpdir: &Path, suffix: &str) -> option<Path> {
+fn mkdtemp(tmpdir: &Path, suffix: &str) -> Option<Path> {
let r = rand::rng();
let mut i = 0u;
while (i < 1000u) {
let p = tmpdir.push(r.gen_str(16u) +
str::from_slice(suffix));
if os::make_dir(&p, 0x1c0i32) { // FIXME: u+rwx (#2349)
- return some(p);
+ return Some(p);
}
i += 1u;
}
- return none;
+ return None;
}
#[test]
fn test_mkdtemp() {
let r = mkdtemp(&Path("."), "foobar");
match r {
- some(p) => {
+ Some(p) => {
os::remove_dir(&p);
assert(str::ends_with(p.to_str(), "foobar"));
}
//! Simple ANSI color library
-import core::option;
+import core::Option;
// FIXME (#2807): Windows support.
let supported_terms = ~[~"xterm-color", ~"xterm",
~"screen-bce", ~"xterm-256color"];
return match os::getenv(~"TERM") {
- option::some(env) => {
+ option::Some(env) => {
for vec::each(supported_terms) |term| {
if term == env { return true; }
}
false
}
- option::none => false
+ option::None => false
};
}
if !run_tests_console(opts, tests) { fail ~"Some tests failed"; }
}
-type test_opts = {filter: option<~str>, run_ignored: bool,
- logfile: option<~str>};
+type test_opts = {filter: Option<~str>, run_ignored: bool,
+ logfile: Option<~str>};
type opt_res = Either<test_opts, ~str>;
let filter =
if vec::len(matches.free) > 0u {
- option::some(matches.free[0])
- } else { option::none };
+ option::Some(matches.free[0])
+ } else { option::None };
let run_ignored = getopts::opt_present(matches, ~"ignored");
let logfile = getopts::opt_maybe_str(matches, ~"logfile");
type console_test_state =
@{out: io::Writer,
- log_out: option<io::Writer>,
+ log_out: Option<io::Writer>,
use_color: bool,
mut total: uint,
mut passed: uint,
te_wait(test) => st.out.write_str(fmt!("test %s ... ", test.name)),
te_result(test, result) => {
match st.log_out {
- some(f) => write_log(f, result, test),
- none => ()
+ Some(f) => write_log(f, result, test),
+ None => ()
}
match result {
tr_ok => {
}
let log_out = match opts.logfile {
- some(path) => match io::file_writer(&Path(path),
+ Some(path) => match io::file_writer(&Path(path),
~[io::Create, io::Truncate]) {
- result::ok(w) => some(w),
+ result::ok(w) => Some(w),
result::err(s) => {
fail(fmt!("can't open output file: %s", s))
}
},
- none => none
+ None => None
};
let st =
let st =
@{out: writer,
- log_out: option::none,
+ log_out: option::None,
use_color: false,
mut total: 0u,
mut passed: 0u,
} else {
let filter_str =
match opts.filter {
- option::some(f) => f,
- option::none => ~""
+ option::Some(f) => f,
+ option::None => ~""
};
fn filter_fn(test: test_desc, filter_str: ~str) ->
- option<test_desc> {
+ Option<test_desc> {
if str::contains(test.name, filter_str) {
- return option::some(copy test);
- } else { return option::none; }
+ return option::Some(copy test);
+ } else { return option::None; }
}
vec::filter_map(filtered, |x| filter_fn(x, filter_str))
filtered = if !opts.run_ignored {
filtered
} else {
- fn filter(test: test_desc) -> option<test_desc> {
+ fn filter(test: test_desc) -> Option<test_desc> {
if test.ignore {
- return option::some({name: test.name,
+ return option::Some({name: test.name,
fn: copy test.fn,
ignore: false,
should_fail: test.should_fail});
- } else { return option::none; }
+ } else { return option::None; }
};
vec::filter_map(filtered, |x| filter(x))
do task::spawn {
let testfn = copy test.fn;
- let mut result_future = none; // task::future_result(builder);
+ let mut result_future = None; // task::future_result(builder);
task::task().unlinked().future_result(|+r| {
- result_future = some(r);
+ result_future = Some(r);
}).spawn(testfn);
let task_result = future::get(&option::unwrap(result_future));
let test_result = calc_result(test, task_result == task::Success);
// When we run ignored tests the test filter should filter out all the
// unignored tests and flip the ignore flag on the rest to false
- let opts = {filter: option::none, run_ignored: true,
- logfile: option::none};
+ let opts = {filter: option::None, run_ignored: true,
+ logfile: option::None};
let tests =
~[{name: ~"1", fn: fn~() { }, ignore: true, should_fail: false},
{name: ~"2", fn: fn~() { }, ignore: false, should_fail: false}];
#[test]
fn sort_tests() {
- let opts = {filter: option::none, run_ignored: false,
- logfile: option::none};
+ let opts = {filter: option::None, run_ignored: false,
+ logfile: option::None};
let names =
~[~"sha1::test", ~"int::test_to_str", ~"int::test_pow",
}
fn match_strs(ss: &str, pos: uint, strs: &[(~str, i32)])
- -> option<(i32, uint)> {
+ -> Option<(i32, uint)> {
let mut i = 0u;
let len = vec::len(strs);
while i < len {
let (needle, value) = strs[i];
if match_str(ss, pos, needle) {
- return some((value, pos + str::len(needle)));
+ return Some((value, pos + str::len(needle)));
}
i += 1u;
}
- none
+ None
}
fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
- -> option<(i32, uint)> {
+ -> Option<(i32, uint)> {
let mut pos = pos;
let mut value = 0_i32;
value = value * 10_i32 + (ch as i32 - '0' as i32);
}
' ' if ws => (),
- _ => return none
+ _ => return None
}
i += 1u;
}
- some((value, pos))
+ Some((value, pos))
}
fn parse_char(s: &str, pos: uint, c: char) -> result<uint, ~str> {
(~"Friday", 5_i32),
(~"Saturday", 6_i32)
]) {
- some(item) => { let (v, pos) = item; tm.tm_wday = v; ok(pos) }
- none => err(~"Invalid day")
+ Some(item) => { let (v, pos) = item; tm.tm_wday = v; ok(pos) }
+ None => err(~"Invalid day")
},
'a' => match match_strs(s, pos, ~[
(~"Sun", 0_i32),
(~"Fri", 5_i32),
(~"Sat", 6_i32)
]) {
- some(item) => { let (v, pos) = item; tm.tm_wday = v; ok(pos) }
- none => err(~"Invalid day")
+ Some(item) => { let (v, pos) = item; tm.tm_wday = v; ok(pos) }
+ None => err(~"Invalid day")
},
'B' => match match_strs(s, pos, ~[
(~"January", 0_i32),
(~"November", 10_i32),
(~"December", 11_i32)
]) {
- some(item) => { let (v, pos) = item; tm.tm_mon = v; ok(pos) }
- none => err(~"Invalid month")
+ Some(item) => { let (v, pos) = item; tm.tm_mon = v; ok(pos) }
+ None => err(~"Invalid month")
},
'b' | 'h' => match match_strs(s, pos, ~[
(~"Jan", 0_i32),
(~"Nov", 10_i32),
(~"Dec", 11_i32)
]) {
- some(item) => { let (v, pos) = item; tm.tm_mon = v; ok(pos) }
- none => err(~"Invalid month")
+ Some(item) => { let (v, pos) = item; tm.tm_mon = v; ok(pos) }
+ None => err(~"Invalid month")
},
'C' => match match_digits(s, pos, 2u, false) {
- some(item) => {
+ Some(item) => {
let (v, pos) = item;
tm.tm_year += (v * 100_i32) - 1900_i32;
ok(pos)
}
- none => err(~"Invalid year")
+ None => err(~"Invalid year")
},
'c' => {
parse_type(s, pos, 'a', tm)
.chain(|pos| parse_type(s, pos, 'y', tm))
}
'd' => match match_digits(s, pos, 2u, false) {
- some(item) => { let (v, pos) = item; tm.tm_mday = v; ok(pos) }
- none => err(~"Invalid day of the month")
+ Some(item) => { let (v, pos) = item; tm.tm_mday = v; ok(pos) }
+ None => err(~"Invalid day of the month")
},
'e' => match match_digits(s, pos, 2u, true) {
- some(item) => { let (v, pos) = item; tm.tm_mday = v; ok(pos) }
- none => err(~"Invalid day of the month")
+ Some(item) => { let (v, pos) = item; tm.tm_mday = v; ok(pos) }
+ None => err(~"Invalid day of the month")
},
'F' => {
parse_type(s, pos, 'Y', tm)
'H' => {
// FIXME (#2350): range check.
match match_digits(s, pos, 2u, false) {
- some(item) => { let (v, pos) = item; tm.tm_hour = v; ok(pos) }
- none => err(~"Invalid hour")
+ Some(item) => { let (v, pos) = item; tm.tm_hour = v; ok(pos) }
+ None => err(~"Invalid hour")
}
}
'I' => {
// FIXME (#2350): range check.
match match_digits(s, pos, 2u, false) {
- some(item) => {
+ Some(item) => {
let (v, pos) = item;
tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
ok(pos)
}
- none => err(~"Invalid hour")
+ None => err(~"Invalid hour")
}
}
'j' => {
// FIXME (#2350): range check.
match match_digits(s, pos, 3u, false) {
- some(item) => {
+ Some(item) => {
let (v, pos) = item;
tm.tm_yday = v - 1_i32;
ok(pos)
}
- none => err(~"Invalid year")
+ None => err(~"Invalid year")
}
}
'k' => {
// FIXME (#2350): range check.
match match_digits(s, pos, 2u, true) {
- some(item) => { let (v, pos) = item; tm.tm_hour = v; ok(pos) }
- none => err(~"Invalid hour")
+ Some(item) => { let (v, pos) = item; tm.tm_hour = v; ok(pos) }
+ None => err(~"Invalid hour")
}
}
'l' => {
// FIXME (#2350): range check.
match match_digits(s, pos, 2u, true) {
- some(item) => {
+ Some(item) => {
let (v, pos) = item;
tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
ok(pos)
}
- none => err(~"Invalid hour")
+ None => err(~"Invalid hour")
}
}
'M' => {
// FIXME (#2350): range check.
match match_digits(s, pos, 2u, false) {
- some(item) => { let (v, pos) = item; tm.tm_min = v; ok(pos) }
- none => err(~"Invalid minute")
+ Some(item) => { let (v, pos) = item; tm.tm_min = v; ok(pos) }
+ None => err(~"Invalid minute")
}
}
'm' => {
// FIXME (#2350): range check.
match match_digits(s, pos, 2u, false) {
- some(item) => {
+ Some(item) => {
let (v, pos) = item;
tm.tm_mon = v - 1_i32;
ok(pos)
}
- none => err(~"Invalid month")
+ None => err(~"Invalid month")
}
}
'n' => parse_char(s, pos, '\n'),
'P' => match match_strs(s, pos,
~[(~"am", 0_i32), (~"pm", 12_i32)]) {
- some(item) => { let (v, pos) = item; tm.tm_hour += v; ok(pos) }
- none => err(~"Invalid hour")
+ Some(item) => { let (v, pos) = item; tm.tm_hour += v; ok(pos) }
+ None => err(~"Invalid hour")
},
'p' => match match_strs(s, pos,
~[(~"AM", 0_i32), (~"PM", 12_i32)]) {
- some(item) => { let (v, pos) = item; tm.tm_hour += v; ok(pos) }
- none => err(~"Invalid hour")
+ Some(item) => { let (v, pos) = item; tm.tm_hour += v; ok(pos) }
+ None => err(~"Invalid hour")
},
'R' => {
parse_type(s, pos, 'H', tm)
'S' => {
// FIXME (#2350): range check.
match match_digits(s, pos, 2u, false) {
- some(item) => {
+ Some(item) => {
let (v, pos) = item;
tm.tm_sec = v;
ok(pos)
}
- none => err(~"Invalid second")
+ None => err(~"Invalid second")
}
}
//'s' {}
'u' => {
// FIXME (#2350): range check.
match match_digits(s, pos, 1u, false) {
- some(item) => {
+ Some(item) => {
let (v, pos) = item;
tm.tm_wday = v;
ok(pos)
}
- none => err(~"Invalid weekday")
+ None => err(~"Invalid weekday")
}
}
'v' => {
'w' => {
// FIXME (#2350): range check.
match match_digits(s, pos, 1u, false) {
- some(item) => { let (v, pos) = item; tm.tm_wday = v; ok(pos) }
- none => err(~"Invalid weekday")
+ Some(item) => { let (v, pos) = item; tm.tm_wday = v; ok(pos) }
+ None => err(~"Invalid weekday")
}
}
//'X' {}
'Y' => {
// FIXME (#2350): range check.
match match_digits(s, pos, 4u, false) {
- some(item) => {
+ Some(item) => {
let (v, pos) = item;
tm.tm_year = v - 1900_i32;
ok(pos)
}
- none => err(~"Invalid weekday")
+ None => err(~"Invalid weekday")
}
}
'y' => {
// FIXME (#2350): range check.
match match_digits(s, pos, 2u, false) {
- some(item) => {
+ Some(item) => {
let (v, pos) = item;
tm.tm_year = v - 1900_i32;
ok(pos)
}
- none => err(~"Invalid weekday")
+ None => err(~"Invalid weekday")
}
}
'Z' => {
if ch == '+' || ch == '-' {
match match_digits(s, next, 4u, false) {
- some(item) => {
+ Some(item) => {
let (v, pos) = item;
if v == 0_i32 {
tm.tm_gmtoff = 0_i32;
ok(pos)
}
- none => err(~"Invalid zone offset")
+ None => err(~"Invalid zone offset")
}
} else {
err(~"Invalid zone offset")
*/
fn recv_timeout<T: copy send>(iotask: iotask,
msecs: uint,
- wait_po: comm::Port<T>) -> option<T> {
+ wait_po: comm::Port<T>) -> Option<T> {
let timeout_po = comm::port::<()>();
let timeout_ch = comm::chan(timeout_po);
delayed_send(iotask, msecs, timeout_ch, ());
|left_val| {
log(debug, fmt!("recv_time .. left_val %?",
left_val));
- none
+ None
}, |right_val| {
- some(*right_val)
+ Some(*right_val)
}, &core::comm::select2(timeout_po, wait_po)
)
}
};
match recv_timeout(hl_loop, 1u, test_po) {
- none => successes += 1,
+ None => successes += 1,
_ => failures += 1
};
}
* red-black tree or something else.
*/
-import core::option::{some, none};
-import option = core::option;
+import core::option::{Some, None};
+import Option = core::Option;
export treemap;
export insert;
type treemap<K, V> = @mut tree_edge<K, V>;
-type tree_edge<K, V> = option<@tree_node<K, V>>;
+type tree_edge<K, V> = Option<@tree_node<K, V>>;
enum tree_node<K, V> = {
key: K,
};
/// Create a treemap
-fn treemap<K, V>() -> treemap<K, V> { @mut none }
+fn treemap<K, V>() -> treemap<K, V> { @mut None }
/// Insert a value into the map
fn insert<K: copy, V: copy>(m: &mut tree_edge<K, V>, k: K, v: V) {
match copy *m {
- none => {
- *m = some(@tree_node({key: k,
+ None => {
+ *m = Some(@tree_node({key: k,
mut value: v,
- mut left: none,
- mut right: none}));
+ mut left: None,
+ mut right: None}));
return;
}
- some(node) => {
+ Some(node) => {
if k == node.key {
node.value = v;
} else if k < node.key {
}
/// Find a value based on the key
-fn find<K: copy, V: copy>(m: &const tree_edge<K, V>, k: K) -> option<V> {
+fn find<K: copy, V: copy>(m: &const tree_edge<K, V>, k: K) -> Option<V> {
match copy *m {
- none => none,
+ None => None,
// FIXME (#2808): was that an optimization?
- some(node) => {
+ Some(node) => {
if k == node.key {
- some(node.value)
+ Some(node.value)
} else if k < node.key {
find(&const node.left, k)
} else {
/// Visit all pairs in the map in order.
fn traverse<K, V: copy>(m: &const tree_edge<K, V>, f: fn(K, V)) {
match copy *m {
- none => (),
- some(node) => {
+ None => (),
+ Some(node) => {
traverse(&const node.left, f);
// copy of value is req'd as f() requires an immutable ptr
f(node.key, copy node.value);
fn insert_find() {
let m = treemap();
insert(m, 1, 2);
- assert (find(m, 1) == some(2));
+ assert (find(m, 1) == Some(2));
}
#[test]
fn find_empty() {
- let m = treemap::<int, int>(); assert (find(m, 1) == none);
+ let m = treemap::<int, int>(); assert (find(m, 1) == None);
}
#[test]
fn find_not_found() {
let m = treemap();
insert(m, 1, 2);
- assert (find(m, 2) == none);
+ assert (find(m, 2) == None);
}
#[test]
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"));
}
}
import codemap::{span, filename};
import std::serialization::{serializer,
deserializer,
- serialize_option,
- deserialize_option,
+ serialize_Option,
+ deserialize_Option,
serialize_uint,
deserialize_uint,
serialize_int,
fn serialize_ident<S: serializer>(s: S, i: ident) {
let intr = match unsafe{task::local_data_get(interner_key!())}{
- none => fail ~"serialization: TLS interner not set up",
- some(intr) => intr
+ None => fail ~"serialization: TLS interner not set up",
+ Some(intr) => intr
};
s.emit_str(*(*intr).get(i));
}
fn deserialize_ident<D: deserializer>(d: D) -> ident {
let intr = match unsafe{task::local_data_get(interner_key!())}{
- none => fail ~"deserialization: TLS interner not set up",
- some(intr) => intr
+ None => fail ~"deserialization: TLS interner not set up",
+ Some(intr) => intr
};
(*intr).intern(@d.read_str())
// Functions may or may not have names.
#[auto_serialize]
-type fn_ident = option<ident>;
+type fn_ident = Option<ident>;
#[auto_serialize]
type path = {span: span,
global: bool,
idents: ~[ident],
- rp: option<@region>,
+ rp: Option<@region>,
types: ~[@ty]};
#[auto_serialize]
#[auto_serialize]
type blk_ = {view_items: ~[@view_item],
stmts: ~[@stmt],
- expr: option<@expr>,
+ expr: Option<@expr>,
id: node_id,
rules: blk_check_mode};
pat_wild,
// A pat_ident may either be a new bound variable,
// or a nullary enum (in which case the second field
- // is none).
+ // is None).
// In the nullary enum case, the parser can't determine
// which it is. The resolver determines this, and
// records this pattern's node_id in an auxiliary
// set (of "pat_idents that refer to nullary enums")
- pat_ident(binding_mode, @path, option<@pat>),
- pat_enum(@path, option<~[@pat]>), // "none" means a * pattern where
+ pat_ident(binding_mode, @path, Option<@pat>),
+ pat_enum(@path, Option<~[@pat]>), // "none" means a * pattern where
// we don't bind the fields to names
pat_rec(~[field_pat], bool),
pat_struct(@path, ~[field_pat], bool),
#[auto_serialize]
enum vstore {
// FIXME (#2112): Change uint to @expr (actually only constant exprs)
- vstore_fixed(option<uint>), // [1,2,3,4]/_ or 4
+ vstore_fixed(Option<uint>), // [1,2,3,4]/_ or 4
vstore_uniq, // ~[1,2,3,4]
vstore_box, // @[1,2,3,4]
vstore_slice(@region) // &[1,2,3,4](foo)?
// a refinement on pat.
#[auto_serialize]
type local_ = {is_mutbl: bool, ty: @ty, pat: @pat,
- init: option<initializer>, id: node_id};
+ init: Option<initializer>, id: node_id};
#[auto_serialize]
type local = spanned<local_>;
enum decl_ { decl_local(~[@local]), decl_item(@item), }
#[auto_serialize]
-type arm = {pats: ~[@pat], guard: option<@expr>, body: blk};
+type arm = {pats: ~[@pat], guard: Option<@expr>, body: blk};
#[auto_serialize]
type field_ = {mutbl: mutability, ident: ident, expr: @expr};
enum expr_ {
expr_vstore(@expr, vstore),
expr_vec(~[@expr], mutability),
- expr_rec(~[field], option<@expr>),
+ expr_rec(~[field], Option<@expr>),
expr_call(@expr, ~[@expr], bool), // True iff last argument is a block
expr_tup(~[@expr]),
expr_binary(binop, @expr, @expr),
expr_unary(unop, @expr),
expr_lit(@lit),
expr_cast(@expr, @ty),
- expr_if(@expr, blk, option<@expr>),
+ expr_if(@expr, blk, Option<@expr>),
expr_while(@expr, blk),
/* Conditionless loop (can be exited with break, cont, ret, or fail)
Same semantics as while(true) { body }, but typestate knows that the
(implicit) condition is always true. */
- expr_loop(blk, option<ident>),
+ expr_loop(blk, Option<ident>),
expr_match(@expr, ~[arm]),
expr_fn(proto, fn_decl, blk, capture_clause),
expr_fn_block(fn_decl, blk, capture_clause),
expr_index(@expr, @expr),
expr_path(@path),
expr_addr_of(mutability, @expr),
- expr_fail(option<@expr>),
- expr_break(option<ident>),
- expr_again(option<ident>),
- expr_ret(option<@expr>),
+ expr_fail(Option<@expr>),
+ expr_break(Option<ident>),
+ expr_again(Option<ident>),
+ expr_ret(Option<@expr>),
expr_log(log_level, @expr, @expr),
/* just an assert */
expr_mac(mac),
// A struct literal expression.
- expr_struct(@path, ~[field], option<@expr>),
+ expr_struct(@path, ~[field], Option<@expr>),
// A vector literal constructed from one repeated element.
expr_repeat(@expr /* element */, @expr /* count */, mutability)
tt_tok(span, token::token),
tt_delim(~[token_tree]),
// These only make sense for right-hand-sides of MBE macros
- tt_seq(span, ~[token_tree], option<token::token>, bool),
+ tt_seq(span, ~[token_tree], Option<token::token>, bool),
tt_nonterminal(span, ident)
}
match_tok(token::token),
// match repetitions of a sequence: body, separator, zero ok?,
// lo, hi position-in-match-array used:
- match_seq(~[matcher], option<token::token>, bool, uint, uint),
+ match_seq(~[matcher], Option<token::token>, bool, uint, uint),
// parse a Rust NT: name to bind, name of NT, position in match array:
match_nonterminal(ident, ident, uint)
}
type mac = spanned<mac_>;
#[auto_serialize]
-type mac_arg = option<@expr>;
+type mac_arg = Option<@expr>;
#[auto_serialize]
type mac_body_ = {span: span};
#[auto_serialize]
-type mac_body = option<mac_body_>;
+type mac_body = Option<mac_body_>;
#[auto_serialize]
enum mac_ {
ty_fn(proto, purity, @~[ty_param_bound], fn_decl),
ty_tup(~[@ty]),
ty_path(@path, node_id),
- ty_fixed_length(@ty, option<uint>),
+ ty_fixed_length(@ty, Option<uint>),
ty_mac(mac),
// ty_infer means the type should be inferred instead of it having been
// specified. This should only appear at the "top level" of a type and not
}
#[auto_serialize]
-enum enum_def = { variants: ~[variant], common: option<@struct_def> };
+enum enum_def = { variants: ~[variant], common: Option<@struct_def> };
#[auto_serialize]
type variant_ = {name: ident, attrs: ~[attribute], kind: variant_kind,
- id: node_id, disr_expr: option<@expr>, vis: visibility};
+ id: node_id, disr_expr: Option<@expr>, vis: visibility};
#[auto_serialize]
type variant = spanned<variant_>;
methods: ~[@method], /* methods */
/* (not including ctor or dtor) */
/* ctor is optional, and will soon go away */
- ctor: option<class_ctor>,
+ ctor: Option<class_ctor>,
/* dtor is optional */
- dtor: option<class_dtor>
+ dtor: Option<class_dtor>
};
#[auto_serialize]
fn node_id_to_str(map: map, id: node_id, itr: ident_interner) -> ~str {
match map.find(id) {
- none => {
+ None => {
fmt!("unknown node (id=%d)", id)
}
- some(node_item(item, path)) => {
+ Some(node_item(item, path)) => {
let path_str = path_ident_to_str(*path, item.ident, itr);
let item_str = match item.node {
item_const(*) => ~"const",
};
fmt!("%s %s (id=%?)", item_str, path_str, id)
}
- some(node_foreign_item(item, abi, path)) => {
+ Some(node_foreign_item(item, abi, path)) => {
fmt!("foreign item %s with abi %? (id=%?)",
path_ident_to_str(*path, item.ident, itr), abi, id)
}
- some(node_method(m, impl_did, path)) => {
+ Some(node_method(m, impl_did, path)) => {
fmt!("method %s in %s (id=%?)",
*itr.get(m.ident), path_to_str(*path, itr), id)
}
- some(node_trait_method(tm, impl_did, path)) => {
+ Some(node_trait_method(tm, impl_did, path)) => {
let m = ast_util::trait_method_to_ty_method(*tm);
fmt!("method %s in %s (id=%?)",
*itr.get(m.ident), path_to_str(*path, itr), id)
}
- some(node_variant(variant, def_id, path)) => {
+ Some(node_variant(variant, def_id, path)) => {
fmt!("variant %s in %s (id=%?)",
*itr.get(variant.node.name), path_to_str(*path, itr), id)
}
- some(node_expr(expr)) => {
+ Some(node_expr(expr)) => {
fmt!("expr %s (id=%?)", pprust::expr_to_str(expr, itr), id)
}
- some(node_stmt(stmt)) => {
+ Some(node_stmt(stmt)) => {
fmt!("stmt %s (id=%?)",
pprust::stmt_to_str(*stmt, itr), id)
}
// FIXMEs are as per #2410
- some(node_export(_, path)) => {
+ Some(node_export(_, path)) => {
fmt!("export %s (id=%?)", // add more info here
path_to_str(*path, itr), id)
}
- some(node_arg(_, _)) => { // add more info here
+ Some(node_arg(_, _)) => { // add more info here
fmt!("arg (id=%?)", id)
}
- some(node_local(_)) => { // add more info here
+ Some(node_local(_)) => { // add more info here
fmt!("local (id=%?)", id)
}
- some(node_ctor(*)) => { // add more info here
+ Some(node_ctor(*)) => { // add more info here
fmt!("node_ctor (id=%?)", id)
}
- some(node_dtor(*)) => { // add more info here
+ Some(node_dtor(*)) => { // add more info here
fmt!("node_dtor (id=%?)", id)
}
- some(node_block(_)) => {
+ Some(node_block(_)) => {
fmt!("block")
}
}
/* assuming that we're not in macro expansion */
pure fn mk_sp(lo: uint, hi: uint) -> span {
- {lo: lo, hi: hi, expn_info: none}
+ {lo: lo, hi: hi, expn_info: None}
}
// make this a const, once the compiler supports it
}
}
-pure fn binop_to_method_name(op: binop) -> option<~str> {
+pure fn binop_to_method_name(op: binop) -> Option<~str> {
match op {
- add => return some(~"add"),
- subtract => return some(~"sub"),
- mul => return some(~"mul"),
- div => return some(~"div"),
- rem => return some(~"modulo"),
- bitxor => return some(~"bitxor"),
- bitand => return some(~"bitand"),
- bitor => return some(~"bitor"),
- shl => return some(~"shl"),
- shr => return some(~"shr"),
- and | or | eq | lt | le | ne | ge | gt => return none
+ add => return Some(~"add"),
+ subtract => return Some(~"sub"),
+ mul => return Some(~"mul"),
+ div => return Some(~"div"),
+ rem => return Some(~"modulo"),
+ bitxor => return Some(~"bitxor"),
+ bitand => return Some(~"bitand"),
+ bitor => return Some(~"bitor"),
+ shl => return Some(~"shl"),
+ shr => return Some(~"shr"),
+ and | or | eq | lt | le | ne | ge | gt => return None
}
}
fn is_exported(i: ident, m: _mod) -> bool {
let mut local = false;
- let mut parent_enum : option<ident> = none;
+ let mut parent_enum : Option<ident> = None;
for m.items.each |it| {
if it.ident == i { local = true; }
match it.node {
for enum_definition.variants.each |v| {
if v.node.name == i {
local = true;
- parent_enum = some(/* FIXME (#2543) */ copy it.ident);
+ parent_enum = Some(/* FIXME (#2543) */ copy it.ident);
}
},
_ => ()
ast::view_path_simple(id, _, _) => {
if id == i { return true; }
match parent_enum {
- some(parent_enum_id) => {
+ Some(parent_enum_id) => {
if id == parent_enum_id { return true; }
}
_ => ()
}
fn block_from_expr(e: @expr) -> blk {
- let blk_ = default_block(~[], option::some::<@expr>(e), e.id);
+ let blk_ = default_block(~[], option::Some::<@expr>(e), e.id);
return {node: blk_, span: e.span};
}
-fn default_block(+stmts1: ~[@stmt], expr1: option<@expr>, id1: node_id) ->
+fn default_block(+stmts1: ~[@stmt], expr1: Option<@expr>, id1: node_id) ->
blk_ {
{view_items: ~[], stmts: stmts1,
expr: expr1, id: id1, rules: default_blk}
fn ident_to_path(s: span, +i: ident) -> @path {
@{span: s, global: false, idents: ~[i],
- rp: none, types: ~[]}
+ rp: None, types: ~[]}
}
pure fn is_unguarded(&&a: arm) -> bool {
match a.guard {
- none => true,
+ None => true,
_ => false
}
}
-pure fn unguarded_pat(a: arm) -> option<~[@pat]> {
- if is_unguarded(a) { some(/* FIXME (#2543) */ copy a.pats) } else { none }
+pure fn unguarded_pat(a: arm) -> Option<~[@pat]> {
+ if is_unguarded(a) { Some(/* FIXME (#2543) */ copy a.pats) } else { None }
}
fn public_methods(ms: ~[@method]) -> ~[@method] {
fn walk_pat(pat: @pat, it: fn(@pat)) {
it(pat);
match pat.node {
- pat_ident(_, _, some(p)) => walk_pat(p, it),
+ pat_ident(_, _, Some(p)) => walk_pat(p, it),
pat_rec(fields, _) | pat_struct(_, fields, _) =>
for fields.each |f| { walk_pat(f.pat, it) },
- pat_enum(_, some(s)) | pat_tup(s) => for s.each |p| {
+ pat_enum(_, Some(s)) | pat_tup(s) => for s.each |p| {
walk_pat(p, it)
},
pat_box(s) | pat_uniq(s) => walk_pat(s, it),
* 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<~str> {
+fn get_meta_item_value_str(meta: @ast::meta_item) -> Option<~str> {
match meta.node {
ast::meta_name_value(_, v) => match v.node {
- ast::lit_str(s) => option::some(*s),
- _ => option::none
+ ast::lit_str(s) => option::Some(*s),
+ _ => option::None
},
- _ => option::none
+ _ => option::None
}
}
/// Gets a list of inner meta items from a list meta_item type
-fn get_meta_item_list(meta: @ast::meta_item) -> option<~[@ast::meta_item]> {
+fn get_meta_item_list(meta: @ast::meta_item) -> Option<~[@ast::meta_item]> {
match meta.node {
- ast::meta_list(_, l) => option::some(/* FIXME (#2543) */ copy l),
- _ => option::none
+ ast::meta_list(_, l) => option::Some(/* FIXME (#2543) */ copy l),
+ _ => option::None
}
}
* If the meta item is a nam-value type with a string value then returns
* a tuple containing the name and string value, otherwise `none`
*/
-fn get_name_value_str_pair(item: @ast::meta_item) -> option<(~str, ~str)> {
+fn get_name_value_str_pair(item: @ast::meta_item) -> Option<(~str, ~str)> {
match attr::get_meta_item_value_str(item) {
- some(value) => {
+ Some(value) => {
let name = attr::get_meta_item_name(item);
- some((name, value))
+ Some((name, value))
}
- none => none
+ None => None
}
}
fn find_attrs_by_name(attrs: ~[ast::attribute], name: ~str) ->
~[ast::attribute] {
let filter = (
- fn@(a: ast::attribute) -> option<ast::attribute> {
+ fn@(a: ast::attribute) -> Option<ast::attribute> {
if get_attr_name(a) == name {
- option::some(a)
- } else { option::none }
+ option::Some(a)
+ } else { option::None }
}
);
return vec::filter_map(attrs, filter);
/// Searcha list of meta items and return only those with a specific name
fn find_meta_items_by_name(metas: ~[@ast::meta_item], name: ~str) ->
~[@ast::meta_item] {
- let filter = fn@(&&m: @ast::meta_item) -> option<@ast::meta_item> {
+ let filter = fn@(&&m: @ast::meta_item) -> Option<@ast::meta_item> {
if get_meta_item_name(m) == name {
- option::some(m)
- } else { option::none }
+ option::Some(m)
+ } else { option::None }
};
return vec::filter_map(metas, filter);
}
}
fn first_attr_value_str_by_name(attrs: ~[ast::attribute], name: ~str)
- -> option<~str> {
+ -> Option<~str> {
let mattrs = find_attrs_by_name(attrs, name);
if vec::len(mattrs) > 0u {
return get_meta_item_value_str(attr_meta(mattrs[0]));
}
- return option::none;
+ return option::None;
}
fn last_meta_item_by_name(items: ~[@ast::meta_item], name: ~str)
- -> option<@ast::meta_item> {
+ -> Option<@ast::meta_item> {
let items = attr::find_meta_items_by_name(items, name);
vec::last_opt(items)
}
fn last_meta_item_value_str_by_name(items: ~[@ast::meta_item], name: ~str)
- -> option<~str> {
+ -> Option<~str> {
match last_meta_item_by_name(items, name) {
- some(item) => match attr::get_meta_item_value_str(item) {
- some(value) => some(value),
- none => none
+ Some(item) => match attr::get_meta_item_value_str(item) {
+ Some(value) => Some(value),
+ None => None
},
- none => none
+ None => None
}
}
fn last_meta_item_list_by_name(items: ~[@ast::meta_item], name: ~str)
- -> option<~[@ast::meta_item]> {
+ -> Option<~[@ast::meta_item]> {
match last_meta_item_by_name(items, name) {
- some(item) => attr::get_meta_item_list(item),
- none => none
+ Some(item) => attr::get_meta_item_list(item),
+ None => None
}
}
return vec::filter_map(items, |item| {
if get_meta_item_name(item) != name {
- option::some(/* FIXME (#2543) */ copy item)
+ option::Some(/* FIXME (#2543) */ copy item)
} else {
- option::none
+ option::None
}
});
}
fn foreign_abi(attrs: ~[ast::attribute]) -> Either<~str, ast::foreign_abi> {
return match attr::first_attr_value_str_by_name(attrs, ~"abi") {
- option::none => {
+ option::None => {
either::Right(ast::foreign_abi_cdecl)
}
- option::some(~"rust-intrinsic") => {
+ option::Some(~"rust-intrinsic") => {
either::Right(ast::foreign_abi_rust_intrinsic)
}
- option::some(~"cdecl") => {
+ option::Some(~"cdecl") => {
either::Right(ast::foreign_abi_cdecl)
}
- option::some(~"stdcall") => {
+ option::Some(~"stdcall") => {
either::Right(ast::foreign_abi_stdcall)
}
- option::some(t) => {
+ option::Some(t) => {
either::Left(~"unsupported abi: " + t)
}
};
}
fn lookup_char_pos_adj(map: codemap, pos: uint)
- -> {filename: ~str, line: uint, col: uint, file: option<filemap>}
+ -> {filename: ~str, line: uint, col: uint, file: Option<filemap>}
{
let loc = lookup_char_pos(map, pos);
match (loc.file.substr) {
{filename: /* FIXME (#2543) */ copy loc.file.name,
line: loc.line,
col: loc.col,
- file: some(loc.file)}
+ file: Some(loc.file)}
}
fss_internal(sp) => {
lookup_char_pos_adj(map, sp.lo + (pos - loc.file.start_pos.ch))
{filename: /* FIXME (#2543) */ copy eloc.filename,
line: eloc.line + loc.line - 1u,
col: if loc.line == 1u {eloc.col + loc.col} else {loc.col},
- file: none}
+ file: None}
}
}
}
enum expn_info_ {
expanded_from({call_site: span,
- callie: {name: ~str, span: option<span>}})
+ callie: {name: ~str, span: Option<span>}})
}
-type expn_info = option<@expn_info_>;
+type expn_info = Option<@expn_info_>;
type span = {lo: uint, hi: uint, expn_info: expn_info};
fn span_to_str_no_adj(sp: span, cm: codemap) -> ~str {
fn get_line(fm: filemap, line: int) -> ~str unsafe {
let begin: uint = fm.lines[line].byte - fm.start_pos.byte;
let end = match str::find_char_from(*fm.src, '\n', begin) {
- some(e) => e,
- none => str::len(*fm.src)
+ Some(e) => e,
+ None => str::len(*fm.src)
};
str::slice(*fm.src, begin, end)
}
export ice_msg;
export expect;
-type emitter = fn@(cmsp: option<(codemap::codemap, span)>,
+type emitter = fn@(cmsp: Option<(codemap::codemap, span)>,
msg: ~str, lvl: level);
fn note(msg: ~str);
fn bug(msg: ~str) -> !;
fn unimpl(msg: ~str) -> !;
- fn emit(cmsp: option<(codemap::codemap, span)>, msg: ~str, lvl: level);
+ fn emit(cmsp: Option<(codemap::codemap, span)>, msg: ~str, lvl: level);
}
type handler_t = @{
impl codemap_t: span_handler {
fn span_fatal(sp: span, msg: ~str) -> ! {
- self.handler.emit(some((self.cm, sp)), msg, fatal);
+ self.handler.emit(Some((self.cm, sp)), msg, fatal);
fail;
}
fn span_err(sp: span, msg: ~str) {
- self.handler.emit(some((self.cm, sp)), msg, error);
+ self.handler.emit(Some((self.cm, sp)), msg, error);
self.handler.bump_err_count();
}
fn span_warn(sp: span, msg: ~str) {
- self.handler.emit(some((self.cm, sp)), msg, warning);
+ self.handler.emit(Some((self.cm, sp)), msg, warning);
}
fn span_note(sp: span, msg: ~str) {
- self.handler.emit(some((self.cm, sp)), msg, note);
+ self.handler.emit(Some((self.cm, sp)), msg, note);
}
fn span_bug(sp: span, msg: ~str) -> ! {
self.span_fatal(sp, ice_msg(msg));
impl handler_t: handler {
fn fatal(msg: ~str) -> ! {
- self.emit(none, msg, fatal);
+ self.emit(None, msg, fatal);
fail;
}
fn err(msg: ~str) {
- self.emit(none, msg, error);
+ self.emit(None, msg, error);
self.bump_err_count();
}
fn bump_err_count() {
self.fatal(s);
}
fn warn(msg: ~str) {
- self.emit(none, msg, warning);
+ self.emit(None, msg, warning);
}
fn note(msg: ~str) {
- self.emit(none, msg, note);
+ self.emit(None, msg, note);
}
fn bug(msg: ~str) -> ! {
self.fatal(ice_msg(msg));
}
fn unimpl(msg: ~str) -> ! { self.bug(~"unimplemented " + msg); }
- fn emit(cmsp: option<(codemap::codemap, span)>, msg: ~str, lvl: level) {
+ fn emit(cmsp: Option<(codemap::codemap, span)>, msg: ~str, lvl: level) {
self.emit(cmsp, msg, lvl);
}
}
@{ handler: handler, cm: cm } as span_handler
}
-fn mk_handler(emitter: option<emitter>) -> handler {
+fn mk_handler(emitter: Option<emitter>) -> handler {
let emit = match emitter {
- some(e) => e,
- none => {
- let f = fn@(cmsp: option<(codemap::codemap, span)>,
+ Some(e) => e,
+ None => {
+ let f = fn@(cmsp: Option<(codemap::codemap, span)>,
msg: ~str, t: level) {
emit(cmsp, msg, t);
};
io::stderr().write_str(fmt!(" %s\n", msg));
}
-fn emit(cmsp: option<(codemap::codemap, span)>,
+fn emit(cmsp: Option<(codemap::codemap, span)>,
msg: ~str, lvl: level) {
match cmsp {
- some((cm, sp)) => {
+ Some((cm, sp)) => {
let sp = codemap::adjust_span(cm,sp);
let ss = codemap::span_to_str(sp, cm);
let lines = codemap::span_to_lines(sp, cm);
highlight_lines(cm, sp, lines);
print_macro_backtrace(cm, sp);
}
- none => {
+ None => {
print_diagnostic(~"", lvl, msg);
}
}
}
fn expect<T: copy>(diag: span_handler,
- opt: option<T>, msg: fn() -> ~str) -> T {
+ opt: Option<T>, msg: fn() -> ~str) -> T {
match opt {
- some(t) => t,
- none => diag.handler().bug(msg())
+ Some(t) => t,
+ None => diag.handler().bug(msg())
}
}
}
fn path(span: span, strs: ~[ast::ident]) -> @ast::path {
- @{span: span, global: false, idents: strs, rp: none, types: ~[]}
+ @{span: span, global: false, idents: strs, rp: None, types: ~[]}
}
fn path_tps(span: span, strs: ~[ast::ident],
tps: ~[@ast::ty]) -> @ast::path {
- @{span: span, global: false, idents: strs, rp: none, types: tps}
+ @{span: span, global: false, idents: strs, rp: None, types: tps}
}
fn ty_path(span: span, strs: ~[ast::ident],
fn blk(span: span, stmts: ~[@ast::stmt]) -> ast::blk {
{node: {view_items: ~[],
stmts: stmts,
- expr: none,
+ expr: None,
id: self.next_id(),
rules: ast::default_blk},
span: span}
fn expr_blk(expr: @ast::expr) -> ast::blk {
{node: {view_items: ~[],
stmts: ~[],
- expr: some(expr),
+ expr: Some(expr),
id: self.next_id(),
rules: ast::default_blk},
span: expr.span}
fn binder_pat(span: span, nm: ast::ident) -> @ast::pat {
let path = @{span: span, global: false, idents: ~[nm],
- rp: none, types: ~[]};
+ rp: None, types: ~[]};
@{id: self.next_id(),
node: ast::pat_ident(ast::bind_by_implicit_ref,
path,
- none),
+ None),
span: span}
}
let body_blk = cx.blk(span, stmts);
let body = cx.blk(span, ~[cx.stmt(bodyfn(s, body_blk))]);
- {pats: ~[pat], guard: none, body: body}
+ {pats: ~[pat], guard: None, body: body}
}
fn ser_lambda(cx: ext_ctxt, tps: ser_tps_map, ty: @ast::ty,
ast::ty_vec(_) => true,
// This may be wrong if the user has shadowed (!) str
ast::ty_path(@{span: _, global: _, idents: ids,
- rp: none, types: _}, _)
+ rp: None, types: _}, _)
if ids == ~[parse::token::special_idents::str] => true,
_ => false
}
let ident = path.idents[0];
match tps.find(ident) {
- some(f) => f(v),
- none => ser_path(cx, tps, path, s, v)
+ Some(f) => f(v),
+ None => ser_path(cx, tps, path, s, v)
}
} else {
ser_path(cx, tps, path, s, v)
expr: #ast{ $(d).read_rec_field($(f), $(i), $(l))} },
span: fld.span}
};
- let fld_expr = cx.expr(ty.span, ast::expr_rec(fields, none));
+ let fld_expr = cx.expr(ty.span, ast::expr_rec(fields, None));
let fld_lambda = cx.lambda(cx.expr_blk(fld_expr));
#ast{ $(d).read_rec($(fld_lambda)) }
}
let ident = path.idents[0];
match tps.find(ident) {
- some(f) => f(),
- none => deser_path(cx, tps, path, d)
+ Some(f) => f(),
+ None => deser_path(cx, tps, path, d)
}
} else {
deser_path(cx, tps, path, d)
if vec::is_empty(pats) {
ast::pat_ident(ast::bind_by_implicit_ref,
cx.path(v_span, ~[v_name]),
- none)
+ None)
} else {
ast::pat_enum(cx.path(v_span, ~[v_name]),
- some(pats))
+ Some(pats))
}
},
{pats: ~[@{id: cx.next_id(),
node: ast::pat_lit(cx.lit_uint(v_span, vidx)),
span: v_span}],
- guard: none,
+ guard: None,
body: cx.expr_blk(body)}
};
let impossible_case = {pats: ~[@{id: cx.next_id(),
node: ast::pat_wild,
span: e_span}],
- guard: none,
+ guard: None,
// FIXME #3198: proper error message
body: cx.expr_blk(cx.expr(e_span,
- ast::expr_fail(none)))};
+ ast::expr_fail(None)))};
arms += ~[impossible_case];
// Generate code like:
type syntax_expander_ =
fn@(ext_ctxt, span, ast::mac_arg, ast::mac_body) -> @ast::expr;
// second argument is the origin of the macro, if user-defined
-type syntax_expander = {expander: syntax_expander_, span: option<span>};
+type syntax_expander = {expander: syntax_expander_, span: Option<span>};
type macro_def = {name: ~str, ext: syntax_extension};
type item_decorator =
fn@(ext_ctxt, span, ast::meta_item, ~[@ast::item]) -> ~[@ast::item];
-type syntax_expander_tt = {expander: syntax_expander_tt_, span: option<span>};
+type syntax_expander_tt = {expander: syntax_expander_tt_, span: Option<span>};
type syntax_expander_tt_ = fn@(ext_ctxt, span, ~[ast::token_tree])
-> mac_result;
type syntax_expander_tt_item
- = {expander: syntax_expander_tt_item_, span: option<span>};
+ = {expander: syntax_expander_tt_item_, span: Option<span>};
type syntax_expander_tt_item_
= fn@(ext_ctxt, span, ast::ident, ~[ast::token_tree]) -> mac_result;
// AST nodes into full ASTs
fn syntax_expander_table() -> hashmap<~str, syntax_extension> {
fn builtin(f: syntax_expander_) -> syntax_extension
- {normal({expander: f, span: none})}
+ {normal({expander: f, span: None})}
fn builtin_expr_tt(f: syntax_expander_tt_) -> syntax_extension {
- expr_tt({expander: f, span: none})
+ expr_tt({expander: f, span: None})
}
fn builtin_item_tt(f: syntax_expander_tt_item_) -> syntax_extension {
- item_tt({expander: f, span: none})
+ item_tt({expander: f, span: None})
}
let syntax_expanders = str_hash::<syntax_extension>();
syntax_expanders.insert(~"macro",
match ei {
expanded_from({call_site: cs, callie: callie}) => {
self.backtrace =
- some(@expanded_from({
+ Some(@expanded_from({
call_site: {lo: cs.lo, hi: cs.hi,
expn_info: self.backtrace},
callie: callie}));
}
fn bt_pop() {
match self.backtrace {
- some(@expanded_from({call_site: {expn_info: prev, _}, _})) => {
+ Some(@expanded_from({call_site: {expn_info: prev, _}, _})) => {
self.backtrace = prev
}
_ => self.bug(~"tried to pop without a push")
let imp : ctxt_repr = {
parse_sess: parse_sess,
cfg: cfg,
- mut backtrace: none,
+ mut backtrace: None,
mut mod_path: ~[],
mut trace_mac: false
};
fn get_mac_args_no_max(cx: ext_ctxt, sp: span, arg: ast::mac_arg,
min: uint, name: ~str) -> ~[@ast::expr] {
- return get_mac_args(cx, sp, arg, min, none, name);
+ return get_mac_args(cx, sp, arg, min, None, name);
}
fn get_mac_args(cx: ext_ctxt, sp: span, arg: ast::mac_arg,
- min: uint, max: option<uint>, name: ~str) -> ~[@ast::expr] {
+ min: uint, max: Option<uint>, name: ~str) -> ~[@ast::expr] {
match arg {
- some(expr) => match expr.node {
+ Some(expr) => match expr.node {
ast::expr_vec(elts, _) => {
let elts_len = vec::len(elts);
match max {
- some(max) if ! (min <= elts_len && elts_len <= max) => {
+ Some(max) if ! (min <= elts_len && elts_len <= max) => {
cx.span_fatal(sp,
fmt!("#%s takes between %u and %u arguments.",
name, min, max));
}
- none if ! (min <= elts_len) => {
+ None if ! (min <= elts_len) => {
cx.span_fatal(sp, fmt!("#%s needs at least %u arguments.",
name, min));
}
cx.span_fatal(sp, fmt!("#%s: malformed invocation", name))
}
},
- none => cx.span_fatal(sp, fmt!("#%s: missing arguments", name))
+ None => cx.span_fatal(sp, fmt!("#%s: missing arguments", name))
}
}
-> ast::mac_body_
{
match (args) {
- some(body) => body,
- none => cx.span_fatal(sp, ~"missing macro body")
+ Some(body) => body,
+ None => cx.span_fatal(sp, ~"missing macro body")
}
}
// these spans won't matter, anyways
fn ms(m: matcher_) -> matcher {
- {node: m, span: {lo: 0u, hi: 0u, expn_info: none}}
+ {node: m, span: {lo: 0u, hi: 0u, expn_info: None}}
}
let arg_nm = cx.parse_sess().interner.gensym(@~"arg");
let argument_gram = ~[ms(match_seq(~[
ms(match_nonterminal(arg_nm, parse::token::special_idents::expr, 0u))
- ], some(parse::token::COMMA), true, 0u, 1u))];
+ ], Some(parse::token::COMMA), true, 0u, 1u))];
let arg_reader = new_tt_reader(cx.parse_sess().span_diagnostic,
- cx.parse_sess().interner, none, arg);
+ cx.parse_sess().interner, None, arg);
let args =
match parse_or_else(cx.parse_sess(), cx.cfg(), arg_reader as reader,
argument_gram).get(arg_nm) {
_ => fail ~"badly-structured parse result"
};
- return some(@{id: parse::next_node_id(cx.parse_sess()),
+ return Some(@{id: parse::next_node_id(cx.parse_sess()),
callee_id: parse::next_node_id(cx.parse_sess()),
node: ast::expr_vec(args, ast::m_imm), span: sp});
}
fn mk_path(cx: ext_ctxt, sp: span, idents: ~[ast::ident]) ->
@ast::expr {
let path = @{span: sp, global: false, idents: idents,
- rp: none, types: ~[]};
+ rp: None, types: ~[]};
let pathexpr = ast::expr_path(path);
mk_expr(cx, sp, pathexpr)
}
}
fn mk_fixed_vec_e(cx: ext_ctxt, sp: span, exprs: ~[@ast::expr]) ->
@ast::expr {
- mk_vstore_e(cx, sp, mk_base_vec_e(cx, sp, exprs), ast::vstore_fixed(none))
+ mk_vstore_e(cx, sp, mk_base_vec_e(cx, sp, exprs), ast::vstore_fixed(None))
}
fn mk_base_str(cx: ext_ctxt, sp: span, s: ~str) -> @ast::expr {
let lit = ast::lit_str(@s);
{node: {mutbl: ast::m_imm, ident: ident, expr: val}, span: sp};
vec::push(astfields, astfield);
}
- let recexpr = ast::expr_rec(astfields, option::none::<@ast::expr>);
+ let recexpr = ast::expr_rec(astfields, option::None::<@ast::expr>);
mk_expr(cx, sp, recexpr)
}
return @{id: cx.next_id(),
callee_id: cx.next_id(),
node: ast::expr_path(@{span: sp, global: false, idents: ~[res],
- rp: none, types: ~[]}),
+ rp: None, types: ~[]}),
span: sp};
}
fn expand_syntax_ext(cx: ext_ctxt, sp: codemap::span, arg: ast::mac_arg,
_body: ast::mac_body) -> @ast::expr {
- let args = get_mac_args(cx, sp, arg, 1u, option::some(1u), ~"env");
+ let args = get_mac_args(cx, sp, arg, 1u, option::Some(1u), ~"env");
// FIXME (#2248): if this was more thorough it would manufacture an
- // option<str> rather than just an maybe-empty string.
+ // Option<str> rather than just an maybe-empty string.
let var = expr_to_str(cx, args[0], ~"#env requires a string");
match os::getenv(var) {
- option::none => return mk_uniq_str(cx, sp, ~""),
- option::some(s) => return mk_uniq_str(cx, sp, s)
+ option::None => return mk_uniq_str(cx, sp, ~""),
+ option::Some(s) => return mk_uniq_str(cx, sp, s)
}
}
the macro names be hygienic */
let extname = cx.parse_sess().interner.get(pth.idents[0]);
match exts.find(*extname) {
- none => {
+ None => {
cx.span_fatal(pth.span,
fmt!("macro undefined: '%s'", *extname))
}
- some(item_decorator(_)) => {
+ Some(item_decorator(_)) => {
cx.span_fatal(
pth.span,
fmt!("%s can only be used as a decorator", *extname));
}
- some(normal({expander: exp, span: exp_sp})) => {
+ Some(normal({expander: exp, span: exp_sp})) => {
let expanded = exp(cx, mac.span, args, body);
cx.bt_push(expanded_from({call_site: s,
(fully_expanded, s)
}
- some(macro_defining(ext)) => {
+ Some(macro_defining(ext)) => {
let named_extension = ext(cx, mac.span, args, body);
exts.insert(named_extension.name, named_extension.ext);
- (ast::expr_rec(~[], none), s)
+ (ast::expr_rec(~[], None), s)
}
- some(expr_tt(_)) => {
+ Some(expr_tt(_)) => {
cx.span_fatal(pth.span,
fmt!("this tt-style macro should be \
invoked '%s!(...)'", *extname))
}
- some(item_tt(*)) => {
+ Some(item_tt(*)) => {
cx.span_fatal(pth.span,
~"cannot use item macros in this context");
}
the macro names be hygienic */
let extname = cx.parse_sess().interner.get(pth.idents[0]);
match exts.find(*extname) {
- none => {
+ None => {
cx.span_fatal(pth.span,
fmt!("macro undefined: '%s'", *extname))
}
- some(expr_tt({expander: exp, span: exp_sp})) => {
+ Some(expr_tt({expander: exp, span: exp_sp})) => {
let expanded = match exp(cx, mac.span, tts) {
mr_expr(e) => e,
_ => cx.span_fatal(
(fully_expanded, s)
}
- some(normal({expander: exp, span: exp_sp})) => {
+ Some(normal({expander: exp, span: exp_sp})) => {
//convert the new-style invoc for the old-style macro
let arg = base::tt_args_to_original_flavor(cx, pth.span,
tts);
- let expanded = exp(cx, mac.span, arg, none);
+ let expanded = exp(cx, mac.span, arg, None);
cx.bt_push(expanded_from({call_site: s,
callie: {name: *extname, span: exp_sp}}));
ast::meta_list(n, _) => n
};
match exts.find(mname) {
- none | some(normal(_)) | some(macro_defining(_))
- | some(expr_tt(_)) | some(item_tt(*)) => items,
- some(item_decorator(dec_fn)) => {
+ None | Some(normal(_)) | Some(macro_defining(_))
+ | Some(expr_tt(_)) | Some(item_tt(*)) => items,
+ Some(item_decorator(dec_fn)) => {
dec_fn(cx, attr.span, attr.node.value, items)
}
}
// When we enter a module, record it, for the sake of `module!`
fn expand_item(exts: hashmap<~str, syntax_extension>,
cx: ext_ctxt, &&it: @ast::item, fld: ast_fold,
- orig: fn@(&&@ast::item, ast_fold) -> option<@ast::item>)
- -> option<@ast::item>
+ orig: fn@(&&@ast::item, ast_fold) -> Option<@ast::item>)
+ -> Option<@ast::item>
{
let is_mod = match it.node {
ast::item_mod(_) | ast::item_foreign_mod(_) => true,
};
let maybe_it = match it.node {
ast::item_mac(*) => expand_item_mac(exts, cx, it, fld),
- _ => some(it)
+ _ => Some(it)
};
match maybe_it {
- some(it) => {
+ Some(it) => {
if is_mod { cx.mod_push(it.ident); }
let ret_val = orig(it, fld);
if is_mod { cx.mod_pop(); }
return ret_val;
}
- none => return none
+ None => return None
}
}
// logic as for expression-position macro invocations.
fn expand_item_mac(exts: hashmap<~str, syntax_extension>,
cx: ext_ctxt, &&it: @ast::item,
- fld: ast_fold) -> option<@ast::item> {
+ fld: ast_fold) -> Option<@ast::item> {
match it.node {
item_mac({node: mac_invoc_tt(pth, tts), span}) => {
let extname = cx.parse_sess().interner.get(pth.idents[0]);
match exts.find(*extname) {
- none => {
+ None => {
cx.span_fatal(pth.span,
fmt!("macro undefined: '%s'", *extname))
}
- some(item_tt(expand)) => {
+ Some(item_tt(expand)) => {
let expanded = expand.expander(cx, it.span, it.ident, tts);
cx.bt_push(expanded_from({call_site: it.span,
callie: {name: *extname,
*extname),
mr_def(mdef) => {
exts.insert(mdef.name, mdef.ext);
- none
+ None
}
};
cx.bt_pop();
}
let unsupported = ~"conversion not supported in #fmt string";
match cnv.param {
- option::none => (),
+ option::None => (),
_ => cx.span_unimpl(sp, unsupported)
}
for cnv.flags.each |f| {
}
fn log_conv(c: conv) {
match c.param {
- some(p) => { log(debug, ~"param: " + int::to_str(p, 10u)); }
+ Some(p) => { log(debug, ~"param: " + int::to_str(p, 10u)); }
_ => debug!("param: none")
}
for c.flags.each |f| {
fn expand_syntax_ext(cx: ext_ctxt, sp: codemap::span, arg: ast::mac_arg,
_body: ast::mac_body) -> @ast::expr {
- let args = get_mac_args(cx,sp,arg,1u,option::some(1u),~"ident_to_str");
+ let args = get_mac_args(cx,sp,arg,1u,option::Some(1u),~"ident_to_str");
return mk_uniq_str(cx, sp, *cx.parse_sess().interner.get(
expr_to_ident(cx, args[0u], ~"expected an ident")));
//trivial expression
return mr_expr(@{id: cx.next_id(), callee_id: cx.next_id(),
- node: ast::expr_rec(~[], option::none), span: sp});
+ node: ast::expr_rec(~[], option::None), span: sp});
}
let sess = cx.parse_sess();
let cfg = cx.cfg();
let tt_rdr = new_tt_reader(cx.parse_sess().span_diagnostic,
- cx.parse_sess().interner, none, tt);
+ cx.parse_sess().interner, None, tt);
let rdr = tt_rdr as reader;
let rust_parser = parser(sess, cfg, rdr.dup(), SOURCE_FILE);
@{span: span,
global: false,
idents: ids,
- rp: none,
+ rp: None,
types: ~[]}
}
fn empty_span() -> span {
- {lo: 0, hi: 0, expn_info: none}
+ {lo: 0, hi: 0, expn_info: None}
}
trait append_types {
impl ext_ctxt: ext_ctxt_ast_builder {
fn ty_option(ty: @ast::ty) -> @ast::ty {
- self.ty_path_ast_builder(path(~[self.ident_of(~"option")],
+ self.ty_path_ast_builder(path(~[self.ident_of(~"Option")],
self.empty_span())
.add_ty(ty))
}
node: ast::pat_ident(ast::bind_by_implicit_ref,
path(~[ident],
self.empty_span()),
- none),
+ None),
span: self.empty_span()},
- init: some({op: ast::init_move,
+ init: Some({op: ast::init_move,
expr: e}),
id: self.next_id()},
span: self.empty_span()}]),
fn rec(+fields: ~[ast::field]) -> @ast::expr {
@{id: self.next_id(),
callee_id: self.next_id(),
- node: ast::expr_rec(fields, none),
+ node: ast::expr_rec(fields, None),
span: self.empty_span()}
}
fn block(+stmts: ~[@ast::stmt], e: @ast::expr) -> ast::blk {
let blk = {view_items: ~[],
stmts: stmts,
- expr: some(e),
+ expr: Some(e),
id: self.next_id(),
rules: ast::default_blk};
attrs: ~[],
kind: ast::tuple_variant_kind(args),
id: self.next_id(),
- disr_expr: none,
+ disr_expr: None,
vis: ast::public},
span: span}
}
fn visit_message(name: ~str, _span: span, _tys: &[@ast::ty],
this: state, next: next_state) {
match next {
- some({state: next, tys: next_tys}) => {
+ Some({state: next, tys: next_tys}) => {
let proto = this.proto;
if !proto.has_state(next) {
// This should be a span fatal, but then we need to
}
}
}
- none => ()
+ None => ()
}
}
}
\ No newline at end of file
// *proto.name,
// states));
- proto.bounded = some(false);
+ proto.bounded = Some(false);
}
else {
debug!("protocol %s is bounded. yay!", proto.name);
- proto.bounded = some(true);
+ proto.bounded = Some(true);
}
}
\ No newline at end of file
let proto = protocol(id, self.span);
self.parse_seq_to_before_end(token::EOF,
- {sep: none, trailing_sep_allowed: false},
+ {sep: None, trailing_sep_allowed: false},
|self| self.parse_state(proto));
return proto;
// parse the messages
self.parse_unspanned_seq(
token::LBRACE, token::RBRACE,
- {sep: some(token::COMMA), trailing_sep_allowed: true},
+ {sep: Some(token::COMMA), trailing_sep_allowed: true},
|self| self.parse_message(state));
}
let args = if self.token == token::LPAREN {
self.parse_unspanned_seq(token::LPAREN,
token::RPAREN,
- {sep: some(token::COMMA),
+ {sep: Some(token::COMMA),
trailing_sep_allowed: true},
|p| p.parse_ty(false))
}
let ntys = if self.token == token::LT {
self.parse_unspanned_seq(token::LT,
token::GT,
- {sep: some(token::COMMA),
+ {sep: Some(token::COMMA),
trailing_sep_allowed: true},
|p| p.parse_ty(false))
}
else { ~[] };
- some({state: name, tys: ntys})
+ Some({state: name, tys: ntys})
}
token::NOT => {
// -> !
self.bump();
- none
+ None
}
_ => self.fatal(~"invalid next state")
};
debug!("pipec: gen_send");
match self {
message(_id, span, tys, this,
- some({state: next, tys: next_tys})) => {
+ Some({state: next, tys: next_tys})) => {
debug!("pipec: next state exists");
let next = this.proto.get_state(next);
assert next_tys.len() == next.ty_params.len();
cx.expr_block(body))
}
- message(_id, span, tys, this, none) => {
+ message(_id, span, tys, this, None) => {
debug!("pipec: no next state");
let arg_names = tys.mapi(|i, _ty| (~"x_" + i.to_str()));
let message(name, span, tys, this, next) = m;
let tys = match next {
- some({state: next, tys: next_tys}) => {
+ Some({state: next, tys: next_tys}) => {
let next = this.proto.get_state(next);
let next_name = cx.str_of(next.data_name());
cx.ident_of(next_name)], span)
.add_tys(next_tys)))
}
- none => tys
+ None => tys
};
let v = cx.variant(cx.ident_of(name), span, tys);
~[cx.item_enum_poly(name,
self.span,
ast::enum_def({ variants: items_msg,
- common: none }),
+ common: None }),
self.ty_params)]
}
for (copy self.states).each |s| {
for s.ty_params.each |tp| {
match params.find(|tpp| tp.ident == tpp.ident) {
- none => vec::push(params, tp),
+ None => vec::push(params, tp),
_ => ()
}
}
let fields = do (copy self.states).map_to_vec |s| {
for s.ty_params.each |tp| {
match params.find(|tpp| tp.ident == tpp.ident) {
- none => vec::push(params, tp),
+ None => vec::push(params, tp),
_ => ()
}
}
~[],
self.parse_sess());
match res {
- some(ast) => ast,
- none => {
+ Some(ast) => ast,
+ None => {
error!("Parse error with ```\n%s\n```", s);
fail
}
}
}
-type next_state = option<{state: ~str, tys: ~[@ast::ty]}>;
+type next_state = Option<{state: ~str, tys: ~[@ast::ty]}>;
enum message {
// name, span, data, current state, next state
fn reachable(f: fn(state) -> bool) {
for self.messages.each |m| {
match m {
- message(_, _, _, _, some({state: id, _})) => {
+ message(_, _, _, _, Some({state: id, _})) => {
let state = self.proto.get_state(id);
if !f(state) { break }
}
let span: span;
let states: DVec<state>;
- let mut bounded: option<bool>;
+ let mut bounded: Option<bool>;
new(name: ~str, span: span) {
self.name = name;
self.span = span;
self.states = dvec();
- self.bounded = none;
+ self.bounded = None;
}
/// Get a state.
fn get_state_by_id(id: uint) -> state { self.states[id] }
fn has_state(name: ~str) -> bool {
- self.states.find(|i| i.name == name) != none
+ self.states.find(|i| i.name == name) != None
}
fn filename() -> ~str {
trait qq_helper {
fn span() -> span;
fn visit(aq_ctxt, vt<aq_ctxt>);
- fn extract_mac() -> option<ast::mac_>;
+ fn extract_mac() -> Option<ast::mac_>;
fn mk_parse_fn(ext_ctxt,span) -> @ast::expr;
fn get_fold_fn() -> ~str;
}
impl @ast::crate: qq_helper {
fn span() -> span {self.span}
fn visit(cx: aq_ctxt, v: vt<aq_ctxt>) {visit_crate(*self, cx, v);}
- fn extract_mac() -> option<ast::mac_> {fail}
+ fn extract_mac() -> Option<ast::mac_> {fail}
fn mk_parse_fn(cx: ext_ctxt, sp: span) -> @ast::expr {
mk_path(cx, sp,
ids_ext(cx, ~[~"syntax", ~"ext", ~"qquote", ~"parse_crate"]))
impl @ast::expr: qq_helper {
fn span() -> span {self.span}
fn visit(cx: aq_ctxt, v: vt<aq_ctxt>) {visit_expr(self, cx, v);}
- fn extract_mac() -> option<ast::mac_> {
+ fn extract_mac() -> Option<ast::mac_> {
match (self.node) {
- ast::expr_mac({node: mac, _}) => some(mac),
- _ => none
+ ast::expr_mac({node: mac, _}) => Some(mac),
+ _ => None
}
}
fn mk_parse_fn(cx: ext_ctxt, sp: span) -> @ast::expr {
impl @ast::ty: qq_helper {
fn span() -> span {self.span}
fn visit(cx: aq_ctxt, v: vt<aq_ctxt>) {visit_ty(self, cx, v);}
- fn extract_mac() -> option<ast::mac_> {
+ fn extract_mac() -> Option<ast::mac_> {
match (self.node) {
- ast::ty_mac({node: mac, _}) => some(mac),
- _ => none
+ ast::ty_mac({node: mac, _}) => Some(mac),
+ _ => None
}
}
fn mk_parse_fn(cx: ext_ctxt, sp: span) -> @ast::expr {
impl @ast::item: qq_helper {
fn span() -> span {self.span}
fn visit(cx: aq_ctxt, v: vt<aq_ctxt>) {visit_item(self, cx, v);}
- fn extract_mac() -> option<ast::mac_> {fail}
+ fn extract_mac() -> Option<ast::mac_> {fail}
fn mk_parse_fn(cx: ext_ctxt, sp: span) -> @ast::expr {
mk_path(cx, sp,
ids_ext(cx, ~[~"syntax", ~"ext", ~"qquote", ~"parse_item"]))
impl @ast::stmt: qq_helper {
fn span() -> span {self.span}
fn visit(cx: aq_ctxt, v: vt<aq_ctxt>) {visit_stmt(self, cx, v);}
- fn extract_mac() -> option<ast::mac_> {fail}
+ fn extract_mac() -> Option<ast::mac_> {fail}
fn mk_parse_fn(cx: ext_ctxt, sp: span) -> @ast::expr {
mk_path(cx, sp,
ids_ext(cx, ~[~"syntax", ~"ext", ~"qquote", ~"parse_stmt"]))
impl @ast::pat: qq_helper {
fn span() -> span {self.span}
fn visit(cx: aq_ctxt, v: vt<aq_ctxt>) {visit_pat(self, cx, v);}
- fn extract_mac() -> option<ast::mac_> {fail}
+ fn extract_mac() -> Option<ast::mac_> {fail}
fn mk_parse_fn(cx: ext_ctxt, sp: span) -> @ast::expr {
mk_path(cx, sp, ids_ext(cx, ~[~"syntax", ~"ext", ~"qquote",
~"parse_pat"]))
fn visit_aq<T:qq_helper>(node: T, constr: ~str, &&cx: aq_ctxt, v: vt<aq_ctxt>)
{
match (node.extract_mac()) {
- some(mac_aq(sp, e)) => {
+ Some(mac_aq(sp, e)) => {
cx.gather.push(gather_item {
lo: sp.lo - cx.lo,
hi: sp.hi - cx.lo,
fn parse_item(p: parser) -> @ast::item {
match p.parse_item(~[]) {
- some(item) => item,
- none => fail ~"parse_item: parsing an item failed"
+ Some(item) => item,
+ None => fail ~"parse_item: parsing an item failed"
}
}
export add_new_extension;
-fn path_to_ident(pth: @path) -> option<ident> {
+fn path_to_ident(pth: @path) -> Option<ident> {
if vec::len(pth.idents) == 1u && vec::len(pth.types) == 0u {
- return some(pth.idents[0u]);
+ return Some(pth.idents[0u]);
}
- return none;
+ return None;
}
//a vec of binders might be a little big.
// If we want better match failure error messages (like in Fortifying Syntax),
// we'll want to return something indicating amount of progress and location
// of failure instead of `none`.
-type match_result = option<arb_depth<matchable>>;
+type match_result = Option<arb_depth<matchable>>;
type selector = fn@(matchable) -> match_result;
fn elts_to_ell(cx: ext_ctxt, elts: ~[@expr]) ->
- {pre: ~[@expr], rep: option<@expr>, post: ~[@expr]} {
+ {pre: ~[@expr], rep: Option<@expr>, post: ~[@expr]} {
let mut idx: uint = 0u;
- let mut res = none;
+ let mut res = None;
for elts.each |elt| {
match elt.node {
expr_mac(m) => match m.node {
ast::mac_ellipsis => {
- if res != none {
+ if res != None {
cx.span_fatal(m.span, ~"only one ellipsis allowed");
}
res =
- some({pre: vec::slice(elts, 0u, idx - 1u),
- rep: some(elts[idx - 1u]),
+ Some({pre: vec::slice(elts, 0u, idx - 1u),
+ rep: Some(elts[idx - 1u]),
post: vec::slice(elts, idx + 1u, vec::len(elts))});
}
_ => ()
idx += 1u;
}
return match res {
- some(val) => val,
- none => {pre: elts, rep: none, post: ~[]}
+ Some(val) => val,
+ None => {pre: elts, rep: None, post: ~[]}
}
}
-fn option_flatten_map<T: copy, U: copy>(f: fn@(T) -> option<U>, v: ~[T]) ->
- option<~[U]> {
+fn option_flatten_map<T: copy, U: copy>(f: fn@(T) -> Option<U>, v: ~[T]) ->
+ Option<~[U]> {
let mut res = ~[];
for v.each |elem| {
match f(elem) {
- none => return none,
- some(fv) => vec::push(res, fv)
+ None => return None,
+ Some(fv) => vec::push(res, fv)
}
}
- return some(res);
+ return Some(res);
}
fn a_d_map(ad: arb_depth<matchable>, f: selector) -> match_result {
match ad {
leaf(x) => return f(x),
seq(ads, span) => match option_flatten_map(|x| a_d_map(x, f), *ads) {
- none => return none,
- some(ts) => return some(seq(@ts, span))
+ None => return None,
+ Some(ts) => return Some(seq(@ts, span))
}
}
}
fn compose_sels(s1: selector, s2: selector) -> selector {
fn scomp(s1: selector, s2: selector, m: matchable) -> match_result {
return match s1(m) {
- none => none,
- some(matches) => a_d_map(matches, s2)
+ None => None,
+ Some(matches) => a_d_map(matches, s2)
}
}
return { |x| scomp(s1, s2, x) };
//this oughta return binders instead, but macro args are a sequence of
//expressions, rather than a single expression
fn trivial_selector(m: matchable) -> match_result {
- return some(leaf(m));
+ return Some(leaf(m));
}
p_t_s_rec(cx, match_expr(e), trivial_selector, res);
return res;
bindings. Most of the work is done in p_t_s, which generates the
selectors. */
-fn use_selectors_to_bind(b: binders, e: @expr) -> option<bindings> {
+fn use_selectors_to_bind(b: binders, e: @expr) -> Option<bindings> {
let res = uint_hash::<arb_depth<matchable>>();
//need to do this first, to check vec lengths.
for b.literal_ast_matchers.each |sel| {
- match sel(match_expr(e)) { none => return none, _ => () }
+ match sel(match_expr(e)) { None => return None, _ => () }
}
let mut never_mind: bool = false;
for b.real_binders.each |key, val| {
match val(match_expr(e)) {
- none => never_mind = true,
- some(mtc) => { res.insert(key, mtc); }
+ None => never_mind = true,
+ Some(mtc) => { res.insert(key, mtc); }
}
};
//HACK: `ret` doesn't work in `for each`
- if never_mind { return none; }
- return some(res);
+ if never_mind { return None; }
+ return Some(res);
}
/* use the bindings on the body to generate the expanded code */
return res;
}
-fn follow_for_trans(cx: ext_ctxt, mmaybe: option<arb_depth<matchable>>,
- idx_path: @mut ~[uint]) -> option<matchable> {
+fn follow_for_trans(cx: ext_ctxt, mmaybe: Option<arb_depth<matchable>>,
+ idx_path: @mut ~[uint]) -> Option<matchable> {
match mmaybe {
- none => return none,
- some(m) => {
+ None => return None,
+ Some(m) => {
return match follow(m, *idx_path) {
seq(_, sp) => {
cx.span_fatal(sp,
~"syntax matched under ... but not " +
~"used that way.")
}
- leaf(m) => return some(m)
+ leaf(m) => return Some(m)
}
}
}
{pre: pre, rep: repeat_me_maybe, post: post} => {
let mut res = vec::map(pre, recur);
match repeat_me_maybe {
- none => (),
- some(repeat_me) => {
- let mut repeat: option<{rep_count: uint, name: ident}> = none;
+ None => (),
+ Some(repeat_me) => {
+ let mut repeat: Option<{rep_count: uint, name: ident}> = None;
/* we need to walk over all the free vars in lockstep, except for
the leaves, which are just duplicated */
do free_vars(b, repeat_me) |fv| {
leaf(_) => (),
seq(ms, _) => {
match repeat {
- none => {
- repeat = some({rep_count: vec::len(*ms), name: fv});
+ None => {
+ repeat = Some({rep_count: vec::len(*ms), name: fv});
}
- some({rep_count: old_len, name: old_name}) => {
+ Some({rep_count: old_len, name: old_name}) => {
let len = vec::len(*ms);
if old_len != len {
let msg = wrong_occurs(cx, fv, len,
}
};
match repeat {
- none => {
+ None => {
cx.span_fatal(repeat_me.span,
~"'...' surrounds an expression without any" +
~" repeating syntax variables");
}
- some({rep_count: rc, _}) => {
+ Some({rep_count: rc, _}) => {
/* Whew, we now know how how many times to repeat */
let mut idx: uint = 0u;
while idx < rc {
fn transcribe_ident(cx: ext_ctxt, b: bindings, idx_path: @mut ~[uint],
&&i: ident, _fld: ast_fold) -> ident {
return match 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"),
- none => i
+ Some(match_ident(a_id)) => a_id.node,
+ Some(m) => match_error(cx, m, ~"an identifier"),
+ None => i
}
}
// Don't substitute into qualified names.
if vec::len(p.types) > 0u || vec::len(p.idents) != 1u { return p; }
match follow_for_trans(cx, b.find(p.idents[0]), idx_path) {
- some(match_ident(id)) => {
+ Some(match_ident(id)) => {
{span: id.span, global: false, idents: ~[id.node],
- rp: none, types: ~[]}
+ rp: None, types: ~[]}
}
- some(match_path(a_pth)) => *a_pth,
- some(m) => match_error(cx, m, ~"a path"),
- none => p
+ Some(match_path(a_pth)) => *a_pth,
+ Some(m) => match_error(cx, m, ~"a path"),
+ None => p
}
}
(e, s);
}
match follow_for_trans(cx, b.find(p.idents[0]), idx_path) {
- some(match_ident(id)) => {
+ Some(match_ident(id)) => {
(expr_path(@{span: id.span,
global: false,
idents: ~[id.node],
- rp: none,
+ rp: None,
types: ~[]}), id.span)
}
- some(match_path(a_pth)) => (expr_path(a_pth), s),
- some(match_expr(a_exp)) => (a_exp.node, a_exp.span),
- some(m) => match_error(cx, m, ~"an expression"),
- none => orig(e, s, fld)
+ Some(match_path(a_pth)) => (expr_path(a_pth), s),
+ Some(match_expr(a_exp)) => (a_exp.node, a_exp.span),
+ Some(m) => match_error(cx, m, ~"an expression"),
+ None => orig(e, s, fld)
}
}
_ => orig(e, s, fld)
return match t {
ast::ty_path(pth, _) => {
match path_to_ident(pth) {
- some(id) => {
+ Some(id) => {
match follow_for_trans(cx, b.find(id), idx_path) {
- some(match_ty(ty)) => (ty.node, ty.span),
- some(m) => match_error(cx, m, ~"a type"),
- none => orig(t, s, fld)
+ Some(match_ty(ty)) => (ty.node, ty.span),
+ Some(m) => match_error(cx, m, ~"a type"),
+ None => orig(t, s, fld)
}
}
- none => orig(t, s, fld)
+ None => orig(t, s, fld)
}
}
_ => orig(t, s, fld)
-> (blk_, span)
{
return match block_to_ident(blk) {
- some(id) => {
+ Some(id) => {
match follow_for_trans(cx, b.find(id), idx_path) {
- some(match_block(new_blk)) => (new_blk.node, new_blk.span),
+ Some(match_block(new_blk)) => (new_blk.node, new_blk.span),
// possibly allow promotion of ident/path/expr to blocks?
- some(m) => match_error(cx, m, ~"a block"),
- none => orig(blk, s, fld)
+ Some(m) => match_error(cx, m, ~"a block"),
+ None => orig(blk, s, fld)
}
}
- none => orig(blk, s, fld)
+ None => orig(blk, s, fld)
}
}
expr_path(p_pth) => p_t_s_r_path(cx, p_pth, s, b),
expr_vec(p_elts, _) => {
match elts_to_ell(cx, p_elts) {
- {pre: pre, rep: some(repeat_me), post: post} => {
+ {pre: pre, rep: Some(repeat_me), post: post} => {
p_t_s_r_length(cx, vec::len(pre) + vec::len(post), true, s,
b);
if vec::len(pre) > 0u {
~"matching after `...` not yet supported");
}
}
- {pre: pre, rep: none, post: post} => {
+ {pre: pre, rep: None, post: post} => {
if post != ~[] {
cx.bug(~"elts_to_ell provided an invalid result");
}
match_result {
return match m {
match_expr(e) => {
- if e == pat { some(leaf(match_exact)) } else { none }
+ if e == pat { Some(leaf(match_exact)) } else { None }
}
_ => cx.bug(~"broken traversal in p_t_s_r")
}
match e.node {
expr_path(pth) => {
match path_to_ident(pth) {
- some(id) => match_ident(respan(pth.span, id)),
- none => match_path(pth)
+ Some(id) => match_ident(respan(pth.span, id)),
+ None => match_path(pth)
}
}
_ => m
/* pattern_to_selectors helper functions */
fn p_t_s_r_path(cx: ext_ctxt, p: @path, s: selector, b: binders) {
match path_to_ident(p) {
- some(p_id) => {
+ Some(p_id) => {
fn select(cx: ext_ctxt, m: matchable) -> match_result {
return match m {
- match_expr(e) => some(leaf(specialize_match(m))),
+ match_expr(e) => Some(leaf(specialize_match(m))),
_ => cx.bug(~"broken traversal in p_t_s_r")
}
}
}
b.real_binders.insert(p_id, compose_sels(s, |x| select(cx, x)));
}
- none => ()
+ None => ()
}
}
-fn block_to_ident(blk: blk_) -> option<ident> {
- if vec::len(blk.stmts) != 0u { return none; }
+fn block_to_ident(blk: blk_) -> Option<ident> {
+ if vec::len(blk.stmts) != 0u { return None; }
return match blk.expr {
- some(expr) => match expr.node {
+ Some(expr) => match expr.node {
expr_path(pth) => path_to_ident(pth),
- _ => none
+ _ => None
},
- none => none
+ None => None
}
}
return match m {
match_expr(e) => match e.node {
expr_mac(mac) => fn_m(mac),
- _ => none
+ _ => None
},
_ => cx.bug(~"broken traversal in p_t_s_r")
}
// using repeat_me.span is a little wacky, but the
// error we want to report is one in the macro def
- some(seq(@elts, repeat_me.span))
+ Some(seq(@elts, repeat_me.span))
}
- _ => none
+ _ => None
}
}
_ => cx.bug(~"broken traversal in p_t_s_r")
expr_vec(arg_elts, _) => {
let actual_len = vec::len(arg_elts);
if at_least && actual_len >= len || actual_len == len {
- some(leaf(match_exact))
- } else { none }
+ Some(leaf(match_exact))
+ } else { None }
}
- _ => none
+ _ => None
}
}
- _ => none
+ _ => None
}
}
b.literal_ast_matchers.push(
match_expr(e) => {
match e.node {
expr_vec(arg_elts, _) => {
- some(leaf(match_expr(arg_elts[idx])))
+ Some(leaf(match_expr(arg_elts[idx])))
}
- _ => none
+ _ => None
}
}
_ => cx.bug(~"broken traversal in p_t_s_r")
_body: ast::mac_body) -> base::macro_def {
let args = get_mac_args_no_max(cx, sp, arg, 0u, ~"macro");
- let mut macro_name: option<~str> = none;
+ let mut macro_name: Option<~str> = None;
let mut clauses: ~[@clause] = ~[];
for args.each |arg| {
match arg.node {
match mac.node {
mac_invoc(pth, invoc_arg, body) => {
match path_to_ident(pth) {
- some(id) => {
+ Some(id) => {
let id_str = cx.str_of(id);
match macro_name {
- none => macro_name = some(id_str),
- some(other_id) => if id_str != other_id {
+ None => macro_name = Some(id_str),
+ Some(other_id) => if id_str != other_id {
cx.span_fatal(pth.span,
~"macro name must be " +
~"consistent");
}
}
},
- none => cx.span_fatal(pth.span,
+ None => cx.span_fatal(pth.span,
~"macro name must not be a path")
}
let arg = match invoc_arg {
- some(arg) => arg,
- none => cx.span_fatal(mac.span,
+ Some(arg) => arg,
+ None => cx.span_fatal(mac.span,
~"macro must have arguments")
};
vec::push(clauses,
return {name:
match macro_name {
- some(id) => id,
- none => cx.span_fatal(sp, ~"macro definition must have " +
+ Some(id) => id,
+ None => cx.span_fatal(sp, ~"macro definition must have " +
~"at least one clause")
},
- ext: normal({expander: ext, span: some(option::get(arg).span)})};
+ ext: normal({expander: ext, span: Some(option::get(arg).span)})};
fn generic_extension(cx: ext_ctxt, sp: span, arg: ast::mac_arg,
_body: ast::mac_body,
clauses: ~[@clause]) -> @expr {
let arg = match arg {
- some(arg) => arg,
- none => cx.span_fatal(sp, ~"macro must have arguments")
+ Some(arg) => arg,
+ None => cx.span_fatal(sp, ~"macro must have arguments")
};
for clauses.each |c| {
match use_selectors_to_bind(c.params, arg) {
- some(bindings) => return transcribe(cx, bindings, c.body),
- none => again
+ Some(bindings) => return transcribe(cx, bindings, c.body),
+ None => again
}
}
cx.span_fatal(sp, ~"no clauses match macro invocation");
/* line!(): expands to the current line number */
fn expand_line(cx: ext_ctxt, sp: span, arg: ast::mac_arg,
_body: ast::mac_body) -> @ast::expr {
- get_mac_args(cx, sp, arg, 0u, option::some(0u), ~"line");
+ get_mac_args(cx, sp, arg, 0u, option::Some(0u), ~"line");
let loc = codemap::lookup_char_pos(cx.codemap(), sp.lo);
return mk_uint(cx, sp, loc.line);
}
/* col!(): expands to the current column number */
fn expand_col(cx: ext_ctxt, sp: span, arg: ast::mac_arg,
_body: ast::mac_body) -> @ast::expr {
- get_mac_args(cx, sp, arg, 0u, option::some(0u), ~"col");
+ get_mac_args(cx, sp, arg, 0u, option::Some(0u), ~"col");
let loc = codemap::lookup_char_pos(cx.codemap(), sp.lo);
return mk_uint(cx, sp, loc.col);
}
* out if we wanted. */
fn expand_file(cx: ext_ctxt, sp: span, arg: ast::mac_arg,
_body: ast::mac_body) -> @ast::expr {
- get_mac_args(cx, sp, arg, 0u, option::some(0u), ~"file");
+ get_mac_args(cx, sp, arg, 0u, option::Some(0u), ~"file");
let { file: @{ name: filename, _ }, _ } =
codemap::lookup_char_pos(cx.codemap(), sp.lo);
return mk_uniq_str(cx, sp, filename);
fn expand_stringify(cx: ext_ctxt, sp: span, arg: ast::mac_arg,
_body: ast::mac_body) -> @ast::expr {
- let args = get_mac_args(cx, sp, arg, 1u, option::some(1u), ~"stringify");
+ let args = get_mac_args(cx, sp, arg, 1u, option::Some(1u), ~"stringify");
let s = pprust::expr_to_str(args[0], cx.parse_sess().interner);
return mk_uniq_str(cx, sp, s);
}
fn expand_mod(cx: ext_ctxt, sp: span, arg: ast::mac_arg, _body: ast::mac_body)
-> @ast::expr {
- get_mac_args(cx, sp, arg, 0u, option::some(0u), ~"file");
+ get_mac_args(cx, sp, arg, 0u, option::Some(0u), ~"file");
return mk_uniq_str(cx, sp,
str::connect(cx.mod_path().map(|x| cx.str_of(x)), ~"::"));
}
fn expand_include(cx: ext_ctxt, sp: span, arg: ast::mac_arg,
_body: ast::mac_body) -> @ast::expr {
- let args = get_mac_args(cx, sp, arg, 1u, option::some(1u), ~"include");
+ let args = get_mac_args(cx, sp, arg, 1u, option::Some(1u), ~"include");
let file = expr_to_str(cx, args[0], ~"#include_str requires a string");
let p = parse::new_parser_from_file(cx.parse_sess(), cx.cfg(),
&res_rel_file(cx, sp, &Path(file)),
fn expand_include_str(cx: ext_ctxt, sp: codemap::span, arg: ast::mac_arg,
_body: ast::mac_body) -> @ast::expr {
- let args = get_mac_args(cx,sp,arg,1u,option::some(1u),~"include_str");
+ let args = get_mac_args(cx,sp,arg,1u,option::Some(1u),~"include_str");
let file = expr_to_str(cx, args[0], ~"#include_str requires a string");
fn expand_include_bin(cx: ext_ctxt, sp: codemap::span, arg: ast::mac_arg,
_body: ast::mac_body) -> @ast::expr {
- let args = get_mac_args(cx,sp,arg,1u,option::some(1u),~"include_bin");
+ let args = get_mac_args(cx,sp,arg,1u,option::Some(1u),~"include_bin");
let file = expr_to_str(cx, args[0], ~"#include_bin requires a string");
let sess = cx.parse_sess();
let cfg = cx.cfg();
let tt_rdr = new_tt_reader(cx.parse_sess().span_diagnostic,
- cx.parse_sess().interner, none, tt);
+ cx.parse_sess().interner, None, tt);
let rdr = tt_rdr as reader;
let rust_parser = parser(sess, cfg, rdr.dup(), SOURCE_FILE);
nonempty body. */
enum matcher_pos_up { /* to break a circularity */
- matcher_pos_up(option<matcher_pos>)
+ matcher_pos_up(Option<matcher_pos>)
}
fn is_some(&&mpu: matcher_pos_up) -> bool {
match mpu {
- matcher_pos_up(none) => false,
+ matcher_pos_up(None) => false,
_ => true
}
}
type matcher_pos = ~{
elts: ~[ast::matcher], // maybe should be /&? Need to understand regions.
- sep: option<token>,
+ sep: Option<token>,
mut idx: uint,
mut up: matcher_pos_up, // mutable for swapping only
matches: ~[DVec<@named_match>],
fn copy_up(&& mpu: matcher_pos_up) -> matcher_pos {
match mpu {
- matcher_pos_up(some(mp)) => copy mp,
+ matcher_pos_up(Some(mp)) => copy mp,
_ => fail
}
}
}
#[allow(non_implicitly_copyable_typarams)]
-fn initial_matcher_pos(ms: ~[matcher], sep: option<token>, lo: uint)
+fn initial_matcher_pos(ms: ~[matcher], sep: Option<token>, lo: uint)
-> matcher_pos {
let mut match_idx_hi = 0u;
for ms.each() |elt| {
}
}
}
- ~{elts: ms, sep: sep, mut idx: 0u, mut up: matcher_pos_up(none),
+ ~{elts: ms, sep: sep, mut idx: 0u, mut up: matcher_pos_up(None),
matches: copy vec::from_fn(count_names(ms), |_i| dvec::dvec()),
match_lo: 0u, match_hi: match_idx_hi, sp_lo: lo}
}
fn parse(sess: parse_sess, cfg: ast::crate_cfg, rdr: reader, ms: ~[matcher])
-> parse_result {
let mut cur_eis = ~[];
- vec::push(cur_eis, initial_matcher_pos(ms, none, rdr.peek().sp.lo));
+ vec::push(cur_eis, initial_matcher_pos(ms, None, rdr.peek().sp.lo));
loop {
let mut bb_eis = ~[]; // black-box parsed by parser.rs
// the *_t vars are workarounds for the lack of unary move
match copy ei.sep {
- some(t) if idx == len => { // we need a separator
+ Some(t) if idx == len => { // we need a separator
if tok == t { //pass the separator
let ei_t <- ei;
ei_t.idx += 1u;
let ei_t <- ei;
vec::push(cur_eis, ~{
elts: matchers, sep: sep, mut idx: 0u,
- mut up: matcher_pos_up(some(ei_t)),
+ mut up: matcher_pos_up(Some(ei_t)),
matches: matches,
match_lo: match_idx_lo, match_hi: match_idx_hi,
sp_lo: sp.lo
fn parse_nt(p: parser, name: ~str) -> nonterminal {
match name {
~"item" => match p.parse_item(~[]) {
- some(i) => token::nt_item(i),
- none => p.fatal(~"expected an item keyword")
+ Some(i) => token::nt_item(i),
+ None => p.fatal(~"expected an item keyword")
},
~"block" => token::nt_block(p.parse_block()),
~"stmt" => token::nt_stmt(p.parse_stmt(~[])),
arg: ~[ast::token_tree]) -> base::mac_result {
// these spans won't matter, anyways
fn ms(m: matcher_) -> matcher {
- {node: m, span: {lo: 0u, hi: 0u, expn_info: none}}
+ {node: m, span: {lo: 0u, hi: 0u, expn_info: None}}
}
let lhs_nm = cx.parse_sess().interner.gensym(@~"lhs");
ms(match_nonterminal(lhs_nm, special_idents::matchers, 0u)),
ms(match_tok(FAT_ARROW)),
ms(match_nonterminal(rhs_nm, special_idents::tt, 1u)),
- ], some(SEMI), false, 0u, 2u)),
+ ], Some(SEMI), false, 0u, 2u)),
//to phase into semicolon-termination instead of
//semicolon-separation
- ms(match_seq(~[ms(match_tok(SEMI))], none, true, 2u, 2u))];
+ ms(match_seq(~[ms(match_tok(SEMI))], None, true, 2u, 2u))];
// Parse the macro_rules! invocation (`none` is for no interpolations):
let arg_reader = new_tt_reader(cx.parse_sess().span_diagnostic,
- cx.parse_sess().interner, none, arg);
+ cx.parse_sess().interner, None, arg);
let argument_map = parse_or_else(cx.parse_sess(), cx.cfg(),
arg_reader as reader, argument_gram);
}
// Which arm's failure should we report? (the one furthest along)
- let mut best_fail_spot = {lo: 0u, hi: 0u, expn_info: none};
+ let mut best_fail_spot = {lo: 0u, hi: 0u, expn_info: None};
let mut best_fail_msg = ~"internal error: ran no matchers";
let s_d = cx.parse_sess().span_diagnostic;
match lhs {
@matched_nonterminal(nt_matchers(mtcs)) => {
// `none` is because we're not interpolating
- let arg_rdr = new_tt_reader(s_d, itr, none, arg) as reader;
+ let arg_rdr = new_tt_reader(s_d, itr, None, arg) as reader;
match parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtcs) {
success(named_matches) => {
let rhs = match rhses[i] {
_ => cx.span_bug(sp, ~"bad thing in rhs")
};
// rhs has holes ( `$id` and `$(...)` that need filled)
- let trncbr = new_tt_reader(s_d, itr, some(named_matches),
+ let trncbr = new_tt_reader(s_d, itr, Some(named_matches),
~[rhs]);
let p = parser(cx.parse_sess(), cx.cfg(),
trncbr as reader, SOURCE_FILE);
return mr_def({
name: *cx.parse_sess().interner.get(name),
- ext: expr_tt({expander: exp, span: some(sp)})
+ ext: expr_tt({expander: exp, span: Some(sp)})
});
}
\ No newline at end of file
export tt_reader, new_tt_reader, dup_tt_reader, tt_next_token;
enum tt_frame_up { /* to break a circularity */
- tt_frame_up(option<tt_frame>)
+ tt_frame_up(Option<tt_frame>)
}
/* FIXME #2811: figure out how to have a uniquely linked stack, and change to
readme: ~[ast::token_tree],
mut idx: uint,
dotdotdoted: bool,
- sep: option<token>,
+ sep: Option<token>,
up: tt_frame_up,
};
* `src` contains no `tt_seq`s and `tt_nonterminal`s, `interp` can (and
* should) be none. */
fn new_tt_reader(sp_diag: span_handler, itr: ident_interner,
- interp: option<std::map::hashmap<ident,@named_match>>,
+ interp: Option<std::map::hashmap<ident,@named_match>>,
src: ~[ast::token_tree])
-> tt_reader {
let r = @{sp_diag: sp_diag, interner: itr,
mut cur: @{readme: src, mut idx: 0u, dotdotdoted: false,
- sep: none, up: tt_frame_up(option::none)},
+ sep: None, up: tt_frame_up(option::None)},
interpolations: match interp { /* just a convienience */
- none => std::map::uint_hash::<@named_match>(),
- some(x) => x
+ None => std::map::uint_hash::<@named_match>(),
+ Some(x) => x
},
mut repeat_idx: ~[mut], mut repeat_len: ~[],
/* dummy values, never read: */
pure fn dup_tt_frame(&&f: tt_frame) -> tt_frame {
@{readme: f.readme, mut idx: f.idx, dotdotdoted: f.dotdotdoted,
sep: f.sep, up: match f.up {
- tt_frame_up(some(up_frame)) => {
- tt_frame_up(some(dup_tt_frame(up_frame)))
+ tt_frame_up(Some(up_frame)) => {
+ tt_frame_up(Some(dup_tt_frame(up_frame)))
}
tt_frame_up(none) => tt_frame_up(none)
}
|| r.repeat_idx.last() == r.repeat_len.last() - 1 {
match r.cur.up {
- tt_frame_up(none) => {
+ tt_frame_up(None) => {
r.cur_tok = EOF;
return ret_val;
}
- tt_frame_up(some(tt_f)) => {
+ tt_frame_up(Some(tt_f)) => {
if r.cur.dotdotdoted {
vec::pop(r.repeat_idx); vec::pop(r.repeat_len);
}
r.cur.idx = 0u;
r.repeat_idx[r.repeat_idx.len() - 1u] += 1u;
match r.cur.sep {
- some(tk) => {
+ Some(tk) => {
r.cur_tok = tk; /* repeat same span, I guess */
return ret_val;
}
- none => ()
+ None => ()
}
}
}
match r.cur.readme[r.cur.idx] {
tt_delim(tts) => {
r.cur = @{readme: tts, mut idx: 0u, dotdotdoted: false,
- sep: none, up: tt_frame_up(option::some(r.cur)) };
+ sep: None, up: tt_frame_up(option::Some(r.cur)) };
// if this could be 0-length, we'd need to potentially recur here
}
tt_tok(sp, tok) => {
vec::push(r.repeat_len, len);
vec::push(r.repeat_idx, 0u);
r.cur = @{readme: tts, mut idx: 0u, dotdotdoted: true,
- sep: sep, up: tt_frame_up(option::some(r.cur))};
+ sep: sep, up: tt_frame_up(option::Some(r.cur))};
}
}
}
fn fold_crate_directive(&&@crate_directive) -> @crate_directive;
fn fold_view_item(&&@view_item) -> @view_item;
fn fold_foreign_item(&&@foreign_item) -> @foreign_item;
- fn fold_item(&&@item) -> option<@item>;
+ fn fold_item(&&@item) -> Option<@item>;
fn fold_struct_field(&&@struct_field) -> @struct_field;
fn fold_item_underscore(item_) -> item_;
fn fold_method(&&@method) -> @method;
ast_fold) -> (crate_directive_, span),
fold_view_item: fn@(view_item_, ast_fold) -> view_item_,
fold_foreign_item: fn@(&&@foreign_item, ast_fold) -> @foreign_item,
- fold_item: fn@(&&@item, ast_fold) -> option<@item>,
+ fold_item: fn@(&&@item, ast_fold) -> Option<@item>,
fold_struct_field: fn@(&&@struct_field, ast_fold) -> @struct_field,
fold_item_underscore: fn@(item_, ast_fold) -> item_,
fold_method: fn@(&&@method, ast_fold) -> @method,
span: fld.new_span(ni.span)};
}
-fn noop_fold_item(&&i: @item, fld: ast_fold) -> option<@item> {
+fn noop_fold_item(&&i: @item, fld: ast_fold) -> Option<@item> {
let fold_attribute = |x| fold_attribute_(x, fld);
- return some(@{ident: fld.fold_ident(i.ident),
+ return Some(@{ident: fld.fold_ident(i.ident),
attrs: vec::map(i.attrs, fold_attribute),
id: fld.new_id(i.id),
node: fld.fold_item_underscore(i.node),
-> @ast::struct_def {
let resulting_optional_constructor;
match struct_def.ctor {
- none => {
- resulting_optional_constructor = none;
+ None => {
+ resulting_optional_constructor = None;
}
- some(constructor) => {
- resulting_optional_constructor = some({
+ Some(constructor) => {
+ resulting_optional_constructor = Some({
node: {
body: fld.fold_block(constructor.node.body),
dec: fold_fn_decl(constructor.node.dec, fld),
match d {
decl_local(ls) => decl_local(vec::map(ls, |x| fld.fold_local(x))),
decl_item(it) => match fld.fold_item(it) {
- some(it_folded) => decl_item(it_folded),
- none => decl_local(~[])
+ Some(it_folded) => decl_item(it_folded),
+ None => decl_local(~[])
}
}
}
fields: vec::map(struct_def.fields,
|f| fld.fold_struct_field(f)),
methods: vec::map(struct_def.methods, |m| fld.fold_method(m)),
- ctor: none,
+ ctor: None,
dtor: dtor
})
}
let attrs = vec::map(v.attrs, fold_attribute);
let de = match v.disr_expr {
- some(e) => some(fld.fold_expr(e)),
- none => none
+ Some(e) => Some(fld.fold_expr(e)),
+ None => None
};
return {name: /* FIXME (#2543) */ copy v.name,
attrs: attrs,
pat: fld.fold_pat(l.pat),
init:
match l.init {
- option::none::<initializer> => l.init,
- option::some::<initializer>(init) => {
- option::some::<initializer>({op: init.op,
+ option::None::<initializer> => l.init,
+ option::Some::<initializer>(init) => {
+ option::Some::<initializer>({op: init.op,
expr: fld.fold_expr(init.expr)})
}
},
-> @foreign_item {
return self.fold_foreign_item(x, self as ast_fold);
}
- fn fold_item(&&i: @item) -> option<@item> {
+ fn fold_item(&&i: @item) -> Option<@item> {
return self.fold_item(i, self as ast_fold);
}
fn fold_struct_field(&&sf: @struct_field) -> @struct_field {
mut byte_pos: uint
};
-fn new_parse_sess(demitter: option<emitter>) -> parse_sess {
+fn new_parse_sess(demitter: Option<emitter>) -> parse_sess {
let cm = codemap::new_codemap();
return @{cm: cm,
mut next_id: 1,
fn parse_crate_from_file(input: &Path, cfg: ast::crate_cfg,
sess: parse_sess) -> @ast::crate {
- if input.filetype() == some(~"rc") {
+ if input.filetype() == Some(~"rc") {
parse_crate_from_crate_file(input, cfg, sess)
- } else if input.filetype() == some(~"rs") {
+ } else if input.filetype() == Some(~"rs") {
parse_crate_from_source_file(input, cfg, sess)
} else {
sess.span_diagnostic.handler().fatal(~"unknown input file type: " +
fn parse_item_from_source_str(name: ~str, source: @~str, cfg: ast::crate_cfg,
+attrs: ~[ast::attribute],
- sess: parse_sess) -> option<@ast::item> {
+ sess: parse_sess) -> Option<@ast::item> {
let (p, rdr) = new_parser_etc_from_source_str(sess, cfg, name,
codemap::fss_none, source);
let r = p.parse_item(attrs);
fn new_parser_from_tt(sess: parse_sess, cfg: ast::crate_cfg,
tt: ~[ast::token_tree]) -> parser {
let trdr = lexer::new_tt_reader(sess.span_diagnostic, sess.interner,
- none, tt);
+ None, tt);
return parser(sess, cfg, trdr as reader, parser::SOURCE_FILE)
}
// A type to distingush between the parsing of item attributes or syntax
// extensions, which both begin with token.POUND
-type attr_or_ext = option<Either<~[ast::attribute], @ast::expr>>;
+type attr_or_ext = Option<Either<~[ast::attribute], @ast::expr>>;
trait parser_attr {
fn parse_outer_attrs_or_ext(first_item_attrs: ~[ast::attribute])
self.bump();
let first_attr =
self.parse_attribute_naked(ast::attr_outer, lo);
- return some(Left(vec::append(~[first_attr],
+ return Some(Left(vec::append(~[first_attr],
self.parse_outer_attributes())));
} else if !(self.look_ahead(1u) == token::LT
|| self.look_ahead(1u) == token::LBRACKET
|| self.look_ahead(1u) == token::POUND
|| expect_item_next) {
self.bump();
- return some(Right(self.parse_syntax_ext_naked(lo)));
- } else { return none; }
+ return Some(Right(self.parse_syntax_ext_naked(lo)));
+ } else { return None; }
}
token::DOC_COMMENT(_) => {
- return some(Left(self.parse_outer_attributes()));
+ return Some(Left(self.parse_outer_attributes()));
}
- _ => return none
+ _ => return None
}
}
ends_in_lit_int(sub)
}
ast::expr_fail(osub) | ast::expr_ret(osub) => match osub {
- some(ex) => ends_in_lit_int(ex),
+ Some(ex) => ends_in_lit_int(ex),
_ => false
},
_ => false
}
// drop leftmost columns that contain only values in chars
- fn block_trim(lines: ~[~str], chars: ~str, max: option<uint>) -> ~[~str] {
+ fn block_trim(lines: ~[~str], chars: ~str, max: Option<uint>) -> ~[~str] {
let mut i = max.get_default(uint::max_value);
for lines.each |line| {
if comment.starts_with(~"/*") {
let lines = str::lines_any(comment.slice(3u, comment.len() - 2u));
let lines = vertical_trim(lines);
- let lines = block_trim(lines, ~"\t ", none);
- let lines = block_trim(lines, ~"*", some(1u));
- let lines = block_trim(lines, ~"\t ", none);
+ let lines = block_trim(lines, ~"\t ", None);
+ let lines = block_trim(lines, ~"*", Some(1u));
+ let lines = block_trim(lines, ~"\t ", None);
return str::connect(lines, ~"\n");
}
import lexer::reader;
type seq_sep = {
- sep: option<token::token>,
+ sep: Option<token::token>,
trailing_sep_allowed: bool
};
fn seq_sep_trailing_disallowed(t: token::token) -> seq_sep {
- return {sep: option::some(t), trailing_sep_allowed: false};
+ return {sep: option::Some(t), trailing_sep_allowed: false};
}
fn seq_sep_trailing_allowed(t: token::token) -> seq_sep {
- return {sep: option::some(t), trailing_sep_allowed: true};
+ return {sep: option::Some(t), trailing_sep_allowed: true};
}
fn seq_sep_none() -> seq_sep {
- return {sep: option::none, trailing_sep_allowed: false};
+ return {sep: option::None, trailing_sep_allowed: false};
}
fn token_to_str(reader: reader, ++token: token::token) -> ~str {
fn check_restricted_keywords();
fn check_restricted_keywords_(w: ~str);
fn expect_gt();
- fn parse_seq_to_before_gt<T: copy>(sep: option<token::token>,
+ fn parse_seq_to_before_gt<T: copy>(sep: Option<token::token>,
f: fn(parser) -> T) -> ~[T];
- fn parse_seq_to_gt<T: copy>(sep: option<token::token>,
+ fn parse_seq_to_gt<T: copy>(sep: Option<token::token>,
f: fn(parser) -> T) -> ~[T];
- fn parse_seq_lt_gt<T: copy>(sep: option<token::token>,
+ fn parse_seq_lt_gt<T: copy>(sep: Option<token::token>,
f: fn(parser) -> T) -> spanned<~[T]>;
fn parse_seq_to_end<T: copy>(ket: token::token, sep: seq_sep,
f: fn(parser) -> T) -> ~[T];
}
}
- fn parse_seq_to_before_gt<T: copy>(sep: option<token::token>,
+ fn parse_seq_to_before_gt<T: copy>(sep: Option<token::token>,
f: fn(parser) -> T) -> ~[T] {
let mut first = true;
let mut v = ~[];
while self.token != token::GT
&& self.token != token::BINOP(token::SHR) {
match sep {
- some(t) => {
+ Some(t) => {
if first { first = false; }
else { self.expect(t); }
}
return v;
}
- fn parse_seq_to_gt<T: copy>(sep: option<token::token>,
+ fn parse_seq_to_gt<T: copy>(sep: Option<token::token>,
f: fn(parser) -> T) -> ~[T] {
let v = self.parse_seq_to_before_gt(sep, f);
self.expect_gt();
return v;
}
- fn parse_seq_lt_gt<T: copy>(sep: option<token::token>,
+ fn parse_seq_lt_gt<T: copy>(sep: Option<token::token>,
f: fn(parser) -> T) -> spanned<~[T]> {
let lo = self.span.lo;
self.expect(token::LT);
let mut v: ~[T] = ~[];
while self.token != ket {
match sep.sep {
- some(t) => {
+ Some(t) => {
if first { first = false; }
else { self.expect(t); }
}
}
fn eval_crate_directives_to_mod(cx: ctx, cdirs: ~[@ast::crate_directive],
- prefix: &Path, suffix: &option<Path>)
+ prefix: &Path, suffix: &Option<Path>)
-> (ast::_mod, ~[ast::attribute]) {
let (cview_items, citems, cattrs)
= parse_companion_mod(cx, prefix, suffix);
We build the path to the companion mod by combining the prefix and the
optional suffix then adding the .rs extension.
*/
-fn parse_companion_mod(cx: ctx, prefix: &Path, suffix: &option<Path>)
+fn parse_companion_mod(cx: ctx, prefix: &Path, suffix: &Option<Path>)
-> (~[@ast::view_item], ~[@ast::item], ~[ast::attribute]) {
- fn companion_file(prefix: &Path, suffix: &option<Path>) -> Path {
+ fn companion_file(prefix: &Path, suffix: &Option<Path>) -> Path {
return match *suffix {
- option::some(s) => prefix.push_many(s.components),
- option::none => copy *prefix
+ option::Some(s) => prefix.push_many(s.components),
+ option::None => copy *prefix
}.with_filetype("rs");
}
fn cdir_path_opt(default: ~str, attrs: ~[ast::attribute]) -> ~str {
match ::attr::first_attr_value_str_by_name(attrs, ~"path") {
- some(d) => d,
- none => default
+ Some(d) => d,
+ None => default
}
}
prefix.push_many(path.components)
};
let (m0, a0) = eval_crate_directives_to_mod(
- cx, cdirs, &full_path, &none);
+ cx, cdirs, &full_path, &None);
let i =
@{ident: /* FIXME (#2543) */ copy id,
attrs: vec::append(attrs, a0),
// might return a sugared-doc-attr
fn consume_whitespace_and_comments(rdr: string_reader)
- -> option<{tok: token::token, sp: span}> {
+ -> Option<{tok: token::token, sp: span}> {
while is_whitespace(rdr.curr) { bump(rdr); }
return consume_any_line_comment(rdr);
}
// might return a sugared-doc-attr
fn consume_any_line_comment(rdr: string_reader)
- -> option<{tok: token::token, sp: span}> {
+ -> Option<{tok: token::token, sp: span}> {
if rdr.curr == '/' {
match nextch(rdr) {
'/' => {
str::push_char(acc, rdr.curr);
bump(rdr);
}
- return some({
+ return Some({
tok: token::DOC_COMMENT(rdr.interner.intern(@acc)),
sp: ast_util::mk_sp(start_chpos, rdr.chpos)
});
}
}
}
- return none;
+ return None;
}
// might return a sugared-doc-attr
fn consume_block_comment(rdr: string_reader)
- -> option<{tok: token::token, sp: span}> {
+ -> Option<{tok: token::token, sp: span}> {
// block comments starting with "/**" or "/*!" are doc-comments
if rdr.curr == '*' || rdr.curr == '!' {
acc += ~"*/";
bump(rdr);
bump(rdr);
- return some({
+ return Some({
tok: token::DOC_COMMENT(rdr.interner.intern(@acc)),
sp: ast_util::mk_sp(start_chpos, rdr.chpos)
});
return consume_whitespace_and_comments(rdr);
}
-fn scan_exponent(rdr: string_reader) -> option<~str> {
+fn scan_exponent(rdr: string_reader) -> Option<~str> {
let mut c = rdr.curr;
let mut rslt = ~"";
if c == 'e' || c == 'E' {
}
let exponent = scan_digits(rdr, 10u);
if str::len(exponent) > 0u {
- return some(rslt + exponent);
+ return Some(rslt + exponent);
} else { rdr.fatal(~"scan_exponent: bad fp literal"); }
- } else { return none::<~str>; }
+ } else { return None::<~str>; }
}
fn scan_digits(rdr: string_reader, radix: uint) -> ~str {
let c = rdr.curr;
if c == '_' { bump(rdr); again; }
match char::to_digit(c, radix) {
- some(_) => {
+ Some(_) => {
str::push_char(rslt, c);
bump(rdr);
}
num_str += ~"." + dec_part;
}
match scan_exponent(rdr) {
- some(s) => {
+ Some(s) => {
is_float = true;
num_str += s;
}
- none => ()
+ None => ()
}
if rdr.curr == 'f' {
bump(rdr);
members(~[@class_member]) }
type arg_or_capture_item = Either<arg, capture_item>;
-type item_info = (ident, item_, option<~[attribute]>);
+type item_info = (ident, item_, Option<~[attribute]>);
enum item_or_view_item {
iovi_none,
INTERPOLATED(token::$constructor(x)) => { $p.bump(); return *x; }
_ => ()
}} ;
- (some $p:expr, $constructor:ident) => { match copy $p.token {
- INTERPOLATED(token::$constructor(x)) => { $p.bump(); return some(x); }
+ (Some $p:expr, $constructor:ident) => { match copy $p.token {
+ INTERPOLATED(token::$constructor(x)) => { $p.bump(); return Some(x); }
_ => ()
}} ;
(iovi $p:expr, $constructor:ident) => { match copy $p.token {
)
-pure fn maybe_append(+lhs: ~[attribute], rhs: option<~[attribute]>)
+pure fn maybe_append(+lhs: ~[attribute], rhs: Option<~[attribute]>)
-> ~[attribute] {
match rhs {
- none => lhs,
- some(attrs) => vec::append(lhs, attrs)
+ None => lhs,
+ Some(attrs) => vec::append(lhs, attrs)
}
}
}
}
- fn region_from_name(s: option<ident>) -> @region {
+ fn region_from_name(s: Option<ident>) -> @region {
let r = match s {
- some (id) => re_named(id),
- none => re_anon
+ Some (id) => re_named(id),
+ None => re_anon
};
@{id: self.get_id(), node: r}
match copy self.token {
token::IDENT(sid, _) => {
self.bump();
- self.region_from_name(some(sid))
+ self.region_from_name(Some(sid))
}
_ => {
- self.region_from_name(none)
+ self.region_from_name(None)
}
}
}
token::IDENT(sid, _) => {
if self.look_ahead(1u) == token::BINOP(token::SLASH) {
self.bump(); self.bump();
- some(sid)
+ Some(sid)
} else {
- none
+ None
}
}
- _ => { none }
+ _ => { None }
};
self.region_from_name(name)
}
let lo = self.span.lo;
match self.maybe_parse_dollar_mac() {
- some(e) => {
+ Some(e) => {
return @{id: self.get_id(),
node: ty_mac(spanned(lo, self.span.hi, e)),
span: mk_sp(lo, self.span.hi)};
}
- none => ()
+ None => ()
}
let t = if self.token == token::LPAREN {
// Parse the `* 3` in `[ int * 3 ]`
match self.maybe_parse_fixed_vstore_with_star() {
- none => {}
- some(suffix) => {
+ None => {}
+ Some(suffix) => {
t = ty_fixed_length(@{
id: self.get_id(),
node: t,
return @{id: self.get_id(),
node: match self.maybe_parse_fixed_vstore() {
// Consider a fixed vstore suffix (/N or /_)
- none => t,
- some(v) => {
+ None => t,
+ Some(v) => {
ty_fixed_length(@{id: self.get_id(), node:t, span: sp}, v)
} },
span: sp}
}
}
- fn maybe_parse_dollar_mac() -> option<mac_> {
+ fn maybe_parse_dollar_mac() -> Option<mac_> {
match copy self.token {
token::DOLLAR => {
let lo = self.span.lo;
match copy self.token {
token::LIT_INT_UNSUFFIXED(num) => {
self.bump();
- some(mac_var(num as uint))
+ Some(mac_var(num as uint))
}
token::LPAREN => {
self.bump();
let e = self.parse_expr();
self.expect(token::RPAREN);
let hi = self.last_span.hi;
- some(mac_aq(mk_sp(lo,hi), e))
+ Some(mac_aq(mk_sp(lo,hi), e))
}
_ => {
self.fatal(~"expected `(` or unsuffixed integer literal");
}
}
}
- _ => none
+ _ => None
}
}
- fn maybe_parse_fixed_vstore() -> option<option<uint>> {
+ fn maybe_parse_fixed_vstore() -> Option<Option<uint>> {
if self.token == token::BINOP(token::SLASH) {
self.bump();
match copy self.token {
token::UNDERSCORE => {
- self.bump(); some(none)
+ self.bump(); Some(None)
}
token::LIT_INT_UNSUFFIXED(i) if i >= 0i64 => {
- self.bump(); some(some(i as uint))
+ self.bump(); Some(Some(i as uint))
}
- _ => none
+ _ => None
}
} else {
- none
+ None
}
}
- fn maybe_parse_fixed_vstore_with_star() -> option<option<uint>> {
+ fn maybe_parse_fixed_vstore_with_star() -> Option<Option<uint>> {
if self.eat(token::BINOP(token::STAR)) {
match copy self.token {
token::UNDERSCORE => {
- self.bump(); some(none)
+ self.bump(); Some(None)
}
token::LIT_INT_UNSUFFIXED(i) if i >= 0i64 => {
- self.bump(); some(some(i as uint))
+ self.bump(); Some(Some(i as uint))
}
- _ => none
+ _ => None
}
} else {
- none
+ None
}
}
}
}
@{span: mk_sp(lo, self.last_span.hi), global: global,
- idents: ids, rp: none, types: ~[]}
+ idents: ids, rp: None, types: ~[]}
}
fn parse_value_path() -> @path {
&& self.look_ahead(1u) == token::BINOP(token::AND) {
self.expect(token::BINOP(token::SLASH));
- some(self.parse_region())
+ Some(self.parse_region())
} else {
- none
+ None
}
};
// Parse any type parameters which may appear:
let tps = {
if self.token == token::LT {
- self.parse_seq_lt_gt(some(token::COMMA),
+ self.parse_seq_lt_gt(Some(token::COMMA),
|p| p.parse_ty(false))
} else {
{node: ~[], span: path.span}
let mut ex: expr_;
match self.maybe_parse_dollar_mac() {
- some(x) => return pexpr(self.mk_mac_expr(lo, self.span.hi, x)),
+ Some(x) => return pexpr(self.mk_mac_expr(lo, self.span.hi, x)),
_ => ()
}
if can_begin_expr(self.token) {
let e = self.parse_expr();
hi = e.span.hi;
- ex = expr_fail(some(e));
- } else { ex = expr_fail(none); }
+ ex = expr_fail(Some(e));
+ } else { ex = expr_fail(None); }
} else if self.eat_keyword(~"log") {
self.expect(token::LPAREN);
let lvl = self.parse_expr();
if can_begin_expr(self.token) {
let e = self.parse_expr();
hi = e.span.hi;
- ex = expr_ret(some(e));
- } else { ex = expr_ret(none); }
+ ex = expr_ret(Some(e));
+ } else { ex = expr_ret(None); }
} else if self.eat_keyword(~"break") {
if is_ident(self.token) {
- ex = expr_break(some(self.parse_ident()));
+ ex = expr_break(Some(self.parse_ident()));
} else {
- ex = expr_break(none);
+ ex = expr_break(None);
}
hi = self.span.hi;
} else if self.eat_keyword(~"again") {
if is_ident(self.token) {
- ex = expr_again(some(self.parse_ident()));
+ ex = expr_again(Some(self.parse_ident()));
} else {
- ex = expr_again(none);
+ ex = expr_again(None);
}
hi = self.span.hi;
} else if self.eat_keyword(~"copy") {
let base;
if self.eat_keyword(~"with") || self.eat(token::DOTDOT) {
- base = some(self.parse_expr());
+ base = Some(self.parse_expr());
} else {
- base = none;
+ base = None;
}
hi = pth.span.hi;
match ex {
expr_lit(@{node: lit_str(_), span: _}) |
expr_vec(_, _) => match self.maybe_parse_fixed_vstore() {
- none => (),
- some(v) => {
+ None => (),
+ Some(v) => {
hi = self.span.hi;
ex = expr_vstore(self.mk_expr(lo, hi, ex), vstore_fixed(v));
}
let pth = self.parse_path_without_tps();
//temporary for a backwards-compatible cycle:
let sep = seq_sep_trailing_disallowed(token::COMMA);
- let mut e = none;
+ let mut e = None;
if (self.token == token::LPAREN || self.token == token::LBRACKET) {
let lo = self.span.lo;
let es =
sep, |p| p.parse_expr())
};
let hi = self.span.hi;
- e = some(self.mk_expr(lo, hi, expr_vec(es, m_imm)));
+ e = Some(self.mk_expr(lo, hi, expr_vec(es, m_imm)));
}
- let mut b = none;
+ let mut b = None;
if self.token == token::LBRACE {
self.bump();
let lo = self.span.lo;
self.bump();
}
let hi = self.last_span.lo;
- b = some({span: mk_sp(lo,hi)});
+ b = Some({span: mk_sp(lo,hi)});
}
return self.mk_mac_expr(lo, self.span.hi, mac_invoc(pth, e, b));
}
self.bump();
let tys = if self.eat(token::MOD_SEP) {
self.expect(token::LT);
- self.parse_seq_to_gt(some(token::COMMA),
+ self.parse_seq_to_gt(Some(token::COMMA),
|p| p.parse_ty(false))
} else { ~[] };
e = self.mk_pexpr(lo, hi, expr_field(self.to_expr(e), i,
return e;
}
- fn parse_sep_and_zerok() -> (option<token::token>, bool) {
+ fn parse_sep_and_zerok() -> (Option<token::token>, bool) {
if self.token == token::BINOP(token::STAR)
|| self.token == token::BINOP(token::PLUS) {
let zerok = self.token == token::BINOP(token::STAR);
self.bump();
- return (none, zerok);
+ return (None, zerok);
} else {
let sep = self.token;
self.bump();
|| self.token == token::BINOP(token::PLUS) {
let zerok = self.token == token::BINOP(token::STAR);
self.bump();
- return (some(sep), zerok);
+ return (Some(sep), zerok);
} else {
self.fatal(~"expected `*` or `+`");
}
ex = match e.node {
expr_vec(*) | expr_lit(@{node: lit_str(_), span: _})
if m == m_imm => {
- expr_vstore(e, vstore_slice(self.region_from_name(none)))
+ expr_vstore(e, vstore_slice(self.region_from_name(None)))
}
_ => expr_addr_of(m, e)
};
}
let cur_opt = token_to_binop(peeked);
match cur_opt {
- some(cur_op) => {
+ Some(cur_op) => {
let cur_prec = operator_prec(cur_op);
if cur_prec > min_prec {
self.bump();
let lo = self.last_span.lo;
let cond = self.parse_expr();
let thn = self.parse_block();
- let mut els: option<@expr> = none;
+ let mut els: Option<@expr> = None;
let mut hi = thn.span.hi;
if self.eat_keyword(~"else") {
let elexpr = self.parse_else_expr();
- els = some(elexpr);
+ els = Some(elexpr);
hi = elexpr.span.hi;
}
let q = {cond: cond, then: thn, els: els, lo: lo, hi: hi};
let lo = self.last_span.lo;
let (decl, captures) = parse_decl();
let body = parse_body();
- let fakeblock = {view_items: ~[], stmts: ~[], expr: some(body),
+ let fakeblock = {view_items: ~[], stmts: ~[], expr: Some(body),
id: self.get_id(), rules: default_blk};
let fakeblock = spanned(body.span.lo, body.span.hi,
fakeblock);
fn parse_loop_expr() -> @expr {
let opt_ident;
if is_ident(self.token) && !self.is_any_keyword(copy self.token) {
- opt_ident = some(self.parse_ident());
+ opt_ident = Some(self.parse_ident());
self.expect(token::COLON);
} else {
- opt_ident = none;
+ opt_ident = None;
}
let lo = self.last_span.lo;
fn parse_record_literal() -> expr_ {
self.expect(token::LBRACE);
let mut fields = ~[self.parse_field(token::COLON)];
- let mut base = none;
+ let mut base = None;
while self.token != token::RBRACE {
if self.token == token::COMMA
&& self.look_ahead(1) == token::DOTDOT {
self.bump();
self.bump();
- base = some(self.parse_expr()); break;
+ base = Some(self.parse_expr()); break;
}
// XXX: Remove "with" after all code is converted over and there's
self.bump();
}
if self.eat_keyword(~"with") {
- base = some(self.parse_expr()); break;
+ base = Some(self.parse_expr()); break;
}
self.expect(token::COMMA);
if self.token == token::RBRACE {
let mut arms: ~[arm] = ~[];
while self.token != token::RBRACE {
let pats = self.parse_pats();
- let mut guard = none;
- if self.eat_keyword(~"if") { guard = some(self.parse_expr()); }
+ let mut guard = None;
+ if self.eat_keyword(~"if") { guard = Some(self.parse_expr()); }
self.expect(token::FAT_ARROW);
let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
let blk = {node: {view_items: ~[],
stmts: ~[],
- expr: some(expr),
+ expr: Some(expr),
id: self.get_id(),
rules: default_blk},
span: expr.span};
return e;
}
- fn parse_initializer() -> option<initializer> {
+ fn parse_initializer() -> Option<initializer> {
match self.token {
token::EQ => {
self.bump();
- return some({op: init_assign, expr: self.parse_expr()});
+ return Some({op: init_assign, expr: self.parse_expr()});
}
token::LARROW => {
self.bump();
- return some({op: init_move, expr: self.parse_expr()});
+ return Some({op: init_move, expr: self.parse_expr()});
}
// Now that the the channel is the first argument to receive,
// combining it with an initializer doesn't really make sense.
// case (token::RECV) {
// self.bump();
- // return some(rec(op = init_recv,
+ // return Some(rec(op = init_recv,
// expr = self.parse_expr()));
// }
_ => {
- return none;
+ return None;
}
}
}
id: self.get_id(),
node: pat_ident(bind_by_implicit_ref,
fieldpath,
- none),
+ None),
span: self.last_span
};
}
let name = self.parse_value_path();
let sub;
if self.eat(token::AT) {
- sub = some(self.parse_pat(refutable));
+ sub = Some(self.parse_pat(refutable));
} else {
- sub = none;
+ sub = None;
};
pat = pat_ident(binding_mode, name, sub);
} else {
// at this point, we're not sure whether it's a
// enum or a bind
if star_pat {
- pat = pat_enum(enum_path, none);
+ pat = pat_enum(enum_path, None);
}
else if vec::is_empty(args) &&
vec::len(enum_path.idents) == 1u {
pat = pat_ident(binding_mode,
enum_path,
- none);
+ None);
}
else {
- pat = pat_enum(enum_path, some(args));
+ pat = pat_enum(enum_path, Some(args));
}
}
}
}
let name = self.parse_value_path();
let sub = if self.eat(token::AT) {
- some(self.parse_pat(refutable))
- } else { none };
+ Some(self.parse_pat(refutable))
+ } else { None };
// just to be friendly, if they write something like
- // ref some(i)
+ // ref Some(i)
// we end up here with ( as the current token. This shortly
// leads to a parse error. Note that if there is no explicit
// binding mode then we do not end up here, because the lookahead
self.expect(token::LPAREN);
self.expect(token::BINOP(token::STAR));
self.expect(token::RPAREN);
- pat_enum(enum_path, none)
+ pat_enum(enum_path, None)
}
_ => { // foo(a, ..., z)
let args = self.parse_unspanned_seq(
token::LPAREN, token::RPAREN,
seq_sep_trailing_disallowed(token::COMMA),
|p| p.parse_pat(refutable));
- pat_enum(enum_path, some(args))
+ pat_enum(enum_path, Some(args))
}
}
}
- _ => { // option::none
- pat_enum(enum_path, some(~[]))
+ _ => { // option::None
+ pat_enum(enum_path, Some(~[]))
}
}
}
node: ty_infer,
span: mk_sp(lo, lo)};
if self.eat(token::COLON) { ty = self.parse_ty(false); }
- let init = if allow_init { self.parse_initializer() } else { none };
+ let init = if allow_init { self.parse_initializer() } else { None };
return @spanned(lo, self.last_span.hi,
{is_mutbl: is_mutbl, ty: ty, pat: pat,
init: init, id: self.get_id()});
} else {
let mut item_attrs;
match self.parse_outer_attrs_or_ext(first_item_attrs) {
- none => item_attrs = ~[],
- some(Left(attrs)) => item_attrs = attrs,
- some(Right(ext)) => {
+ None => item_attrs = ~[],
+ Some(Left(attrs)) => item_attrs = attrs,
+ Some(Right(ext)) => {
return @spanned(lo, ext.span.hi,
stmt_expr(ext, self.get_id()));
}
fn parse_block_tail_(lo: uint, s: blk_check_mode,
+first_item_attrs: ~[attribute]) -> blk {
let mut stmts = ~[];
- let mut expr = none;
+ let mut expr = None;
let {attrs_remaining, view_items, items: items} =
self.parse_items_and_view_items(first_item_attrs,
@{node: stmt_semi(e, stmt_id) with *stmt});
}
token::RBRACE => {
- expr = some(e);
+ expr = Some(e);
}
t => {
if classify::stmt_ends_with_semi(*stmt) {
fn parse_ty_params() -> ~[ty_param] {
if self.eat(token::LT) {
- self.parse_seq_to_gt(some(token::COMMA), |p| p.parse_ty_param())
+ self.parse_seq_to_gt(Some(token::COMMA), |p| p.parse_ty_param())
} else { ~[] }
}
let t = self.parse_fn_header();
let (decl, _) = self.parse_fn_decl(|p| p.parse_arg());
let (inner_attrs, body) = self.parse_inner_attrs_and_block(true);
- (t.ident, item_fn(decl, purity, t.tps, body), some(inner_attrs))
+ (t.ident, item_fn(decl, purity, t.tps, body), Some(inner_attrs))
}
fn parse_method_name() -> ident {
}
let meths = self.parse_trait_methods();
- (ident, item_trait(tps, traits, meths), none)
+ (ident, item_trait(tps, traits, meths), None)
}
// Parses four variants (with the region/type params always optional):
while !self.eat(token::RBRACE) {
vec::push(meths, self.parse_method(public));
}
- (ident, item_impl(tps, traits, ty, meths), none)
+ (ident, item_impl(tps, traits, ty, meths), None)
}
// Instantiates ident <i> with references to <typarams> as arguments.
let s = self.last_span;
@{span: s, global: false, idents: ~[i],
- rp: none,
+ rp: None,
types: vec::map(typarams, |tp| {
@{id: self.get_id(),
node: ty_path(ident_to_path(s, tp.ident), self.get_id()),
let mut fields: ~[@struct_field];
let mut methods: ~[@method] = ~[];
- let mut the_ctor: option<(fn_decl, ~[attribute], blk, codemap::span)>
- = none;
- let mut the_dtor: option<(blk, ~[attribute], codemap::span)> = none;
+ let mut the_ctor: Option<(fn_decl, ~[attribute], blk, codemap::span)>
+ = None;
+ let mut the_dtor: Option<(blk, ~[attribute], codemap::span)> = None;
let ctor_id = self.get_id();
if self.eat(token::LBRACE) {
match self.parse_class_item(class_path) {
ctor_decl(a_fn_decl, attrs, blk, s) => {
match the_ctor {
- some((_, _, _, s_first)) => {
+ Some((_, _, _, s_first)) => {
self.span_note(s, #fmt("Duplicate constructor \
declaration for class %s",
*self.interner.get(class_name)));
self.span_fatal(copy s_first, ~"First constructor \
declared here");
}
- none => {
- the_ctor = some((a_fn_decl, attrs, blk, s));
+ None => {
+ the_ctor = Some((a_fn_decl, attrs, blk, s));
}
}
}
dtor_decl(blk, attrs, s) => {
match the_dtor {
- some((_, _, s_first)) => {
+ Some((_, _, s_first)) => {
self.span_note(s, #fmt("Duplicate destructor \
declaration for class %s",
*self.interner.get(class_name)));
self.span_fatal(copy s_first, ~"First destructor \
declared here");
}
- none => {
- the_dtor = some((blk, attrs, s));
+ None => {
+ the_dtor = Some((blk, attrs, s));
}
}
}
body: d_body},
span: d_s}};
match the_ctor {
- some((ct_d, ct_attrs, ct_b, ct_s)) => {
+ Some((ct_d, ct_attrs, ct_b, ct_s)) => {
(class_name,
item_class(@{
traits: traits,
fields: move fields,
methods: move methods,
- ctor: some({
+ ctor: Some({
node: {id: ctor_id,
attrs: ct_attrs,
self_id: self.get_id(),
span: ct_s}),
dtor: actual_dtor
}, ty_params),
- none)
+ None)
}
- none => {
+ None => {
(class_name,
item_class(@{
traits: traits,
fields: move fields,
methods: move methods,
- ctor: none,
+ ctor: None,
dtor: actual_dtor
}, ty_params),
- none)
+ None)
}
}
}
self.expect(token::EQ);
let e = self.parse_expr();
self.expect(token::SEMI);
- (id, item_const(ty, e), none)
+ (id, item_const(ty, e), None)
}
fn parse_item_mod() -> item_info {
let inner_attrs = self.parse_inner_attrs_and_next();
let m = self.parse_mod_items(token::RBRACE, inner_attrs.next);
self.expect(token::RBRACE);
- (id, item_mod(m), some(inner_attrs.inner))
+ (id, item_mod(m), Some(inner_attrs.inner))
}
fn parse_item_foreign_fn(+attrs: ~[attribute]) -> @foreign_item {
return iovi_item(self.mk_item(lo, self.last_span.hi, ident,
item_foreign_mod(m), visibility,
maybe_append(attrs,
- some(extra_attrs.
+ Some(extra_attrs.
inner))));
}
self.expect(token::EQ);
let ty = self.parse_ty(false);
self.expect(token::SEMI);
- (t.ident, item_ty(ty, tps), none)
+ (t.ident, item_ty(ty, tps), None)
}
fn parse_region_param() {
}
fn parse_struct_def(path: @path) -> @struct_def {
- let mut the_dtor: option<(blk, ~[attribute], codemap::span)> = none;
+ let mut the_dtor: Option<(blk, ~[attribute], codemap::span)> = None;
let mut fields: ~[@struct_field] = ~[];
let mut methods: ~[@method] = ~[];
while self.token != token::RBRACE {
}
dtor_decl(blk, attrs, s) => {
match the_dtor {
- some((_, _, s_first)) => {
+ Some((_, _, s_first)) => {
self.span_note(s, ~"duplicate destructor \
declaration");
self.span_fatal(copy s_first,
~"first destructor \
declared here");
}
- none => {
- the_dtor = some((blk, attrs, s));
+ None => {
+ the_dtor = Some((blk, attrs, s));
}
}
}
traits: ~[],
fields: move fields,
methods: move methods,
- ctor: none,
+ ctor: None,
dtor: actual_dtor
};
}
-> enum_def {
let mut variants: ~[variant] = ~[];
let mut all_nullary = true, have_disr = false;
- let mut common_fields = none;
+ let mut common_fields = None;
while self.token != token::RBRACE {
let variant_attrs = self.parse_outer_attributes();
}
self.expect(token::LBRACE);
let path = self.ident_to_path_tys(ident, ty_params);
- common_fields = some(self.parse_struct_def(path));
+ common_fields = Some(self.parse_struct_def(path));
again;
}
// Is this a nested enum declaration?
let ident, needs_comma, kind;
- let mut args = ~[], disr_expr = none;
+ let mut args = ~[], disr_expr = None;
if self.eat_keyword(~"enum") {
ident = self.parse_ident();
self.expect(token::LBRACE);
kind = tuple_variant_kind(args);
} else if self.eat(token::EQ) {
have_disr = true;
- disr_expr = some(self.parse_expr());
+ disr_expr = Some(self.parse_expr());
kind = tuple_variant_kind(args);
} else {
kind = tuple_variant_kind(~[]);
kind: tuple_variant_kind
(~[{ty: ty, id: self.get_id()}]),
id: self.get_id(),
- disr_expr: none,
+ disr_expr: None,
vis: public});
return (id, item_enum(enum_def({ variants: ~[variant],
- common: none }),
- ty_params), none);
+ common: None }),
+ ty_params), None);
}
self.expect(token::LBRACE);
let enum_definition = self.parse_enum_def(id, ty_params);
- (id, item_enum(enum_definition, ty_params), none)
+ (id, item_enum(enum_definition, ty_params), None)
}
fn parse_fn_ty_proto() -> proto {
let m: ast::mac = {node: m,
span: {lo: self.span.lo,
hi: self.span.hi,
- expn_info: none}};
+ expn_info: None}};
let item_ = item_mac(m);
return iovi_item(self.mk_item(lo, self.last_span.hi, id, item_,
visibility, attrs));
};
}
- fn parse_item(+attrs: ~[attribute]) -> option<@ast::item> {
+ fn parse_item(+attrs: ~[attribute]) -> Option<@ast::item> {
match self.parse_item_or_view_item(attrs, true) {
iovi_none =>
- none,
+ None,
iovi_view_item(_) =>
self.fatal(~"view items are not allowed here"),
iovi_item(item) =>
- some(item)
+ Some(item)
}
}
vec::push(path, id);
}
let path = @{span: mk_sp(lo, self.span.hi), global: false,
- idents: path, rp: none, types: ~[]};
+ idents: path, rp: None, types: ~[]};
return @spanned(lo, self.span.hi,
view_path_simple(first_ident, path, self.get_id()));
}
|p| p.parse_path_list_ident());
let path = @{span: mk_sp(lo, self.span.hi),
global: false, idents: path,
- rp: none, types: ~[]};
+ rp: None, types: ~[]};
return @spanned(lo, self.span.hi,
view_path_list(path, idents, self.get_id()));
}
self.bump();
let path = @{span: mk_sp(lo, self.span.hi),
global: false, idents: path,
- rp: none, types: ~[]};
+ rp: None, types: ~[]};
return @spanned(lo, self.span.hi,
view_path_glob(path, self.get_id()));
}
}
let last = path[vec::len(path) - 1u];
let path = @{span: mk_sp(lo, self.span.hi), global: false,
- idents: path, rp: none, types: ~[]};
+ idents: path, rp: None, types: ~[]};
return @spanned(lo, self.span.hi,
view_path_simple(last, path, self.get_id()));
}
* Maps a token to a record specifying the corresponding binary
* operator and its precedence
*/
-fn token_to_binop(tok: token) -> option<ast::binop> {
+fn token_to_binop(tok: token) -> Option<ast::binop> {
match tok {
- BINOP(STAR) => some(mul),
- BINOP(SLASH) => some(div),
- BINOP(PERCENT) => some(rem),
+ BINOP(STAR) => Some(mul),
+ BINOP(SLASH) => Some(div),
+ BINOP(PERCENT) => Some(rem),
// 'as' sits between here with 11
- BINOP(PLUS) => some(add),
- BINOP(MINUS) => some(subtract),
- BINOP(SHL) => some(shl),
- BINOP(SHR) => some(shr),
- BINOP(AND) => some(bitand),
- BINOP(CARET) => some(bitxor),
- BINOP(OR) => some(bitor),
- LT => some(lt),
- LE => some(le),
- GE => some(ge),
- GT => some(gt),
- EQEQ => some(eq),
- NE => some(ne),
- ANDAND => some(and),
- OROR => some(or),
- _ => none
+ BINOP(PLUS) => Some(add),
+ BINOP(MINUS) => Some(subtract),
+ BINOP(SHL) => Some(shl),
+ BINOP(SHR) => Some(shr),
+ BINOP(AND) => Some(bitand),
+ BINOP(CARET) => Some(bitxor),
+ BINOP(OR) => Some(bitor),
+ LT => Some(lt),
+ LE => Some(le),
+ GE => Some(ge),
+ GT => Some(gt),
+ EQEQ => Some(eq),
+ NE => Some(ne),
+ ANDAND => Some(and),
+ OROR => Some(or),
+ _ => None
}
}
|x,y| str::eq(*x, *y), init_vec);
/* having multiple interners will just confuse the serializer */
- unsafe{ assert task::local_data_get(interner_key!()) == none };
+ unsafe{ assert task::local_data_get(interner_key!()) == None };
unsafe{ task::local_data_set(interner_key!(), @rv) };
rv
}
type ps =
@{s: pp::printer,
- cm: option<codemap>,
+ cm: Option<codemap>,
intr: token::ident_interner,
- comments: option<~[comments::cmnt]>,
- literals: option<~[comments::lit]>,
+ comments: Option<~[comments::cmnt]>,
+ literals: Option<~[comments::lit]>,
mut cur_cmnt: uint,
mut cur_lit: uint,
boxes: DVec<pp::breaks>,
fn rust_printer(writer: io::Writer, intr: ident_interner) -> ps {
return @{s: pp::mk_printer(writer, default_columns),
- cm: none::<codemap>,
+ cm: None::<codemap>,
intr: intr,
- comments: none::<~[comments::cmnt]>,
- literals: none::<~[comments::lit]>,
+ comments: None::<~[comments::cmnt]>,
+ literals: None::<~[comments::lit]>,
mut cur_cmnt: 0u,
mut cur_lit: 0u,
boxes: dvec(),
filename, in);
let s =
@{s: pp::mk_printer(out, default_columns),
- cm: some(cm),
+ cm: Some(cm),
intr: intr,
- comments: some(r.cmnts),
+ comments: Some(r.cmnts),
// If the code is post expansion, don't use the table of
// literals, since it doesn't correspond with the literals
// in the AST anymore.
- literals: if is_expanded { none } else { some(r.lits) },
+ literals: if is_expanded { None } else { Some(r.lits) },
mut cur_cmnt: 0u,
mut cur_lit: 0u,
boxes: dvec(),
params: ~[ast::ty_param], intr: ident_interner) -> ~str {
let buffer = io::mem_buffer();
let s = rust_printer(io::mem_buffer_writer(buffer), intr);
- print_fn(s, decl, none, name, params, none);
+ print_fn(s, decl, None, name, params, None);
end(s); // Close the head box
end(s); // Close the outer box
eof(s.s);
if i < len {
word(s.s, ~",");
maybe_print_trailing_comment(s, get_span(elt),
- some(get_span(elts[i]).hi));
+ Some(get_span(elts[i]).hi));
space_if_not_bol(s);
}
}
pclose(s);
}
ast::ty_fn(proto, purity, bounds, d) => {
- print_ty_fn(s, some(proto), purity, bounds, d, none, none, none);
+ print_ty_fn(s, Some(proto), purity, bounds, d, None, None, None);
}
ast::ty_path(path, _) => print_path(s, path, print_colons),
ast::ty_fixed_length(t, v) => {
print_outer_attributes(s, item.attrs);
match item.node {
ast::foreign_item_fn(decl, purity, typarams) => {
- print_fn(s, decl, some(purity), item.ident, typarams, none);
+ print_fn(s, decl, Some(purity), item.ident, typarams, None);
end(s); // end head-ibox
word(s.s, ~";");
end(s); // end the outer fn box
}
ast::item_fn(decl, purity, typarams, body) => {
- print_fn(s, decl, some(purity), item.ident, typarams, none);
+ print_fn(s, decl, Some(purity), item.ident, typarams, None);
word(s.s, ~" ");
print_block_with_attrs(s, body, item.attrs);
}
print_variant(s, v);
word(s.s, ~",");
end(s);
- maybe_print_trailing_comment(s, v.span, none::<uint>);
+ maybe_print_trailing_comment(s, v.span, None::<uint>);
}
bclose(s, span);
}
cbox(s, indent_unit);
ibox(s, 4);
word(s.s, ~"new(");
- print_fn_args(s, ctor.node.dec, ~[], none);
+ print_fn_args(s, ctor.node.dec, ~[], None);
word(s.s, ~")");
space(s.s);
print_block(s, ctor.node.body);
for tts.each() |tt_elt| { print_tt(s, tt_elt); }
word(s.s, ~")");
match sep {
- some(tk) => word(s.s, parse::token::to_str(s.intr, tk)),
- none => ()
+ Some(tk) => word(s.s, parse::token::to_str(s.intr, tk)),
+ None => ()
}
word(s.s, if zerok { ~"*" } else { ~"+" });
s.s.token_tree_last_was_ident = false;
}
}
match v.node.disr_expr {
- some(d) => {
+ Some(d) => {
space(s.s);
word_space(s, ~"=");
print_expr(s, d);
hardbreak_if_not_bol(s);
maybe_print_comment(s, m.span.lo);
print_outer_attributes(s, m.attrs);
- print_ty_fn(s, none, m.purity,
- @~[], m.decl, some(m.ident), some(m.tps),
- some(m.self_ty.node));
+ print_ty_fn(s, None, m.purity,
+ @~[], m.decl, Some(m.ident), Some(m.tps),
+ Some(m.self_ty.node));
word(s.s, ~";");
}
hardbreak_if_not_bol(s);
maybe_print_comment(s, meth.span.lo);
print_outer_attributes(s, meth.attrs);
- print_fn(s, meth.decl, some(meth.purity),
- meth.ident, meth.tps, some(meth.self_ty.node));
+ print_fn(s, meth.decl, Some(meth.purity),
+ meth.ident, meth.tps, Some(meth.self_ty.node));
word(s.s, ~" ");
print_block_with_attrs(s, meth.body, meth.attrs);
}
}
}
if parse::classify::stmt_ends_with_semi(st) { word(s.s, ~";"); }
- maybe_print_trailing_comment(s, st.span, none::<uint>);
+ maybe_print_trailing_comment(s, st.span, None::<uint>);
}
fn print_block(s: ps, blk: ast::blk) {
print_stmt(s, *st);
}
match blk.node.expr {
- some(expr) => {
+ Some(expr) => {
space_if_not_bol(s);
print_expr(s, expr);
- maybe_print_trailing_comment(s, expr.span, some(blk.span.hi));
+ maybe_print_trailing_comment(s, expr.span, Some(blk.span.hi));
}
_ => ()
}
// alt, do, & while unambiguously without being parenthesized
fn print_maybe_parens_discrim(s: ps, e: @ast::expr) {
let disambig = match e.node {
- ast::expr_ret(none) | ast::expr_fail(none) => true,
+ ast::expr_ret(None) | ast::expr_fail(None) => true,
_ => false
};
if disambig { popen(s); }
}
fn print_if(s: ps, test: @ast::expr, blk: ast::blk,
- elseopt: option<@ast::expr>, chk: bool) {
+ elseopt: Option<@ast::expr>, chk: bool) {
head(s, ~"if");
if chk { word_nbsp(s, ~"check"); }
print_maybe_parens_discrim(s, test);
space(s.s);
print_block(s, blk);
- fn do_else(s: ps, els: option<@ast::expr>) {
+ fn do_else(s: ps, els: Option<@ast::expr>) {
match els {
- some(_else) => {
+ Some(_else) => {
match _else.node {
// "another else-if"
ast::expr_if(i, t, e) => {
word(s.s, ~"#");
print_path(s, path, false);
match arg {
- some(@{node: ast::expr_vec(_, _), _}) => (),
+ Some(@{node: ast::expr_vec(_, _), _}) => (),
_ => word(s.s, ~" ")
}
option::iter(arg, |a| print_expr(s, a));
fn print_vstore(s: ps, t: ast::vstore) {
match t {
- ast::vstore_fixed(some(i)) => word(s.s, fmt!("%u", i)),
- ast::vstore_fixed(none) => word(s.s, ~"_"),
+ ast::vstore_fixed(Some(i)) => word(s.s, fmt!("%u", i)),
+ ast::vstore_fixed(None) => word(s.s, ~"_"),
ast::vstore_uniq => word(s.s, ~"~"),
ast::vstore_box => word(s.s, ~"@"),
ast::vstore_slice(r) => match r.node {
word(s.s, ~"{");
commasep_cmnt(s, consistent, fields, print_field, get_span);
match wth {
- some(expr) => {
+ Some(expr) => {
ibox(s, indent_unit);
word(s.s, ~",");
space(s.s);
word(s.s, ~"{");
commasep_cmnt(s, consistent, fields, print_field, get_span);
match wth {
- some(expr) => {
+ Some(expr) => {
if vec::len(fields) > 0u { space(s.s); }
ibox(s, indent_unit);
word(s.s, ~",");
ast::expr_do_body(_) => { head(s, ~"do"); }
_ => {}
}
- some(blk_arg)
- } else { none };
+ Some(blk_arg)
+ } else { None };
print_expr_parens_if_not_bot(s, func);
if !has_block || vec::len(base_args) > 0u {
popen(s);
}
space(s.s);
match arm.guard {
- some(e) => {
+ Some(e) => {
word_space(s, ~"if");
print_expr(s, e);
space(s.s);
}
- none => ()
+ None => ()
}
word_space(s, ~"=>");
// Extract the expression from the extra block the parser adds
assert arm.body.node.stmts.is_empty();
assert arm.body.node.rules == ast::default_blk;
match arm.body.node.expr {
- some(expr) => {
+ Some(expr) => {
match expr.node {
ast::expr_block(blk) => {
// the block will close the pattern's ibox
}
end(s); // close enclosing cbox
}
- none => fail
+ None => fail
}
}
bclose_(s, expr.span, alt_indent_unit);
cbox(s, indent_unit);
// head-box, will be closed by print-block at start
ibox(s, 0u);
- word(s.s, fn_header_info_to_str(none, none, some(proto)));
- print_fn_args_and_ret(s, decl, *cap_clause, none);
+ word(s.s, fn_header_info_to_str(None, None, Some(proto)));
+ print_fn_args_and_ret(s, decl, *cap_clause, None);
space(s.s);
print_block(s, body);
}
ast::expr_fail(maybe_fail_val) => {
word(s.s, ~"fail");
match maybe_fail_val {
- some(expr) => { word(s.s, ~" "); print_expr(s, expr); }
+ Some(expr) => { word(s.s, ~" "); print_expr(s, expr); }
_ => ()
}
}
ast::expr_ret(result) => {
word(s.s, ~"return");
match result {
- some(expr) => { word(s.s, ~" "); print_expr(s, expr); }
+ Some(expr) => { word(s.s, ~" "); print_expr(s, expr); }
_ => ()
}
}
print_local_decl(s, loc);
end(s);
match loc.node.init {
- some(init) => {
+ Some(init) => {
nbsp(s);
match init.op {
ast::init_assign => word_space(s, ~"="),
if colons_before_params { word(s.s, ~"::"); }
match path.rp {
- none => { /* ok */ }
- some(r) => {
+ None => { /* ok */ }
+ Some(r) => {
word(s.s, ~"/");
print_region(s, r);
}
}
print_path(s, path, true);
match sub {
- some(p) => { word(s.s, ~"@"); print_pat(s, p); }
- none => ()
+ Some(p) => { word(s.s, ~"@"); print_pat(s, p); }
+ None => ()
}
}
ast::pat_enum(path, args_) => {
print_path(s, path, true);
match args_ {
- none => word(s.s, ~"(*)"),
- some(args) => {
+ None => word(s.s, ~"(*)"),
+ Some(args) => {
if vec::len(args) > 0u {
popen(s);
commasep(s, inconsistent, args, print_pat);
return true;
}
-fn print_fn(s: ps, decl: ast::fn_decl, purity: option<ast::purity>,
+fn print_fn(s: ps, decl: ast::fn_decl, purity: Option<ast::purity>,
name: ast::ident,
typarams: ~[ast::ty_param],
- opt_self_ty: option<ast::self_ty_>) {
- head(s, fn_header_info_to_str(opt_self_ty, purity, none));
+ opt_self_ty: Option<ast::self_ty_>) {
+ head(s, fn_header_info_to_str(opt_self_ty, purity, None));
print_ident(s, name);
print_type_params(s, typarams);
print_fn_args_and_ret(s, decl, ~[], opt_self_ty);
fn print_fn_args(s: ps, decl: ast::fn_decl,
cap_items: ~[ast::capture_item],
- opt_self_ty: option<ast::self_ty_>) {
+ opt_self_ty: Option<ast::self_ty_>) {
// It is unfortunate to duplicate the commasep logic, but we
// we want the self type, the args, and the capture clauses all
// in the same box.
fn print_fn_args_and_ret(s: ps, decl: ast::fn_decl,
cap_items: ~[ast::capture_item],
- opt_self_ty: option<ast::self_ty_>) {
+ opt_self_ty: Option<ast::self_ty_>) {
popen(s);
print_fn_args(s, decl, cap_items, opt_self_ty);
pclose(s);
fn print_fn_block_args(s: ps, decl: ast::fn_decl,
cap_items: ~[ast::capture_item]) {
word(s.s, ~"|");
- print_fn_args(s, decl, cap_items, none);
+ print_fn_args(s, decl, cap_items, None);
word(s.s, ~"|");
if decl.output.node != ast::ty_infer {
space_if_not_bol(s);
end(s);
}
-fn print_ty_fn(s: ps, opt_proto: option<ast::proto>, purity: ast::purity,
+fn print_ty_fn(s: ps, opt_proto: Option<ast::proto>, purity: ast::purity,
bounds: @~[ast::ty_param_bound],
- decl: ast::fn_decl, id: option<ast::ident>,
- tps: option<~[ast::ty_param]>,
- opt_self_ty: option<ast::self_ty_>) {
+ decl: ast::fn_decl, id: Option<ast::ident>,
+ tps: Option<~[ast::ty_param]>,
+ opt_self_ty: Option<ast::self_ty_>) {
ibox(s, indent_unit);
- word(s.s, fn_header_info_to_str(opt_self_ty, some(purity), opt_proto));
+ word(s.s, fn_header_info_to_str(opt_self_ty, Some(purity), opt_proto));
print_bounds(s, bounds);
- match id { some(id) => { word(s.s, ~" "); print_ident(s, id); } _ => () }
- match tps { some(tps) => print_type_params(s, tps), _ => () }
+ match id { Some(id) => { word(s.s, ~" "); print_ident(s, id); } _ => () }
+ match tps { Some(tps) => print_type_params(s, tps), _ => () }
zerobreak(s.s);
popen(s);
}
fn maybe_print_trailing_comment(s: ps, span: codemap::span,
- next_pos: option<uint>) {
+ next_pos: Option<uint>) {
let mut cm;
- match s.cm { some(ccm) => cm = ccm, _ => return }
+ match s.cm { Some(ccm) => cm = ccm, _ => return }
match next_comment(s) {
- some(cmnt) => {
+ Some(cmnt) => {
if cmnt.style != comments::trailing { return; }
let span_line = codemap::lookup_char_pos(cm, span.hi);
let comment_line = codemap::lookup_char_pos(cm, cmnt.pos);
let mut next = cmnt.pos + 1u;
- match next_pos { none => (), some(p) => next = p }
+ match next_pos { None => (), Some(p) => next = p }
if span.hi < cmnt.pos && cmnt.pos < next &&
span_line.line == comment_line.line {
print_comment(s, cmnt);
if option::is_none(next_comment(s)) { hardbreak(s.s); }
loop {
match next_comment(s) {
- some(cmnt) => { print_comment(s, cmnt); s.cur_cmnt += 1u; }
+ Some(cmnt) => { print_comment(s, cmnt); s.cur_cmnt += 1u; }
_ => break
}
}
fn print_literal(s: ps, &&lit: @ast::lit) {
maybe_print_comment(s, lit.span.lo);
match next_lit(s, lit.span.lo) {
- some(ltrl) => {
+ Some(ltrl) => {
word(s.s, ltrl.lit);
return;
}
return to_str(l, print_literal, parse::token::mk_fake_ident_interner());
}
-fn next_lit(s: ps, pos: uint) -> option<comments::lit> {
+fn next_lit(s: ps, pos: uint) -> Option<comments::lit> {
match s.literals {
- some(lits) => {
+ Some(lits) => {
while s.cur_lit < vec::len(lits) {
let ltrl = lits[s.cur_lit];
- if ltrl.pos > pos { return none; }
+ if ltrl.pos > pos { return None; }
s.cur_lit += 1u;
- if ltrl.pos == pos { return some(ltrl); }
+ if ltrl.pos == pos { return Some(ltrl); }
}
- return none;
+ return None;
}
- _ => return none
+ _ => return None
}
}
fn maybe_print_comment(s: ps, pos: uint) {
loop {
match next_comment(s) {
- some(cmnt) => {
+ Some(cmnt) => {
if cmnt.pos < pos {
print_comment(s, cmnt);
s.cur_cmnt += 1u;
io::mem_buffer_str(buffer)
}
-fn next_comment(s: ps) -> option<comments::cmnt> {
+fn next_comment(s: ps) -> Option<comments::cmnt> {
match s.comments {
- some(cmnts) => {
+ Some(cmnts) => {
if s.cur_cmnt < vec::len(cmnts) {
- return some(cmnts[s.cur_cmnt]);
- } else { return none::<comments::cmnt>; }
+ return Some(cmnts[s.cur_cmnt]);
+ } else { return None::<comments::cmnt>; }
}
- _ => return none::<comments::cmnt>
+ _ => return None::<comments::cmnt>
}
}
-fn fn_header_info_to_str(opt_sty: option<ast::self_ty_>,
- opt_purity: option<ast::purity>,
- opt_p: option<ast::proto>) -> ~str {
+fn fn_header_info_to_str(opt_sty: Option<ast::self_ty_>,
+ opt_purity: Option<ast::purity>,
+ opt_p: Option<ast::proto>) -> ~str {
let mut s = match opt_sty {
- some(ast::sty_static) => ~"static ",
+ Some(ast::sty_static) => ~"static ",
_ => ~ ""
};
match opt_purity {
- some(ast::impure_fn) => { }
- some(purity) => {
+ Some(ast::impure_fn) => { }
+ Some(purity) => {
str::push_str(s, purity_to_str(purity));
str::push_char(s, ' ');
}
- none => {}
+ None => {}
}
str::push_str(s, opt_proto_to_str(opt_p));
return s;
}
-fn opt_proto_to_str(opt_p: option<ast::proto>) -> ~str {
+fn opt_proto_to_str(opt_p: Option<ast::proto>) -> ~str {
match opt_p {
- none => ~"fn",
- some(p) => proto_to_str(p)
+ None => ~"fn",
+ Some(p) => proto_to_str(p)
}
}
impl <T: const copy> hash_interner<T>: interner<T> {
fn intern(val: T) -> uint {
match self.map.find(val) {
- some(idx) => return idx,
- none => {
+ Some(idx) => return idx,
+ None => {
let new_idx = self.vect.len();
self.map.insert(val, new_idx);
self.vect.push(val);
v.visit_pat(loc.node.pat, e, v);
v.visit_ty(loc.node.ty, e, v);
match loc.node.init {
- none => (),
- some(i) => v.visit_expr(i.expr, e, v)
+ None => (),
+ Some(i) => v.visit_expr(i.expr, e, v)
}
}
}
}
-fn visit_expr_opt<E>(eo: option<@expr>, e: E, v: vt<E>) {
- match eo { none => (), some(ex) => v.visit_expr(ex, e, v) }
+fn visit_expr_opt<E>(eo: Option<@expr>, e: E, v: vt<E>) {
+ match eo { None => (), Some(ex) => v.visit_expr(ex, e, v) }
}
fn visit_exprs<E>(exprs: ~[@expr], e: E, v: vt<E>) {
symbol_hasher: &hash::State) -> link_meta {
type provided_metas =
- {name: option<~str>,
- vers: option<~str>,
+ {name: Option<~str>,
+ vers: Option<~str>,
cmh_items: ~[@ast::meta_item]};
fn provided_link_metas(sess: session, c: ast::crate) ->
provided_metas {
- let mut name: option<~str> = none;
- let mut vers: option<~str> = none;
+ let mut name: Option<~str> = None;
+ let mut vers: Option<~str> = None;
let mut cmh_items: ~[@ast::meta_item] = ~[];
let linkage_metas = attr::find_linkage_metas(c.node.attrs);
attr::require_unique_names(sess.diagnostic(), linkage_metas);
for linkage_metas.each |meta| {
if attr::get_meta_item_name(meta) == ~"name" {
match attr::get_meta_item_value_str(meta) {
- some(v) => { name = some(v); }
- none => vec::push(cmh_items, meta)
+ Some(v) => { name = Some(v); }
+ None => vec::push(cmh_items, meta)
}
} else if attr::get_meta_item_name(meta) == ~"vers" {
match attr::get_meta_item_value_str(meta) {
- some(v) => { vers = some(v); }
- none => vec::push(cmh_items, meta)
+ Some(v) => { vers = Some(v); }
+ None => vec::push(cmh_items, meta)
}
} else { vec::push(cmh_items, meta); }
}
fn crate_meta_name(sess: session, _crate: ast::crate,
output: &Path, metas: provided_metas) -> ~str {
return match metas.name {
- some(v) => v,
- none => {
+ Some(v) => v,
+ None => {
let name = match output.filestem() {
- none => sess.fatal(fmt!("output file name `%s` doesn't\
+ None => sess.fatal(fmt!("output file name `%s` doesn't\
appear to have a stem",
output.to_str())),
- some(s) => s
+ Some(s) => s
};
warn_missing(sess, ~"name", name);
name
fn crate_meta_vers(sess: session, _crate: ast::crate,
metas: provided_metas) -> ~str {
return match metas.vers {
- some(v) => v,
- none => {
+ Some(v) => v,
+ None => {
let vers = ~"0.0";
warn_missing(sess, ~"vers", vers);
vers
fn get_symbol_hash(ccx: @crate_ctxt, t: ty::t) -> ~str {
match ccx.type_hashcodes.find(t) {
- some(h) => return h,
- none => {
+ Some(h) => return h,
+ None => {
let hash = symbol_hash(ccx.tcx, ccx.symbol_hasher, t, ccx.link_meta);
ccx.type_hashcodes.insert(t, hash);
return hash;
let cstore = sess.cstore;
for cstore::get_used_crate_files(cstore).each |cratepath| {
- if cratepath.filetype() == some(~"rlib") {
+ if cratepath.filetype() == Some(~"rlib") {
vec::push(cc_args, cratepath.to_str());
again;
}
fn compile_upto(sess: session, cfg: ast::crate_cfg,
input: input, upto: compile_upto,
- outputs: option<output_filenames>)
- -> {crate: @ast::crate, tcx: option<ty::ctxt>} {
+ outputs: Option<output_filenames>)
+ -> {crate: @ast::crate, tcx: Option<ty::ctxt>} {
let time_passes = sess.time_passes();
let mut crate = time(time_passes, ~"parsing",
||parse_input(sess, cfg, input) );
- if upto == cu_parse { return {crate: crate, tcx: none}; }
+ if upto == cu_parse { return {crate: crate, tcx: None}; }
sess.building_library = session::building_library(
sess.opts.crate_type, crate, sess.opts.test);
syntax::ext::expand::expand_crate(sess.parse_sess, sess.opts.cfg,
crate));
- if upto == cu_expand { return {crate: crate, tcx: none}; }
+ if upto == cu_expand { return {crate: crate, tcx: None}; }
crate = time(time_passes, ~"intrinsic injection", ||
front::intrinsic_inject::inject_intrinsic(sess, crate));
middle::check_const::check_crate(sess, crate, ast_map, def_map,
method_map, ty_cx));
- if upto == cu_typeck { return {crate: crate, tcx: some(ty_cx)}; }
+ if upto == cu_typeck { return {crate: crate, tcx: Some(ty_cx)}; }
time(time_passes, ~"loop checking", ||
middle::check_loop::check_crate(ty_cx, crate));
time(time_passes, ~"lint checking", || lint::check_crate(ty_cx, crate));
- if upto == cu_no_trans { return {crate: crate, tcx: some(ty_cx)}; }
+ if upto == cu_no_trans { return {crate: crate, tcx: Some(ty_cx)}; }
let outputs = option::get(outputs);
let maps = {mutbl_map: mutbl_map,
sess.opts.output_type != link::output_type_exe ||
sess.opts.static && sess.building_library;
- if stop_after_codegen { return {crate: crate, tcx: some(ty_cx)}; }
+ if stop_after_codegen { return {crate: crate, tcx: Some(ty_cx)}; }
time(time_passes, ~"linking", ||
link::link_binary(sess,
&outputs.obj_filename,
&outputs.out_filename, link_meta));
- return {crate: crate, tcx: some(ty_cx)};
+ return {crate: crate, tcx: Some(ty_cx)};
}
fn compile_input(sess: session, cfg: ast::crate_cfg, input: input,
- outdir: &option<Path>, output: &option<Path>) {
+ outdir: &Option<Path>, output: &Option<Path>) {
let upto = if sess.opts.parse_only { cu_parse }
else if sess.opts.no_trans { cu_no_trans }
else { cu_everything };
let outputs = build_output_filenames(input, outdir, output, sess);
- compile_upto(sess, cfg, input, upto, some(outputs));
+ compile_upto(sess, cfg, input, upto, Some(outputs));
}
fn pretty_print_input(sess: session, cfg: ast::crate_cfg, input: input,
ppm_typed => cu_typeck,
_ => cu_parse
};
- let {crate, tcx} = compile_upto(sess, cfg, input, upto, none);
+ let {crate, tcx} = compile_upto(sess, cfg, input, upto, None);
let ann = match ppm {
ppm_typed => {
}
}
-fn get_os(triple: ~str) -> option<session::os> {
+fn get_os(triple: ~str) -> Option<session::os> {
if str::contains(triple, ~"win32") ||
str::contains(triple, ~"mingw32") {
- some(session::os_win32)
+ Some(session::os_win32)
} else if str::contains(triple, ~"darwin") {
- some(session::os_macos)
+ Some(session::os_macos)
} else if str::contains(triple, ~"linux") {
- some(session::os_linux)
+ Some(session::os_linux)
} else if str::contains(triple, ~"freebsd") {
- some(session::os_freebsd)
- } else { none }
+ Some(session::os_freebsd)
+ } else { None }
}
-fn get_arch(triple: ~str) -> option<session::arch> {
+fn get_arch(triple: ~str) -> Option<session::arch> {
if str::contains(triple, ~"i386") ||
str::contains(triple, ~"i486") ||
str::contains(triple, ~"i586") ||
str::contains(triple, ~"i686") ||
str::contains(triple, ~"i786") {
- some(session::arch_x86)
+ Some(session::arch_x86)
} else if str::contains(triple, ~"x86_64") {
- some(session::arch_x86_64)
+ Some(session::arch_x86_64)
} else if str::contains(triple, ~"arm") ||
str::contains(triple, ~"xscale") {
- some(session::arch_arm)
- } else { none }
+ Some(session::arch_arm)
+ } else { None }
}
fn build_target_config(sopts: @session::options,
demitter: diagnostic::emitter) -> @session::config {
let os = match get_os(sopts.target_triple) {
- some(os) => os,
- none => early_error(demitter, ~"unknown operating system")
+ Some(os) => os,
+ None => early_error(demitter, ~"unknown operating system")
};
let arch = match get_arch(sopts.target_triple) {
- some(arch) => arch,
- none => early_error(demitter,
+ Some(arch) => arch,
+ None => early_error(demitter,
~"unknown architecture: " + sopts.target_triple)
};
let (int_type, uint_type, float_type) = match arch {
for flags.each |lint_name| {
let lint_name = str::replace(lint_name, ~"-", ~"_");
match lint_dict.find(lint_name) {
- none => {
+ None => {
early_error(demitter, fmt!("unknown %s flag: %s",
level_name, lint_name));
}
- some(lint) => {
+ Some(lint) => {
vec::push(lint_opts, (lint.lint, level));
}
}
} else { No };
let target =
match target_opt {
- none => host_triple(),
- some(s) => s
+ None => host_triple(),
+ Some(s) => s
};
let addl_lib_search_paths =
demitter: diagnostic::emitter) -> session {
let codemap = codemap::new_codemap();
let diagnostic_handler =
- diagnostic::mk_handler(some(demitter));
+ diagnostic::mk_handler(Some(demitter));
let span_diagnostic_handler =
diagnostic::mk_span_handler(diagnostic_handler, codemap);
build_session_(sopts, codemap, demitter, span_diagnostic_handler)
parse_sess: p_s,
codemap: cm,
// For a library crate, this is always none
- mut main_fn: none,
+ mut main_fn: None,
span_diagnostic: span_diagnostic_handler,
filesearch: filesearch,
mut building_library: false,
type output_filenames = @{out_filename:Path, obj_filename:Path};
fn build_output_filenames(input: input,
- odir: &option<Path>,
- ofile: &option<Path>,
+ odir: &Option<Path>,
+ ofile: &Option<Path>,
sess: session)
-> output_filenames {
let obj_path;
};
match *ofile {
- none => {
+ None => {
// "-" as input file will cause the parser to read from stdin so we
// have to make up a name
// We want to toss everything after the final '.'
let dirpath = match *odir {
- some(d) => d,
- none => match input {
+ Some(d) => d,
+ None => match input {
str_input(_) => os::getcwd(),
file_input(ifile) => ifile.dir_path()
}
}
}
- some(out_file) => {
+ Some(out_file) => {
out_path = out_file;
obj_path = if stop_after_codegen {
out_file
// lib<basename>-<hash>-<version>.so no matter what.
}
- if *odir != none {
+ if *odir != None {
sess.warn(~"ignoring --out-dir flag due to -o flag.");
}
}
}
fn early_error(emitter: diagnostic::emitter, msg: ~str) -> ! {
- emitter(none, msg, diagnostic::fatal);
+ emitter(None, msg, diagnostic::fatal);
fail;
}
~"normal"),
|a| parse_pretty(sess, a) );
match pretty {
- some::<pp_mode>(ppm) => {
+ Some::<pp_mode>(ppm) => {
pretty_print_input(sess, cfg, input, ppm);
return;
}
- none::<pp_mode> => {/* continue */ }
+ None::<pp_mode> => {/* continue */ }
}
let ls = opt_present(matches, ~"ls");
if ls {
// The 'diagnostics emitter'. Every error, warning, etc. should
// go through this function.
- let demitter = fn@(cmsp: option<(codemap::codemap, codemap::span)>,
+ let demitter = fn@(cmsp: Option<(codemap::codemap, codemap::span)>,
msg: ~str, lvl: diagnostic::level) {
if lvl == diagnostic::fatal {
comm::send(ch, fatal);
// Task failed without emitting a fatal diagnostic
if comm::recv(p) == done {
diagnostic::emit(
- none,
+ None,
diagnostic::ice_msg(~"unexpected failure"),
diagnostic::error);
to get further details and report the results \
to github.com/mozilla/rust/issues"
]/_.each |note| {
- diagnostic::emit(none, note, diagnostic::note)
+ diagnostic::emit(None, note, diagnostic::note)
}
}
// Fail so the process returns a failure code
save_temps: bool,
output_type: back::link::output_type,
addl_lib_search_paths: ~[Path],
- maybe_sysroot: option<Path>,
+ maybe_sysroot: Option<Path>,
target_triple: ~str,
cfg: ast::crate_cfg,
test: bool,
parse_sess: parse_sess,
codemap: codemap::codemap,
// For a library crate, this is always none
- mut main_fn: option<(node_id, codemap::span)>,
+ mut main_fn: Option<(node_id, codemap::span)>,
span_diagnostic: diagnostic::span_handler,
filesearch: filesearch::filesearch,
mut building_library: bool,
save_temps: false,
output_type: link::output_type_exe,
addl_lib_search_paths: ~[],
- maybe_sysroot: none,
+ maybe_sysroot: None,
target_triple: driver::host_triple(),
cfg: ~[],
test: false,
}
// Seems out of place, but it uses session, so I'm putting it here
-fn expect<T: copy>(sess: session, opt: option<T>, msg: fn() -> ~str) -> T {
+fn expect<T: copy>(sess: session, opt: Option<T>, msg: fn() -> ~str) -> T {
diagnostic::expect(sess.diagnostic(), opt, msg)
}
match syntax::attr::first_attr_value_str_by_name(
crate.node.attrs,
~"crate_type") {
- option::some(~"lib") => true,
+ option::Some(~"lib") => true,
_ => false
}
}
}
fn filter_item(cx: ctxt, &&item: @ast::item) ->
- option<@ast::item> {
- if item_in_cfg(cx, item) { option::some(item) } else { option::none }
+ Option<@ast::item> {
+ if item_in_cfg(cx, item) { option::Some(item) } else { option::None }
}
fn filter_view_item(cx: ctxt, &&view_item: @ast::view_item
- )-> option<@ast::view_item> {
+ )-> Option<@ast::view_item> {
if view_item_in_cfg(cx, view_item) {
- option::some(view_item)
+ option::Some(view_item)
} else {
- option::none
+ option::None
}
}
}
fn filter_foreign_item(cx: ctxt, &&item: @ast::foreign_item) ->
- option<@ast::foreign_item> {
+ Option<@ast::foreign_item> {
if foreign_item_in_cfg(cx, item) {
- option::some(item)
- } else { option::none }
+ option::Some(item)
+ } else { option::None }
}
fn fold_foreign_mod(cx: ctxt, nm: ast::foreign_mod,
}
fn filter_stmt(cx: ctxt, &&stmt: @ast::stmt) ->
- option<@ast::stmt> {
+ Option<@ast::stmt> {
match stmt.node {
ast::stmt_decl(decl, _) => {
match decl.node {
ast::decl_item(item) => {
if item_in_cfg(cx, item) {
- option::some(stmt)
- } else { option::none }
+ option::Some(stmt)
+ } else { option::None }
}
- _ => option::some(stmt)
+ _ => option::Some(stmt)
}
}
- _ => option::some(stmt)
+ _ => option::Some(stmt)
}
}
sess.parse_sess);
let item =
match item {
- some(i) => i,
- none => {
+ Some(i) => i,
+ None => {
sess.fatal(~"no item found in intrinsic module");
}
};
// FIXME (#2403): This is sloppy. Instead we should have some mechanism to
// indicate to the translation pass which function we want to be main.
- fn nomain(cx: test_ctxt, item: @ast::item) -> option<@ast::item> {
+ fn nomain(cx: test_ctxt, item: @ast::item) -> Option<@ast::item> {
match item.node {
ast::item_fn(*) => {
if item.ident == cx.sess.ident_of(~"main") {
- option::none
- } else { option::some(item) }
+ option::None
+ } else { option::Some(item) }
}
- _ => option::some(item)
+ _ => option::Some(item)
}
}
fn fold_item(cx: test_ctxt, &&i: @ast::item, fld: fold::ast_fold) ->
- option<@ast::item> {
+ Option<@ast::item> {
vec::push(cx.path, i.ident);
debug!("current path: %s",
}
fn path_node(ids: ~[ast::ident]) -> @ast::path {
- @{span: dummy_sp(), global: false, idents: ids, rp: none, types: ~[]}
+ @{span: dummy_sp(), global: false, idents: ids, rp: None, types: ~[]}
}
fn mk_tests(cx: test_ctxt) -> @ast::item {
let test_descs = mk_test_desc_vec(cx);
let body_: ast::blk_ =
- default_block(~[], option::some(test_descs), cx.sess.next_node_id());
+ default_block(~[], option::Some(test_descs), cx.sess.next_node_id());
let body = nospan(body_);
let item_ = ast::item_fn(decl, ast::impure_fn, ~[], body);
let is_std = {
let items = attr::find_linkage_metas(cx.crate.node.attrs);
match attr::last_meta_item_value_str_by_name(items, ~"name") {
- some(~"std") => true,
+ Some(~"std") => true,
_ => false
}
};
let desc_rec_: ast::expr_ =
ast::expr_rec(~[name_field, fn_field, ignore_field, fail_field],
- option::none);
+ option::None);
let desc_rec: ast::expr =
{id: cx.sess.next_node_id(), callee_id: cx.sess.next_node_id(),
node: desc_rec_, span: span};
let wrapper_body: ast::blk = nospan({
view_items: ~[],
stmts: ~[@call_stmt],
- expr: option::none,
+ expr: option::None,
id: cx.sess.next_node_id(),
rules: ast::default_blk
});
let test_main_call_expr = mk_test_main_call(cx);
let body_: ast::blk_ =
- default_block(~[], option::some(test_main_call_expr),
+ default_block(~[], option::Some(test_main_call_expr),
cx.sess.next_node_id());
let body = {node: body_, span: dummy_sp()};
assert tn.named_types.insert(s, t);
}
-fn type_has_name(tn: type_names, t: TypeRef) -> option<~str> {
+fn type_has_name(tn: type_names, t: TypeRef) -> Option<~str> {
return tn.type_names.find(t);
}
-fn name_has_type(tn: type_names, s: ~str) -> option<TypeRef> {
+fn name_has_type(tn: type_names, s: ~str) -> Option<TypeRef> {
return tn.named_types.find(s);
}
fn type_to_str_inner(names: type_names, outer0: ~[TypeRef], ty: TypeRef) ->
~str {
match type_has_name(names, ty) {
- option::some(n) => return n,
+ option::Some(n) => return n,
_ => {}
}
type object_file = {llof: ObjectFileRef, dtor: @object_file_res};
-fn mk_object_file(llmb: MemoryBufferRef) -> option<object_file> {
+fn mk_object_file(llmb: MemoryBufferRef) -> Option<object_file> {
let llof = llvm::LLVMCreateObjectFile(llmb);
- if llof as int == 0 { return option::none::<object_file>; }
- return option::some({llof: llof, dtor: @object_file_res(llof)});
+ if llof as int == 0 { return option::None::<object_file>; }
+ return option::Some({llof: llof, dtor: @object_file_res(llof)});
}
/* Memory-managed interface to section iterators. */
let cstore = e.cstore;
let foreign_name =
match attr::first_attr_value_str_by_name(i.attrs, ~"link_name") {
- some(nn) => {
+ Some(nn) => {
if nn == ~"" {
e.diag.span_fatal(
i.span,
}
nn
}
- none => *e.intr.get(i.ident)
+ None => *e.intr.get(i.ident)
};
let mut already_added = false;
if vec::len(attr::find_attrs_by_name(i.attrs, ~"nolink")) == 0u {
}
for link_args.each |a| {
match attr::get_meta_item_value_str(attr::attr_meta(a)) {
- some(linkarg) => {
+ Some(linkarg) => {
cstore::add_used_link_args(cstore, linkarg);
}
- none => {/* fallthrough */ }
+ None => {/* fallthrough */ }
}
}
}
}
fn existing_match(e: env, metas: ~[@ast::meta_item], hash: ~str) ->
- option<int> {
+ Option<int> {
for e.crate_cache.each |c| {
if loader::metadata_matches(*c.metas, metas)
&& (hash.is_empty() || c.hash == hash) {
- return some(c.cnum);
+ return Some(c.cnum);
}
}
- return none;
+ return None;
}
fn resolve_crate(e: env, ident: ast::ident, metas: ~[@ast::meta_item],
let metas = metas_with_ident(*e.intr.get(ident), metas);
match existing_match(e, metas, hash) {
- none => {
+ None => {
let load_ctxt: loader::ctxt = {
diag: e.diag,
filesearch: e.filesearch,
let cname =
match attr::last_meta_item_value_str_by_name(metas, ~"name") {
- option::some(v) => v,
- option::none => *e.intr.get(ident)
+ option::Some(v) => v,
+ option::None => *e.intr.get(ident)
};
let cmeta = @{name: cname, data: cdata,
cnum_map: cnum_map, cnum: cnum};
cstore::add_used_crate_file(cstore, &cfilename);
return cnum;
}
- some(cnum) => {
+ Some(cnum) => {
return cnum;
}
}
*e.intr.get(dep.name), dep.vers, dep.hash);
match existing_match(e, metas_with_ident(*e.intr.get(cname), cmetas),
dep.hash) {
- some(local_cnum) => {
+ Some(local_cnum) => {
debug!("already have it");
// We've already seen this crate
cnum_map.insert(extrn_cnum, local_cnum);
}
- none => {
+ None => {
debug!("need to load it");
// This is a new one so we've got to load it
// FIXME (#2404): Need better error reporting than just a bogus
import syntax::ast_util;
import syntax::ast_map;
import middle::ty;
-import option::{some, none};
+import option::{Some, None};
import syntax::diagnostic::span_handler;
import syntax::diagnostic::expect;
import ast_util::dummy_sp;
}
fn get_impls_for_mod(cstore: cstore::cstore, def: ast::def_id,
- name: option<ast::ident>)
+ name: Option<ast::ident>)
-> @~[@decoder::_impl] {
let cdata = cstore::get_crate_data(cstore, def.crate);
do decoder::get_impls_for_mod(cstore.intr, cdata, def.node, name) |cnum| {
}
fn get_method_names_if_trait(cstore: cstore::cstore, def: ast::def_id)
- -> option<@DVec<(ast::ident, ast::self_ty_)>> {
+ -> Option<@DVec<(ast::ident, ast::self_ty_)>> {
let cdata = cstore::get_crate_data(cstore, def.crate);
return decoder::get_method_names_if_trait(cstore.intr, cdata, def.node);
}
fn get_region_param(cstore: metadata::cstore::cstore,
- def: ast::def_id) -> option<ty::region_variance> {
+ def: ast::def_id) -> Option<ty::region_variance> {
let cdata = cstore::get_crate_data(cstore, def.crate);
return decoder::get_region_param(cdata, def.node);
}
debug!("got field data %?", the_field);
let ty = decoder::item_type(def, the_field, tcx, cdata);
return {bounds: @~[],
- region_param: none,
+ region_param: None,
ty: ty};
}
/* If def names a class with a dtor, return it. Otherwise, return none. */
fn class_dtor(cstore: cstore::cstore, def: ast::def_id)
- -> option<ast::def_id> {
+ -> Option<ast::def_id> {
let cdata = cstore::get_crate_data(cstore, def.crate);
decoder::class_dtor(cdata, def.node)
}
}
fn find_use_stmt_cnum(cstore: cstore,
- use_id: ast::node_id) -> option<ast::crate_num> {
+ use_id: ast::node_id) -> Option<ast::crate_num> {
p(cstore).use_crate_map.find(use_id)
}
// build.
fn lookup_hash(d: ebml::doc, eq_fn: fn(x:&[u8]) -> bool, hash: uint) ->
- option<ebml::doc> {
+ Option<ebml::doc> {
let index = ebml::get_doc(d, tag_index);
let table = ebml::get_doc(index, tag_index_table);
let hash_pos = table.start + hash % 256u * 4u;
for ebml::tagged_docs(bucket, belt) |elt| {
let pos = io::u64_from_be_bytes(*elt.data, elt.start, 4u) as uint;
if eq_fn(vec::view(*elt.data, elt.start + 4u, elt.end)) {
- return some(ebml::doc_at(d.data, pos).doc);
+ return Some(ebml::doc_at(d.data, pos).doc);
}
};
- none
+ None
}
-fn maybe_find_item(item_id: int, items: ebml::doc) -> option<ebml::doc> {
+fn maybe_find_item(item_id: int, items: ebml::doc) -> Option<ebml::doc> {
fn eq_item(bytes: &[u8], item_id: int) -> bool {
return io::u64_from_be_bytes(vec::view(bytes, 0u, 4u), 0u, 4u) as int
== item_id;
fn lookup_item(item_id: int, data: @~[u8]) -> ebml::doc {
let items = ebml::get_doc(ebml::doc(data), tag_items);
match maybe_find_item(item_id, items) {
- none => fail(fmt!("lookup_item: id not found: %d", item_id)),
- some(d) => d
+ None => fail(fmt!("lookup_item: id not found: %d", item_id)),
+ Some(d) => d
}
}
return str::from_bytes(ebml::doc_data(sym));
}
-fn item_parent_item(d: ebml::doc) -> option<ast::def_id> {
+fn item_parent_item(d: ebml::doc) -> Option<ast::def_id> {
for ebml::tagged_docs(d, tag_items_data_parent_item) |did| {
- return some(ebml::with_doc_data(did, |d| parse_def_id(d)));
+ return Some(ebml::with_doc_data(did, |d| parse_def_id(d)));
}
- none
+ None
}
fn item_def_id(d: ebml::doc, cdata: cmd) -> ast::def_id {
})
}
-fn variant_disr_val(d: ebml::doc) -> option<int> {
+fn variant_disr_val(d: ebml::doc) -> Option<int> {
do option::chain(ebml::maybe_get_doc(d, tag_disr_val)) |val_doc| {
int::parse_buf(ebml::doc_data(val_doc), 10u)
}
@bounds
}
-fn item_ty_region_param(item: ebml::doc) -> option<ty::region_variance> {
+fn item_ty_region_param(item: ebml::doc) -> Option<ty::region_variance> {
ebml::maybe_get_doc(item, tag_region_param).map(|doc| {
let d = ebml::ebml_deserializer(doc);
ty::deserialize_region_variance(d)
ForeignMod => dl_def(ast::def_foreign_mod(did)),
Variant => {
match item_parent_item(item) {
- some(t) => {
+ Some(t) => {
let tid = {crate: cnum, node: t.node};
dl_def(ast::def_variant(tid, did))
}
- none => fail ~"item_to_def_like: enum item has no parent"
+ None => fail ~"item_to_def_like: enum item has no parent"
}
}
Trait | Enum => dl_def(ast::def_ty(did)),
}
fn get_region_param(cdata: cmd, id: ast::node_id)
- -> option<ty::region_variance> {
+ -> Option<ty::region_variance> {
let item = lookup_item(id, cdata.data);
return item_ty_region_param(item);
fn get_impl_method(intr: ident_interner, cdata: cmd, id: ast::node_id,
name: ast::ident) -> ast::def_id {
let items = ebml::get_doc(ebml::doc(cdata.data), tag_items);
- let mut found = none;
+ let mut found = None;
for ebml::tagged_docs(find_item(id, items), tag_item_impl_method) |mid| {
let m_did = ebml::with_doc_data(mid, |d| parse_def_id(d));
if item_name(intr, find_item(m_did.node, items)) == name {
- found = some(translate_def_id(cdata, m_did));
+ found = Some(translate_def_id(cdata, m_did));
}
}
option::get(found)
fn get_class_method(intr: ident_interner, cdata: cmd, id: ast::node_id,
name: ast::ident) -> ast::def_id {
let items = ebml::get_doc(ebml::doc(cdata.data), tag_items);
- let mut found = none;
+ let mut found = None;
let cls_items = match maybe_find_item(id, items) {
- some(it) => it,
- none => fail (fmt!("get_class_method: class id not found \
+ Some(it) => it,
+ None => fail (fmt!("get_class_method: class id not found \
when looking up method %s", *intr.get(name)))
};
for ebml::tagged_docs(cls_items, tag_item_trait_method) |mid| {
let m_did = item_def_id(mid, cdata);
if item_name(intr, mid) == name {
- found = some(m_did);
+ found = Some(m_did);
}
}
match found {
- some(found) => found,
- none => fail (fmt!("get_class_method: no method named %s",
+ Some(found) => found,
+ None => fail (fmt!("get_class_method: no method named %s",
*intr.get(name)))
}
}
-fn class_dtor(cdata: cmd, id: ast::node_id) -> option<ast::def_id> {
+fn class_dtor(cdata: cmd, id: ast::node_id) -> Option<ast::def_id> {
let items = ebml::get_doc(ebml::doc(cdata.data), tag_items);
- let mut found = none;
+ let mut found = None;
let cls_items = match maybe_find_item(id, items) {
- some(it) => it,
- none => fail (fmt!("class_dtor: class id not found \
+ Some(it) => it,
+ None => fail (fmt!("class_dtor: class id not found \
when looking up dtor for %d", id))
};
for ebml::tagged_docs(cls_items, tag_item_dtor) |doc| {
let doc1 = ebml::get_doc(doc, tag_def_id);
let did = ebml::with_doc_data(doc1, |d| parse_def_id(d));
- found = some(translate_def_id(cdata, did));
+ found = Some(translate_def_id(cdata, did));
};
found
}
// Get the item.
match maybe_find_item(def_id.node, items) {
- none => {}
- some(item_doc) => {
+ None => {}
+ Some(item_doc) => {
// Construct the def for this item.
let def_like = item_to_def_like(item_doc,
def_id,
cdata: cstore::crate_metadata,
tcx: ty::ctxt,
path: ast_map::path,
- par_doc: ebml::doc) -> option<ast::inlined_item>;
+ par_doc: ebml::doc) -> Option<ast::inlined_item>;
fn maybe_get_item_ast(intr: ident_interner, cdata: cmd, tcx: ty::ctxt,
id: ast::node_id,
let item_doc = lookup_item(id, cdata.data);
let path = vec::init(item_path(intr, item_doc));
match decode_inlined_item(cdata, tcx, path, item_doc) {
- some(ii) => csearch::found(ii),
- none => {
+ Some(ii) => csearch::found(ii),
+ None => {
match item_parent_item(item_doc) {
- some(did) => {
+ Some(did) => {
let did = translate_def_id(cdata, did);
let parent_item = lookup_item(did.node, cdata.data);
match decode_inlined_item(cdata, tcx, path,
parent_item) {
- some(ii) => csearch::found_parent(did, ii),
- none => csearch::not_found
+ Some(ii) => csearch::found_parent(did, ii),
+ None => csearch::not_found
}
}
- none => csearch::not_found
+ None => csearch::not_found
}
}
}
_ => { /* Nullary enum variant. */ }
}
match variant_disr_val(item) {
- some(val) => { disr_val = val; }
+ Some(val) => { disr_val = val; }
_ => { /* empty */ }
}
vec::push(infos, @{args: arg_tys, ctor_ty: ctor_ty, name: name,
}
fn get_impls_for_mod(intr: ident_interner, cdata: cmd,
- m_id: ast::node_id, name: option<ast::ident>,
+ m_id: ast::node_id, name: Option<ast::ident>,
get_cdata: fn(ast::crate_num) -> cmd)
-> @~[@_impl] {
let impl_data = impl_cdata.data;
let item = lookup_item(local_did.node, impl_data);
let nm = item_name(intr, item);
- if match name { some(n) => { n == nm } none => { true } } {
+ if match name { Some(n) => { n == nm } None => { true } } {
let base_tps = item_ty_param_count(item);
vec::push(result, @{
did: local_did, ident: nm,
// annoying way with get_trait_methods.
fn get_method_names_if_trait(intr: ident_interner, cdata: cmd,
node_id: ast::node_id)
- -> option<@DVec<(ast::ident, ast::self_ty_)>> {
+ -> Option<@DVec<(ast::ident, ast::self_ty_)>> {
let item = lookup_item(node_id, cdata.data);
if item_family(item) != Trait {
- return none;
+ return None;
}
let resulting_methods = @dvec();
resulting_methods.push(
(item_name(intr, method), get_self_ty(method)));
}
- return some(resulting_methods);
+ return Some(resulting_methods);
}
fn get_item_attrs(cdata: cmd,
fn describe_def(items: ebml::doc, id: ast::def_id) -> ~str {
if id.crate != ast::local_crate { return ~"external"; }
let it = match maybe_find_item(id.node, items) {
- some(it) => it,
- none => fail (fmt!("describe_def: item not found %?", id))
+ Some(it) => it,
+ None => fail (fmt!("describe_def: item not found %?", id))
};
return item_family_to_str(item_family(it));
}
fn get_attributes(md: ebml::doc) -> ~[ast::attribute] {
let mut attrs: ~[ast::attribute] = ~[];
match ebml::maybe_get_doc(md, tag_attributes) {
- option::some(attrs_d) => {
+ option::Some(attrs_d) => {
for ebml::tagged_docs(attrs_d, tag_attribute) |attr_doc| {
let meta_items = get_meta_items(attr_doc);
// Currently it's only possible to have a single meta item on
span: ast_util::dummy_sp()});
};
}
- option::none => ()
+ option::None => ()
}
return attrs;
}
let attrs = decoder::get_crate_attributes(data);
return match attr::last_meta_item_value_str_by_name(
attr::find_linkage_metas(attrs), ~"vers") {
- some(ver) => ver,
- none => ~"0.0"
+ Some(ver) => ver,
+ None => ~"0.0"
};
}
}
match cdata.cnum_map.find(did.crate) {
- option::some(n) => return {crate: n, node: did.node},
- option::none => fail ~"didn't find a crate in the cnum_map"
+ option::Some(n) => return {crate: n, node: did.node},
+ option::None => fail ~"didn't find a crate in the cnum_map"
}
}
fn encode_symbol(ecx: @encode_ctxt, ebml_w: ebml::writer, id: node_id) {
ebml_w.start_tag(tag_items_data_item_symbol);
let sym = match ecx.item_symbols.find(id) {
- some(x) => x,
- none => {
+ Some(x) => x,
+ None => {
ecx.diag.handler().bug(
fmt!("encode_symbol: id not found %d", id));
}
// Encode the reexports of this module.
debug!("(encoding info for module) encoding reexports for %d", id);
match ecx.reexports2.find(id) {
- some(exports) => {
+ Some(exports) => {
debug!("(encoding info for module) found reexports for %d", id);
for exports.each |exp| {
debug!("(encoding info for module) reexport '%s' for %d",
ebml_w.end_tag();
}
}
- none => {
+ None => {
debug!("(encoding info for module) found no reexports for %d",
id);
}
// This is for encoding info for ctors and dtors
fn encode_info_for_ctor(ecx: @encode_ctxt, ebml_w: ebml::writer,
id: node_id, ident: ident, path: ast_map::path,
- item: option<inlined_item>, tps: ~[ty_param]) {
+ item: Option<inlined_item>, tps: ~[ty_param]) {
ebml_w.start_tag(tag_items_data_item);
encode_name(ecx, ebml_w, ident);
encode_def_id(ebml_w, local_def(id));
encode_type(ecx, ebml_w, its_ty);
encode_path(ecx, ebml_w, path, ast_map::path_name(ident));
match item {
- some(it) => {
+ Some(it) => {
ecx.encode_inlined_item(ecx, ebml_w, path, it);
}
- none => {
+ None => {
encode_symbol(ecx, ebml_w, id);
}
}
ecx.tcx.sess.str_of(item.ident) +
~"_dtor"),
path, if tps.len() > 0u {
- some(ii_dtor(dtor, item.ident, tps,
+ Some(ii_dtor(dtor, item.ident, tps,
local_def(item.id))) }
- else { none }, tps);
+ else { None }, tps);
}
/* Index the class*/
encode_def_id(ebml_w, local_def(item.id));
match struct_def.ctor {
- none => encode_family(ebml_w, 'S'),
- some(_) => encode_family(ebml_w, 'C')
+ None => encode_family(ebml_w, 'S'),
+ Some(_) => encode_family(ebml_w, 'C')
}
encode_type_param_bounds(ebml_w, ecx, tps);
});
encode_info_for_ctor(ecx, ebml_w, ctor.node.id, item.ident,
path, if tps.len() > 0u {
- some(ii_ctor(ctor, item.ident, tps,
+ Some(ii_ctor(ctor, item.ident, tps,
local_def(item.id))) }
- else { none }, tps);
+ else { None }, tps);
}
}
item_impl(tps, traits, _, methods) => {
export get_cargo_root_nearest;
export libdir;
-type pick<T> = fn(path: &Path) -> option<T>;
+type pick<T> = fn(path: &Path) -> Option<T>;
-fn pick_file(file: Path, path: &Path) -> option<Path> {
- if path.file_path() == file { option::some(copy *path) }
- else { option::none }
+fn pick_file(file: Path, path: &Path) -> Option<Path> {
+ if path.file_path() == file { option::Some(copy *path) }
+ else { option::None }
}
trait filesearch {
fn get_target_lib_file_path(file: &Path) -> Path;
}
-fn mk_filesearch(maybe_sysroot: option<Path>,
+fn mk_filesearch(maybe_sysroot: Option<Path>,
target_triple: &str,
addl_lib_search_paths: ~[Path]) -> filesearch {
type filesearch_impl = {sysroot: Path,
target_triple: str::from_slice(target_triple)} as filesearch
}
-fn search<T: copy>(filesearch: filesearch, pick: pick<T>) -> option<T> {
- let mut rslt = none;
+fn search<T: copy>(filesearch: filesearch, pick: pick<T>) -> Option<T> {
+ let mut rslt = None;
for filesearch.lib_search_paths().each |lib_search_path| {
debug!("searching %s", lib_search_path.to_str());
for os::list_dir_path(&lib_search_path).each |path| {
fn get_default_sysroot() -> Path {
match os::self_exe_path() {
- option::some(p) => p.pop(),
- option::none => fail ~"can't determine value for sysroot"
+ option::Some(p) => p.pop(),
+ option::None => fail ~"can't determine value for sysroot"
}
}
-fn get_sysroot(maybe_sysroot: option<Path>) -> Path {
+fn get_sysroot(maybe_sysroot: Option<Path>) -> Path {
match maybe_sysroot {
- option::some(sr) => sr,
- option::none => get_default_sysroot()
+ option::Some(sr) => sr,
+ option::None => get_default_sysroot()
}
}
fn get_cargo_root() -> result<Path, ~str> {
match os::getenv(~"CARGO_ROOT") {
- some(_p) => result::ok(Path(_p)),
- none => match os::homedir() {
- some(_q) => result::ok(_q.push(".cargo")),
- none => result::err(~"no CARGO_ROOT or home directory")
+ Some(_p) => result::ok(Path(_p)),
+ None => match os::homedir() {
+ Some(_q) => result::ok(_q.push(".cargo")),
+ None => result::err(~"no CARGO_ROOT or home directory")
}
}
}
fn load_library_crate(cx: ctxt) -> {ident: ~str, data: @~[u8]} {
match find_library_crate(cx) {
- some(t) => return t,
- none => {
+ Some(t) => return t,
+ None => {
cx.diag.span_fatal(
cx.span, fmt!("can't find crate for `%s`",
*cx.intr.get(cx.ident)));
}
}
-fn find_library_crate(cx: ctxt) -> option<{ident: ~str, data: @~[u8]}> {
+fn find_library_crate(cx: ctxt) -> Option<{ident: ~str, data: @~[u8]}> {
attr::require_unique_names(cx.diag, cx.metas);
find_library_crate_aux(cx, libname(cx), cx.filesearch)
}
fn find_library_crate_aux(cx: ctxt,
nn: {prefix: ~str, suffix: ~str},
filesearch: filesearch::filesearch) ->
- option<{ident: ~str, data: @~[u8]}> {
+ Option<{ident: ~str, data: @~[u8]}> {
let crate_name = crate_name_from_metas(cx.metas);
let prefix: ~str = nn.prefix + crate_name + ~"-";
let suffix: ~str = nn.suffix;
if !(str::starts_with(f, prefix) && str::ends_with(f, suffix)) {
debug!("skipping %s, doesn't look like %s*%s", path.to_str(),
prefix, suffix);
- option::none::<()>
+ option::None::<()>
} else {
debug!("%s is a candidate", path.to_str());
match get_metadata_section(cx.os, path) {
- option::some(cvec) => {
+ option::Some(cvec) => {
if !crate_matches(cvec, cx.metas, cx.hash) {
debug!("skipping %s, metadata doesn't match",
path.to_str());
- option::none::<()>
+ option::None::<()>
} else {
debug!("found %s with matching metadata", path.to_str());
vec::push(matches, {ident: path.to_str(), data: cvec});
- option::none::<()>
+ option::None::<()>
}
}
_ => {
debug!("could not load metadata for %s", path.to_str());
- option::none::<()>
+ option::None::<()>
}
}
}
});
if matches.is_empty() {
- none
+ None
} else if matches.len() == 1u {
- some(matches[0])
+ Some(matches[0])
} else {
cx.diag.span_err(
cx.span, fmt!("multiple matching crates for `%s`", crate_name));
note_linkage_attrs(cx.intr, cx.diag, attrs);
}
cx.diag.handler().abort_if_errors();
- none
+ None
}
}
fn crate_name_from_metas(metas: ~[@ast::meta_item]) -> ~str {
let name_items = attr::find_meta_items_by_name(metas, ~"name");
match vec::last_opt(name_items) {
- some(i) => {
+ Some(i) => {
match attr::get_meta_item_value_str(i) {
- some(n) => n,
+ Some(n) => n,
// FIXME (#2406): Probably want a warning here since the user
// is using the wrong type of meta item.
_ => fail
}
}
- none => fail ~"expected to find the crate name"
+ None => fail ~"expected to find the crate name"
}
}
}
fn get_metadata_section(os: os,
- filename: &Path) -> option<@~[u8]> unsafe {
+ filename: &Path) -> Option<@~[u8]> unsafe {
let mb = str::as_c_str(filename.to_str(), |buf| {
llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf)
});
- if mb as int == 0 { return option::none::<@~[u8]>; }
+ if mb as int == 0 { return option::None::<@~[u8]>; }
let of = match mk_object_file(mb) {
- option::some(of) => of,
- _ => return option::none::<@~[u8]>
+ option::Some(of) => of,
+ _ => return option::None::<@~[u8]>
};
let si = mk_section_iter(of.llof);
while llvm::LLVMIsSectionIteratorAtEnd(of.llof, si.llsi) == False {
let csz = llvm::LLVMGetSectionSize(si.llsi) as uint;
unsafe {
let cvbuf: *u8 = unsafe::reinterpret_cast(cbuf);
- return some(@vec::unsafe::from_buf(cvbuf, csz));
+ return Some(@vec::unsafe::from_buf(cvbuf, csz));
}
}
llvm::LLVMMoveToNextSection(si.llsi);
}
- return option::none::<@~[u8]>;
+ return option::None::<@~[u8]>;
}
fn meta_section_name(os: os) -> ~str {
fn list_file_metadata(intr: ident_interner,
os: os, path: &Path, out: io::Writer) {
match get_metadata_section(os, path) {
- option::some(bytes) => decoder::list_crate_metadata(intr, bytes, out),
- option::none => {
+ option::Some(bytes) => decoder::list_crate_metadata(intr, bytes, out),
+ option::None => {
out.write_str(~"could not find metadata in "
+ path.to_str() + ~".\n");
}
if c == '(' {
return @{span: ast_util::dummy_sp(),
global: false, idents: idents,
- rp: none, types: ~[]};
+ rp: None, types: ~[]};
} else { vec::push(idents, parse_ident_(st, is_last)); }
}
}
}
}
-fn parse_opt<T>(st: @pstate, f: fn() -> T) -> option<T> {
+fn parse_opt<T>(st: @pstate, f: fn() -> T) -> Option<T> {
match next(st) {
- 'n' => none,
- 's' => some(f()),
+ 'n' => None,
+ 's' => Some(f()),
_ => fail ~"parse_opt: bad input"
}
}
let len = parse_hex(st);
assert (next(st) == '#');
match st.tcx.rcache.find({cnum: st.crate, pos: pos, len: len}) {
- some(tt) => return tt,
- none => {
+ Some(tt) => return tt,
+ None => {
let ps = @{pos: pos with *st};
let tt = parse_ty(ps, conv);
st.tcx.rcache.insert({cnum: st.crate, pos: pos, len: len}, tt);
let def_part = vec::view(buf, colon_idx + 1u, len);
let crate_num = match uint::parse_buf(crate_part, 10u) {
- some(cn) => cn as int,
- none => fail (fmt!("internal error: parse_def_id: crate number \
+ Some(cn) => cn as int,
+ None => fail (fmt!("internal error: parse_def_id: crate number \
expected, but found %?", crate_part))
};
let def_num = match uint::parse_buf(def_part, 10u) {
- some(dn) => dn as int,
- none => fail (fmt!("internal error: parse_def_id: id expected, but \
+ Some(dn) => dn as int,
+ None => fail (fmt!("internal error: parse_def_id: id expected, but \
found %?", def_part))
};
return {crate: crate_num, node: def_num};
match cx.abbrevs {
ac_no_abbrevs => {
let result_str = match cx.tcx.short_names_cache.find(t) {
- some(s) => *s,
- none => {
+ Some(s) => *s,
+ None => {
let buf = io::mem_buffer();
enc_sty(io::mem_buffer_writer(buf), cx, ty::get(t).struct);
cx.tcx.short_names_cache.insert(t, @io::mem_buffer_str(buf));
}
ac_use_abbrevs(abbrevs) => {
match abbrevs.find(t) {
- some(a) => { w.write_str(*a.s); return; }
- none => {
+ Some(a) => { w.write_str(*a.s); return; }
+ None => {
let pos = w.tell();
match ty::type_def_id(t) {
- some(def_id) => {
+ Some(def_id) => {
// Do not emit node ids that map to unexported names. Those
// are not helpful.
if def_id.crate != local_crate ||
enc_ty(w, cx, mt.ty);
}
-fn enc_opt<T>(w: io::Writer, t: option<T>, enc_f: fn(T)) {
+fn enc_opt<T>(w: io::Writer, t: Option<T>, enc_f: fn(T)) {
match t {
- none => w.write_char('n'),
- some(v) => {
+ None => w.write_char('n'),
+ Some(v) => {
w.write_char('s');
enc_f(v);
}
tcx: ty::ctxt,
maps: maps,
path: ast_map::path,
- par_doc: ebml::doc) -> option<ast::inlined_item> {
+ par_doc: ebml::doc) -> Option<ast::inlined_item> {
let dcx = @{cdata: cdata, tcx: tcx, maps: maps};
match par_doc.opt_child(c::tag_ast) {
- none => none,
- some(ast_doc) => {
+ None => None,
+ Some(ast_doc) => {
debug!("> Decoding inlined fn: %s::?",
ast_map::path_to_str(path, tcx.sess.parse_sess.interner));
let ast_dsr = ebml::ebml_deserializer(ast_doc);
}
_ => { }
}
- some(ii)
+ Some(ii)
}
}
}
trait doc_decoder_helpers {
fn as_int() -> int;
- fn opt_child(tag: c::astencode_tag) -> option<ebml::doc>;
+ fn opt_child(tag: c::astencode_tag) -> Option<ebml::doc>;
}
impl ebml::doc: doc_decoder_helpers {
fn as_int() -> int { ebml::doc_as_u64(self) as int }
- fn opt_child(tag: c::astencode_tag) -> option<ebml::doc> {
+ fn opt_child(tag: c::astencode_tag) -> Option<ebml::doc> {
ebml::maybe_get_doc(self, tag as uint)
}
}
#[cfg(test)]
fn mk_ctxt() -> fake_ext_ctxt {
- parse::new_parse_sess(none) as fake_ext_ctxt
+ parse::new_parse_sess(None) as fake_ext_ctxt
}
#[cfg(test)]
In other cases, like an enum on the stack, the memory cannot be freed
but its type can change:
- let mut x = some(5);
+ let mut x = Some(5);
match x {
- some(ref y) => { ... }
- none => { ... }
+ Some(ref y) => { ... }
+ None => { ... }
}
Here as before, the pointer `y` would be invalidated if we were to
impl check_loan_ctxt {
fn tcx() -> ty::ctxt { self.bccx.tcx }
- fn purity(scope_id: ast::node_id) -> option<purity_cause> {
+ fn purity(scope_id: ast::node_id) -> Option<purity_cause> {
let default_purity = match self.declared_purity {
// an unsafe declaration overrides all
- ast::unsafe_fn => return none,
+ ast::unsafe_fn => return None,
// otherwise, remember what was declared as the
// default, but we must scan for requirements
// imposed by the borrow check
- ast::pure_fn => some(pc_pure_fn),
- ast::extern_fn | ast::impure_fn => none
+ ast::pure_fn => Some(pc_pure_fn),
+ ast::extern_fn | ast::impure_fn => None
};
// scan to see if this scope or any enclosing scope requires
let pure_map = self.req_maps.pure_map;
loop {
match pure_map.find(scope_id) {
- none => (),
- some(e) => return some(pc_cmt(e))
+ None => (),
+ Some(e) => return Some(pc_cmt(e))
}
match region_map.find(scope_id) {
- none => return default_purity,
- some(next_scope_id) => scope_id = next_scope_id
+ None => return default_purity,
+ Some(next_scope_id) => scope_id = next_scope_id
}
}
}
}
match region_map.find(scope_id) {
- none => return,
- some(next_scope_id) => scope_id = next_scope_id,
+ None => return,
+ Some(next_scope_id) => scope_id = next_scope_id,
}
}
}
// overloaded operators the callee has an id but no expr.
// annoying.
fn check_pure_callee_or_arg(pc: purity_cause,
- opt_expr: option<@ast::expr>,
+ opt_expr: Option<@ast::expr>,
callee_id: ast::node_id,
callee_span: span) {
let tcx = self.tcx();
// (d) B is not a fn.
match opt_expr {
- some(expr) => {
+ Some(expr) => {
match expr.node {
ast::expr_path(_) if pc == pc_pure_fn => {
let def = self.tcx().def_map.get(expr.id);
_ => ()
}
}
- none => ()
+ None => ()
}
let callee_ty = ty::node_id_to_type(tcx, callee_id);
fn check_for_conflicting_loans(scope_id: ast::node_id) {
let new_loanss = match self.req_maps.req_loan_map.find(scope_id) {
- none => return,
- some(loanss) => loanss
+ None => return,
+ Some(loanss) => loanss
};
let par_scope_id = self.tcx().region_map.get(scope_id);
// assigned, because it is uniquely tied to this function and
// is not visible from the outside
match self.purity(ex.id) {
- none => (),
- some(pc @ pc_cmt(_)) => {
+ None => (),
+ Some(pc @ pc_cmt(_)) => {
// Subtle: Issue #3162. If we are enforcing purity
// because there is a reference to aliasable, mutable data
// that we require to be immutable, we can't allow writes
self.report_purity_error(
pc, ex.span, at.ing_form(self.bccx.cmt_to_str(cmt)));
}
- some(pc_pure_fn) => {
+ Some(pc_pure_fn) => {
if cmt.lp.is_none() {
self.report_purity_error(
pc_pure_fn, ex.span,
// is inherited from the thing that the component is embedded
// within, then we have to check whether that thing has been
// loaned out as immutable! An example:
- // let mut x = {f: some(3)};
+ // let mut x = {f: Some(3)};
// let y = &x; // x loaned out as immutable
// x.f = none; // changes type of y.f, which appears to be imm
match *lp {
// check for a conflicting loan:
let lp = match cmt.lp {
- none => return,
- some(lp) => lp
+ None => return,
+ Some(lp) => lp
};
for self.walk_loans_of(cmt.id, lp) |loan| {
self.bccx.span_err(
fn check_last_use(expr: @ast::expr) {
let cmt = self.bccx.cat_expr(expr);
let lp = match cmt.lp {
- none => return,
- some(lp) => lp
+ None => return,
+ Some(lp) => lp
};
for self.walk_loans_of(cmt.id, lp) |_loan| {
debug!("Removing last use entry %? due to outstanding loan",
}
fn check_call(expr: @ast::expr,
- callee: option<@ast::expr>,
+ callee: Option<@ast::expr>,
callee_id: ast::node_id,
callee_span: span,
args: ~[@ast::expr]) {
match self.purity(expr.id) {
- none => {}
- some(pc) => {
+ None => {}
+ Some(pc) => {
self.check_pure_callee_or_arg(
pc, callee, callee_id, callee_span);
for args.each |arg| {
self.check_pure_callee_or_arg(
- pc, some(arg), arg.id, arg.span);
+ pc, Some(arg), arg.id, arg.span);
}
}
}
&&self: check_loan_ctxt,
vt: visit::vt<check_loan_ctxt>) {
match local.node.init {
- some({op: ast::init_move, expr: expr}) => {
+ Some({op: ast::init_move, expr: expr}) => {
self.check_move_out(expr);
}
- some({op: ast::init_assign, _}) | none => {}
+ Some({op: ast::init_assign, _}) | None => {}
}
visit::visit_local(local, self, vt);
}
}
}
ast::expr_call(f, args, _) => {
- self.check_call(expr, some(f), f.id, f.span, args);
+ self.check_call(expr, Some(f), f.id, f.span, args);
}
ast::expr_index(_, rval) |
ast::expr_binary(_, _, rval)
if self.bccx.method_map.contains_key(expr.id) => {
self.check_call(expr,
- none,
+ None,
expr.callee_id,
expr.span,
~[rval]);
ast::expr_unary(*) | ast::expr_index(*)
if self.bccx.method_map.contains_key(expr.id) => {
self.check_call(expr,
- none,
+ None,
expr.callee_id,
expr.span,
~[]);
// fine).
//
match opt_deref_kind(arg_ty.ty) {
- some(deref_ptr(region_ptr(_))) |
- some(deref_ptr(unsafe_ptr)) => {
+ Some(deref_ptr(region_ptr(_))) |
+ Some(deref_ptr(unsafe_ptr)) => {
/* region pointers are (by induction) guaranteed */
/* unsafe pointers are the user's problem */
}
- some(deref_comp(_)) |
- none => {
+ Some(deref_comp(_)) |
+ None => {
/* not a pointer, no worries */
}
- some(deref_ptr(_)) => {
+ Some(deref_ptr(_)) => {
let arg_cmt = self.bccx.cat_borrow_of_expr(arg);
self.guarantee_valid(arg_cmt, m_const, scope_r);
}
// duration of the reference: if there is an attempt to move
// it within that scope, the loan will be detected and an
// error will be reported.
- some(_) => {
+ Some(_) => {
match self.bccx.loan(cmt, scope_r, req_mutbl) {
err(e) => { self.bccx.report(e); }
ok(loans) if loans.len() == 0 => {}
// also check that the mutability of the desired pointer
// matches with the actual mutability (but if an immutable
// pointer is desired, that is ok as long as we are pure)
- none => {
+ None => {
let result: bckres<preserve_condition> = {
do self.check_mutbl(req_mutbl, cmt).chain |pc1| {
do self.bccx.preserve(cmt, scope_r,
fn add_loans(scope_id: ast::node_id, loans: @DVec<loan>) {
match self.req_maps.req_loan_map.find(scope_id) {
- some(l) => {
+ Some(l) => {
(*l).push(loans);
}
- none => {
+ None => {
self.req_maps.req_loan_map.insert(
scope_id, @dvec::from_vec(~[mut loans]));
}
// As an example, consider this scenario:
//
// let mut x = @some(3);
- // match *x { some(y) {...} none {...} }
+ // match *x { Some(y) {...} none {...} }
//
// Technically, the value `x` need only be rooted
// in the `some` arm. However, we evaluate `x` in trans
type capture_var = {
def: ast::def, // Variable being accessed free
span: span, // Location of access or cap item
- cap_item: option<ast::capture_item>, // Capture item, if any
+ cap_item: Option<ast::capture_item>, // Capture item, if any
mode: capture_mode // How variable is being accessed
};
if vec::any(*freevars, |fv| fv.def == cap_def ) {
cap_map.insert(cap_def_id, {def:cap_def,
span: cap_item.span,
- cap_item: some(cap_item),
+ cap_item: Some(cap_item),
mode:cap_move});
} else {
cap_map.insert(cap_def_id, {def:cap_def,
span: cap_item.span,
- cap_item: some(cap_item),
+ cap_item: Some(cap_item),
mode:cap_drop});
}
} else {
if vec::any(*freevars, |fv| fv.def == cap_def ) {
cap_map.insert(cap_def_id, {def:cap_def,
span: cap_item.span,
- cap_item: some(cap_item),
+ cap_item: Some(cap_item),
mode:cap_copy});
}
}
do vec::iter(*freevars) |fvar| {
let fvar_def_id = ast_util::def_id_of_def(fvar.def).node;
match cap_map.find(fvar_def_id) {
- option::some(_) => { /* was explicitly named, do nothing */ }
- option::none => {
+ option::Some(_) => { /* was explicitly named, do nothing */ }
+ option::None => {
cap_map.insert(fvar_def_id, {def:fvar.def,
span: fvar.span,
- cap_item: none,
+ cap_item: None,
mode:implicit_mode});
}
}
fn raw_pat(p: @pat) -> @pat {
match p.node {
- pat_ident(_, _, some(s)) => { raw_pat(s) }
+ pat_ident(_, _, Some(s)) => { raw_pat(s) }
_ => { p }
}
}
assert(pats.is_not_empty());
let ext = match is_useful(tcx, vec::map(pats, |p| ~[p]), ~[wild()]) {
not_useful => return, // This is good, wildcard pattern isn't reachable
- useful_ => none,
+ useful_ => None,
useful(ty, ctor) => {
match ty::get(ty).struct {
ty::ty_bool => {
match ctor {
- val(const_bool(true)) => some(~"true"),
- val(const_bool(false)) => some(~"false"),
- _ => none
+ val(const_bool(true)) => Some(~"true"),
+ val(const_bool(false)) => Some(~"false"),
+ _ => None
}
}
ty::ty_enum(id, _) => {
_ => fail ~"check_exhaustive: non-variant ctor" };
match vec::find(*ty::enum_variants(tcx, id),
|v| v.id == vid) {
- some(v) => some(tcx.sess.str_of(v.name)),
- none => fail ~"check_exhaustive: bad variant in ctor"
+ Some(v) => Some(tcx.sess.str_of(v.name)),
+ None => fail ~"check_exhaustive: bad variant in ctor"
}
}
- _ => none
+ _ => None
}
}
};
let msg = ~"non-exhaustive patterns" + match ext {
- some(s) => ~": " + s + ~" not covered",
- none => ~""
+ Some(s) => ~": " + s + ~" not covered",
+ None => ~""
};
tcx.sess.span_err(sp, msg);
}
if m.len() == 0u { return useful_; }
if m[0].len() == 0u { return not_useful; }
let real_pat = match vec::find(m, |r| r[0].id != 0) {
- some(r) => r[0], none => v[0]
+ Some(r) => r[0], None => v[0]
};
let left_ty = if real_pat.id == 0 { ty::mk_nil(tcx) }
else { ty::node_id_to_type(tcx, real_pat.id) };
match pat_ctor_id(tcx, v[0]) {
- none => {
+ None => {
match missing_ctor(tcx, m, left_ty) {
- none => {
+ None => {
match ty::get(left_ty).struct {
ty::ty_bool => {
match is_useful_specialized(tcx, m, v, val(const_bool(true)),
}
}
}
- some(ctor) => {
+ Some(ctor) => {
match is_useful(tcx, vec::filter_map(m, |r| default(tcx, r) ),
vec::tail(v)) {
useful_ => useful(left_ty, ctor),
}
}
}
- some(v0_ctor) => {
+ Some(v0_ctor) => {
let arity = ctor_arity(tcx, v0_ctor, left_ty);
is_useful_specialized(tcx, m, v, v0_ctor, arity, left_ty)
}
}
}
-fn pat_ctor_id(tcx: ty::ctxt, p: @pat) -> option<ctor> {
+fn pat_ctor_id(tcx: ty::ctxt, p: @pat) -> Option<ctor> {
let pat = raw_pat(p);
match pat.node {
- pat_wild => { none }
+ pat_wild => { None }
pat_ident(_, _, _) | pat_enum(_, _) => {
match tcx.def_map.find(pat.id) {
- some(def_variant(_, id)) => some(variant(id)),
- _ => none
+ Some(def_variant(_, id)) => Some(variant(id)),
+ _ => None
}
}
- pat_lit(expr) => { some(val(eval_const_expr(tcx, expr))) }
+ pat_lit(expr) => { Some(val(eval_const_expr(tcx, expr))) }
pat_range(lo, hi) => {
- some(range(eval_const_expr(tcx, lo), eval_const_expr(tcx, hi)))
+ Some(range(eval_const_expr(tcx, lo), eval_const_expr(tcx, hi)))
}
pat_box(_) | pat_uniq(_) | pat_rec(_, _) | pat_tup(_) |
pat_struct(*) => {
- some(single)
+ Some(single)
}
}
}
pat_wild => { true }
pat_ident(_, _, _) => {
match tcx.def_map.find(pat.id) {
- some(def_variant(_, _)) => { false }
+ Some(def_variant(_, _)) => { false }
_ => { true }
}
}
}
}
-fn missing_ctor(tcx: ty::ctxt, m: matrix, left_ty: ty::t) -> option<ctor> {
+fn missing_ctor(tcx: ty::ctxt, m: matrix, left_ty: ty::t) -> Option<ctor> {
match ty::get(left_ty).struct {
ty::ty_box(_) | ty::ty_uniq(_) | ty::ty_tup(_) | ty::ty_rec(_) |
ty::ty_class(*) => {
for m.each |r| {
- if !is_wild(tcx, r[0]) { return none; }
+ if !is_wild(tcx, r[0]) { return None; }
}
- return some(single);
+ return Some(single);
}
ty::ty_enum(eid, _) => {
let mut found = ~[];
if found.len() != (*variants).len() {
for vec::each(*variants) |v| {
if !found.contains(variant(v.id)) {
- return some(variant(v.id));
+ return Some(variant(v.id));
}
}
fail;
- } else { none }
+ } else { None }
}
- ty::ty_nil => none,
+ ty::ty_nil => None,
ty::ty_bool => {
let mut true_found = false, false_found = false;
for m.each |r| {
match pat_ctor_id(tcx, r[0]) {
- none => (),
- some(val(const_bool(true))) => true_found = true,
- some(val(const_bool(false))) => false_found = true,
+ None => (),
+ Some(val(const_bool(true))) => true_found = true,
+ Some(val(const_bool(false))) => false_found = true,
_ => fail ~"impossible case"
}
}
- if true_found && false_found { none }
- else if true_found { some(val(const_bool(false))) }
- else { some(val(const_bool(true))) }
+ if true_found && false_found { None }
+ else if true_found { Some(val(const_bool(false))) }
+ else { Some(val(const_bool(true))) }
}
- _ => some(single)
+ _ => Some(single)
}
}
let id = match ctor { variant(id) => id,
_ => fail ~"impossible case" };
match vec::find(*ty::enum_variants(tcx, eid), |v| v.id == id ) {
- some(v) => v.args.len(),
- none => fail ~"impossible case"
+ Some(v) => v.args.len(),
+ None => fail ~"impossible case"
}
}
ty::ty_class(cid, _) => ty::lookup_class_fields(tcx, cid).len(),
}
fn specialize(tcx: ty::ctxt, r: ~[@pat], ctor_id: ctor, arity: uint,
- left_ty: ty::t) -> option<~[@pat]> {
+ left_ty: ty::t) -> Option<~[@pat]> {
let r0 = raw_pat(r[0]);
match r0.node {
- pat_wild => some(vec::append(vec::from_elem(arity, wild()),
+ pat_wild => Some(vec::append(vec::from_elem(arity, wild()),
vec::tail(r))),
pat_ident(_, _, _) => {
match tcx.def_map.find(r0.id) {
- some(def_variant(_, id)) => {
- if variant(id) == ctor_id { some(vec::tail(r)) }
- else { none }
+ Some(def_variant(_, id)) => {
+ if variant(id) == ctor_id { Some(vec::tail(r)) }
+ else { None }
}
- _ => some(vec::append(vec::from_elem(arity, wild()), vec::tail(r)))
+ _ => Some(vec::append(vec::from_elem(arity, wild()), vec::tail(r)))
}
}
pat_enum(_, args) => {
match tcx.def_map.get(r0.id) {
def_variant(_, id) if variant(id) == ctor_id => {
let args = match args {
- some(args) => args,
- none => vec::from_elem(arity, wild())
+ Some(args) => args,
+ None => vec::from_elem(arity, wild())
};
- some(vec::append(args, vec::tail(r)))
+ Some(vec::append(args, vec::tail(r)))
}
- def_variant(_, _) => none,
- _ => none
+ def_variant(_, _) => None,
+ _ => None
}
}
pat_rec(flds, _) => {
};
let args = vec::map(ty_flds, |ty_f| {
match vec::find(flds, |f| f.ident == ty_f.ident ) {
- some(f) => f.pat,
+ Some(f) => f.pat,
_ => wild()
}
});
- some(vec::append(args, vec::tail(r)))
+ Some(vec::append(args, vec::tail(r)))
}
pat_struct(_, flds, _) => {
// Grab the class data that we care about.
}
let args = vec::map(class_fields, |class_field| {
match vec::find(flds, |f| f.ident == class_field.ident ) {
- some(f) => f.pat,
+ Some(f) => f.pat,
_ => wild()
}
});
- some(vec::append(args, vec::tail(r)))
+ Some(vec::append(args, vec::tail(r)))
}
- pat_tup(args) => some(vec::append(args, vec::tail(r))),
- pat_box(a) | pat_uniq(a) => some(vec::append(~[a], vec::tail(r))),
+ pat_tup(args) => Some(vec::append(args, vec::tail(r))),
+ pat_box(a) | pat_uniq(a) => Some(vec::append(~[a], vec::tail(r))),
pat_lit(expr) => {
let e_v = eval_const_expr(tcx, expr);
let match_ = match ctor_id {
single => true,
_ => fail ~"type error"
};
- if match_ { some(vec::tail(r)) } else { none }
+ if match_ { Some(vec::tail(r)) } else { None }
}
pat_range(lo, hi) => {
let (c_lo, c_hi) = match ctor_id {
val(v) => (v, v),
range(lo, hi) => (lo, hi),
- single => return some(vec::tail(r)),
+ single => return Some(vec::tail(r)),
_ => fail ~"type error"
};
let v_lo = eval_const_expr(tcx, lo),
v_hi = eval_const_expr(tcx, hi);
let match_ = compare_const_vals(c_lo, v_lo) >= 0 &&
compare_const_vals(c_hi, v_hi) <= 0;
- if match_ { some(vec::tail(r)) } else { none }
+ if match_ { Some(vec::tail(r)) } else { None }
}
}
}
-fn default(tcx: ty::ctxt, r: ~[@pat]) -> option<~[@pat]> {
- if is_wild(tcx, r[0]) { some(vec::tail(r)) }
- else { none }
+fn default(tcx: ty::ctxt, r: ~[@pat]) -> Option<~[@pat]> {
+ if is_wild(tcx, r[0]) { Some(vec::tail(r)) }
+ else { None }
}
fn check_local(tcx: ty::ctxt, loc: @local, &&s: (), v: visit::vt<()>) {
fn is_refutable(tcx: ty::ctxt, pat: @pat) -> bool {
match tcx.def_map.find(pat.id) {
- some(def_variant(enum_id, var_id)) => {
+ Some(def_variant(enum_id, var_id)) => {
if vec::len(*ty::enum_variants(tcx, enum_id)) != 1u {
return true;
}
}
match pat.node {
- pat_box(sub) | pat_uniq(sub) | pat_ident(_, _, some(sub)) => {
+ pat_box(sub) | pat_uniq(sub) | pat_ident(_, _, Some(sub)) => {
is_refutable(tcx, sub)
}
- pat_wild | pat_ident(_, _, none) => { false }
+ pat_wild | pat_ident(_, _, None) => { false }
pat_lit(@{node: expr_lit(@{node: lit_nil, _}), _}) => { false } // "()"
pat_lit(_) | pat_range(_, _) => { true }
pat_rec(fields, _) => {
for elts.each |elt| { if is_refutable(tcx, elt) { return true; } }
false
}
- pat_enum(_, some(args)) => {
+ pat_enum(_, Some(args)) => {
for args.each |p| { if is_refutable(tcx, p) { return true; } };
false
}
}
expr_path(_) => {
match def_map.find(e.id) {
- some(def_const(def_id)) => {
+ Some(def_const(def_id)) => {
if !ast_util::is_local(def_id) {
sess.span_err(
e.span, ~"paths in constants may only refer to \
match e.node {
expr_path(path) => {
match env.def_map.find(e.id) {
- some(def_const(def_id)) => {
+ Some(def_const(def_id)) => {
match env.ast_map.get(def_id.node) {
ast_map::node_item(it, _) => {
v.visit_item(it, env, v);
tcx: ty::ctxt) -> constness {
let did = ast_util::local_def(e.id);
match tcx.ccache.find(did) {
- some(x) => x,
- none => {
+ Some(x) => x,
+ None => {
let cn =
match e.node {
ast::expr_lit(lit) => {
}
}
- ast::expr_struct(_, fs, none) |
- ast::expr_rec(fs, none) => {
+ ast::expr_struct(_, fs, None) |
+ ast::expr_rec(fs, None) => {
let cs = do vec::map(fs) |f| {
if f.node.mutbl == ast::m_imm {
classify(f.node.expr, def_map, tcx)
// surrounding nonlocal constants. But we don't yet.
ast::expr_path(_) => {
match def_map.find(e.id) {
- some(ast::def_const(def_id)) => {
+ Some(ast::def_const(def_id)) => {
if ast_util::is_local(def_id) {
let ty = ty::expr_ty(tcx, e);
if ty::type_is_integral(ty) {
non_const
}
}
- some(_) => {
+ Some(_) => {
non_const
}
- none => {
+ None => {
tcx.sess.span_bug(e.span,
~"unknown path when \
classifying constants");
ast::expr_path(path) => {
let mut i = 0;
match def_map.find(expr.id) {
- none => fail ~"path not found",
- some(df) => {
+ None => fail ~"path not found",
+ Some(df) => {
let mut def = df;
while i < depth {
match copy def {
fn get_freevars(tcx: ty::ctxt, fid: ast::node_id) -> freevar_info {
match tcx.freevars.find(fid) {
- none => fail ~"get_freevars: " + int::str(fid) + ~" has no freevars",
- some(d) => return d
+ None => fail ~"get_freevars: " + int::str(fid) + ~" has no freevars",
+ Some(d) => return d
}
}
fn has_freevars(tcx: ty::ctxt, fid: ast::node_id) -> bool {
tcx.sess.abort_if_errors();
}
-type check_fn = fn@(ctx, node_id, option<@freevar_entry>,
+type check_fn = fn@(ctx, node_id, Option<@freevar_entry>,
bool, ty::t, sp: span);
// Yields the appropriate function to check the kind of closed over
// variables. `id` is the node_id for some expression that creates the
// closure.
fn with_appropriate_checker(cx: ctx, id: node_id, b: fn(check_fn)) {
- fn check_for_uniq(cx: ctx, id: node_id, fv: option<@freevar_entry>,
+ fn check_for_uniq(cx: ctx, id: node_id, fv: Option<@freevar_entry>,
is_move: bool, var_t: ty::t, sp: span) {
// all captured data must be sendable, regardless of whether it is
// moved in or copied in. Note that send implies owned.
let is_implicit = fv.is_some();
if !is_move {
check_copy(cx, id, var_t, sp, is_implicit,
- some(("non-copyable value cannot be copied into a \
+ Some(("non-copyable value cannot be copied into a \
~fn closure",
"to copy values into a ~fn closure, use a \
capture clause: `fn~(copy x)` or `|copy x|`")));
}
}
- fn check_for_box(cx: ctx, id: node_id, fv: option<@freevar_entry>,
+ fn check_for_box(cx: ctx, id: node_id, fv: Option<@freevar_entry>,
is_move: bool, var_t: ty::t, sp: span) {
// all captured data must be owned
if !check_owned(cx.tcx, var_t, sp) { return; }
let is_implicit = fv.is_some();
if !is_move {
check_copy(cx, id, var_t, sp, is_implicit,
- some(("non-copyable value cannot be copied into a \
+ Some(("non-copyable value cannot be copied into a \
@fn closure",
"to copy values into a @fn closure, use a \
capture clause: `fn~(copy x)` or `|copy x|`")));
}
}
- fn check_for_block(cx: ctx, _id: node_id, fv: option<@freevar_entry>,
+ fn check_for_block(cx: ctx, _id: node_id, fv: Option<@freevar_entry>,
_is_move: bool, _var_t: ty::t, sp: span) {
// only restriction: no capture clauses (we would have to take
// ownership of the moved/copied in data).
}
}
- fn check_for_bare(cx: ctx, _id: node_id, _fv: option<@freevar_entry>,
+ fn check_for_bare(cx: ctx, _id: node_id, _fv: Option<@freevar_entry>,
_is_move: bool,_var_t: ty::t, sp: span) {
cx.tcx.sess.span_err(sp, ~"attempted dynamic environment capture");
}
let cap_def = cx.tcx.def_map.get(cap_item.id);
let cap_def_id = ast_util::def_id_of_def(cap_def).node;
let ty = ty::node_id_to_type(cx.tcx, cap_def_id);
- chk(cx, fn_id, none, cap_item.is_move, ty, cap_item.span);
+ chk(cx, fn_id, None, cap_item.is_move, ty, cap_item.span);
cap_def_id
};
// a move and not a copy
let is_move = {
match cx.last_use_map.find(fn_id) {
- some(vars) => (*vars).contains(id),
- none => false
+ Some(vars) => (*vars).contains(id),
+ None => false
}
};
let ty = ty::node_id_to_type(cx.tcx, id);
- chk(cx, fn_id, some(fv), is_move, ty, fv.span);
+ chk(cx, fn_id, Some(fv), is_move, ty, fv.span);
}
}
fn check_block(b: blk, cx: ctx, v: visit::vt<ctx>) {
match b.node.expr {
- some(ex) => maybe_copy(cx, ex, none),
+ Some(ex) => maybe_copy(cx, ex, None),
_ => ()
}
visit::visit_block(b, cx, v);
if mode == bind_by_value {
let t = ty::node_id_to_type(cx.tcx, id);
let reason = "consider binding with `ref` or `move` instead";
- check_copy(cx, id, t, span, false, some((reason,reason)));
+ check_copy(cx, id, t, span, false, Some((reason,reason)));
}
}
}
match e.node {
expr_assign(_, ex) |
expr_unary(box(_), ex) | expr_unary(uniq(_), ex) |
- expr_ret(some(ex)) => {
- maybe_copy(cx, ex, none);
+ expr_ret(Some(ex)) => {
+ maybe_copy(cx, ex, None);
}
expr_cast(source, _) => {
- maybe_copy(cx, source, none);
+ maybe_copy(cx, source, None);
check_cast_for_escaping_regions(cx, source, e);
}
- expr_copy(expr) => check_copy_ex(cx, expr, false, none),
+ expr_copy(expr) => check_copy_ex(cx, expr, false, None),
// Vector add copies, but not "implicitly"
- expr_assign_op(_, _, ex) => check_copy_ex(cx, ex, false, none),
+ expr_assign_op(_, _, ex) => check_copy_ex(cx, ex, false, None),
expr_binary(add, ls, rs) => {
- check_copy_ex(cx, ls, false, none);
- check_copy_ex(cx, rs, false, none);
+ check_copy_ex(cx, ls, false, None);
+ check_copy_ex(cx, rs, false, None);
}
expr_rec(fields, def) => {
- for fields.each |field| { maybe_copy(cx, field.node.expr, none); }
+ for fields.each |field| { maybe_copy(cx, field.node.expr, None); }
match def {
- some(ex) => {
+ Some(ex) => {
// All noncopyable fields must be overridden
let t = ty::expr_ty(cx.tcx, ex);
let ty_fields = match ty::get(t).struct {
}
}
expr_tup(exprs) | expr_vec(exprs, _) => {
- for exprs.each |expr| { maybe_copy(cx, expr, none); }
+ for exprs.each |expr| { maybe_copy(cx, expr, None); }
}
expr_call(f, args, _) => {
let mut i = 0u;
for ty::ty_fn_args(ty::expr_ty(cx.tcx, f)).each |arg_t| {
match ty::arg_mode(cx.tcx, arg_t) {
- by_copy => maybe_copy(cx, args[i], none),
+ by_copy => maybe_copy(cx, args[i], None),
by_ref | by_val | by_mutbl_ref | by_move => ()
}
i += 1u;
// If this is a method call with a by-val argument, we need
// to check the copy
match cx.method_map.find(e.id) {
- some({self_mode: by_copy, _}) => maybe_copy(cx, lhs, none),
+ Some({self_mode: by_copy, _}) => maybe_copy(cx, lhs, None),
_ => ()
}
}
expr_repeat(element, count_expr, _) => {
let count = ty::eval_repeat_count(cx.tcx, count_expr, e.span);
if count == 1 {
- maybe_copy(cx, element, none);
+ maybe_copy(cx, element, None);
} else {
let element_ty = ty::expr_ty(cx.tcx, element);
- check_copy(cx, element.id, element_ty, element.span, true, none);
+ check_copy(cx, element.id, element_ty, element.span, true, None);
}
}
_ => { }
stmt_decl(@{node: decl_local(locals), _}, _) => {
for locals.each |local| {
match local.node.init {
- some({op: init_assign, expr}) => maybe_copy(cx, expr, none),
+ Some({op: init_assign, expr}) => maybe_copy(cx, expr, None),
_ => {}
}
}
}
}
-fn maybe_copy(cx: ctx, ex: @expr, why: option<(&str,&str)>) {
+fn maybe_copy(cx: ctx, ex: @expr, why: Option<(&str,&str)>) {
check_copy_ex(cx, ex, true, why);
}
}
fn check_copy_ex(cx: ctx, ex: @expr, implicit_copy: bool,
- why: option<(&str,&str)>) {
+ why: Option<(&str,&str)>) {
if ty::expr_is_lval(cx.method_map, ex) &&
// this is a move
!cx.last_use_map.contains_key(ex.id) &&
// a reference to a constant like `none`... no need to warn
- // about *this* even if the type is option<~int>
+ // about *this* even if the type is Option<~int>
!is_nullary_variant(cx, ex) &&
// borrowed unique value isn't really a copy
}
fn check_copy(cx: ctx, id: node_id, ty: ty::t, sp: span,
- implicit_copy: bool, why: option<(&str,&str)>) {
+ implicit_copy: bool, why: Option<(&str,&str)>) {
let k = ty::type_kind(cx.tcx, ty);
if !ty::kind_can_be_copied(k) {
cx.tcx.sess.span_err(sp, ~"copying a noncopyable value");
// possibly escape the enclosing fn item (note that all type parameters
// must have been declared on the enclosing fn item):
match target_substs.self_r {
- some(ty::re_scope(*)) => { return; /* case (1) */ }
- none | some(ty::re_static) | some(ty::re_free(*)) => {}
- some(ty::re_bound(*)) | some(ty::re_var(*)) => {
+ Some(ty::re_scope(*)) => { return; /* case (1) */ }
+ None | Some(ty::re_static) | Some(ty::re_free(*)) => {}
+ Some(ty::re_bound(*)) | Some(ty::re_var(*)) => {
cx.tcx.sess.span_bug(
source.span,
fmt!("bad region found in kind: %?", target_substs.self_r));
import str_eq = str::eq;
struct LanguageItems {
- let mut const_trait: option<def_id>;
- let mut copy_trait: option<def_id>;
- let mut send_trait: option<def_id>;
- let mut owned_trait: option<def_id>;
-
- let mut add_trait: option<def_id>;
- let mut sub_trait: option<def_id>;
- let mut mul_trait: option<def_id>;
- let mut div_trait: option<def_id>;
- let mut modulo_trait: option<def_id>;
- let mut neg_trait: option<def_id>;
- let mut bitxor_trait: option<def_id>;
- let mut bitand_trait: option<def_id>;
- let mut bitor_trait: option<def_id>;
- let mut shl_trait: option<def_id>;
- let mut shr_trait: option<def_id>;
- let mut index_trait: option<def_id>;
+ let mut const_trait: Option<def_id>;
+ let mut copy_trait: Option<def_id>;
+ let mut send_trait: Option<def_id>;
+ let mut owned_trait: Option<def_id>;
+
+ let mut add_trait: Option<def_id>;
+ let mut sub_trait: Option<def_id>;
+ let mut mul_trait: Option<def_id>;
+ let mut div_trait: Option<def_id>;
+ let mut modulo_trait: Option<def_id>;
+ let mut neg_trait: Option<def_id>;
+ let mut bitxor_trait: Option<def_id>;
+ let mut bitand_trait: Option<def_id>;
+ let mut bitor_trait: Option<def_id>;
+ let mut shl_trait: Option<def_id>;
+ let mut shr_trait: Option<def_id>;
+ let mut index_trait: Option<def_id>;
new() {
- self.const_trait = none;
- self.copy_trait = none;
- self.send_trait = none;
- self.owned_trait = none;
-
- self.add_trait = none;
- self.sub_trait = none;
- self.mul_trait = none;
- self.div_trait = none;
- self.modulo_trait = none;
- self.neg_trait = none;
- self.bitxor_trait = none;
- self.bitand_trait = none;
- self.bitor_trait = none;
- self.shl_trait = none;
- self.shr_trait = none;
- self.index_trait = none;
+ self.const_trait = None;
+ self.copy_trait = None;
+ self.send_trait = None;
+ self.owned_trait = None;
+
+ self.add_trait = None;
+ self.sub_trait = None;
+ self.mul_trait = None;
+ self.div_trait = None;
+ self.modulo_trait = None;
+ self.neg_trait = None;
+ self.bitxor_trait = None;
+ self.bitand_trait = None;
+ self.bitor_trait = None;
+ self.shl_trait = None;
+ self.shr_trait = None;
+ self.index_trait = None;
}
}
let crate: @crate;
let session: session;
- let item_refs: hashmap<~str,&mut option<def_id>>;
+ let item_refs: hashmap<~str,&mut Option<def_id>>;
new(crate: @crate, session: session, items: &self/LanguageItems) {
self.crate = crate;
}
match self.item_refs.find(value) {
- none => {
+ None => {
// Didn't match.
}
- some(item_ref) => {
+ Some(item_ref) => {
// Check for duplicates.
match copy *item_ref {
- some(original_def_id)
+ Some(original_def_id)
if original_def_id != item_def_id => {
self.session.err(fmt!("duplicate entry for `%s`",
value));
}
- some(_) | none => {
+ Some(_) | None => {
// OK.
}
}
// Matched.
- *item_ref = some(item_def_id);
+ *item_ref = Some(item_def_id);
}
}
}
fn check_completeness() {
for self.item_refs.each |key, item_ref| {
match copy *item_ref {
- none => {
+ None => {
self.session.err(fmt!("no item found for `%s`", key));
}
- some(_) => {
+ Some(_) => {
// OK.
}
}
fn get_lint_level(modes: lint_modes, lint: lint) -> level {
match modes.find(lint as uint) {
- some(c) => c,
- none => allow
+ Some(c) => c,
+ None => allow
}
}
_expr_id: ast::node_id,
item_id: ast::node_id) -> level {
match settings.settings_map.find(item_id) {
- some(modes) => get_lint_level(modes, lint_mode),
- none => get_lint_level(settings.default_settings, lint_mode)
+ Some(modes) => get_lint_level(modes, lint_mode),
+ None => get_lint_level(settings.default_settings, lint_mode)
}
}
for triples.each |pair| {
let (meta, level, lintname) = pair;
match self.dict.find(lintname) {
- none => {
+ None => {
self.span_lint(
new_ctxt.get_level(unrecognized_lint),
meta.span,
fmt!("unknown `%s` attribute: `%s`",
level_to_str(level), lintname));
}
- some(lint) => {
+ Some(lint) => {
if new_ctxt.get_level(lint.lint) == forbid &&
level != forbid {
fn ident_without_trailing_underscores(ident: ~str) -> ~str {
match str::rfind(ident, |c| c != '_') {
- some(idx) => (ident).slice(0, idx + 1),
- none => { ident } // all underscores
+ Some(idx) => (ident).slice(0, idx + 1),
+ None => { ident } // all underscores
}
}
fn ident_without_leading_underscores(ident: ~str) -> ~str {
match str::find(ident, |c| c != '_') {
- some(idx) => ident.slice(idx, ident.len()),
- none => {
+ Some(idx) => ident.slice(idx, ident.len()),
+ None => {
// all underscores
ident
}
ImplicitRet
}
-fn relevant_def(def: def) -> option<RelevantDef> {
+fn relevant_def(def: def) -> Option<RelevantDef> {
match def {
- def_self(_) => some(RelevantSelf),
+ def_self(_) => Some(RelevantSelf),
def_binding(nid, _) |
def_arg(nid, _) |
- def_local(nid, _) => some(RelevantVar(nid)),
+ def_local(nid, _) => Some(RelevantVar(nid)),
- _ => none
+ _ => None
}
}
fn variable(node_id: node_id, span: span) -> Variable {
match self.variable_map.find(node_id) {
- some(var) => var,
- none => {
+ Some(var) => var,
+ None => {
self.tcx.sess.span_bug(
span, fmt!("No variable registered for id %d", node_id));
}
fn captures(expr: @expr) -> @~[CaptureInfo] {
match self.capture_map.find(expr.id) {
- some(caps) => caps,
- none => {
+ Some(caps) => caps,
+ None => {
self.tcx.sess.span_bug(expr.span, ~"no registered caps");
}
}
Local(LocalInfo {id:id, ident:name,
kind: FromMatch(bind_by_move), _}) => {
let v = match self.last_use_map.find(expr_id) {
- some(v) => v,
- none => {
+ Some(v) => v,
+ None => {
let v = @dvec();
self.last_use_map.insert(expr_id, v);
v
let name = ast_util::path_to_ident(path);
self.add_live_node_for_node(p_id, VarDefNode(sp));
let kind = match local.node.init {
- some(_) => FromLetWithInitializer,
- none => FromLetNoInitializer
+ Some(_) => FromLetWithInitializer,
+ None => FromLetNoInitializer
};
self.add_variable(Local(LocalInfo {
id: p_id,
let mut call_caps = ~[];
for cvs.each |cv| {
match relevant_def(cv.def) {
- some(rv) => {
+ Some(rv) => {
let cv_ln = self.add_live_node(FreeVarNode(cv.span));
let is_move = match cv.mode {
cap_move | cap_drop => true, // var must be dead afterwards
};
vec::push(call_caps, {ln: cv_ln, is_move: is_move, rv: rv});
}
- none => {}
+ None => {}
}
}
self.set_captures(expr.id, call_caps);
impl Liveness {
fn live_node(node_id: node_id, span: span) -> LiveNode {
match self.ir.live_node_map.find(node_id) {
- some(ln) => ln,
- none => {
+ Some(ln) => ln,
+ None => {
// This must be a mismatch between the ir_map construction
// above and the propagation code below; the two sets of
// code have to agree about which AST nodes are worth
}
}
- fn variable_from_path(expr: @expr) -> option<Variable> {
+ fn variable_from_path(expr: @expr) -> Option<Variable> {
match expr.node {
expr_path(_) => {
let def = self.tcx.def_map.get(expr.id);
|rdef| self.variable_from_rdef(rdef, expr.span)
)
}
- _ => none
+ _ => None
}
}
}
fn variable_from_def_map(node_id: node_id,
- span: span) -> option<Variable> {
+ span: span) -> Option<Variable> {
match self.tcx.def_map.find(node_id) {
- some(def) => {
+ Some(def) => {
relevant_def(def).map(
|rdef| self.variable_from_rdef(rdef, span)
)
}
- none => {
+ None => {
self.tcx.sess.span_bug(
span, ~"Not present in def map")
}
}
fn live_on_entry(ln: LiveNode, var: Variable)
- -> option<LiveNodeKind> {
+ -> Option<LiveNodeKind> {
assert ln.is_valid();
let reader = self.users[self.idx(ln, var)].reader;
- if reader.is_valid() {some((*self.ir).lnk(reader))} else {none}
+ if reader.is_valid() {Some((*self.ir).lnk(reader))} else {None}
}
fn live_on_exit(ln: LiveNode, var: Variable)
- -> option<LiveNodeKind> {
+ -> Option<LiveNodeKind> {
self.live_on_entry(copy self.successors[*ln], var)
}
}
fn assigned_on_entry(ln: LiveNode, var: Variable)
- -> option<LiveNodeKind> {
+ -> Option<LiveNodeKind> {
assert ln.is_valid();
let writer = self.users[self.idx(ln, var)].writer;
- if writer.is_valid() {some((*self.ir).lnk(writer))} else {none}
+ if writer.is_valid() {Some((*self.ir).lnk(writer))} else {None}
}
fn assigned_on_exit(ln: LiveNode, var: Variable)
- -> option<LiveNodeKind> {
+ -> Option<LiveNodeKind> {
self.assigned_on_entry(copy self.successors[*ln], var)
}
}
}
- fn propagate_through_opt_expr(opt_expr: option<@expr>,
+ fn propagate_through_opt_expr(opt_expr: Option<@expr>,
succ: LiveNode) -> LiveNode {
do opt_expr.foldl(succ) |succ, expr| {
self.propagate_through_expr(expr, succ)
// Otherwise, we ignore it and just propagate down to
// process `e`.
match self.as_self_field(e, nm) {
- some((ln, var)) => {
+ Some((ln, var)) => {
self.init_from_succ(ln, succ);
self.acc(ln, var, ACC_READ | ACC_USE);
ln
}
- none => {
+ None => {
self.propagate_through_expr(e, succ)
}
}
}
expr_while(cond, blk) => {
- self.propagate_through_loop(expr, some(cond), blk, succ)
+ self.propagate_through_loop(expr, Some(cond), blk, succ)
}
expr_loop(blk, _) => {
- self.propagate_through_loop(expr, none, blk, succ)
+ self.propagate_through_loop(expr, None, blk, succ)
}
expr_match(e, arms) => {
match expr.node {
expr_path(_) => succ,
expr_field(e, nm, _) => match self.as_self_field(e, nm) {
- some(_) => succ,
- none => self.propagate_through_expr(e, succ)
+ Some(_) => succ,
+ None => self.propagate_through_expr(e, succ)
},
_ => self.propagate_through_expr(expr, succ)
}
match expr.node {
expr_path(_) => self.access_path(expr, succ, acc),
expr_field(e, nm, _) => match self.as_self_field(e, nm) {
- some((ln, var)) => {
+ Some((ln, var)) => {
self.init_from_succ(ln, succ);
self.acc(ln, var, acc);
ln
}
- none => succ
+ None => succ
},
// We do not track other lvalues, so just propagate through
fn access_path(expr: @expr, succ: LiveNode, acc: uint) -> LiveNode {
let def = self.tcx.def_map.get(expr.id);
match relevant_def(def) {
- some(RelevantSelf) => {
+ Some(RelevantSelf) => {
// Accessing `self` is like accessing every field of
// the current object. This allows something like
// `self = ...;` (it will be considered a write to
}
ln
}
- some(RelevantVar(nid)) => {
+ Some(RelevantVar(nid)) => {
let ln = self.live_node(expr.id, expr.span);
if acc != 0u {
self.init_from_succ(ln, succ);
}
ln
}
- none => succ
+ None => succ
}
}
fn as_self_field(expr: @expr,
- fld: ident) -> option<(LiveNode,Variable)> {
+ fld: ident) -> Option<(LiveNode,Variable)> {
// If we checking a constructor, then we treat self.f as a
// variable. we use the live_node id that will be assigned to
// the reference to self but the variable id for `f`.
(ln, var)
});
}
- _ => return none
+ _ => return None
}
}
- _ => return none
+ _ => return None
}
}
fn propagate_through_loop(expr: @expr,
- cond: option<@expr>,
+ cond: Option<@expr>,
body: blk,
succ: LiveNode) -> LiveNode {
fn check_local(local: @local, &&self: @Liveness, vt: vt<@Liveness>) {
match local.node.init {
- some({op: op, expr: expr}) => {
+ Some({op: op, expr: expr}) => {
// Initializer:
self.check_for_reassignments_in_pat(local.node.pat);
}
}
- none => {
+ None => {
// No initializer: the variable might be unused; if not, it
// should not be live at this point.
do self.pat_bindings(local.node.pat) |ln, var, sp| {
if !self.warn_about_unused(sp, ln, var) {
match self.live_on_exit(ln, var) {
- none => { /* not live: good */ }
- some(lnk) => {
+ None => { /* not live: good */ }
+ Some(lnk) => {
self.report_illegal_read(
local.span, lnk, var,
PossiblyUninitializedVariable);
fn check_fields(sp: span, entry_ln: LiveNode) {
for self.ir.field_map.each |nm, var| {
match self.live_on_entry(entry_ln, var) {
- none => { /* ok */ }
- some(ExitNode) => {
+ None => { /* ok */ }
+ Some(ExitNode) => {
self.tcx.sess.span_err(
sp, fmt!("field `self.%s` is never initialized",
self.tcx.sess.str_of(nm)));
}
- some(lnk) => {
+ Some(lnk) => {
self.report_illegal_read(
sp, lnk, var, PossiblyUninitializedField);
}
ln.to_str(), var.to_str());
match self.live_on_exit(ln, var) {
- none => {}
- some(lnk) => self.report_illegal_move(span, lnk, var)
+ None => {}
+ Some(lnk) => self.report_illegal_move(span, lnk, var)
}
}
fn consider_last_use(expr: @expr, ln: LiveNode, var: Variable) {
match self.live_on_exit(ln, var) {
- some(_) => {}
- none => (*self.ir).add_last_use(expr.id, var)
+ Some(_) => {}
+ None => (*self.ir).add_last_use(expr.id, var)
}
}
match expr.node {
expr_path(_) => {
match self.variable_from_path(expr) {
- some(var) => {
+ Some(var) => {
let ln = self.live_node(expr.id, expr.span);
self.check_move_from_var(expr.span, ln, var);
}
- none => {}
+ None => {}
}
}
}
def => {
match relevant_def(def) {
- some(RelevantVar(nid)) => {
+ Some(RelevantVar(nid)) => {
let ln = self.live_node(expr.id, expr.span);
let var = self.variable(nid, expr.span);
self.warn_about_dead_assign(expr.span, ln, var);
}
- some(RelevantSelf) => {}
- none => {}
+ Some(RelevantSelf) => {}
+ None => {}
}
}
}
fn check_for_reassignment(ln: LiveNode, var: Variable,
orig_span: span) {
match self.assigned_on_exit(ln, var) {
- some(ExprNode(span)) => {
+ Some(ExprNode(span)) => {
self.tcx.sess.span_err(
span,
~"re-assignment of immutable variable");
orig_span,
~"prior assignment occurs here");
}
- some(lnk) => {
+ Some(lnk) => {
self.tcx.sess.span_bug(
orig_span,
fmt!("illegal writer: %?", lnk));
}
- none => {}
+ None => {}
}
}
}
}
- fn should_warn(var: Variable) -> option<~str> {
+ fn should_warn(var: Variable) -> Option<~str> {
let name = (*self.ir).variable_name(var);
- if name[0] == ('_' as u8) {none} else {some(name)}
+ if name[0] == ('_' as u8) {None} else {Some(name)}
}
fn warn_about_unused_args(sp: span, decl: fn_decl, entry_ln: LiveNode) {
// is not worth warning about, as it has visible
// side effects outside the fn.
match self.assigned_on_entry(entry_ln, var) {
- some(_) => { /*ok*/ }
- none => {
+ Some(_) => { /*ok*/ }
+ None => {
// but if it is not written, it ought to be used
self.warn_about_unused(sp, entry_ln, var);
}
type cmt = @{id: ast::node_id, // id of expr/pat producing this value
span: span, // span of same expr/pat
cat: categorization, // categorization of expr
- lp: option<@loan_path>, // loan path for expr, if any
+ lp: Option<@loan_path>, // loan path for expr, if any
mutbl: ast::mutability, // mutability of expr as lvalue
ty: ty::t}; // type of the expr
// Categorizes a derefable type. Note that we include vectors and strings as
// derefable (we model an index as the combination of a deref and then a
// pointer adjustment).
-fn opt_deref_kind(t: ty::t) -> option<deref_kind> {
+fn opt_deref_kind(t: ty::t) -> Option<deref_kind> {
match ty::get(t).struct {
ty::ty_uniq(*) |
ty::ty_evec(_, ty::vstore_uniq) |
ty::ty_estr(ty::vstore_uniq) => {
- some(deref_ptr(uniq_ptr))
+ Some(deref_ptr(uniq_ptr))
}
ty::ty_rptr(r, _) |
ty::ty_evec(_, ty::vstore_slice(r)) |
ty::ty_estr(ty::vstore_slice(r)) => {
- some(deref_ptr(region_ptr(r)))
+ Some(deref_ptr(region_ptr(r)))
}
ty::ty_box(*) |
ty::ty_evec(_, ty::vstore_box) |
ty::ty_estr(ty::vstore_box) => {
- some(deref_ptr(gc_ptr))
+ Some(deref_ptr(gc_ptr))
}
ty::ty_ptr(*) => {
- some(deref_ptr(unsafe_ptr))
+ Some(deref_ptr(unsafe_ptr))
}
ty::ty_enum(did, _) => {
- some(deref_comp(comp_variant(did)))
+ Some(deref_comp(comp_variant(did)))
}
ty::ty_evec(mt, ty::vstore_fixed(_)) => {
- some(deref_comp(comp_index(t, mt.mutbl)))
+ Some(deref_comp(comp_index(t, mt.mutbl)))
}
ty::ty_estr(ty::vstore_fixed(_)) => {
- some(deref_comp(comp_index(t, m_imm)))
+ Some(deref_comp(comp_index(t, m_imm)))
}
- _ => none
+ _ => None
}
}
fn deref_kind(tcx: ty::ctxt, t: ty::t) -> deref_kind {
match opt_deref_kind(t) {
- some(k) => k,
- none => {
+ Some(k) => k,
+ None => {
tcx.sess.bug(
fmt!("deref_cat() invoked on non-derefable type %s",
ty_to_str(tcx, t)));
let base_cmt = self.cat_expr(e_base);
match self.cat_deref(expr, base_cmt, 0u, true) {
- some(cmt) => return cmt,
- none => {
+ Some(cmt) => return cmt,
+ None => {
tcx.sess.span_bug(
e_base.span,
fmt!("Explicit deref of non-derefable type `%s`",
ast::def_typaram_binder(*) | ast::def_region(_) |
ast::def_label(_) => {
@{id:id, span:span,
- cat:cat_special(sk_static_item), lp:none,
+ cat:cat_special(sk_static_item), lp:None,
mutbl:m_imm, ty:expr_ty}
}
// lp: loan path, must be none for aliasable things
let {m,lp} = match ty::resolved_mode(self.tcx, mode) {
ast::by_mutbl_ref => {
- {m: m_mutbl, lp: none}
+ {m: m_mutbl, lp: None}
}
ast::by_move | ast::by_copy => {
- {m: m_imm, lp: some(@lp_arg(vid))}
+ {m: m_imm, lp: Some(@lp_arg(vid))}
}
ast::by_ref => {
- {m: m_imm, lp: none}
+ {m: m_imm, lp: None}
}
ast::by_val => {
// by-value is this hybrid mode where we have a
// considered loanable because, for example, a by-ref
// and and by-val argument might both actually contain
// the same unique ptr.
- {m: m_imm, lp: none}
+ {m: m_imm, lp: None}
}
};
@{id:id, span:span,
ast::def_self(_) => {
@{id:id, span:span,
- cat:cat_special(sk_self), lp:none,
+ cat:cat_special(sk_self), lp:None,
mutbl:m_imm, ty:expr_ty}
}
ty::proto_vstore(ty::vstore_box) => {
// FIXME #2152 allow mutation of moved upvars
@{id:id, span:span,
- cat:cat_special(sk_heap_upvar), lp:none,
+ cat:cat_special(sk_heap_upvar), lp:None,
mutbl:m_imm, ty:expr_ty}
}
ty::proto_vstore(ty::vstore_fixed(_)) =>
ast::def_local(vid, mutbl) => {
let m = if mutbl {m_mutbl} else {m_imm};
@{id:id, span:span,
- cat:cat_local(vid), lp:some(@lp_local(vid)),
+ cat:cat_local(vid), lp:Some(@lp_local(vid)),
mutbl:m, ty:expr_ty}
}
ast::def_binding(vid, ast::bind_by_ref(_)) => {
// by-value/by-ref bindings are local variables
@{id:id, span:span,
- cat:cat_local(vid), lp:some(@lp_local(vid)),
+ cat:cat_local(vid), lp:Some(@lp_local(vid)),
mutbl:m_imm, ty:expr_ty}
}
// dependencies.
@{id:id, span:span,
- cat:cat_binding(pid), lp:none,
+ cat:cat_binding(pid), lp:None,
mutbl:m_imm, ty:expr_ty}
}
}
fn cat_rvalue(expr: @ast::expr, expr_ty: ty::t) -> cmt {
@{id:expr.id, span:expr.span,
- cat:cat_rvalue, lp:none,
+ cat:cat_rvalue, lp:None,
mutbl:m_imm, ty:expr_ty}
}
fn cat_field<N:ast_node>(node: N, base_cmt: cmt,
f_name: ast::ident) -> cmt {
let f_mutbl = match field_mutbl(self.tcx, base_cmt.ty, f_name) {
- some(f_mutbl) => f_mutbl,
- none => {
+ Some(f_mutbl) => f_mutbl,
+ None => {
self.tcx.sess.span_bug(
node.span(),
fmt!("Cannot find field `%s` in type `%s`",
}
fn cat_deref<N:ast_node>(node: N, base_cmt: cmt, derefs: uint,
- expl: bool) -> option<cmt> {
+ expl: bool) -> Option<cmt> {
do ty::deref(self.tcx, base_cmt.ty, expl).map |mt| {
match deref_kind(self.tcx, base_cmt.ty) {
deref_ptr(ptr) => {
// Other ptr types admit aliases and are therefore
// not loanable.
match ptr {
- uniq_ptr => {some(@lp_deref(l, ptr))}
- gc_ptr | region_ptr(_) | unsafe_ptr => {none}
+ uniq_ptr => {Some(@lp_deref(l, ptr))}
+ gc_ptr | region_ptr(_) | unsafe_ptr => {None}
}
};
let base_cmt = self.cat_autoderef(base);
let mt = match ty::index(self.tcx, base_cmt.ty) {
- some(mt) => mt,
- none => {
+ Some(mt) => mt,
+ None => {
self.tcx.sess.span_bug(
expr.span,
fmt!("Explicit index of non-index type `%s`",
// and this is a *unique* vector
let deref_lp = match ptr {
uniq_ptr => {base_cmt.lp.map(|lp| @lp_deref(lp, uniq_ptr))}
- _ => {none}
+ _ => {None}
};
// (b) for unique ptrs, we inherit mutability from the
fn cat_method_ref(expr: @ast::expr, expr_ty: ty::t) -> cmt {
@{id:expr.id, span:expr.span,
- cat:cat_special(sk_method), lp:none,
+ cat:cat_special(sk_method), lp:None,
mutbl:m_imm, ty:expr_ty}
}
loop {
ctr += 1u;
match self.cat_deref(base, cmt, ctr, false) {
- none => return cmt,
- some(cmt1) => cmt = cmt1
+ None => return cmt,
+ Some(cmt1) => cmt = cmt1
}
}
}
// _
}
- ast::pat_enum(_, none) => {
+ ast::pat_enum(_, None) => {
// variant(*)
}
- ast::pat_enum(_, some(subpats)) => {
+ ast::pat_enum(_, Some(subpats)) => {
// variant(x, y, z)
let enum_did = match self.tcx.def_map.find(pat.id) {
- some(ast::def_variant(enum_did, _)) => enum_did,
+ Some(ast::def_variant(enum_did, _)) => enum_did,
e => tcx.sess.span_bug(pat.span,
fmt!("resolved to %?, not variant", e))
};
}
}
- ast::pat_ident(_, _, some(subpat)) => {
+ ast::pat_ident(_, _, Some(subpat)) => {
self.cat_pattern(cmt, subpat, op);
}
- ast::pat_ident(_, _, none) => {
+ ast::pat_ident(_, _, None) => {
// nullary variant or identifier: ignore
}
ast::pat_box(subpat) | ast::pat_uniq(subpat) => {
// @p1, ~p1
match self.cat_deref(subpat, cmt, 0u, true) {
- some(subcmt) => {
+ Some(subcmt) => {
self.cat_pattern(subcmt, subpat, op);
}
- none => {
+ None => {
tcx.sess.span_bug(pat.span, ~"Non derefable type");
}
}
fn field_mutbl(tcx: ty::ctxt,
base_ty: ty::t,
- f_name: ast::ident) -> option<ast::mutability> {
+ f_name: ast::ident) -> Option<ast::mutability> {
// Need to refactor so that records/class fields can be treated uniformly.
match ty::get(base_ty).struct {
ty::ty_rec(fields) => {
for fields.each |f| {
if f.ident == f_name {
- return some(f.mt.mutbl);
+ return Some(f.mt.mutbl);
}
}
}
ast::class_mutable => ast::m_mutbl,
ast::class_immutable => ast::m_imm
};
- return some(m);
+ return Some(m);
}
}
}
_ => { }
}
- return none;
+ return None;
}
fn pat_is_variant(dm: resolve3::DefMap, pat: @pat) -> bool {
match pat.node {
pat_enum(_, _) => true,
- pat_ident(_, _, none) => match dm.find(pat.id) {
- some(def_variant(_, _)) => true,
+ pat_ident(_, _, None) => match dm.find(pat.id) {
+ Some(def_variant(_, _)) => true,
_ => false
},
_ => false
import std::list::list;
import std::map::{hashmap, int_hash};
-type parent = option<ast::node_id>;
+type parent = Option<ast::node_id>;
/* Records the parameter ID of a region name. */
type binding = {node_id: ast::node_id,
let mut subscope = subscope;
while superscope != subscope {
match region_map.find(subscope) {
- none => return false,
- some(scope) => subscope = scope
+ None => return false,
+ Some(scope) => subscope = scope
}
}
return true;
/// is, finds the smallest scope which is greater than or equal to
/// both `scope_a` and `scope_b`.
fn nearest_common_ancestor(region_map: region_map, scope_a: ast::node_id,
- scope_b: ast::node_id) -> option<ast::node_id> {
+ scope_b: ast::node_id) -> Option<ast::node_id> {
fn ancestors_of(region_map: region_map, scope: ast::node_id)
-> ~[ast::node_id] {
let mut scope = scope;
loop {
match region_map.find(scope) {
- none => return result,
- some(superscope) => {
+ None => return result,
+ Some(superscope) => {
vec::push(result, superscope);
scope = superscope;
}
}
}
- if scope_a == scope_b { return some(scope_a); }
+ if scope_a == scope_b { return Some(scope_a); }
let a_ancestors = ancestors_of(region_map, scope_a);
let b_ancestors = ancestors_of(region_map, scope_b);
// then the corresponding scope is a superscope of the other.
if a_ancestors[a_index] != b_ancestors[b_index] {
- return none;
+ return None;
}
loop {
// Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
// for all indices between a_index and the end of the array
- if a_index == 0u { return some(scope_a); }
- if b_index == 0u { return some(scope_b); }
+ if a_index == 0u { return Some(scope_a); }
+ if b_index == 0u { return Some(scope_b); }
a_index -= 1u;
b_index -= 1u;
if a_ancestors[a_index] != b_ancestors[b_index] {
- return some(a_ancestors[a_index + 1u]);
+ return Some(a_ancestors[a_index + 1u]);
}
}
}
/// Extracts that current parent from cx, failing if there is none.
fn parent_id(cx: ctxt, span: span) -> ast::node_id {
match cx.parent {
- none => {
+ None => {
cx.sess.span_bug(span, ~"crate should not be parent here");
}
- some(parent_id) => {
+ Some(parent_id) => {
parent_id
}
}
record_parent(cx, blk.node.id);
// Descend.
- let new_cx: ctxt = ctxt {parent: some(blk.node.id) with cx};
+ let new_cx: ctxt = ctxt {parent: Some(blk.node.id) with cx};
visit::visit_block(blk, new_cx, visitor);
}
ast::pat_ident(_, path, _) => {
let defn_opt = cx.def_map.find(pat.id);
match defn_opt {
- some(ast::def_variant(_,_)) => {
+ Some(ast::def_variant(_,_)) => {
/* Nothing to do; this names a variant. */
}
_ => {
ast::stmt_semi(expr, stmt_id) => {
record_parent(cx, stmt_id);
let mut expr_cx = cx;
- expr_cx.parent = some(stmt_id);
+ expr_cx.parent = Some(stmt_id);
visit::visit_stmt(stmt, expr_cx, visitor);
}
}
ast::expr_call(*) => {
debug!("node %d: %s", expr.id, pprust::expr_to_str(expr,
cx.sess.intr()));
- new_cx.parent = some(expr.id);
+ new_cx.parent = Some(expr.id);
}
ast::expr_match(subexpr, _) => {
debug!("node %d: %s", expr.id, pprust::expr_to_str(expr,
cx.sess.intr()));
- new_cx.parent = some(expr.id);
+ new_cx.parent = Some(expr.id);
}
ast::expr_fn(_, _, _, cap_clause) |
ast::expr_fn_block(_, _, cap_clause) => {
};
if new_cx.root_exprs.contains_key(expr.id) {
- new_cx.parent = some(expr.id);
+ new_cx.parent = Some(expr.id);
}
visit::visit_expr(expr, new_cx, visitor);
fn resolve_item(item: @ast::item, cx: ctxt, visitor: visit::vt<ctxt>) {
// Items create a new outer block scope as far as we're concerned.
- let new_cx: ctxt = ctxt {parent: none with cx};
+ let new_cx: ctxt = ctxt {parent: None with cx};
visit::visit_item(item, new_cx, visitor);
}
visit::fk_item_fn(*) | visit::fk_method(*) |
visit::fk_ctor(*) | visit::fk_dtor(*) => {
// Top-level functions are a root scope.
- ctxt {parent: some(id) with cx}
+ ctxt {parent: Some(id) with cx}
}
visit::fk_anon(*) | visit::fk_fn_block(*) => {
def_map: def_map,
region_map: int_hash(),
root_exprs: int_hash(),
- parent: none};
+ parent: None};
let visitor = visit::mk_vt(@{
visit_block: resolve_block,
visit_item: resolve_item,
assert id != 0;
let old_variance = self.region_paramd_items.find(id);
let joined_variance = match old_variance {
- none => variance,
- some(v) => join_variance(v, variance)
+ None => variance,
+ Some(v) => join_variance(v, variance)
};
debug!("add_rp() variance for %s: %? == %? ^ %?",
self.sess.parse_sess.interner),
joined_variance, old_variance, variance);
- if some(joined_variance) != old_variance {
+ if Some(joined_variance) != old_variance {
self.region_paramd_items.insert(id, joined_variance);
self.worklist.push(id);
}
self.sess.parse_sess.interner),
copy self.ambient_variance);
let vec = match self.dep_map.find(from) {
- some(vec) => vec,
- none => {
+ Some(vec) => vec,
+ None => {
let vec = @dvec();
self.dep_map.insert(from, vec);
vec
//
// If the region is explicitly specified, then we follows the
// normal rules.
- fn opt_region_is_relevant(opt_r: option<@ast::region>) -> bool {
+ fn opt_region_is_relevant(opt_r: Option<@ast::region>) -> bool {
debug!("opt_region_is_relevant: %? (anon_implies_rp=%b)",
opt_r, self.anon_implies_rp);
match opt_r {
- none => self.anon_implies_rp,
- some(r) => self.region_is_relevant(r)
+ None => self.anon_implies_rp,
+ Some(r) => self.region_is_relevant(r)
}
}
} else {
let cstore = cx.sess.cstore;
match csearch::get_region_param(cstore, did) {
- none => {}
- some(variance) => {
+ None => {}
+ Some(variance) => {
debug!("reference to external, rp'd type %s",
pprust::ty_to_str(ty, cx.sess.intr()));
if cx.opt_region_is_relevant(path.rp) {
let c_variance = cx.region_paramd_items.get(c_id);
debug!("popped %d from worklist", c_id);
match cx.dep_map.find(c_id) {
- none => {}
- some(deps) => {
+ None => {}
+ Some(deps) => {
for deps.each |dep| {
let v = add_variance(dep.ambient_variance, c_variance);
cx.add_rp(dep.id, v);
let mut outstanding_references: uint;
- let mut module_target: option<Target>;
- let mut value_target: option<Target>;
- let mut type_target: option<Target>;
+ let mut module_target: Option<Target>;
+ let mut value_target: Option<Target>;
+ let mut type_target: Option<Target>;
let mut used: bool;
self.outstanding_references = 0u;
- self.module_target = none;
- self.value_target = none;
- self.type_target = none;
+ self.module_target = None;
+ self.value_target = None;
+ self.type_target = None;
self.used = false;
}
- fn target_for_namespace(namespace: Namespace) -> option<Target> {
+ fn target_for_namespace(namespace: Namespace) -> Option<Target> {
match namespace {
ModuleNS => return copy self.module_target,
TypeNS => return copy self.type_target,
/// One node in the tree of modules.
struct Module {
let parent_link: ParentLink;
- let mut def_id: option<def_id>;
+ let mut def_id: Option<def_id>;
let children: hashmap<Atom,@NameBindings>;
let imports: DVec<@ImportDirective>;
// The index of the import we're resolving.
let mut resolved_import_count: uint;
- new(parent_link: ParentLink, def_id: option<def_id>) {
+ new(parent_link: ParentLink, def_id: Option<def_id>) {
self.parent_link = parent_link;
self.def_id = def_id;
// XXX: This is a workaround due to is_none in the standard library mistakenly
// requiring a T:copy.
-pure fn is_none<T>(x: option<T>) -> bool {
+pure fn is_none<T>(x: Option<T>) -> bool {
match x {
- none => return true,
- some(_) => return false
+ None => return true,
+ Some(_) => return false
}
}
// bound to.
struct NameBindings {
let mut module_def: ModuleDef; //< Meaning in module namespace.
- let mut type_def: option<Definition>; //< Meaning in type namespace.
- let mut value_def: option<Definition>; //< Meaning in value namespace.
+ let mut type_def: Option<Definition>; //< Meaning in type namespace.
+ let mut value_def: Option<Definition>; //< Meaning in value namespace.
// For error reporting
// XXX: Merge me into Definition.
- let mut module_span: option<span>;
- let mut type_span: option<span>;
- let mut value_span: option<span>;
+ let mut module_span: Option<span>;
+ let mut type_span: Option<span>;
+ let mut value_span: Option<span>;
new() {
self.module_def = NoModuleDef;
- self.type_def = none;
- self.value_def = none;
- self.module_span = none;
- self.type_span = none;
- self.value_span = none;
+ self.type_def = None;
+ self.value_def = None;
+ self.module_span = None;
+ self.type_span = None;
+ self.value_span = None;
}
/// Creates a new module in this set of name bindings.
- fn define_module(parent_link: ParentLink, def_id: option<def_id>,
+ fn define_module(parent_link: ParentLink, def_id: Option<def_id>,
sp: span) {
if self.module_def == NoModuleDef {
let module_ = @Module(parent_link, def_id);
self.module_def = ModuleDef(module_);
- self.module_span = some(sp);
+ self.module_span = Some(sp);
}
}
/// Records a type definition.
fn define_type(privacy: Privacy, def: def, sp: span) {
- self.type_def = some(Definition { privacy: privacy, def: def });
- self.type_span = some(sp);
+ self.type_def = Some(Definition { privacy: privacy, def: def });
+ self.type_span = Some(sp);
}
/// Records a value definition.
fn define_value(privacy: Privacy, def: def, sp: span) {
- self.value_def = some(Definition { privacy: privacy, def: def });
- self.value_span = some(sp);
+ self.value_def = Some(Definition { privacy: privacy, def: def });
+ self.value_span = Some(sp);
}
/// Returns the module node if applicable.
- fn get_module_if_available() -> option<@Module> {
+ fn get_module_if_available() -> Option<@Module> {
match self.module_def {
- NoModuleDef => return none,
- ModuleDef(module_) => return some(module_)
+ NoModuleDef => return None,
+ ModuleDef(module_) => return Some(module_)
}
}
fn defined_in_namespace(namespace: Namespace) -> bool {
match namespace {
ModuleNS => return self.module_def != NoModuleDef,
- TypeNS => return self.type_def != none,
- ValueNS => return self.value_def != none
+ TypeNS => return self.type_def != None,
+ ValueNS => return self.value_def != None
}
}
- fn def_for_namespace(namespace: Namespace) -> option<Definition> {
+ fn def_for_namespace(namespace: Namespace) -> Option<Definition> {
match namespace {
TypeNS => return self.type_def,
ValueNS => return self.value_def,
ModuleNS => match self.module_def {
- NoModuleDef => return none,
+ NoModuleDef => return None,
ModuleDef(module_) =>
match module_.def_id {
- none => return none,
- some(def_id) => {
- return some(Definition {
+ None => return None,
+ Some(def_id) => {
+ return Some(Definition {
privacy: Public,
def: def_mod(def_id)
});
}
}
- fn span_for_namespace(namespace: Namespace) -> option<span> {
+ fn span_for_namespace(namespace: Namespace) -> Option<span> {
match self.def_for_namespace(namespace) {
- some(d) => {
+ Some(d) => {
match namespace {
TypeNS => self.type_span,
ValueNS => self.value_span,
ModuleNS => self.module_span
}
}
- none => none
+ None => None
}
}
}
let mut xray_context: XrayFlag;
// The trait that the current context can refer to.
- let mut current_trait_refs: option<@DVec<def_id>>;
+ let mut current_trait_refs: Option<@DVec<def_id>>;
// The atom for the keyword "self".
let self_atom: Atom;
self.graph_root = @NameBindings();
(*self.graph_root).define_module(NoParentLink,
- some({ crate: 0, node: 0 }),
+ Some({ crate: 0, node: 0 }),
crate.span);
self.unused_import_lint_level = unused_import_lint_level(session);
self.label_ribs = @dvec();
self.xray_context = NoXray;
- self.current_trait_refs = none;
+ self.current_trait_refs = None;
self.self_atom = syntax::parse::token::special_idents::self_;
self.primitive_type_table = @PrimitiveTypeTable(self.session.
// Add or reuse the child.
let new_parent = ModuleReducedGraphParent(module_);
match module_.children.find(name) {
- none => {
+ None => {
let child = @NameBindings();
module_.children.insert(name, child);
return (child, new_parent);
}
- some(child) => {
+ Some(child) => {
// We don't want to complain if the multiple definitions
// are in different namespaces.
match ns.find(|n| child.defined_in_namespace(n)) {
- some(ns) => {
+ Some(ns) => {
self.session.span_err(sp,
#fmt("Duplicate definition of %s %s",
namespace_to_str(ns),
let parent_link = self.get_parent_link(new_parent, atom);
let def_id = { crate: 0, node: item.id };
- (*name_bindings).define_module(parent_link, some(def_id),
+ (*name_bindings).define_module(parent_link, Some(def_id),
sp);
let new_parent =
let parent_link = self.get_parent_link(new_parent, atom);
let def_id = { crate: 0, node: item.id };
- (*name_bindings).define_module(parent_link, some(def_id),
+ (*name_bindings).define_module(parent_link, Some(def_id),
sp);
let new_parent =
item_class(struct_definition, _) => {
let new_parent =
match struct_definition.ctor {
- none => {
+ None => {
let (name_bindings, new_parent) =
self.add_child(atom, parent, ~[TypeNS], sp);
sp);
new_parent
}
- some(ctor) => {
+ Some(ctor) => {
let (name_bindings, new_parent) =
self.add_child(atom, parent, ~[ValueNS, TypeNS],
sp);
view_item_use(name, _, node_id) => {
match find_use_stmt_cnum(self.session.cstore, node_id) {
- some(crate_id) => {
+ Some(crate_id) => {
let (child_name_bindings, new_parent) =
// should this be in ModuleNS? --tjc
self.add_child(name, parent, ~[ModuleNS],
(self.get_module_from_parent(new_parent), name);
(*child_name_bindings).define_module(parent_link,
- some(def_id),
+ Some(def_id),
view_item.span);
self.build_reduced_graph_for_external_crate
((*child_name_bindings).get_module());
}
- none => {
+ None => {
/* Ignore. */
}
}
let parent_module = self.get_module_from_parent(parent);
let new_module = @Module(BlockParentLink(parent_module, block_id),
- none);
+ None);
parent_module.anonymous_children.insert(block_id, new_module);
new_parent = ModuleReducedGraphParent(new_module);
} else {
let parent_link = self.get_parent_link(new_parent, atom);
match modules.find(def_id) {
- none => {
+ None => {
child_name_bindings.define_module(parent_link,
- some(def_id),
+ Some(def_id),
dummy_sp());
modules.insert(def_id,
child_name_bindings.get_module());
}
- some(existing_module) => {
+ Some(existing_module) => {
// Create an import resolution to
// avoid creating cycles in the
// module graph.
let name_bindings = parent_module.children.get(atom);
resolution.module_target =
- some(Target(parent_module, name_bindings));
+ Some(Target(parent_module, name_bindings));
}
}
debug!("(building reduced graph for \
external crate) already created \
module");
- module_.def_id = some(def_id);
+ module_.def_id = Some(def_id);
modules.insert(def_id, module_);
}
}
match get_method_names_if_trait(self.session.cstore,
def_id) {
- none => {
+ None => {
// Nothing to do.
}
- some(method_names) => {
+ Some(method_names) => {
let interned_method_names = @atom_hashmap();
for method_names.each |method_data| {
let (method_name, self_ty) = method_data;
let parent_link = self.get_parent_link(new_parent,
ident);
(*child_name_bindings).define_module(parent_link,
- none, dummy_sp());
+ None, dummy_sp());
}
ModuleDef(_) => { /* Fall through. */ }
}
match *subclass {
SingleImport(target, _) => {
match module_.import_resolutions.find(target) {
- some(resolution) => {
+ Some(resolution) => {
resolution.outstanding_references += 1u;
}
- none => {
+ None => {
let resolution = @ImportResolution(span);
resolution.outstanding_references = 1u;
module_.import_resolutions.insert(target, resolution);
for module_.children.each |_name, child_node| {
match (*child_node).get_module_if_available() {
- none => {
+ None => {
// Nothing to do.
}
- some(child_module) => {
+ Some(child_module) => {
self.resolve_imports_for_module_subtree(child_module);
}
}
// Search for direct children of the containing module.
match containing_module.children.find(source) {
- none => {
+ None => {
// Continue.
}
- some(child_name_bindings) => {
+ Some(child_name_bindings) => {
if (*child_name_bindings).defined_in_namespace(ModuleNS) {
module_result = BoundResult(containing_module,
child_name_bindings);
// module.
match containing_module.import_resolutions.find(source) {
- none => {
+ None => {
// The containing module definitely doesn't have an
// exported import with the name in question. We can
// therefore accurately report that the names are
type_result = UnboundResult;
}
}
- some(import_resolution)
+ Some(import_resolution)
if import_resolution.outstanding_references
== 0u => {
match (*import_resolution).
target_for_namespace(namespace) {
- none => {
+ None => {
return UnboundResult;
}
- some(target) => {
+ Some(target) => {
import_resolution.used = true;
return BoundResult(target.target_module,
target.bindings);
TypeNS);
}
}
- some(_) => {
+ Some(_) => {
// The import is unresolved. Bail out.
debug!("(resolving single import) unresolved import; \
bailing out");
BoundResult(target_module, name_bindings) => {
debug!("(resolving single import) found module binding");
import_resolution.module_target =
- some(Target(target_module, name_bindings));
+ Some(Target(target_module, name_bindings));
}
UnboundResult => {
debug!("(resolving single import) didn't find module \
match value_result {
BoundResult(target_module, name_bindings) => {
import_resolution.value_target =
- some(Target(target_module, name_bindings));
+ Some(Target(target_module, name_bindings));
}
UnboundResult => { /* Continue. */ }
UnknownResult => {
match type_result {
BoundResult(target_module, name_bindings) => {
import_resolution.type_target =
- some(Target(target_module, name_bindings));
+ Some(Target(target_module, name_bindings));
}
UnboundResult => { /* Continue. */ }
UnknownResult => {
If this name wasn't found in any of the four namespaces, it's
definitely unresolved
*/
- (none, none, none) => { return Failed; }
+ (None, None, None) => { return Failed; }
_ => {}
}
// Here we merge two import resolutions.
match module_.import_resolutions.find(atom) {
- none => {
+ None => {
// Simple: just copy the old import resolution.
let new_import_resolution =
@ImportResolution(target_import_resolution.span);
module_.import_resolutions.insert
(atom, new_import_resolution);
}
- some(dest_import_resolution) => {
+ Some(dest_import_resolution) => {
// Merge the two import resolutions at a finer-grained
// level.
match copy target_import_resolution.module_target {
- none => {
+ None => {
// Continue.
}
- some(module_target) => {
+ Some(module_target) => {
dest_import_resolution.module_target =
- some(copy module_target);
+ Some(copy module_target);
}
}
match copy target_import_resolution.value_target {
- none => {
+ None => {
// Continue.
}
- some(value_target) => {
+ Some(value_target) => {
dest_import_resolution.value_target =
- some(copy value_target);
+ Some(copy value_target);
}
}
match copy target_import_resolution.type_target {
- none => {
+ None => {
// Continue.
}
- some(type_target) => {
+ Some(type_target) => {
dest_import_resolution.type_target =
- some(copy type_target);
+ Some(copy type_target);
}
}
}
let mut dest_import_resolution;
match module_.import_resolutions.find(atom) {
- none => {
+ None => {
// Create a new import resolution from this child.
dest_import_resolution = @ImportResolution(span);
module_.import_resolutions.insert
(atom, dest_import_resolution);
}
- some(existing_import_resolution) => {
+ Some(existing_import_resolution) => {
dest_import_resolution = existing_import_resolution;
}
}
if (*name_bindings).defined_in_namespace(ModuleNS) {
debug!("(resolving glob import) ... for module target");
dest_import_resolution.module_target =
- some(Target(containing_module, name_bindings));
+ Some(Target(containing_module, name_bindings));
}
if (*name_bindings).defined_in_namespace(ValueNS) {
debug!("(resolving glob import) ... for value target");
dest_import_resolution.value_target =
- some(Target(containing_module, name_bindings));
+ Some(Target(containing_module, name_bindings));
}
if (*name_bindings).defined_in_namespace(TypeNS) {
debug!("(resolving glob import) ... for type target");
dest_import_resolution.type_target =
- some(Target(containing_module, name_bindings));
+ Some(Target(containing_module, name_bindings));
}
}
// its immediate children.
match module_.children.find(name) {
- some(name_bindings)
+ Some(name_bindings)
if (*name_bindings).defined_in_namespace(namespace) => {
return Success(Target(module_, name_bindings));
}
- some(_) | none => { /* Not found; continue. */ }
+ Some(_) | None => { /* Not found; continue. */ }
}
// Now check for its import directives. We don't have to have resolved
// current scope.
match module_.import_resolutions.find(name) {
- none => {
+ None => {
// Not found; continue.
}
- some(import_resolution) => {
+ Some(import_resolution) => {
match (*import_resolution).target_for_namespace(namespace) {
- none => {
+ None => {
// Not found; continue.
debug!("(resolving item in lexical scope) found \
import resolution, but not in namespace %?",
namespace);
}
- some(target) => {
+ Some(target) => {
import_resolution.used = true;
return Success(copy target);
}
// First, check the direct children of the module.
match module_.children.find(name) {
- some(name_bindings)
+ Some(name_bindings)
if (*name_bindings).defined_in_namespace(namespace) => {
debug!("(resolving name in module) found node as child");
return Success(Target(module_, name_bindings));
}
- some(_) | none => {
+ Some(_) | None => {
// Continue.
}
}
// Otherwise, we check the list of resolved imports.
match module_.import_resolutions.find(name) {
- some(import_resolution) => {
+ Some(import_resolution) => {
if import_resolution.outstanding_references != 0u {
debug!("(resolving name in module) import unresolved; \
bailing out");
}
match (*import_resolution).target_for_namespace(namespace) {
- none => {
+ None => {
debug!("(resolving name in module) name found, but \
not in namespace %?",
namespace);
}
- some(target) => {
+ Some(target) => {
debug!("(resolving name in module) resolved to \
import");
import_resolution.used = true;
}
}
}
- none => {
+ None => {
// Continue.
}
}
Failed => {
debug!("(resolving one-level renaming import) didn't find \
module result");
- module_result = none;
+ module_result = None;
}
Indeterminate => {
debug!("(resolving one-level renaming import) module result \
Success(name_bindings) => {
debug!("(resolving one-level renaming import) module result \
found");
- module_result = some(copy name_bindings);
+ module_result = Some(copy name_bindings);
}
}
Failed => {
debug!("(resolving one-level renaming import) didn't find \
value result");
- value_result = none;
+ value_result = None;
}
Indeterminate => {
debug!("(resolving one-level renaming import) value result \
Success(name_bindings) => {
debug!("(resolving one-level renaming import) value result \
found");
- value_result = some(copy name_bindings);
+ value_result = Some(copy name_bindings);
}
}
Failed => {
debug!("(resolving one-level renaming import) didn't find \
type result");
- type_result = none;
+ type_result = None;
}
Indeterminate => {
debug!("(resolving one-level renaming import) type result is \
Success(name_bindings) => {
debug!("(resolving one-level renaming import) type result \
found");
- type_result = some(copy name_bindings);
+ type_result = Some(copy name_bindings);
}
}
// Otherwise, proceed and write in the bindings.
match module_.import_resolutions.find(target_name) {
- none => {
+ None => {
fail ~"(resolving one-level renaming import) reduced graph \
construction or glob importing should have created the \
import resolution name by now";
}
- some(import_resolution) => {
+ Some(import_resolution) => {
debug!("(resolving one-level renaming import) writing module \
result %? for `%s` into `%s`",
is_none(module_result),
// Descend into children and anonymous children.
for module_.children.each |_name, child_node| {
match (*child_node).get_module_if_available() {
- none => {
+ None => {
// Continue.
}
- some(child_module) => {
+ Some(child_module) => {
self.report_unresolved_imports(child_module);
}
}
// exports for local crates.
match module_.def_id {
- some(def_id) if def_id.crate == local_crate => {
+ Some(def_id) if def_id.crate == local_crate => {
// OK. Continue.
}
- none => {
+ None => {
// Record exports for the root module.
}
- some(_) => {
+ Some(_) => {
// Bail out.
debug!("(recording exports for module subtree) not recording \
exports for `%s`",
for module_.children.each |_atom, child_name_bindings| {
match (*child_name_bindings).get_module_if_available() {
- none => {
+ None => {
// Nothing to do.
}
- some(child_module) => {
+ Some(child_module) => {
self.record_exports_for_module_subtree(child_module);
}
}
}
match copy module_.def_id {
- some(def_id) => {
+ Some(def_id) => {
self.export_map2.insert(def_id.node, move exports2);
debug!("(computing exports) writing exports for %d (some)",
def_id.node);
}
- none => {}
+ None => {}
}
}
// generate a fake "implementation scope" containing all the
// implementations thus found, for compatibility with old resolve pass.
- fn with_scope(name: option<Atom>, f: fn()) {
+ fn with_scope(name: Option<Atom>, f: fn()) {
let orig_module = self.current_module;
// Move down in the graph.
match name {
- none => {
+ None => {
// Nothing to do.
}
- some(name) => {
+ Some(name) => {
match orig_module.children.find(name) {
- none => {
+ None => {
debug!("!!! (with scope) didn't find `%s` in `%s`",
self.session.str_of(name),
self.module_to_str(orig_module));
}
- some(name_bindings) => {
+ Some(name_bindings) => {
match (*name_bindings).get_module_if_available() {
- none => {
+ None => {
debug!("!!! (with scope) didn't find module \
for `%s` in `%s`",
self.session.str_of(name),
self.module_to_str(orig_module));
}
- some(module_) => {
+ Some(module_) => {
self.current_module = module_;
}
}
fn upvarify(ribs: @DVec<@Rib>, rib_index: uint, def_like: def_like,
span: span, allow_capturing_self: AllowCapturingSelfFlag)
- -> option<def_like> {
+ -> Option<def_like> {
let mut def;
let mut is_ty_param;
is_ty_param = false;
}
_ => {
- return some(def_like);
+ return Some(def_like);
}
}
// item, it's ok
match def {
def_ty_param(did, _) if self.def_map.find(copy(did.node))
- == some(def_typaram_binder(item_id)) => {
+ == Some(def_typaram_binder(item_id)) => {
// ok
}
_ => {
argument out of scope");
}
- return none;
+ return None;
}
}
}
argument out of scope");
}
- return none;
+ return None;
}
}
rib_index += 1u;
}
- return some(dl_def(def));
+ return Some(dl_def(def));
}
fn search_ribs(ribs: @DVec<@Rib>, name: Atom, span: span,
allow_capturing_self: AllowCapturingSelfFlag)
- -> option<def_like> {
+ -> Option<def_like> {
// XXX: This should not use a while loop.
// XXX: Try caching?
i -= 1u;
let rib = (*ribs).get_elt(i);
match rib.bindings.find(name) {
- some(def_like) => {
+ Some(def_like) => {
return self.upvarify(ribs, i, def_like, span,
allow_capturing_self);
}
- none => {
+ None => {
// Continue.
}
}
}
- return none;
+ return None;
}
fn resolve_crate(@self) {
for traits.each |trt| {
match self.resolve_path(trt.path, TypeNS, true,
visitor) {
- none =>
+ None =>
self.session.span_err(trt.path.span,
~"attempt to derive a \
nonexistent trait"),
- some(def) => {
+ Some(def) => {
// Write a mapping from the trait ID to the
// definition of the trait into the definition
// map.
}
item_mod(module_) => {
- do self.with_scope(some(item.ident)) {
+ do self.with_scope(Some(item.ident)) {
self.resolve_module(module_, item.span, item.ident,
item.id, visitor);
}
}
item_foreign_mod(foreign_module) => {
- do self.with_scope(some(item.ident)) {
+ do self.with_scope(Some(item.ident)) {
for foreign_module.items.each |foreign_item| {
match foreign_item.node {
foreign_item_fn(_, _, type_parameters) => {
is_none(self.session.main_fn) &&
item.ident == syntax::parse::token::special_idents::main {
- self.session.main_fn = some((item.id, item.span));
+ self.session.main_fn = Some((item.id, item.span));
}
self.resolve_function(OpaqueFunctionRibKind,
- some(@fn_decl),
+ Some(@fn_decl),
HasTypeParameters
(&ty_params,
item.id,
}
fn resolve_function(rib_kind: RibKind,
- optional_declaration: option<@fn_decl>,
+ optional_declaration: Option<@fn_decl>,
type_parameters: TypeParameters,
block: blk,
self_binding: SelfBinding,
ValueNS,
true,
capture_item.span) {
- none => {
+ None => {
self.session.span_err(capture_item.span,
~"unresolved name in \
capture clause");
}
- some(def) => {
+ Some(def) => {
self.record_def(capture_item.id, def);
}
}
// Add each argument to the rib.
match optional_declaration {
- none => {
+ None => {
// Nothing to do.
}
- some(declaration) => {
+ Some(declaration) => {
for declaration.inputs.each |argument| {
let name = argument.ident;
let def_like = dl_def(def_arg(argument.id,
traits: ~[@trait_ref],
fields: ~[@struct_field],
methods: ~[@method],
- optional_constructor: option<class_ctor>,
- optional_destructor: option<class_dtor>,
+ optional_constructor: Option<class_ctor>,
+ optional_destructor: Option<class_dtor>,
visitor: ResolveVisitor) {
// If applicable, create a rib for the type parameters.
// Resolve implemented traits.
for traits.each |trt| {
match self.resolve_path(trt.path, TypeNS, true, visitor) {
- none => {
+ None => {
self.session.span_err(trt.path.span,
~"attempt to implement a \
nonexistent trait");
}
- some(def) => {
+ Some(def) => {
// Write a mapping from the trait ID to the
// definition of the trait into the definition
// map.
// Resolve the constructor, if applicable.
match optional_constructor {
- none => {
+ None => {
// Nothing to do.
}
- some(constructor) => {
+ Some(constructor) => {
self.resolve_function(NormalRibKind,
- some(@constructor.node.dec),
+ Some(@constructor.node.dec),
NoTypeParameters,
constructor.node.body,
HasSelfBinding(constructor.node.
// Resolve the destructor, if applicable.
match optional_destructor {
- none => {
+ None => {
// Nothing to do.
}
- some(destructor) => {
+ Some(destructor) => {
self.resolve_function(NormalRibKind,
- none,
+ None,
NoTypeParameters,
destructor.node.body,
HasSelfBinding
};
self.resolve_function(rib_kind,
- some(@method.decl),
+ Some(@method.decl),
type_parameters,
method.body,
self_binding,
for trait_references.each |trait_reference| {
match self.resolve_path(
trait_reference.path, TypeNS, true, visitor) {
- none => {
+ None => {
self.session.span_err(span,
~"attempt to implement an \
unknown trait");
}
- some(def) => {
+ Some(def) => {
self.record_def(trait_reference.ref_id, def);
// Record the current trait reference.
}
// Record the current set of trait references.
- self.current_trait_refs = some(new_trait_refs);
+ self.current_trait_refs = Some(new_trait_refs);
}
// Resolve the self type.
/*
let borrowed_type_parameters = &method.tps;
self.resolve_function(MethodRibKind(id, Provided(method.id)),
- some(@method.decl),
+ Some(@method.decl),
HasTypeParameters
(borrowed_type_parameters,
method.id,
// Resolve the initializer, if necessary.
match local.node.init {
- none => {
+ None => {
// Nothing to do.
}
- some(initializer) => {
+ Some(initializer) => {
self.resolve_expr(initializer.expr, visitor);
}
}
// Resolve the pattern.
self.resolve_pattern(local.node.pat, IrrefutableMode, mutability,
- none, visitor);
+ None, visitor);
}
fn binding_mode_map(pat: @pat) -> BindingMap {
for map_0.each |key, binding_0| {
match map_i.find(key) {
- none => {
+ None => {
self.session.span_err(
p.span,
fmt!("variable `%s` from pattern #1 is \
not bound in pattern #%u",
self.session.str_of(key), i + 1));
}
- some(binding_i) => {
+ Some(binding_i) => {
if binding_0.binding_mode != binding_i.binding_mode {
self.session.span_err(
binding_i.span,
let bindings_list = atom_hashmap();
for arm.pats.each |pattern| {
self.resolve_pattern(pattern, RefutableMode, Immutable,
- some(bindings_list), visitor);
+ Some(bindings_list), visitor);
}
// This has to happen *after* we determine which
// Move down in the graph, if there's an anonymous module rooted here.
let orig_module = self.current_module;
match self.current_module.anonymous_children.find(block.node.id) {
- none => { /* Nothing to do. */ }
- some(anonymous_module) => {
+ None => { /* Nothing to do. */ }
+ Some(anonymous_module) => {
debug!("(resolving block) found anonymous module, moving \
down");
self.current_module = anonymous_module;
let mut result_def;
match self.resolve_path(path, TypeNS, true, visitor) {
- some(def) => {
+ Some(def) => {
debug!("(resolving type) resolved `%s` to type",
self.session.str_of(path.idents.last()));
- result_def = some(def);
+ result_def = Some(def);
}
- none => {
- result_def = none;
+ None => {
+ result_def = None;
}
}
match result_def {
- some(_) => {
+ Some(_) => {
// Continue.
}
- none => {
+ None => {
// Check to see whether the name is a primitive type.
if path.idents.len() == 1u {
let name = path.idents.last();
.primitive_types
.find(name) {
- some(primitive_type) => {
+ Some(primitive_type) => {
result_def =
- some(def_prim_ty(primitive_type));
+ Some(def_prim_ty(primitive_type));
}
- none => {
+ None => {
// Continue.
}
}
}
match copy result_def {
- some(def) => {
+ Some(def) => {
// Write the result into the def map.
debug!("(resolving type) writing resolution for `%s` \
(id %d)",
path_id);
self.record_def(path_id, def);
}
- none => {
+ None => {
self.session.span_err
(ty.span, fmt!("use of undeclared type name `%s`",
connect(path.idents.map(
mutability: Mutability,
// Maps idents to the node ID for the (outermost)
// pattern that binds them
- bindings_list: option<hashmap<Atom,node_id>>,
+ bindings_list: Option<hashmap<Atom,node_id>>,
visitor: ResolveVisitor) {
let pat_id = pattern.id;
// passes make about or-patterns.)
match bindings_list {
- some(bindings_list)
+ Some(bindings_list)
if !bindings_list.contains_key(atom) => {
let last_rib = (*self.value_ribs).last();
last_rib.bindings.insert(atom,
dl_def(def));
bindings_list.insert(atom, pat_id);
}
- some(b) => {
- if b.find(atom) == some(pat_id) {
+ Some(b) => {
+ if b.find(atom) == Some(pat_id) {
// Then this is a duplicate variable
// in the same disjunct, which is an
// error
}
// Not bound in the same pattern: do nothing
}
- none => {
+ None => {
let last_rib = (*self.value_ribs).last();
last_rib.bindings.insert(atom,
dl_def(def));
pat_ident(_, path, _) | pat_enum(path, _) => {
// These two must be enum variants.
match self.resolve_path(path, ValueNS, false, visitor) {
- some(def @ def_variant(*)) => {
+ Some(def @ def_variant(*)) => {
self.record_def(pattern.id, def);
}
- some(_) => {
+ Some(_) => {
self.session.span_err(
path.span,
fmt!("not an enum variant: %s",
self.session.str_of(
path.idents.last())));
}
- none => {
+ None => {
self.session.span_err(path.span,
~"unresolved enum variant");
}
pat_struct(path, _, _) => {
match self.resolve_path(path, TypeNS, false, visitor) {
- some(def_ty(class_id))
+ Some(def_ty(class_id))
if self.structs.contains_key(class_id) => {
let has_constructor = self.structs.get(class_id);
let class_def = def_class(class_id,
has_constructor);
self.record_def(pattern.id, class_def);
}
- some(definition @ def_variant(_, variant_id))
+ Some(definition @ def_variant(_, variant_id))
if self.structs.contains_key(variant_id) => {
self.record_def(pattern.id, definition);
}
Success(target) => {
match target.bindings.value_def {
- none => {
+ None => {
fail ~"resolved name in the value namespace to a set \
of name bindings with no def?!";
}
- some(def) => {
+ Some(def) => {
match def.def {
def @ def_variant(*) => {
return FoundEnumVariant(def);
*/
fn resolve_path(path: @path, namespace: Namespace, check_ribs: bool,
visitor: ResolveVisitor)
- -> option<def> {
+ -> Option<def> {
// First, resolve the types.
for path.types.each |ty| {
namespace: Namespace,
check_ribs: bool,
span: span)
- -> option<def> {
+ -> Option<def> {
if check_ribs {
match self.resolve_identifier_in_local_ribs(identifier,
namespace,
span) {
- some(def) => {
- return some(def);
+ Some(def) => {
+ return Some(def);
}
- none => {
+ None => {
// Continue.
}
}
// First, search children.
match containing_module.children.find(name) {
- some(child_name_bindings) => {
+ Some(child_name_bindings) => {
match (*child_name_bindings).def_for_namespace(namespace) {
- some(def) if def.privacy == Public => {
+ Some(def) if def.privacy == Public => {
// Found it. Stop the search here.
return ChildNameDefinition(def.def);
}
- some(_) | none => {
+ Some(_) | None => {
// Continue.
}
}
}
- none => {
+ None => {
// Continue.
}
}
// Next, search import resolutions.
match containing_module.import_resolutions.find(name) {
- some(import_resolution) => {
+ Some(import_resolution) => {
match (*import_resolution).target_for_namespace(namespace) {
- some(target) => {
+ Some(target) => {
match (*target.bindings)
.def_for_namespace(namespace) {
- some(def) if def.privacy == Public => {
+ Some(def) if def.privacy == Public => {
// Found it.
import_resolution.used = true;
return ImportNameDefinition(def.def);
}
- some(_) | none => {
+ Some(_) | None => {
// This can happen with external impls, due to
// the imperfect way we read the metadata.
}
}
}
- none => {
+ None => {
return NoNameDefinition;
}
}
}
- none => {
+ None => {
return NoNameDefinition;
}
}
fn resolve_module_relative_path(path: @path,
+xray: XrayFlag,
namespace: Namespace)
- -> option<def> {
+ -> Option<def> {
let module_path_atoms = self.intern_module_part_of_path(path);
fmt!("use of undeclared module `%s`",
self.atoms_to_str(
(*module_path_atoms).get())));
- return none;
+ return None;
}
Indeterminate => {
fmt!("unresolved name: %s::%s",
self.atoms_to_str((*module_path_atoms).get()),
self.session.str_of(name)));
- return none;
+ return None;
}
ChildNameDefinition(def) | ImportNameDefinition(def) => {
- return some(def);
+ return Some(def);
}
}
}
fn resolve_crate_relative_path(path: @path,
+xray: XrayFlag,
namespace: Namespace)
- -> option<def> {
+ -> Option<def> {
let module_path_atoms = self.intern_module_part_of_path(path);
fmt!("use of undeclared module `::%s`",
self.atoms_to_str
((*module_path_atoms).get())));
- return none;
+ return None;
}
Indeterminate => {
fmt!("unresolved name: %s::%s", self.atoms_to_str(
(*module_path_atoms).get()),
self.session.str_of(name)));
- return none;
+ return None;
}
ChildNameDefinition(def) | ImportNameDefinition(def) => {
- return some(def);
+ return Some(def);
}
}
}
fn resolve_identifier_in_local_ribs(ident: ident,
namespace: Namespace,
span: span)
- -> option<def> {
+ -> Option<def> {
// Check the local set of ribs.
let mut search_result;
match namespace {
}
match copy search_result {
- some(dl_def(def)) => {
+ Some(dl_def(def)) => {
debug!("(resolving path in local ribs) resolved `%s` to \
local: %?",
self.session.str_of(ident),
def);
- return some(def);
+ return Some(def);
}
- some(dl_field) | some(dl_impl(_)) | none => {
- return none;
+ Some(dl_field) | Some(dl_impl(_)) | None => {
+ return None;
}
}
}
fn resolve_item_by_identifier_in_lexical_scope(ident: ident,
namespace: Namespace)
- -> option<def> {
+ -> Option<def> {
// Check the items.
match self.resolve_item_in_lexical_scope(self.current_module,
Success(target) => {
match (*target.bindings).def_for_namespace(namespace) {
- none => {
+ None => {
fail ~"resolved name in a namespace to a set of name \
bindings with no def for that namespace?!";
}
- some(def) => {
+ Some(def) => {
debug!("(resolving item path in lexical scope) \
resolved `%s` to item",
self.session.str_of(ident));
- return some(def.def);
+ return Some(def.def);
}
}
}
fail ~"unexpected indeterminate result";
}
Failed => {
- return none;
+ return None;
}
}
}
// scopes looking for it.
match self.resolve_path(path, ValueNS, true, visitor) {
- some(def) => {
+ Some(def) => {
// Write the result into the def map.
debug!("(resolving expr) resolved `%s`",
connect(path.idents.map(
|x| self.session.str_of(x)), ~"::"));
self.record_def(expr.id, def);
}
- none => {
+ None => {
let wrong_name =
connect(path.idents.map(
|x| self.session.str_of(x)), ~"::") ;
expr_fn(_, fn_decl, block, capture_clause) |
expr_fn_block(fn_decl, block, capture_clause) => {
self.resolve_function(FunctionRibKind(expr.id, block.node.id),
- some(@fn_decl),
+ Some(@fn_decl),
NoTypeParameters,
block,
NoSelfBinding,
// let bar = Bar { ... } // no type parameters
match self.resolve_path(path, TypeNS, false, visitor) {
- some(def_ty(class_id)) | some(def_class(class_id, _))
+ Some(def_ty(class_id)) | Some(def_class(class_id, _))
if self.structs.contains_key(class_id) => {
let has_constructor = self.structs.get(class_id);
let class_def = def_class(class_id, has_constructor);
self.record_def(expr.id, class_def);
}
- some(definition @ def_variant(_, class_id))
+ Some(definition @ def_variant(_, class_id))
if self.structs.contains_key(class_id) => {
self.record_def(expr.id, definition);
}
visit_expr(expr, (), visitor);
}
- expr_loop(_, some(label)) => {
+ expr_loop(_, Some(label)) => {
do self.with_label_rib {
let def_like = dl_def(def_label(expr.id));
self.label_ribs.last().bindings.insert(label, def_like);
}
}
- expr_break(some(label)) | expr_again(some(label)) => {
+ expr_break(Some(label)) | expr_again(Some(label)) => {
match self.search_ribs(self.label_ribs, label, expr.span,
DontAllowCapturingSelf) {
- none =>
+ None =>
self.session.span_err(expr.span,
fmt!("use of undeclared label \
`%s`", self.session.str_of(
label))),
- some(dl_def(def @ def_label(id))) =>
+ Some(dl_def(def @ def_label(id))) =>
self.record_def(expr.id, def),
- some(_) =>
+ Some(_) =>
self.session.span_bug(expr.span,
~"label wasn't mapped to a \
label def!")
loop {
// Look for the current trait.
match copy self.current_trait_refs {
- some(trait_def_ids) => {
+ Some(trait_def_ids) => {
for trait_def_ids.each |trait_def_id| {
self.add_trait_info_if_containing_method
(found_traits, trait_def_id, name);
}
}
- none => {
+ None => {
// Nothing to do.
}
}
// Look for trait children.
for search_module.children.each |_name, child_name_bindings| {
match child_name_bindings.def_for_namespace(TypeNS) {
- some(def) => {
+ Some(def) => {
match def.def {
def_ty(trait_def_id) => {
self.add_trait_info_if_containing_method
}
}
}
- none => {
+ None => {
// Continue.
}
}
|_atom, import_resolution| {
match import_resolution.target_for_namespace(TypeNS) {
- none => {
+ None => {
// Continue.
}
- some(target) => {
+ Some(target) => {
match target.bindings.def_for_namespace(TypeNS) {
- some(def) => {
+ Some(def) => {
match def.def {
def_ty(trait_def_id) => {
self.
}
}
}
- none => {
+ None => {
// Continue.
}
}
name: Atom) {
match self.trait_info.find(trait_def_id) {
- some(trait_info) if trait_info.contains_key(name) => {
+ Some(trait_info) if trait_info.contains_key(name) => {
debug!("(adding trait info if containing method) found trait \
%d:%d for method '%s'",
trait_def_id.crate,
self.session.str_of(name));
(*found_traits).push(trait_def_id);
}
- some(_) | none => {
+ Some(_) | None => {
// Continue.
}
}
}
- fn add_fixed_trait_for_expr(expr_id: node_id, +trait_id: option<def_id>) {
+ fn add_fixed_trait_for_expr(expr_id: node_id, +trait_id: Option<def_id>) {
let traits = @dvec();
traits.push(trait_id.get());
self.trait_map.insert(expr_id, traits);
// for unused imports in external crates.
match module_.def_id {
- some(def_id) if def_id.crate == local_crate => {
+ Some(def_id) if def_id.crate == local_crate => {
// OK. Continue.
}
- none => {
+ None => {
// Check for unused imports in the root module.
}
- some(_) => {
+ Some(_) => {
// Bail out.
debug!("(checking for unused imports in module subtree) not \
checking for unused imports for `%s`",
for module_.children.each |_atom, child_name_bindings| {
match (*child_name_bindings).get_module_if_available() {
- none => {
+ None => {
// Nothing to do.
}
- some(child_module) => {
+ Some(child_module) => {
self.check_for_unused_imports_in_module_subtree
(child_module);
}
for module_.import_resolutions.each |name, import_resolution| {
let mut module_repr;
match (*import_resolution).target_for_namespace(ModuleNS) {
- none => { module_repr = ~""; }
- some(target) => {
+ None => { module_repr = ~""; }
+ Some(target) => {
module_repr = ~" module:?";
// XXX
}
let mut value_repr;
match (*import_resolution).target_for_namespace(ValueNS) {
- none => { value_repr = ~""; }
- some(target) => {
+ None => { value_repr = ~""; }
+ Some(target) => {
value_repr = ~" value:?";
// XXX
}
let mut type_repr;
match (*import_resolution).target_for_namespace(TypeNS) {
- none => { type_repr = ~""; }
- some(target) => {
+ None => { type_repr = ~""; }
+ Some(target) => {
type_repr = ~" type:?";
// XXX
}
ast::vstore_uniq) => {
let strty = ty::mk_estr(bcx.tcx(), ty::vstore_uniq);
let cell = empty_dest_cell();
- bcx = tvec::trans_estr(bcx, s, some(ast::vstore_uniq),
+ bcx = tvec::trans_estr(bcx, s, Some(ast::vstore_uniq),
by_val(cell));
add_clean_temp_immediate(bcx, *cell, strty);
return single_result(rslt(bcx, *cell));
binding: binding
}];
-fn assoc(key: ast::ident, list: bind_map) -> option<binding> {
+fn assoc(key: ast::ident, list: bind_map) -> Option<binding> {
for vec::each(list) |elt| {
if elt.ident == key {
- return some(elt.binding);
+ return Some(elt.binding);
}
}
- return none;
+ return None;
}
type match_branch =
@{pats: ~[@ast::pat],
bound: bind_map,
data: @{bodycx: block,
- guard: option<@ast::expr>,
+ guard: Option<@ast::expr>,
id_map: pat_id_map}};
type match_ = ~[match_branch];
fn has_nested_bindings(m: match_, col: uint) -> bool {
for vec::each(m) |br| {
match br.pats[col].node {
- ast::pat_ident(_, _, some(_)) => return true,
+ ast::pat_ident(_, _, Some(_)) => return true,
_ => ()
}
}
let mut result = ~[];
for vec::each(m) |br| {
match br.pats[col].node {
- ast::pat_ident(mode, name, some(inner)) => {
+ ast::pat_ident(mode, name, Some(inner)) => {
let pats = vec::append(
vec::slice(br.pats, 0u, col),
vec::append(~[inner],
result
}
-type enter_pat = fn(@ast::pat) -> option<~[@ast::pat]>;
+type enter_pat = fn(@ast::pat) -> Option<~[@ast::pat]>;
fn enter_match(bcx: block, dm: DefMap, m: match_, col: uint, val: ValueRef,
e: enter_pat) -> match_ {
let mut result = ~[];
for vec::each(m) |br| {
match e(br.pats[col]) {
- some(sub) => {
+ Some(sub) => {
let pats = vec::append(
vec::append(sub, vec::view(br.pats, 0u, col)),
vec::view(br.pats, col + 1u, br.pats.len()));
let self = br.pats[col];
let bound = match self.node {
- ast::pat_ident(mode, name, none)
+ ast::pat_ident(mode, name, None)
if !pat_is_variant(dm, self) => {
vec::append(br.bound,
~[{ident: path_to_ident(name),
};
vec::push(result, @{pats: pats, bound: bound with *br});
}
- none => ()
+ None => ()
}
}
return result;
do enter_match(bcx, dm, m, col, val) |p| {
match p.node {
ast::pat_wild | ast::pat_rec(_, _) | ast::pat_tup(_) |
- ast::pat_struct(*) => some(~[]),
- ast::pat_ident(_, _, none) if !pat_is_variant(dm, p) => some(~[]),
- _ => none
+ ast::pat_struct(*) => Some(~[]),
+ ast::pat_ident(_, _, None) if !pat_is_variant(dm, p) => Some(~[]),
+ _ => None
}
}
}
match p.node {
ast::pat_enum(_, subpats) => {
if opt_eq(tcx, variant_opt(tcx, p.id), opt) {
- some(option::get_default(subpats,
+ Some(option::get_default(subpats,
vec::from_elem(variant_size, dummy))) }
- else { none }
+ else { None }
}
- ast::pat_ident(_, _, none) if pat_is_variant(tcx.def_map, p) => {
- if opt_eq(tcx, variant_opt(tcx, p.id), opt) { some(~[]) }
- else { none }
+ ast::pat_ident(_, _, None) if pat_is_variant(tcx.def_map, p) => {
+ if opt_eq(tcx, variant_opt(tcx, p.id), opt) { Some(~[]) }
+ else { None }
}
ast::pat_lit(l) => {
- if opt_eq(tcx, lit(l), opt) { some(~[]) } else { none }
+ if opt_eq(tcx, lit(l), opt) { Some(~[]) } else { None }
}
ast::pat_range(l1, l2) => {
- if opt_eq(tcx, range(l1, l2), opt) { some(~[]) } else { none }
+ if opt_eq(tcx, range(l1, l2), opt) { Some(~[]) } else { None }
}
- _ => some(vec::from_elem(variant_size, dummy))
+ _ => Some(vec::from_elem(variant_size, dummy))
}
}
}
}
vec::push(pats, pat);
}
- some(pats)
+ Some(pats)
}
- _ => some(vec::from_elem(fields.len(), dummy))
+ _ => Some(vec::from_elem(fields.len(), dummy))
}
}
}
let dummy = @{id: 0, node: ast::pat_wild, span: dummy_sp()};
do enter_match(bcx, dm, m, col, val) |p| {
match p.node {
- ast::pat_tup(elts) => some(elts),
- _ => some(vec::from_elem(n_elts, dummy))
+ ast::pat_tup(elts) => Some(elts),
+ _ => Some(vec::from_elem(n_elts, dummy))
}
}
}
let dummy = @{id: 0, node: ast::pat_wild, span: dummy_sp()};
do enter_match(bcx, dm, m, col, val) |p| {
match p.node {
- ast::pat_box(sub) => some(~[sub]),
- _ => some(~[dummy])
+ ast::pat_box(sub) => Some(~[sub]),
+ _ => Some(~[dummy])
}
}
}
let dummy = @{id: 0, node: ast::pat_wild, span: dummy_sp()};
do enter_match(bcx, dm, m, col, val) |p| {
match p.node {
- ast::pat_uniq(sub) => some(~[sub]),
- _ => some(~[dummy])
+ ast::pat_uniq(sub) => Some(~[sub]),
+ _ => Some(~[dummy])
}
}
}
let pat_id = br.pats[col].id;
match bcx.ccx().maps.root_map.find({id:pat_id, derefs:0u}) {
- none => (),
- some(scope_id) => {
+ None => (),
+ Some(scope_id) => {
// Note: the scope_id will always be the id of the alt. See the
// extended comment in rustc::middle::borrowck::preserve() for
// details (look for the case covering cat_discr).
fn score(p: @ast::pat) -> uint {
match p.node {
ast::pat_lit(_) | ast::pat_enum(_, _) | ast::pat_range(_, _) => 1u,
- ast::pat_ident(_, _, some(p)) => score(p),
+ ast::pat_ident(_, _, Some(p)) => score(p),
_ => 0u
}
}
}
fn compile_submatch(bcx: block, m: match_, vals: ~[ValueRef],
- chk: option<mk_fail>, &exits: ~[exit_node]) {
+ chk: Option<mk_fail>, &exits: ~[exit_node]) {
/*
For an empty match, a fall-through case must exist
*/
if m[0].pats.len() == 0u {
let data = m[0].data;
match data.guard {
- some(e) => {
+ Some(e) => {
// Temporarily set bindings. They'll be rewritten to PHI nodes
// for the actual arm block.
//
compare => {
let t = node_id_type(bcx, pat_id);
let {bcx: after_cx, val: matches} = {
- do with_scope_result(bcx, none, ~"compare_scope") |bcx| {
+ do with_scope_result(bcx, None, ~"compare_scope") |bcx| {
match trans_opt(bcx, opt) {
single_result({bcx, val}) => {
trans_compare(bcx, ast::eq, test_val, t, val, t)
fn make_phi_bindings(bcx: block,
map: ~[exit_node],
ids: pat_util::pat_id_map)
- -> option<phi_bindings_list> {
+ -> Option<phi_bindings_list> {
let _icx = bcx.insn_ctxt("alt::make_phi_bindings");
let our_block = bcx.llbb as uint;
let mut phi_bindings = ~[];
for ids.each |name, node_id| {
let mut llbbs = ~[];
let mut vals = ~[];
- let mut binding = none;
+ let mut binding = None;
for vec::each(map) |ex| {
if ex.to as uint == our_block {
match assoc(name, ex.bound) {
- some(b) => {
+ Some(b) => {
vec::push(llbbs, ex.from);
vec::push(vals, b.val);
- binding = some(b);
+ binding = Some(b);
}
- none => ()
+ None => ()
}
}
}
let binding = match binding {
- some(binding) => binding,
- none => {
+ Some(binding) => binding,
+ None => {
Unreachable(bcx);
- return none;
+ return None;
}
};
ty: binding.ty
});
}
- return some(move phi_bindings);
+ return Some(move phi_bindings);
}
// Copies by-value bindings into their homes.
}
fn mk_fail(bcx: block, sp: span, msg: ~str,
- done: @mut option<BasicBlockRef>) -> BasicBlockRef {
- match *done { some(bb) => return bb, _ => () }
+ done: @mut Option<BasicBlockRef>) -> BasicBlockRef {
+ match *done { Some(bb) => return bb, _ => () }
let fail_cx = sub_block(bcx, ~"case_fallthrough");
- trans_fail(fail_cx, some(sp), msg);
- *done = some(fail_cx.llbb);
+ trans_fail(fail_cx, Some(sp), msg);
+ *done = Some(fail_cx.llbb);
return fail_cx.llbb;
}
let t = node_id_type(bcx, expr.id);
- let mk_fail = { let fail_cx = @mut none;
+ let mk_fail = { let fail_cx = @mut None;
// special case for uninhabited type
if ty::type_is_empty(tcx, t) {
- some(|| mk_fail(scope_cx, expr.span,
+ Some(|| mk_fail(scope_cx, expr.span,
~"scrutinizing value that can't exist", fail_cx))
}
else {
- none
+ None
}
};
let mut exit_map = ~[];
let body_cx = bodies[i];
let id_map = pat_util::pat_id_map(tcx.def_map, a.pats[0]);
match make_phi_bindings(body_cx, exit_map, id_map) {
- none => {}
- some(phi_bindings) => {
+ None => {}
+ Some(phi_bindings) => {
let body_cx = make_pattern_bindings(body_cx, phi_bindings);
let arm_dest = dup_for_join(dest);
vec::push(arm_dests, arm_dest);
add_clean(bcx, alloc, ty);
} else { bcx.fcx.lllocals.insert(pat.id, local_mem(val)); }
match inner {
- some(pat) => { bcx = bind_irrefutable_pat(bcx, pat, val, true); }
+ Some(pat) => { bcx = bind_irrefutable_pat(bcx, pat, val, true); }
_ => ()
}
}
fn join_returns(parent_cx: block, in_cxs: ~[block],
in_ds: ~[dest], out_dest: dest) -> block {
let out = sub_block(parent_cx, ~"join");
- let mut reachable = false, i = 0u, phi = none;
+ let mut reachable = false, i = 0u, phi = None;
for vec::each(in_cxs) |cx| {
if !cx.unreachable {
Br(cx, out.llbb);
match in_ds[i] {
by_val(cell) => {
if option::is_none(phi) {
- phi = some(EmptyPhi(out, val_ty(*cell)));
+ phi = Some(EmptyPhi(out, val_ty(*cell)));
}
AddIncomingToPhi(option::get(phi), *cell, cx.llbb);
}
fn get_tydesc(ccx: @crate_ctxt, t: ty::t) -> @tydesc_info {
match ccx.tydescs.find(t) {
- some(inf) => inf,
+ Some(inf) => inf,
_ => {
ccx.stats.n_static_tydescs += 1u;
let inf = declare_tydesc(ccx, t);
size: llsize,
align: llalign,
addrspace: addrspace,
- mut take_glue: none,
- mut drop_glue: none,
- mut free_glue: none,
- mut visit_glue: none};
+ mut take_glue: None,
+ mut drop_glue: None,
+ mut free_glue: None,
+ mut visit_glue: None};
log(debug, ~"--- declare_tydesc " + ppaux::ty_to_str(ccx.tcx, t));
return inf;
}
fn make_generic_glue_inner(ccx: @crate_ctxt, t: ty::t,
llfn: ValueRef, helper: glue_helper) -> ValueRef {
let _icx = ccx.insn_ctxt("make_generic_glue_inner");
- let fcx = new_fn_ctxt(ccx, ~[], llfn, none);
+ let fcx = new_fn_ctxt(ccx, ~[], llfn, None);
lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
ccx.stats.n_glues_created += 1u;
// All glue functions take values passed *by alias*; this is a
// llfn is expected be declared to take a parameter of the appropriate
// type, so we don't need to explicitly cast the function parameter.
- let bcx = top_scope_block(fcx, none);
+ let bcx = top_scope_block(fcx, None);
let lltop = bcx.llbb;
let llrawptr0 = llvm::LLVMGetParam(llfn, 3u as c_uint);
helper(bcx, llrawptr0, t);
// calling it.
let take_glue =
match copy ti.take_glue {
- none => { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
- some(v) => {
+ None => { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
+ Some(v) => {
ccx.stats.n_real_glues += 1u;
llvm::LLVMConstPointerCast(v, glue_fn_ty)
}
};
let drop_glue =
match copy ti.drop_glue {
- none => { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
- some(v) => {
+ None => { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
+ Some(v) => {
ccx.stats.n_real_glues += 1u;
llvm::LLVMConstPointerCast(v, glue_fn_ty)
}
};
let free_glue =
match copy ti.free_glue {
- none => { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
- some(v) => {
+ None => { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
+ Some(v) => {
ccx.stats.n_real_glues += 1u;
llvm::LLVMConstPointerCast(v, glue_fn_ty)
}
};
let visit_glue =
match copy ti.visit_glue {
- none => { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
- some(v) => {
+ None => { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
+ Some(v) => {
ccx.stats.n_real_glues += 1u;
llvm::LLVMConstPointerCast(v, glue_fn_ty)
}
// Generate code that, dynamically, indexes into the
// tydesc and calls the drop glue that got set dynamically
call_tydesc_glue_full(bcx, valptr, td, abi::tydesc_field_drop_glue,
- none);
+ None);
trans_free(bcx, v)
}
ty::ty_uniq(*) => {
ty::ty_class(did, ref substs) => {
let tcx = bcx.tcx();
match ty::ty_dtor(tcx, did) {
- some(dtor) => {
+ Some(dtor) => {
trans_class_drop(bcx, v0, dtor, did, substs)
}
- none => {
+ None => {
// No dtor? Just the default case
iter_structural_ty(bcx, v0, t, drop_ty)
}
maybe_instantiate_inline(ccx, did)
} else { did };
assert did.crate == ast::local_crate;
- monomorphic_fn(ccx, did, substs, none, none).val
+ monomorphic_fn(ccx, did, substs, None, None).val
} else if did.crate == ast::local_crate {
get_item_val(ccx, did.node)
} else {
ty::ty_uint(_) => return rslt(cx, f(unsigned_int)),
ty::ty_float(_) => return rslt(cx, f(floating_point)),
ty::ty_type => {
- return rslt(trans_fail(cx, none,
+ return rslt(trans_fail(cx, None,
~"attempt to compare values of type type"),
C_nil());
}
let llfnty = type_of_glue_fn(ccx, ti.ty);
if field == abi::tydesc_field_take_glue {
match ti.take_glue {
- some(_) => (),
- none => {
+ Some(_) => (),
+ None => {
debug!("+++ lazily_emit_tydesc_glue TAKE %s",
ppaux::ty_to_str(ccx.tcx, ti.ty));
let glue_fn = declare_generic_glue(ccx, ti.ty, llfnty, ~"take");
- ti.take_glue = some(glue_fn);
+ ti.take_glue = Some(glue_fn);
make_generic_glue(ccx, ti.ty, glue_fn, make_take_glue, ~"take");
debug!("--- lazily_emit_tydesc_glue TAKE %s",
ppaux::ty_to_str(ccx.tcx, ti.ty));
}
} else if field == abi::tydesc_field_drop_glue {
match ti.drop_glue {
- some(_) => (),
- none => {
+ Some(_) => (),
+ None => {
debug!("+++ lazily_emit_tydesc_glue DROP %s",
ppaux::ty_to_str(ccx.tcx, ti.ty));
let glue_fn = declare_generic_glue(ccx, ti.ty, llfnty, ~"drop");
- ti.drop_glue = some(glue_fn);
+ ti.drop_glue = Some(glue_fn);
make_generic_glue(ccx, ti.ty, glue_fn, make_drop_glue, ~"drop");
debug!("--- lazily_emit_tydesc_glue DROP %s",
ppaux::ty_to_str(ccx.tcx, ti.ty));
}
} else if field == abi::tydesc_field_free_glue {
match ti.free_glue {
- some(_) => (),
- none => {
+ Some(_) => (),
+ None => {
debug!("+++ lazily_emit_tydesc_glue FREE %s",
ppaux::ty_to_str(ccx.tcx, ti.ty));
let glue_fn = declare_generic_glue(ccx, ti.ty, llfnty, ~"free");
- ti.free_glue = some(glue_fn);
+ ti.free_glue = Some(glue_fn);
make_generic_glue(ccx, ti.ty, glue_fn, make_free_glue, ~"free");
debug!("--- lazily_emit_tydesc_glue FREE %s",
ppaux::ty_to_str(ccx.tcx, ti.ty));
}
} else if field == abi::tydesc_field_visit_glue {
match ti.visit_glue {
- some(_) => (),
- none => {
+ Some(_) => (),
+ None => {
debug!("+++ lazily_emit_tydesc_glue VISIT %s",
ppaux::ty_to_str(ccx.tcx, ti.ty));
let glue_fn = declare_generic_glue(ccx, ti.ty, llfnty, ~"visit");
- ti.visit_glue = some(glue_fn);
+ ti.visit_glue = Some(glue_fn);
make_generic_glue(ccx, ti.ty, glue_fn, make_visit_glue, ~"visit");
debug!("--- lazily_emit_tydesc_glue VISIT %s",
ppaux::ty_to_str(ccx.tcx, ti.ty));
// See [Note-arg-mode]
fn call_tydesc_glue_full(++bcx: block, v: ValueRef, tydesc: ValueRef,
- field: uint, static_ti: option<@tydesc_info>) {
+ field: uint, static_ti: Option<@tydesc_info>) {
let _icx = bcx.insn_ctxt("call_tydesc_glue_full");
if bcx.unreachable { return; }
let ccx = bcx.ccx();
let static_glue_fn = match static_ti {
- none => none,
- some(sti) => {
+ None => None,
+ Some(sti) => {
lazily_emit_tydesc_glue(ccx, field, sti);
if field == abi::tydesc_field_take_glue {
sti.take_glue
} else if field == abi::tydesc_field_visit_glue {
sti.visit_glue
} else {
- none
+ None
}
}
};
// When available, use static type info to give glue the right type.
let static_glue_fn = match static_ti {
- none => none,
- some(sti) => {
+ None => None,
+ Some(sti) => {
match static_glue_fn {
- none => none,
- some(sgf) => some(
+ None => None,
+ Some(sgf) => Some(
PointerCast(bcx, sgf, T_ptr(type_of_glue_fn(ccx, sti.ty))))
}
}
let llfn = {
match static_glue_fn {
- none => {
+ None => {
// Select out the glue function to call from the tydesc
let llfnptr = GEPi(bcx, tydesc, ~[0u, field]);
Load(bcx, llfnptr)
}
- some(sgf) => sgf
+ Some(sgf) => sgf
}
};
-> block {
let _icx = cx.insn_ctxt("call_tydesc_glue");
let ti = get_tydesc(cx.ccx(), t);
- call_tydesc_glue_full(cx, v, ti.tydesc, field, some(ti));
+ call_tydesc_glue_full(cx, v, ti.tydesc, field, Some(ti));
return cx;
}
let _icx = cx.insn_ctxt("trans_lit");
if dest == ignore { return cx; }
match lit.node {
- ast::lit_str(s) => tvec::trans_estr(cx, s, none, dest),
+ ast::lit_str(s) => tvec::trans_estr(cx, s, None, dest),
_ => store_in_dest(cx, consts::const_lit(cx.ccx(), e, lit), dest)
}
}
let _icx = bcx.insn_ctxt("trans_unary");
// Check for user-defined method call
match bcx.ccx().maps.method_map.find(un_expr.id) {
- some(mentry) => {
+ Some(mentry) => {
let fty = node_id_type(bcx, un_expr.callee_id);
return trans_call_inner(
bcx, un_expr.info(), fty,
}
};
do with_cond(cx, is_zero) |bcx| {
- trans_fail(bcx, some(span), text)
+ trans_fail(bcx, Some(span), text)
}
}
// A user-defined operator method
match bcx.ccx().maps.method_map.find(ex.id) {
- some(origin) => {
+ Some(origin) => {
let bcx = lhs_res.bcx;
debug!("user-defined method callee_id: %s",
ast_map::node_id_to_str(bcx.tcx().items, ex.callee_id,
if bcx.sess().trace() {
trans_trace(
- bcx, none,
+ bcx, None,
fmt!("preserving until end of scope %d", scope_id));
}
// root the autoderef'd value, if necessary:
derefs += 1u;
match ccx.maps.root_map.find({id:e_id, derefs:derefs}) {
- none => (),
- some(scope_id) => {
+ None => (),
+ Some(scope_id) => {
root_value(cx, v1, t1, scope_id);
}
}
let _icx = bcx.insn_ctxt("trans_binary");
// User-defined operators
match bcx.ccx().maps.method_map.find(ex.id) {
- some(origin) => {
+ Some(origin) => {
let fty = node_id_type(bcx, ex.callee_id);
return trans_call_inner(
bcx, ex.info(), fty,
}
fn trans_if(cx: block, cond: @ast::expr, thn: ast::blk,
- els: option<@ast::expr>, dest: dest)
+ els: Option<@ast::expr>, dest: dest)
-> block {
let _icx = cx.insn_ctxt("trans_if");
let {bcx, val: cond_val} = trans_temp_expr(cx, cond);
// context for the block, but we've already got the
// 'else' context
let else_bcx = match els {
- some(elexpr) => {
+ Some(elexpr) => {
match elexpr.node {
ast::expr_if(_, _, _) => {
let elseif_blk = ast_util::block_from_expr(elexpr);
enum callee_env {
null_env,
is_closure,
- self_env(ValueRef, ty::t, option<ValueRef>, ast::rmode),
+ self_env(ValueRef, ty::t, Option<ValueRef>, ast::rmode),
}
type lval_maybe_callee = {bcx: block,
val: ValueRef,
};
}
-fn normalize_for_monomorphization(tcx: ty::ctxt, ty: ty::t) -> option<ty::t> {
+fn normalize_for_monomorphization(tcx: ty::ctxt, ty: ty::t) -> Option<ty::t> {
// FIXME[mono] could do this recursively. is that worthwhile? (#2529)
match ty::get(ty).struct {
ty::ty_box(*) => {
- some(ty::mk_opaque_box(tcx))
+ Some(ty::mk_opaque_box(tcx))
}
ty::ty_fn(ref fty) => {
- some(ty::mk_fn(tcx, {purity: ast::impure_fn,
+ Some(ty::mk_fn(tcx, {purity: ast::impure_fn,
proto: fty.proto,
bounds: @~[],
inputs: ~[],
ret_style: ast::return_val}))
}
ty::ty_trait(_, _, _) => {
- some(ty::mk_fn(tcx, {purity: ast::impure_fn,
+ Some(ty::mk_fn(tcx, {purity: ast::impure_fn,
proto: ty::proto_vstore(ty::vstore_box),
bounds: @~[],
inputs: ~[],
output: ty::mk_nil(tcx),
ret_style: ast::return_val}))
}
- ty::ty_ptr(_) => some(ty::mk_uint(tcx)),
- _ => none
+ ty::ty_ptr(_) => Some(ty::mk_uint(tcx)),
+ _ => None
}
}
fn make_mono_id(ccx: @crate_ctxt, item: ast::def_id, substs: ~[ty::t],
- vtables: option<typeck::vtable_res>,
- param_uses: option<~[type_use::type_uses]>) -> mono_id {
+ vtables: Option<typeck::vtable_res>,
+ param_uses: Option<~[type_use::type_uses]>) -> mono_id {
let precise_param_ids = match vtables {
- some(vts) => {
+ Some(vts) => {
let bounds = ty::lookup_item_type(ccx.tcx, item).bounds;
let mut i = 0u;
vec::map2(*bounds, substs, |bounds, subst| {
_ => ()
}
}
- (subst, if v.len() > 0u { some(v) } else { none })
+ (subst, if v.len() > 0u { Some(v) } else { None })
})
}
- none => {
- vec::map(substs, |subst| (subst, none))
+ None => {
+ vec::map(substs, |subst| (subst, None))
}
};
let param_ids = match param_uses {
- some(uses) => {
+ Some(uses) => {
vec::map2(precise_param_ids, uses, |id, uses| {
match id {
- (a, b@some(_)) => mono_precise(a, b),
- (subst, none) => {
+ (a, b@Some(_)) => mono_precise(a, b),
+ (subst, None) => {
if uses == 0u { mono_any }
else if uses == type_use::use_repr &&
!ty::type_needs_drop(ccx.tcx, subst) {
if size == 1u && ty::type_is_nil(subst) {
mono_repr(0u, 0u)
} else { mono_repr(size, align) }
- } else { mono_precise(subst, none) }
+ } else { mono_precise(subst, None) }
}
}
})
}
- none => precise_param_ids.map(|x| { let (a, b) = x;
+ None => precise_param_ids.map(|x| { let (a, b) = x;
mono_precise(a, b) })
};
@{def: item, params: param_ids}
fn monomorphic_fn(ccx: @crate_ctxt, fn_id: ast::def_id,
real_substs: ~[ty::t],
- vtables: option<typeck::vtable_res>,
- ref_id: option<ast::node_id>)
+ vtables: Option<typeck::vtable_res>,
+ ref_id: Option<ast::node_id>)
-> {val: ValueRef, must_cast: bool} {
let _icx = ccx.insn_ctxt("monomorphic_fn");
let mut must_cast = false;
let substs = vec::map(real_substs, |t| {
match normalize_for_monomorphization(ccx.tcx, t) {
- some(t) => { must_cast = true; t }
- none => t
+ Some(t) => { must_cast = true; t }
+ None => t
}
});
for real_substs.each() |s| { assert !ty::type_has_params(s); }
for substs.each() |s| { assert !ty::type_has_params(s); }
let param_uses = type_use::type_uses_for(ccx, fn_id, substs.len());
- let hash_id = make_mono_id(ccx, fn_id, substs, vtables, some(param_uses));
+ let hash_id = make_mono_id(ccx, fn_id, substs, vtables, Some(param_uses));
if vec::any(hash_id.params,
|p| match p { mono_precise(_, _) => false, _ => true }) {
must_cast = true;
substs.map(|s| ty_to_str(ccx.tcx, s)), hash_id];
match ccx.monomorphized.find(hash_id) {
- some(val) => {
+ Some(val) => {
debug!("leaving monomorphic fn %s",
ty::item_path_str(ccx.tcx, fn_id));
return {val: val, must_cast: must_cast};
}
- none => ()
+ None => ()
}
let tpt = ty::lookup_item_type(ccx.tcx, fn_id);
lldecl
};
- let psubsts = some({tys: substs, vtables: vtables, bounds: tpt.bounds});
+ let psubsts = Some({tys: substs, vtables: vtables, bounds: tpt.bounds});
let lldecl = match map_node {
ast_map::node_item(i@@{node: ast::item_fn(decl, _, _, body), _}, _) => {
let d = mk_lldecl();
let tp_tys = ty::ty_params_to_tys(ccx.tcx, tps);
trans_class_ctor(ccx, pt, ctor.node.dec, ctor.node.body, d,
option::get_default(psubsts,
- {tys:tp_tys, vtables: none, bounds: @~[]}),
+ {tys:tp_tys, vtables: None, bounds: @~[]}),
fn_id.node, parent_id, ctor.span);
d
}
ast_map::node_dtor(_, dtor, _, pt) => {
let parent_id = match ty::ty_to_def_id(ty::node_id_to_type(ccx.tcx,
dtor.node.self_id)) {
- some(did) => did,
- none => ccx.sess.span_bug(dtor.span, ~"Bad self ty in \
+ Some(did) => did,
+ None => ccx.sess.span_bug(dtor.span, ~"Bad self ty in \
dtor")
};
trans_class_dtor(ccx, *pt, dtor.node.body,
- dtor.node.id, psubsts, some(hash_id), parent_id)
+ dtor.node.id, psubsts, Some(hash_id), parent_id)
}
// Ugh -- but this ensures any new variants won't be forgotten
ast_map::node_expr(*) |
-> ast::def_id {
let _icx = ccx.insn_ctxt("maybe_instantiate_inline");
match ccx.external.find(fn_id) {
- some(some(node_id)) => {
+ Some(Some(node_id)) => {
// Already inline
debug!("maybe_instantiate_inline(%s): already inline as node id %d",
ty::item_path_str(ccx.tcx, fn_id), node_id);
local_def(node_id)
}
- some(none) => fn_id, // Not inlinable
- none => { // Not seen yet
+ Some(None) => fn_id, // Not inlinable
+ None => { // Not seen yet
match csearch::maybe_get_item_ast(
ccx.tcx, fn_id,
|a,b,c,d| {
}) {
csearch::not_found => {
- ccx.external.insert(fn_id, none);
+ ccx.external.insert(fn_id, None);
fn_id
}
csearch::found(ast::ii_item(item)) => {
- ccx.external.insert(fn_id, some(item.id));
+ ccx.external.insert(fn_id, Some(item.id));
trans_item(ccx, *item);
local_def(item.id)
}
csearch::found(ast::ii_ctor(ctor, _, tps, _)) => {
- ccx.external.insert(fn_id, some(ctor.node.id));
+ ccx.external.insert(fn_id, Some(ctor.node.id));
local_def(ctor.node.id)
}
csearch::found(ast::ii_foreign(item)) => {
- ccx.external.insert(fn_id, some(item.id));
+ ccx.external.insert(fn_id, Some(item.id));
local_def(item.id)
}
csearch::found_parent(parent_id, ast::ii_item(item)) => {
- ccx.external.insert(parent_id, some(item.id));
+ ccx.external.insert(parent_id, Some(item.id));
let mut my_id = 0;
match item.node {
ast::item_enum(_, _) => {
let vs_there = ty::enum_variants(ccx.tcx, parent_id);
do vec::iter2(*vs_here, *vs_there) |here, there| {
if there.id == fn_id { my_id = here.id.node; }
- ccx.external.insert(there.id, some(here.id.node));
+ ccx.external.insert(there.id, Some(here.id.node));
}
}
_ => ccx.sess.bug(~"maybe_instantiate_inline: item has a \
with a non-item parent");
}
csearch::found(ast::ii_method(impl_did, mth)) => {
- ccx.external.insert(fn_id, some(mth.id));
+ ccx.external.insert(fn_id, Some(mth.id));
let {bounds: impl_bnds, region_param: _, ty: impl_ty} =
ty::lookup_item_type(ccx.tcx, impl_did);
if (*impl_bnds).len() + mth.tps.len() == 0u {
ty::item_path(ccx.tcx, impl_did),
~[path_name(mth.ident)]);
trans_fn(ccx, path, mth.decl, mth.body,
- llfn, impl_self(impl_ty), none, mth.id);
+ llfn, impl_self(impl_ty), None, mth.id);
}
local_def(mth.id)
}
csearch::found(ast::ii_dtor(dtor, _, tps, _)) => {
- ccx.external.insert(fn_id, some(dtor.node.id));
+ ccx.external.insert(fn_id, Some(dtor.node.id));
local_def(dtor.node.id)
}
}
}
fn lval_static_fn_inner(bcx: block, fn_id: ast::def_id, id: ast::node_id,
- tys: ~[ty::t], vtables: option<typeck::vtable_res>)
+ tys: ~[ty::t], vtables: Option<typeck::vtable_res>)
-> lval_maybe_callee {
let _icx = bcx.insn_ctxt("lval_static_fn_inner");
let ccx = bcx.ccx(), tcx = ccx.tcx;
if fn_id.crate == ast::local_crate && tys.len() > 0u {
let mut {val, must_cast} =
- monomorphic_fn(ccx, fn_id, tys, vtables, some(id));
+ monomorphic_fn(ccx, fn_id, tys, vtables, Some(id));
if must_cast {
val = PointerCast(bcx, val, T_ptr(type_of_fn_from_ty(
ccx, node_id_type(bcx, id))));
fn lookup_discriminant(ccx: @crate_ctxt, vid: ast::def_id) -> ValueRef {
let _icx = ccx.insn_ctxt("lookup_discriminant");
match ccx.discrims.find(vid) {
- none => {
+ None => {
// It's an external discriminant that we haven't seen yet.
assert (vid.crate != ast::local_crate);
let sym = csearch::get_symbol(ccx.sess.cstore, vid);
ccx.discrims.insert(vid, gvar);
return gvar;
}
- some(llval) => return llval,
+ Some(llval) => return llval,
}
}
fn take_local(table: hashmap<ast::node_id, local_val>,
id: ast::node_id) -> local_var_result {
match table.find(id) {
- some(local_mem(v)) => {val: v, kind: lv_owned},
- some(local_imm(v)) => {val: v, kind: lv_owned_imm},
- none => fail(fmt!("take_local: internal error, \
+ Some(local_mem(v)) => {val: v, kind: lv_owned},
+ Some(local_imm(v)) => {val: v, kind: lv_owned_imm},
+ None => fail(fmt!("take_local: internal error, \
found no entry for %?", id))
}
}
}
ast::def_self(_) => {
let slf = match copy cx.fcx.llself {
- some(s) => cast_self(cx, s),
- none => cx.sess().bug(~"trans_local_var: reference to self \
+ Some(s) => cast_self(cx, s),
+ None => cx.sess().bug(~"trans_local_var: reference to self \
out of context")
};
return {val: slf, kind: lv_owned};
-> lval_maybe_callee {
let _icx = cx.insn_ctxt("trans_path");
match cx.tcx().def_map.find(id) {
- none => cx.sess().bug(~"trans_path: unbound node ID"),
- some(df) => {
+ None => cx.sess().bug(~"trans_path: unbound node ID"),
+ Some(df) => {
return trans_var(cx, df, id);
}
}
let bounds_check = ICmp(bcx, lib::llvm::IntUGE, scaled_ix, len);
let bcx = do with_cond(bcx, bounds_check) |bcx| {
// fail: bad bounds check.
- trans_fail(bcx, some(ex.span), ~"bounds check")
+ trans_fail(bcx, Some(ex.span), ~"bounds check")
};
let elt = InBoundsGEP(bcx, base, ~[ix_val]);
return lval_owned(bcx, PointerCast(bcx, elt, T_ptr(llunitty)));
// Lval means this is a record field, so not a method
if !expr_is_lval(bcx, e) {
match bcx.ccx().maps.method_map.find(e.id) {
- some(origin) => { // An impl method
+ Some(origin) => { // An impl method
return impl::trans_method_callee(bcx, e.id, base, origin);
}
_ => {
fn trans_lval(cx: block, e: @ast::expr) -> lval_result {
return match cx.ccx().maps.root_map.find({id:e.id, derefs:0u}) {
// No need to root this lvalue.
- none => unrooted(cx, e),
+ None => unrooted(cx, e),
// Lvalue must remain rooted until exit of `scope_id`. See
// add_root_cleanup() for comments on why this works the way it does.
- some(scope_id) => {
+ Some(scope_id) => {
let lv = unrooted(cx, e);
if !cx.sess().no_asm_comments() {
fn trans_loop_body(bcx: block, id: ast::node_id,
decl: ast::fn_decl, body: ast::blk,
proto: ty::fn_proto, cap: ast::capture_clause,
- ret_flag: option<ValueRef>,
+ ret_flag: Option<ValueRef>,
dest: dest) -> block {
closure::trans_expr_fn(bcx, proto, decl, body, id,
- cap, some(ret_flag), dest)
+ cap, Some(ret_flag), dest)
}
// temp_cleanups: cleanups that should run only if failure occurs before the
// call takes place:
fn trans_arg_expr(cx: block, arg: ty::arg, lldestty: TypeRef, e: @ast::expr,
- &temp_cleanups: ~[ValueRef], ret_flag: option<ValueRef>,
+ &temp_cleanups: ~[ValueRef], ret_flag: Option<ValueRef>,
derefs: uint)
-> result {
let _icx = cx.insn_ctxt("trans_arg_expr");
// translate the arg expr as an lvalue
let lv = match ret_flag {
// If there is a ret_flag, this *must* be a loop body
- some(_) => match e.node {
+ Some(_) => match e.node {
ast::expr_loop_body(blk@@{node:
ast::expr_fn_block(decl, body, cap),_}) => {
let scratch = alloc_ty(cx, expr_ty(cx, blk));
_ => cx.sess().impossible_case(e.span, ~"ret_flag with non-loop-\
body expr")
},
- none => {
+ None => {
trans_temp_lval(cx, e)
}
};
// - new_fn_ctxt
// - trans_args
fn trans_args(cx: block, llenv: ValueRef, args: call_args, fn_ty: ty::t,
- dest: dest, ret_flag: option<ValueRef>)
+ dest: dest, ret_flag: Option<ValueRef>)
-> {bcx: block, args: ~[ValueRef], retslot: ValueRef} {
let _icx = cx.insn_ctxt("trans_args");
let mut temp_cleanups = ~[];
do vec::iteri(es) |i, e| {
let r = trans_arg_expr(bcx, arg_tys[i], llarg_tys[i],
e, temp_cleanups, if i == last { ret_flag }
- else { none }, 0u);
+ else { None }, 0u);
bcx = r.bcx;
vec::push(llargs, r.val);
}
// See [Note-arg-mode]
fn trans_call_inner(
++in_cx: block,
- call_info: option<node_info>,
+ call_info: Option<node_info>,
fn_expr_ty: ty::t,
ret_ty: ty::t,
get_callee: fn(block) -> lval_maybe_callee,
let ret_flag = if ret_in_loop {
let flag = alloca(bcx, T_bool());
Store(bcx, C_bool(false), flag);
- some(flag)
- } else { none };
+ Some(flag)
+ } else { None };
let mut faddr = f_res.val;
let llenv = match f_res.env {
Store(bcx, C_bool(true), lret.flagptr);
Store(bcx, C_bool(false), bcx.fcx.llretptr);
}
- cleanup_and_leave(bcx, none, some(bcx.fcx.llreturn));
+ cleanup_and_leave(bcx, None, Some(bcx.fcx.llreturn));
Unreachable(bcx);
bcx
}
_ => ()
}
cur = match cur.parent {
- some(next) => next,
- none => return false
+ Some(next) => next,
+ None => return false
}
}
}
let mut res = false;
do in_lpad_scope_cx(bcx) |inf| {
match inf.landing_pad {
- some(_) => res = true,
- none => res = false
+ Some(_) => res = true,
+ None => res = false
}
}
return res;
fn get_landing_pad(bcx: block) -> BasicBlockRef {
let _icx = bcx.insn_ctxt("get_landing_pad");
- let mut cached = none, pad_bcx = bcx; // Guaranteed to be set below
+ let mut cached = None, pad_bcx = bcx; // Guaranteed to be set below
do in_lpad_scope_cx(bcx) |inf| {
// If there is a valid landing pad still around, use it
match copy inf.landing_pad {
- some(target) => cached = some(target),
- none => {
+ Some(target) => cached = Some(target),
+ None => {
pad_bcx = lpad_block(bcx, ~"unwind");
- inf.landing_pad = some(pad_bcx.llbb);
+ inf.landing_pad = Some(pad_bcx.llbb);
}
}
}
// Can't return from block above
- match cached { some(b) => return b, none => () }
+ match cached { Some(b) => return b, None => () }
// The landing pad return type (the type being propagated). Not sure what
// this represents but it's determined by the personality function and
// this is what the EH proposal example uses.
// We store the retval in a function-central alloca, so that calls to
// Resume can find it.
match copy bcx.fcx.personality {
- some(addr) => Store(pad_bcx, llretval, addr),
- none => {
+ Some(addr) => Store(pad_bcx, llretval, addr),
+ None => {
let addr = alloca(pad_bcx, val_ty(llretval));
- bcx.fcx.personality = some(addr);
+ bcx.fcx.personality = Some(addr);
Store(pad_bcx, llretval, addr);
}
}
// Unwind all parent scopes, and finish with a Resume instr
- cleanup_and_leave(pad_bcx, none, none);
+ cleanup_and_leave(pad_bcx, None, None);
return pad_bcx.llbb;
}
}
fn trans_rec(bcx: block, fields: ~[ast::field],
- base: option<@ast::expr>, id: ast::node_id,
+ base: Option<@ast::expr>, id: ast::node_id,
// none = ignore; some(x) = save_in(x)
- dest: option<ValueRef>) -> block {
+ dest: Option<ValueRef>) -> block {
let _icx = bcx.insn_ctxt("trans_rec");
let t = node_id_type(bcx, id);
let mut bcx = bcx;
let addr = match dest {
- none => {
+ None => {
for vec::each(fields) |fld| {
bcx = trans_expr(bcx, fld.node.expr, ignore);
}
return bcx;
}
- some(pos) => pos
+ Some(pos) => pos
};
let ty_fields = match ty::get(t).struct {
vec::push(temp_cleanups, dst);
}
match base {
- some(bexp) => {
+ Some(bexp) => {
let {bcx: cx, val: base_val} = trans_temp_expr(bcx, bexp);
bcx = cx;
// Copy over inherited fields
}
}
}
- none => ()
+ None => ()
};
// Now revoke the cleanups as we pass responsibility for the data
}
fn trans_struct(block_context: block, span: span, fields: ~[ast::field],
- base: option<@ast::expr>, id: ast::node_id, dest: dest)
+ base: Option<@ast::expr>, id: ast::node_id, dest: dest)
-> block {
let _instruction_context = block_context.insn_ctxt("trans_struct");
// Now translate each field.
let mut temp_cleanups = ~[];
for fields.each |field| {
- let mut found = none;
+ let mut found = None;
for class_fields.eachi |i, class_field| {
if class_field.ident == field.node.ident {
- found = some((i, class_field.id));
+ found = Some((i, class_field.id));
break;
}
}
let index, field_id;
match found {
- some((found_index, found_field_id)) => {
+ Some((found_index, found_field_id)) => {
index = found_index;
field_id = found_field_id;
}
- none => {
+ None => {
type_context.sess.span_bug(span, ~"unknown field");
}
}
}
match base {
- some(base_expr) => {
+ Some(base_expr) => {
let { bcx: bcx, val: llbasevalue } =
trans_temp_expr(block_context, base_expr);
block_context = bcx;
field_type);
}
}
- none => ()
+ None => ()
}
// Now revoke the cleanups, as we pass responsibility for the data
let mut bcx_sid = bcx;
loop {
bcx_sid = match bcx_sid.node_info {
- some({id, _}) if id == scope_id => {
+ Some({id, _}) if id == scope_id => {
return bcx_sid
}
_ => {
match bcx_sid.parent {
- none => bcx.tcx().sess.bug(
+ None => bcx.tcx().sess.bug(
fmt!("no enclosing scope with id %d", scope_id)),
- some(bcx_par) => bcx_par
+ Some(bcx_par) => bcx_par
}
}
}
}
return match bcx.ccx().maps.root_map.find({id:e.id, derefs:0u}) {
- none => unrooted(bcx, e, dest),
- some(scope_id) => {
+ None => unrooted(bcx, e, dest),
+ Some(scope_id) => {
debug!("expression %d found in root map with scope %d",
e.id, scope_id);
}
ast::expr_rec(args, base) => {
let d = match dest {
- ignore => none,
- save_in(p) => some(p),
+ ignore => None,
+ save_in(p) => Some(p),
_ => bcx.sess().impossible_case(e.span,
"trans_expr::unrooted: can't pass a record by val")
};
ast::expr_lit(lit) => return trans_lit(bcx, e, *lit, dest),
ast::expr_vec(args, _) => {
return tvec::trans_evec(bcx, tvec::individual_evec(args),
- ast::vstore_fixed(none), e.id, dest);
+ ast::vstore_fixed(None), e.id, dest);
}
ast::expr_repeat(element, count_expr, _) => {
let count = ty::eval_repeat_count(bcx.tcx(), count_expr, e.span);
return tvec::trans_evec(bcx, tvec::repeating_evec(element, count),
- ast::vstore_fixed(none), e.id, dest);
+ ast::vstore_fixed(None), e.id, dest);
}
ast::expr_binary(op, lhs, rhs) => {
return trans_binary(bcx, op, lhs, rhs, dest, e);
// guess?); @fn() { ... } won't work.
return closure::trans_expr_fn(bcx,
ast_proto_to_proto_simple(proto),
- decl, body, e.id, cap_clause, none,
+ decl, body, e.id, cap_clause, None,
dest);
}
ast::expr_fn_block(decl, body, cap_clause) => {
expr_to_str(e, tcx.sess.intr()),
ppaux::ty_to_str(tcx, expr_ty(bcx, e)));
return closure::trans_expr_fn(bcx, proto, decl, body,
- e.id, cap_clause, none, dest);
+ e.id, cap_clause, None, dest);
}
_ => bcx.sess().impossible_case(e.span, "fn_block has \
body with a non-fn type")
match blk.node {
ast::expr_fn_block(decl, body, cap) =>
return trans_loop_body(bcx, blk.id, decl, body,
- proto, cap, none, dest),
+ proto, cap, None, dest),
_ => bcx.sess().impossible_case(e.span, "loop_body \
has the wrong kind of contents")
}
}
ast::expr_fail(expr) => {
assert dest == ignore;
- return trans_fail_expr(bcx, some(e.span), expr);
+ return trans_fail_expr(bcx, Some(e.span), expr);
}
ast::expr_log(_, lvl, a) => {
assert dest == ignore;
}
};
do with_cond(bcx, Not(bcx, val)) |bcx| {
- trans_fail(bcx, some(pred_expr.span), expr_str)
+ trans_fail(bcx, Some(pred_expr.span), expr_str)
}
}
-fn trans_fail_expr(bcx: block, sp_opt: option<span>,
- fail_expr: option<@ast::expr>) -> block {
+fn trans_fail_expr(bcx: block, sp_opt: Option<span>,
+ fail_expr: Option<@ast::expr>) -> block {
let _icx = bcx.insn_ctxt("trans_fail_expr");
let mut bcx = bcx;
match fail_expr {
- some(expr) => {
+ Some(expr) => {
let ccx = bcx.ccx(), tcx = ccx.tcx;
let expr_res = trans_temp_expr(bcx, expr);
let e_ty = expr_ty(bcx, expr);
}
}
-fn trans_trace(bcx: block, sp_opt: option<span>, trace_str: ~str) {
+fn trans_trace(bcx: block, sp_opt: Option<span>, trace_str: ~str) {
if !bcx.sess().trace() { return; }
let _icx = bcx.insn_ctxt("trans_trace");
add_comment(bcx, trace_str);
let V_trace_str = C_cstr(bcx.ccx(), trace_str);
let {V_filename, V_line} = match sp_opt {
- some(sp) => {
+ Some(sp) => {
let sess = bcx.sess();
let loc = codemap::lookup_char_pos(sess.parse_sess.cm, sp.lo);
{V_filename: C_cstr(bcx.ccx(), loc.file.name),
V_line: loc.line as int}
}
- none => {
+ None => {
{V_filename: C_cstr(bcx.ccx(), ~"<runtime>"),
V_line: 0}
}
Call(bcx, ccx.upcalls.trace, args);
}
-fn trans_fail(bcx: block, sp_opt: option<span>, fail_str: ~str) ->
+fn trans_fail(bcx: block, sp_opt: Option<span>, fail_str: ~str) ->
block {
let _icx = bcx.insn_ctxt("trans_fail");
let V_fail_str = C_cstr(bcx.ccx(), fail_str);
return trans_fail_value(bcx, sp_opt, V_fail_str);
}
-fn trans_fail_value(bcx: block, sp_opt: option<span>,
+fn trans_fail_value(bcx: block, sp_opt: Option<span>,
V_fail_str: ValueRef) -> block {
let _icx = bcx.insn_ctxt("trans_fail_value");
let ccx = bcx.ccx();
let {V_filename, V_line} = match sp_opt {
- some(sp) => {
+ Some(sp) => {
let sess = bcx.sess();
let loc = codemap::lookup_char_pos(sess.parse_sess.cm, sp.lo);
{V_filename: C_cstr(bcx.ccx(), loc.file.name),
V_line: loc.line as int}
}
- none => {
+ None => {
{V_filename: C_cstr(bcx.ccx(), ~"<runtime>"),
V_line: 0}
}
};
let rty = ty::ty_fn_ret(fty);
return trans_call_inner(
- bcx, none, fty, rty,
- |bcx| lval_static_fn_inner(bcx, did, 0, ~[], none),
+ bcx, None, fty, rty,
+ |bcx| lval_static_fn_inner(bcx, did, 0, ~[], None),
arg_vals(args), dest);
}
let mut target;
loop {
match unwind.kind {
- block_scope({loop_break: some(brk), _}) => {
+ block_scope({loop_break: Some(brk), _}) => {
target = if to_end {
brk
} else {
_ => ()
}
unwind = match unwind.parent {
- some(cx) => cx,
+ Some(cx) => cx,
// This is a return from a loop body block
- none => {
+ None => {
Store(bcx, C_bool(!to_end), bcx.fcx.llretptr);
- cleanup_and_leave(bcx, none, some(bcx.fcx.llreturn));
+ cleanup_and_leave(bcx, None, Some(bcx.fcx.llreturn));
Unreachable(bcx);
return bcx;
}
return trans_break_cont(cx, false);
}
-fn trans_ret(bcx: block, e: option<@ast::expr>) -> block {
+fn trans_ret(bcx: block, e: Option<@ast::expr>) -> block {
let _icx = bcx.insn_ctxt("trans_ret");
let mut bcx = bcx;
let retptr = match copy bcx.fcx.loop_ret {
- some({flagptr, retptr}) => {
+ Some({flagptr, retptr}) => {
// This is a loop body return. Must set continue flag (our retptr)
// to false, return flag to true, and then store the value in the
// parent's retptr.
Store(bcx, C_bool(true), flagptr);
Store(bcx, C_bool(false), bcx.fcx.llretptr);
match e {
- some(x) => PointerCast(bcx, retptr,
+ Some(x) => PointerCast(bcx, retptr,
T_ptr(type_of(bcx.ccx(), expr_ty(bcx, x)))),
- none => retptr
+ None => retptr
}
}
- none => bcx.fcx.llretptr
+ None => bcx.fcx.llretptr
};
match e {
- some(x) => {
+ Some(x) => {
bcx = trans_expr_save_in(bcx, x, retptr);
}
_ => ()
}
- cleanup_and_leave(bcx, none, some(bcx.fcx.llreturn));
+ cleanup_and_leave(bcx, None, Some(bcx.fcx.llreturn));
Unreachable(bcx);
return bcx;
}
if ignore_lhs(bcx, local) {
// Handle let _ = e; just like e;
match local.node.init {
- some(init) => {
+ Some(init) => {
return trans_expr(bcx, init.expr, ignore);
}
- none => { return bcx; }
+ None => { return bcx; }
}
}
let llptr = match bcx.fcx.lllocals.find(local.node.id) {
- some(local_mem(v)) => v,
+ Some(local_mem(v)) => v,
_ => { bcx.tcx().sess.span_bug(local.span,
~"init_local: Someone forgot to document why it's\
safe to assume local.node.init must be local_mem!");
let mut bcx = bcx;
match local.node.init {
- some(init) => {
+ Some(init) => {
if init.op == ast::init_assign || !expr_is_lval(bcx, init.expr) {
bcx = trans_expr_save_in(bcx, init.expr, llptr);
} else { // This is a move from an lval, must perform an actual move
// You probably don't want to use this one. See the
// next three functions instead.
-fn new_block(cx: fn_ctxt, parent: option<block>, +kind: block_kind,
- is_lpad: bool, name: ~str, opt_node_info: option<node_info>)
+fn new_block(cx: fn_ctxt, parent: Option<block>, +kind: block_kind,
+ is_lpad: bool, name: ~str, opt_node_info: Option<node_info>)
-> block {
let s = if cx.ccx.sess.opts.save_temps || cx.ccx.sess.opts.debuginfo {
}
fn simple_block_scope() -> block_kind {
- block_scope({loop_break: none, mut cleanups: ~[],
- mut cleanup_paths: ~[], mut landing_pad: none})
+ block_scope({loop_break: None, mut cleanups: ~[],
+ mut cleanup_paths: ~[], mut landing_pad: None})
}
// Use this when you're at the top block of a function or the like.
-fn top_scope_block(fcx: fn_ctxt, opt_node_info: option<node_info>) -> block {
- return new_block(fcx, none, simple_block_scope(), false,
+fn top_scope_block(fcx: fn_ctxt, opt_node_info: Option<node_info>) -> block {
+ return new_block(fcx, None, simple_block_scope(), false,
~"function top level", opt_node_info);
}
fn scope_block(bcx: block,
- opt_node_info: option<node_info>,
+ opt_node_info: Option<node_info>,
n: ~str) -> block {
- return new_block(bcx.fcx, some(bcx), simple_block_scope(), bcx.is_lpad,
+ return new_block(bcx.fcx, Some(bcx), simple_block_scope(), bcx.is_lpad,
n, opt_node_info);
}
fn loop_scope_block(bcx: block, loop_break: block, n: ~str,
- opt_node_info: option<node_info>) -> block {
- return new_block(bcx.fcx, some(bcx), block_scope({
- loop_break: some(loop_break),
+ opt_node_info: Option<node_info>) -> block {
+ return new_block(bcx.fcx, Some(bcx), block_scope({
+ loop_break: Some(loop_break),
mut cleanups: ~[],
mut cleanup_paths: ~[],
- mut landing_pad: none
+ mut landing_pad: None
}), bcx.is_lpad, n, opt_node_info);
}
// Use this when creating a block for the inside of a landing pad.
fn lpad_block(bcx: block, n: ~str) -> block {
- new_block(bcx.fcx, some(bcx), block_non_scope, true, n, none)
+ new_block(bcx.fcx, Some(bcx), block_non_scope, true, n, None)
}
// Use this when you're making a general CFG BB within a scope.
fn sub_block(bcx: block, n: ~str) -> block {
- new_block(bcx.fcx, some(bcx), block_non_scope, bcx.is_lpad, n, none)
+ new_block(bcx.fcx, Some(bcx), block_non_scope, bcx.is_lpad, n, None)
}
fn raw_block(fcx: fn_ctxt, is_lpad: bool, llbb: BasicBlockRef) -> block {
- mk_block(llbb, none, block_non_scope, is_lpad, none, fcx)
+ mk_block(llbb, None, block_non_scope, is_lpad, None, fcx)
}
return bcx;
}
-// In the last argument, some(block) mean jump to this block, and none means
+// In the last argument, Some(block) mean jump to this block, and none means
// this is a landing pad and leaving should be accomplished with a resume
// instruction.
-fn cleanup_and_leave(bcx: block, upto: option<BasicBlockRef>,
- leave: option<BasicBlockRef>) {
+fn cleanup_and_leave(bcx: block, upto: Option<BasicBlockRef>,
+ leave: Option<BasicBlockRef>) {
let _icx = bcx.insn_ctxt("cleanup_and_leave");
let mut cur = bcx, bcx = bcx;
- let is_lpad = leave == none;
+ let is_lpad = leave == None;
loop {
debug!("cleanup_and_leave: leaving %s", cur.to_str());
if bcx.sess().trace() {
trans_trace(
- bcx, none,
+ bcx, None,
fmt!("cleanup_and_leave(%s)", cur.to_str()));
}
_ => ()
}
match upto {
- some(bb) => { if cur.llbb == bb { break; } }
+ Some(bb) => { if cur.llbb == bb { break; } }
_ => ()
}
cur = match cur.parent {
- some(next) => next,
- none => { assert is_none(upto); break; }
+ Some(next) => next,
+ None => { assert is_none(upto); break; }
};
}
match leave {
- some(target) => Br(bcx, target),
- none => { Resume(bcx, Load(bcx, option::get(bcx.fcx.personality))); }
+ Some(target) => Br(bcx, target),
+ None => { Resume(bcx, Load(bcx, option::get(bcx.fcx.personality))); }
}
}
fn cleanup_and_Br(bcx: block, upto: block,
target: BasicBlockRef) {
let _icx = bcx.insn_ctxt("cleanup_and_Br");
- cleanup_and_leave(bcx, some(upto.llbb), some(target));
+ cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
}
fn leave_block(bcx: block, out_of: block) -> block {
next_cx
}
-fn with_scope(bcx: block, opt_node_info: option<node_info>,
+fn with_scope(bcx: block, opt_node_info: Option<node_info>,
name: ~str, f: fn(block) -> block) -> block {
let _icx = bcx.insn_ctxt("with_scope");
let scope_cx = scope_block(bcx, opt_node_info, name);
leave_block(f(scope_cx), scope_cx)
}
-fn with_scope_result(bcx: block, opt_node_info: option<node_info>,
+fn with_scope_result(bcx: block, opt_node_info: Option<node_info>,
name: ~str, f: fn(block) -> result)
-> result {
let _icx = bcx.insn_ctxt("with_scope_result");
let _icx = cx.insn_ctxt("alloc_local");
let t = node_id_type(cx, local.node.id);
let simple_name = match local.node.pat.node {
- ast::pat_ident(_, pth, none) => some(path_to_ident(pth)),
- _ => none
+ ast::pat_ident(_, pth, None) => Some(path_to_ident(pth)),
+ _ => None
};
let val = alloc_ty(cx, t);
if cx.sess().opts.debuginfo {
bcx = trans_stmt(bcx, *s);
}
match b.node.expr {
- some(e) => {
+ Some(e) => {
let bt = ty::type_is_bot(expr_ty(bcx, e));
debuginfo::update_source_pos(bcx, e.span);
bcx = trans_expr(bcx, e, if bt { ignore } else { dest });
// - trans_args
fn new_fn_ctxt_w_id(ccx: @crate_ctxt, path: path,
llfndecl: ValueRef, id: ast::node_id,
- param_substs: option<param_substs>,
- sp: option<span>) -> fn_ctxt {
+ param_substs: Option<param_substs>,
+ sp: Option<span>) -> fn_ctxt {
let llbbs = mk_standard_basic_blocks(llfndecl);
return @{llfn: llfndecl,
llenv: llvm::LLVMGetParam(llfndecl, 1u as c_uint),
mut llstaticallocas: llbbs.sa,
mut llloadenv: llbbs.ca,
mut llreturn: llbbs.rt,
- mut llself: none,
- mut personality: none,
- mut loop_ret: none,
+ mut llself: None,
+ mut personality: None,
+ mut loop_ret: None,
llargs: int_hash::<local_val>(),
lllocals: int_hash::<local_val>(),
llupvars: int_hash::<ValueRef>(),
}
fn new_fn_ctxt(ccx: @crate_ctxt, path: path, llfndecl: ValueRef,
- sp: option<span>) -> fn_ctxt {
- return new_fn_ctxt_w_id(ccx, path, llfndecl, -1, none, sp);
+ sp: Option<span>) -> fn_ctxt {
+ return new_fn_ctxt_w_id(ccx, path, llfndecl, -1, None, sp);
}
// NB: must keep 4 fns in sync:
let mut arg_n = first_real_arg;
match ty_self {
impl_self(tt) => {
- cx.llself = some({v: cx.llenv, t: tt, is_owned: false});
+ cx.llself = Some({v: cx.llenv, t: tt, is_owned: false});
}
impl_owned_self(tt) => {
- cx.llself = some({v: cx.llenv, t: tt, is_owned: true});
+ cx.llself = Some({v: cx.llenv, t: tt, is_owned: true});
}
no_self => ()
}
};
match fcx.llself {
- some(copy slf) => {
+ Some(copy slf) => {
// We really should do this regardless of whether self is owned,
// but it doesn't work right with default method impls yet.
if slf.is_owned {
let self_val = PointerCast(bcx, slf.v,
T_ptr(type_of(bcx.ccx(), slf.t)));
- fcx.llself = some({v: self_val with slf});
+ fcx.llself = Some({v: self_val with slf});
add_clean(bcx, self_val, slf.t);
}
}
fn trans_closure(ccx: @crate_ctxt, path: path, decl: ast::fn_decl,
body: ast::blk, llfndecl: ValueRef,
ty_self: self_arg,
- param_substs: option<param_substs>,
+ param_substs: Option<param_substs>,
id: ast::node_id,
maybe_load_env: fn(fn_ctxt),
finish: fn(block)) {
// Set up arguments to the function.
let fcx = new_fn_ctxt_w_id(ccx, path, llfndecl, id, param_substs,
- some(body.span));
+ Some(body.span));
create_llargs_for_fn_args(fcx, ty_self, decl.inputs);
// Set GC for function.
body: ast::blk,
llfndecl: ValueRef,
ty_self: self_arg,
- param_substs: option<param_substs>,
+ param_substs: Option<param_substs>,
id: ast::node_id) {
let do_time = ccx.sess.trans_stats();
let start = if do_time { time::get_time() }
variant: ast::variant,
args: ~[ast::variant_arg],
disr: int, is_degen: bool,
- param_substs: option<param_substs>,
+ param_substs: Option<param_substs>,
llfndecl: ValueRef) {
let _icx = ccx.insn_ctxt("trans_enum_variant");
// Translate variant arguments to function arguments.
ident: special_idents::arg,
id: varg.id});
let fcx = new_fn_ctxt_w_id(ccx, ~[], llfndecl, variant.node.id,
- param_substs, none);
+ param_substs, None);
create_llargs_for_fn_args(fcx, no_self, fn_args);
let ty_param_substs = match param_substs {
- some(substs) => substs.tys,
- none => ~[]
+ Some(substs) => substs.tys,
+ None => ~[]
};
- let bcx = top_scope_block(fcx, none), lltop = bcx.llbb;
+ let bcx = top_scope_block(fcx, None), lltop = bcx.llbb;
let arg_tys = ty::ty_fn_args(node_id_type(bcx, variant.node.id));
let bcx = copy_args_to_allocas(fcx, bcx, fn_args, arg_tys);
// this function as an opaque blob due to the way that type_of()
// works. So we have to cast to the destination's view of the type.
let llarg = match fcx.llargs.find(va.id) {
- some(local_mem(x)) => x,
+ Some(local_mem(x)) => x,
_ => fail ~"trans_enum_variant: how do we know this works?",
};
let arg_ty = arg_tys[i].ty;
// Make the fn context
let fcx = new_fn_ctxt_w_id(ccx, path, llctor_decl, ctor_id,
- some(psubsts), some(sp));
+ Some(psubsts), Some(sp));
create_llargs_for_fn_args(fcx, no_self, decl.inputs);
let mut bcx_top = top_scope_block(fcx, body.info());
let lltop = bcx_top.llbb;
}
// note we don't want to take *or* drop self.
- fcx.llself = some({v: selfptr, t: rslt_ty, is_owned: false});
+ fcx.llself = Some({v: selfptr, t: rslt_ty, is_owned: false});
// Translate the body of the ctor
bcx = trans_block(bcx_top, body, ignore);
// Generate the return expression
bcx = store_temp_expr(bcx, INIT, fcx.llretptr, lval_res,
rslt_ty, true);
- cleanup_and_leave(bcx, none, some(fcx.llreturn));
+ cleanup_and_leave(bcx, None, Some(fcx.llreturn));
Unreachable(bcx);
finish_fn(fcx, lltop);
}
fn trans_class_dtor(ccx: @crate_ctxt, path: path,
body: ast::blk, dtor_id: ast::node_id,
- psubsts: option<param_substs>,
- hash_id: option<mono_id>, parent_id: ast::def_id)
+ psubsts: Option<param_substs>,
+ hash_id: Option<mono_id>, parent_id: ast::def_id)
-> ValueRef {
let tcx = ccx.tcx;
/* Look up the parent class's def_id */
ast::tuple_variant_kind(args) if args.len() > 0 => {
let llfn = get_item_val(ccx, variant.node.id);
trans_enum_variant(ccx, id, variant, args, disr_val,
- degen, none, llfn);
+ degen, None, llfn);
}
ast::tuple_variant_kind(_) => {
// Nothing to do.
let llfndecl = get_item_val(ccx, item.id);
trans_fn(ccx,
vec::append(*path, ~[path_name(item.ident)]),
- decl, body, llfndecl, no_self, none, item.id);
+ decl, body, llfndecl, no_self, None, item.id);
} else {
for vec::each(body.node.stmts) |stmt| {
match stmt.node {
ident: ast::ident, id: ast::node_id) {
if tps.len() == 0u {
let psubsts = {tys: ty::ty_params_to_tys(ccx.tcx, tps),
- vtables: none,
+ vtables: None,
bounds: @~[]};
do option::iter(struct_def.ctor) |ctor| {
trans_class_ctor(ccx, *path, ctor.node.dec, ctor.node.body,
}
do option::iter(struct_def.dtor) |dtor| {
trans_class_dtor(ccx, *path, dtor.node.body,
- dtor.node.id, none, none, local_def(id));
+ dtor.node.id, None, None, local_def(id));
};
}
// If there are ty params, the ctor will get monomorphized
fn create_main_wrapper(ccx: @crate_ctxt, sp: span, main_llfn: ValueRef,
main_node_type: ty::t) {
- if ccx.main_fn != none::<ValueRef> {
+ if ccx.main_fn != None::<ValueRef> {
ccx.sess.span_fatal(sp, ~"multiple 'main' functions");
}
};
let llfn = create_main(ccx, main_llfn, main_takes_argv);
- ccx.main_fn = some(llfn);
+ ccx.main_fn = Some(llfn);
create_entry_fn(ccx, llfn);
fn create_main(ccx: @crate_ctxt, main_llfn: ValueRef,
let llfdecl = decl_fn(ccx.llmod, ~"_rust_main",
lib::llvm::CCallConv, llfty);
- let fcx = new_fn_ctxt(ccx, ~[], llfdecl, none);
+ let fcx = new_fn_ctxt(ccx, ~[], llfdecl, None);
- let bcx = top_scope_block(fcx, none);
+ let bcx = top_scope_block(fcx, None);
let lltop = bcx.llbb;
let lloutputarg = llvm::LLVMGetParam(llfdecl, 0 as c_uint);
/* If there's already a symbol for the dtor with <id> and substs <substs>,
return it; otherwise, create one and register it, returning it as well */
fn get_dtor_symbol(ccx: @crate_ctxt, path: path, id: ast::node_id,
- substs: option<param_substs>) -> ~str {
+ substs: Option<param_substs>) -> ~str {
let t = ty::node_id_to_type(ccx.tcx, id);
match ccx.item_symbols.find(id) {
- some(s) => s,
- none if is_none(substs) => {
+ Some(s) => s,
+ None if is_none(substs) => {
let s = mangle_exported_name(
ccx,
vec::append(path, ~[path_name(ccx.names(~"dtor"))]),
ccx.item_symbols.insert(id, s);
s
}
- none => {
+ None => {
// Monomorphizing, so just make a symbol, don't add
// this to item_symbols
match substs {
- some(ss) => {
+ Some(ss) => {
let mono_ty = ty::subst_tps(ccx.tcx, ss.tys, t);
mangle_exported_name(
ccx,
~[path_name(ccx.names(~"dtor"))]),
mono_ty)
}
- none => {
+ None => {
ccx.sess.bug(fmt!("get_dtor_symbol: not monomorphizing and \
couldn't find a symbol for dtor %?", path));
}
debug!("get_item_val(id=`%?`)", id);
let tcx = ccx.tcx;
match ccx.item_vals.find(id) {
- some(v) => v,
- none => {
+ Some(v) => v,
+ None => {
let mut exprt = false;
let val = match ccx.tcx.items.get(id) {
ast_map::node_item(i, pth) => {
let lldty = T_fn(~[T_ptr(type_of(ccx, ty::mk_nil(tcx))),
T_ptr(type_of(ccx, class_ty))],
llvm::LLVMVoidType());
- let s = get_dtor_symbol(ccx, *pt, dt.node.id, none);
+ let s = get_dtor_symbol(ccx, *pt, dt.node.id, None);
/* Make the declaration for the dtor */
let llfn = decl_internal_cdecl_fn(ccx.llmod, s, lldty);
fn trap(bcx: block) {
let v: ~[ValueRef] = ~[];
match bcx.ccx().intrinsics.find(~"llvm.trap") {
- some(x) => { Call(bcx, x, v); },
+ Some(x) => { Call(bcx, x, v); },
_ => bcx.sess().bug(~"unbound llvm.trap in trap")
}
}
attr::find_attrs_by_name(item.attrs, ~"rt"));
do vec::iter(attr_metas) |attr_meta| {
match attr::get_meta_item_list(attr_meta) {
- some(list) => {
+ Some(list) => {
let name = attr::get_meta_item_name(vec::head(list));
push_rtcall(ccx, name, {crate: ast::local_crate,
node: item.id});
}
- none => ()
+ None => ()
}
}
}
lib::llvm::associate_type(tn, ~"tydesc", tydesc_type);
let crate_map = decl_crate_map(sess, link_meta, llmod);
let dbg_cx = if sess.opts.debuginfo {
- option::some(debuginfo::mk_ctxt(llmod_id, sess.parse_sess.interner))
+ option::Some(debuginfo::mk_ctxt(llmod_id, sess.parse_sess.interner))
} else {
- option::none
+ option::None
};
let ccx =
exp_map2: emap2,
reachable: reachable,
item_symbols: int_hash::<~str>(),
- mut main_fn: none::<ValueRef>,
+ mut main_fn: None::<ValueRef>,
link_meta: link_meta,
enum_sizes: ty::new_ty_hash(),
discrims: ast_util::new_def_hash::<ValueRef>(),
s += category;
let n = match h.find(s) {
- some(n) => n,
+ Some(n) => n,
_ => 0u
};
h.insert(s, n+1u);
cap_vars: ~[capture::capture_var],
ck: ty::closure_kind,
id: ast::node_id,
- include_ret_handle: option<ValueRef>) -> closure_result {
+ include_ret_handle: Option<ValueRef>) -> closure_result {
let _icx = bcx0.insn_ctxt("closure::build_closure");
// If we need to, package up the iterator body to call
let mut env_vals = ~[];
}
capture::cap_copy => {
let mv = match ccx.maps.last_use_map.find(id) {
- none => false,
- some(vars) => (*vars).contains(nid)
+ None => false,
+ Some(vars) => (*vars).contains(nid)
};
if mv { vec::push(env_vals, env_move(lv.val, ty, lv.kind)); }
else { vec::push(env_vals, env_copy(lv.val, ty, lv.kind)); }
}
do option::iter(include_ret_handle) |flagptr| {
let our_ret = match bcx.fcx.loop_ret {
- some({retptr, _}) => retptr,
- none => bcx.fcx.llretptr
+ Some({retptr, _}) => retptr,
+ None => bcx.fcx.llretptr
};
let nil_ret = PointerCast(bcx, our_ret, T_ptr(T_nil()));
vec::push(env_vals,
let retptr = Load(bcx,
GEPi(bcx, llcdata,
~[0u, i+1u]));
- fcx.loop_ret = some({flagptr: flagptr, retptr: retptr});
+ fcx.loop_ret = Some({flagptr: flagptr, retptr: retptr});
}
}
body: ast::blk,
id: ast::node_id,
cap_clause: ast::capture_clause,
- is_loop_body: option<option<ValueRef>>,
+ is_loop_body: Option<Option<ValueRef>>,
dest: dest) -> block {
let _icx = bcx.insn_ctxt("closure::trans_expr_fn");
if dest == ignore { return bcx; }
let trans_closure_env = fn@(ck: ty::closure_kind) -> result {
let cap_vars = capture::compute_capture_vars(ccx.tcx, id, proto,
cap_clause);
- let ret_handle = match is_loop_body { some(x) => x, none => none };
+ let ret_handle = match is_loop_body { Some(x) => x, None => None };
let {llbox, cdata_ty, bcx} = build_closure(bcx, cap_vars, ck, id,
ret_handle);
trans_closure(ccx, sub_path, decl, body, llfn, no_self,
ty::proto_vstore(ty::vstore_uniq) =>
trans_closure_env(ty::ck_uniq),
ty::proto_bare => {
- trans_closure(ccx, sub_path, decl, body, llfn, no_self, none,
+ trans_closure(ccx, sub_path, decl, body, llfn, no_self, None,
id, |_fcx| { }, |_bcx| { });
{bcx: bcx, val: C_null(T_opaque_box_ptr(ccx))}
}
// Take the data in the tuple
let cdata_out = GEPi(bcx, cbox_out, ~[0u, abi::box_field_body]);
call_tydesc_glue_full(bcx, cdata_out, tydesc,
- abi::tydesc_field_take_glue, none);
+ abi::tydesc_field_take_glue, None);
bcx
}
}
// Drop the tuple data then free the descriptor
let cdata = GEPi(bcx, cbox, ~[0u, abi::box_field_body]);
call_tydesc_glue_full(bcx, cdata, tydesc,
- abi::tydesc_field_drop_glue, none);
+ abi::tydesc_field_drop_glue, None);
// Free the ty descr (if necc) and the box itself
match ck {
size: ValueRef,
align: ValueRef,
addrspace: addrspace,
- mut take_glue: option<ValueRef>,
- mut drop_glue: option<ValueRef>,
- mut free_glue: option<ValueRef>,
- mut visit_glue: option<ValueRef>};
+ mut take_glue: Option<ValueRef>,
+ mut drop_glue: Option<ValueRef>,
+ mut free_glue: Option<ValueRef>,
+ mut visit_glue: Option<ValueRef>};
/*
* A note on nomenclature of linking: "extern", "foreign", and "upcall".
exp_map2: resolve3::ExportMap2,
reachable: reachable::map,
item_symbols: hashmap<ast::node_id, ~str>,
- mut main_fn: option<ValueRef>,
+ mut main_fn: Option<ValueRef>,
link_meta: link_meta,
enum_sizes: hashmap<ty::t, uint>,
discrims: hashmap<ast::def_id, ValueRef>,
discrim_symbols: hashmap<ast::node_id, ~str>,
tydescs: hashmap<ty::t, @tydesc_info>,
// Track mapping of external ids to local items imported for inlining
- external: hashmap<ast::def_id, option<ast::node_id>>,
+ external: hashmap<ast::def_id, Option<ast::node_id>>,
// Cache instances of monomorphized functions
monomorphized: hashmap<mono_id, ValueRef>,
monomorphizing: hashmap<ast::def_id, uint>,
builder: BuilderRef_res,
shape_cx: shape::ctxt,
crate_map: ValueRef,
- dbg_cx: option<debuginfo::debug_ctxt>,
+ dbg_cx: Option<debuginfo::debug_ctxt>,
// Mapping from class constructors to parent class --
// used in base::trans_closure
// parent_class must be a def_id because ctors can be
enum local_val { local_mem(ValueRef), local_imm(ValueRef), }
type param_substs = {tys: ~[ty::t],
- vtables: option<typeck::vtable_res>,
+ vtables: Option<typeck::vtable_res>,
bounds: @~[ty::param_bounds]};
// Function context. Every LLVM function we create will have one of
mut llreturn: BasicBlockRef,
// The 'self' value currently in use in this function, if there
// is one.
- mut llself: option<val_self_data>,
+ mut llself: Option<val_self_data>,
// The a value alloca'd for calls to upcalls.rust_personality. Used when
// outputting the resume instruction.
- mut personality: option<ValueRef>,
+ mut personality: Option<ValueRef>,
// If this is a for-loop body that returns, this holds the pointers needed
// for that
- mut loop_ret: option<{flagptr: ValueRef, retptr: ValueRef}>,
+ mut loop_ret: Option<{flagptr: ValueRef, retptr: ValueRef}>,
// Maps arguments to allocas created for them in llallocas.
llargs: hashmap<ast::node_id, local_val>,
// If this function is being monomorphized, this contains the type
// substitutions used.
- param_substs: option<param_substs>,
+ param_substs: Option<param_substs>,
// The source span and nesting context where this function comes from, for
// error reporting and symbol generation.
- span: option<span>,
+ span: Option<span>,
path: path,
// This function's enclosing crate context.
// Used to remember and reuse existing cleanup paths
// target: none means the path ends in an resume instruction
-type cleanup_path = {target: option<BasicBlockRef>,
+type cleanup_path = {target: Option<BasicBlockRef>,
dest: BasicBlockRef};
fn scope_clean_changed(info: scope_info) {
if info.cleanup_paths.len() > 0u { info.cleanup_paths = ~[]; }
- info.landing_pad = none;
+ info.landing_pad = None;
}
fn cleanup_type(cx: ty::ctxt, ty: ty::t) -> cleantype {
}
type scope_info = {
- loop_break: option<block>,
+ loop_break: Option<block>,
// A list of functions that must be run at when leaving this
// block, cleaning up any variables that were introduced in the
// block.
// cleared when the set of cleanups changes.
mut cleanup_paths: ~[cleanup_path],
// Unwinding landing pad. Also cleared when cleanups change.
- mut landing_pad: option<BasicBlockRef>,
+ mut landing_pad: Option<BasicBlockRef>,
};
trait get_node_info {
- fn info() -> option<node_info>;
+ fn info() -> Option<node_info>;
}
impl @ast::expr: get_node_info {
- fn info() -> option<node_info> {
- some({id: self.id, span: self.span})
+ fn info() -> Option<node_info> {
+ Some({id: self.id, span: self.span})
}
}
impl ast::blk: get_node_info {
- fn info() -> option<node_info> {
- some({id: self.node.id, span: self.span})
+ fn info() -> Option<node_info> {
+ Some({id: self.node.id, span: self.span})
}
}
// XXX: Work around a trait parsing bug. remove after snapshot
-type optional_boxed_ast_expr = option<@ast::expr>;
+type optional_boxed_ast_expr = Option<@ast::expr>;
impl optional_boxed_ast_expr: get_node_info {
- fn info() -> option<node_info> {
+ fn info() -> Option<node_info> {
self.chain(|s| s.info())
}
}
let llbb: BasicBlockRef;
let mut terminated: bool;
let mut unreachable: bool;
- let parent: option<block>;
+ let parent: Option<block>;
// The 'kind' of basic block this is.
let kind: block_kind;
// Is this block part of a landing pad?
let is_lpad: bool;
// info about the AST node this block originated from, if any
- let node_info: option<node_info>;
+ let node_info: Option<node_info>;
// The function context for the function to which this block is
// attached.
let fcx: fn_ctxt;
- new(llbb: BasicBlockRef, parent: option<block>, -kind: block_kind,
- is_lpad: bool, node_info: option<node_info>, fcx: fn_ctxt) {
+ new(llbb: BasicBlockRef, parent: Option<block>, -kind: block_kind,
+ is_lpad: bool, node_info: Option<node_info>, fcx: fn_ctxt) {
// sigh
self.llbb = llbb; self.terminated = false; self.unreachable = false;
self.parent = parent; self.kind = kind; self.is_lpad = is_lpad;
*/
enum block = @block_;
-fn mk_block(llbb: BasicBlockRef, parent: option<block>, -kind: block_kind,
- is_lpad: bool, node_info: option<node_info>, fcx: fn_ctxt)
+fn mk_block(llbb: BasicBlockRef, parent: Option<block>, -kind: block_kind,
+ is_lpad: bool, node_info: Option<node_info>, fcx: fn_ctxt)
-> block {
block(@block_(llbb, parent, kind, is_lpad, node_info, fcx))
}
fn block_parent(cx: block) -> block {
match cx.parent {
- some(b) => b,
- none => cx.sess().bug(fmt!("block_parent called on root block %?",
+ Some(b) => b,
+ None => cx.sess().bug(fmt!("block_parent called on root block %?",
cx))
}
}
}
fn to_str() -> ~str {
match self.node_info {
- some(node_info) => {
+ Some(node_info) => {
fmt!("[block %d]", node_info.id)
}
- none => {
+ None => {
fmt!("[block %x]", ptr::addr_of(*self) as uint)
}
}
fn T_generic_glue_fn(cx: @crate_ctxt) -> TypeRef {
let s = ~"glue_fn";
match name_has_type(cx.tn, s) {
- some(t) => return t,
+ Some(t) => return t,
_ => ()
}
let t = T_tydesc_field(cx, abi::tydesc_field_drop_glue);
fn T_typaram(tn: type_names) -> TypeRef {
let s = ~"typaram";
match name_has_type(tn, s) {
- some(t) => return t,
+ Some(t) => return t,
_ => ()
}
let t = T_i8();
fn T_opaque_enum(cx: @crate_ctxt) -> TypeRef {
let s = ~"opaque_enum";
match name_has_type(cx.tn, s) {
- some(t) => return t,
+ Some(t) => return t,
_ => ()
}
let t = T_struct(~[T_enum_discrim(cx), T_i8()]);
// our boxed-and-length-annotated strings.
fn C_cstr(cx: @crate_ctxt, s: ~str) -> ValueRef {
match cx.const_cstr_cache.find(s) {
- some(llval) => return llval,
- none => ()
+ Some(llval) => return llval,
+ None => ()
}
let sc = do str::as_c_str(s) |buf| {
// Used to identify cached monomorphized functions and vtables
enum mono_param_id {
- mono_precise(ty::t, option<~[mono_id]>),
+ mono_precise(ty::t, Option<~[mono_id]>),
mono_any,
mono_repr(uint /* size */, uint /* align */),
}
let tcx = bcx.tcx();
let t = ty::node_id_to_type(tcx, id);
match bcx.fcx.param_substs {
- some(substs) => ty::subst_tps(tcx, substs.tys, t),
+ Some(substs) => ty::subst_tps(tcx, substs.tys, t),
_ => { assert !ty::type_has_params(t); t }
}
}
let tcx = bcx.tcx();
let params = ty::node_id_to_type_params(tcx, id);
match bcx.fcx.param_substs {
- some(substs) => {
+ Some(substs) => {
vec::map(params, |t| ty::subst_tps(tcx, substs.tys, t))
}
_ => params
fields: ~[ty::field])
-> uint {
match ty::field_idx(ident, fields) {
- none => cx.sess.span_bug(
+ None => cx.sess.span_bug(
sp, fmt!("base expr doesn't appear to \
have a field named %s", cx.sess.str_of(ident))),
- some(i) => i
+ Some(i) => i
}
}
fn dummy_substs(tps: ~[ty::t]) -> ty::substs {
- {self_r: some(ty::re_bound(ty::br_self)),
- self_ty: none,
+ {self_r: Some(ty::re_bound(ty::br_self)),
+ self_ty: None,
tps: tps}
}
fn const_deref(cx: @crate_ctxt, v: ValueRef) -> ValueRef {
let v = match cx.const_globals.find(v as int) {
- some(v) => v,
- none => v
+ Some(v) => v,
+ None => v
};
assert llvm::LLVMIsGlobalConstant(v) == True;
let v = llvm::LLVMGetInitializer(v);
}
C_named_struct(llty, cs)
}
- ast::expr_rec(fs, none) => {
+ ast::expr_rec(fs, None) => {
C_struct(fs.map(|f| const_expr(cx, f.node.expr)))
}
ast::expr_vec(es, ast::m_imm) => {
}
ast::expr_path(_) => {
match cx.tcx.def_map.find(e.id) {
- some(ast::def_const(def_id)) => {
+ Some(ast::def_const(def_id)) => {
// Don't know how to handle external consts
assert ast_util::is_local(def_id);
match cx.tcx.items.get(def_id.node) {
}
fn cached_metadata<T: copy>(cache: metadata_cache, mdtag: int,
- eq: fn(md: T) -> bool) -> option<T> unsafe {
+ eq: fn(md: T) -> bool) -> Option<T> unsafe {
if cache.contains_key(mdtag) {
let items = cache.get(mdtag);
for items.each |item| {
let md: T = md_from_metadata::<T>(item);
if eq(md) {
- return option::some(md);
+ return option::Some(md);
}
}
}
- return option::none;
+ return option::None;
}
fn create_compile_unit(cx: @crate_ctxt)
let tg = CompileUnitTag;
match cached_metadata::<@metadata<compile_unit_md>>(cache, tg,
|md| md.data.name == crate_name) {
- option::some(md) => return md,
- option::none => ()
+ option::Some(md) => return md,
+ option::None => ()
}
let (_, work_dir) = get_file_path_and_dir(cx.sess.working_dir.to_str(),
let tg = FileDescriptorTag;
match cached_metadata::<@metadata<file_md>>(
cache, tg, |md| md.data.path == full_path) {
- option::some(md) => return md,
- option::none => ()
+ option::Some(md) => return md,
+ option::None => ()
}
let (file_path, work_dir) =
let mut cx = cx;
while option::is_none(cx.node_info) {
match cx.parent {
- some(b) => cx = b,
- none => fail
+ Some(b) => cx = b,
+ None => fail
}
}
let sp = option::get(cx.node_info).span;
/*alt cached_metadata::<@metadata<block_md>>(
cache, tg,
{|md| start == md.data.start && end == md.data.end}) {
- option::some(md) { return md; }
- option::none {}
+ option::Some(md) { return md; }
+ option::None {}
}*/
let parent = match cx.parent {
- none => create_function(cx.fcx).node,
- some(bcx) => create_block(bcx).node
+ None => create_function(cx.fcx).node,
+ Some(bcx) => create_block(bcx).node
};
let file_node = create_file(cx.ccx(), fname);
let unique_id = match cache.find(LexicalBlockTag) {
- option::some(v) => vec::len(v) as int,
- option::none => 0
+ option::Some(v) => vec::len(v) as int,
+ option::None => 0
};
let lldata = ~[lltag(tg),
parent,
let tg = BasicTypeDescriptorTag;
match cached_metadata::<@metadata<tydesc_md>>(
cache, tg, |md| ty::type_id(t) == md.data.hash) {
- option::some(md) => return md,
- option::none => ()
+ option::Some(md) => return md,
+ option::None => ()
}
let (name, encoding) = (~"uint", DW_ATE_unsigned);
/*let cache = cx.llmetadata;
match cached_metadata::<@metadata<tydesc_md>>(
cache, tg, {|md| ty::hash_ty(t) == ty::hash_ty(md.data.hash)}) {
- option::some(md) { return md; }
- option::none {}
+ option::Some(md) { return md; }
+ option::None {}
}*/
let (size, align) = size_and_align_of(cx, t);
let fname = filename_from_span(cx, span);
fn finish_structure(cx: @struct_ctxt) -> ValueRef {
return create_composite_type(StructureTypeTag, cx.name, cx.file, cx.line,
- cx.total_size, cx.align, 0, option::none,
- option::some(cx.members));
+ cx.total_size, cx.align, 0, option::None,
+ option::Some(cx.members));
}
fn create_structure(file: @metadata<file_md>, name: ~str, line: int)
/*let cache = cx.llmetadata;
match cached_metadata::<@metadata<tydesc_md>>(
cache, tg, {|md| ty::hash_ty(outer) == ty::hash_ty(md.data.hash)}) {
- option::some(md) { return md; }
- option::none {}
+ option::Some(md) { return md; }
+ option::None {}
}*/
let fname = filename_from_span(cx, span);
let file_node = create_file(cx, fname);
fn create_composite_type(type_tag: int, name: ~str, file: ValueRef, line: int,
size: int, align: int, offset: int,
- derived: option<ValueRef>,
- members: option<~[ValueRef]>)
+ derived: Option<ValueRef>,
+ members: Option<~[ValueRef]>)
-> ValueRef {
let lldata = ~[lltag(type_tag),
file,
let (arr_size, arr_align) = size_and_align_of(cx, elem_t);
let data_ptr = create_composite_type(ArrayTypeTag, ~"", file_node.node, 0,
arr_size, arr_align, 0,
- option::some(elem_ty_md.node),
- option::some(~[subrange]));
+ option::Some(elem_ty_md.node),
+ option::Some(~[subrange]));
add_member(scx, ~"data", 0, 0, // clang says the size should be 0
sys::min_align_of::<u8>() as int, data_ptr);
let llnode = finish_structure(scx);
/*let cache = get_cache(cx);
match cached_metadata::<@metadata<tydesc_md>>(
cache, tg, {|md| t == md.data.hash}) {
- option::some(md) { return md; }
- option::none {}
+ option::Some(md) { return md; }
+ option::None {}
}*/
/* FIXME (#2012): disabled this code as part of the patch that moves
let tg = AutoVariableTag;
match cached_metadata::<@metadata<local_var_md>>(
cache, tg, |md| md.data.id == local.node.id) {
- option::some(md) => return md,
- option::none => ()
+ option::Some(md) => return md,
+ option::None => ()
}
let name = match local.node.pat.node {
let tymd = create_ty(cx, ty, local.node.ty);
let filemd = create_file(cx, loc.file.name);
let context = match bcx.parent {
- none => create_function(bcx.fcx).node,
- some(_) => create_block(bcx).node
+ None => create_function(bcx.fcx).node,
+ Some(_) => create_block(bcx).node
};
let mdnode = create_var(tg, context, cx.sess.str_of(name), filemd.node,
loc.line as int, tymd.node);
update_cache(cache, AutoVariableTag, local_var_metadata(mdval));
let llptr = match bcx.fcx.lllocals.find(local.node.id) {
- option::some(local_mem(v)) => v,
- option::some(_) => {
+ option::Some(local_mem(v)) => v,
+ option::Some(_) => {
bcx.tcx().sess.span_bug(local.span, ~"local is bound to \
something weird");
}
- option::none => {
+ option::None => {
match bcx.fcx.lllocals.get(local.node.pat.id) {
local_imm(v) => v,
_ => bcx.tcx().sess.span_bug(local.span, ~"local is bound to \
let tg = ArgVariableTag;
match cached_metadata::<@metadata<argument_md>>(
cache, ArgVariableTag, |md| md.data.id == arg.id) {
- option::some(md) => return md,
- option::none => ()
+ option::Some(md) => return md,
+ option::None => ()
}
let loc = codemap::lookup_char_pos(cx.sess.codemap,
let cache = get_cache(cx);
match cached_metadata::<@metadata<subprogram_md>>(
cache, SubprogramTag, |md| md.data.id == id) {
- option::some(md) => return md,
- option::none => ()
+ option::Some(md) => return md,
+ option::None => ()
}
let loc = codemap::lookup_char_pos(cx.sess.codemap,
llnull()
};
let sub_node = create_composite_type(SubroutineTag, ~"", file_node, 0, 0,
- 0, 0, option::none,
- option::some(~[ty_node]));
+ 0, 0, option::None,
+ option::Some(~[ty_node]));
let fn_metadata = ~[lltag(SubprogramTag),
llunused(),
type x86_64_tys = {
arg_tys: ~[x86_64_llty],
ret_ty: x86_64_llty,
- attrs: ~[option<Attribute>],
+ attrs: ~[Option<Attribute>],
sret: bool
};
fn x86_64_ty(ty: TypeRef,
is_mem_cls: fn(cls: ~[x86_64_reg_class]) -> bool,
- attr: Attribute) -> (x86_64_llty, option<Attribute>) {
+ attr: Attribute) -> (x86_64_llty, Option<Attribute>) {
let mut cast = false;
- let mut ty_attr = option::none;
+ let mut ty_attr = option::None;
let mut llty = ty;
if !is_reg_ty(ty) {
let cls = classify_ty(ty);
if is_mem_cls(cls) {
llty = T_ptr(ty);
- ty_attr = option::some(attr);
+ ty_attr = option::Some(attr);
} else {
cast = true;
llty = llreg_ty(cls);
do vec::iteri(tys.attrs) |i, a| {
match a {
- option::some(attr) => {
+ option::Some(attr) => {
let llarg = get_param(llfn, i);
llvm::LLVMAddAttribute(llarg, attr as c_uint);
}
fn link_name(ccx: @crate_ctxt, i: @ast::foreign_item) -> ~str {
match attr::first_attr_value_str_by_name(i.attrs, ~"link_name") {
- none => ccx.sess.str_of(i.ident),
- option::some(ln) => ln
+ None => ccx.sess.str_of(i.ident),
+ option::Some(ln) => ln
}
}
ret_def: bool,
bundle_ty: TypeRef,
shim_fn_ty: TypeRef,
- x86_64_tys: option<x86_64_tys>
+ x86_64_tys: Option<x86_64_tys>
};
fn c_arg_and_ret_lltys(ccx: @crate_ctxt,
let bundle_ty = T_struct(vec::append_one(llargtys, T_ptr(llretty)));
let ret_def = !ty::type_is_bot(ret_ty) && !ty::type_is_nil(ret_ty);
let x86_64 = if ccx.sess.targ_cfg.arch == arch_x86_64 {
- option::some(x86_64_tys(llargtys, llretty, ret_def))
+ option::Some(x86_64_tys(llargtys, llretty, ret_def))
} else {
- option::none
+ option::None
};
return @{
arg_tys: llargtys,
ccx.llmod, shim_name, tys.shim_fn_ty);
// Declare the body of the shim function:
- let fcx = new_fn_ctxt(ccx, ~[], llshimfn, none);
- let bcx = top_scope_block(fcx, none);
+ let fcx = new_fn_ctxt(ccx, ~[], llshimfn, None);
+ let bcx = top_scope_block(fcx, None);
let lltop = bcx.llbb;
let llargbundle = get_param(llshimfn, 0u);
let llargvals = arg_builder(bcx, tys, llargbundle);
ret_builder: wrap_ret_builder) {
let _icx = ccx.insn_ctxt("foreign::build_wrap_fn_");
- let fcx = new_fn_ctxt(ccx, ~[], llwrapfn, none);
- let bcx = top_scope_block(fcx, none);
+ let fcx = new_fn_ctxt(ccx, ~[], llwrapfn, None);
+ let bcx = top_scope_block(fcx, None);
let lltop = bcx.llbb;
// Allocate the struct and write the arguments into it.
let n = vec::len(tys.arg_tys);
match tys.x86_64_tys {
- some(x86_64) => {
+ Some(x86_64) => {
let mut atys = x86_64.arg_tys;
let mut attrs = x86_64.attrs;
if x86_64.sret {
llargbundle: ValueRef, llretval: ValueRef) {
let _icx = bcx.insn_ctxt("foreign::shim::build_ret");
match tys.x86_64_tys {
- some(x86_64) => {
+ Some(x86_64) => {
do vec::iteri(x86_64.attrs) |i, a| {
match a {
- some(attr) => {
+ Some(attr) => {
llvm::LLVMAddInstrAttribute(
llretval, (i + 1u) as c_uint,
attr as c_uint);
cc: lib::llvm::CallConv) -> ValueRef {
// Declare the "prototype" for the base function F:
match tys.x86_64_tys {
- some(x86_64) => {
+ Some(x86_64) => {
do decl_x86_64_fn(x86_64) |fnty| {
decl_fn(ccx.llmod, lname, cc, fnty)
}
fn build_direct_fn(ccx: @crate_ctxt, decl: ValueRef,
item: @ast::foreign_item, tys: @c_stack_tys,
cc: lib::llvm::CallConv) {
- let fcx = new_fn_ctxt(ccx, ~[], decl, none);
- let bcx = top_scope_block(fcx, none), lltop = bcx.llbb;
+ let fcx = new_fn_ctxt(ccx, ~[], decl, None);
+ let bcx = top_scope_block(fcx, None), lltop = bcx.llbb;
let llbasefn = base_fn(ccx, link_name(ccx, item), tys, cc);
let ty = ty::lookup_item_type(ccx.tcx,
ast_util::local_def(item.id)).ty;
if typarams.is_empty() {
let llwrapfn = get_item_val(ccx, id);
let path = match ccx.tcx.items.find(id) {
- some(ast_map::node_foreign_item(_, _, pt)) => pt,
+ Some(ast_map::node_foreign_item(_, _, pt)) => pt,
_ => {
ccx.sess.span_bug(foreign_item.span,
~"can't find intrinsic path")
};
let psubsts = {
tys: ~[],
- vtables: none,
+ vtables: None,
bounds: @~[]
};
trans_intrinsic(ccx, llwrapfn, foreign_item,
- *path, psubsts, none);
+ *path, psubsts, None);
}
}
}
fn trans_intrinsic(ccx: @crate_ctxt, decl: ValueRef, item: @ast::foreign_item,
path: ast_map::path, substs: param_substs,
- ref_id: option<ast::node_id>) {
+ ref_id: Option<ast::node_id>) {
let fcx = new_fn_ctxt_w_id(ccx, path, decl, item.id,
- some(substs), some(item.span));
- let mut bcx = top_scope_block(fcx, none), lltop = bcx.llbb;
+ Some(substs), Some(item.span));
+ let mut bcx = top_scope_block(fcx, None), lltop = bcx.llbb;
match ccx.sess.str_of(item.ident) {
~"atomic_xchg" => {
let old = AtomicRMW(bcx, Xchg,
let visitor = get_param(decl, first_real_arg + 1u);
let td = PointerCast(bcx, td, T_ptr(ccx.tydesc_type));
call_tydesc_glue_full(bcx, visitor, td,
- abi::tydesc_field_visit_glue, none);
+ abi::tydesc_field_visit_glue, None);
}
~"frame_address" => {
let frameaddress = ccx.intrinsics.get(~"llvm.frameaddress");
output: ty::mk_nil(bcx.tcx()),
ret_style: ast::return_val
});
- bcx = trans_call_inner(bcx, none, fty, ty::mk_nil(bcx.tcx()),
+ bcx = trans_call_inner(bcx, None, fty, ty::mk_nil(bcx.tcx()),
|bcx| lval_no_env(
bcx,
get_param(decl, first_real_arg),
)));
let llty = type_of_fn_from_ty(ccx, t);
let llfndecl = decl_internal_cdecl_fn(ccx.llmod, ps, llty);
- trans_fn(ccx, path, decl, body, llfndecl, no_self, none, id);
+ trans_fn(ccx, path, decl, body, llfndecl, no_self, None, id);
return llfndecl;
}
llwrapfn: ValueRef, llargbundle: ValueRef) {
let _icx = bcx.insn_ctxt("foreign::foreign::wrap::build_args");
match tys.x86_64_tys {
- option::some(x86_64) => {
+ option::Some(x86_64) => {
let mut atys = x86_64.arg_tys;
let mut attrs = x86_64.attrs;
let mut j = 0u;
llargbundle: ValueRef) {
let _icx = bcx.insn_ctxt("foreign::foreign::wrap::build_ret");
match tys.x86_64_tys {
- option::some(x86_64) => {
+ option::Some(x86_64) => {
if x86_64.sret || !tys.ret_def {
RetVoid(bcx);
return;
fn abi_of_foreign_fn(ccx: @crate_ctxt, i: @ast::foreign_item)
-> ast::foreign_abi {
match attr::first_attr_value_str_by_name(i.attrs, ~"abi") {
- none => match ccx.tcx.items.get(i.id) {
+ None => match ccx.tcx.items.get(i.id) {
ast_map::node_foreign_item(_, abi, _) => abi,
// ??
_ => fail ~"abi_of_foreign_fn: not foreign"
},
- some(_) => match attr::foreign_abi(i.attrs) {
+ Some(_) => match attr::foreign_abi(i.attrs) {
either::Right(abi) => abi,
either::Left(msg) => ccx.sess.span_fatal(i.span, msg)
}
if method.tps.len() == 0u {
let llfn = get_item_val(ccx, method.id);
let path = vec::append_one(sub_path, path_name(method.ident));
- trans_method(ccx, path, method, none, llfn);
+ trans_method(ccx, path, method, None, llfn);
}
}
}
fn trans_method(ccx: @crate_ctxt,
path: path,
method: &ast::method,
- param_substs: option<param_substs>,
+ param_substs: Option<param_substs>,
llfn: ValueRef) {
// figure out how self is being passed
// this method
let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id);
let self_ty = match param_substs {
- none => self_ty,
- some({tys: ref tys, _}) => ty::subst_tps(ccx.tcx, *tys, self_ty)
+ None => self_ty,
+ Some({tys: ref tys, _}) => ty::subst_tps(ccx.tcx, *tys, self_ty)
};
match method.self_ty.node {
ast::sty_value => {
let mut temp_cleanups = ~[];
let result = trans_arg_expr(bcx, {mode: mode, ty: basety},
T_ptr(type_of::type_of(bcx.ccx(), basety)),
- base, temp_cleanups, none, mentry.derefs);
+ base, temp_cleanups, None, mentry.derefs);
// by-ref self argument should not require cleanup in the case of
// other arguments failing:
let {bcx, val} = trans_self_arg(bcx, self, mentry);
- {env: self_env(val, node_id_type(bcx, self.id), none,
+ {env: self_env(val, node_id_type(bcx, self.id), None,
mentry.self_mode)
with lval_static_fn(bcx, did, callee_id)}
}
typeck::method_param({trait_id:trait_id, method_num:off,
param_num:p, bound_num:b}) => {
match bcx.fcx.param_substs {
- some(substs) => {
+ Some(substs) => {
let vtbl = find_vtable_in_fn_ctxt(substs, p, b);
trans_monomorphized_callee(bcx, callee_id, self, mentry,
trait_id, off, vtbl)
}
// how to get rid of this?
- none => fail ~"trans_method_callee: missing param_substs"
+ None => fail ~"trans_method_callee: missing param_substs"
}
}
typeck::method_trait(_, off) => {
node_substs.len() - n_m_tps));
let lval = lval_static_fn_inner(bcx, mth_id, callee_id, ty_substs,
- some(sub_origins));
+ Some(sub_origins));
{env: null_env,
val: PointerCast(bcx, lval.val, T_ptr(type_of_fn_from_ty(
ccx, node_id_type(bcx, callee_id))))
node_substs.len() - n_m_tps));
let {bcx, val} = trans_self_arg(bcx, base, mentry);
let lval = lval_static_fn_inner(bcx, mth_id, callee_id, ty_substs,
- some(sub_origins));
+ Some(sub_origins));
{env: self_env(val, node_id_type(bcx, base.id),
- none, mentry.self_mode),
+ None, mentry.self_mode),
val: PointerCast(bcx, lval.val, T_ptr(type_of_fn_from_ty(
ccx, node_id_type(bcx, callee_id))))
with lval}
let llbox = Load(bcx, GEPi(bcx, val, ~[0u, 1u]));
// FIXME[impl] I doubt this is alignment-safe (#2534)
let self = GEPi(bcx, llbox, ~[0u, abi::box_field_body]);
- let env = self_env(self, ty::mk_opaque_box(bcx.tcx()), some(llbox),
+ let env = self_env(self, ty::mk_opaque_box(bcx.tcx()), Some(llbox),
// XXX: is this bogosity?
ast::by_ref);
let llfty = type_of::type_of_fn_from_ty(ccx, callee_ty);
match vt {
typeck::vtable_static(trait_id, tys, sub) => {
let tys = match fcx.param_substs {
- some(substs) => {
+ Some(substs) => {
vec::map(tys, |t| ty::subst_tps(fcx.ccx.tcx, substs.tys, t))
}
_ => tys
}
typeck::vtable_param(n_param, n_bound) => {
match fcx.param_substs {
- some(substs) => {
+ Some(substs) => {
find_vtable_in_fn_ctxt(substs, n_param, n_bound)
}
_ => fail ~"resolve_vtable_in_fn_ctxt: no substs"
match origin {
typeck::vtable_static(impl_id, substs, sub_vtables) => {
make_mono_id(ccx, impl_id, substs,
- if (*sub_vtables).len() == 0u { none }
- else { some(sub_vtables) }, none)
+ if (*sub_vtables).len() == 0u { None }
+ else { Some(sub_vtables) }, None)
}
typeck::vtable_trait(trait_id, substs) => {
@{def: trait_id,
- params: vec::map(substs, |t| mono_precise(t, none))}
+ params: vec::map(substs, |t| mono_precise(t, None))}
}
// can't this be checked at the callee?
_ => fail ~"vtable_id"
-> ValueRef {
let hash_id = vtable_id(ccx, origin);
match ccx.vtables.find(hash_id) {
- some(val) => val,
- none => match origin {
+ Some(val) => val,
+ None => match origin {
typeck::vtable_static(id, substs, sub_vtables) => {
make_impl_vtable(ccx, id, substs, sub_vtables)
}
if m_id.crate != ast::local_crate {
m_id = maybe_instantiate_inline(ccx, m_id);
}
- monomorphic_fn(ccx, m_id, substs, some(vtables), none).val
+ monomorphic_fn(ccx, m_id, substs, Some(vtables), None).val
} else if m_id.crate == ast::local_crate {
get_item_val(ccx, m_id.node)
} else {
fn traverse_def_id(cx: ctx, did: def_id) {
if did.crate != local_crate { return; }
let n = match cx.tcx.items.find(did.node) {
- none => return, // This can happen for self, for example
- some(n) => n
+ None => return, // This can happen for self, for example
+ Some(n) => n
};
match n {
ast_map::node_item(item, _) => traverse_public_item(cx, item),
match cx.tcx.def_map.find(p_id) {
// Kind of a hack to check this here, but I'm not sure what else
// to do
- some(def_prim_ty(_)) => { /* do nothing */ }
- some(d) => traverse_def_id(cx, def_id_of_def(d)),
- none => { /* do nothing -- but should we fail here? */ }
+ Some(def_prim_ty(_)) => { /* do nothing */ }
+ Some(d) => traverse_def_id(cx, def_id_of_def(d)),
+ None => { /* do nothing -- but should we fail here? */ }
}
for p.types.each |t| { v.visit_ty(t, cx, v); };
}
match e.node {
expr_path(_) => {
match cx.tcx.def_map.find(e.id) {
- some(d) => {
+ Some(d) => {
traverse_def_id(cx, def_id_of_def(d));
}
- none => cx.tcx.sess.span_bug(e.span, fmt!("Unbound node \
+ None => cx.tcx.sess.span_bug(e.span, fmt!("Unbound node \
id %? while traversing %s", e.id,
expr_to_str(e, cx.tcx.sess.intr())))
}
}
expr_field(_, _, _) => {
match cx.method_map.find(e.id) {
- some({origin: typeck::method_static(did), _}) => {
+ Some({origin: typeck::method_static(did), _}) => {
traverse_def_id(cx, did);
}
_ => ()
}
let d = empty_dest_cell();
let bcx =
- trans_call_inner(self.bcx, none, mth_ty, ty::mk_bool(tcx),
+ trans_call_inner(self.bcx, None, mth_ty, ty::mk_bool(tcx),
get_lval, arg_vals(args), by_val(d));
let next_bcx = sub_block(bcx, ~"next");
CondBr(bcx, *d, next_bcx.llbb, self.final_bcx.llbb);
import ty_ctxt = middle::ty::ctxt;
-type nominal_id = @{did: ast::def_id, parent_id: option<ast::def_id>,
+type nominal_id = @{did: ast::def_id, parent_id: Option<ast::def_id>,
tps: ~[ty::t]};
fn mk_nominal_id(tcx: ty::ctxt, did: ast::def_id,
- parent_id: option<ast::def_id>,
+ parent_id: Option<ast::def_id>,
tps: ~[ty::t]) -> nominal_id {
let tps_norm = tps.map(|t| ty::normalize_ty(tcx, t));
@{did: did, parent_id: parent_id, tps: tps_norm}
tk_enum => ~[s_variant_enum_t(ccx.tcx)],
tk_newtype | tk_complex => {
let mut s = ~[shape_enum], id;
- let nom_id = mk_nominal_id(ccx.tcx, did, none, substs.tps);
+ let nom_id = mk_nominal_id(ccx.tcx, did, None, substs.tps);
match ccx.shape_cx.tag_id_to_index.find(nom_id) {
- none => {
+ None => {
id = ccx.shape_cx.next_tag_id;
ccx.shape_cx.tag_id_to_index.insert(nom_id, id);
ccx.shape_cx.tag_order.push({did: did, substs: substs});
ccx.shape_cx.next_tag_id += 1u16;
}
- some(existing_id) => id = existing_id,
+ Some(existing_id) => id = existing_id,
}
add_u16(s, id as u16);
}
else { ~[shape_struct] }, sub = ~[];
do option::iter(m_dtor_did) |dtor_did| {
- let ri = @{did: dtor_did, parent_id: some(did), tps: tps};
+ let ri = @{did: dtor_did, parent_id: Some(did), tps: tps};
let id = ccx.shape_cx.resources.intern(ri);
add_u16(s, id as u16);
};
v: ast::vstore, dest: dest) -> block {
match e.node {
ast::expr_lit(@{node: ast::lit_str(s), span: _}) => {
- return trans_estr(bcx, s, some(v), dest);
+ return trans_estr(bcx, s, Some(v), dest);
}
ast::expr_vec(es, mutbl) => {
return trans_evec(bcx, individual_evec(es), v, e.id, dest);
}
}
-fn trans_estr(bcx: block, s: @~str, vstore: option<ast::vstore>,
+fn trans_estr(bcx: block, s: @~str, vstore: Option<ast::vstore>,
dest: dest) -> block {
let _icx = bcx.insn_ctxt("tvec::trans_estr");
if dest == base::ignore { return bcx; }
let ccx = bcx.ccx();
let c = match vstore {
- some(ast::vstore_fixed(_)) => {
+ Some(ast::vstore_fixed(_)) => {
// "hello"/_ => "hello"/5 => ~[i8 x 6] in llvm
debug!("trans_estr: fixed: %s", *s);
C_postr(*s)
}
- some(ast::vstore_slice(_)) | none => {
+ Some(ast::vstore_slice(_)) | None => {
// "hello" => (*i8, 6u) in llvm
debug!("trans_estr: slice '%s'", *s);
C_estr_slice(ccx, *s)
}
- some(ast::vstore_uniq) => {
+ Some(ast::vstore_uniq) => {
let cs = PointerCast(bcx, C_cstr(ccx, *s), T_ptr(T_i8()));
let len = C_uint(ccx, str::len(*s));
let c = Call(bcx, ccx.upcalls.str_new_uniq, ~[cs, len]);
T_unique_ptr(T_unique(ccx, T_vec(ccx, T_i8()))))
}
- some(ast::vstore_box) => {
+ Some(ast::vstore_box) => {
let cs = PointerCast(bcx, C_cstr(ccx, *s), T_ptr(T_i8()));
let len = C_uint(ccx, str::len(*s));
let c = Call(bcx, ccx.upcalls.str_new_shared, ~[cs, len]);
type_of(cx, t)
};
- if ty::ty_dtor(cx.tcx, did) != none {
+ if ty::ty_dtor(cx.tcx, did) != None {
// resource type
tys = ~[T_i8(), T_struct(tys)];
}
util::ppaux::parameterized(
cx.tcx,
ty::item_path_str(cx.tcx, did),
- none,
+ None,
tps),
did.crate
);
fn type_uses_for(ccx: @crate_ctxt, fn_id: def_id, n_tps: uint)
-> ~[type_uses] {
match ccx.type_use_cache.find(fn_id) {
- some(uses) => return uses,
- none => ()
+ Some(uses) => return uses,
+ None => ()
}
let fn_id_loc = if fn_id.crate == local_crate { fn_id }
else { base::maybe_instantiate_inline(ccx, fn_id) };
return uses;
}
let map_node = match ccx.tcx.items.find(fn_id_loc.node) {
- some(x) => x,
- none => ccx.sess.bug(fmt!("type_uses_for: unbound item ID %?",
+ Some(x) => x,
+ None => ccx.sess.bug(fmt!("type_uses_for: unbound item ID %?",
fn_id_loc))
};
match map_node {
}
}
expr_assign(val, _) | expr_swap(val, _) | expr_assign_op(_, val, _) |
- expr_ret(some(val)) => {
+ expr_ret(Some(val)) => {
node_type_needs(cx, use_repr, val.id);
}
expr_index(base, _) | expr_field(base, _, _) => {
ccx.node_anns[i] = a;
}
-fn get_ts_ann(ccx: crate_ctxt, i: node_id) -> option<ts_ann> {
+fn get_ts_ann(ccx: crate_ctxt, i: node_id) -> Option<ts_ann> {
if i as uint < vec::len(*ccx.node_anns) {
return some::<ts_ann>(ccx.node_anns[i]);
} else { return none::<ts_ann>; }
error!("node_id_to_ts_ann: no ts_ann for node_id %d", id);
fail;
}
- some(tt) { return tt; }
+ Some(tt) { return tt; }
}
}
error!("node_id_to_def: node_id %d has no def", id);
fail;
}
- some(d) { return d; }
+ Some(d) { return d; }
}
}
-fn node_id_to_def(ccx: crate_ctxt, id: node_id) -> option<def> {
+fn node_id_to_def(ccx: crate_ctxt, id: node_id) -> Option<def> {
return ccx.tcx.def_map.find(id);
}
none {
tcx.sess.bug(~"node_id_for_constr: bad node_id " + int::str(t));
}
- some(def_fn(i, _)) { return i; }
+ Some(def_fn(i, _)) { return i; }
_ { tcx.sess.bug(~"node_id_for_constr: pred is not a function"); }
}
}
match e.node {
expr_path(p) {
match tcx.def_map.find(e.id) {
- some(def_local(nid, _)) | some(def_arg(nid, _)) |
- some(def_binding(nid, _)) | some(def_upvar(nid, _, _, _)) {
+ Some(def_local(nid, _)) | Some(def_arg(nid, _)) |
+ Some(def_binding(nid, _)) | Some(def_upvar(nid, _, _, _)) {
return @respan(p.span,
carg_ident({ident: p.idents[0], node: nid}));
}
- some(what) {
+ Some(what) {
tcx.sess.span_bug(e.span,
fmt!("exprs_to_constr_args: non-local variable %? \
as pred arg", what));
fn find_instance_(pattern: ~[constr_arg_general_<inst>],
descs: ~[pred_args]) ->
- option<uint> {
+ Option<uint> {
for descs.each |d| {
- if pred_args_matches(pattern, d) { return some(d.node.bit_num); }
+ if pred_args_matches(pattern, d) { return Some(d.node.bit_num); }
}
return none;
}
let old_bit_num = d.node.bit_num;
let newv = replace(subst, d);
match find_instance_(newv, v) {
- some(d1) {vec::push(res, {from: old_bit_num, to: d1})}
+ Some(d1) {vec::push(res, {from: old_bit_num, to: d1})}
_ {}
}
} else {}
return res;
}
-fn find_in_subst(id: node_id, s: subst) -> option<inst> {
+fn find_in_subst(id: node_id, s: subst) -> Option<inst> {
for s.each |p| {
- if id == p.from.node { return some(p.to); }
+ if id == p.from.node { return Some(p.to); }
}
return none;
}
match c.node {
carg_ident(p) {
match find_in_subst(p.node, subst) {
- some(newv) { vec::push(rslt, carg_ident(newv)); }
+ Some(newv) { vec::push(rslt, carg_ident(newv)); }
_ { vec::push(rslt, c.node); }
}
}
fn local_node_id_to_def_id_strict(fcx: fn_ctxt, sp: span, i: node_id) ->
def_id {
match local_node_id_to_def(fcx, i) {
- some(def_local(nid, _)) | some(def_arg(nid, _)) |
- some(def_upvar(nid, _, _)) {
+ Some(def_local(nid, _)) | Some(def_arg(nid, _)) |
+ Some(def_upvar(nid, _, _)) {
return local_def(nid);
}
- some(_) {
+ Some(_) {
fcx.ccx.tcx.sess.span_fatal(sp,
~"local_node_id_to_def_id: id \
isn't a local");
}
}
-fn local_node_id_to_def(fcx: fn_ctxt, i: node_id) -> option<def> {
+fn local_node_id_to_def(fcx: fn_ctxt, i: node_id) -> Option<def> {
fcx.ccx.tcx.def_map.find(i)
}
-fn local_node_id_to_def_id(fcx: fn_ctxt, i: node_id) -> option<def_id> {
+fn local_node_id_to_def_id(fcx: fn_ctxt, i: node_id) -> Option<def_id> {
match local_node_id_to_def(fcx, i) {
- some(def_local(nid, _)) | some(def_arg(nid, _)) |
- some(def_binding(nid, _)) | some(def_upvar(nid, _, _)) {
- some(local_def(nid))
+ Some(def_local(nid, _)) | Some(def_arg(nid, _)) |
+ Some(def_binding(nid, _)) | Some(def_upvar(nid, _, _)) {
+ Some(local_def(nid))
}
_ { none }
}
}
fn local_node_id_to_local_def_id(fcx: fn_ctxt, i: node_id) ->
- option<node_id> {
+ Option<node_id> {
match local_node_id_to_def_id(fcx, i) {
- some(did) { some(did.node) }
+ Some(did) { Some(did.node) }
_ { none }
}
}
return respan(c.span, tconstr);
}
-type binding = {lhs: ~[dest], rhs: option<initializer>};
+type binding = {lhs: ~[dest], rhs: Option<initializer>};
fn local_to_bindings(tcx: ty::ctxt, loc: @local) -> binding {
let mut lhs = ~[];
let mut i = 0u;
for ops.each |op| {
vec::push(bindings,
- {lhs: ~[call], rhs: some({op: op, expr: es[i]})});
+ {lhs: ~[call], rhs: Some({op: op, expr: es[i]})});
i += 1u;
}
return bindings;
let {path: p, def_id: d_id, args: args} = c.node;
match tbl.find(d_id) {
- some(ct) {
+ Some(ct) {
(*ct.descs).push(respan(c.span, {args: args, bit_num: next}));
}
- none {
+ None {
let rslt = @dvec();
(*rslt).push(respan(c.span, {args: args, bit_num: next}));
tbl.insert(d_id, {path:p, descs:rslt});
// annotation for an if-expression with consequent conseq
// and alternative maybe_alt
fn join_then_else(fcx: fn_ctxt, antec: @expr, conseq: blk,
- maybe_alt: option<@expr>, id: node_id, chck: if_ty) {
+ maybe_alt: Option<@expr>, id: node_id, chck: if_ty) {
find_pre_post_expr(fcx, antec);
find_pre_post_block(fcx, conseq);
match maybe_alt {
set_pre_and_post(fcx.ccx, id, precond_res,
expr_poststate(fcx.ccx, antec));
}
- some(altern) {
+ Some(altern) {
/*
if check = if_check, then
be sure that the predicate implied by antec
fn gen_if_local(fcx: fn_ctxt, lhs: @expr, rhs: @expr, larger_id: node_id,
new_var: node_id) {
match node_id_to_def(fcx.ccx, new_var) {
- some(d) {
+ Some(d) {
match d {
def_local(nid, _) {
find_pre_post_expr(fcx, rhs);
let d = local_node_id_to_local_def_id(fcx, lhs.id);
let d1 = local_node_id_to_local_def_id(fcx, rhs.id);
match d {
- some(id) {
+ Some(id) {
match d1 {
- some(id1) {
+ Some(id1) {
let instlhs =
{ident: path_to_ident(p), node: id};
let instrhs =
}
expr_rec(fields, maybe_base) {
let mut es = field_exprs(fields);
- match maybe_base { none {/* no-op */ } some(b) { vec::push(es, b); } }
+ match maybe_base { none {/* no-op */ } Some(b) { vec::push(es, b); } }
find_pre_post_exprs(fcx, es, e.id);
}
expr_tup(elts) { find_pre_post_exprs(fcx, elts, e.id); }
clear_precond(fcx.ccx, e.id);
set_postcond_false(fcx.ccx, e.id);
}
- some(ret_val) {
+ Some(ret_val) {
find_pre_post_expr(fcx, ret_val);
set_precondition(node_id_to_ts_ann(fcx.ccx, e.id),
expr_precond(fcx.ccx, ret_val));
find_pre_post_expr(fcx, ex);
fn do_an_alt(fcx: fn_ctxt, an_alt: arm) -> pre_and_post {
match an_alt.guard {
- some(e) { find_pre_post_expr(fcx, e); }
+ Some(e) { find_pre_post_expr(fcx, e); }
_ {}
}
find_pre_post_block(fcx, an_alt.body);
let mut prestate;
match maybe_val {
none { prestate = empty_prestate(num_local_vars); }
- some(fail_val) {
+ Some(fail_val) {
find_pre_post_expr(fcx, fail_val);
prestate = expr_precond(fcx.ccx, fail_val);
}
let prev_pp = empty_pre_post(num_constraints(fcx.enclosing));
for alocals.each |alocal| {
match alocal.node.init {
- some(an_init) {
+ Some(an_init) {
/* LHS always becomes initialized,
whether or not this is a move */
find_pre_post_expr(fcx, an_init.expr);
let mut p = none;
match an_init.expr.node {
- expr_path(_p) { p = some(_p); }
+ expr_path(_p) { p = Some(_p); }
_ { }
}
|p_id, _s, n| {
let ident = path_to_ident(n);
match p {
- some(p) {
+ Some(p) {
copy_in_postcond(fcx, id,
{ident: ident, node: p_id},
{ident:
for b.node.stmts.each |s| { vec::push(pps, stmt_pp(fcx.ccx, *s)); }
match b.node.expr {
none {/* no-op */ }
- some(e) { vec::push(pps, expr_pp(fcx.ccx, e)); }
+ Some(e) { vec::push(pps, expr_pp(fcx.ccx, e)); }
}
let block_precond = seq_preconds(fcx, pps);
// Treat the tail expression as a return statement
match body.node.expr {
- some(tailexpr) { set_postcond_false(fcx.ccx, tailexpr.id); }
+ Some(tailexpr) { set_postcond_false(fcx.ccx, tailexpr.id); }
none {/* fallthrough */ }
}
}
match t {
oper_move {
match local_node_id_to_def(fcx, rhs_id) {
- some(def_upvar(_, _, _)) {
+ Some(def_upvar(_, _, _)) {
fcx.ccx.tcx.sess.span_err(sp,
~"tried to deinitialize a variable \
declared in a different scope");
let rhs_d_id = local_node_id_to_def_id(fcx, rhs_id);
match rhs_d_id {
- some(rhsid) {
+ Some(rhsid) {
// RHS is a local var
let instrhs =
{ident: path_to_ident(rhs_path), node: rhsid.node};
let mut post = pres.clone();
for bindings.each |b| {
match b.rhs {
- some(an_init) {
+ Some(an_init) {
// an expression, with or without a destination
changed |=
find_pre_post_state_expr(fcx, post, an_init.expr) || changed;
}
fn find_pre_post_state_sub(fcx: fn_ctxt, pres: prestate, e: @expr,
- parent: node_id, c: option<tsconstr>) -> bool {
+ parent: node_id, c: Option<tsconstr>) -> bool {
let mut changed = find_pre_post_state_expr(fcx, pres, e);
changed = set_prestate_ann(fcx.ccx, parent, pres) || changed;
let post = expr_poststate(fcx.ccx, e).clone();
match c {
none { }
- some(c1) { set_in_poststate_(bit_num(fcx, c1), post); }
+ Some(c1) { set_in_poststate_(bit_num(fcx, c1), post); }
}
changed = set_poststate_ann(fcx.ccx, parent, post) || changed;
let d = local_node_id_to_local_def_id(fcx, lhs.id);
let d1 = local_node_id_to_local_def_id(fcx, rhs.id);
match d {
- some(id) {
+ Some(id) {
match d1 {
- some(id1) {
+ Some(id1) {
let instlhs =
{ident: path_to_ident(p), node: id};
let instrhs =
}
fn join_then_else(fcx: fn_ctxt, antec: @expr, conseq: blk,
- maybe_alt: option<@expr>, id: node_id, chk: if_ty,
+ maybe_alt: Option<@expr>, id: node_id, chk: if_ty,
pres: prestate) -> bool {
let mut changed =
set_prestate_ann(fcx.ccx, id, pres) |
}
}
}
- some(altern) {
+ Some(altern) {
changed |=
find_pre_post_state_expr(fcx, expr_poststate(fcx.ccx, antec),
altern);
exs, return_val);
let base_pres = match vec::last_opt(exs) { none { pres }
- some(f) { expr_poststate(fcx.ccx, f) }};
+ Some(f) { expr_poststate(fcx.ccx, f) }};
option::iter(maybe_base, |base| {
changed |= find_pre_post_state_expr(fcx, base_pres, base) |
set_poststate_ann(fcx.ccx, e.id,
match maybe_ret_val {
none {/* do nothing */ }
- some(ret_val) {
+ Some(ret_val) {
changed |= find_pre_post_state_expr(fcx, pres, ret_val);
}
}
a_post = false_postcond(num_constrs);
for alts.each |an_alt| {
match an_alt.guard {
- some(e) {
+ Some(e) {
changed |= find_pre_post_state_expr(fcx, e_post, e);
}
_ {}
expr_unary(_, x) |
expr_addr_of(_, x) | expr_assert(x) | expr_cast(x, _) |
expr_copy(x) {
- return find_pre_post_state_sub(fcx, pres, x, e.id, none);
+ return find_pre_post_state_sub(fcx, pres, x, e.id, None);
}
expr_fail(maybe_fail_val) {
/* if execution continues after fail, then everything is true!
expr_check(_, p) {
/* predicate p holds after this expression executes */
let c: sp_constr = expr_to_constr(fcx.ccx.tcx, p);
- return find_pre_post_state_sub(fcx, pres, p, e.id, some(c.node));
+ return find_pre_post_state_sub(fcx, pres, p, e.id, Some(c.node));
}
expr_if_check(p, conseq, maybe_alt) {
return join_then_else(
let mut post = pres;
match b.node.expr {
none { }
- some(e) {
+ Some(e) {
changed |= find_pre_post_state_expr(fcx, pres, e);
post = expr_poststate(fcx.ccx, e);
}
import syntax::ast::*;
import syntax::print::pprust::*;
import util::ppaux::{ty_to_str, proto_ty_to_str, tys_to_str};
-import std::serialization::{serialize_option,
- deserialize_option};
+import std::serialization::{serialize_Option,
+ deserialize_Option};
export tv_vid, tvi_vid, region_vid, vid;
export br_hashmap;
// the types of AST nodes.
type creader_cache = hashmap<{cnum: int, pos: uint, len: uint}, t>;
-type intern_key = {struct: sty, o_def_id: option<ast::def_id>};
+type intern_key = {struct: sty, o_def_id: Option<ast::def_id>};
enum ast_ty_to_ty_cache_entry {
atttce_unresolved, /* not resolved yet */
}
#[auto_serialize]
-type opt_region_variance = option<region_variance>;
+type opt_region_variance = Option<region_variance>;
#[auto_serialize]
enum region_variance { rv_covariant, rv_invariant, rv_contravariant }
type t_box = @{struct: sty,
id: uint,
flags: uint,
- o_def_id: option<ast::def_id>};
+ o_def_id: Option<ast::def_id>};
// To reduce refcounting cost, we're representing types as unsafe pointers
// throughout the compiler. These are simply casted t_box values. Use ty::get
pure fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
pure fn type_needs_infer(t: t) -> bool { tbox_has_flag(get(t), needs_infer) }
pure fn type_has_regions(t: t) -> bool { tbox_has_flag(get(t), has_regions) }
-pure fn type_def_id(t: t) -> option<ast::def_id> { get(t).o_def_id }
+pure fn type_def_id(t: t) -> Option<ast::def_id> { get(t).o_def_id }
pure fn type_id(t: t) -> uint { get(t).id }
enum closure_kind {
br_cap_avoid(ast::node_id, @bound_region),
}
-type opt_region = option<region>;
+type opt_region = Option<region>;
/// The type substs represents the kinds of things that can be substituted to
/// convert a polytype into a monotype. Note however that substituting bound
/// `self_r` indicates the region parameter `self` that is present on nominal
/// types (enums, classes) declared as having a region parameter. `self_r`
/// should always be none for types that are not region-parameterized and
-/// some(_) for types that are. The only bound region parameter that should
+/// Some(_) for types that are. The only bound region parameter that should
/// appear within a region-parameterized type is `self`.
///
/// `self_ty` is the type to which `self` should be remapped, if any. The
/// is always substituted away to the implementing type for a trait.
type substs = {
self_r: opt_region,
- self_ty: option<ty::t>,
+ self_ty: Option<ty::t>,
tps: ~[t]
};
/// - `ty`: the base type. May have reference to the (unsubstituted) bound
/// region `&self` or to (unsubstituted) ty_param types
type ty_param_bounds_and_ty = {bounds: @~[param_bounds],
- region_param: option<region_variance>,
+ region_param: Option<region_variance>,
ty: t};
type type_cache = hashmap<ast::def_id, ty_param_bounds_and_ty>;
// Type constructors
-fn mk_t(cx: ctxt, +st: sty) -> t { mk_t_with_id(cx, st, none) }
+fn mk_t(cx: ctxt, +st: sty) -> t { mk_t_with_id(cx, st, None) }
// Interns a type/name combination, stores the resulting box in cx.interner,
// and returns the box as cast to an unsafe ptr (see comments for t above).
-fn mk_t_with_id(cx: ctxt, +st: sty, o_def_id: option<ast::def_id>) -> t {
+fn mk_t_with_id(cx: ctxt, +st: sty, o_def_id: Option<ast::def_id>) -> t {
let key = {struct: st, o_def_id: o_def_id};
match cx.interner.find(key) {
- some(t) => unsafe { return unsafe::reinterpret_cast(t); },
+ Some(t) => unsafe { return unsafe::reinterpret_cast(t); },
_ => ()
}
let mut flags = 0u;
fn mk_opaque_box(cx: ctxt) -> t { mk_t(cx, ty_opaque_box) }
fn mk_with_id(cx: ctxt, base: t, def_id: ast::def_id) -> t {
- mk_t_with_id(cx, get(base).struct, some(def_id))
+ mk_t_with_id(cx, get(base).struct, Some(def_id))
}
// Converts s to its machine type equivalent
// with id `id`.
fn encl_region(cx: ctxt, id: ast::node_id) -> ty::region {
match cx.region_map.find(id) {
- some(encl_scope) => ty::re_scope(encl_scope),
- none => ty::re_static
+ Some(encl_scope) => ty::re_scope(encl_scope),
+ None => ty::re_static
}
}
fn type_needs_drop(cx: ctxt, ty: t) -> bool {
match cx.needs_drop_cache.find(ty) {
- some(result) => return result,
- none => {/* fall through */ }
+ Some(result) => return result,
+ None => {/* fall through */ }
}
let mut accum = false;
// cleanups.
fn type_needs_unwind_cleanup(cx: ctxt, ty: t) -> bool {
match cx.needs_unwind_cleanup_cache.find(ty) {
- some(result) => return result,
- none => ()
+ Some(result) => return result,
+ None => ()
}
let tycache = new_ty_hash();
// Prevent infinite recursion
match tycache.find(ty) {
- some(_) => return false,
- none => { tycache.insert(ty, ()); }
+ Some(_) => return false,
+ None => { tycache.insert(ty, ()); }
}
let mut encountered_box = encountered_box;
fn type_kind(cx: ctxt, ty: t) -> kind {
match cx.kind_cache.find(ty) {
- some(result) => return result,
- none => {/* fall through */ }
+ Some(result) => return result,
+ None => {/* fall through */ }
}
// Insert a default in case we loop back on self recursively.
}
}
-fn type_param(ty: t) -> option<uint> {
+fn type_param(ty: t) -> Option<uint> {
match get(ty).struct {
- ty_param(p) => return some(p.idx),
+ ty_param(p) => return Some(p.idx),
_ => {/* fall through */ }
}
- return none;
+ return None;
}
// Returns the type and mutability of *t.
//
// The parameter `expl` indicates if this is an *explicit* dereference. Some
// types---notably unsafe ptrs---can only be dereferenced explicitly.
-fn deref(cx: ctxt, t: t, expl: bool) -> option<mt> {
+fn deref(cx: ctxt, t: t, expl: bool) -> Option<mt> {
deref_sty(cx, &get(t).struct, expl)
}
-fn deref_sty(cx: ctxt, sty: &sty, expl: bool) -> option<mt> {
+fn deref_sty(cx: ctxt, sty: &sty, expl: bool) -> Option<mt> {
match *sty {
ty_rptr(_, mt) | ty_box(mt) | ty_uniq(mt) => {
- some(mt)
+ Some(mt)
}
ty_ptr(mt) if expl => {
- some(mt)
+ Some(mt)
}
ty_enum(did, ref substs) => {
let variants = enum_variants(cx, did);
if vec::len(*variants) == 1u && vec::len(variants[0].args) == 1u {
let v_t = subst(cx, substs, variants[0].args[0]);
- some({ty: v_t, mutbl: ast::m_imm})
+ Some({ty: v_t, mutbl: ast::m_imm})
} else {
- none
+ None
}
}
- _ => none
+ _ => None
}
}
let mut t = t;
loop {
match deref(cx, t, false) {
- none => return t,
- some(mt) => t = mt.ty
+ None => return t,
+ Some(mt) => t = mt.ty
}
}
}
// Returns the type and mutability of t[i]
-fn index(cx: ctxt, t: t) -> option<mt> {
+fn index(cx: ctxt, t: t) -> Option<mt> {
index_sty(cx, &get(t).struct)
}
-fn index_sty(cx: ctxt, sty: &sty) -> option<mt> {
+fn index_sty(cx: ctxt, sty: &sty) -> Option<mt> {
match *sty {
- ty_evec(mt, _) => some(mt),
- ty_estr(_) => some({ty: mk_u8(cx), mutbl: ast::m_imm}),
- _ => none
+ ty_evec(mt, _) => Some(mt),
+ ty_estr(_) => Some({ty: mk_u8(cx), mutbl: ast::m_imm}),
+ _ => None
}
}
fn node_id_to_type(cx: ctxt, id: ast::node_id) -> t {
//io::println(fmt!("%?/%?", id, cx.node_types.size()));
match smallintmap::find(*cx.node_types, id as uint) {
- some(t) => t,
- none => cx.sess.bug(
+ Some(t) => t,
+ None => cx.sess.bug(
fmt!("node_id_to_type: unbound node ID %s",
ast_map::node_id_to_str(cx.items, id,
cx.sess.parse_sess.interner)))
fn node_id_to_type_params(cx: ctxt, id: ast::node_id) -> ~[t] {
match cx.node_type_substs.find(id) {
- none => return ~[],
- some(ts) => return ts
+ None => return ~[],
+ Some(ts) => return ts
}
}
fn method_call_bounds(tcx: ctxt, method_map: typeck::method_map,
id: ast::node_id)
- -> option<@~[param_bounds]> {
+ -> Option<@~[param_bounds]> {
do method_map.find(id).map |method| {
match method.origin {
typeck::method_static(did) => {
}
}
-fn field_idx(id: ast::ident, fields: ~[field]) -> option<uint> {
+fn field_idx(id: ast::ident, fields: ~[field]) -> Option<uint> {
let mut i = 0u;
- for fields.each |f| { if f.ident == id { return some(i); } i += 1u; }
- return none;
+ for fields.each |f| { if f.ident == id { return Some(i); } i += 1u; }
+ return None;
}
fn get_field(tcx: ctxt, rec_ty: t, id: ast::ident) -> field {
match vec::find(get_fields(rec_ty), |f| f.ident == id) {
- some(f) => f,
+ Some(f) => f,
// Do we only call this when we know the field is legit?
- none => fail (#fmt("get_field: ty doesn't have a field %s",
+ None => fail (#fmt("get_field: ty doesn't have a field %s",
tcx.sess.str_of(id)))
}
}
}
}
-fn method_idx(id: ast::ident, meths: &[method]) -> option<uint> {
+fn method_idx(id: ast::ident, meths: &[method]) -> Option<uint> {
let mut i = 0u;
- for meths.each |m| { if m.ident == id { return some(i); } i += 1u; }
- return none;
+ for meths.each |m| { if m.ident == id { return Some(i); } i += 1u; }
+ return None;
}
/// Returns a vector containing the indices of all type parameters that appear
+m0: ast::inferable<T>) -> ast::inferable<T> {
match m0 {
ast::infer(id) => match tbl.find(id) {
- none => m0,
- some(m1) => {
+ None => m0,
+ Some(m1) => {
let cm1 = canon(tbl, m1);
// path compression:
if cm1 != m1 { tbl.insert(id, cm1); }
fn trait_methods(cx: ctxt, id: ast::def_id) -> @~[method] {
match cx.trait_method_cache.find(id) {
// Local traits are supposed to have been added explicitly.
- some(ms) => ms,
+ Some(ms) => ms,
_ => {
// If the lookup in trait_method_cache fails, assume that the trait
// method we're trying to look up is in a different crate, and look
if id.crate == ast::local_crate {
debug!("(impl_traits) searching for trait impl %?", id);
match cx.items.find(id.node) {
- some(ast_map::node_item(@{
+ Some(ast_map::node_item(@{
node: ast::item_impl(_, trait_refs, _, _),
_},
_)) => {
node_id_to_type(cx, trait_ref.ref_id)
}
}
- some(ast_map::node_item(@{node: ast::item_class(*),
+ Some(ast_map::node_item(@{node: ast::item_class(*),
_},_)) => {
match cx.def_map.find(id.node) {
- some(def_ty(trait_id)) => {
+ Some(def_ty(trait_id)) => {
// XXX: Doesn't work cross-crate.
debug!("(impl_traits) found trait id %?", trait_id);
~[node_id_to_type(cx, trait_id.node)]
}
- some(x) => {
+ Some(x) => {
cx.sess.bug(fmt!("impl_traits: trait ref is in trait map \
but is bound to %?", x));
}
- none => {
+ None => {
~[]
}
}
}
}
-fn ty_to_def_id(ty: t) -> option<ast::def_id> {
+fn ty_to_def_id(ty: t) -> Option<ast::def_id> {
match get(ty).struct {
- ty_trait(id, _, _) | ty_class(id, _) | ty_enum(id, _) => some(id),
- _ => none
+ ty_trait(id, _, _) | ty_class(id, _) | ty_enum(id, _) => Some(id),
+ _ => None
}
}
ast_map::path_to_str(item_path(cx, id), cx.sess.parse_sess.interner)
}
-/* If class_id names a class with a dtor, return some(the dtor's id).
+/* If class_id names a class with a dtor, return Some(the dtor's id).
Otherwise return none. */
-fn ty_dtor(cx: ctxt, class_id: def_id) -> option<def_id> {
+fn ty_dtor(cx: ctxt, class_id: def_id) -> Option<def_id> {
if is_local(class_id) {
match cx.items.find(class_id.node) {
- some(ast_map::node_item(@{
- node: ast::item_class(@{ dtor: some(dtor), _ }, _),
+ Some(ast_map::node_item(@{
+ node: ast::item_class(@{ dtor: Some(dtor), _ }, _),
_
}, _)) =>
- some(local_def(dtor.node.id)),
+ Some(local_def(dtor.node.id)),
_ =>
- none
+ None
}
}
else {
fn enum_variants(cx: ctxt, id: ast::def_id) -> @~[variant_info] {
match cx.enum_var_cache.find(id) {
- some(variants) => return variants,
+ Some(variants) => return variants,
_ => { /* fallthrough */ }
}
}
};
match variant.node.disr_expr {
- some (ex) => {
+ Some (ex) => {
// FIXME: issue #1417
disr_val = match const_eval::eval_const_expr(cx,
ex) {
// the type cache. Returns the type parameters and type.
fn lookup_item_type(cx: ctxt, did: ast::def_id) -> ty_param_bounds_and_ty {
match cx.tcache.find(did) {
- some(tpt) => return tpt,
- none => {
+ Some(tpt) => return tpt,
+ None => {
// The item is in this crate. The caller should have added it to the
// type cache already
assert did.crate != ast::local_crate;
}
else {
match tcx.tcache.find(id) {
- some(tpt) => tpt.ty,
- none => {
+ Some(tpt) => tpt.ty,
+ None => {
let tpt = csearch::get_field_type(tcx, class_id, id);
tcx.tcache.insert(id, tpt);
tpt.ty
fn lookup_class_fields(cx: ctxt, did: ast::def_id) -> ~[field_ty] {
if did.crate == ast::local_crate {
match cx.items.find(did.node) {
- some(ast_map::node_item(i,_)) => {
+ Some(ast_map::node_item(i,_)) => {
match i.node {
ast::item_class(struct_def, _) => {
class_field_tys(struct_def.fields)
-> field_ty {
match vec::find(lookup_class_fields(cx, parent),
|f| f.id.node == field_id.node) {
- some(t) => t,
- none => cx.sess.bug(~"class ID not found in parent's fields")
+ Some(t) => t,
+ None => cx.sess.bug(~"class ID not found in parent's fields")
}
}
assert is_local(did);
match cx.items.find(did.node) {
- some(ast_map::node_item(@{
+ Some(ast_map::node_item(@{
node: item_class(struct_def, _), _
}, _)) => {
vec::map(struct_def.methods, |m| {name: m.ident,
}
match cx.normalized_cache.find(t) {
- some(t) => return t,
- none => ()
+ Some(t) => return t,
+ None => ()
}
let t = match get(t).struct {
ty_enum(did, r) =>
match r.self_r {
- some(_) =>
+ Some(_) =>
// This enum has a self region. Get rid of it
mk_enum(cx, did,
- {self_r: none, self_ty: none, tps: r.tps}),
- none =>
+ {self_r: None, self_ty: None, tps: r.tps}),
+ None =>
t
},
ty_class(did, r) =>
match r.self_r {
- some(_) =>
+ Some(_) =>
// Ditto.
- mk_class(cx, did, {self_r: none, self_ty: none, tps: r.tps}),
- none =>
+ mk_class(cx, did, {self_r: None, self_ty: None, tps: r.tps}),
+ None =>
t
},
fn lookup_def_tcx(tcx: ty::ctxt, sp: span, id: ast::node_id) -> ast::def {
match tcx.def_map.find(id) {
- some(x) => x,
+ Some(x) => x,
_ => {
tcx.sess.span_fatal(sp, ~"internal error looking up a definition")
}
}
fn no_params(t: ty::t) -> ty::ty_param_bounds_and_ty {
- {bounds: @~[], region_param: none, ty: t}
+ {bounds: @~[], region_param: None, ty: t}
}
fn require_same_types(
tcx: ty::ctxt,
- maybe_infcx: option<infer::infer_ctxt>,
+ maybe_infcx: Option<infer::infer_ctxt>,
t1_is_expected: bool,
span: span,
t1: ty::t,
let l_tcx, l_infcx;
match maybe_infcx {
- none => {
+ None => {
l_tcx = tcx;
l_infcx = infer::new_infer_ctxt(tcx);
}
- some(i) => {
+ Some(i) => {
l_tcx = i.tcx;
l_infcx = i;
}
ty::ty_fn({purity: ast::impure_fn, proto: ty::proto_bare, bounds,
inputs, output, ret_style: ast::return_val}) => {
match tcx.items.find(main_id) {
- some(ast_map::node_item(it,_)) => {
+ Some(ast_map::node_item(it,_)) => {
match it.node {
ast::item_fn(_,_,ps,_) if vec::is_not_empty(ps) => {
tcx.sess.span_err(main_span,
let tcx = ccx.tcx;
if !tcx.sess.building_library {
match copy tcx.sess.main_fn {
- some((id, sp)) => check_main_fn_ty(ccx, id, sp),
- none => tcx.sess.err(~"main function not found")
+ Some((id, sp)) => check_main_fn_ty(ccx, id, sp),
+ None => tcx.sess.err(~"main function not found")
}
}
}
// region with the current anon region binding (in other words,
// whatever & would get replaced with).
let self_r = match (decl_rp, path.rp) {
- (none, none) => {
- none
+ (None, None) => {
+ None
}
- (none, some(_)) => {
+ (None, Some(_)) => {
tcx.sess.span_err(
path.span,
fmt!("no region bound is allowed on `%s`, \
which is not declared as containing region pointers",
ty::item_path_str(tcx, did)));
- none
+ None
}
- (some(_), none) => {
+ (Some(_), None) => {
let res = rscope.anon_region(path.span);
let r = get_region_reporting_err(self.tcx(), path.span, res);
- some(r)
+ Some(r)
}
- (some(_), some(r)) => {
- some(ast_region_to_region(self, rscope, path.span, r))
+ (Some(_), Some(r)) => {
+ Some(ast_region_to_region(self, rscope, path.span, r))
}
};
}
let tps = path.types.map(|a_t| ast_ty_to_ty(self, rscope, a_t));
- let substs = {self_r:self_r, self_ty:none, tps:tps};
+ let substs = {self_r:self_r, self_ty:None, tps:tps};
{substs: substs, ty: ty::subst(tcx, &substs, decl_ty)}
}
}
ast::ty_path(path, id) => {
match tcx.def_map.find(id) {
- some(ast::def_prim_ty(ast::ty_str)) => {
+ Some(ast::def_prim_ty(ast::ty_str)) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
return ty::mk_estr(tcx, vst);
}
- some(ast::def_ty(type_def_id)) => {
+ Some(ast::def_ty(type_def_id)) => {
let result = ast_path_to_substs_and_ty(self, rscope,
type_def_id, path);
match ty::get(result.ty).struct {
let bounds = collect::compute_bounds(self.ccx(), ast_bounds);
let fn_decl = ty_of_fn_decl(self, rscope, new_proto, purity,
bounds,
- ast_fn_decl, none, span);
+ ast_fn_decl, None, span);
return ty::mk_fn(tcx, fn_decl);
}
_ => ()
let tcx = self.tcx();
match tcx.ast_ty_to_ty_cache.find(ast_ty) {
- some(ty::atttce_resolved(ty)) => return ty,
- some(ty::atttce_unresolved) => {
+ Some(ty::atttce_resolved(ty)) => return ty,
+ Some(ty::atttce_unresolved) => {
tcx.sess.span_fatal(ast_ty.span, ~"illegal recursive type; \
insert an enum in the cycle, \
if this is desired");
}
- none => { /* go on */ }
+ None => { /* go on */ }
}
tcx.ast_ty_to_ty_cache.insert(ast_ty, ty::atttce_unresolved);
ast::ty_fn(proto, purity, ast_bounds, decl) => {
let bounds = collect::compute_bounds(self.ccx(), ast_bounds);
let fn_decl = ty_of_fn_decl(self, rscope, proto, purity,
- bounds, decl, none,
+ bounds, decl, None,
ast_ty.span);
ty::mk_fn(tcx, fn_decl)
}
ast::ty_path(path, id) => {
let a_def = match tcx.def_map.find(id) {
- none => tcx.sess.span_fatal(
+ None => tcx.sess.span_fatal(
ast_ty.span, fmt!("unbound path %s",
path_to_str(path, tcx.sess.intr()))),
- some(d) => d
+ Some(d) => d
};
match a_def {
ast::def_ty(did) | ast::def_class(did, _) => {
}
}
}
- ast::ty_fixed_length(a_t, some(u)) => {
+ ast::ty_fixed_length(a_t, Some(u)) => {
mk_maybe_vstore(self, rscope, {ty: a_t, mutbl: ast::m_imm},
ty::vstore_fixed(u),
ast_ty.span,
ty.ty
})
}
- ast::ty_fixed_length(_, none) => {
+ ast::ty_fixed_length(_, None) => {
tcx.sess.span_bug(
ast_ty.span,
~"implied fixed length for bound");
fn ty_of_arg<AC: ast_conv, RS: region_scope copy owned>(
self: AC, rscope: RS, a: ast::arg,
- expected_ty: option<ty::arg>) -> ty::arg {
+ expected_ty: Option<ty::arg>) -> ty::arg {
let ty = match a.ty.node {
ast::ty_infer if expected_ty.is_some() => expected_ty.get().ty,
}
}
-type expected_tys = option<{inputs: ~[ty::arg],
+type expected_tys = Option<{inputs: ~[ty::arg],
output: ty::t}>;
fn ty_of_fn_decl<AC: ast_conv, RS: region_scope copy owned>(
let expected_arg_ty = do expected_tys.chain |e| {
// no guarantee that the correct number of expected args
// were supplied
- if i < e.inputs.len() {some(e.inputs[i])} else {none}
+ if i < e.inputs.len() {Some(e.inputs[i])} else {None}
};
ty_of_arg(self, rb, a, expected_arg_ty)
};
// var_bindings, locals and next_var_id are shared
// with any nested functions that capture the environment
// (and with any functions whose environment is being captured).
- self_impl_def_id: option<ast::def_id>;
+ self_impl_def_id: Option<ast::def_id>;
ret_ty: ty::t;
// Used by loop bodies that return from the outer function
- indirect_ret_ty: option<ty::t>;
+ indirect_ret_ty: Option<ty::t>;
purity: ast::purity;
infcx: infer::infer_ctxt;
locals: hashmap<ast::node_id, tv_vid>;
// It's kind of a kludge to manufacture a fake function context
// and statement context, but we might as well do write the code only once
@fn_ctxt {
- self_impl_def_id: none,
+ self_impl_def_id: None,
ret_ty: rty,
- indirect_ret_ty: none,
+ indirect_ret_ty: None,
purity: ast::pure_fn,
infcx: infer::new_infer_ctxt(ccx.tcx),
locals: int_hash(),
trait get_and_find_region {
fn get(br: ty::bound_region) -> ty::region;
- fn find(br: ty::bound_region) -> option<ty::region>;
+ fn find(br: ty::bound_region) -> Option<ty::region>;
}
impl isr_alist: get_and_find_region {
option::get(self.find(br))
}
- fn find(br: ty::bound_region) -> option<ty::region> {
+ fn find(br: ty::bound_region) -> Option<ty::region> {
for list::each(self) |isr| {
let (isr_br, isr_r) = isr;
- if isr_br == br { return some(isr_r); }
+ if isr_br == br { return Some(isr_r); }
}
- return none;
+ return None;
}
}
decl: ast::fn_decl,
body: ast::blk,
id: ast::node_id,
- self_info: option<self_info>) {
+ self_info: Option<self_info>) {
let fty = ty::node_id_to_type(ccx.tcx, id);
match ty::get(fty).struct {
ty::ty_fn(ref fn_ty) => {
- check_fn(ccx, self_info, fn_ty, decl, body, false, none)
+ check_fn(ccx, self_info, fn_ty, decl, body, false, None)
}
_ => ccx.tcx.sess.impossible_case(body.span,
"check_bare_fn: function type expected")
}
fn check_fn(ccx: @crate_ctxt,
- self_info: option<self_info>,
+ self_info: Option<self_info>,
fn_ty: &ty::fn_ty,
decl: ast::fn_decl,
body: ast::blk,
indirect_ret: bool,
- old_fcx: option<@fn_ctxt>) {
+ old_fcx: Option<@fn_ctxt>) {
let tcx = ccx.tcx;
let fcx: @fn_ctxt = {
let {infcx, locals, purity, node_types, node_type_substs} =
match old_fcx {
- none => {
+ None => {
{infcx: infer::new_infer_ctxt(tcx),
locals: int_hash(),
purity: fn_ty.purity,
node_types: map::int_hash(),
node_type_substs: map::int_hash()}
}
- some(fcx) => {
+ Some(fcx) => {
{infcx: fcx.infcx,
locals: fcx.locals,
purity: ty::determine_inherited_purity(fcx.purity, fn_ty.purity,
let indirect_ret_ty = if indirect_ret {
let ofcx = option::get(old_fcx);
match ofcx.indirect_ret_ty {
- some(t) => some(t),
- none => some(ofcx.ret_ty)
+ Some(t) => Some(t),
+ None => Some(ofcx.ret_ty)
}
- } else { none };
+ } else { None };
@fn_ctxt {
self_impl_def_id: self_info.map(|info| info.def_id),
let self_info = do self_info.chain |info| {
// If the self type is sty_static, we don't have a self ty.
if info.explicit_self.node == ast::sty_static {
- none
+ None
} else {
let self_region = fcx.in_scope_regions.find(ty::br_self);
let ty = method::transform_self_type_for_method(
fcx.tcx(), self_region,
info.self_ty, info.explicit_self.node);
- some({self_ty: ty with info})
+ Some({self_ty: ty with info})
}
};
// We unify the tail expr's type with the
// function result type, if there is a tail expr.
match body.node.expr {
- some(tail_expr) => {
+ Some(tail_expr) => {
let tail_expr_ty = fcx.expr_ty(tail_expr);
demand::suptype(fcx, tail_expr.span, fcx.ret_ty, tail_expr_ty);
}
- none => ()
+ None => ()
}
for self_info.each |info| {
decl: ast::fn_decl,
body: ast::blk,
arg_tys: ~[ty::t],
- self_info: option<self_info>) {
+ self_info: Option<self_info>) {
let tcx = fcx.ccx.tcx;
let assign = fn@(span: span, nid: ast::node_id,
- ty_opt: option<ty::t>) {
+ ty_opt: Option<ty::t>) {
let var_id = fcx.infcx.next_ty_var_id();
fcx.locals.insert(nid, var_id);
match ty_opt {
- none => {/* nothing to do */ }
- some(typ) => {
+ None => {/* nothing to do */ }
+ Some(typ) => {
infer::mk_eqty(fcx.infcx, false, span,
ty::mk_var(tcx, var_id), typ);
}
// Add the self parameter
for self_info.each |info| {
assign(info.explicit_self.span,
- info.self_id, some(info.self_ty));
+ info.self_id, Some(info.self_ty));
debug!("self is assigned to %s",
fcx.locals.get(info.self_id).to_str());
}
// Add formal parameters.
do vec::iter2(arg_tys, decl.inputs) |arg_ty, input| {
- assign(input.ty.span, input.id, some(arg_ty));
+ assign(input.ty.span, input.id, Some(arg_ty));
debug!("Argument %s is assigned to %s",
tcx.sess.str_of(input.ident),
fcx.locals.get(input.id).to_str());
let visit_local = fn@(local: @ast::local,
&&e: (), v: visit::vt<()>) {
let o_ty = match local.node.ty.node {
- ast::ty_infer => none,
- _ => some(fcx.to_ty(local.node.ty))
+ ast::ty_infer => None,
+ _ => Some(fcx.to_ty(local.node.ty))
};
assign(local.span, local.node.id, o_ty);
debug!("Local variable %s is assigned to %s",
match p.node {
ast::pat_ident(_, path, _)
if !pat_util::pat_is_variant(fcx.ccx.tcx.def_map, p) => {
- assign(p.span, p.id, none);
+ assign(p.span, p.id, None);
debug!("Pattern binding %s is assigned to %s",
tcx.sess.str_of(path.idents[0]),
fcx.locals.get(p.id).to_str());
self_id: method.self_id,
def_id: self_impl_def_id,
explicit_self: method.self_ty };
- check_bare_fn(ccx, method.decl, method.body, method.id, some(self_info));
+ check_bare_fn(ccx, method.decl, method.body, method.id, Some(self_info));
}
fn check_no_duplicate_fields(tcx: ty::ctxt, fields:
for fields.each |p| {
let (id, sp) = p;
match field_names.find(id) {
- some(orig_sp) => {
+ Some(orig_sp) => {
tcx.sess.span_err(sp, fmt!("Duplicate field \
name %s in record type declaration",
tcx.sess.str_of(id)));
this field occurred here");
break;
}
- none => {
+ None => {
field_names.insert(id, sp);
}
}
// typecheck the ctor
check_bare_fn(ccx, ctor.node.dec,
ctor.node.body, ctor.node.id,
- some(class_t));
+ Some(class_t));
}
do option::iter(struct_def.dtor) |dtor| {
// typecheck the dtor
check_bare_fn(ccx, ast_util::dtor_dec(),
dtor.node.body, dtor.node.id,
- some(class_t));
+ Some(class_t));
};
// typecheck the methods
check_enum_variants(ccx, it.span, enum_definition.variants, it.id);
}
ast::item_fn(decl, _, tps, body) => {
- check_bare_fn(ccx, decl, body, it.id, none);
+ check_bare_fn(ccx, decl, body, it.id, None);
}
ast::item_impl(tps, _, ty, ms) => {
let rp = ccx.tcx.region_paramd_items.find(it.id);
fn named_region(span: span, id: ast::ident) -> result<ty::region, ~str> {
do empty_rscope.named_region(span, id).chain_err |_e| {
match self.in_scope_regions.find(ty::br_named(id)) {
- some(r) => result::ok(r),
- none if id == syntax::parse::token::special_idents::blk
+ Some(r) => result::ok(r),
+ None if id == syntax::parse::token::special_idents::blk
=> result::ok(self.block_region()),
- none => {
+ None => {
result::err(fmt!("named region `%s` not in scope here",
self.ccx.tcx.sess.str_of(id)))
}
fn expr_ty(ex: @ast::expr) -> ty::t {
match self.node_types.find(ex.id) {
- some(t) => t,
- none => {
+ Some(t) => t,
+ None => {
self.tcx().sess.bug(
fmt!("no type for expr %d (%s) in fcx %s",
ex.id, expr_to_str(ex, self.ccx.tcx.sess.intr()),
}
fn node_ty(id: ast::node_id) -> ty::t {
match self.node_types.find(id) {
- some(t) => t,
- none => {
+ Some(t) => t,
+ None => {
self.tcx().sess.bug(
fmt!("no type for node %d: %s in fcx %s",
id, ast_map::node_id_to_str(
}
fn node_ty_substs(id: ast::node_id) -> ty::substs {
match self.node_type_substs.find(id) {
- some(ts) => ts,
- none => {
+ Some(ts) => ts,
+ None => {
self.tcx().sess.bug(
fmt!("no type substs for node %d: %s in fcx %s",
id, ast_map::node_id_to_str(
}
}
}
- fn opt_node_ty_substs(id: ast::node_id) -> option<ty::substs> {
+ fn opt_node_ty_substs(id: ast::node_id) -> Option<ty::substs> {
self.node_type_substs.find(id)
}
return v;
}
- fn region_var_if_parameterized(rp: option<ty::region_variance>,
+ fn region_var_if_parameterized(rp: Option<ty::region_variance>,
span: span,
lower_bound: ty::region)
- -> option<ty::region>
+ -> Option<ty::region>
{
rp.map(
|_rp| self.infcx.next_region_var_with_lb(span,
// Otherwise, deref if type is derefable:
match ty::deref_sty(fcx.ccx.tcx, &sty, false) {
- none => return t1,
- some(mt) => t1 = mt.ty
+ None => return t1,
+ Some(mt) => t1 = mt.ty
}
};
}
}
fn check_expr_with(fcx: @fn_ctxt, expr: @ast::expr, expected: ty::t) -> bool {
- check_expr(fcx, expr, some(expected))
+ check_expr(fcx, expr, Some(expected))
}
fn check_expr(fcx: @fn_ctxt, expr: @ast::expr,
- expected: option<ty::t>) -> bool {
+ expected: Option<ty::t>) -> bool {
return do check_expr_with_unifier(fcx, expr, expected) {
for expected.each |t| {
demand::suptype(fcx, expr.span, t, fcx.expr_ty(expr));
let {n_tps, region_param, raw_ty} = if did.crate == ast::local_crate {
let region_param = fcx.tcx().region_paramd_items.find(did.node);
match tcx.items.find(did.node) {
- some(ast_map::node_item(@{node: ast::item_impl(ts, _, st, _),
+ Some(ast_map::node_item(@{node: ast::item_impl(ts, _, st, _),
_}, _)) => {
{n_tps: ts.len(),
region_param: region_param,
raw_ty: fcx.ccx.to_ty(rscope::type_rscope(region_param), st)}
}
- some(ast_map::node_item(@{node: ast::item_class(_, ts),
+ Some(ast_map::node_item(@{node: ast::item_class(_, ts),
id: class_id, _},_)) => {
/* If the impl is a class, the self ty is just the class ty
(doing a no-op subst for the ty params; in the next step,
region_param: region_param,
raw_ty: ty::mk_class(tcx, local_def(class_id),
{self_r: rscope::bound_self_region(region_param),
- self_ty: none,
+ self_ty: None,
tps: ty::ty_params_to_tys(tcx, ts)})}
}
_ => { tcx.sess.bug(~"impl_self_ty: unbound item or item that \
};
let self_r = if region_param.is_some() || require_rp {
- some(fcx.infcx.next_region_var(expr.span, expr.id))
+ Some(fcx.infcx.next_region_var(expr.span, expr.id))
} else {
- none
+ None
};
let tps = fcx.infcx.next_ty_vars(n_tps);
- let substs = {self_r: self_r, self_ty: none, tps: tps};
+ let substs = {self_r: self_r, self_ty: None, tps: tps};
let substd_ty = ty::subst(tcx, &substs, raw_ty);
{substs: substs, ty: substd_ty}
}
class_id: ast::def_id,
items: &[ty::field_ty],
fieldname: ast::ident,
- substs: &ty::substs) -> option<ty::t> {
+ substs: &ty::substs) -> Option<ty::t> {
let o_field = vec::find(items, |f| f.ident == fieldname);
do option::map(o_field) |f| {
fn check_expr_with_unifier(fcx: @fn_ctxt,
expr: @ast::expr,
- expected: option<ty::t>,
+ expected: Option<ty::t>,
unifier: fn()) -> bool {
debug!(
match structure_of(fcx, sp, in_fty) {
sty @ ty::ty_fn(ref fn_ty) => {
replace_bound_regions_in_fn_ty(
- fcx.ccx.tcx, @nil, none, fn_ty,
+ fcx.ccx.tcx, @nil, None, fn_ty,
|_br| fcx.infcx.next_region_var(sp,
call_expr_id)).fn_ty
}
if is_block == check_blocks {
let arg_ty = arg_tys[i];
bot |= check_expr_with_unifier(
- fcx, a, some(arg_ty),
+ fcx, a, Some(arg_ty),
|| demand::assign(fcx, a.span, call_expr_id,
arg_ty, a)
);
// A generic function for checking assignment expressions
fn check_assignment(fcx: @fn_ctxt, _sp: span, lhs: @ast::expr,
rhs: @ast::expr, id: ast::node_id) -> bool {
- let mut bot = check_expr(fcx, lhs, none);
+ let mut bot = check_expr(fcx, lhs, None);
bot |= check_expr_with(fcx, rhs, fcx.expr_ty(lhs));
fcx.write_ty(id, ty::mk_nil(fcx.ccx.tcx));
return bot;
ast::expr_field(base, field, tys) => {
check_field(fcx, f, true, base, field, tys)
}
- _ => check_expr(fcx, f, none)
+ _ => check_expr(fcx, f, None)
};
let fn_ty = fcx.expr_ty(f);
// A generic function for checking the then and else in an if
// or if-check
fn check_then_else(fcx: @fn_ctxt, thn: ast::blk,
- elsopt: option<@ast::expr>, id: ast::node_id,
+ elsopt: Option<@ast::expr>, id: ast::node_id,
_sp: span) -> bool {
let (if_t, if_bot) =
match elsopt {
- some(els) => {
+ Some(els) => {
let if_t = fcx.infcx.next_ty_var();
let thn_bot = check_block(fcx, thn);
let thn_t = fcx.node_ty(thn.node.id);
let els_bot = check_expr_with(fcx, els, if_t);
(if_t, thn_bot & els_bot)
}
- none => {
+ None => {
check_block_no_value(fcx, thn);
(ty::mk_nil(fcx.ccx.tcx), false)
}
fn lookup_op_method(fcx: @fn_ctxt, op_ex: @ast::expr,
self_ex: @ast::expr, self_t: ty::t,
opname: ast::ident, args: ~[@ast::expr])
- -> option<(ty::t, bool)> {
+ -> Option<(ty::t, bool)> {
let lkup = method::lookup(fcx, op_ex, self_ex, op_ex.id,
op_ex.callee_id, opname, self_t, ~[], false);
match lkup.method() {
- some(origin) => {
+ Some(origin) => {
let {fty: method_ty, bot: bot} = {
let method_ty = fcx.node_ty(op_ex.callee_id);
check_call_inner(fcx, op_ex.span, op_ex.id,
method_ty, op_ex, args)
};
fcx.ccx.method_map.insert(op_ex.id, origin);
- some((ty::ty_fn_ret(method_ty), bot))
+ Some((ty::ty_fn_ret(method_ty), bot))
}
- _ => none
+ _ => None
}
}
// could be either a expr_binop or an expr_assign_binop
lhs: @ast::expr,
rhs: @ast::expr) -> bool {
let tcx = fcx.ccx.tcx;
- let lhs_bot = check_expr(fcx, lhs, none);
+ let lhs_bot = check_expr(fcx, lhs, None);
let lhs_t = fcx.expr_ty(lhs);
let lhs_t = structurally_resolved_type(fcx, lhs.span, lhs_t);
return match (op, ty::get(lhs_t).struct) {
(_, _) if ty::type_is_integral(lhs_t) &&
ast_util::is_shift_binop(op) => {
// Shift is a special case: rhs can be any integral type
- let rhs_bot = check_expr(fcx, rhs, none);
+ let rhs_bot = check_expr(fcx, rhs, None);
let rhs_t = fcx.expr_ty(rhs);
require_integral(fcx, rhs.span, rhs_t);
fcx.write_ty(expr.id, lhs_t);
op: ast::binop, rhs: @ast::expr) -> (ty::t, bool) {
let tcx = fcx.ccx.tcx;
match ast_util::binop_to_method_name(op) {
- some(name) => {
+ Some(name) => {
match lookup_op_method(fcx, ex, lhs_expr, lhs_resolved_t,
fcx.tcx().sess.ident_of(name), ~[rhs]) {
- some(pair) => return pair,
+ Some(pair) => return pair,
_ => ()
}
}
_ => ()
}
- check_expr(fcx, rhs, none);
+ check_expr(fcx, rhs, None);
tcx.sess.span_err(
ex.span, ~"binary operation " + ast_util::binop_to_str(op) +
rhs_expr: @ast::expr, rhs_t: ty::t) -> ty::t {
match lookup_op_method(fcx, ex, rhs_expr, rhs_t,
fcx.tcx().sess.ident_of(mname), ~[]) {
- some((ret_ty, _)) => ret_ty,
+ Some((ret_ty, _)) => ret_ty,
_ => {
fcx.ccx.tcx.sess.span_err(
ex.span, fmt!("cannot apply unary operator `%s` to type `%s`",
// through the `unpack` function. It there is no expected type or
// resolution is not possible (e.g., no constraints yet present), just
// returns `none`.
- fn unpack_expected<O: copy>(fcx: @fn_ctxt, expected: option<ty::t>,
- unpack: fn(ty::sty) -> option<O>)
- -> option<O> {
+ fn unpack_expected<O: copy>(fcx: @fn_ctxt, expected: Option<ty::t>,
+ unpack: fn(ty::sty) -> Option<O>)
+ -> Option<O> {
match expected {
- some(t) => {
+ Some(t) => {
match resolve_type(fcx.infcx, t, force_tvar) {
result::ok(t) => unpack(ty::get(t).struct),
- _ => none
+ _ => None
}
}
- _ => none
+ _ => None
}
}
fn check_expr_fn(fcx: @fn_ctxt,
expr: @ast::expr,
- ast_proto_opt: option<ast::proto>,
+ ast_proto_opt: Option<ast::proto>,
decl: ast::fn_decl,
body: ast::blk,
is_loop_body: bool,
- expected: option<ty::t>) {
+ expected: Option<ty::t>) {
let tcx = fcx.ccx.tcx;
// Find the expected input/output types (if any). Careful to
// to impure and block. Note that we only will use those for
// block syntax lambdas; that is, lambdas without explicit
// protos.
- let expected_sty = unpack_expected(fcx, expected, |x| some(x));
+ let expected_sty = unpack_expected(fcx, expected, |x| Some(x));
let (expected_tys, expected_purity, expected_proto) =
match expected_sty {
- some(ty::ty_fn(ref fn_ty)) => {
+ Some(ty::ty_fn(ref fn_ty)) => {
let {fn_ty, _} =
replace_bound_regions_in_fn_ty(
- tcx, @nil, none, fn_ty,
+ tcx, @nil, None, fn_ty,
|br| ty::re_bound(ty::br_cap_avoid(expr.id, @br)));
- (some({inputs:fn_ty.inputs,
+ (Some({inputs:fn_ty.inputs,
output:fn_ty.output}),
fn_ty.purity,
fn_ty.proto)
}
_ => {
- (none, ast::impure_fn, ty::proto_vstore(ty::vstore_box))
+ (None, ast::impure_fn, ty::proto_vstore(ty::vstore_box))
}
};
// Patch up the function declaration, if necessary.
match ast_proto_opt {
- none => {
+ None => {
fn_ty.purity = expected_purity;
fn_ty.proto = expected_proto;
}
- some(_) => { }
+ Some(_) => { }
}
let fty = ty::mk_fn(tcx, fn_ty);
fcx.write_ty(expr.id, fty);
- check_fn(fcx.ccx, none, &fn_ty, decl, body,
- is_loop_body, some(fcx));
+ check_fn(fcx.ccx, None, &fn_ty, decl, body,
+ is_loop_body, Some(fcx));
}
base: @ast::expr, field: ast::ident, tys: ~[@ast::ty])
-> bool {
let tcx = fcx.ccx.tcx;
- let bot = check_expr(fcx, base, none);
+ let bot = check_expr(fcx, base, None);
let expr_t = structurally_resolved_type(fcx, expr.span,
fcx.expr_ty(base));
let base_t = do_autoderef(fcx, expr.span, expr_t);
match structure_of(fcx, expr.span, base_t) {
ty::ty_rec(fields) => {
match ty::field_idx(field, fields) {
- some(ix) => {
+ Some(ix) => {
if n_tys > 0u {
tcx.sess.span_err(expr.span,
~"can't provide type parameters \
lookup_public_fields(tcx, base_id)
};
match lookup_field_ty(tcx, base_id, cls_items, field, &substs) {
- some(field_ty) => {
+ Some(field_ty) => {
// (2) look up what field's type is, and return it
fcx.write_ty(expr.id, field_ty);
handled = true;
}
- none => ()
+ None => ()
}
}
_ => ()
expr.id, field, expr_t, tps,
is_self_ref);
match lkup.method() {
- some(entry) => {
+ Some(entry) => {
fcx.ccx.method_map.insert(expr.id, entry);
// If we have resolved to a method but this is not in
(try writing an anonymous function)");
}
}
- none => {
+ None => {
let t_err = fcx.infcx.resolve_type_vars_if_possible(expr_t);
let msg = fmt!("attempted access of field `%s` on type `%s`, \
but no public field or method with that name \
let exp_inner = do unpack_expected(fcx, expected) |sty| {
match unop {
ast::box(_) | ast::uniq(_) => match sty {
- ty::ty_box(mt) | ty::ty_uniq(mt) => some(mt.ty),
- _ => none
+ ty::ty_box(mt) | ty::ty_uniq(mt) => Some(mt.ty),
+ _ => None
},
ast::not | ast::neg => expected,
- ast::deref => none
+ ast::deref => None
}
};
bot = check_expr(fcx, oprnd, exp_inner);
}
match ty::deref_sty(tcx, &sty, true) {
- some(mt) => { oprnd_t = mt.ty }
- none => {
+ Some(mt) => { oprnd_t = mt.ty }
+ None => {
match sty {
ty::ty_enum(*) => {
tcx.sess.span_err(
}
ast::expr_addr_of(mutbl, oprnd) => {
bot = check_expr(fcx, oprnd, unpack_expected(fcx, expected, |ty|
- match ty { ty::ty_rptr(_, mt) => some(mt.ty), _ => none }
+ match ty { ty::ty_rptr(_, mt) => Some(mt.ty), _ => None }
));
// Note: at this point, we cannot say what the best lifetime
ast::expr_fail(expr_opt) => {
bot = true;
match expr_opt {
- none => {/* do nothing */ }
- some(e) => {
+ None => {/* do nothing */ }
+ Some(e) => {
check_expr_with(fcx, e,
ty::mk_estr(tcx, ty::vstore_uniq));
}
ast::expr_ret(expr_opt) => {
bot = true;
let ret_ty = match fcx.indirect_ret_ty {
- some(t) => t, none => fcx.ret_ty
+ Some(t) => t, None => fcx.ret_ty
};
match expr_opt {
- none => match fcx.mk_eqty(false, expr.span,
+ None => match fcx.mk_eqty(false, expr.span,
ret_ty, ty::mk_nil(tcx)) {
result::ok(_) => { /* fall through */ }
result::err(_) => {
~"`return;` in function returning non-nil");
}
},
- some(e) => { check_expr_with(fcx, e, ret_ty); }
+ Some(e) => { check_expr_with(fcx, e, ret_ty); }
}
fcx.write_bot(id);
}
ast::expr_log(_, lv, e) => {
bot = check_expr_with(fcx, lv, ty::mk_mach_uint(tcx, ast::ty_u32));
// Note: this does not always execute, so do not propagate bot:
- check_expr(fcx, e, none);
+ check_expr(fcx, e, None);
fcx.write_nil(id);
}
ast::expr_assert(e) => {
bot = alt::check_alt(fcx, expr, discrim, arms);
}
ast::expr_fn(proto, decl, body, cap_clause) => {
- check_expr_fn(fcx, expr, some(proto),
+ check_expr_fn(fcx, expr, Some(proto),
decl, body, false,
expected);
capture::check_capture_clause(tcx, expr.id, cap_clause);
}
ast::expr_fn_block(decl, body, cap_clause) => {
- check_expr_fn(fcx, expr, none,
+ check_expr_fn(fcx, expr, None,
decl, body, false,
expected);
capture::check_capture_clause(tcx, expr.id, cap_clause);
// parameter. The catch here is that we need to validate two things:
// 1. a closure that returns a bool is expected
// 2. the cloure that was given returns unit
- let expected_sty = unpack_expected(fcx, expected, |x| some(x));
+ let expected_sty = unpack_expected(fcx, expected, |x| Some(x));
let inner_ty = match expected_sty {
- some(ty::ty_fn(fty)) => {
+ Some(ty::ty_fn(fty)) => {
match fcx.mk_subty(false, expr.span,
fty.output, ty::mk_bool(tcx)) {
result::ok(_) => (),
};
match b.node {
ast::expr_fn_block(decl, body, cap_clause) => {
- check_expr_fn(fcx, b, none,
+ check_expr_fn(fcx, b, None,
decl, body, true,
- some(inner_ty));
+ Some(inner_ty));
demand::suptype(fcx, b.span, inner_ty, fcx.expr_ty(b));
capture::check_capture_clause(tcx, b.id, cap_clause);
}
}
}
ast::expr_do_body(b) => {
- let expected_sty = unpack_expected(fcx, expected, |x| some(x));
+ let expected_sty = unpack_expected(fcx, expected, |x| Some(x));
let inner_ty = match expected_sty {
- some(ty::ty_fn(fty)) => {
+ Some(ty::ty_fn(fty)) => {
ty::mk_fn(tcx, fty)
}
_ => {
};
match b.node {
ast::expr_fn_block(decl, body, cap_clause) => {
- check_expr_fn(fcx, b, none,
+ check_expr_fn(fcx, b, None,
decl, body, true,
- some(inner_ty));
+ Some(inner_ty));
demand::suptype(fcx, b.span, inner_ty, fcx.expr_ty(b));
capture::check_capture_clause(tcx, b.id, cap_clause);
}
bot = check_block(fcx, b);
let typ =
match b.node.expr {
- some(expr) => fcx.expr_ty(expr),
- none => ty::mk_nil(tcx)
+ Some(expr) => fcx.expr_ty(expr),
+ None => ty::mk_nil(tcx)
};
fcx.write_ty(id, typ);
}
bot = check_call(fcx, expr.span, expr.id, f, args);
}
ast::expr_cast(e, t) => {
- bot = check_expr(fcx, e, none);
+ bot = check_expr(fcx, e, None);
let t_1 = fcx.to_ty(t);
let t_e = fcx.expr_ty(e);
let mut elt_ts = ~[];
vec::reserve(elt_ts, vec::len(elts));
let flds = unpack_expected(fcx, expected, |sty| {
- match sty { ty::ty_tup(flds) => some(flds), _ => none }
+ match sty { ty::ty_tup(flds) => Some(flds), _ => None }
});
for elts.eachi |i, e| {
check_expr(fcx, e, flds.map(|fs| fs[i]));
}
ast::expr_rec(fields, base) => {
option::iter(base, |b| { check_expr(fcx, b, expected); });
- let expected = if expected == none && base != none {
- some(fcx.expr_ty(base.get()))
+ let expected = if expected == None && base != None {
+ Some(fcx.expr_ty(base.get()))
} else { expected };
let flds = unpack_expected(fcx, expected, |sty|
- match sty { ty::ty_rec(flds) => some(flds), _ => none }
+ match sty { ty::ty_rec(flds) => Some(flds), _ => None }
);
let fields_t = vec::map(fields, |f| {
bot |= check_expr(fcx, f.node.expr, flds.chain(|flds|
respan(f.node.expr.span, {ident: f.node.ident, mt: expr_mt})
});
match base {
- none => {
+ None => {
fn get_node(f: spanned<field>) -> field { f.node }
let typ = ty::mk_rec(tcx, vec::map(fields_t, get_node));
fcx.write_ty(id, typ);
check_no_duplicate_fields(tcx, fields.map(|f|
(f.node.ident, f.span)));
}
- some(bexpr) => {
+ Some(bexpr) => {
let bexpr_t = fcx.expr_ty(bexpr);
let base_fields = match structure_of(fcx, expr.span, bexpr_t) {
ty::ty_rec(flds) => flds,
// Resolve the path.
let class_id;
match tcx.def_map.find(id) {
- some(ast::def_class(type_def_id, _)) => {
+ Some(ast::def_class(type_def_id, _)) => {
class_id = type_def_id;
}
_ => {
region_parameterized =
tcx.region_paramd_items.find(class_id.node);
match tcx.items.find(class_id.node) {
- some(ast_map::node_item(@{
+ Some(ast_map::node_item(@{
node: ast::item_class(_, type_parameters),
_
}, _)) => {
raw_type = ty::mk_class(tcx, class_id, {
self_r: self_region,
- self_ty: none,
+ self_ty: None,
tps: ty::ty_params_to_tys(tcx, type_parameters)
});
}
let type_parameters = fcx.infcx.next_ty_vars(type_parameter_count);
let substitutions = {
self_r: self_region,
- self_ty: none,
+ self_ty: None,
tps: type_parameters
};
// Typecheck each field.
for fields.each |field| {
match class_field_map.find(field.node.ident) {
- none => {
+ None => {
tcx.sess.span_err(
field.span,
fmt!("structure has no field named field named `%s`",
tcx.sess.str_of(field.node.ident)));
}
- some((_, true)) => {
+ Some((_, true)) => {
tcx.sess.span_err(
field.span,
fmt!("field `%s` specified more than once",
tcx.sess.str_of(field.node.ident)));
}
- some((field_id, false)) => {
+ Some((field_id, false)) => {
let expected_field_type =
ty::lookup_field_type(tcx, class_id, field_id,
&substitutions);
bot |= check_expr(fcx,
field.node.expr,
- some(expected_field_type));
+ Some(expected_field_type));
fields_found += 1;
}
}
}
match base_expr {
- none => {
+ None => {
// Make sure the programmer specified all the fields.
assert fields_found <= class_fields.len();
if fields_found < class_fields.len() {
~", ")));
}
}
- some(base_expr) => {
+ Some(base_expr) => {
// Just check the base expression.
- check_expr(fcx, base_expr, some(struct_type));
+ check_expr(fcx, base_expr, Some(struct_type));
}
}
bot = check_field(fcx, expr, false, base, field, tys);
}
ast::expr_index(base, idx) => {
- bot |= check_expr(fcx, base, none);
+ bot |= check_expr(fcx, base, None);
let raw_base_t = fcx.expr_ty(base);
let base_t = do_autoderef(fcx, expr.span, raw_base_t);
- bot |= check_expr(fcx, idx, none);
+ bot |= check_expr(fcx, idx, None);
let idx_t = fcx.expr_ty(idx);
let base_sty = structure_of(fcx, expr.span, base_t);
match ty::index_sty(tcx, &base_sty) {
- some(mt) => {
+ Some(mt) => {
require_integral(fcx, idx.span, idx_t);
fcx.write_ty(id, mt.ty);
}
- none => {
+ None => {
let resolved = structurally_resolved_type(fcx, expr.span,
raw_base_t);
match lookup_op_method(fcx, expr, base, resolved,
tcx.sess.ident_of(~"index"),
~[idx]) {
- some((ret_ty, _)) => fcx.write_ty(id, ret_ty),
+ Some((ret_ty, _)) => fcx.write_ty(id, ret_ty),
_ => {
tcx.sess.span_fatal(
expr.span, ~"cannot index a value of type `" +
syntax::print::pprust::expr_to_str(expr, tcx.sess.intr()),
ty_to_str(tcx, fcx.expr_ty(expr)),
match expected {
- some(t) => ty_to_str(tcx, t),
+ Some(t) => ty_to_str(tcx, t),
_ => ~"empty"
});
let t = ty::mk_var(fcx.ccx.tcx, fcx.locals.get(local.node.id));
fcx.write_ty(local.node.id, t);
match local.node.init {
- some(init) => {
+ Some(init) => {
bot = check_decl_initializer(fcx, local.node.id, init);
}
_ => {/* fall through */ }
}
ast::stmt_semi(expr, id) => {
node_id = id;
- bot = check_expr(fcx, expr, none);
+ bot = check_expr(fcx, expr, None);
}
}
fcx.write_nil(node_id);
bot |= check_stmt(fcx, s);
}
match blk.node.expr {
- none => fcx.write_nil(blk.node.id),
- some(e) => {
+ None => fcx.write_nil(blk.node.id),
+ Some(e) => {
if bot && !warned {
fcx.ccx.tcx.sess.span_warn(e.span, ~"unreachable expression");
}
- bot |= check_expr(fcx, e, none);
+ bot |= check_expr(fcx, e, None);
let ety = fcx.expr_ty(e);
fcx.write_ty(blk.node.id, ety);
}
fn check_const(ccx: @crate_ctxt, _sp: span, e: @ast::expr, id: ast::node_id) {
let rty = ty::node_id_to_type(ccx.tcx, id);
let fcx = blank_fn_ctxt(ccx, rty, e.id);
- check_expr(fcx, e, none);
+ check_expr(fcx, e, None);
let cty = fcx.expr_ty(e);
let declty = fcx.ccx.tcx.tcache.get(local_def(id)).ty;
demand::suptype(fcx, e.span, declty, cty);
/// This is similar but different from the question of whether a type
/// can be represented. For example, the following type:
///
-/// enum foo { none, some(foo) }
+/// enum foo { None, Some(foo) }
///
/// is instantiable but is not representable. Similarly, the type
///
-/// enum foo { some(@foo) }
+/// enum foo { Some(@foo) }
///
/// is representable, but not instantiable.
fn check_instantiable(tcx: ty::ctxt,
let rty = ty::node_id_to_type(ccx.tcx, id);
for vs.each |v| {
match v.node.disr_expr {
- some(e) => {
+ Some(e) => {
let fcx = blank_fn_ctxt(ccx, rty, e.id);
- check_expr(fcx, e, none);
+ check_expr(fcx, e, None);
let cty = fcx.expr_ty(e);
let declty = ty::mk_int(ccx.tcx);
demand::suptype(fcx, e.span, declty, cty);
match v.node.kind {
ast::tuple_variant_kind(args) if args.len() > 0u => {
- arg_tys = some(ty::ty_fn_args(ctor_ty).map(|a| a.ty));
+ arg_tys = Some(ty::ty_fn_args(ctor_ty).map(|a| a.ty));
}
ast::tuple_variant_kind(_) | ast::struct_variant_kind(_) => {
- arg_tys = some(~[]);
+ arg_tys = Some(~[]);
}
ast::enum_variant_kind(subvariants) => {
- arg_tys = none;
+ arg_tys = None;
do_check(ccx, sp, vs, id, disr_vals, disr_val, variants);
}
}
match arg_tys {
- none => {}
- some(arg_tys) => {
+ None => {}
+ Some(arg_tys) => {
vec::push(*variants, @{args: arg_tys, ctor_ty: ctor_ty,
name: v.node.name, id: local_def(v.node.id),
disr_val: this_disr_val});
fn lookup_local(fcx: @fn_ctxt, sp: span, id: ast::node_id) -> tv_vid {
match fcx.locals.find(id) {
- some(x) => x,
+ Some(x) => x,
_ => {
fcx.ccx.tcx.sess.span_fatal(sp,
~"internal error looking up a local var")
// extern functions are just u8 pointers
return {
bounds: @~[],
- region_param: none,
+ region_param: None,
ty: ty::mk_ptr(
fcx.ccx.tcx,
{
// determine the region bound, using the value given by the user
// (if any) and otherwise using a fresh region variable
let self_r = match pth.rp {
- some(r) => {
+ Some(r) => {
match tpt.region_param {
- none => {
+ None => {
fcx.ccx.tcx.sess.span_err
(span, ~"this item is not region-parameterized");
- none
+ None
}
- some(_) => {
- some(ast_region_to_region(fcx, fcx, span, r))
+ Some(_) => {
+ Some(ast_region_to_region(fcx, fcx, span, r))
}
}
}
- none => {
+ None => {
fcx.region_var_if_parameterized(
tpt.region_param, span, region_lb)
}
pth.types.map(|aty| fcx.to_ty(aty))
};
- let substs = {self_r: self_r, self_ty: none, tps: tps};
+ let substs = {self_r: self_r, self_ty: None, tps: tps};
fcx.write_ty_substs(node_id, tpt.ty, substs);
}
fn ast_expr_vstore_to_vstore(fcx: @fn_ctxt, e: @ast::expr, n: uint,
v: ast::vstore) -> ty::vstore {
match v {
- ast::vstore_fixed(none) => ty::vstore_fixed(n),
- ast::vstore_fixed(some(u)) => {
+ ast::vstore_fixed(None) => ty::vstore_fixed(n),
+ ast::vstore_fixed(Some(u)) => {
if n != u {
let s = fmt!("fixed-size sequence mismatch: %u vs. %u",u, n);
fcx.ccx.tcx.sess.span_err(e.span,s);
expected %u", i_n_tps, n_tps));
} else {
require_same_types(
- tcx, none, false, it.span, i_ty.ty, fty,
+ tcx, None, false, it.span, i_ty.ty, fty,
|| fmt!("intrinsic has wrong type: \
expected `%s`",
ty_to_str(ccx.tcx, fty)));
let mut arm_non_bot = false;
for arms.each |arm| {
match 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 = fcx.node_ty(arm.body.node.id);
};
fn check_pat_variant(pcx: pat_ctxt, pat: @ast::pat, path: @ast::path,
- subpats: option<~[@ast::pat]>, expected: ty::t) {
+ subpats: Option<~[@ast::pat]>, expected: ty::t) {
// Typecheck the path.
let fcx = pcx.fcx;
vinfo.args.map(|t| { ty::subst(tcx, expected_substs, t) })
};
let arg_len = arg_types.len(), subpats_len = match subpats {
- none => arg_len,
- some(ps) => ps.len()
+ None => arg_len,
+ Some(ps) => ps.len()
};
if arg_len > 0u {
// N-ary variant.
debug!("pat_range beginning type: %?", b_ty);
debug!("pat_range ending type: %?", e_ty);
if !require_same_types(
- tcx, some(fcx.infcx), false, pat.span, b_ty, e_ty,
+ tcx, Some(fcx.infcx), false, pat.span, b_ty, e_ty,
|| ~"mismatched types in range") {
// no-op
} else if !ty::type_is_numeric(b_ty) {
}
fcx.write_ty(pat.id, typ);
match sub {
- some(p) => check_pat(pcx, p, expected),
+ Some(p) => check_pat(pcx, p, expected),
_ => ()
}
}
ast::pat_ident(_, path, c) => {
- check_pat_variant(pcx, pat, path, some(~[]), expected);
+ check_pat_variant(pcx, pat, path, Some(~[]), expected);
}
ast::pat_enum(path, subpats) => {
check_pat_variant(pcx, pat, path, subpats, expected);
for fields.each |f| {
match vec::find(ex_fields, |a| f.ident == a.ident) {
- some(field) => {
+ Some(field) => {
check_pat(pcx, f.pat, field.mt.ty);
}
- none => {
+ None => {
tcx.sess.span_fatal(pat.span,
fmt!("mismatched types: did not \
expect a record with a field `%s`",
let found_fields = std::map::uint_hash();
for fields.each |field| {
match field_map.find(field.ident) {
- some(index) => {
+ Some(index) => {
let class_field = class_fields[index];
let field_type = ty::lookup_field_type(tcx,
class_id,
check_pat(pcx, field.pat, field_type);
found_fields.insert(index, ());
}
- none => {
+ None => {
let name = pprust::path_to_str(path, tcx.sess.intr());
tcx.sess.span_err(pat.span,
fmt!("struct `%s` does not have a field
fn transform_self_type_for_method
(tcx: ty::ctxt,
- self_region: option<ty::region>,
+ self_region: Option<ty::region>,
impl_ty: ty::t,
self_type: ast::self_ty_)
-> ty::t {
}
// Entrypoint:
- fn method() -> option<method_map_entry> {
+ fn method() -> Option<method_map_entry> {
debug!("method lookup(m_name=%s, self_ty=%s, %?)",
self.fcx.tcx().sess.str_of(self.m_name),
self.fcx.infcx.ty_to_str(self.self_ty),
match get_base_type_def_id(self.fcx.infcx,
self.self_expr.span,
self.self_ty) {
- none => {
- optional_inherent_methods = none;
+ None => {
+ optional_inherent_methods = None;
}
- some(base_type_def_id) => {
+ Some(base_type_def_id) => {
debug!("(checking method) found base type");
optional_inherent_methods =
self.fcx.ccx.coherence_info.inherent_methods.find
// check whether we can autoderef and if so loop around again.
match ty::deref(self.tcx(), self.self_ty, false) {
- none => break,
- some(mt) => {
+ None => break,
+ Some(mt) => {
self.self_ty = mt.ty;
self.derefs += 1u;
}
if self.candidates.len() == 0u {
debug!("(checking method) couldn't find any candidate methods; \
returning none");
- return none;
+ return None;
}
if self.candidates.len() > 1u {
}
}
- some(self.write_mty_from_candidate(self.candidates[0u]))
+ Some(self.write_mty_from_candidate(self.candidates[0u]))
}
fn tcx() -> ty::ctxt { self.fcx.ccx.tcx }
~"unexpected `none` for self_impl_def_id");
let substs = {
- self_r: none,
- self_ty: none,
+ self_r: None,
+ self_ty: None,
tps: ~[],
};
let trt_methods = ty::trait_methods(tcx, trait_id);
match vec::position(*trt_methods, |m| m.ident == self.m_name) {
- none => {
+ None => {
/* check next bound */
trait_bnd_idx += 1u;
}
- some(pos) => {
+ Some(pos) => {
// Replace any appearance of `self` with the type of the
// generic parameter itself. Note that this is the only case
// where this replacement is necessary: in all other cases, we
// (where the self type is not permitted), or from a trait
// type (in which case methods that refer to self are not
// permitted).
- let substs = {self_ty: some(self.self_ty)
+ let substs = {self_ty: Some(self.self_ty)
with bound_substs};
self.add_candidates_from_m(
// Note: although it is illegal to invoke a method that uses self
// through a trait instance, we use a dummy subst here so that we
// can soldier on with the compilation.
- let substs = {self_ty: some(self.self_ty)
+ let substs = {self_ty: Some(self.self_ty)
with trait_substs};
self.add_candidates_from_m(
// If we don't have a self region but have an region pointer
// explicit self, we need to make up a new region.
let self_r = match self_substs.self_r {
- none => {
+ None => {
match m.self_ty {
ast::sty_region(_) =>
- some(self.fcx.infcx.next_region_var(
+ Some(self.fcx.infcx.next_region_var(
self.self_expr.span,
self.self_expr.id)),
- _ => none
+ _ => None
}
}
- some(_) => self_substs.self_r
+ Some(_) => self_substs.self_r
};
let self_substs = {self_r: self_r with self_substs};
}
fn add_inherent_and_extension_candidates(optional_inherent_methods:
- option<@DVec<@Impl>>,
+ Option<@DVec<@Impl>>,
mode: method_lookup_mode) {
// Add inherent methods.
match optional_inherent_methods {
- none => {
+ None => {
// Continue.
}
- some(inherent_methods) => {
+ Some(inherent_methods) => {
debug!("(adding inherent and extension candidates) adding \
inherent candidates");
for inherent_methods.each |implementation| {
// Add trait methods.
match self.fcx.ccx.trait_map.find(self.expr.id) {
- none => {
+ None => {
// Should only happen for placement new right now.
}
- some(trait_ids) => {
+ Some(trait_ids) => {
for (*trait_ids).each |trait_id| {
debug!("(adding inherent and extension candidates) \
trying trait: %s",
let coherence_info = self.fcx.ccx.coherence_info;
match coherence_info.extension_methods.find(trait_id) {
- none => {
+ None => {
// Do nothing.
}
- some(extension_methods) => {
+ Some(extension_methods) => {
for extension_methods.each |implementation| {
debug!("(adding inherent and extension \
candidates) adding impl %s",
match ty::get(target_ty).struct {
ty::ty_trait(_, substs, _) => {
let trait_region = match substs.self_r {
- some(r) => {r}
- none => {ty::re_static}
+ Some(r) => {r}
+ None => {ty::re_static}
};
let source_ty = rcx.fcx.expr_ty(source);
constrain_regions_in_type(rcx, trait_region,
fn replace_bound_regions_in_fn_ty(
tcx: ty::ctxt,
isr: isr_alist,
- self_info: option<self_info>,
+ self_info: Option<self_info>,
fn_ty: &ty::fn_ty,
mapf: fn(ty::bound_region) -> ty::region) ->
- {isr: isr_alist, self_info: option<self_info>, fn_ty: ty::fn_ty} {
+ {isr: isr_alist, self_info: Option<self_info>, fn_ty: ty::fn_ty} {
// Take self_info apart; the self_ty part is the only one we want
// to update here.
let (self_ty, rebuild_self_info) = match self_info {
- some(s) => (some(s.self_ty), |t| some({self_ty: t with s})),
- none => (none, |_t| none)
+ Some(s) => (Some(s.self_ty), |t| Some({self_ty: t with s})),
+ None => (None, |_t| None)
};
let mut all_tys = ty::tys_in_fn_ty(fn_ty);
match self_info {
- some({explicit_self: {node: ast::sty_region(m), _}, _}) => {
+ Some({explicit_self: {node: ast::sty_region(m), _}, _}) => {
let region = ty::re_bound(ty::br_self);
let ty = ty::mk_rptr(tcx, region,
{ ty: ty::mk_self(tcx), mutbl: m });
// Glue updated self_ty back together with its original def_id.
- let new_self_info: option<self_info> = match t_self {
- none => none,
- some(t) => rebuild_self_info(t)
+ let new_self_info: Option<self_info> = match t_self {
+ None => None,
+ Some(t) => rebuild_self_info(t)
};
return {isr: isr,
}
ty::re_bound(br) => {
match isr.find(br) {
- some(_) => isr,
- none => @cons((br, to_r(br)), isr)
+ Some(_) => isr,
+ None => @cons((br, to_r(br)), isr)
}
}
}
match isr.find(br) {
// In most cases, all named, bound regions will be
// mapped to some free region.
- some(fr) => fr,
+ Some(fr) => fr,
// But in the case of a fn() type, there may be
// named regions within that remain bound:
- none if in_fn => r,
- none => {
+ None if in_fn => r,
+ None => {
tcx.sess.bug(
fmt!("Bound region not found in \
in_scope_regions list: %s",
// arguments and before typechecking closure arguments) in the hope of
// solving for the trait parameters from the impl. (For example,
// determining that if a parameter bounded by BaseIter<A> is
-// instantiated with option<int>, that A = int.)
+// instantiated with Option<int>, that A = int.)
//
// In early resolution mode, no vtables are recorded, and a number of
// errors are ignored. Early resolution only works if a type is
fn fixup_substs(fcx: @fn_ctxt, expr: @ast::expr,
id: ast::def_id, substs: ty::substs,
- is_early: bool) -> option<ty::substs> {
+ is_early: bool) -> Option<ty::substs> {
let tcx = fcx.ccx.tcx;
// use a dummy type just to package up the substs that need fixing up
let t = ty::mk_trait(tcx, id, substs, ty::vstore_slice(ty::re_static));
don't know how to handle a non-trait ty")
};
let ty = match fixup_ty(fcx, expr, ty, is_early) {
- some(ty) => ty,
- none => {
+ Some(ty) => ty,
+ None => {
// fixup_ty can only fail if this is early resolution
assert is_early;
// The type has unconstrained type variables in it, so we can't
let mut impls_seen = new_def_hash();
match fcx.ccx.coherence_info.extension_methods.find(trait_id) {
- none => {
+ None => {
// Nothing found. Continue.
}
- some(implementations) => {
+ Some(implementations) => {
for uint::range(0, implementations.len()) |i| {
let im = implementations[i];
// see comments around the earlier call to fixup_ty
let substs_f = match fixup_substs(fcx, expr, trait_id,
substs, is_early) {
- some(substs) => substs,
- none => {
+ Some(substs) => substs,
+ None => {
assert is_early;
// Bail out with a bogus answer
return vtable_param(0, 0);
fn fixup_ty(fcx: @fn_ctxt,
expr: @ast::expr,
ty: ty::t,
- is_early: bool) -> option<ty::t>
+ is_early: bool) -> Option<ty::t>
{
let tcx = fcx.ccx.tcx;
match resolve_type(fcx.infcx, ty, resolve_and_force_all_but_regions) {
- result::ok(new_type) => some(new_type),
+ result::ok(new_type) => Some(new_type),
result::err(e) if !is_early => {
tcx.sess.span_fatal(
expr.span,
fixup_err_to_str(e)))
}
result::err(e) => {
- none
+ None
}
}
}
match ex.node {
ast::expr_path(*) => {
match fcx.opt_node_ty_substs(ex.id) {
- some(ref substs) => {
+ Some(ref substs) => {
let did = ast_util::def_id_of_def(cx.tcx.def_map.get(ex.id));
let item_ty = ty::lookup_item_type(cx.tcx, did);
if has_trait_bounds(*item_ty.bounds) {
ast::expr_unary(*) | ast::expr_assign_op(*) |
ast::expr_index(*) => {
match ty::method_call_bounds(cx.tcx, cx.method_map, ex.id) {
- some(bounds) => {
+ Some(bounds) => {
if has_trait_bounds(*bounds) {
let callee_id = match ex.node {
ast::expr_field(_, _, _) => ex.id,
if !is_early { cx.vtable_map.insert(callee_id, vtbls); }
}
}
- none => ()
+ None => ()
}
}
ast::expr_cast(src, _) => {
export resolve_type_vars_in_expr;
fn resolve_type_vars_in_type(fcx: @fn_ctxt, sp: span, typ: ty::t) ->
- option<ty::t> {
- if !ty::type_needs_infer(typ) { return some(typ); }
+ Option<ty::t> {
+ if !ty::type_needs_infer(typ) { return Some(typ); }
match resolve_type(fcx.infcx, typ, resolve_all | force_all) {
- result::ok(new_type) => return some(new_type),
+ result::ok(new_type) => return Some(new_type),
result::err(e) => {
if !fcx.ccx.tcx.sess.has_errors() {
fcx.ccx.tcx.sess.span_err(
for this expression: %s",
infer::fixup_err_to_str(e)))
}
- return none;
+ return None;
}
}
}
fn resolve_type_vars_for_node(wbcx: wb_ctxt, sp: span, id: ast::node_id)
- -> option<ty::t> {
+ -> Option<ty::t> {
let fcx = wbcx.fcx, tcx = fcx.ccx.tcx;
let n_ty = fcx.node_ty(id);
match resolve_type_vars_in_type(fcx, sp, n_ty) {
- none => {
+ None => {
wbcx.success = false;
- return none;
+ return None;
}
- some(t) => {
+ Some(t) => {
debug!("resolve_type_vars_for_node(id=%d, n_ty=%s, t=%s)",
id, ty_to_str(tcx, n_ty), ty_to_str(tcx, t));
write_ty_to_tcx(tcx, id, t);
match fcx.opt_node_ty_substs(id) {
- some(substs) => {
+ Some(substs) => {
let mut new_tps = ~[];
for substs.tps.each |subst| {
match resolve_type_vars_in_type(fcx, sp, subst) {
- some(t) => vec::push(new_tps, t),
- none => { wbcx.success = false; return none; }
+ Some(t) => vec::push(new_tps, t),
+ None => { wbcx.success = false; return None; }
}
}
write_substs_to_tcx(tcx, id, new_tps);
}
- none => ()
+ None => ()
}
- return some(t);
+ return Some(t);
}
}
}
fn maybe_resolve_type_vars_for_node(wbcx: wb_ctxt, sp: span,
id: ast::node_id)
- -> option<ty::t> {
+ -> Option<ty::t> {
if wbcx.fcx.node_types.contains_key(id) {
resolve_type_vars_for_node(wbcx, sp, id)
} else {
- none
+ None
}
}
// Just in case we never constrained the mode to anything,
// constrain it to the default for the type in question.
match (r_ty, input.mode) {
- (some(t), ast::infer(_)) => {
+ (Some(t), ast::infer(_)) => {
let tcx = wbcx.fcx.ccx.tcx;
let m_def = ty::default_arg_mode_for_ty(t);
ty::set_default_mode(tcx, input.mode, m_def);
fn resolve_type_vars_in_fn(fcx: @fn_ctxt,
decl: ast::fn_decl,
blk: ast::blk,
- self_info: option<self_info>) -> bool {
+ self_info: Option<self_info>) -> bool {
let wbcx = {fcx: fcx, mut success: true};
let visit = mk_visitor();
visit.visit_block(blk, wbcx, visit);
import vec::{len, push};
fn get_base_type(inference_context: infer_ctxt, span: span, original_type: t)
- -> option<t> {
+ -> Option<t> {
let resolved_type;
match resolve_type(inference_context,
ty_enum(*) | ty_trait(*) | ty_class(*) => {
debug!("(getting base type) found base type");
- some(resolved_type)
+ Some(resolved_type)
}
ty_nil | ty_bot | ty_bool | ty_int(*) | ty_uint(*) | ty_float(*) |
ty_opaque_closure_ptr(*) | ty_unboxed_vec(*) => {
debug!("(getting base type) no base type; found %?",
get(original_type).struct);
- none
+ None
}
}
}
fn get_base_type_def_id(inference_context: infer_ctxt,
span: span,
original_type: t)
- -> option<def_id> {
+ -> Option<def_id> {
match get_base_type(inference_context, span, original_type) {
- none => {
- return none;
+ None => {
+ return None;
}
- some(base_type) => {
+ Some(base_type) => {
match get(base_type).struct {
ty_enum(def_id, _) |
ty_class(def_id, _) |
ty_trait(def_id, _, _) => {
- return some(def_id);
+ return Some(def_id);
}
_ => {
fail ~"get_base_type() returned a type that wasn't an \
let mi = method_to_MethodInfo(m);
match pmm.find(item.id) {
- some(mis) => {
+ Some(mis) => {
// If the trait already has an
// entry in the
// provided_methods_map, we just
push(method_infos, mi);
pmm.insert(item.id, method_infos);
}
- none => {
+ None => {
// If the trait doesn't have an
// entry yet, create one.
debug!("(building provided \
match get_base_type_def_id(self.inference_context,
item.span,
self_type.ty) {
- none => {
+ None => {
let session = self.crate_context.tcx.sess;
session.span_err(item.span,
~"no base type found for inherent \
implementation; implement a \
trait or new type instead");
}
- some(_) => {
+ Some(_) => {
// Nothing to do.
}
}
match get_base_type_def_id(self.inference_context,
item.span,
self_type.ty) {
- none => {
+ None => {
// Nothing to do.
}
- some(base_type_def_id) => {
+ Some(base_type_def_id) => {
let implementation = self.create_impl_from_item(item);
self.add_inherent_method(base_type_def_id, implementation);
match self.crate_context.coherence_info.inherent_methods
.find(base_def_id) {
- none => {
+ None => {
implementation_list = @dvec();
self.crate_context.coherence_info.inherent_methods
.insert(base_def_id, implementation_list);
}
- some(existing_implementation_list) => {
+ Some(existing_implementation_list) => {
implementation_list = existing_implementation_list;
}
}
match self.crate_context.coherence_info.extension_methods
.find(trait_id) {
- none => {
+ None => {
implementation_list = @dvec();
self.crate_context.coherence_info.extension_methods
.insert(trait_id, implementation_list);
}
- some(existing_implementation_list) => {
+ Some(existing_implementation_list) => {
implementation_list = existing_implementation_list;
}
}
let substitutions = {
self_r: self_region,
- self_ty: none,
+ self_ty: None,
tps: type_parameters
};
match self.base_type_def_ids.find(
local_def(item.id)) {
- none => {
+ None => {
// Nothing to do.
}
- some(base_type_def_id) => {
+ Some(base_type_def_id) => {
// Check to see whether the implementation is
// in the scope of its base type.
match self.crate_context.provided_methods_map
.find(trait_did.node) {
- none => {
+ None => {
debug!("(creating impl) trait with node_id `%d` \
has no provided methods", trait_did.node);
/* fall through */
}
- some(all_provided)
+ Some(all_provided)
=> {
debug!("(creating impl) trait with node_id `%d` \
has provided methods", trait_did.node);
fn span_of_impl(implementation: @Impl) -> span {
assert implementation.did.crate == local_crate;
match self.crate_context.tcx.items.find(implementation.did.node) {
- some(node_item(item, _)) => {
+ Some(node_item(item, _)) => {
return item.span;
}
_ => {
let implementations = get_impls_for_mod(crate_store,
module_def_id,
- none);
+ None);
for (*implementations).each |implementation| {
// Make sure we don't visit the same implementation
// multiple times.
match impls_seen.find(implementation.did) {
- none => {
+ None => {
// Good. Continue.
impls_seen.insert(implementation.did, ());
}
- some(_) => {
+ Some(_) => {
// Skip this one.
again;
}
match get_base_type_def_id(self.inference_context,
dummy_sp(),
self_type.ty) {
- none => {
+ None => {
let session = self.crate_context.tcx.sess;
session.bug(fmt!(
"no base type for external impl \
session.str_of(implementation.ident),
ty_to_str(self.crate_context.tcx,self_type.ty)));
}
- some(_) => {
+ Some(_) => {
// Nothing to do.
}
}
match get_base_type_def_id(self.inference_context,
dummy_sp(),
self_type.ty) {
- none => {
+ None => {
// Nothing to do.
}
- some(base_type_def_id) => {
+ Some(base_type_def_id) => {
self.add_inherent_method(base_type_def_id,
implementation);
for m.items.each |intrinsic_item| {
let def_id = { crate: ast::local_crate,
node: intrinsic_item.id };
- let substs = {self_r: none, self_ty: none, tps: ~[]};
+ let substs = {self_r: None, self_ty: None, tps: ~[]};
match intrinsic_item.node {
ast::item_trait(*) => {
csearch::get_type(self.tcx, id)
} else {
match self.tcx.items.find(id.node) {
- some(ast_map::node_item(item, _)) => {
+ Some(ast_map::node_item(item, _)) => {
ty_of_item(self, item)
}
- some(ast_map::node_foreign_item(foreign_item, _, _)) => {
+ Some(ast_map::node_foreign_item(foreign_item, _, _)) => {
ty_of_foreign_item(self, foreign_item)
}
x => {
enum_ty: ty::t,
variants: ~[ast::variant],
ty_params: ~[ast::ty_param],
- rp: option<ty::region_variance>) {
+ rp: Option<ty::region_variance>) {
let tcx = ccx.tcx;
// Create a set of parameter types shared among all the variants.
let arg_ty = ccx.to_ty(rs, va.ty);
{mode: ast::expl(ast::by_copy), ty: arg_ty}
});
- result_ty = some(ty::mk_fn(tcx,
+ result_ty = Some(ty::mk_fn(tcx,
{purity: ast::pure_fn,
proto: ty::proto_vstore
(ty::vstore_box),
ret_style: ast::return_val}));
}
ast::tuple_variant_kind(_) | ast::struct_variant_kind(_) => {
- result_ty = some(enum_ty);
+ result_ty = Some(enum_ty);
}
ast::enum_variant_kind(enum_definition) => {
get_enum_variant_types(ccx, enum_ty, enum_definition.variants,
ty_params, rp);
- result_ty = none;
+ result_ty = None;
}
};
match result_ty {
- none => {}
- some(result_ty) => {
+ None => {}
+ Some(result_ty) => {
let tpt = {bounds: ty_param_bounds(ccx, ty_params),
region_param: rp,
ty: result_ty};
fn make_static_method_ty(ccx: @crate_ctxt,
am: ast::ty_method,
- rp: option<ty::region_variance>,
+ rp: Option<ty::region_variance>,
m: ty::method,
// Take this as an argument b/c we may check
// the impl before the trait.
ty::mk_param(ccx.tcx, i + 1, dummy_defid)
};
- let substs = { self_r: none, self_ty: some(self_param),
+ let substs = { self_r: None, self_ty: Some(self_param),
tps: non_shifted_trait_tps + shifted_method_tps };
let ty = ty::subst(ccx.tcx, &substs, ty::mk_fn(ccx.tcx, m.fty));
let bounds = @(*trait_bounds + ~[@~[ty::bound_trait(trait_ty)]]
ty::mk_param(tcx, i + impl_tps, {crate: 0, node: 0})
};
let substs = {
- self_r: some(dummy_self_r),
- self_ty: some(self_ty),
+ self_r: Some(dummy_self_r),
+ self_ty: Some(self_ty),
tps: vec::append(trait_substs.tps, dummy_tps)
};
let trait_fty = ty::mk_fn(tcx, trait_m.fty);
ty::subst(tcx, &substs, trait_fty)
};
require_same_types(
- tcx, none, false, sp, impl_fty, trait_fty,
+ tcx, None, false, sp, impl_fty, trait_fty,
|| ~"method `" + tcx.sess.str_of(trait_m.ident)
+ ~"` has an incompatible type");
return;
fn check_methods_against_trait(ccx: @crate_ctxt,
tps: ~[ast::ty_param],
- rp: option<ty::region_variance>,
+ rp: Option<ty::region_variance>,
selfty: ty::t,
a_trait_ty: @ast::trait_ref,
impl_ms: ~[converted_method]) {
}
for vec::each(*ty::trait_methods(tcx, did)) |trait_m| {
match vec::find(impl_ms, |impl_m| trait_m.ident == impl_m.mty.ident) {
- some({mty: impl_m, id, span}) => {
+ Some({mty: impl_m, id, span}) => {
compare_impl_method(
ccx.tcx, span, impl_m, vec::len(tps),
trait_m, tpt.substs, selfty);
}
- none => {
+ None => {
// If we couldn't find an implementation for trait_m in
// the impl, then see if there was a default
// implementation in the trait itself. If not, raise a
match vec::find(provided_methods, |provided_method|
provided_method.ident == trait_m.ident) {
- some(m) => {
+ Some(m) => {
// If there's a provided method with the name we
// want, then we're fine; nothing else to do.
}
- none => {
+ None => {
tcx.sess.span_err(
a_trait_ty.path.span,
fmt!("missing method `%s`",
} // fn
fn convert_field(ccx: @crate_ctxt,
- rp: option<ty::region_variance>,
+ rp: Option<ty::region_variance>,
bounds: @~[ty::param_bounds],
v: @ast::struct_field) {
let tt = ccx.to_ty(type_rscope(rp), v.node.ty);
fn convert_methods(ccx: @crate_ctxt,
ms: ~[@ast::method],
- rp: option<ty::region_variance>,
+ rp: Option<ty::region_variance>,
rcvr_bounds: @~[ty::param_bounds]) -> ~[converted_method] {
let tcx = ccx.tcx;
}
fn convert_struct(ccx: @crate_ctxt,
- rp: option<ty::region_variance>,
+ rp: Option<ty::region_variance>,
struct_def: @ast::struct_def,
tps: ~[ast::ty_param],
tpt: ty::ty_param_bounds_and_ty,
do option::iter(struct_def.ctor) |ctor| {
// Write the ctor type
let t_args = ctor.node.dec.inputs.map(
- |a| ty_of_arg(ccx, type_rscope(rp), a, none) );
+ |a| ty_of_arg(ccx, type_rscope(rp), a, None) );
let t_res = ty::mk_class(
tcx, local_def(id),
{self_r: rscope::bound_self_region(rp),
- self_ty: none,
+ self_ty: None,
tps: ty::ty_params_to_tys(tcx, tps)});
let t_ctor = ty::mk_fn(
tcx, {purity: ast::impure_fn,
tcx,
ty_of_fn_decl(ccx, type_rscope(rp), ast::proto_bare,
ast::impure_fn, @~[],
- ast_util::dtor_dec(), none, dtor.span));
+ ast_util::dtor_dec(), None, dtor.span));
write_ty_to_tcx(tcx, dtor.node.id, t_dtor);
tcx.tcache.insert(local_def(dtor.node.id),
{bounds: tpt.bounds,
fn ty_of_method(ccx: @crate_ctxt,
m: @ast::method,
- rp: option<ty::region_variance>) -> ty::method {
+ rp: Option<ty::region_variance>) -> ty::method {
{ident: m.ident,
tps: ty_param_bounds(ccx, m.tps),
fty: ty_of_fn_decl(ccx, type_rscope(rp), ast::proto_bare,
m.purity, @~[],
- m.decl, none, m.span),
+ m.decl, None, m.span),
self_ty: m.self_ty.node,
vis: m.vis}
}
fn ty_of_ty_method(self: @crate_ctxt,
m: ast::ty_method,
- rp: option<ty::region_variance>) -> ty::method {
+ rp: Option<ty::region_variance>) -> ty::method {
{ident: m.ident,
tps: ty_param_bounds(self, m.tps),
fty: ty_of_fn_decl(self, type_rscope(rp), ast::proto_bare, m.purity,
- @~[], m.decl, none, m.span),
+ @~[], m.decl, None, m.span),
// assume public, because this is only invoked on trait methods
self_ty: m.self_ty.node,
vis: ast::public}
trait. Fails if the type is a type other than an trait type.
*/
fn instantiate_trait_ref(ccx: @crate_ctxt, t: @ast::trait_ref,
- rp: option<ty::region_variance>)
+ rp: Option<ty::region_variance>)
-> (ast::def_id, ty_param_substs_and_ty) {
let sp = t.path.span, err = ~"can only implement trait types",
let def_id = local_def(it.id);
let tcx = ccx.tcx;
match tcx.tcache.find(def_id) {
- some(tpt) => return tpt,
+ Some(tpt) => return tpt,
_ => {}
}
let rp = tcx.region_paramd_items.find(it.id);
let bounds = ty_param_bounds(ccx, tps);
let tofd = ty_of_fn_decl(ccx, empty_rscope,
ast::proto_bare, purity, @~[],
- decl, none, it.span);
+ decl, None, it.span);
let tpt = {bounds: bounds,
- region_param: none,
+ region_param: None,
ty: ty::mk_fn(ccx.tcx, tofd)};
debug!("type of %s (id %d) is %s",
tcx.sess.str_of(it.ident), it.id, ty_to_str(tcx, tpt.ty));
}
ast::item_ty(t, tps) => {
match tcx.tcache.find(local_def(it.id)) {
- some(tpt) => return tpt,
- none => { }
+ Some(tpt) => return tpt,
+ None => { }
}
let rp = tcx.region_paramd_items.find(it.id);
let rb = in_binding_rscope(empty_rscope);
return {
bounds: @~[],
- region_param: none,
+ region_param: None,
ty: ast_ty_to_ty(ccx, rb, t)
};
}
@do params.map |param| {
match ccx.tcx.ty_param_bounds.find(param.id) {
- some(bs) => bs,
- none => {
+ Some(bs) => bs,
+ None => {
let bounds = compute_bounds(ccx, param.bounds);
ccx.tcx.ty_param_bounds.insert(param.id, bounds);
bounds
let bounds = ty_param_bounds(ccx, ty_params);
let rb = in_binding_rscope(empty_rscope);
- let input_tys = decl.inputs.map(|a| ty_of_arg(ccx, rb, a, none) );
+ let input_tys = decl.inputs.map(|a| ty_of_arg(ccx, rb, a, None) );
let output_ty = ast_ty_to_ty(ccx, rb, decl.output);
let t_fn = ty::mk_fn(ccx.tcx, {purity: purity,
inputs: input_tys,
output: output_ty,
ret_style: ast::return_val});
- let tpt = {bounds: bounds, region_param: none, ty: t_fn};
+ let tpt = {bounds: bounds, region_param: None, ty: t_fn};
ccx.tcx.tcache.insert(def_id, tpt);
return tpt;
}
}
fn mk_substs(ccx: @crate_ctxt, atps: ~[ast::ty_param],
- rp: option<ty::region_variance>)
+ rp: Option<ty::region_variance>)
-> {bounds: @~[ty::param_bounds], substs: ty::substs} {
let {bounds, params} = mk_ty_params(ccx, atps);
let self_r = rscope::bound_self_region(rp);
- {bounds: bounds, substs: {self_r: self_r, self_ty: none, tps: params}}
+ {bounds: bounds, substs: {self_r: self_r, self_ty: None, tps: params}}
}
borrow_lb: ast::node_id,
};
-type bound<T:copy> = option<T>;
+type bound<T:copy> = Option<T>;
type bounds<T:copy> = {lb: bound<T>, ub: bound<T>};
type cres<T> = result<T,ty::type_err>;
let id = *self.ty_var_counter;
*self.ty_var_counter += 1u;
self.ty_var_bindings.vals.insert(id,
- root({lb: none, ub: none}, 0u));
+ root({lb: None, ub: None}, 0u));
return tv_vid(id);
}
impl infer_ctxt {
fn assign_tys(anmnt: &assignment, a: ty::t, b: ty::t) -> ures {
- fn select(fst: option<ty::t>, snd: option<ty::t>) -> option<ty::t> {
+ fn select(fst: Option<ty::t>, snd: Option<ty::t>) -> Option<ty::t> {
match fst {
- some(t) => some(t),
- none => match snd {
- some(t) => some(t),
- none => none
+ Some(t) => Some(t),
+ None => match snd {
+ Some(t) => Some(t),
+ None => None
}
}
}
let a_bounds = nde_a.possible_types;
let a_bnd = select(a_bounds.ub, a_bounds.lb);
- self.assign_tys_or_sub(anmnt, a, b, a_bnd, some(b))
+ self.assign_tys_or_sub(anmnt, a, b, a_bnd, Some(b))
}
(_, ty::ty_var(b_id)) => {
let b_bounds = nde_b.possible_types;
let b_bnd = select(b_bounds.lb, b_bounds.ub);
- self.assign_tys_or_sub(anmnt, a, b, some(a), b_bnd)
+ self.assign_tys_or_sub(anmnt, a, b, Some(a), b_bnd)
}
(_, _) => {
- self.assign_tys_or_sub(anmnt, a, b, some(a), some(b))
+ self.assign_tys_or_sub(anmnt, a, b, Some(a), Some(b))
}
}
}
fn assign_tys_or_sub(
anmnt: &assignment,
a: ty::t, b: ty::t,
- +a_bnd: option<ty::t>, +b_bnd: option<ty::t>) -> ures {
+ +a_bnd: Option<ty::t>, +b_bnd: Option<ty::t>) -> ures {
debug!("assign_tys_or_sub(anmnt=%?, %s -> %s, %s -> %s)",
anmnt, a.to_str(self), b.to_str(self),
}
match (a_bnd, b_bnd) {
- (some(a_bnd), some(b_bnd)) => {
+ (Some(a_bnd), Some(b_bnd)) => {
match (ty::get(a_bnd).struct, ty::get(b_bnd).struct) {
(ty::ty_box(mt_a), ty::ty_rptr(r_b, mt_b)) => {
let nr_b = ty::mk_box(self.tcx, {ty: mt_b.ty,
fn contratys(a: ty::t, b: ty::t) -> cres<ty::t>;
fn tys(a: ty::t, b: ty::t) -> cres<ty::t>;
fn tps(as: &[ty::t], bs: &[ty::t]) -> cres<~[ty::t]>;
- fn self_tys(a: option<ty::t>, b: option<ty::t>) -> cres<option<ty::t>>;
+ fn self_tys(a: Option<ty::t>, b: Option<ty::t>) -> cres<Option<ty::t>>;
fn substs(did: ast::def_id, as: &ty::substs,
bs: &ty::substs) -> cres<ty::substs>;
fn fns(a: &ty::fn_ty, b: &ty::fn_ty) -> cres<ty::fn_ty>;
fn eq_opt_regions<C:combine>(
self: &C,
- a: option<ty::region>,
- b: option<ty::region>) -> cres<option<ty::region>> {
+ a: Option<ty::region>,
+ b: Option<ty::region>) -> cres<Option<ty::region>> {
match (a, b) {
- (none, none) => {
- ok(none)
+ (None, None) => {
+ ok(None)
}
- (some(a), some(b)) => {
+ (Some(a), Some(b)) => {
do eq_regions(self, a, b).then {
- ok(some(a))
+ ok(Some(a))
}
}
(_, _) => {
fn relate_region_param<C:combine>(
self: &C,
did: ast::def_id,
- a: option<ty::region>,
- b: option<ty::region>)
- -> cres<option<ty::region>>
+ a: Option<ty::region>,
+ b: Option<ty::region>)
+ -> cres<Option<ty::region>>
{
let polyty = ty::lookup_item_type(self.infcx().tcx, did);
match (polyty.region_param, a, b) {
- (none, none, none) => {
- ok(none)
+ (None, None, None) => {
+ ok(None)
}
- (some(ty::rv_invariant), some(a), some(b)) => {
+ (Some(ty::rv_invariant), Some(a), Some(b)) => {
do eq_regions(self, a, b).then {
- ok(some(a))
+ ok(Some(a))
}
}
- (some(ty::rv_covariant), some(a), some(b)) => {
+ (Some(ty::rv_covariant), Some(a), Some(b)) => {
do self.regions(a, b).chain |r| {
- ok(some(r))
+ ok(Some(r))
}
}
- (some(ty::rv_contravariant), some(a), some(b)) => {
+ (Some(ty::rv_contravariant), Some(a), Some(b)) => {
do self.contraregions(a, b).chain |r| {
- ok(some(r))
+ ok(Some(r))
}
}
(_, _, _) => {
}
fn super_self_tys<C:combine>(
- self: &C, a: option<ty::t>, b: option<ty::t>) -> cres<option<ty::t>> {
+ self: &C, a: Option<ty::t>, b: Option<ty::t>) -> cres<Option<ty::t>> {
// Note: the self type parameter is (currently) always treated as
// *invariant* (otherwise the type system would be unsound).
match (a, b) {
- (none, none) => {
- ok(none)
+ (None, None) => {
+ ok(None)
}
- (some(a), some(b)) => {
- eq_tys(self, a, b).then(|| ok(some(a)) )
+ (Some(a), Some(b)) => {
+ eq_tys(self, a, b).then(|| ok(Some(a)) )
}
- (none, some(_)) |
- (some(_), none) => {
+ (None, Some(_)) |
+ (Some(_), None) => {
// I think it should never happen that we unify two substs and
// one of them has a self_ty and one doesn't...? I could be
// wrong about this.
super_tps(&self, as, bs)
}
- fn self_tys(a: option<ty::t>, b: option<ty::t>) -> cres<option<ty::t>> {
+ fn self_tys(a: Option<ty::t>, b: Option<ty::t>) -> cres<Option<ty::t>> {
super_self_tys(&self, a, b)
}
}
}
fn single_type_contained_in(tcx: ty::ctxt, a: int_ty_set) ->
- option<ty::t> {
+ Option<ty::t> {
debug!("single_type_contained_in(a=%s)", uint::to_str(*a, 10u));
- if *a == INT_TY_SET_i8 { return some(ty::mk_i8(tcx)); }
- if *a == INT_TY_SET_u8 { return some(ty::mk_u8(tcx)); }
- if *a == INT_TY_SET_i16 { return some(ty::mk_i16(tcx)); }
- if *a == INT_TY_SET_u16 { return some(ty::mk_u16(tcx)); }
- if *a == INT_TY_SET_i32 { return some(ty::mk_i32(tcx)); }
- if *a == INT_TY_SET_u32 { return some(ty::mk_u32(tcx)); }
- if *a == INT_TY_SET_i64 { return some(ty::mk_i64(tcx)); }
- if *a == INT_TY_SET_u64 { return some(ty::mk_u64(tcx)); }
- if *a == INT_TY_SET_i { return some(ty::mk_int(tcx)); }
- if *a == INT_TY_SET_u { return some(ty::mk_uint(tcx)); }
- return none;
+ if *a == INT_TY_SET_i8 { return Some(ty::mk_i8(tcx)); }
+ if *a == INT_TY_SET_u8 { return Some(ty::mk_u8(tcx)); }
+ if *a == INT_TY_SET_i16 { return Some(ty::mk_i16(tcx)); }
+ if *a == INT_TY_SET_u16 { return Some(ty::mk_u16(tcx)); }
+ if *a == INT_TY_SET_i32 { return Some(ty::mk_i32(tcx)); }
+ if *a == INT_TY_SET_u32 { return Some(ty::mk_u32(tcx)); }
+ if *a == INT_TY_SET_i64 { return Some(ty::mk_i64(tcx)); }
+ if *a == INT_TY_SET_u64 { return Some(ty::mk_u64(tcx)); }
+ if *a == INT_TY_SET_i { return Some(ty::mk_int(tcx)); }
+ if *a == INT_TY_SET_u { return Some(ty::mk_uint(tcx)); }
+ return None;
}
fn convert_integral_ty_to_int_ty_set(tcx: ty::ctxt, t: ty::t)
// for pairs of variables or for variables and values.
trait lattice_ops {
- fn bnd(b: bounds<ty::t>) -> option<ty::t>;
+ fn bnd(b: bounds<ty::t>) -> Option<ty::t>;
fn with_bnd(b: bounds<ty::t>, t: ty::t) -> bounds<ty::t>;
fn ty_bot(t: ty::t) -> cres<ty::t>;
}
impl Lub: lattice_ops {
- fn bnd(b: bounds<ty::t>) -> option<ty::t> { b.ub }
+ fn bnd(b: bounds<ty::t>) -> Option<ty::t> { b.ub }
fn with_bnd(b: bounds<ty::t>, t: ty::t) -> bounds<ty::t> {
- {ub: some(t) with b}
+ {ub: Some(t) with b}
}
fn ty_bot(t: ty::t) -> cres<ty::t> {
ok(t)
}
impl Glb: lattice_ops {
- fn bnd(b: bounds<ty::t>) -> option<ty::t> { b.lb }
+ fn bnd(b: bounds<ty::t>) -> Option<ty::t> { b.lb }
fn with_bnd(b: bounds<ty::t>, t: ty::t) -> bounds<ty::t> {
- {lb: some(t) with b}
+ {lb: Some(t) with b}
}
fn ty_bot(_t: ty::t) -> cres<ty::t> {
ok(ty::mk_bot(self.infcx.tcx))
// LUB of those types:
let a_bnd = self.bnd(a_bounds), b_bnd = self.bnd(b_bounds);
match (a_bnd, b_bnd) {
- (some(a_ty), some(b_ty)) => {
+ (Some(a_ty), Some(b_ty)) => {
match self.infcx().try(|| c_ts(a_ty, b_ty) ) {
ok(t) => return ok(t),
err(_) => { /*fallthrough */ }
b.to_str(self.infcx()));
match self.bnd(a_bounds) {
- some(a_bnd) => {
+ Some(a_bnd) => {
// If a has an upper bound, return the LUB(a.ub, b)
debug!("bnd=some(%s)", a_bnd.to_str(self.infcx()));
return c_ts(a_bnd, b);
}
- none => {
+ None => {
// If a does not have an upper bound, make b the upper bound of a
// and then return b.
debug!("bnd=none");
super_tps(&self, as, bs)
}
- fn self_tys(a: option<ty::t>, b: option<ty::t>) -> cres<option<ty::t>> {
+ fn self_tys(a: Option<ty::t>, b: Option<ty::t>) -> cres<Option<ty::t>> {
super_self_tys(&self, a, b)
}
}
let vars = TwoRegions { a: a, b: b };
match combines.find(vars) {
- some(c) => ok(ty::re_var(c)),
- none => {
+ Some(c) => ok(ty::re_var(c)),
+ None => {
let c = self.new_region_var(span);
combines.insert(vars, c);
if self.in_snapshot() {
// if the free region's scope `f_id` is bigger than
// the scope region `s_id`, then the LUB is the free
// region itself:
- some(r_id) if r_id == f_id => f,
+ Some(r_id) if r_id == f_id => f,
// otherwise, we don't know what the free region is,
// so we must conservatively say the LUB is static:
// block.
let rm = self.tcx.region_map;
match region::nearest_common_ancestor(rm, a_id, b_id) {
- some(r_id) => ty::re_scope(r_id),
+ Some(r_id) => ty::re_scope(r_id),
_ => ty::re_static
}
}
// big the free region is precisely, the GLB is undefined.
let rm = self.tcx.region_map;
match region::nearest_common_ancestor(rm, f_id, s_id) {
- some(r_id) if r_id == f_id => ok(s),
+ Some(r_id) if r_id == f_id => ok(s),
_ => err(ty::terr_regions_no_overlap(b, a))
}
}
// it. Otherwise fail.
let rm = self.tcx.region_map;
match region::nearest_common_ancestor(rm, a_id, b_id) {
- some(r_id) if a_id == r_id => ok(ty::re_scope(b_id)),
- some(r_id) if b_id == r_id => ok(ty::re_scope(a_id)),
+ Some(r_id) if a_id == r_id => ok(ty::re_scope(b_id)),
+ Some(r_id) if b_id == r_id => ok(ty::re_scope(a_id)),
_ => err(ty::terr_regions_no_overlap(b, a))
}
}
type resolve_state_ = {
infcx: infer_ctxt,
modes: uint,
- mut err: option<fixup_err>,
+ mut err: Option<fixup_err>,
mut v_seen: ~[tv_vid]
};
fn resolver(infcx: infer_ctxt, modes: uint) -> resolve_state {
resolve_state_(@{infcx: infcx,
modes: modes,
- mut err: none,
+ mut err: None,
mut v_seen: ~[]})
}
}
fn resolve_type_chk(typ: ty::t) -> fres<ty::t> {
- self.err = none;
+ self.err = None;
debug!("Resolving %s (modes=%x)",
ty_to_str(self.infcx.tcx, typ),
let rty = indent(|| self.resolve_type(typ) );
assert vec::is_empty(self.v_seen);
match self.err {
- none => {
+ None => {
debug!("Resolved to %s (modes=%x)",
ty_to_str(self.infcx.tcx, rty),
self.modes);
return ok(rty);
}
- some(e) => return err(e)
+ Some(e) => return err(e)
}
}
fn resolve_region_chk(orig: ty::region) -> fres<ty::region> {
- self.err = none;
+ self.err = None;
let resolved = indent(|| self.resolve_region(orig) );
match self.err {
- none => ok(resolved),
- some(e) => err(e)
+ None => ok(resolved),
+ Some(e) => err(e)
}
}
fn assert_not_rvar(rid: region_vid, r: ty::region) {
match r {
ty::re_var(rid2) => {
- self.err = some(region_var_bound_by_region_var(rid, rid2));
+ self.err = Some(region_var_bound_by_region_var(rid, rid2));
}
_ => { }
}
fn resolve_ty_var(vid: tv_vid) -> ty::t {
if vec::contains(self.v_seen, vid) {
- self.err = some(cyclic_ty(vid));
+ self.err = Some(cyclic_ty(vid));
return ty::mk_var(self.infcx.tcx, vid);
} else {
vec::push(self.v_seen, vid);
let bounds = nde.possible_types;
let t1 = match bounds {
- { ub:_, lb:some(t) } if !type_is_bot(t) => self.resolve_type(t),
- { ub:some(t), lb:_ } => self.resolve_type(t),
- { ub:_, lb:some(t) } => self.resolve_type(t),
- { ub:none, lb:none } => {
+ { ub:_, lb:Some(t) } if !type_is_bot(t) => self.resolve_type(t),
+ { ub:Some(t), lb:_ } => self.resolve_type(t),
+ { ub:_, lb:Some(t) } => self.resolve_type(t),
+ { ub:None, lb:None } => {
if self.should(force_tvar) {
- self.err = some(unresolved_ty(vid));
+ self.err = Some(unresolved_ty(vid));
}
ty::mk_var(tcx, vid)
}
// If there's only one type in the set of possible types, then
// that's the answer.
match single_type_contained_in(self.infcx.tcx, pt) {
- some(t) => t,
- none => {
+ Some(t) => t,
+ None => {
if self.should(force_ivar) {
// As a last resort, default to int.
let ty = ty::mk_int(self.infcx.tcx);
// region variable.
let {fn_ty: a_fn_ty, _} = {
do replace_bound_regions_in_fn_ty(self.infcx.tcx, @nil,
- none, a) |br| {
+ None, a) |br| {
// N.B.: The name of the bound region doesn't have
// anything to do with the region variable that's created
// for it. The only thing we're doing with `br` here is
// fresh concrete region.
let {fn_ty: b_fn_ty, _} = {
do replace_bound_regions_in_fn_ty(self.infcx.tcx, @nil,
- none, b) |br| {
+ None, b) |br| {
// FIXME: eventually re_skolemized (issue #2263)
ty::re_bound(br)
}
super_tps(&self, as, bs)
}
- fn self_tys(a: option<ty::t>, b: option<ty::t>) -> cres<option<ty::t>> {
+ fn self_tys(a: Option<ty::t>, b: Option<ty::t>) -> cres<Option<ty::t>> {
super_self_tys(&self, a, b)
}
}
impl<V:copy to_str> bound<V>: to_str {
fn to_str(cx: infer_ctxt) -> ~str {
match self {
- some(v) => v.to_str(cx),
- none => ~"none"
+ Some(v) => v.to_str(cx),
+ None => ~"none"
}
}
}
let vid_u = vid.to_uint();
match vb.vals.find(vid_u) {
- none => {
+ None => {
self.tcx.sess.bug(fmt!("failed lookup of vid `%u`", vid_u));
}
- some(var_val) => {
+ Some(var_val) => {
match var_val {
redirect(vid) => {
let node = self.get(vb, vid);
let _r = indenter();
match (a, b) {
- (none, none) => ok(none),
- (some(_), none) => ok(a),
- (none, some(_)) => ok(b),
- (some(v_a), some(v_b)) => {
+ (None, None) => ok(None),
+ (Some(_), None) => ok(a),
+ (None, Some(_)) => ok(b),
+ (Some(v_a), Some(v_b)) => {
do merge_op(v_a, v_b).chain |v| {
- ok(some(v))
+ ok(Some(v))
}
}
}
// If both A's UB and B's LB have already been bound to types,
// see if we can make those types subtypes.
match (a_bounds.ub, b_bounds.lb) {
- (some(a_ub), some(b_lb)) => {
+ (Some(a_ub), Some(b_lb)) => {
let r = self.infcx().try(|| self.sub().tys(a_ub, b_lb));
match r {
ok(_ty) => return result::ok(()),
a_id.to_str(),
a_bounds.to_str(self.infcx()),
b.to_str(self.infcx()));
- let b_bounds = {lb: none, ub: some(b)};
+ let b_bounds = {lb: None, ub: Some(b)};
set_var_to_merged_bounds(self, a_id, a_bounds, b_bounds, nde_a.rank)
}
fn t_sub_var<C: combine>(self: &C, a: ty::t, b_id: ty::tv_vid) -> ures {
let vb = &self.infcx().ty_var_bindings;
- let a_bounds = {lb: some(a), ub: none};
+ let a_bounds = {lb: Some(a), ub: None};
let nde_b = self.infcx().get(vb, b_id);
let b_id = nde_b.root;
let b_bounds = nde_b.possible_types;
debug!("bnds(%s <: %s)", a.to_str(self.infcx()), b.to_str(self.infcx()));
do indent {
match (a, b) {
- (none, none) |
- (some(_), none) |
- (none, some(_)) => {
+ (None, None) |
+ (Some(_), None) |
+ (None, Some(_)) => {
uok()
}
- (some(t_a), some(t_b)) => {
+ (Some(t_a), Some(t_b)) => {
self.sub().tys(t_a, t_b).to_ures()
}
}
}
}
-enum type_rscope = option<ty::region_variance>;
+enum type_rscope = Option<ty::region_variance>;
impl type_rscope: region_scope {
fn anon_region(_span: span) -> result<ty::region, ~str> {
match *self {
- some(_) => result::ok(ty::re_bound(ty::br_self)),
- none => result::err(~"to use region types here, the containing \
+ Some(_) => result::ok(ty::re_bound(ty::br_self)),
+ None => result::err(~"to use region types here, the containing \
type must be declared with a region bound")
}
}
}
}
-fn bound_self_region(rp: option<ty::region_variance>) -> option<ty::region> {
+fn bound_self_region(rp: Option<ty::region_variance>) -> Option<ty::region> {
match rp {
- some(_) => some(ty::re_bound(ty::br_self)),
- none => none
+ Some(_) => Some(ty::re_bound(ty::br_self)),
+ None => None
}
}
fn local_rhs_span(l: @ast::local, def: span) -> span {
match l.node.init {
- some(i) => return i.expr.span,
+ Some(i) => return i.expr.span,
_ => return def
}
}
fn note_and_explain_region(cx: ctxt, prefix: ~str, region: ty::region) {
match explain_region_and_span(cx, region) {
- (str, some(span)) => {
+ (str, Some(span)) => {
cx.sess.span_note(
span,
fmt!("%s %s", prefix, str));
}
- (str, none) => {
+ (str, None) => {
cx.sess.note(
fmt!("%s %s", prefix, str));
}
fn explain_region_and_span(cx: ctxt, region: ty::region)
- -> (~str, option<span>)
+ -> (~str, Option<span>)
{
return match region {
re_scope(node_id) => {
match cx.items.find(node_id) {
- some(ast_map::node_block(blk)) => {
+ Some(ast_map::node_block(blk)) => {
explain_span(cx, ~"block", blk.span)
}
- some(ast_map::node_expr(expr)) => {
+ Some(ast_map::node_expr(expr)) => {
match expr.node {
ast::expr_call(*) => explain_span(cx, ~"call", expr.span),
ast::expr_match(*) => explain_span(cx, ~"alt", expr.span),
_ => explain_span(cx, ~"expression", expr.span)
}
}
- some(_) | none => {
+ Some(_) | None => {
// this really should not happen
(fmt!("unknown scope: %d. Please report a bug.", node_id),
- none)
+ None)
}
}
}
};
match cx.items.find(id) {
- some(ast_map::node_block(blk)) => {
+ Some(ast_map::node_block(blk)) => {
let (msg, opt_span) = explain_span(cx, ~"block", blk.span);
(fmt!("%s %s", prefix, msg), opt_span)
}
- some(_) | none => {
+ Some(_) | None => {
// this really should not happen
- (fmt!("%s node %d", prefix, id), none)
+ (fmt!("%s node %d", prefix, id), None)
}
}
}
- re_static => { (~"the static lifetime", none) }
+ re_static => { (~"the static lifetime", None) }
// I believe these cases should not occur (except when debugging,
// perhaps)
re_var(_) | re_bound(_) => {
- (fmt!("lifetime %?", region), none)
+ (fmt!("lifetime %?", region), None)
}
};
fn explain_span(cx: ctxt, heading: ~str, span: span)
- -> (~str, option<span>)
+ -> (~str, Option<span>)
{
let lo = codemap::lookup_char_pos_adj(cx.sess.codemap, span.lo);
- (fmt!("the %s at %u:%u", heading, lo.line, lo.col), some(span))
+ (fmt!("the %s at %u:%u", heading, lo.line, lo.col), Some(span))
}
}
fn re_scope_id_to_str(cx: ctxt, node_id: ast::node_id) -> ~str {
match cx.items.find(node_id) {
- some(ast_map::node_block(blk)) => {
+ Some(ast_map::node_block(blk)) => {
fmt!("<block at %s>",
codemap::span_to_str(blk.span, cx.sess.codemap))
}
- some(ast_map::node_expr(expr)) => {
+ Some(ast_map::node_expr(expr)) => {
match expr.node {
ast::expr_call(*) => {
fmt!("<call at %s>",
}
}
}
- none => {
+ None => {
fmt!("<unknown-%d>", node_id)
}
_ => { cx.sess.bug(
modestr + ty_to_str(cx, ty)
}
fn fn_to_str(cx: ctxt, purity: ast::purity, proto: ty::fn_proto,
- ident: option<ast::ident>,
+ ident: Option<ast::ident>,
inputs: ~[arg], output: t, cf: ast::ret_style) -> ~str {
let mut s;
s += proto_ty_to_str(cx, proto);
match ident {
- some(i) => { s += ~" "; s += cx.sess.str_of(i); }
+ Some(i) => { s += ~" "; s += cx.sess.str_of(i); }
_ => { }
}
s += ~"(";
}
fn method_to_str(cx: ctxt, m: method) -> ~str {
return fn_to_str(
- cx, m.fty.purity, m.fty.proto, some(m.ident), m.fty.inputs,
+ cx, m.fty.purity, m.fty.proto, Some(m.ident), m.fty.inputs,
m.fty.output, m.fty.ret_style) + ~";";
}
fn field_to_str(cx: ctxt, f: field) -> ~str {
~"(" + str::connect(strs, ~",") + ~")"
}
ty_fn(f) => {
- fn_to_str(cx, f.purity, f.proto, none, f.inputs,
+ fn_to_str(cx, f.purity, f.proto, None, f.inputs,
f.output, f.ret_style)
}
ty_var(v) => v.to_str(),
fn parameterized(cx: ctxt,
base: ~str,
- self_r: option<ty::region>,
+ self_r: Option<ty::region>,
tps: ~[ty::t]) -> ~str {
let r_str = match self_r {
- none => ~"",
- some(r) => {
+ None => ~"",
+ Some(r) => {
fmt!("/%s", region_to_str(cx, r))
}
};
fn note(msg: ~str) { self.inner.note(msg) }
fn bug(msg: ~str) -> ! { self.inner.bug(msg) }
fn unimpl(msg: ~str) -> ! { self.inner.unimpl(msg) }
- fn emit(cmsp: option<(codemap::codemap, codemap::span)>,
+ fn emit(cmsp: Option<(codemap::codemap, codemap::span)>,
msg: ~str, lvl: diagnostic::level) {
self.inner.emit(cmsp, msg, lvl)
}
}
- let emitter = fn@(cmsp: option<(codemap::codemap, codemap::span)>,
+ let emitter = fn@(cmsp: Option<(codemap::codemap, codemap::span)>,
msg: ~str, lvl: diagnostic::level) {
diagnostic::emit(cmsp, msg, lvl);
};
- let inner_handler = diagnostic::mk_handler(some(emitter));
+ let inner_handler = diagnostic::mk_handler(Some(emitter));
let handler = {
inner: inner_handler,
};
export parse_hidden;
type crate_attrs = {
- name: option<~str>
+ name: Option<~str>
};
#[cfg(test)]
import syntax::codemap;
import syntax::diagnostic;
- let parse_sess = syntax::parse::new_parse_sess(none);
+ let parse_sess = syntax::parse::new_parse_sess(None);
let parser = parse::new_parser_from_source_str(
parse_sess, ~[], ~"-", codemap::fss_none, @source);
fn doc_meta(
attrs: ~[ast::attribute]
-) -> option<@ast::meta_item> {
+) -> Option<@ast::meta_item> {
/*!
* Given a vec of attributes, extract the meta_items contained in the \
if vec::len(doc_metas) != 1u {
warn!("ignoring %u doc attributes", vec::len(doc_metas) - 1u);
}
- some(doc_metas[0])
+ Some(doc_metas[0])
} else {
- none
+ None
}
}
let source = ~"#[link(name = \"snuggles\")]";
let attrs = test::parse_attributes(source);
let attrs = parse_crate(attrs);
- assert attrs.name == some(~"snuggles");
+ assert attrs.name == Some(~"snuggles");
}
#[test]
let source = ~"";
let attrs = test::parse_attributes(source);
let attrs = parse_crate(attrs);
- assert attrs.name == none;
+ assert attrs.name == None;
}
#[test]
let source = ~"#[link(whatever)]";
let attrs = test::parse_attributes(source);
let attrs = parse_crate(attrs);
- assert attrs.name == none;
+ assert attrs.name == None;
}
-fn parse_desc(attrs: ~[ast::attribute]) -> option<~str> {
+fn parse_desc(attrs: ~[ast::attribute]) -> Option<~str> {
match doc_meta(attrs) {
- some(meta) => {
+ Some(meta) => {
attr::get_meta_item_value_str(meta)
}
- none => none
+ None => None
}
}
let source = ~"";
let attrs = test::parse_attributes(source);
let attrs = parse_desc(attrs);
- assert attrs == none;
+ assert attrs == None;
}
#[test]
let source = ~"#[doc = \"basic\"]";
let attrs = test::parse_attributes(source);
let attrs = parse_desc(attrs);
- assert attrs == some(~"basic");
+ assert attrs == Some(~"basic");
}
fn parse_hidden(attrs: ~[ast::attribute]) -> bool {
match doc_meta(attrs) {
- some(meta) => {
+ Some(meta) => {
match attr::get_meta_item_list(meta) {
- some(metas) => {
+ Some(metas) => {
let hiddens = attr::find_meta_items_by_name(metas, ~"hidden");
vec::is_not_empty(hiddens)
}
- none => false
+ None => false
}
}
- none => false
+ None => false
}
}
#[test]
fn should_should_extract_mod_attributes() {
let doc = test::mk_doc(~"#[doc = \"test\"] mod a { }");
- assert doc.cratemod().mods()[0].desc() == some(~"test");
+ assert doc.cratemod().mods()[0].desc() == Some(~"test");
}
#[test]
fn should_extract_top_mod_attributes() {
let doc = test::mk_doc(~"#[doc = \"test\"];");
- assert doc.cratemod().desc() == some(~"test");
+ assert doc.cratemod().desc() == Some(~"test");
}
#[test]
fn should_extract_foreign_mod_attributes() {
let doc = test::mk_doc(~"#[doc = \"test\"] extern mod a { }");
- assert doc.cratemod().nmods()[0].desc() == some(~"test");
+ assert doc.cratemod().nmods()[0].desc() == Some(~"test");
}
#[test]
fn should_extract_foreign_fn_attributes() {
let doc = test::mk_doc(~"extern mod a { #[doc = \"test\"] fn a(); }");
- assert doc.cratemod().nmods()[0].fns[0].desc() == some(~"test");
+ assert doc.cratemod().nmods()[0].fns[0].desc() == Some(~"test");
}
#[test]
fn should_extract_fn_attributes() {
let doc = test::mk_doc(~"#[doc = \"test\"] fn a() -> int { }");
- assert doc.cratemod().fns()[0].desc() == some(~"test");
+ assert doc.cratemod().fns()[0].desc() == Some(~"test");
}
fn fold_enum(
fn should_extract_enum_docs() {
let doc = test::mk_doc(~"#[doc = \"b\"]\
enum a { v }");
- assert doc.cratemod().enums()[0].desc() == some(~"b");
+ assert doc.cratemod().enums()[0].desc() == Some(~"b");
}
#[test]
fn should_extract_variant_docs() {
let doc = test::mk_doc(~"enum a { #[doc = \"c\"] v }");
- assert doc.cratemod().enums()[0].variants[0].desc == some(~"c");
+ assert doc.cratemod().enums()[0].variants[0].desc == Some(~"c");
}
fn fold_trait(
) -> ~[doc::methoddoc] {
// Create an assoc list from method name to attributes
- let attrs: ~[(~str, option<~str>)] = do astsrv::exec(srv) |ctxt| {
+ let attrs: ~[(~str, Option<~str>)] = do astsrv::exec(srv) |ctxt| {
match ctxt.ast_map.get(item_id) {
ast_map::node_item(@{
node: ast::item_trait(_, _, methods), _
#[test]
fn should_extract_trait_docs() {
let doc = test::mk_doc(~"#[doc = \"whatever\"] trait i { fn a(); }");
- assert doc.cratemod().traits()[0].desc() == some(~"whatever");
+ assert doc.cratemod().traits()[0].desc() == Some(~"whatever");
}
#[test]
#[doc = \"desc\"]\
fn f(a: bool) -> bool;\
}");
- assert doc.cratemod().traits()[0].methods[0].desc == some(~"desc");
+ assert doc.cratemod().traits()[0].methods[0].desc == Some(~"desc");
}
fn should_extract_impl_docs() {
let doc = test::mk_doc(
~"#[doc = \"whatever\"] impl int { fn a() { } }");
- assert doc.cratemod().impls()[0].desc() == some(~"whatever");
+ assert doc.cratemod().impls()[0].desc() == Some(~"whatever");
}
#[test]
#[doc = \"desc\"]\
fn f(a: bool) -> bool { }\
}");
- assert doc.cratemod().impls()[0].methods[0].desc == some(~"desc");
+ assert doc.cratemod().impls()[0].methods[0].desc == Some(~"desc");
}
#[cfg(test)]
output_dir: Path,
output_format: output_format,
output_style: output_style,
- pandoc_cmd: option<~str>
+ pandoc_cmd: Option<~str>
};
fn opt_output_dir() -> ~str { ~"output-dir" }
output_dir: Path("."),
output_format: pandoc_html,
output_style: doc_per_mod,
- pandoc_cmd: none
+ pandoc_cmd: None
}
}
fn maybe_find_pandoc(
config: config,
- maybe_pandoc_cmd: option<~str>,
+ maybe_pandoc_cmd: Option<~str>,
program_output: program_output
-) -> result<option<~str>, ~str> {
+) -> result<Option<~str>, ~str> {
if config.output_format != pandoc_html {
return result::ok(maybe_pandoc_cmd);
}
let possible_pandocs = match maybe_pandoc_cmd {
- some(pandoc_cmd) => ~[pandoc_cmd],
- none => {
+ Some(pandoc_cmd) => ~[pandoc_cmd],
+ None => {
~[~"pandoc"] + match os::homedir() {
- some(dir) => {
+ Some(dir) => {
~[dir.push_rel(&Path(".cabal/bin/pandoc")).to_str()]
}
- none => ~[]
+ None => ~[]
}
}
};
status: 0, out: ~"pandoc 1.8.2.1", err: ~""
}
};
- let result = maybe_find_pandoc(config, none, mock_program_output);
- assert result == result::ok(some(~"pandoc"));
+ let result = maybe_find_pandoc(config, None, mock_program_output);
+ assert result == result::ok(Some(~"pandoc"));
}
#[test]
status: 1, out: ~"", err: ~""
}
};
- let result = maybe_find_pandoc(config, none, mock_program_output);
+ let result = maybe_find_pandoc(config, None, mock_program_output);
assert result == result::err(~"couldn't find pandoc");
}
let config = test::parse_config(~[
~"rustdoc", ~"crate.rc", ~"--pandoc-cmd", ~"panda-bear-doc"
]);
- assert result::get(config).pandoc_cmd == some(~"panda-bear-doc");
+ assert result::get(config).pandoc_cmd == Some(~"panda-bear-doc");
}
#[test]
fn should_set_pandoc_command_when_using_pandoc() {
let config = test::parse_config(~[~"rustdoc", ~"crate.rc"]);
- assert result::get(config).pandoc_cmd == some(~"pandoc");
+ assert result::get(config).pandoc_cmd == Some(~"pandoc");
}
#[test]
fn should_promote_desc() {
let doc = test::mk_doc(~"#[doc = \"desc\"] mod m { }");
- assert doc.cratemod().mods()[0].brief() == some(~"desc");
+ assert doc.cratemod().mods()[0].brief() == Some(~"desc");
}
#[test]
fn should_promote_trait_method_desc() {
let doc = test::mk_doc(~"trait i { #[doc = \"desc\"] fn a(); }");
- assert doc.cratemod().traits()[0].methods[0].brief == some(~"desc");
+ assert doc.cratemod().traits()[0].methods[0].brief == Some(~"desc");
}
#[test]
fn should_promote_impl_method_desc() {
let doc = test::mk_doc(
~"impl int { #[doc = \"desc\"] fn a() { } }");
- assert doc.cratemod().impls()[0].methods[0].brief == some(~"desc");
+ assert doc.cratemod().impls()[0].methods[0].brief == Some(~"desc");
}
#[cfg(test)]
}
}
-fn extract(desc: option<~str>) -> option<~str> {
+fn extract(desc: Option<~str>) -> Option<~str> {
if option::is_none(desc) {
- return none
+ return None
}
parse_desc(option::get(desc))
}
-fn parse_desc(desc: ~str) -> option<~str> {
+fn parse_desc(desc: ~str) -> Option<~str> {
const max_brief_len: uint = 120u;
match first_sentence(desc) {
- some(first_sentence) => {
+ Some(first_sentence) => {
if str::len(first_sentence) <= max_brief_len {
- some(first_sentence)
+ Some(first_sentence)
} else {
- none
+ None
}
}
- none => none
+ None => None
}
}
-fn first_sentence(s: ~str) -> option<~str> {
+fn first_sentence(s: ~str) -> Option<~str> {
let paras = paragraphs(s);
if vec::is_not_empty(paras) {
let first_para = vec::head(paras);
- some(str::replace(first_sentence_(first_para), ~"\n", ~" "))
+ Some(str::replace(first_sentence_(first_para), ~"\n", ~" "))
} else {
- none
+ None
}
}
}
};
match idx {
- some(idx) if idx > 2u => {
+ Some(idx) if idx > 2u => {
str::slice(s, 0u, idx - 1u)
}
_ => {
#[test]
fn should_promote_short_descs() {
- let desc = some(~"desc");
+ let desc = Some(~"desc");
let brief = extract(desc);
assert brief == desc;
}
#[test]
fn should_not_promote_long_descs() {
- let desc = some(~"Warkworth Castle is a ruined medieval building
+ let desc = Some(~"Warkworth Castle is a ruined medieval building
in the town of the same name in the English county of Northumberland,
and the town and castle occupy a loop of the River Coquet, less than a mile
from England's north-east coast. When the castle was founded is uncertain,
King Henry II of England when he took control of England'snorthern
counties.");
let brief = extract(desc);
- assert brief == none;
+ assert brief == None;
}
#[test]
fn should_promote_first_sentence() {
- let desc = some(~"Warkworth Castle is a ruined medieval building
+ let desc = Some(~"Warkworth Castle is a ruined medieval building
in the town. of the same name in the English county of Northumberland,
and the town and castle occupy a loop of the River Coquet, less than a mile
from England's north-east coast. When the castle was founded is uncertain,
King Henry II of England when he took control of England'snorthern
counties.");
let brief = extract(desc);
- assert brief == some(
+ assert brief == Some(
~"Warkworth Castle is a ruined medieval building in the town");
}
#[test]
fn should_not_consider_double_period_to_end_sentence() {
- let desc = some(~"Warkworth..Castle is a ruined medieval building
+ let desc = Some(~"Warkworth..Castle is a ruined medieval building
in the town. of the same name in the English county of Northumberland,
and the town and castle occupy a loop of the River Coquet, less than a mile
from England's north-east coast. When the castle was founded is uncertain,
King Henry II of England when he took control of England'snorthern
counties.");
let brief = extract(desc);
- assert brief == some(
+ assert brief == Some(
~"Warkworth..Castle is a ruined medieval building in the town");
}
#[test]
fn should_not_consider_triple_period_to_end_sentence() {
- let desc = some(~"Warkworth... Castle is a ruined medieval building
+ let desc = Some(~"Warkworth... Castle is a ruined medieval building
in the town. of the same name in the English county of Northumberland,
and the town and castle occupy a loop of the River Coquet, less than a mile
from England's north-east coast. When the castle was founded is uncertain,
King Henry II of England when he took control of England'snorthern
counties.");
let brief = extract(desc);
- assert brief == some(
+ assert brief == Some(
~"Warkworth... Castle is a ruined medieval building in the town");
}
id: ast_id,
name: ~str,
path: ~[~str],
- brief: option<~str>,
- desc: option<~str>,
+ brief: Option<~str>,
+ desc: Option<~str>,
sections: ~[section],
// Indicates that this node is a reexport of a different item
reexport: bool
type simpleitemdoc = {
item: itemdoc,
- sig: option<~str>
+ sig: Option<~str>
};
type moddoc_ = {
item: itemdoc,
items: ~[itemtag],
- index: option<index>
+ index: Option<index>
};
enum moddoc {
type nmoddoc = {
item: itemdoc,
fns: ~[fndoc],
- index: option<index>
+ index: Option<index>
};
type constdoc = simpleitemdoc;
type variantdoc = {
name: ~str,
- desc: option<~str>,
- sig: option<~str>
+ desc: Option<~str>,
+ sig: Option<~str>
};
type traitdoc = {
type methoddoc = {
name: ~str,
- brief: option<~str>,
- desc: option<~str>,
+ brief: Option<~str>,
+ desc: Option<~str>,
sections: ~[section],
- sig: option<~str>,
+ sig: Option<~str>,
implementation: implementation,
};
type impldoc = {
item: itemdoc,
trait_types: ~[~str],
- self_ty: option<~str>,
+ self_ty: Option<~str>,
methods: ~[methoddoc]
};
type index_entry = {
kind: ~str,
name: ~str,
- brief: option<~str>,
+ brief: Option<~str>,
link: ~str
};
impl doc {
fn cratedoc() -> cratedoc {
- option::get(vec::foldl(none, self.pages, |_m, page| {
+ option::get(vec::foldl(None, self.pages, |_m, page| {
match page {
- doc::cratepage(doc) => some(doc),
- _ => none
+ doc::cratepage(doc) => Some(doc),
+ _ => None
}
}))
}
fn mods() -> ~[moddoc] {
do vec::filter_map(self.items) |itemtag| {
match itemtag {
- modtag(moddoc) => some(moddoc),
- _ => none
+ modtag(moddoc) => Some(moddoc),
+ _ => None
}
}
}
fn nmods() -> ~[nmoddoc] {
do vec::filter_map(self.items) |itemtag| {
match itemtag {
- nmodtag(nmoddoc) => some(nmoddoc),
- _ => none
+ nmodtag(nmoddoc) => Some(nmoddoc),
+ _ => None
}
}
}
fn fns() -> ~[fndoc] {
do vec::filter_map(self.items) |itemtag| {
match itemtag {
- fntag(fndoc) => some(fndoc),
- _ => none
+ fntag(fndoc) => Some(fndoc),
+ _ => None
}
}
}
fn consts() -> ~[constdoc] {
do vec::filter_map(self.items) |itemtag| {
match itemtag {
- consttag(constdoc) => some(constdoc),
- _ => none
+ consttag(constdoc) => Some(constdoc),
+ _ => None
}
}
}
fn enums() -> ~[enumdoc] {
do vec::filter_map(self.items) |itemtag| {
match itemtag {
- enumtag(enumdoc) => some(enumdoc),
- _ => none
+ enumtag(enumdoc) => Some(enumdoc),
+ _ => None
}
}
}
fn traits() -> ~[traitdoc] {
do vec::filter_map(self.items) |itemtag| {
match itemtag {
- traittag(traitdoc) => some(traitdoc),
- _ => none
+ traittag(traitdoc) => Some(traitdoc),
+ _ => None
}
}
}
fn impls() -> ~[impldoc] {
do vec::filter_map(self.items) |itemtag| {
match itemtag {
- impltag(impldoc) => some(impldoc),
- _ => none
+ impltag(impldoc) => Some(impldoc),
+ _ => None
}
}
}
fn types() -> ~[tydoc] {
do vec::filter_map(self.items) |itemtag| {
match itemtag {
- tytag(tydoc) => some(tydoc),
- _ => none
+ tytag(tydoc) => Some(tydoc),
+ _ => None
}
}
}
fn mods() -> ~[moddoc] {
do vec::filter_map(self) |page| {
match page {
- itempage(modtag(moddoc)) => some(moddoc),
- _ => none
+ itempage(modtag(moddoc)) => Some(moddoc),
+ _ => None
}
}
}
fn nmods() -> ~[nmoddoc] {
do vec::filter_map(self) |page| {
match page {
- itempage(nmodtag(nmoddoc)) => some(nmoddoc),
- _ => none
+ itempage(nmodtag(nmoddoc)) => Some(nmoddoc),
+ _ => None
}
}
}
fn fns() -> ~[fndoc] {
do vec::filter_map(self) |page| {
match page {
- itempage(fntag(fndoc)) => some(fndoc),
- _ => none
+ itempage(fntag(fndoc)) => Some(fndoc),
+ _ => None
}
}
}
fn consts() -> ~[constdoc] {
do vec::filter_map(self) |page| {
match page {
- itempage(consttag(constdoc)) => some(constdoc),
- _ => none
+ itempage(consttag(constdoc)) => Some(constdoc),
+ _ => None
}
}
}
fn enums() -> ~[enumdoc] {
do vec::filter_map(self) |page| {
match page {
- itempage(enumtag(enumdoc)) => some(enumdoc),
- _ => none
+ itempage(enumtag(enumdoc)) => Some(enumdoc),
+ _ => None
}
}
}
fn traits() -> ~[traitdoc] {
do vec::filter_map(self) |page| {
match page {
- itempage(traittag(traitdoc)) => some(traitdoc),
- _ => none
+ itempage(traittag(traitdoc)) => Some(traitdoc),
+ _ => None
}
}
}
fn impls() -> ~[impldoc] {
do vec::filter_map(self) |page| {
match page {
- itempage(impltag(impldoc)) => some(impldoc),
- _ => none
+ itempage(impltag(impldoc)) => Some(impldoc),
+ _ => None
}
}
}
fn types() -> ~[tydoc] {
do vec::filter_map(self) |page| {
match page {
- itempage(tytag(tydoc)) => some(tydoc),
- _ => none
+ itempage(tytag(tydoc)) => Some(tydoc),
+ _ => None
}
}
}
pure fn id() -> ast_id;
pure fn name() -> ~str;
pure fn path() -> ~[~str];
- pure fn brief() -> option<~str>;
- pure fn desc() -> option<~str>;
+ pure fn brief() -> Option<~str>;
+ pure fn desc() -> Option<~str>;
pure fn sections() -> ~[section];
}
self.item().path
}
- pure fn brief() -> option<~str> {
+ pure fn brief() -> Option<~str> {
self.item().brief
}
- pure fn desc() -> option<~str> {
+ pure fn desc() -> Option<~str> {
self.item().desc
}
id: id,
name: name,
path: ~[],
- brief: none,
- desc: none,
+ brief: None,
+ desc: None,
sections: ~[],
reexport: false
}
let itemdoc = mk_itemdoc(item.id, to_str(item.ident));
match item.node {
ast::item_mod(m) => {
- some(doc::modtag(
+ Some(doc::modtag(
moddoc_from_mod(itemdoc, m)
))
}
ast::item_foreign_mod(nm) => {
- some(doc::nmodtag(
+ Some(doc::nmodtag(
nmoddoc_from_mod(itemdoc, nm)
))
}
ast::item_fn(*) => {
- some(doc::fntag(
+ Some(doc::fntag(
fndoc_from_fn(itemdoc)
))
}
ast::item_const(_, _) => {
- some(doc::consttag(
+ Some(doc::consttag(
constdoc_from_const(itemdoc)
))
}
ast::item_enum(enum_definition, _) => {
- some(doc::enumtag(
+ Some(doc::enumtag(
enumdoc_from_enum(itemdoc, enum_definition.variants)
))
}
ast::item_trait(_, _, methods) => {
- some(doc::traittag(
+ Some(doc::traittag(
traitdoc_from_trait(itemdoc, methods)
))
}
ast::item_impl(_, _, _, methods) => {
- some(doc::impltag(
+ Some(doc::impltag(
impldoc_from_impl(itemdoc, methods)
))
}
ast::item_ty(_, _) => {
- some(doc::tytag(
+ Some(doc::tytag(
tydoc_from_ty(itemdoc)
))
}
- _ => none
+ _ => None
}
},
- index: none
+ index: None
})
}
{
item: itemdoc,
fns: fns,
- index: none
+ index: None
}
}
fn fndoc_from_fn(itemdoc: doc::itemdoc) -> doc::fndoc {
{
item: itemdoc,
- sig: none
+ sig: None
}
}
fn constdoc_from_const(itemdoc: doc::itemdoc) -> doc::constdoc {
{
item: itemdoc,
- sig: none
+ sig: None
}
}
{
name: to_str(variant.node.name),
- desc: none,
- sig: none
+ desc: None,
+ sig: None
}
}
ast::required(ty_m) => {
{
name: to_str(ty_m.ident),
- brief: none,
- desc: none,
+ brief: None,
+ desc: None,
sections: ~[],
- sig: none,
+ sig: None,
implementation: doc::required,
}
}
ast::provided(m) => {
{
name: to_str(m.ident),
- brief: none,
- desc: none,
+ brief: None,
+ desc: None,
sections: ~[],
- sig: none,
+ sig: None,
implementation: doc::provided,
}
}
{
item: itemdoc,
trait_types: ~[],
- self_ty: none,
+ self_ty: None,
methods: do vec::map(methods) |method| {
{
name: to_str(method.ident),
- brief: none,
- desc: none,
+ brief: None,
+ desc: None,
sections: ~[],
- sig: none,
+ sig: None,
implementation: doc::provided,
}
}
) -> doc::tydoc {
{
item: itemdoc,
- sig: none
+ sig: None
}
}
let doc = fold::default_any_fold_mod(fold, doc);
doc::moddoc_({
- index: some(build_mod_index(doc, fold.ctxt))
+ index: Some(build_mod_index(doc, fold.ctxt))
with *doc
})
}
let doc = fold::default_any_fold_nmod(fold, doc);
{
- index: some(build_nmod_index(doc, fold.ctxt))
+ index: Some(build_nmod_index(doc, fold.ctxt))
with doc
}
}
assert option::get(doc.cratemod().index).entries[0] == {
kind: ~"Module",
name: ~"a",
- brief: none,
+ brief: None,
link: ~"#module-a"
};
assert option::get(doc.cratemod().index).entries[1] == {
kind: ~"Function",
name: ~"b",
- brief: none,
+ brief: None,
link: ~"#function-b"
};
}
assert option::get(doc.cratemod().index).entries[0] == {
kind: ~"Module",
name: ~"a",
- brief: none,
+ brief: None,
link: ~"a.html"
};
assert option::get(doc.cratemod().index).entries[1] == {
kind: ~"Function",
name: ~"b",
- brief: none,
+ brief: None,
link: ~"#function-b"
};
}
assert option::get(doc.cratemod().index).entries[0] == {
kind: ~"Foreign module",
name: ~"a",
- brief: none,
+ brief: None,
link: ~"a.html"
};
}
~"#[doc = \"test\"] mod a { }"
);
assert option::get(doc.cratemod().index).entries[0].brief
- == some(~"test");
+ == Some(~"test");
}
#[test]
assert option::get(doc.cratemod().nmods()[0].index).entries[0] == {
kind: ~"Function",
name: ~"b",
- brief: none,
+ brief: None,
link: ~"#function-b"
};
}
fn write_common(
ctxt: ctxt,
- desc: option<~str>,
+ desc: Option<~str>,
sections: ~[doc::section]
) {
write_desc(ctxt, desc);
fn write_desc(
ctxt: ctxt,
- desc: option<~str>
+ desc: Option<~str>
) {
match desc {
- some(desc) => {
+ Some(desc) => {
ctxt.w.write_line(desc);
ctxt.w.write_line(~"");
}
- none => ()
+ None => ()
}
}
fn write_fnlike(
ctxt: ctxt,
- sig: option<~str>,
- desc: option<~str>,
+ sig: Option<~str>,
+ desc: Option<~str>,
sections: ~[doc::section]
) {
write_sig(ctxt, sig);
write_common(ctxt, desc, sections);
}
-fn write_sig(ctxt: ctxt, sig: option<~str>) {
+fn write_sig(ctxt: ctxt, sig: Option<~str>) {
match sig {
- some(sig) => {
+ Some(sig) => {
ctxt.w.write_line(code_block_indent(sig));
ctxt.w.write_line(~"");
}
- none => fail ~"unimplemented"
+ None => fail ~"unimplemented"
}
}
doc::cratepage({
topmod: doc::moddoc_({
items: ~[doc::fntag({
- sig: some(~"line 1\nline 2")
+ sig: Some(~"line 1\nline 2")
with doc.cratemod().fns()[0]
})]
with *doc.cratemod()
assert option::is_some(doc.sig);
let sig = option::get(doc.sig);
match doc.desc {
- some(desc) => {
+ Some(desc) => {
ctxt.w.write_line(fmt!("* `%s` - %s", sig, desc));
}
- none => {
+ None => {
ctxt.w.write_line(fmt!("* `%s`", sig));
}
}
let pipe_out = os::pipe();
let pipe_err = os::pipe();
let pid = run::spawn_process(
- pandoc_cmd, pandoc_args, &none, &none,
+ pandoc_cmd, pandoc_args, &None, &None,
pipe_in.in, pipe_out.out, pipe_err.out);
let writer = io::fd_writer(pipe_in.out, false);
comm::recv(result_port)
}
-type page_port = comm::Port<option<doc::page>>;
-type page_chan = comm::Chan<option<doc::page>>;
+type page_port = comm::Port<Option<doc::page>>;
+type page_chan = comm::Chan<Option<doc::page>>;
fn make_doc_from_pages(page_port: page_port) -> doc::doc {
let mut pages = ~[];
});
fold.fold_doc(fold, doc);
- comm::send(page_chan, none);
+ comm::send(page_chan, None);
}
fn fold_crate(
with doc
});
- comm::send(fold.ctxt, some(page));
+ comm::send(fold.ctxt, Some(page));
doc
}
let doc = strip_mod(doc);
let page = doc::itempage(doc::modtag(doc));
- comm::send(fold.ctxt, some(page));
+ comm::send(fold.ctxt, Some(page));
}
doc
) -> doc::nmoddoc {
let doc = fold::default_seq_fold_nmod(fold, doc);
let page = doc::itempage(doc::nmodtag(doc));
- comm::send(fold.ctxt, some(page));
+ comm::send(fold.ctxt, Some(page));
return doc;
}
fn from_file(file: &Path) -> @ast::crate {
parse::parse_crate_from_file(
- file, ~[], parse::new_parse_sess(none))
+ file, ~[], parse::new_parse_sess(None))
}
fn from_str(source: ~str) -> @ast::crate {
parse::parse_crate_from_source_str(
- ~"-", @source, ~[], parse::new_parse_sess(none))
+ ~"-", @source, ~[], parse::new_parse_sess(None))
}
fn from_file_sess(sess: session::session, file: &Path) -> @ast::crate {
with doc.cratemod().item
},
items: ~[],
- index: none
+ index: None
})
})
]
with doc.cratemod().item
},
items: ~[],
- index: none
+ index: None
})
})
]
}
}
-fn sectionalize(desc: option<~str>) -> (option<~str>, ~[doc::section]) {
+fn sectionalize(desc: Option<~str>) -> (Option<~str>, ~[doc::section]) {
/*!
* Take a description of the form
*/
if option::is_none(desc) {
- return (none, ~[]);
+ return (None, ~[]);
}
let lines = str::lines(option::get(desc));
- let mut new_desc = none::<~str>;
- let mut current_section = none;
+ let mut new_desc = None::<~str>;
+ let mut current_section = None;
let mut sections = ~[];
for lines.each |line| {
match parse_header(line) {
- some(header) => {
+ Some(header) => {
if option::is_some(current_section) {
sections += ~[option::get(current_section)];
}
- current_section = some({
+ current_section = Some({
header: header,
body: ~""
});
}
- none => {
+ None => {
match copy current_section {
- some(section) => {
- current_section = some({
+ Some(section) => {
+ current_section = Some({
body: section.body + ~"\n" + line
with section
});
}
- none => {
+ None => {
new_desc = match new_desc {
- some(desc) => {
- some(desc + ~"\n" + line)
+ Some(desc) => {
+ Some(desc + ~"\n" + line)
}
- none => {
- some(line)
+ None => {
+ Some(line)
}
};
}
(new_desc, sections)
}
-fn parse_header(line: ~str) -> option<~str> {
+fn parse_header(line: ~str) -> Option<~str> {
if str::starts_with(line, ~"# ") {
- some(str::slice(line, 2u, str::len(line)))
+ Some(str::slice(line, 2u, str::len(line)))
} else {
- none
+ None
}
}
# Header\n\
Body\"]\
mod a { }");
- assert doc.cratemod().mods()[0].desc() == none;
+ assert doc.cratemod().mods()[0].desc() == None;
}
#[test]
fold.fold_doc(fold, doc)
}
-fn maybe_apply_op(op: op, s: option<~str>) -> option<~str> {
+fn maybe_apply_op(op: op, s: Option<~str>) -> Option<~str> {
option::map(s, |s| op(s) )
}
#[test]
fn should_execute_op_on_enum_brief() {
let doc = test::mk_doc(~"#[doc = \" a \"] enum a { b }");
- assert doc.cratemod().enums()[0].brief() == some(~"a");
+ assert doc.cratemod().enums()[0].brief() == Some(~"a");
}
#[test]
fn should_execute_op_on_enum_desc() {
let doc = test::mk_doc(~"#[doc = \" a \"] enum a { b }");
- assert doc.cratemod().enums()[0].desc() == some(~"a");
+ assert doc.cratemod().enums()[0].desc() == Some(~"a");
}
#[test]
fn should_execute_op_on_variant_desc() {
let doc = test::mk_doc(~"enum a { #[doc = \" a \"] b }");
- assert doc.cratemod().enums()[0].variants[0].desc == some(~"a");
+ assert doc.cratemod().enums()[0].variants[0].desc == Some(~"a");
}
#[test]
fn should_execute_op_on_trait_brief() {
let doc = test::mk_doc(
~"#[doc = \" a \"] trait i { fn a(); }");
- assert doc.cratemod().traits()[0].brief() == some(~"a");
+ assert doc.cratemod().traits()[0].brief() == Some(~"a");
}
#[test]
fn should_execute_op_on_trait_desc() {
let doc = test::mk_doc(
~"#[doc = \" a \"] trait i { fn a(); }");
- assert doc.cratemod().traits()[0].desc() == some(~"a");
+ assert doc.cratemod().traits()[0].desc() == Some(~"a");
}
#[test]
fn should_execute_op_on_trait_method_brief() {
let doc = test::mk_doc(
~"trait i { #[doc = \" a \"] fn a(); }");
- assert doc.cratemod().traits()[0].methods[0].brief == some(~"a");
+ assert doc.cratemod().traits()[0].methods[0].brief == Some(~"a");
}
#[test]
fn should_execute_op_on_trait_method_desc() {
let doc = test::mk_doc(
~"trait i { #[doc = \" a \"] fn a(); }");
- assert doc.cratemod().traits()[0].methods[0].desc == some(~"a");
+ assert doc.cratemod().traits()[0].methods[0].desc == Some(~"a");
}
#[test]
fn should_execute_op_on_impl_brief() {
let doc = test::mk_doc(
~"#[doc = \" a \"] impl int { fn a() { } }");
- assert doc.cratemod().impls()[0].brief() == some(~"a");
+ assert doc.cratemod().impls()[0].brief() == Some(~"a");
}
#[test]
fn should_execute_op_on_impl_desc() {
let doc = test::mk_doc(
~"#[doc = \" a \"] impl int { fn a() { } }");
- assert doc.cratemod().impls()[0].desc() == some(~"a");
+ assert doc.cratemod().impls()[0].desc() == Some(~"a");
}
#[test]
fn should_execute_op_on_impl_method_brief() {
let doc = test::mk_doc(
~"impl int { #[doc = \" a \"] fn a() { } }");
- assert doc.cratemod().impls()[0].methods[0].brief == some(~"a");
+ assert doc.cratemod().impls()[0].methods[0].brief == Some(~"a");
}
#[test]
fn should_execute_op_on_impl_method_desc() {
let doc = test::mk_doc(
~"impl int { #[doc = \" a \"] fn a() { } }");
- assert doc.cratemod().impls()[0].methods[0].desc == some(~"a");
+ assert doc.cratemod().impls()[0].methods[0].desc == Some(~"a");
}
#[test]
fn should_execute_op_on_type_brief() {
let doc = test::mk_doc(
~"#[doc = \" a \"] type t = int;");
- assert doc.cratemod().types()[0].brief() == some(~"a");
+ assert doc.cratemod().types()[0].brief() == Some(~"a");
}
#[test]
fn should_execute_op_on_type_desc() {
let doc = test::mk_doc(
~"#[doc = \" a \"] type t = int;");
- assert doc.cratemod().types()[0].desc() == some(~"a");
+ assert doc.cratemod().types()[0].desc() == Some(~"a");
}
#[test]
fn should_trim_text() {
let doc = test::mk_doc(~"#[doc = \" desc \"] \
mod m { }");
- assert doc.cratemod().mods()[0].desc() == some(~"desc");
+ assert doc.cratemod().mods()[0].desc() == Some(~"desc");
}
#[cfg(test)]
}
}
-fn get_fn_sig(srv: astsrv::srv, fn_id: doc::ast_id) -> option<~str> {
+fn get_fn_sig(srv: astsrv::srv, fn_id: doc::ast_id) -> Option<~str> {
do astsrv::exec(srv) |ctxt| {
match ctxt.ast_map.get(fn_id) {
ast_map::node_item(@{
ident: ident,
node: ast::foreign_item_fn(decl, _, tys), _
}, _, _) => {
- some(pprust::fun_to_str(decl, ident, tys, extract::interner()))
+ Some(pprust::fun_to_str(decl, ident, tys, extract::interner()))
}
_ => fail ~"get_fn_sig: fn_id not bound to a fn item"
}
#[test]
fn should_add_fn_sig() {
let doc = test::mk_doc(~"fn a<T>() -> int { }");
- assert doc.cratemod().fns()[0].sig == some(~"fn a<T>() -> int");
+ assert doc.cratemod().fns()[0].sig == Some(~"fn a<T>() -> int");
}
#[test]
fn should_add_foreign_fn_sig() {
let doc = test::mk_doc(~"extern mod a { fn a<T>() -> int; }");
- assert doc.cratemod().nmods()[0].fns[0].sig == some(~"fn a<T>() -> int");
+ assert doc.cratemod().nmods()[0].fns[0].sig == Some(~"fn a<T>() -> int");
}
fn fold_const(
let srv = fold.ctxt;
{
- sig: some(do astsrv::exec(srv) |ctxt| {
+ sig: Some(do astsrv::exec(srv) |ctxt| {
match ctxt.ast_map.get(doc.id()) {
ast_map::node_item(@{
node: ast::item_const(ty, _), _
#[test]
fn should_add_const_types() {
let doc = test::mk_doc(~"const a: bool = true;");
- assert doc.cratemod().consts()[0].sig == some(~"bool");
+ assert doc.cratemod().consts()[0].sig == Some(~"bool");
}
fn fold_enum(
};
{
- sig: some(sig)
+ sig: Some(sig)
with variant
}
}
#[test]
fn should_add_variant_sigs() {
let doc = test::mk_doc(~"enum a { b(int) }");
- assert doc.cratemod().enums()[0].variants[0].sig == some(~"b(int)");
+ assert doc.cratemod().enums()[0].variants[0].sig == Some(~"b(int)");
}
fn fold_trait(
srv: astsrv::srv,
item_id: doc::ast_id,
method_name: ~str
-) -> option<~str> {
+) -> Option<~str> {
do astsrv::exec(srv) |ctxt| {
match ctxt.ast_map.get(item_id) {
ast_map::node_item(@{
ast::provided(m) => to_str(m.ident) == method_name,
}
}) {
- some(method) => {
+ Some(method) => {
match method {
ast::required(ty_m) => {
- some(pprust::fun_to_str(
+ Some(pprust::fun_to_str(
ty_m.decl,
ty_m.ident,
ty_m.tps,
))
}
ast::provided(m) => {
- some(pprust::fun_to_str(
+ Some(pprust::fun_to_str(
m.decl,
m.ident,
m.tps,
match vec::find(methods, |method| {
to_str(method.ident) == method_name
}) {
- some(method) => {
- some(pprust::fun_to_str(
+ Some(method) => {
+ Some(pprust::fun_to_str(
method.decl,
method.ident,
method.tps,
extract::interner()
))
}
- none => fail ~"method not found"
+ None => fail ~"method not found"
}
}
_ => fail ~"get_method_sig: item ID not bound to trait or impl"
fn should_add_trait_method_sigs() {
let doc = test::mk_doc(~"trait i { fn a<T>() -> int; }");
assert doc.cratemod().traits()[0].methods[0].sig
- == some(~"fn a<T>() -> int");
+ == Some(~"fn a<T>() -> int");
}
fn fold_impl(
let trait_types = vec::map(trait_types, |p| {
pprust::path_to_str(p.path, extract::interner())
});
- (trait_types, some(pprust::ty_to_str(self_ty,
+ (trait_types, Some(pprust::ty_to_str(self_ty,
extract::interner())))
}
_ => fail ~"expected impl"
#[test]
fn should_add_impl_self_ty() {
let doc = test::mk_doc(~"impl int { fn a() { } }");
- assert doc.cratemod().impls()[0].self_ty == some(~"int");
+ assert doc.cratemod().impls()[0].self_ty == Some(~"int");
}
#[test]
fn should_add_impl_method_sigs() {
let doc = test::mk_doc(~"impl int { fn a<T>() -> int { fail } }");
assert doc.cratemod().impls()[0].methods[0].sig
- == some(~"fn a<T>() -> int");
+ == Some(~"fn a<T>() -> int");
}
fn fold_type(
ident: ident,
node: ast::item_ty(ty, params), _
}, _) => {
- some(fmt!(
+ Some(fmt!(
"type %s%s = %s",
to_str(ident),
pprust::typarams_to_str(params, extract::interner()),
#[test]
fn should_add_type_signatures() {
let doc = test::mk_doc(~"type t<T> = int;");
- assert doc.cratemod().types()[0].sig == some(~"type t<T> = int");
+ assert doc.cratemod().types()[0].sig == Some(~"type t<T> = int");
}
#[cfg(test)]
export foo;
-type oint = option<int>;
-fn foo() -> oint { some(3) }
+type oint = Option<int>;
+fn foo() -> oint { Some(3) }
export read, readMaybe;
trait read {
- static fn readMaybe(s: ~str) -> option<self>;
+ static fn readMaybe(s: ~str) -> Option<self>;
}
impl int: read {
- static fn readMaybe(s: ~str) -> option<int> {
+ static fn readMaybe(s: ~str) -> Option<int> {
int::from_str(s)
}
}
impl bool: read {
- static fn readMaybe(s: ~str) -> option<bool> {
+ static fn readMaybe(s: ~str) -> Option<bool> {
match s {
- ~"true" => some(true),
- ~"false" => some(false),
- _ => none
+ ~"true" => Some(true),
+ ~"false" => Some(false),
+ _ => None
}
}
}
fn read<T: read copy>(s: ~str) -> T {
match readMaybe(s) {
- some(x) => x,
+ Some(x) => x,
_ => fail ~"read failed!"
}
}
let mut found = 0;
for int::range(0, 1000) |_i| {
match s.find(r.gen_str(10)) {
- some(_) => { found += 1; }
- none => { }
+ Some(_) => { found += 1; }
+ None => { }
}
}
}
let mut done = false;
while !done {
match requests.try_recv() {
- some(get_count) => { responses.send(copy count); }
- some(bytes(b)) => {
+ Some(get_count) => { responses.send(copy count); }
+ Some(bytes(b)) => {
//error!("server: received %? bytes", b);
count += b;
}
- none => { done = true; }
+ None => { done = true; }
_ => { }
}
}
let mut done = false;
while !done {
match requests.try_recv() {
- some(get_count) => { responses.send(copy count); }
- some(bytes(b)) => {
+ Some(get_count) => { responses.send(copy count); }
+ Some(bytes(b)) => {
//error!("server: received %? bytes", b);
count += b;
}
- none => { done = true; }
+ None => { done = true; }
_ => { }
}
}
count: uint,
+num_chan: pipe,
+num_port: pipe) {
- let mut num_chan <- some(num_chan);
- let mut num_port <- some(num_port);
+ let mut num_chan <- Some(num_chan);
+ let mut num_port <- Some(num_port);
// Send/Receive lots of messages.
for uint::range(0u, count) |j| {
//error!("task %?, iter %?", i, j);
let mut num_chan2 = option::swap_unwrap(&mut num_chan);
let mut num_port2 = option::swap_unwrap(&mut num_port);
send(&num_chan2, i * j);
- num_chan = some(num_chan2);
+ num_chan = Some(num_chan2);
let _n = recv(&num_port2);
//log(error, _n);
- num_port = some(num_port2);
+ num_port = Some(num_port2);
};
}
let msg_per_task = option::get(uint::from_str(args[2]));
let (num_chan, num_port) = init();
- let mut num_chan = some(num_chan);
+ let mut num_chan = Some(num_chan);
let start = time::precise_time_s();
for uint::range(1u, num_tasks) |i| {
//error!("spawning %?", i);
let (new_chan, num_port) = init();
- let num_chan2 = ~mut none;
+ let num_chan2 = ~mut None;
*num_chan2 <-> num_chan;
- let num_port = ~mut some(num_port);
+ let num_port = ~mut Some(num_port);
futures += ~[future::spawn(|move num_chan2, move num_port| {
- let mut num_chan = none;
+ let mut num_chan = None;
num_chan <-> *num_chan2;
- let mut num_port1 = none;
+ let mut num_port1 = None;
num_port1 <-> *num_port;
thread_ring(i, msg_per_task,
option::unwrap(num_chan),
option::unwrap(num_port1))
})];
- num_chan = some(new_chan);
+ num_chan = Some(new_chan);
};
// do our iteration
count: uint,
+num_chan: ring::client::num,
+num_port: ring::server::num) {
- let mut num_chan <- some(num_chan);
- let mut num_port <- some(num_port);
+ let mut num_chan <- Some(num_chan);
+ let mut num_port <- Some(num_port);
// Send/Receive lots of messages.
for uint::range(0u, count) |j| {
//error!("task %?, iter %?", i, j);
- let mut num_chan2 = none;
- let mut num_port2 = none;
+ let mut num_chan2 = None;
+ let mut num_port2 = None;
num_chan2 <-> num_chan;
num_port2 <-> num_port;
- num_chan = some(ring::client::num(option::unwrap(num_chan2), i * j));
+ num_chan = Some(ring::client::num(option::unwrap(num_chan2), i * j));
let port = option::unwrap(num_port2);
match recv(port) {
ring::num(_n, p) => {
//log(error, _n);
- num_port = some(move_out!(p));
+ num_port = Some(move_out!(p));
}
}
};
let msg_per_task = option::get(uint::from_str(args[2]));
let (num_chan, num_port) = ring::init();
- let mut num_chan = some(num_chan);
+ let mut num_chan = Some(num_chan);
let start = time::precise_time_s();
for uint::range(1u, num_tasks) |i| {
//error!("spawning %?", i);
let (new_chan, num_port) = ring::init();
- let num_chan2 = ~mut none;
+ let num_chan2 = ~mut None;
*num_chan2 <-> num_chan;
- let num_port = ~mut some(num_port);
+ let num_port = ~mut Some(num_port);
futures += ~[future::spawn(|move num_chan2, move num_port| {
- let mut num_chan = none;
+ let mut num_chan = None;
num_chan <-> *num_chan2;
- let mut num_port1 = none;
+ let mut num_port1 = None;
num_port1 <-> *num_port;
thread_ring(i, msg_per_task,
option::unwrap(num_chan),
option::unwrap(num_port1))
})];
- num_chan = some(new_chan);
+ num_chan = Some(new_chan);
};
// do our iteration
count: uint,
+num_chan: pipe,
+num_port: pipe) {
- let mut num_chan <- some(num_chan);
- let mut num_port <- some(num_port);
+ let mut num_chan <- Some(num_chan);
+ let mut num_port <- Some(num_port);
// Send/Receive lots of messages.
for uint::range(0u, count) |j| {
//error!("task %?, iter %?", i, j);
let mut num_chan2 = option::swap_unwrap(&mut num_chan);
let mut num_port2 = option::swap_unwrap(&mut num_port);
send(&num_chan2, i * j);
- num_chan = some(num_chan2);
+ num_chan = Some(num_chan2);
let _n = recv(&num_port2);
//log(error, _n);
- num_port = some(num_port2);
+ num_port = Some(num_port2);
};
}
let msg_per_task = option::get(uint::from_str(args[2]));
let (num_chan, num_port) = init();
- let mut num_chan = some(num_chan);
+ let mut num_chan = Some(num_chan);
let start = time::precise_time_s();
for uint::range(1u, num_tasks) |i| {
//error!("spawning %?", i);
let (new_chan, num_port) = init();
- let num_chan2 = ~mut none;
+ let num_chan2 = ~mut None;
*num_chan2 <-> num_chan;
- let num_port = ~mut some(num_port);
+ let num_port = ~mut Some(num_port);
futures += ~[future::spawn(|move num_chan2, move num_port| {
- let mut num_chan = none;
+ let mut num_chan = None;
num_chan <-> *num_chan2;
- let mut num_port1 = none;
+ let mut num_port1 = None;
num_port1 <-> *num_port;
thread_ring(i, msg_per_task,
option::unwrap(num_chan),
option::unwrap(num_port1))
})];
- num_chan = some(new_chan);
+ num_chan = Some(new_chan);
};
// do our iteration
$($message:path($($x: ident),+) -> $next:ident $e:expr)+
} => (
|m| match move m {
- $(some($message($($x,)* next)) => {
+ $(Some($message($($x,)* next)) => {
// FIXME (#2329) use regular move here once move out of
// enums is supported.
let $next = unsafe { move_it!(next) };
$($message:path -> $next:ident $e:expr)+
} => (
|m| match move m {
- $(some($message(next)) => {
+ $(Some($message(next)) => {
// FIXME (#2329) use regular move here once move out of
// enums is supported.
let $next = unsafe { move_it!(next) };
)
fn switch<T: send, Tb: send, U>(+endp: pipes::recv_packet_buffered<T, Tb>,
- f: fn(+option<T>) -> U) -> U {
+ f: fn(+Option<T>) -> U) -> U {
f(pipes::try_recv(endp))
}
fn creature(
name: uint,
color: color,
- from_rendezvous: comm::Port<option<creature_info>>,
+ from_rendezvous: comm::Port<Option<creature_info>>,
to_rendezvous: comm::Chan<creature_info>,
to_rendezvous_log: comm::Chan<~str>
) {
// log and change, or print and quit
match resp {
- option::some(other_creature) => {
+ option::Some(other_creature) => {
color = transform(color, other_creature.color);
// track some statistics
evil_clones_met += 1;
}
}
- option::none => {
+ option::None => {
// log creatures met and evil clones of self
let report = fmt!("%u", creatures_met) + ~" " +
show_number(evil_clones_met);
let to_rendezvous_log = comm::chan(from_creatures_log);
// these channels will allow us to talk to each creature by 'name'/index
- let to_creature: ~[comm::Chan<option<creature_info>>] =
+ let to_creature: ~[comm::Chan<Option<creature_info>>] =
vec::mapi(set,
- fn@(ii: uint, col: color) -> comm::Chan<option<creature_info>> {
+ fn@(ii: uint, col: color) -> comm::Chan<Option<creature_info>> {
// create each creature as a listener with a port, and
// give us a channel to talk to each
return do task::spawn_listener |from_rendezvous| {
creatures_met += 2;
- comm::send(to_creature[fst_creature.name], some(snd_creature));
- comm::send(to_creature[snd_creature.name], some(fst_creature));
+ comm::send(to_creature[fst_creature.name], Some(snd_creature));
+ comm::send(to_creature[snd_creature.name], Some(fst_creature));
}
// tell each creature to stop
for vec::eachi(to_creature) |_ii, to_one| {
- comm::send(to_one, none);
+ comm::send(to_one, None);
}
// save each creature's meeting stats
// given a map, search for the frequency of a pattern
fn find(mm: hashmap<~[u8], uint>, key: ~str) -> uint {
match mm.find(str::to_bytes(str::to_lower(key))) {
- option::none => { return 0u; }
- option::some(num) => { return num; }
+ option::None => { return 0u; }
+ option::Some(num) => { return num; }
}
}
fn update_freq(mm: hashmap<~[u8], uint>, key: &[u8]) {
let key = vec::slice(key, 0, key.len());
match mm.find(key) {
- option::none => { mm.insert(key, 1u ); }
- option::some(val) => { mm.insert(key, 1u + val); }
+ option::None => { mm.insert(key, 1u ); }
+ option::Some(val) => { mm.insert(key, 1u + val); }
}
}
// initialize each sequence sorter
let sizes = ~[1u,2u,3u,4u,6u,12u,18u];
- let streams = vec::map(sizes, |_sz| some(stream()));
+ let streams = vec::map(sizes, |_sz| Some(stream()));
let streams = vec::to_mut(streams);
let mut from_child = ~[];
let to_child = vec::mapi(sizes, |ii, sz| {
- let mut stream = none;
+ let mut stream = None;
stream <-> streams[ii];
let (to_parent_, from_child_) = option::unwrap(stream);
// start processing if this is the one
('>' as u8, false) => {
match str::find_str_from(line, ~"THREE", 1u) {
- option::some(_) => { proc_mode = true; }
- option::none => { }
+ option::Some(_) => { proc_mode = true; }
+ option::None => { }
}
}
// given a map, search for the frequency of a pattern
fn find(mm: hashmap<~[u8], uint>, key: ~str) -> uint {
match mm.find(str::to_bytes(str::to_lower(key))) {
- option::none => { return 0u; }
- option::some(num) => { return num; }
+ option::None => { return 0u; }
+ option::Some(num) => { return num; }
}
}
fn update_freq(mm: hashmap<~[u8], uint>, key: &[u8]) {
let key = vec::slice(key, 0, key.len());
match mm.find(key) {
- option::none => { mm.insert(key, 1u ); }
- option::some(val) => { mm.insert(key, 1u + val); }
+ option::None => { mm.insert(key, 1u ); }
+ option::Some(val) => { mm.insert(key, 1u + val); }
}
}
// start processing if this is the one
('>' as u8, false) => {
match str::find_str_from(line, ~"THREE", 1u) {
- option::some(_) => proc_mode = true,
- option::none => ()
+ option::Some(_) => proc_mode = true,
+ option::None => ()
}
}
for iter::repeat(repeat as uint) {
debug!("starting %.4f", precise_time_s());
do task::try {
- recurse_or_fail(depth, none)
+ recurse_or_fail(depth, None)
};
debug!("stopping %.4f", precise_time_s());
}
drop {}
}
-fn recurse_or_fail(depth: int, st: option<st>) {
+fn recurse_or_fail(depth: int, st: Option<st>) {
if depth == 0 {
debug!("unwinding %.4f", precise_time_s());
fail;
let depth = depth - 1;
let st = match st {
- none => {
+ None => {
st_({
box: @nil,
unique: ~nil,
res: r(@nil)
})
}
- some(st) => {
+ Some(st) => {
let fn_box = st.fn_box;
let fn_unique = st.fn_unique;
}
};
- recurse_or_fail(depth, some(st));
+ recurse_or_fail(depth, Some(st));
}
}
// This used to be O(n^2) in the number of generations that ever existed.
// With this code, only as many generations are alive at a time as tasks
// alive at a time,
- let c = ~mut some(c);
+ let c = ~mut Some(c);
do task::spawn_supervised {
let c = option::swap_unwrap(c);
if gens_left & 1 == 1 {
}
fn spawn_supervised_blocking(myname: &str, +f: fn~()) {
- let mut res = none;
- task::task().future_result(|+r| res = some(r)).supervised().spawn(f);
+ let mut res = None;
+ task::task().future_result(|+r| res = Some(r)).supervised().spawn(f);
#error["%s group waiting", myname];
let x = future::get(&option::unwrap(res));
assert x == task::Success;
use std;
import option = option;
-import option::some;
-import option::none;
+import option::Some;
+import option::None;
import str;
import std::map;
import std::map::hashmap;
)
trait word_reader {
- fn read_word() -> option<~str>;
+ fn read_word() -> Option<~str>;
}
trait hash_key {
}
impl io::Reader: word_reader {
- fn read_word() -> option<~str> { read_word(self) }
+ fn read_word() -> Option<~str> { read_word(self) }
}
fn file_word_reader(filename: ~str) -> word_reader {
let f = f();
loop {
match f.read_word() {
- some(w) => { emit(w, 1); }
- none => { break; }
+ Some(w) => { emit(w, 1); }
+ None => { break; }
}
}
}
fn reduce(&&word: ~str, get: map_reduce::getter<int>) {
let mut count = 0;
- loop { match get() { some(_) => { count += 1; } none => { break; } } }
+ loop { match get() { Some(_) => { count += 1; } None => { break; } } }
io::println(fmt!("%s\t%?", word, count));
}
struct box<T> {
- let mut contents: option<T>;
- new(+x: T) { self.contents = some(x); }
+ let mut contents: Option<T>;
+ new(+x: T) { self.contents = Some(x); }
fn swap(f: fn(+T) -> T) {
- let mut tmp = none;
+ let mut tmp = None;
self.contents <-> tmp;
- self.contents = some(f(option::unwrap(tmp)));
+ self.contents = Some(f(option::unwrap(tmp)));
}
fn unwrap() -> T {
- let mut tmp = none;
+ let mut tmp = None;
self.contents <-> tmp;
option::unwrap(tmp)
}
type mapper<K1: send, K2: send, V: send> = fn~(K1, putter<K2, V>);
- type getter<V: send> = fn() -> option<V>;
+ type getter<V: send> = fn() -> Option<V>;
type reducer<K: copy send, V: copy send> = fn~(K, getter<V>);
let intermediates = mk_hash();
do map(input) |key, val| {
- let mut c = none;
+ let mut c = None;
match intermediates.find(key) {
- some(_c) => { c = some(_c); }
- none => {
+ Some(_c) => { c = Some(_c); }
+ None => {
do ctrl.swap |ctrl| {
let ctrl = ctrl_proto::client::find_reducer(ctrl, key);
match pipes::recv(ctrl) {
ctrl_proto::reducer(c_, ctrl) => {
- c = some(c_);
+ c = Some(c_);
move_out!(ctrl)
}
}
fn get<V: copy send>(p: Port<reduce_proto<V>>,
&ref_count: int, &is_done: bool)
- -> option<V> {
+ -> Option<V> {
while !is_done || ref_count > 0 {
match recv(p) {
emit_val(v) => {
// error!("received %d", v);
- return some(v);
+ return Some(v);
}
done => {
// error!("all done");
release => { ref_count -= 1; }
}
}
- return none;
+ return None;
}
reduce(key, || get(p, ref_count, is_done) );
let c;
// log(error, "finding reducer for " + k);
match reducers.find(k) {
- some(_c) => {
+ Some(_c) => {
// log(error,
// "reusing existing reducer for " + k);
c = _c;
}
- none => {
+ None => {
// log(error, "creating new reducer for " + k);
let p = port();
let ch = chan(p);
+ u64::str(elapsed) + ~"ms");
}
-fn read_word(r: io::Reader) -> option<~str> {
+fn read_word(r: io::Reader) -> Option<~str> {
let mut w = ~"";
while !r.eof() {
if is_word_char(c) {
w += str::from_char(c);
- } else { if w != ~"" { return some(w); } }
+ } else { if w != ~"" { return Some(w); } }
}
- return none;
+ return None;
}
fn is_word_char(c: char) -> bool {
self.rng = rand::rng();
}
- fn read_word() -> option<~str> {
+ fn read_word() -> Option<~str> {
if self.remaining > 0 {
self.remaining -= 1;
let len = self.rng.gen_uint_range(1, 4);
- some(self.rng.gen_str(len))
+ Some(self.rng.gen_str(len))
}
- else { none }
+ else { None }
}
}
import std::arc;
fn main() {
let x = ~arc::rw_arc(1);
- let mut y = none;
+ let mut y = None;
do x.write_cond |_one, cond| {
- y = some(cond);
+ y = Some(cond);
}
option::unwrap(y).wait();
}
import std::arc;
fn main() {
let x = ~arc::rw_arc(1);
- let mut y = none;
+ let mut y = None;
do x.write_downgrade |write_mode| {
- y = some(x.downgrade(write_mode));
+ y = Some(x.downgrade(write_mode));
//~^ ERROR cannot infer an appropriate lifetime
}
// Adding this line causes a method unification failure instead
import std::arc;
fn main() {
let x = ~arc::rw_arc(1);
- let mut y = none;
+ let mut y = None;
do x.write |one| {
- y = some(one);
+ y = Some(one);
}
*option::unwrap(y) = 2;
}
import std::arc;
fn main() {
let x = ~arc::rw_arc(1);
- let mut y = none;
+ let mut y = None;
do x.write_downgrade |write_mode| {
do (&write_mode).write_cond |_one, cond| {
- y = some(cond);
+ y = Some(cond);
}
}
option::unwrap(y).wait();
import std::arc;
fn main() {
let x = ~arc::rw_arc(1);
- let mut y = none;
+ let mut y = None;
do x.write_downgrade |write_mode| {
- y = some(write_mode);
+ y = Some(write_mode);
}
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).write |state| { assert *state == 1; }
struct X { x: (); drop { error!("destructor runs"); } }
fn main() {
- let x = some(X { x: () });
+ let x = Some(X { x: () });
match move x {
- some(ref _y @ move _z) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern
- none => fail
+ Some(ref _y @ move _z) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern
+ None => fail
}
}
struct X { x: (); drop { error!("destructor runs"); } }
fn main() {
- let x = some((X { x: () }, X { x: () }));
+ let x = Some((X { x: () }, X { x: () }));
match move x {
- some((ref _y, move _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern
- none => fail
+ Some((ref _y, move _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern
+ None => fail
}
}
fn main() {
let (c,p) = pipes::stream();
- let x = some(p);
+ let x = Some(p);
c.send(false);
match move x {
- some(move z) if z.recv() => { fail }, //~ ERROR cannot bind by-move into a pattern guard
- some(move z) => { assert !z.recv(); },
- none => fail
+ Some(move z) if z.recv() => { fail }, //~ ERROR cannot bind by-move into a pattern guard
+ Some(move z) => { assert !z.recv(); },
+ None => fail
}
}
struct X { x: (); drop { error!("destructor runs"); } }
fn main() {
- let x = some(X { x: () });
+ let x = Some(X { x: () });
match x {
- some(move _z) => { }, //~ ERROR cannot bind by-move when matching an lvalue
- none => fail
+ Some(move _z) => { }, //~ ERROR cannot bind by-move when matching an lvalue
+ None => fail
}
}
struct X { x: (); drop { error!("destructor runs"); } }
-struct Y { y: option<X>; }
+struct Y { y: Option<X>; }
fn main() {
- let x = Y { y: some(X { x: () }) };
+ let x = Y { y: Some(X { x: () }) };
match x.y {
- some(move _z) => { }, //~ ERROR cannot bind by-move when matching an lvalue
- none => fail
+ Some(move _z) => { }, //~ ERROR cannot bind by-move when matching an lvalue
+ None => fail
}
}
struct X { x: (); drop { error!("destructor runs"); } }
fn main() {
- let x = some(X { x: () });
+ let x = Some(X { x: () });
match move x {
- some(move _y @ ref _z) => { }, //~ ERROR cannot bind by-move with sub-bindings
- none => fail
+ Some(move _y @ ref _z) => { }, //~ ERROR cannot bind by-move with sub-bindings
+ None => fail
}
}
fn main() {
// assigning to various global constants
- none = some(3); //~ ERROR assigning to static item
+ None = Some(3); //~ ERROR assigning to static item
foo = 6; //~ ERROR assigning to static item
}
\ No newline at end of file
fn main() {
-let x = some(~1);
+let x = Some(~1);
match x { //~ NOTE loan of immutable local variable granted here
- some(ref _y) => {
+ Some(ref _y) => {
let _a <- x; //~ ERROR moving out of immutable local variable prohibited due to outstanding loan
}
_ => {}
fn main() {
-let x = some(~1);
+let x = Some(~1);
match x {
- some(ref y) => {
+ Some(ref y) => {
let _b <- *y; //~ ERROR moving out of dereference of immutable & pointer
}
_ => {}
fn process<T>(_t: T) {}
-fn match_const_opt_by_mut_ref(v: &const option<int>) {
+fn match_const_opt_by_mut_ref(v: &const Option<int>) {
match *v {
- some(ref mut i) => process(i), //~ ERROR illegal borrow
- none => ()
+ Some(ref mut i) => process(i), //~ ERROR illegal borrow
+ None => ()
}
}
-fn match_const_opt_by_const_ref(v: &const option<int>) {
+fn match_const_opt_by_const_ref(v: &const Option<int>) {
match *v {
- some(ref const i) => process(i), //~ ERROR illegal borrow unless pure
+ Some(ref const i) => process(i), //~ ERROR illegal borrow unless pure
//~^ NOTE impure due to
- none => ()
+ None => ()
}
}
-fn match_const_opt_by_imm_ref(v: &const option<int>) {
+fn match_const_opt_by_imm_ref(v: &const Option<int>) {
match *v {
- some(ref i) => process(i), //~ ERROR illegal borrow unless pure
+ Some(ref i) => process(i), //~ ERROR illegal borrow unless pure
//~^ NOTE impure due to
- none => ()
+ None => ()
}
}
-fn match_const_opt_by_value(v: &const option<int>) {
+fn match_const_opt_by_value(v: &const Option<int>) {
match *v {
- some(copy i) => process(i),
- none => ()
+ Some(copy i) => process(i),
+ None => ()
}
}
-fn match_imm_box(v: &const @option<int>) -> int {
+fn match_imm_box(v: &const @Option<int>) -> int {
match *v {
- @some(ref i) => {*i}
- @none => {0}
+ @Some(ref i) => {*i}
+ @None => {0}
}
}
-fn match_const_box(v: &const @const option<int>) -> int {
+fn match_const_box(v: &const @const Option<int>) -> int {
match *v {
- @some(ref i) => { *i } // ok because this is pure
- @none => {0}
+ @Some(ref i) => { *i } // ok because this is pure
+ @None => {0}
}
}
pure fn pure_process(_i: int) {}
-fn match_const_box_and_do_pure_things(v: &const @const option<int>) {
+fn match_const_box_and_do_pure_things(v: &const @const Option<int>) {
match *v {
- @some(ref i) => {
+ @Some(ref i) => {
pure_process(*i)
}
- @none => {}
+ @None => {}
}
}
fn process(_i: int) {}
-fn match_const_box_and_do_bad_things(v: &const @const option<int>) {
+fn match_const_box_and_do_bad_things(v: &const @const Option<int>) {
match *v {
- @some(ref i) => { //~ ERROR illegal borrow unless pure
+ @Some(ref i) => { //~ ERROR illegal borrow unless pure
process(*i) //~ NOTE impure due to access to impure function
}
- @none => {}
+ @None => {}
}
}
-fn match_ref(&&v: option<int>) -> int {
+fn match_ref(&&v: Option<int>) -> int {
match v {
- some(ref i) => {
+ Some(ref i) => {
*i
}
- none => {0}
+ None => {0}
}
}
-fn match_ref_unused(&&v: option<int>) {
+fn match_ref_unused(&&v: Option<int>) {
match v {
- some(_) => {}
- none => {}
+ Some(_) => {}
+ None => {}
}
}
-fn match_const_reg(v: &const option<int>) -> int {
+fn match_const_reg(v: &const Option<int>) -> int {
match *v {
- some(ref i) => {*i} // OK because this is pure
- none => {0}
+ Some(ref i) => {*i} // OK because this is pure
+ None => {0}
}
}
fn impure(_i: int) {
}
-fn match_const_reg_unused(v: &const option<int>) {
+fn match_const_reg_unused(v: &const Option<int>) {
match *v {
- some(_) => {impure(0)} // OK because nothing is captured
- none => {}
+ Some(_) => {impure(0)} // OK because nothing is captured
+ None => {}
}
}
-fn match_const_reg_impure(v: &const option<int>) {
+fn match_const_reg_impure(v: &const Option<int>) {
match *v {
- some(ref i) => {impure(*i)} //~ ERROR illegal borrow unless pure
+ Some(ref i) => {impure(*i)} //~ ERROR illegal borrow unless pure
//~^ NOTE impure due to access to impure function
- none => {}
+ None => {}
}
}
-fn match_imm_reg(v: &option<int>) {
+fn match_imm_reg(v: &Option<int>) {
match *v {
- some(ref i) => {impure(*i)} // OK because immutable
- none => {}
+ Some(ref i) => {impure(*i)} // OK because immutable
+ None => {}
}
}
// xfail-pretty -- comments are infaithfully preserved
fn main() {
- let mut x: option<int> = none;
+ let mut x: Option<int> = None;
match x { //~ NOTE loan of mutable local variable granted here
- none => {}
- some(ref i) => {
+ None => {}
+ Some(ref i) => {
// Not ok: i is an outstanding ptr into x.
- x = some(*i+1); //~ ERROR assigning to mutable local variable prohibited due to outstanding loan
+ x = Some(*i+1); //~ ERROR assigning to mutable local variable prohibited due to outstanding loan
}
}
copy x; // just to prevent liveness warnings
// xfail-pretty -- comments are infaithfully preserved
fn main() {
- let mut x = none;
+ let mut x = None;
match x { //~ NOTE loan of mutable local variable granted here
- none => {
+ None => {
// It is ok to reassign x here, because there is in
// fact no outstanding loan of x!
- x = some(0);
+ x = Some(0);
}
- some(ref _i) => {
- x = some(1); //~ ERROR assigning to mutable local variable prohibited due to outstanding loan
+ Some(ref _i) => {
+ x = Some(1); //~ ERROR assigning to mutable local variable prohibited due to outstanding loan
}
}
copy x; // just to prevent liveness warnings
fn main() {
let msg;
- match some(~"Hello") { //~ ERROR illegal borrow
- some(ref m) => {
+ match Some(~"Hello") { //~ ERROR illegal borrow
+ Some(ref m) => {
msg = m;
},
- none => { fail }
+ None => { fail }
}
io::println(*msg);
}
-fn destructure(x: option<int>) -> int {
+fn destructure(x: Option<int>) -> int {
match x {
- none => 0,
- some(ref mut v) => *v //~ ERROR illegal borrow
+ None => 0,
+ Some(ref mut v) => *v //~ ERROR illegal borrow
}
}
fn main() {
- assert destructure(some(22)) == 22;
+ assert destructure(Some(22)) == 22;
}
fn impure(_i: int) {}
// check that unchecked alone does not override borrowck:
-fn foo(v: &const option<int>) {
+fn foo(v: &const Option<int>) {
match *v {
- some(ref i) => {
+ Some(ref i) => {
//~^ ERROR illegal borrow unless pure
unchecked {
impure(*i); //~ NOTE impure due to access to impure function
}
}
- none => {
+ None => {
}
}
}
-fn bar(v: &const option<int>) {
+fn bar(v: &const Option<int>) {
match *v {
- some(ref i) => {
+ Some(ref i) => {
unsafe {
impure(*i);
}
}
- none => {
+ None => {
}
}
}
// Test that we use fully-qualified type names in error messages.
fn main() {
- let x: option<uint>;
+ let x: Option<uint>;
x = 5;
- //~^ ERROR mismatched types: expected `core::option::option<uint>`
+ //~^ ERROR mismatched types: expected `core::option::Option<uint>`
}
// issue 2258
trait to_opt {
- fn to_option() -> option<self>;
+ fn to_option() -> Option<self>;
}
impl uint: to_opt {
- fn to_option() -> option<uint> {
- some(self)
+ fn to_option() -> Option<uint> {
+ Some(self)
}
}
-impl<T:copy> option<T>: to_opt {
- fn to_option() -> option<option<T>> {
- some(self)
+impl<T:copy> Option<T>: to_opt {
+ fn to_option() -> Option<Option<T>> {
+ Some(self)
}
}
-fn foo(a: option<uint>, b: option<uint>) {
- match (a,b) { //~ ERROR: non-exhaustive patterns: none not covered
- (some(a), some(b)) if a == b => { }
- (some(_), none) |
- (none, some(_)) => { }
+fn foo(a: Option<uint>, b: Option<uint>) {
+ match (a,b) { //~ ERROR: non-exhaustive patterns: None not covered
+ (Some(a), Some(b)) if a == b => { }
+ (Some(_), None) |
+ (None, Some(_)) => { }
}
}
fn main() {
- foo(none, none);
+ foo(None, None);
}
\ No newline at end of file
use std;
import option;
-fn f<T>(&o: option<T>) {
- assert o == option::none;
+fn f<T>(&o: Option<T>) {
+ assert o == option::None;
}
fn main() {
- f::<int>(option::none);
+ f::<int>(option::None);
//~^ ERROR taking mut reference to static item
//~^^ ERROR illegal borrow: creating mutable alias to aliasable, immutable memory
}
\ No newline at end of file
}
fn f4() {
- match some(3) {
- some(i) => {
+ match Some(3) {
+ Some(i) => {
//~^ WARNING unused variable: `i`
}
- none => {}
+ None => {}
}
}
-// error-pattern:declaration of `none` shadows
+// error-pattern:declaration of `None` shadows
import option::*;
fn main() {
- let none: int = 42;
- log(debug, none);
+ let None: int = 42;
+ log(debug, None);
}
drop {}
}
- let x = ~mut some(foo(comm::port()));
+ let x = ~mut Some(foo(comm::port()));
do task::spawn |move x| { //~ ERROR not a sendable value
- let mut y = none;
+ let mut y = None;
*x <-> y;
log(error, y);
}
// because the def_id associated with the type was
// not convertible to a path.
let x: int = noexporttypelib::foo();
- //~^ ERROR expected `int` but found `core::option::option<int>`
+ //~^ ERROR expected `int` but found `core::option::Option<int>`
}
match true { //~ ERROR non-exhaustive patterns
true => {}
}
- match @some(10) { //~ ERROR non-exhaustive patterns
- @none => {}
+ match @Some(10) { //~ ERROR non-exhaustive patterns
+ @None => {}
}
match (2, 3, 4) { //~ ERROR non-exhaustive patterns
(_, _, 4) => {}
fn main() {
- let x = some(unsafe::exclusive(false));
+ let x = Some(unsafe::exclusive(false));
match x {
- some(copy z) => { //~ ERROR copying a noncopyable value
+ Some(copy z) => { //~ ERROR copying a noncopyable value
do z.with |b| { assert !*b; }
}
- none => fail
+ None => fail
}
}
use std;
import option;
-import option::some;
+import option::Some;
// error-pattern: mismatched types
-enum bar { t1((), option<~[int]>), t2, }
+enum bar { t1((), Option<~[int]>), t2, }
-fn foo(t: bar) -> int { match t { t1(_, some(x)) => { return x * 3; } _ => { fail; } } }
+fn foo(t: bar) -> int { match t { t1(_, Some(x)) => { return x * 3; } _ => { fail; } } }
fn main() { }
// -*- rust -*-
use std;
import option;
-import option::some;
+import option::Some;
// error-pattern: mismatched types
-enum bar { t1((), option<~[int]>), t2, }
+enum bar { t1((), Option<~[int]>), t2, }
fn foo(t: bar) {
match t {
- t1(_, some::<int>(x)) => {
+ t1(_, Some::<int>(x)) => {
log(debug, x);
}
_ => { fail; }
-type foo = option<int>;
+type foo = Option<int>;
fn bar(_t: foo) {}
fn main() {
// we used to print foo<int>:
- bar(some(3u)); //~ ERROR mismatched types: expected `foo`
+ bar(Some(3u)); //~ ERROR mismatched types: expected `foo`
}
\ No newline at end of file
}
fn main() {
- let mut x = none;
+ let mut x = None;
//~^ ERROR reference is not valid outside of its lifetime
- with_int(|y| x = some(y));
+ with_int(|y| x = Some(y));
}
}
fn main() {
- let mut x: option<&int> = none; //~ ERROR cannot infer
- with_int(|y| x = some(y));
+ let mut x: Option<&int> = None; //~ ERROR cannot infer
+ with_int(|y| x = Some(y));
}
fn main() {
let m = ~sync::mutex();
- let mut cond = none;
+ let mut cond = None;
do m.lock_cond |c| {
- cond = some(c);
+ cond = Some(c);
}
option::unwrap(cond).signal();
}
import std::sync;
fn main() {
let x = ~sync::rwlock();
- let mut y = none;
+ let mut y = None;
do x.write_cond |cond| {
- y = some(cond);
+ y = Some(cond);
}
option::unwrap(y).wait();
}
import std::sync;
fn main() {
let x = ~sync::rwlock();
- let mut y = none;
+ let mut y = None;
do x.write_downgrade |write_mode| {
- y = some(x.downgrade(write_mode));
+ y = Some(x.downgrade(write_mode));
}
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).read { }
import std::sync;
fn main() {
let x = ~sync::rwlock();
- let mut y = none;
+ let mut y = None;
do x.write_downgrade |write_mode| {
do (&write_mode).write_cond |cond| {
- y = some(cond);
+ y = Some(cond);
}
}
option::unwrap(y).wait();
import std::sync;
fn main() {
let x = ~sync::rwlock();
- let mut y = none;
+ let mut y = None;
do x.write_downgrade |write_mode| {
- y = some(write_mode);
+ y = Some(write_mode);
}
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).write { }
use core;
-fn last<T: copy>(v: ~[const T]) -> core::option<T> {
+fn last<T: copy>(v: ~[const T]) -> core::Option<T> {
fail;
}
// error-pattern: implement a trait or new type instead
-impl <T> option<T> {
+impl <T> Option<T> {
fn foo() { }
}
// get the prettyprinter to indent the long expr
fn main() {
- let x = some(3);
+ let x = Some(3);
let y =
match x {
- some(_) =>
+ Some(_) =>
~"some" + ~"very" + ~"very" + ~"very" + ~"very" + ~"very" +
~"very" + ~"very" + ~"very" + ~"long" + ~"string",
- none => ~"none"
+ None => ~"none"
};
assert y == ~"some(_)";
}
// pretty-exact
fn main() {
- let x = some(3);
+ let x = Some(3);
let _y =
match x {
- some(_) => ~[~"some(_)", ~"not", ~"SO", ~"long", ~"string"],
- none => ~[~"none"]
+ Some(_) => ~[~"some(_)", ~"not", ~"SO", ~"long", ~"string"],
+ None => ~[~"none"]
};
}
// pretty-exact
fn main() {
- let x = some(3);
- let y = match x { some(_) => ~"some(_)", none => ~"none" };
+ let x = Some(3);
+ let y = match x { Some(_) => ~"some(_)", None => ~"none" };
assert y == ~"some(_)";
}
fn main() {
let i =
- match some::<int>(3) { none::<int> => { fail } some::<int>(_) => { fail } };
+ match Some::<int>(3) { None::<int> => { fail } Some::<int>(_) => { fail } };
foo(i);
}
// error-pattern:squirrelcupcake
fn cmp() -> int {
- match (option::some('a'), option::none::<char>) {
- (option::some(_), _) => { fail ~"squirrelcupcake"; }
- (_, option::some(_)) => { fail; }
+ match (option::Some('a'), option::None::<char>) {
+ (option::Some(_), _) => { fail ~"squirrelcupcake"; }
+ (_, option::Some(_)) => { fail; }
_ => { fail ~"wat"; }
}
}
}
fn mk_ctxt() -> fake_ext_ctxt {
- parse::new_parse_sess(none) as fake_ext_ctxt
+ parse::new_parse_sess(None) as fake_ext_ctxt
}
// Regression test for issue #374
use std;
import option;
-import option::none;
+import option::None;
enum sty { ty_nil, }
-type raw_t = {struct: sty, cname: option<~str>, hash: uint};
+type raw_t = {struct: sty, cname: Option<~str>, hash: uint};
-fn mk_raw_ty(st: sty, cname: option<~str>) -> raw_t {
+fn mk_raw_ty(st: sty, cname: Option<~str>) -> raw_t {
return {struct: st, cname: cname, hash: 0u};
}
-fn main() { mk_raw_ty(ty_nil, none::<~str>); }
+fn main() { mk_raw_ty(ty_nil, None::<~str>); }
enum rec<A> = _rec<A>;
type _rec<A> = {
val: A,
- mut rec: option<@rec<A>>
+ mut rec: Option<@rec<A>>
};
fn make_cycle<A:copy>(a: A) {
- let g: @rec<A> = @rec({val: a, mut rec: none});
- g.rec = some(g);
+ let g: @rec<A> = @rec({val: a, mut rec: None});
+ g.rec = Some(g);
}
fn f<A:send copy, B:send copy>(a: A, b: B) -> fn@() -> (A, B) {
fn main() {
let i: int =
- match some::<int>(3) { none::<int> => { fail } some::<int>(_) => { 5 } };
+ match Some::<int>(3) { None::<int> => { fail } Some::<int>(_) => { 5 } };
log(debug, i);
}
use std;
import option;
-fn foo<T>(y: option<T>) {
+fn foo<T>(y: Option<T>) {
let mut x: int;
let mut rs: ~[int] = ~[];
/* tests that x doesn't get put in the precondition for the
if true {
} else {
match y {
- none::<T> => x = 17,
+ None::<T> => x = 17,
_ => x = 42
}
rs += ~[x];
return;
}
-fn main() { debug!("hello"); foo::<int>(some::<int>(5)); }
+fn main() { debug!("hello"); foo::<int>(Some::<int>(5)); }
fn main() {
- let mut v = some(22);
+ let mut v = Some(22);
match v {
- none => {}
- some(ref mut p) => { *p += 1; }
+ None => {}
+ Some(ref mut p) => { *p += 1; }
}
- assert v == some(23);
+ assert v == Some(23);
}
-fn destructure(x: option<int>) -> int {
+fn destructure(x: Option<int>) -> int {
match x {
- none => 0,
- some(ref v) => *v
+ None => 0,
+ Some(ref v) => *v
}
}
fn main() {
- assert destructure(some(22)) == 22;
+ assert destructure(Some(22)) == 22;
}
// the right type for f, as we unified
// bot and u32 here
let f = match uint::from_str(~"1234") {
- none => return (),
- some(num) => num as u32
+ None => return (),
+ Some(num) => num as u32
};
assert f == 1234u32;
log(error, f)
fn main() {
- let mut x = none;
+ let mut x = None;
match x {
- none => {
+ None => {
// It is ok to reassign x here, because there is in
// fact no outstanding loan of x!
- x = some(0);
+ x = Some(0);
}
- some(_) => { }
+ Some(_) => { }
}
}
// exec-env:RUST_POISON_ON_FREE=1
fn main() {
- let x: @mut @option<~int> = @mut @none;
+ let x: @mut @Option<~int> = @mut @None;
match x {
- @@some(y) => {
+ @@Some(y) => {
// here, the refcount of `*x` is bumped so
// `y` remains valid even if `*x` is modified.
- *x = @none;
+ *x = @None;
}
- @@none => {
+ @@None => {
// here, no bump of the ref count of `*x` is needed, but in
// fact a bump occurs anyway because of how pattern marching
// works.
// exec-env:RUST_POISON_ON_FREE=1
-fn switcher(x: option<@int>) {
+fn switcher(x: Option<@int>) {
let mut x = x;
match x {
- some(@y) => { copy y; x = none; }
- none => { }
+ Some(@y) => { copy y; x = None; }
+ None => { }
}
}
fn main() {
- switcher(none);
- switcher(some(@3));
+ switcher(None);
+ switcher(Some(@3));
}
\ No newline at end of file
// the boxed type parameter
type Tree<T> = {
- mut parent: option<T>,
+ mut parent: Option<T>,
};
fn empty<T>() -> Tree<T> { fail }
}
enum layout_data = {
- mut box: option<@Box>
+ mut box: Option<@Box>
};
fn main() { }
\ No newline at end of file
fn contains_key_ref(k: &int) -> bool { self.contains_key(*k) }
fn get(+k:int) -> T { match self.find(k) {
- some(v) => { v }
- none => { fail ~"epic fail"; }
+ Some(v) => { v }
+ None => { fail ~"epic fail"; }
}
}
- fn find(+k:int) -> option<T> { if k <= self.meows {
- some(self.name)
+ fn find(+k:int) -> Option<T> { if k <= self.meows {
+ Some(self.name)
}
- else { none }
+ else { None }
}
fn remove(+k:int) -> bool {
match self.find(k) {
- some(x) => {
+ Some(x) => {
self.meows -= k; true
}
- none => { false }
+ None => { false }
}
}
fn main() {
let nyan : cat<~str> = cat(0, 2, ~"nyan");
for uint::range(1u, 5u) |_i| { nyan.speak(); }
- assert(nyan.find(1) == some(~"nyan"));
- assert(nyan.find(10) == none);
+ assert(nyan.find(1) == Some(~"nyan"));
+ assert(nyan.find(10) == None);
let spotty : cat<cat_type> = cat(2, 57, tuxedo);
for uint::range(0u, 6u) |_i| { spotty.speak(); }
assert(spotty.size() == 8u);
struct kitten {
- let cat: option<cat>;
- new(cat: option<cat>) {
+ let cat: Option<cat>;
+ new(cat: Option<cat>) {
self.cat = cat;
}
}
type an_int = int;
-fn cmp(x: option<an_int>, y: option<int>) -> bool {
+fn cmp(x: Option<an_int>, y: Option<int>) -> bool {
x == y
}
fn main() {
- assert !cmp(some(3), none);
- assert !cmp(some(3), some(4));
- assert cmp(some(3), some(3));
- assert cmp(none, none);
+ assert !cmp(Some(3), None);
+ assert !cmp(Some(3), Some(4));
+ assert cmp(Some(3), Some(3));
+ assert cmp(None, None);
}
\ No newline at end of file
trait thing<A> {
- fn foo() -> option<A>;
+ fn foo() -> Option<A>;
}
impl<A> int: thing<A> {
- fn foo() -> option<A> { none }
+ fn foo() -> Option<A> { None }
}
-fn foo_func<A, B: thing<A>>(x: B) -> option<A> { x.foo() }
+fn foo_func<A, B: thing<A>>(x: B) -> Option<A> { x.foo() }
fn main() {
- for iter::eachi(some({a: 0})) |i, a| {
+ for iter::eachi(Some({a: 0})) |i, a| {
#debug["%u %d", i, a.a];
}
- let _x: option<float> = foo_func(0);
+ let _x: Option<float> = foo_func(0);
}
// exec-env:TEST_EXEC_ENV=22
fn main() {
- assert os::getenv(~"TEST_EXEC_ENV") == some(~"22");
+ assert os::getenv(~"TEST_EXEC_ENV") == Some(~"22");
}
use std;
import option = option;
-import option::some;
-import option::none;
+import option::Some;
+import option::None;
import str;
import vec;
import std::map;
val: ~str) {
let mut c;
match im.find(key) {
- some(_c) => { c = _c }
- none => {
+ Some(_c) => { c = _c }
+ None => {
let p = port();
error!("sending find_reducer");
send(ctrl, find_reducer(str::to_bytes(key), chan(p)));
find_reducer(k, cc) => {
let mut c;
match reducers.find(str::from_bytes(k)) {
- some(_c) => { c = _c; }
- none => { c = 0; }
+ Some(_c) => { c = _c; }
+ None => { c = 0; }
}
send(cc, c);
}
enum ear_kind { lop, upright }
enum animal { cat(pattern), dog(breed), rabbit(name, ear_kind), tiger }
-fn noise(a: animal) -> option<~str> {
+fn noise(a: animal) -> Option<~str> {
match a {
- cat(*) => { some(~"meow") }
- dog(*) => { some(~"woof") }
- rabbit(*) => { none }
- tiger(*) => { some(~"roar") }
+ cat(*) => { Some(~"meow") }
+ dog(*) => { Some(~"woof") }
+ rabbit(*) => { None }
+ tiger(*) => { Some(~"roar") }
}
}
fn main() {
- assert noise(cat(tabby)) == some(~"meow");
- assert noise(dog(pug)) == some(~"woof");
- assert noise(rabbit(~"Hilbert", upright)) == none;
- assert noise(tiger) == some(~"roar");
+ assert noise(cat(tabby)) == Some(~"meow");
+ assert noise(dog(pug)) == Some(~"woof");
+ assert noise(rabbit(~"Hilbert", upright)) == None;
+ assert noise(tiger) == Some(~"roar");
}
\ No newline at end of file
type packet<T: send> = {
mut state: state,
- mut blocked_task: option<task::Task>,
- mut payload: option<T>
+ mut blocked_task: Option<task::Task>,
+ mut payload: Option<T>
};
fn packet<T: send>() -> *packet<T> unsafe {
let p: *packet<T> = unsafe::transmute(~{
mut state: empty,
- mut blocked_task: none::<task::Task>,
- mut payload: none::<T>
+ mut blocked_task: None::<task::Task>,
+ mut payload: None::<T>
});
p
}
fn send<T: send>(-p: send_packet<T>, -payload: T) {
let p = p.unwrap();
let p = unsafe { uniquify(p) };
- assert (*p).payload == none;
- (*p).payload <- some(payload);
+ assert (*p).payload == None;
+ (*p).payload <- Some(payload);
let old_state = swap_state_rel(&mut (*p).state, full);
match old_state {
empty => {
}
}
- fn recv<T: send>(-p: recv_packet<T>) -> option<T> {
+ fn recv<T: send>(-p: recv_packet<T>) -> Option<T> {
let p = p.unwrap();
let p = unsafe { uniquify(p) };
loop {
match old_state {
empty | blocked => { task::yield(); }
full => {
- let mut payload = none;
+ let mut payload = None;
payload <-> (*p).payload;
- return some(option::unwrap(payload))
+ return Some(option::unwrap(payload))
}
terminated => {
assert old_state == terminated;
- return none;
+ return None;
}
}
}
}
struct send_packet<T: send> {
- let mut p: option<*packet<T>>;
- new(p: *packet<T>) { self.p = some(p); }
+ let mut p: Option<*packet<T>>;
+ new(p: *packet<T>) { self.p = Some(p); }
drop {
- if self.p != none {
- let mut p = none;
+ if self.p != None {
+ let mut p = None;
p <-> self.p;
sender_terminate(option::unwrap(p))
}
}
fn unwrap() -> *packet<T> {
- let mut p = none;
+ let mut p = None;
p <-> self.p;
option::unwrap(p)
}
}
struct recv_packet<T: send> {
- let mut p: option<*packet<T>>;
- new(p: *packet<T>) { self.p = some(p); }
+ let mut p: Option<*packet<T>>;
+ new(p: *packet<T>) { self.p = Some(p); }
drop {
- if self.p != none {
- let mut p = none;
+ if self.p != None {
+ let mut p = None;
p <-> self.p;
receiver_terminate(option::unwrap(p))
}
}
fn unwrap() -> *packet<T> {
- let mut p = none;
+ let mut p = None;
p <-> self.p;
option::unwrap(p)
}
fn do_pong(-c: pong) -> (ping, ()) {
let packet = pipes::recv(c);
- if packet == none {
+ if packet == None {
fail ~"sender closed the connection"
}
(liberate_pong(option::unwrap(packet)), ())
fn do_ping(-c: ping) -> (pong, ()) {
let packet = pipes::recv(c);
- if packet == none {
+ if packet == None {
fail ~"sender closed the connection"
}
(liberate_ping(option::unwrap(packet)), ())
{
match table.find(key)
{
- option::some(std::json::string(s)) =>
+ option::Some(std::json::string(s)) =>
{
*s
}
- option::some(value) =>
+ option::Some(value) =>
{
error!("%s was expected to be a string but is a %?", key, value);
default
}
- option::none =>
+ option::None =>
{
default
}
fn main() {
let b = @mut 0;
{
- let p = some(r(b));
+ let p = Some(r(b));
}
assert *b == 1;
assert [2u, 4u]/_.all(is_even);
assert []/_.all(is_even);
- assert !some(1u).all(is_even);
- assert some(2u).all(is_even);
- assert none.all(is_even);
+ assert !Some(1u).all(is_even);
+ assert Some(2u).all(is_even);
+ assert None.all(is_even);
}
assert [1u, 2u]/_.any(is_even);
assert ![]/_.any(is_even);
- assert !some(1u).any(is_even);
- assert some(2u).any(is_even);
- assert !none.any(is_even);
+ assert !Some(1u).any(is_even);
+ assert Some(2u).any(is_even);
+ assert !None.any(is_even);
}
assert [22u, 1u, 3u]/_.contains(22u) == true;
assert [1u, 22u, 3u]/_.contains(22u) == true;
assert [1u, 3u, 22u]/_.contains(22u) == true;
- assert none.contains(22u) == false;
- assert some(1u).contains(22u) == false;
- assert some(22u).contains(22u) == true;
+ assert None.contains(22u) == false;
+ assert Some(1u).contains(22u) == false;
+ assert Some(22u).contains(22u) == true;
}
assert [1u, 3u]/_.count(22u) == 0u;
assert [22u, 1u, 3u]/_.count(22u) == 1u;
assert [22u, 1u, 22u]/_.count(22u) == 2u;
- assert none.count(22u) == 0u;
- assert some(1u).count(22u) == 0u;
- assert some(22u).count(22u) == 1u;
+ assert None.count(22u) == 0u;
+ assert Some(1u).count(22u) == 0u;
+ assert Some(22u).count(22u) == 1u;
}
}
assert c == 5u;
- for none::<uint>.eachi |i, v| { fail; }
+ for None::<uint>.eachi |i, v| { fail; }
let mut c = 0u;
- for some(1u).eachi |i, v| {
+ for Some(1u).eachi |i, v| {
assert (i + 1u) == v;
c += 1u;
}
fn main() {
assert [1u, 3u]/_.filter_to_vec(is_even) == ~[];
assert [1u, 2u, 3u]/_.filter_to_vec(is_even) == ~[2u];
- assert none.filter_to_vec(is_even) == ~[];
- assert some(1u).filter_to_vec(is_even) == ~[];
- assert some(2u).filter_to_vec(is_even) == ~[2u];
+ assert None.filter_to_vec(is_even) == ~[];
+ assert Some(1u).filter_to_vec(is_even) == ~[];
+ assert Some(2u).filter_to_vec(is_even) == ~[2u];
}
fn main() {
assert [1u, 3u]/_.foldl(20f, add) == 24f;
assert []/_.foldl(20f, add) == 20f;
- assert none.foldl(20f, add) == 20f;
- assert some(1u).foldl(20f, add) == 21f;
- assert some(2u).foldl(20f, add) == 22f;
+ assert None.foldl(20f, add) == 20f;
+ assert Some(1u).foldl(20f, add) == 21f;
+ assert Some(2u).foldl(20f, add) == 22f;
}
fn main() {
assert [1u, 3u]/_.map_to_vec(inc) == ~[2u, 4u];
assert [1u, 2u, 3u]/_.map_to_vec(inc) == ~[2u, 3u, 4u];
- assert none.map_to_vec(inc) == ~[];
- assert some(1u).map_to_vec(inc) == ~[2u];
- assert some(2u).map_to_vec(inc) == ~[3u];
+ assert None.map_to_vec(inc) == ~[];
+ assert Some(1u).map_to_vec(inc) == ~[2u];
+ assert Some(2u).map_to_vec(inc) == ~[3u];
}
fn main() {
assert [1u, 3u]/_.min() == 1u;
assert [3u, 1u]/_.min() == 1u;
- assert some(1u).min() == 1u;
+ assert Some(1u).min() == 1u;
assert [1u, 3u]/_.max() == 3u;
assert [3u, 1u]/_.max() == 3u;
- assert some(3u).max() == 3u;
+ assert Some(3u).max() == 3u;
}
assert [1u, 3u]/_.to_vec() == ~[1u, 3u];
let e: ~[uint] = ~[];
assert e.to_vec() == ~[];
- assert none::<uint>.to_vec() == ~[];
- assert some(1u).to_vec() == ~[1u];
- assert some(2u).to_vec() == ~[2u];
+ assert None::<uint>.to_vec() == ~[];
+ assert Some(1u).to_vec() == ~[1u];
+ assert Some(2u).to_vec() == ~[2u];
}
fn main() {
let p = test_comm::port();
- match none::<int> {
- none => {}
- some(_) =>{
+ match None::<int> {
+ None => {}
+ Some(_) =>{
if test_comm::recv(p) == 0 {
error!("floop");
}
macro_rules! overly_complicated (
($fnname:ident, $arg:ident, $ty:ty, $body:block, $val:expr, $pat:pat, $res:path) =>
{
- fn $fnname($arg: $ty) -> option<$ty> $body
+ fn $fnname($arg: $ty) -> Option<$ty> $body
match $fnname($val) {
- some($pat) => {
+ Some($pat) => {
$res
}
_ => { fail; }
)
fn main() {
- assert overly_complicated!(f, x, option<uint>, { return some(x); },
- some(8u), some(y), y) == 8u
+ assert overly_complicated!(f, x, Option<uint>, { return Some(x); },
+ Some(8u), Some(y), y) == 8u
}
\ No newline at end of file
}
trait option_monad<A> {
- fn bind<B>(f: fn(A) -> option<B>) -> option<B>;
+ fn bind<B>(f: fn(A) -> Option<B>) -> Option<B>;
}
-impl<A> option<A>: option_monad<A> {
- fn bind<B>(f: fn(A) -> option<B>) -> option<B> {
+impl<A> Option<A>: option_monad<A> {
+ fn bind<B>(f: fn(A) -> Option<B>) -> Option<B> {
match self {
- some(a) => { f(a) }
- none => { none }
+ Some(a) => { f(a) }
+ None => { None }
}
}
}
-fn transform(x: option<int>) -> option<~str> {
- x.bind(|n| some(n + 1) ).bind(|n| some(int::str(n)) )
+fn transform(x: Option<int>) -> Option<~str> {
+ x.bind(|n| Some(n + 1) ).bind(|n| Some(int::str(n)) )
}
fn main() {
- assert transform(some(10)) == some(~"11");
- assert transform(none) == none;
+ assert transform(Some(10)) == Some(~"11");
+ assert transform(None) == None;
assert (~[~"hi"]).bind(|x| ~[x, x + ~"!"] ).bind(|x| ~[x, x + ~"?"] ) ==
~[~"hi", ~"hi?", ~"hi!", ~"hi!?"];
}
fn baz() -> ! { fail; }
fn foo() {
- match some::<int>(5) {
- some::<int>(x) => {
+ match Some::<int>(5) {
+ Some::<int>(x) => {
let mut bar;
- match none::<int> { none::<int> => { bar = 5; } _ => { baz(); } }
+ match None::<int> { None::<int> => { bar = 5; } _ => { baz(); } }
log(debug, bar);
}
- none::<int> => { debug!("hello"); }
+ None::<int> => { debug!("hello"); }
}
}
fn main() {
- match @{foo: true, bar: some(10), baz: 20} {
- @{foo: true, bar: some(_), _} => {}
- @{foo: false, bar: none, _} => {}
- @{foo: true, bar: none, _} => {}
- @{foo: false, bar: some(_), _} => {}
+ match @{foo: true, bar: Some(10), baz: 20} {
+ @{foo: true, bar: Some(_), _} => {}
+ @{foo: false, bar: None, _} => {}
+ @{foo: true, bar: None, _} => {}
+ @{foo: false, bar: Some(_), _} => {}
}
}
// a bug was causing this to complain about leaked memory on exit
use std;
import option;
-import option::some;
-import option::none;
+import option::Some;
+import option::None;
-enum t { foo(int, uint), bar(int, option<int>), }
+enum t { foo(int, uint), bar(int, Option<int>), }
fn nested(o: t) {
match o {
- bar(i, some::<int>(_)) => { error!("wrong pattern matched"); fail; }
+ bar(i, Some::<int>(_)) => { error!("wrong pattern matched"); fail; }
_ => { error!("succeeded"); }
}
}
-fn main() { nested(bar(1, none::<int>)); }
+fn main() { nested(bar(1, None::<int>)); }
}
}
-fn unwrap<T>(+o: option<T>) -> T {
+fn unwrap<T>(+o: Option<T>) -> T {
match move o {
- some(move v) => v,
- none => fail
+ Some(move v) => v,
+ None => fail
}
}
let x = @mut 1;
{
- let b = some(dtor { x:x });
+ let b = Some(dtor { x:x });
let c = unwrap(b);
}
fn foo(src: uint) {
- match some(src) {
- some(src_id) => {
+ match Some(src) {
+ Some(src_id) => {
for uint::range(0u, 10u) |i| {
let yyy = src_id;
assert (yyy == 0u);
)
fn switch<T: send, U>(+endp: pipes::recv_packet<T>,
- f: fn(+option<T>) -> U) -> U {
+ f: fn(+Option<T>) -> U) -> U {
f(pipes::try_recv(endp))
}
$($message:path$(($($x: ident),+))||* -> $next:ident $e:expr)+
} => (
|m| match move m {
- $(some($message($($($x,)+)* next)) => {
+ $(Some($message($($($x,)+)* next)) => {
let $next = move_it!(next);
$e })+
_ => { fail }
let bank = client::login(bank, ~"theincredibleholk", ~"1234");
let bank = match try_recv(bank) {
- some(ok(connected)) => {
+ Some(ok(connected)) => {
move_it!(connected)
}
- some(invalid(_)) => { fail ~"login unsuccessful" }
- none => { fail ~"bank closed the connection" }
+ Some(invalid(_)) => { fail ~"login unsuccessful" }
+ None => { fail ~"bank closed the connection" }
};
let bank = client::deposit(bank, 100.00);
let bank = client::withdrawal(bank, 50.00);
match try_recv(bank) {
- some(money(m, _)) => {
+ Some(money(m, _)) => {
io::println(~"Yay! I got money!");
}
- some(insufficient_funds(_)) => {
+ Some(insufficient_funds(_)) => {
fail ~"someone stole my money"
}
- none => {
+ None => {
fail ~"bank closed the connection"
}
}
pipes::spawn_service(oneshot::init, |p| {
match try_recv(p) {
- some(*) => { fail }
- none => { }
+ Some(*) => { fail }
+ None => { }
}
});
fn main() {
let (client_, server_) = pingpong::init();
- let client_ = ~mut some(client_);
- let server_ = ~mut some(server_);
+ let client_ = ~mut Some(client_);
+ let server_ = ~mut Some(server_);
do task::spawn |move client_| {
- let mut client__ = none;
+ let mut client__ = None;
*client_ <-> client__;
test::client(option::unwrap(client__));
};
do task::spawn |move server_| {
- let mut server_ˊ = none;
+ let mut server_ˊ = None;
*server_ <-> server_ˊ;
test::server(option::unwrap(server_ˊ));
};
fn main() {
let (client_, server_) = pingpong::init();
- let client_ = ~mut some(client_);
- let server_ = ~mut some(server_);
+ let client_ = ~mut Some(client_);
+ let server_ = ~mut Some(server_);
do task::spawn |move client_| {
- let mut client__ = none;
+ let mut client__ = None;
*client_ <-> client__;
test::client(option::unwrap(client__));
};
do task::spawn |move server_| {
- let mut server_ˊ = none;
+ let mut server_ˊ = None;
*server_ <-> server_ˊ;
test::server(option::unwrap(server_ˊ));
};
} => {
if $index == $count {
match move pipes::try_recv($port) {
- $(some($message($($(move $x,)+)* next)) => {
+ $(Some($message($($(move $x,)+)* next)) => {
let $next = unsafe { let x <- *ptr::addr_of(next); x };
$e
})+
error!("selecting");
let (i, m, _) = select(~[left, right]);
error!("selected %?", i);
- if m != none {
+ if m != None {
assert i == 1;
}
});
-fn get<T>(opt: &r/option<T>) -> &r/T {
+fn get<T>(opt: &r/Option<T>) -> &r/T {
match *opt {
- some(ref v) => v,
- none => fail ~"none"
+ Some(ref v) => v,
+ None => fail ~"none"
}
}
fn main() {
- let mut x = some(23);
+ let mut x = Some(23);
{
let y = get(&x);
assert *y == 23;
}
- x = some(24);
+ x = Some(24);
{
let y = get(&x);
}
enum t = {
- mut next: option<@t>,
+ mut next: Option<@t>,
r: r
};
unsafe::forget(i2);
let x1 = @t({
- mut next: none,
+ mut next: None,
r: {
let rs = r(i1p);
debug!("r = %x",
unsafe::reinterpret_cast::<*r, uint>(ptr::addr_of(x1.r)));
let x2 = @t({
- mut next: none,
+ mut next: None,
r: {
let rs = r(i2p);
debug!("r2 = %x",
unsafe::reinterpret_cast::<@t, uint>(x2),
unsafe::reinterpret_cast::<*r, uint>(ptr::addr_of(x2.r)));
- x1.next = some(x2);
- x2.next = some(x1);
+ x1.next = Some(x2);
+ x2.next = Some(x1);
}
}
enum t = {
- mut next: option<@t>,
+ mut next: Option<@t>,
r: r
};
let u2 = {a: 0xB, b: 0xC, c: i2p};
let x1 = @t({
- mut next: none,
+ mut next: None,
r: r(u1)
});
let x2 = @t({
- mut next: none,
+ mut next: None,
r: r(u2)
});
- x1.next = some(x2);
- x2.next = some(x1);
+ x1.next = Some(x2);
+ x2.next = Some(x1);
}
}
enum t = {
- mut next: option<@t>,
+ mut next: Option<@t>,
r: r
};
let u2 = {a: 0xB, b: 0xC, c: i2p};
let x1 = @t({
- mut next: none,
+ mut next: None,
r: r(u1, 42, i1p)
});
let x2 = @t({
- mut next: none,
+ mut next: None,
r: r(u2, 42, i2p)
});
- x1.next = some(x2);
- x2.next = some(x1);
+ x1.next = Some(x2);
+ x2.next = Some(x1);
}
}
}
-fn find_pos<T>(n: T, h: ~[T]) -> option<uint> {
+fn find_pos<T>(n: T, h: ~[T]) -> Option<uint> {
let mut i = 0u;
for iter(h) |e| {
- if e == n { return some(i); }
+ if e == n { return Some(i); }
i += 1u;
}
- none
+ None
}
fn bail_deep(x: ~[~[bool]]) {
};
assert last == 5;
- assert find_pos(1, ~[0, 1, 2, 3]) == some(1u);
- assert find_pos(1, ~[0, 4, 2, 3]) == none;
- assert find_pos(~"hi", ~[~"foo", ~"bar", ~"baz", ~"hi"]) == some(3u);
+ assert find_pos(1, ~[0, 1, 2, 3]) == Some(1u);
+ assert find_pos(1, ~[0, 4, 2, 3]) == None;
+ assert find_pos(~"hi", ~[~"foo", ~"bar", ~"baz", ~"hi"]) == Some(3u);
bail_deep(~[~[false, false], ~[true, true], ~[false, true]]);
bail_deep(~[~[true]]);
} => {
if $index == $count {
match move pipes::try_recv($port) {
- $(some($message($($(ref $x,)+)* ref next)) => {
+ $(Some($message($($(ref $x,)+)* ref next)) => {
// FIXME (#2329) we really want move out of enum here.
let $next = unsafe { let x <- *ptr::addr_of(*next); x };
$e
fn main() {
assert read(~"5") == 5;
- assert readMaybeRenamed(~"false") == some(false);
- assert readMaybeRenamed(~"foo") == none::<bool>;
+ assert readMaybeRenamed(~"false") == Some(false);
+ assert readMaybeRenamed(~"foo") == None::<bool>;
}
fn test00() {
let i: int = 0;
- let mut result = none;
- do task::task().future_result(|+r| { result = some(r); }).spawn {
+ let mut result = None;
+ do task::task().future_result(|+r| { result = Some(r); }).spawn {
start(i)
}
let number_of_messages: int = 10;
let ch = p.chan();
- let mut result = none;
- do task::task().future_result(|+r| { result = some(r); }).spawn {
+ let mut result = None;
+ do task::task().future_result(|+r| { result = Some(r); }).spawn {
test00_start(ch, number_of_messages);
}
enum Tree = TreeR;
type TreeR = @{
- mut left: option<Tree>,
- mut right: option<Tree>,
+ mut left: Option<Tree>,
+ mut right: Option<Tree>,
val: to_str
};
fn to_str() -> ~str;
}
-impl <T: to_str> option<T>: to_str {
+impl <T: to_str> Option<T>: to_str {
fn to_str() -> ~str {
match self {
- none => { ~"none" }
- some(t) => { ~"some(" + t.to_str() + ~")" }
+ None => { ~"none" }
+ Some(t) => { ~"some(" + t.to_str() + ~")" }
}
}
}
fn foo<T: to_str>(x: T) -> ~str { x.to_str() }
fn main() {
- let t1 = Tree(@{mut left: none,
- mut right: none,
+ let t1 = Tree(@{mut left: None,
+ mut right: None,
val: 1 as to_str });
- let t2 = Tree(@{mut left: some(t1),
- mut right: some(t1),
+ let t2 = Tree(@{mut left: Some(t1),
+ mut right: Some(t1),
val: 2 as to_str });
let expected = ~"[2, some([1, none, none]), some([1, none, none])]";
assert t2.to_str() == expected;
assert foo(t2 as to_str) == expected;
- t1.left = some(t2); // create cycle
+ t1.left = Some(t2); // create cycle
}
import task::*;
fn main() {
- let mut result = none;
- task::task().future_result(|+r| { result = some(r); }).spawn(child);
+ let mut result = None;
+ task::task().future_result(|+r| { result = Some(r); }).spawn(child);
error!("1");
yield();
error!("2");
import task::*;
fn main() {
- let mut result = none;
- task::task().future_result(|+r| { result = some(r); }).spawn(child);
+ let mut result = None;
+ task::task().future_result(|+r| { result = Some(r); }).spawn(child);
error!("1");
yield();
future::get(&option::unwrap(result));