diff --git a/src/compiletest/compiletest.rs b/src/compiletest/compiletest.rs index 270b1097c55..93324007f98 100644 --- a/src/compiletest/compiletest.rs +++ b/src/compiletest/compiletest.rs @@ -91,10 +91,10 @@ pub fn parse_config(args: ~[~str]) -> config { let matches = &match getopts::groups::getopts(args_, groups) { Ok(m) => m, - Err(f) => fail!(getopts::fail_str(f)) + Err(f) => fail!(f.to_err_msg()) }; - if getopts::opt_present(matches, "h") || getopts::opt_present(matches, "help") { + if matches.opt_present("h") || matches.opt_present("help") { let message = fmt!("Usage: %s [OPTIONS] [TESTNAME...]", argv0); println(getopts::groups::usage(message, groups)); println(""); @@ -102,53 +102,51 @@ pub fn parse_config(args: ~[~str]) -> config { } fn opt_path(m: &getopts::Matches, nm: &str) -> Path { - Path(getopts::opt_str(m, nm)) + Path(m.opt_str(nm).unwrap()) } config { - compile_lib_path: getopts::opt_str(matches, "compile-lib-path"), - run_lib_path: getopts::opt_str(matches, "run-lib-path"), + compile_lib_path: matches.opt_str("compile-lib-path").unwrap(), + run_lib_path: matches.opt_str("run-lib-path").unwrap(), rustc_path: opt_path(matches, "rustc-path"), - clang_path: getopts::opt_maybe_str(matches, "clang-path").map_move(|s| Path(s)), - llvm_bin_path: getopts::opt_maybe_str(matches, "llvm-bin-path").map_move(|s| Path(s)), + clang_path: matches.opt_str("clang-path").map_move(|s| Path(s)), + llvm_bin_path: matches.opt_str("llvm-bin-path").map_move(|s| Path(s)), src_base: opt_path(matches, "src-base"), build_base: opt_path(matches, "build-base"), aux_base: opt_path(matches, "aux-base"), - stage_id: getopts::opt_str(matches, "stage-id"), - mode: str_mode(getopts::opt_str(matches, "mode")), - run_ignored: getopts::opt_present(matches, "ignored"), + stage_id: matches.opt_str("stage-id").unwrap(), + mode: str_mode(matches.opt_str("mode").unwrap()), + run_ignored: matches.opt_present("ignored"), filter: if !matches.free.is_empty() { Some(matches.free[0].clone()) } else { None }, - logfile: getopts::opt_maybe_str(matches, "logfile").map_move(|s| Path(s)), - save_metrics: getopts::opt_maybe_str(matches, "save-metrics").map_move(|s| Path(s)), + logfile: matches.opt_str("logfile").map_move(|s| Path(s)), + save_metrics: matches.opt_str("save-metrics").map_move(|s| Path(s)), ratchet_metrics: - getopts::opt_maybe_str(matches, "ratchet-metrics").map_move(|s| Path(s)), + matches.opt_str("ratchet-metrics").map_move(|s| Path(s)), ratchet_noise_percent: - getopts::opt_maybe_str(matches, - "ratchet-noise-percent").map_move(|s| - from_str::(s).unwrap()), - runtool: getopts::opt_maybe_str(matches, "runtool"), - rustcflags: getopts::opt_maybe_str(matches, "rustcflags"), - jit: getopts::opt_present(matches, "jit"), - target: opt_str2(getopts::opt_maybe_str(matches, "target")).to_str(), - adb_path: opt_str2(getopts::opt_maybe_str(matches, "adb-path")).to_str(), + matches.opt_str("ratchet-noise-percent").and_then(|s| from_str::(s)), + runtool: matches.opt_str("runtool"), + rustcflags: matches.opt_str("rustcflags"), + jit: matches.opt_present("jit"), + target: opt_str2(matches.opt_str("target")).to_str(), + adb_path: opt_str2(matches.opt_str("adb-path")).to_str(), adb_test_dir: - opt_str2(getopts::opt_maybe_str(matches, "adb-test-dir")).to_str(), + opt_str2(matches.opt_str("adb-test-dir")).to_str(), adb_device_status: - if (opt_str2(getopts::opt_maybe_str(matches, "target")) == + if (opt_str2(matches.opt_str("target")) == ~"arm-linux-androideabi") { - if (opt_str2(getopts::opt_maybe_str(matches, "adb-test-dir")) != + if (opt_str2(matches.opt_str("adb-test-dir")) != ~"(none)" && - opt_str2(getopts::opt_maybe_str(matches, "adb-test-dir")) != + opt_str2(matches.opt_str("adb-test-dir")) != ~"") { true } else { false } } else { false }, - test_shard: test::opt_shard(getopts::opt_maybe_str(matches, "test-shard")), - verbose: getopts::opt_present(matches, "verbose") + test_shard: test::opt_shard(matches.opt_str("test-shard")), + verbose: matches.opt_present("verbose") } } diff --git a/src/libextra/getopts.rs b/src/libextra/getopts.rs index a21d9dc605f..0116c5a1f66 100644 --- a/src/libextra/getopts.rs +++ b/src/libextra/getopts.rs @@ -8,93 +8,89 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/*! - * Simple getopt alternative. - * - * Construct a vector of options, either by using reqopt, optopt, and optflag - * or by building them from components yourself, and pass them to getopts, - * along with a vector of actual arguments (not including argv[0]). You'll - * either get a failure code back, or a match. You'll have to verify whether - * the amount of 'free' arguments in the match is what you expect. Use opt_* - * accessors to get argument values out of the matches object. - * - * Single-character options are expected to appear on the command line with a - * single preceding dash; multiple-character options are expected to be - * proceeded by two dashes. Options that expect an argument accept their - * argument following either a space or an equals sign. Single-character - * options don't require the space. - * - * # Example - * - * The following example shows simple command line parsing for an application - * that requires an input file to be specified, accepts an optional output - * file name following -o, and accepts both -h and --help as optional flags. - * - * ``` - * extern mod extra; - * use extra::getopts::*; - * use std::os; - * - * fn do_work(in: &str, out: Option<~str>) { - * println(in); - * println(match out { - * Some(x) => x, - * None => ~"No Output" - * }); - * } - * - * fn print_usage(program: &str, _opts: &[Opt]) { - * printfln!("Usage: %s [options]", program); - * println("-o\t\tOutput"); - * println("-h --help\tUsage"); - * } - * - * fn main() { - * let args = os::args(); - * - * let program = args[0].clone(); - * - * let opts = ~[ - * optopt("o"), - * optflag("h"), - * optflag("help") - * ]; - * let matches = match getopts(args.tail(), opts) { - * Ok(m) => { m } - * Err(f) => { fail!(fail_str(f)) } - * }; - * if opt_present(&matches, "h") || opt_present(&matches, "help") { - * print_usage(program, opts); - * return; - * } - * let output = opt_maybe_str(&matches, "o"); - * let input: &str = if !matches.free.is_empty() { - * matches.free[0].clone() - * } else { - * print_usage(program, opts); - * return; - * }; - * do_work(input, output); - * } - * ``` - */ - -#[allow(missing_doc)]; - +//! Simple getopt alternative. +//! +//! Construct a vector of options, either by using reqopt, optopt, and optflag +//! or by building them from components yourself, and pass them to getopts, +//! along with a vector of actual arguments (not including argv[0]). You'll +//! either get a failure code back, or a match. You'll have to verify whether +//! the amount of 'free' arguments in the match is what you expect. Use opt_* +//! accessors to get argument values out of the matches object. +//! +//! Single-character options are expected to appear on the command line with a +//! single preceding dash; multiple-character options are expected to be +//! proceeded by two dashes. Options that expect an argument accept their +//! argument following either a space or an equals sign. Single-character +//! options don't require the space. +//! +//! # Example +//! +//! The following example shows simple command line parsing for an application +//! that requires an input file to be specified, accepts an optional output +//! file name following -o, and accepts both -h and --help as optional flags. +//! +//! ``` +//! exter mod extra; +//! use extra::getopts::*; +//! use std::os; +//! +//! fn do_work(inp: &str, out: Option<~str>) { +//! println(inp); +//! println(match out { +//! Some(x) => x, +//! None => ~"No Output" +//! }); +//! } +//! +//! fn print_usage(program: &str, _opts: &[Opt]) { +//! printfln!("Usage: %s [options]", program); +//! println("-o\t\tOutput"); +//! println("-h --help\tUsage"); +//! } +//! +//! fn main() { +//! let args = os::args(); +//! +//! let program = args[0].clone(); +//! +//! let opts = ~[ +//! optopt("o"), +//! optflag("h"), +//! optflag("help") +//! ]; +//! let matches = match getopts(args.tail(), opts) { +//! Ok(m) => { m } +//! Err(f) => { fail!(f.to_err_msg()) } +//! }; +//! if matches.opt_present("h") || matches.opt_present("help") { +//! print_usage(program, opts); +//! return; +//! } +//! let output = matches.opt_str("o"); +//! let input: &str = if !matches.free.is_empty() { +//! matches.free[0].clone() +//! } else { +//! print_usage(program, opts); +//! return; +//! }; +//! do_work(input, output); +//! } +//! ``` use std::cmp::Eq; use std::result::{Err, Ok}; use std::result; use std::option::{Some, None}; -use std::str; use std::vec; +/// Name of an option. Either a string or a single char. #[deriving(Clone, Eq)] pub enum Name { Long(~str), Short(char), } +/// Describes whether an option has an argument. #[deriving(Clone, Eq)] pub enum HasArg { Yes, @@ -102,6 +98,7 @@ pub enum HasArg { Maybe, } +/// Describes how often an option may occur. #[deriving(Clone, Eq)] pub enum Occur { Req, @@ -109,107 +106,40 @@ pub enum Occur { Multi, } -/// A description of a possible option +/// A description of a possible option. #[deriving(Clone, Eq)] pub struct Opt { + /// Name of the option name: Name, + /// Wheter it has an argument hasarg: HasArg, + /// How often it can occur occur: Occur, + /// Which options it aliases aliases: ~[Opt], } -fn mkname(nm: &str) -> Name { - if nm.len() == 1u { - Short(nm.char_at(0u)) - } else { - Long(nm.to_owned()) - } -} - -/// Create an option that is required and takes an argument -pub fn reqopt(name: &str) -> Opt { - return Opt {name: mkname(name), hasarg: Yes, occur: Req, aliases: ~[]}; -} - -/// Create an option that is optional and takes an argument -pub fn optopt(name: &str) -> Opt { - return Opt {name: mkname(name), hasarg: Yes, occur: Optional, aliases: ~[]}; -} - -/// Create an option that is optional and does not take an argument -pub fn optflag(name: &str) -> Opt { - return Opt {name: mkname(name), hasarg: No, occur: Optional, aliases: ~[]}; -} - -/** Create an option that is optional, does not take an argument, - * and may occur multiple times. - */ -pub fn optflagmulti(name: &str) -> Opt { - return Opt {name: mkname(name), hasarg: No, occur: Multi, aliases: ~[]}; -} - -/// Create an option that is optional and takes an optional argument -pub fn optflagopt(name: &str) -> Opt { - return Opt {name: mkname(name), hasarg: Maybe, occur: Optional, aliases: ~[]}; -} - -/** - * Create an option that is optional, takes an argument, and may occur - * multiple times - */ -pub fn optmulti(name: &str) -> Opt { - return Opt {name: mkname(name), hasarg: Yes, occur: Multi, aliases: ~[]}; -} - +/// Describes wether an option is given at all or has a value. #[deriving(Clone, Eq)] enum Optval { Val(~str), Given, } -/** - * The result of checking command line arguments. Contains a vector - * of matches and a vector of free strings. - */ +/// The result of checking command line arguments. Contains a vector +/// of matches and a vector of free strings. #[deriving(Clone, Eq)] pub struct Matches { + /// Options that matched opts: ~[Opt], + /// Values of the Options that matched vals: ~[~[Optval]], + /// Free string fragments free: ~[~str] } -fn is_arg(arg: &str) -> bool { - return arg.len() > 1 && arg[0] == '-' as u8; -} - -fn name_str(nm: &Name) -> ~str { - return match *nm { - Short(ch) => str::from_char(ch), - Long(ref s) => (*s).clone() - }; -} - -fn find_opt(opts: &[Opt], nm: Name) -> Option { - // search main options - let pos = opts.iter().position(|opt| opt.name == nm); - if pos.is_some() { - return pos - } - - // search in aliases - for candidate in opts.iter() { - if candidate.aliases.iter().position(|opt| opt.name == nm).is_some() { - return opts.iter().position(|opt| opt.name == candidate.name); - } - } - - None -} - -/** - * The type returned when the command line does not conform to the - * expected format. Pass this value to to get an error message. - */ +/// The type returned when the command line does not conform to the +/// expected format. Pass this value to to get an error message. #[deriving(Clone, Eq, ToStr)] pub enum Fail_ { ArgumentMissing(~str), @@ -219,43 +149,250 @@ pub enum Fail_ { UnexpectedArgument(~str), } -/// Convert a `fail_` enum into an error string -pub fn fail_str(f: Fail_) -> ~str { - return match f { - ArgumentMissing(ref nm) => { - fmt!("Argument to option '%s' missing.", *nm) - } - UnrecognizedOption(ref nm) => { - fmt!("Unrecognized option: '%s'.", *nm) - } - OptionMissing(ref nm) => { - fmt!("Required option '%s' missing.", *nm) - } - OptionDuplicated(ref nm) => { - fmt!("Option '%s' given more than once.", *nm) - } - UnexpectedArgument(ref nm) => { - fmt!("Option '%s' does not take an argument.", *nm) - } - }; +/// The type of failure that occured. +#[deriving(Eq)] +pub enum FailType { + ArgumentMissing_, + UnrecognizedOption_, + OptionMissing_, + OptionDuplicated_, + UnexpectedArgument_, } -/** - * The result of parsing a command line with a set of options - * (result::t) - */ +/// The result of parsing a command line with a set of options. pub type Result = result::Result; -/** - * Parse command line arguments according to the provided options - * - * On success returns `ok(Opt)`. Use functions such as `opt_present` - * `opt_str`, etc. to interrogate results. Returns `err(Fail_)` on failure. - * Use to get an error message. - */ +impl Name { + fn from_str(nm: &str) -> Name { + if nm.len() == 1u { + Short(nm.char_at(0u)) + } else { + Long(nm.to_owned()) + } + } + + fn to_str(&self) -> ~str { + match *self { + Short(ch) => ch.to_str(), + Long(ref s) => s.to_owned() + } + } +} + +impl Matches { + /// FIXME: #9311 This used to be private, but rustpkg somehow managed to depend on it. + /// No idea what this does. + pub fn opt_vals(&self, nm: &str) -> ~[Optval] { + match find_opt(self.opts, Name::from_str(nm)) { + Some(id) => self.vals[id].clone(), + None => fail!("No option '%s' defined", nm) + } + } + + /// FIXME: #9311 This used to be private, but rustpkg somehow managed to depend on it. + /// No idea what this does. + pub fn opt_val(&self, nm: &str) -> Option { + let vals = self.opt_vals(nm); + if (vals.is_empty()) { + None + } else { + Some(vals[0].clone()) + } + } + + /// Returns true if an option was matched. + pub fn opt_present(&self, nm: &str) -> bool { + !self.opt_vals(nm).is_empty() + } + + /// Returns the number of times an option was matched. + pub fn opt_count(&self, nm: &str) -> uint { + self.opt_vals(nm).len() + } + + /// Returns true if any of several options were matched. + pub fn opts_present(&self, names: &[~str]) -> bool { + for nm in names.iter() { + match find_opt(self.opts, Name::from_str(*nm)) { + Some(id) if !self.vals[id].is_empty() => return true, + _ => (), + }; + } + false + } + + /// Returns the string argument supplied to one of several matching options or `None`. + pub fn opts_str(&self, names: &[~str]) -> Option<~str> { + for nm in names.iter() { + match self.opt_val(*nm) { + Some(Val(ref s)) => return Some(s.clone()), + _ => () + } + } + None + } + + /// Returns a vector of the arguments provided to all matches of the given + /// option. + /// + /// Used when an option accepts multiple values. + pub fn opt_strs(&self, nm: &str) -> ~[~str] { + let mut acc: ~[~str] = ~[]; + let r = self.opt_vals(nm); + for v in r.iter() { + match *v { + Val(ref s) => acc.push((*s).clone()), + _ => () + } + } + acc + } + + /// Returns the string argument supplied to a matching option or `None`. + pub fn opt_str(&self, nm: &str) -> Option<~str> { + let vals = self.opt_vals(nm); + if vals.is_empty() { + return None::<~str>; + } + match vals[0] { + Val(ref s) => Some((*s).clone()), + _ => None + } + } + + + /// Returns the matching string, a default, or none. + /// + /// Returns none if the option was not present, `def` if the option was + /// present but no argument was provided, and the argument if the option was + /// present and an argument was provided. + pub fn opt_default(&self, nm: &str, def: &str) -> Option<~str> { + let vals = self.opt_vals(nm); + if vals.is_empty() { return None; } + match vals[0] { + Val(ref s) => Some((*s).clone()), + _ => Some(def.to_owned()) + } + } + +} + +fn is_arg(arg: &str) -> bool { + arg.len() > 1 && arg[0] == '-' as u8 +} + +fn find_opt(opts: &[Opt], nm: Name) -> Option { + // Search main options. + let pos = opts.iter().position(|opt| opt.name == nm); + if pos.is_some() { + return pos + } + + // Search in aliases. + for candidate in opts.iter() { + if candidate.aliases.iter().position(|opt| opt.name == nm).is_some() { + return opts.iter().position(|opt| opt.name == candidate.name); + } + } + + None +} + +/// Create an option that is required and takes an argument. +pub fn reqopt(name: &str) -> Opt { + Opt { + name: Name::from_str(name), + hasarg: Yes, + occur: Req, + aliases: ~[] + } +} + +/// Create an option that is optional and takes an argument. +pub fn optopt(name: &str) -> Opt { + Opt { + name: Name::from_str(name), + hasarg: Yes, + occur: Optional, + aliases: ~[] + } +} + +/// Create an option that is optional and does not take an argument. +pub fn optflag(name: &str) -> Opt { + Opt { + name: Name::from_str(name), + hasarg: No, + occur: Optional, + aliases: ~[] + } +} + +/// Create an option that is optional, does not take an argument, +/// and may occur multiple times. +pub fn optflagmulti(name: &str) -> Opt { + Opt { + name: Name::from_str(name), + hasarg: No, + occur: Multi, + aliases: ~[] + } +} + +/// Create an option that is optional and takes an optional argument. +pub fn optflagopt(name: &str) -> Opt { + Opt { + name: Name::from_str(name), + hasarg: Maybe, + occur: Optional, + aliases: ~[] + } +} + +/// Create an option that is optional, takes an argument, and may occur +/// multiple times. +pub fn optmulti(name: &str) -> Opt { + Opt { + name: Name::from_str(name), + hasarg: Yes, + occur: Multi, + aliases: ~[] + } +} + +impl Fail_ { + /// Convert a `Fail_` enum into an error string. + pub fn to_err_msg(self) -> ~str { + match self { + ArgumentMissing(ref nm) => { + fmt!("Argument to option '%s' missing.", *nm) + } + UnrecognizedOption(ref nm) => { + fmt!("Unrecognized option: '%s'.", *nm) + } + OptionMissing(ref nm) => { + fmt!("Required option '%s' missing.", *nm) + } + OptionDuplicated(ref nm) => { + fmt!("Option '%s' given more than once.", *nm) + } + UnexpectedArgument(ref nm) => { + fmt!("Option '%s' does not take an argument.", *nm) + } + } + } +} + +/// Parse command line arguments according to the provided options. +/// +/// On success returns `Ok(Opt)`. Use methods such as `opt_present` +/// `opt_str`, etc. to interrogate results. Returns `Err(Fail_)` on failure. +/// Use `to_err_msg` to get an error message. pub fn getopts(args: &[~str], opts: &[Opt]) -> Result { let n_opts = opts.len(); + fn f(_x: uint) -> ~[Optval] { return ~[]; } + let mut vals = vec::from_fn(n_opts, f); let mut free: ~[~str] = ~[]; let l = args.len(); @@ -325,12 +462,12 @@ pub fn getopts(args: &[~str], opts: &[Opt]) -> Result { name_pos += 1; let optid = match find_opt(opts, (*nm).clone()) { Some(id) => id, - None => return Err(UnrecognizedOption(name_str(nm))) + None => return Err(UnrecognizedOption(nm.to_str())) }; match opts[optid].hasarg { No => { if !i_arg.is_none() { - return Err(UnexpectedArgument(name_str(nm))); + return Err(UnexpectedArgument(nm.to_str())); } vals[optid].push(Given); } @@ -346,7 +483,7 @@ pub fn getopts(args: &[~str], opts: &[Opt]) -> Result { if !i_arg.is_none() { vals[optid].push(Val(i_arg.clone().unwrap())); } else if i + 1 == l { - return Err(ArgumentMissing(name_str(nm))); + return Err(ArgumentMissing(nm.to_str())); } else { i += 1; vals[optid].push(Val(args[i].clone())); } } } @@ -360,289 +497,183 @@ pub fn getopts(args: &[~str], opts: &[Opt]) -> Result { let occ = opts[i].occur; if occ == Req { if n == 0 { - return Err(OptionMissing(name_str(&(opts[i].name)))); + return Err(OptionMissing(opts[i].name.to_str())); } } if occ != Multi { if n > 1 { - return Err(OptionDuplicated(name_str(&(opts[i].name)))); + return Err(OptionDuplicated(opts[i].name.to_str())); } } i += 1; } - return Ok(Matches {opts: opts.to_owned(), - vals: vals, - free: free}); + Ok(Matches { + opts: opts.to_owned(), + vals: vals, + free: free + }) } -fn opt_vals(mm: &Matches, nm: &str) -> ~[Optval] { - return match find_opt(mm.opts, mkname(nm)) { - Some(id) => mm.vals[id].clone(), - None => { - error!("No option '%s' defined", nm); - fail!() - } - }; -} - -fn opt_val(mm: &Matches, nm: &str) -> Option { - let vals = opt_vals(mm, nm); - if (vals.is_empty()) { - None - } else { - Some(opt_vals(mm, nm)[0].clone()) - } -} - -/// Returns true if an option was matched -pub fn opt_present(mm: &Matches, nm: &str) -> bool { - !opt_vals(mm, nm).is_empty() -} - -/// Returns the number of times an option was matched -pub fn opt_count(mm: &Matches, nm: &str) -> uint { - opt_vals(mm, nm).len() -} - -/// Returns true if any of several options were matched -pub fn opts_present(mm: &Matches, names: &[~str]) -> bool { - for nm in names.iter() { - match find_opt(mm.opts, mkname(*nm)) { - Some(id) if !mm.vals[id].is_empty() => return true, - _ => (), - }; - } - false -} - - -/** - * Returns the string argument supplied to a matching option - * - * Fails if the option was not matched or if the match did not take an - * argument - */ -pub fn opt_str(mm: &Matches, nm: &str) -> ~str { - return match opt_val(mm, nm) { - Some(Val(s)) => s, - _ => fail!() - }; -} - -/** - * Returns the string argument supplied to one of several matching options - * - * Fails if the no option was provided from the given list, or if the no such - * option took an argument - */ -pub fn opts_str(mm: &Matches, names: &[~str]) -> ~str { - for nm in names.iter() { - match opt_val(mm, *nm) { - Some(Val(ref s)) => return (*s).clone(), - _ => () - } - } - fail!(); -} - - -/** - * Returns a vector of the arguments provided to all matches of the given - * option. - * - * Used when an option accepts multiple values. - */ -pub fn opt_strs(mm: &Matches, nm: &str) -> ~[~str] { - let mut acc: ~[~str] = ~[]; - let r = opt_vals(mm, nm); - for v in r.iter() { - match *v { Val(ref s) => acc.push((*s).clone()), _ => () } - } - acc -} - -/// Returns the string argument supplied to a matching option or none -pub fn opt_maybe_str(mm: &Matches, nm: &str) -> Option<~str> { - let vals = opt_vals(mm, nm); - if vals.is_empty() { return None::<~str>; } - return match vals[0] { - Val(ref s) => Some((*s).clone()), - _ => None - }; -} - - -/** - * Returns the matching string, a default, or none - * - * Returns none if the option was not present, `def` if the option was - * present but no argument was provided, and the argument if the option was - * present and an argument was provided. - */ -pub fn opt_default(mm: &Matches, nm: &str, def: &str) -> Option<~str> { - let vals = opt_vals(mm, nm); - if vals.is_empty() { return None::<~str>; } - return match vals[0] { Val(ref s) => Some::<~str>((*s).clone()), - _ => Some::<~str>(def.to_owned()) } -} - -#[deriving(Eq)] -pub enum FailType { - ArgumentMissing_, - UnrecognizedOption_, - OptionMissing_, - OptionDuplicated_, - UnexpectedArgument_, -} - -/** A module which provides a way to specify descriptions and - * groups of short and long option names, together. - */ +/// A module which provides a way to specify descriptions and +/// groups of short and long option names, together. pub mod groups { use getopts::{HasArg, Long, Maybe, Multi, No, Occur, Opt, Optional, Req}; use getopts::{Short, Yes}; - /** one group of options, e.g., both -h and --help, along with - * their shared description and properties - */ + /// One group of options, e.g., both -h and --help, along with + /// their shared description and properties. #[deriving(Clone, Eq)] pub struct OptGroup { + /// Short Name of the `OptGroup` short_name: ~str, + /// Long Name of the `OptGroup` long_name: ~str, + /// Hint hint: ~str, + /// Description desc: ~str, + /// Whether it has an argument hasarg: HasArg, + /// How often it can occur occur: Occur } - /// Create a long option that is required and takes an argument - pub fn reqopt(short_name: &str, long_name: &str, - desc: &str, hint: &str) -> OptGroup { - let len = short_name.len(); - assert!(len == 1 || len == 0); - return OptGroup { short_name: short_name.to_owned(), - long_name: long_name.to_owned(), - hint: hint.to_owned(), - desc: desc.to_owned(), - hasarg: Yes, - occur: Req}; - } + impl OptGroup { + /// Translate OptGroup into Opt. + /// (Both short and long names correspond to different Opts). + pub fn long_to_short(&self) -> Opt { + let OptGroup { + short_name: short_name, + long_name: long_name, + hasarg: hasarg, + occur: occur, + _ + } = (*self).clone(); - /// Create a long option that is optional and takes an argument - pub fn optopt(short_name: &str, long_name: &str, - desc: &str, hint: &str) -> OptGroup { - let len = short_name.len(); - assert!(len == 1 || len == 0); - return OptGroup {short_name: short_name.to_owned(), - long_name: long_name.to_owned(), - hint: hint.to_owned(), - desc: desc.to_owned(), - hasarg: Yes, - occur: Optional}; - } - - /// Create a long option that is optional and does not take an argument - pub fn optflag(short_name: &str, long_name: &str, - desc: &str) -> OptGroup { - let len = short_name.len(); - assert!(len == 1 || len == 0); - return OptGroup {short_name: short_name.to_owned(), - long_name: long_name.to_owned(), - hint: ~"", - desc: desc.to_owned(), - hasarg: No, - occur: Optional}; - } - - /// Create a long option that can occur more than once and does not - /// take an argument - pub fn optflagmulti(short_name: &str, long_name: &str, - desc: &str) -> OptGroup { - let len = short_name.len(); - assert!(len == 1 || len == 0); - return OptGroup {short_name: short_name.to_owned(), - long_name: long_name.to_owned(), - hint: ~"", - desc: desc.to_owned(), - hasarg: No, - occur: Multi}; - } - - /// Create a long option that is optional and takes an optional argument - pub fn optflagopt(short_name: &str, long_name: &str, - desc: &str, hint: &str) -> OptGroup { - let len = short_name.len(); - assert!(len == 1 || len == 0); - return OptGroup {short_name: short_name.to_owned(), - long_name: long_name.to_owned(), - hint: hint.to_owned(), - desc: desc.to_owned(), - hasarg: Maybe, - occur: Optional}; - } - - /** - * Create a long option that is optional, takes an argument, and may occur - * multiple times - */ - pub fn optmulti(short_name: &str, long_name: &str, - desc: &str, hint: &str) -> OptGroup { - let len = short_name.len(); - assert!(len == 1 || len == 0); - return OptGroup {short_name: short_name.to_owned(), - long_name: long_name.to_owned(), - hint: hint.to_owned(), - desc: desc.to_owned(), - hasarg: Yes, - occur: Multi}; - } - - // translate OptGroup into Opt - // (both short and long names correspond to different Opts) - pub fn long_to_short(lopt: &OptGroup) -> Opt { - let OptGroup{short_name: short_name, - long_name: long_name, - hasarg: hasarg, - occur: occur, - _} = (*lopt).clone(); - - match (short_name.len(), long_name.len()) { - (0,0) => fail!("this long-format option was given no name"), - - (0,_) => Opt {name: Long((long_name)), - hasarg: hasarg, - occur: occur, - aliases: ~[]}, - - (1,0) => Opt {name: Short(short_name.char_at(0)), - hasarg: hasarg, - occur: occur, - aliases: ~[]}, - - (1,_) => Opt {name: Long((long_name)), - hasarg: hasarg, - occur: occur, - aliases: ~[Opt { - name: Short(short_name.char_at(0)), - hasarg: hasarg, - occur: occur, - aliases: ~[] - }]}, - - (_,_) => fail!("something is wrong with the long-form opt") + match (short_name.len(), long_name.len()) { + (0,0) => fail!("this long-format option was given no name"), + (0,_) => Opt { + name: Long((long_name)), + hasarg: hasarg, + occur: occur, + aliases: ~[] + }, + (1,0) => Opt { + name: Short(short_name.char_at(0)), + hasarg: hasarg, + occur: occur, + aliases: ~[] + }, + (1,_) => Opt { + name: Long((long_name)), + hasarg: hasarg, + occur: occur, + aliases: ~[ + Opt { + name: Short(short_name.char_at(0)), + hasarg: hasarg, + occur: occur, + aliases: ~[] + } + ] + }, + (_,_) => fail!("something is wrong with the long-form opt") + } } } - /* - * Parse command line args with the provided long format options - */ - pub fn getopts(args: &[~str], opts: &[OptGroup]) -> ::getopts::Result { - ::getopts::getopts(args, opts.map(long_to_short)) + /// Create a long option that is required and takes an argument. + pub fn reqopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptGroup { + let len = short_name.len(); + assert!(len == 1 || len == 0); + OptGroup { + short_name: short_name.to_owned(), + long_name: long_name.to_owned(), + hint: hint.to_owned(), + desc: desc.to_owned(), + hasarg: Yes, + occur: Req + } } - /** - * Derive a usage message from a set of long options - */ + /// Create a long option that is optional and takes an argument. + pub fn optopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptGroup { + let len = short_name.len(); + assert!(len == 1 || len == 0); + OptGroup { + short_name: short_name.to_owned(), + long_name: long_name.to_owned(), + hint: hint.to_owned(), + desc: desc.to_owned(), + hasarg: Yes, + occur: Optional + } + } + + /// Create a long option that is optional and does not take an argument. + pub fn optflag(short_name: &str, long_name: &str, desc: &str) -> OptGroup { + let len = short_name.len(); + assert!(len == 1 || len == 0); + OptGroup { + short_name: short_name.to_owned(), + long_name: long_name.to_owned(), + hint: ~"", + desc: desc.to_owned(), + hasarg: No, + occur: Optional + } + } + + /// Create a long option that can occur more than once and does not + /// take an argument. + pub fn optflagmulti(short_name: &str, long_name: &str, desc: &str) -> OptGroup { + let len = short_name.len(); + assert!(len == 1 || len == 0); + OptGroup { + short_name: short_name.to_owned(), + long_name: long_name.to_owned(), + hint: ~"", + desc: desc.to_owned(), + hasarg: No, + occur: Multi + } + } + + /// Create a long option that is optional and takes an optional argument. + pub fn optflagopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptGroup { + let len = short_name.len(); + assert!(len == 1 || len == 0); + OptGroup { + short_name: short_name.to_owned(), + long_name: long_name.to_owned(), + hint: hint.to_owned(), + desc: desc.to_owned(), + hasarg: Maybe, + occur: Optional + } + } + + /// Create a long option that is optional, takes an argument, and may occur + /// multiple times. + pub fn optmulti(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptGroup { + let len = short_name.len(); + assert!(len == 1 || len == 0); + OptGroup { + short_name: short_name.to_owned(), + long_name: long_name.to_owned(), + hint: hint.to_owned(), + desc: desc.to_owned(), + hasarg: Yes, + occur: Multi + } + } + + /// Parse command line args with the provided long format options. + pub fn getopts(args: &[~str], opts: &[OptGroup]) -> ::getopts::Result { + ::getopts::getopts(args, opts.map(|x| x.long_to_short())) + } + + /// Derive a usage message from a set of long options. pub fn usage(brief: &str, opts: &[OptGroup]) -> ~str { let desc_sep = "\n" + " ".repeat(24); @@ -721,28 +752,24 @@ pub mod groups { row }); - return brief.to_owned() + - "\n\nOptions:\n" + - rows.collect::<~[~str]>().connect("\n") + - "\n"; + fmt!("%s\n\nOptions:\n%s\n", brief, rows.collect::<~[~str]>().connect("\n")) } - /** Splits a string into substrings with possibly internal whitespace, - * each of them at most `lim` bytes long. The substrings have leading and trailing - * whitespace removed, and are only cut at whitespace boundaries. - * - * Note: Function was moved here from `std::str` because this module is the only place that - * uses it, and because it was to specific for a general string function. - * - * #Failure: - * - * Fails during iteration if the string contains a non-whitespace - * sequence longer than the limit. - */ + /// Splits a string into substrings with possibly internal whitespace, + /// each of them at most `lim` bytes long. The substrings have leading and trailing + /// whitespace removed, and are only cut at whitespace boundaries. + /// + /// Note: Function was moved here from `std::str` because this module is the only place that + /// uses it, and because it was to specific for a general string function. + /// + /// #Failure: + /// + /// Fails during iteration if the string contains a non-whitespace + /// sequence longer than the limit. fn each_split_within<'a>(ss: &'a str, lim: uint, it: &fn(&'a str) -> bool) -> bool { - // Just for fun, let's write this as an state machine: + // Just for fun, let's write this as a state machine: enum SplitWithinState { A, // leading whitespace, initial state @@ -853,8 +880,8 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, "test"))); - assert_eq!(opt_str(m, "test"), ~"20"); + assert!(m.opt_present("test")); + assert_eq!(m.opt_str("test").unwrap(), ~"20"); } _ => { fail!("test_reqopt_long failed"); } } @@ -900,8 +927,8 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, "t"))); - assert_eq!(opt_str(m, "t"), ~"20"); + assert!(m.opt_present("t")); + assert_eq!(m.opt_str("t").unwrap(), ~"20"); } _ => fail!() } @@ -949,8 +976,8 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, "test"))); - assert_eq!(opt_str(m, "test"), ~"20"); + assert!(m.opt_present("test")); + assert_eq!(m.opt_str("test").unwrap(), ~"20"); } _ => fail!() } @@ -962,7 +989,7 @@ mod tests { let opts = ~[optopt("test")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(!opt_present(m, "test")), + Ok(ref m) => assert!(!m.opt_present("test")), _ => fail!() } } @@ -996,8 +1023,8 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, "t"))); - assert_eq!(opt_str(m, "t"), ~"20"); + assert!((m.opt_present("t"))); + assert_eq!(m.opt_str("t").unwrap(), ~"20"); } _ => fail!() } @@ -1009,7 +1036,7 @@ mod tests { let opts = ~[optopt("t")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(!opt_present(m, "t")), + Ok(ref m) => assert!(!m.opt_present("t")), _ => fail!() } } @@ -1044,7 +1071,7 @@ mod tests { let opts = ~[optflag("test")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(opt_present(m, "test")), + Ok(ref m) => assert!(m.opt_present("test")), _ => fail!() } } @@ -1055,7 +1082,7 @@ mod tests { let opts = ~[optflag("test")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(!opt_present(m, "test")), + Ok(ref m) => assert!(!m.opt_present("test")), _ => fail!() } } @@ -1067,7 +1094,7 @@ mod tests { let rs = getopts(args, opts); match rs { Err(f) => { - error!(fail_str(f.clone())); + error!(f.clone().to_err_msg()); check_fail_type(f, UnexpectedArgument_); } _ => fail!() @@ -1091,7 +1118,7 @@ mod tests { let opts = ~[optflag("t")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(opt_present(m, "t")), + Ok(ref m) => assert!(m.opt_present("t")), _ => fail!() } } @@ -1102,7 +1129,7 @@ mod tests { let opts = ~[optflag("t")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(!opt_present(m, "t")), + Ok(ref m) => assert!(!m.opt_present("t")), _ => fail!() } } @@ -1141,7 +1168,7 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert_eq!(opt_count(m, "v"), 1); + assert_eq!(m.opt_count("v"), 1); } _ => fail!() } @@ -1154,7 +1181,7 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert_eq!(opt_count(m, "v"), 2); + assert_eq!(m.opt_count("v"), 2); } _ => fail!() } @@ -1167,7 +1194,7 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert_eq!(opt_count(m, "v"), 2); + assert_eq!(m.opt_count("v"), 2); } _ => fail!() } @@ -1180,7 +1207,7 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert_eq!(opt_count(m, "verbose"), 1); + assert_eq!(m.opt_count("verbose"), 1); } _ => fail!() } @@ -1193,7 +1220,7 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert_eq!(opt_count(m, "verbose"), 2); + assert_eq!(m.opt_count("verbose"), 2); } _ => fail!() } @@ -1207,8 +1234,8 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, "test"))); - assert_eq!(opt_str(m, "test"), ~"20"); + assert!((m.opt_present("test"))); + assert_eq!(m.opt_str("test").unwrap(), ~"20"); } _ => fail!() } @@ -1220,7 +1247,7 @@ mod tests { let opts = ~[optmulti("test")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(!opt_present(m, "test")), + Ok(ref m) => assert!(!m.opt_present("test")), _ => fail!() } } @@ -1243,9 +1270,9 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!(opt_present(m, "test")); - assert_eq!(opt_str(m, "test"), ~"20"); - let pair = opt_strs(m, "test"); + assert!(m.opt_present("test")); + assert_eq!(m.opt_str("test").unwrap(), ~"20"); + let pair = m.opt_strs("test"); assert!(pair[0] == ~"20"); assert!(pair[1] == ~"30"); } @@ -1260,8 +1287,8 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, "t"))); - assert_eq!(opt_str(m, "t"), ~"20"); + assert!((m.opt_present("t"))); + assert_eq!(m.opt_str("t").unwrap(), ~"20"); } _ => fail!() } @@ -1273,7 +1300,7 @@ mod tests { let opts = ~[optmulti("t")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(!opt_present(m, "t")), + Ok(ref m) => assert!(!m.opt_present("t")), _ => fail!() } } @@ -1296,9 +1323,9 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, "t"))); - assert_eq!(opt_str(m, "t"), ~"20"); - let pair = opt_strs(m, "t"); + assert!((m.opt_present("t"))); + assert_eq!(m.opt_str("t").unwrap(), ~"20"); + let pair = m.opt_strs("t"); assert!(pair[0] == ~"20"); assert!(pair[1] == ~"30"); } @@ -1343,18 +1370,18 @@ mod tests { Ok(ref m) => { assert!(m.free[0] == ~"prog"); assert!(m.free[1] == ~"free1"); - assert_eq!(opt_str(m, "s"), ~"20"); + assert_eq!(m.opt_str("s").unwrap(), ~"20"); assert!(m.free[2] == ~"free2"); - assert!((opt_present(m, "flag"))); - assert_eq!(opt_str(m, "long"), ~"30"); - assert!((opt_present(m, "f"))); - let pair = opt_strs(m, "m"); + assert!((m.opt_present("flag"))); + assert_eq!(m.opt_str("long").unwrap(), ~"30"); + assert!((m.opt_present("f"))); + let pair = m.opt_strs("m"); assert!(pair[0] == ~"40"); assert!(pair[1] == ~"50"); - let pair = opt_strs(m, "n"); + let pair = m.opt_strs("n"); assert!(pair[0] == ~"-A B"); assert!(pair[1] == ~"-60 70"); - assert!((!opt_present(m, "notpresent"))); + assert!((!m.opt_present("notpresent"))); } _ => fail!() } @@ -1369,34 +1396,34 @@ mod tests { result::Ok(m) => m, result::Err(_) => fail!() }; - assert!(opts_present(matches_single, [~"e"])); - assert!(opts_present(matches_single, [~"encrypt", ~"e"])); - assert!(opts_present(matches_single, [~"e", ~"encrypt"])); - assert!(!opts_present(matches_single, [~"encrypt"])); - assert!(!opts_present(matches_single, [~"thing"])); - assert!(!opts_present(matches_single, [])); + assert!(matches_single.opts_present([~"e"])); + assert!(matches_single.opts_present([~"encrypt", ~"e"])); + assert!(matches_single.opts_present([~"e", ~"encrypt"])); + assert!(!matches_single.opts_present([~"encrypt"])); + assert!(!matches_single.opts_present([~"thing"])); + assert!(!matches_single.opts_present([])); - assert_eq!(opts_str(matches_single, [~"e"]), ~"foo"); - assert_eq!(opts_str(matches_single, [~"e", ~"encrypt"]), ~"foo"); - assert_eq!(opts_str(matches_single, [~"encrypt", ~"e"]), ~"foo"); + assert_eq!(matches_single.opts_str([~"e"]).unwrap(), ~"foo"); + assert_eq!(matches_single.opts_str([~"e", ~"encrypt"]).unwrap(), ~"foo"); + assert_eq!(matches_single.opts_str([~"encrypt", ~"e"]).unwrap(), ~"foo"); let args_both = ~[~"-e", ~"foo", ~"--encrypt", ~"foo"]; let matches_both = &match getopts(args_both, opts) { result::Ok(m) => m, result::Err(_) => fail!() }; - assert!(opts_present(matches_both, [~"e"])); - assert!(opts_present(matches_both, [~"encrypt"])); - assert!(opts_present(matches_both, [~"encrypt", ~"e"])); - assert!(opts_present(matches_both, [~"e", ~"encrypt"])); - assert!(!opts_present(matches_both, [~"f"])); - assert!(!opts_present(matches_both, [~"thing"])); - assert!(!opts_present(matches_both, [])); + assert!(matches_both.opts_present([~"e"])); + assert!(matches_both.opts_present([~"encrypt"])); + assert!(matches_both.opts_present([~"encrypt", ~"e"])); + assert!(matches_both.opts_present([~"e", ~"encrypt"])); + assert!(!matches_both.opts_present([~"f"])); + assert!(!matches_both.opts_present([~"thing"])); + assert!(!matches_both.opts_present([])); - assert_eq!(opts_str(matches_both, [~"e"]), ~"foo"); - assert_eq!(opts_str(matches_both, [~"encrypt"]), ~"foo"); - assert_eq!(opts_str(matches_both, [~"e", ~"encrypt"]), ~"foo"); - assert_eq!(opts_str(matches_both, [~"encrypt", ~"e"]), ~"foo"); + assert_eq!(matches_both.opts_str([~"e"]).unwrap(), ~"foo"); + assert_eq!(matches_both.opts_str([~"encrypt"]).unwrap(), ~"foo"); + assert_eq!(matches_both.opts_str([~"e", ~"encrypt"]).unwrap(), ~"foo"); + assert_eq!(matches_both.opts_str([~"encrypt", ~"e"]).unwrap(), ~"foo"); } #[test] @@ -1407,10 +1434,10 @@ mod tests { result::Ok(m) => m, result::Err(_) => fail!() }; - assert!(opts_present(matches, [~"L"])); - assert_eq!(opts_str(matches, [~"L"]), ~"foo"); - assert!(opts_present(matches, [~"M"])); - assert_eq!(opts_str(matches, [~"M"]), ~"."); + assert!(matches.opts_present([~"L"])); + assert_eq!(matches.opts_str([~"L"]).unwrap(), ~"foo"); + assert!(matches.opts_present([~"M"])); + assert_eq!(matches.opts_str([~"M"]).unwrap(), ~"."); } @@ -1475,7 +1502,7 @@ mod tests { short.aliases = ~[reqopt("b")]; let verbose = groups::reqopt("b", "banana", "some bananas", "VAL"); - assert_eq!(groups::long_to_short(&verbose), short); + assert_eq!(verbose.long_to_short(), short); } #[test] @@ -1519,8 +1546,8 @@ mod tests { let args = ~[~"-a", ~"--apple", ~"-a"]; let matches = groups::getopts(args, opts).unwrap(); - assert_eq!(3, opt_count(&matches, "a")); - assert_eq!(3, opt_count(&matches, "apple")); + assert_eq!(3, matches.opt_count("a")); + assert_eq!(3, matches.opt_count("apple")); } #[test] diff --git a/src/libextra/test.rs b/src/libextra/test.rs index 4dcb48d2751..cc80da1506a 100644 --- a/src/libextra/test.rs +++ b/src/libextra/test.rs @@ -226,11 +226,11 @@ pub fn parse_opts(args: &[~str]) -> OptRes { let matches = match groups::getopts(args_, optgroups()) { Ok(m) => m, - Err(f) => return Err(getopts::fail_str(f)) + Err(f) => return Err(f.to_err_msg()) }; - if getopts::opt_present(&matches, "h") { usage(args[0], "h"); } - if getopts::opt_present(&matches, "help") { usage(args[0], "help"); } + if matches.opt_present("h") { usage(args[0], "h"); } + if matches.opt_present("help") { usage(args[0], "help"); } let filter = if matches.free.len() > 0 { @@ -239,25 +239,25 @@ pub fn parse_opts(args: &[~str]) -> OptRes { None }; - let run_ignored = getopts::opt_present(&matches, "ignored"); + let run_ignored = matches.opt_present("ignored"); - let logfile = getopts::opt_maybe_str(&matches, "logfile"); + let logfile = matches.opt_str("logfile"); let logfile = logfile.map_move(|s| Path(s)); - let run_benchmarks = getopts::opt_present(&matches, "bench"); + let run_benchmarks = matches.opt_present("bench"); let run_tests = ! run_benchmarks || - getopts::opt_present(&matches, "test"); + matches.opt_present("test"); - let ratchet_metrics = getopts::opt_maybe_str(&matches, "ratchet-metrics"); + let ratchet_metrics = matches.opt_str("ratchet-metrics"); let ratchet_metrics = ratchet_metrics.map_move(|s| Path(s)); - let ratchet_noise_percent = getopts::opt_maybe_str(&matches, "ratchet-noise-percent"); + let ratchet_noise_percent = matches.opt_str("ratchet-noise-percent"); let ratchet_noise_percent = ratchet_noise_percent.map_move(|s| from_str::(s).unwrap()); - let save_metrics = getopts::opt_maybe_str(&matches, "save-metrics"); + let save_metrics = matches.opt_str("save-metrics"); let save_metrics = save_metrics.map_move(|s| Path(s)); - let test_shard = getopts::opt_maybe_str(&matches, "test-shard"); + let test_shard = matches.opt_str("test-shard"); let test_shard = opt_shard(test_shard); let test_opts = TestOpts { diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 5078d0ded18..bd0462119bd 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -30,7 +30,6 @@ use std::io; use std::os; use std::vec; use extra::getopts::groups::{optopt, optmulti, optflag, optflagopt}; -use extra::getopts::{opt_present}; use extra::getopts; use syntax::ast; use syntax::abi; @@ -606,15 +605,15 @@ pub fn build_session_options(binary: @str, matches: &getopts::Matches, demitter: diagnostic::Emitter) -> @session::options { - let crate_type = if opt_present(matches, "lib") { + let crate_type = if matches.opt_present("lib") { session::lib_crate - } else if opt_present(matches, "bin") { + } else if matches.opt_present("bin") { session::bin_crate } else { session::unknown_crate }; - let parse_only = opt_present(matches, "parse-only"); - let no_trans = opt_present(matches, "no-trans"); + let parse_only = matches.opt_present("parse-only"); + let no_trans = matches.opt_present("no-trans"); let lint_levels = [lint::allow, lint::warn, lint::deny, lint::forbid]; @@ -627,8 +626,8 @@ pub fn build_session_options(binary: @str, // to_ascii_move and to_str_move to not do a unnecessary copy. let level_short = level_name.slice_chars(0, 1); let level_short = level_short.to_ascii().to_upper().to_str_ascii(); - let flags = vec::append(getopts::opt_strs(matches, level_short), - getopts::opt_strs(matches, level_name)); + let flags = vec::append(matches.opt_strs(level_short), + matches.opt_strs(level_name)); for lint_name in flags.iter() { let lint_name = lint_name.replace("-", "_"); match lint_dict.find_equiv(&lint_name) { @@ -644,7 +643,7 @@ pub fn build_session_options(binary: @str, } let mut debugging_opts = 0u; - let debug_flags = getopts::opt_strs(matches, "Z"); + let debug_flags = matches.opt_strs("Z"); let debug_map = session::debugging_opts_map(); for debug_flag in debug_flags.iter() { let mut this_bit = 0u; @@ -670,31 +669,31 @@ pub fn build_session_options(binary: @str, let output_type = if parse_only || no_trans { link::output_type_none - } else if opt_present(matches, "S") && - opt_present(matches, "emit-llvm") { + } else if matches.opt_present("S") && + matches.opt_present("emit-llvm") { link::output_type_llvm_assembly - } else if opt_present(matches, "S") { + } else if matches.opt_present("S") { link::output_type_assembly - } else if opt_present(matches, "c") { + } else if matches.opt_present("c") { link::output_type_object - } else if opt_present(matches, "emit-llvm") { + } else if matches.opt_present("emit-llvm") { link::output_type_bitcode } else { link::output_type_exe }; - let sysroot_opt = getopts::opt_maybe_str(matches, "sysroot").map_move(|m| @Path(m)); - let target = getopts::opt_maybe_str(matches, "target").unwrap_or(host_triple()); - let target_cpu = getopts::opt_maybe_str(matches, "target-cpu").unwrap_or(~"generic"); - let target_feature = getopts::opt_maybe_str(matches, "target-feature").unwrap_or(~""); - let save_temps = getopts::opt_present(matches, "save-temps"); + let sysroot_opt = matches.opt_str("sysroot").map_move(|m| @Path(m)); + let target = matches.opt_str("target").unwrap_or(host_triple()); + let target_cpu = matches.opt_str("target-cpu").unwrap_or(~"generic"); + let target_feature = matches.opt_str("target-feature").unwrap_or(~""); + let save_temps = matches.opt_present("save-temps"); let opt_level = { if (debugging_opts & session::no_opt) != 0 { No - } else if opt_present(matches, "O") { - if opt_present(matches, "opt-level") { + } else if matches.opt_present("O") { + if matches.opt_present("opt-level") { early_error(demitter, ~"-O and --opt-level both provided"); } Default - } else if opt_present(matches, "opt-level") { - match getopts::opt_str(matches, "opt-level") { + } else if matches.opt_present("opt-level") { + match matches.opt_str("opt-level").unwrap() { ~"0" => No, ~"1" => Less, ~"2" => Default, @@ -720,18 +719,17 @@ pub fn build_session_options(binary: @str, let statik = debugging_opts & session::statik != 0; - let addl_lib_search_paths = getopts::opt_strs(matches, "L").map(|s| Path(*s)); - let linker = getopts::opt_maybe_str(matches, "linker"); - let linker_args = getopts::opt_strs(matches, "link-args").flat_map( |a| { + let addl_lib_search_paths = matches.opt_strs("L").map(|s| Path(*s)); + let linker = matches.opt_str("linker"); + let linker_args = matches.opt_strs("link-args").flat_map( |a| { a.split_iter(' ').map(|arg| arg.to_owned()).collect() }); - let cfg = parse_cfgspecs(getopts::opt_strs(matches, "cfg"), demitter); - let test = opt_present(matches, "test"); - let android_cross_path = getopts::opt_maybe_str( - matches, "android-cross-path"); + let cfg = parse_cfgspecs(matches.opt_strs("cfg"), demitter); + let test = matches.opt_present("test"); + let android_cross_path = matches.opt_str("android-cross-path"); - let custom_passes = match getopts::opt_maybe_str(matches, "passes") { + let custom_passes = match matches.opt_str("passes") { None => ~[], Some(s) => { s.split_iter(|c: char| c == ' ' || c == ',').map(|s| { @@ -739,7 +737,7 @@ pub fn build_session_options(binary: @str, }).collect() } }; - let llvm_args = match getopts::opt_maybe_str(matches, "llvm-args") { + let llvm_args = match matches.opt_str("llvm-args") { None => ~[], Some(s) => { s.split_iter(|c: char| c == ' ' || c == ',').map(|s| { @@ -1020,7 +1018,6 @@ mod test { use driver::driver::{build_session_options, optgroups}; use extra::getopts::groups::getopts; - use extra::getopts; use syntax::attr; use syntax::diagnostic; @@ -1030,7 +1027,7 @@ mod test { let matches = &match getopts([~"--test"], optgroups()) { Ok(m) => m, - Err(f) => fail!("test_switch_implies_cfg_test: %s", getopts::fail_str(f)) + Err(f) => fail!("test_switch_implies_cfg_test: %s", f.to_err_msg()) }; let sessopts = build_session_options( @"rustc", matches, diagnostic::emit); @@ -1047,7 +1044,7 @@ mod test { &match getopts([~"--test", ~"--cfg=test"], optgroups()) { Ok(m) => m, Err(f) => { - fail!("test_switch_implies_cfg_test_unless_cfg_test: %s", getopts::fail_str(f)); + fail!("test_switch_implies_cfg_test_unless_cfg_test: %s", f.to_err_msg()); } }; let sessopts = build_session_options( diff --git a/src/librustc/rustc.rs b/src/librustc/rustc.rs index 902734b05a2..8c3e198e5d6 100644 --- a/src/librustc/rustc.rs +++ b/src/librustc/rustc.rs @@ -40,7 +40,7 @@ use std::result; use std::str; use std::task; use std::vec; -use extra::getopts::{groups, opt_present}; +use extra::getopts::groups; use extra::getopts; use syntax::codemap; use syntax::diagnostic; @@ -204,39 +204,39 @@ pub fn run_compiler(args: &[~str], demitter: diagnostic::Emitter) { &match getopts::groups::getopts(args, optgroups()) { Ok(m) => m, Err(f) => { - early_error(demitter, getopts::fail_str(f)); + early_error(demitter, f.to_err_msg()); } }; - if opt_present(matches, "h") || opt_present(matches, "help") { + if matches.opt_present("h") || matches.opt_present("help") { usage(binary); return; } // Display the available lint options if "-W help" or only "-W" is given. - let lint_flags = vec::append(getopts::opt_strs(matches, "W"), - getopts::opt_strs(matches, "warn")); + let lint_flags = vec::append(matches.opt_strs("W"), + matches.opt_strs("warn")); let show_lint_options = lint_flags.iter().any(|x| x == &~"help") || - (opt_present(matches, "W") && lint_flags.is_empty()); + (matches.opt_present("W") && lint_flags.is_empty()); if show_lint_options { describe_warnings(); return; } - let r = getopts::opt_strs(matches, "Z"); + let r = matches.opt_strs("Z"); if r.iter().any(|x| x == &~"help") { describe_debug_flags(); return; } - if getopts::opt_maybe_str(matches, "passes") == Some(~"list") { + if matches.opt_str("passes") == Some(~"list") { unsafe { lib::llvm::llvm::LLVMRustPrintPasses(); } return; } - if opt_present(matches, "v") || opt_present(matches, "version") { + if matches.opt_present("v") || matches.opt_present("version") { version(binary); return; } @@ -256,10 +256,10 @@ pub fn run_compiler(args: &[~str], demitter: diagnostic::Emitter) { let sopts = build_session_options(binary, matches, demitter); let sess = build_session(sopts, demitter); - let odir = getopts::opt_maybe_str(matches, "out-dir").map_move(|o| Path(o)); - let ofile = getopts::opt_maybe_str(matches, "o").map_move(|o| Path(o)); + let odir = matches.opt_str("out-dir").map_move(|o| Path(o)); + let ofile = matches.opt_str("o").map_move(|o| Path(o)); let cfg = build_configuration(sess); - let pretty = do getopts::opt_default(matches, "pretty", "normal").map_move |a| { + let pretty = do matches.opt_default("pretty", "normal").map_move |a| { parse_pretty(sess, a) }; match pretty { @@ -269,7 +269,7 @@ pub fn run_compiler(args: &[~str], demitter: diagnostic::Emitter) { } None:: => {/* continue */ } } - let ls = opt_present(matches, "ls"); + let ls = matches.opt_present("ls"); if ls { match input { file_input(ref ifile) => { diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index ff6401456b6..71ece178807 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -125,7 +125,7 @@ pub fn parse_config_( } } Err(f) => { - Err(getopts::fail_str(f)) + Err(f.to_err_msg()) } } } @@ -139,7 +139,7 @@ fn config_from_opts( let config = default_config(input_crate); let result = result::Ok(config); let result = do result.and_then |config| { - let output_dir = getopts::opt_maybe_str(matches, opt_output_dir()); + let output_dir = matches.opt_str(opt_output_dir()); let output_dir = output_dir.map_move(|s| Path(s)); result::Ok(Config { output_dir: output_dir.unwrap_or(config.output_dir.clone()), @@ -147,7 +147,7 @@ fn config_from_opts( }) }; let result = do result.and_then |config| { - let output_format = getopts::opt_maybe_str(matches, opt_output_format()); + let output_format = matches.opt_str(opt_output_format()); do output_format.map_move_default(result::Ok(config.clone())) |output_format| { do parse_output_format(output_format).and_then |output_format| { result::Ok(Config { @@ -159,7 +159,7 @@ fn config_from_opts( }; let result = do result.and_then |config| { let output_style = - getopts::opt_maybe_str(matches, opt_output_style()); + matches.opt_str(opt_output_style()); do output_style.map_move_default(result::Ok(config.clone())) |output_style| { do parse_output_style(output_style).and_then |output_style| { result::Ok(Config { @@ -171,7 +171,7 @@ fn config_from_opts( }; let process_output = Cell::new(process_output); let result = do result.and_then |config| { - let pandoc_cmd = getopts::opt_maybe_str(matches, opt_pandoc_cmd()); + let pandoc_cmd = matches.opt_str(opt_pandoc_cmd()); let pandoc_cmd = maybe_find_pandoc( &config, pandoc_cmd, process_output.take()); do pandoc_cmd.and_then |pandoc_cmd| { diff --git a/src/librustpkg/rustpkg.rs b/src/librustpkg/rustpkg.rs index 7cd30c7af9e..0187a8d189c 100644 --- a/src/librustpkg/rustpkg.rs +++ b/src/librustpkg/rustpkg.rs @@ -641,53 +641,53 @@ pub fn main_args(args: &[~str]) { let matches = &match getopts::getopts(args, opts) { result::Ok(m) => m, result::Err(f) => { - error(fmt!("%s", getopts::fail_str(f))); + error(fmt!("%s", f.to_err_msg())); return; } }; - let mut help = getopts::opt_present(matches, "h") || - getopts::opt_present(matches, "help"); - let no_link = getopts::opt_present(matches, "no-link"); - let no_trans = getopts::opt_present(matches, "no-trans"); - let supplied_sysroot = getopts::opt_val(matches, "sysroot"); - let generate_asm = getopts::opt_present(matches, "S") || - getopts::opt_present(matches, "assembly"); - let parse_only = getopts::opt_present(matches, "parse-only"); - let pretty = getopts::opt_present(matches, "pretty"); - let emit_llvm = getopts::opt_present(matches, "emit-llvm"); + let mut help = matches.opt_present("h") || + matches.opt_present("help"); + let no_link = matches.opt_present("no-link"); + let no_trans = matches.opt_present("no-trans"); + let supplied_sysroot = matches.opt_val("sysroot"); + let generate_asm = matches.opt_present("S") || + matches.opt_present("assembly"); + let parse_only = matches.opt_present("parse-only"); + let pretty = matches.opt_present("pretty"); + let emit_llvm = matches.opt_present("emit-llvm"); - if getopts::opt_present(matches, "v") || - getopts::opt_present(matches, "version") { + if matches.opt_present("v") || + matches.opt_present("version") { rustc::version(args[0]); return; } - let use_rust_path_hack = getopts::opt_present(matches, "r") || - getopts::opt_present(matches, "rust-path-hack"); + let use_rust_path_hack = matches.opt_present("r") || + matches.opt_present("rust-path-hack"); - let linker = getopts::opt_maybe_str(matches, "linker"); - let link_args = getopts::opt_maybe_str(matches, "link-args"); - let cfgs = getopts::opt_strs(matches, "cfg") + getopts::opt_strs(matches, "c"); + let linker = matches.opt_str("linker"); + let link_args = matches.opt_str("link-args"); + let cfgs = matches.opt_strs("cfg") + matches.opt_strs("c"); let mut user_supplied_opt_level = true; - let opt_level = match getopts::opt_maybe_str(matches, "opt-level") { + let opt_level = match matches.opt_str("opt-level") { Some(~"0") => session::No, Some(~"1") => session::Less, Some(~"2") => session::Default, Some(~"3") => session::Aggressive, - _ if getopts::opt_present(matches, "O") => session::Default, + _ if matches.opt_present("O") => session::Default, _ => { user_supplied_opt_level = false; session::No } }; - let save_temps = getopts::opt_present(matches, "save-temps"); - let target = getopts::opt_maybe_str(matches, "target"); - let target_cpu = getopts::opt_maybe_str(matches, "target-cpu"); + let save_temps = matches.opt_present("save-temps"); + let target = matches.opt_str("target"); + let target_cpu = matches.opt_str("target-cpu"); let experimental_features = { - let strs = getopts::opt_strs(matches, "Z"); - if getopts::opt_present(matches, "Z") { + let strs = matches.opt_strs("Z"); + if matches.opt_present("Z") { Some(strs) } else { diff --git a/src/rustdoc_ng/rustdoc_ng.rs b/src/rustdoc_ng/rustdoc_ng.rs index ec6ad6974e9..a4e3bc50d11 100644 --- a/src/rustdoc_ng/rustdoc_ng.rs +++ b/src/rustdoc_ng/rustdoc_ng.rs @@ -41,7 +41,6 @@ pub fn main() { } pub fn main_args(args: &[~str]) { - use extra::getopts::*; use extra::getopts::groups::*; let opts = ~[ @@ -56,20 +55,20 @@ pub fn main_args(args: &[~str]) { let matches = getopts(args.tail(), opts).unwrap(); - if opt_present(&matches, "h") || opt_present(&matches, "help") { + if matches.opt_present("h") || matches.opt_present("help") { println(usage(args[0], opts)); return; } - let libs = Cell::new(opt_strs(&matches, "L").map(|s| Path(*s))); + let libs = Cell::new(matches.opt_strs("L").map(|s| Path(*s))); - let mut passes = if opt_present(&matches, "n") { + let mut passes = if matches.opt_present("n") { ~[] } else { ~[~"collapse-docs", ~"clean-comments", ~"collapse-privacy" ] }; - opt_strs(&matches, "a").map(|x| passes.push(x.clone())); + matches.opt_strs("a").map(|x| passes.push(x.clone())); if matches.free.len() != 1 { println(usage(args[0], opts)); @@ -99,7 +98,7 @@ pub fn main_args(args: &[~str]) { }) } - for pname in opt_strs(&matches, "p").move_iter() { + for pname in matches.opt_strs("p").move_iter() { pm.load_plugin(pname); } diff --git a/src/test/bench/shootout-pfib.rs b/src/test/bench/shootout-pfib.rs index 7029ca2a492..0896682b322 100644 --- a/src/test/bench/shootout-pfib.rs +++ b/src/test/bench/shootout-pfib.rs @@ -64,7 +64,7 @@ fn parse_opts(argv: ~[~str]) -> Config { match getopts::getopts(opt_args, opts) { Ok(ref m) => { - return Config {stress: getopts::opt_present(m, "stress")} + return Config {stress: m.opt_present("stress")} } Err(_) => { fail!(); } } diff --git a/src/test/run-pass/getopts_ref.rs b/src/test/run-pass/getopts_ref.rs index cebd2910070..d1964b5d94b 100644 --- a/src/test/run-pass/getopts_ref.rs +++ b/src/test/run-pass/getopts_ref.rs @@ -20,8 +20,8 @@ pub fn main() { match getopts(args, opts) { Ok(ref m) => - assert!(!opt_present(m, "b")), - Err(ref f) => fail!(fail_str((*f).clone())) + assert!(!m.opt_present("b")), + Err(ref f) => fail!((*f).clone().to_err_msg()) }; }