-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtakina.cc
697 lines (621 loc) · 21.3 KB
/
takina.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
#include "takina.h"
#include <assert.h>
#include <stddef.h> // size_t
#include <stdio.h> // snprintf()
#include <stdlib.h> // exit()
#include <string.h> // strlen()
#include <unordered_map>
#include <utility> // move()
#include <vector>
#include <limits>
#include <cstdint>
namespace takina {
enum OptType : uint8_t {
OT_STR = 0,
OT_FSTR, // fixed string
OT_MSTR, // Multiple string
OT_INT,
OT_FINT,
OT_MINT,
OT_DOUBLE,
OT_FDOUBLE,
OT_MDOUBLE,
OT_VOID, // No argument, use a boolean variable to indicates the option is set
OT_USR, // user-defined
OT_NUM,
};
static inline std::string const &OptType2Str(OptType t) noexcept;
struct OptionParameter {
/* Because options will be parsed only once,
* I don't use union to compress the space */
OptType type; // interpret the param field
unsigned int size = 0; // Used for fixed or user-defined option
void *param = nullptr; // pointer to the user-defined varaible
OptionFunction opt_fn{};
std::string type_hint;
};
/* FIXME
* How to collect the memory of static variable?
* If use a class wrapper, will move some headers to the header file(takina.h).
* Besides, I think global function is easy to use.
*/
// Help message
static std::string help;
static bool has_help = false;
static bool enable_independent_non_opt_arg = false;
void EnableIndependentNonOptionArgument(bool opt) noexcept { enable_independent_non_opt_arg = opt; }
/*
* To implement the AddUsage() and AddDescription() to
* position-of-call-independent, split them from help e.g.
* ```cpp
* takina::AddDescription()
* takina::AddUsage()
* ```
* This is also OK
*/
// Usage message
static std::string usage;
// Description of process
static std::string description;
/*
* The long_param_map store the parameter object,
* and the short_param_map just store the pointer to it.
* Instread approach:
* ```cpp
* std::vector<OptionParameter> params;
* std::unordered_map<std::string, OptionParameter*> long_param_map;
* std::unordered_map<std::string, OptionParameter*> short_param_map;
* ```
*
* This make the process of long_param_map and short_param_map to same.
* But the params is not necessary in fact.
* Therefore, I don't define params.
*/
// long option -> OptionParameter
static std::unordered_map<std::string, OptionParameter> long_param_map;
// short option -> OptionParameter
static std::unordered_map<std::string, OptionParameter *> short_param_map;
// When there are some sections at least 1
// section -> { short, long, desc }[]
// Register a dummy section to handle no section case
static std::unordered_map<std::string, std::vector<OptionDescption>> section_opt_map({{"", {}}});
// To make the section output in the FIFO order
// since the section_opt_map is unordered(hash table)
static std::vector<std::string const *> sections = {§ion_opt_map.begin()->first};
/* Store the non-options arguments */
/* static std::vector<char const *> non_opt_args; */
/* Utility function */
static void AddOption_impl(OptDesc &&desc, OptionParameter opt_param);
static void GenOptions(
std::vector<OptionDescption> const &opts,
int long_opt_param_align_len,
int short_opt_align_len
);
static void GenHelp();
static bool StrInt(int *param, char const *arg, std::string const &cur_option, std::string *errmsg);
static bool StrDouble(
double *param,
char const *arg,
std::string const &cur_option,
std::string *errmsg
);
static bool SetParameter(
OptionParameter *param,
char const *arg,
unsigned int cur_arg_num,
std::string const &cur_option,
std::string *errmsg
);
static bool CheckArgumentIsLess(
OptionParameter *cur_param,
std::string const &cur_option,
unsigned int cur_arg_num,
std::string *errmsg
);
static bool CheckArgumentIsGreater(
OptionParameter *cur_param,
std::string const &cur_option,
unsigned int cur_arg_num,
std::string *errmsg
);
void AddUsage(std::string const &desc)
{
usage.reserve(7 + desc.size() + 1);
usage = "Usage: ";
usage += desc;
usage += "\n\n";
}
void AddDescription(std::string const &desc)
{
description = desc;
description += "\n\n";
}
void AddSection(std::string &§ion)
{
auto res = section_opt_map.insert({std::move(section), {}});
if (!res.second) {
::fprintf(stderr, "The section %s does exists!\n", section.c_str());
return;
}
// FIXME
sections.emplace_back(&res.first->first);
}
void AddOption(OptDesc &&desc, bool *param)
{
*param = false;
OptionParameter opt;
opt.type = OT_VOID;
opt.param = param;
desc.param_name = OptType2Str(opt.type);
AddOption_impl(std::move(desc), opt);
}
#define DEFINE_ADD_OPTION(_ptype, _type) \
void AddOption(OptDesc &&desc, _ptype *param) \
{ \
OptionParameter opt; \
opt.type = _type; \
opt.param = param; \
desc.param_name.reserve(2 + OptType2Str(opt.type).size()); \
desc.param_name = '<'; \
desc.param_name += OptType2Str(opt.type); \
desc.param_name += '>'; \
AddOption_impl(std::move(desc), opt); \
}
DEFINE_ADD_OPTION(std::string, OT_STR)
DEFINE_ADD_OPTION(int, OT_INT)
DEFINE_ADD_OPTION(double, OT_DOUBLE)
#define DEFINE_ADD_OPTION_MULTI(_ptype, _type) \
void AddOption(OptDesc &&desc, _ptype *param) \
{ \
OptionParameter opt; \
opt.type = _type; \
opt.param = param; \
desc.param_name.reserve(4 + OptType2Str(opt.type).size()); \
desc.param_name = "<n "; \
desc.param_name += OptType2Str(opt.type); \
desc.param_name += '>'; \
AddOption_impl(std::move(desc), opt); \
}
DEFINE_ADD_OPTION_MULTI(std::vector<std::string>, OT_MSTR)
DEFINE_ADD_OPTION_MULTI(std::vector<int>, OT_MINT)
DEFINE_ADD_OPTION_MULTI(std::vector<double>, OT_MDOUBLE)
#define DEFINE_ADD_OPTION_FIXED(_ptype, _type) \
void AddOption(OptDesc &&desc, _ptype *param, unsigned int n) \
{ \
OptionParameter opt; \
opt.type = _type; \
opt.size = n; \
opt.param = param; \
auto numeric = std::to_string(opt.size); \
/* <numeric param-str> */ \
desc.param_name.reserve(numeric.size() + 3); \
desc.param_name = '<'; \
desc.param_name += numeric; \
desc.param_name += ' '; \
desc.param_name += OptType2Str(opt.type); \
desc.param_name += '>'; \
AddOption_impl(std::move(desc), opt); \
}
DEFINE_ADD_OPTION_FIXED(std::string, OT_FSTR)
DEFINE_ADD_OPTION_FIXED(int, OT_FINT)
DEFINE_ADD_OPTION_FIXED(double, OT_FDOUBLE)
void AddOption(OptDesc &&desc, OptionFunction fn, unsigned int n)
{
OptionParameter opt;
opt.type = OT_USR;
opt.size = n;
opt.opt_fn = std::move(fn);
AddOption_impl(std::move(desc), std::move(opt));
}
#define CHECK_OPTION_EXISTS(iter, _map) \
auto iter = _map.find(cur_option); \
if (iter == _map.end()) { \
*errmsg = "Option: "; \
*errmsg += cur_option; \
*errmsg += " is not an valid option. Please type --help to check all " \
"allowed options"; \
return false; \
}
bool Parse(char **argv_begin, char **argv_end, std::string *errmsg)
{
OptionParameter *cur_param = nullptr;
std::string cur_option;
unsigned int cur_arg_num = 0;
errmsg->clear();
AddOption({"", "help", "Display the help message"}, &has_help);
for (; argv_begin != argv_end; ++argv_begin) {
char const *arg = *argv_begin;
const size_t len = ::strlen(arg);
assert(len != 0);
bool is_long_opt = (arg[0] == '-' && arg[1] == '-') && len > 2;
bool is_short_opt = (arg[0] == '-') && len > 1;
// Check if is a option
// short option or long option
// PS: ---+ shouldn't think as a option.
if (is_long_opt || is_short_opt) {
if (CheckArgumentIsLess(cur_param, cur_option, cur_arg_num, errmsg)) return false;
cur_arg_num = 0;
// long option
if (arg[1] == '-') {
cur_option = std::string(&arg[2], len - 2);
CHECK_OPTION_EXISTS(iter, long_param_map)
cur_param = &iter->second;
} else {
// short option
cur_option = std::string(&arg[1], len - 1);
CHECK_OPTION_EXISTS(iter, short_param_map)
cur_param = iter->second;
}
if (cur_param->type == OT_VOID) {
*(bool *)(cur_param->param) = true;
}
} else {
// Non option arguments
if (!cur_param) {
if (enable_independent_non_opt_arg) {
GetNonOptionArguments().push_back(arg);
continue;
} else {
*errmsg += "No option, invalid argument";
return false;
}
}
cur_arg_num++;
if (CheckArgumentIsGreater(cur_param, cur_option, cur_arg_num, errmsg)) {
if (enable_independent_non_opt_arg) {
GetNonOptionArguments().push_back(arg);
} else {
return false;
}
} else {
if (!SetParameter(cur_param, arg, cur_arg_num, cur_option, errmsg)) {
return false;
}
}
}
if (has_help) {
// Only generate help when help is specified
GenHelp();
::fputs(help.c_str(), stdout);
::exit(0);
return true;
}
}
if (CheckArgumentIsLess(cur_param, cur_option, cur_arg_num, errmsg)) return false;
return true;
}
void DebugPrint()
{
#ifdef TAKINA_DEBUG
printf("======= Debug Print =======\n");
printf("All long options: \n");
for (auto const &long_opt : long_param_map) {
printf("--%s\n", long_opt.first.c_str());
}
printf("All short options: \n");
for (auto const &short_opt : short_param_map) {
printf("-%s\n", short_opt.first.c_str());
}
puts("");
#endif
}
static inline void Teardown(std::string *str)
{
str->clear();
str->shrink_to_fit();
}
template <typename T>
static inline void Teardown(std::vector<T> *vec)
{
vec->clear();
vec->shrink_to_fit();
}
template <typename T>
static inline void Teardown(T *cont)
{
cont->clear();
}
#define TAKINA_TEARDOWN(obj) (Teardown(obj))
void Teardown()
{
TAKINA_TEARDOWN(&help);
TAKINA_TEARDOWN(&usage);
TAKINA_TEARDOWN(&description);
TAKINA_TEARDOWN(&long_param_map);
TAKINA_TEARDOWN(&short_param_map);
TAKINA_TEARDOWN(§ion_opt_map);
TAKINA_TEARDOWN(§ions);
}
static inline void GenHelp()
{
help.reserve(usage.size() + description.size());
help = usage;
help += description;
int short_opt_align_len = 0;
int long_opt_param_align_len = 0;
if (!sections.empty()) {
for (auto const §ion_opt : section_opt_map) {
auto &options = section_opt.second;
for (auto const &option : options) {
long_opt_param_align_len = TAKINA_MAX(
long_opt_param_align_len,
int(option.param_name.size() + option.lopt.size())
);
short_opt_align_len = TAKINA_MAX(short_opt_align_len, (int)option.sopt.size());
}
}
}
help += "Options: \n";
for (auto const §ion : sections) {
help += *section;
if (!section->empty()) help += ":\n";
auto const &opts = section_opt_map[*section];
GenOptions(opts, long_opt_param_align_len, short_opt_align_len);
help += "\n";
}
// Remove the last newline
help.pop_back();
}
void GenOptions(
std::vector<OptionDescption> const &opts,
int long_opt_param_align_len,
int short_opt_align_len
)
{
char buf[65535];
std::string lopt_param;
lopt_param.reserve(long_opt_param_align_len + 1);
// Format:
// -[short-opt],--[long-opt] [param-name] [description]
// If there are no short options, put blackspace as placeholders.
// --[long-opt] [param-name] [description]
// To don't split long-opt and param-name too long,
// combine them to single unit.
for (auto const &opt : opts) {
std::string format;
if (opt.sopt.empty()) {
format = " %-*s ";
} else {
format = "-%-*s,";
}
format += " --%-*s %s\n";
lopt_param = opt.lopt;
lopt_param += " ";
lopt_param += opt.param_name;
::snprintf(
buf,
sizeof buf,
format.c_str(),
short_opt_align_len,
opt.sopt.c_str(),
long_opt_param_align_len + 1,
lopt_param.c_str(),
opt.desc.c_str()
);
help += buf;
}
}
inline void AddOption_impl(OptDesc &&desc, OptionParameter opt_param)
{
if (desc.lopt.empty()) return;
auto res = long_param_map.insert({(desc.lopt), opt_param});
if (!res.second) {
::fprintf(stderr, "The long option: %s does exists\n", desc.lopt.c_str());
return;
}
if (!desc.sopt.empty()) {
if (!short_param_map.insert({(desc.sopt), &res.first->second}).second) {
::fprintf(stderr, "The short option: %s does exists\n", desc.sopt.c_str());
return;
}
}
assert(!sections.empty());
section_opt_map[*sections.back()].push_back(std::move(desc));
}
static inline bool StrInt(
int *param,
char const *arg,
std::string const &cur_option,
std::string *errmsg
)
{
char *end = nullptr;
const auto res = ::strtol(arg, &end, 10);
if (res == 0 && end == arg) {
*errmsg = "Option: ";
*errmsg += cur_option;
*errmsg += '\n';
*errmsg += "syntax error: this is not a valid integer argument";
return false;
}
*param = res;
return true;
}
static inline bool StrDouble(
double *param,
char const *arg,
std::string const &cur_option,
std::string *errmsg
)
{
char *end = nullptr;
const auto res = ::strtod(arg, &end);
if (res == 0 && end == arg) {
*errmsg = "Option: ";
*errmsg += cur_option;
*errmsg += '\n';
*errmsg += "Syntax error: this is not a valid float-pointing number argument";
return false;
}
*param = res;
return true;
}
static inline bool SetParameter(
OptionParameter *param,
char const *arg,
unsigned int cur_arg_num,
std::string const &cur_option,
std::string *errmsg
)
{
switch (param->type) {
case OT_STR:
*(std::string *)(param->param) = arg;
break;
case OT_INT: {
int res;
if (!StrInt(&res, arg, cur_option, errmsg)) return false;
*(int *)(param->param) = res;
} break;
case OT_DOUBLE: {
double res;
if (!StrDouble(&res, arg, cur_option, errmsg)) return false;
*(double *)(param->param) = res;
} break;
case OT_MSTR: {
((std::vector<std::string> *)(param->param))->emplace_back(arg);
break;
} break;
case OT_MINT: {
int res;
if (!StrInt(&res, arg, cur_option, errmsg)) return false;
((std::vector<int> *)(param->param))->emplace_back(res);
} break;
case OT_MDOUBLE: {
double res;
if (!StrDouble(&res, arg, cur_option, errmsg)) return false;
((std::vector<double> *)(param->param))->emplace_back(res);
} break;
#define FIXED_ARGUMENTS_ERR_ROUTINE \
if (cur_arg_num > param->size) { \
*errmsg = "Option: "; \
*errmsg += cur_option; \
*errmsg += ", The number of arguments more than required"; \
return false; \
}
case OT_FSTR: {
FIXED_ARGUMENTS_ERR_ROUTINE
auto arr = (std::string *)(param->param);
arr[cur_arg_num - 1] = arg;
} break;
case OT_FINT: {
FIXED_ARGUMENTS_ERR_ROUTINE
auto arr = (int *)(param->param);
int res;
if (!StrInt(&res, arg, cur_option, errmsg)) return false;
arr[cur_arg_num - 1] = res;
} break;
case OT_FDOUBLE: {
FIXED_ARGUMENTS_ERR_ROUTINE
auto arr = (double *)(param->param);
double res;
if (!StrDouble(&res, arg, cur_option, errmsg)) return false;
arr[cur_arg_num - 1] = res;
} break;
case OT_USR: {
if (!param->opt_fn(arg)) {
*errmsg += "Option error: Invalid arguments for ";
*errmsg += cur_option;
return false;
}
} break;
}
return true;
}
static inline bool CheckArgumentIsLess(
OptionParameter *cur_param,
std::string const &cur_option,
unsigned int cur_arg_num,
std::string *errmsg
)
{
bool condition = false;
if (cur_param) {
switch (cur_param->type) {
case OT_STR:
case OT_INT:
case OT_DOUBLE:
condition = cur_arg_num == 0;
break;
case OT_FSTR:
case OT_FINT:
case OT_FDOUBLE:
condition = cur_arg_num < cur_param->size;
break;
case OT_USR:
condition = (cur_arg_num < cur_param->size);
break;
}
}
if (condition) {
*errmsg = "Option: ";
*errmsg += cur_option;
*errmsg += ", the number of arguments is less than required";
return true;
}
return false;
}
static inline bool CheckArgumentIsGreater(
OptionParameter *cur_param,
std::string const &cur_option,
unsigned int cur_arg_num,
std::string *errmsg
)
{
unsigned int size = 0;
assert(cur_param);
switch (cur_param->type) {
case OT_STR:
case OT_INT:
case OT_DOUBLE: {
size = 1;
} break;
case OT_FDOUBLE:
case OT_FINT:
case OT_FSTR:
case OT_USR: {
size = cur_param->size;
} break;
case OT_MDOUBLE:
case OT_MINT:
case OT_MSTR: {
size = std::numeric_limits<unsigned int>::max();
} break;
}
if (cur_arg_num > size) {
if (!enable_independent_non_opt_arg) {
*errmsg = "To unary argument option: ";
*errmsg += cur_option;
*errmsg += ", the number of arguments more than ";
/* Because SSO, no dynamic allocation in most */
*errmsg += std::to_string(size);
}
return true;
}
return false;
}
std::vector<char const *> &GetNonOptionArguments()
{
/* non_opt_args isn't a trivial class,
* If some non trivial class initialization depend on
* this variable, it is dangerous since non_opt_args
* may be initialized after the depended class
*/
static std::vector<char const *> non_opt_args;
return non_opt_args;
}
std::string opt_strings[OT_NUM] = {
"string",
"strings",
"strings",
"integer",
"integers",
"integers",
"float number",
"float numbers",
"float numbers",
"",
"user",
};
static std::string const &OptType2Str(OptType t) noexcept { return opt_strings[(int)t]; }
} // namespace takina