ref: 21265af6b02141e340a953540e760b2e683de562
parent: 9125dee98dc51e46a35c5e30a8a228031dcca44d
author: Ori Bernstein <[email protected]>
date: Thu Apr 4 13:04:20 EDT 2013
Make it easier to iterate with option parsing.
--- a/libstd/optparse.myr
+++ b/libstd/optparse.myr
@@ -14,7 +14,8 @@
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 @@
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 @@
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 @@
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 @@
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 @@
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
--- a/libstd/test.myr
+++ b/libstd/test.myr
@@ -4,7 +4,7 @@
var x : byte#[1024]
var sz
var i
- var opt
+ var ctx
var o
var a
@@ -13,18 +13,14 @@
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])
;;