Skip to content

Commit

Permalink
[lib] Update Option to return bool success/fail on parse
Browse files Browse the repository at this point in the history
  • Loading branch information
titzer committed Aug 26, 2024
1 parent a0ad84a commit 421613b
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions lib/util/Option.v3
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@ class Option<T> extends Opt {
// The Options class represents a collection of options, each with a name and a value.
// Any option that has been set to a value other than its default is also remembered.
class Options(prefix: string) {
def map = Strings.newMap<Opt>();
var names = Vector<string>.new();
var vals = Vector<string>.new();
def map = Strings.newMap<Opt>(); // maps names to options
var nullOpt: Opt; // an option with no name
var names = Vector<string>.new(); // the names of all parsed options
var vals = Vector<string>.new(); // the values of all options
var setUnmatched: (string, string) -> void;

// Add {option} to the set of options.
def add<T>(option: Option<T>) -> Option<T> {
if (option.name == null) return nullOpt = option;
var name = option.name;
if (prefix != null) {
name = Strings.builderOf(prefix).putc('.').puts(name).toString();
Expand All @@ -51,7 +53,7 @@ class Options(prefix: string) {
return [];
}
// Parse and set a single option from {arg}.
def parseOption(arg: string) {
def parseOption(arg: string) -> bool {
var name: string, val: string;
for (i = 1; true; i++) {
if (i == arg.length) {
Expand All @@ -64,15 +66,20 @@ class Options(prefix: string) {
break;
}
}
setOption(name, val);
return setOption(name, val);
}
// Set the option with name {name} to a given value {val}.
def setOption(name: string, val: string) {
var option = map[name];
if (option != null) option.parse(val);
else if (setUnmatched != null) setUnmatched(name, val);
// Set the option with name {name} to a given value {val}. If {name == null}, then
// the {nullOpt} will be set. Returns {true} if the option was successfully set.
def setOption(name: string, val: string) -> bool {
names.put(name);
vals.put(val);
var option = if(name == null, nullOpt, map[name]);
if (option != null) {
option.parse(val);
return true;
}
if (setUnmatched != null) setUnmatched(name, val);
return false;
}
}
// BasicOptions adds a set of utility methods for adding and parsing options
Expand Down

0 comments on commit 421613b

Please sign in to comment.