summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorOri Bernstein <ori@eigenstate.org>2013-04-04 17:04:20 -0400
committerOri Bernstein <ori@eigenstate.org>2013-04-04 17:04:20 -0400
commit21265af6b02141e340a953540e760b2e683de562 (patch)
treee6d69d6752c3b3c7b515889c48f29873c61d5904
parent9125dee98dc51e46a35c5e30a8a228031dcca44d (diff)
downloadmc-21265af6b02141e340a953540e760b2e683de562.tar.gz
Make it easier to iterate with option parsing.
-rw-r--r--libstd/optparse.myr24
-rw-r--r--libstd/test.myr18
2 files changed, 22 insertions, 20 deletions
diff --git a/libstd/optparse.myr b/libstd/optparse.myr
index 383e083..0f3b68a 100644
--- a/libstd/optparse.myr
+++ b/libstd/optparse.myr
@@ -14,7 +14,8 @@ pkg std =
args : byte[:][:]
/* state */
- done : bool /* if we've seen '--', everything's an arg */
+ optdone : bool /* if we've seen '--', everything's an arg */
+ done : bool /* if we've processed all the args */
argidx : size
curarg : byte[:]
arglist : byte[:][:]
@@ -22,6 +23,7 @@ pkg std =
const optinit : (opts : byte[:], args : byte[:][:] -> optctx#)
const optnext : (ctx : optctx# -> [char, byte[:]])
+ const optdone : (ctx : optctx# -> bool)
;;
const optinit = {opts, args
@@ -31,10 +33,12 @@ const optinit = {opts, args
ctx.opts = opts
ctx.args = args
+ ctx.optdone = false
ctx.done = false
ctx.argidx = 0
ctx.arglist = [][:]
ctx.curarg = [][:]
+ next(ctx)
-> ctx
}
@@ -45,13 +49,6 @@ const optnext = {ctx
var tryarg
var needarg
- /* end of arguments */
- if !ctx.curarg.len
- if !next(ctx)
- -> (Badchar, "")
- ;;
- ;;
-
(c, ctx.curarg) = striter(ctx.curarg)
(valid, tryarg, needarg) = optinfo(ctx, c)
@@ -72,9 +69,17 @@ const optnext = {ctx
arg = ""
;;
+ if !ctx.curarg.len
+ next(ctx)
+ ;;
+
-> (c, arg)
}
+const optdone = {ctx
+ -> !ctx.curarg.len && ctx.done
+}
+
const optinfo = {ctx, arg
var s
var c
@@ -103,12 +108,13 @@ const next = {ctx
var i
for i = ctx.argidx + 1; i < ctx.args.len; i++
- if !ctx.done && decode(ctx.args[i]) == '-'
+ if !ctx.optdone && decode(ctx.args[i]) == '-'
goto foundopt
else
ctx.arglist = slappend(ctx.arglist, ctx.args[i])
;;
;;
+ ctx.done = true
-> false
:foundopt
ctx.argidx = i
diff --git a/libstd/test.myr b/libstd/test.myr
index f8ff2f1..4cdac50 100644
--- a/libstd/test.myr
+++ b/libstd/test.myr
@@ -4,7 +4,7 @@ const main = {args : byte[:][:]
var x : byte#[1024]
var sz
var i
- var opt
+ var ctx
var o
var a
@@ -13,18 +13,14 @@ const main = {args : byte[:][:]
std.put("args[%i] = %s\n", i, args[i])
;;
- opt = std.optinit("asdf:g?", args)
- std.put("arglen = %i\n", opt.args.len)
- while true
- (o, a) = std.optnext(opt)
- if o == std.Badchar
- goto done
- ;;
+ ctx = std.optinit("asdf:g?", args)
+ std.put("arglen = %i\n", ctx.args.len)
+ while !std.optdone(ctx)
+ (o, a) = std.optnext(ctx)
std.put("option %c, arg = %s\n", o, a)
;;
-:done
- for i = 0; i < opt.arglist.len; i++
- std.put("arg %s\n", opt.arglist[i])
+ for i = 0; i < ctx.arglist.len; i++
+ std.put("arg %s\n", ctx.arglist[i])
;;