shithub: mc

ref: 03af679a2a685afe93242d2751ea1a94d9c17569
dir: /libstd/optparse.myr/

View raw version
use "alloc.use"
use "die.use"
use "extremum.use"
use "slappend.use"
use "types.use"
use "utf.use"

pkg std =
	type optctx = struct
		/* data passed in */
		opts	: byte[:]
		args	: byte[:][:]

		/* state */
		argidx	: size
		curarg	: byte[:]
		arglist	: byte[:][:]
	;;

	const optinit	: (opts	: byte[:], args : byte[:][:] -> optctx#)
	const optnext	: (ctx : optctx# -> char)
	const optarg	: (ctx : optctx# -> byte[:])
;;

const optinit = {opts, args
	var ctx

	ctx = alloc()
	ctx.opts = opts
	ctx.args = args
	ctx.argidx = 0
	ctx.arglist = [][:]
	ctx.curarg = [][:]
	next(ctx)
	-> ctx
}

const optnext = {ctx
	var c

	if !ctx.curarg.len
		if !next(ctx)
			-> Badchar
		;;
	;;
	(c, ctx.curarg) = striter(ctx.curarg)
	-> c
}

const optarg = {ctx
	var arg

	if ctx.curarg.len > 0
		arg = ctx.curarg
		ctx.curarg = ctx.curarg[ctx.curarg.len:]
	elif ctx.argidx > ctx.args.len
		arg = ctx.args[ctx.argidx + 1]
		ctx.argidx++
		next(ctx)
	else
		die("Arg needed")
	;;
	-> arg
}

const next = {ctx
	var i

	for i = ctx.argidx + 1; i < ctx.args.len; i++
		if decode(ctx.args[i]) == '-'
			goto foundopt
		else
			ctx.args = slappend(ctx.args, ctx.args[i])
		;;
	;;
	-> false
:foundopt
	ctx.argidx = i
	ctx.curarg = ctx.args[i][1:]
	-> true
}