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
| | /*
* Copyright (C) 2024 olang maintainers
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "cli.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *
cli_args_shift(cli_args_t *args);
static void
cli_opts_parse_output(cli_opts_t *opts, cli_args_t *args);
cli_opts_t
cli_parse_args(int argc, char **argv)
{
cli_args_t args = { .argc = argc, .argv = argv };
cli_opts_t opts = { 0 };
opts.compiler_path = cli_args_shift(&args);
char *arg = cli_args_shift(&args);
while (arg != NULL) {
if (strcmp(arg, "--dump-tokens") == 0) {
opts.options |= CLI_OPT_DUMP_TOKENS;
} else if (strcmp(arg, "--save-temps") == 0) {
opts.options |= CLI_OPT_SAVE_TEMPS;
} else if (strcmp(arg, "-o") == 0) {
cli_opts_parse_output(&opts, &args);
} else {
opts.file_path = arg;
}
arg = cli_args_shift(&args);
}
if (opts.options & CLI_OPT_OUTPUT || opts.options & CLI_OPT_DUMP_TOKENS) {
return opts;
}
cli_print_usage(stderr, opts.compiler_path);
exit(EXIT_FAILURE);
return opts;
}
static char *
cli_args_shift(cli_args_t *args)
{
if (args->argc == 0)
return NULL;
--(args->argc);
return *(args->argv)++;
}
static void
cli_opts_parse_output(cli_opts_t *opts, cli_args_t *args)
{
assert(opts && "opts is required");
assert(args && "args is required");
char *output_bin = cli_args_shift(args);
if (output_bin == NULL) {
fprintf(stderr, "error: missing filename after '-o'\n");
cli_print_usage(stderr, opts->compiler_path);
exit(EXIT_FAILURE);
}
opts->options |= CLI_OPT_OUTPUT;
opts->output_bin = string_view_from_cstr(output_bin);
}
void
cli_print_usage(FILE *stream, char *compiler_path)
{
fprintf(stream,
"Usage: %s [options] file...\n"
"Options:\n"
" --dump-tokens\t\tDisplay lexer token stream\n"
" -o <file>\t\tCompile program into a binary file\n"
" --save-temps\t\tKeep temp files used to compile program\n",
compiler_path);
}
|