zuzu-rust 0.3.0

Rust implementation of ZuzuScript
Documentation
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
=encoding utf8

=head1 NAME

std/getopt - Parse command line arguments.

=head1 SYNOPSIS

  from std/getopt import Getopt;

  function __main__ (argv) {
    let parsed := Getopt.parse(
      argv,
      [ "help|h", "verbose|v", "count|c=i", "name|n=s" ]
    );

    if ( not parsed{ok} ) {
      say( parsed{error} );
      return 2;
    }

    let opts := parsed{options};
    let rest := parsed{argv};

    if ( opts{help} ) {
      say( "usage: tool [--count N] [--name STR] args..." );
      return 0;
    }

    say( "remaining args = " + rest.length() );
    return 0;
  }

=head1 IMPLEMENTATION SUPPORT

This module is supported by all implementations of ZuzuScript.

=head1 DESCRIPTION

This module parses command-line option arrays for ZuzuScript programs.

Use C<Getopt.parse(argv, specs, config?)> and pass the C<argv> array
that your C<__main__> function receives.

It intentionally does not read a host process argument global.

=head1 EXPORTS

=head2 Classes

=over

=item C<Getopt>

Static methods:

=over

=item * C<parse(Array argv, Array specs, Array config?)>

Parameters: C<argv> is the command-line argument array, C<specs> is an
option-spec array, and C<config> is optional parser configuration.
Returns: C<Dict>. Parses arguments into options and remaining
positional arguments.

=item * C<schema(Array argv, Array schema, Array config?)>

Parameters: C<argv> is the command-line argument array, C<schema> is an
array of option schema dictionaries, and C<config> is optional parser
configuration. Returns: C<Dict>. Parses arguments using structured
option metadata and produces errors and usage text.

Schema entries use fields such as C<name>, C<short>,
C<type> (for example C<Number>, C<String>, C<Boolean>),
C<required> (Boolean), C<default>, C<multiple>, and C<desc>.

Returns a dictionary:

=over

=item * C<ok> (Boolean-like Number)

=item * C<options> (Dict)

=item * C<argv> (remaining positional args)

=item * C<error> (String or null)

=item * C<errors> (Array, for C<schema>)

=item * C<usage> (String, for C<schema>)

=back

=back

=back

=head1 COPYRIGHT AND LICENCE

B<< std/getopt >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/string import split, substr, starts_with, ends_with, join;


function _spec_kind_from_suffix ( suffix ) {
	if ( suffix ≡ "i" ) {
		return "integer";
	}
	if ( suffix ≡ "f" ) {
		return "number";
	}
	if ( suffix ≡ "s" ) {
		return "string";
	}
	return "flag";
}

function _normalize_schema_type ( raw_type ) {
	if ( raw_type ≡ null ) {
		return "Boolean";
	}
	if ( raw_type instanceof Function ) {
		let function_name := null;
		try {
			function_name := raw_type.name;
		}
		catch {
		}
		if (
			function_name ≡ "Boolean" or
			function_name ≡ "Number" or
			function_name ≡ "String"
		) {
			return function_name;
		}
	}
	if ( raw_type ≡ Boolean ) {
		return "Boolean";
	}
	if ( raw_type ≡ Number ) {
		return "Number";
	}
	if ( raw_type ≡ String ) {
		return "String";
	}
	let type_name := "" _ raw_type;
	if ( type_name ≡ "" ) {
		return "Boolean";
	}
	return type_name;
}

function _schema_type_suffix ( type_name ) {
	let lowered := lc( "" _ type_name );
	if ( lowered ≡ "boolean" or lowered ≡ "bool" ) {
		return "";
	}
	if ( lowered ≡ "number" or lowered ≡ "num" ) {
		return "=f";
	}
	if ( lowered ≡ "int" or lowered ≡ "integer" ) {
		return "=i";
	}
	return "=s";
}

function _parse_spec ( spec ) {
	let out := {
		name: "",
		short: "",
		suffix: "",
		kind: "flag",
		multiple: 0,
	};

	let base := "" _ spec;
	let spec_parts := split(base, "=");
	let names_part := spec_parts[0];
	if ( spec_parts.length() > 1 ) {
		let rhs := spec_parts[1];
		if ( rhs ≢ null and rhs ≢ "" ) {
			out{suffix} := substr(rhs, 0, 1);
		}
	}

	let aliases := split(names_part, "|");
	if ( aliases.length() > 0 and aliases[0] ≢ null ) {
		out{name} := "" _ aliases[0];
	}
	if ( aliases.length() > 1 and aliases[1] ≢ null ) {
		out{short} := "" _ aliases[1];
	}

	if ( ends_with(base, "@") ) {
		out{multiple} := 1;
	}

	out{kind} := _spec_kind_from_suffix( out{suffix} );
	return out;
}

function _coerce_value ( kind, raw ) {
	if ( kind ≡ "flag" ) {
		return 1;
	}
	if ( kind ≡ "integer" ) {
		return int(raw);
	}
	if ( kind ≡ "number" ) {
		return 0 + raw;
	}
	return "" _ raw;
}

