From 421613baef34f0291c4166b57e5e0729108a5505 Mon Sep 17 00:00:00 2001 From: "Ben L. Titzer" Date: Sun, 25 Aug 2024 23:17:38 -0400 Subject: [PATCH] [lib] Update Option to return bool success/fail on parse --- lib/util/Option.v3 | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/lib/util/Option.v3 b/lib/util/Option.v3 index ce54006f0..5fe51ab85 100644 --- a/lib/util/Option.v3 +++ b/lib/util/Option.v3 @@ -20,13 +20,15 @@ class Option 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(); - var names = Vector.new(); - var vals = Vector.new(); + def map = Strings.newMap(); // maps names to options + var nullOpt: Opt; // an option with no name + var names = Vector.new(); // the names of all parsed options + var vals = Vector.new(); // the values of all options var setUnmatched: (string, string) -> void; // Add {option} to the set of options. def add(option: Option) -> Option { + if (option.name == null) return nullOpt = option; var name = option.name; if (prefix != null) { name = Strings.builderOf(prefix).putc('.').puts(name).toString(); @@ -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) { @@ -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