summaryrefslogtreecommitdiff
path: root/libstd/optparse.myr
blob: 40374dbcc0c833ee9b528a41f8811198404c0f90 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
use "alloc.use"
use "die.use"
use "extremum.use"
use "fmt.use"
use "option.use"
use "slpush.use"
use "syswrap.use"
use "types.use"
use "utf.use"

pkg std =
	type optctx = struct
		/* public variables */
		args	: byte[:][:]

		/* data passed in */
		optstr	: byte[:]
		optargs	: 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[:]
	;;

	const optinit	: (optstr: byte[:], optargs : byte[:][:] -> optctx#)
	const optnext	: (ctx : optctx# -> (char, byte[:]))
	const optdone	: (ctx : optctx# -> bool)
	const optfin	: (ctx : optctx# -> byte[:][:])
;;

const optinit = {optstr, optargs
	var ctx

	ctx = alloc()
	ctx.optstr= optstr
	ctx.optargs =optargs

	ctx.optdone = false
	ctx.finished = false
	ctx.argidx = 0
	ctx.curarg = [][:]

	ctx.args = [][:]

	next(ctx)
	-> ctx
}

const optfin = {ctx
	var a

	a = ctx.args
	free(ctx)
	-> a
}

const optnext = {ctx
	var c
	var arg

	(c, ctx.curarg) = striter(ctx.curarg)

	match optinfo(ctx, c)
	| `None:
		fatal(1, "Unexpected argument %c\n", c)
	| `Some (true, needed):
		/* -arg => '-a' 'rg' */
		if ctx.curarg.len > 0
			arg = ctx.curarg
			ctx.curarg = ctx.curarg[ctx.curarg.len:]
			next(ctx)
		/* '-a rg' => '-a' 'rg' */
		elif ctx.argidx < (ctx.optargs.len - 1)
			arg = ctx.optargs[ctx.argidx + 1]
			ctx.argidx++
			next(ctx)
		elif needed
			put("Expected argument for %c\n", c)
			exit(1)
		;;
	| `Some (false, _):
		arg = ""
		if ctx.curarg.len != 0
			next(ctx)
		;;
	;;


	-> (c, arg)
}

const optdone = {ctx
	-> ctx.curarg.len == 0 && ctx.finished
}

const optinfo = {ctx, arg
	var s
	var c

	s = ctx.optstr
	while s.len != 0
		(c, s) = striter(s)
		if c == arg
			(c, s) = striter(s)
			/* mandatory arg */
			if c == ':'
				-> `Some (true, true)
			/* optional arg */
			elif c == '?'
				-> `Some (true, false)
			/* no arg */
			else
				-> `Some (false, false)
			;;
		;;
	;;
	-> `None
}

const next = {ctx
	var i

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