1292 lines
43 KiB
C
1292 lines
43 KiB
C
#ifndef __SCC_ARGPARSE_H__
|
||
#define __SCC_ARGPARSE_H__
|
||
|
||
#include "optparse.h"
|
||
|
||
#ifndef SCC_ARGPARSE_NOT_USE_STD
|
||
#include <stdbool.h>
|
||
#include <stdint.h>
|
||
#include <stdio.h> // only for printf
|
||
#include <stdlib.h> // only for realloc/free
|
||
#include <string.h> // only for memcpy/strcmp/strlen
|
||
typedef bool cbool;
|
||
|
||
#ifndef SPL_USIZE_TYPEDEF
|
||
#define SPL_USIZE_TYPEDEF
|
||
typedef uintptr_t usize;
|
||
#endif
|
||
#define __vec_realloc realloc
|
||
#define __vec_free free
|
||
#define __vec_memcpy memcpy
|
||
|
||
#define scc_vec_free(vec) \
|
||
(free((vec).items), (vec).items = nullptr, (vec).count = 0, (vec).capacity = 0)
|
||
#define scc_vec_init(vec) ((vec).count = 0, (vec).capacity = 0, (vec).items = nullptr)
|
||
#define scc_vec_reserve(vec, expected_capacity) \
|
||
do { \
|
||
if ((expected_capacity) > (vec)->capacity) { \
|
||
if ((vec)->capacity == 0) { \
|
||
(vec)->capacity = 8; \
|
||
} \
|
||
while ((expected_capacity) > (vec)->capacity) { \
|
||
(vec)->capacity *= 2; \
|
||
} \
|
||
(vec)->items = __vec_realloc((vec)->items, (vec)->capacity * sizeof(*(vec)->items)); \
|
||
/* NOB_ASSERT((vec)->items != NULL && "Buy more RAM lol"); */ \
|
||
} \
|
||
} while (0)
|
||
|
||
// Append an item to a dynamic array
|
||
#define scc_vec_push(vec, item) \
|
||
do { \
|
||
scc_vec_reserve((vec), (vec)->count + 1); \
|
||
(vec)->items[(vec)->count++] = (item); \
|
||
} while (0)
|
||
|
||
// Append several items to a dynamic array
|
||
#define scc_vec_push_many(vec, new_items, new_items_count) \
|
||
do { \
|
||
scc_vec_reserve((vec), (vec)->count + (new_items_count)); \
|
||
__vec_memcpy((vec)->items + (vec)->count, (new_items), \
|
||
(new_items_count) * sizeof(*(vec)->items)); \
|
||
(vec)->count += (new_items_count); \
|
||
} while (0)
|
||
|
||
#define scc_strcmp strcmp
|
||
#define scc_strlen strlen
|
||
#define scc_printf printf
|
||
#define scc_realloc realloc
|
||
#define scc_free free
|
||
#else
|
||
typedef int cbool;
|
||
#define true 1
|
||
#define false 0
|
||
#error "Please define your own types and functions."
|
||
#endif
|
||
|
||
// TODO: 实现更多高级功能
|
||
// 1. 支持子命令嵌套层级限制
|
||
// 2. 支持选项分组显示(Grouping)
|
||
// 3. 支持自动补全脚本生成(Bash/Zsh/Fish/Powershell)
|
||
// 4. 支持配置文件解析
|
||
// 5. 支持国际化(i18n)
|
||
|
||
/// @brief 命令行参数约束
|
||
typedef struct scc_argparse_spec scc_argparse_spec_t;
|
||
/// @brief 命令行参数 eg. someting
|
||
typedef struct scc_argparse_arg scc_argparse_arg_t;
|
||
/// @brief 命令行参数选项 eg. -a --long
|
||
typedef struct scc_argparse_opt scc_argparse_opt_t;
|
||
/// @brief 命令集合
|
||
typedef struct scc_argparse_cmd scc_argparse_cmd_t;
|
||
|
||
typedef struct {
|
||
scc_argparse_arg_t *items;
|
||
usize count;
|
||
usize capacity;
|
||
} scc_argparse_arg_vec_t;
|
||
typedef struct {
|
||
scc_argparse_opt_t *items;
|
||
usize count;
|
||
usize capacity;
|
||
} scc_argparse_opt_vec_t;
|
||
typedef struct {
|
||
scc_argparse_cmd_t *items;
|
||
usize count;
|
||
usize capacity;
|
||
} scc_argparse_cmd_vec_t;
|
||
|
||
typedef enum scc_argparse_val_type {
|
||
SCC_ARGPARSE_VAL_TYPE_UNKNOWN,
|
||
SCC_ARGPARSE_VAL_TYPE_STRING,
|
||
SCC_ARGPARSE_VAL_TYPE_BOOL,
|
||
SCC_ARGPARSE_VAL_TYPE_INT,
|
||
SCC_ARGPARSE_VAL_TYPE_FLOAT,
|
||
SCC_ARGPARSE_VAL_TYPE_ENUM,
|
||
SCC_ARGPARSE_VAL_TYPE_LIST,
|
||
SCC_ARGPARSE_VAL_TYPE_COUNT,
|
||
} scc_argparse_val_type_t;
|
||
|
||
typedef enum scc_argparse_err {
|
||
SCC_ARGPARSE_ERR_NONE,
|
||
SCC_ARGPARSE_ERR_UNREACHABLE,
|
||
SCC_ARGPARSE_ERR_PNT_DEFAULT,
|
||
SCC_ARGPARSE_ERR_UNKNOWN_ERR,
|
||
SCC_ARGPARSE_ERR_INVALID_ARG,
|
||
SCC_ARGPARSE_ERR_INVALID_VALUE,
|
||
SCC_ARGPARSE_ERR_MISSING_ARG,
|
||
SCC_ARGPARSE_ERR_MISSING_VALUE,
|
||
SCC_ARGPARSE_ERR_UNKNOWN_ARG,
|
||
SCC_ARGPARSE_ERR_UNKNOWN_VALUE,
|
||
} scc_argparse_err_t;
|
||
|
||
typedef struct {
|
||
const char **items;
|
||
usize count;
|
||
usize capacity;
|
||
} scc_argparse_list_t;
|
||
|
||
// 约束规范结构体
|
||
struct scc_argparse_spec {
|
||
scc_argparse_val_type_t value_type; // 值类型
|
||
const char *raw_value;
|
||
|
||
// 存储位置
|
||
union {
|
||
cbool *bool_store; // 布尔值存储
|
||
int *int_store; // 整数存储
|
||
float *float_store; // 浮点数存储
|
||
const char **str_store; // 字符串存储
|
||
char **str_alloc_store; // 字符串存储(使用alloc,需要free)
|
||
void **ptr_store; // 通用指针存储
|
||
scc_argparse_list_t *vec_store; // 新增:指向字符串向量的指针
|
||
} store;
|
||
|
||
// 枚举值约束
|
||
struct {
|
||
const char **values; // 枚举值数组
|
||
int count; // 枚举值数量
|
||
} choices;
|
||
|
||
// 其他约束标志
|
||
cbool flag_required; // 是否必须
|
||
cbool flag_store_as_count; // 是否存储为计数(如 -vvv 返回3)
|
||
cbool flag_allow_empty; // 是否允许空字符串
|
||
cbool flag_hidden; // 是否隐藏(不显示在帮助)
|
||
cbool flag_takes_multiple; // 是否接受多个值(如 -I dir1 -I dir2)
|
||
cbool flag_parse_complex; // 是否进行复杂解析(如 1K, 2M, 3G)
|
||
};
|
||
|
||
struct scc_argparse_arg {
|
||
scc_argparse_spec_t spec;
|
||
const char *name;
|
||
const char *description;
|
||
};
|
||
|
||
struct scc_argparse_opt {
|
||
scc_argparse_spec_t spec;
|
||
char short_name;
|
||
const char *long_name;
|
||
const char *description;
|
||
};
|
||
|
||
struct scc_argparse_cmd {
|
||
const char *name;
|
||
const char *description;
|
||
cbool *triggered; // 命中该子命令时置 true,可为 NULL
|
||
scc_argparse_arg_vec_t args;
|
||
scc_argparse_opt_vec_t opts;
|
||
scc_argparse_cmd_vec_t subcmds;
|
||
};
|
||
|
||
typedef enum {
|
||
SCC_ARGPARSE_LANG_EN,
|
||
SCC_ARGPARSE_LANG_ZH,
|
||
} scc_argparse_lang_t;
|
||
|
||
#ifndef __SCC_FMT_H__
|
||
#define __SCC_FMT_H__
|
||
|
||
typedef struct {
|
||
char *items;
|
||
usize count;
|
||
usize capacity;
|
||
} scc_str_t;
|
||
|
||
#include <stdarg.h>
|
||
|
||
// 反复 push 同一个填充字符
|
||
static void scc_fmt_pad(scc_str_t *out, char pad, int n) {
|
||
while (n-- > 0)
|
||
scc_vec_push(out, pad);
|
||
}
|
||
|
||
// 十进制/十六进制有符号整数输出,支持宽度、左对齐、零填充
|
||
// 完全自己算,不调用 snprintf/itoa
|
||
static void scc_fmt_int(scc_str_t *out, long long v, unsigned base, int upper, int width,
|
||
int left_align, int zero_pad) {
|
||
char buf[32];
|
||
int n = 0;
|
||
int neg = 0;
|
||
unsigned long long uv;
|
||
|
||
// 处理负数(避免 -LLONG_MIN 溢出)
|
||
if (v < 0) {
|
||
neg = 1;
|
||
uv = (unsigned long long)(-(v + 1)) + 1;
|
||
} else {
|
||
uv = (unsigned long long)v;
|
||
}
|
||
|
||
const char *digits = upper ? "0123456789ABCDEF" : "0123456789abcdef";
|
||
|
||
if (uv == 0) {
|
||
buf[n++] = '0';
|
||
} else {
|
||
while (uv) {
|
||
buf[n++] = digits[uv % base];
|
||
uv /= base;
|
||
}
|
||
}
|
||
|
||
int total = n + (neg ? 1 : 0);
|
||
int pad = width > total ? width - total : 0;
|
||
|
||
// 左侧填充(空格)
|
||
if (!left_align && !zero_pad)
|
||
scc_fmt_pad(out, ' ', pad);
|
||
if (neg)
|
||
scc_vec_push(out, '-');
|
||
// 零填充写在符号位之后
|
||
if (!left_align && zero_pad)
|
||
scc_fmt_pad(out, '0', pad);
|
||
|
||
// buf 中是反序的,倒着 push
|
||
while (n > 0)
|
||
scc_vec_push(out, buf[--n]);
|
||
|
||
// 右侧填充
|
||
if (left_align)
|
||
scc_fmt_pad(out, ' ', pad);
|
||
}
|
||
|
||
// 字符串输出,仅支持宽度和左对齐(字符串默认右对齐没意义,这里按 printf 习惯:
|
||
// 不带 "-" 就左对齐——也就是 "%-20s" 的效果)
|
||
static void scc_fmt_str(scc_str_t *out, const char *s, int width, int left_align) {
|
||
if (!s)
|
||
s = "(null)";
|
||
usize len = scc_strlen(s);
|
||
int pad = width > (int)len ? width - (int)len : 0;
|
||
|
||
if (!left_align)
|
||
scc_fmt_pad(out, ' ', pad);
|
||
scc_vec_push_many(out, s, len);
|
||
if (left_align)
|
||
scc_fmt_pad(out, ' ', pad);
|
||
}
|
||
|
||
/**
|
||
* @brief 按顺序把模板中的 "{}" 用可变参数替换后输出
|
||
* 模板中不含 "{}" 时等同于
|
||
* 参数为 NULL 时输出 "(null)"
|
||
* @warning
|
||
* 模板语法
|
||
*
|
||
* {} 默认字符串
|
||
*
|
||
* {:s} {:d} {:u} {:x} {:X} {:c} 显式类型
|
||
*
|
||
* {:5d} {:<20} {:>20s} {:05d} 宽度 / 对齐 / 零填充
|
||
*
|
||
* {{ }} 转义为字面量 '{' / '}'
|
||
*
|
||
* 支持说明符形式:{[:[<|>][0][宽度][类型]]}
|
||
* 其中类型 ∈ { s, d, u, x, X, c },缺省为 s。
|
||
* @param out 输出字符串
|
||
* @param s2 格式化(非空,以'\0'结尾)
|
||
* @param ... 可变参数列表(const char*列表)
|
||
*/
|
||
void scc_fmt(scc_str_t *out, const char *tpl, ...) {
|
||
if (!tpl)
|
||
return;
|
||
|
||
va_list ap;
|
||
va_start(ap, tpl);
|
||
|
||
for (const char *p = tpl; *p; p++) {
|
||
// 1) 普通字符
|
||
if (*p != '{') {
|
||
scc_vec_push(out, *p);
|
||
continue;
|
||
}
|
||
|
||
// 2) "{{" → 字面量 '{'
|
||
if (p[1] == '{') {
|
||
scc_vec_push(out, '{');
|
||
p++;
|
||
continue;
|
||
}
|
||
|
||
// 3) "{}" → 默认字符串
|
||
if (p[1] == '}') {
|
||
const char *s = va_arg(ap, const char *);
|
||
scc_fmt_str(out, s, 0, 0);
|
||
p++;
|
||
continue;
|
||
}
|
||
|
||
// 4) "{:spec}" → 带说明符
|
||
if (p[1] == ':') {
|
||
p += 2;
|
||
|
||
int left_align = 0;
|
||
int zero_pad = 0;
|
||
int width = 0;
|
||
char type = 's';
|
||
|
||
// 对齐
|
||
if (*p == '<') {
|
||
left_align = 1;
|
||
p++;
|
||
} else if (*p == '>') { /* 右对齐:默认行为 */
|
||
p++;
|
||
}
|
||
|
||
// 零填充
|
||
if (*p == '0') {
|
||
zero_pad = 1;
|
||
p++;
|
||
}
|
||
|
||
// 宽度
|
||
while (*p >= '0' && *p <= '9') {
|
||
width = width * 10 + (*p - '0');
|
||
p++;
|
||
}
|
||
|
||
// 类型
|
||
if (*p && *p != '}') {
|
||
type = *p;
|
||
p++;
|
||
}
|
||
|
||
// 跳到 '}',同时防止未闭合
|
||
while (*p && *p != '}')
|
||
p++;
|
||
if (!*p)
|
||
break; // 模板未闭合,直接结束
|
||
|
||
// 根据类型取参数
|
||
switch (type) {
|
||
case 'd': {
|
||
int v = va_arg(ap, int);
|
||
scc_fmt_int(out, v, 10, 0, width, left_align, zero_pad);
|
||
break;
|
||
}
|
||
case 'u': {
|
||
unsigned v = va_arg(ap, unsigned);
|
||
scc_fmt_int(out, (long long)(unsigned long long)v, 10, 0, width, left_align,
|
||
zero_pad);
|
||
break;
|
||
}
|
||
case 'x':
|
||
case 'X': {
|
||
unsigned v = va_arg(ap, unsigned);
|
||
scc_fmt_int(out, (long long)(unsigned long long)v, 16, type == 'X', width,
|
||
left_align, zero_pad);
|
||
break;
|
||
}
|
||
case 'c': {
|
||
int c = va_arg(ap, int);
|
||
scc_vec_push(out, (char)c);
|
||
break;
|
||
}
|
||
case 's':
|
||
default: {
|
||
const char *s = va_arg(ap, const char *);
|
||
scc_fmt_str(out, s, width, left_align);
|
||
break;
|
||
}
|
||
}
|
||
continue;
|
||
}
|
||
|
||
// 5) '{' 后面是意外字符,当字面量处理
|
||
scc_vec_push(out, '{');
|
||
}
|
||
|
||
va_end(ap);
|
||
}
|
||
#endif // __SCC_FMT_H__
|
||
|
||
typedef struct {
|
||
const char *prog_name;
|
||
const char *version;
|
||
const char *description;
|
||
const char *epilog;
|
||
scc_str_t out; // 用于打印帮助和错误信息的缓冲区
|
||
scc_argparse_cmd_t root_cmd;
|
||
scc_argparse_lang_t lang;
|
||
char short_prefix; // 短选项前缀,默认 '-'
|
||
const char *long_prefix; // 长选项前缀,默认 "--"
|
||
const char *separator; // 分隔符,默认 "--";nullptr = 不识别
|
||
cbool need_help;
|
||
cbool need_version;
|
||
cbool need_debug;
|
||
cbool need_error_add_help;
|
||
cbool need_error_add_usage;
|
||
} scc_argparse_t;
|
||
|
||
typedef struct {
|
||
scc_optparse_opt_t *items;
|
||
usize count;
|
||
usize capacity;
|
||
} scc_optparse_opt_vec_t;
|
||
|
||
typedef struct {
|
||
scc_argparse_cmd_t *current_cmd; // 当前正在解析的命令
|
||
scc_optparse_t optparse; // 底层解析器
|
||
scc_optparse_opt_vec_t opts; // 当前命令的选项列表
|
||
scc_optparse_result_t result; // 底层解析结果
|
||
const void *err_ctx; // 错误上下文(期待的参数或者当前解析的参数)
|
||
int positional_index; // 当前处理的位置参数索引
|
||
cbool parsing_done; // 是否已完成解析
|
||
} scc_argparse_context_t;
|
||
|
||
void scc_argparse_init(scc_argparse_t *parser, const char *program_name, const char *description);
|
||
scc_argparse_cmd_t *scc_argparse_get_root(scc_argparse_t *parser);
|
||
void scc_argparse_drop(scc_argparse_t *parser);
|
||
int scc_argparse_parse(scc_argparse_t *parser, int argc, const char **argv);
|
||
|
||
// 选项前缀与分隔符:nullptr = 关闭该项(例如 DOS 风格用 short='/', long="/", separator=nullptr)。
|
||
void scc_argparse_set_prefix(scc_argparse_t *parser, char short_prefix, const char *long_prefix,
|
||
const char *separator);
|
||
|
||
void scc_argparse_cmd_init(scc_argparse_cmd_t *cmd, const char *name, const char *description);
|
||
void scc_argparse_cmd_drop(scc_argparse_cmd_t *cmd);
|
||
|
||
static inline void scc_argparse_cmd_set_triggered(scc_argparse_cmd_t *cmd, cbool *store) {
|
||
cmd->triggered = store;
|
||
}
|
||
void scc_argparse_cmd_add_arg(scc_argparse_cmd_t *cmd, const scc_argparse_arg_t *arg);
|
||
void scc_argparse_cmd_add_opt(scc_argparse_cmd_t *cmd, const scc_argparse_opt_t *opt);
|
||
/**
|
||
* @warning 浅拷贝:subcmd->args / opts / subcmds 的底层 items 所有权转移给 cmd。
|
||
* 调用 add_subcmd 之后,不要再对 subcmd 调用 scc_argparse_cmd_drop,
|
||
* 也不要再修改 subcmd 及其 vector。parser 销毁时会递归释放。
|
||
*/
|
||
void scc_argparse_cmd_add_subcmd(scc_argparse_cmd_t *cmd, const scc_argparse_cmd_t *subcmd);
|
||
|
||
void scc_argparse_print_help(scc_argparse_t *parser, scc_argparse_cmd_t *cmd);
|
||
void scc_argparse_print_error(scc_argparse_context_t *ctx, scc_argparse_t *parser,
|
||
scc_argparse_err_t err);
|
||
|
||
static inline void scc_argparse_spec_init(scc_argparse_spec_t *spec) {
|
||
spec->value_type = SCC_ARGPARSE_VAL_TYPE_STRING;
|
||
spec->raw_value = nullptr;
|
||
spec->store.ptr_store = nullptr;
|
||
|
||
spec->choices.count = 0;
|
||
spec->choices.values = nullptr;
|
||
|
||
spec->flag_required = false;
|
||
spec->flag_store_as_count = false;
|
||
spec->flag_allow_empty = false;
|
||
spec->flag_hidden = false;
|
||
spec->flag_takes_multiple = false;
|
||
spec->flag_parse_complex = false;
|
||
}
|
||
|
||
static inline void scc_argparse_opt_init(scc_argparse_opt_t *opt, char short_name,
|
||
const char *long_name, const char *desc) {
|
||
opt->short_name = short_name;
|
||
opt->long_name = long_name;
|
||
opt->description = desc;
|
||
scc_argparse_spec_init(&opt->spec);
|
||
}
|
||
|
||
static inline void scc_argparse_arg_init(scc_argparse_arg_t *arg, const char *name,
|
||
const char *desc) {
|
||
arg->name = name;
|
||
arg->description = desc;
|
||
scc_argparse_spec_init(&arg->spec);
|
||
}
|
||
|
||
static inline void scc_argparse_spec_setup_bool(scc_argparse_spec_t *spec, cbool *store) {
|
||
spec->value_type = SCC_ARGPARSE_VAL_TYPE_BOOL;
|
||
spec->store.bool_store = store;
|
||
}
|
||
|
||
static inline void scc_argparse_spec_setup_count(scc_argparse_spec_t *spec, int *store) {
|
||
spec->value_type = SCC_ARGPARSE_VAL_TYPE_COUNT;
|
||
spec->flag_store_as_count = true; // 自动设为计数模式
|
||
spec->store.int_store = store;
|
||
}
|
||
|
||
static inline void scc_argparse_spec_setup_string(scc_argparse_spec_t *spec, const char **store) {
|
||
spec->value_type = SCC_ARGPARSE_VAL_TYPE_STRING;
|
||
spec->store.str_store = store;
|
||
}
|
||
|
||
static inline void scc_argparse_spec_setup_int(scc_argparse_spec_t *spec, int *store) {
|
||
spec->value_type = SCC_ARGPARSE_VAL_TYPE_INT;
|
||
spec->store.int_store = store;
|
||
}
|
||
|
||
static inline void scc_argparse_spec_setup_float(scc_argparse_spec_t *spec, float *store) {
|
||
spec->value_type = SCC_ARGPARSE_VAL_TYPE_FLOAT;
|
||
spec->store.float_store = store;
|
||
}
|
||
|
||
static inline void scc_argparse_spec_setup_choices(scc_argparse_spec_t *spec, const char **values,
|
||
int count, int *store) {
|
||
spec->value_type = SCC_ARGPARSE_VAL_TYPE_ENUM;
|
||
spec->choices.values = values;
|
||
spec->choices.count = count;
|
||
spec->store.int_store = store;
|
||
}
|
||
|
||
// 添加设置列表的辅助函数(内联)
|
||
static inline void scc_argparse_spec_setup_list(scc_argparse_spec_t *spec,
|
||
scc_argparse_list_t *vec) {
|
||
spec->value_type = SCC_ARGPARSE_VAL_TYPE_LIST;
|
||
spec->store.vec_store = vec;
|
||
spec->flag_takes_multiple = false;
|
||
}
|
||
|
||
#define SCC_ARGPARSE_MACRO_SETTER(attr) \
|
||
static inline void scc_argparse_spec_set_##attr(scc_argparse_spec_t *spec, cbool flag) { \
|
||
spec->flag_##attr = flag; \
|
||
}
|
||
SCC_ARGPARSE_MACRO_SETTER(required)
|
||
SCC_ARGPARSE_MACRO_SETTER(allow_empty)
|
||
SCC_ARGPARSE_MACRO_SETTER(hidden)
|
||
SCC_ARGPARSE_MACRO_SETTER(takes_multiple)
|
||
SCC_ARGPARSE_MACRO_SETTER(parse_complex)
|
||
|
||
#ifndef SCC_UNSTRIP_PREFIX
|
||
// TODO
|
||
#endif // SCC_UNSTRIP_PREFIX
|
||
|
||
#ifdef SCC_ARGPARSE_IMPLEMENTATION
|
||
void scc_argparse_init(scc_argparse_t *parser, const char *program_name, const char *description) {
|
||
parser->prog_name = program_name;
|
||
parser->version = "0.1.0";
|
||
parser->description = description;
|
||
parser->epilog = nullptr;
|
||
|
||
parser->out = (scc_str_t){0};
|
||
|
||
parser->lang = SCC_ARGPARSE_LANG_EN;
|
||
parser->short_prefix = '-';
|
||
parser->long_prefix = "--";
|
||
parser->separator = "--";
|
||
parser->need_help = true;
|
||
parser->need_version = true;
|
||
parser->need_debug = false;
|
||
parser->need_error_add_help = false;
|
||
parser->need_error_add_usage = true;
|
||
scc_argparse_cmd_init(&parser->root_cmd, parser->prog_name, parser->description);
|
||
}
|
||
|
||
scc_argparse_cmd_t *scc_argparse_get_root(scc_argparse_t *parser) { return &parser->root_cmd; }
|
||
|
||
void scc_argparse_drop(scc_argparse_t *parser) {
|
||
scc_vec_free(parser->out);
|
||
scc_argparse_cmd_drop(&parser->root_cmd);
|
||
}
|
||
|
||
void scc_argparse_set_prefix(scc_argparse_t *parser, char short_prefix, const char *long_prefix,
|
||
const char *separator) {
|
||
parser->short_prefix = short_prefix;
|
||
parser->long_prefix = long_prefix;
|
||
parser->separator = separator;
|
||
}
|
||
|
||
static inline scc_argparse_cmd_t *is_subcommand(scc_argparse_cmd_t *cmd, const char *name) {
|
||
if (!cmd->subcmds.count) {
|
||
return nullptr;
|
||
}
|
||
for (usize i = 0; i < cmd->subcmds.count; i++) {
|
||
scc_argparse_cmd_t *subcmd = &cmd->subcmds.items[i];
|
||
if (scc_strcmp(subcmd->name, name) == 0) {
|
||
return subcmd;
|
||
}
|
||
}
|
||
return nullptr;
|
||
}
|
||
|
||
static inline void prepare_cmd(scc_optparse_t *optparse, scc_optparse_opt_vec_t *opts,
|
||
scc_argparse_cmd_t *cmd) {
|
||
scc_vec_free(*opts);
|
||
scc_vec_init(*opts);
|
||
for (usize i = 0; i < cmd->opts.count; i++) {
|
||
scc_argparse_opt_t *opt = &cmd->opts.items[i];
|
||
int min_args = 0;
|
||
int max_args = 0;
|
||
|
||
// 根据选项类型推断 min_args 和 max_args
|
||
switch (opt->spec.value_type) {
|
||
case SCC_ARGPARSE_VAL_TYPE_STRING:
|
||
case SCC_ARGPARSE_VAL_TYPE_INT:
|
||
case SCC_ARGPARSE_VAL_TYPE_FLOAT:
|
||
min_args = 1;
|
||
max_args = 1;
|
||
break;
|
||
case SCC_ARGPARSE_VAL_TYPE_BOOL:
|
||
min_args = 0;
|
||
max_args = 0;
|
||
break;
|
||
case SCC_ARGPARSE_VAL_TYPE_COUNT:
|
||
min_args = 0;
|
||
max_args = 0;
|
||
break;
|
||
case SCC_ARGPARSE_VAL_TYPE_LIST:
|
||
min_args = 1;
|
||
max_args = opt->spec.flag_takes_multiple ? 65535 : 1;
|
||
break;
|
||
case SCC_ARGPARSE_VAL_TYPE_ENUM:
|
||
min_args = 1;
|
||
max_args = 1;
|
||
break;
|
||
default:
|
||
min_args = 0;
|
||
max_args = 0;
|
||
break;
|
||
}
|
||
|
||
scc_vec_push(opts, ((scc_optparse_opt_t){
|
||
.prefix = optparse->short_prefix,
|
||
.short_name = opt->short_name,
|
||
.long_name = opt->long_name,
|
||
.min_args = min_args,
|
||
.max_args = max_args,
|
||
.user_data = opt,
|
||
}));
|
||
}
|
||
scc_vec_push(opts, (scc_optparse_opt_t)SCC_OPTPARSE_OPT_END());
|
||
scc_optparse_swap_opts(optparse, opts->items);
|
||
}
|
||
|
||
static int scc_argparse_cmd_has_long_opt(const scc_argparse_cmd_t *cmd, const char *long_name) {
|
||
for (usize i = 0; i < cmd->opts.count; i++) {
|
||
const char *n = cmd->opts.items[i].long_name;
|
||
if (n && scc_strcmp(n, long_name) == 0)
|
||
return 1;
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
static void push_help(scc_argparse_cmd_t *cmd) {
|
||
if (cmd == nullptr) {
|
||
return;
|
||
}
|
||
|
||
if (!scc_argparse_cmd_has_long_opt(cmd, "help")) {
|
||
scc_vec_push(&cmd->opts, ((scc_argparse_opt_t){
|
||
.short_name = 'h',
|
||
.long_name = "help",
|
||
.description = 0,
|
||
.spec.value_type = SCC_ARGPARSE_VAL_TYPE_BOOL,
|
||
}));
|
||
}
|
||
for (usize i = 0; i < cmd->subcmds.count; i++) {
|
||
push_help(&cmd->subcmds.items[i]);
|
||
}
|
||
}
|
||
|
||
static void push_version(scc_argparse_cmd_t *cmd) {
|
||
if (cmd == nullptr)
|
||
return;
|
||
|
||
if (!scc_argparse_cmd_has_long_opt(cmd, "version")) {
|
||
scc_vec_push(&cmd->opts, ((scc_argparse_opt_t){
|
||
.short_name = 0,
|
||
.long_name = "version",
|
||
.description = 0,
|
||
.spec.value_type = SCC_ARGPARSE_VAL_TYPE_BOOL,
|
||
}));
|
||
}
|
||
}
|
||
|
||
static void init_context(scc_argparse_context_t *ctx, scc_argparse_t *parser, int argc,
|
||
const char **argv) {
|
||
ctx->current_cmd = scc_argparse_get_root(parser);
|
||
if (parser->need_help) {
|
||
push_help(ctx->current_cmd);
|
||
}
|
||
if (parser->need_version) {
|
||
push_version(ctx->current_cmd);
|
||
}
|
||
scc_optparse_init(&ctx->optparse, argc, argv);
|
||
ctx->optparse.short_prefix = parser->short_prefix;
|
||
ctx->optparse.long_prefix = parser->long_prefix;
|
||
ctx->optparse.separator = parser->separator;
|
||
scc_vec_init(ctx->opts);
|
||
prepare_cmd(&ctx->optparse, &ctx->opts, ctx->current_cmd);
|
||
ctx->positional_index = 0;
|
||
ctx->parsing_done = false;
|
||
}
|
||
|
||
static int transite_error(scc_argparse_context_t *ctx) {
|
||
scc_argparse_err_t error = SCC_ARGPARSE_ERR_NONE;
|
||
switch (ctx->result.error) {
|
||
case SCC_OPT_ERROR_NOT_FOUND_SHORT_ARG:
|
||
case SCC_OPT_ERROR_NOT_FOUND_LONG_ARG:
|
||
error = SCC_ARGPARSE_ERR_UNKNOWN_ARG;
|
||
break;
|
||
case SCC_OPT_ERROR_NOT_ENOUGH_ARGS:
|
||
error = SCC_ARGPARSE_ERR_MISSING_VALUE;
|
||
break;
|
||
case SCC_OPT_ERROR_TOO_MANY_ARGS:
|
||
error = SCC_ARGPARSE_ERR_INVALID_ARG;
|
||
break;
|
||
default:
|
||
error = SCC_ARGPARSE_ERR_UNKNOWN_ERR;
|
||
break;
|
||
}
|
||
return error;
|
||
}
|
||
|
||
static int check_choices(const scc_argparse_spec_t *spec, const char *value, int *out_index) {
|
||
if (!spec->choices.values || spec->choices.count == 0) {
|
||
return SCC_ARGPARSE_ERR_NONE;
|
||
}
|
||
|
||
if (value == nullptr) {
|
||
return SCC_ARGPARSE_ERR_MISSING_VALUE;
|
||
}
|
||
if (out_index)
|
||
*out_index = -1;
|
||
|
||
for (int i = 0; i < spec->choices.count; i += 1) {
|
||
if (scc_strcmp(value, spec->choices.values[i]) == 0) {
|
||
if (out_index)
|
||
*out_index = i;
|
||
return SCC_ARGPARSE_ERR_NONE;
|
||
}
|
||
}
|
||
return SCC_ARGPARSE_ERR_INVALID_VALUE;
|
||
}
|
||
|
||
static int scc_argparse_parse_int(const char *s, usize *out) {
|
||
if (!s || !*s)
|
||
return SCC_ARGPARSE_ERR_MISSING_VALUE;
|
||
char *end = NULL;
|
||
// TODO 手动解析整数,避免使用 strtoull
|
||
usize v = strtoull(s, &end, 10);
|
||
if (end == s || *end != '\0')
|
||
return SCC_ARGPARSE_ERR_INVALID_VALUE;
|
||
*out = v;
|
||
return SCC_ARGPARSE_ERR_NONE;
|
||
}
|
||
|
||
static int scc_argparse_parse_float(const char *s, float *out) {
|
||
if (!s || !*s)
|
||
return SCC_ARGPARSE_ERR_MISSING_VALUE;
|
||
char *end = NULL;
|
||
// TODO 手动解析浮点数,避免使用 strtof
|
||
float v = strtof(s, &end);
|
||
if (end == s || *end != '\0')
|
||
return SCC_ARGPARSE_ERR_INVALID_VALUE;
|
||
*out = v;
|
||
return SCC_ARGPARSE_ERR_NONE;
|
||
}
|
||
|
||
static int scc_argparse_store_value(scc_argparse_spec_t *spec, const char *value) {
|
||
if (!spec)
|
||
return SCC_ARGPARSE_ERR_INVALID_ARG;
|
||
if (!value)
|
||
return SCC_ARGPARSE_ERR_MISSING_VALUE;
|
||
|
||
if (value[0] == '\0' && !spec->flag_allow_empty &&
|
||
spec->value_type != SCC_ARGPARSE_VAL_TYPE_LIST) {
|
||
return SCC_ARGPARSE_ERR_MISSING_VALUE;
|
||
}
|
||
|
||
spec->raw_value = value;
|
||
|
||
switch (spec->value_type) {
|
||
case SCC_ARGPARSE_VAL_TYPE_STRING:
|
||
if (spec->store.str_store)
|
||
*spec->store.str_store = value;
|
||
return SCC_ARGPARSE_ERR_NONE;
|
||
|
||
case SCC_ARGPARSE_VAL_TYPE_INT:
|
||
if (!spec->store.int_store)
|
||
return SCC_ARGPARSE_ERR_INVALID_ARG;
|
||
return scc_argparse_parse_int(value, (void *)spec->store.int_store);
|
||
|
||
case SCC_ARGPARSE_VAL_TYPE_FLOAT:
|
||
if (!spec->store.float_store)
|
||
return SCC_ARGPARSE_ERR_INVALID_ARG;
|
||
return scc_argparse_parse_float(value, spec->store.float_store);
|
||
|
||
case SCC_ARGPARSE_VAL_TYPE_ENUM: {
|
||
int idx = -1;
|
||
int err = check_choices(spec, value, &idx);
|
||
if (err != SCC_ARGPARSE_ERR_NONE)
|
||
return err;
|
||
if (spec->store.int_store)
|
||
*spec->store.int_store = idx;
|
||
return SCC_ARGPARSE_ERR_NONE;
|
||
}
|
||
|
||
case SCC_ARGPARSE_VAL_TYPE_LIST:
|
||
if (!spec->store.vec_store)
|
||
return SCC_ARGPARSE_ERR_INVALID_ARG;
|
||
scc_vec_push(spec->store.vec_store, value);
|
||
return SCC_ARGPARSE_ERR_NONE;
|
||
|
||
default:
|
||
return SCC_ARGPARSE_ERR_INVALID_ARG;
|
||
}
|
||
}
|
||
|
||
static int validate_and_cleanup(scc_argparse_context_t *ctx, scc_argparse_t *parser, int errcode) {
|
||
if (errcode != SCC_ARGPARSE_ERR_NONE) {
|
||
goto END;
|
||
}
|
||
cbool provided;
|
||
// 检查必需的位置参数
|
||
for (usize i = 0; i < ctx->current_cmd->args.count; i++) {
|
||
scc_argparse_arg_t *arg = &ctx->current_cmd->args.items[i];
|
||
if (arg->spec.flag_required) {
|
||
provided = false;
|
||
if (arg->spec.value_type == SCC_ARGPARSE_VAL_TYPE_LIST) {
|
||
provided = arg->spec.store.vec_store && arg->spec.store.vec_store->count > 0;
|
||
} else {
|
||
provided = arg->spec.raw_value != nullptr;
|
||
}
|
||
|
||
if (!provided) {
|
||
errcode = SCC_ARGPARSE_ERR_MISSING_ARG;
|
||
ctx->err_ctx = arg->name;
|
||
goto END;
|
||
}
|
||
}
|
||
}
|
||
for (usize i = 0; i < ctx->current_cmd->opts.count; i++) {
|
||
scc_argparse_opt_t *opt = &ctx->current_cmd->opts.items[i];
|
||
if (opt->spec.flag_required) {
|
||
provided = false;
|
||
|
||
if (opt->spec.flag_store_as_count ||
|
||
opt->spec.value_type == SCC_ARGPARSE_VAL_TYPE_COUNT) {
|
||
provided = opt->spec.store.int_store && *opt->spec.store.int_store > 0;
|
||
} else if (opt->spec.value_type == SCC_ARGPARSE_VAL_TYPE_BOOL) {
|
||
provided = opt->spec.store.bool_store && *opt->spec.store.bool_store;
|
||
} else if (opt->spec.value_type == SCC_ARGPARSE_VAL_TYPE_LIST) {
|
||
provided = opt->spec.store.vec_store && opt->spec.store.vec_store->count > 0;
|
||
} else {
|
||
provided = opt->spec.raw_value != nullptr;
|
||
}
|
||
|
||
if (!provided) {
|
||
errcode = SCC_ARGPARSE_ERR_MISSING_ARG;
|
||
ctx->err_ctx = opt->long_name ? opt->long_name : "option";
|
||
goto END;
|
||
}
|
||
}
|
||
}
|
||
|
||
END:
|
||
if (errcode != SCC_ARGPARSE_ERR_NONE) {
|
||
scc_argparse_print_error(ctx, parser, errcode);
|
||
}
|
||
scc_vec_free(ctx->opts);
|
||
scc_optparse_drop(&ctx->optparse);
|
||
return errcode;
|
||
}
|
||
|
||
static int handle_option(scc_argparse_context_t *ctx, scc_argparse_t *parser) {
|
||
scc_argparse_opt_t *opt = (scc_argparse_opt_t *)ctx->result.opt->user_data;
|
||
|
||
ctx->err_ctx = opt->long_name ? opt->long_name : "option";
|
||
|
||
if (parser->need_help && opt->long_name && scc_strcmp(opt->long_name, "help") == 0) {
|
||
scc_argparse_print_help(parser, ctx->current_cmd);
|
||
ctx->parsing_done = true;
|
||
return SCC_ARGPARSE_ERR_PNT_DEFAULT;
|
||
}
|
||
|
||
if (parser->need_version && opt->long_name && scc_strcmp(opt->long_name, "version") == 0) {
|
||
scc_fmt(&parser->out, "{:s} {:s}\n", parser->prog_name, parser->version);
|
||
ctx->parsing_done = true;
|
||
return SCC_ARGPARSE_ERR_PNT_DEFAULT;
|
||
}
|
||
|
||
if (opt->spec.flag_store_as_count || opt->spec.value_type == SCC_ARGPARSE_VAL_TYPE_COUNT) {
|
||
if (opt->spec.store.int_store)
|
||
(*opt->spec.store.int_store)++;
|
||
return SCC_ARGPARSE_ERR_NONE;
|
||
}
|
||
|
||
if (opt->spec.value_type == SCC_ARGPARSE_VAL_TYPE_BOOL) {
|
||
if (opt->spec.store.bool_store)
|
||
*opt->spec.store.bool_store = true;
|
||
return SCC_ARGPARSE_ERR_NONE;
|
||
}
|
||
|
||
if (!ctx->result.value) {
|
||
return SCC_ARGPARSE_ERR_MISSING_VALUE;
|
||
}
|
||
|
||
return scc_argparse_store_value(&opt->spec, ctx->result.value);
|
||
}
|
||
|
||
static int handle_positional_arg(scc_argparse_context_t *ctx, scc_argparse_t *parser) {
|
||
(void)parser;
|
||
|
||
scc_argparse_cmd_t *subcmd = is_subcommand(ctx->current_cmd, ctx->result.value);
|
||
if (subcmd != nullptr) {
|
||
ctx->current_cmd = subcmd;
|
||
if (subcmd->triggered)
|
||
*subcmd->triggered = true;
|
||
ctx->positional_index = 0;
|
||
prepare_cmd(&ctx->optparse, &ctx->opts, ctx->current_cmd);
|
||
return SCC_ARGPARSE_ERR_NONE;
|
||
}
|
||
|
||
if (ctx->positional_index < (int)ctx->current_cmd->args.count) {
|
||
scc_argparse_arg_t *arg = &ctx->current_cmd->args.items[ctx->positional_index];
|
||
|
||
int err = scc_argparse_store_value(&arg->spec, ctx->result.value);
|
||
if (err != SCC_ARGPARSE_ERR_NONE) {
|
||
ctx->err_ctx = arg->name;
|
||
return err;
|
||
}
|
||
|
||
if (arg->spec.value_type != SCC_ARGPARSE_VAL_TYPE_LIST) {
|
||
ctx->positional_index++;
|
||
}
|
||
} else {
|
||
ctx->parsing_done = true;
|
||
return SCC_ARGPARSE_ERR_UNKNOWN_ARG;
|
||
}
|
||
|
||
return SCC_ARGPARSE_ERR_NONE;
|
||
}
|
||
|
||
int scc_argparse_parse(scc_argparse_t *parser, int argc, const char **argv) {
|
||
scc_argparse_context_t ctx = {0};
|
||
init_context(&ctx, parser, argc, argv); // 初始化上下文
|
||
int errcode = SCC_ARGPARSE_ERR_NONE;
|
||
|
||
while (!ctx.parsing_done && errcode == SCC_ARGPARSE_ERR_NONE &&
|
||
scc_optparse_parse(&ctx.optparse, &ctx.result)) {
|
||
if (parser->need_debug) {
|
||
scc_fmt(&parser->out, "debug:[{:c}:{:s}:{:d}] {:s}\n",
|
||
ctx.result.opt ? ctx.result.opt->short_name : '-',
|
||
ctx.result.opt ? ctx.result.opt->long_name : "--", ctx.result.error,
|
||
ctx.result.value ? ctx.result.value : "<nullptr>");
|
||
}
|
||
|
||
if (ctx.result.error == SCC_OPT_ERROR_SEPARATOR) {
|
||
continue; // 分隔符不是失败:argparse 的策略是吞掉它本身
|
||
}
|
||
|
||
if (ctx.result.error) {
|
||
errcode = transite_error(&ctx);
|
||
continue;
|
||
}
|
||
|
||
if (ctx.result.opt != nullptr) {
|
||
errcode = handle_option(&ctx, parser);
|
||
} else if (ctx.result.value != nullptr) {
|
||
errcode = handle_positional_arg(&ctx, parser);
|
||
} else {
|
||
errcode = SCC_ARGPARSE_ERR_UNREACHABLE; // 不应到达此处
|
||
}
|
||
}
|
||
|
||
return validate_and_cleanup(&ctx, parser, errcode);
|
||
}
|
||
|
||
void scc_argparse_cmd_init(scc_argparse_cmd_t *cmd, const char *name, const char *description) {
|
||
cmd->name = name ? name : "cmd_name";
|
||
cmd->description = description ? description : "cmd_description";
|
||
cmd->triggered = nullptr;
|
||
scc_vec_init(cmd->args);
|
||
scc_vec_init(cmd->opts);
|
||
scc_vec_init(cmd->subcmds);
|
||
}
|
||
|
||
void scc_argparse_cmd_drop(scc_argparse_cmd_t *cmd) {
|
||
scc_vec_free(cmd->args);
|
||
scc_vec_free(cmd->opts);
|
||
for (usize i = 0; i < cmd->subcmds.count; i++) {
|
||
scc_argparse_cmd_drop(&cmd->subcmds.items[i]);
|
||
}
|
||
scc_vec_free(cmd->subcmds);
|
||
}
|
||
|
||
void scc_argparse_cmd_add_arg(scc_argparse_cmd_t *cmd, const scc_argparse_arg_t *arg) {
|
||
scc_vec_push(&cmd->args, *arg);
|
||
}
|
||
|
||
void scc_argparse_cmd_add_opt(scc_argparse_cmd_t *cmd, const scc_argparse_opt_t *opt) {
|
||
scc_vec_push(&cmd->opts, *opt);
|
||
}
|
||
|
||
void scc_argparse_cmd_add_subcmd(scc_argparse_cmd_t *cmd, const scc_argparse_cmd_t *subcmd) {
|
||
scc_vec_push(&cmd->subcmds, *subcmd);
|
||
}
|
||
|
||
// TODO: maybe add a macro to enable/disable the help message printing implementation
|
||
#define SCC_ARGPARSE_PRINT_HELP_IMPLEMENTATION
|
||
|
||
#endif // SCC_ARGPARSE_IMPLEMENTATION
|
||
|
||
#ifdef SCC_ARGPARSE_PRINT_HELP_IMPLEMENTATION
|
||
|
||
// 帮助信息处理函数
|
||
enum {
|
||
ARGPARSE_USAGE,
|
||
ARGPARSE_OPTION,
|
||
ARGPARSE_COMMAND,
|
||
ARGPARSE_ARGUMENT,
|
||
|
||
ARGPARSE_SHOW_ARG,
|
||
ARGPARSE_SHOW_OPT,
|
||
ARGPARSE_SHOW_CMD,
|
||
ARGPARSE_SHOW_HELP_MSG,
|
||
|
||
ARGPRASE_USING_HELP_HINT,
|
||
ARGPARSE_UNKNOWN_ARGUMENT,
|
||
ARGPARSE_INVALID_VALUE_FOR_OPTION,
|
||
ARGPARSE_OPTION_MISSING_VALUE,
|
||
ARGPARSE_DID_YOU_MEAN,
|
||
};
|
||
|
||
static const char *fmt_en[] = {
|
||
[ARGPARSE_USAGE] = "Usage: {:s}",
|
||
[ARGPARSE_OPTION] = " [Options]",
|
||
[ARGPARSE_COMMAND] = " [Commands]",
|
||
|
||
[ARGPARSE_SHOW_ARG] = "Arguments:\n",
|
||
[ARGPARSE_SHOW_OPT] = "Options:\n",
|
||
[ARGPARSE_SHOW_CMD] = "Commands:\n",
|
||
[ARGPARSE_SHOW_HELP_MSG] = "Show this help message and exit",
|
||
|
||
[ARGPRASE_USING_HELP_HINT] = "Using '-h' or '--help' to get more information\n",
|
||
[ARGPARSE_UNKNOWN_ARGUMENT] = "Unknown argument '{:s}'\n",
|
||
[ARGPARSE_INVALID_VALUE_FOR_OPTION] = "Invalid value for option '{:s}'\n",
|
||
[ARGPARSE_OPTION_MISSING_VALUE] = "Option '{:s}' missing value\n",
|
||
[ARGPARSE_DID_YOU_MEAN] = "Did you mean: '{:s}'?\n",
|
||
};
|
||
|
||
static const char *fmt_zh[] = {
|
||
[ARGPARSE_USAGE] = "用法: {:s}",
|
||
[ARGPARSE_OPTION] = " [选项]",
|
||
[ARGPARSE_COMMAND] = " [命令]",
|
||
|
||
[ARGPARSE_SHOW_ARG] = "参数:\n",
|
||
[ARGPARSE_SHOW_OPT] = "选项:\n",
|
||
[ARGPARSE_SHOW_CMD] = "命令:\n",
|
||
[ARGPARSE_SHOW_HELP_MSG] = "显示帮助信息并退出",
|
||
|
||
[ARGPRASE_USING_HELP_HINT] = "使用 '-h' 或者 '--help' 获取更多信息\n",
|
||
[ARGPARSE_UNKNOWN_ARGUMENT] = "未知的参数 '{:s}'\n",
|
||
[ARGPARSE_INVALID_VALUE_FOR_OPTION] = "无效的选项值 '{:s}'\n",
|
||
[ARGPARSE_OPTION_MISSING_VALUE] = "选项 '{:s}' 缺少值\n",
|
||
[ARGPARSE_DID_YOU_MEAN] = "您是不是想要输入: '{:s}'?\n",
|
||
};
|
||
|
||
/**
|
||
* @brief 计算两个字符串的编辑距离(Levenshtein距离)
|
||
* @param s1 字符串1(非空,以'\0'结尾)
|
||
* @param s2 字符串2(非空,以'\0'结尾)
|
||
* @return 编辑距离,内存分配失败返回 -1
|
||
*/
|
||
static int scc_levenshtein(const char *s1, const char *s2) {
|
||
usize len1 = scc_strlen(s1);
|
||
usize len2 = scc_strlen(s2);
|
||
|
||
// 保证 len1 >= len2 以减少内存占用
|
||
if (len1 < len2) {
|
||
const char *tmp = s1;
|
||
s1 = s2;
|
||
s2 = tmp;
|
||
usize tlen = len1;
|
||
len1 = len2;
|
||
len2 = tlen;
|
||
}
|
||
|
||
// 分配滚动数组(只需 len2+1 个 int)
|
||
int *dp = (int *)scc_realloc(nullptr, sizeof(int) * (len2 + 1));
|
||
if (!dp) {
|
||
return -1;
|
||
}
|
||
|
||
// 初始化第0行
|
||
for (usize j = 0; j <= len2; ++j) {
|
||
dp[j] = (int)j;
|
||
}
|
||
|
||
for (usize i = 1; i <= len1; ++i) {
|
||
int prev = dp[0];
|
||
dp[0] = (int)i;
|
||
for (usize j = 1; j <= len2; ++j) {
|
||
int temp = dp[j];
|
||
int cost = (s1[i - 1] == s2[j - 1]) ? 0 : 1;
|
||
#define scc_min(a, b) ((a) < (b) ? (a) : (b))
|
||
dp[j] = scc_min(scc_min(dp[j] + 1, dp[j - 1] + 1), prev + cost);
|
||
#undef scc_min
|
||
prev = temp;
|
||
}
|
||
}
|
||
|
||
int dist = dp[len2];
|
||
scc_free(dp);
|
||
return dist;
|
||
}
|
||
|
||
static void scc_print_usage(scc_argparse_t *parser, scc_argparse_cmd_t *cmd, scc_str_t *out) {
|
||
const char **lines = (parser->lang == SCC_ARGPARSE_LANG_ZH) ? fmt_zh : fmt_en;
|
||
|
||
scc_fmt(out, lines[ARGPARSE_USAGE], cmd->name ? cmd->name : parser->prog_name);
|
||
if (cmd->opts.count > 0) {
|
||
scc_fmt(out, lines[ARGPARSE_OPTION]);
|
||
}
|
||
for (usize i = 0; i < cmd->args.count; i++) {
|
||
scc_argparse_arg_t *arg = &cmd->args.items[i];
|
||
scc_fmt(out, arg->spec.flag_required ? " <{:s}>" : " [{:s}]", arg->name);
|
||
}
|
||
if (cmd->subcmds.count > 0) {
|
||
scc_fmt(out, lines[ARGPARSE_COMMAND]);
|
||
}
|
||
scc_fmt(out, "\n\n");
|
||
}
|
||
|
||
void scc_argparse_print_help(scc_argparse_t *parser, scc_argparse_cmd_t *cmd) {
|
||
const char **lines = (parser->lang == SCC_ARGPARSE_LANG_ZH) ? fmt_zh : fmt_en;
|
||
scc_str_t *out = &parser->out;
|
||
scc_print_usage(parser, cmd, out);
|
||
|
||
if (cmd->description) {
|
||
scc_fmt(out, "{:s}\n\n", cmd->description);
|
||
}
|
||
|
||
if (cmd->args.count > 0) {
|
||
scc_fmt(out, lines[ARGPARSE_SHOW_ARG]);
|
||
for (usize i = 0; i < cmd->args.count; i++) {
|
||
scc_argparse_arg_t *arg = &cmd->args.items[i];
|
||
scc_fmt(out, " {:<20s} {:s}", arg->name, arg->description ? arg->description : "");
|
||
// if (!arg->spec.required && arg->spec.flags.has_default)
|
||
// scc_fmt(out, " (default: %s)", arg->spec.default_value);
|
||
scc_fmt(out, "\n");
|
||
}
|
||
scc_fmt(out, "\n");
|
||
}
|
||
|
||
if (cmd->opts.count > 0) {
|
||
scc_fmt(out, lines[ARGPARSE_SHOW_OPT]);
|
||
for (usize i = 0; i < cmd->opts.count; i++) {
|
||
scc_argparse_opt_t *opt = &cmd->opts.items[i];
|
||
if (opt->spec.flag_hidden)
|
||
continue;
|
||
if (opt->short_name == 'h')
|
||
opt->description = lines[ARGPARSE_SHOW_HELP_MSG];
|
||
scc_str_t buf = {0};
|
||
if (opt->short_name) {
|
||
scc_vec_push(&buf, '-');
|
||
scc_vec_push(&buf, opt->short_name);
|
||
if (opt->long_name) {
|
||
scc_vec_push(&buf, ',');
|
||
scc_vec_push(&buf, ' ');
|
||
}
|
||
}
|
||
if (opt->long_name) {
|
||
scc_vec_push(&buf, '-');
|
||
scc_vec_push(&buf, '-');
|
||
for (const char *p = opt->long_name; *p; p++) {
|
||
scc_vec_push(&buf, *p);
|
||
}
|
||
}
|
||
if (opt->spec.value_type == SCC_ARGPARSE_VAL_TYPE_ENUM) {
|
||
scc_vec_push(&buf, '=');
|
||
scc_vec_push(&buf, '<');
|
||
for (int j = 0; j < opt->spec.choices.count; j += 1) {
|
||
if (opt->spec.choices.values[j] == 0) {
|
||
continue;
|
||
}
|
||
|
||
if (j != 0) {
|
||
scc_vec_push(&buf, '|');
|
||
}
|
||
|
||
for (const char *p = opt->spec.choices.values[j]; *p; p++) {
|
||
scc_vec_push(&buf, *p);
|
||
}
|
||
}
|
||
scc_vec_push(&buf, '>');
|
||
}
|
||
scc_vec_push(&buf, '\0');
|
||
scc_fmt(out, " {:<25s} {:s}", buf.items, opt->description ? opt->description : "");
|
||
// if (opt->spec.default_value)
|
||
// scc_fmt(out, " (default: {:s})", opt->spec.default_value);
|
||
scc_fmt(out, "\n");
|
||
}
|
||
scc_fmt(out, "\n");
|
||
}
|
||
|
||
if (cmd->subcmds.count > 0) {
|
||
scc_fmt(out, lines[ARGPARSE_SHOW_CMD]);
|
||
for (usize i = 0; i < cmd->subcmds.count; i++) {
|
||
scc_argparse_cmd_t *sub = &cmd->subcmds.items[i];
|
||
scc_fmt(out, " {:<20s} {:s}\n", sub->name, sub->description ? sub->description : "");
|
||
}
|
||
scc_fmt(out, "\n");
|
||
}
|
||
|
||
if (parser->epilog) {
|
||
scc_fmt(out, "{:s}\n", parser->epilog);
|
||
}
|
||
}
|
||
|
||
const char *scc_argparse_find_similar_arg(scc_argparse_cmd_t *cmd, const char *arg) {
|
||
if (arg == nullptr || cmd == nullptr) {
|
||
return nullptr;
|
||
}
|
||
if (arg[0] == '-' && arg[1] == '-' && arg[2] != '\0') {
|
||
// opt arg
|
||
for (usize i = 0; i < cmd->opts.count; i++) {
|
||
const char *long_name = cmd->opts.items[i].long_name;
|
||
if (long_name && scc_levenshtein(arg + 2, long_name) <= 2) {
|
||
return long_name;
|
||
}
|
||
}
|
||
} else {
|
||
// subcmd arg
|
||
for (usize i = 0; i < cmd->subcmds.count; i++) {
|
||
if (scc_levenshtein(arg, cmd->subcmds.items[i].name) <= 2) {
|
||
return cmd->subcmds.items[i].name;
|
||
}
|
||
}
|
||
}
|
||
return nullptr;
|
||
}
|
||
|
||
void scc_argparse_print_error(scc_argparse_context_t *ctx, scc_argparse_t *parser,
|
||
scc_argparse_err_t err) {
|
||
scc_str_t *out = &parser->out;
|
||
const char **lines = (parser->lang == SCC_ARGPARSE_LANG_ZH) ? fmt_zh : fmt_en;
|
||
switch (err) {
|
||
case SCC_ARGPARSE_ERR_INVALID_ARG:
|
||
case SCC_ARGPARSE_ERR_INVALID_VALUE:
|
||
scc_fmt(out, lines[ARGPARSE_INVALID_VALUE_FOR_OPTION], ctx->err_ctx);
|
||
break;
|
||
case SCC_ARGPARSE_ERR_MISSING_ARG:
|
||
case SCC_ARGPARSE_ERR_MISSING_VALUE:
|
||
scc_fmt(out, lines[ARGPARSE_OPTION_MISSING_VALUE], ctx->err_ctx);
|
||
break;
|
||
case SCC_ARGPARSE_ERR_UNKNOWN_ARG:
|
||
case SCC_ARGPARSE_ERR_UNKNOWN_VALUE:
|
||
scc_fmt(out, lines[ARGPARSE_UNKNOWN_ARGUMENT], ctx->result.raw_arg);
|
||
const char *similar_arg =
|
||
scc_argparse_find_similar_arg(ctx->current_cmd, ctx->result.raw_arg);
|
||
if (similar_arg != nullptr) {
|
||
scc_fmt(out, lines[ARGPARSE_DID_YOU_MEAN], similar_arg);
|
||
}
|
||
break;
|
||
// FACK ERROR
|
||
case SCC_ARGPARSE_ERR_PNT_DEFAULT:
|
||
return;
|
||
default:
|
||
scc_fmt(out, "Unknown error: {:d}\n", err);
|
||
break;
|
||
}
|
||
if (parser->need_help) {
|
||
scc_fmt(out, lines[ARGPRASE_USING_HELP_HINT]);
|
||
}
|
||
if (parser->need_error_add_help) {
|
||
scc_argparse_print_help(parser, ctx->current_cmd);
|
||
} else if (parser->need_error_add_usage) {
|
||
scc_print_usage(parser, ctx->current_cmd, out);
|
||
}
|
||
}
|
||
#endif // SCC_ARGPARSE_PRINT_HELP_IMPLEMENTATION
|
||
|
||
#endif /* __SCC_ARGPARSE_H__ */
|