function _parse_from_specs ( argv, specs ) {
	let parsed_specs := [];
	let long_lookup := {};
	let short_lookup := {};
	for ( let spec_text in specs ) {
		let spec := _parse_spec(spec_text);
		if ( spec{name} ≡ "" ) {
			next;
		}
		parsed_specs.push(spec);
			long_lookup{( spec{name} )} := spec;
			if ( spec{short} ≢ "" ) {
				short_lookup{( spec{short} )} := spec;
			}
	}

	let remaining := [];
	let options := {};
	let parse_error := null;
	let i := 0;
	while ( i < argv.length() ) {
		let arg := "" _ argv[i];
		if ( arg ≡ "--" ) {
			let j := i + 1;
			while ( j < argv.length() ) {
				remaining.push( "" _ argv[j] );
				j++;
			}
			last;
		}

		if ( starts_with(arg, "--") and length arg > 2 ) {
			let raw := substr(arg, 2);
			let name := raw;
			let inline_value := null;
			if ( raw ~ /=/ ) {
				let parts := split(raw, "=");
				name := parts[0];
				inline_value := join( "=", parts.slice(1) );
			}
			if ( not( name in long_lookup ) ) {
				parse_error := `Unknown option --${name}`;
				last;
			}
				let spec := long_lookup{( name )};
			if ( spec{kind} ≡ "flag" ) {
				options{( spec{name} )} := 1;
				i++;
				next;
			}

			let value_text := inline_value;
			if ( value_text ≡ null ) {
				if ( i + 1 >= argv.length() ) {
					parse_error := `Option --${name} requires a value`;
					last;
				}
				value_text := "" _ argv[i + 1];
				i++;
			}

			let coerced := _coerce_value( spec{kind}, value_text );
			if ( spec{multiple} ) {
				if ( not( spec{name} in options ) ) {
					options{( spec{name} )} := [];
				}
				options{( spec{name} )}.push(coerced);
			}
			else {
				options{( spec{name} )} := coerced;
			}
			i++;
			next;
		}

		if ( starts_with(arg, "-") and length arg > 1 ) {
			let short_name := substr(arg, 1);
			if ( not( short_name in short_lookup ) ) {
				parse_error := `Unknown option -${short_name}`;
				last;
			}
				let spec := short_lookup{( short_name )};
			if ( spec{kind} ≡ "flag" ) {
				options{( spec{name} )} := 1;
				i++;
				next;
			}
			if ( i + 1 >= argv.length() ) {
				parse_error := `Option -${short_name} requires a value`;
				last;
			}
			let coerced := _coerce_value( spec{kind}, "" _ argv[i + 1] );
			if ( spec{multiple} ) {
				if ( not( spec{name} in options ) ) {
					options{( spec{name} )} := [];
				}
				options{( spec{name} )}.push(coerced);
			}
			else {
				options{( spec{name} )} := coerced;
			}
			i += 2;
			next;
		}

		remaining.push(arg);
		i++;
	}

	return {
		ok: parse_error ≡ null ? 1: 0,
		options: options,
		argv: remaining,
		error: parse_error,
		specs: parsed_specs,
	};
}

class Getopt {
	static method parse ( argv, specs, config? ) {
		let parsed_argv := argv instanceof Array ? argv: [];
		let parsed_specs := specs instanceof Array ? specs: [];
		let _cfg := config;
		let result := _parse_from_specs( parsed_argv, parsed_specs );
		return {
			ok: result{ok},
			options: result{options},
			argv: result{argv},
			error: result{error},
		};
	}

	static method schema ( argv, schema, config? ) {
		let parsed_argv := argv instanceof Array ? argv: [];
		let parsed_schema := schema instanceof Array ? schema: [];
		let _cfg := config;
		let specs := [];
		let usage_lines := [];
		let meta := {};

		for ( let entry in parsed_schema ) {
			if ( not( entry instanceof Dict ) ) {
				next;
			}
			if ( not( "name" in entry ) ) {
				next;
			}
			let name := "" _ entry{name};
			if ( name ≡ "" ) {
				next;
			}
			let short := entry{short} ≡ null ? "": "" _ entry{short};
			let type_name := _normalize_schema_type( entry{type} );
			let suffix := _schema_type_suffix(type_name);
			let is_multiple := entry{multiple} ? 1: 0;
			if ( is_multiple ) {
				suffix _= "@";
			}
			let spec := short ≡ "" ? `${name}${suffix}`: `${name}|${short}${suffix}`;
			specs.push(spec);
			meta{name} := {
				required: entry{required} ? 1: 0,
				has_default: "default" in entry ? 1: 0,
				default_value: entry{default},
			};

			let usage := `  --${name}`;
			if ( short ≢ "" ) {
				usage _= `, -${short}`;
			}
			let lowered := lc(type_name);
			if ( lowered ≢ "boolean" and lowered ≢ "bool" ) {
				usage _= ` <${type_name}>`;
			}
			if ( entry{required} ) {
				usage _= " (required)";
			}
			if ( entry{desc} ≢ null and entry{desc} ≢ "" ) {
				usage _= `  ${entry{desc}}`;
			}
			usage_lines.push(usage);
		}

		let result := _parse_from_specs( parsed_argv, specs );
		let errors := [];
		if ( result{error} ≢ null ) {
			errors.push(result{error});
		}

		for ( let name in meta.keys() ) {
			let entry := meta{name};
			if ( not( name in result{options} ) and entry{has_default} ) {
				result{options}{name} := entry{default_value};
			}
			if ( entry{required} and not( name in result{options} ) ) {
				errors.push( `missing required option --${name}` );
			}
		}

		let ok := errors.length() > 0 ? 0: result{ok};
		return {
			ok: ok,
			options: result{options},
			argv: result{argv},
			error: errors.length() > 0 ? join( "\n", errors ): null,
			errors: errors,
			usage: join( "\n", usage_lines ),
			specs: specs,
		};
	}
}