Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-12-06 13:39:23 -06:00
commit b1e8b0939d
1624 files changed
+43436

No files matched your search

+70
View File
@@ -0,0 +1,70 @@
# std::args
`std::args` reads a program's arguments into a struct, by the attributes the
program marks it with, and writes the help that says what it reads from the
same marks. A struct marked `@args::command` is read: each field marked
`@args::option` from `--name value`, `--name=value`, or its short form, and
those marked `@args::argument` from what's left. A union of commands is a
command's subcommands, each a field. `args::parse` gives what was read or why it
couldn't be, and `args::parse_or_exit` prints the help or the mistake and exits
where it is asked to.
## Using it
Require the standard library in your blossomfile, and name the module among a
target's `deps`, with the other modules of std it reads:
```yaml
requires:
- https://git.malunal.studio/sakura/std@v1.0.0
targets:
- name: app
type: program
deps: [std.args, std.io]
```
```sakura
import std::io;
import std::args;
@args::command{ name = "greet", help = "Says hello." }
struct greeting {
@args::option{ short = 'n', value = "N", help = "How many times." }
var times: u32 = 1;
@args::option{ short = 'l', help = "Says it loudly." }
var loud: bool;
@args::argument{ value = "NAME", help = "Who to greet." }
var names: vector<strview>;
}
def main(args: span<strview>): void {
val asked := args::parse_or_exit::<greeting>(args);
for &name in asked.names {
for _ in 0..asked.times {
io::println(asked.loud ? $"HELLO, {name}!" : $"Hello, {name}.");
}
}
}
```
## What it reads
The marks are `args::command`, `args::option`, `args::argument`, `args::group`, and
`args::choice`, written with `args::`, as above, or without it, as below, where the file
imports `std::args`.
- **Options** are read by their long names, `--times 2` or `--times=2`, which are their fields' with each `_` written `-`, and by short names, `-n 2` or `-n2`. A `bool` is a switch, and switches are written together, as `-ln2`. A value may begin with `-`, and `--` ends the options, as a lone `-` is positional.
- **Values**: integers within their range, reals, `strview`, `string`, `path`, an enum by the names of its members marked `@choice`, and a program's own type implementing `args::value`. `maybe` may be left out, and a `vector` takes each one written. `count = true` counts how often an integer's option is written, as `-vvv`, and any other option keeps the last one written.
- **Positional arguments** go to the `@argument` fields in turn: a plain one takes one, a `maybe` one where one is left over, a `vector` what is left over, and the one marked `rest = true` what follows `--`.
- **Subcommands**: a union marked `@command`, whose fields are marked `@command`, is either what `parse` is given or a struct's last argument. Its word picks the field, whose own struct reads the arguments after it.
- **Groups**: options several commands share are written once, in a struct marked `@group`. A field of that type, also marked `@group`, reads them as if the command declared them in its place, and the help text shows them there. A group may hold groups, but no positional arguments.
- **Help and mistakes**: `-h`, `--help`, and, where a command gives a `version`, `--version` print the help text or the version and exit with 0, and a mistake in the arguments prints why and exits with 2. `args::parse` gives each as an `args::error` instead, and `args::help::<T>(args)` and `args::usage::<T>(args)` give the text of the subcommand the arguments reach. A mistake in the marks, as two options of one name, stops a checked program the first time it runs.
## Testing
From the standard library's root, `blossom test --suite std.args` runs them, or:
```sh
sakurac run --lib std=. tests/main.sakura tests/args/*.sakura
```
+228
View File
@@ -0,0 +1,228 @@
#! @file args.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what reading a program's arguments knows apart from the walk: the
#! attributes a program marks the struct it reads them into with, the traits of
#! the types read, the errors, and `args::parse` with the functions around it.
#! The help text is written from the same marks, so it says what is read.
import std::io;
import system;
module std::args;
#! Marks a struct or union `args::parse` reads, and each field of a union of
#! subcommands, which is a subcommand of the field's name.
#!
#! The marks are also what lets `std::args` see a type private to the program,
#! since reflection gives a module what carries an attribute it declares. So a
#! command is marked, and each field read, even where it is `pub`.
@core::usage{ on = target::structs | target::unions | target::fields }
pub struct command : attribute {
pub val name: strview = ""; #! Its word, or the program's name in the help text, in place of the declaration's.
pub val help: strview = ""; #! What it does, in a sentence or two.
pub val version: strview = ""; #! What `--version` prints, where it is not empty.
}
#! Marks a field read from an option: `--name value` or `--name=value`, and,
#! where it has a short name, `-n value` or `-nvalue`.
@core::usage{ on = target::fields }
pub struct option : attribute {
pub val name: strview = ""; #! Its long name, without `--`, in place of the field's, whose `_` are written `-`.
pub val short: u8 = 0; #! Its short name, a letter or digit, or 0 for none.
pub val value: strview = ""; #! What the help text calls its value, as `DIR`, in place of its name in capitals.
pub val help: strview = ""; #! What it does.
pub val required: bool = false; #! Whether leaving it out is an error.
pub val count: bool = false; #! Whether an integer counts how often it is written, as `-vvv`.
}
#! Marks a field read from the positional arguments, which go to such fields in
#! the order they are declared. The last may be a union marked `@command`,
#! whose subcommand the next positional argument names.
@core::usage{ on = target::fields }
pub struct argument : attribute {
pub val value: strview = ""; #! What the help text calls it, as `FILE`, in place of its name in capitals.
pub val help: strview = ""; #! What it is.
pub val rest: bool = false; #! Whether it takes only what follows `--`.
}
#! Marks a struct of options several commands share, and each field of such a
#! struct that a command reads, whose options are read, and shown in the help
#! text, as if the command declared them in place of the field. A group holds
#! options, and groups of them, but no positional arguments.
@core::usage{ on = target::structs | target::fields }
pub struct group : attribute {}
#! Marks an enum member read by its name, which is the member's, whose `_` are
#! written `-`, or the `name` given. Members left unmarked are not read.
@core::usage{ on = target::members }
pub struct choice : attribute {
pub val name: strview = ""; #! The word for it, in place of the member's.
pub val help: strview = ""; #! What it means.
}
#! A type an option or an argument is read as, from the text written.
#!
#! std's numbers, `strview`, `string`, `path`, and `maybe` of any of them
#! implement it, and a program's own type may, by declaring it, as
#! `struct celsius : args::value`. An enum whose members are marked `@choice`
#! is read by their names without it.
pub trait value {
#! Reads a value from an argument.
#! @param text The argument, as written.
#! @returns The value, or why the text is not one, as `is not a whole number`.
def from_argument(text: strview): result<self, strview>;
}
#! A type an option is a switch of: on where the option is written, which
#! takes no value. Only `bool` is one.
pub trait switch {
#! The value a switch has where it is written.
#! @returns The value.
def switched_on(): self;
}
#! Why the arguments could not be read.
pub enum error_kind: u8 {
unknown_option, #! An option no field takes, as `--colour`.
missing_value, #! An option taking a value ends the arguments.
invalid_value, #! A value its type refuses, as `300` for a `u8`.
switch_given_value, #! A switch written with a value, as `--verbose=yes`.
missing_option, #! A `required` option is left out.
missing_argument, #! A positional argument that is not a `maybe` or `vector` is left out.
unexpected_argument, #! A positional argument no field takes.
unknown_command, #! A word that names no subcommand.
missing_command, #! The arguments end where a subcommand is needed.
help_asked, #! `-h` or `--help` was written.
version_asked, #! `--version` was written.
}
#! Why the arguments could not be read, and where.
#!
#! An error is plain data, viewing the arguments and the marks, so `else (e)`
#! names it, and it lasts as long as the arguments do.
pub struct error {
pub var kind: error_kind; #! What went wrong.
pub var at: u64; #! The argument's index, or how many there are, at their end.
pub var text: strview; #! That argument, as written, or the value alone where one is wrong, as `300` of `-O300`.
pub var name: strview; #! The option, as written, or the argument, as the help text names it.
pub var reason: strview; #! Why the value was refused, from `value`, or empty.
}
#! Says what went wrong, in a sentence.
#! @param this The error to describe.
#! @returns The sentence, as "`-O 300`: 300 is not between 0 and 255."
pub def error::describe(&this): string {
return match this.kind {
unknown_option => $"`{this.name}` is not an option.",
missing_value => $"`{this.name}` needs a value.",
invalid_value => this.name.length != 0 && this.name[0] == '-'
? $"`{this.name} {this.text}`: {this.text} {this.reason}."
: $"{this.name} `{this.text}` {this.reason}.",
switch_given_value => $"`{this.name}` takes no value, but is given `{this.text}`.",
missing_option => $"`{this.name}` is required.",
missing_argument => $"{this.name} is missing.",
unexpected_argument => $"`{this.text}` is more than the arguments taken.",
unknown_command => $"`{this.text}` is not a command.",
missing_command => string::from("A command is needed.", nothing {}),
help_asked => string::from("The help text is asked for.", nothing {}),
version_asked => string::from("The version is asked for.", nothing {}),
};
}
#! Reads the arguments into a `T`, a struct or union marked `@command`.
#!
#! Each field marked `@option` is read from the option of its name, each marked
#! `@argument` from the positional arguments, in turn, and each marked `@group`
#! from the options of its struct, as the README's "Command-line arguments"
#! says. A field left unmarked, or left out of the arguments, keeps its default,
#! or else its zero value. Before the arguments are read, the marks of `T` and of
#! every subcommand and group within it are checked, and a mistake in them, as
#! two options of one name, stops a checked program, so it is found the first
#! time the program runs, whatever it is given.
#! @tparam T The command, which is `zeroable`, so a field left unread has a
#! value.
#! @param args The arguments, as `main` is given them.
#! @returns The command read, or why the arguments are not one of it, which is
#! `help_asked` or `version_asked` where they ask for those.
pub def parse<T>(args: span<strview>): result<T, error> where T: zeroable {
var reached := reach { words = vector::<strview>::new() };
return read_command::<T>(args, &mut reached);
}
#! Reads the arguments into a `T`, as `parse` does, or else writes why not and
#! stops the program: the help text to the standard output, or the version,
#! with status 0, or the error to the standard error, with a line saying where
#! the help text is, with status 2.
#! @tparam T The command, which is `zeroable`.
#! @param args The arguments, as `main` is given them.
#! @returns The command read.
pub def parse_or_exit<T>(args: span<strview>): T where T: zeroable {
var reached := reach { words = vector::<strview>::new() };
var made := read_command::<T>(args, &mut reached) else (wrong) {
stop::<T>(&wrong, &reached);
var none: T;
return move(none);
};
return move(made);
}
#! The help text of the command the arguments reach, so `tool build --help`
#! gives `build`'s: its usage, what it does, its arguments, its subcommands,
#! and its options, each with what it does.
#! @tparam T The command, which is `zeroable`, so the defaults of its
#! options are shown.
#! @param args The arguments, of which only the subcommands are followed.
#! @returns The text, ending in a line break.
pub def help<T>(args: span<strview> = span::<strview>::blank()): string where T: zeroable {
var reached := reach { words = vector::<strview>::new() };
_ = read_command::<T>(args, &mut reached);
val program := program_name::<T>();
return help_at::<T>(reached.words.span, 0, program, "", true);
}
#! The usage of the command the arguments reach, in one line.
#! @tparam T The command, which is `zeroable`.
#! @param args The arguments, of which only the subcommands are followed.
#! @returns The line, as "usage: sakura build [options] FILE...", without a
#! line break.
pub def usage<T>(args: span<strview> = span::<strview>::blank()): string where T: zeroable {
var reached := reach { words = vector::<strview>::new() };
_ = read_command::<T>(args, &mut reached);
val program := program_name::<T>();
return help_at::<T>(reached.words.span, 0, program, "", false);
}
# What reading the arguments reached, which the help text and the report of an
# error follow: the word of each subcommand the arguments named, in turn, and
# the version of the command `--version` was written to.
struct reach {
var words: vector<strview>;
var version: strview;
}
# Writes why the arguments could not be read, or the help text or version they
# ask for, and stops the program.
def stop<T>(wrong: &error, reached: &reach): void where T: zeroable {
if wrong.kind == error_kind::help_asked {
val text := help_at::<T>(reached.words.span, 0, program_name::<T>(), "", true);
print(text.span);
system::exit(0);
}
if wrong.kind == error_kind::version_asked {
print($"{reached.version}\n");
system::exit(0);
}
var named := string::from(program_name::<T>(), nothing {});
for &each in reached.words {
named.append(" ");
named.append(each);
}
val described := wrong.describe();
val said := $"{program_name::<T>()}: {described}\nTry `{named} --help`.\n";
_ = io::error_output().write(said.span);
system::exit(2);
}
+403
View File
@@ -0,0 +1,403 @@
#! @file help.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the help text `args::help` and `args::usage` write from the marks of
#! a command: its usage, what it does, its arguments, its subcommands, and its
#! options, each with what it does, its default, and the choices it takes, in
#! columns.
import std::semver;
import std::io;
module std::args;
# A type whose default an option's help text shows, as std's numbers and text
# are.
trait shown {
def shown_argument(&this): string;
}
# A type holding values of another, whose choices an option's help text lists,
# as a `maybe` or a vector of an enum does.
trait listed {
def list_choices(into: &mut page): void;
}
# Where a row of the help text goes: under the arguments, the subcommands, or
# the options, or under the option before it, as one of its choices.
enum row_place: u8 { arguments, commands, options, choices }
# The rows of a help text, each a name and what it is, in turn.
struct page {
var places: vector<row_place>;
var lefts: vector<string>;
var rights: vector<string>;
}
# Makes a help text with no rows.
def page::new(): page {
return page {
places = vector::<row_place>::new(),
lefts = vector::<string>::new(),
rights = vector::<string>::new()
};
}
# Adds a row to a help text.
def page::add(&mut this, place: row_place, left: string, right: string): void {
this.places.append(place);
this.lefts.append(move(left));
this.rights.append(move(right));
}
# Writes the sections of a help text, each a heading and its rows, whose names
# are padded so what each is begins in one column, with an option's choices in
# a column of their own under it.
def page::write(&this, into: &mut string): void {
var width := 0u;
for i in 0..this.places.length {
if this.places[i] != row_place::choices && this.lefts[i].length > width {
width = this.lefts[i].length;
}
}
width += 3;
val sections: row_place[3] = [row_place::arguments, row_place::commands, row_place::options];
val headings: strview[3] = ["arguments", "commands", "options"];
for s in 0u..3u {
var any := false;
for &each in this.places {
any = any || each == sections[s];
}
continue if !any;
into.append($"\n{headings[s]}:\n");
for i in 0..this.places.length {
continue if this.places[i] != sections[s];
line(into, this.lefts[i].span, width, this.rights[i].span);
# The choices after an option are padded to the widest of them.
var end := i + 1;
var widest := 0u;
while end < this.places.length && this.places[end] == row_place::choices {
widest = this.lefts[end].length > widest ? this.lefts[end].length : widest;
end++;
}
for j in i + 1..end {
var left := spaces(width + 2);
left.append(this.lefts[j].span);
line(into, left.span, width + 4 + widest, this.rights[j].span);
}
}
}
}
# Writes a row: its name, padded to a width where something follows it, and
# what follows.
def line(into: &mut string, left: strview, width: u64, right: strview): void {
into.append(left);
if right.length != 0 {
for _ in left.length..width {
into.push(' ');
}
into.append(right);
}
into.append("\n");
}
# Text of a number of spaces.
def spaces(count: u64): string {
var made := string::new(nothing {});
for _ in 0..count {
made.push(' ');
}
return made;
}
# The name of the program, as the help text and errors call it: the command's
# `name`, or else its declaration's.
def program_name<T>(): strview {
if const T is switch || T is value || T is repeated {
return "";
} else {
val given := attached::<command>(decl_of::<T>())[0].name;
return given.length != 0 ? given : decl_of::<T>().name;
}
}
# The help text, or only its usage, of the command the words reach within a
# command, through each subcommand they name in turn.
def help_at<T>(words: span<strview>, depth: u64, path: strview, about: strview, whole: bool): string where T: zeroable {
if const T is switch || T is value || T is repeated {
return string::new(nothing {});
} else if const decl_of::<T>().kind == target::unions {
if depth < words.length {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<command>(field).length > 0 {
if named_as(words[depth], field.name, attached::<command>(field)[0].name) {
val deeper := $"{path} {words[depth]}";
return help_at::<type_of(field)>(words, depth + 1, deeper.span, attached::<command>(field)[0].help, whole);
}
}
}
}
return union_help::<T>(path, about, whole);
} else {
if depth < words.length {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
if is_command::<type_of(field)>() {
return help_within::<type_of(field)>(words, depth, path, about, whole);
}
}
}
}
return struct_help::<T>(path, about, whole);
}
}
# The help text the words reach within a field's union of subcommands, or
# nothing for any other field.
def help_within<V>(words: span<strview>, depth: u64, path: strview, about: strview, whole: bool): string {
if const V is switch || V is value || V is repeated {
return string::new(nothing {});
} else if const decl_of::<V>().kind == target::unions && attached::<command>(decl_of::<V>()).length > 0 {
if const V is zeroable {
return help_at::<V>(words, depth, path, about, whole);
} else {
return string::new(nothing {});
}
} else {
return string::new(nothing {});
}
}
# The help text, or only its usage, of a union of subcommands.
def union_help<U>(path: strview, about: strview, whole: bool): string {
var made := $"usage: {path} [options] COMMAND ...";
return made if !whole;
made.append("\n");
val own := attached::<command>(decl_of::<U>())[0].help;
val said := own.length != 0 ? own : about;
if said.length != 0 {
made.append($"\n{said}\n");
}
var rows := page::new();
commands_of::<U>(&mut rows);
helped(&mut rows, true, true, attached::<command>(decl_of::<U>())[0].version.length != 0);
rows.write(&mut made);
return made;
}
# The help text, or only its usage, of a struct of options and arguments.
def struct_help<T>(path: strview, about: strview, whole: bool): string where T: zeroable {
var made := $"usage: {path} [options]";
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
if is_command::<type_of(field)>() {
made.append(" COMMAND ...");
} else {
val marked := attached::<argument>(field)[0];
val name := value_name(field.name, marked.value);
made.append(" ");
made.append(argument_shown(name.span, shape_of::<type_of(field)>(), marked.rest).span);
}
}
}
return made if !whole;
made.append("\n");
val own := attached::<command>(decl_of::<T>())[0].help;
val said := own.length != 0 ? own : about;
if said.length != 0 {
made.append($"\n{said}\n");
}
var rows := page::new();
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
if is_command::<type_of(field)>() {
commands_within::<type_of(field)>(&mut rows);
} else {
val marked := attached::<argument>(field)[0];
val name := value_name(field.name, marked.value);
var left := string::from(" ", nothing {});
var shown := argument_shown(name.span, shape_of::<type_of(field)>(), marked.rest);
if marked.rest {
shown = $"-- {name}...";
}
left.append(shown.span);
rows.add(row_place::arguments, move(left), string::from(marked.help, nothing {}));
}
}
}
var defaults: T;
option_rows::<T>(&mut rows, &defaults);
helped(&mut rows, helps::<T>(true), helps::<T>(false), attached::<command>(decl_of::<T>())[0].version.length != 0);
rows.write(&mut made);
return made;
}
# Adds a row for each option of a command, or of a group within it, in the
# order they are declared, those of a group where its field is: its names, and
# what it does, with its default, read from what holds the defaults, or that it
# is required, and its choices under it.
def option_rows<T>(rows: &mut page, defaults: &T): void {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
val marked := attached::<option>(field)[0];
var left := string::from(marked.short != 0 ? $" {short_written(marked.short)}, --" : " --", nothing {});
left.append(long_name(field.name, marked.name).span);
var switched := marked.count;
if const type_of(field) is switch {
switched = true;
}
if !switched {
left.append(" ");
left.append(value_name(marked.name.length != 0 ? marked.name : field.name, marked.value).span);
}
var right := string::from(marked.help, nothing {});
if marked.required {
right.append(right.length != 0 ? " Required." : "Required.");
} else if !marked.count {
val shown := default_of::<type_of(field)>(&defaults.(field));
if shown.length != 0 {
right.append(right.length != 0 ? " Default: " : "Default: ");
right.append(shown.span);
right.append(".");
}
}
rows.add(row_place::options, move(left), move(right));
choices_of::<type_of(field)>(rows);
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
option_rows::<type_of(field)>(rows, &defaults.(field));
}
}
}
# How a positional argument is shown: as its name, in brackets where it may be
# left out, and followed by `...` where it takes as many as are left over.
def argument_shown(name: strview, taken: shape, rest: bool): string {
if rest {
return $"[-- {name}...]";
}
return match taken {
shape::one => string::from(name, nothing {}),
shape::optional => $"[{name}]",
shape::many => $"{name}...",
};
}
# Adds the rows of the options every command has: `-h` and `--help`, where no
# option of its own takes their names, and `--version`, where it gives one.
def helped(rows: &mut page, short: bool, long: bool, version: bool): void {
if short || long {
val left: strview = short && long ? " -h, --help" : short ? " -h" : " --help";
rows.add(row_place::options, string::from(left, nothing {}), string::from("Shows this help.", nothing {}));
}
if version {
rows.add(row_place::options, string::from(" --version", nothing {}), string::from("Shows the version.", nothing {}));
}
}
# Adds a row for each subcommand of a field's union of them, or none for any
# other field.
def commands_within<V>(rows: &mut page): void {
if const V is switch || V is value || V is repeated {
} else if const decl_of::<V>().kind == target::unions && attached::<command>(decl_of::<V>()).length > 0 {
commands_of::<V>(rows);
}
}
# Adds a row for each subcommand of a union of them: its word, and what it does,
# as its mark in the union says, or else the mark of its own type.
def commands_of<U>(rows: &mut page): void {
for const field in members_of(decl_of::<U>()) {
if const field.kind == target::fields && attached::<command>(field).length > 0 {
val given := attached::<command>(field)[0].help;
val said := given.length != 0 ? given : command_help::<type_of(field)>();
var left := string::from(" ", nothing {});
left.append(long_name(field.name, attached::<command>(field)[0].name).span);
rows.add(row_place::commands, move(left), string::from(said, nothing {}));
}
}
}
# What a command says it does, in its own mark.
def command_help<V>(): strview {
if const V is switch || V is value || V is repeated {
return "";
} else if const attached::<command>(decl_of::<V>()).length > 0 {
return attached::<command>(decl_of::<V>())[0].help;
} else {
return "";
}
}
# Adds a row for each choice an option of a type takes, under it: those of an
# enum, or of the enum a `maybe` or a vector holds.
def choices_of<V>(rows: &mut page): void {
if const V is listed {
V::list_choices(rows);
} else if const V is switch || V is value {
} else if const decl_of::<V>().kind == target::enums {
for const member in members_of(decl_of::<V>()) {
if const member.kind == target::members && attached::<choice>(member).length > 0 {
rows.add(
row_place::choices,
long_name(member.name, attached::<choice>(member)[0].name),
string::from(attached::<choice>(member)[0].help, nothing {})
);
}
}
}
}
# The default an option's help text shows, or nothing for a switch, a `maybe`,
# a vector, empty text, and a program's own type.
def default_of<V>(value: &V): string {
if const V is switch || V is vacant || V is repeated {
return string::new(nothing {});
} else if const V is shown {
return value.shown_argument();
} else if const V is value {
return string::new(nothing {});
} else if const decl_of::<V>().kind == target::enums {
for const member in members_of(decl_of::<V>()) {
if const member.kind == target::members && attached::<choice>(member).length > 0 {
if value == value_of(member) {
return long_name(member.name, attached::<choice>(member)[0].name);
}
}
}
return string::new(nothing {});
} else {
return string::new(nothing {});
}
}
def i8::shown_argument(&this): string { return $"{this}"; }
def i16::shown_argument(&this): string { return $"{this}"; }
def i32::shown_argument(&this): string { return $"{this}"; }
def i64::shown_argument(&this): string { return $"{this}"; }
def u8::shown_argument(&this): string { return $"{this}"; }
def u16::shown_argument(&this): string { return $"{this}"; }
def u32::shown_argument(&this): string { return $"{this}"; }
def u64::shown_argument(&this): string { return $"{this}"; }
def f32::shown_argument(&this): string { return $"{this}"; }
def f64::shown_argument(&this): string { return $"{this}"; }
def strview::shown_argument(&this): string { return string::from(this, nothing {}); }
def string::shown_argument(&this): string { return string::copy_of(this); }
def path::shown_argument(&this): string { return string::from(this.span, nothing {}); }
def maybe<T>::list_choices(into: &mut page): void {
choices_of::<T>(into);
}
def vector<T>::list_choices(into: &mut page): void {
choices_of::<T>(into);
}
+996
View File
@@ -0,0 +1,996 @@
#! @file walk.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the walk `args::parse` reads the arguments by, through what the
#! program marks of the command it is given, the checks of those marks, and the
#! forms of the types std gives: numbers, text, paths, `maybe`, and vectors.
#!
#! A field's type decides how it is read, which `if const` tells by the traits
#! the type implements, and by the kind of its declaration, which only a type
#! the program or std declares has: a switch, a `value`, a vector, an enum of
#! choices, or a union of subcommands. Each step on a field is a function
#! deciding so itself, since `if const` decides by types and kinds alone, not by
#! what a function gives.
#!
#! The options of a command are counted in the order they are declared, those
#! of a group where the group's field is, so each step on an option given by its
#! index goes into the group holding it with the index within the group.
import std::semver;
import std::io;
module std::args;
# A type each argument for it is added to, as a vector is, rather than the last
# being kept.
trait repeated {
def add_argument(&mut this, text: strview): result<void, strview>;
}
# A type that may be left out, as `maybe` is, so a positional argument of it
# takes one only where one is left over.
trait vacant {
def vacant_argument(): self;
}
# How many positional arguments a field takes: one, one where one is left over,
# or as many as are left over.
enum shape: u8 { one, optional, many }
# The index of no option.
const no_option: u64 = 0xFFFFFFFFFFFFFFFF;
# Reads the arguments into a command, after checking its marks.
def read_command<T>(args: span<strview>, reached: &mut reach): result<T, error> where T: zeroable {
check_command::<T>();
return read_part::<T>(args, 0, reached);
}
# Reads the arguments from an index into a command: a struct of options and
# arguments, or a union of subcommands.
def read_part<T>(args: span<strview>, from: u64, reached: &mut reach): result<T, error> where T: zeroable {
if const T is switch || T is value || T is repeated {
compile_error("The type is not `@command`, so its arguments are not read. Mark a struct or union `@command`, and each field to read `@option` or `@argument`.");
return error { kind = error_kind::missing_command, at = from };
} else if const attached::<command>(decl_of::<T>()).length == 0 {
compile_error("The type is not `@command`, so its arguments are not read. Mark it `@command`, and each field to read `@option` or `@argument`.");
return error { kind = error_kind::missing_command, at = from };
} else if const decl_of::<T>().kind == target::unions {
return read_union::<T>(args, from, reached);
} else {
return read_struct::<T>(args, from, reached);
}
}
# Reads a union of subcommands: the options it has, which are only those asking
# for the help text and the version, then the word naming the subcommand, then
# the subcommand's own arguments.
def read_union<U>(args: span<strview>, from: u64, reached: &mut reach): result<U, error> where U: zeroable {
var at := from;
while at < args.length {
val arg := args[at];
if arg == "--" {
at++;
break;
}
break if arg.length < 2 || arg[0] != '-';
if arg == "-h" || arg == "--help" {
return asked(error_kind::help_asked, at, arg);
}
val version := attached::<command>(decl_of::<U>())[0].version;
if arg == "--version" && version.length != 0 {
reached.version = version;
return asked(error_kind::version_asked, at, arg);
}
return error { kind = error_kind::unknown_option, at = at, text = arg, name = arg };
}
if at >= args.length {
return error { kind = error_kind::missing_command, at = args.length };
}
val word := args[at];
for const field in members_of(decl_of::<U>()) {
if const field.kind == target::fields && attached::<command>(field).length > 0 {
if named_as(word, field.name, attached::<command>(field)[0].name) {
reached.words.append(word);
var sub := read_part::<type_of(field)>(args, at + 1, reached) else (wrong) { return wrong; };
var made: U;
made.(field) = move(sub);
return move(made);
}
}
}
return error { kind = error_kind::unknown_command, at = at, text = word, name = word };
}
# Reads a struct of options and positional arguments, the last of which may be
# a union of subcommands, which every argument after its word belongs to.
def read_struct<T>(args: span<strview>, from: u64, reached: &mut reach): result<T, error> where T: zeroable {
var made: T;
var seen := vector::<u64>::new();
var positional := vector::<u64>::new();
var after := vector::<u64>::new();
val before := arguments_before_command::<T>();
val commanded := before != no_option;
var named := false;
var ended := false;
var at := from;
while at < args.length {
val arg := args[at];
var plain := ended;
if !ended {
if arg == "--" {
ended = true;
} else if arg.length > 2 && arg[0] == '-' && arg[1] == '-' {
_ = read_long::<T>(&mut made, args, &mut at, &mut seen, reached) else (wrong) { return wrong; };
} else if arg.length > 1 && arg[0] == '-' && !(arg[1].is_digit && !digit_named::<T>()) {
_ = read_short::<T>(&mut made, args, &mut at, &mut seen, reached) else (wrong) { return wrong; };
} else {
plain = true;
}
}
if plain {
# The positional argument after those the fields before it take names a
# subcommand, which reads the rest.
if commanded && positional.length + after.length == before {
_ = read_subcommand::<T>(&mut made, args, at, reached) else (wrong) { return wrong; };
named = true;
break;
}
if ended {
after.append(at);
} else {
positional.append(at);
}
}
at++;
}
if commanded && !named {
return error { kind = error_kind::missing_command, at = args.length };
}
val left := required_left::<T>(&seen, 0);
if left.length != 0 {
return error { kind = error_kind::missing_option, at = args.length, name = keep($"--{left}") };
}
_ = read_positional::<T>(&mut made, args, &mut positional, &after) else (wrong) { return wrong; };
return move(made);
}
# Reads an option written by its long name, as `--name value` or `--name=value`,
# taking its value from the next argument where none is attached, or the help
# text or the version where it asks for them.
def read_long<T>(made: &mut T, args: span<strview>, at: &mut u64, seen: &mut vector<u64>, reached: &mut reach): result<void, error> where T: zeroable {
val arg := args[at];
var name := arg.substr(2, arg.length - 2);
var value: strview = "";
var joined := false;
for i in 0..name.length {
if name[i] == '=' {
value = name.substr(i + 1, name.length - i - 1);
name = name.substr(0, i);
joined = true;
break;
}
}
val written := arg.substr(0, name.length + 2);
val which := option_named::<T>(name);
if which == no_option {
if name == "help" && !joined && helps::<T>(false) {
return asked(error_kind::help_asked, at, arg);
}
val version := attached::<command>(decl_of::<T>())[0].version;
if name == "version" && !joined && version.length != 0 {
reached.version = version;
return asked(error_kind::version_asked, at, arg);
}
return error { kind = error_kind::unknown_option, at = at, text = arg, name = written };
}
seen.append(which);
if !takes_value::<T>(which) {
if joined {
return error { kind = error_kind::switch_given_value, at = at, text = value, name = written };
}
return take_option::<T>(made, which, "", at, written);
}
if !joined {
if at + 1 >= args.length {
return error { kind = error_kind::missing_value, at = args.length, text = arg, name = written };
}
at++;
value = args[at];
}
return take_option::<T>(made, which, value, at, written);
}
# Reads options written by their short names, as `-v`, `-vq`, `-O 2`, or `-vO2`:
# switches may be written together, and the last written together may take a
# value, which is what follows it, or the next argument.
def read_short<T>(made: &mut T, args: span<strview>, at: &mut u64, seen: &mut vector<u64>, reached: &mut reach): result<void, error> where T: zeroable {
val arg := args[at];
var i := 1u;
while i < arg.length {
val letter := arg[i];
val written := short_written(letter);
val which := option_lettered::<T>(letter);
if which == no_option {
if letter == 'h' && helps::<T>(true) {
return asked(error_kind::help_asked, at, arg);
}
return error { kind = error_kind::unknown_option, at = at, text = arg, name = written.length == 2 ? written : arg };
}
seen.append(which);
if !takes_value::<T>(which) {
_ = take_option::<T>(made, which, "", at, written) else (wrong) { return wrong; };
i++;
continue;
}
if i + 1 < arg.length {
return take_option::<T>(made, which, arg.substr(i + 1, arg.length - i - 1), at, written);
}
if at + 1 >= args.length {
return error { kind = error_kind::missing_value, at = args.length, text = arg, name = written };
}
at++;
return take_option::<T>(made, which, args[at], at, written);
}
return;
}
# Reads the subcommand whose word is at an index into the field holding the
# union of them.
def read_subcommand<T>(made: &mut T, args: span<strview>, at: u64, reached: &mut reach): result<void, error> where T: zeroable {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
_ = read_into::<type_of(field)>(&mut made.(field), args, at, reached) else (wrong) { return wrong; };
}
}
return;
}
# Reads a subcommand into a field, where the field holds a union of them, and
# does nothing to any other.
def read_into<V>(place: &mut V, args: span<strview>, at: u64, reached: &mut reach): result<void, error> {
if const V is switch || V is value || V is repeated {
return;
} else if const decl_of::<V>().kind == target::unions && attached::<command>(decl_of::<V>()).length > 0 {
if const V is zeroable {
var sub := read_part::<V>(args, at, reached) else (wrong) { return wrong; };
place = move(sub);
}
return;
} else {
return;
}
}
# Reads the positional arguments into the fields marked `@argument`, in the
# order they are declared: one takes one, a `maybe` one where one is left over
# for those after it, and a vector as many as are left over. The arguments after
# `--` go to the one taking the rest, where there is one, and are otherwise read
# as the others are.
def read_positional<T>(made: &mut T, args: span<strview>, positional: &mut vector<u64>, after: &vector<u64>): result<void, error> where T: zeroable {
var shapes := vector::<shape>::new();
var rests := vector::<bool>::new();
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
if !is_command::<type_of(field)>() {
shapes.append(shape_of::<type_of(field)>());
rests.append(attached::<argument>(field)[0].rest);
}
}
}
var resting := false;
for &each in rests {
resting = resting || each;
}
if !resting {
for &each in after {
positional.append(each);
}
}
# How many each takes, leaving those after it the one each needs.
var counts := vector::<u64>::new();
var left := positional.length;
for k in 0..shapes.length {
var needed := 0u;
for j in k + 1..shapes.length {
if !rests[j] && shapes[j] == shape::one {
needed++;
}
}
var taken := 0u;
if !rests[k] {
if shapes[k] == shape::one {
taken = left > 0 ? 1 : 0;
} else if shapes[k] == shape::optional {
taken = left > needed ? 1 : 0;
} else {
taken = left > needed ? left - needed : 0;
}
}
counts.append(taken);
left -= taken;
}
if left > 0 {
val extra := positional[positional.length - left];
return error { kind = error_kind::unexpected_argument, at = extra, text = args[extra] };
}
var k := 0u;
var next := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
if !is_command::<type_of(field)>() {
val name := attached::<argument>(field)[0].value;
if rests[k] {
for &each in after {
_ = store::<type_of(field)>(&mut made.(field), args[each]) else (why) {
return refused(each, args[each], argument_name(field.name, name), why);
};
}
} else {
if shapes[k] == shape::one && counts[k] == 0 {
return error { kind = error_kind::missing_argument, at = args.length, name = argument_name(field.name, name) };
}
for _ in 0..counts[k] {
val each := positional[next];
next++;
_ = store::<type_of(field)>(&mut made.(field), args[each]) else (why) {
return refused(each, args[each], argument_name(field.name, name), why);
};
}
}
k++;
}
}
}
return;
}
# Reads an option into its field, by its index among the options: a count adds
# one, a switch is turned on, and anything else reads the value written.
def take_option<T>(made: &mut T, which: u64, value: strview, at: u64, written: strview): result<void, error> where T: zeroable {
var index := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if index == which {
if attached::<option>(field)[0].count {
count_one::<type_of(field)>(&mut made.(field));
return;
}
if const type_of(field) is switch {
made.(field) = switched::<type_of(field)>();
return;
} else {
_ = store::<type_of(field)>(&mut made.(field), value) else (why) {
return refused(at, value, written, why);
};
return;
}
}
index++;
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
val held := options_in::<type_of(field)>();
if which < index + held {
return take_option::<type_of(field)>(&mut made.(field), which - index, value, at, written);
}
index += held;
}
}
return;
}
# How many options a struct holds, those of its groups among them.
def options_in<T>(): u64 {
var count := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
count++;
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
count += options_in::<type_of(field)>();
}
}
return count;
}
# The index among the options of the one of a long name, or `no_option`.
def option_named<T>(name: strview): u64 {
var index := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if named_as(name, field.name, attached::<option>(field)[0].name) {
return index;
}
index++;
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
val found := option_named::<type_of(field)>(name);
if found != no_option {
return index + found;
}
index += options_in::<type_of(field)>();
}
}
return no_option;
}
# The index among the options of the one of a short name, or `no_option`.
def option_lettered<T>(letter: u8): u64 {
var index := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if attached::<option>(field)[0].short == letter {
return index;
}
index++;
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
val found := option_lettered::<type_of(field)>(letter);
if found != no_option {
return index + found;
}
index += options_in::<type_of(field)>();
}
}
return no_option;
}
# Whether the option of an index takes a value, which a switch and a count do
# not.
def takes_value<T>(which: u64): bool {
var index := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if index == which {
if attached::<option>(field)[0].count {
return false;
}
if const type_of(field) is switch {
return false;
} else {
return true;
}
}
index++;
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
val held := options_in::<type_of(field)>();
if which < index + held {
return takes_value::<type_of(field)>(which - index);
}
index += held;
}
}
return false;
}
# The long name of the first `required` option left out, counting the options
# from an index, or empty text where none is.
def required_left<T>(seen: &vector<u64>, from: u64): string {
var index := from;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if attached::<option>(field)[0].required && !holds(seen, index) {
return long_name(field.name, attached::<option>(field)[0].name);
}
index++;
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
val left := required_left::<type_of(field)>(seen, index);
if left.length != 0 {
return left;
}
index += options_in::<type_of(field)>();
}
}
return string::new(nothing {});
}
# Whether any option's short name is a digit, which makes `-5` an option rather
# than a positional argument.
def digit_named<T>(): bool {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if attached::<option>(field)[0].short.is_digit {
return true;
}
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
if digit_named::<type_of(field)>() {
return true;
}
}
}
return false;
}
# Whether the command has `-h`, where `short`, or else `--help`, which it has
# unless an option of its own takes the name.
def helps<T>(short: bool): bool {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if short && attached::<option>(field)[0].short == 'h' {
return false;
}
if !short && named_as("help", field.name, attached::<option>(field)[0].name) {
return false;
}
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
if !helps::<type_of(field)>(short) {
return false;
}
}
}
return true;
}
# How many positional arguments come before a struct's union of subcommands, or
# `no_option` where it has none.
def arguments_before_command<T>(): u64 {
var count := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
if is_command::<type_of(field)>() {
return count;
}
count++;
}
}
return no_option;
}
# Whether a type is a union of subcommands, which a field marked `@argument`
# holds. Only a type with a declaration of its own may be one, which the
# language's own types are not.
def is_command<V>(): bool {
if const V is switch || V is value || V is repeated {
return false;
} else if const decl_of::<V>().kind == target::unions && attached::<command>(decl_of::<V>()).length > 0 {
return true;
} else {
return false;
}
}
# How many positional arguments a field of a type takes.
def shape_of<V>(): shape {
if const V is repeated {
return shape::many;
} else if const V is vacant {
return shape::optional;
} else {
return shape::one;
}
}
# Stores what an argument gives into a field: one more element of what is
# repeated, or else the value read, in place of any before. A union of
# subcommands is read otherwise, and takes nothing here.
def store<V>(place: &mut V, text: strview): result<void, strview> {
if const V is repeated {
return place.add_argument(text);
} else if const V is value {
var read := V::from_argument(text) else (why) { return why; };
place = move(read);
return;
} else if const V is switch {
return "is a switch";
} else if const decl_of::<V>().kind == target::enums {
var read := read_value::<V>(text) else (why) { return why; };
place = move(read);
return;
} else {
return "is not read";
}
}
# Reads a value of a type from the text written: a `value` reads itself, and an
# enum is read by the name of a member marked `@choice`.
def read_value<V>(text: strview): result<V, strview> {
if const V is value {
return V::from_argument(text);
} else if const V is switch {
compile_error("A switch is turned on by its option alone, so it is not read from text: a `maybe` or `vector` of `bool` is not read.");
return "is not read";
} else if const decl_of::<V>().kind == target::enums {
for const member in members_of(decl_of::<V>()) {
if const member.kind == target::members && attached::<choice>(member).length > 0 {
if named_as(text, member.name, attached::<choice>(member)[0].name) {
return value_of(member);
}
}
}
return "is not one of the choices";
} else {
compile_error("The type is not read from an argument. A field read is a `bool` switch, an enum of members marked `@choice`, or what implements `args::value`, or a `maybe` or `vector` of one.");
return "is not read";
}
}
# Adds one to a count, which is an integer.
def count_one<V>(place: &mut V): void {
if const V is integer {
place = place + 1;
}
}
# The value a switch has where its option is written.
def switched<V>(): V where V: switch {
return V::switched_on();
}
# Whether the indices hold one.
def holds(indices: &vector<u64>, index: u64): bool {
for &each in indices {
return true if each == index;
}
return false;
}
# The error of a value its type refused, at the argument holding it.
def refused(at: u64, text: strview, name: strview, why: strview): error {
return error { kind = error_kind::invalid_value, at = at, text = text, name = name, reason = why };
}
# The error of the help text or the version asked for, at the argument asking.
def asked(kind: error_kind, at: u64, text: strview): error {
return error { kind = kind, at = at, text = text, name = text };
}
# Whether a word names what is declared: the name given in its mark, where it
# is not empty, as it is written, or else the declaration's, whose `_` are
# written `-`.
def named_as(word: strview, declared: strview, given: strview): bool {
if given.length != 0 {
return word == given;
}
if word.length != declared.length {
return false;
}
for i in 0..word.length {
if word[i] != (declared[i] == '_' ? '-' : declared[i]) {
return false;
}
}
return true;
}
# A name as it is written: the name given in a mark, where it is not empty, or
# else the declaration's, whose `_` are written `-`.
def long_name(declared: strview, given: strview): string {
if given.length != 0 {
return string::from(given, nothing {});
}
var made := string::new(nothing {});
for each in declared {
made.push(each == '_' ? '-' : each);
}
return made;
}
# What the help text calls a positional argument, or an option's value: the
# name given in its mark, or else the declaration's in capitals.
def value_name(declared: strview, given: strview): string {
if given.length != 0 {
return string::from(given, nothing {});
}
var made := string::new(nothing {});
for each in declared {
made.push(each.to_upper);
}
return made;
}
# What an error calls a positional argument, as the help text does.
def argument_name(declared: strview, given: strview): strview {
return given.length != 0 ? given : keep(value_name(declared, given));
}
# Each short name as written, `-` and the letter or digit, which an error views.
const shorts: strview = "-0-1-2-3-4-5-6-7-8-9-A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z-a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z";
# A short name as written, as an error names it, or `-` alone for a byte that
# is no letter or digit.
def short_written(letter: u8): strview {
for i in 0..shorts.length / 2 {
if shorts[i * 2 + 1] == letter {
return shorts.substr(i * 2, 2);
}
}
return shorts.substr(0, 1);
}
# Text made for an error, which views it, kept for as long as the program runs,
# as an error's views of the arguments are.
var kept: vector<string>;
# Keeps text for as long as the program runs.
def keep(text: string): strview {
kept.append(move(text));
return kept[kept.length - 1].span;
}
# Checks the marks of a command, and of each command within it: while compiling,
# that each field read is of a type read from an argument, and before reading,
# what `if const` cannot decide, stopping the program with an `asserts` at the
# first mistake.
def check_command<T>(): void {
if const decl_of::<T>().kind == target::unions {
var names := vector::<string>::new();
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<command>(field).length > 0 {
if const type_of(field) is switch || type_of(field) is value || type_of(field) is repeated {
compile_error("A subcommand is a struct or union marked `@command`.", field.at);
} else if const attached::<command>(decl_of::<type_of(field)>()).length == 0 {
compile_error("A subcommand is a struct or union marked `@command`.", field.at);
} else {
check_command::<type_of(field)>();
}
var name := long_name(field.name, attached::<command>(field)[0].name);
for &other in names {
asserts(other.span != name.span, $"Two subcommands are named `{name}`.");
}
names.append(move(name));
}
}
} else {
var longs := vector::<string>::new();
var letters := vector::<u8>::new();
check_options::<T>(&mut longs, &mut letters);
var rests := 0u;
var commanded := false;
var single := true;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
asserts(!commanded, "A union of subcommands is the last argument.");
if const type_of(field) is switch {
compile_error("A switch is an option, which a positional argument is not.", field.at);
} else if const type_of(field) is value || type_of(field) is repeated {
} else if const decl_of::<type_of(field)>().kind == target::enums {
} else if const decl_of::<type_of(field)>().kind == target::unions && attached::<command>(decl_of::<type_of(field)>()).length > 0 {
asserts(single, "The arguments before a union of subcommands each take one.");
commanded = true;
check_command::<type_of(field)>();
} else {
compile_error("The type is not read from an argument. An argument is an enum of members marked `@choice`, or what implements `args::value`, or a `maybe` or `vector` of one, or a union of subcommands.", field.at);
}
if !commanded {
val rest := attached::<argument>(field)[0].rest;
single = single && !rest && shape_of::<type_of(field)>() == shape::one;
if rest {
rests++;
asserts(shape_of::<type_of(field)>() == shape::many, "The argument taking what follows `--` is a vector.");
asserts(rests <= 1, "Only one argument takes what follows `--`.");
}
}
}
}
}
}
# Checks the marks of the options of a command, or of a group within it, and of
# the groups within that, which share the names the options are given: while
# compiling, that each is of a type read from an argument, and that a group is
# a struct of options marked `@group`, and before reading, that no two options
# share a name, which an `asserts` stops a checked program at.
def check_options<T>(longs: &mut vector<string>, letters: &mut vector<u8>): void {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 && attached::<argument>(field).length > 0 {
compile_error("A field is read from an option or from the positional arguments, not both.", field.at);
}
if const field.kind == target::fields && attached::<group>(field).length > 0 && (attached::<option>(field).length > 0 || attached::<argument>(field).length > 0) {
compile_error("A group's field is read from the options of its struct, so it is marked only `@group`.", field.at);
}
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if const type_of(field) is switch || type_of(field) is value || type_of(field) is repeated {
} else if const decl_of::<type_of(field)>().kind == target::enums {
} else if const decl_of::<type_of(field)>().kind == target::unions && attached::<command>(decl_of::<type_of(field)>()).length > 0 {
compile_error("Subcommands are read from the positional arguments, so their union is marked `@argument`.", field.at);
} else {
compile_error("The type is not read from an argument. An option is a `bool` switch, an enum of members marked `@choice`, or what implements `args::value`, or a `maybe` or `vector` of one.", field.at);
}
val marked := attached::<option>(field)[0];
var name := long_name(field.name, marked.name);
for &other in longs {
asserts(other.span != name.span, $"Two options are named `--{name}`.");
}
longs.append(move(name));
if marked.short != 0 {
asserts(marked.short.is_alnum, "A short name is a letter or a digit.");
for &other in letters {
asserts(other != marked.short, $"Two options are named `{short_written(marked.short)}`.");
}
letters.append(marked.short);
}
asserts(!marked.count || counts::<type_of(field)>(), "A `count` option is an integer.");
}
if const field.kind == target::fields && attached::<group>(field).length > 0 {
if const type_of(field) is switch || type_of(field) is value || type_of(field) is repeated {
compile_error("A group is a struct of options marked `@group`.", field.at);
} else if const decl_of::<type_of(field)>().kind != target::structs || attached::<group>(decl_of::<type_of(field)>()).length == 0 {
compile_error("A group is a struct of options marked `@group`.", field.at);
} else {
check_group::<type_of(field)>(longs, letters);
}
}
}
}
# Checks the marks of a group, which holds options and groups of them, as
# `check_options` does, and no positional argument.
def check_group<G>(longs: &mut vector<string>, letters: &mut vector<u8>): void {
for const field in members_of(decl_of::<G>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
compile_error("A group holds options, and groups of them, but no positional argument.", field.at);
}
}
check_options::<G>(longs, letters);
}
# Whether a type counts how often its option is written, as an integer does.
def counts<V>(): bool {
if const V is integer {
return true;
} else {
return false;
}
}
def bool::switched_on(): bool { return true; }
def i8::from_argument(text: strview): result<i8, strview> {
val read := signed_within(text, 0 - 128, 127) else (why) { return why; };
return read as i8;
}
def i16::from_argument(text: strview): result<i16, strview> {
val read := signed_within(text, 0 - 32768, 32767) else (why) { return why; };
return read as i16;
}
def i32::from_argument(text: strview): result<i32, strview> {
val read := signed_within(text, 0 - 2147483648, 2147483647) else (why) { return why; };
return read as i32;
}
def i64::from_argument(text: strview): result<i64, strview> {
return signed_within(text, 0 - 9223372036854775807 - 1, 9223372036854775807);
}
def u8::from_argument(text: strview): result<u8, strview> {
val read := unsigned_within(text, 255) else (why) { return why; };
return read as u8;
}
def u16::from_argument(text: strview): result<u16, strview> {
val read := unsigned_within(text, 65535) else (why) { return why; };
return read as u16;
}
def u32::from_argument(text: strview): result<u32, strview> {
val read := unsigned_within(text, 4294967295) else (why) { return why; };
return read as u32;
}
def u64::from_argument(text: strview): result<u64, strview> {
return unsigned_within(text, 18446744073709551615);
}
def f32::from_argument(text: strview): result<f32, strview> {
val read := real_of(text) else (why) { return why; };
if read > 3.4028234663852886e38 || read < -3.4028234663852886e38 {
return "is too large";
}
return read as f32;
}
def f64::from_argument(text: strview): result<f64, strview> {
return real_of(text);
}
# A view of the argument, which lasts as long as the arguments do.
def strview::from_argument(text: strview): result<strview, strview> {
return result::<strview, strview> { value = text };
}
def string::from_argument(text: strview): result<string, strview> {
return string::from(text, nothing {});
}
def path::from_argument(text: strview): result<path, strview> {
var read := path::parse(text) else (_) { return "is not a path"; };
return move(read);
}
def maybe<T>::from_argument(text: strview): result<maybe<T>, strview> {
var read := read_value::<T>(text) else (why) { return why; };
var made: maybe<T> = move(read);
return move(made);
}
def maybe<T>::vacant_argument(): maybe<T> {
return nothing {};
}
def vector<T>::add_argument(&mut this, text: strview): result<void, strview> {
var read := read_value::<T>(text) else (why) { return why; };
this.append(move(read));
return;
}
# A whole number written in decimal, or after `0x`, `0o`, or `0b`, where `_` may
# separate digits, and a sign may come first: how large it is, and its sign.
struct whole {
var magnitude: u64;
var negative: bool;
}
# Reads a whole number, giving nothing where the text is no such number, or one
# past 64 bits.
def whole_of(text: strview): maybe<whole> {
var at := 0u;
var negative := false;
if text.length > 0 && (text[0] == '-' || text[0] == '+') {
negative = text[0] == '-';
at = 1;
}
var base := 10u;
if text.length > at + 1 && text[at] == '0' {
val marker := text[at + 1];
if marker == 'x' || marker == 'X' { base = 16; }
if marker == 'o' || marker == 'O' { base = 8; }
if marker == 'b' || marker == 'B' { base = 2; }
if base != 10 { at += 2; }
}
var digits := 0u;
var magnitude := 0u;
while at < text.length {
val byte := text[at];
at++;
continue if byte == '_' && digits != 0;
return nothing {} if !byte.is_alnum;
val digit := byte.digit_value;
return nothing {} if digit >= base;
return nothing {} if magnitude > (18446744073709551615 - digit) / base;
magnitude = magnitude * base + digit;
digits++;
}
return nothing {} if digits == 0;
return whole { magnitude = magnitude, negative = negative };
}
# A signed integer read from text, within bounds.
def signed_within(text: strview, low: i64, high: i64): result<i64, strview> {
val read := whole_of(text) else { return "is not a whole number"; };
val limit: u64 = read.negative ? (0 - (low + 1)) as u64 + 1 : high as u64;
if read.magnitude > limit {
return keep($"is not between {low} and {high}");
}
return read.negative ? (0 - read.magnitude) as i64 : read.magnitude as i64;
}
# An unsigned integer read from text, within a bound.
def unsigned_within(text: strview, high: u64): result<u64, strview> {
val read := whole_of(text) else { return "is not a whole number"; };
if read.magnitude > high || (read.negative && read.magnitude != 0) {
return keep($"is not between 0 and {high}");
}
return read.magnitude;
}
# A real number read from text.
def real_of(text: strview): result<f64, strview> {
return match real::parse::<f64>(text) {
value(read) => read,
error(_) => "is not a number",
};
}