summaryrefslogtreecommitdiff
path: root/libstd/optparse.myr
blob: ae65b775b2590c651777b5bef89fad8964b679d2 (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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
use "alloc.use"
use "die.use"
use "extremum.use"
use "fmt.use"
use "strbuf.use"
use "option.use"
use "sleq.use"
use "slpush.use"
use "syswrap-ss.use"
use "syswrap.use"
use "types.use"
use "utf.use"

pkg std =
	type optdef = struct
		argdesc	: byte[:]	/* the description for the usage */
		minargs	: std.size	/* the minimum number of positional args */
		maxargs	: std.size	/* the maximum number of positional args (0 = unlimited) */
		noargs	: std.bool	/* whether we accept args at all */
		opts	: optdesc[:]	/* the description of the options */
	;;

	type optdesc = struct
		opt	: char
		arg	: byte[:]
		desc	: byte[:]
		optional	: bool
	;;

	type optparsed = struct
		opts	: (char, byte[:])[:]
		args	: byte[:][:]
	;;

	const optparse	: (optargs : byte[:][:], def : optdef# -> optparsed)
	const optusage	: (prog : byte[:], def : optdef# -> void)
;;

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

	/* data passed in */
	optdef	: optdef#
	optargs	: byte[:][:]

	/* state */
	argidx	: size
	curarg	: byte[:]
	optdone	: bool	/* if we've seen '--', everything's an arg */
	finished	: bool	/* if we've processed all the optargs */
;;


const optparse = {args, def
	var ctx : optctx
	var parsed

	parsed = [
		.opts=[][:],
		.args=[][:]
	]
	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 {} args, got {}\n", def.minargs, ctx.args.len)
		optusage(ctx.optargs[0], ctx.optdef)
		exit(1)
	;;
	if def.maxargs > 0 && ctx.args.len < def.minargs
		put("error: expected at most {} args, got {}\n", def.minargs, ctx.args.len)
		optusage(ctx.optargs[0], ctx.optdef)
		exit(1)
	;;
	if def.noargs && ctx.args.len != 0
		put("error: expected no args, got {}\n", ctx.args.len)
		optusage(ctx.optargs[0], ctx.optdef)
		exit(1)
	;;
	parsed.args = ctx.args
	-> parsed
}

const optinit = {ctx, args, def
	ctx# = [
		.optargs = args,
		.optdef = def,
		.optdone = false,
		.finished = false,
		.argidx = 0,
		.curarg = [][:],
		.args = [][:],
	]

	next(ctx)
	-> ctx
}

const optnext = {ctx
	var c
	var arg

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

	match optinfo(ctx, c)
	| `None:
		if c == 'h' || c == '?'
			optusage(ctx.optargs[0], ctx.optdef)
			exit(0)
		else
			fatal("unexpected argument '{}'\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 {}\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, opt
	for o in ctx.optdef.opts
		if o.opt == opt
			-> `Some (o.arg.len != 0, !o.optional)
		;;
	;;
	-> `None
}

const next = {ctx
	var i

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

const optusage = {prog, def
	var sb, s

	sb = mksb()
	std.sbfmt(sb, "usage: {} [-h?", prog)
	for o in def.opts
		if o.arg.len == 0
			std.sbfmt(sb, "{}", o.opt)
		;;
	;;
	std.sbfmt(sb, "] ")
	for o in def.opts
		if o.arg.len != 0
			std.sbfmt(sb, "[-{} {}] ", o.opt, o.arg)
		;;
	;;
	std.sbfmt(sb, "{}\n", def.argdesc)
	std.sbfmt(sb, "\t-h\tprint this help message\n")
	std.sbfmt(sb, "\t-?\tprint this help message\n")
	for o in def.opts
		std.sbfmt(sb, "\t-{}{}{}\t{}\n", o.opt, sep(o.arg), o.arg, o.desc)
	;;
	s = sbfin(sb)
	write(1, s)
	slfree(s)
}

const sep = {s
	if s.len > 0
		-> " "
	else
		-> ""
	;;
}