summaryrefslogtreecommitdiff
path: root/libstd
diff options
context:
space:
mode:
authorOri Bernstein <ori@eigenstate.org>2015-05-01 22:06:57 -0700
committerOri Bernstein <ori@eigenstate.org>2015-05-01 22:07:29 -0700
commitf80db1cc005bd118f5e6910be4fa305290832a54 (patch)
tree41af8e87714e250b4304ddf6d715b89e4aa1b5f8 /libstd
parentcca9d66940c892e52559bfb2f71dcec92e4ddc46 (diff)
downloadmc-f80db1cc005bd118f5e6910be4fa305290832a54.tar.gz
More improvements in CLI option parsing.
Diffstat (limited to 'libstd')
-rw-r--r--libstd/optparse.myr67
1 files changed, 39 insertions, 28 deletions
diff --git a/libstd/optparse.myr b/libstd/optparse.myr
index 7bd0739..697aba5 100644
--- a/libstd/optparse.myr
+++ b/libstd/optparse.myr
@@ -12,8 +12,9 @@ use "utf.use"
pkg std =
type optdef = struct
- argdesc : byte[:]
- opts : optdesc[:]
+ argdesc : byte[:] /* the description for the usage */
+ minargs : std.size /* the minimum number of positional args */
+ opts : optdesc[:] /* the description of the options */
;;
type optdesc = struct
@@ -23,32 +24,50 @@ pkg std =
needed : bool
;;
- type optctx = struct
- /* public variables */
+ type optparsed = struct
+ opts : (char, byte[:])[:]
args : byte[:][:]
+ ;;
+
+ const optparse : (optargs : byte[:][:], def : optdef# -> optparsed)
+;;
- /* data passed in */
- optdef : optdef#
- optargs : byte[:][:]
+type optctx = struct
+ /* public variables */
+ args : byte[:][:]
- /* state */
- optdone : bool /* if we've seen '--', everything's an arg */
- finished : bool /* if we've processed all the optargs */
- argidx : size
- curarg : byte[:]
- ;;
+ /* data passed in */
+ optdef : optdef#
+ optargs : byte[:][:]
- const optinit : (optargs : byte[:][:], def : optdef# -> optctx#)
- const optnext : (ctx : optctx# -> (char, byte[:]))
- const optdone : (ctx : optctx# -> bool)
- const optfin : (ctx : optctx# -> byte[:][:])
- const optusage : (ctx : optctx# -> void)
+ /* state */
+ optdone : bool /* if we've seen '--', everything's an arg */
+ finished : bool /* if we've processed all the optargs */
+ argidx : size
+ curarg : byte[:]
;;
-const optinit = {args, def
+
+const optparse = {args, def
+ var ctx : optctx
+ var parsed
+
+ optinit(&ctx, args, def)
+ while !optdone(&ctx)
+ parsed.opts = slpush(parsed.opts, optnext(&ctx))
+ ;;
+ if ctx.args.len < def.minargs
+ put("error: expected at least %z args, got %z\n", def.minargs, ctx.args.len)
+ optusage(&ctx)
+ exit(1)
+ ;;
+ parsed.args = ctx.args
+ -> parsed
+}
+
+const optinit = {ctx, args, def
var ctx
- ctx = alloc()
ctx.optargs = args
ctx.optdef = def
@@ -63,14 +82,6 @@ const optinit = {args, def
-> ctx
}
-const optfin = {ctx
- var a
-
- a = ctx.args
- free(ctx)
- -> a
-}
-
const optnext = {ctx
var c
var arg