shithub: mc

ref: f6fadc8f08a0732f22ec6df34822f45e0f3a7f60
dir: /libstd/optparse.myr/

View raw version
use "types.use"
use "alloc.use"
use "utf.use"
use "die.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 = [][:]
	nextopt(ctx)
	-> ctx
}

const optnext = {ctx
	var c

	if !ctx.curarg.len
		if !nextopt(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++
		nextopt(ctx)
	else
		die("Arg needed")
	;;
	-> arg
}

const nextopt = {ctx
	var i

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